text
stringlengths 8
6.88M
|
|---|
#include <stdio.h>
#include <limits.h>
#include <time.h>
#include <stdlib.h>
#include "resource.h"
#ifdef _WIN32
#define XTRACE_SUPPLEMENT
#include <xtrace.h>
#endif
#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_FontCache.c>
#include "res/nunito.h"
#include "lyrics.h"
static const int MEDIASIZE = 16;
static bool G_Running = true;
static int G_WindowWidth = -1;
static int G_WindowHeight = -1;
static int font_size = 12;
static int VOLUME = MIX_MAX_VOLUME - (MIX_MAX_VOLUME / 4);
struct Media {
unsigned char *music;
const char **lyrics;
int columns;
int length;
};
void SetMedia(Media **media, unsigned char *music, const char **lyrics, int size,
int length, int index) {
if(index > MEDIASIZE-1) {
printf("Did not add media: not enough slots\n");
return;
}
(*media)[index].music = music;
(*media)[index].lyrics = lyrics;
(*media)[index].columns = size;
(*media)[index].length = length;
}
void LoadMedia(Media **media, int id, const char **lyrics, int size, int index) {
#ifdef _WIN32
HRSRC resource = FindResource(NULL, MAKEINTRESOURCE(id), LPCSTR("MUSICDATA_TYPE"));
if(!resource) {
printf("Error: Resource with ID: %d could not be found\n", id);
return;
}
HGLOBAL memory = LoadResource(NULL, resource);
if(!memory) {
printf("Error: Could not load resource %d's memory\n", id);
return;
}
DWORD length = SizeofResource(NULL, resource);
if(length == 0) {
printf("Error: Size of resource %d is 0\n", id);
return;
}
SetMedia(media, (unsigned char *)memory, lyrics, size, length, index);
#else
// Linux
#endif
}
enum WAVEFORM_DISPLAY {
WFD_BUFFER,
WFD_SCROLL
};
int InitSDL(int flags = 0) {
if (flags == 0)
flags = SDL_INIT_EVERYTHING;
if (SDL_Init(flags) != 0) {
printf("Error initializing SDL2: %s\n", SDL_GetError());
return -1;
}
SDL_version compiled;
SDL_version linked;
SDL_VERSION(&compiled);
SDL_VERSION(&linked);
printf("SDL2 Version:\n\tCompiled: %d.%d.%d\n\tLinked: %d.%d.%d\n\n",
compiled.major, compiled.minor, compiled.patch, linked.major,
linked.minor, linked.patch);
return 0;
}
enum SDL_LIBRARY_TYPE {
SDL_MIXER_LIB,
SDL_TTF_LIB,
};
int InitSDL_Library(enum SDL_LIBRARY_TYPE libtype, int flags = 0) {
SDL_version compiled = {};
const SDL_version *linked = {0};
const char *libname;
switch (libtype) {
case SDL_MIXER_LIB: {
if (flags == 0)
flags = MIX_INIT_FLAC | MIX_INIT_MOD | MIX_INIT_MP3 | MIX_INIT_OGG;
int mixer_init = Mix_Init(flags);
if (mixer_init & flags != flags) {
printf("Error initializing SDL Mixer: %s\n", Mix_GetError());
return -1;
}
SDL_MIXER_VERSION(&compiled);
linked = Mix_Linked_Version();
libname = "Mixer";
} break;
case SDL_TTF_LIB: {
if (TTF_Init() == -1) {
printf("Error initializing SDL TTF: %s\n", TTF_GetError());
return -1;
}
SDL_TTF_VERSION(&compiled);
linked = TTF_Linked_Version();
libname = "TTF";
} break;
default: {
printf(
"Error initializing SDL Library: %d is not a valid SDL Library Type\n",
libtype);
return -1;
}
}
printf("SDL2 %s Version:\n\tCompiled: %d.%d.%d\n\tLinked: %d.%d.%d\n\n", libname,
compiled.major, compiled.minor, compiled.patch, linked->major,
linked->minor, linked->patch);
return 0;
}
const char *SDL_Mixer_GetFormatString(uint16_t format) {
const char *format_str;
switch (format) {
case AUDIO_U8:
format_str = "U8";
break;
case AUDIO_S8:
format_str = "S8";
break;
case AUDIO_U16LSB:
format_str = "U16LSB";
break;
case AUDIO_S16LSB:
format_str = "S16LSB";
break;
case AUDIO_U16MSB:
format_str = "U16MSB";
break;
case AUDIO_S16MSB:
format_str = "S16MSB";
break;
default:
format_str = "UNKNOWN";
}
return format_str;
}
#define BUFFER 8192
#define Y(sample) (((sample)*G_WindowHeight) / 4 / 0x7fff)
int16_t stream[2][BUFFER * 2 * 2];
int len = BUFFER * 2 * 2, which = 0, sample_size, position = 0, rate;
const uint32_t pinky = 0x8043FFFF;
const uint32_t pinky_H = 0x6D0080FF;
const uint32_t orangey = 0x4380FFFF;
const uint32_t orangey_H = 0x804321FF;
const uint32_t pinker = 0xDB00FFFF;
const uint32_t greenish = 0x80FF80FF;
const uint32_t reddish = 0xFF8080FF;
const uint32_t black = 0x000000FF;
const uint32_t white = 0xFFFFFFFF;
const uint32_t transparent = 0x00000000;
void MusicPostMix(void *_udata, uint8_t *_stream, int _len) {
SDL_Surface *surface = (SDL_Surface *)_udata;
if (!Mix_PausedMusic() && Mix_PlayingMusic())
position += _len / sample_size;
len = _len;
if (surface)
memcpy(stream[which], _stream,
len > (surface->w * 4) ? (surface->w * 4) : len);
which = (which + 1) % 2;
}
void WaveFormBuffer(SDL_Surface *surface, SDL_Rect *rects) {
Sint16 *buf = stream[which];
SDL_LockSurface(surface);
SDL_FillRect(surface, NULL, transparent); // Clear
SDL_Rect r;
uint32_t wav_color = black;
int width = 1;
for (int x = 0; x < (G_WindowWidth * 2) / width; x++) {
const int X = x >> 1, b = x & 1, t = (G_WindowHeight / 4) + (G_WindowHeight / 2) * b;
int y1, h1;
if (buf[x] < 0) {
h1 = -Y(buf[x]);
y1 = t - h1;
} else {
y1 = t;
h1 = Y(buf[x]);
}
rects[x] = {X, y1, width, h1};
}
SDL_FillRects(surface, rects, G_WindowWidth * 2, wav_color);
SDL_UnlockSurface(surface);
}
int scroll_x = G_WindowWidth - 1;
void WaveFormScroll(SDL_Surface *surface, int buffersize) {
Sint16 *buf = stream[which];
SDL_LockSurface(surface);
SDL_Rect rect;
uint32_t wav_color = black;
int accum = INT_MIN;
for(int x = 0; x < buffersize; ++x) {
if(buf[x] > accum) accum = buf[x];
}
int y1, h1;
y1 = G_WindowHeight / 2;
// The minus twenty is for padding out the window to the rectangle won't hit
// the edge of the screen
h1 = ((accum * (G_WindowHeight - 20)) / 2) / 0x7fff;
if(h1 < 1) h1 = 1;
int width = 1;
accum = 0;
rect = {scroll_x, 0, width, G_WindowHeight};
SDL_FillRect(surface, &rect, transparent);
rect = {scroll_x, y1 - h1, width, h1 * 2};
SDL_FillRect(surface, &rect, wav_color);
if(scroll_x == 0) scroll_x = G_WindowWidth - 1;
else scroll_x--;
SDL_UnlockSurface(surface);
}
#include "handleevents.h"
int main(int argc, char **argv) {
printf("Hello world\n\n");
srand(time(NULL));
// -------- Initialize SDL --------
if (InitSDL() != 0)
return -1;
if (InitSDL_Library(SDL_MIXER_LIB, MIX_INIT_OGG) != 0)
return -1;
if (InitSDL_Library(SDL_TTF_LIB) != 0)
return -1;
// -------- Create SDL Window --------
int display_count = 0, display_index = 0, mode_index = 0;
SDL_DisplayMode mode = {SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0};
if(display_count = SDL_GetNumVideoDisplays() < 1) {
printf("Error: no displays!\n");
return -1;
}
if(SDL_GetDisplayMode(display_index, mode_index, &mode) != 0) {
printf("Error: Getting display mode failed: %s\n\n", SDL_GetError());
return -1;
}
printf("Display Dimensions: %dx%d\n", mode.w, mode.h);
if(mode.h < 576) {
printf("Window size too small :(\n");
return -1;
}
if(mode.w % 16 != 0 || mode.h % 9 != 0) {
printf("Not 16:9\n");
}
printf("Finding best resolution\n");
G_WindowHeight = mode.h - (mode.h / 8);
if(G_WindowHeight > 1080) G_WindowHeight = 1080;
G_WindowWidth = (int)((float)G_WindowHeight * 1.7f);
if(G_WindowHeight >= 576 && G_WindowHeight < 648) font_size = 12;
else if(G_WindowHeight >= 648 && G_WindowHeight < 720) font_size = 14;
else if(G_WindowHeight >= 720 && G_WindowHeight < 1080) font_size = 16;
else if(G_WindowHeight == 1080) font_size = 24;
else font_size = 12;
int window_flags = 0;
SDL_Window *window = SDL_CreateWindow(
"hex static", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, G_WindowWidth, G_WindowHeight, window_flags);
if (!window) {
printf("Error creating SDL Window: %s\n", SDL_GetError());
return -1;
}
printf("\n");
// -------- Create SDL Renderer --------
int renderer_flags = 0;
renderer_flags |= SDL_RENDERER_ACCELERATED;
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, renderer_flags);
if (!renderer) {
printf("Error creating SDL Renderer: %s\n", SDL_GetError());
return -1;
}
SDL_RendererInfo rinfo;
SDL_GetRendererInfo(renderer, &rinfo);
printf("Renderer:\n");
printf("\tName: %s\n", rinfo.name);
printf("\tFlags: %d\n", rinfo.flags);
printf("\tTexture formats:\n");
for (int i = 0; i < rinfo.num_texture_formats; ++i) {
printf("\t\t%s\n", SDL_GetPixelFormatName(rinfo.texture_formats[i]));
}
printf("\tMax Texture dimensions: %dx%d\n",
rinfo.max_texture_width, rinfo.max_texture_height);
printf("\n");
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
// -------- Set up Background Surfaces --------
SDL_Surface *surface =
SDL_CreateRGBSurface(0, G_WindowWidth, G_WindowHeight, 32, 0, 0, 0, 0);
SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_BLEND);
SDL_Texture *texture =
SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_STREAMING, surface->w, surface->h);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
SDL_Surface *background_surface =
SDL_CreateRGBSurface(0, G_WindowWidth, G_WindowHeight, 32, 0, 0, 0, 0);
SDL_SetSurfaceBlendMode(background_surface, SDL_BLENDMODE_BLEND);
const uint32_t background_color_1 = 0xFF3E1F7F;
const uint32_t background_color_2 = 0xFF1F3E7F;
SDL_Rect background_rect;
background_rect = {0, 0, background_surface->w, G_WindowHeight / 4};
SDL_FillRect(background_surface, &background_rect, background_color_1);
background_rect = {0, G_WindowHeight / 4, background_surface->w, G_WindowHeight / 4};
SDL_FillRect(background_surface, &background_rect, background_color_2);
background_rect = {0, (G_WindowHeight / 4) * 2, background_surface->w, G_WindowHeight / 4};
SDL_FillRect(background_surface, &background_rect, background_color_1);
background_rect = {0, (G_WindowHeight / 4) * 3, background_surface->w, G_WindowHeight / 4};
SDL_FillRect(background_surface, &background_rect, background_color_2);
SDL_Texture *background_texture =
SDL_CreateTextureFromSurface(renderer, background_surface);
// -------- Open SDL Mixer and set up audio --------
int wanted_frequency = 48000, wanted_channels = 2, audio_buffersize = 2048;
uint16_t wanted_format = MIX_DEFAULT_FORMAT;
if (Mix_OpenAudio(wanted_frequency, wanted_format, wanted_channels,
audio_buffersize) == -1) {
printf("Error opening SDL Mixer audio: %s\n", Mix_GetError());
return -1;
}
int frequency, channels;
uint16_t format;
Mix_QuerySpec(&frequency, &format, &channels);
printf(
"Succesfully opened audio:\n\tFrequency: %d\n\tFormat: %s\n\tChannels: %d\n",
frequency, SDL_Mixer_GetFormatString(format), channels);
printf("\tMusic Decoders:\n");
for (int i = 0; i < Mix_GetNumMusicDecoders(); ++i) {
printf("\t\t%s\n", Mix_GetMusicDecoder(i));
}
printf("\n");
// -------- Media loading --------
int current_media = rand() % MEDIASIZE;
static Media *media = (Media *)calloc(MEDIASIZE, sizeof(Media));
#ifdef _WIN32
LoadMedia(&media, BIRDSOFPREY_ID, birdsofprey_lyrics, birdsofprey_size, 0);
LoadMedia(&media, BROKE_ID, broke_lyrics, broke_size, 1);
LoadMedia(&media, DRAMAMINE_ID, dramamine_lyrics, dramamine_size, 2);
LoadMedia(&media, EVENINGSUN_ID, eveningsun_lyrics, eveningsun_size, 3);
LoadMedia(&media, GREYICEWATER_ID, greyicewater_lyrics, greyicewater_size, 4);
LoadMedia(&media, HEARTCOOKSBRAIN_ID, heartcooksbrain_lyrics, heartcooksbrain_size, 5);
LoadMedia(&media, HEYMOON_ID, heymoon_lyrics, heymoon_size, 6);
LoadMedia(&media, HOTCHAGIRLS_ID, hotchagirls_lyrics, hotchagirls_size, 7);
LoadMedia(&media, INCOMBAT_ID, incombat_lyrics, incombat_size, 8);
LoadMedia(&media, ITTWR_ID, ittwr_lyrics, ittwr_size, 9);
LoadMedia(&media, NEWSLANG_ID, newslang_lyrics, newslang_size, 10);
LoadMedia(&media, ROLLINGOVER_ID, rollingover_lyrics, rollingover_size, 11);
LoadMedia(&media, SLEEPWALKIN_ID, sleepwalkin_lyrics, sleepwalkin_size, 12);
LoadMedia(&media, THEARRIVAL_ID, thearrival_lyrics, thearrival_size, 13);
LoadMedia(&media, TIMESTOPS_ID, timestops_lyrics, timestops_size, 14);
LoadMedia(&media, YOUONLYLIVEONCE_ID, youonlyliveonce_lyrics, youonlyliveonce_size, 15);
#else
// Linux
#endif
// -------- Music loading --------
Mix_Music *music = NULL;
bool music_from_arg = false;
SDL_RWops *music_ops = NULL;
if(argc == 2) {
const char *music_file = argv[1];
music = Mix_LoadMUS(music_file);
if(!music) {
printf("Error loading music from argument: %s\n", Mix_GetError());
} else {
music_from_arg = true;
}
} else if(!music) {
// We else if because we will always get the song from memory if
// we can't load from an argument
music_ops = SDL_RWFromConstMem(media[current_media].music, media[current_media].length);
music = Mix_LoadMUSType_RW(music_ops, MUS_OGG, 0);
}
if(!music) {
printf("Could not load any music!!\n");
}
Mix_SetPostMix(MusicPostMix, surface);
Mix_VolumeMusic(VOLUME);
int bits = format & 0xFF;
sample_size = bits / 8 + channels;
Mix_PlayMusic(music, 0);
// -------- Open font files --------
FC_Font *font = FC_CreateFont();
if(!font) {
printf("Could not create font\n");
return -1;
}
SDL_Color font_color = FC_MakeColor(255, 255, 255, 255);
SDL_Color font_color_black = FC_MakeColor(0, 0, 0, 255);
SDL_RWops *font_ops = SDL_RWFromConstMem(nunito, nunito_length);
if(!font_ops) {
printf("Could not read font from memory!\n");
return -1;
}
FC_LoadFont_RW(font, renderer, font_ops, 0, font_size, font_color, TTF_STYLE_NORMAL);
// -------- Set up for main loop --------
char title[64];
#ifdef _WIN32
char *loading_circles[] = {u8"\u25DC", u8"\u25DD", u8"\u25DE", u8"\u25DF"};
#else
char const *loading_circles[] = {
"\U000025DC", "\U000025DD", "\U000025DE", "\U000025DF"
};
#endif
char *load_circle = loading_circles[0];
int info_pad = 10;
int current_loader = 0;
Mouse mouse;
printf("\n\n");
WAVEFORM_DISPLAY wfd = WFD_BUFFER;
Mix_PlayMusic(music, 1);
uint64_t counter = 0;
char volume_arr[16];
char current_media_arr[8];
SDL_Rect *rects = (SDL_Rect *)calloc(G_WindowWidth * 2, sizeof(SDL_Rect));
if(!rects) {
printf("Error: Could not allocate waveform buffer rects\n");
return -1;
}
int lessthanthirtycount = 0;
// -------- Main loop --------
while (G_Running) {
uint64_t start = SDL_GetTicks();
HandleEvents(&mouse, surface, &scroll_x, wfd, media, &music,
music_ops, ¤t_media);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, background_texture, NULL, NULL);
#if 1
if(wfd == WFD_BUFFER) {
WaveFormBuffer(surface, rects);
} else if(wfd == WFD_SCROLL) {
WaveFormScroll(surface, audio_buffersize / 4);
}
SDL_LockTexture(texture, NULL, &surface->pixels, &surface->pitch);
SDL_UnlockTexture(texture);
SDL_RenderCopy(renderer, texture, NULL, NULL);
#endif
// Render the lyrics text
#if 1
if (!music_from_arg) {
int text_pad = 40;
int text_x = 10;
int text_y = 10;
for(int i = 0; i < media[current_media].columns; ++i) {
FC_Rect r1 = FC_Draw(font, renderer, text_x, text_y, media[current_media].lyrics[i]);
text_x += text_pad + r1.w;
}
}
#endif
int vol = Mix_VolumeMusic(-1);
int current = current_media + 1;
uint16_t volume_width = FC_GetWidth(font, "Media %d/%d | Volume: %d", current, MEDIASIZE, vol);
uint16_t volume_height = FC_GetHeight(font, "Media %d/%d | Volume: %d",current, MEDIASIZE, vol);
FC_Draw(font, renderer, G_WindowWidth - volume_width - info_pad,
G_WindowHeight - volume_height - info_pad, "Media %d/%d | Volume: %d",
current, MEDIASIZE, vol);
FC_DrawColor(font, renderer, 10, G_WindowHeight - volume_height - info_pad, font_color_black,
"TAB/Tilde: Change song, 1/2: Change Waveform view, +/-: Change volume, Space: Play/Pause");
SDL_RenderPresent(renderer);
#if 0
// DEBUG ONLY
uint64_t end = SDL_GetTicks();
float mspf = (float)end - (float)start;
float fps = (1.0f / mspf) * 1000.0f;
counter += end - start;
if (!Mix_PausedMusic() || !Mix_PlayingMusic()) {
load_circle = loading_circles[current_loader];
if (counter >= 500) {
current_loader = (++current_loader) % 4;
counter = 0;
}
} else {
#ifdef _WIN32
load_circle = u8"\u2015";
#else
load_circle = "\U00002015";
#endif
}
sprintf(title, "%s FPS: %.2f | MSPF: %.2f", load_circle, fps, mspf);
SDL_SetWindowTitle(window, title);
if(fps < 30.0f) printf("%d: Less than 30 fps! :(\n", lessthanthirtycount++);
#else
uint64_t end = SDL_GetTicks();
float mspf = (float)end - (float)start;
float fps = (1.0f / mspf) * 1000.0f;
if(fps < 30.0f) printf("%d: Less than 30 fps! :(\n", lessthanthirtycount++);
#endif
}
// -------- Cleanup --------
FC_FreeFont(font);
SDL_RWclose(font_ops);
if(music) Mix_FreeMusic(music);
Mix_CloseAudio();
if(music_ops) SDL_RWclose(music_ops);
SDL_Quit();
printf("\nGoodbye\n");
return 0;
}
|
//$Id: DSNTwoWayDoppler.cpp 1398 2011-04-21 20:39:37Z $
//------------------------------------------------------------------------------
// DSNTwoWayDoppler
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2015 United States Government as represented by the
// Administrator of The National Aeronautics and Space Administration.
// All Other 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.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under FDSS
// Task 28
//
// Author: Darrel J. Conway, Thinking Systems, Inc.
// Created: Jul 27, 2010
//
/**
* Measurement model class for Doppler measurements made by the deep space
* network
*/
//------------------------------------------------------------------------------
// this needs to be at the top for Ionosphere to work on Mac!
#include "RandomNumber.hpp"
#include "DSNTwoWayDoppler.hpp"
#include "MeasurementException.hpp"
#include "GmatConstants.hpp"
#include "MessageInterface.hpp"
#include "GroundstationInterface.hpp"
#include "Transmitter.hpp"
#include "Receiver.hpp"
#include "Transponder.hpp"
#include <sstream>
//#define DEBUG_DOPPLER_CALC_WITH_EVENTS
//#define VIEW_PARTICIPANT_STATES_WITH_EVENTS
//#define DEBUG_DERIVATIVES
//#define DEBUG_DOPPLER_CALC
//#define VIEW_PARTICIPANT_STATES
//------------------------------------------------------------------------------
// DSNTwoWayDoppler(const std::string& withName)
//------------------------------------------------------------------------------
/**
* Default constructor
*
* @param withName Name of the new object
*/
//------------------------------------------------------------------------------
DSNTwoWayDoppler::DSNTwoWayDoppler(const std::string& withName) :
AveragedDoppler ("DSNTwoWayDoppler", withName)
{
objectTypeNames.push_back("DSNTwoWayDoppler");
// Prep value array in measurement
currentMeasurement.value.push_back(0.0);
currentMeasurement.typeName = "DSNTwoWayDoppler";
currentMeasurement.type = Gmat::DSN_TWOWAYDOPPLER;
currentMeasurement.eventCount = 4;
currentMeasurement.participantIDs.push_back("NotSet");
currentMeasurement.participantIDs.push_back("NotSet");
covariance.SetDimension(1);
covariance(0,0) = 1.0;
}
//------------------------------------------------------------------------------
// ~DSNTwoWayDoppler()
//------------------------------------------------------------------------------
/**
* Destructor
*/
//------------------------------------------------------------------------------
DSNTwoWayDoppler::~DSNTwoWayDoppler()
{
}
//------------------------------------------------------------------------------
// DSNTwoWayDoppler(const DSNTwoWayDoppler & dd)
//------------------------------------------------------------------------------
/**
* Copy constructor
*
* @param dd The object that gets copied to make this new one
*/
//------------------------------------------------------------------------------
DSNTwoWayDoppler::DSNTwoWayDoppler(const DSNTwoWayDoppler & dd) :
AveragedDoppler (dd)
{
currentMeasurement.value.push_back(0.0);
currentMeasurement.typeName = "DSNTwoWayDoppler";
currentMeasurement.type = Gmat::DSN_TWOWAYDOPPLER;
currentMeasurement.eventCount = 4;
currentMeasurement.uniqueID = dd.currentMeasurement.uniqueID;
currentMeasurement.participantIDs.push_back("NotSet");
currentMeasurement.participantIDs.push_back("NotSet");
covariance = dd.covariance;
}
//------------------------------------------------------------------------------
// DSNTwoWayDoppler& operator=(const DSNTwoWayDoppler& dd)
//------------------------------------------------------------------------------
/**
* Assignment operator
*
* @param dd The object that gets copied to make this new one
*
* @return this object configured to match dd
*/
//------------------------------------------------------------------------------
DSNTwoWayDoppler& DSNTwoWayDoppler::operator=(const DSNTwoWayDoppler& dd)
{
if (this != &dd)
{
AveragedDoppler::operator=(dd);
// Allocate exactly one value in current measurement for range
currentMeasurement.value.clear();
currentMeasurement.value.push_back(0.0);
currentMeasurement.typeName = "DSNTwoWayDoppler";
currentMeasurement.type = Gmat::DSN_TWOWAYDOPPLER;
currentMeasurement.eventCount = 4;
currentMeasurement.uniqueID = dd.currentMeasurement.uniqueID;
currentMeasurement.participantIDs = dd.currentMeasurement.participantIDs;
covariance = dd.covariance;
}
return *this;
}
//------------------------------------------------------------------------------
// GmatBase* Clone() const
//------------------------------------------------------------------------------
/**
* Method used to make a new instance from a GMatBase pointer
*
* @return A copy of this object
*/
//------------------------------------------------------------------------------
GmatBase* DSNTwoWayDoppler::Clone() const
{
return new DSNTwoWayDoppler(*this);
}
//------------------------------------------------------------------------------
// const std::vector<RealArray>& CalculateMeasurementDerivatives(
// GmatBase *obj, Integer id)
//------------------------------------------------------------------------------
/**
* Derivative evaluation method used in estimation
*
* @param obj The object supplying the "with respect to" parameter
* @param id The id of the with respect to parameter
*
* @return The array of derivative data
*/
//------------------------------------------------------------------------------
const std::vector<RealArray>& DSNTwoWayDoppler::CalculateMeasurementDerivatives(
GmatBase *obj, Integer id)
{
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage("DSNTwoWayDoppler::CalculateMeasurement"
"Derivatives(%s, %d) called\n", obj->GetName().c_str(), id);
#endif
if (obj == NULL)
throw MeasurementException("Error: a NULL object inputs to DSNTwoWayDoppler::CalculateMeasurementDerivatives() function\n");
if (!initialized)
InitializeMeasurement();
GmatBase *objPtr = NULL;
Integer size = obj->GetEstimationParameterSize(id);
Integer objNumber = -1;
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" ParameterSize = %d\n", size);
#endif
if (size <= 0)
throw MeasurementException("The derivative parameter on derivative "
"object " + obj->GetName() + "is not recognized");
// Check to see if obj is a participant
for (UnsignedInt i = 0; i < participants.size(); ++i)
{
if (participants[i] == obj)
{
objPtr = participants[i];
objNumber = i + 1;
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Participant %s found\n",
objPtr->GetName().c_str());
#endif
break;
}
}
// Or if it is the measurement model for this object
if (obj->IsOfType(Gmat::MEASUREMENT_MODEL))
if (obj->GetRefObject(Gmat::CORE_MEASUREMENT, "") == this)
{
objPtr = obj;
objNumber = 0;
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" The measurement is the object\n",
objPtr->GetName().c_str());
#endif
}
RealArray oneRow;
oneRow.assign(size, 0.0);
currentDerivatives.clear();
currentDerivatives.push_back(oneRow);
if (objNumber == -1)
return currentDerivatives; // return zero vector when variable is independent of DSNTwoWay range
Integer parameterID = GetParmIdFromEstID(id, obj);
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Looking up id %d\n", parameterID);
#endif
// At this point, objPtr points to obj. Therefore, its value is not NULL
if (objPtr != NULL)
{
Real preFactorS = turnaround * frequency / (interval * GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM / GmatMathConstants::KM_TO_M);
Real preFactorE = turnaround * frequencyE / (interval * GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM / GmatMathConstants::KM_TO_M);
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage("preFactorE = %.12lf prefactorS = %.12lf\n", preFactorE, preFactorS);
#endif
if (objNumber == 1) // participant number 1, either a GroundStation or a Spacecraft
{
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Deriv is w.r.t. %s of Participant"
" 1\n", objPtr->GetParameterText(parameterID).c_str());
#endif
if (objPtr->GetParameterText(parameterID) == "Position")
{
throw MeasurementException("Derivative w.r.t. " +
participants[0]->GetName() +" position is not yet implemented");
}
else if (objPtr->GetParameterText(parameterID) == "Velocity")
{
throw MeasurementException("Derivative w.r.t. " +
participants[0]->GetName() +" velocity is not yet implemented");
}
else if (objPtr->GetParameterText(parameterID) == "CartesianX")
{
throw MeasurementException("Derivative w.r.t. " +
participants[0]->GetName() + " CartesianState is not yet "
"implemented");
}
else if (objPtr->GetParameterText(parameterID) == "Bias")
{
for (Integer i = 0; i < size; ++i)
currentDerivatives[0][i] = 1.0;
}
else
{
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Deriv is w.r.t. something "
"independent, so zero\n");
#endif
for (Integer i = 0; i < size; ++i)
currentDerivatives[0][i] = 0.0;
}
}
else if (objNumber == 2) // participant 2, always a Spacecraft
{
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Deriv is w.r.t. %s of Participant"
" 2\n", objPtr->GetParameterText(parameterID).c_str());
#endif
if (objPtr->GetParameterText(parameterID) == "Position")
{
// Get the inverse of the orbit STM at the measurement epoch
// Will need adjustment if stm changes
Rmatrix stmInv(6,6);
GetInverseSTM(obj, stmInv);
// Uplink leg
Rvector3 uplinkDerivS, uplinkDerivE;
GetRangeDerivative(uplinkLegS, stmInv, uplinkDerivS, false, 0, 1, true, false); // for uplink leg, transmiter is station (index = 0), receiver is spacecraft (index = 1), derivative w.r.t transmiter object is false (w.r.t spacecraft)
GetRangeDerivative(uplinkLegE, stmInv, uplinkDerivE, false, 0, 1, true, false); // partial derivative w.r.t R but V
// Downlink leg
Rvector3 downlinkDerivS, downlinkDerivE;
GetRangeDerivative(downlinkLegS, stmInv, downlinkDerivS, true, 1, 0, true, false); // for downlink leg, transmiter is spacecarft (index = 1), receiver is station (index = 0), derivative w.r.t transmiter object is true (w.r.t spacecraft)
GetRangeDerivative(downlinkLegE, stmInv, downlinkDerivE, true, 1, 0, true, false); // partial derivative w.r.t R but V
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage("uplinkLegS derivative : %s\n",uplinkDerivS.ToString().c_str());
MessageInterface::ShowMessage("downlinkLegS derivative : %s\n\n",downlinkDerivS.ToString().c_str());
MessageInterface::ShowMessage("uplinkLegE derivative : %s\n",uplinkDerivE.ToString().c_str());
MessageInterface::ShowMessage("downlinkLegE derivative : %s\n\n",downlinkDerivE.ToString().c_str());
#endif
for (Integer i = 0; i < size; ++i)
{
currentDerivatives[0][i] = preFactorE * (uplinkDerivE[i] + downlinkDerivE[i]) -
preFactorS * (uplinkDerivS[i] + downlinkDerivS[i]);
}
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage("Position Derivative: [%.12lf "
"%.12lf %.12lf]\n", currentDerivatives[0][0],
currentDerivatives[0][1], currentDerivatives[0][2]);
#endif
}
else if (objPtr->GetParameterText(parameterID) == "Velocity")
{
// Get the inverse of the orbit STM at the measurement epoch
// Will need adjustment if stm changes
Rmatrix stmInv(6,6);
GetInverseSTM(obj, stmInv);
Rvector3 uplinkDerivS, uplinkDerivE;
GetRangeDerivative(uplinkLegS, stmInv, uplinkDerivS, false, 0, 1, false, true); // for uplink leg, transmiter is station (index = 0), receiver is spacecraft (index = 1), derivative w.r.t transmiter object is false (w.r.t spacecraft)
GetRangeDerivative(uplinkLegE, stmInv, uplinkDerivE, false, 0, 1, false, true); // partial derivative w.r.t V but R
// Downlink leg
Rvector3 downlinkDerivS, downlinkDerivE;
GetRangeDerivative(downlinkLegS, stmInv, downlinkDerivS, true, 1, 0, false, true); // for downlink leg, transmiter is spacecarft (index = 1), receiver is station (index = 0), derivative w.r.t transmiter object is true (w.r.t spacecraft)
GetRangeDerivative(downlinkLegE, stmInv, downlinkDerivE, true, 1, 0, false, true); // partial derivative w.r.t V but R
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage("uplinkLegS derivative : %s\n",uplinkDerivS.ToString().c_str());
MessageInterface::ShowMessage("downlinkLegS derivative : %s\n\n",downlinkDerivS.ToString().c_str());
MessageInterface::ShowMessage("uplinkLegE derivative : %s\n",uplinkDerivE.ToString().c_str());
MessageInterface::ShowMessage("downlinkLegE derivative : %s\n\n",downlinkDerivE.ToString().c_str());
#endif
for (Integer i = 0; i < size; ++i)
{
currentDerivatives[0][i] = preFactorE * (uplinkDerivE[i] + downlinkDerivE[i]) -
preFactorS * (uplinkDerivS[i] + downlinkDerivS[i]);
}
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage("Velocity Derivative: [%.12lf "
"%.12lf %.12lf]\n", currentDerivatives[0][0],
currentDerivatives[0][1], currentDerivatives[0][2]);
#endif
}
else if (objPtr->GetParameterText(parameterID) == "CartesianX")
{
// Get the inverse of the orbit STM at the measurement epoch
// Will need adjustment if stm changes
Rmatrix stmInv(6,6);
GetInverseSTM(obj, stmInv);
Rvector6 uplinkDerivS, uplinkDerivE;
// GetRangeDerivative(uplinkLegS, stmInv, uplinkDerivS, false, 0, 1, true, true); // for uplink leg, transmiter is station (index = 0), receiver is spacecraft (index = 1), derivative w.r.t transmiter object is false (w.r.t spacecraft)
// GetRangeDerivative(uplinkLegE, stmInv, uplinkDerivE, false, 0, 1, true, true); // partial derivative w.r.t R and V
GetRangeDerivative(uplinkLegS, stmInv, uplinkDerivS, false); // for uplink leg, transmiter is station (index = 0), receiver is spacecraft (index = 1), derivative w.r.t transmiter object is false (w.r.t spacecraft)
GetRangeDerivative(uplinkLegE, stmInv, uplinkDerivE, false); // partial derivative w.r.t R and V
// Downlink leg
Rvector6 downlinkDerivS, downlinkDerivE;
// GetRangeDerivative(downlinkLegS, stmInv, downlinkDerivS, true, 1, 0, true, true); // for downlink leg, transmiter is spacecarft (index = 1), receiver is station (index = 0), derivative w.r.t transmiter object is true (w.r.t spacecraft)
// GetRangeDerivative(downlinkLegE, stmInv, downlinkDerivE, true, 1, 0, true, true); // partial derivative w.r.t R and V
GetRangeDerivative(downlinkLegS, stmInv, downlinkDerivS, false); // for downlink leg, transmiter is spacecarft (index = 1), receiver is station (index = 0), derivative w.r.t transmiter object is true (w.r.t spacecraft)
GetRangeDerivative(downlinkLegE, stmInv, downlinkDerivE, false); // partial derivative w.r.t R and V
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage("uplinkLegS derivative : %s\n",uplinkDerivS.ToString().c_str());
MessageInterface::ShowMessage("downlinkLegS derivative : %s\n\n",downlinkDerivS.ToString().c_str());
MessageInterface::ShowMessage("uplinkLegE derivative : %s\n",uplinkDerivE.ToString().c_str());
MessageInterface::ShowMessage("downlinkLegE derivative : %s\n\n",downlinkDerivE.ToString().c_str());
#endif
for (Integer i = 0; i < size; ++i)
{
currentDerivatives[0][i] = preFactorE * (uplinkDerivE[i] + downlinkDerivE[i]) -
preFactorS * (uplinkDerivS[i] + downlinkDerivS[i]);
}
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage("CartesianState Derivative: "
"[%.12lf %.12lf %.12lf %.12lf %.12lf %.12lf]\n",
currentDerivatives[0][0], currentDerivatives[0][1],
currentDerivatives[0][2], currentDerivatives[0][3],
currentDerivatives[0][4], currentDerivatives[0][5]);
#endif
}
else if (objPtr->GetParameterText(parameterID) == "Bias")
{
for (Integer i = 0; i < size; ++i)
currentDerivatives[0][i] = 1.0;
}
else
{
for (Integer i = 0; i < size; ++i)
currentDerivatives[0][i] = 0.0;
}
}
else if (objNumber == 0) // measurement model
{
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Deriv is w.r.t. %s of the "
"measurement model\n",
objPtr->GetParameterText(parameterID).c_str());
#endif
if (objPtr->GetParameterText(parameterID) == "Bias")
{
for (Integer i = 0; i < size; ++i)
currentDerivatives[0][i] = 1.0;
}
}
else
{
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Deriv is w.r.t. %s of a non-"
"Participant\n",
objPtr->GetParameterText(parameterID).c_str());
#endif
for (Integer i = 0; i < size; ++i)
currentDerivatives[0][i] = 0.0;
}
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Deriv =\n ");
for (Integer i = 0; i < size; ++i)
MessageInterface::ShowMessage(" %.12le",currentDerivatives[0][i]);
MessageInterface::ShowMessage("\n");
#endif
}
return currentDerivatives;
}
//------------------------------------------------------------------------------
// bool Evaluate(bool withEvents)
//------------------------------------------------------------------------------
/**
* Evaluates the measurement
*
* When evaluated without events, the DSN 2-way Doppler measurement value is
* always zero. That evaluation is used to determine is there is a nominal
* (geometric) line of sight between the participants at the measurement epoch.
*
* @param withEvents Flag used to trigger usage of data from event evaluation as
* part of the measurement
*
* @return true if the event is feasible, false if it could not be calculated
* or is infeasible
*/
//------------------------------------------------------------------------------
//#define USE_EARTHMJ2000EQ_CS
bool DSNTwoWayDoppler::Evaluate(bool withEvents)
{
bool retval = false;
if (!initialized)
InitializeMeasurement();
#ifdef DEBUG_DOPPLER_CALC
MessageInterface::ShowMessage("Entered DSNTwoWayDoppler::Evaluate()\n");
MessageInterface::ShowMessage(" ParticipantCount: %d\n",
participants.size());
#endif
// Get minimum elevation angle from ground station
Real minAngle;
if (participants[0]->IsOfType(Gmat::SPACECRAFT) == false)
minAngle = ((GroundstationInterface*)participants[0])->GetRealParameter("MinimumElevationAngle");
else if (participants[1]->IsOfType(Gmat::SPACECRAFT) == false)
minAngle = ((GroundstationInterface*)participants[1])->GetRealParameter("MinimumElevationAngle");
if (withEvents == false)
{
#ifdef DEBUG_DOPPLER_CALC
MessageInterface::ShowMessage("DSN 2-Way Doppler Calculation without "
"events\n");
#endif
#ifdef VIEW_PARTICIPANT_STATES
DumpParticipantStates("++++++++++++++++++++++++++++++++++++++++++++\n"
"Evaluating DSN 2-Way Doppler without events");
#endif
CalculateRangeVectorInertial();
Rvector3 outState;
// Set feasibility off of topocentric horizon, set by the Z value in topo
// coords
std::string updateAll = "All";
UpdateRotationMatrix(currentMeasurement.epoch, updateAll);
// outState = R_o_j2k * rangeVecInertial;
// currentMeasurement.feasibilityValue = outState[2];
outState = (R_o_j2k * rangeVecInertial).GetUnitVector();
currentMeasurement.feasibilityValue = asin(outState[2])*GmatMathConstants::DEG_PER_RAD; // elevation angle in degree
#ifdef CHECK_PARTICIPANT_LOCATIONS
MessageInterface::ShowMessage("Evaluating without events\n");
MessageInterface::ShowMessage("Calculating DSN 2-Way Doppler at epoch "
"%.12lf\n", currentMeasurement.epoch);
MessageInterface::ShowMessage(" J2K Location of %s, id = '%s': %s",
participants[0]->GetName().c_str(),
currentMeasurement.participantIDs[0].c_str(),
p1Loc.ToString().c_str());
MessageInterface::ShowMessage(" J2K Location of %s, id = '%s': %s",
participants[1]->GetName().c_str(),
currentMeasurement.participantIDs[1].c_str(),
p2Loc.ToString().c_str());
Rvector3 bfLoc = R_o_j2k * p1Loc;
MessageInterface::ShowMessage(" BodyFixed Location of %s: %s",
participants[0]->GetName().c_str(),
bfLoc.ToString().c_str());
bfLoc = R_o_j2k * p2Loc;
MessageInterface::ShowMessage(" BodyFixed Location of %s: %s\n",
participants[1]->GetName().c_str(),
bfLoc.ToString().c_str());
#endif
// if (currentMeasurement.feasibilityValue > minAngle)
{
currentMeasurement.isFeasible = true;
currentMeasurement.value[0] = 2*rangeVecInertial.GetMagnitude(); // It is set to range value
currentMeasurement.eventCount = 4;
retval = true;
}
// else
// {
// currentMeasurement.isFeasible = false;
// currentMeasurement.value[0] = 0.0;
// currentMeasurement.eventCount = 0;
// }
#ifdef DEBUG_DOPPLER_CALC
MessageInterface::ShowMessage("Calculating Range at epoch %.12lf\n",
currentMeasurement.epoch);
MessageInterface::ShowMessage(" Location of %s, id = '%s': %s",
participants[0]->GetName().c_str(),
currentMeasurement.participantIDs[0].c_str(),
p1Loc.ToString().c_str());
MessageInterface::ShowMessage(" Location of %s, id = '%s': %s",
participants[1]->GetName().c_str(),
currentMeasurement.participantIDs[1].c_str(),
p2Loc.ToString().c_str());
MessageInterface::ShowMessage(" Range Vector: %s\n",
rangeVecInertial.ToString().c_str());
MessageInterface::ShowMessage(" Elevation angle = %lf degree\n",
currentMeasurement.feasibilityValue);
MessageInterface::ShowMessage(" Feasibility: %s\n",
(currentMeasurement.isFeasible ? "true" : "false"));
MessageInterface::ShowMessage(" Range is %.12lf\n",
currentMeasurement.value[0]);
MessageInterface::ShowMessage(" EventCount is %d\n",
currentMeasurement.eventCount);
#endif
#ifdef SHOW_RANGE_CALC
MessageInterface::ShowMessage("Range at epoch %.12lf is ",
currentMeasurement.epoch);
if (currentMeasurement.isFeasible)
MessageInterface::ShowMessage("feasible, value = %.12lf\n",
currentMeasurement.value[0]);
else
MessageInterface::ShowMessage("not feasible\n");
#endif
}
else
{
// Calculate the corrected range measurement
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("DSN 2-Way Doppler Calculation:\n");
#endif
#ifdef VIEW_PARTICIPANT_STATES_WITH_EVENTS
DumpParticipantStates("********************************************\n"
"Evaluating DSN 2-Way Doppler with located events");
#endif
SpecialCelestialPoint* ssb = solarSystem->GetSpecialPoint("SolarSystemBarycenter");
std::string cbName1 = ((SpacePoint*)participants[0])->GetJ2000BodyName();
CelestialBody* cb1 = solarSystem->GetBody(cbName1);
std::string cbName2 = ((SpacePoint*)participants[1])->GetJ2000BodyName();
CelestialBody* cb2 = solarSystem->GetBody(cbName2);
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
//MessageInterface::ShowMessage("For Measurement S:\n");
MessageInterface::ShowMessage("1. Range and range rate for measurement S:\n");
#endif
// 1. Get the range from the down link leg for measurement S:
Rvector3 r1S, r2S; // position of downlink leg's participants in central body MJ2000Eq coordinate system
Rvector3 r1SB, r2SB; // position of downlink leg's participants in solar system bary center MJ2000Eq coordinate system
Real t3RS, t2TS;
r1S = downlinkLegS.GetPosition(participants[0]); // position of station at reception time t3R in central body MJ2000Eq coordinate system
r2S = downlinkLegS.GetPosition(participants[1]); // position of spacecraft at transmit time t2T in central body MJ2000Eq coordinate system
t3RS = downlinkLegS.GetEventData((GmatBase*) participants[0]).epoch; // reception time t3R at station for downlink leg
t2TS = downlinkLegS.GetEventData((GmatBase*) participants[1]).epoch; // transmit time t2T at spacecraft for downlink leg
Rvector3 ssb2cb_t3RS = cb1->GetMJ2000Position(t3RS) - ssb->GetMJ2000Position(t3RS); // vector from solar system bary center to central body in SSB MJ2000Eq coordinate system at time t3R
Rvector3 ssb2cb_t2TS = cb2->GetMJ2000Position(t2TS) - ssb->GetMJ2000Position(t2TS); // vector from solar system bary center to central body in SSB MJ2000Eq coordinate system at time t2T
r1SB = ssb2cb_t3RS + r1S; // position of station at reception time t3R in SSB coordinate system
r2SB = ssb2cb_t2TS + r2S; // position of spacecraft at transmit time t2T in SSB coordinate system
# ifdef USE_EARTHMJ2000EQ_CS
Rvector3 downlinkVectorS = r2S - r1S; // down link vector in EarthMJ2000Eq coordinate system
#else
Rvector3 downlinkVectorS = r2SB - r1SB; // down link vector in SSB coordinate system
#endif
Real downlinkRangeS = downlinkVectorS.GetMagnitude(); // down link range (unit: km)
// Calculate ET-TAI at t3RS:
Real ettaiT3S = downlinkLegS.ETminusTAI(t3RS, (GmatBase*)participants[0]);
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
Rmatrix33 mtS = downlinkLegS.GetEventData((GmatBase*) participants[0]).rInertial2obj.Transpose();
MessageInterface::ShowMessage("1.1. Downlink leg range for measurement S:\n");
MessageInterface::ShowMessage(" Station %s position in %sMJ2000 coordinate system : r1S = (%.12lf, %.12lf, %.12lf) km at epoch t3R = %.12lf\n", participants[0]->GetName().c_str(), participants[0]->GetJ2000BodyName().c_str(), r1S(0), r1S(1), r1S(2), t3RS);
MessageInterface::ShowMessage(" Spacecraft %s position in %sMJ2000 coordinate system : r2S = (%.12lf, %.12lf, %.12lf) km at epoch t2T = %.12lf\n", participants[1]->GetName().c_str(), participants[1]->GetJ2000BodyName().c_str(), r2S(0), r2S(1), r2S(2), t2TS);
MessageInterface::ShowMessage(" Station %s position in SSB inertial coordinate system : r1SB = (%.12lf, %.12lf, %.12lf) km at epoch t3R = %.12lf\n", participants[0]->GetName().c_str(), r1SB(0), r1SB(1), r1SB(2), t3RS);
MessageInterface::ShowMessage(" Spacecraft %s position in SSB inertial coordinate system: r2SB = (%.12lf, %.12lf, %.12lf) km at epoch t2T = %.12lf\n", participants[1]->GetName().c_str(), r2SB(0), r2SB(1), r2SB(2), t2TS);
MessageInterface::ShowMessage(" Transformation matrix from Earth fixed coordinate system to FK5 coordinate system at epoch t3R = %.12lf:\n", t3RS);
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mtS(0,0), mtS(0,1), mtS(0,2));
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mtS(1,0), mtS(1,1), mtS(1,2));
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mtS(2,0), mtS(2,1), mtS(2,2));
#ifdef USE_EARTHMJ2000EQ_CS
MessageInterface::ShowMessage(" Downlink vector in EarthMJ2000Eq coordinate system: downlinkVectorS = r2S - r1S = (%.12lf, %.12lf, %.12lf) km\n", downlinkVectorS(0), downlinkVectorS(1), downlinkVectorS(2));
#else
MessageInterface::ShowMessage(" Downlink vector in SSB inertial coordinate system: downlinkVectorS = r2SB - r1SB = (%.12lf, %.12lf, %.12lf) km\n", downlinkVectorS(0), downlinkVectorS(1), downlinkVectorS(2));
#endif
MessageInterface::ShowMessage(" Downlink range without relativity correction: %.12lf km\n",downlinkRangeS);
MessageInterface::ShowMessage(" Relativity correction for downlink leg : %.12lf km\n", downlinkLegS.GetRelativityCorrection());
MessageInterface::ShowMessage(" Downlink range with relativity correction : %.12lf km\n", downlinkLegS.GetRelativityCorrection() + downlinkRangeS);
MessageInterface::ShowMessage(" (ET-TAI) at t3RS = %.12le s\n", ettaiT3S);
#endif
// 2. Calculate down link range rate for measurement S:
Rvector3 p1VS = downlinkLegS.GetVelocity(participants[0]); // velocity of station at reception time t3R in central body MJ2000 coordinate system
Rvector3 p2VS = downlinkLegS.GetVelocity(participants[1]); // velocity of spacecraft at transmit time t2T in central body MJ2000 coordinate system
Rvector3 ssb2cbV_t3RS = cb1->GetMJ2000Velocity(t3RS) - ssb->GetMJ2000Velocity(t3RS); // velocity of central body at time t3R w.r.t SSB MJ2000Eq coordinate system
Rvector3 ssb2cbV_t2TS = cb2->GetMJ2000Velocity(t2TS) - ssb->GetMJ2000Velocity(t2TS); // velocity of central body at time t2T w.r.t SSB MJ2000Eq coordinate system
Rvector3 p1VSB = ssb2cbV_t3RS + p1VS; // velocity of station at reception time t3R in SSB coordinate system
Rvector3 p2VSB = ssb2cbV_t2TS + p2VS; // velocity of spacecraft at transmit time t2T in SSB coordinate system
// @todo Relative origin velocities need to be subtracted when the origins
// differ; check and fix that part using r12_j2k_vel here. It's not yet
// incorporated because we need to handle the different epochs for the
// bodies, and we ought to do this part in barycentric coordinates
#ifdef USE_EARTHMJ2000EQ_CS
Rvector3 downRRateVecS = p2VS - p1VS;
#else
Rvector3 downRRateVecS = p2VSB - p1VSB /* - r12_j2k_vel*/;
#endif
Rvector3 rangeUnit = downlinkVectorS.GetUnitVector();
downlinkRangeRate[0] = downRRateVecS * rangeUnit;
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("1.2. Downlink leg range rate for measurement S:\n");
MessageInterface::ShowMessage(" Station %s velocity in %sMJ2000 coordinate system : p1VS = (%.12lf, %.12lf, %.12lf)km/s\n", participants[0]->GetName().c_str(), participants[0]->GetJ2000BodyName().c_str(), p1VS(0), p1VS(1), p1VS(2));
MessageInterface::ShowMessage(" Spacecraft %s velocity in %sMJ2000 coordinate system : p2VS = (%.12lf, %.12lf, %.12lf)km/s\n", participants[1]->GetName().c_str(), participants[1]->GetJ2000BodyName().c_str(), p2VS(0), p2VS(1), p2VS(2));
MessageInterface::ShowMessage(" Station %s velocity in SSB inertial coordinate system : p1VSB = (%.12lf, %.12lf, %.12lf)km/s\n", participants[0]->GetName().c_str(), p1VSB(0), p1VSB(1), p1VSB(2));
MessageInterface::ShowMessage(" Spacecraft %s velocity in SSB inertial coordinate system : p2VSB = (%.12lf, %.12lf, %.12lf)km/s\n", participants[1]->GetName().c_str(), p2VSB(0), p2VSB(1), p2VSB(2));
#ifdef USE_EARTHMJ2000EQ_CS
MessageInterface::ShowMessage(" Spacecraft velocity w/r/t Station in EarthMJ2000Eq coordinate system: downRRateVecS = (%.12lf, %.12lf, %.12lf)km/s\n", downRRateVecS(0), downRRateVecS(1), downRRateVecS(2));
#else
MessageInterface::ShowMessage(" Spacecraft velocity w/r/t Station in SSB inertial coordinate system: downRRateVecS = (%.12lf, %.12lf, %.12lf)km/s\n", downRRateVecS(0), downRRateVecS(1), downRRateVecS(2));
#endif
MessageInterface::ShowMessage(" Downlink range Rate: downlinkRangeRateS = %.12lf km/s\n", downlinkRangeRate[0]);
//MessageInterface::ShowMessage(" .Downlink Range Rate: %.12lf km/s\n", downlinkRangeRate[0]);
#endif
// 3. Get the range from the up link leg for measurement S:
Rvector3 r3S, r4S; // position of uplink leg's participants in central body MJ2000Eq coordinate system
Rvector3 r3SB, r4SB; // position of uplink leg's participants in Solar system bary center inertial coordinate system
Real t1TS, t2RS;
r3S = uplinkLegS.GetPosition(participants[0]); // position of station at transmit time t1T in central body MJ2000Eq coordinate system
r4S = uplinkLegS.GetPosition(participants[1]); // position of spacecraft at reception time t2R in central body MJ2000Eq coordinate system
t1TS = uplinkLegS.GetEventData((GmatBase*) participants[0]).epoch; // transmit time t1T at station for uplink leg
t2RS = uplinkLegS.GetEventData((GmatBase*) participants[1]).epoch; // reception time t2R at spacecraft for uplink leg
Rvector3 ssb2cb_t1TS = cb1->GetMJ2000Position(t1TS) - ssb->GetMJ2000Position(t1TS); // vector from solar system bary center to central body in SSB MJ2000Eq coordinate system at time t1T
Rvector3 ssb2cb_t2RS = cb2->GetMJ2000Position(t2RS) - ssb->GetMJ2000Position(t2RS); // vector from solar system bary center to central body in SSB MJ2000Eq coordinate system at time t2R
r3SB = ssb2cb_t1TS + r3S; // position of station at transmit time t1T in SSB coordinate system
r4SB = ssb2cb_t2TS + r4S; // position of spacecraft at reception time t2R in SSB coordinate system
#ifdef USE_EARTHMJ2000EQ_CS
Rvector3 uplinkVectorS = r4S - r3S;
#else
Rvector3 uplinkVectorS = r4SB - r3SB;
#endif
Real uplinkRangeS = uplinkVectorS.GetMagnitude();
// Calculate ET-TAI at t1TS:
Real ettaiT1S = uplinkLegS.ETminusTAI(t1TS, (GmatBase*)participants[0]);
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
Rmatrix33 mtS1 = uplinkLegS.GetEventData((GmatBase*) participants[0]).rInertial2obj.Transpose();
MessageInterface::ShowMessage("1.3. Uplink leg range for measurement S:\n");
MessageInterface::ShowMessage(" Spacecraft %s position in %sMJ2000 coordinate system : r4S = (%.12lf, %.12lf, %.12lf) km at epoch t2RS = %.12lf\n", participants[1]->GetName().c_str(), participants[1]->GetJ2000BodyName().c_str(), r4S(0), r4S(1), r4S(2), t2RS);
MessageInterface::ShowMessage(" Station %s position in %sMJ2000 coordinate system : r3S = (%.12lf, %.12lf, %.12lf) km at epoch t1TS = %.12lf\n", participants[0]->GetName().c_str(), participants[0]->GetJ2000BodyName().c_str(), r3S(0), r3S(1), r3S(2), t1TS);
MessageInterface::ShowMessage(" Spacecraft %s position in SSB inertial coordinate system: r4SB = (%.12lf, %.12lf, %.12lf) km at epoch t2RS = %.12lf\n", participants[1]->GetName().c_str(), r4SB(0), r4SB(1), r4SB(2), t2RS);
MessageInterface::ShowMessage(" Station %s position in SSB inertial coordinate system : r3SB = (%.12lf, %.12lf, %.12lf) km at epoch t1TS = %.12lf\n", participants[0]->GetName().c_str(), r3SB(0), r3SB(1), r3SB(2), t1TS);
MessageInterface::ShowMessage(" Transformation matrix from Earth fixed coordinate system to FK5 coordinate system at epoch tS3 = %.12lf:\n", t1TS);
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mtS1(0,0), mtS1(0,1), mtS1(0,2));
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mtS1(1,0), mtS1(1,1), mtS1(1,2));
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mtS1(2,0), mtS1(2,1), mtS1(2,2));
#ifdef USE_EARTHMJ2000EQ_CS
MessageInterface::ShowMessage(" Uplink vector in EarthMJ2000Eq coordinate system: uplinkVectorS = r4S - r3S = (%.12lf, %.12lf, %.12lf) km\n", uplinkVectorS(0), uplinkVectorS(1), uplinkVectorS(2));
#else
MessageInterface::ShowMessage(" Uplink vector in SSB inertial coordinate system: uplinkVectorS = r4SB - r3SB = (%.12lf, %.12lf, %.12lf) km\n", uplinkVectorS(0), uplinkVectorS(1), uplinkVectorS(2));
#endif
MessageInterface::ShowMessage(" Uplink range without ralativity correction: %.12lf km\n", uplinkRangeS);
MessageInterface::ShowMessage(" Relativity correction for uplink leg : %.12lf km\n", uplinkLegS.GetRelativityCorrection());
MessageInterface::ShowMessage(" Uplink range with relativity correction : %.12lf km\n", uplinkLegS.GetRelativityCorrection() + uplinkRangeS);
MessageInterface::ShowMessage(" (ET-TAI) at t1TS = %.12le s\n", ettaiT1S);
#endif
// 4. Calculate up link range rate for measurement S:
Rvector3 p3VS = uplinkLegS.GetVelocity(participants[0]); // velocity of station at transmit time t1T in central body MJ2000 coordinate system
Rvector3 p4VS = uplinkLegS.GetVelocity(participants[1]); // velocity of specraft at reception time t2R in central body MJ2000 coordinate system
Rvector3 ssb2cbV_t1TS = cb1->GetMJ2000Velocity(t1TS) - ssb->GetMJ2000Velocity(t1TS); // velocity of central body at time t1T w.r.t SSB inertial coordinate system
Rvector3 ssb2cbV_t2RS = cb2->GetMJ2000Velocity(t2RS) - ssb->GetMJ2000Velocity(t2RS); // velocity of central body at time t2R w.r.t SSB inertial coordinate system
Rvector3 p3VSB = ssb2cbV_t1TS + p3VS; // velocity of station at transmit time t1T in SSB inertial coordinate system
Rvector3 p4VSB = ssb2cbV_t2RS + p4VS; // velocity of spacecraft at reception time t2R in SSB inertial coordinate system
// @todo Relative origin velocities need to be subtracted when the origins
// differ; check and fix that part using r12_j2k_vel here. It's not yet
// incorporated because we need to handle the different epochs for the
// bodies, and we ought to do this part in barycentric coordinates
#ifdef USE_EARTHMJ2000EQ_CS
Rvector3 upRRateVecS = p4VS - p3VS;
#else
Rvector3 upRRateVecS = p4VSB - p3VSB /* - r12_j2k_vel*/ ;
#endif
rangeUnit = uplinkVectorS.GetUnitVector();
uplinkRangeRate[0] = upRRateVecS * rangeUnit;
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("1.4. Uplink leg range rate for measurement S:\n");
MessageInterface::ShowMessage(" Station %s velocity in %sMJ2000 coordinate system : p3VS = (%.12lf, %.12lf, %.12lf)km/s\n", participants[0]->GetName().c_str(), participants[0]->GetJ2000BodyName().c_str(), p3VS(0), p3VS(1), p3VS(2));
MessageInterface::ShowMessage(" Spacecraft %s velocity in %sMJ2000 coordinate system : p4VS = (%.12lf, %.12lf, %.12lf)km/s\n", participants[1]->GetName().c_str(), participants[1]->GetJ2000BodyName().c_str(), p4VS(0), p4VS(1), p4VS(2));
MessageInterface::ShowMessage(" Station %s velocity in SSB inertial coordinate system : p3VSB = (%.12lf, %.12lf, %.12lf)km/s\n", participants[0]->GetName().c_str(), p3VSB(0), p3VSB(1), p3VSB(2));
MessageInterface::ShowMessage(" Spacecraft %s velocity in SSB inertial coordinate system: p4VSB = (%.12lf, %.12lf, %.12lf)km/s\n", participants[1]->GetName().c_str(), p4VSB(0), p4VSB(1), p4VSB(2));
#ifdef USE_EARTHMJ2000EQ_CS
MessageInterface::ShowMessage(" Spacecraft velocity w/r/t Station in EarthMJ2000Eq coordinate system: upRRateVecS = (%.12lf, %.12lf, %.12lf)km/s\n", upRRateVecS(0), upRRateVecS(1), upRRateVecS(2));
#else
MessageInterface::ShowMessage(" Spacecraft velocity w/r/t Station in SSB inertial coordinate system: upRRateVecS = (%.12lf, %.12lf, %.12lf)km/s\n", upRRateVecS(0), upRRateVecS(1), upRRateVecS(2));
#endif
MessageInterface::ShowMessage(" Uplink range rate: uplinkRangeRateS = %.12lf km/s\n", uplinkRangeRate[0]);
#endif
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("1.5. Travel time and delays for measurement S:\n");
MessageInterface::ShowMessage(" Uplink travel time w/o relativity, media corrections : %.12lf s\n", uplinkRangeS*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM);
MessageInterface::ShowMessage(" Downlink travel time w/o relativity, media corrections: %.12lf s\n", downlinkRangeS*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM);
MessageInterface::ShowMessage(" Delay between receiving and transmitting signal on participant 2: %.12lf s\n", (t2TS - t2RS)*86400);
#endif
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("2. Range and range rate for measurement E:\n");
//MessageInterface::ShowMessage("For Measurement E:\n");
#endif
// 5. Get the range from the down link leg for measurement E:
Rvector3 r1E, r2E; // position of downlink leg's participants in central body MJ2000Eq coordinate system
Rvector3 r1EB, r2EB; // position of downlink leg's participants in Solar system bary center inertial coordinate system
Real t3RE, t2TE;
r1E = downlinkLegE.GetPosition(participants[0]); // position of station at reception time t3R in central body MJ2000Eq coordinate system
r2E = downlinkLegE.GetPosition(participants[1]); // position of spacecraft at reception time t2T in central body MJ2000Eq coordinate system
t3RE = downlinkLegE.GetEventData((GmatBase*) participants[0]).epoch; // reception time t3R at station for downlink leg
t2TE = downlinkLegE.GetEventData((GmatBase*) participants[1]).epoch; // transmit time t2T at spacecraft for downlink leg
Rvector3 ssb2cb_t3RE = cb1->GetMJ2000Position(t3RE) - ssb->GetMJ2000Position(t3RE); // vector from solar system bary center to central body in SSB MJ2000Eq coordinate system at time t3R
Rvector3 ssb2cb_t2TE = cb2->GetMJ2000Position(t2TE) - ssb->GetMJ2000Position(t2TE); // vector from solar system bary center to central body in SSB MJ2000Eq coordinate system at time t2T
r1EB = ssb2cb_t3RE + r1E; // position of station at reception time t3R in SSB coordinate system
r2EB = ssb2cb_t2TE + r2E; // position of spacecraft at transmit time t2T in SSB coordinate system
#ifdef USE_EARTHMJ2000EQ_CS
Rvector3 downlinkVectorE = r2E - r1E;
#else
Rvector3 downlinkVectorE = r2EB - r1EB; // down link vector in SSB coordinate system
#endif
Real downlinkRangeE = downlinkVectorE.GetMagnitude(); // down link range (unit: km)
// Calculate ET-TAI at t3RE:
Real ettaiT3E = downlinkLegE.ETminusTAI(t3RE, (GmatBase*)participants[0]);
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
Rmatrix33 mtE = downlinkLegE.GetEventData((GmatBase*) participants[0]).rInertial2obj.Transpose();
MessageInterface::ShowMessage("2.1. Downlink leg range for measurement E:\n");
MessageInterface::ShowMessage(" Station %s position in %sMJ2000 coordinate system : r1E = (%.12lf, %.12lf, %.12lf) km at epoch t3RE= %.12lf\n", participants[0]->GetName().c_str(), participants[0]->GetJ2000BodyName().c_str(), r1E(0), r1E(1), r1E(2), t3RE);
MessageInterface::ShowMessage(" Spacecraft %s position in %sMJ2000 coordinate system : r2E = (%.12lf, %.12lf, %.12lf) km at epoch t2TE= %.12lf\n", participants[1]->GetName().c_str(), participants[1]->GetJ2000BodyName().c_str(), r2E(0), r2E(1), r2E(2), t2TE);
MessageInterface::ShowMessage(" Station %s position in SSB inertial coordinate system : r1EB = (%.12lf, %.12lf, %.12lf) km at epoch t3RE= %.12lf\n", participants[0]->GetName().c_str(), r1EB(0), r1EB(1), r1EB(2), t3RE);
MessageInterface::ShowMessage(" Spacecraft %s position in SSB inertial coordinate system: r2EB = (%.12lf, %.12lf, %.12lf) km at epoch t2TE= %.12lf\n", participants[1]->GetName().c_str(), r2EB(0), r2EB(1), r2EB(2), t2TE);
MessageInterface::ShowMessage(" Transformation matrix from Earth fixed coordinate system to FK5 coordinate system at epoch t3RE = %.12lf:\n", t3RE);
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mtE(0,0), mtE(0,1), mtE(0,2));
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mtE(1,0), mtE(1,1), mtE(1,2));
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mtE(2,0), mtE(2,1), mtE(2,2));
#ifdef USE_EARTHMJ2000EQ_CS
MessageInterface::ShowMessage(" Downlink vector in EarthMJ2000Eq coordinate system: downlinkVectorE = r2E - r1E = (%.12lf, %.12lf, %.12lf) km\n", downlinkVectorE(0), downlinkVectorE(1), downlinkVectorE(2));
#else
MessageInterface::ShowMessage(" Downlink vector in SSB inertial coordinate system: downlinkVectorE = r2EB - r1EB = (%.12lf, %.12lf, %.12lf) km\n", downlinkVectorE(0), downlinkVectorE(1), downlinkVectorE(2));
#endif
MessageInterface::ShowMessage(" Downlink range without relativity correction: %.12lf km\n",downlinkRangeE);
MessageInterface::ShowMessage(" Relativity correction for downlink leg : %.12lf km\n", downlinkLegE.GetRelativityCorrection());
MessageInterface::ShowMessage(" Downlink range with relativity correction : %.12lf km\n", downlinkLegE.GetRelativityCorrection() + downlinkRangeE);
MessageInterface::ShowMessage(" (ET-TAI) at t3RE = %.12le s\n", ettaiT3E);
#endif
// 6. Calculate down link range rate for measurement E:
Rvector3 p1VE = downlinkLegE.GetVelocity(participants[0]); // velocity of station at reception time t3R in central body MJ2000 coordinate system
Rvector3 p2VE = downlinkLegE.GetVelocity(participants[1]); // velocity of spacecraft at transmit time t2T in central body MJ2000 coordinate system
Rvector3 ssb2cbV_t3RE = cb1->GetMJ2000Velocity(t3RE) - ssb->GetMJ2000Velocity(t3RE); // velocity of central body at time t3R w.r.t SSB MJ2000Eq coordinate system
Rvector3 ssb2cbV_t2TE = cb2->GetMJ2000Velocity(t2TE) - ssb->GetMJ2000Velocity(t2TE); // velocity of central body at time t2T w.r.t SSB MJ2000Eq coordinate system
Rvector3 p1VEB = ssb2cbV_t3RE + p1VE; // velocity of station at reception time t3R in SSB coordinate system
Rvector3 p2VEB = ssb2cbV_t2TE + p2VE; // velocity of spacecraft at transmit time t2T in SSB coordinate system
// @todo Relative origin velocities need to be subtracted when the origins
// differ; check and fix that part using r12_j2k_vel here. It's not yet
// incorporated because we need to handle the different epochs for the
// bodies, and we ought to do this part in barycentric coordinates
#ifdef USE_EARTHMJ2000EQ_CS
Rvector3 downRRateVecE = p2VE - p1VE;
#else
Rvector3 downRRateVecE = p2VEB - p1VEB /* - r12_j2k_vel*/;
#endif
rangeUnit = downlinkVectorE.GetUnitVector();
downlinkRangeRate[1] = downRRateVecE * rangeUnit;
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("2.2. Downlink leg range rate for measurement E:\n");
MessageInterface::ShowMessage(" Station %s velocity in %sMJ2000 coordiante system : p1VE = (%.12lf, %.12lf, %.12lf)km/s\n", participants[0]->GetName().c_str(), participants[0]->GetJ2000BodyName().c_str(), p1VE(0), p1VE(1), p1VE(2));
MessageInterface::ShowMessage(" Spacecraft %s velocity in %sMJ2000 coordiante system : p2VE = (%.12lf, %.12lf, %.12lf)km/s\n", participants[1]->GetName().c_str(), participants[1]->GetJ2000BodyName().c_str(), p2VE(0), p2VE(1), p2VE(2));
MessageInterface::ShowMessage(" Station %s velocity in SSB inertial coordiante system : p1VEB = (%.12lf, %.12lf, %.12lf)km/s\n", participants[0]->GetName().c_str(), p1VEB(0), p1VEB(1), p1VEB(2));
MessageInterface::ShowMessage(" Spacecraft %s velocity in SSB inertial coordiante system: p2VEB = (%.12lf, %.12lf, %.12lf)km/s\n", participants[1]->GetName().c_str(), p2VEB(0), p2VEB(1), p2VEB(2));
#ifdef USE_EARTHMJ2000EQ_CS
MessageInterface::ShowMessage(" Spacecraft velocity w/r/t Station in EarthMJ2000Eq coordinate system: downRRateVecE = (%.12lf, %.12lf, %.12lf)km/s\n", downRRateVecE(0), downRRateVecE(1), downRRateVecE(2));
#else
MessageInterface::ShowMessage(" Spacecraft velocity w/r/t Station in SSB inertial coordinate system: downRRateVecE = (%.12lf, %.12lf, %.12lf)km/s\n", downRRateVecE(0), downRRateVecE(1), downRRateVecE(2));
#endif
MessageInterface::ShowMessage(" Downlink range Rate: downlinkRangeRateE = %.12lf km/s\n", downlinkRangeRate[1]);
#endif
// 7. Get the range from the up link leg for measurement E:
Rvector3 r3E, r4E; // position of uplink leg's participants in central body MJ2000Eq coordinate system
Rvector3 r3EB, r4EB; // position of uplink leg's participants in Solar system bary center inertial coordinate system
Real t1TE, t2RE;
r3E = uplinkLegE.GetPosition(participants[0]); // position of station at transmit time t1T in central body MJ2000Eq coordinate system
r4E = uplinkLegE.GetPosition(participants[1]); // position of spacecraft at reception time t2R in central body MJ2000Eq coordinate system
t1TE = uplinkLegE.GetEventData((GmatBase*) participants[0]).epoch; // transmit time t1T at station for uplink leg
t2RE = uplinkLegE.GetEventData((GmatBase*) participants[1]).epoch; // reception time t2R at spacecraft for uplink leg
Rvector3 ssb2cb_t1TE = cb1->GetMJ2000Position(t1TE) - ssb->GetMJ2000Position(t1TE); // vector from solar system bary center to central body in SSB MJ2000Eq coordinate system at time t1T
Rvector3 ssb2cb_t2RE = cb2->GetMJ2000Position(t2RE) - ssb->GetMJ2000Position(t2RE); // vector from solar system bary center to central body in SSB MJ2000Eq coordinate system at time t2R
r3EB = ssb2cb_t1TE + r3E; // position of station at transmit time t1T in SSB inertial coordinate system
r4EB = ssb2cb_t2TE + r4E; // position of spacecraft at reception time t2R in SSB inertial coordinate system
#ifdef USE_EARTHMJ2000EQ_CS
Rvector3 uplinkVectorE = r4E - r3E;
#else
Rvector3 uplinkVectorE = r4EB - r3EB;
#endif
Real uplinkRangeE = uplinkVectorE.GetMagnitude();
// Calculate ET-TAI at t1TE:
Real ettaiT1E = uplinkLegE.ETminusTAI(t1TE, (GmatBase*)participants[0]);
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
Rmatrix33 mtE1 = uplinkLegE.GetEventData((GmatBase*) participants[0]).rInertial2obj.Transpose();
MessageInterface::ShowMessage("2.3. Uplink leg range for measurement E:\n");
MessageInterface::ShowMessage(" Spacecraft %s position in %sMJ2000 coordinate system : r4E = (%.12lf, %.12lf, %.12lf) km at epoch t2RE = %.12lf\n", participants[1]->GetName().c_str(), participants[1]->GetJ2000BodyName().c_str(), r4E(0), r4E(1), r4E(2), t2RE);
MessageInterface::ShowMessage(" Station %s position in %sMJ2000 coordinate system : r3E = (%.12lf, %.12lf, %.12lf) km at epoch t1TE = %.12lf\n", participants[0]->GetName().c_str(), participants[0]->GetJ2000BodyName().c_str(), r3E(0), r3E(1), r3E(2), t1TE);
MessageInterface::ShowMessage(" Spacecraft %s position in SSB inertial coordinate system: r4EB = (%.12lf, %.12lf, %.12lf) km at epoch t2RE = %.12lf\n", participants[1]->GetName().c_str(), r4EB(0), r4EB(1), r4EB(2), t2RE);
MessageInterface::ShowMessage(" Station %s position in SSB inertial coordinate system : r3EB = (%.12lf, %.12lf, %.12lf) km at epoch t1TE = %.12lf\n", participants[0]->GetName().c_str(), r3EB(0), r3EB(1), r3EB(2), t1TE);
MessageInterface::ShowMessage(" Transformation matrix from Earth fixed coordinate system to FK5 coordinate system at epoch t1TE = %.12lf:\n", t1TE);
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mtE1(0,0), mtE1(0,1), mtE1(0,2));
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mtE1(1,0), mtE1(1,1), mtE1(1,2));
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mtE1(2,0), mtE1(2,1), mtE1(2,2));
#ifdef USE_EARTHMJ2000EQ_CS
MessageInterface::ShowMessage(" Uplink vector in EarthMJ2000Eq coordinate system: uplinkVectorE = r4E - r3E = (%.12lf, %.12lf, %.12lf) km\n", uplinkVectorE(0), uplinkVectorE(1), uplinkVectorE(2));
#else
MessageInterface::ShowMessage(" Uplink vector in SSB inertial coordinate system: uplinkVectorE = r4EB - r3EB = (%.12lf, %.12lf, %.12lf) km\n", uplinkVectorE(0), uplinkVectorE(1), uplinkVectorE(2));
#endif
MessageInterface::ShowMessage(" Uplink range without ralativity correction: %.12lf km\n", uplinkRangeE);
MessageInterface::ShowMessage(" Relativity correction for uplink leg : %.12lf km\n", uplinkLegE.GetRelativityCorrection());
MessageInterface::ShowMessage(" Uplink range with relativity correction : %.12lf km\n", uplinkLegE.GetRelativityCorrection() + uplinkRangeE);
MessageInterface::ShowMessage(" (ET-TAI) at t1TE = %.12le s\n", ettaiT1E);
#endif
// 8. Calculate up link range rate for measurement E:
Rvector3 p3VE = uplinkLegE.GetVelocity(participants[0]); // velocity of station at transmit time t1T in central body MJ2000 coordinate system
Rvector3 p4VE = uplinkLegE.GetVelocity(participants[1]); // velocity of spacecraft at reception time t2R in central body MJ2000 coordinate system
Rvector3 ssb2cbV_t1TE = cb1->GetMJ2000Velocity(t1TE) - ssb->GetMJ2000Velocity(t1TE); // velocity of central body at time t1T w.r.t SSB MJ2000Eq coordinate system
Rvector3 ssb2cbV_t2RE = cb2->GetMJ2000Velocity(t2RE) - ssb->GetMJ2000Velocity(t2RE); // velocity of central body at time t2R w.r.t SSB MJ2000Eq coordinate system
Rvector3 p3VEB = ssb2cbV_t1TE + p3VE; // velocity of station at transmit time t1T in SSB coordinate system
Rvector3 p4VEB = ssb2cbV_t2RE + p4VE; // velocity of spacecraft at reception time t2R in SSB coordinate system
// @todo Relative origin velocities need to be subtracted when the origins
// differ; check and fix that part using r12_j2k_vel here. It's not yet
// incorporated because we need to handle the different epochs for the
// bodies, and we ought to do this part in barycentric coordinates
#ifdef USE_EARTHMJ2000EQ_CS
Rvector3 upRRateVecE = p4VE - p3VE;
#else
Rvector3 upRRateVecE = p4VEB - p3VEB /* - r12_j2k_vel*/ ;
#endif
rangeUnit = uplinkVectorE.GetUnitVector();
uplinkRangeRate[1] = upRRateVecE * rangeUnit;
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("2.4. Uplink leg range rate for measurement E:\n");
MessageInterface::ShowMessage(" Station %s velocity in %sMJ2000 coordinate system : p3VE = (%.12lf, %.12lf, %.12lf)km/s\n", participants[0]->GetName().c_str(), participants[0]->GetJ2000BodyName().c_str(), p3VE(0), p3VE(1), p3VE(2));
MessageInterface::ShowMessage(" Spacecraft %s velocity in %sMJ2000 coordinate system : p4VE = (%.12lf, %.12lf, %.12lf)km/s\n", participants[1]->GetName().c_str(), participants[1]->GetJ2000BodyName().c_str(), p4VE(0), p4VE(1), p4VE(2));
MessageInterface::ShowMessage(" Station %s velocity in SSB inertial coordinate system : p3VEB = (%.12lf, %.12lf, %.12lf)km/s\n", participants[0]->GetName().c_str(), p3VEB(0), p3VEB(1), p3VEB(2));
MessageInterface::ShowMessage(" Spacecraft %s velocity in SSB inertial coordinate system: p4VEB = (%.12lf, %.12lf, %.12lf)km/s\n", participants[1]->GetName().c_str(), p4VEB(0), p4VEB(1), p4VEB(2));
#ifdef USE_EARTHMJ2000EQ_CS
MessageInterface::ShowMessage(" Spacecraft velocity w/r/t Station in EarthMJ2000Eq coordinate system: upRRateVecE = (%.12lf, %.12lf, %.12lf)km/s\n", upRRateVecE(0), upRRateVecE(1), upRRateVecE(2));
#else
MessageInterface::ShowMessage(" Spacecraft velocity w/r/t Station in SSB inertial coordinate system: upRRateVecE = (%.12lf, %.12lf, %.12lf)km/s\n", upRRateVecE(0), upRRateVecE(1), upRRateVecE(2));
#endif
MessageInterface::ShowMessage(" Uplink range rate: uplinkRangeRateE = %.12lf km/s\n", uplinkRangeRate[1]);
#endif
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("2.5. Travel time and delays for measurement E:\n");
MessageInterface::ShowMessage(" Uplink travel time : %.12lf s\n", uplinkRangeE*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM);
MessageInterface::ShowMessage(" Downlink travel time: %.12lf s\n", downlinkRangeE*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM);
MessageInterface::ShowMessage(" Delay between receiving and transmitting on participant 2: %.12lf s\n", (t2TE - t2RE)*86400);
#endif
Real dtS, dtE, dtdt, preFactor;
// 9. Get sensors used in DSN 2-ways Doppler
UpdateHardware();
if (participantHardware.empty()||
((!participantHardware.empty())&&
participantHardware[0].empty()&&
participantHardware[1].empty()
)
)
{
// Throw an exception when no hardware is defined due to signal frequency is specified base on hardware
throw MeasurementException("No transmmitter, transponder, and receiver is defined in measurement participants.\n");
return false;
}
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("Start real measurement (with hardware delay and media correction):\n");
#endif
ObjectArray objList1;
ObjectArray objList2;
ObjectArray objList3;
// objList1 := all transmitters in participantHardware list
// objList2 := all receivers in participantHardware list
// objList3 := all transponders in participantHardware list
for(std::vector<Hardware*>::iterator hw = this->participantHardware[0].begin();
hw != this->participantHardware[0].end(); ++hw)
{
if ((*hw) != NULL)
{
if ((*hw)->GetTypeName() == "Transmitter")
objList1.push_back(*hw);
if ((*hw)->GetTypeName() == "Receiver")
objList2.push_back(*hw);
}
else
MessageInterface::ShowMessage(" sensor = NULL\n");
}
for(std::vector<Hardware*>::iterator hw = this->participantHardware[1].begin();
hw != this->participantHardware[1].end(); ++hw)
{
if ((*hw) != NULL)
{
if ((*hw)->GetTypeName() == "Transponder")
objList3.push_back(*hw);
}
else
MessageInterface::ShowMessage(" sensor = NULL\n");
}
if (objList1.size() != 1)
throw MeasurementException(((objList1.size() == 0)?"Error: The first participant does not have a transmitter to send signal.\n":"Error: The first participant has more than one transmitter.\n"));
if (objList2.size() != 1)
throw MeasurementException(((objList2.size() == 0)?"Error: The first participant does not have a receiver to receive signal.\n":"Error: The first participant has more than one receiver.\n"));
if (objList3.size() != 1)
throw MeasurementException((objList3.size() == 0)?"Error: The second participant does not have a transponder to transpond signal.\n":"Error: The second participant has more than one transponder.\n");
Transmitter* gsTransmitter = (Transmitter*)objList1[0];
Receiver* gsReceiver = (Receiver*)objList2[0];
Transponder* scTransponder = (Transponder*)objList3[0];
if (gsTransmitter == NULL)
throw MeasurementException("Transmitter is NULL object.\n");
if (gsReceiver == NULL)
throw MeasurementException("Receiver is NULL object.\n");
if (scTransponder == NULL)
throw MeasurementException("Transponder is NULL object.\n");
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" List of sensors: %s, %s, %s\n",
gsTransmitter->GetName().c_str(), gsReceiver->GetName().c_str(),
scTransponder->GetName().c_str());
#endif
// 10. Get transmitter, receiver, and transponder delays:
Real transmitDelay = gsTransmitter->GetDelay();
Real receiveDelay = gsReceiver->GetDelay();
Real targetDelay = scTransponder->GetDelay();
// 11. Get frequency, frequency band, turn around ratio, and time interval:
Real uplinkFreqS, uplinkFreqE;
Real uplinkFreqAtRecei; // uplink frequency at receive epoch // unit: MHz
if (rampTB == NULL)
{
// Get uplink frequency from transmitter of ground station (participants[0])
Signal* uplinkSignal = gsTransmitter->GetSignal();
uplinkFreqS = uplinkFreqE = uplinkSignal->GetValue(); // unit: MHz
uplinkFreqAtRecei = uplinkFreqS; // unit: MHz // for constant frequency
frequency = frequencyE = uplinkFreqS*1.0e6; // unit: Hz
// Get frequency band:
if (obsData != NULL)
freqBand = freqBandE = obsData->uplinkBand; // frequency band for this case is specified by observation data
else
freqBand = freqBandE = FrequencyBand(frequency); // frequency band for this case is specified as shown in WikiPedia
// Get turn around ratio:
turnaround = scTransponder->GetTurnAroundRatio(); // the value of turn around ratio is get from GMAT script
if (turnaround == 1.0) // if the value of turn around ratio is not set by GMAT script, GMAT sets the value associated to frequency band
turnaround = GetTurnAroundRatio(freqBand);
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Uplink frequency is gotten from hardware...\n");
#endif
}
else
{
// Get uplink frequency from ramped frequency table
frequency = GetFrequencyFromRampTable(t1TS); // unit: Hz
frequencyE = GetFrequencyFromRampTable(t1TE); // unit: Hz
uplinkFreqS = frequency/1.0e6; // unit: MHz
uplinkFreqE = frequencyE/1.0e6; // unit: MHz
uplinkFreqAtRecei = GetFrequencyFromRampTable(t3RE) / 1.0e6; // unit: MHz // for ramped frequency
// Get frequency band from ramp table:
freqBand = GetUplinkBandFromRampTable(t1TS);
freqBandE = GetUplinkBandFromRampTable(t1TE);
if (freqBand != freqBandE)
throw MeasurementException("Error: Frequency bands for S path and E path are not the same. In DSNTwoWayDoppler calculation, it assumes that frequency band for S path and E path signals have to be the same !!!\n");
turnaround = GetTurnAroundRatio(freqBand); // Get value of turn around ratio associated with frequency band
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Uplink frequency is gotten from ramp table...: frequency = %.12le\n", frequency);
#endif
}
// Get time interval
// Note that: when no observation data is used, interval value obtained from GMAT script was used
if (obsData != NULL)
interval = obsData->dopplerCountInterval;
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("3. Sensors' infor:\n");
MessageInterface::ShowMessage(" List of sensors: %s, %s, %s\n",
gsTransmitter->GetName().c_str(), gsReceiver->GetName().c_str(),
scTransponder->GetName().c_str());
MessageInterface::ShowMessage(" Transmitter delay = %.12le s\n", transmitDelay);
MessageInterface::ShowMessage(" Receiver delay = %.12le s\n", receiveDelay);
MessageInterface::ShowMessage(" Transponder delay = %.12le s\n", targetDelay);
MessageInterface::ShowMessage(" UpLink signal frequency for S path = %.12le MHz\n", uplinkFreqS);
MessageInterface::ShowMessage(" UpLink signal frequency for E path = %.12le MHz\n", uplinkFreqE);
MessageInterface::ShowMessage(" frequency band for S path = %d\n", freqBand);
MessageInterface::ShowMessage(" frequency band for E path = %d\n", freqBandE);
MessageInterface::ShowMessage(" turn around ratio = %lf\n", turnaround);
MessageInterface::ShowMessage(" time interval = %lf s\n", interval);
#endif
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("4. Media Correction Calculation:\n");
#endif
// 12. Calculate for measurement S:
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("4.1. Media correction calculation for measurement S:\n");
MessageInterface::ShowMessage("4.1.1. Media correction for uplink leg:\n");
#endif
// 12.1. Calculate media correction for uplink leg:
// r3SB and r4SB are location of station and spacecraft in SSB inertial coordinate system for uplink leg for S path
RealArray uplinkCorrectionS = CalculateMediaCorrection(uplinkFreqS, r3SB, r4SB, t1TS, t2RS, minAngle);
Real uplinkRangeCorrectionS = uplinkCorrectionS[0]*GmatMathConstants::M_TO_KM + uplinkLegS.GetRelativityCorrection();
Real uplinkRealRangeS = uplinkRangeS + uplinkRangeCorrectionS;
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Uplink media correction = %.12lf m\n",uplinkCorrectionS[0]);
MessageInterface::ShowMessage(" Uplink relativity correction = %.12lf km\n",uplinkLegS.GetRelativityCorrection());
MessageInterface::ShowMessage(" Uplink range correction = %.12lf km\n",uplinkRangeCorrectionS);
MessageInterface::ShowMessage(" Uplink precision light time range = %.12lf km\n",uplinkRangeS);
MessageInterface::ShowMessage(" Uplink real range = %.12lf km\n",uplinkRealRangeS);
#endif
// 12.2. Doppler shift the frequency from the transmitter using uplinkRangeRate:
Real uplinkDSFreqS = (1 - uplinkRangeRate[0]*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)*uplinkFreqS;
// 12.3. Set frequency for the input signal of transponder
Signal* inputSignal = scTransponder->GetSignal(0);
inputSignal->SetValue(uplinkDSFreqS);
scTransponder->SetSignal(inputSignal, 0);
// 12.4. Check the transponder feasibility to receive the input signal:
if (scTransponder->IsFeasible(0) == false)
{
currentMeasurement.isFeasible = false;
currentMeasurement.value[0] = 0;
throw MeasurementException("The transponder is unfeasible to receive uplink signal for S path.\n");
}
// 12.5. Get frequency of transponder output signal
Signal* outputSignal = scTransponder->GetSignal(1);
Real downlinkFreqS = outputSignal->GetValue();
// 12.6. Doppler shift the transponder output frequency by the downlinkRangeRate:
Real downlinkDSFreqS = (1 - downlinkRangeRate[0]*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)*downlinkFreqS;
// 12.7. Set frequency on receiver
Signal* downlinkSignal = gsReceiver->GetSignal();
downlinkSignal->SetValue(downlinkDSFreqS);
// 12.8. Check the receiver feasibility to receive the downlink signal
if (gsReceiver->IsFeasible() == false)
{
currentMeasurement.isFeasible = false;
currentMeasurement.value[0] = 0;
throw MeasurementException("The receiver is unfeasible to receive downlink signal for S path.\n");
}
// 12.9. Calculate media correction for downlink leg:
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("4.1.2. Media correction for downlink leg:\n");
MessageInterface::ShowMessage(" Uplink transmit frequency = %.12le MHz\n", uplinkFreqS);
MessageInterface::ShowMessage(" Uplink Doppler shift frequency = %.12le MHz\n", uplinkDSFreqS);
MessageInterface::ShowMessage(" Downlink frequency = Turn around ratio x Uplink Doppler shift frequency = %.12le Mhz\n", downlinkFreqS);
MessageInterface::ShowMessage(" Downlink Doppler shift frequency = (1 - downlink range rate / c)x Downlink frequency = %.12le MHz\n", downlinkDSFreqS);
#endif
// r1SB and r2SB are location of station and spacecraft in central body inertial coordinate system for downlink leg for S path
RealArray downlinkCorrectionS = CalculateMediaCorrection(downlinkDSFreqS, r1SB, r2SB, t3RS, t2TS, minAngle);
Real downlinkRangeCorrectionS = downlinkCorrectionS[0]*GmatMathConstants::M_TO_KM + downlinkLegS.GetRelativityCorrection();
Real downlinkRealRangeS = downlinkRangeS + downlinkRangeCorrectionS;
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Downlink media correction = %.12lf m\n",downlinkCorrectionS[0]);
MessageInterface::ShowMessage(" Downlink relativity correction = %.12lf km\n",downlinkLegS.GetRelativityCorrection());
MessageInterface::ShowMessage(" Downlink range correction = %.12lf km\n",downlinkRangeCorrectionS);
MessageInterface::ShowMessage(" Downlink precision light time range = %.12lf km\n",downlinkRangeS);
MessageInterface::ShowMessage(" Downlink real range = %.12lf km\n",downlinkRealRangeS);
#endif
// 13. Calculate for measurement E:
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("4.2. Media correction calculation for measurement E:\n");
MessageInterface::ShowMessage("4.2.1. Media correction for uplink leg:\n");
#endif
// 13.1. Calculate media correction for uplink leg:
// r3EB and r4EB are location of station and spacecraft in SSB inertial coordinate system for uplink leg for E path
RealArray uplinkCorrectionE = CalculateMediaCorrection(uplinkFreqE, r3EB, r4EB, t1TE, t2RE, minAngle);
Real uplinkRangeCorrectionE = uplinkCorrectionE[0]*GmatMathConstants::M_TO_KM + uplinkLegE.GetRelativityCorrection();
Real uplinkRealRangeE = uplinkRangeE + uplinkRangeCorrectionE;
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Uplink media correction = %.12lf m\n",uplinkCorrectionE[0]);
MessageInterface::ShowMessage(" Uplink relativity correction = %.12lf km\n",uplinkLegE.GetRelativityCorrection());
MessageInterface::ShowMessage(" Uplink range correction = %.12lf km\n",uplinkRangeCorrectionE);
MessageInterface::ShowMessage(" Uplink precision light time range = %.12lf km\n",uplinkRangeE);
MessageInterface::ShowMessage(" Uplink real range = %.12lf km\n",uplinkRealRangeE);
#endif
// 13.2. Doppler shift the frequency from the transmitter using uplinkRangeRate:
Real uplinkDSFreqE = (1 - uplinkRangeRate[1]*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)*uplinkFreqE;
// 13.3. Set frequency for the input signal of transponder
inputSignal = scTransponder->GetSignal(0);
inputSignal->SetValue(uplinkDSFreqE);
scTransponder->SetSignal(inputSignal, 0);
// 13.4. Check the transponder feasibility to receive the input signal:
if (scTransponder->IsFeasible(0) == false)
{
currentMeasurement.isFeasible = false;
currentMeasurement.value[0] = 0;
throw MeasurementException("The transponder is unfeasible to receive uplink signal for E path.\n");
}
// 13.5. Get frequency of transponder output signal
outputSignal = scTransponder->GetSignal(1);
Real downlinkFreqE = outputSignal->GetValue();
// 13.6. Doppler shift the transponder output frequency by the downlinkRangeRate:
Real downlinkDSFreqE = (1 - downlinkRangeRate[1]*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)*downlinkFreqE;
// 13.7. Set frequency on receiver
downlinkSignal = gsReceiver->GetSignal();
downlinkSignal->SetValue(downlinkDSFreqE);
// 13.8. Check the receiver feasibility to receive the downlink signal
if (gsReceiver->IsFeasible() == false)
{
currentMeasurement.isFeasible = false;
currentMeasurement.value[0] = 0;
throw MeasurementException("The receiver is unfeasible to receive downlink signal for E path.\n");
}
// 13.9. Calculate media correction for downlink leg:
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("4.2.2. Media correction for downlink leg:\n");
MessageInterface::ShowMessage(" Uplink transmit frequency = %.12le MHz\n", uplinkFreqE);
MessageInterface::ShowMessage(" Uplink Doppler shift frequency = %.12le MHz\n", uplinkDSFreqE);
MessageInterface::ShowMessage(" Downlink frequency = Turn around ratio x Uplink Doppler shift frequency = %.12le Mhz\n", downlinkFreqE);
MessageInterface::ShowMessage(" Downlink Doppler shift frequency = (1 - downlink range rate / c)x Downlink frequency = %.12le MHz\n", downlinkDSFreqE);
#endif
// r1EB and r2EB are location of station and spacecraft in SSB inertial coordinate system for downlink leg for E path
RealArray downlinkCorrectionE = CalculateMediaCorrection(downlinkDSFreqE, r1EB, r2EB, t3RE, t2TE, minAngle);
Real downlinkRangeCorrectionE = downlinkCorrectionE[0]*GmatMathConstants::M_TO_KM + downlinkLegE.GetRelativityCorrection();
Real downlinkRealRangeE = downlinkRangeE + downlinkRangeCorrectionE;
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Downlink media correction = %.12lf m\n",downlinkCorrectionE[0]);
MessageInterface::ShowMessage(" Downlink relativity correction = %.12lf km\n",downlinkLegE.GetRelativityCorrection());
MessageInterface::ShowMessage(" Downlink range correction = %.12lf km\n",downlinkRangeCorrectionE);
MessageInterface::ShowMessage(" Downlink precision light time range = %.12lf km\n",downlinkRangeE);
MessageInterface::ShowMessage(" Downlink real range = %.12lf km\n",downlinkRealRangeE);
#endif
// 14. Time travel for start path and the end path:
// 14.1. Calculate ET-TAI correction
Real ettaiCorrectionS = (useETminusTAICorrection?(ettaiT1S - ettaiT3S):0.0);
Real ettaiCorrectionE = (useETminusTAICorrection?(ettaiT1E - ettaiT3E):0.0);
// 14.2 Total times for the start path and the end path:
dtS = (uplinkRealRangeS + downlinkRealRangeS)*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM + ettaiCorrectionS +
transmitDelay + receiveDelay + targetDelay;
dtE = (uplinkRealRangeE + downlinkRealRangeE)*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM + ettaiCorrectionE +
transmitDelay + receiveDelay + targetDelay;
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
Real uplinkTimeS = uplinkRealRangeS*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM;
Real downlinkTimeS = downlinkRealRangeS*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM;
Real uplinkTimeE = uplinkRealRangeE*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM;
Real downlinkTimeE = downlinkRealRangeE*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM;
MessageInterface::ShowMessage("5. Travel time:\n");
MessageInterface::ShowMessage("5.1. Travel time for S-path:\n");
MessageInterface::ShowMessage(" Uplink time = %.12lf s\n", uplinkTimeS);
MessageInterface::ShowMessage(" Downlink time = %.12lf s\n", downlinkTimeS);
MessageInterface::ShowMessage(" (ET-TAI) correction = %.12le s\n", ettaiCorrectionS);
MessageInterface::ShowMessage(" Transmit delay = %.12le s\n", transmitDelay);
MessageInterface::ShowMessage(" Transpond delay = %.12le s\n", targetDelay);
MessageInterface::ShowMessage(" Receive delay = %.12le s\n", receiveDelay);
MessageInterface::ShowMessage(" Real travel time = %.15lf s\n", dtS);
MessageInterface::ShowMessage("5.2. Travel time for E-path:\n");
MessageInterface::ShowMessage(" Uplink time = %.12lf s\n", uplinkTimeE);
MessageInterface::ShowMessage(" Downlink time = %.12lf s\n", downlinkTimeE);
MessageInterface::ShowMessage(" (ET-TAI) correction = %.12le s\n", ettaiCorrectionE);
MessageInterface::ShowMessage(" Transmit delay = %.12le s\n", transmitDelay);
MessageInterface::ShowMessage(" Transpond delay = %.12le s\n", targetDelay);
MessageInterface::ShowMessage(" Receive delay = %.12le s\n", receiveDelay);
MessageInterface::ShowMessage(" Real travel time = %.15lf s\n", dtE);
#endif
// 15. Check feasibility of signals for Start path and End path:
currentMeasurement.isFeasible = true;
// 15.1. Check for Start part
// UpdateRotationMatrix(t1TS, "R_o_j2k");
UpdateRotationMatrix(t1TS, "o_j2k");
Rvector3 outState = (R_o_j2k * (r4S - r3S)).GetUnitVector();
currentMeasurement.feasibilityValue = asin(outState[2])*GmatMathConstants::DEG_PER_RAD; // elevation angle in degree
if (currentMeasurement.feasibilityValue > minAngle)
{
// UpdateRotationMatrix(t3RS, "R_o_j2k");
UpdateRotationMatrix(t3RS, "o_j2k");
outState = (R_o_j2k * (r2S - r1S)).GetUnitVector();
Real feasibilityValue = asin(outState[2])*GmatMathConstants::DEG_PER_RAD; // elevation angle in degree
if (feasibilityValue > minAngle)
{
currentMeasurement.unfeasibleReason = "N";
currentMeasurement.isFeasible = true;
}
else
{
currentMeasurement.feasibilityValue = feasibilityValue;
currentMeasurement.unfeasibleReason = "B2S"; // S-path's downlink leg signal was blocked
currentMeasurement.isFeasible = false;
}
}
else
{
currentMeasurement.unfeasibleReason = "B1S"; // S-path's uplink leg signal was blocked
currentMeasurement.isFeasible = false;
}
// 15.2. When Start path is feasible, we check for End part
if (currentMeasurement.isFeasible)
{
// UpdateRotationMatrix(t1TE, "R_o_j2k");
UpdateRotationMatrix(t1TE, "o_j2k");
outState = (R_o_j2k * (r4E - r3E)).GetUnitVector();
currentMeasurement.feasibilityValue = asin(outState[2])*GmatMathConstants::DEG_PER_RAD; // elevation angle in degree
if (currentMeasurement.feasibilityValue > minAngle)
{
// UpdateRotationMatrix(t3RE, "R_o_j2k");
UpdateRotationMatrix(t3RE, "o_j2k");
outState = (R_o_j2k * (r2E - r1E)).GetUnitVector();
Real feasibilityValue = asin(outState[2])*GmatMathConstants::DEG_PER_RAD; // elevation angle in degree
if (feasibilityValue > minAngle)
{
currentMeasurement.unfeasibleReason = "N";
currentMeasurement.isFeasible = true;
}
else
{
currentMeasurement.feasibilityValue = feasibilityValue;
currentMeasurement.unfeasibleReason = "B2E"; // E-path's downlink leg signal was blocked
currentMeasurement.isFeasible = false;
}
}
else
{
currentMeasurement.unfeasibleReason = "B1E"; // E-path's uplink leg signal was blocked
currentMeasurement.isFeasible = false;
}
}
// 16. Calculate Frequency Doppler Shift:
dtdt = dtE - dtS;
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("6. Calculate Frequency Doppler Shift:\n");
MessageInterface::ShowMessage(" t1S : %.12lf s\n"
" t1E : %.12lf s\n"
" t3S : %.12lf s\n"
" t3E : %.12lf s\n"
" Turnaround ratio : %.15lf\n"
" M2R : %.15lf\n"
" Time interval : %.12lf s\n", t1TS, t1TE, t3RS, t3RE, turnaround, M2R, interval);
MessageInterface::ShowMessage(" Travel time for S path: %.15lf s\n", dtS);
MessageInterface::ShowMessage(" Travel time for E path: %.15lf s\n", dtE);
MessageInterface::ShowMessage(" dtdt = dtE - dtS : %.15lf s\n", dtdt);
#endif
currentMeasurement.uplinkFreq = frequencyE; // unit: Hz // uplink frequency for E path
currentMeasurement.uplinkFreqAtRecei = uplinkFreqAtRecei * 1.0e6; // unit: Hz
currentMeasurement.uplinkBand = freqBand;
currentMeasurement.dopplerCountInterval = interval;
if (rampTB != NULL)
{
Integer errnum;
try
{
// currentMeasurement.value[0] = (M2R*IntegralRampedFrequency(t3RE, interval) - turnaround*IntegralRampedFrequency(t1TE, interval + dtS-dtE))/ interval;
currentMeasurement.value[0] = - turnaround*IntegralRampedFrequency(t1TE, interval + dtS-dtE, errnum)/ interval;
} catch (MeasurementException exp)
{
currentMeasurement.value[0] = 0.0; // It has no C-value due to the failure of calculation of IntegralRampedFrequency()
// currentMeasurement.uplinkFreq = frequencyE; // unit: Hz
// currentMeasurement.uplinkFreqAtRecei = uplinkFreqAtRecei * 1.0e6; // unit: Hz
// currentMeasurement.uplinkBand = freqBand;
// currentMeasurement.dopplerCountInterval = interval;
currentMeasurement.isFeasible = false;
currentMeasurement.unfeasibleReason = "R";
// currentMeasurement.feasibilityValue is set to elevation angle as shown in section 15
if ((errnum == 2)||(errnum == 3))
throw exp;
else
return false;
}
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
Real rampedIntegral = IntegralRampedFrequency(t1TE, interval + dtS-dtE, errnum);
MessageInterface::ShowMessage(" Use ramped DSNTwoWayDoppler calculation:\n");
MessageInterface::ShowMessage(" ramped integral = %.12lf\n", rampedIntegral);
#endif
}
else
{
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Use unramped DSNTwoWayDoppler calculation:\n");
MessageInterface::ShowMessage(" frequency : %.12lf Hz\n", frequency);
#endif
currentMeasurement.value[0] = -turnaround*frequency*(interval - dtdt)/interval;
}
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Calculated Doppler C = %.12le Hz\n", currentMeasurement.value[0]);
if (obsData != NULL)
{
MessageInterface::ShowMessage(" Observated Doppler O = %.12le Hz\n", obsData->value[0]);
MessageInterface::ShowMessage(" O-C = %.12lf Hz\n", obsData->value[0] - currentMeasurement.value[0]);
}
#endif
#ifdef PRELIMINARY_DERIVATIVE_CHECK
MessageInterface::ShowMessage("Participants:\n ");
for (UnsignedInt i = 0; i < participants.size(); ++i)
MessageInterface::ShowMessage(" %d: %s of type %s\n", i,
participants[i]->GetName().c_str(),
participants[i]->GetTypeName().c_str());
Integer id = participants[1]->GetType() * 250 +
participants[1]->GetParameterID("CartesianX");
CalculateMeasurementDerivatives(participants[1], id);
#endif
// Add noise to calculated measurement
if (noiseSigma != NULL)
{
#ifdef DEBUG_DOPPLER_CALC_WITH_EVENTS
MessageInterface::ShowMessage("Generate noise and it to measurement\n");
#endif
Real v_sign = ((currentMeasurement.value[0] < 0.0)?-1.0:1.0);
RandomNumber* rn = RandomNumber::Instance();
Real val = rn->Gaussian(currentMeasurement.value[0], noiseSigma->GetElement(0));
while (val*v_sign <= 0.0)
val = rn->Gaussian(currentMeasurement.value[0], noiseSigma->GetElement(0));
currentMeasurement.value[0] = val;
}
retval = true;
}
return retval;
}
//------------------------------------------------------------------------------
// void SetHardwareDelays(bool loadEvents)
//------------------------------------------------------------------------------
/**
* Retrieves hardware delays is available
*
* @param loadEvents Flag used to indicate if events can be preloaded; if true,
* those that can be loaded are passed the corresponding
* delays.
*/
//------------------------------------------------------------------------------
void DSNTwoWayDoppler::SetHardwareDelays(bool loadEvents)
{
AveragedDoppler::SetHardwareDelays(loadEvents);
}
//------------------------------------------------------------------------------
// Real DSNTwoWayDoppler::GetTurnAroundRatio(Integer freqBand)
//------------------------------------------------------------------------------
/**
* Retrieves trun around ratio
*
* @param freqBand frequency band
*
* return the value of trun around ratio associated with frequency band
*/
//------------------------------------------------------------------------------
Real DSNTwoWayDoppler::GetTurnAroundRatio(Integer freqBand)
{
switch (freqBand)
{
case 1: // for S-band, turn around ratio is 240/221
return 240.0/221.0;
case 2: // for X-band, turn around ratio is 880/749
return 880.0/749.0;
}
// Display an error message when frequency band is not specified
std::stringstream ss;
ss << "Error: frequency band " << freqBand << " is not specified.\n";
throw MeasurementException(ss.str());
}
|
#pragma once
#include "cocos2d.h"
using namespace cocos2d;
enum {
EMOTION_ID_DEFUALT,
EMOTION_ID_HAPPY,
EMOTION_ID_QUEST,
EMOTION_ID_SAD,
};
class TextLayer;
class StudyScene : public Scene
{
public:
static Scene* createScene(std::string& worldName, int level, std::string& text)
{
StudyScene* pRes = StudyScene::create();
pRes->initVal(worldName, level, text);
return pRes;
}
CREATE_FUNC(StudyScene);
std::vector<TextLayer*> m_arrayTextLayer;
std::vector<TextLayer*> m_arrayAnswerLayer;
std::vector<TextLayer*> m_wordQueue;
std::string m_wordName;
std::string m_fileName;
std::string m_text;
bool m_isSuccessed;
int m_level;
//Audio* m_wordSound;
Point arrayPoint[4];
bool m_isLavar;
Sequence* m_timeFuncAction;
Sprite* m_lavar;
cocos2d::Size frameSize;
float H_OFFSET;
public:
StudyScene();
~StudyScene();
virtual bool init();
void initVal(std::string& worldName, int level, std::string& text);
Point getBoxPoint(int index);
void OnPassed();
void OnSkip();
void TurnPage();
void GoAppleTreeScene(void);
void OnExitStudy();
void ChangeEmotion(int emotionID);
void DrowApple(bool showEffect, bool isRedrow);
void DrowStar();
void ShowHint();
void PlayWordSound();
void TimeRun(int sec);
void RemoveLavar();
bool checkWord();
int GetEmptyBoxID();
void popCallback_Ok(Ref* pSender);
void callbackOnPushedPrevBtnItem(Ref* sender);
void callbackOnPushedNextBtnItem(Ref* sender);
void callbackOnPushedHomeBtnItem(Ref* sender);
void callbackOnPushedHintBtnItem(Ref* sender);
void callbackOnPushedBuyMenuItem(Ref* sender);
};
|
#ifndef OPERATOR_NEGATE_H
#define OPERATOR_NEGATE_H
#include "operator.h"
#include "../type.h"
#include "../visitors/operatorvisitor.h"
using namespace std;
/**
* Operator for the boolean NOT
*/
class NegateOp: public Operator {
public:
NegateOp(): Operator("!") { }
virtual bool canHandle(Type t) const;
virtual void accept(OperatorVisitor* v);
virtual Constant* evaluate(Constant* c1, Constant* c2) const;
/**
* Not really applicable. Returns false.
*/
virtual bool isCommutative() const { return false; }
};
#endif
|
#include "HDREnvironment.h"
#include <tinyxml2.h>
HDREnvironment::HDREnvironment()
{
}
HDREnvironment::~HDREnvironment()
{
}
void HDREnvironment::Deserialization( tinyxml2::XMLElement* RootElement )
{
const char* name = RootElement->Attribute( "filename" );
mFilename.insert( mFilename.size() , name , strlen( name ) );
}
void HDREnvironment::Serialization( tinyxml2::XMLDocument& xmlDoc , tinyxml2::XMLElement* pRootElement )
{
pRootElement->SetAttribute( "type" , GetName() );
pRootElement->SetAttribute( "filename" , mFilename.c_str() );
}
|
#ifndef SPROGRESS_CPP
#define SPROGRESS_CPP
#define _WIN32_IE 0x0500
#include <windows.h>
#include <commctrl.h>
#include "SApp.h"
#include "SWindow.h"
#include "SProgress.h"
SProgress::SProgress(SWindow * pWin):
SWindow(pWin->GetSApp(), PROGRESS_CLASS, pWin->GetHwnd(), 0, WS_CHILD)
{
pWin->AddChild(this);
SendMessage(hwnd, PBM_SETSTEP, 1, 0);
}
SProgress::~SProgress()
{ }
DWORD SProgress::SetRange(DWORD dwRange)
{
SendMessage(hwnd, PBM_SETRANGE32, 0, dwRange);
return 0;
}
DWORD SProgress::MoveTo(DWORD iPos)
{
SendMessage(hwnd, PBM_SETPOS, iPos, 0);
return 0;
}
DWORD SProgress::Move(DWORD iMove)
{
SendMessage(hwnd, PBM_DELTAPOS, iMove, 0);
return 0;
}
DWORD SProgress::StepIt()
{
SendMessage(hwnd, PBM_STEPIT, 0, 0);
return 0;
}
DWORD SProgress::GetRange() const
{
return (DWORD)SendMessage(hwnd, PBM_GETRANGE, FALSE, (LPARAM)NULL);
}
DWORD SProgress::GetCurrentPosition() const
{
return (DWORD)SendMessage(hwnd, PBM_GETPOS, 0, 0);
}
#endif
|
// This file is subject to the terms and conditions defined in 'LICENSE' in the source code package
#include <gtest/gtest.h>
#include "game/world/chunk_tile.h"
#include "data/cereal/register_type.h" // Just has to be included somewhere once
#include "jactorioTests.h"
namespace jactorio::game
{
class ChunkTileTest : public testing::Test
{
protected:
proto::ContainerEntity proto_;
};
TEST_F(ChunkTileTest, CopyTopLeft) {
proto_.SetDimension({2, 5});
ChunkTile top_left;
top_left.SetPrototype(Orientation::right, proto_);
top_left.MakeUniqueData<proto::ContainerEntityData>(32);
const ChunkTile copy{top_left};
EXPECT_EQ(copy.GetMultiTileIndex(), 0);
EXPECT_EQ(copy.GetDimension().x, 5);
EXPECT_EQ(copy.GetDimension().y, 2);
EXPECT_EQ(copy.GetDimension(), top_left.GetDimension());
EXPECT_EQ(copy.GetUniqueData<proto::ContainerEntityData>()->inventory.Size(), 32);
EXPECT_EQ(copy.GetOrientation(), Orientation::right);
}
TEST_F(ChunkTileTest, CopyNonTopLeft) {
// Since orientation is right, width and height are swapped
proto_.SetDimension({2, 5});
ChunkTile top_left;
ChunkTile tile;
tile.SetupMultiTile(4, top_left);
tile.SetPrototype(Orientation::right, proto_);
const ChunkTile copy = tile;
EXPECT_EQ(copy.GetMultiTileIndex(), 4);
EXPECT_EQ(copy.GetDimension().x, 5);
EXPECT_EQ(copy.GetDimension().y, 2);
EXPECT_EQ(copy.GetTopLeft(), nullptr); // top left tile not copied
}
TEST_F(ChunkTileTest, MoveTopLeft) {
ChunkTile top_left;
top_left.MakeUniqueData<proto::ContainerEntityData>(32);
const ChunkTile move_to = std::move(top_left);
EXPECT_EQ(top_left.GetUniqueData<proto::ContainerEntityData>(), nullptr); // Gave ownership
EXPECT_NE(move_to.GetUniqueData<proto::ContainerEntityData>(), nullptr); // Took ownership
EXPECT_EQ(move_to.GetOrientation(), Orientation::up);
}
TEST_F(ChunkTileTest, MoveNonTopLeft) {
ChunkTile top_left;
ChunkTile tile;
tile.SetupMultiTile(4, top_left);
tile.SetPrototype(Orientation::right, proto_);
const ChunkTile move_to = std::move(tile);
EXPECT_EQ(move_to.GetTopLeft(), &top_left);
EXPECT_EQ(move_to.GetOrientation(), Orientation::right);
}
TEST_F(ChunkTileTest, ClearTopLeft) {
ChunkTile tile;
tile.SetPrototype(Orientation::up, proto_);
tile.MakeUniqueData<proto::ContainerEntityData>();
tile.Clear();
EXPECT_EQ(tile.GetPrototype(), nullptr);
EXPECT_EQ(tile.GetUniqueData(), nullptr);
EXPECT_EQ(tile.GetMultiTileIndex(), 0);
}
TEST_F(ChunkTileTest, ClearNonTopLeft) {
ChunkTile top_left;
ChunkTile tile;
tile.SetupMultiTile(2, top_left);
tile.SetPrototype(Orientation::up, proto_);
tile.Clear();
EXPECT_EQ(tile.GetPrototype(), nullptr);
EXPECT_EQ(tile.GetUniqueData(), nullptr);
EXPECT_EQ(tile.GetMultiTileIndex(), 0);
}
TEST_F(ChunkTileTest, GetSetOrientation) {
ChunkTile top_left;
top_left.SetPrototype(Orientation::right, proto_);
EXPECT_EQ(top_left.GetOrientation(), Orientation::right);
}
TEST_F(ChunkTileTest, GetSetPrototype) {
ChunkTile tile;
tile.SetPrototype(Orientation::right, proto_);
EXPECT_EQ(tile.GetPrototype(), &proto_);
EXPECT_EQ(tile.GetOrientation(), Orientation::right);
tile.SetPrototype(Orientation::up, nullptr);
EXPECT_EQ(tile.GetPrototype(), nullptr);
EXPECT_EQ(tile.GetOrientation(), Orientation::up);
tile.SetPrototype(Orientation::right, proto_);
tile.SetPrototype(nullptr);
EXPECT_EQ(tile.GetPrototype(), nullptr);
}
TEST_F(ChunkTileTest, GetUniqueData) {
ChunkTile top_left;
top_left.MakeUniqueData<proto::ContainerEntityData>(10);
ChunkTile tile;
tile.SetupMultiTile(3, top_left);
EXPECT_EQ(top_left.GetUniqueData(), tile.GetUniqueData());
}
TEST_F(ChunkTileTest, IsTopLeft) {
{
const ChunkTile tile;
EXPECT_TRUE(tile.IsTopLeft());
}
{
ChunkTile top_left;
ChunkTile tile;
tile.SetupMultiTile(4, top_left);
EXPECT_FALSE(tile.IsTopLeft());
}
}
TEST_F(ChunkTileTest, IsMultiTile) {
{
const ChunkTile tile;
EXPECT_FALSE(tile.IsMultiTile());
}
{
// Top left has to look at prototype to determine if it is multi tile
proto_.SetWidth(3);
ChunkTile tile;
tile.SetPrototype(Orientation::up, proto_);
EXPECT_TRUE(tile.IsMultiTile());
}
{
ChunkTile top_left;
ChunkTile tile;
tile.SetupMultiTile(1, top_left);
EXPECT_TRUE(tile.IsMultiTile());
}
}
TEST_F(ChunkTileTest, IsMultiTileTopLeft) {
{
ChunkTile tile;
EXPECT_FALSE(tile.IsMultiTileTopLeft());
}
{
proto_.SetWidth(3);
ChunkTile tile;
tile.SetPrototype(Orientation::up, proto_);
EXPECT_TRUE(tile.IsMultiTileTopLeft());
}
{
ChunkTile top_left;
ChunkTile tile;
tile.SetupMultiTile(4, top_left);
EXPECT_FALSE(tile.IsMultiTileTopLeft());
}
}
TEST_F(ChunkTileTest, GetDimensions) {
const ChunkTile first;
const auto dimens = first.GetDimension();
EXPECT_EQ(dimens.x, 1);
EXPECT_EQ(dimens.y, 1);
}
TEST_F(ChunkTileTest, GetDimensionsMultiTile) {
proto::ContainerEntity container;
container.SetDimension({2, 3});
ChunkTile first;
first.SetPrototype(Orientation::right, &container);
const auto& dimens = first.GetDimension();
EXPECT_EQ(dimens.x, container.GetWidth(Orientation::right));
EXPECT_EQ(dimens.y, container.GetHeight(Orientation::right));
}
TEST_F(ChunkTileTest, SetupMultiTile) {
ChunkTile top_left;
ChunkTile tile;
tile.SetupMultiTile(1, top_left);
EXPECT_EQ(tile.GetMultiTileIndex(), 1);
EXPECT_EQ(tile.GetTopLeft(), &top_left);
}
TEST_F(ChunkTileTest, GetTopLeftAlreadyTopleft) {
ChunkTile tile;
EXPECT_EQ(tile.GetTopLeft(), &tile);
}
TEST_F(ChunkTileTest, AdjustToTopleft) {
proto_.SetWidth(3);
ChunkTile top_left;
ChunkTile tile;
tile.SetPrototype(Orientation::up, proto_);
tile.SetupMultiTile(5, top_left);
Position2<int> p;
Position2Increment(tile, p, -2);
EXPECT_EQ(p.x, 4);
EXPECT_EQ(p.y, 2);
}
TEST_F(ChunkTileTest, AdjustToTopleftNonMultiTile) {
const ChunkTile tile;
Position2<int> p;
Position2Increment(tile, p, 100);
EXPECT_EQ(p.x, 0);
EXPECT_EQ(p.y, 0);
}
TEST_F(ChunkTileTest, GetOffsetX) {
proto_.SetWidth(10);
ChunkTile top_left;
ChunkTile tile;
tile.SetPrototype(Orientation::up, proto_);
tile.SetupMultiTile(19, top_left);
EXPECT_EQ(tile.GetOffsetX(), 9);
}
TEST_F(ChunkTileTest, GetOffsetY) {
proto_.SetWidth(5);
ChunkTile top_left;
ChunkTile tile;
tile.SetPrototype(Orientation::up, proto_);
tile.SetupMultiTile(20, top_left);
EXPECT_EQ(tile.GetOffsetY(), 4);
}
TEST_F(ChunkTileTest, Serialize) {
data::PrototypeManager proto;
data::UniqueDataManager unique;
data::active_prototype_manager = &proto;
data::active_unique_data_manager = &unique;
auto& container = proto.Make<proto::ContainerEntity>();
container.SetDimension({2, 3}); // Width and height are flipped since orientation is right
ChunkTile top_left;
top_left.SetPrototype(Orientation::right, container);
top_left.MakeUniqueData<proto::ContainerEntityData>(10);
ChunkTile bot_right;
bot_right.SetupMultiTile(3, top_left);
bot_right.SetPrototype(Orientation::right, container);
proto.GenerateRelocationTable();
// ======================================================================
auto result_tl = TestSerializeDeserialize(top_left);
auto result_br = TestSerializeDeserialize(bot_right);
EXPECT_EQ(result_tl.GetPrototype(), &container);
ASSERT_NE(result_tl.GetUniqueData(), nullptr);
EXPECT_EQ(result_tl.GetUniqueData()->internalId, 1);
EXPECT_EQ(result_tl.GetDimension().x, 3);
EXPECT_EQ(result_tl.GetDimension().y, 2);
EXPECT_EQ(result_tl.GetOrientation(), Orientation::right);
EXPECT_EQ(result_br.GetPrototype(), &container);
EXPECT_EQ(result_br.GetTopLeft(), nullptr);
EXPECT_EQ(result_br.GetDimension().x, 3);
EXPECT_EQ(result_br.GetDimension().y, 2);
EXPECT_EQ(unique.GetDebugInfo().dataEntries.size(), 1);
}
} // namespace jactorio::game
|
#include "SolarFarm.hpp"
SolarFarm::SolarFarm(SDL_Renderer *renderer, Texture *texture, int level) :
Building(renderer, texture, "Solar Farm", level) {
spriteClip = {
1670,
0,
345,
250
};
}
|
/*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY
- 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.
*====================================================================*/
/*
* fpix1.c
*
* This file has basic constructors, destructors and field accessors
* for FPix, FPixa and DPix. It also has uncompressed read/write.
*
* FPix Create/copy/destroy
* FPIX *fpixCreate()
* FPIX *fpixCreateTemplate()
* FPIX *fpixClone()
* FPIX *fpixCopy()
* l_int32 fpixResizeImageData()
* void fpixDestroy()
*
* FPix accessors
* l_int32 fpixGetDimensions()
* l_int32 fpixSetDimensions()
* l_int32 fpixGetWpl()
* l_int32 fpixSetWpl()
* l_int32 fpixGetRefcount()
* l_int32 fpixChangeRefcount()
* l_int32 fpixGetResolution()
* l_int32 fpixSetResolution()
* l_int32 fpixCopyResolution()
* l_float32 *fpixGetData()
* l_int32 fpixSetData()
* l_int32 fpixGetPixel()
* l_int32 fpixSetPixel()
*
* FPixa Create/copy/destroy
* FPIXA *fpixaCreate()
* FPIXA *fpixaCopy()
* void fpixaDestroy()
*
* FPixa addition
* l_int32 fpixaAddFPix()
* static l_int32 fpixaExtendArray()
* static l_int32 fpixaExtendArrayToSize()
*
* FPixa accessors
* l_int32 fpixaGetCount()
* l_int32 fpixaChangeRefcount()
* FPIX *fpixaGetFPix()
* l_int32 fpixaGetFPixDimensions()
* l_int32 fpixaGetPixel()
* l_int32 fpixaSetPixel()
*
* DPix Create/copy/destroy
* DPIX *dpixCreate()
* DPIX *dpixCreateTemplate()
* DPIX *dpixClone()
* DPIX *dpixCopy()
* l_int32 dpixResizeImageData()
* void dpixDestroy()
*
* DPix accessors
* l_int32 dpixGetDimensions()
* l_int32 dpixSetDimensions()
* l_int32 dpixGetWpl()
* l_int32 dpixSetWpl()
* l_int32 dpixGetRefcount()
* l_int32 dpixChangeRefcount()
* l_int32 dpixGetResolution()
* l_int32 dpixSetResolution()
* l_int32 dpixCopyResolution()
* l_float64 *dpixGetData()
* l_int32 dpixSetData()
* l_int32 dpixGetPixel()
* l_int32 dpixSetPixel()
*
* FPix serialized I/O
* FPIX *fpixRead()
* FPIX *fpixReadStream()
* l_int32 fpixWrite()
* l_int32 fpixWriteStream()
* FPIX *fpixEndianByteSwap()
*
* DPix serialized I/O
* DPIX *dpixRead()
* DPIX *dpixReadStream()
* l_int32 dpixWrite()
* l_int32 dpixWriteStream()
* DPIX *dpixEndianByteSwap()
*
* Print FPix (subsampled, for debugging)
* l_int32 fpixPrintStream()
*/
#include <string.h>
#include "allheaders.h"
static const l_int32 INITIAL_PTR_ARRAYSIZE = 20; /* must be > 0 */
/* Static functions */
static l_int32 fpixaExtendArray(FPIXA *fpixa);
static l_int32 fpixaExtendArrayToSize(FPIXA *fpixa, l_int32 size);
/*--------------------------------------------------------------------*
* FPix Create/copy/destroy *
*--------------------------------------------------------------------*/
/*!
* fpixCreate()
*
* Input: width, height
* Return: fpixd (with data allocated and initialized to 0),
* or null on error
*
* Notes:
* (1) Makes a FPix of specified size, with the data array
* allocated and initialized to 0.
*/
FPIX *
fpixCreate(l_int32 width,
l_int32 height)
{
l_float32 *data;
l_uint64 bignum;
FPIX *fpixd;
PROCNAME("fpixCreate");
if (width <= 0)
{
return (FPIX *)ERROR_PTR("width must be > 0", procName, NULL);
}
if (height <= 0)
{
return (FPIX *)ERROR_PTR("height must be > 0", procName, NULL);
}
/* Avoid overflow in malloc arg, malicious or otherwise */
bignum = 4L * width * height; /* max number of bytes requested */
if (bignum > ((1LL << 31) - 1))
{
L_ERROR("requested w = %d, h = %d\n", procName, width, height);
return (FPIX *)ERROR_PTR("requested bytes >= 2^31", procName, NULL);
}
if ((fpixd = (FPIX *)CALLOC(1, sizeof(FPIX))) == NULL)
{
return (FPIX *)ERROR_PTR("CALLOC fail for fpixd", procName, NULL);
}
fpixSetDimensions(fpixd, width, height);
fpixSetWpl(fpixd, width); /* 4-byte words */
fpixd->refcount = 1;
data = (l_float32 *)CALLOC(width * height, sizeof(l_float32));
if (!data)
{
return (FPIX *)ERROR_PTR("CALLOC fail for data", procName, NULL);
}
fpixSetData(fpixd, data);
return fpixd;
}
/*!
* fpixCreateTemplate()
*
* Input: fpixs
* Return: fpixd, or null on error
*
* Notes:
* (1) Makes a FPix of the same size as the input FPix, with the
* data array allocated and initialized to 0.
* (2) Copies the resolution.
*/
FPIX *
fpixCreateTemplate(FPIX *fpixs)
{
l_int32 w, h;
FPIX *fpixd;
PROCNAME("fpixCreateTemplate");
if (!fpixs)
{
return (FPIX *)ERROR_PTR("fpixs not defined", procName, NULL);
}
fpixGetDimensions(fpixs, &w, &h);
fpixd = fpixCreate(w, h);
fpixCopyResolution(fpixd, fpixs);
return fpixd;
}
/*!
* fpixClone()
*
* Input: fpix
* Return: same fpix (ptr), or null on error
*
* Notes:
* (1) See pixClone() for definition and usage.
*/
FPIX *
fpixClone(FPIX *fpix)
{
PROCNAME("fpixClone");
if (!fpix)
{
return (FPIX *)ERROR_PTR("fpix not defined", procName, NULL);
}
fpixChangeRefcount(fpix, 1);
return fpix;
}
/*!
* fpixCopy()
*
* Input: fpixd (<optional>; can be null, or equal to fpixs,
* or different from fpixs)
* fpixs
* Return: fpixd, or null on error
*
* Notes:
* (1) There are three cases:
* (a) fpixd == null (makes a new fpix; refcount = 1)
* (b) fpixd == fpixs (no-op)
* (c) fpixd != fpixs (data copy; no change in refcount)
* If the refcount of fpixd > 1, case (c) will side-effect
* these handles.
* (2) The general pattern of use is:
* fpixd = fpixCopy(fpixd, fpixs);
* This will work for all three cases.
* For clarity when the case is known, you can use:
* (a) fpixd = fpixCopy(NULL, fpixs);
* (c) fpixCopy(fpixd, fpixs);
* (3) For case (c), we check if fpixs and fpixd are the same size.
* If so, the data is copied directly.
* Otherwise, the data is reallocated to the correct size
* and the copy proceeds. The refcount of fpixd is unchanged.
* (4) This operation, like all others that may involve a pre-existing
* fpixd, will side-effect any existing clones of fpixd.
*/
FPIX *
fpixCopy(FPIX *fpixd, /* can be null */
FPIX *fpixs)
{
l_int32 w, h, bytes;
l_float32 *datas, *datad;
PROCNAME("fpixCopy");
if (!fpixs)
{
return (FPIX *)ERROR_PTR("fpixs not defined", procName, NULL);
}
if (fpixs == fpixd)
{
return fpixd;
}
/* Total bytes in image data */
fpixGetDimensions(fpixs, &w, &h);
bytes = 4 * w * h;
/* If we're making a new fpix ... */
if (!fpixd)
{
if ((fpixd = fpixCreateTemplate(fpixs)) == NULL)
{
return (FPIX *)ERROR_PTR("fpixd not made", procName, NULL);
}
datas = fpixGetData(fpixs);
datad = fpixGetData(fpixd);
memcpy((char *)datad, (char *)datas, bytes);
return fpixd;
}
/* Reallocate image data if sizes are different */
fpixResizeImageData(fpixd, fpixs);
/* Copy data */
fpixCopyResolution(fpixd, fpixs);
datas = fpixGetData(fpixs);
datad = fpixGetData(fpixd);
memcpy((char*)datad, (char*)datas, bytes);
return fpixd;
}
/*!
* fpixResizeImageData()
*
* Input: fpixd, fpixs
* Return: 0 if OK, 1 on error
*
* Notes:
* (1) If the data sizes differ, this destroys the existing
* data in fpixd and allocates a new, uninitialized, data array
* of the same size as the data in fpixs. Otherwise, this
* doesn't do anything.
*/
l_int32
fpixResizeImageData(FPIX *fpixd,
FPIX *fpixs)
{
l_int32 ws, hs, wd, hd, bytes;
l_float32 *data;
PROCNAME("fpixResizeImageData");
if (!fpixs)
{
return ERROR_INT("fpixs not defined", procName, 1);
}
if (!fpixd)
{
return ERROR_INT("fpixd not defined", procName, 1);
}
fpixGetDimensions(fpixs, &ws, &hs);
fpixGetDimensions(fpixd, &wd, &hd);
if (ws == wd && hs == hd) /* nothing to do */
{
return 0;
}
fpixSetDimensions(fpixd, ws, hs);
fpixSetWpl(fpixd, ws);
bytes = 4 * ws * hs;
data = fpixGetData(fpixd);
if (data)
{
FREE(data);
}
if ((data = (l_float32 *)MALLOC(bytes)) == NULL)
{
return ERROR_INT("MALLOC fail for data", procName, 1);
}
fpixSetData(fpixd, data);
return 0;
}
/*!
* fpixDestroy()
*
* Input: &fpix <will be nulled>
* Return: void
*
* Notes:
* (1) Decrements the ref count and, if 0, destroys the fpix.
* (2) Always nulls the input ptr.
*/
void
fpixDestroy(FPIX **pfpix)
{
l_float32 *data;
FPIX *fpix;
PROCNAME("fpixDestroy");
if (!pfpix)
{
L_WARNING("ptr address is null!\n", procName);
return;
}
if ((fpix = *pfpix) == NULL)
{
return;
}
/* Decrement the ref count. If it is 0, destroy the fpix. */
fpixChangeRefcount(fpix, -1);
if (fpixGetRefcount(fpix) <= 0)
{
if ((data = fpixGetData(fpix)) != NULL)
{
FREE(data);
}
FREE(fpix);
}
*pfpix = NULL;
return;
}
/*--------------------------------------------------------------------*
* FPix Accessors *
*--------------------------------------------------------------------*/
/*!
* fpixGetDimensions()
*
* Input: fpix
* &w, &h (<optional return>; each can be null)
* Return: 0 if OK, 1 on error
*/
l_int32
fpixGetDimensions(FPIX *fpix,
l_int32 *pw,
l_int32 *ph)
{
PROCNAME("fpixGetDimensions");
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, 1);
}
if (pw)
{
*pw = fpix->w;
}
if (ph)
{
*ph = fpix->h;
}
return 0;
}
/*!
* fpixSetDimensions()
*
* Input: fpix
* w, h
* Return: 0 if OK, 1 on error
*/
l_int32
fpixSetDimensions(FPIX *fpix,
l_int32 w,
l_int32 h)
{
PROCNAME("fpixSetDimensions");
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, 1);
}
fpix->w = w;
fpix->h = h;
return 0;
}
l_int32
fpixGetWpl(FPIX *fpix)
{
PROCNAME("fpixGetWpl");
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, UNDEF);
}
return fpix->wpl;
}
l_int32
fpixSetWpl(FPIX *fpix,
l_int32 wpl)
{
PROCNAME("fpixSetWpl");
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, 1);
}
fpix->wpl = wpl;
return 0;
}
l_int32
fpixGetRefcount(FPIX *fpix)
{
PROCNAME("fpixGetRefcount");
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, UNDEF);
}
return fpix->refcount;
}
l_int32
fpixChangeRefcount(FPIX *fpix,
l_int32 delta)
{
PROCNAME("fpixChangeRefcount");
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, 1);
}
fpix->refcount += delta;
return 0;
}
l_int32
fpixGetResolution(FPIX *fpix,
l_int32 *pxres,
l_int32 *pyres)
{
PROCNAME("fpixGetResolution");
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, 1);
}
if (pxres)
{
*pxres = fpix->xres;
}
if (pyres)
{
*pyres = fpix->yres;
}
return 0;
}
l_int32
fpixSetResolution(FPIX *fpix,
l_int32 xres,
l_int32 yres)
{
PROCNAME("fpixSetResolution");
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, 1);
}
fpix->xres = xres;
fpix->yres = yres;
return 0;
}
l_int32
fpixCopyResolution(FPIX *fpixd,
FPIX *fpixs)
{
l_int32 xres, yres;
PROCNAME("fpixCopyResolution");
if (!fpixs || !fpixd)
{
return ERROR_INT("fpixs and fpixd not both defined", procName, 1);
}
fpixGetResolution(fpixs, &xres, &yres);
fpixSetResolution(fpixd, xres, yres);
return 0;
}
l_float32 *
fpixGetData(FPIX *fpix)
{
PROCNAME("fpixGetData");
if (!fpix)
{
return (l_float32 *)ERROR_PTR("fpix not defined", procName, NULL);
}
return fpix->data;
}
l_int32
fpixSetData(FPIX *fpix,
l_float32 *data)
{
PROCNAME("fpixSetData");
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, 1);
}
fpix->data = data;
return 0;
}
/*!
* fpixGetPixel()
*
* Input: fpix
* (x,y) pixel coords
* &val (<return> pixel value)
* Return: 0 if OK; 1 on error
*/
l_int32
fpixGetPixel(FPIX *fpix,
l_int32 x,
l_int32 y,
l_float32 *pval)
{
l_int32 w, h;
PROCNAME("fpixGetPixel");
if (!pval)
{
return ERROR_INT("pval not defined", procName, 1);
}
*pval = 0.0;
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, 1);
}
fpixGetDimensions(fpix, &w, &h);
if (x < 0 || x >= w)
{
return ERROR_INT("x out of bounds", procName, 1);
}
if (y < 0 || y >= h)
{
return ERROR_INT("y out of bounds", procName, 1);
}
*pval = *(fpix->data + y * w + x);
return 0;
}
/*!
* fpixSetPixel()
*
* Input: fpix
* (x,y) pixel coords
* val (pixel value)
* Return: 0 if OK; 1 on error
*/
l_int32
fpixSetPixel(FPIX *fpix,
l_int32 x,
l_int32 y,
l_float32 val)
{
l_int32 w, h;
PROCNAME("fpixSetPixel");
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, 1);
}
fpixGetDimensions(fpix, &w, &h);
if (x < 0 || x >= w)
{
return ERROR_INT("x out of bounds", procName, 1);
}
if (y < 0 || y >= h)
{
return ERROR_INT("y out of bounds", procName, 1);
}
*(fpix->data + y * w + x) = val;
return 0;
}
/*--------------------------------------------------------------------*
* FPixa Create/copy/destroy *
*--------------------------------------------------------------------*/
/*!
* fpixaCreate()
*
* Input: n (initial number of ptrs)
* Return: fpixa, or null on error
*/
FPIXA *
fpixaCreate(l_int32 n)
{
FPIXA *fpixa;
PROCNAME("fpixaCreate");
if (n <= 0)
{
n = INITIAL_PTR_ARRAYSIZE;
}
if ((fpixa = (FPIXA *)CALLOC(1, sizeof(FPIXA))) == NULL)
{
return (FPIXA *)ERROR_PTR("pixa not made", procName, NULL);
}
fpixa->n = 0;
fpixa->nalloc = n;
fpixa->refcount = 1;
if ((fpixa->fpix = (FPIX **)CALLOC(n, sizeof(FPIX *))) == NULL)
{
return (FPIXA *)ERROR_PTR("fpix ptrs not made", procName, NULL);
}
return fpixa;
}
/*!
* fpixaCopy()
*
* Input: fpixas
* copyflag:
* L_COPY makes a new fpixa and copies each fpix
* L_CLONE gives a new ref-counted handle to the input fpixa
* L_COPY_CLONE makes a new fpixa with clones of all fpix
* Return: new fpixa, or null on error
*/
FPIXA *
fpixaCopy(FPIXA *fpixa,
l_int32 copyflag)
{
l_int32 i;
FPIX *fpixc;
FPIXA *fpixac;
PROCNAME("fpixaCopy");
if (!fpixa)
{
return (FPIXA *)ERROR_PTR("fpixa not defined", procName, NULL);
}
if (copyflag == L_CLONE)
{
fpixaChangeRefcount(fpixa, 1);
return fpixa;
}
if (copyflag != L_COPY && copyflag != L_COPY_CLONE)
{
return (FPIXA *)ERROR_PTR("invalid copyflag", procName, NULL);
}
if ((fpixac = fpixaCreate(fpixa->n)) == NULL)
{
return (FPIXA *)ERROR_PTR("fpixac not made", procName, NULL);
}
for (i = 0; i < fpixa->n; i++)
{
if (copyflag == L_COPY)
{
fpixc = fpixaGetFPix(fpixa, i, L_COPY);
}
else /* copy-clone */
{
fpixc = fpixaGetFPix(fpixa, i, L_CLONE);
}
fpixaAddFPix(fpixac, fpixc, L_INSERT);
}
return fpixac;
}
/*!
* fpixaDestroy()
*
* Input: &fpixa (<can be nulled>)
* Return: void
*
* Notes:
* (1) Decrements the ref count and, if 0, destroys the fpixa.
* (2) Always nulls the input ptr.
*/
void
fpixaDestroy(FPIXA **pfpixa)
{
l_int32 i;
FPIXA *fpixa;
PROCNAME("fpixaDestroy");
if (pfpixa == NULL)
{
L_WARNING("ptr address is NULL!\n", procName);
return;
}
if ((fpixa = *pfpixa) == NULL)
{
return;
}
/* Decrement the refcount. If it is 0, destroy the pixa. */
fpixaChangeRefcount(fpixa, -1);
if (fpixa->refcount <= 0)
{
for (i = 0; i < fpixa->n; i++)
{
fpixDestroy(&fpixa->fpix[i]);
}
FREE(fpixa->fpix);
FREE(fpixa);
}
*pfpixa = NULL;
return;
}
/*--------------------------------------------------------------------*
* FPixa addition *
*--------------------------------------------------------------------*/
/*!
* fpixaAddFPix()
*
* Input: fpixa
* fpix (to be added)
* copyflag (L_INSERT, L_COPY, L_CLONE)
* Return: 0 if OK; 1 on error
*/
l_int32
fpixaAddFPix(FPIXA *fpixa,
FPIX *fpix,
l_int32 copyflag)
{
l_int32 n;
FPIX *fpixc;
PROCNAME("fpixaAddFPix");
if (!fpixa)
{
return ERROR_INT("fpixa not defined", procName, 1);
}
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, 1);
}
if (copyflag == L_INSERT)
{
fpixc = fpix;
}
else if (copyflag == L_COPY)
{
fpixc = fpixCopy(NULL, fpix);
}
else if (copyflag == L_CLONE)
{
fpixc = fpixClone(fpix);
}
else
{
return ERROR_INT("invalid copyflag", procName, 1);
}
if (!fpixc)
{
return ERROR_INT("fpixc not made", procName, 1);
}
n = fpixaGetCount(fpixa);
if (n >= fpixa->nalloc)
{
fpixaExtendArray(fpixa);
}
fpixa->fpix[n] = fpixc;
fpixa->n++;
return 0;
}
/*!
* fpixaExtendArray()
*
* Input: fpixa
* Return: 0 if OK; 1 on error
*
* Notes:
* (1) Doubles the size of the fpixa ptr array.
*/
static l_int32
fpixaExtendArray(FPIXA *fpixa)
{
PROCNAME("fpixaExtendArray");
if (!fpixa)
{
return ERROR_INT("fpixa not defined", procName, 1);
}
return fpixaExtendArrayToSize(fpixa, 2 * fpixa->nalloc);
}
/*!
* fpixaExtendArrayToSize()
*
* Input: fpixa
* Return: 0 if OK; 1 on error
*
* Notes:
* (1) If necessary, reallocs new fpixa ptrs array to @size.
*/
static l_int32
fpixaExtendArrayToSize(FPIXA *fpixa,
l_int32 size)
{
PROCNAME("fpixaExtendArrayToSize");
if (!fpixa)
{
return ERROR_INT("fpixa not defined", procName, 1);
}
if (size > fpixa->nalloc)
{
if ((fpixa->fpix = (FPIX **)reallocNew((void **)&fpixa->fpix,
sizeof(FPIX *) * fpixa->nalloc,
size * sizeof(FPIX *))) == NULL)
{
return ERROR_INT("new ptr array not returned", procName, 1);
}
fpixa->nalloc = size;
}
return 0;
}
/*--------------------------------------------------------------------*
* FPixa accessors *
*--------------------------------------------------------------------*/
/*!
* fpixaGetCount()
*
* Input: fpixa
* Return: count, or 0 if no pixa
*/
l_int32
fpixaGetCount(FPIXA *fpixa)
{
PROCNAME("fpixaGetCount");
if (!fpixa)
{
return ERROR_INT("fpixa not defined", procName, 0);
}
return fpixa->n;
}
/*!
* fpixaChangeRefcount()
*
* Input: fpixa
* Return: 0 if OK, 1 on error
*/
l_int32
fpixaChangeRefcount(FPIXA *fpixa,
l_int32 delta)
{
PROCNAME("fpixaChangeRefcount");
if (!fpixa)
{
return ERROR_INT("fpixa not defined", procName, 1);
}
fpixa->refcount += delta;
return 0;
}
/*!
* fpixaGetFPix()
*
* Input: fpixa
* index (to the index-th fpix)
* accesstype (L_COPY or L_CLONE)
* Return: fpix, or null on error
*/
FPIX *
fpixaGetFPix(FPIXA *fpixa,
l_int32 index,
l_int32 accesstype)
{
PROCNAME("fpixaGetFPix");
if (!fpixa)
{
return (FPIX *)ERROR_PTR("fpixa not defined", procName, NULL);
}
if (index < 0 || index >= fpixa->n)
{
return (FPIX *)ERROR_PTR("index not valid", procName, NULL);
}
if (accesstype == L_COPY)
{
return fpixCopy(NULL, fpixa->fpix[index]);
}
else if (accesstype == L_CLONE)
{
return fpixClone(fpixa->fpix[index]);
}
else
{
return (FPIX *)ERROR_PTR("invalid accesstype", procName, NULL);
}
}
/*!
* fpixaGetFPixDimensions()
*
* Input: fpixa
* index (to the index-th box)
* &w, &h (<optional return>; each can be null)
* Return: 0 if OK, 1 on error
*/
l_int32
fpixaGetFPixDimensions(FPIXA *fpixa,
l_int32 index,
l_int32 *pw,
l_int32 *ph)
{
FPIX *fpix;
PROCNAME("fpixaGetFPixDimensions");
if (!fpixa)
{
return ERROR_INT("fpixa not defined", procName, 1);
}
if (index < 0 || index >= fpixa->n)
{
return ERROR_INT("index not valid", procName, 1);
}
if ((fpix = fpixaGetFPix(fpixa, index, L_CLONE)) == NULL)
{
return ERROR_INT("fpix not found!", procName, 1);
}
fpixGetDimensions(fpix, pw, ph);
fpixDestroy(&fpix);
return 0;
}
/*!
* fpixaGetPixel()
*
* Input: fpixa
* index (into fpixa array)
* (x,y) pixel coords
* &val (<return> pixel value)
* Return: 0 if OK; 1 on error
*/
l_int32
fpixaGetPixel(FPIXA *fpixa,
l_int32 index,
l_int32 x,
l_int32 y,
l_float32 *pval)
{
l_int32 n, ret;
FPIX *fpix;
PROCNAME("fpixaGetPixel");
if (!pval)
{
return ERROR_INT("pval not defined", procName, 1);
}
*pval = 0.0;
if (!fpixa)
{
return ERROR_INT("fpixa not defined", procName, 1);
}
n = fpixaGetCount(fpixa);
if (index < 0 || index >= n)
{
return ERROR_INT("invalid index into fpixa", procName, 1);
}
fpix = fpixaGetFPix(fpixa, index, L_CLONE);
ret = fpixGetPixel(fpix, x, y, pval);
fpixDestroy(&fpix);
return ret;
}
/*!
* fpixaSetPixel()
*
* Input: fpixa
* index (into fpixa array)
* (x,y) pixel coords
* val (pixel value)
* Return: 0 if OK; 1 on error
*/
l_int32
fpixaSetPixel(FPIXA *fpixa,
l_int32 index,
l_int32 x,
l_int32 y,
l_float32 val)
{
l_int32 n, ret;
FPIX *fpix;
PROCNAME("fpixaSetPixel");
if (!fpixa)
{
return ERROR_INT("fpixa not defined", procName, 1);
}
n = fpixaGetCount(fpixa);
if (index < 0 || index >= n)
{
return ERROR_INT("invalid index into fpixa", procName, 1);
}
fpix = fpixaGetFPix(fpixa, index, L_CLONE);
ret = fpixSetPixel(fpix, x, y, val);
fpixDestroy(&fpix);
return ret;
}
/*--------------------------------------------------------------------*
* DPix Create/copy/destroy *
*--------------------------------------------------------------------*/
/*!
* dpixCreate()
*
* Input: width, height
* Return: dpix (with data allocated and initialized to 0),
* or null on error
*
* Notes:
* (1) Makes a DPix of specified size, with the data array
* allocated and initialized to 0.
*/
DPIX *
dpixCreate(l_int32 width,
l_int32 height)
{
l_float64 *data;
l_uint64 bignum;
DPIX *dpix;
PROCNAME("dpixCreate");
if (width <= 0)
{
return (DPIX *)ERROR_PTR("width must be > 0", procName, NULL);
}
if (height <= 0)
{
return (DPIX *)ERROR_PTR("height must be > 0", procName, NULL);
}
/* Avoid overflow in malloc arg, malicious or otherwise */
bignum = 8L * width * height; /* max number of bytes requested */
if (bignum > ((1LL << 31) - 1))
{
L_ERROR("requested w = %d, h = %d\n", procName, width, height);
return (DPIX *)ERROR_PTR("requested bytes >= 2^31", procName, NULL);
}
if ((dpix = (DPIX *)CALLOC(1, sizeof(DPIX))) == NULL)
{
return (DPIX *)ERROR_PTR("CALLOC fail for dpix", procName, NULL);
}
dpixSetDimensions(dpix, width, height);
dpixSetWpl(dpix, width); /* 8 byte words */
dpix->refcount = 1;
data = (l_float64 *)CALLOC(width * height, sizeof(l_float64));
if (!data)
{
return (DPIX *)ERROR_PTR("CALLOC fail for data", procName, NULL);
}
dpixSetData(dpix, data);
return dpix;
}
/*!
* dpixCreateTemplate()
*
* Input: dpixs
* Return: dpixd, or null on error
*
* Notes:
* (1) Makes a DPix of the same size as the input DPix, with the
* data array allocated and initialized to 0.
* (2) Copies the resolution.
*/
DPIX *
dpixCreateTemplate(DPIX *dpixs)
{
l_int32 w, h;
DPIX *dpixd;
PROCNAME("dpixCreateTemplate");
if (!dpixs)
{
return (DPIX *)ERROR_PTR("dpixs not defined", procName, NULL);
}
dpixGetDimensions(dpixs, &w, &h);
dpixd = dpixCreate(w, h);
dpixCopyResolution(dpixd, dpixs);
return dpixd;
}
/*!
* dpixClone()
*
* Input: dpix
* Return: same dpix (ptr), or null on error
*
* Notes:
* (1) See pixClone() for definition and usage.
*/
DPIX *
dpixClone(DPIX *dpix)
{
PROCNAME("dpixClone");
if (!dpix)
{
return (DPIX *)ERROR_PTR("dpix not defined", procName, NULL);
}
dpixChangeRefcount(dpix, 1);
return dpix;
}
/*!
* dpixCopy()
*
* Input: dpixd (<optional>; can be null, or equal to dpixs,
* or different from dpixs)
* dpixs
* Return: dpixd, or null on error
*
* Notes:
* (1) There are three cases:
* (a) dpixd == null (makes a new dpix; refcount = 1)
* (b) dpixd == dpixs (no-op)
* (c) dpixd != dpixs (data copy; no change in refcount)
* If the refcount of dpixd > 1, case (c) will side-effect
* these handles.
* (2) The general pattern of use is:
* dpixd = dpixCopy(dpixd, dpixs);
* This will work for all three cases.
* For clarity when the case is known, you can use:
* (a) dpixd = dpixCopy(NULL, dpixs);
* (c) dpixCopy(dpixd, dpixs);
* (3) For case (c), we check if dpixs and dpixd are the same size.
* If so, the data is copied directly.
* Otherwise, the data is reallocated to the correct size
* and the copy proceeds. The refcount of dpixd is unchanged.
* (4) This operation, like all others that may involve a pre-existing
* dpixd, will side-effect any existing clones of dpixd.
*/
DPIX *
dpixCopy(DPIX *dpixd, /* can be null */
DPIX *dpixs)
{
l_int32 w, h, bytes;
l_float64 *datas, *datad;
PROCNAME("dpixCopy");
if (!dpixs)
{
return (DPIX *)ERROR_PTR("dpixs not defined", procName, NULL);
}
if (dpixs == dpixd)
{
return dpixd;
}
/* Total bytes in image data */
dpixGetDimensions(dpixs, &w, &h);
bytes = 8 * w * h;
/* If we're making a new dpix ... */
if (!dpixd)
{
if ((dpixd = dpixCreateTemplate(dpixs)) == NULL)
{
return (DPIX *)ERROR_PTR("dpixd not made", procName, NULL);
}
datas = dpixGetData(dpixs);
datad = dpixGetData(dpixd);
memcpy((char *)datad, (char *)datas, bytes);
return dpixd;
}
/* Reallocate image data if sizes are different */
dpixResizeImageData(dpixd, dpixs);
/* Copy data */
dpixCopyResolution(dpixd, dpixs);
datas = dpixGetData(dpixs);
datad = dpixGetData(dpixd);
memcpy((char*)datad, (char*)datas, bytes);
return dpixd;
}
/*!
* dpixResizeImageData()
*
* Input: dpixd, dpixs
* Return: 0 if OK, 1 on error
*/
l_int32
dpixResizeImageData(DPIX *dpixd,
DPIX *dpixs)
{
l_int32 ws, hs, wd, hd, bytes;
l_float64 *data;
PROCNAME("dpixResizeImageData");
if (!dpixs)
{
return ERROR_INT("dpixs not defined", procName, 1);
}
if (!dpixd)
{
return ERROR_INT("dpixd not defined", procName, 1);
}
dpixGetDimensions(dpixs, &ws, &hs);
dpixGetDimensions(dpixd, &wd, &hd);
if (ws == wd && hs == hd) /* nothing to do */
{
return 0;
}
dpixSetDimensions(dpixd, ws, hs);
dpixSetWpl(dpixd, ws); /* 8 byte words */
bytes = 8 * ws * hs;
data = dpixGetData(dpixd);
if (data)
{
FREE(data);
}
if ((data = (l_float64 *)MALLOC(bytes)) == NULL)
{
return ERROR_INT("MALLOC fail for data", procName, 1);
}
dpixSetData(dpixd, data);
return 0;
}
/*!
* dpixDestroy()
*
* Input: &dpix <will be nulled>
* Return: void
*
* Notes:
* (1) Decrements the ref count and, if 0, destroys the dpix.
* (2) Always nulls the input ptr.
*/
void
dpixDestroy(DPIX **pdpix)
{
l_float64 *data;
DPIX *dpix;
PROCNAME("dpixDestroy");
if (!pdpix)
{
L_WARNING("ptr address is null!\n", procName);
return;
}
if ((dpix = *pdpix) == NULL)
{
return;
}
/* Decrement the ref count. If it is 0, destroy the dpix. */
dpixChangeRefcount(dpix, -1);
if (dpixGetRefcount(dpix) <= 0)
{
if ((data = dpixGetData(dpix)) != NULL)
{
FREE(data);
}
FREE(dpix);
}
*pdpix = NULL;
return;
}
/*--------------------------------------------------------------------*
* DPix Accessors *
*--------------------------------------------------------------------*/
/*!
* dpixGetDimensions()
*
* Input: dpix
* &w, &h (<optional return>; each can be null)
* Return: 0 if OK, 1 on error
*/
l_int32
dpixGetDimensions(DPIX *dpix,
l_int32 *pw,
l_int32 *ph)
{
PROCNAME("dpixGetDimensions");
if (!dpix)
{
return ERROR_INT("dpix not defined", procName, 1);
}
if (pw)
{
*pw = dpix->w;
}
if (ph)
{
*ph = dpix->h;
}
return 0;
}
/*!
* dpixSetDimensions()
*
* Input: dpix
* w, h
* Return: 0 if OK, 1 on error
*/
l_int32
dpixSetDimensions(DPIX *dpix,
l_int32 w,
l_int32 h)
{
PROCNAME("dpixSetDimensions");
if (!dpix)
{
return ERROR_INT("dpix not defined", procName, 1);
}
dpix->w = w;
dpix->h = h;
return 0;
}
l_int32
dpixGetWpl(DPIX *dpix)
{
PROCNAME("dpixGetWpl");
if (!dpix)
{
return ERROR_INT("dpix not defined", procName, 1);
}
return dpix->wpl;
}
l_int32
dpixSetWpl(DPIX *dpix,
l_int32 wpl)
{
PROCNAME("dpixSetWpl");
if (!dpix)
{
return ERROR_INT("dpix not defined", procName, 1);
}
dpix->wpl = wpl;
return 0;
}
l_int32
dpixGetRefcount(DPIX *dpix)
{
PROCNAME("dpixGetRefcount");
if (!dpix)
{
return ERROR_INT("dpix not defined", procName, UNDEF);
}
return dpix->refcount;
}
l_int32
dpixChangeRefcount(DPIX *dpix,
l_int32 delta)
{
PROCNAME("dpixChangeRefcount");
if (!dpix)
{
return ERROR_INT("dpix not defined", procName, 1);
}
dpix->refcount += delta;
return 0;
}
l_int32
dpixGetResolution(DPIX *dpix,
l_int32 *pxres,
l_int32 *pyres)
{
PROCNAME("dpixGetResolution");
if (!dpix)
{
return ERROR_INT("dpix not defined", procName, 1);
}
if (pxres)
{
*pxres = dpix->xres;
}
if (pyres)
{
*pyres = dpix->yres;
}
return 0;
}
l_int32
dpixSetResolution(DPIX *dpix,
l_int32 xres,
l_int32 yres)
{
PROCNAME("dpixSetResolution");
if (!dpix)
{
return ERROR_INT("dpix not defined", procName, 1);
}
dpix->xres = xres;
dpix->yres = yres;
return 0;
}
l_int32
dpixCopyResolution(DPIX *dpixd,
DPIX *dpixs)
{
l_int32 xres, yres;
PROCNAME("dpixCopyResolution");
if (!dpixs || !dpixd)
{
return ERROR_INT("dpixs and dpixd not both defined", procName, 1);
}
dpixGetResolution(dpixs, &xres, &yres);
dpixSetResolution(dpixd, xres, yres);
return 0;
}
l_float64 *
dpixGetData(DPIX *dpix)
{
PROCNAME("dpixGetData");
if (!dpix)
{
return (l_float64 *)ERROR_PTR("dpix not defined", procName, NULL);
}
return dpix->data;
}
l_int32
dpixSetData(DPIX *dpix,
l_float64 *data)
{
PROCNAME("dpixSetData");
if (!dpix)
{
return ERROR_INT("dpix not defined", procName, 1);
}
dpix->data = data;
return 0;
}
/*!
* dpixGetPixel()
*
* Input: dpix
* (x,y) pixel coords
* &val (<return> pixel value)
* Return: 0 if OK; 1 on error
*/
l_int32
dpixGetPixel(DPIX *dpix,
l_int32 x,
l_int32 y,
l_float64 *pval)
{
l_int32 w, h;
PROCNAME("dpixGetPixel");
if (!pval)
{
return ERROR_INT("pval not defined", procName, 1);
}
*pval = 0.0;
if (!dpix)
{
return ERROR_INT("dpix not defined", procName, 1);
}
dpixGetDimensions(dpix, &w, &h);
if (x < 0 || x >= w)
{
return ERROR_INT("x out of bounds", procName, 1);
}
if (y < 0 || y >= h)
{
return ERROR_INT("y out of bounds", procName, 1);
}
*pval = *(dpix->data + y * w + x);
return 0;
}
/*!
* dpixSetPixel()
*
* Input: dpix
* (x,y) pixel coords
* val (pixel value)
* Return: 0 if OK; 1 on error
*/
l_int32
dpixSetPixel(DPIX *dpix,
l_int32 x,
l_int32 y,
l_float64 val)
{
l_int32 w, h;
PROCNAME("dpixSetPixel");
if (!dpix)
{
return ERROR_INT("dpix not defined", procName, 1);
}
dpixGetDimensions(dpix, &w, &h);
if (x < 0 || x >= w)
{
return ERROR_INT("x out of bounds", procName, 1);
}
if (y < 0 || y >= h)
{
return ERROR_INT("y out of bounds", procName, 1);
}
*(dpix->data + y * w + x) = val;
return 0;
}
/*--------------------------------------------------------------------*
* FPix serialized I/O *
*--------------------------------------------------------------------*/
/*!
* fpixRead()
*
* Input: filename
* Return: fpix, or null on error
*/
FPIX *
fpixRead(const char *filename)
{
FILE *fp;
FPIX *fpix;
PROCNAME("fpixRead");
if (!filename)
{
return (FPIX *)ERROR_PTR("filename not defined", procName, NULL);
}
if ((fp = fopenReadStream(filename)) == NULL)
{
return (FPIX *)ERROR_PTR("stream not opened", procName, NULL);
}
if ((fpix = fpixReadStream(fp)) == NULL)
{
fclose(fp);
return (FPIX *)ERROR_PTR("fpix not read", procName, NULL);
}
fclose(fp);
return fpix;
}
/*!
* fpixReadStream()
*
* Input: stream
* Return: fpix, or null on error
*/
FPIX *
fpixReadStream(FILE *fp)
{
char buf[256];
l_int32 w, h, nbytes, xres, yres, version;
l_float32 *data;
FPIX *fpix;
PROCNAME("fpixReadStream");
if (!fp)
{
return (FPIX *)ERROR_PTR("stream not defined", procName, NULL);
}
if (fscanf(fp, "\nFPix Version %d\n", &version) != 1)
{
return (FPIX *)ERROR_PTR("not a fpix file", procName, NULL);
}
if (version != FPIX_VERSION_NUMBER)
{
return (FPIX *)ERROR_PTR("invalid fpix version", procName, NULL);
}
if (fscanf(fp, "w = %d, h = %d, nbytes = %d\n", &w, &h, &nbytes) != 3)
{
return (FPIX *)ERROR_PTR("read fail for data size", procName, NULL);
}
/* Use fgets() and sscanf(); not fscanf(), for the last
* bit of header data before the float data. The reason is
* that fscanf throws away white space, and if the float data
* happens to begin with ascii character(s) that are white
* space, it will swallow them and all will be lost! */
if (fgets(buf, sizeof(buf), fp) == NULL)
{
return (FPIX *)ERROR_PTR("fgets read fail", procName, NULL);
}
if (sscanf(buf, "xres = %d, yres = %d\n", &xres, &yres) != 2)
{
return (FPIX *)ERROR_PTR("read fail for xres, yres", procName, NULL);
}
if ((fpix = fpixCreate(w, h)) == NULL)
{
return (FPIX *)ERROR_PTR("fpix not made", procName, NULL);
}
fpixSetResolution(fpix, xres, yres);
data = fpixGetData(fpix);
if (fread(data, 1, nbytes, fp) != nbytes)
{
return (FPIX *)ERROR_PTR("read error for nbytes", procName, NULL);
}
fgetc(fp); /* ending nl */
/* Convert to little-endian if necessary */
fpixEndianByteSwap(fpix, fpix);
return fpix;
}
/*!
* fpixWrite()
*
* Input: filename
* fpix
* Return: 0 if OK, 1 on error
*/
l_int32
fpixWrite(const char *filename,
FPIX *fpix)
{
FILE *fp;
PROCNAME("fpixWrite");
if (!filename)
{
return ERROR_INT("filename not defined", procName, 1);
}
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, 1);
}
if ((fp = fopenWriteStream(filename, "wb")) == NULL)
{
return ERROR_INT("stream not opened", procName, 1);
}
if (fpixWriteStream(fp, fpix))
{
return ERROR_INT("fpix not written to stream", procName, 1);
}
fclose(fp);
return 0;
}
/*!
* fpixWriteStream()
*
* Input: stream (opened for "wb")
* fpix
* Return: 0 if OK, 1 on error
*/
l_int32
fpixWriteStream(FILE *fp,
FPIX *fpix)
{
l_int32 w, h, nbytes, xres, yres;
l_float32 *data;
FPIX *fpixt;
PROCNAME("fpixWriteStream");
if (!fp)
{
return ERROR_INT("stream not defined", procName, 1);
}
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, 1);
}
/* Convert to little-endian if necessary */
fpixt = fpixEndianByteSwap(NULL, fpix);
fpixGetDimensions(fpixt, &w, &h);
data = fpixGetData(fpixt);
nbytes = w * h * sizeof(l_float32);
fpixGetResolution(fpixt, &xres, &yres);
fprintf(fp, "\nFPix Version %d\n", FPIX_VERSION_NUMBER);
fprintf(fp, "w = %d, h = %d, nbytes = %d\n", w, h, nbytes);
fprintf(fp, "xres = %d, yres = %d\n", xres, yres);
fwrite(data, 1, nbytes, fp);
fprintf(fp, "\n");
fpixDestroy(&fpixt);
return 0;
}
/*!
* fpixEndianByteSwap()
*
* Input: fpixd (can be equal to fpixs or NULL)
* fpixs
* Return: fpixd always
*
* Notes:
* (1) On big-endian hardware, this does byte-swapping on each of
* the 4-byte floats in the fpix data. On little-endians,
* the data is unchanged. This is used for serialization
* of fpix; the data is serialized in little-endian byte
* order because most hardware is little-endian.
* (2) The operation can be either in-place or, if fpixd == NULL,
* a new fpix is made. If not in-place, caller must catch
* the returned pointer.
*/
FPIX *
fpixEndianByteSwap(FPIX *fpixd,
FPIX *fpixs)
{
PROCNAME("fpixEndianByteSwap");
if (!fpixs)
{
return (FPIX *)ERROR_PTR("fpixs not defined", procName, fpixd);
}
if (fpixd && (fpixs != fpixd))
{
return (FPIX *)ERROR_PTR("fpixd != fpixs", procName, fpixd);
}
#ifdef L_BIG_ENDIAN
{
l_uint32 *data;
l_int32 i, j, w, h;
l_uint32 word;
fpixGetDimensions(fpixs, &w, &h);
fpixd = fpixCopy(fpixd, fpixs); /* no copy if fpixd == fpixs */
data = (l_uint32 *)fpixGetData(fpixd);
for (i = 0; i < h; i++)
{
for (j = 0; j < w; j++, data++)
{
word = *data;
*data = (word >> 24) |
((word >> 8) & 0x0000ff00) |
((word << 8) & 0x00ff0000) |
(word << 24);
}
}
return fpixd;
}
#else /* L_LITTLE_ENDIAN */
if (fpixd)
{
return fpixd; /* no-op */
}
else
{
return fpixClone(fpixs);
}
#endif /* L_BIG_ENDIAN */
}
/*--------------------------------------------------------------------*
* DPix serialized I/O *
*--------------------------------------------------------------------*/
/*!
* dpixRead()
*
* Input: filename
* Return: dpix, or null on error
*/
DPIX *
dpixRead(const char *filename)
{
FILE *fp;
DPIX *dpix;
PROCNAME("dpixRead");
if (!filename)
{
return (DPIX *)ERROR_PTR("filename not defined", procName, NULL);
}
if ((fp = fopenReadStream(filename)) == NULL)
{
return (DPIX *)ERROR_PTR("stream not opened", procName, NULL);
}
if ((dpix = dpixReadStream(fp)) == NULL)
{
fclose(fp);
return (DPIX *)ERROR_PTR("dpix not read", procName, NULL);
}
fclose(fp);
return dpix;
}
/*!
* dpixReadStream()
*
* Input: stream
* Return: dpix, or null on error
*/
DPIX *
dpixReadStream(FILE *fp)
{
char buf[256];
l_int32 w, h, nbytes, version, xres, yres;
l_float64 *data;
DPIX *dpix;
PROCNAME("dpixReadStream");
if (!fp)
{
return (DPIX *)ERROR_PTR("stream not defined", procName, NULL);
}
if (fscanf(fp, "\nDPix Version %d\n", &version) != 1)
{
return (DPIX *)ERROR_PTR("not a dpix file", procName, NULL);
}
if (version != DPIX_VERSION_NUMBER)
{
return (DPIX *)ERROR_PTR("invalid dpix version", procName, NULL);
}
if (fscanf(fp, "w = %d, h = %d, nbytes = %d\n", &w, &h, &nbytes) != 3)
{
return (DPIX *)ERROR_PTR("read fail for data size", procName, NULL);
}
/* Use fgets() and sscanf(); not fscanf(), for the last
* bit of header data before the float data. The reason is
* that fscanf throws away white space, and if the float data
* happens to begin with ascii character(s) that are white
* space, it will swallow them and all will be lost! */
if (fgets(buf, sizeof(buf), fp) == NULL)
{
return (DPIX *)ERROR_PTR("fgets read fail", procName, NULL);
}
if (sscanf(buf, "xres = %d, yres = %d\n", &xres, &yres) != 2)
{
return (DPIX *)ERROR_PTR("read fail for xres, yres", procName, NULL);
}
if ((dpix = dpixCreate(w, h)) == NULL)
{
return (DPIX *)ERROR_PTR("dpix not made", procName, NULL);
}
dpixSetResolution(dpix, xres, yres);
data = dpixGetData(dpix);
if (fread(data, 1, nbytes, fp) != nbytes)
{
return (DPIX *)ERROR_PTR("read error for nbytes", procName, NULL);
}
fgetc(fp); /* ending nl */
/* Convert to little-endian if necessary */
dpixEndianByteSwap(dpix, dpix);
return dpix;
}
/*!
* dpixWrite()
*
* Input: filename
* dpix
* Return: 0 if OK, 1 on error
*/
l_int32
dpixWrite(const char *filename,
DPIX *dpix)
{
FILE *fp;
PROCNAME("dpixWrite");
if (!filename)
{
return ERROR_INT("filename not defined", procName, 1);
}
if (!dpix)
{
return ERROR_INT("dpix not defined", procName, 1);
}
if ((fp = fopenWriteStream(filename, "wb")) == NULL)
{
return ERROR_INT("stream not opened", procName, 1);
}
if (dpixWriteStream(fp, dpix))
{
return ERROR_INT("dpix not written to stream", procName, 1);
}
fclose(fp);
return 0;
}
/*!
* dpixWriteStream()
*
* Input: stream (opened for "wb")
* dpix
* Return: 0 if OK, 1 on error
*/
l_int32
dpixWriteStream(FILE *fp,
DPIX *dpix)
{
l_int32 w, h, nbytes, xres, yres;
l_float64 *data;
DPIX *dpixt;
PROCNAME("dpixWriteStream");
if (!fp)
{
return ERROR_INT("stream not defined", procName, 1);
}
if (!dpix)
{
return ERROR_INT("dpix not defined", procName, 1);
}
/* Convert to little-endian if necessary */
dpixt = dpixEndianByteSwap(NULL, dpix);
dpixGetDimensions(dpixt, &w, &h);
dpixGetResolution(dpixt, &xres, &yres);
data = dpixGetData(dpixt);
nbytes = w * h * sizeof(l_float64);
fprintf(fp, "\nDPix Version %d\n", DPIX_VERSION_NUMBER);
fprintf(fp, "w = %d, h = %d, nbytes = %d\n", w, h, nbytes);
fprintf(fp, "xres = %d, yres = %d\n", xres, yres);
fwrite(data, 1, nbytes, fp);
fprintf(fp, "\n");
dpixDestroy(&dpixt);
return 0;
}
/*!
* dpixEndianByteSwap()
*
* Input: dpixd (can be equal to dpixs or NULL)
* dpixs
* Return: dpixd always
*
* Notes:
* (1) On big-endian hardware, this does byte-swapping on each of
* the 4-byte words in the dpix data. On little-endians,
* the data is unchanged. This is used for serialization
* of dpix; the data is serialized in little-endian byte
* order because most hardware is little-endian.
* (2) The operation can be either in-place or, if dpixd == NULL,
* a new dpix is made. If not in-place, caller must catch
* the returned pointer.
*/
DPIX *
dpixEndianByteSwap(DPIX *dpixd,
DPIX *dpixs)
{
PROCNAME("dpixEndianByteSwap");
if (!dpixs)
{
return (DPIX *)ERROR_PTR("dpixs not defined", procName, dpixd);
}
if (dpixd && (dpixs != dpixd))
{
return (DPIX *)ERROR_PTR("dpixd != dpixs", procName, dpixd);
}
#ifdef L_BIG_ENDIAN
{
l_uint32 *data;
l_int32 i, j, w, h;
l_uint32 word;
dpixGetDimensions(dpixs, &w, &h);
dpixd = dpixCopy(dpixd, dpixs); /* no copy if dpixd == dpixs */
data = (l_uint32 *)dpixGetData(dpixd);
for (i = 0; i < h; i++)
{
for (j = 0; j < 2 * w; j++, data++)
{
word = *data;
*data = (word >> 24) |
((word >> 8) & 0x0000ff00) |
((word << 8) & 0x00ff0000) |
(word << 24);
}
}
return dpixd;
}
#else /* L_LITTLE_ENDIAN */
if (dpixd)
{
return dpixd; /* no-op */
}
else
{
return dpixClone(dpixs);
}
#endif /* L_BIG_ENDIAN */
}
/*--------------------------------------------------------------------*
* Print FPix (subsampled, for debugging) *
*--------------------------------------------------------------------*/
/*!
* fpixPrintStream()
*
* Input: stream
* fpix
* factor (subsampled)
* Return: 0 if OK, 1 on error
*
* Notes:
* (1) Subsampled printout of fpix for debugging.
*/
l_int32
fpixPrintStream(FILE *fp,
FPIX *fpix,
l_int32 factor)
{
l_int32 i, j, w, h, count;
l_float32 val;
PROCNAME("fpixPrintStream");
if (!fp)
{
return ERROR_INT("stream not defined", procName, 1);
}
if (!fpix)
{
return ERROR_INT("fpix not defined", procName, 1);
}
if (factor < 1)
{
return ERROR_INT("sampling factor < 1f", procName, 1);
}
fpixGetDimensions(fpix, &w, &h);
fprintf(fp, "\nFPix: w = %d, h = %d\n", w, h);
for (i = 0; i < h; i += factor)
{
for (count = 0, j = 0; j < w; j += factor, count++)
{
fpixGetPixel(fpix, j, i, &val);
fprintf(fp, "val[%d, %d] = %f ", i, j, val);
if ((count + 1) % 3 == 0)
{
fprintf(fp, "\n");
}
}
if (count % 3)
{
fprintf(fp, "\n");
}
}
fprintf(fp, "\n");
return 0;
}
|
// bbox.h
//
////////////////////////////////////////////////////////////////////////
#if !defined(__BBOX_H)
#define __BBOX_H
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "..\fwlib\factory.h"
#include "..\fwlib\fwunknown.h"
#include "boundplus.h"
#include "kinetemplate.h"
////////////////////////////////////////////////////////////////////////////////////////////////////
// CBoundingBox
class CBoundingBox : public CTKineNode<FWUNKNOWN<
BASECLASS<IBounding, IKineNode>,
IID_IBounding, IBounding,
IID_IKineNode, IKineNode,
IID_IKineChild, IKineChild,
IID_IKineObj3D, IKineObj3D> >
{
public:
// IKineNode: CreateChild returns E_NOTIMPL
virtual HRESULT _stdcall CreateChild(LPOLESTR pLabel, /*[out, retval]*/ IKineNode **p);
// Data Transfer
virtual HRESULT _stdcall PutData(enum BOUND_FORMAT nFormat, FWULONG nSize, /*[in, size_is(nSize)]*/ BYTE *pBuf);
virtual HRESULT _stdcall GetData(enum BOUND_FORMAT nFormat, FWULONG nSize, /*[out, size_is(nSize)]*/ BYTE *pBuf);
// Query about Supported Formats
HRESULT _InternalQueryInputFormat(enum BOUND_FORMAT, /*[out, retval]*/ enum BOUND_PREFERENCE*);
HRESULT _InternalQueryOutputFormat(enum BOUND_FORMAT, /*[out, retval]*/ enum BOUND_PREFERENCE*);
virtual HRESULT _stdcall QueryInputFormat(enum BOUND_FORMAT, /*[out, retval]*/ enum BOUND_PREFERENCE*);
virtual HRESULT _stdcall QueryOutputFormat(enum BOUND_FORMAT, /*[out, retval]*/ enum BOUND_PREFERENCE*);
virtual HRESULT _stdcall QueryInputFormatEx(FWULONG nLen, /*[in, size_is(nLen)]*/ enum BOUND_FORMAT*, /*[out, size_is(nLen)]*/ enum BOUND_PREFERENCE*);
virtual HRESULT _stdcall QueryOutputFormatEx(FWULONG nLen, /*[in, size_is(nLen)]*/ enum BOUND_FORMAT*, /*[out, size_is(nLen)]*/ enum BOUND_PREFERENCE*);
virtual HRESULT _stdcall QueryDetect(IBounding *pWith, /*[out]*/ enum BOUND_FORMAT*, /*[out]*/ enum BOUND_PREFERENCE*, /*[out]*/ enum BOUND_PRECISION*);
// Collision Detection Test
virtual HRESULT _stdcall Detect(IBounding *pWith);
virtual HRESULT _stdcall DetectEx(IBounding *pWith, BOUND_FORMAT fmt);
// Sub-Boundings (with Hierarchical Tree Algorithms only)
virtual HRESULT _stdcall GetSubBoundings(/*[in, out]*/ FWULONG *nSize, /*[out, size_is(*nSize)]*/ IBounding**)
{ return ERROR(E_NOTIMPL); }
DECLARE_FACTORY_CLASS(BoundingBox, Bounding)
FW_RTTI(BoundingBox)
CBoundingBox();
~CBoundingBox();
protected:
BOUND_OBB m_obb;
};
#endif
|
// This file has been generated by Py++.
#ifndef ConstBaseIterator_663c592fa58613dab4f9509d04eb6cc1_hpp__pyplusplus_wrapper
#define ConstBaseIterator_663c592fa58613dab4f9509d04eb6cc1_hpp__pyplusplus_wrapper
void register_ConstBaseIterator_663c592fa58613dab4f9509d04eb6cc1_class();
#endif//ConstBaseIterator_663c592fa58613dab4f9509d04eb6cc1_hpp__pyplusplus_wrapper
|
#include <iostream>
#include<bitset>
using namespace std;
string panagram(string str)
{
bitset<26> b;
for(int i=0;i<str.length();i++)
{
if(isalpha(str[i]))
b[tolower(str[i])-97]=1;
}
if(b.count()==26)
return "pangram";
return "not pangram";
}
int main() {
// your code goes here
string str;
getline(cin,str);
cout<<panagram(str)<<endl;
return 0;
}
|
// ------------------------------------------------------------------------------------------------
#include "Library/IO/INI.hpp"
// ------------------------------------------------------------------------------------------------
#include <cerrno>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(ResultTypename, _SC("SqIniResult"))
SQMODE_DECL_TYPENAME(EntriesTypename, _SC("SqIniEntries"))
SQMODE_DECL_TYPENAME(DocumentTypename, _SC("SqIniDocument"))
// ------------------------------------------------------------------------------------------------
void IniResult::Check() const
{
// Identify the error type
switch (m_Result)
{
case SI_FAIL:
STHROWF("Unable to %s. Probably invalid", m_Action.c_str());
break;
case SI_NOMEM:
STHROWF("Unable to %s. Ran out of memory", m_Action.c_str());
break;
case SI_FILE:
STHROWF("Unable to %s. %s", strerror(errno));
break;
case SI_OK:
case SI_UPDATED:
case SI_INSERTED:
break; /* These are not error messahes. */
default:
STHROWF("Unable to %s for some unforeseen reason", m_Action.c_str());
}
}
// ------------------------------------------------------------------------------------------------
void DocumentRef::Validate() const
{
// Is the document handle valid?
if (!m_Ptr)
{
STHROWF("Invalid INI document reference");
}
}
// ------------------------------------------------------------------------------------------------
Int32 Entries::Cmp(const Entries & o) const
{
if (m_Elem == o.m_Elem)
{
return 0;
}
else if (m_List.size() > o.m_List.size())
{
return 1;
}
else
{
return -1;
}
}
// ------------------------------------------------------------------------------------------------
void Entries::Next()
{
// Are there any other elements ahead?
if (!m_List.empty() && m_Elem != m_List.end())
{
++m_Elem; // Go ahead one element
}
}
// ------------------------------------------------------------------------------------------------
void Entries::Prev()
{
// Are there any other elements behind?
if (!m_List.empty() && m_Elem != m_List.begin())
{
--m_Elem; // Go back one element
}
}
// ------------------------------------------------------------------------------------------------
void Entries::Advance(Int32 n)
{
// Are there any other elements ahead?
if (m_List.empty() || m_Elem == m_List.end())
{
return;
}
// Jump as many elements as possible within the specified distance
while ((--n >= 0) && m_Elem != m_List.end())
{
++m_Elem;
}
}
// ------------------------------------------------------------------------------------------------
void Entries::Retreat(Int32 n)
{
// Are there any other elements behind?
if (m_List.empty() || m_Elem == m_List.begin())
{
return;
}
// Jump as many elements as possible within the specified distance
while ((--n >= 0) && m_Elem != m_List.begin())
{
--m_Elem;
}
}
// ------------------------------------------------------------------------------------------------
CSStr Entries::GetItem() const
{
// is the current element valid?
if (m_List.empty() || m_Elem == m_List.end())
{
STHROWF("Invalid INI entry [item]");
}
// Return the requested information
return m_Elem->pItem;
}
// ------------------------------------------------------------------------------------------------
CSStr Entries::GetComment() const
{
// is the current element valid?
if (m_List.empty() || m_Elem == m_List.end())
{
STHROWF("Invalid INI entry [comment]");
}
// Return the requested information
return m_Elem->pComment;
}
// ------------------------------------------------------------------------------------------------
Int32 Entries::GetOrder() const
{
// is the current element valid?
if (m_List.empty() || m_Elem == m_List.end())
{
STHROWF("Invalid INI entry [order]");
}
// Return the requested information
return m_Elem->nOrder;
}
// ------------------------------------------------------------------------------------------------
Int32 Document::Cmp(const Document & o) const
{
if (m_Doc == o.m_Doc)
{
return 0;
}
else if (m_Doc.m_Ptr > o.m_Doc.m_Ptr)
{
return 1;
}
else
{
return -1;
}
}
// ------------------------------------------------------------------------------------------------
IniResult Document::LoadFile(CSStr filepath)
{
// Validate the handle
m_Doc.Validate();
// Attempt to load the file from disk and return the result
return IniResult("load INI file", m_Doc->LoadFile(filepath));
}
// ------------------------------------------------------------------------------------------------
IniResult Document::LoadData(CSStr source, Int32 size)
{
// Validate the handle
m_Doc.Validate();
// Attempt to load the file from memory and return the result
return IniResult("load INI file", m_Doc->LoadData(source, size < 0 ? strlen(source) : size));
}
// ------------------------------------------------------------------------------------------------
IniResult Document::SaveFile(CSStr filepath, bool signature)
{
// Validate the handle
m_Doc.Validate();
// Attempt to save the file to disk and return the result
return IniResult("save INI file", m_Doc->SaveFile(filepath, signature));
}
// ------------------------------------------------------------------------------------------------
Object Document::SaveData(bool signature)
{
// Validate the handle
m_Doc.Validate();
// The string where the content will be saved
String source;
// Attempt to save the data to string
if (m_Doc->Save(source, signature) < 0)
{
STHROWF("Unable to save INI document");
}
// Obtain the initial stack size
const StackGuard sg(DefaultVM::Get());
// Transform it into a script object
sq_pushstring(DefaultVM::Get(), source.c_str(), source.size());
// Get the object from the stack and return it
return Var< Object >(DefaultVM::Get(), -1).value;
}
// ------------------------------------------------------------------------------------------------
Entries Document::GetAllSections() const
{
// Validate the handle
m_Doc.Validate();
// Prepare a container to receive the entries
static Container entries;
// Obtain all sections from the INI document
m_Doc->GetAllSections(entries);
// Return the entries and take over content
return Entries(m_Doc, entries);
}
// ------------------------------------------------------------------------------------------------
Entries Document::GetAllKeys(CSStr section) const
{
// Validate the handle
m_Doc.Validate();
// Prepare a container to receive the entries
static Container entries;
// Obtain all sections from the INI document
m_Doc->GetAllKeys(section, entries);
// Return the entries and take over content
return Entries(m_Doc, entries);
}
// ------------------------------------------------------------------------------------------------
Entries Document::GetAllValues(CSStr section, CSStr key) const
{
// Validate the handle
m_Doc.Validate();
// Prepare a container to receive the entries
static Container entries;
// Obtain all sections from the INI document
m_Doc->GetAllValues(section, key, entries);
// Return the entries and take over content
return Entries(m_Doc, entries);
}
// ------------------------------------------------------------------------------------------------
Int32 Document::GetSectionSize(CSStr section) const
{
// Validate the handle
m_Doc.Validate();
// Return the requested information
return m_Doc->GetSectionSize(section);
}
// ------------------------------------------------------------------------------------------------
bool Document::HasMultipleKeys(CSStr section, CSStr key) const
{
// Validate the handle
m_Doc.Validate();
// Where to retrive whether the key has multiple instances
bool multiple = false;
// Attempt to query the information
if (m_Doc->GetValue(section, key, nullptr, &multiple) == nullptr)
{
return true; // Doesn't exist
}
// Return the result
return multiple;
}
// ------------------------------------------------------------------------------------------------
CCStr Document::GetValue(CSStr section, CSStr key, CSStr def) const
{
// Validate the handle
m_Doc.Validate();
// Attempt to query the information and return it
return m_Doc->GetValue(section, key, def, nullptr);
}
// ------------------------------------------------------------------------------------------------
SQInteger Document::GetInteger(CSStr section, CSStr key, SQInteger def) const
{
// Validate the handle
m_Doc.Validate();
// Attempt to query the information and return it
return static_cast< SQInteger >(m_Doc->GetLongValue(section, key, def, nullptr));
}
// ------------------------------------------------------------------------------------------------
SQFloat Document::GetFloat(CSStr section, CSStr key, SQFloat def) const
{
// Validate the handle
m_Doc.Validate();
// Attempt to query the information and return it
return static_cast< SQFloat >(m_Doc->GetDoubleValue(section, key, def, nullptr));
}
// ------------------------------------------------------------------------------------------------
bool Document::GetBoolean(CSStr section, CSStr key, bool def) const
{
// Validate the handle
m_Doc.Validate();
// Attempt to query the information and return it
return m_Doc->GetBoolValue(section, key, def, nullptr);
}
// ------------------------------------------------------------------------------------------------
IniResult Document::SetValue(CSStr section, CSStr key, CSStr value, bool force, CSStr comment)
{
// Validate the handle
m_Doc.Validate();
// Attempt to apply the specified information and return the result
return IniResult("set INI value", m_Doc->SetValue(section, key, value, comment, force));
}
// ------------------------------------------------------------------------------------------------
IniResult Document::SetInteger(CSStr section, CSStr key, SQInteger value, bool hex, bool force, CSStr comment)
{
// Validate the handle
m_Doc.Validate();
// Attempt to apply the specified information and return the result
return IniResult("set INI integer", m_Doc->SetLongValue(section, key, value, comment, hex, force));
}
// ------------------------------------------------------------------------------------------------
IniResult Document::SetFloat(CSStr section, CSStr key, SQFloat value, bool force, CSStr comment)
{
// Validate the handle
m_Doc.Validate();
// Attempt to apply the specified information and return the result
return IniResult("set INI float", m_Doc->SetDoubleValue(section, key, value, comment, force));
}
// ------------------------------------------------------------------------------------------------
IniResult Document::SetBoolean(CSStr section, CSStr key, bool value, bool force, CSStr comment)
{
// Validate the handle
m_Doc.Validate();
// Attempt to apply the specified information
return IniResult("set INI boolean", m_Doc->SetBoolValue(section, key, value, comment, force));
}
// ------------------------------------------------------------------------------------------------
bool Document::DeleteValue(CSStr section, CSStr key, CSStr value, bool empty)
{
// Validate the handle
m_Doc.Validate();
// Attempt to remove the specified value and return the result
return m_Doc->DeleteValue(section, key, value, empty);
}
// ================================================================================================
void Register_INI(HSQUIRRELVM vm)
{
Table inins(vm);
inins.Bind(_SC("Result"),
Class< IniResult >(vm, ResultTypename::Str)
// Constructors
.Ctor()
.Ctor< CSStr, SQInteger >()
.Ctor< const IniResult & >()
// Core Meta-methods
.SquirrelFunc(_SC("_typename"), &ResultTypename::Fn)
.Func(_SC("_tostring"), &IniResult::ToString)
.Func(_SC("cmp"), &IniResult::Cmp)
// Properties
.Prop(_SC("Valid"), &IniResult::IsValid)
.Prop(_SC("Action"), &IniResult::GetAction)
.Prop(_SC("Result"), &IniResult::GetResult)
// Member Methods
.Func(_SC("Check"), &IniResult::Check)
);
inins.Bind(_SC("Entries"),
Class< Entries >(vm, EntriesTypename::Str)
// Constructors
.Ctor()
.Ctor< const Entries & >()
// Core Meta-methods
.SquirrelFunc(_SC("_typename"), &EntriesTypename::Fn)
.Func(_SC("_tostring"), &Entries::ToString)
.Func(_SC("cmp"), &Entries::Cmp)
// Properties
.Prop(_SC("Valid"), &Entries::IsValid)
.Prop(_SC("Empty"), &Entries::IsEmpty)
.Prop(_SC("References"), &Entries::GetRefCount)
.Prop(_SC("Size"), &Entries::GetSize)
.Prop(_SC("Item"), &Entries::GetItem)
.Prop(_SC("Comment"), &Entries::GetComment)
.Prop(_SC("Order"), &Entries::GetOrder)
// Member Methods
.Func(_SC("Reset"), &Entries::Reset)
.Func(_SC("Next"), &Entries::Next)
.Func(_SC("Prev"), &Entries::Prev)
.Func(_SC("Advance"), &Entries::Advance)
.Func(_SC("Retreat"), &Entries::Retreat)
.Func(_SC("Sort"), &Entries::Sort)
.Func(_SC("SortByKeyOrder"), &Entries::SortByKeyOrder)
.Func(_SC("SortByLoadOrder"), &Entries::SortByLoadOrder)
);
inins.Bind(_SC("Document"),
Class< Document, NoCopy< Document > >(vm, DocumentTypename::Str)
// Constructors
.Ctor()
.Ctor< bool >()
.Ctor< bool, bool >()
.Ctor< bool, bool, bool >()
// Core Meta-methods
.SquirrelFunc(_SC("_typename"), &DocumentTypename::Fn)
.Func(_SC("_tostring"), &Document::ToString)
.Func(_SC("cmp"), &Document::Cmp)
// Properties
.Prop(_SC("Valid"), &Document::IsValid)
.Prop(_SC("Empty"), &Document::IsEmpty)
.Prop(_SC("References"), &Document::GetRefCount)
.Prop(_SC("Unicode"), &Document::GetUnicode, &Document::SetUnicode)
.Prop(_SC("MultiKey"), &Document::GetMultiKey, &Document::SetMultiKey)
.Prop(_SC("MultiLine"), &Document::GetMultiLine, &Document::SetMultiLine)
.Prop(_SC("Spaces"), &Document::GetSpaces, &Document::SetSpaces)
// Member Methods
.Func(_SC("Reset"), &Document::Reset)
.Func(_SC("LoadFile"), &Document::LoadFile)
.Overload< IniResult (Document::*)(CSStr) >(_SC("LoadString"), &Document::LoadData)
.Overload< IniResult (Document::*)(CSStr, Int32) >(_SC("LoadString"), &Document::LoadData)
.Overload< IniResult (Document::*)(CSStr) >(_SC("SaveFile"), &Document::SaveFile)
.Overload< IniResult (Document::*)(CSStr, bool) >(_SC("SaveFile"), &Document::SaveFile)
.Func(_SC("SaveData"), &Document::SaveData)
.Func(_SC("GetSections"), &Document::GetAllSections)
.Func(_SC("GetKeys"), &Document::GetAllKeys)
.Func(_SC("GetValues"), &Document::GetAllValues)
.Func(_SC("GetSectionSize"), &Document::GetSectionSize)
.Func(_SC("HasMultipleKeys"), &Document::HasMultipleKeys)
.Func(_SC("GetValue"), &Document::GetValue)
.Func(_SC("GetInteger"), &Document::GetInteger)
.Func(_SC("GetFloat"), &Document::GetFloat)
.Func(_SC("GetBoolean"), &Document::GetBoolean)
.Overload< IniResult (Document::*)(CSStr, CSStr, CSStr) >(_SC("SetValue"), &Document::SetValue)
.Overload< IniResult (Document::*)(CSStr, CSStr, CSStr, bool) >(_SC("SetValue"), &Document::SetValue)
.Overload< IniResult (Document::*)(CSStr, CSStr, CSStr, bool, CSStr) >(_SC("SetValue"), &Document::SetValue)
.Overload< IniResult (Document::*)(CSStr, CSStr, SQInteger) >(_SC("SetInteger"), &Document::SetInteger)
.Overload< IniResult (Document::*)(CSStr, CSStr, SQInteger, bool) >(_SC("SetInteger"), &Document::SetInteger)
.Overload< IniResult (Document::*)(CSStr, CSStr, SQInteger, bool, bool) >(_SC("SetInteger"), &Document::SetInteger)
.Overload< IniResult (Document::*)(CSStr, CSStr, SQInteger, bool, bool, CSStr) >(_SC("SetInteger"), &Document::SetInteger)
.Overload< IniResult (Document::*)(CSStr, CSStr, SQFloat) >(_SC("SetFloat"), &Document::SetFloat)
.Overload< IniResult (Document::*)(CSStr, CSStr, SQFloat, bool) >(_SC("SetFloat"), &Document::SetFloat)
.Overload< IniResult (Document::*)(CSStr, CSStr, SQFloat, bool, CSStr) >(_SC("SetFloat"), &Document::SetFloat)
.Overload< IniResult (Document::*)(CSStr, CSStr, bool) >(_SC("SetBoolean"), &Document::SetBoolean)
.Overload< IniResult (Document::*)(CSStr, CSStr, bool, bool) >(_SC("SetBoolean"), &Document::SetBoolean)
.Overload< IniResult (Document::*)(CSStr, CSStr, bool, bool, CSStr) >(_SC("SetBoolean"), &Document::SetBoolean)
.Overload< bool (Document::*)(CSStr) >(_SC("DeleteValue"), &Document::DeleteValue)
.Overload< bool (Document::*)(CSStr, CSStr) >(_SC("DeleteValue"), &Document::DeleteValue)
.Overload< bool (Document::*)(CSStr, CSStr, CSStr) >(_SC("DeleteValue"), &Document::DeleteValue)
.Overload< bool (Document::*)(CSStr, CSStr, CSStr, bool) >(_SC("DeleteValue"), &Document::DeleteValue)
);
RootTable(vm).Bind(_SC("SqIni"), inins);
ConstTable(vm).Enum(_SC("SqIniError"), Enumeration(vm)
.Const(_SC("Ok"), Int32(SI_OK))
.Const(_SC("Updated"), Int32(SI_UPDATED))
.Const(_SC("Inserted"), Int32(SI_INSERTED))
.Const(_SC("Fail"), Int32(SI_FAIL))
.Const(_SC("NoMem"), Int32(SI_NOMEM))
.Const(_SC("File"), Int32(SI_FILE))
);
}
} // Namespace:: SqMod
|
#ifndef FUZZYCORE_SPACE_DELETION_VIEW_H
#define FUZZYCORE_SPACE_DELETION_VIEW_H
#include "../abstractView/AbstractView.h"
#include "../../models/space/Space.h"
class SpaceDeletionView : public AbstractView {
private:
std::vector<Space> spaces;
void display_spaces() const;
public:
SpaceDeletionView();
void displayStaticContent() override;
void displayDynamicContent() override;
};
#endif
|
#include <bits/stdc++.h>
using namespace std;
class conversion
{
void stack_op(stack<string> &values, stack<char> &opr, bool is_postfix)
{
auto b = values.top();
values.pop();
auto a = values.top();
values.pop();
char op = opr.top();
opr.pop();
string temp = is_postfix ? a + b + op : op + a + b;
values.push(temp);
}
int precedence(char c)
{
if (c == '*' || c == '/')
return 2;
else if (c == '+' || c == '-')
return 1;
return -1;
}
public:
string to_postfix(string eqn)
{
stack<string> post;
stack<char> opr;
for (auto a : eqn)
{
if (a == '(')
opr.push(a);
else if (a == '+' || a == '-' || a == '*' || a == '/')
{
while (precedence(a) >= precedence(opr.top()))
stack_op(post, opr, true);
opr.pop();
}
else if (a == ')')
while (opr.top() != '(')
stack_op(post, opr, true);
else
post.push(a + "");
}
return post.top();
}
string to_prefix(string eqn)
{
stack<string> pre;
stack<char> opr;
for (auto a : eqn)
{
if (a == '(')
opr.push(a);
else if (a == '+' || a == '-' || a == '*' || a == '/')
{
while (precedence(a) >= precedence(opr.top()))
stack_op(pre, opr, false);
opr.pop();
}
else if (a == ')')
while (opr.top() != '(')
stack_op(pre, opr, false);
else
pre.push(a + "");
}
return pre.top();
}
};
int main()
{
return 0;
}
|
/*******************************************************************************
* Cristian Alexandrescu *
* 2163013577ba2bc237f22b3f4d006856 *
* 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 *
* bc9a53289baf23d369484f5343ed5d6c *
*******************************************************************************/
/* Problem 642 - Word Amalgamation */
#if defined(ONLINE_JUDGE) || (!defined(_MSC_VER) || (_MSC_VER > 1600))
#define COMPILER_SUPPORTS_RANGE_BASED_FOR_LOOP
#endif // defined(ONLINE_JUDGE) || (!defined(_MSC_VER) || (_MSC_VER > 1600))
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class AnagramDict {
public:
void Read() {
string oLine;
while (getline(cin, oLine), oLine[0] != 'X') {
string oSorted(oLine);
sort(oSorted.begin(), oSorted.end());
m_oMap[oSorted].push_back(move(oLine));
}
#ifdef COMPILER_SUPPORTS_RANGE_BASED_FOR_LOOP
for (auto &roIt : m_oMap) {
#else
for (auto roItMap = m_oMap.begin(); roItMap != m_oMap.end(); ++roItMap) {
auto &roIt = *roItMap;
#endif // COMPILER_SUPPORTS_RANGE_BASED_FOR_LOOP
auto &roVec = roIt.second;
sort(roVec.begin(), roVec.end());
}
}
vector<string>& GetAnagramGroup(const string &roString) {
return m_oMap[roString];
}
private:
unordered_map<string, vector<string>> m_oMap;
};
int main() {
AnagramDict oDict;
oDict.Read();
for (string oLine; getline(cin, oLine), oLine[0] != 'X'; ) {
string oSorted(oLine);
sort(oSorted.begin(), oSorted.end());
auto &roVec = oDict.GetAnagramGroup(oSorted);
if (roVec.size() == 0) {
cout << "NOT A VALID WORD" << endl;
} else {
#ifdef COMPILER_SUPPORTS_RANGE_BASED_FOR_LOOP
for (const auto &roString : roVec) {
#else
for (auto roItString = roVec.cbegin(); roItString != roVec.cend(); ++roItString) {
auto &roString = *roItString;
#endif // COMPILER_SUPPORTS_RANGE_BASED_FOR_LOOP
cout << roString << endl;
}
}
cout << "******" << endl;
}
return 0;
}
|
#define FILED_GATE_MAX 12
#define FIELD_MAX 256
#define FIELD_AMBENT_MAX 80
class sFIELD;
//필드의 게이트
struct sFGATE {
int x,z,y; //필드 게이트 위치
sFIELD *lpsField; //필드 포인터
};
//필드의 게이트
struct sWARPGATE {
int x,z,y; //필드 게이트 위치
int height,size; //범위
sFGATE OutGate[FILED_GATE_MAX]; //출구 위치
int OutGateCount; //출구 카운터
int LimitLevel; //레벨제한
int SpecialEffect; //특수 효과
};
struct sAMBIENT_POS {
int x,y,z;
int round;
int AmbentNum;
};
#define FIELD_STATE_VILLAGE 0x100
#define FIELD_STATE_FOREST 0x200
#define FIELD_STATE_DESERT 0x300
#define FIELD_STATE_RUIN 0x400
#define FIELD_STATE_DUNGEON 0x500
#define FIELD_STATE_IRON 0x600
#define FIELD_STATE_ROOM 0x800
#define FIELD_STATE_QUEST_ARENA FIELD_STATE_DUNGEON
//######################################################################################
//작 성 자 : 오 영 석
#define FIELD_STATE_ICE 0x900
//######################################################################################
#define FIELD_STATE_CASTLE 0xA00
#define FIELD_STATE_ACTION 0xB00
#define FIELD_STATE_ALL 0x1000
#define FIELD_BACKIMAGE_RAIN 0x00
#define FIELD_BACKIMAGE_NIGHT 0x01
#define FIELD_BACKIMAGE_DAY 0x02
#define FIELD_BACKIMAGE_GLOWDAY 0x03
#define FIELD_BACKIMAGE_DESERT 0x04
#define FIELD_BACKIMAGE_GLOWDESERT 0x05
#define FIELD_BACKIMAGE_NIGHTDESERT 0x06
#define FIELD_BACKIMAGE_RUIN1 0x07
#define FIELD_BACKIMAGE_RUIN2 0x08
#define FIELD_BACKIMAGE_NIGHTRUIN1 0x09
#define FIELD_BACKIMAGE_NIGHTRUIN2 0x0A
#define FIELD_BACKIMAGE_GLOWRUIN1 0x0B
#define FIELD_BACKIMAGE_GLOWRUIN2 0x0C
#define FIELD_BACKIMAGE_NIGHTFALL 0x11
#define FIELD_BACKIMAGE_DAYFALL 0x12
#define FIELD_BACKIMAGE_GLOWFALL 0x13
#define FIELD_BACKIMAGE_NIGHTIRON1 0x14
#define FIELD_BACKIMAGE_NIGHTIRON2 0x15
#define FIELD_BACKIMAGE_DAYIRON 0x16
#define FIELD_BACKIMAGE_GLOWIRON 0x17
#define FIELD_BACKIMAGE_SODSKY 0x18 //천공의 홀
#define FIELD_BACKIMAGE_SODMOON 0x19 //달의 장
#define FIELD_BACKIMAGE_SODSUN 0x20 //태양의 장
#define FIELD_BACKIMAGE_SODNONE 0x21 //아무것두 안나오는 하늘 나머지 장들은 하늘을 없애 버립니다.
#define FIELD_BACKIMAGE_IRONBOSS 0x22 //아이언 보스몹 나오는 하늘
#define FIELD_BACKIMAGE_DAYSNOW 0x23 //
#define FIELD_BACKIMAGE_GLOWSNOW 0x24 //
#define FIELD_BACKIMAGE_NIGHTSNOW 0x25 //
#define FIELD_BACKIMAGE_DAYGREDDY 0x26 //
#define FIELD_BACKIMAGE_GLOWGREDDY 0x27 //
#define FIELD_BACKIMAGE_NIGHTGREDDY 0x28 //
#define FIELD_BACKIMAGE_DAYLOST 0x29 //로스트월드 낮 (성근추가)
#define FIELD_BACKIMAGE_GLOWLOST 0x2A //로스트월드 저녁
#define FIELD_BACKIMAGE_NIGHTLOST 0x2B //로스트월드 밤
#define FIELD_BACKIMAGE_DAYTEMPLE 0x2C //로스트템플 낮
#define FIELD_BACKIMAGE_GLOWTEMPLE 0x2D //로스트템플 저녁
#define FIELD_BACKIMAGE_NIGHTTEMPLE 0x2E //로스트템플 밤
#define FIELD_EVENT_NIGHTMARE 0x01
#define FIELD_START_POINT_MAX 8
#define FIELD_STAGE_OBJ_MAX 50
////////////////// 시작 필드 번호 ///////////////////////
#define START_FIELD_NUM 3
#define START_FIELD_NEBISCO 9
#define START_FIELD_MORYON 21
#define START_FIELD_CASTLE 33
struct ACTION_FIELD_CAMERA {
POINT3D FixPos;
int LeftX,RightX;
};
//필드 구조
class sFIELD {
DWORD head;
public:
char szName[64]; //필드 파일 이름
char szNameMap[64]; //지역 지도 이미지 파일
char szNameTitle[64]; //지역 이름 이미지 파일
int State; //필드 속성
int BackImageCode[3]; //기본 배경 하늘 번호
int BackMusicCode; //배경음악 코드
int FieldEvent; //필드의 이벤트
int GateCount; //필드 게이트의 수
sFGATE FieldGate[FILED_GATE_MAX]; //필드 게이트 ( 연결되는 필드 )
int WarpGateCount; //워프 게이트의 수
int WarpGateActiveNum; //워프케이트 활성 번호
sWARPGATE WarpGate[FILED_GATE_MAX]; //워프 게이트
POINT3D PosWarpOut; //워프 게이트 출구
sAMBIENT_POS AmbientPos[FIELD_AMBENT_MAX]; //배경 효과음
int AmbentCount; //배경 효과음 수
int LimitLevel; //레벨제한
int FieldSight; //필드시야
char *lpStageObjectName[FIELD_STAGE_OBJ_MAX]; //배경 보조 오브젝트
DWORD StgObjBip[FIELD_STAGE_OBJ_MAX]; //배경 보조 오브젝트 BIP애니메이션 사용유무
int StgObjCount;
int cX,cZ; //필드 중앙
int FieldCode; //필드의 코드 번호
int ServerCode;
POINT StartPoint[FIELD_START_POINT_MAX]; //필드 시작 지점
int StartPointCnt; //시작 지점 포인트
ACTION_FIELD_CAMERA ActionCamera; //액션필드에서의 카메라 정보
int AddStageObject( char *szStgObjName , int BipAnimation=0 ); //배경 보조 오브젝트 추가
int GetStageObjectName( int num , char *szNameBuff ); //배경 보조 오브젝트 이름 얻기
int SetCenterPos( int x, int z ); //필드 중앙 좌표 입력
int AddGate( sFIELD *lpsField , int x, int z, int y ); //게이트 추가
int SetName( char *lpName , char *lpNameMap=0 ); //이름 설정
int AddGate2( sFIELD *lpsField , int x, int z, int y ); //게이트 추가
int AddWarpGate( int x, int y, int z, int size , int height ); //워프게이트 추가
int AddWarpOutGate( sFIELD *lpsField , int x, int z, int y ); //워프게이트 출구 추가
int CheckWarpGate( int x, int y, int z ); //워프게이트 확인
int AddStartPoint( int x, int z ); //시작 좌표를 설정 추가
int GetStartPoint( int x, int z , int *mx , int *mz ); //제일 근접한 시작 좌표를 얻는다
int CheckStartPoint( int x, int z ); //시작 좌표상에 캐릭터가 있는지 확인
int AddAmbientPos( int x, int y, int z , int round , int AmbCode ); //배경 효과음 추가
int PlayAmbient(); //배경 효과음 연주 ( 주기적 호출 )
};
//필드 자동 변경 메인
int FieldMain( int x, int y, int z );
//필드 초기화
int InitField();
//필드 시작
int StartField();
//필드 시작
int WarpNextField( int *mx, int *mz );
//필드 워프
int WarpField( int FieldNum , int *mx, int *mz );
//필드 워프
int WarpFieldNearPos( int FieldNum , int x, int z , int *mx, int *mz );
//필드 시작
int WarpStartField( int *mx, int *mz );
//커스텀 필드로 이동
int WarpCustomField( int *mx, int *mz );
//필드 시작 ( 귀환용 )
int WarpStartField( int FieldNum , int *mx, int *mz );
//감옥에서 시작
int WarpPrisonField( int *mx, int *mz );
//윙을 사용한 워프
int WingWarpGate_Field( int dwFieldCode );
//워프 필드
int WarpField2( int Num );
//워프 블레스 캐슬 필드
int WarpCastleField( int MasterClan , int *dx, int *dz );
extern sFIELD sField[ FIELD_MAX ];
extern int PrisonX; //감옥위치
extern int PrisonZ; //감옥위치
extern RECT PrisonRect; //감옥 지역
extern DWORD dwNextWarpDelay; //워프 딜레이
/////////////////////// playmain.cpp 선언 ////////////////////////
//배경을 읽어 온다 ( 쓰레드 사용 )
smSTAGE3D *LoadStageFromField( sFIELD *lpField , sFIELD *lpSecondField );
//배경을 읽어 온다
smSTAGE3D *LoadStageFromField2( sFIELD *lpField , sFIELD *lpSecondField );
extern sFIELD *StageField[2];
extern int FieldLimitLevel_Table[];
//######################################################################################
//작 성 자 : 오 영 석
extern int FieldCount;
//######################################################################################
|
#ifndef COUNTING_WORDS_TIME_MEASURE_H
#define COUNTING_WORDS_TIME_MEASURE_H
#include <chrono>
#include <atomic>
inline std::chrono::steady_clock::time_point get_current_time_fenced() {
static_assert(std::chrono::steady_clock::is_steady, "Timer should be steady (monotonic).");
std::atomic_thread_fence(std::memory_order_seq_cst);
auto res_time = std::chrono::steady_clock::now();
std::atomic_thread_fence(std::memory_order_seq_cst);
return res_time;
}
template<class D>
inline long long to_us(const D& d)
{ return std::chrono::duration_cast<std::chrono::microseconds>(d).count(); }
#endif //COUNTING_WORDS_TIME_MEASURE_H
|
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<iterator>
#include<cassert>
using namespace std;
void insert_sorted(vector<string> &v,const string &word)
{
const auto insert_pos (lower_bound(begin(v),end(v),word));
v.insert(insert_pos,word);
}
int main()
{
vector<string> v{"some","random","words","win","old","a","yy"};
assert(false==is_sorted(begin(v),end(v)));
sort(begin(v),end(v));
assert(true==is_sorted(begin(v),end(v)));
insert_sorted(v,"foo");
insert_sorted(v,"zz");
for(const auto &w:v){
cout<<w<<" ";
}
cout<<'\n';
}
|
#include<stdio.h>
int main()
{
int n=62;
int a,b,m;
printf("%d\n",m);
return 0;
}
|
/*
* Copyright (C) 2018-2019 wuuhii. All rights reserved.
*
* The file is encoding with utf-8 (with BOM). It is a part of QtSwissArmyKnife
* project. The project is a open source project, you can get the source from:
* https://github.com/wuuhii/QtSwissArmyKnife
* https://gitee.com/wuuhii/QtSwissArmyKnife
*
* If you want to know more about the project, please join our QQ group(952218522).
* In addition, the email address of the project author is wuuhii@outlook.com.
*/
#ifndef SAKHIGHLIGHTERSETTINGSWIDGET_HH
#define SAKHIGHLIGHTERSETTINGSWIDGET_HH
#include <QWidget>
#include <QLineEdit>
#include <QGridLayout>
#include <QPushButton>
#include <QTextDocument>
namespace Ui {
class SAKHighlightSettingsWidget;
}
class SAKHighlightSettings;
class SAKHighlightSettingsWidget:public QWidget
{
Q_OBJECT
public:
SAKHighlightSettingsWidget(QTextDocument *doc, QWidget* parent = nullptr);
~SAKHighlightSettingsWidget();
bool eventFilter(QObject *watched, QEvent *event);
private:
Ui::SAKHighlightSettingsWidget *ui = nullptr;
SAKHighlightSettings *highlighter = nullptr;
QLineEdit *inputLineEdit = nullptr;
QPushButton *clearLabelBt = nullptr;
QPushButton *addLabelBt = nullptr;
QGridLayout labelLayout;
QList<QPushButton*> labelList;
private:
void clearLabel();
void resetLabelViewer();
void addLabelFromInput();
void addLabel(QString str);
void deleteLabel(QPushButton *bt);
void resetHighlightKeyword(QStringList keyWords);
};
#endif
|
#ifndef SMART_TEMPERATURE_LCDSCREEN_H
#define SMART_TEMPERATURE_LCDSCREEN_H
#include <LiquidCrystal.h>
class LcdScreen {
public:
virtual void display(const char *message);
virtual void initialize();
explicit LcdScreen(LiquidCrystal *pLiquidCrystal, uint8_t backLightPin) {
this->pLiquidCrystal = pLiquidCrystal;
this->backLightPin = backLightPin;
}
private:
LiquidCrystal *pLiquidCrystal;
uint8_t backLightPin;
};
#endif //SMART_TEMPERATURE_LCDSCREEN_H
|
//Dalton Hook
//4/24/2018
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
int tries = 0;
int toGuess;
bool error = false;
enum statusTypes { NADA, HIGH, LOW, CORRECT };
int status = NADA;
int min = 0;
int max = 101;
int guess = rand() % 100 + 1;
cout << "Welcome to my computer guesss game ";
cout << "Where the computer guesses the number!";
cout << "Please enter your number (between 1 & 100): ";
cin >> toGuess;
cin.get();
while (status != CORRECT)
{
++tries;
cout << "Computer's Guess: " << guess << "\n";
cout << "Press ENTER to continue..." << endl;
cin.get();
if (guess < toGuess)
{
status = LOW;
}
else if (guess > toGuess)
{
status = HIGH;
}
else if (guess == toGuess)
{
status = CORRECT;
}
else
{
error = true;
cout << "OOPS SOmehing is wrong.\n";
cout << "Here are the values: \n";
cout << "Status: " << status << endl;
cout << "toGuess: " << toGuess << endl;
cout << "guess: " << guess << endl;
cout << "tries: " << tries << endl;
}
if (status == HIGH)
{
max = guess;
do
{
guess = rand() % 100 + 1;
} while (guess > max || guess < min);
}
else if (status == LOW)
{
min = guess;
do
{
guess = rand() % 100 + 1;
} while (guess > max || guess < min);
}
else if (status == CORRECT)
{
cout << "It took mark zuckerburg the robot " << tries << " tries!\n";
cout << "The Number REALLY was " << guess << "\n";
cout << "Thank you for playing!" << endl;
}
else
{
error = true;
cout << "Something is wrong.\n";
cout << "Here's are the values: \n";
cout << "Status: " << status << endl;
cout << "toGuess: " << toGuess << endl;
cout << "guess: " << guess << endl;
cout << "tries: " << tries << endl;
}
}
system("pause");
return 0;
}
|
#include "Player2.h"
Player2::Player2()
{
x = 0;
y = 0;
}
|
struct Coordinate
{
double x;
double y;
};
struct DetectionResult
{
Coordinate* topLeft;
Coordinate* topRight;
Coordinate* bottomLeft;
Coordinate* bottomRight;
};
extern "C"
struct ProcessingInput
{
char* path;
DetectionResult detectionResult;
};
extern "C"
struct DetectionResult *detect_edges(char *str);
extern "C"
bool process_image(
char* path,
double topLeftX,
double topLeftY,
double topRightX,
double topRightY,
double bottomLeftX,
double bottomLeftY,
double bottomRightX,
double bottomRightY
);
|
class Solution {
public:
int findDuplicate(vector<int>& num) {
int fast=num[0];
int slow=num[0];
do{
slow=num[slow];
fast=num[num[fast]];
}while(fast!=slow);
fast=num[0];
while(fast!=slow)
{
fast=num[fast];
slow=num[slow];
}
return slow;
}
};
|
#pragma once
#include "Array2D.h"
#include "DungeonGenerator.h"
class Level {
private:
int width, height, floor;
Room* startRoom;
Room* stairRoom;
Room* bossRoom;
RandomInt rnd;
public:
Array2D* dungeon;
Level(int width, int height, int floor);
~Level();
void chooseStartRoom();
void chooseBossRoom();
void chooseStairRoom();
void setStartRoom(Room* room) { startRoom = room; }
void setStairRoom(Room* room) { stairRoom = room; }
void setBossRoom(Room* room) { bossRoom = room; }
Room* getBossRoom() { return bossRoom; }
Room* getStartRoom() { return startRoom; }
Room* getStairRoom() { return stairRoom; }
int getFloor() { return floor; }
};
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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 University of Oxford 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 ARCHIVEOPENER_HPP_
#define ARCHIVEOPENER_HPP_
#include <string>
#include <cassert>
#include "PetscTools.hpp"
#include "FileFinder.hpp"
/**
* A convenience class to assist with managing archives for parallel checkpointing.
*
* When checkpointing a parallel simulation, there are two kinds of data that need to be saved:
* replicated (same for every process) and distributed (different on each process). We wish to
* write these to separate archive files. This class hides the complexity of doing so, such
* that all a user needs to do is create an instance of this class, call GetCommonArchive, and
* read from/write to the returned archive. When done, just destroy the instance (e.g. by
* closing the scope).
*
* Internally the class uses ProcessSpecificArchive<Archive> to store the secondary archive.
*
* Note also that implementations of this templated class only exist for text archives, i.e.
* Archive = boost::archive::text_iarchive (with Stream = std::ifstream), or
* Archive = boost::archive::text_oarchive (with Stream = std::ofstream).
*/
template <class Archive, class Stream>
class ArchiveOpener
{
private:
friend class TestArchivingHelperClasses;
public:
/**
* Open the archives for this process, either for reading or writing depending on the
* template parameter Archive.
*
* Note that when writing, only the master process writes to the main archive. For other
* processes the main archive is a dummy, writing to /dev/null.
*
* @note Must be called collectively, i.e. by all processes!
*
* If writing, and rDirectory is relative to CHASTE_TEST_OUTPUT, it will be created if it
* doesn't exist.
*
* @param rDirectory folder containing archive files.
* @param rFileNameBase base name of archive files. This will be used for the main archive
* (for replicated data) with ".n" (where n is the process index) being appended for
* the secondary archive.
* @param procId this can be specified to read a specific secondary archive, rather than
* this process' default. Should not be used for writing!
*/
ArchiveOpener(const FileFinder& rDirectory,
const std::string& rFileNameBase,
unsigned procId=PetscTools::GetMyRank());
/**
* Close the opened archives.
*/
~ArchiveOpener();
/**
* @return the main archive for replicated data.
*/
Archive* GetCommonArchive()
{
assert(mpCommonArchive != NULL);
return mpCommonArchive;
}
private:
/** The file stream for the main archive. */
Stream* mpCommonStream;
/** The file stream for the secondary archive. */
Stream* mpPrivateStream;
/** The main archive. */
Archive* mpCommonArchive;
/** The secondary archive. */
Archive* mpPrivateArchive;
};
#endif /*ARCHIVEOPENER_HPP_*/
|
#include "audio.h"
Audio::Audio() : Binary()
{
}
Audio::Audio(const QString& id, const QString& titre, const QString &path, const QString &desc) : Binary(id,titre,path,desc)
{
}
Note::NoteType Audio::getType() const{
return AUDIO;
}
|
#include "MissionImpossible/derivatives.hpp"
using namespace MissionImpossible;
int
main()
{
AD<double> x0(3), x1(4), y;
y = (1 - x0) * (1 - x0) + 10 * (x1 - x0 * x0) * (x1 - x0 * x0);
std::cout << y.tape() << std::endl;
// auto grad = gradient(y);
std::cout << "f value \n" << y.value();
std::cout << "Jacobian_row \n" << Jacobian_row(y);
std::cout << "Jacobian_column\n" << Jacobian_column(x0);
std::cout << "Jacobian_column\n" << Jacobian_column(x1);
}
|
/*************************************************************
Author : qmeng
MailTo : qmeng1128@163.com
QQ : 1163306125
Blog : http://blog.csdn.net/Mq_Go/
Create : 2018-03-24 09:29:00
Version: 1.0
**************************************************************/
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
struct node{
string str;
int end;
};
int main(){
int n;
cin >> n;
node temp[1000];
node a;
int b;
for(int i = 0 ; i < n ; i++){
cin >> a.str >> b >> a.end;
temp[b] = a;
}
cin >> n;
for(int i = 0 ; i < n ; i++){
cin >> b;
cout << temp[b].str <<" "<<temp[b].end<<endl;
}
return 0;
}
|
#ifndef CFONTMGR_H
#define CFONTMGR_H
#include <map>
#include <FTGL/ftgl.h>
#include "typedefs.h"
class Font;
class CFontMgr{
typedef std::map<String, Font*> FontList;
public:
Font* getFont(const String& name, const double size);
FTGLTextureFont* loadFont(const String& name, const double size);
private:
FTGLTextureFont* createFTGLFont(const String& name);
FontList _fonts;
};
#endif
|
#include <algorithm> // copy
#include <iostream> // cin, cout, streamsize
#include <iterator> // back_inserter, istream_iterator
#include <limits> // numeric_limits
#include <sstream> // istringstream
#include <string> // getline, string
#include <vector> // vector
int storage_optimization(int n, int m, std::vector<int> h, std::vector<int> v) {
// WRITE YOUR BRILLIANT CODE HERE
std::vector<int> gridx(n+2);
std::vector<int> gridy(m+2);
for(int i = 0; i < gridx.size(); i++)gridx.at(i) = i; //create x-grid from 0 to n+1
for(int j = 0; j < gridy.size(); j++)gridy.at(j) = j; //same as above for y-grid
for(int i = 0; i < gridx.size(); i++){
for(int j = 0; j < h.size(); j++){
if(gridx.at(i) == h.at(j))gridx.erase(gridx.begin() + i); //for loop to remove all dividers from gridx
}
}
for(int i = 0; i < gridy.size(); i++){
for(int j = 0; j < v.size(); j++){
if(gridy.at(i) == v.at(j))gridy.erase(gridy.begin() + i); //same loop as above for gridy
}
}
std::vector<int> newx;
std::vector<int> newy;
for(int i = gridx.size()-1; i > 0; i--)newx.push_back(gridx.at(i) - gridx.at(i-1));
for(int i = gridy.size()-1; i > 0; i--)newy.push_back(gridy.at(i) - gridy.at(i-1));
int max_X = *max_element(newx.begin(), newx.end());
int max_Y = *max_element(newy.begin(), newy.end());
int volume = max_X * max_Y;
return volume;
}
void ignore_line() {
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
template<typename T>
std::vector<T> get_words() {
std::string line;
std::getline(std::cin, line);
std::istringstream ss{line};
std::vector<T> v;
std::copy(std::istream_iterator<T>{ss}, std::istream_iterator<T>{}, std::back_inserter(v));
return v;
}
int main() {
int n;
std::cin >> n;
ignore_line();
int m;
std::cin >> m;
ignore_line();
std::vector<int> h = get_words<int>();
std::vector<int> v = get_words<int>();
int res = storage_optimization(n, m, h, v);
std::cout << res << '\n';
}
|
#ifndef MULTICYCLE_SIM_H
#define MULTICYCLE_SIM_H
#include "elf_reader.h"
#include "reg_def.h"
#include "if.h"
#include "id.h"
#include "ex.h"
#include "mem.h"
#include "wb.h"
#include <cstdio>
#include <iostream>
#define FS_MAX_MEMORY (4 * 1024 * 1024)
#define FS_SP_DEFAULT (FS_MAX_MEMORY - 10000)
class Multicycle_Sim
{
public:
Multicycle_Sim();
bool readelf(char* filename, char* elfname, char** vals, int n_val);
bool init(char* filename, char *elfname, char **vals, int n_val);
void one_step(unsigned int verbose = 1);
void sim(unsigned int verbose = 1);
ERROR_NUM get_errno();
REG read_regfile(int idx);
char read_memory(long long addr);
void print_res();
private:
unsigned long long inst_cnt;
unsigned long long cycle_cnt;
unsigned long long err_loc;
char* interested[20];
int n_interested;
ELF_Reader elf_reader;
IF inst_fetcher;
ID inst_identifier;
EX inst_executor;
MEM inst_memory;
WB inst_writor;
char type;
ERROR_NUM err_no;
char memory[FS_MAX_MEMORY];
TEMPORAL_REG regfile[32];
//FREG fregfile[32];
void init_RegMem();
void load_memory(char* filename);
void update_regfile();
void IFID_PROCEDURE(unsigned int verbose);
void EX_PROCEDURE(unsigned int verbose);
void EXWB_PROCEDURE(unsigned int verbose);
void EXMEM_PROCEDURE(unsigned int verbose);
void EXMEMWB_PROCEDURE(unsigned int verbose);
};
#endif // MULTICYCLE_SIM_H
|
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main( )
{
Mat image;
image = imread("robot.png", 1 );//图像与.cpp文件在同一目录下
if (!image.data)
{
printf("No image data \n");
return -1;
}
// 文件顺利读取, 首先输出一些基本信息
cout<<"图像宽为"<<image.cols<<",高为"<<image.rows<<",通道数为"<<image.channels()<<endl;
namedWindow("Display Image", WINDOW_AUTOSIZE );
imshow("Display Image", image);
waitKey(0);
return 0;
}
|
#include "object.h"
Object::Object(bool moon, float baseSc, float baseOS, float baseSS)
{
/*
# Blender File for a Cube
o Cube
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 1.000000 -0.999999
v 0.999999 1.000000 1.000001
v -1.000000 1.000000 1.000000
v -1.000000 1.000000 -1.000000
s off
f 2 3 4
f 8 7 6
f 1 5 6
f 2 6 7
f 7 8 4
f 1 4 8
f 1 2 4
f 5 8 6
f 2 1 6
f 3 2 7
f 3 7 4
f 5 1 8
*/
Vertices = {
{{1.0f, -1.0f, -1.0f}, {0.0f, 0.0f, 0.0f}},
{{1.0f, -1.0f, 1.0f}, {1.0f, 0.0f, 0.0f}},
{{-1.0f, -1.0f, 1.0f}, {0.0f, 1.0f, 0.0f}},
{{-1.0f, -1.0f, -1.0f}, {0.0f, 0.0f, 1.0f}},
{{1.0f, 1.0f, -1.0f}, {1.0f, 1.0f, 0.0f}},
{{1.0f, 1.0f, 1.0f}, {1.0f, 0.0f, 1.0f}},
{{-1.0f, 1.0f, 1.0f}, {0.0f, 1.0f, 1.0f}},
{{-1.0f, 1.0f, -1.0f}, {1.0f, 1.0f, 1.0f}}
};
Indices = {
2, 3, 4,
8, 7, 6,
1, 5, 6,
2, 6, 7,
7, 8, 4,
1, 4, 8,
1, 2, 4,
5, 8, 6,
2, 1, 6,
3, 2, 7,
3, 7, 4,
5, 1, 8
};
// The index works at a 0th index
for(unsigned int i = 0; i < Indices.size(); i++)
{
Indices[i] = Indices[i] - 1;
}
isMoon = moon;
angleOrbit = 0.0f;
angleSelf = 0.0f;
pausedOrbit = false;
pausedSpin = false;
reversedOrbit = false;
reversedSpin = false;
position = glm::mat4(1.0f);
baseScale = baseSc;
scaleMult = 1.0f; //scales up/down 0.25 w/ each keypress
maxScale = 3.0f;
minScale = 0.25f;
baseOrbitSpeed = baseOS;
baseSpinSpeed = baseSS;
orbitSpeedMult = 1.0f; //scales up/down 0.25 w/ each keypress
spinSpeedMult = 1.0f; //scales up/down 0.25 w/ each keypress
maxSpeed = 3.0f;
minSpeed = 0.25f;
glGenBuffers(1, &VB);
glBindBuffer(GL_ARRAY_BUFFER, VB);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * Vertices.size(), &Vertices[0], GL_STATIC_DRAW);
glGenBuffers(1, &IB);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IB);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * Indices.size(), &Indices[0], GL_STATIC_DRAW);
}
Object::~Object()
{
Vertices.clear();
Indices.clear();
}
void Object::Update(unsigned int dt, glm::mat4 orbitOrigin)
{
if(!pausedOrbit)
{
if(reversedOrbit)
angleOrbit -= dt * M_PI/(baseOrbitSpeed / orbitSpeedMult); //the angle of the object's orbit
else
angleOrbit += dt * M_PI/(baseOrbitSpeed / orbitSpeedMult); //the angle of the object's orbit
}
if(!pausedSpin)
{
if(reversedSpin)
angleSelf -= dt * M_PI/(baseSpinSpeed / spinSpeedMult); //the angle of the object's orbit
else
angleSelf += dt * M_PI/(baseSpinSpeed / spinSpeedMult); //the angle of the object's orbit
}
position = glm::translate(orbitOrigin, glm::vec3((5.0f * sin(angleOrbit)), 0.0f, (5.0f * cos(angleOrbit)))); //translates cube about the designated orbitOrigin
glm::mat4 rotSelf = glm::rotate(glm::mat4(1.0f), (angleSelf), glm::vec3(0.0, 1.0, 0.0)); //sets the cube's rotation about its center y-axis
glm::mat4 scaleMat = glm::scale(glm::vec3((scaleMult * baseScale), (scaleMult * baseScale), (scaleMult * baseScale))); //set the scale of the object
model = position * rotSelf * scaleMat; //multiply matrices to apply effects to the model
}
glm::mat4 Object::GetModel()
{
return model;
}
glm::mat4 Object::GetPosition()
{
return position;
}
void Object::Render()
{
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, VB);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex,color));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IB);
glDrawElements(GL_TRIANGLES, Indices.size(), GL_UNSIGNED_INT, 0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
}
void Object::SetScale(bool scalar)
{
if(scalar) //if increasing
{
if(scaleMult + 0.25f > maxScale) //be sure not to go over the max limit
scaleMult = maxScale;
else
scaleMult += 0.25f;
}
else //if decreasing
{
if(scaleMult - 0.25f < minScale) //be sure not to go under the min limit
scaleMult = minScale;
else
scaleMult -= 0.25f;
}
}
void Object::SetOrbitSpeed(bool scalar)
{
if(scalar) //if increasing
{
if(orbitSpeedMult + 0.25f > maxSpeed) //be sure not to go over the max limit
orbitSpeedMult = maxSpeed;
else
orbitSpeedMult += 0.25f;
}
else //if decreasing
{
if(orbitSpeedMult - 0.25f < minSpeed) //be sure not to go under the min limit
orbitSpeedMult = minSpeed;
else
orbitSpeedMult -= 0.25f;
}
}
void Object::SetSpinSpeed(bool scalar)
{
if(scalar) //if increasing
{
if(spinSpeedMult + 0.25f > maxSpeed) //be sure not to go over the max limit
spinSpeedMult = maxSpeed;
else
spinSpeedMult += 0.25f;
}
else //if decreasing
{
if(spinSpeedMult - 0.25f < minSpeed) //be sure not to go under the min limit
spinSpeedMult = minSpeed;
else
spinSpeedMult -= 0.25f;
}
}
|
#include "physics\Singularity.Physics.h"
namespace Singularity
{
namespace Physics
{
class PhysicsMotionState : public btMotionState
{
public:
#pragma region Variables
Vector3 m_kCenterOfMass;
Singularity::Components::Transform* m_pBoundTransform;
bool m_bLockRotation;
#pragma endregion
#pragma region Constructors and Finalizers
PhysicsMotionState(Singularity::Components::Transform* transform, Vector3 centerOfMass = Vector3(0,0,0), bool lockRotation = false);
~PhysicsMotionState() {};
#pragma endregion
#pragma region Overriden Methods
void getWorldTransform(btTransform& worldTrans) const;
void setWorldTransform(const btTransform& worldTrans);
#pragma endregion
friend class RigidBody;
friend class Collider;
};
}
}
|
#ifndef MENU_CHICKFILA
#define MENU_CHICKFILA
#include "../../menu_component.hpp"
#include <iostream>
using namespace std;
class menu_chickfila : public menu_component
{
protected:
string menu_name_chickfila;
string menu_description_chickfila;
vector<menu_component *> v_menu_chickfila;
public:
menu_chickfila(string menu_name_chickfila, string menu_description_chickfila) : menu_component()
{
this->menu_name_chickfila = menu_name_chickfila;
this->menu_description_chickfila = menu_description_chickfila;
}
string get_name()
{
return this->menu_name_chickfila;
}
string get_description()
{
return this->menu_description_chickfila;
}
void add(menu_component *menu_component)
{
v_menu_chickfila.push_back(menu_component);
}
void print()
{
cout << "\nMenu Name: " << this->menu_name_chickfila << endl
<< "Menu Description: " << this->menu_description_chickfila << endl
<< endl;
for (auto m_menu_chickfila : v_menu_chickfila)
{
m_menu_chickfila->print();
}
}
};
#endif /* MENU_CHICKFILA */
|
// This file has been generated by Py++.
#include "boost/python.hpp"
#include "generators/include/python_CEGUI.h"
#include "ImagePropertyDim.pypp.hpp"
namespace bp = boost::python;
struct ImagePropertyDim_wrapper : CEGUI::ImagePropertyDim, bp::wrapper< CEGUI::ImagePropertyDim > {
ImagePropertyDim_wrapper(CEGUI::ImagePropertyDim const & arg )
: CEGUI::ImagePropertyDim( arg )
, bp::wrapper< CEGUI::ImagePropertyDim >(){
// copy constructor
}
ImagePropertyDim_wrapper( )
: CEGUI::ImagePropertyDim( )
, bp::wrapper< CEGUI::ImagePropertyDim >(){
// null constructor
}
ImagePropertyDim_wrapper(::CEGUI::String const & property_name, ::CEGUI::DimensionType dim )
: CEGUI::ImagePropertyDim( boost::ref(property_name), dim )
, bp::wrapper< CEGUI::ImagePropertyDim >(){
// constructor
}
virtual ::CEGUI::BaseDim * clone( ) const {
if( bp::override func_clone = this->get_override( "clone" ) )
return func_clone( );
else{
return this->CEGUI::ImagePropertyDim::clone( );
}
}
::CEGUI::BaseDim * default_clone( ) const {
return CEGUI::ImagePropertyDim::clone( );
}
virtual ::CEGUI::Image const * getSourceImage( ::CEGUI::Window const & wnd ) const {
if( bp::override func_getSourceImage = this->get_override( "getSourceImage" ) )
return func_getSourceImage( boost::ref(wnd) );
else{
return this->CEGUI::ImagePropertyDim::getSourceImage( boost::ref(wnd) );
}
}
virtual ::CEGUI::Image const * default_getSourceImage( ::CEGUI::Window const & wnd ) const {
return CEGUI::ImagePropertyDim::getSourceImage( boost::ref(wnd) );
}
virtual void writeXMLElementAttributes_impl( ::CEGUI::XMLSerializer & xml_stream ) const {
if( bp::override func_writeXMLElementAttributes_impl = this->get_override( "writeXMLElementAttributes_impl" ) )
func_writeXMLElementAttributes_impl( boost::ref(xml_stream) );
else{
this->CEGUI::ImagePropertyDim::writeXMLElementAttributes_impl( boost::ref(xml_stream) );
}
}
virtual void default_writeXMLElementAttributes_impl( ::CEGUI::XMLSerializer & xml_stream ) const {
CEGUI::ImagePropertyDim::writeXMLElementAttributes_impl( boost::ref(xml_stream) );
}
virtual void writeXMLElementName_impl( ::CEGUI::XMLSerializer & xml_stream ) const {
if( bp::override func_writeXMLElementName_impl = this->get_override( "writeXMLElementName_impl" ) )
func_writeXMLElementName_impl( boost::ref(xml_stream) );
else{
this->CEGUI::ImagePropertyDim::writeXMLElementName_impl( boost::ref(xml_stream) );
}
}
virtual void default_writeXMLElementName_impl( ::CEGUI::XMLSerializer & xml_stream ) const {
CEGUI::ImagePropertyDim::writeXMLElementName_impl( boost::ref(xml_stream) );
}
virtual bool handleFontRenderSizeChange( ::CEGUI::Window & window, ::CEGUI::Font const * font ) const {
if( bp::override func_handleFontRenderSizeChange = this->get_override( "handleFontRenderSizeChange" ) )
return func_handleFontRenderSizeChange( boost::ref(window), boost::python::ptr(font) );
else{
return this->CEGUI::BaseDim::handleFontRenderSizeChange( boost::ref(window), boost::python::ptr(font) );
}
}
bool default_handleFontRenderSizeChange( ::CEGUI::Window & window, ::CEGUI::Font const * font ) const {
return CEGUI::BaseDim::handleFontRenderSizeChange( boost::ref(window), boost::python::ptr(font) );
}
virtual void writeXMLToStream( ::CEGUI::XMLSerializer & xml_stream ) const {
if( bp::override func_writeXMLToStream = this->get_override( "writeXMLToStream" ) )
func_writeXMLToStream( boost::ref(xml_stream) );
else{
this->CEGUI::BaseDim::writeXMLToStream( boost::ref(xml_stream) );
}
}
void default_writeXMLToStream( ::CEGUI::XMLSerializer & xml_stream ) const {
CEGUI::BaseDim::writeXMLToStream( boost::ref(xml_stream) );
}
};
void register_ImagePropertyDim_class(){
{ //::CEGUI::ImagePropertyDim
typedef bp::class_< ImagePropertyDim_wrapper > ImagePropertyDim_exposer_t;
ImagePropertyDim_exposer_t ImagePropertyDim_exposer = ImagePropertyDim_exposer_t( "ImagePropertyDim", "! ImageDimBase subclass that accesses an image fetched via a property.\n", bp::init< >() );
bp::scope ImagePropertyDim_scope( ImagePropertyDim_exposer );
ImagePropertyDim_exposer.def( bp::init< CEGUI::String const &, CEGUI::DimensionType >(( bp::arg("property_name"), bp::arg("dim") ), "*!\n\
\n\
Constructor.\n\
\n\
@param property_name\n\
String holding the name of the property on the target that will be\n\
accessed to retrieve the name of the image to be accessed by the\n\
ImageDim.\n\
\n\
@param dim\n\
DimensionType value indicating which dimension of an Image that\n\
this ImageDim is to represent.\n\
*\n") );
{ //::CEGUI::ImagePropertyDim::clone
typedef ::CEGUI::BaseDim * ( ::CEGUI::ImagePropertyDim::*clone_function_type )( ) const;
typedef ::CEGUI::BaseDim * ( ImagePropertyDim_wrapper::*default_clone_function_type )( ) const;
ImagePropertyDim_exposer.def(
"clone"
, clone_function_type(&::CEGUI::ImagePropertyDim::clone)
, default_clone_function_type(&ImagePropertyDim_wrapper::default_clone)
, bp::return_value_policy< bp::reference_existing_object >() );
}
{ //::CEGUI::ImagePropertyDim::getSourceImage
typedef ::CEGUI::Image const * ( ImagePropertyDim_wrapper::*getSourceImage_function_type )( ::CEGUI::Window const & ) const;
ImagePropertyDim_exposer.def(
"getSourceImage"
, getSourceImage_function_type( &ImagePropertyDim_wrapper::default_getSourceImage )
, ( bp::arg("wnd") )
, bp::return_value_policy< bp::reference_existing_object >()
, "Implementation overrides of functions in superclasses\n" );
}
{ //::CEGUI::ImagePropertyDim::getSourceProperty
typedef ::CEGUI::String const & ( ::CEGUI::ImagePropertyDim::*getSourceProperty_function_type )( ) const;
ImagePropertyDim_exposer.def(
"getSourceProperty"
, getSourceProperty_function_type( &::CEGUI::ImagePropertyDim::getSourceProperty )
, bp::return_value_policy< bp::copy_const_reference >()
, "! return the name of the property accessed by this ImagePropertyDim.\n" );
}
{ //::CEGUI::ImagePropertyDim::setSourceProperty
typedef void ( ::CEGUI::ImagePropertyDim::*setSourceProperty_function_type )( ::CEGUI::String const & ) ;
ImagePropertyDim_exposer.def(
"setSourceProperty"
, setSourceProperty_function_type( &::CEGUI::ImagePropertyDim::setSourceProperty )
, ( bp::arg("property_name") )
, "! return the name of the property accessed by this ImagePropertyDim.\n\
! set the name of the property accessed by this ImagePropertyDim.\n" );
}
{ //::CEGUI::ImagePropertyDim::writeXMLElementAttributes_impl
typedef void ( ImagePropertyDim_wrapper::*writeXMLElementAttributes_impl_function_type )( ::CEGUI::XMLSerializer & ) const;
ImagePropertyDim_exposer.def(
"writeXMLElementAttributes_impl"
, writeXMLElementAttributes_impl_function_type( &ImagePropertyDim_wrapper::default_writeXMLElementAttributes_impl )
, ( bp::arg("xml_stream") ) );
}
{ //::CEGUI::ImagePropertyDim::writeXMLElementName_impl
typedef void ( ImagePropertyDim_wrapper::*writeXMLElementName_impl_function_type )( ::CEGUI::XMLSerializer & ) const;
ImagePropertyDim_exposer.def(
"writeXMLElementName_impl"
, writeXMLElementName_impl_function_type( &ImagePropertyDim_wrapper::default_writeXMLElementName_impl )
, ( bp::arg("xml_stream") )
, "Implementation overrides of functions in superclasses\n" );
}
{ //::CEGUI::BaseDim::handleFontRenderSizeChange
typedef bool ( ::CEGUI::BaseDim::*handleFontRenderSizeChange_function_type )( ::CEGUI::Window &,::CEGUI::Font const * ) const;
typedef bool ( ImagePropertyDim_wrapper::*default_handleFontRenderSizeChange_function_type )( ::CEGUI::Window &,::CEGUI::Font const * ) const;
ImagePropertyDim_exposer.def(
"handleFontRenderSizeChange"
, handleFontRenderSizeChange_function_type(&::CEGUI::BaseDim::handleFontRenderSizeChange)
, default_handleFontRenderSizeChange_function_type(&ImagePropertyDim_wrapper::default_handleFontRenderSizeChange)
, ( bp::arg("window"), bp::arg("font") ) );
}
{ //::CEGUI::BaseDim::writeXMLToStream
typedef void ( ::CEGUI::BaseDim::*writeXMLToStream_function_type )( ::CEGUI::XMLSerializer & ) const;
typedef void ( ImagePropertyDim_wrapper::*default_writeXMLToStream_function_type )( ::CEGUI::XMLSerializer & ) const;
ImagePropertyDim_exposer.def(
"writeXMLToStream"
, writeXMLToStream_function_type(&::CEGUI::BaseDim::writeXMLToStream)
, default_writeXMLToStream_function_type(&ImagePropertyDim_wrapper::default_writeXMLToStream)
, ( bp::arg("xml_stream") ) );
}
}
}
|
#include <bits/stdc++.h>
using namespace std;
class StackArray{
int *data;
int nextindex;
int capacity;
public:
StackArray(int totalsize){
data=new int[4];
nextindex=0;
capacity=4;
}
//return the number of elements present in the stack
int size(){
return nextindex;
}
bool isEmpty(){
return nextindex==0;
}
//insert push function
void push(int element){
if(capacity==nextindex){
int *newdata = new int[2*capacity];
for(int i=0;i<capacity;i++){
newdata[i]=data[i];
}
capacity = capacity*2;
delete [] data;
data =newdata;
}
data[nextindex]=element;
nextindex++;
}
//delete element
int pop(){
if(isEmpty()){
cout<<"stack is empty";
return 0;
}
nextindex--;
return data[nextindex];
}
int top(){
if(isEmpty()){
cout<<"stack is empty";
return 0;
}
return data[nextindex-1];
}
};
int main(){
StackArray s1(4);
s1.push(10);
s1.push(20);
s1.push(30);
s1.push(40);
s1.push(50);
cout<<s1.top()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.size()<<endl;
cout<<s1.isEmpty()<<endl;
return 0;
}
|
#include "../include/Outils.h"
#include <openssl/sha.h>
#include <sstream>
#include <iostream>
#include <math.h>
#include <fstream>
#include <stdlib.h>
std::vector<int> outils::chaine_to_ascii(const std::string& message) {
std::vector<int> tab_ascii;
for (unsigned int i = 0; i < message.size(); ++i)
tab_ascii.push_back((int)message[i]);
return tab_ascii;
}
std::vector<int> outils::ascii_to_binaire(const std::vector<int>& tab_ascii) {
std::vector<int> tab_binaire;
for (unsigned int j = 0; j < tab_ascii.size(); ++j) {
int valeur = tab_ascii[j];
int val_binaire;
for (unsigned int i = 0; i < 8; ++i) {
if (pow(2,7-i) <= valeur) {
val_binaire = 1;
valeur -= pow(2,7-i);
}
else {
val_binaire = -1;
}
tab_binaire.push_back(val_binaire);
}
}
return tab_binaire;
}
std::string outils::ascii_to_chaine(const std::vector<int>& tab_ascii) {
std::string message;
for (unsigned int i = 0; i < tab_ascii.size(); ++i)
message += (char)tab_ascii[i];
return message;
}
std::vector<int> outils::binaire_to_ascii(const std::vector<int>& tab_binaire) {
std::vector<int> tab_ascii;
int val = 0;
for (unsigned int i = 0; i < tab_binaire.size(); i += 8) {
for (unsigned int j = i; j < i+8 ; ++j) {
if(tab_binaire[j] == 1) {
val += pow(2, 7-(j%8));
}
}
tab_ascii.push_back(val);
val = 0;
}
return tab_ascii;
}
void outils::affiche_ascii(const std::vector<int>& tab_ascii) {
std::cout << "ASCII: [" ;
for (unsigned int i = 0; i < tab_ascii.size(); ++i)
std::cout << tab_ascii[i] << ", ";
std::cout << "\b\b]\n\n";
}
void outils::affiche_binaire(const std::vector<int> tab_binaire) {
std::cout << "Binaire: [" ;
for (unsigned int i = 0; i < tab_binaire.size(); ++i)
std::cout << tab_binaire[i] << ", ";
std::cout << "\b\b]\n\n";
}
mpz_class outils::calcul_a(const mpz_class& n, const std::string& ID) {
mpz_class a;
// ############# Initialisation #############
unsigned char tab_hash_base_64[SHA256_DIGEST_LENGTH]; //Contient les résultats du hachage
SHA256_CTX ctx;
// ############# Hachages successifs #############
std::string to_hash = ID;
do {
// on prépare le contexte pour le hash
SHA256_Init(&ctx);
SHA256_Update(&ctx, to_hash.c_str(), to_hash.length());
SHA256_Final(tab_hash_base_64, &ctx);
// on transforme le base 64 du hash en base 32
char tab_hash_base_32[SHA256_DIGEST_LENGTH*2+1];
for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i)
sprintf(&tab_hash_base_32[i*2], "%02x", tab_hash_base_64[i]);
// on met dans une mpz_class le hash et base 32
mpz_class hh;
mpz_set_str(hh.get_mpz_t(), tab_hash_base_32, 16);
// on teste la condition de bouclage
if(mpz_jacobi(hh.get_mpz_t(), n.get_mpz_t()) == 1) {
a = hh;
break;
}
to_hash = tab_hash_base_32;
} while(1);
return a;
}
std::string outils::generer_cle_aleatoire_AES() {
int valeur;
std::string res = "";
for (unsigned int i=0; i < 16; ++i) {
valeur = rand()%128+1;
res += (char)valeur;
}
return res;
}
void outils::error_(const char *file, const int ligne, const std::string &msg, bool cond, int errnum, bool exception) {
if (cond) {
std::ostringstream c;
if (exception) {
c << "\033[31;11mERREUR\033[00m";
} else {
c << "\033[34;11mWARNING\033[00m";
}
c << " fichier " << file << " ligne " << ligne << " : ";
if (errnum != 0) {
std::system_error err = std::system_error(errno, std::system_category(), msg);
c << err.what() << std::endl;
std::cerr << c.str();
if (exception) {
throw err;
}
} else {
std::runtime_error err = std::runtime_error(msg);
c << err.what() << std::endl;
std::cerr << c.str();
if (exception) {
throw err;
}
}
}
}
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string outils::base64_encode(const unsigned char * bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = ( char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
std::string outils::base64_decode(const std::string& chaine) {
int in_len = chaine.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( chaine[in_] != '=') && is_base64(chaine[in_])) {
char_array_4[i++] = chaine[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = ( char_array_4[0] << 2 ) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = 0; j < i; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
std::string outils::hasher(const std::string& to_hash) {
unsigned char tab_hash_base_64[SHA256_DIGEST_LENGTH]; //Contient les résultats du hachage
SHA256_CTX ctx;
// on prépare le contexte pour le hash
SHA256_Init(&ctx);
SHA256_Update(&ctx, to_hash.c_str(), to_hash.length());
SHA256_Final(tab_hash_base_64, &ctx);
// on transforme le base 64 du hash en base 32
char tab_hash_base_32[SHA256_DIGEST_LENGTH*2+1];
for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i)
sprintf(&tab_hash_base_32[i*2], "%02x", tab_hash_base_64[i]);
std::string res(tab_hash_base_32);
return res;
}
bool outils::fichier_existe(const std::string& _nom_fichier) {
std::ifstream f(_nom_fichier.c_str());
return f.good();
}
void outils::creer_dossiers(const std::string& chemin) {
std::string commande = "mkdir -p " + chemin;
int dir_err = system(commande.c_str());
if (-1 == dir_err) {
printf("Error creating directory!n");
exit(1);
}
}
std::string outils::smtp_get_current_date() {
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,sizeof(buffer),"%a, %d %b %Y %T %z",timeinfo);
std::string res(buffer);
return res;
}
int outils::nombre_aleatoire(int min, int max){
return rand() % (max - min) + min;
}
void outils::recuperer_dernier_mail(std::string mail, std::string mdp) {
system("g++ -lcurl src/curl.cpp -o bin/curl.app");
std::string cmd = "./bin/curl.app " + mail + " " + mdp + " > data/clients/" + mail + "/mail_recu.txt";
system(cmd.c_str());
}
|
#include "Sphere.h"
#include <assert.h>
// Implements Gear integration.
// Computes the positions, velocities and higher-order time derivatives as Taylor expansions of the present values.
void Sphere::predict(double dt)
{
double a1 = dt;
double a2 = a1 * dt / 2;
double a3 = a2 * dt / 3;
double a4 = a3 * dt / 4;
rtd0 += a1 * rtd1 + a2 * rtd2 + a3 * rtd3 + a4 * rtd4;
rtd1 += a1 * rtd2 + a2 * rtd3 + a3 * rtd4;
rtd2 += a1 * rtd3 + a2 * rtd4;
rtd3 += a1 * rtd4;
}
void Sphere::correct(double dt, const Vector& G)
{
static Vector accel, corr;
double dtrez = 1 / dt;
const double coeff0 = double(19) / double(90) * (dt * dt / double(2));
const double coeff1 = double(3) / double(4) * (dt / double(2));
const double coeff3 = double(1) / double(2) * (double(3) * dtrez);
const double coeff4 = double(1) / double(12) * (double(12) * (dtrez * dtrez));
accel = Vector((1 / _m) * _force.x() + G.x(),
(1 / _m) * _force.y() + G.y(),
(1 / _J) * _force.phi() + G.phi());
corr = accel - rtd2;
rtd0 += coeff0 * corr;
rtd1 += coeff1 * corr;
rtd2 = accel;
rtd3 += coeff3 * corr;
rtd4 += coeff4 * corr;
}
double Sphere::kinetic_energy() const
{
return _m * (rtd1.x() * rtd1.x() / 2 + rtd1.y() * rtd1.y() / 2)
+ _J * rtd1.phi() * rtd1.phi() / 2;
}
// Container walls are built of particles that behave differently
void Sphere::boundary_conditions(double timestep, double Time)
{
switch (ptype())
{
// Normal particle that can move
case(0): break;
case(1): break; // Particle cannot move
case(2): {
x() = 0.5 - 0.4 * cos(10 * Time);
y() = 0.1;
vx() = 10 * 0.4 * sin(Time);
vy() = 0;
} break;
case(3): {
double xx = x() - 0.5;
double yy = y() - 0.5;
double xp = xx * cos(timestep) - yy * sin(timestep);
double yp = xx * sin(timestep) + yy * cos(timestep);
x() = 0.5 + xp;
y() = 0.5 + yp;
vx() = -yp;
vy() = xp;
omega() = 1;
} break;
//case(4): {
// x() = 0.5 + 0.1 * cos(Time) + 0.4 * cos(Time + 2 * n * 3.141 / 128);
// y() = 0.5 + 0.1 * sin(Time) + 0.4 * sin(Time + 2 * n * 3.141 / 128);
// vx() = -0.1 * sin(Time) - 0.4 * sin(Time + 2 * n * 3.141 / 128);
// vy() = 0.1 * cos(Time) - 0.4 * cos(Time + 2 * n * 3.141 / 128);
// omega() = 1;
//} break;
case(5): {
y() = 0.1 + 0.02 * sin(30 * Time);
vx() = 0;
vy() = 0.02 * 30 * cos(30 * Time);
} break;
//case(6): {
// int i = n / 2;
// y() = i * 0.02 + 0.1 + 0.02 * sin(30 * Time);
// vx() = 0;
// vy() = 0.02 * 30 * cos(30 * Time);
//} break;
default: {
std::cout << "\n" << *this << "\n";
std::cerr << "ptype: " << ptype() << " not implemented\n";
abort();
}
}
}
// Enforces the periodic boundary confitions.
// Places the particle at the position of its periodic image if it crossed the boundary
void Sphere::periodic_bc(double x_0, double y_0, double lx, double ly)
{
while (rtd0.x() < x_0) rtd0.x() += lx;
while (rtd0.x() > x_0 + lx) rtd0.x() -= lx;
while (rtd0.y() < y_0) rtd0.y() += ly;
while (rtd0.y() > y_0 + ly) rtd0.y() -= ly;
}
std::istream& operator>>(std::istream& is, Sphere& p)
{
is >> p.rtd0 >> p.rtd1
>> p._r >> p._m >> p._ptype
>> p.Y >> p.A >> p.mu >> p.gamma
>> p._force
>> p.rtd2 >> p.rtd3 >> p.rtd4;
p._J = p._m * p._r * p._r / 2;
return is;
}
std::ostream& operator<<(std::ostream& os, const Sphere& p)
{
os << p.rtd0 << " " << p.rtd1 << " ";
os << p._r << " " << p._m << " " << p._ptype << " ";
os << p.Y << " " << p.A << " " << p.mu << " " << p.gamma << " ";
os << p._force << " ";
os << p.rtd2 << " " << p.rtd3 << " " << p.rtd4 << "\n" << std::flush;
return os;
}
// Computes the force which is exerted by two spheres
void force(Sphere& p1, Sphere& p2, double lx, double ly)
{
double dx = normalize(p1.x() - p2.x(), lx);
double dy = normalize(p1.y() - p2.y(), ly);
double rr = sqrt(dx * dx + dy * dy);
double r1 = p1.r();
double r2 = p2.r();
double xi = r1 + r2 - rr;
if (xi > 0) {
double Y = p1.Y * p2.Y / (p1.Y + p2.Y);
double A = 0.5 * (p1.A + p2.A);
double mu = (p1.mu < p2.mu ? p1.mu : p2.mu);
double gamma = (p1.gamma < p2.gamma ? p1.gamma : p2.gamma);
double reff = (r1 * r2) / (r1 + r2);
double dvx = p1.vx() - p2.vx();
double dvy = p1.vy() - p2.vy();
double rr_rez = 1 / rr;
double ex = dx * rr_rez;
double ey = dy * rr_rez;
double xidot = -(ex * dvx + ey * dvy);
double vtrel = -dvx * ey + dvy * ex + p1.omega() * p1.r() - p2.omega() * p2.r();
double fn = std::sqrt(xi) * Y * sqrt(reff) * (xi + A * xidot);
double ft = -gamma * vtrel;
if (fn < 0) fn = 0;
if (ft < -mu * fn) ft = -mu * fn;
if (ft > mu * fn) ft = mu * fn;
if (p1.ptype() == 0) {
p1.add_force(Vector(fn * ex - ft * ey, fn * ey + ft * ex, r1 * ft));
}
if (p2.ptype() == 0) {
p2.add_force(Vector(-fn * ex + ft * ey, -fn * ey - ft * ex, -r2 * ft));
}
}
}
|
#include "hdivider_test.h"
void worker_func(void *a)
{
worker_args *args = (worker_args*)a;
HdividerWorker *hdivider = args->hdivider;
map<InputId, int > *input_data = args->input_data;
vector<int> *result = args->result;
while (!hdivider->isFinished())
{
vector<int64_t> ids = hdivider->getInput(312, "worker1");
for (int j = 0; j<ids.size(); j++)
{
map<int64_t, int >::iterator it = input_data->find(ids[j]);
if (it==input_data->end())
{
cout << "input_data[" << ids[j] << "] not found";
}
else
{
result->push_back(2*it->second);
hdivider->setHandled(ids[j]);
}
}
}
}
void HdividerTests::testOneWorker()
{
// multiply on 2 all inputs and write to result. 1 worker
int first_summ;
map<InputId, int > *input_data = new map<InputId, int > ;
vector<int> *result = new vector<int>;
first_summ = 0;
for (int i = 0; i<1000; i++)
{
input_data->insert(pair<InputId, int>(i , i));
first_summ += i;
}
HdividerWatcher* watcher = new HdividerWatcher(new HdividerTestInputIdIt (input_data), \
new HdividerTestStateAccessor());
worker_func((void*) (new worker_args(new HdividerTestWorker(watcher), input_data, result)));
TS_ASSERT(result->size() == 1000);
int summ = 0;
for (int i = 0; i<result->size(); i++)
{
summ += result->at(i);
}
TS_ASSERT(2*first_summ == summ);
}
|
#include <iostream>
#include <set>
#include <vector>
/**
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
*/
static std::set<std::uint32_t> CreatedPrimeNumbers = {2, 3, 5, 7};
void generatePrimeNumber(std::uint32_t targetNumber)
{
auto lastPrimeNumber = *std::prev(std::end(CreatedPrimeNumbers));
if (targetNumber <= lastPrimeNumber) {
return;
}
auto currentNumber = lastPrimeNumber + 1;
while (true) {
if (currentNumber > targetNumber) {
return;
}
bool isPrime = true;
for (auto primeNumber : CreatedPrimeNumbers) {
if (currentNumber % primeNumber == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
// found
CreatedPrimeNumbers.insert(currentNumber);
}
++currentNumber;
}
}
std::set<std::uint32_t> calculatePrimeFactor(std::uint32_t value)
{
if (CreatedPrimeNumbers.find(value) != std::end(CreatedPrimeNumbers)) {
return std::set<std::uint32_t>{value};
}
std::set<std::uint32_t> factors;
while (true) {
bool divided = false;
for (auto primeNumber : CreatedPrimeNumbers) {
if (value % primeNumber) {
factors.insert(primeNumber);
value = value / primeNumber;
divided = true;
break;
}
}
if (divided) {
continue;
}
return std::move(factors);
}
}
int main()
{
generatePrimeNumber(13195);
auto factors = calculatePrimeFactor(13195);
for (auto factor : factors) {
std::cout << factor << std::endl;
}
// std::cout << "hello" << std::endl;
// std::cout << "next : " << generatePrimeNumber(7) << std::endl;
return 0;
}
|
#pragma once
#include <utility>
#include <vector>
#include <string>
#include <landstalker-lib/tools/json.hpp>
#include "world_node.hpp"
class HintSource
{
private:
std::vector<uint16_t> _text_ids;
std::string _description;
WorldNode* _node = nullptr;
bool _small_textbox = false;
std::string _text;
std::vector<uint16_t> _map_ids;
Position _position;
uint8_t _orientation = 0;
bool _high_palette = false;
public:
HintSource(std::vector<uint16_t> text_ids, std::string description,
WorldNode* node, bool small_textbox,
std::vector<uint16_t> map_ids, Position position, uint8_t orientation, bool high_palette);
[[nodiscard]] const std::string& description() const { return _description; }
[[nodiscard]] WorldNode* node() const { return _node; }
[[nodiscard]] bool special() const { return _map_ids.empty(); }
[[nodiscard]] bool small_textbox() const { return _small_textbox; }
[[nodiscard]] std::string text() const;
void text(const std::string& text) { _text = text; }
void apply_text(World& world);
[[nodiscard]] const std::vector<uint16_t>& text_ids() const { return _text_ids; }
void text_id(uint16_t text_id) { _text_ids = { text_id }; }
void text_ids(const std::vector<uint16_t>& text_ids) { _text_ids = text_ids; }
[[nodiscard]] const std::vector<uint16_t>& map_ids() const { return _map_ids; }
[[nodiscard]] Position position() const { return _position; }
[[nodiscard]] uint8_t orientation() const { return _orientation; }
[[nodiscard]] bool high_palette() const { return _high_palette; }
[[nodiscard]] virtual Json to_json() const;
[[nodiscard]] static HintSource* from_json(const Json& json, const std::map<std::string, WorldNode*>& nodes);
};
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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 University of Oxford 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 MULTISTIMULUS_HPP_
#define MULTISTIMULUS_HPP_
#include <vector>
#include "ChasteSerialization.hpp"
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include "AbstractStimulusFunction.hpp"
/**
* This class provides a stimulus function which is the
* sum of an arbitrary number of stimuli.
*
* After creation it behaves like a ZeroStimulus until
* any number of stimuli are added.
*/
class MultiStimulus : public AbstractStimulusFunction
{
private:
/** Needed for serialization. */
friend class boost::serialization::access;
/**
* Archive the simple stimulus, never used directly - boost uses this.
*
* @param archive
* @param version
*/
template<class Archive>
void serialize(Archive & archive, const unsigned int version)
{
// This calls serialize on the base class.
archive & boost::serialization::base_object<AbstractStimulusFunction>(*this);
archive & mStimuli;
}
protected:
/** Vector of stimuli. */
std::vector<boost::shared_ptr<AbstractStimulusFunction> > mStimuli;
public:
/**
* Destructor - just calls #Clear().
*/
~MultiStimulus();
/**
* Combine a stimulus with the existing ones.
*
* @param pStimulus pointer to the stimulus to be added.
*/
void AddStimulus(boost::shared_ptr<AbstractStimulusFunction> pStimulus);
/**
* Get the magnitude of the multiple stimuli at time 'time'
*
* @param time time at which to return the stimulus
* @return Magnitude of stimulus at time 'time'.
*/
virtual double GetStimulus(double time);
/**
* Clear is responsible for managing the memory of
* delegated stimuli
*/
void Clear();
};
#include "SerializationExportWrapper.hpp"
// Declare identifier for the serializer
CHASTE_CLASS_EXPORT(MultiStimulus)
#endif /*MULTISTIMULUS_HPP_*/
|
#include "physics\Singularity.Physics.h"
namespace Singularity
{
namespace Physics
{
class BooleanCollider : public Collider
{
public:
#pragma region Variables
bool IsPositiveSpace;
BooleanCollider* Container;
#pragma endregion
protected:
#pragma region Methods
bool TestCollision(Collider* collider, CollisionInfo* collisionInfo);
virtual void OnCollisionEnter(CollisionInfo collision) = 0;
virtual void OnCollisionExit(CollisionInfo collision) = 0;
virtual void OnCollisionStay(CollisionInfo collision) = 0;
#pragma endregion
public:
#pragma region Constructors and Finalizers
BooleanCollider(String name, bool isPositiveSpace) : Collider(name), IsPositiveSpace(isPositiveSpace) {}
~BooleanCollider() {}
#pragma endregion
};
}
}
|
#include <stdio.h>
#include <algorithm>
using namespace std;
int russia[100];
int korea[100];
int n;
int main()
{
int c;
scanf("%d",&c);
while(c--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&russia[i]);
for(int i=0;i<n;i++)
scanf("%d",&korea[i]);
sort(russia,russia+n);
sort(korea,korea+n);
int ret = 0;
int j = 0;
for(int i=0;i<n;i++)
{
if(russia[j] <= korea[i])
{
ret+=1;
j+=1;
}
}
printf("%d\n",ret);
}
}
|
// input channel angle from remote
long roll, pitch, throttle, yaw, AUX1;
//This function will return a mapping value(in range out_min-out_min) for the input x(in range in_min-in_max)
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
return (x - in_min)* (out_max - out_min)/(in_max - in_min)+out_min;
}
void read_input(){
uint16_t inputs[8]; // store value of 8 input channels
//Read RC(radio code) singals from 8 input channels and store in inputs array
hal.rcin->read(inputs, 8);
roll = map(inputs[3], 1050, 1840, -45, 45);
pitch = map(inputs[1], 1110, 1860, -45, 45);
throttle = map(inputs[2], 1130, 1880, 1000, 1800); //2000 is the maximum of throttle, set a lower value to remain some room for PID controls
yaw = map(inputs[0], 1150, 1880, -180, 180);
AUX1 = inputs[4];
// hal.console->printf_P(PSTR("remote input 5 is %d\r\n"),inputs[4]);
//fixing small errors of signals from remote controller
if(abs(roll)<=5)
roll = 0;
if(abs(pitch)<=5)
pitch = 0;
if(abs(yaw)<=5)
yaw = 0;
}
|
#include "Zombie.h"
#include <QGraphicsScene>
#include <QList>
#include "Plant.h"
#include "Nut.h"
#include "CherryBomb.h"
Zombie::Zombie(const int& pixPer40MiliSec , QTimer *timer
,const int lives , QGraphicsItem *parent , bool isLord )
: QObject () , QGraphicsPixmapItem (parent) ,
pixPer40MiliSec{pixPer40MiliSec} , lives{lives} , isLord{isLord}
{
xx=-1;
yy=-1;
gameOv=false;
Layer=0;
if(isLord==false){
//set picture
setPixmap(QPixmap(":/images/Layer 1.png"));}
if(isLord==true){
setPixmap(QPixmap(":/images/lord1.png"));}
//connect timer to moveToLeft
connect(timer , SIGNAL(timeout()) , this , SLOT(moveToLeft()));
//set zombie sound
zombieMusic = new QMediaPlayer();
zombieMusic->setMedia(QUrl("qrc:/music/Groan4.mp3"));
if(zombieMusic->state() == QMediaPlayer::PlayingState){
zombieMusic->setPosition(0);
}
else if(zombieMusic->state() == QMediaPlayer::StoppedState){
zombieMusic->play();
}
}
Zombie::~Zombie()
{
delete zombieMusic;
}
void Zombie::decrementLives()
{
if (lives != 0 ){ //decrement zombies lives
--lives;
}
//remove and delete if lives == 0
if(lives==0){
scene()->removeItem(this);
}
}
int Zombie::getLives()
{
return lives;
}
void Zombie::setLives(int lives)
{
this->lives = lives;
}
bool Zombie::getisLord()
{
return isLord;
}
int Zombie::getxx()
{
return xx;
}
int Zombie::getyy()
{
return yy;
}
void Zombie::moveToLeft()
{
//collect colliding items in the list
QList<QGraphicsItem *> collidingObjects = collidingItems();
//remove and delete collidingItem if it was a plant
for(size_t i{0} ; i<collidingObjects.size();++i){
//zombie natoone gilas va balut ro bokhore
if(typeid(*(collidingObjects)[i])!=typeid (Nut) && typeid(*(collidingObjects)[i])!=typeid (CherryBomb)){
Plant* plant = dynamic_cast<Plant*>(collidingObjects[i]);
if(plant){
scene()->removeItem(collidingObjects[i]);
this->xx=plant->x();
this->yy=plant->y();
delete collidingObjects[i];
plant->isDead =true;
QMediaPlayer* zombieBiteMusic = new QMediaPlayer();
zombieBiteMusic->setMedia(QUrl("qrc:/music/ZombieBite.mp3"));
if(zombieBiteMusic->state() == QMediaPlayer::PlayingState){
zombieBiteMusic->setPosition(0);
}
else if(zombieBiteMusic->state() == QMediaPlayer::StoppedState){
zombieBiteMusic->play();
}
}
}
}
setPos( x() - pixPer40MiliSec , y() );
if(isLord==false){
if(Layer%6==0){
setPos( x() - pixPer40MiliSec , y() );
setPixmap(QPixmap(":/images/Layer 1.png"));}
if(Layer%6==1){
setPos( x() - pixPer40MiliSec , y() );
setPixmap(QPixmap(":/images/Layer 2.png"));}
if(Layer%6==2){
setPos( x() - pixPer40MiliSec , y() );
setPixmap(QPixmap(":/images/Layer 3.png")); }
if(Layer%6==3){
setPos( x() - pixPer40MiliSec , y() );
setPixmap(QPixmap(":/images/Layer 4.png"));}
if(Layer%6==4){
setPos( x() - pixPer40MiliSec , y() );
setPixmap(QPixmap(":/images/Layer 5.png"));}
if(Layer%6==5){
setPos( x() - pixPer40MiliSec , y() );
setPixmap(QPixmap(":/images/Layer 6.png"));}
if( x() == 0 && lives!= 0){
gameOv=true;
}
Layer=Layer+1;
}
if(isLord==true){
if(Layer%7==0){
setPos( x() - pixPer40MiliSec , y());
setPixmap(QPixmap(":/images/lord1.png"));}
if(Layer%7==1){
setPos( x() - pixPer40MiliSec , y() );
setPixmap(QPixmap(":/images/lord2.png"));}
if(Layer%7==2){
setPos( x() - pixPer40MiliSec , y());
setPixmap(QPixmap(":/images/lord3.png")); }
if(Layer%7==3){
setPos( x() - pixPer40MiliSec , y() );
setPixmap(QPixmap(":/images/lord4.png"));}
if(Layer%7==4){
setPos( x() - pixPer40MiliSec , y() );
setPixmap(QPixmap(":/images/lord5.png"));}
if(Layer%7==5){
setPos( x() - pixPer40MiliSec , y());
setPixmap(QPixmap(":/images/lord6.png"));}
if(Layer%7==6){
setPos( x() - pixPer40MiliSec , y() );
setPixmap(QPixmap(":/images/lord7.png"));}
if( x() == 0 && lives!= 0){
gameOv=true;
}
Layer=Layer+1; }
}
|
#include <iostream>
using namespace std;
class point;
class anotherPoint //anotherPoint类定义
{
private:
double x;
double y;
public:
anotherPoint(double xx = 1, double yy = 1)
{
x = xx;
y = yy;
}
void print()
{
cout << "( " << x << " , " << y << " )";
}
friend class point;
};
class point
{
private:
int xPos;
int yPos;
public:
// explicit //如果在构造函数前加上explicit, 就不允许 point pt1 = 5这种隐式转换了
point(int x = 0, int y = 0)
{
xPos = x;
yPos = y;
}
point(anotherPoint aP) //构造函数,参数为anotherPoint类对象
{
xPos = aP.x; //由于point类是anotherPoint类的友元类,
yPos = aP.y; //因此这里可以访问anotherPoint的私有变量x和y
}
void print()
{
cout << "( " << xPos << " , " << yPos << " )" << endl;
}
};
int main()
{
//1. 将int类型数字5转换成point类型
point p1; //创建point类对象p1,采用带缺省参数的构造函数,即x=0、y=0
cout << 5 << " 转换成 ";
p1 = 5; //等价于p1=point(5,0);
p1.print(); //输出点p1的信息
//2. 将double类型变量dX转换成point类型
double dX = 1.2; //声明一个double变量dX
cout << dX << " 转换成 ";
p1 = dX; //等价于p1=point(int(dX),0)
p1.print(); //输出点p1的信息
//3. 将anotherPoint类型转换成point类型
anotherPoint p2(12.34, 56.78); //创建anotherPoint类的对象p2
p2.print();
cout << " 转换成 ";
p1 = p2; //等价于p1=point(p2);
p1.print(); //输出点p1的信息
//4. 测试在point构造函数前加上explicit以阻止隐性转换的情况
system("pause");
return 0;
}
/*
5 转换成 ( 5 , 0 )
1.2 转换成 ( 1 , 0 )
( 12.34 , 56.78 ) 转换成 ( 12 , 56 )
*/
|
// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "PerspectiveSample.h"
#include "MainMenu.h"
using namespace std;
using namespace ouzel;
PerspectiveSample::PerspectiveSample()
{
cursor.init(input::SystemCursor::CROSS);
sharedEngine->getInput()->setCursor(&cursor);
eventHandler.keyboardHandler = bind(&PerspectiveSample::handleKeyboard, this, placeholders::_1, placeholders::_2);
eventHandler.mouseHandler = bind(&PerspectiveSample::handleMouse, this, placeholders::_1, placeholders::_2);
eventHandler.touchHandler = bind(&PerspectiveSample::handleTouch, this, placeholders::_1, placeholders::_2);
eventHandler.gamepadHandler = bind(&PerspectiveSample::handleGamepad, this, placeholders::_1, placeholders::_2);
eventHandler.uiHandler = bind(&PerspectiveSample::handleUI, this, placeholders::_1, placeholders::_2);
sharedEngine->getEventDispatcher()->addEventHandler(&eventHandler);
sharedEngine->getRenderer()->setClearDepthBuffer(true);
camera.reset(new scene::Camera());
camera->setDepthTest(true);
camera->setDepthWrite(true);
camera->setType(scene::Camera::Type::PERSPECTIVE);
camera->setFarPlane(1000.0f);
camera->setPosition(Vector3(0.0f, 0.0f, -400.0f));
layer.reset(new scene::Layer());
layer->addChild(camera.get());
addLayer(layer.get());
// floor
floorSprite.reset(new scene::Sprite());
floorSprite->init("floor.jpg");
for (const scene::SpriteFrame& spriteFrame : floorSprite->getFrames())
{
spriteFrame.getTexture()->setMaxAnisotropy(4);
}
floor.reset(new scene::Node());
floor->addComponent(floorSprite.get());
layer->addChild(floor.get());
floor->setPosition(Vector2(0.0f, -50.0f));
floor->setRotation(Vector3(TAU_4, TAU / 8.0f, 0.0f));
// character
characterSprite.reset(new scene::Sprite());
characterSprite->init("run.json");
characterSprite->play(true);
for (const scene::SpriteFrame& spriteFrame : characterSprite->getFrames())
{
spriteFrame.getTexture()->setMaxAnisotropy(4);
}
character.reset(new scene::Node());
character->addComponent(characterSprite.get());
layer->addChild(character.get());
character->setPosition(Vector2(10.0f, 0.0f));
jumpSound.reset(new audio::Sound());
std::shared_ptr<ouzel::audio::SoundDataWave> soundData = std::make_shared<ouzel::audio::SoundDataWave>();
soundData->init("jump.wav");
jumpSound->init(soundData);
jumpSound->setPosition(character->getPosition());
rotate.reset(new scene::Rotate(10.0f, Vector3(0.0f, TAU, 0.0f)));
character->addComponent(rotate.get());
rotate->start();
guiCamera.reset(new scene::Camera());
guiCamera->setScaleMode(scene::Camera::ScaleMode::SHOW_ALL);
guiCamera->setTargetContentSize(Size2(800.0f, 600.0f));
guiLayer.reset(new scene::Layer());
guiLayer->addChild(guiCamera.get());
addLayer(guiLayer.get());
menu.reset(new gui::Menu());
guiLayer->addChild(menu.get());
backButton.reset(new ouzel::gui::Button("button.png", "button_selected.png", "button_down.png", "", "Back", "arial.fnt", Color::BLACK, Color::BLACK, Color::BLACK));
backButton->setPosition(Vector2(-200.0f, -200.0f));
menu->addWidget(backButton.get());
}
bool PerspectiveSample::handleUI(ouzel::Event::Type type, const ouzel::UIEvent& event)
{
if (type == Event::Type::CLICK_NODE)
{
if (event.node == backButton.get())
{
sharedEngine->getSceneManager()->setScene(std::unique_ptr<scene::Scene>(new MainMenu()));
}
}
return true;
}
bool PerspectiveSample::handleKeyboard(ouzel::Event::Type type, const ouzel::KeyboardEvent& event)
{
if (type == Event::Type::KEY_DOWN ||
type == Event::Type::KEY_REPEAT)
{
switch (event.key)
{
case input::KeyboardKey::UP:
cameraRotation.x() -= TAU / 100.0f;
break;
case input::KeyboardKey::DOWN:
cameraRotation.x() += TAU / 100.0f;
break;
case input::KeyboardKey::LEFT:
cameraRotation.y() -= TAU / 100.0f;
break;
case input::KeyboardKey::RIGHT:
cameraRotation.y() += TAU / 100.0f;
break;
case input::KeyboardKey::ESCAPE:
sharedEngine->getSceneManager()->setScene(std::unique_ptr<scene::Scene>(new MainMenu()));
return true;
case input::KeyboardKey::TAB:
jumpSound->play();
break;
case input::KeyboardKey::KEY_S:
sharedEngine->getRenderer()->saveScreenshot("test.png");
break;
default:
break;
}
if (cameraRotation.x() < -TAU / 6.0f) cameraRotation.x() = -TAU / 6.0f;
if (cameraRotation.x() > TAU / 6.0f) cameraRotation.x() = TAU / 6.0f;
camera->setRotation(cameraRotation);
sharedEngine->getAudio()->setListenerRotation(camera->getRotation());
}
return true;
}
bool PerspectiveSample::handleMouse(ouzel::Event::Type type, const ouzel::MouseEvent& event)
{
if (event.modifiers & LEFT_MOUSE_DOWN)
{
if (type == Event::Type::MOUSE_MOVE)
{
cameraRotation.x() += event.difference.y();
cameraRotation.y() -= event.difference.x();
if (cameraRotation.x() < -TAU / 6.0f) cameraRotation.x() = -TAU / 6.0f;
if (cameraRotation.x() > TAU / 6.0f) cameraRotation.x() = TAU / 6.0f;
camera->setRotation(cameraRotation);
}
}
return true;
}
bool PerspectiveSample::handleTouch(ouzel::Event::Type type, const ouzel::TouchEvent& event)
{
if (type == Event::Type::TOUCH_MOVE)
{
cameraRotation.x() += event.difference.y();
cameraRotation.y() -= event.difference.x();
if (cameraRotation.x() < -TAU / 6.0f) cameraRotation.x() = -TAU / 6.0f;
if (cameraRotation.x() > TAU / 6.0f) cameraRotation.x() = TAU / 6.0f;
camera->setRotation(cameraRotation);
}
return true;
}
bool PerspectiveSample::handleGamepad(Event::Type type, const GamepadEvent& event)
{
if (type == Event::Type::GAMEPAD_BUTTON_CHANGE)
{
if (event.pressed &&
event.button == input::GamepadButton::FACE2)
{
sharedEngine->getSceneManager()->setScene(std::unique_ptr<scene::Scene>(new MainMenu()));
}
}
return true;
}
|
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
void Print(BinaryTreeNode* pRoot)
{
if(pRoot==nullptr)
return ;
std::stack<BinaryTreeNode*> levels[2];
int current=0;
int next=1;
levels[current].push(pRoot);
while(!levels[0].empty()||!levels[1].empty())
{
BinaryTreeNode* pNode=levels[current].top();
levels[current].pop();
printf("%d",pNode->m_nValue);
if(current==0)
{
if(pNode->m_pLeft)
levels[next].push(pNode->m_pLeft);
if(pNode->m_pRight)
levels[next].push(pNode->m_pRight);
}else
{
if(pNode->m_pRight)
levels[next].push(pNode->m_pRight);
if(pNode->m_pLeft)
levels[next].push(pNode->m_pLeft);
}
if(levels[current].empty())
{
printf("\n");
current=1-current;
next=1-next;
}
}
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Phone.PersonalInformation.Provisioning.2.h"
WINRT_EXPORT namespace winrt {
namespace Windows::Phone::PersonalInformation::Provisioning {
struct ContactPartnerProvisioningManager
{
ContactPartnerProvisioningManager() = delete;
static Windows::Foundation::IAsyncAction AssociateNetworkAccountAsync(const Windows::Phone::PersonalInformation::ContactStore & store, hstring_view networkName, hstring_view networkAccountId);
static Windows::Foundation::IAsyncAction ImportVcardToSystemAsync(const Windows::Storage::Streams::IInputStream & stream);
static Windows::Foundation::IAsyncAction AssociateSocialNetworkAccountAsync(const Windows::Phone::PersonalInformation::ContactStore & store, hstring_view networkName, hstring_view networkAccountId);
};
struct MessagePartnerProvisioningManager
{
MessagePartnerProvisioningManager() = delete;
static Windows::Foundation::IAsyncAction ImportSmsToSystemAsync(bool incoming, bool read, hstring_view body, hstring_view sender, vector_view<hstring> recipients, const Windows::Foundation::DateTime & deliveryTime);
static Windows::Foundation::IAsyncAction ImportMmsToSystemAsync(bool incoming, bool read, hstring_view subject, hstring_view sender, vector_view<hstring> recipients, const Windows::Foundation::DateTime & deliveryTime, vector_view<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>> attachments);
};
}
}
|
#include "span/fibers/WorkerPool.hh"
#include "span/fibers/Fiber.hh"
#include "glog/logging.h"
namespace span {
namespace fibers {
WorkerPool::WorkerPool(size_t threads, bool useCaller, size_t batchSize)
: Scheduler(threads, useCaller, batchSize) {
start();
}
void WorkerPool::idle() {
while (true) {
if (Stopping()) {
return;
}
sema.wait();
try {
Fiber::yield();
} catch (...) {
return;
}
}
}
void WorkerPool::tickle() {
LOG(INFO) << this << " tickling";
sema.notify();
}
} // namespace fibers
} // namespace span
|
#include <immintrin.h>
#include <cstring>
#include <fcntl.h>
#include <immintrin.h>
#include <iostream>
#include <stdexcept>
#include <sys/mman.h>
#include <unistd.h>
#include "log.hpp"
#include "nontemporal.h"
#include "../utils/macros.hpp"
namespace mcsLog {
LogEntry::LogEntry(const char *entry) {
_value = entry;
_length = strlen(entry);
}
const char *LogEntry::getEntry() {
return _value;
}
int LogEntry::getEntryLength() {
return _length;
}
void Logger::preset() {
memset(_logfile_mmap_addr, '-', _logfile_size);
}
Logger::Logger(const char *path, long long size) {
_logfile_path = path;
// Sets _logfile_fd, _logfile_size, and _logfile_offset
recover(size);
_logfile_mmap_addr = mmap(NULL, _logfile_size, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_POPULATE, _logfile_fd, 0);
preset();
if (_logfile_mmap_addr == 0) {
throw std::runtime_error("Error: Could not mmap the logfile");
}
}
Logger::~Logger() {
munmap(_logfile_mmap_addr, _logfile_size);
close(_logfile_fd);
}
const char *Logger::getLogfilePath() {
return _logfile_path;
}
void Logger::recover(long long size) {
_logfile_fd = open(_logfile_path, O_RDWR, 0666);
if (_logfile_fd < 0) {
_logfile_offset = 0;
_logfile_fd = open(_logfile_path, O_RDWR | O_CREAT, 0666);
if (_logfile_fd < 0) {
std::cout << _logfile_path << std::endl;
throw std::runtime_error("Error: Could not open the logfile ");
}
// TODO: Make this environment independent?
int falloc_ret = posix_fallocate(_logfile_fd, 0, size);
if (falloc_ret < 0)
throw std::runtime_error("Error: Could not allocate space for the logfile");
_logfile_size = size;
}
else {
_logfile_offset = 0;
_logfile_size = size;
// TODO: Implement recovery on the existing logfile
// For now, rewriting the logfile - setting the offset to 0
throw std::runtime_error("Error: Recovery is not implemented");
}
}
void *Logger::Write(const char *value, int length) {
for (auto iter = 0; iter < ITERATIONS; iter++) {
// TODO: If write_offset is beyond resize_threshold, extend the file size
std::memcpy((void *)((unsigned long)_logfile_mmap_addr + _logfile_offset), value, length);
for (auto cl = 0; cl < length; cl += CLFLUSH_SIZE) {
_mm_clwb((unsigned long)_logfile_mmap_addr + _logfile_offset + cl);
}
_mm_sfence();
// std::memset((void *)((unsigned long)_logfile_mmap_addr + _logfile_offset), 'A', length);
_logfile_offset += length;
}
}
void *Logger::WriteNT(const char *value, int length) {
for (auto iter = 0; iter < ITERATIONS; iter++) {
MOVNT((void *)((unsigned long)_logfile_mmap_addr + _logfile_offset), value, length);
_mm_sfence();
_logfile_offset += length;
}
}
} // namespace mcsLog
|
#ifndef CAMERA_H
#define CAMERA_H
#include "gfp.h"
#include "utility.h"
#include <vector>
using namespace std;
// header file CAMERA.H for class camera
class Camera
{
public:
void setCamera(
float eyex, float eyey, float eyez,
float lookx, float looky, float lookz,
float upx, float upy, float upz);
void roll(float angle);
void pitch(float angle);
void yaw(float angle);
void slide(float delU, float delV, float delN);
GLfloatPoint getEye(void);
private:
vector<GLfloatPoint> eyeLookUp;
vector<GLfloatPoint> nuv;
double viewAngle, aspect, near, far;
void setModelViewMatrix(void);
GLfloatPoint crossProduct(GLfloatPoint a, GLfloatPoint b);
GLfloatPoint normalize(GLfloatPoint a);
GLfloat dotProduct(GLfloatPoint a, GLfloatPoint b);
};
#endif //BEZIER_H
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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 University of Oxford 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 TESTNUMERICALMETHODS_HPP_
#define TESTNUMERICALMETHODS_HPP_
#include <cxxtest/TestSuite.h>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include "CellsGenerator.hpp"
#include "FixedG1GenerationalCellCycleModel.hpp"
#include "MeshBasedCellPopulation.hpp"
#include "MeshBasedCellPopulationWithGhostNodes.hpp"
#include "VertexBasedCellPopulation.hpp"
#include "NodeBasedCellPopulationWithParticles.hpp"
#include "NodeBasedCellPopulationWithBuskeUpdate.hpp"
#include "GeneralisedLinearSpringForce.hpp"
#include "HoneycombMeshGenerator.hpp"
#include "HoneycombVertexMeshGenerator.hpp"
#include "AbstractCellBasedTestSuite.hpp"
#include "ArchiveOpener.hpp"
#include "ApcOneHitCellMutationState.hpp"
#include "ApcTwoHitCellMutationState.hpp"
#include "BetaCateninOneHitCellMutationState.hpp"
#include "WildTypeCellMutationState.hpp"
#include "CellLabel.hpp"
#include "CellAncestor.hpp"
#include "CellId.hpp"
#include "CellPropertyRegistry.hpp"
#include "SmartPointers.hpp"
#include "FileComparison.hpp"
#include "PopulationTestingForce.hpp"
#include "PlaneBoundaryCondition.hpp"
#include "ForwardEulerNumericalMethod.hpp"
#include "Warnings.hpp"
#include "PetscSetupAndFinalize.hpp"
class TestNumericalMethods : public AbstractCellBasedTestSuite
{
public:
void TestMethodsAndExceptions()
{
EXIT_IF_PARALLEL; // HoneycombMeshGenerator doesn't work in parallel.
{
unsigned cells_across = 7;
unsigned cells_up = 5;
HoneycombMeshGenerator generator(cells_across, cells_up, 0);
MutableMesh<2,2>* p_mesh = generator.GetMesh();
// Create cells
std::vector<CellPtr> cells;
CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator;
cells_generator.GenerateBasic(cells, p_mesh->GetNumNodes());
// Create cell population
MeshBasedCellPopulation<2> cell_population(*p_mesh, cells);
// Create a force collection
std::vector<boost::shared_ptr<AbstractForce<2,2> > > force_collection;
MAKE_PTR(PopulationTestingForce<2>, p_test_force);
force_collection.push_back(p_test_force);
// Create Numerical method
ForwardEulerNumericalMethod<2> numerical_method;
numerical_method.SetCellPopulation(&cell_population);
numerical_method.SetForceCollection(&force_collection);
numerical_method.SetUseAdaptiveTimestep(true);
std::vector<c_vector<double, 2> > saved_locations;
saved_locations = numerical_method.SaveCurrentLocations();
TS_ASSERT_EQUALS(saved_locations.size(), cell_population.GetNumRealCells());
}
// This tests the exceptions for Node based with Buske Update
{
// Create a simple mesh
TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/square_4_elements");
MutableMesh<2,2> generating_mesh;
generating_mesh.ConstructFromMeshReader(mesh_reader);
// Convert this to a NodesOnlyMesh
NodesOnlyMesh<2> mesh;
mesh.ConstructNodesWithoutMesh(generating_mesh, 1.2);
std::vector<CellPtr> cells;
CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator;
cells_generator.GenerateBasic(cells, mesh.GetNumNodes());
// Create a cell population, with no ghost nodes at the moment
NodeBasedCellPopulationWithBuskeUpdate<2> cell_population(mesh, cells);
// Create Numerical method
ForwardEulerNumericalMethod<2> numerical_method;
numerical_method.SetCellPopulation(&cell_population);
TS_ASSERT_EQUALS(Warnings::Instance()->GetNumWarnings(), 1u);
TS_ASSERT_EQUALS(Warnings::Instance()->GetNextWarningMessage(), "Non-Euler steppers are not yet implemented for NodeBasedCellPopulationWithBuskeUpdate");
Warnings::QuietDestroy();
}
}
void TestApplyingBoundaryConditions()
{
EXIT_IF_PARALLEL; // HoneycombMeshGenerator doesn't work in parallel.
unsigned cells_across = 7;
unsigned cells_up = 5;
HoneycombMeshGenerator generator(cells_across, cells_up, 0);
MutableMesh<2,2>* p_mesh = generator.GetMesh();
// Create cells
std::vector<CellPtr> cells;
CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator;
cells_generator.GenerateBasic(cells, p_mesh->GetNumNodes());
// Create cell population
MeshBasedCellPopulation<2> cell_population(*p_mesh, cells);
// Create a force collection
std::vector<boost::shared_ptr<AbstractForce<2,2> > > force_collection;
MAKE_PTR(PopulationTestingForce<2>, p_test_force);
force_collection.push_back(p_test_force);
// Create a Boundary condition collection
std::vector<boost::shared_ptr<AbstractCellPopulationBoundaryCondition<2,2> > > boundary_condition_collection;
c_vector<double,2> point = zero_vector<double>(2);
point(1) = 0.5;
c_vector<double,2> normal = zero_vector<double>(2);
normal(1) = -1.0;
MAKE_PTR_ARGS(PlaneBoundaryCondition<2>, p_test_bcs, (&cell_population, point, normal)); // y>0.5
boundary_condition_collection.push_back(p_test_bcs);
// Create Numerical method
ForwardEulerNumericalMethod<2> numerical_method;
numerical_method.SetCellPopulation(&cell_population);
numerical_method.SetForceCollection(&force_collection);
numerical_method.SetUseAdaptiveTimestep(true);
numerical_method.SetBoundaryConditions(&boundary_condition_collection);
std::map<Node<2>*, c_vector<double, 2> > saved_locations;
saved_locations = numerical_method.SaveCurrentNodeLocations();
TS_ASSERT_EQUALS(saved_locations.size(), cell_population.GetNumRealCells());
numerical_method.ImposeBoundaryConditions(saved_locations);
std::map<Node<2>*, c_vector<double, 2> > new_locations;
new_locations = numerical_method.SaveCurrentNodeLocations();
TS_ASSERT_EQUALS(new_locations.size(), saved_locations.size());
// Check the bcs has been imposed
for (unsigned node_index=0; node_index<p_mesh->GetNumNodes(); node_index++)
{
TS_ASSERT_DELTA(new_locations[cell_population.GetNode(node_index)](0), saved_locations[cell_population.GetNode(node_index)](0), 1e-3);
if (node_index<7) // These nodes moved by BCS
{
TS_ASSERT_DELTA(new_locations[cell_population.GetNode(node_index)](1), 0.5, 1e-3);
}
else
{
TS_ASSERT_DELTA(new_locations[cell_population.GetNode(node_index)](1), saved_locations[cell_population.GetNode(node_index)](1), 1e-3);
}
}
}
void TestUpdateAllNodePositionsWithMeshBased()
{
// Create a simple mesh
TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/square_4_elements");
MutableMesh<2,2> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
// Create cells
std::vector<CellPtr> cells;
CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator;
cells_generator.GenerateBasic(cells, mesh.GetNumNodes());
// Create a cell population, with no ghost nodes at the moment
MeshBasedCellPopulation<2> cell_population(mesh, cells);
cell_population.SetDampingConstantNormal(1.1);
// Create a force collection
std::vector<boost::shared_ptr<AbstractForce<2,2> > > force_collection;
MAKE_PTR(PopulationTestingForce<2>, p_test_force);
force_collection.push_back(p_test_force);
// Create numerical method for testing
MAKE_PTR(ForwardEulerNumericalMethod<2>, p_fe_method);
double dt = 0.01;
p_fe_method->SetCellPopulation(&cell_population);
p_fe_method->SetForceCollection(&force_collection);
// Save starting positions
std::vector<c_vector<double, 2> > old_posns(cell_population.GetNumNodes());
for (unsigned j=0; j<cell_population.GetNumNodes(); j++)
{
old_posns[j][0] = cell_population.GetNode(j)->rGetLocation()[0];
old_posns[j][1] = cell_population.GetNode(j)->rGetLocation()[1];
}
// Update positions and check the answer
p_fe_method->UpdateAllNodePositions(dt);
for (unsigned j=0; j<cell_population.GetNumNodes(); j++)
{
c_vector<double, 2> actualLocation = cell_population.GetNode(j)->rGetLocation();
double damping = cell_population.GetDampingConstant(j);
c_vector<double, 2> expectedLocation;
expectedLocation = p_test_force->GetExpectedOneStepLocationFE(j, damping, old_posns[j], dt);
TS_ASSERT_DELTA(norm_2(actualLocation - expectedLocation), 0, 1e-6);
}
}
void TestUpdateAllNodePositionsWithMeshBasedWithGhosts()
{
EXIT_IF_PARALLEL; // HoneycombMeshGenerator doesn't work in parallel.
HoneycombMeshGenerator generator(3, 3, 1);
MutableMesh<2,2>* p_mesh = generator.GetMesh();
std::vector<unsigned> location_indices = generator.GetCellLocationIndices();
// Create cells
std::vector<CellPtr> cells;
CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator;
cells_generator.GenerateBasic(cells, location_indices.size());
MeshBasedCellPopulationWithGhostNodes<2> cell_population(*p_mesh, cells, location_indices);
cell_population.SetDampingConstantNormal(1.1);
// Create a force collection
std::vector<boost::shared_ptr<AbstractForce<2,2> > > force_collection;
MAKE_PTR(PopulationTestingForce<2>, p_test_force);
force_collection.push_back(p_test_force);
// Create numerical methods for testing
MAKE_PTR(ForwardEulerNumericalMethod<2>, p_fe_method);
double dt = 0.01;
p_fe_method->SetCellPopulation(&cell_population);
p_fe_method->SetForceCollection(&force_collection);
// Save starting positions
std::vector<c_vector<double, 2> > old_posns(cell_population.GetNumNodes());
for (unsigned j=0; j<cell_population.GetNumNodes(); j++)
{
old_posns[j][0] = cell_population.GetNode(j)->rGetLocation()[0];
old_posns[j][1] = cell_population.GetNode(j)->rGetLocation()[1];
}
// Update positions
p_fe_method->UpdateAllNodePositions(dt);
//Check the answer (for cell associated nodes only)
for (AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin();
cell_iter != cell_population.End();
++cell_iter)
{
int j = cell_population.GetLocationIndexUsingCell(*cell_iter);
c_vector<double, 2> actualLocation = cell_population.GetNode(j)->rGetLocation();
double damping = cell_population.GetDampingConstant(j);
c_vector<double, 2> expectedLocation;
expectedLocation = p_test_force->GetExpectedOneStepLocationFE(j, damping, old_posns[j], dt);
TS_ASSERT_DELTA(norm_2(actualLocation - expectedLocation), 0, 1e-9);
}
}
void TestUpdateAllNodePositionsWithNodeBased()
{
EXIT_IF_PARALLEL; // This test doesn't work in parallel.
HoneycombMeshGenerator generator(3, 3, 0);
TetrahedralMesh<2,2>* p_generating_mesh = generator.GetMesh();
// Convert this to a NodesOnlyMesh
MAKE_PTR(NodesOnlyMesh<2>, p_mesh);
p_mesh->ConstructNodesWithoutMesh(*p_generating_mesh, 2.0);
// Create cells
std::vector<CellPtr> cells;
CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator;
cells_generator.GenerateBasic(cells, p_mesh->GetNumNodes());
NodeBasedCellPopulation<2> cell_population(*p_mesh, cells);
cell_population.SetDampingConstantNormal(1.1);
// Create a force collection
std::vector<boost::shared_ptr<AbstractForce<2,2> > > force_collection;
MAKE_PTR(PopulationTestingForce<2>, p_test_force);
force_collection.push_back(p_test_force);
// Create numerical method for testing
MAKE_PTR(ForwardEulerNumericalMethod<2>, p_fe_method);
double dt = 0.01;
p_fe_method->SetCellPopulation(&cell_population);
p_fe_method->SetForceCollection(&force_collection);
// Save starting positions
std::vector<c_vector<double, 2> > old_posns(cell_population.GetNumNodes());
for (unsigned j=0; j<cell_population.GetNumNodes(); j++)
{
old_posns[j][0] = cell_population.GetNode(j)->rGetLocation()[0];
old_posns[j][1] = cell_population.GetNode(j)->rGetLocation()[1];
}
// Update positions and check the answer
p_fe_method->UpdateAllNodePositions(dt);
for (unsigned j=0; j<cell_population.GetNumNodes(); j++)
{
c_vector<double, 2> actualLocation = cell_population.GetNode(j)->rGetLocation();
double damping = cell_population.GetDampingConstant(j);
c_vector<double, 2> expectedLocation;
expectedLocation = p_test_force->GetExpectedOneStepLocationFE(j, damping, old_posns[j], dt);
TS_ASSERT_DELTA(norm_2(actualLocation - expectedLocation), 0, 1e-12);
}
}
void TestUpdateAllNodePositionsWithNodeBasedWithBuskeUpdate()
{
EXIT_IF_PARALLEL; // This test doesn't work in parallel.
HoneycombMeshGenerator generator(3, 3, 0);
TetrahedralMesh<2,2>* p_generating_mesh = generator.GetMesh();
// Convert this to a NodesOnlyMesh
MAKE_PTR(NodesOnlyMesh<2>, p_mesh);
p_mesh->ConstructNodesWithoutMesh(*p_generating_mesh, 2.0);
// Create cells
std::vector<CellPtr> cells;
CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator;
cells_generator.GenerateBasic(cells, p_mesh->GetNumNodes());
NodeBasedCellPopulationWithBuskeUpdate<2> cell_population(*p_mesh, cells);
cell_population.SetDampingConstantNormal(1.1);
// Create a force collection
std::vector<boost::shared_ptr<AbstractForce<2,2> > > force_collection;
MAKE_PTR(PopulationTestingForce<2>, p_test_force);
force_collection.push_back(p_test_force);
// Create numerical method for testing
MAKE_PTR(ForwardEulerNumericalMethod<2>, p_fe_method);
double dt = 0.01;
p_fe_method->SetCellPopulation(&cell_population);
p_fe_method->SetForceCollection(&force_collection);
// Save starting positions
std::vector<c_vector<double, 2> > old_posns(cell_population.GetNumNodes());
for (unsigned j=0; j<cell_population.GetNumNodes(); j++)
{
old_posns[j][0] = cell_population.GetNode(j)->rGetLocation()[0];
old_posns[j][1] = cell_population.GetNode(j)->rGetLocation()[1];
}
// Update positions and check the answer
// Currently this throws an error as not set up correctly as it is in a simulation #2087
TS_ASSERT_THROWS_THIS(p_fe_method->UpdateAllNodePositions(dt),"You must provide a rowPreallocation argument for a large sparse system");
// for (unsigned j=0; j<cell_population.GetNumNodes(); j++)
// {
// c_vector<double, 2> actualLocation = cell_population.GetNode(j)->rGetLocation();
// double damping = cell_population.GetDampingConstant(j);
// c_vector<double, 2> expectedLocation;
// expectedLocation = p_test_force->GetExpectedOneStepLocationFE(j, damping, old_posns[j], dt);
// TS_ASSERT_DELTA(norm_2(actualLocation - expectedLocation), 0, 1e-12);
// }
}
void TestUpdateAllNodePositionsWithNodeBasedWithParticles()
{
EXIT_IF_PARALLEL; // This test doesn't work in parallel.
HoneycombMeshGenerator generator(3, 3, 1);
TetrahedralMesh<2,2>* p_generating_mesh = generator.GetMesh();
// Convert this to a NodesOnlyMesh
MAKE_PTR(NodesOnlyMesh<2>, p_mesh);
p_mesh->ConstructNodesWithoutMesh(*p_generating_mesh, 2.0);
std::vector<unsigned> location_indices = generator.GetCellLocationIndices();
// Create cells
std::vector<CellPtr> cells;
CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator;
cells_generator.GenerateBasic(cells, location_indices.size());
NodeBasedCellPopulationWithParticles<2> cell_population(*p_mesh, cells, location_indices);
cell_population.SetDampingConstantNormal(1.1);
// Create a force collection
std::vector<boost::shared_ptr<AbstractForce<2,2> > > force_collection;
MAKE_PTR(PopulationTestingForce<2>, p_test_force);
force_collection.push_back(p_test_force);
// Create numerical method for testing
MAKE_PTR(ForwardEulerNumericalMethod<2>, p_fe_method);
double dt = 0.01;
p_fe_method->SetCellPopulation(&cell_population);
p_fe_method->SetForceCollection(&force_collection);
// Save starting positions
std::vector<c_vector<double, 2> > old_posns(cell_population.GetNumNodes());
for (unsigned j=0; j<cell_population.GetNumNodes(); j++)
{
old_posns[j][0] = cell_population.GetNode(j)->rGetLocation()[0];
old_posns[j][1] = cell_population.GetNode(j)->rGetLocation()[1];
}
// Update positions and check the answer
p_fe_method->UpdateAllNodePositions(dt);
for (unsigned j=0; j<cell_population.GetNumNodes(); j++)
{
c_vector<double, 2> actualLocation = cell_population.GetNode(j)->rGetLocation();
double damping = cell_population.GetDampingConstant(j);
c_vector<double, 2> expectedLocation;
expectedLocation = p_test_force->GetExpectedOneStepLocationFE(j, damping, old_posns[j], dt);
TS_ASSERT_DELTA(norm_2(actualLocation - expectedLocation), 0, 1e-12);
}
}
void TestUpdateAllNodePositionsWithVertexBased()
{
// Create a simple 2D VertexMesh
HoneycombVertexMeshGenerator generator(5, 3);
MutableVertexMesh<2,2>* p_mesh = generator.GetMesh();
// Impose a larger cell rearrangement threshold so that motion is uninhibited (see #1376)
p_mesh->SetCellRearrangementThreshold(0.1);
// Create cells
std::vector<CellPtr> cells;
CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator;
cells_generator.GenerateBasic(cells, p_mesh->GetNumElements());
// Create a cell population
VertexBasedCellPopulation<2> cell_population(*p_mesh, cells);
cell_population.SetDampingConstantNormal(1.1);
// Create a force collection
std::vector<boost::shared_ptr<AbstractForce<2,2> > > force_collection;
MAKE_PTR(PopulationTestingForce<2>, p_test_force);
force_collection.push_back(p_test_force);
// Create numerical methods for testing
MAKE_PTR(ForwardEulerNumericalMethod<2>, p_fe_method);
double dt = 0.01;
p_fe_method->SetCellPopulation(&cell_population);
p_fe_method->SetForceCollection(&force_collection);
// Save starting positions
std::vector<c_vector<double, 2> > old_posns(cell_population.GetNumNodes());
for (unsigned j=0; j<cell_population.GetNumNodes(); j++)
{
old_posns[j][0] = cell_population.GetNode(j)->rGetLocation()[0];
old_posns[j][1] = cell_population.GetNode(j)->rGetLocation()[1];
}
// Update positions and check the answer
p_fe_method->UpdateAllNodePositions(dt);
for (unsigned j=0; j<cell_population.GetNumNodes(); j++)
{
c_vector<double, 2> actualLocation = cell_population.GetNode(j)->rGetLocation();
double damping = cell_population.GetDampingConstant(j);
c_vector<double, 2> expectedLocation;
expectedLocation = p_test_force->GetExpectedOneStepLocationFE(j, damping, old_posns[j], dt);
TS_ASSERT_DELTA(norm_2(actualLocation - expectedLocation), 0, 1e-12);
}
}
void TestSettingAndGettingFlags()
{
// Create numerical methods for testing
MAKE_PTR(ForwardEulerNumericalMethod<2>, p_fe_method);
// mUseUpdateNodeLocation should default to false
TS_ASSERT(!(p_fe_method->GetUseUpdateNodeLocation()));
// Set mUseUpdateNodeLocation to true and check
p_fe_method->SetUseUpdateNodeLocation(true);
TS_ASSERT(p_fe_method->GetUseUpdateNodeLocation());
}
};
#endif /*TESTMESHBASEDCELLPOPULATION_HPP_*/
|
#pragma once
#define NULL 0
#include <string.h>
#include <malloc.h>
class String
{
public:
String::String(const char *cstr) {
init();
if (cstr)
copy(cstr, strlen(cstr));
}
String::String()
{
init();
}
String & String::copy(const char *cstr, unsigned int length) {
if (!reserve(length)) {
invalidate();
return *this;
}
len = length;
strcpy(buffer, cstr);
return *this;
}
#if test
String & String::copy(const __FlashStringHelper *pstr, unsigned int length) {
if (!reserve(length)) {
invalidate();
return *this;
}
len = length;
strcpy_P(buffer, (PGM_P)pstr);
return *this;
}
#endif
const char* c_str() const { return buffer; }
int String::compareTo(const String &s) const {
if (!buffer || !s.buffer) {
if (s.buffer && s.len > 0)
return 0 - *(unsigned char *)s.buffer;
if (buffer && len > 0)
return *(unsigned char *)buffer;
return 0;
}
return strcmp(buffer, s.buffer);
}
bool String::startsWith(const String &s) const
{
return strncmp(buffer, s.buffer, s.len) == 0;
}
int length() const
{
return len;
}
void toCharArray(char* pBuffer, int bufferSize) const
{
strncpy(pBuffer, buffer, bufferSize);
}
unsigned char String::concat(const char *cstr, unsigned int length) {
unsigned int newlen = len + length;
if (!cstr)
return 0;
if (length == 0)
return 1;
if (!reserve(newlen))
return 0;
strcpy(buffer + len, cstr);
len = newlen;
return 1;
}
unsigned char String::concat(const char *cstr) {
if (!cstr)
return 0;
return concat(cstr, strlen(cstr));
}
unsigned char String::concat(const String &rhs)
{
return concat(rhs.c_str());
}
char String::charAt(unsigned int loc) const {
return buffer[loc];
}
void String::setCharAt(unsigned int loc, char c) {
if (loc < len)
buffer[loc] = c;
}
String String::substring(unsigned int left, unsigned int right) const {
if (left > right) {
unsigned int temp = right;
right = left;
left = temp;
}
String out;
if (left >= len)
return out;
if (right > len)
right = len;
char temp = buffer[right]; // save the replaced character
buffer[right] = '\0';
out = buffer + left; // pointer arithmetic
buffer[right] = temp; //restore character
return out;
}
int String::indexOf(char c) const {
return indexOf(c, 0);
}
int String::indexOf(char ch, unsigned int fromIndex) const {
if (fromIndex >= len)
return -1;
const char* temp = strchr(buffer + fromIndex, ch);
if (temp == NULL)
return -1;
return temp - buffer;
}
long String::toInt(void) const {
if (buffer)
return atol(buffer);
return 0;
}
unsigned char operator ==(const char *cstr) const {
return equals(cstr);
}
unsigned char operator ==(const String &rhs) const {
return equals(rhs);
}
unsigned char String::equals(const String &s2) const {
return (len == s2.len && compareTo(s2) == 0);
}
unsigned char operator !=(const String &rhs) const {
return !equals(rhs);
}
unsigned char String::equals(const char *cstr) const {
if (len == 0)
return (cstr == NULL || *cstr == 0);
if (cstr == NULL)
return buffer[0] == 0;
return strcmp(buffer, cstr) == 0;
}
unsigned char String::operator<(const String &rhs) const {
return compareTo(rhs) < 0;
}
unsigned char String::operator>(const String &rhs) const {
return compareTo(rhs) > 0;
}
unsigned char String::operator<=(const String &rhs) const {
return compareTo(rhs) <= 0;
}
unsigned char String::operator>=(const String &rhs) const {
return compareTo(rhs) >= 0;
}
friend std::ostream& operator<<(std::ostream &os, const String &rhs) {
return os << rhs.buffer;
}
protected:
char *buffer; // the actual char array
unsigned int capacity; // the array length minus one (for the '\0')
unsigned int len; // the String length (not counting the '\0')
inline void String::init(void) {
buffer = NULL;
capacity = 0;
len = 0;
}
void String::invalidate(void) {
if (buffer)
free(buffer);
init();
}
unsigned char String::reserve(unsigned int size) {
if (buffer && capacity >= size)
return 1;
if (changeBuffer(size)) {
if (len == 0)
buffer[0] = 0;
return 1;
}
return 0;
}
unsigned char String::changeBuffer(unsigned int maxStrLen) {
size_t newSize = (maxStrLen + 16) & (~0xf);
char *newbuffer = (char *)realloc(buffer, newSize);
if (newbuffer) {
size_t oldSize = capacity + 1; // include NULL.
if (newSize > oldSize)
{
memset(newbuffer + oldSize, 0, newSize - oldSize);
}
capacity = newSize - 1;
buffer = newbuffer;
return 1;
}
return 0;
}
};
|
#include "mainwidget.h"
#include "types.h"
#include <QtWidgets/QApplication>
#include <QtDebug>
int main(int argc, char *argv[])
{
QApplication aplication(argc, argv);
MainWidget w;
w.show();
return aplication.exec();
}
|
// github.com/andy489
#include <stdio.h>
#define MAXREM 100
int main(){ int n,k,i,a,res(0);
int* r = new int[MAXREM];
scanf("%d%d",&n,&k);
for(i=0;i<n;++i){ scanf("%d",&a);
++r[a%k];
}
int end=(k+1)/2;
for(i=1;i<end;++i){
res+=(r[i]>r[k-i]?r[i]:r[k-i]);
}
if(r[0]) ++res;
if(!(k&1)&&r[k/2]) ++res;
printf("%d",res);
}
|
#include <vector>
#include "externals.h"
#include "typedValue.h"
#include "stack.h"
#include "word.h"
#include "context.h"
#include "mathMacro.h"
void ShowStack(Stack& inStack,const char *inStackName);
void InitDict_Control() {
Install(new Word("_branch-if-false",WORD_FUNC {
if(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }
TypedValue tos=Pop(inContext.DS);
if(tos.dataType!=kTypeBool) {
return inContext.Error_InvalidType(E_TOS_BOOL,tos);
}
if( tos.boolValue ) {
inContext.ip+=2; // Next
} else {
inContext.ip=(const Word**)(*(inContext.ip+1));
}
return true;
}));
Install(new Word("_branch-if-true",WORD_FUNC {
if(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }
TypedValue tos=Pop(inContext.DS);
if(tos.dataType!=kTypeBool) {
return inContext.Error_InvalidType(E_TOS_BOOL,tos);
}
if( tos.boolValue ) {
inContext.ip=(const Word**)(*(inContext.ip+1));
} else {
inContext.ip+=2; // Next
}
return true;
}));
Install(new Word("_absolute-jump",WORD_FUNC {
inContext.ip=(const Word**)(*(inContext.ip+1));
return true;
}));
Install(new Word("if",WordLevel::Immediate,WORD_FUNC {
inContext.BeginControlBlock(kSyntax_IF);
inContext.Compile(std::string("_branch-if-false"));
inContext.MarkAndCreateEmptySlot();
NEXT;
}));
Install(new Word("else",WordLevel::Immediate,WORD_FUNC {
if(inContext.CheckCompileMode()==false) {
return inContext.Error(E_SHOULD_BE_COMPILE_MODE);
}
if(inContext.SS.size()<1) { return inContext.Error(E_SS_BROKEN); }
TypedValue& tvSyntax=ReadTOS(inContext.SS);
if(tvSyntax.dataType!=kTypeMiscInt || tvSyntax.intValue!=kSyntax_IF) {
return inContext.Error(E_SYNTAX_MISMATCH_IF);
}
int p=inContext.GetEmptySlotPosition();
if(p<0) { return false; }
inContext.Compile(p,TypedValue(kTypeAddress,
inContext.GetNextThreadAddressOnCompile()+2));
inContext.Compile(std::string("_absolute-jump"));
inContext.MarkAndCreateEmptySlot();
NEXT;
}));
Install(new Word("then",WordLevel::Immediate,WORD_FUNC {
if(inContext.CheckCompileMode()==false) {
return inContext.Error(E_SHOULD_BE_COMPILE_MODE);
}
if(inContext.SS.size()<1) { return inContext.Error(E_SS_BROKEN); }
TypedValue& tvSyntax=ReadTOS(inContext.SS);
if(tvSyntax.dataType!=kTypeMiscInt || tvSyntax.intValue!=kSyntax_IF) {
return inContext.Error(E_SYNTAX_MISMATCH_IF);
}
int p=inContext.GetEmptySlotPosition();
if(p<0) { return inContext.Error(E_RS_BROKEN); }
inContext.Compile(p,TypedValue(kTypeAddress,
inContext.GetNextThreadAddressOnCompile()));
if(inContext.EndControlBlock()==false) {
return false;
}
NEXT;
}));
// equivalent: @r> +second/r> <=
Install(new Word("_repeat?+",WORD_FUNC {
const size_t n=inContext.RS.size();
if(n<2) { return inContext.Error(E_RS_BROKEN); }
TypedValue& rsTos=ReadTOS(inContext.RS);
if(rsTos.dataType!=kTypeInt
&& rsTos.dataType!=kTypeLong
&& rsTos.dataType!=kTypeBigInt) {
return inContext.Error_InvalidType(E_RS_TOS_INT_OR_LONG_OR_BIGINT,rsTos);
}
TypedValue& rsSecond=inContext.RS[n-2];
if(rsSecond.dataType!=kTypeInt
&& rsSecond.dataType!=kTypeLong
&& rsSecond.dataType!=kTypeBigInt) {
return inContext.Error_InvalidType(E_RS_SECOND_INT_OR_LONG_OR_BIGINT,
rsSecond);
}
bool result;
GetIntegerCmpOpResult_AndConvert(result,rsTos,<=,rsSecond);
inContext.DS.emplace_back(result);
NEXT;
}));
// equivalent: @r> +second/r> >=
Install(new Word("_repeat?-",WORD_FUNC {
const size_t n=inContext.RS.size();
if(n<2) { return inContext.Error(E_RS_BROKEN); }
TypedValue& rsTos=ReadTOS(inContext.RS);
if(rsTos.dataType!=kTypeInt
&& rsTos.dataType!=kTypeLong
&& rsTos.dataType!=kTypeBigInt) {
return inContext.Error_InvalidType(E_RS_TOS_INT_OR_LONG_OR_BIGINT,rsTos);
}
TypedValue& rsSecond=inContext.RS[n-2];
if(rsSecond.dataType!=kTypeInt
&& rsSecond.dataType!=kTypeLong
&& rsSecond.dataType!=kTypeBigInt) {
return inContext.Error_InvalidType(E_RS_SECOND_INT_OR_LONG_OR_BIGINT,
rsSecond);
}
bool result;
GetIntegerCmpOpResult_AndConvert(result,rsTos,>=,rsSecond);
inContext.DS.emplace_back(result);
NEXT;
}));
// equivalent: r> 1+ >r
Install(new Word("_inc-loop-counter",WORD_FUNC {
if(inContext.RS.size()<1) { return inContext.Error(E_RS_IS_EMPTY); }
TypedValue& tvCounter=ReadTOS(inContext.RS);
switch(tvCounter.dataType) {
case kTypeInt: tvCounter.intValue++; break;
case kTypeLong: tvCounter.longValue++; break;
case kTypeBigInt: (*tvCounter.bigIntPtr)++; break;
default:
return inContext.Error_InvalidType(E_RS_TOS_INT_OR_LONG_OR_BIGINT,
tvCounter);
}
NEXT;
}));
// equivalent: r> 1- >r
Install(new Word("_dec-loop-counter",WORD_FUNC {
if(inContext.RS.size()<1) { return inContext.Error(E_RS_IS_EMPTY); }
TypedValue& tvCounter=ReadTOS(inContext.RS);
switch(tvCounter.dataType) {
case kTypeInt: tvCounter.intValue--; break;
case kTypeLong: tvCounter.longValue--; break;
case kTypeBigInt: (*tvCounter.bigIntPtr)--; break;
default:
return inContext.Error_InvalidType(E_RS_TOS_INT_OR_LONG_OR_BIGINT,
tvCounter);
}
NEXT;
}));
// equivalent: drop-rs drop-rs
Install(new Word("_loop-epilogue",WORD_FUNC {
if(inContext.RS.size()<2) { return inContext.Error(E_RS_BROKEN); }
inContext.RS.pop_back();
inContext.RS.pop_back();
NEXT;
}));
Install(new Word("for+",WordLevel::Immediate,WORD_FUNC {
inContext.BeginControlBlock(kSyntax_FOR_PLUS);
inContext.Compile(std::string(">r")); // target value
inContext.Compile(std::string(">r")); // current value
inContext.MarkHere(); // come back here.
inContext.Compile(std::string("_repeat?+"));
inContext.Compile(std::string("_branch-if-false"));
inContext.MarkAndCreateEmptySlot(); // jump to _loop-epilogue
inContext.EnterLeavableLoop();
NEXT;
}));
Install(new Word("for-",WordLevel::Immediate,WORD_FUNC {
inContext.BeginControlBlock(kSyntax_FOR_MINUS);
inContext.Compile(std::string(">r")); // target value
inContext.Compile(std::string(">r")); // current value
inContext.MarkHere(); // come back here.
inContext.Compile(std::string("_repeat?-"));
inContext.Compile(std::string("_branch-if-false"));
inContext.MarkAndCreateEmptySlot(); // jump to _loop-epilogue
inContext.EnterLeavableLoop();
NEXT;
}));
Install(new Word("next",WordLevel::Immediate,WORD_FUNC {
if(inContext.CheckCompileMode()==false) {
return inContext.Error(E_SHOULD_BE_COMPILE_MODE);
}
TypedValue& tvSyntax=ReadTOS(inContext.SS);
if(tvSyntax.dataType!=kTypeMiscInt
|| (tvSyntax.intValue!=kSyntax_FOR_PLUS
&& tvSyntax.intValue!=kSyntax_FOR_MINUS)) {
return inContext.Error(E_SYNTAX_MISMATCH_FOR);
}
const int slotPosToExit=inContext.GetMarkPosition();
if(slotPosToExit<0) { return false; }
if(tvSyntax.intValue==kSyntax_FOR_PLUS) {
inContext.Compile(std::string("_inc-loop-counter"));
} else {
inContext.Compile(std::string("_dec-loop-counter"));
}
const int p=inContext.GetMarkPosition();
if(p<0) { return false; }
TypedValue tvAddrLoopTop(kTypeAddress,p);
inContext.Compile(std::string("_absolute-jump"));
inContext.Compile(tvAddrLoopTop);
inContext.ExitLeavableLoop();
TypedValue tvAddressToExit(kTypeAddress,
inContext.GetNextThreadAddressOnCompile());
inContext.Compile(slotPosToExit,tvAddressToExit);
inContext.Compile(std::string("_loop-epilogue"));
if(inContext.EndControlBlock()==false) { return false; }
NEXT;
}));
Install(new Word("leave",WordLevel::Immediate,WORD_FUNC {
if(inContext.CheckCompileMode()==false) {
return inContext.Error(E_SHOULD_BE_COMPILE_MODE);
}
inContext.Compile_Leave();
NEXT;
}));
Install(new Word("i",Dict["@r>"]->code));
// loopCounter+=TOS
// usage: n step
// equivalent: r> + 1- >R
Install(new Word("step",WordLevel::Immediate,WORD_FUNC {
if(inContext.SS.size()<1) { return inContext.Error(E_SS_BROKEN); }
TypedValue& tvSyntax=ReadTOS(inContext.SS);
if(tvSyntax.dataType!=kTypeMiscInt
|| (tvSyntax.intValue!=kSyntax_FOR_PLUS
&& tvSyntax.intValue!=kSyntax_FOR_MINUS)) {
return inContext.Error(E_SYNTAX_MISMATCH_FOR);
}
if(tvSyntax.intValue==kSyntax_FOR_PLUS) {
inContext.Compile(std::string("std:_step+"));
} else {
inContext.Compile(std::string("std:_step-"));
}
NEXT;
}));
// step for count up.
Install(new Word("_step+",WORD_FUNC {
if(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }
TypedValue tos=Pop(inContext.DS);
if(inContext.RS.size()<1) { return inContext.Error(E_RS_IS_EMPTY); }
TypedValue& tvCounter=ReadTOS(inContext.RS);
// tvCounter=tvCounter+tos-1
AssignOp(tvCounter,+,tos);
switch(tvCounter.dataType) {
case kTypeInt: tvCounter.intValue--; break;
case kTypeLong: tvCounter.longValue--; break;
case kTypeBigInt: (*tvCounter.bigIntPtr)--; break;
case kTypeFloat: tvCounter.floatValue--; break;
case kTypeDouble: tvCounter.doubleValue--; break;
case kTypeBigFloat: (*tvCounter.bigFloatPtr)--; break;
default:
inContext.Error(E_SYSTEM_ERROR);
exit(-1);
}
NEXT;
}));
// equivalent to "2 _step+"
Install(new Word("_step++",WORD_FUNC {
TypedValue& tvCounter=ReadTOS(inContext.RS);
switch(tvCounter.dataType) {
case kTypeInt: tvCounter.intValue++; break;
case kTypeLong: tvCounter.longValue++; break;
case kTypeBigInt: (*tvCounter.bigIntPtr)++; break;
case kTypeFloat: tvCounter.floatValue++; break;
case kTypeDouble: tvCounter.doubleValue++; break;
case kTypeBigFloat: (*tvCounter.bigFloatPtr)++; break;
default:
inContext.Error(E_SYSTEM_ERROR);
exit(-1);
}
NEXT;
}));
// step for count down.
Install(new Word("_step-",WORD_FUNC {
if(inContext.DS.size()<1) { return inContext.Error(E_DS_IS_EMPTY); }
TypedValue tos=Pop(inContext.DS);
if(inContext.RS.size()<1) { return inContext.Error(E_RS_IS_EMPTY); }
TypedValue& tvCounter=ReadTOS(inContext.RS);
// tvCounter=tvCounter+tos+1
AssignOp(tvCounter,+,tos);
switch(tvCounter.dataType) {
case kTypeInt: tvCounter.intValue++; break;
case kTypeLong: tvCounter.longValue++; break;
case kTypeBigInt: (*tvCounter.bigIntPtr)++; break;
case kTypeFloat: tvCounter.floatValue++; break;
case kTypeDouble: tvCounter.doubleValue++; break;
case kTypeBigFloat: (*tvCounter.bigFloatPtr)++; break;
default:
inContext.Error(E_SYSTEM_ERROR);
exit(-1);
}
NEXT;
}));
// while - repeat
// ex:
// input : 10 true while dup . 1 - dup 0 > repeat
// output: 10 9 8 7 6 5 4 3 2 1 ok.
Install(new Word("while",WordLevel::Immediate,WORD_FUNC {
inContext.BeginControlBlock(kSyntax_WHILE);
inContext.MarkHere(); // come back here.
inContext.Compile(std::string("_branch-if-false"));
inContext.MarkAndCreateEmptySlot(); // exit address slot
inContext.EnterLeavableLoop();
NEXT;
}));
Install(new Word("repeat",WordLevel::Immediate,WORD_FUNC {
if(inContext.CheckCompileMode()==false) {
return inContext.Error(E_SHOULD_BE_COMPILE_MODE);
}
if(inContext.RS.size()<3) { return inContext.Error(E_RS_NOT_ENOUGH); }
if(inContext.SS.size()<1) { return inContext.Error(E_SS_BROKEN); }
TypedValue& tvSyntax=ReadTOS(inContext.SS);
if(tvSyntax.dataType!=kTypeMiscInt
|| (tvSyntax.intValue!=kSyntax_WHILE
&& tvSyntax.intValue!=kSyntax_WHILE_COND)) {
return inContext.Error(E_SYNTAX_MISMATCH_WHILE);
}
if(tvSyntax.intValue==kSyntax_WHILE_COND) {
inContext.Compile(std::string("@r>exec"));
}
const int addrSlotToExit=inContext.GetEmptySlotPosition();
if(addrSlotToExit<0) { return false; }
const int jumpAddrToLoop=inContext.GetMarkPosition();
if(jumpAddrToLoop<0) { return false; }
inContext.Compile(std::string("_absolute-jump"));
inContext.Compile(TypedValue(kTypeAddress,jumpAddrToLoop));
TypedValue emptySlot=inContext.newWord->tmpParam->at(addrSlotToExit);
if(emptySlot.dataType!=kTypeEmptySlot) {
return inContext.Error(E_SYSTEM_ERROR);
}
inContext.Compile(addrSlotToExit,
TypedValue(kTypeAddress,
inContext.GetNextThreadAddressOnCompile()));
inContext.ExitLeavableLoop();
if(inContext.EndControlBlock()==false) { return false; }
NEXT;
}));
// for optimize
Install(new Word("_branchIfNotZero",WORD_FUNC {
if(inContext.DS.size()<1) { return inContext.Error(E_RS_IS_EMPTY); }
TypedValue& tos=inContext.DS.back();
if((tos.dataType==kTypeInt && tos.intValue!=0)
|| (tos.dataType==kTypeLong && tos.longValue!=0)
|| (tos.dataType==kTypeFloat && tos.floatValue!=0)
|| (tos.dataType==kTypeDouble && tos.doubleValue!=0)
|| (tos.dataType==kTypeBigInt && *tos.bigIntPtr!=0)
|| (tos.dataType==kTypeBigFloat && *tos.bigFloatPtr!=0)) {
// BRANCH!
inContext.ip=(const Word**)(*(inContext.ip+1));
} else {
inContext.ip+=2; // Next
}
inContext.DS.pop_back();
return true;
}));
// for optimize
// equivalent to "_repeat?+ branch-if-false"
Install(new Word("_branchWhenLoopEnded",WORD_FUNC {
const size_t n=inContext.RS.size();
if(n<2) { return inContext.Error(E_RS_BROKEN); }
TypedValue& rsTos=inContext.RS.back();
TypedValue& rsSecond=inContext.RS[n-2];
bool result;
GetIntegerCmpOpResult_AndConvert(result,rsTos,<=,rsSecond);
if( result ) {
inContext.ip+=2; // Next
} else {
inContext.ip=(const Word**)(*(inContext.ip+1));
}
return true;
}));
Alias("while{","{");
// equivalent to "} >r @r>exec while"
Install(new Word("}->",WordLevel::Level2,WORD_FUNC {
if(inContext.Exec(std::string("}"))==false) { return false; }
switch(inContext.ExecutionThreshold) {
case kInterpretLevel:
inContext.Exec(std::string(">r"));
inContext.Exec(std::string("@r>exec"));
inContext.Exec(std::string("while"));
break;
case kCompileLevel:
inContext.Compile(std::string(">r"));
inContext.Compile(std::string("@r>exec"));
inContext.Exec(std::string("while"));
break;
default: // kSymbolLevel or unknown case
inContext.Error(E_SYSTEM_ERROR);
exit(-1);
}
TypedValue& ssTos=ReadTOS(inContext.SS);
assert(ssTos.dataType==kTypeMiscInt && ssTos.intValue==kSyntax_WHILE);
ssTos.intValue=kSyntax_WHILE_COND;
NEXT;
}));
Install(new Word("do",WordLevel::Immediate,WORD_FUNC {
inContext.BeginControlBlock(kSyntax_DO);
inContext.MarkHere(); // come back here.
inContext.EnterLeavableLoop();
NEXT;
}));
Install(new Word("loop",WordLevel::Immediate,WORD_FUNC {
if(inContext.CheckCompileMode()==false) {
return inContext.Error(E_SHOULD_BE_COMPILE_MODE);
}
if(inContext.RS.size()<1) { return inContext.Error(E_RS_NOT_ENOUGH); }
if(inContext.SS.size()<1) { return inContext.Error(E_SS_BROKEN); }
TypedValue tvSyntax=ReadTOS(inContext.SS);
if(tvSyntax.dataType!=kTypeMiscInt || tvSyntax.intValue!=kSyntax_DO) {
return inContext.Error(E_SYNTAX_MISMATCH_DO);
}
const int jumpAddrToLoop=inContext.GetMarkPosition();
if(jumpAddrToLoop<0) { return false; }
inContext.Compile(std::string("_absolute-jump"));
inContext.Compile(TypedValue(kTypeAddress,jumpAddrToLoop));
inContext.ExitLeavableLoop();
if(inContext.EndControlBlock()==false) { return false; }
NEXT;
}));
Install(new Word("switch",WordLevel::Immediate,WORD_FUNC {
inContext.BeginControlBlock(kSyntax_SWITCH);
inContext.EnterSwitchBlock();
NEXT;
}));
Install(new Word("->",WordLevel::Immediate,WORD_FUNC {
if(inContext.CheckCompileMode()==false) {
return inContext.Error(E_SHOULD_BE_COMPILE_MODE);;
}
TypedValue& tvSyntax=ReadTOS(inContext.SS);
if(tvSyntax.dataType!=kTypeMiscInt && tvSyntax.intValue!=kSyntax_SWITCH) {
return inContext.Error(E_SYNTAX_MISMATCH_SWITCH);
}
inContext.Compile(std::string("_branch-if-false"));
inContext.MarkAndCreateEmptySlot();
inContext.Compile(std::string("drop"));
NEXT;
}));
Install(new Word("break",WordLevel::Immediate,WORD_FUNC {
if(inContext.CheckCompileMode()==false) {
return inContext.Error(E_SHOULD_BE_COMPILE_MODE);
}
if(inContext.RS.size()<1) { return inContext.Error(E_RS_BROKEN); }
TypedValue& tvSyntax=ReadTOS(inContext.SS);
if(tvSyntax.dataType!=kTypeMiscInt && tvSyntax.intValue!=kSyntax_SWITCH) {
return inContext.Error(E_SYNTAX_MISMATCH_SWITCH);
}
int p=inContext.GetEmptySlotPosition();
if(p<0) { return false; }
inContext.Compile_Break();
inContext.Compile(p,TypedValue(kTypeAddress,
inContext.GetNextThreadAddressOnCompile()));
NEXT;
}));
Install(new Word("case",Dict["dup"]->code));
Install(new Word("dispatch",WordLevel::Immediate,WORD_FUNC {
if(inContext.CheckCompileMode()==false) {
return inContext.Error(E_SHOULD_BE_COMPILE_MODE);
}
inContext.ExitSwitchBlock();
if(inContext.EndControlBlock()==false) { return false; }
NEXT;
}));
}
|
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
void drawdot(int count, int SCC_count, string names[], int SCC[], int edges[], int labelling[]);
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* AMateria.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: eyohn <sopka13@mail.ru> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/08 15:34:36 by eyohn #+# #+# */
/* Updated: 2021/07/08 20:17:34 by eyohn ### ########.fr */
/* */
/* ************************************************************************** */
#pragma once
#ifndef _AMATERIA_HPP_
#define _AMATERIA_HPP_
#include <iostream>
class AMateria;
#include "ICharacter.hpp"
class AMateria
{
protected:
std::string _type;
unsigned int _xp;
public:
AMateria();
AMateria(std::string const & type);
AMateria(const AMateria &other);
virtual ~AMateria();
AMateria &operator= (const AMateria &amateria);
std::string const & getType() const; //Returns the materia type
unsigned int getXP() const; //Returns the Materia's XP
virtual AMateria* clone() const = 0;
virtual void use(ICharacter& target);
};
#endif
|
#pragma once
#include <iostream>
#include <string>
#include <algorithm>
#include "University.h"
#include "Variables.h"
class FieldOfStudy;
class Faculty;
double maximum_advanced_science(Faculty x, double AdvancedMaturaResults[8]);
double maximum_advanced_language(Faculty x, double AdvancedMaturaResults[8]);
University EmptyUniversity;
class Faculty
{
public:
Faculty(std::string name = " ", int how_many = 0, int focus1= 0, int focus2 = 0, University& uni = EmptyUniversity)
{
name_of_faculty = name;
how_many_fields = how_many;
main_focus1 = focus1;
main_focus2 = focus2;
fields = nullptr;
father = uni;
}
~Faculty() {}
std::string name_of_faculty; //nazwa wydzialu
int how_many_fields; //ile kierunkow na tym wydziale
int main_focus1; //glowna rzecz na tym wydziale
int main_focus2; //glowna rzecz na tym wydziale nr 2
FieldOfStudy* fields;
University father;
int MaturasRate[8]; //tablica w ktorej jesli 0 to dana matura sie nie wlicza, a jak 1 to sie wlicza
void SetMaturasRate(int mathematics, int physics, int computer_science, int chemistry, int biology, int geography, int english, int other_language) //ciag 0 i 1 odpowiadajacy temu czy dana matura sie liczy czy nie
{
MaturasRate[0] = mathematics;
MaturasRate[1] = physics;
MaturasRate[2] = computer_science;
MaturasRate[3] = chemistry;
MaturasRate[4] = biology;
MaturasRate[5] = geography;
MaturasRate[6] = english;
MaturasRate[7] = other_language;
}
double student_score;
void CountStudentScoreUJ(double BasicMaturaResults[3], double AdvancedMaturaResults[8])
{
double language = std::max(BasicMaturaResults[2] / 2, maximum_advanced_language(*this, AdvancedMaturaResults));
double science = std::max(maximum_advanced_science(*this, AdvancedMaturaResults), BasicMaturaResults[0] / 2);
student_score = (2 * science + language)/300; // 3 * 100, bo progi na dostanie się na studia są w przedziale 0-1
}
void CountStudentScoreAGH(double BasicMaturaResults[3], double AdvancedMaturaResults[8])
{
double tmp = maximum_advanced_science(*this, AdvancedMaturaResults);
if (tmp >= 80) tmp += 100; //jesli z rozszerzenia było wiecej niż 80 pkt dodajemy do wyniku 100
else tmp = std::max(tmp + 2 * (tmp - 30),AdvancedMaturaResults[0] + BasicMaturaResults[0]); // dla wyniku z rozszerzenia mniejszego niż 80
double science = 4 * tmp;
double tmp2 = maximum_advanced_language(*this, AdvancedMaturaResults);
if (tmp2 >= 80) tmp2 += 100;
else tmp2 = std::max(tmp2 + 2 * (tmp2 - 30), AdvancedMaturaResults[6] + BasicMaturaResults[2]);
double language = tmp2;
student_score = (science + language)/ 1000;
}
void CountStudentScorePK(double BasicMaturaResults[3], double AdvancedMaturaResults[8])
{
double advanced = 2 * maximum_advanced_science(*this, AdvancedMaturaResults);
double basic = BasicMaturaResults[0];
if (basic > advanced) student_score = basic/200;
else student_score = advanced/200;
}
};
double maximum_advanced_language(Faculty x, double AdvancedMaturaResults[8])
{
if (AdvancedMaturaResults[6] < AdvancedMaturaResults[7])
return AdvancedMaturaResults[7];
else return AdvancedMaturaResults[6];
}
double maximum_advanced_science(Faculty x, double AdvancedMaturaResults[8])
{
double tabOfSubject[6];
for (int i = 0; i < 6; i++)
tabOfSubject[i] = AdvancedMaturaResults[i] * x.MaturasRate[i];
double max = -1000000;
for(int i = 0; i < 6; i++)
{
if (max < tabOfSubject[i])
max = tabOfSubject[i];
}
return max;
}
|
#include <iostream>
#include <conio.h>
#include <math.h>
using namespace std;
int rotation(int );
int result,rotatednum;
int main(){
int numb,numb2,numb3;
cout<<"\nInput any integer number ";
cin>>numb;
cout<<"\nThe rotated number is "<<rotation(numb);
cout<<"\nInput any integer number ";
cin>>numb2;
cout<<"\nThe rotated number is "<<rotation(numb2);
cout<<"\nInput any integer number ";
cin>>numb3;
cout<<"\nThe rotated number is "<<rotation(numb3);
getch();
return 0;
}
int rotation(int number){
int balance;
balance=number%10;
rotatednum=rotatednum*10+balance;
if ((number-balance)/10!=0) {
return rotation((number-balance)/10);
}
else {
result=rotatednum;
rotatednum=0;
return result;
}
}
|
#pragma once
#include "Graphics.h"
#include "Font.h"
#include "Vei2.h"
class Scorecounter
{
private:
int score = 0;
const Font& font;
Vei2 displayPos;
Color color;
public:
Scorecounter(const Font& font_in, const Vei2& displayPos_in, const Color color_in);
void add(const int points);
int get() const;
void display(Graphics& gfx) const;
};
|
#include "LatticeEngine.h"
#include <algorithm>
void LatticeEngine::step()
{
make_ilist();
integrate();
check_dump();
}
void LatticeEngine::make_ilist()
{
for (unsigned int i{ 0 }; i < particle.size(); i++) {
double x{ particle[i].x() }, y{ particle[i].y() };
if ((x >= x_0) && (x < x_0 + lx) && (y >= y_0) && (y < y_0 + ly)) {
int ix = int((x - x_0) / gk);
int iy = int((y - y_0) / gk);
pindex[ix][iy] = i;
partners[i].clear();
}
}
// for each particle i located at (ix, iy), the adjacent sites up to the distance
// +- gm are scanned for possible interaction partners and these particles are
// recorded in the vector partners[i].
for (unsigned int i{ 0 }; i < particle.size(); i++) {
double x{ particle[i].x() }, y{ particle[i].y() };
if ((x >= x_0) && (x < x_0 + lx) && (y >= y_0) && (y < y_0 + ly)) {
int ix = int((x - x_0) / gk);
int iy = int((y - y_0) / gk);
for (int dx{ -gm }; dx < gm; dx++) {
for (int dy{ -gm }; dy < gm; dy++) {
int i0 = (ix + dx + nx) % nx;
int i1 = (iy + dy + ny) % ny;
int k = pindex[i0][i1];
if (k > (int)i) {
partners[i].push_back(k);
}
}
}
}
}
clear_pindex();
}
void LatticeEngine::clear_pindex()
{
std::for_each(pindex.begin(), pindex.end(), [](auto& vec) {std::fill(vec.begin(), vec.end(), -1); });
}
void LatticeEngine::init_algorithm()
{
rmin = particle[0].r();
rmax = particle[0].r();
for (unsigned int i = 1; i < particle.size(); i++) {
if (particle[i].r() < rmin) {
rmin = particle[i].r();
}
if (particle[i].r() > rmax) {
rmax = particle[i].r();
}
}
gk = sqrt(2) * rmin;
gm = int(2 * rmax / gk) + 1;
nx = int(lx / gk) + 1;
ny = int(ly / gk) + 1;
partners.resize(no_of_particles);
pindex.resize(nx);
for (unsigned int ix{ 0 }; ix < pindex.size(); ix++) {
pindex[ix].resize(ny);
}
clear_pindex();
make_ilist();
}
void LatticeEngine::make_forces()
{
for (unsigned int i{ 0 }; i < no_of_particles; i++) {
for (unsigned int k{ 0 }; k < partners[i].size(); k++) {
int pk = partners[i][k];
force(particle[i], particle[pk], lx, ly);
}
}
}
|
#ifndef CLEXICON_H
#define CLEXICON_H
#include <QMap>
#include <QMapIterator>
#include <QString>
#include <QList>
#include <QPair>
#include <QSet>
#include <QStatusBar>
#include "SignatureCollection.h"
#include "Typedefs.h"
class MainWindow;
class CWordCollection;
class CStemCollection;
class CSuffixCollection;
class CPrefixCollection;
class QProgressBar;
class CHypothesis;
// part of an experiment:
class Collection
{
eComponentType m_component_type;
public:
Collection(eComponentType this_type) {m_component_type = this_type;}
QString get_output();
};
// end of experiment
//-----------------------------------------------------------------------//
class simple_sig_graph_edge{
//-----------------------------------------------------------------------//
public:
CSignature* m_sig_1;
CSignature* m_sig_2;
CLexicon * m_Lexicon;
sig_string m_sig_string_1;
sig_string m_sig_string_2;
double m_sig_1_entropy = -1;
double m_sig_2_entropy = -1;
morph_t morph;
word_t word;
stem_t stem_1;
stem_t stem_2;
simple_sig_graph_edge();
simple_sig_graph_edge(CLexicon* lexicon, CSignature* pSig1, CSignature* pSig2, sigstring_t sig_string_1, sigstring_t sig_string_2,morph_t m,word_t w, stem_t stem1, stem_t stem2)
{
m_sig_1 = pSig1;
m_sig_2 = pSig2;
m_Lexicon = lexicon;
m_sig_string_1 = sig_string_1;
m_sig_string_2 = sig_string_2;
morph = m;
word = w;
stem_1 = stem1;
stem_2 = stem2;
};
QString label() {return morph + "/" + m_sig_string_1 + "/" + m_sig_string_2; }
};
//-----------------------------------------------------------------------//
//-----------------------------------------------------------------------//
class sig_graph_edge{
//-----------------------------------------------------------------------//
public:
CSignature* m_sig_1;
CSignature* m_sig_2;
CLexicon* m_lexicon;
sig_string m_sig_string_1;
sig_string m_sig_string_2;
double m_sig_1_entropy = -1;
double m_sig_2_entropy = -1;
morph_t morph;
QMap<QString, word_stem_struct*> shared_word_stems;
sig_graph_edge();
sig_graph_edge(simple_sig_graph_edge this_edge){
m_lexicon = this_edge.m_Lexicon;
m_sig_1 = this_edge.m_sig_1;
m_sig_2 = this_edge.m_sig_2;
m_sig_string_1 = this_edge.m_sig_string_1;
m_sig_string_2 = this_edge.m_sig_string_2;
m_sig_1_entropy = this_edge.m_sig_1_entropy;
m_sig_2_entropy = this_edge.m_sig_2_entropy;
morph = this_edge.morph;
word_stem_struct * this_word_stems = new word_stem_struct;
this_word_stems->word = this_edge.word;
this_word_stems->stem_1 = this_edge.stem_1;
this_word_stems->stem_2 = this_edge.stem_2;
shared_word_stems[this_word_stems->get_label()] = this_word_stems;
}
QString label() {return morph + "/" + m_sig_string_1 + "/" + m_sig_string_2; }
int get_number_of_words() {return shared_word_stems.size();}
CSignature* get_sig_1() {return m_sig_1;}
CSignature* get_sig_2() {return m_sig_2;}
sig_string get_sig1_string() { return m_sig_string_1;}
sig_string get_sig2_string() { return m_sig_string_2;}
morph_t get_morph() {return morph;}
};
//-----------------------------------------------------------------------//
class protostem{
//-----------------------------------------------------------------------//
QString m_protostem;
int m_start_word;
int m_end_word;
public:
protostem(QString stem, int start_word, int end_word=-1) { m_protostem = stem; m_start_word = start_word; m_end_word = end_word;}
QString get_stem() { return m_protostem;}
int get_start_word() { return m_start_word;}
int get_end_word() {return m_end_word;}
};
//-----------------------------------------------------------------------//
class CLexicon
//-----------------------------------------------------------------------//
{
protected:
// this is part of an experiment.
QMap<QString,eComponentType> m_category_types; // part of the experiment. It serves
// as the principal way in which the Lexicon communicates
// with the GUI as far as architecture is concerned.
// Each entry in this must have a pointer to a real Collection (of the sort that follows here):
MainWindow* m_main_window;
CWordCollection * m_Words;
CStemCollection * m_suffixal_stems;
CStemCollection * m_prefixal_stems;
CSuffixCollection * m_Suffixes;
CPrefixCollection * m_Prefixes;
CSignatureCollection * m_Signatures;
CSignatureCollection * m_PrefixSignatures;
CWordCollection * m_Compounds;
QList<QPair<QString,QString>> * m_Parses;
QMap<QString,int> m_Parse_map;
// QMap<QString, int> m_suffix_protostems;
QMap<QString, int> m_prefix_protostems;
// m_protostems_2 is used in order to keep track of exactly which interval of words in the word list begins
// with a particular proto-stem (i.e., a word-beginning). This replaces using a huge signature to store
// that same information.
QMap<QString, protostem*> m_suffix_protostems_2;
QMap<QString, protostem*> m_prefix_protostems_2;
bool m_SuffixesFlag;
CLexicon* m_parent_lexicon;
CSignatureCollection* m_ParaSignatures; /*!< the information we have about stems which we have not yet integrated into a morphological system. */
CSuffixCollection * m_ParaSuffixes;
CStemCollection * m_ResidualStems;
CSignatureCollection * m_ResidualPrefixSignatures;
CStemCollection * m_StemsFromSubsignatures;
CSignatureCollection* m_Subsignatures;
QList<simple_sig_graph_edge*> m_SigGraphEdgeList; /*!< the sig_graph_edges in here contain only one word associated with each. */
lxa_sig_graph_edge_map m_SigGraphEdgeMap; /*!< the sig_graph_edges in here contain lists of words associated with them. */
CSignatureCollection * m_PassiveSignatures; /*!< these signatures have stems one letter off from another signature. */
CSignatureCollection * m_SequentialSignatures; /*! signatures where one affix leads to another signature. */
QList<CHypothesis*> * m_Hypotheses;
QMap<QString, CHypothesis*> * m_Hypothesis_map;
// add component 1
QProgressBar* m_ProgressBar;
QStatusBar * m_StatusBar;
double m_entropy_threshold_for_stems;
public:
CLexicon(CLexicon* parent_lexicon = NULL, bool suffix_flag = true);
public:
~CLexicon();
void dump_signatures_to_debug();
// accessors and protostems
void dump_suffixes(QList<QString>*);
void collect_parasuffixes();
void compute_sig_graph_edges();
void generate_hypotheses();
CSignatureCollection* get_active_signature_collection();
QMap<QString, eComponentType> & get_category_types() { return m_category_types;}
double get_entropy_threshold_for_positive_signatures() {return m_entropy_threshold_for_stems;}
//void get_epositive_signatures(QList<CSignature*> *);
QList<CHypothesis*>* get_hypotheses () {return m_Hypotheses;}
QMap<QString, CHypothesis*> * get_hypothesis_map() { return m_Hypothesis_map;}
CHypothesis* get_hypothesis(QString hypothesis_label);
QList<QPair<QString,QString> > * get_parses() {return m_Parses;}
CSuffixCollection* get_parasuffixes() { return m_ParaSuffixes;}
CSignatureCollection* get_passive_signatures() { return m_PassiveSignatures;}
CSignatureCollection* get_prefix_signatures() { return m_PrefixSignatures;}
CStemCollection * get_prefixal_stems() { return m_prefixal_stems;}
CSignatureCollection * get_residual_signatures() { return m_ParaSignatures;}
CSignatureCollection * get_sequential_signatures() { return m_SequentialSignatures;}
CSignatureCollection* get_signatures() { return m_Signatures;}
CSignatureCollection* get_suffix_signatures() { return m_Signatures;}
CSuffixCollection* get_suffixes() {return m_Suffixes;}
CStemCollection * get_suffixal_stems() { return m_suffixal_stems;}
// QMap<QString,int>* get_protostems() { return &m_suffix_protostems;}
QList<simple_sig_graph_edge*> * get_sig_graph_edges() { return &m_SigGraphEdgeList;}
lxa_sig_graph_edge_map * get_sig_graph_edge_map() { return & m_SigGraphEdgeMap;}
sig_graph_edge* get_sig_graph_edge(QString label) {return m_SigGraphEdgeMap[label];}
QListIterator<simple_sig_graph_edge*> * get_sig_graph_edge_list_iter();
lxa_sig_graph_edge_map_iter * get_sig_graph_edge_map_iter();
bool get_suffix_flag() { return m_SuffixesFlag; }
CWordCollection* get_word_collection() { return m_Words; }
CWordCollection * get_words() { return m_Words;}
void set_progress_bar (QProgressBar * pPB) { m_ProgressBar = pPB;}
void set_status_bar(QStatusBar* pBar) {m_StatusBar = pBar;}
void set_prefixes_flag() { m_SuffixesFlag = false;}
void set_suffixes_flag() { m_SuffixesFlag = true;}
void set_suffix_flag(bool flag) { m_SuffixesFlag = flag;}
void set_window(MainWindow* window) { m_main_window = window; }
CLexicon * build_sublexicon(MainWindow* = NULL);
void link_signature_and_stem(stem_t , CSignature*, QString this_signature_string );
void link_signature_and_affix(CSignature*, affix_t);
public:
// insert functions here
void assign_suffixes_to_stems(QString name_of_calling_function);
void clear_lexicon();
void compare_opposite_sets_of_signatures(QSet<CSignature*>* sig_set_1, QSet<CSignature*>* sig_set_2,QString letter);
void compute_sig_graph_edge_map();
void Crab_1();
void Crab_2();
void CreateStemAffixPairs();
void create_temporary_map_from_stems_to_affix_sets(map_sigstring_to_morph_set &); //map_sigstring_to_stem_list &);
void create_sublexicon ();
void find_full_signatures();
void FindGoodSignaturesInsideParaSignatures();
void FindProtostems();
void replace_parse_pairs_from_current_signature_structure(bool FindSuffixesFlag=true);
void ReSignaturizeWithKnownAffixes();
void test_for_phonological_relations_between_signatures();
};
#endif // CLEXICON_H
|
//
// ProgressPopup.cpp
// SMFrameWork
//
// Created by SteveMac on 2018. 5. 24..
//
#include "ProgressPopup.h"
#include "PopupManager.h"
#include "../Base/ShaderNode.h"
#include "../UI/ProgressView.h"
#include "../Base/ViewAction.h"
#include "../Util/ViewUtil.h"
#define POPUP_ID_PROGRESS (0xFFFFFE)
#define ACTION_TAG_SHOW (0x100)
#define OPEN_TIME (0.1)
#define CLOSE_TIME (0.1)
#define BG_SIZE (200.0f)
#define PROGRESS_SIZE (BG_SIZE*0.85f)
class ProgressPopup::ShowAction : public ViewAction::TransformAction {
public:
CREATE_DELAY_ACTION(ShowAction);
virtual void onStart() override {
_popup = (ProgressPopup*)getTarget();
_from = _popup->_showValue;
_to = _isOpen ? 1 : 0;
}
virtual void onUpdate(float t) override {
TransformAction::onUpdate(t);
_popup->_showValue = ViewUtil::interpolation(_from, _to, t);
_popup->setOpacity((GLubyte)(0xff*_popup->_showValue));
}
void setOpenValue(float duration, float delay) {
_isOpen = true;
setTimeValue(duration, delay);
}
void setCloseValue(float duration, float delay) {
_isOpen = false;
setTimeValue(duration, delay);
}
bool isOpen() {return _isOpen;}
private:
bool _isOpen;
float _from, _to;
ProgressPopup* _popup;
};
ProgressPopup* ProgressPopup::showProgress(float maxProgress, float delay)
{
ProgressPopup * popup = nullptr;
auto view = findPopupByTag(POPUP_ID_PROGRESS);
if (view) {
// 기존에 돌고 있냐?
popup = reinterpret_cast<ProgressPopup*>(view);
if (popup->getActionByTag(ACTION_TAG_SHOW)) {
auto action = popup->getActionByTag(ACTION_TAG_SHOW);
popup->stopAction(action);
}
PopupManager::getInstance().bringOnTop(view);
float t = 1.0f - popup->_showValue;
if (t>0) {
auto action = ShowAction::create();
action->setTag(ACTION_TAG_SHOW);
action->setOpenValue(OPEN_TIME*t, 0);
popup->runAction(action);
}
} else {
popup = new (std::nothrow)ProgressPopup();
if (popup && popup->initWithDelay(delay)) {
popup->autorelease();
popup->setTag(POPUP_ID_PROGRESS);
auto action = ShowAction::create();
action->setTag(ACTION_TAG_SHOW);
action->setOpenValue(OPEN_TIME, delay);
popup->runAction(action);
auto sharedLayer = cocos2d::Director::getInstance()->getSharedLayer(cocos2d::Director::SharedLayer::POPUP);
sharedLayer->addChild(popup);
} else {
CC_SAFE_DELETE(popup);
}
}
return popup;
}
void ProgressPopup::close(bool success)
{
if (success) {
_progress->setOnCompleteCallback(CC_CALLBACK_1(ProgressPopup::onComplete, this));
_progress->setProgress(100.0f);
} else {
dismiss(false);
}
}
void ProgressPopup::onComplete(ProgressView *progress)
{
auto popup = findPopupByTag(POPUP_ID_PROGRESS);
if (popup) {
popup->dismiss(true);
}
if (_dismissCallback) {
_dismissCallback();
}
}
ProgressPopup::ProgressPopup() : _showValue(0), _dismissCallback(nullptr)
{
}
ProgressPopup::~ProgressPopup()
{
}
bool ProgressPopup::initWithDelay(float delay)
{
if (!Popup::init()) {
return false;
}
auto s = cocos2d::Director::getInstance()->getWinSize();
setContentSize(s);
_progress = ProgressView::create(100.0f);
_progress->setPosition(s/2);
addChild(_progress);
auto action = ViewAction::TransformAction::create();
action->toAlpha(1).toScale(1).setTweenFunc(cocos2d::tweenfunc::TweenType::Back_EaseOut);
action->setTimeValue(0.3f, delay);
_progress->setOpacity(0);
_progress->setScale(0.5f);
_progress->runAction(action);
return true;
}
void ProgressPopup::show()
{
Popup::show();
}
void ProgressPopup::dismiss(bool imediate)
{
if (imediate) {
callbackOnDismiss();
removeFromParent();
} else {
auto action = dynamic_cast<ShowAction*>(getActionByTag(ACTION_TAG_SHOW));
if (action) {
if (!action->isOpen()) {
return;
}
stopAction(action);
}
action = ShowAction::create();
action->setTag(ACTION_TAG_SHOW);
action->setCloseValue(CLOSE_TIME, 0);
action->removeOnFinish();
runAction(action);
callbackOnDismiss();
}
}
int ProgressPopup::dispatchTouchEvent(const int action, const cocos2d::Touch *touch, const cocos2d::Vec2 *point, MotionEvent *event)
{
return TOUCH_INTERCEPT;
}
void ProgressPopup::setProgress(const float progress)
{
_progress->setProgress(progress);
}
|
#include <sstream>
#include <iostream>
#include <windows.h>
using namespace std;
void kylskapMedWhileTrue()
{
SetConsoleOutputCP(1252);
cout << "Välkommen till kylskåpsloopen 1" << endl;
while (true)
{
int temp2;
string temp;
cout << "Vilken temp har kylskåpet? " << endl;
cin >> temp;
stringstream ss;
ss << temp;
ss >> temp2;
if (temp2 < -273)
{
break;
}
if (temp2 <= 2)
{
cout << "För kallt" << endl;
}
if(temp2 >= 8)
{
cout << "För varmt" << endl;
}
if (temp2 > 2 || temp2 < 8)
{
cout << "Lagom" << endl;
}
}
cout << "Lämnar kylskåpsloopen 1" << endl;
}
void kylskapMedWhileVillkor()
{
SetConsoleOutputCP(1252);
cout << "Välkommen till kylskåpsloopen 2" << endl;
double temperatur = 0;
while (temperatur > -273)
{
int temp2;
string temp;
cout << "Vilken temp har kylskåpet? (om du vill avbryta skriv (avbryt)) " << endl;
cin >> temp;
stringstream ss;
ss << temp;
ss >> temp2;
if (temp2 <= 2)
{
cout << "För kallt" << endl;
}
if (temp2 >= 8)
{
cout << "För varmt" << endl;
}
if (temp2 > 2 || temp2 < 8)
{
cout << "Lagom" << endl;
}
if (temp == "avbryt")
{
temperatur = -274;
}
}
cout << "Lämnar kylskåpsloopen 2" << endl;
}
int main()
{
//kylskapMedWhileTrue ();
kylskapMedWhileVillkor();
}
|
#include <iostream>
using namespace std;
class MyClass {
int x;
public:
MyClass() :
x(0) {
cout << "Default Constructor" << endl;
}
MyClass(int i) :
x(i) {
cout << "Parameter Constructor" << endl;
}
MyClass(const MyClass& other) :
x(other.x) {
cout << "Copy Constructor" << endl;
}
// Two existing objects!
MyClass& operator=(const MyClass& other) {
x = other.x;
cout << "Copy Assignment Operator" << endl;
return *this;
}
//C++11
MyClass(MyClass&& other) {
x = std::move(other.x);
cout << "Move Constructor" << endl;
}
//C++11
MyClass& operator=(MyClass&& other) {
x = std::move(other.x);
cout << "Move Operator" << endl;
return *this;
}
void setX(int x){
this->x=x;
}
friend ostream& operator<< (ostream &out, const MyClass &m);
};
ostream& operator<< (ostream &out, const MyClass &m)
{
out << "MyClass x=" << m.x << endl;
return out;
}
// Dummy func to show C++11 move constructor
MyClass f(MyClass m) {
return m;
}
// create class and return
MyClass f1() {
MyClass m(10);
return m;
}
// return new class
MyClass f2() {
return MyClass(11);
}
// Change the value of the class, return ref!
MyClass& f3(MyClass &m) {
m.setX(21);
return m;
}
int main_rvo(void) {
MyClass m1(1);
MyClass m2 = m1; //copy
MyClass m3(m1); //copy
MyClass m4;
m4 = m1; //Assignment
cout << "* Move Contructor C++11" << endl;
MyClass m5(f(MyClass()));
cout << "* Move Operator C++11" << endl;
MyClass m6;
m6 = MyClass();
cout << "* Optimisation 1:" << endl;
MyClass m7 = f1();
cout << m7;
cout << "* Optimisation 2:" << endl;
MyClass m8 = f2();
cout << m8;
cout << "* Optimisation 3:" << endl;
const MyClass &m9 = f1();
cout << m9;
// Does not work! lvalue must be const!
// f() returns a temporary object (i.e., rvalue) and only lvalues can be bound to references to non-const.
// cout << "Optimisation 4:" << endl;
// MyClass &m10 = f2();
// cout << m10;
cout << "* NO Optimisation 5:" << endl;
MyClass m11(15) ;
cout << " :( Copy constructor:" << endl;
MyClass m12 = f3(m11);
cout << " :( Copy Assignement Operator:" << endl;
m12 = f3(m12);
cout << m12;
cout << "* Optimisation 6:" << endl;
MyClass m13(15) ;
MyClass &m14 = f3(m11); // if function return ref this is OK! NO COPY!
m14 = f3(m14);
cout << m14;
return 0;
}
|
class Solution {
public:
int removeDuplicatesI(int A[], int n) {
if(n <= 0)
return 0;
int c = 0;
for(int i = 1;i < n;++i)
if(A[c] != A[i])
A[++c] = A[i];
return c + 1;
}
int removeDuplicatesII(int A[], int n) {
if(n < 3)
return n;
int i = 2, p = i;
for(;i < n;++i)
if(A[i] != A[p - 2])
A[p++] = A[i];
return p;
}
};
|
#include <mutex>
#include <thread>
#include <condition_variable>
#include <queue>
class data_chunk
{
};
std::mutex mut;
std::queue<int> data_queue; // 1
std::condition_variable data_cond;
void data_preparation_thread()
{
while (true)
{
int data = 1;
std::lock_guard<std::mutex> lk(mut);
data_queue.push(data); // 2
data_cond.notify_one(); // 3
}
}
void data_processing_thread()
{
while (true)
{
std::unique_lock<std::mutex> lk(mut); // 4
data_cond.wait(
lk, [] { return !data_queue.empty(); }); // 5
int data = data_queue.front();
data_queue.pop();
lk.unlock(); // 6
data += 1; // process
}
}
|
// Problem: K-th beautiful String
// Link: https://codeforces.com/contest/1328/problem/B
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin >> t;
while(t>0){
unsigned long long n, k, num;
cin >> n >> k;
unsigned long long pos1, pos2;
if(k==1){
pos1 = n-1;
pos2 = n-2;
}else{
unsigned long long ct=2;
bool flag = false;
while(ct<=n){
num = (ct*(ct-1))/2 ;
if( num >= k ){
flag = true;
break;
}
ct++;
}
if(!flag){
pos1 = 0;
pos2 = 1;
}else{
unsigned long long requiredNum = ct - 1;
//cout << requiredNum << endl;
unsigned long long diff = k - ((requiredNum*(requiredNum - 1))/2);
pos1 = n - (requiredNum+1);
pos2 = n - (diff);
}
}
//cout << pos1 << pos2 << endl;
string ans;
for(long i=0; i<n; i++){
if(i==pos1 || i==pos2){
ans.append("b");
}else{
ans.append("a");
}
}
cout << ans << endl;
// baaba
t--;
}
return 0;
}
|
#include "include2.h"
#include "include1.h"
int main(int argc, char* argv[])
{
importantthing s1;
something2 s3;
s1.x = OPTION1;
s1.y = OPTION2;
return 0;
}
|
/*
* row.h
*
* Created on: Feb 24, 2016
* Author: Todd
*/
#ifndef ROW_H_
#define ROW_H_
#include "common.h"
#include "cell.h"
#include "grid.h"
class Row {
Grid& grid;
int rowNo;
public:
Row(Grid& grid, int rowNo);
Row(const Row& row);
class Iterator: iterator<input_iterator_tag, int> {
public:
Row& row;
int columnNo;
Iterator(Row& row, int columnNo);
Iterator(const Iterator& iter);
Iterator& operator++();
Iterator operator++(int);
bool operator==(const Iterator rhs);
bool operator!=(const Iterator rhs);
Point operator*();
};
Row& operator=(const Row& row_);
Iterator begin();
Iterator end();
Cell& getCell(int columnNo);
string toString();
};
typedef Row::Iterator RowIterator;
typedef vector<Row> RowVector;
#endif /* ROW_H_ */
|
#pragma once
/* Enable Naked Mode
* PATCHES: XXX.dll
*
* CTRL+H "EnableNakedMode"
*/
#include "../Main.h"
#include "../Singleton.h"
#include "GenericPatcher.h"
class CPatcher_EnableNakedMode : public IGenericPatcher {
public:
CPatcher_EnableNakedMode();
bool ReadINI(void);
bool WriteINI(void);
private:
// Hook functions
// Variables for hook functions
};
typedef Singleton<CPatcher_EnableNakedMode> SngPatcher_EnableNakedMode;
|
#include "FuGenPipelineEdge.h"
#include <iostream>
void FuGenPipelineEdge::mouseReleaseEvent(QGraphicsSceneMouseEvent *Event)
{
QGraphicsLineItem::mouseReleaseEvent(Event);
//
if (Event->button() == Qt::LeftButton)
{
for(IPipelineEdgeListener *Listener : Listeners)
{
Listener->OnClicked();
}
}
}
void FuGenPipelineEdge::paint(QPainter *painter,const QStyleOptionGraphicsItem *option,QWidget *widget)
{
QGraphicsLineItem::paint(painter,option,widget);
//
float DirX = line().dx();
float DirY = line().dy();
//
float PointX = line().x1() + DirX / 2.0f;
float PointY = line().y1() + DirY / 2.0f;
//
float Length = line().length();
DirX /= Length;
DirY /= Length;
float SideDirX = DirY;
float SideDirY = -DirX;
//
float ArrowSize = 10.0;
//
QPointF Dir(DirX,DirY);
QPointF SideDir(SideDirX,SideDirY);
//
QPointF ArrowPoint(PointX,PointY);
QPointF ArrowOnePoint = ArrowPoint - 10.0f * Dir + 10.0f * SideDir;
QPointF ArrowOtherPoint = ArrowPoint - 10.0f * Dir - 10.0f * SideDir;
//
QLineF ArrowOnePart(ArrowPoint,ArrowOnePoint);
QLineF ArrowOtherPart(ArrowPoint,ArrowOtherPoint);
//
painter->drawLine(ArrowOnePart);
painter->drawLine(ArrowOtherPart);
}
FuGenPipelineEdge::FuGenPipelineEdge(FuGenPipelineNode *begin_node,FuGenPipelineNode *end_node)
:QGraphicsLineItem(QLineF(begin_node->GetCenter(),end_node->GetCenter())),BeginNode(begin_node),EndNode(end_node),BeginListener(this,true,BeginNode),EndListener(this,false,EndNode)
{
setFlag(QGraphicsItem::ItemIsSelectable);
}
FuGenPipelineEdge::~FuGenPipelineEdge()
{
if(!BeginListener.IsDeleted())
{BeginNode->RemoveListener(&BeginListener);}
if(!EndListener.IsDeleted())
{EndNode->RemoveListener(&EndListener);}
//
for(IPipelineEdgeListener *Listener : Listeners)
{
Listener->OnDeleted();
}
}
|
#ifndef MCEVENT_H
#define MCEVENT_H
#include <map>
#include <vector>
#include "TTree.h"
class MCGeometry;
class TFile;
class TH2F;
class MCEvent {
public:
//-------------------------------------
MCEvent(const char* dataFileName="");
virtual ~MCEvent();
// methods
TTree* Tree() { return simTree; }
void InitBranchAddress();
void GetEntry(int i);
void Reset();
void PrintInfo(int level=0); // print the current event(entry) info
void InitHistograms();
void ProcessTracks();
// void ProcessChannels();
bool IsPrimary(int i) { return mc_mother[i] == 0; }
void FillPixel(int plane); // U=0, V=1, Z=2
TFile *rootFile;
TTree *simTree;
MCGeometry *geom;
enum LIMITS {
MAX_CHANNEL = 8254,
MAX_TRACKS = 3000,
MAX_HITS = 20000,
MAX_TRACKER = 10,
};
enum DISPLAY {
kRAW = 1,
kCALIB = 2,
kHITS = 3,
kTRACK = 4,
};
int nEvents;
int currentEventEntry;
// simTree Leafs
int eventNo;
int runNo;
int subRunNo;
int raw_Nhit; // number of hit channels
int raw_channelId[MAX_CHANNEL]; // hit channel id; size == raw_Nhit
int raw_baseline[MAX_CHANNEL]; // hit channel baseline; size == raw_Nhit
int raw_charge[MAX_CHANNEL]; // hit channel charge (simple alg); size == raw_Nhit
int raw_time[MAX_CHANNEL]; // hit channel time (simple alg); size == raw_Nhit
std::vector<std::vector<int> > *raw_wfADC;
std::vector<std::vector<int> > *raw_wfTDC;
int calib_Nhit; // number of hit channels
int calib_channelId[MAX_CHANNEL]; // hit channel id; size == raw_Nhit
std::vector<std::vector<int> > *calib_wfADC;
std::vector<std::vector<int> > *calib_wfTDC;
int mc_Ntrack; // number of tracks in MC
int mc_id[MAX_TRACKS]; // track id; size == mc_Ntrack
int mc_pdg[MAX_TRACKS]; // track particle pdg; size == mc_Ntrack
int mc_process[MAX_TRACKS]; // track generation process code; size == mc_Ntrack
int mc_mother[MAX_TRACKS]; // mother id of this track; size == mc_Ntrack
float mc_startXYZT[MAX_TRACKS][4]; // start position of this track; size == mc_Ntrack
float mc_endXYZT[MAX_TRACKS][4]; // end position of this track; size == mc_Ntrack
float mc_startMomentum[MAX_TRACKS][4]; // start momentum of this track; size == mc_Ntrack
float mc_endMomentum[MAX_TRACKS][4]; // end momentum of this track; size == mc_Ntrack
std::vector<std::vector<int> > *mc_daughters; // daughters id of this track; vector
int mc_isnu; // is neutrino interaction
int mc_nGeniePrimaries; // number of Genie primaries
int mc_nu_pdg; // pdg code of neutrino
int mc_nu_ccnc; // cc or nc
int mc_nu_mode; // mode: http://nusoft.fnal.gov/larsoft/doxsvn/html/MCNeutrino_8h_source.html
int mc_nu_intType; // interaction type
int mc_nu_target; // target interaction
int mc_hitnuc; // hit nucleon
int mc_hitquark; // hit quark
double mc_nu_Q2; // Q^2
double mc_nu_W; // W
double mc_nu_X; // X
double mc_nu_Y; // Y
double mc_nu_Pt; // Pt
double mc_nu_Theta; // angle relative to lepton
float mc_nu_pos[4]; // interaction position of nu
float mc_nu_mom[4]; // interaction momentum of nu
int no_hits; //number of hits
int hit_channel[MAX_HITS]; //channel ID
int hit_plane[MAX_HITS]; //channel ID
float hit_peakT[MAX_HITS]; //peak time
float hit_charge[MAX_HITS]; //charge (area)
int trk_nTrack[MAX_TRACKER]; // no. of tracks of each tracker.
std::vector<int>* trk_nHit[MAX_TRACKER]; // no. of hits of each track
std::vector<double>* trk_length[MAX_TRACKER]; // length of each track
std::vector<std::vector<double> >* trk_start_xyz[MAX_TRACKER]; // position of start vertex
std::vector<std::vector<double> >* trk_end_xyz[MAX_TRACKER]; // position of end vertex
std::vector<std::vector<double> >* trk_start_dxyz[MAX_TRACKER]; // direction of start vertex
std::vector<std::vector<double> >* trk_end_dxyz[MAX_TRACKER]; // direction of end vertex
std::vector<std::vector<double> >* trk_points_x[MAX_TRACKER]; // position of all points on trajectory
std::vector<std::vector<double> >* trk_points_y[MAX_TRACKER]; // position of all points on trajectory
std::vector<std::vector<double> >* trk_points_z[MAX_TRACKER]; // position of all points on trajectory
std::vector<double>* trk_calo_KE[MAX_TRACKER][3]; // KE of calorimetry from each plan of each trk
std::vector<double>* trk_calo_range[MAX_TRACKER][3]; // Range of calorimetry from each plan of each trk
std::vector<int>* trk_calo_nHit[MAX_TRACKER][3]; // hits of calorimetry from each plan of each trk
std::vector<std::vector<double> >* trk_calo_dedx[MAX_TRACKER][3]; // dedx of calorimetry from each plan of each trk
std::vector<std::vector<double> >* trk_calo_dqdx[MAX_TRACKER][3]; // dqdx of calorimetry from each plan of each trk
std::vector<std::vector<double> >* trk_calo_resRange[MAX_TRACKER][3]; // residual range of calorimetry from each plan of each trk
// // derived variables
// int raw_NZchannels;
// int raw_NUchannels;
// int raw_NVchannels;
// std::vector<int> raw_ZchannelId;
// std::vector<int> raw_UchannelId;
// std::vector<int> raw_VchannelId;
// int hit_NZchannels;
// int hit_NUchannels;
// int hit_NVchannels;
// std::vector<int> hit_ZchannelId;
// std::vector<int> hit_UchannelId;
// std::vector<int> hit_VchannelId;
std::map<int, int> trackIndex;
std::vector<std::vector<int> > trackParents;
std::vector<std::vector<int> > trackChildren;
std::vector<std::vector<int> > trackSiblings;
// histograms
TH2F *hPixel[3]; // 0: XvsU; 1: XvsV; 2: XvsZ;
std::map<int, int> bintoWireHash[3]; // for the three histograms, maps bin number to wire hash
double adc_thresh; // noise threshold for histogram
// std::map<int, int> zBintoWireHash;
// std::map<int, int> uBintoWireHash;
// std::map<int, int> vBintoWireHash;
int optionDisplay;
int optionInductionSignal; // 1:pos; 0:both; -1:neg
// bool showAPA[4];
};
#endif
|
#include "../../include/primitives/HashOpenSSL.hpp"
OpenSSLHash::OpenSSLHash(string hashName) {
//Instantiates a hash object in OpenSSL. We keep a pointer to the created hash object in c++.
//Remember to delete it using the finalize method.
EVP_MD_CTX* mdctx;
const EVP_MD *md;
OpenSSL_add_all_digests();
//Get the string from java.
const char* name = hashName.c_str();
// Get the OpenSSL digest.
md = EVP_get_digestbyname(name);
if (md == 0)
throw runtime_error("failed to create hash");
// Create an OpenSSL EVP_MD_CTX struct and initialize it with the created hash.
mdctx = EVP_MD_CTX_create();
if (0 == (EVP_DigestInit(mdctx, md)))
throw runtime_error("failed to create hash");
hash = mdctx;
hashSize = EVP_MD_CTX_size(hash);
}
OpenSSLHash::~OpenSSLHash() {
EVP_MD_CTX_destroy(hash);
}
string OpenSSLHash::getAlgorithmName() {
int type = EVP_MD_CTX_type(hash);
const char* name = OBJ_nid2sn(type);
return string(name);
}
void OpenSSLHash::update(const vector<byte> &in, int inOffset, int inLen){
//Check that the offset and length are correct.
if ((inOffset > in.size()) || (inOffset + inLen > in.size()) || (inOffset<0))
throw out_of_range("wrong offset for the given input buffer");
if (inLen < 0)
throw invalid_argument("wrong length for the given input buffer");
if (inLen == 0)
throw new out_of_range("wrong length for the given input buffer");
//The dll function does the update from offset 0.
//If the given offset is greater than 0, copy the relevant bytes to a new array and send it to the dll function.
byte * input = new byte[inLen];
copy_byte_vector_to_byte_array(in, input, inOffset);
// Update the hash with the message.
EVP_DigestUpdate(hash, input, inLen);
}
void OpenSSLHash::hashFinal(vector<byte> &out, int outOffset) {
//Checks that the offset and length are correct.
if (outOffset<0)
throw new out_of_range("wrong offset for the given output buffer");
int length = EVP_MD_CTX_size(hash);
byte* tempOut = new byte[length];
EVP_DigestFinal_ex(hash, tempOut, NULL);
copy_byte_array_to_byte_vector(tempOut, length, out, outOffset);
delete tempOut;
}
CryptographicHash* CryptographicHash::get_new_cryptographic_hash(string hashName)
{
set<string> algSet = { "SHA1", "SHA224", "SHA256", "SHA384", "SHA512" };
if (algSet.find(hashName) == algSet.end())
throw invalid_argument("unexpected hash_name");
return new OpenSSLHash(hashName);
}
|
#ifndef GTS_PAINTSHAPE_H
#define GTS_PAINTSHAPE_H
#include<QPoint>
#include<QPainter>
/////////////////////////////////////////////////////////////////////////////////////////
class Shape2D
{
public:
enum shapeType{LINE, RECT, POLYGON, CURVES};
Shape2D();
void setStartPoint(QPoint s){start_ = s; }
void setEndPoint(QPoint s){ end_ = s;}
QPoint getStartPoint(){return start_;}
QPoint getEndPoint(){return end_;}
bool isShapeCompleted(){return PaintCompleted_;}
bool setShapeCompleted(bool judge){PaintCompleted_ = judge;}
int getPointsSize(){return points_.size();}
QPoint getNthPoint(int n){return points_.at(n);}
void virtual paint(QPainter &painter)=0;
void virtual addPoint(QPoint point){}
void setColor(QColor&color){ s_color_ = color;}
protected:
QPoint start_;
QPoint end_;
QVector<QPoint> points_;
QColor s_color_;
bool PaintCompleted_;
};
/////////////////////////////////////////////////////////////////////////////////////////
class Line2D: public Shape2D
{
public:
Line2D();
void paint(QPainter &painter);
};
////////////////////////////////////////////////////////////////////////////////////////////
class Polygon2D: public Shape2D
{
public:
Polygon2D();
void paint(QPainter &painter);
void addPoint(QPoint point);
void draw();
private:
};
///////////////////////////////////////////////////////////////////////////////////////////
class Rect2D: public Shape2D
{
public:
Rect2D();
void paint(QPainter &painter);
};
///////////////////////////////////////////////////////////////////////////////////////////////
class Curves2D: public Shape2D{
public:
Curves2D();
void paint(QPainter &painter);
void addPoint(QPoint point);
private:
};
#endif // PAINTSHAPE_H
|
/*
CTC GO! MOTION
PROJECT - SPIN-A-WHEEL
This sketch is written to accompany Stage 5 of the SPIN-A-WHEEL project
*/
#include <Servo.h>
Servo servo_wheel;
Servo servo_pointer;
int button_1 = 2;
int button_2 = 3;
int yellowLED = 4;
int blueLED = 5;
int piezo = 8;
int buttonState_1;
int buttonState_2;
int counter;
void setup() {
pinMode(button_1, INPUT);
pinMode(button_2, INPUT);
pinMode(yellowLED, OUTPUT);
pinMode(blueLED, OUTPUT);
servo_pointer.attach(6);
servo_wheel.attach(9);
Serial.begin(9600);
}
void loop() {
buttonState_1 = digitalRead(button_1);
buttonState_2 = digitalRead(button_2);
if(buttonState_1 == HIGH)
{
Serial.println("Button 1 pressed");
servo_pointer.write(30);
delay(10);
servo_wheel.write(30);
delay(1000);
}
if(buttonState_2 == HIGH)
{
Serial.println("Button 2 pressed");
servo_pointer.write(70);
delay(10);
servo_wheel.write(93);
delay(1000);
____________();
}
}
void ____________() {
______++;
if(counter <= 2)
{
digitalWrite(yellowLED, HIGH);
digitalWrite(blueLED, LOW);
}
else if(counter == 3)
{
______();
counter++;
digitalWrite(blueLED, HIGH);
digitalWrite(yellowLED, LOW);
}
else if(counter >= 4 && counter <= 6)
{
digitalWrite(blueLED, HIGH);
digitalWrite(yellowLED, LOW);
}
else if(counter == 7)
{
______();
______ = 0;
digitalWrite(blueLED, LOW);
digitalWrite(yellowLED, HIGH);
}
delay(100);
}
void ______() {
tone(______, 500);
delay(300);
______(______);
delay(300);
tone(______, 1200);
delay(500);
______(______);
delay(300);
tone(______, 200);
delay(700);
______(______);
delay(300);
}
|
/* Copyright 2017-2018 All Rights Reserved.
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* [Contact]
* Gyeonghwan Hong (redcarrottt@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 __ARRIVAL_TIME_COUNTER_H__
#define __ARRIVAL_TIME_COUNTER_H__
#include "Counter.h"
#include <sys/time.h>
#include <mutex>
#include <vector>
namespace sc {
class ArrivalTimeCounter : public Counter {
public:
ArrivalTimeCounter(void) : Counter() {
this->mLastAccessedTS.tv_sec = 0;
this->mLastAccessedTS.tv_usec = 0;
}
void arrive(void) {
std::unique_lock<std::mutex> lock(this->mArriveLock);
struct timeval startTS, endTS;
startTS = this->mLastAccessedTS;
gettimeofday(&endTS, NULL);
// Get and store interval
if (startTS.tv_sec != 0 || startTS.tv_usec != 0) {
uint64_t endUS = (uint64_t)endTS.tv_sec * 1000 * 1000 + endTS.tv_usec;
uint64_t startUS =
(uint64_t)startTS.tv_sec * 1000 * 1000 + startTS.tv_usec;
int intervalUS = (int)(endUS - startUS);
this->set_value(intervalUS);
}
// Store last accessed timestamp
this->mLastAccessedTS = endTS;
}
private:
std::mutex mArriveLock;
struct timeval mLastAccessedTS;
}; /* class ArrivalTimeCounter */
} /* namespace sc */
#endif /* !defined(__ARRIVAL_TIME_COUNTER_H__) */
|
//
// marketdata.cpp
//
#include "marketdata.hpp"
#include "database.hpp"
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
int RetrieveMarketData(string url_request, string & read_buffer)
{
curl_global_init(CURL_GLOBAL_ALL);
CURL * myHandle;
CURLcode result;
myHandle = curl_easy_init();
curl_easy_setopt(myHandle, CURLOPT_URL, url_request.c_str());
//adding a user agent
curl_easy_setopt(myHandle, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201");
curl_easy_setopt(myHandle, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(myHandle, CURLOPT_SSL_VERIFYHOST, 0);
//curl_easy_setopt(myHandle, CURLOPT_VERBOSE, 1);
// send all data to this function
curl_easy_setopt(myHandle, CURLOPT_WRITEFUNCTION, WriteCallback);
// we pass our 'chunk' struct to the callback function
curl_easy_setopt(myHandle, CURLOPT_WRITEDATA, &read_buffer);
//perform a blocking file transfer
result = curl_easy_perform(myHandle);
// check for errors
if (result != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(result));
return -1;
}
curl_easy_cleanup(myHandle);
return 0;
}
int PopulatePairTable(sqlite3 *db, const map<int, pair<string, string>> & pairs)
{
for (map<int, pair<string, string>>::const_iterator itr = pairs.begin(); itr != pairs.end(); itr++)
{
char pair_insert_table[512];
sprintf(pair_insert_table, "INSERT INTO PAIRS (id, symbol1, symbol2, variance, profit) VALUES(%d, \"%s\", \"%s\", %.2f, %.2f)", itr->first, itr->second.first.c_str(), itr->second.second.c_str(), 0.0, 0.0);
if (InsertTable(pair_insert_table, db) == -1)
return -1;
}
return 0;
}
int PopulatePairStockTable(sqlite3 *db, const map<string, Stock> & stocks)
{
for (auto stock_itr = stocks.begin(); stock_itr != stocks.end(); ++stock_itr)
{
vector<TradeData> trades = stock_itr->second.getTrades();
for (auto trade_itr = trades.begin(); trade_itr != trades.end(); ++trade_itr)
{
char pair_insert_table[512];
sprintf(pair_insert_table, "Insert into PairStocks (symbol, date, open, high, low, close, adjusted_close, volume) \
VALUES(\"%s\", \"%s\", %.2f, %.2f, %.2f, %.2f, %.2f, %ld)",
stock_itr->first.c_str(), trade_itr->getDate().c_str(), trade_itr->getOpen(), trade_itr->getHigh(), trade_itr->getLow(),
trade_itr->getClose(), trade_itr->getAdjClose(), trade_itr->getVolume());
if (InsertTable(pair_insert_table, db) == -1)
return -1;
}
}
return 0;
}
|
#include "Collidable.h"
#include "Utilities/Logger/Log.h"
#include "../Physics/Movable.h"
namespace liman {
const char* Collidable::g_Name = "CollisionComponent";
Collidable::Collidable() = default;
// TODO: place somewhere in settings
// const float g_paramColision = 1;
// TIP: Collision result logic
maths::Vec2f Collidable::Collide(Actor* pPairedActor, CollisionSide side) {
auto* pMoveComp = this->GetOwner()->GetComponent<Movable>(Movable::g_Name);
if (pMoveComp) {
pMoveComp->SetVelocity(0.0f, 0.0f);
pMoveComp->AddAccel(0.0f, Movable::g_gravity * 0.0001f);
}
return maths::Vec2f();
}
void Collidable::OnCollision() {
// TODO: create collision event
}
}
|
void setUpRF() {
Serial.println("-----------------------------");
Serial.println("Iniciando RF");
radio.begin();
radio.setChannel(115);
radio.setPALevel(RF24_PA_LOW);
radio.setPayloadSize(32);
radio.openWritingPipe(direccion[0]);
radio.stopListening();
Serial.println("RF iniciado!");
Serial.println("-----------------------------");
}
void setUpData(){
dataTemp.id=7;
dataTemp.typeOfData=1;
dataHum.id=7;
dataHum.typeOfData=2;
dataElectric.id=7;
dataElectric.typeOfData=5;
}
|
#include <iostream>
#include <vector>
using namespace std;
int lowerBound(vector<int> &nums, int target) {
int low = 0, high = nums.size(); // high not be nums.size() to void that all elements less than target, then nums.size() return
while (low < high) { // if low <= high, maybe infinite loop
//cout << "bingbing" << endl;
int mid = low + (high-low)/2;
if (target > nums[mid]) low = mid+1;
else high = mid;
}
return low;
}
int main(int argc, char**argv) {
vector<int> nums {2, 3, 4, 4, 6};
int idx = lowerBound(nums, 6);
cout << idx << endl;
return 0;
}
|
//
// Copyright (c) 2003--2009
// Toon Knapen, Karl Meerbergen, Kresimir Fresl,
// Thomas Klimpel and Rutger ter Borg
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// THIS FILE IS AUTOMATICALLY GENERATED
// PLEASE DO NOT EDIT!
//
#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_COMPUTATIONAL_TREXC_HPP
#define BOOST_NUMERIC_BINDINGS_LAPACK_COMPUTATIONAL_TREXC_HPP
#include <boost/assert.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/numeric/bindings/lapack/detail/lapack.h>
#include <boost/numeric/bindings/lapack/workspace.hpp>
#include <boost/numeric/bindings/traits/detail/array.hpp>
#include <boost/numeric/bindings/traits/is_complex.hpp>
#include <boost/numeric/bindings/traits/is_real.hpp>
#include <boost/numeric/bindings/traits/traits.hpp>
#include <boost/numeric/bindings/traits/type_traits.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/utility/enable_if.hpp>
namespace boost {
namespace numeric {
namespace bindings {
namespace lapack {
//$DESCRIPTION
// overloaded functions to call lapack
namespace detail {
inline void trexc( char const compq, integer_t const n, float* t,
integer_t const ldt, float* q, integer_t const ldq,
integer_t& ifst, integer_t& ilst, float* work, integer_t& info ) {
LAPACK_STREXC( &compq, &n, t, &ldt, q, &ldq, &ifst, &ilst, work,
&info );
}
inline void trexc( char const compq, integer_t const n, double* t,
integer_t const ldt, double* q, integer_t const ldq,
integer_t& ifst, integer_t& ilst, double* work, integer_t& info ) {
LAPACK_DTREXC( &compq, &n, t, &ldt, q, &ldq, &ifst, &ilst, work,
&info );
}
inline void trexc( char const compq, integer_t const n,
traits::complex_f* t, integer_t const ldt, traits::complex_f* q,
integer_t const ldq, integer_t const ifst, integer_t const ilst,
integer_t& info ) {
LAPACK_CTREXC( &compq, &n, traits::complex_ptr(t), &ldt,
traits::complex_ptr(q), &ldq, &ifst, &ilst, &info );
}
inline void trexc( char const compq, integer_t const n,
traits::complex_d* t, integer_t const ldt, traits::complex_d* q,
integer_t const ldq, integer_t const ifst, integer_t const ilst,
integer_t& info ) {
LAPACK_ZTREXC( &compq, &n, traits::complex_ptr(t), &ldt,
traits::complex_ptr(q), &ldq, &ifst, &ilst, &info );
}
}
// value-type based template
template< typename ValueType, typename Enable = void >
struct trexc_impl{};
// real specialization
template< typename ValueType >
struct trexc_impl< ValueType, typename boost::enable_if< traits::is_real<ValueType> >::type > {
typedef ValueType value_type;
typedef typename traits::type_traits<ValueType>::real_type real_type;
// templated specialization
template< typename MatrixT, typename MatrixQ >
static void invoke( char const compq, MatrixT& t, MatrixQ& q,
integer_t& ifst, integer_t& ilst, integer_t& info ) {
BOOST_STATIC_ASSERT( (boost::is_same< typename traits::matrix_traits<
MatrixT >::value_type, typename traits::matrix_traits<
MatrixQ >::value_type >::value) );
BOOST_ASSERT( compq == 'V' || compq == 'N' );
BOOST_ASSERT( traits::matrix_num_columns(t) >= 0 );
BOOST_ASSERT( traits::leading_dimension(t) >= std::max(1,
traits::matrix_num_columns(t)) );
BOOST_ASSERT( traits::leading_dimension(q) >= std::max(1,
traits::matrix_num_columns(t)) );
BOOST_ASSERT( traits::vector_size(work.select(real_type())) >=
min_size_work( traits::matrix_num_columns(t) ));
detail::trexc( compq, traits::matrix_num_columns(t),
traits::matrix_storage(t), traits::leading_dimension(t),
traits::matrix_storage(q), traits::leading_dimension(q), ifst,
ilst, traits::vector_storage(work.select(real_type())), info );
}
};
// complex specialization
template< typename ValueType >
struct trexc_impl< ValueType, typename boost::enable_if< traits::is_complex<ValueType> >::type > {
typedef ValueType value_type;
typedef typename traits::type_traits<ValueType>::real_type real_type;
// user-defined workspace specialization
template< typename MatrixT, typename MatrixQ, $WORKSPACE_TYPENAMES >
static void invoke( char const compq, MatrixT& t, MatrixQ& q,
integer_t const ifst, integer_t const ilst, integer_t& info,
detail::workspace$WORKSPACE_SIZE< $WORKSPACE_TYPES > work ) {
BOOST_STATIC_ASSERT( (boost::is_same< typename traits::matrix_traits<
MatrixT >::value_type, typename traits::matrix_traits<
MatrixQ >::value_type >::value) );
BOOST_ASSERT( compq == 'V' || compq == 'N' );
BOOST_ASSERT( traits::matrix_num_columns(t) >= 0 );
BOOST_ASSERT( traits::leading_dimension(t) >= std::max(1,
traits::matrix_num_columns(t)) );
BOOST_ASSERT( traits::leading_dimension(q) >= std::max(1,
traits::matrix_num_columns(t)) );
detail::trexc( compq, traits::matrix_num_columns(t),
traits::matrix_storage(t), traits::leading_dimension(t),
traits::matrix_storage(q), traits::leading_dimension(q), ifst,
ilst, info );
}
// minimal workspace specialization
template< typename MatrixT, typename MatrixQ >
static void invoke( char const compq, MatrixT& t, MatrixQ& q,
integer_t const ifst, integer_t const ilst, integer_t& info,
minimal_workspace work ) {
$SETUP_MIN_WORKARRAYS_POST
invoke( compq, t, q, ifst, ilst, info, workspace( $TMP_WORKARRAYS ) );
}
// optimal workspace specialization
template< typename MatrixT, typename MatrixQ >
static void invoke( char const compq, MatrixT& t, MatrixQ& q,
integer_t const ifst, integer_t const ilst, integer_t& info,
optimal_workspace work ) {
$OPT_WORKSPACE_FUNC
}
$MIN_SIZE_FUNCS
};
// template function to call trexc
template< typename MatrixT, typename MatrixQ >
inline integer_t trexc( char const compq, MatrixT& t, MatrixQ& q,
integer_t& ifst, integer_t& ilst ) {
typedef typename traits::matrix_traits< MatrixT >::value_type value_type;
integer_t info(0);
trexc_impl< value_type >::invoke( compq, t, q, ifst, ilst, info );
return info;
}
// template function to call trexc
template< typename MatrixT, typename MatrixQ, typename Workspace >
inline integer_t trexc( char const compq, MatrixT& t, MatrixQ& q,
integer_t const ifst, integer_t const ilst, Workspace work ) {
typedef typename traits::matrix_traits< MatrixT >::value_type value_type;
integer_t info(0);
trexc_impl< value_type >::invoke( compq, t, q, ifst, ilst, info,
work );
return info;
}
// template function to call trexc, default workspace type
template< typename MatrixT, typename MatrixQ >
inline integer_t trexc( char const compq, MatrixT& t, MatrixQ& q,
integer_t const ifst, integer_t const ilst ) {
typedef typename traits::matrix_traits< MatrixT >::value_type value_type;
integer_t info(0);
trexc_impl< value_type >::invoke( compq, t, q, ifst, ilst, info,
optimal_workspace() );
return info;
}
}}}} // namespace boost::numeric::bindings::lapack
#endif
|
#ifndef _SERVER_H_
#define _SERVER_H_
#include <string.h>
#ifdef WIN32
#include <winsock2.h>
// #include <Ws2tcpip.h>
#else
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h> /* Needed for getaddrinfo() and freeaddrinfo() */
#include <unistd.h> /* Needed for close() */
#endif
#include "json11.h"
class tcp_server
{
public:
tcp_server(int);
virtual ~tcp_server();
int start_listening();
int receive_json(Json* packet);
int send_json(Json* packet);
protected:
int port;
int sSock; // Server Socket
int cSock; // Server Socket
private:
int socket_init(void);
int socket_quit(void);
int socket_close(int sock);
int accept_connection();
};
#endif
|
#include <sstream>
#include <string>
template <class T>
bool transfChaine (const string chaine, T &tmp){
bool res = false;
istringstream iss(chaine);
if(iss>>tmp){
res = true;
}
return res ;
}
template <class T>
bool verifType (const string chaine, T tmp){
// créer un flux à partir de la chaîne donnée
istringstream iss( chaine );
// tenter la conversion et
// vérifier qu'il ne reste plus rien dans la chaîne
return ( iss >> tmp ) && ( iss.eof() );
}
|
#include <bits/stdc++.h>
using namespace std;
bool isPal(long int);
int main()
{
freopen("out", "w", stdout);
int n = 0, a[2470];
for(int i=100; i<1000; i++)
{
for(int j=100; j<1000; j++)
{
if(isPal(i*j))
{
cout<<i*j<<", ";
n++;
}
}
}
cout<<"\n\n"<<n;
return 0;
}
bool isPal(long int n)
{
string a = "";
while(n!=0)
{
int d = n%10;
a += d+'0';
n /= 10;
}
int len = a.length();
int i = 0, j = len-1;
while(i<j)
{
if(a[i]!=a[j]) return false;
i++;
j--;
}
return true;
}
|
/****************************************
*
* INSERT-PROJECT-NAME-HERE - INSERT-GENERIC-NAME-HERE
* Copyright (C) 2021 Victor Tran
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* *************************************/
#include "gamepadbuttoniconselectiondialog.h"
#include "ui_gamepadbuttoniconselectiondialog.h"
#include <QShortcut>
#include "gamepadbuttons.h"
#include "entertainingsettings.h"
GamepadButtonIconSelectionDialog::GamepadButtonIconSelectionDialog(QWidget* parent) :
QWidget(parent),
ui(new Ui::GamepadButtonIconSelectionDialog) {
ui->setupUi(this);
ui->titleLabel->setBackButtonShown(true);
ui->optionsWidget->setFixedWidth(SC_DPI(600));
this->setFocusProxy(ui->optionsWidget);
ui->gamepadHud->setButtonText(QGamepadManager::ButtonA, tr("Select"));
ui->gamepadHud->setButtonText(QGamepadManager::ButtonB, tr("Back"));
ui->gamepadHud->setButtonAction(QGamepadManager::ButtonA, [ = ] {
on_optionsWidget_activated(ui->optionsWidget->currentIndex());
});
ui->gamepadHud->setButtonAction(QGamepadManager::ButtonB, [ = ] {
emit done();
});
QShortcut* backShortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this);
connect(backShortcut, &QShortcut::activated, this, [ = ] {
emit done();
});
connect(backShortcut, &QShortcut::activatedAmbiguously, this, [ = ] {
emit done();
});
for (int i = 0; i < 4; i++) {
ui->optionsWidget->addItem(GamepadButtons::iconTypeNameForIndex(i));
}
}
GamepadButtonIconSelectionDialog::~GamepadButtonIconSelectionDialog() {
delete ui;
}
void GamepadButtonIconSelectionDialog::on_titleLabel_backButtonClicked() {
emit done();
}
void GamepadButtonIconSelectionDialog::on_optionsWidget_activated(const QModelIndex& index) {
EntertainingSettings::instance()->setValue("gamepad/icons", index.row());
emit done();
}
|
#ifndef TEXTURE
#define TEXTURE
#include "init.hpp"
class Image{
public:
Image( std::string path );
Image( std::string path , const int x, const int y, const int w, const int h );
~Image( );
int render( const int x, const int y );
int render( const int x, const int y, const double multipX, const double multipY );
int setRectSrc( const int x, const int y, const int w, const int h );
int getError() { return error; }
protected:
SDL_Texture* texture;
SDL_Rect src;
int width;
int height;
int error = -1;
};
class MultiImage {
public:
MultiImage( std::string path, int nbX, int nbY );
~MultiImage();
int render( int const x, int const y, int const nImageX, int const nImageY );
int render( int const x, int const y, double const multipX, double const multipY, int const nImageX, int const nImageY );
protected:
SDL_Texture* texture;
int width;
int height;
int error;
};
class Anim{
public:
Anim( std::string path, int images[][4], const int l, const double mPI );
int render( const int x, const int y, const double multipX, const double multipY );
int update();
~Anim();
private:
double msPerImg;
time_t nbMs;
vector<Image> frames;
int nImg;
int fLength;
};
#endif // TEXTURE
|
#include <iostream>
using namespace std;
void hanoy(int, int, int, int);
int main()
{
hanoy(3, 1, 2, 3);
cout << endl;
return 0;
}
// val - количество дисков.
// start - 1 стержень (стартовый).
// buff - 2 стержень (переходный).
// end - 3 стержень (куда надо переместить).
void hanoy(int val, int start, int buff, int end)
{
if (val == 0)
return;
hanoy(val - 1, start, end, buff);
cout << start << " -- > " << end << endl;
hanoy(val - 1, buff, start, end);
return;
}
|
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if (nums.empty()) return 0;
return helper(nums, 0, nums.size() - 1);
}
int helper(vector<int> & nums, int left, int right) {
if (left >= right) return nums[left]; // must be >=, not ==
int mid = left + (right - left) / 2;
int lmax = helper(nums, left, mid - 1);
int rmax = helper(nums, mid + 1, right);
// start from nums[mid] to calculate mid-maxSubArray
int mmax = nums[mid], tmp = mmax;
// extent midmax-subarray from mid to left
for (int i = mid - 1; i >= left; --i) { // must be >=, not >
tmp += nums[i];
mmax = max(mmax, tmp);
}
// extent midmax-subarray from mid to right
tmp = mmax;
for (int i = mid + 1; i <= right; ++i) { // must be <=, not <
tmp += nums[i];
mmax = max(mmax, tmp);
}
return max(mmax, max(lmax, rmax));
}
};
|
#include "Node.h"
template <class T>
Node<T>::Node(T value)
{
this->data = value;
}
template <class T>
Node<T>::~Node()
{
delete this->next;
}
template <class T>
T Node<T>::getData() const
{
return this->data;
}
template <class T>
void Node<T>::setData(T data)
{
this->data = data;
}
template <class T>
Node<T>* Node<T>::getNext()
{
return this->next;
}
template <class T>
void Node<T>::setNext(Node<T>* next)
{
this->next = next;
}
|
//! Bismillahi-Rahamanirahim.
/** ========================================**
** @Author: Md. Abu Farhad ( RUET, CSE'15)
** @Category:
/** ========================================**/
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
#define ll long long
#define scl(n) scanf("%lld", &n)
#define scc(c) scanf(" %c", &c);
#define fr(i,n) for (ll i=0;i<n;i++)
#define fr1(i,n) for(ll i=1;i<=n;i++)
#define pfl(x) printf("%lld\n",x)
#define pb push_back
#define l(s) s.size()
#define asort(a) sort(a,a+n)
#define all(x) (x).begin(), (x).end()
#define dsort(a) sort(a,a+n,greater<int>())
#define vasort(v) sort(v.begin(), v.end());
#define vdsort(v) sort(v.begin(), v.end(),greater<int>());
int main()
{
ll m,n,t,i,j,k,x,y,z,l,q,r;
cin>>t;
while(t--){
ll a,b,c,d;
cin>>a>>b>>c>>d;
ll cnt=0;
ll tmp=d%c;
ll vag=d/c;
if(vag>a )
{
k=a*c;
if(k+b >=d)cnt=1;
}
else if( vag<=a)
{
k=vag*c;
if(k+b >=d)cnt=1;
}
else if(tmp !=0)if(tmp <=b )cnt=1;
else if(tmp ==0 and vag <=a)cnt=1;
if(cnt==1 or d<=b )cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
|
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct line
{
int l,r;
int value;
};
int dp[1000001];
bool cmp(const line &a,const line &b)
{
return a.r<b.r;
}
line l[1000];
int main()
{
int n;
cin >>n;
for(int j=0;j<=1000000;j++)
{
dp[j]=0;
}
for(int i=0;i<n;i++)
{
cin >>l[i].l>>l[i].r>>l[i].value;
}
sort(l,l+n,cmp);
for(int i=0;i<n;i++)
{
for(int j=0;j<l[i].l;j++)
{
dp[l[i].r]=max(dp[l[i].r],dp[j]+l[i].value);
}
}
int ans=0;
for(int i=0;i<=1000000;i++)
{
ans=max(ans,dp[i]);
}
cout <<ans<<endl;
return 0;
}
|
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
int delete_node(struct node *);
int push(struct node **,int);
int print(struct node *);
int main(){
struct node* head=NULL;
push(&head,23);
push(&head,65);
push(&head,11);
push(&head,33);
printf("before delete\n");
print(head);
delete_node(head);
printf("\nafter delete\n");
print(head);
}
int push(struct node **head_ref,int new_data){
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp->data=new_data;
temp->next=*head_ref;
*head_ref=temp;
}
int print(struct node* head){
struct node *temp=head;
while(temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
}
int delete_node(struct node *node_ptr){
struct node *temp=node_ptr->next;
node_ptr->data=temp->data;
node_ptr->next=temp->next;
free(temp);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.