blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c8782cefd7047e26f43ec18bba5dabc10e8b0f71 | 675c821072436a56ee1f9678c50abb6a87bfc9ea | /MUZ/muzlib/MUZ-Common/StrUtils.h | e3201b72338e2c0b0aef6e9e2307a71398e58950 | [] | no_license | bkg2018/MUZ-Workshop | f4e95b491e9be3f4f0842a978aaff1d647e87b8d | ebb133dccb43d984928b67f3a7cf02d4fa49b2a0 | refs/heads/master | 2021-07-16T00:09:00.178200 | 2020-05-28T14:38:32 | 2020-05-28T14:38:32 | 162,558,361 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,983 | h | StrUtils.h | //
// StrUtils.h
// MUZ-Workshop
//
// Created by Francis Pierot on 04/12/2018.
// Copyright © 2018 Francis Pierot. All rights reserved.
//
#ifndef StrUtils_h
#define StrUtils_h
#include "Types.h"
#include <string>
/** add to_string() on MUZ addresses, extension to std namespace */
namespace std {
string to_string(MUZ::ADDRESSTYPE address);
string to_upper(string);
} // namespace std
/** Checks if a string contains only hexadecimal characters. */
bool isHexa(std::string s);
/** Checks if a string contains only octal characters. */
bool isOctal(std::string s);
/** Checks if a string contains only decimal characters. */
bool isDecimal(std::string s);
/** Checks if a string contains only binary characters. */
bool isBinary(std::string s);
/** Converts a base N number to unsigned int, */
unsigned int base_to_unsigned(std::string s, int base);
/** Converts an hexadecimal number to unsigned int, */
unsigned int hex_to_unsigned(std::string s);
/** Converts a binary number to unsigned int, */
unsigned int bin_to_unsigned(std::string s);
/** Converts an octal number to unsigned int, */
unsigned int oct_to_unsigned(std::string s);
/** Converts a decimal number string to unsigned int, */
unsigned int dec_to_unsigned(std::string s);
/** Converts an address to an hexa, octal or binary string. */
std::string address_to_base(unsigned int address, unsigned int base, int nbdigits);
/** Converts a byte to an hexa string. */
std::string data_to_hex(MUZ::DATATYPE data);
/** Converts a 0-15 value in hexadecimal character '0' to 'F'. */
char byte_to_hexchar(unsigned int b);
/** Tells if a character is a binary digit. */
inline bool isBinDigit(char c) { return c == '0' || c == '1'; }
/** Tells if a character is an octal digit. */
inline bool isDecDigit(char c) { return c >= '0' && c <= '9'; }
/** Tells if a character is a decimal digit. */
inline bool isOctDigit(char c) { return c >= '0' && c <= '7'; }
/** Tells if a character is an hexadecimal digit. */
inline bool isHexDigit(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); }
/** Unescapes the escape sequences in a character string.
Escape sequences begin with a \ backshlash and are followed by:
'\t' : replaced by the $09 tabulation character
'\n' : replaced by 0x0D carriage return
'\r' : replaced by 0x0A line feed
'*' : replaced by joker 0x1A (ASCII SUB) if joker flag is true
'\*' : replaced by star (cancels jokering)
'\\' : replaced by a single backslash
'\h' : replaced by 0x08 del character
'\NNN': replaced by the character with decimal code NNN if doesn't start with a 0 (max 255)
'\xHH': replaced by the character with hexadecimal code 0xHH (max 0xFF)
'\0NNN' : replaced by the character with octal code 0NNN (max 0377)
*/
std::string unescape(std::string s, bool joker);
/** Trim spaces at the end */
void strtrimright(std::string& s);
/** returns a string with a number of spaces */
std::string spaces(int number);
/** Read a line of file until a null, a \r or a \r\n is found. */
bool fgetline(MUZ::BYTE** buffer, int *length, FILE* f);
/** Split a file path into path and filename parts. */
bool splitpath(std::string filepath, std::string& path, std::string& name);
/** Returns the uppercase of a character if it is a letter. Returns unchanged character for anything else. */
char upperchar(char c);
extern const char NORMAL_DIR_SEPARATOR; // Windows backslash and UNIXes slash
extern const char OTHER_DIR_SEPARATOR; // slash allowed on Windows, and backslash will be changed to slash on UNIXes
extern const char ALTERNATE_ROOTDIR; // '~' on UNIXes, '\0' elsewhere
/** HEX files support. */
MUZ::ADDRESSSIZETYPE hexNbBytes(const MUZ::BYTE* hexline);
bool hexEOF(const MUZ::BYTE* hexline);
MUZ::ADDRESSTYPE hexAddress(const MUZ::BYTE* hexline);
int hexType(const MUZ::BYTE* hexline);
void hexStore(const MUZ::BYTE* hexline, MUZ::DATATYPE* buffer);
MUZ::BYTE hex2byte(const MUZ::BYTE* p);
#endif /* StrUtils_h */
|
bbe54ad67a2879a10871870a468637f2432f0334 | bca382e0fc9860969f77fefb9b7ed2c3eeacdd66 | /bond specific classes/GUIService.hpp | 9b0bd7b91e5a3ec04307b099cf7d852b9f28c9c9 | [] | no_license | ssh352/MTH9815Final----Trading-System | 40cd35663e911f66a4e9ece6edf6a9149fb1daf4 | f65c2c44480455261a6a738472fe13e7a4254604 | refs/heads/master | 2022-03-24T16:45:17.932916 | 2019-12-27T03:00:47 | 2019-12-27T03:00:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,802 | hpp | GUIService.hpp | /**
* GUISERVICE_HPP
*
* @author Bin Zhu
*/
#pragma once
#ifndef GUISERVICE_HPP
#define GUISERVICE_HPP
#include "boost/date_time/posix_time/posix_time.hpp"
#include <boost/date_time.hpp>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include "pricingservice.hpp"
#include "soa.hpp"
using namespace boost::posix_time;
using namespace std;
//PriceWithTimeStamp
class TimeStampPrice : public Price<Bond> {
private:
ptime timeStamp;
public:
TimeStampPrice(ptime _timeStamp, Price<Bond> _price)
:Price<Bond>(_price) {
timeStamp = _timeStamp;
}
ptime GetTimeStamp() {
return timeStamp;
}
};
//Connector
class GUIServiceConnector : public Connector<TimeStampPrice > {
public:
// constructor
GUIServiceConnector() {};
virtual void Publish(TimeStampPrice& data) override;
virtual void Subscribe() override {}
};
void GUIServiceConnector::Publish(TimeStampPrice& data) {
auto timeStamp = data.GetTimeStamp();
auto bond = data.GetProduct();
auto mid = data.GetMid();
auto spread = data.GetBidOfferSpread();
ofstream out;
out.open("gui.txt", ios::app);
out << timeStamp << "," << bond.GetProductId() << "," << mid << "," << spread << endl;
return;
}
class GUIService:public PricingService<Bond> {
private:
GUIServiceConnector* gUIServiceConnector;
ptime last;
time_duration throtteTime;
public:
// constructor
GUIService(GUIServiceConnector* _gUIServiceConnector);
void Throttle(Price<Bond>& data);
// override class
virtual Price<Bond>& GetData(string id) override {}
virtual void OnMessage(Price<Bond> &data) override{}
virtual void AddListener(ServiceListener<Price<Bond> > *listener) override{}
virtual const vector< ServiceListener<Price<Bond> >* >& GetListeners() const override{}
};
class GUIService;
GUIService::GUIService(GUIServiceConnector* _gUIServiceConnector){
gUIServiceConnector=_gUIServiceConnector;
throtteTime=millisec(3);
last=microsec_clock::local_time();
}
void GUIService::Throttle(Price<Bond>& data) {
ptime Now = microsec_clock::local_time();
time_duration diff = Now - last;
if (diff < throtteTime) {
return;
}
last = Now;
auto pts = TimeStampPrice(Now, data);
gUIServiceConnector->Publish(pts);
return;
}
//Listener
class GUIServiceListener : public ServiceListener<Price<Bond> > {
private:
GUIService* gUIService;
public:
// constructor
GUIServiceListener(GUIService* _gUIService);
// override
virtual void ProcessAdd(Price<Bond>& price) override;
virtual void ProcessRemove(Price<Bond>&) override {};
virtual void ProcessUpdate(Price<Bond>&) override {};
};
GUIServiceListener::GUIServiceListener(GUIService* _gUIService) {
gUIService = _gUIService;
}
void GUIServiceListener::ProcessAdd(Price<Bond>& price) {
gUIService->Throttle(price);
return;
}
#endif |
1680a0889fd76bb1251e72dc2214456caa1e8cd3 | c29ea02c80cd4e9ee1280dff2ca202221eef8f2a | /G53GRA-Coursework/Code/Lighting/Lantern.cpp | d17dad88a586cdaaca366a9834215dc0880ce3d0 | [] | no_license | BadgerCode/G53GRA-Coursework | 25708a5fe60d3a69581353fbe1c792b2cce2b373 | 3daa1cfd9d2fa36cac7cc27a0e260879f7f974f4 | refs/heads/master | 2021-03-19T06:46:16.789322 | 2020-03-03T12:59:18 | 2020-03-03T13:00:21 | 89,589,833 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 302 | cpp | Lantern.cpp | #include "Lantern.h"
Lantern::Lantern( float x, float y, float z) : Fire(x, y, z)
{
SetOrbDrawing(false);
SetAmbience(1.f, 1.f, 0.9f, 1.f);
SetDiffuse(1.f, 1.f, 0.5f, 1.f);
SetSpecular(1.f, 1.f, 1.f, 1.f);
SetDistance(150.f);
SetMaxEmberHeight(10.f);
SetMaxEmbers(3);
SetEmberRadius(0.25);
}
|
1d731897707be4ad1d9466053d06efb87a3e7f9d | b4af26ef6994f4cbb738cdfd182e0a992d2e5baa | /source/leetcode/2309/신입.cpp | 69d9b3ec5242339959cb7f0a0249a1c7a0e1e644 | [] | no_license | wisest30/AlgoStudy | 6819b193c8e9245104fc52df5852cd487ae7a26e | 112de912fc10933445c2ad36ce30fd404c493ddf | refs/heads/master | 2023-08-08T17:01:12.324470 | 2023-08-06T11:54:15 | 2023-08-06T11:54:15 | 246,302,438 | 10 | 17 | null | 2021-09-26T13:52:18 | 2020-03-10T13:02:56 | C++ | UTF-8 | C++ | false | false | 300 | cpp | 신입.cpp | class Solution {
public:
string greatestLetter(string s) {
bool exist[256]{};
for(char ch : s) exist[ch] = true;
for(int i=25;i>=0;i--)
{
if(exist[i+'a'] && exist[i+'A']) return string(1, i+'A');
}
return "";
}
};
|
381db8ce7126e8864b4dc98826460763c8754e30 | 6093d435261473aaf0763fc9ea020a2d01be0561 | /30-Day_LeetCoding_Challenge_May_2020/Week_1/Jewels_and_Stones.cpp | 6dddad2fa92bd5f8ee35606d4dfaa03d9ca26dd9 | [] | no_license | master-fury/Leet_Code | 377bf316b4ac4113fa99bd4c8eee703369db3a74 | 753da44ff8a142642e30ccbe2baeef3e4b2b4874 | refs/heads/master | 2022-07-09T18:14:49.920210 | 2020-05-10T18:06:56 | 2020-05-10T18:06:56 | 260,646,406 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 274 | cpp | Jewels_and_Stones.cpp | class Solution {
public:
int numJewelsInStones(string J, string S) {
int count =0;
for (char ch:J){
for (int i = 0; i < S.size(); i++){
if (ch == S[i])
++ count;
}
}
return count;
}
}; |
2660d32b975cd494be0defa5c4824f6c331e18b3 | e374f0f4f958434cc515e67b494b1115b28389ad | /Source/DGame/Private/UI/DMainUI.cpp | 79a3ce687ffee874ba333afe9863dc86d1845ab2 | [] | no_license | Duadua/DGame | 4f9e10111a53c094fa8f897d6e88821634da2e4c | 2f171399b81d636a9e53a777771b44c7b9c2867a | refs/heads/master | 2020-03-24T03:28:12.710823 | 2018-07-29T16:57:44 | 2018-07-29T16:57:44 | 140,232,937 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 443 | cpp | DMainUI.cpp | #include "DMainUI.h"
#include "DGame.h"
bool UDMainUI::Initialize() {
if (!Super::Initialize()) return false;
init();
return true;
}
void UDMainUI::init()
{
m_login_bt = Cast<UButton>(GetWidgetFromName(TEXT("bt_login")));
m_localin_bt = Cast<UButton>(GetWidgetFromName(TEXT("bt_localin")));
m_option_bt = Cast<UButton>(GetWidgetFromName(TEXT("bt_option")));
m_exit_bt = Cast<UButton>(GetWidgetFromName(TEXT("bt_exit")));
}
|
56ff3900fb4c10c4ba621bea2f1a94176b338f0a | 7a20b3db1a185ecdf12ad86f38edaa03742abd7b | /src/pipe/SkPipeReader.cpp | ada4a21342800a43ae5702a8b0eb0dad75b99dd3 | [
"BSD-3-Clause"
] | permissive | revery-ui/esy-skia | 7ef96ceeca94d001264684b7dc1ac24db0381ad4 | 29349b9279ed24a73ec41acd7082caea9bd8c04e | refs/heads/master | 2022-05-29T17:50:23.722723 | 2022-04-02T09:37:52 | 2022-04-02T09:37:52 | 203,015,081 | 24 | 26 | BSD-3-Clause | 2022-04-02T09:37:52 | 2019-08-18T14:24:21 | C++ | UTF-8 | C++ | false | false | 33,460 | cpp | SkPipeReader.cpp | /*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkCanvas.h"
#include "SkCanvasPriv.h"
#include "SkDeduper.h"
#include "SkDrawShadowInfo.h"
#include "SkPicture.h"
#include "SkPictureRecorder.h"
#include "SkPipe.h"
#include "SkPipeFormat.h"
#include "SkReadBuffer.h"
#include "SkRefSet.h"
#include "SkRSXform.h"
#include "SkTextBlob.h"
#include "SkTypeface.h"
#include "SkVertices.h"
class SkPipeReader;
static bool do_playback(SkPipeReader& reader, SkCanvas* canvas, int* endPictureIndex = nullptr);
///////////////////////////////////////////////////////////////////////////////////////////////////
class SkPipeInflator : public SkInflator {
public:
SkPipeInflator(SkRefSet<SkImage>* images, SkRefSet<SkPicture>* pictures,
SkRefSet<SkTypeface>* typefaces, SkTDArray<SkFlattenable::Factory>* factories,
const SkDeserialProcs& procs)
: fImages(images)
, fPictures(pictures)
, fTypefaces(typefaces)
, fFactories(factories)
, fProcs(procs)
{}
SkImage* getImage(int index) override {
return index ? fImages->get(index - 1) : nullptr;
}
SkPicture* getPicture(int index) override {
return index ? fPictures->get(index - 1) : nullptr;
}
SkTypeface* getTypeface(int index) override {
return fTypefaces->get(index - 1);
}
SkFlattenable::Factory getFactory(int index) override {
return index ? fFactories->getAt(index - 1) : nullptr;
}
bool setImage(int index, SkImage* img) {
return fImages->set(index - 1, img);
}
bool setPicture(int index, SkPicture* pic) {
return fPictures->set(index - 1, pic);
}
bool setTypeface(int index, SkTypeface* face) {
return fTypefaces->set(index - 1, face);
}
bool setFactory(int index, SkFlattenable::Factory factory) {
SkASSERT(index > 0);
SkASSERT(factory);
index -= 1;
if ((unsigned)index < (unsigned)fFactories->count()) {
(*fFactories)[index] = factory;
return true;
}
if (fFactories->count() == index) {
*fFactories->append() = factory;
return true;
}
SkDebugf("setFactory: index [%d] out of range %d\n", index, fFactories->count());
return false;
}
void setDeserialProcs(const SkDeserialProcs& procs) {
fProcs = procs;
}
sk_sp<SkTypeface> makeTypeface(const void* data, size_t size);
sk_sp<SkImage> makeImage(const sk_sp<SkData>&);
private:
SkRefSet<SkImage>* fImages;
SkRefSet<SkPicture>* fPictures;
SkRefSet<SkTypeface>* fTypefaces;
SkTDArray<SkFlattenable::Factory>* fFactories;
SkDeserialProcs fProcs;
};
///////////////////////////////////////////////////////////////////////////////////////////////////
static SkRRect read_rrect(SkReadBuffer& reader) {
SkRRect rrect;
rrect.readFromMemory(reader.skip(SkRRect::kSizeInMemory), SkRRect::kSizeInMemory);
return rrect;
}
static SkMatrix read_sparse_matrix(SkReadBuffer& reader, SkMatrix::TypeMask tm) {
SkMatrix matrix;
matrix.reset();
if (tm & SkMatrix::kPerspective_Mask) {
matrix.set9(reader.skipT<SkScalar>(9));
} else if (tm & SkMatrix::kAffine_Mask) {
const SkScalar* tmp = reader.skipT<SkScalar>(6);
matrix[SkMatrix::kMScaleX] = tmp[0];
matrix[SkMatrix::kMSkewX] = tmp[1];
matrix[SkMatrix::kMTransX] = tmp[2];
matrix[SkMatrix::kMScaleY] = tmp[3];
matrix[SkMatrix::kMSkewY] = tmp[4];
matrix[SkMatrix::kMTransY] = tmp[5];
} else if (tm & SkMatrix::kScale_Mask) {
const SkScalar* tmp = reader.skipT<SkScalar>(4);
matrix[SkMatrix::kMScaleX] = tmp[0];
matrix[SkMatrix::kMTransX] = tmp[1];
matrix[SkMatrix::kMScaleY] = tmp[2];
matrix[SkMatrix::kMTransY] = tmp[3];
} else if (tm & SkMatrix::kTranslate_Mask) {
const SkScalar* tmp = reader.skipT<SkScalar>(2);
matrix[SkMatrix::kMTransX] = tmp[0];
matrix[SkMatrix::kMTransY] = tmp[1];
}
// else read nothing for Identity
return matrix;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#define CHECK_SET_SCALAR(Field) \
do { if (nondef & k##Field##_NonDef) { \
paint.set##Field(reader.readScalar()); \
}} while (0)
#define CHECK_SET_FLATTENABLE(Field) \
do { if (nondef & k##Field##_NonDef) { \
paint.set##Field(reader.read##Field()); \
}} while (0)
/*
* Header:
* paint flags : 32
* non_def bits : 16
* xfermode enum : 8
* pad zeros : 8
*/
static SkPaint read_paint(SkReadBuffer& reader) {
SkPaint paint;
uint32_t packedFlags = reader.read32();
uint32_t extra = reader.read32();
unsigned nondef = extra >> 16;
paint.setBlendMode(SkBlendMode((extra >> 8) & 0xFF));
SkASSERT((extra & 0xFF) == 0); // zero pad byte
packedFlags >>= 2; // currently unused
paint.setTextEncoding((SkPaint::TextEncoding)(packedFlags & 3)); packedFlags >>= 2;
paint.setTextAlign((SkPaint::Align)(packedFlags & 3)); packedFlags >>= 2;
paint.setHinting((SkPaint::Hinting)(packedFlags & 3)); packedFlags >>= 2;
paint.setStrokeJoin((SkPaint::Join)(packedFlags & 3)); packedFlags >>= 2;
paint.setStrokeCap((SkPaint::Cap)(packedFlags & 3)); packedFlags >>= 2;
paint.setStyle((SkPaint::Style)(packedFlags & 3)); packedFlags >>= 2;
paint.setFilterQuality((SkFilterQuality)(packedFlags & 3)); packedFlags >>= 2;
paint.setFlags(packedFlags);
CHECK_SET_SCALAR(TextSize);
CHECK_SET_SCALAR(TextScaleX);
CHECK_SET_SCALAR(TextSkewX);
CHECK_SET_SCALAR(StrokeWidth);
CHECK_SET_SCALAR(StrokeMiter);
if (nondef & kColor_NonDef) {
paint.setColor(reader.read32());
}
CHECK_SET_FLATTENABLE(Typeface);
CHECK_SET_FLATTENABLE(PathEffect);
CHECK_SET_FLATTENABLE(Shader);
CHECK_SET_FLATTENABLE(MaskFilter);
CHECK_SET_FLATTENABLE(ColorFilter);
CHECK_SET_FLATTENABLE(ImageFilter);
CHECK_SET_FLATTENABLE(DrawLooper);
return paint;
}
class SkPipeReader : public SkReadBuffer {
public:
SkPipeReader(SkPipeDeserializer* sink, const void* data, size_t size)
: SkReadBuffer(data, size)
, fSink(sink)
{}
SkPipeDeserializer* fSink;
SkFlattenable::Factory findFactory(const char name[]) {
SkFlattenable::Factory factory;
// Check if a custom Factory has been specified for this flattenable.
if (!(factory = this->getCustomFactory(SkString(name)))) {
// If there is no custom Factory, check for a default.
factory = SkFlattenable::NameToFactory(name);
}
return factory;
}
bool readPaint(SkPaint* paint) override {
*paint = read_paint(*this);
return this->isValid();
}
};
///////////////////////////////////////////////////////////////////////////////////////////////////
typedef void (*SkPipeHandler)(SkPipeReader&, uint32_t packedVerb, SkCanvas*);
static void save_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kSave == unpack_verb(packedVerb));
canvas->save();
}
static void saveLayer_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kSaveLayer == unpack_verb(packedVerb));
unsigned extra = unpack_verb_extra(packedVerb);
const SkRect* bounds = (extra & kHasBounds_SaveLayerMask) ? reader.skipT<SkRect>() : nullptr;
SkPaint paintStorage, *paint = nullptr;
if (extra & kHasPaint_SaveLayerMask) {
paintStorage = read_paint(reader);
paint = &paintStorage;
}
sk_sp<SkImageFilter> backdrop;
if (extra & kHasBackdrop_SaveLayerMask) {
backdrop = reader.readImageFilter();
}
sk_sp<SkImage> clipMask;
if (extra & kHasClipMask_SaveLayerMask) {
clipMask = reader.readImage();
}
SkMatrix clipMatrix;
if (extra & kHasClipMatrix_SaveLayerMask) {
reader.readMatrix(&clipMatrix);
}
SkCanvas::SaveLayerFlags flags = (SkCanvas::SaveLayerFlags)(extra & kFlags_SaveLayerMask);
// unremap this wacky flag
if (extra & kDontClipToLayer_SaveLayerMask) {
flags |= SkCanvasPriv::kDontClipToLayer_SaveLayerFlag;
}
canvas->saveLayer(SkCanvas::SaveLayerRec(bounds, paint, backdrop.get(), clipMask.get(),
(extra & kHasClipMatrix_SaveLayerMask) ? &clipMatrix : nullptr, flags));
}
static void restore_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kRestore == unpack_verb(packedVerb));
canvas->restore();
}
static void concat_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kConcat == unpack_verb(packedVerb));
SkMatrix::TypeMask tm = (SkMatrix::TypeMask)(packedVerb & kTypeMask_ConcatMask);
const SkMatrix matrix = read_sparse_matrix(reader, tm);
if (packedVerb & kSetMatrix_ConcatMask) {
canvas->setMatrix(matrix);
} else {
canvas->concat(matrix);
}
}
static void clipRect_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kClipRect == unpack_verb(packedVerb));
SkClipOp op = (SkClipOp)(unpack_verb_extra(packedVerb) >> 1);
bool isAA = unpack_verb_extra(packedVerb) & 1;
canvas->clipRect(*reader.skipT<SkRect>(), op, isAA);
}
static void clipRRect_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kClipRRect == unpack_verb(packedVerb));
SkClipOp op = (SkClipOp)(unpack_verb_extra(packedVerb) >> 1);
bool isAA = unpack_verb_extra(packedVerb) & 1;
canvas->clipRRect(read_rrect(reader), op, isAA);
}
static void clipPath_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kClipPath == unpack_verb(packedVerb));
SkClipOp op = (SkClipOp)(unpack_verb_extra(packedVerb) >> 1);
bool isAA = unpack_verb_extra(packedVerb) & 1;
SkPath path;
reader.readPath(&path);
canvas->clipPath(path, op, isAA);
}
static void clipRegion_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kClipRegion == unpack_verb(packedVerb));
SkClipOp op = (SkClipOp)(unpack_verb_extra(packedVerb) >> 1);
SkRegion region;
reader.readRegion(®ion);
canvas->clipRegion(region, op);
}
static void drawArc_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawArc == unpack_verb(packedVerb));
const bool useCenter = (bool)(unpack_verb_extra(packedVerb) & 1);
const SkScalar* scalars = reader.skipT<SkScalar>(6); // bounds[0..3], start[4], sweep[5]
const SkRect* bounds = (const SkRect*)scalars;
canvas->drawArc(*bounds, scalars[4], scalars[5], useCenter, read_paint(reader));
}
static void drawAtlas_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawAtlas == unpack_verb(packedVerb));
SkBlendMode mode = (SkBlendMode)(packedVerb & kMode_DrawAtlasMask);
sk_sp<SkImage> image(reader.readImage());
int count = reader.read32();
const SkRSXform* xform = reader.skipT<SkRSXform>(count);
const SkRect* rect = reader.skipT<SkRect>(count);
const SkColor* color = nullptr;
if (packedVerb & kHasColors_DrawAtlasMask) {
color = reader.skipT<SkColor>(count);
}
const SkRect* cull = nullptr;
if (packedVerb & kHasCull_DrawAtlasMask) {
cull = reader.skipT<SkRect>();
}
SkPaint paintStorage, *paint = nullptr;
if (packedVerb & kHasPaint_DrawAtlasMask) {
paintStorage = read_paint(reader);
paint = &paintStorage;
}
canvas->drawAtlas(image, xform, rect, color, count, mode, cull, paint);
}
static void drawDRRect_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawDRRect == unpack_verb(packedVerb));
const SkRRect outer = read_rrect(reader);
const SkRRect inner = read_rrect(reader);
canvas->drawDRRect(outer, inner, read_paint(reader));
}
static void drawText_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawText == unpack_verb(packedVerb));
uint32_t len = unpack_verb_extra(packedVerb);
if (0 == len) {
len = reader.read32();
}
const void* text = reader.skip(SkAlign4(len));
SkScalar x = reader.readScalar();
SkScalar y = reader.readScalar();
canvas->drawText(text, len, x, y, read_paint(reader));
}
static void drawPosText_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawPosText == unpack_verb(packedVerb));
uint32_t len = unpack_verb_extra(packedVerb);
if (0 == len) {
len = reader.read32();
}
const void* text = reader.skip(SkAlign4(len));
int count = reader.read32();
const SkPoint* pos = reader.skipT<SkPoint>(count);
SkPaint paint = read_paint(reader);
SkASSERT(paint.countText(text, len) == count);
canvas->drawPosText(text, len, pos, paint);
}
static void drawPosTextH_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawPosTextH == unpack_verb(packedVerb));
uint32_t len = unpack_verb_extra(packedVerb);
if (0 == len) {
len = reader.read32();
}
const void* text = reader.skip(SkAlign4(len));
int count = reader.read32();
const SkScalar* xpos = reader.skipT<SkScalar>(count);
SkScalar constY = reader.readScalar();
SkPaint paint = read_paint(reader);
SkASSERT(paint.countText(text, len) == count);
canvas->drawPosTextH(text, len, xpos, constY, paint);
}
static void drawTextOnPath_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawTextOnPath == unpack_verb(packedVerb));
uint32_t byteLength = packedVerb & kTextLength_DrawTextOnPathMask;
SkMatrix::TypeMask tm = (SkMatrix::TypeMask)
((packedVerb & kMatrixType_DrawTextOnPathMask) >> kMatrixType_DrawTextOnPathShift);
if (0 == byteLength) {
byteLength = reader.read32();
}
const void* text = reader.skip(SkAlign4(byteLength));
SkPath path;
reader.readPath(&path);
const SkMatrix* matrix = nullptr;
SkMatrix matrixStorage;
if (tm != SkMatrix::kIdentity_Mask) {
matrixStorage = read_sparse_matrix(reader, tm);
matrix = &matrixStorage;
}
canvas->drawTextOnPath(text, byteLength, path, matrix, read_paint(reader));
}
static void drawTextBlob_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
sk_sp<SkTextBlob> tb = SkTextBlob::MakeFromBuffer(reader);
SkScalar x = reader.readScalar();
SkScalar y = reader.readScalar();
canvas->drawTextBlob(tb, x, y, read_paint(reader));
}
static void drawTextRSXform_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawTextRSXform == unpack_verb(packedVerb));
uint32_t len = unpack_verb_extra(packedVerb) >> 1;
if (0 == len) {
len = reader.read32();
}
const void* text = reader.skip(SkAlign4(len));
int count = reader.read32();
const SkRSXform* xform = reader.skipT<SkRSXform>(count);
const SkRect* cull = (packedVerb & 1) ? reader.skipT<SkRect>() : nullptr;
SkPaint paint = read_paint(reader);
SkASSERT(paint.countText(text, len) == count);
canvas->drawTextRSXform(text, len, xform, cull, paint);
}
static void drawPatch_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawPatch == unpack_verb(packedVerb));
const SkColor* colors = nullptr;
const SkPoint* tex = nullptr;
const SkPoint* cubics = reader.skipT<SkPoint>(12);
if (packedVerb & kHasColors_DrawPatchExtraMask) {
colors = reader.skipT<SkColor>(4);
}
if (packedVerb & kHasTexture_DrawPatchExtraMask) {
tex = reader.skipT<SkPoint>(4);
}
SkBlendMode mode = (SkBlendMode)(packedVerb & kModeEnum_DrawPatchExtraMask);
canvas->drawPatch(cubics, colors, tex, mode, read_paint(reader));
}
static void drawPaint_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawPaint == unpack_verb(packedVerb));
canvas->drawPaint(read_paint(reader));
}
static void drawRect_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawRect == unpack_verb(packedVerb));
const SkRect* rect = reader.skipT<SkRect>();
canvas->drawRect(*rect, read_paint(reader));
}
static void drawRegion_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawRegion == unpack_verb(packedVerb));
size_t size = unpack_verb_extra(packedVerb);
if (0 == size) {
size = reader.read32();
}
SkRegion region;
region.readFromMemory(reader.skipT<char>(size), size);
canvas->drawRegion(region, read_paint(reader));
}
static void drawOval_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawOval == unpack_verb(packedVerb));
const SkRect* rect = reader.skipT<SkRect>();
canvas->drawOval(*rect, read_paint(reader));
}
static void drawRRect_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawRRect == unpack_verb(packedVerb));
SkRRect rrect = read_rrect(reader);
canvas->drawRRect(rrect, read_paint(reader));
}
static void drawPath_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawPath == unpack_verb(packedVerb));
SkPath path;
reader.readPath(&path);
canvas->drawPath(path, read_paint(reader));
}
static void drawShadowRec_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawShadowRec == unpack_verb(packedVerb));
SkPath path;
reader.readPath(&path);
SkDrawShadowRec rec;
reader.readPad32(&rec, sizeof(rec));
canvas->private_draw_shadow_rec(path, rec);
}
static void drawPoints_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawPoints == unpack_verb(packedVerb));
SkCanvas::PointMode mode = (SkCanvas::PointMode)unpack_verb_extra(packedVerb);
int count = reader.read32();
const SkPoint* points = reader.skipT<SkPoint>(count);
canvas->drawPoints(mode, count, points, read_paint(reader));
}
static void drawImage_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawImage == unpack_verb(packedVerb));
sk_sp<SkImage> image(reader.readImage());
SkScalar x = reader.readScalar();
SkScalar y = reader.readScalar();
SkPaint paintStorage, *paint = nullptr;
if (packedVerb & kHasPaint_DrawImageMask) {
paintStorage = read_paint(reader);
paint = &paintStorage;
}
canvas->drawImage(image, x, y, paint);
}
static void drawImageRect_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawImageRect == unpack_verb(packedVerb));
sk_sp<SkImage> image(reader.readImage());
SkCanvas::SrcRectConstraint constraint =
(SkCanvas::SrcRectConstraint)(packedVerb & kConstraint_DrawImageRectMask);
const SkRect* src = (packedVerb & kHasSrcRect_DrawImageRectMask) ?
reader.skipT<SkRect>() : nullptr;
const SkRect* dst = reader.skipT<SkRect>();
SkPaint paintStorage, *paint = nullptr;
if (packedVerb & kHasPaint_DrawImageRectMask) {
paintStorage = read_paint(reader);
paint = &paintStorage;
}
if (src) {
canvas->drawImageRect(image, *src, *dst, paint, constraint);
} else {
canvas->drawImageRect(image, *dst, paint);
}
}
static void drawImageNine_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawImageNine == unpack_verb(packedVerb));
sk_sp<SkImage> image(reader.readImage());
const SkIRect* center = reader.skipT<SkIRect>();
const SkRect* dst = reader.skipT<SkRect>();
SkPaint paintStorage, *paint = nullptr;
if (packedVerb & kHasPaint_DrawImageNineMask) {
paintStorage = read_paint(reader);
paint = &paintStorage;
}
canvas->drawImageNine(image, *center, *dst, paint);
}
static void drawImageLattice_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawImageLattice == unpack_verb(packedVerb));
sk_sp<SkImage> image(reader.readImage());
SkCanvas::Lattice lattice;
if (!SkCanvasPriv::ReadLattice(reader, &lattice)) {
return;
}
const SkRect* dst = reader.skipT<SkRect>();
SkPaint paintStorage, *paint = nullptr;
if (packedVerb & kHasPaint_DrawImageLatticeMask) {
paintStorage = read_paint(reader);
paint = &paintStorage;
}
canvas->drawImageLattice(image.get(), lattice, *dst, paint);
}
static void drawVertices_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawVertices == unpack_verb(packedVerb));
SkBlendMode bmode = (SkBlendMode)unpack_verb_extra(packedVerb);
if (sk_sp<SkData> data = reader.readByteArrayAsData()) {
canvas->drawVertices(SkVertices::Decode(data->data(), data->size()), bmode,
read_paint(reader));
}
}
static void drawPicture_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawPicture == unpack_verb(packedVerb));
unsigned extra = unpack_verb_extra(packedVerb);
int index = extra & kIndex_ObjectDefinitionMask;
SkPicture* pic = reader.getInflator()->getPicture(index);
SkMatrix matrixStorage, *matrix = nullptr;
SkPaint paintStorage, *paint = nullptr;
if (extra & kHasMatrix_DrawPictureExtra) {
reader.readMatrix(&matrixStorage);
matrix = &matrixStorage;
}
if (extra & kHasPaint_DrawPictureExtra) {
paintStorage = read_paint(reader);
paint = &paintStorage;
}
canvas->drawPicture(pic, matrix, paint);
}
static void drawAnnotation_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDrawAnnotation == unpack_verb(packedVerb));
const SkRect* rect = reader.skipT<SkRect>();
// len includes the key's trailing 0
uint32_t len = unpack_verb_extra(packedVerb) >> 1;
if (0 == len) {
len = reader.read32();
}
const char* key = reader.skipT<char>(len);
sk_sp<SkData> data;
if (packedVerb & 1) {
uint32_t size = reader.read32();
data = SkData::MakeWithCopy(reader.skip(SkAlign4(size)), size);
}
canvas->drawAnnotation(*rect, key, data);
}
#if 0
stream.write("skiacodc", 8);
stream.write32(pmap.width());
stream.write32(pmap.height());
stream.write16(pmap.colorType());
stream.write16(pmap.alphaType());
stream.write32(0); // no colorspace for now
for (int y = 0; y < pmap.height(); ++y) {
stream.write(pmap.addr8(0, y), pmap.width());
}
#endif
sk_sp<SkImage> SkPipeInflator::makeImage(const sk_sp<SkData>& data) {
if (fProcs.fImageProc) {
return fProcs.fImageProc(data->data(), data->size(), fProcs.fImageCtx);
}
return SkImage::MakeFromEncoded(data);
}
static void defineImage_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas*) {
SkASSERT(SkPipeVerb::kDefineImage == unpack_verb(packedVerb));
SkPipeInflator* inflator = (SkPipeInflator*)reader.getInflator();
uint32_t extra = unpack_verb_extra(packedVerb);
int index = extra & kIndex_ObjectDefinitionMask;
if (extra & kUndef_ObjectDefinitionMask) {
// zero-index means we are "forgetting" that cache entry
inflator->setImage(index, nullptr);
} else {
// we are defining a new image
sk_sp<SkData> data = reader.readByteArrayAsData();
sk_sp<SkImage> image = data ? inflator->makeImage(data) : nullptr;
if (!image) {
SkDebugf("-- failed to decode\n");
}
inflator->setImage(index, image.get());
}
}
sk_sp<SkTypeface> SkPipeInflator::makeTypeface(const void* data, size_t size) {
if (fProcs.fTypefaceProc) {
return fProcs.fTypefaceProc(data, size, fProcs.fTypefaceCtx);
}
SkMemoryStream stream(data, size, false);
return SkTypeface::MakeDeserialize(&stream);
}
static void defineTypeface_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDefineTypeface == unpack_verb(packedVerb));
SkPipeInflator* inflator = (SkPipeInflator*)reader.getInflator();
uint32_t extra = unpack_verb_extra(packedVerb);
int index = extra & kIndex_ObjectDefinitionMask;
if (extra & kUndef_ObjectDefinitionMask) {
// zero-index means we are "forgetting" that cache entry
inflator->setTypeface(index, nullptr);
} else {
// we are defining a new image
sk_sp<SkData> data = reader.readByteArrayAsData();
// TODO: seems like we could "peek" to see the array, and not need to copy it.
sk_sp<SkTypeface> tf = data ? inflator->makeTypeface(data->data(), data->size()) : nullptr;
inflator->setTypeface(index, tf.get());
}
}
static void defineFactory_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDefineFactory == unpack_verb(packedVerb));
SkPipeInflator* inflator = (SkPipeInflator*)reader.getInflator();
uint32_t extra = unpack_verb_extra(packedVerb);
int index = extra >> kNameLength_DefineFactoryExtraBits;
size_t len = extra & kNameLength_DefineFactoryExtraMask;
// +1 for the trailing null char
const char* name = (const char*)reader.skip(SkAlign4(len + 1));
SkFlattenable::Factory factory = reader.findFactory(name);
if (factory) {
inflator->setFactory(index, factory);
}
}
static void definePicture_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SkASSERT(SkPipeVerb::kDefinePicture == unpack_verb(packedVerb));
int deleteIndex = unpack_verb_extra(packedVerb);
SkPipeInflator* inflator = (SkPipeInflator*)reader.getInflator();
if (deleteIndex) {
inflator->setPicture(deleteIndex - 1, nullptr);
} else {
SkPictureRecorder recorder;
int pictureIndex = -1; // invalid
const SkRect* cull = reader.skipT<SkRect>();
if (!cull) {
return;
}
do_playback(reader, recorder.beginRecording(*cull), &pictureIndex);
SkASSERT(pictureIndex > 0);
sk_sp<SkPicture> picture = recorder.finishRecordingAsPicture();
inflator->setPicture(pictureIndex, picture.get());
}
}
static void endPicture_handler(SkPipeReader& reader, uint32_t packedVerb, SkCanvas* canvas) {
SK_ABORT("not reached"); // never call me
}
///////////////////////////////////////////////////////////////////////////////////////////////////
struct HandlerRec {
SkPipeHandler fProc;
const char* fName;
};
#define HANDLER(name) { name##_handler, #name }
const HandlerRec gPipeHandlers[] = {
HANDLER(save),
HANDLER(saveLayer),
HANDLER(restore),
HANDLER(concat),
HANDLER(clipRect),
HANDLER(clipRRect),
HANDLER(clipPath),
HANDLER(clipRegion),
HANDLER(drawArc),
HANDLER(drawAtlas),
HANDLER(drawDRRect),
HANDLER(drawText),
HANDLER(drawPosText),
HANDLER(drawPosTextH),
HANDLER(drawRegion),
HANDLER(drawTextOnPath),
HANDLER(drawTextBlob),
HANDLER(drawTextRSXform),
HANDLER(drawPatch),
HANDLER(drawPaint),
HANDLER(drawPoints),
HANDLER(drawRect),
HANDLER(drawPath),
HANDLER(drawShadowRec),
HANDLER(drawOval),
HANDLER(drawRRect),
HANDLER(drawImage),
HANDLER(drawImageRect),
HANDLER(drawImageNine),
HANDLER(drawImageLattice),
HANDLER(drawVertices),
HANDLER(drawPicture),
HANDLER(drawAnnotation),
HANDLER(defineImage),
HANDLER(defineTypeface),
HANDLER(defineFactory),
HANDLER(definePicture),
HANDLER(endPicture), // handled special -- should never be called
};
#undef HANDLER
///////////////////////////////////////////////////////////////////////////////////////////////////
class SkPipeDeserializer::Impl {
public:
SkRefSet<SkImage> fImages;
SkRefSet<SkPicture> fPictures;
SkRefSet<SkTypeface> fTypefaces;
SkTDArray<SkFlattenable::Factory> fFactories;
SkDeserialProcs fProcs;
};
SkPipeDeserializer::SkPipeDeserializer() : fImpl(new Impl) {}
SkPipeDeserializer::~SkPipeDeserializer() {}
void SkPipeDeserializer::setDeserialProcs(const SkDeserialProcs& procs) {
fImpl->fProcs = procs;
}
sk_sp<SkImage> SkPipeDeserializer::readImage(const void* data, size_t size) {
if (size < sizeof(uint32_t)) {
SkDebugf("-------- data length too short for readImage %d\n", size);
return nullptr;
}
const uint32_t* ptr = (const uint32_t*)data;
uint32_t packedVerb = *ptr++;
size -= 4;
if (SkPipeVerb::kDefineImage == unpack_verb(packedVerb)) {
SkPipeInflator inflator(&fImpl->fImages, &fImpl->fPictures,
&fImpl->fTypefaces, &fImpl->fFactories,
fImpl->fProcs);
SkPipeReader reader(this, ptr, size);
reader.setInflator(&inflator);
defineImage_handler(reader, packedVerb, nullptr);
packedVerb = reader.read32(); // read the next verb
}
if (SkPipeVerb::kWriteImage != unpack_verb(packedVerb)) {
SkDebugf("-------- unexpected verb for readImage %d\n", unpack_verb(packedVerb));
return nullptr;
}
int index = unpack_verb_extra(packedVerb);
if (0 == index) {
return nullptr; // writer failed
}
return sk_ref_sp(fImpl->fImages.get(index - 1));
}
sk_sp<SkPicture> SkPipeDeserializer::readPicture(const void* data, size_t size) {
if (size < sizeof(uint32_t)) {
SkDebugf("-------- data length too short for readPicture %d\n", size);
return nullptr;
}
const uint32_t* ptr = (const uint32_t*)data;
uint32_t packedVerb = *ptr++;
size -= 4;
if (SkPipeVerb::kDefinePicture == unpack_verb(packedVerb)) {
SkPipeInflator inflator(&fImpl->fImages, &fImpl->fPictures,
&fImpl->fTypefaces, &fImpl->fFactories,
fImpl->fProcs);
SkPipeReader reader(this, ptr, size);
reader.setInflator(&inflator);
definePicture_handler(reader, packedVerb, nullptr);
packedVerb = reader.read32(); // read the next verb
}
if (SkPipeVerb::kWritePicture != unpack_verb(packedVerb)) {
SkDebugf("-------- unexpected verb for readPicture %d\n", unpack_verb(packedVerb));
return nullptr;
}
int index = unpack_verb_extra(packedVerb);
if (0 == index) {
return nullptr; // writer failed
}
return sk_ref_sp(fImpl->fPictures.get(index - 1));
}
static bool do_playback(SkPipeReader& reader, SkCanvas* canvas, int* endPictureIndex) {
int indent = 0;
const bool showEachVerb = false;
int counter = 0;
while (!reader.eof()) {
uint32_t prevOffset = reader.offset();
uint32_t packedVerb = reader.read32();
SkPipeVerb verb = unpack_verb(packedVerb);
if ((unsigned)verb >= SK_ARRAY_COUNT(gPipeHandlers)) {
SkDebugf("------- bad verb %d\n", verb);
return false;
}
if (SkPipeVerb::kRestore == verb) {
indent -= 1;
SkASSERT(indent >= 0);
}
if (SkPipeVerb::kEndPicture == verb) {
if (endPictureIndex) {
*endPictureIndex = unpack_verb_extra(packedVerb);
}
return true;
}
HandlerRec rec = gPipeHandlers[(unsigned)verb];
rec.fProc(reader, packedVerb, canvas);
if (showEachVerb) {
for (int i = 0; i < indent; ++i) {
SkDebugf(" ");
}
SkDebugf("%d [%d] %s %d\n", prevOffset, counter++, rec.fName, reader.offset() - prevOffset);
}
if (!reader.isValid()) {
SkDebugf("-------- bad reader\n");
return false;
}
switch (verb) {
case SkPipeVerb::kSave:
case SkPipeVerb::kSaveLayer:
indent += 1;
break;
default:
break;
}
}
return true;
}
bool SkPipeDeserializer::playback(const void* data, size_t size, SkCanvas* canvas) {
SkPipeInflator inflator(&fImpl->fImages, &fImpl->fPictures,
&fImpl->fTypefaces, &fImpl->fFactories,
fImpl->fProcs);
SkPipeReader reader(this, data, size);
reader.setInflator(&inflator);
return do_playback(reader, canvas);
}
|
90fe7587e604bb98130252fd496dae0833d74dc7 | 0f8bc2c77825484831e55c0e95f3f5ecaf253161 | /Week4/test/2.組合字串.cpp | 0abd73dc8c5c43144fc9a25621a97b1cfe436f1f | [] | no_license | D0683497/FCU_Data_Structure | 2fb625d39d7cc461af23f411b082e22e515075c0 | 8a68e63cddff7176dbd0f2f38b5c6d3af1c59f95 | refs/heads/master | 2023-02-06T04:46:03.437552 | 2020-12-30T00:51:10 | 2020-12-30T00:51:10 | 301,861,293 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 356 | cpp | 2.組合字串.cpp | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char string[6];
printf("輸入字串:");
scanf("%s", string);
int len = strlen(string);
int num, i;
for (i = len; i > 0; i--)
{
if (i == len)
{
num = i;
}
else
{
num = i*num;
}
}
printf("字串%s有%d種組合字串:", string, num);
return 0;
}
|
04c5e9536bb65e46e57d669e4f9b0aa2cc242e6e | b3a94f8a7c2cfb75bc7671db4388d1893f7dc42c | /src/model/settings.h | cae5581883f32d9135f73f4a9ea466f239884d08 | [] | no_license | Kermit/ROJA-converter | c1cfe16a9ce70378b8ac66d977b1ae162029e119 | 39415252f842c3a10d32807019f3e02719784033 | refs/heads/master | 2021-01-01T17:43:39.578900 | 2013-01-07T20:04:33 | 2013-01-07T20:04:33 | 2,218,264 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 226 | h | settings.h | #ifndef SETTINGS_H
#define SETTINGS_H
#include <QtCore/QString>
class Settings
{
private:
QString version;
public:
Settings();
void setVersion(QString value);
QString getVersion();
};
#endif // SETTINGS_H
|
20dc100acd13c288c567dc39def5bbf11697116a | 1e45f0478453f98bfecf3eab6a0d73b01d3d53d0 | /args/editor/editor/editormodule.hpp | 2afc87db945ea1bd8623841327e157b84a8e095d | [
"MIT"
] | permissive | Algo-ryth-mix/Args-Engine | 841403155eb212285496cd5d697591ff5dbcaa83 | cc5084c5060ff071602cc9e2fdfb52791e65ca5b | refs/heads/main | 2022-12-25T14:19:06.220699 | 2020-10-01T20:55:01 | 2020-10-01T20:55:01 | 279,065,733 | 0 | 0 | MIT | 2021-04-02T08:47:28 | 2020-07-12T13:03:29 | C++ | UTF-8 | C++ | false | false | 288 | hpp | editormodule.hpp | #pragma once
/**
* @file editormodule.hpp
*/
namespace args::editor
{
/**@class EditorModule
* @brief interface for editor-modules, must be implemented
* @ref args::editor::Editor::reportModule<T,...>()
*/
class EditorModule
{
};
struct editor_module_initializer_t {};
}
|
688569bb52228348dd7ac161f38c8e1505efebfd | e15fd92ed52e166bbea5de9740d0f15b8bc4a43f | /src/Level/SSerialization.cpp | 8878c3c0c76d356f6d7b620ea2a8de78f7a2c5ed | [] | no_license | BlueSpud/Spud-Engine-2 | 1a14cf909a3860fb7d12b51a39db02d5963e0ce2 | c42b8b354c173ede0901c2ac625cce65c74ae182 | refs/heads/master | 2020-12-05T05:35:52.021427 | 2018-02-26T01:33:10 | 2018-02-26T01:33:10 | 67,078,816 | 0 | 0 | null | 2016-12-25T17:08:03 | 2016-08-31T22:44:14 | C++ | UTF-8 | C++ | false | false | 2,481 | cpp | SSerialization.cpp | //
// SSerialization.cpp
// Spud Engine 2
//
// Created by Logan Pazol on 3/6/17.
// Copyright © 2017 Logan Pazol. All rights reserved.
//
#include "SSerialization.hpp"
/******************************************************************************
* Implemetation for serialized data *
******************************************************************************/
SSerializedData::SSerializedData(size_t _size) {
// Create a data block of the proper size
size = _size;
data = (char*)malloc(size);
}
SSerializedData::~SSerializedData() { free(data); }
/******************************************************************************
* Implemetation for serializer *
******************************************************************************/
SSerializedData* SSerializer::serialize() {
// The first thing we need to do is create a block of memory large enough
SSerializedData* data = new SSerializedData(size);
// Now go through each of the items and have them copy in their data
size_t offset = 0;
for (int i = 0; i < item_queue.size(); i++) {
item_queue[i]->copy(data->data + offset);
offset = offset + item_queue[i]->getSize();
// Delete it (dynamically allocated)
delete item_queue[i];
}
// Clear the queue
item_queue.clear();
// Clear the paths
resource_paths.clear();
// Return the data
return data;
}
void SSerializer::addResource(std::shared_ptr<SResource> resource) {
// Add the resource hash
SSerializerQueueItemStorage<size_t>* resource_storage = new SSerializerQueueItemStorage<size_t>();
resource_storage->value = resource->getHash();
item_queue.emplace_back(resource_storage);
size = size + resource_storage->getSize();
// Save the path
resource_paths.push_back(resource->getPath().getPathAsString());
}
const std::vector<std::string>& SSerializer::getPaths() const { return resource_paths; }
/******************************************************************************
* Implementation for de-serializer *
******************************************************************************/
SDeserializer::SDeserializer(SSerializedData* _data, const std::vector<std::string>& paths) {
data = _data;
// Hash all of the paths and save the path
for (int i = 0; i < paths.size(); i++) {
size_t hash = SHash::hashString(paths[i]);
hashed_paths[hash] = paths.at(i);
}
}
SDeserializer::~SDeserializer() { delete data; }
|
b1b2b1859aa150318d57e695164d8738f10fe015 | d6258ae3c0fd9f36efdd859a2c93ab489da2aa9b | /fulldocset/add/codesnippet/CPP/p-system.windows.forms.a_3_1.cpp | 6481d83d1d12ff83be1160a39c8cd10eaa9a6788 | [
"CC-BY-4.0",
"MIT"
] | permissive | OpenLocalizationTestOrg/ECMA2YamlTestRepo2 | ca4d3821767bba558336b2ef2d2a40aa100d67f6 | 9a577bbd8ead778fd4723fbdbce691e69b3b14d4 | refs/heads/master | 2020-05-26T22:12:47.034527 | 2017-03-07T07:07:15 | 2017-03-07T07:07:15 | 82,508,764 | 1 | 0 | null | 2017-02-28T02:14:26 | 2017-02-20T02:36:59 | Visual Basic | UTF-8 | C++ | false | false | 140 | cpp | p-system.windows.forms.a_3_1.cpp | private:
void PrintProductVersion()
{
textBox1->Text = "The product version is: {0}",
Application::ProductVersion;
} |
b8a838c8dd597de2240aea18d8e989c9654b9b9c | 549dcbba3b5c1496d8481088c461949459e9c9e5 | /GAME3015_A1/MenuState.hpp | 55368fd5dcd9f93e81ddf5420a9064e30c2c77c1 | [] | no_license | inparia/GAME3015_A1 | 7fe12f6a117f45f0278cd13437e7266c6ad152c8 | ed96c74b47975e5b74b2e2a4f3d3f74f23cf252a | refs/heads/main | 2023-03-29T13:12:53.839271 | 2021-03-24T03:50:06 | 2021-03-24T03:50:06 | 343,686,341 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 425 | hpp | MenuState.hpp | #pragma once
#pragma region step 1
#include "State.hpp"
#include "SpriteNode.h"
class MenuState : public State
{
public:
MenuState(StateStack* stack, Context* context);
virtual void draw();
virtual bool update(GameTimer& gt);
virtual bool handleEvent(WPARAM btnState);
virtual bool handleRealtimeInput();
void updateOptionText();
private:
enum OptionNames
{
Play,
Exit,
};
};
#pragma endregion
|
0ec50886977c461c5f018716bc657d33bd9f6829 | f83ef53177180ebfeb5a3e230aa29794f52ce1fc | /ACE/ACE_wrappers/examples/C++NPv1/Thread_Per_Connection_Logging_Server.h | 65f916146ae57a3b5d772ae1e2cfae9d605cbf67 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | msrLi/portingSources | fe7528b3fd08eed4a1b41383c88ee5c09c2294ef | 57d561730ab27804a3172b33807f2bffbc9e52ae | refs/heads/master | 2021-07-08T01:22:29.604203 | 2019-07-10T13:07:06 | 2019-07-10T13:07:06 | 196,183,165 | 2 | 1 | Apache-2.0 | 2020-10-13T14:30:53 | 2019-07-10T10:16:46 | null | UTF-8 | C++ | false | false | 1,258 | h | Thread_Per_Connection_Logging_Server.h | /*
** Copyright 2001 Addison Wesley. All Rights Reserved.
*/
#ifndef _THREAD_PER_CONNECTION_LOGGING_SERVER_H
#define _THREAD_PER_CONNECTION_LOGGING_SERVER_H
#include "ace/SOCK_Stream.h"
#include "Logging_Server.h"
class Thread_Per_Connection_Logging_Server : public Logging_Server
{
private:
struct Thread_Args {
Thread_Args (Thread_Per_Connection_Logging_Server *lsp) : this_ (lsp) {}
Thread_Per_Connection_Logging_Server *this_;
ACE_SOCK_Stream logging_peer_;
};
// Passed as a parameter to <ACE_Thread_Manager::spawn>.
static ACE_THR_FUNC_RETURN run_svc (void *arg);
protected:
virtual int handle_connections ();
virtual int handle_data (ACE_SOCK_Stream * = 0);
public:
// Template Method that runs logging server's event loop. Need to
// reimplement this here because the threads spawned from handle_connections
// call handle_data; therefore, this method must not.
virtual int run (int argc, char *argv[]) {
if (open (argc > 1 ? atoi (argv[1]) : 0) == -1)
return -1;
for (;;) {
if (wait_for_multiple_events () == -1)
return -1;
if (handle_connections () == -1)
return -1;
}
ACE_NOTREACHED (return 0;)
}
};
#endif /* _THREAD_PER_CONNECTION_LOGGING_SERVER_H */
|
2a03791eb340d24ceddca04a325cd1b3d3ab5017 | 1ec2bbf1d08b5a27dbf16b8ea327d6dda4222861 | /src/Random.h | 3090f74da232bc0114b8b96a36f00595893c9104 | [] | no_license | myhau/geometry-orthogonal-space-search | ee967520e6fa5a493ab6cd24279d98471f92dede | a2a74d7d1fabe334ac8038253c660c0425899d76 | refs/heads/master | 2021-01-13T12:44:07.037649 | 2017-10-21T21:57:30 | 2017-10-21T21:57:30 | 72,533,074 | 1 | 2 | null | 2017-10-21T21:57:31 | 2016-11-01T12:15:08 | C++ | UTF-8 | C++ | false | false | 2,947 | h | Random.h | #ifndef GEO_PROJ_RANDOM_H
#define GEO_PROJ_RANDOM_H
#include "Point.h"
#include <vector>
#include <cmath>
#include <random>
using namespace std;
default_random_engine generator;
uniform_real_distribution<double> angleDistribution(0, 2 * M_PI);
class Random {
public:
static auto randomPoints(const Rect<>& insideRect, int count) {
uniform_real_distribution<double> xDistribution(insideRect.xFrom, insideRect.xTo);
uniform_real_distribution<double> yDistribution(insideRect.yFrom, insideRect.yTo);
vector<Point<>> points;
for (int i = 0; i < count; ++i) {
points.push_back(point(xDistribution(generator), yDistribution(generator)));
}
return points;
}
static auto randomPoint(const Rect<>& insideRect) {
return randomPoints(insideRect, 1)[0];
}
static auto randomRect(const Rect<>& insideRect) {
return make_rect(randomPoint(insideRect), randomPoint(insideRect));
}
inline static auto randomPointsOnCircle(Point<> center, double r, int count) {
vector<Point<>> out;
for (int i = 0; i < count; ++i) {
double angle = angleDistribution(generator);
double x = r * cos(angle) + center.x;
double y = r * sin(angle) + center.y;
out.push_back(Point<>(x, y));
}
return out;
}
inline static auto randomPointsInCircle(Point<> center, double maxR, int count) {
uniform_real_distribution<double> rDistribution(0, maxR);
vector<Point<>> out;
for (int i = 0; i < count; ++i) {
double angle = angleDistribution(generator);
double r = rDistribution(generator);
double x = r * cos(angle) + center.x;
double y = r * sin(angle) + center.y;
out.push_back(point(x, y));
}
return out;
}
inline static auto randomPointsInRect(double minX, double maxX, double minY, double maxY,
int count) {
uniform_real_distribution<double> xDistribution(minX, maxX);
uniform_real_distribution<double> yDistribution(minY, maxY);
vector<Point<>> out;
for (int i = 0; i < count; ++i) {
out.push_back(
point(xDistribution(generator), yDistribution(generator))
);
}
return out;
}
inline static auto randomPointsOnRect(double minX, double maxX, double minY, double maxY,
double count) {
double r[2][2] = {{minX, maxX}, {minY, maxY}};
int whichCoordIsConst[] = {0, 1};
discrete_distribution<int> chooseFrom0To1({1, 1});
vector<Point<>> out;
for (int i = 0; i < count; ++i) {
int c1 = whichCoordIsConst[chooseFrom0To1(generator)];
int c2 = 1 - c1;
uniform_real_distribution<double> distr(r[c2][0], r[c2][1]);
double coords[2];
coords[c1] = r[c1][chooseFrom0To1(generator)];
coords[c2] = distr(generator);
out.push_back(Point<>(coords));
}
return out;
}
};
#endif //GEO_PROJ_RANDOM_H
|
da3e44d86980d97182de3aefe7ad4924a22fa333 | 0e0bd3ad21931a20b8440505fe6c0792225ce411 | /main.cpp | 8806471bdf9e65e30a2fec04094d765b6ca698c9 | [] | no_license | Ilya7531/Ring- | f8ed38f73cc2e7c25cda0801f508d34243f9f2bd | 74dfffe35282462fb86e84a842cca65f04240f17 | refs/heads/master | 2020-05-20T10:41:47.343879 | 2013-11-05T01:39:54 | 2013-11-05T01:39:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281 | cpp | main.cpp | #include <iostream>
#include <cstring>
#include "ring.h"
using namespace std;
int main()
{
Ring r;
//r.add(3);
cout << r.isEmpty() << endl;
//r.add(4);
cout << r.isEmpty() << endl;
cout << r.del() << endl;
cout << r.del() << endl;
cout << r.isEmpty() << endl;
return 0;
}
|
4347edcfa366c6ee83e00be8bf99217272a087eb | cd0515449a11d4fc8c3807edfce6f2b3e9b748d3 | /src/yb/util/util_pch.h | 1a4716c76b3fd28aeac8d558b68364d0726f3554 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"OpenSSL"
] | permissive | wwjiang007/yugabyte-db | 27e14de6f26af8c6b1c5ec2db4c14b33f7442762 | d56b534a0bc1e8f89d1cf44142227de48ec69f27 | refs/heads/master | 2023-07-20T13:20:25.270832 | 2023-07-11T08:55:18 | 2023-07-12T10:21:24 | 150,573,130 | 0 | 0 | Apache-2.0 | 2019-07-23T06:48:08 | 2018-09-27T10:59:24 | C | UTF-8 | C++ | false | false | 8,306 | h | util_pch.h | // Copyright (c) YugaByte, Inc.
// This file was auto generated by python/yb/gen_pch.py
#pragma once
#include <assert.h>
#include <crcutil/interface.h>
#include <curl/curl.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <float.h>
#include <ifaddrs.h>
#include <inttypes.h>
#include <math.h>
#include <netinet/in.h>
#include <openssl/bn.h>
#include <openssl/ossl_typ.h>
#include <pthread.h>
#include <pwd.h>
#include <semaphore.h>
#include <signal.h>
#include <spawn.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <time.h>
#include <unicode/gregocal.h>
#include <unistd.h>
#include <uuid/uuid.h>
#include <zlib.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <chrono>
#include <cmath>
#include <compare>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <filesystem>
#include <fstream>
#include <functional>
#include <future>
#include <iomanip>
#include <iosfwd>
#include <iostream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <new>
#include <numeric>
#include <optional>
#include <ostream>
#include <queue>
#include <random>
#include <regex>
#include <set>
#include <shared_mutex>
#include <sstream>
#include <stack>
#include <string>
#include <string_view>
#include <thread>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/address_v4.hpp>
#include <boost/asio/ip/address_v6.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/write.hpp>
#include <boost/atomic.hpp>
#include <boost/container/small_vector.hpp>
#include <boost/container/stable_vector.hpp>
#include <boost/core/demangle.hpp>
#include <boost/date_time/c_local_time_adjustor.hpp>
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/function.hpp>
#include <boost/functional/hash.hpp>
#include <boost/icl/discrete_interval.hpp>
#include <boost/icl/interval_set.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/lockfree/queue.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/if.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/ranked_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/optional.hpp>
#include <boost/optional/optional.hpp>
#include <boost/optional/optional_fwd.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/config/config.hpp>
#include <boost/preprocessor/expr_if.hpp>
#include <boost/preprocessor/facilities/apply.hpp>
#include <boost/preprocessor/if.hpp>
#include <boost/preprocessor/punctuation/is_begin_parens.hpp>
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/transform.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/variadic/to_seq.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/range/adaptor/indirected.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/signals2/dummy_mutex.hpp>
#include <boost/smart_ptr/detail/yield_k.hpp>
#include <boost/smart_ptr/make_shared.hpp>
#include <boost/static_assert.hpp>
#include <boost/system/error_code.hpp>
#include <boost/tti/has_type.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/make_signed.hpp>
#include <boost/unordered_map.hpp>
#include <boost/utility/binary.hpp>
#include <boost/uuid/detail/sha1.hpp>
#include <boost/uuid/nil_generator.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <cds/container/basket_queue.h>
#include <cds/container/moir_queue.h>
#include <cds/container/optimistic_queue.h>
#include <cds/container/rwqueue.h>
#include <cds/container/segmented_queue.h>
#include <cds/container/vyukov_mpmc_cycle_queue.h>
#include <cds/gc/dhp.h>
#include <cds/init.h>
#undef EV_ERROR // On mac is it defined as some number, but ev++.h uses it in enum
#include <ev++.h>
#include <gflags/gflags.h>
#include <gflags/gflags_declare.h>
#include <glog/logging.h>
#include <glog/stl_logging.h>
#include <gmock/gmock.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/plugin.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor_database.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/message.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/util/message_differencer.h>
#include <gtest/gtest-spi.h>
#include <gtest/gtest.h>
#include <gtest/gtest_prod.h>
#include <rapidjson/document.h>
#include <rapidjson/error/en.h>
#include <rapidjson/istreamwrapper.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/writer.h>
#include "yb/gutil/atomicops.h"
#include "yb/gutil/bind.h"
#include "yb/gutil/bind_internal.h"
#include "yb/gutil/bits.h"
#include "yb/gutil/callback.h"
#include "yb/gutil/callback_forward.h"
#include "yb/gutil/callback_internal.h"
#include "yb/gutil/casts.h"
#include "yb/gutil/dynamic_annotations.h"
#include "yb/gutil/endian.h"
#include "yb/gutil/hash/builtin_type_hash.h"
#include "yb/gutil/hash/city.h"
#include "yb/gutil/hash/hash.h"
#include "yb/gutil/hash/hash128to64.h"
#include "yb/gutil/hash/jenkins.h"
#include "yb/gutil/hash/jenkins_lookup2.h"
#include "yb/gutil/hash/legacy_hash.h"
#include "yb/gutil/hash/string_hash.h"
#include "yb/gutil/int128.h"
#include "yb/gutil/integral_types.h"
#include "yb/gutil/logging-inl.h"
#include "yb/gutil/macros.h"
#include "yb/gutil/map-util.h"
#include "yb/gutil/mathlimits.h"
#include "yb/gutil/once.h"
#include "yb/gutil/port.h"
#include "yb/gutil/ref_counted.h"
#include "yb/gutil/ref_counted_memory.h"
#include "yb/gutil/singleton.h"
#include "yb/gutil/spinlock.h"
#include "yb/gutil/stl_util.h"
#include "yb/gutil/stringprintf.h"
#include "yb/gutil/strings/ascii_ctype.h"
#include "yb/gutil/strings/charset.h"
#include "yb/gutil/strings/escaping.h"
#include "yb/gutil/strings/fastmem.h"
#include "yb/gutil/strings/human_readable.h"
#include "yb/gutil/strings/join.h"
#include "yb/gutil/strings/numbers.h"
#include "yb/gutil/strings/split.h"
#include "yb/gutil/strings/split_internal.h"
#include "yb/gutil/strings/strcat.h"
#include "yb/gutil/strings/stringpiece.h"
#include "yb/gutil/strings/strip.h"
#include "yb/gutil/strings/substitute.h"
#include "yb/gutil/strings/util.h"
#include "yb/gutil/sysinfo.h"
#include "yb/gutil/template_util.h"
#include "yb/gutil/thread_annotations.h"
#include "yb/gutil/threading/thread_collision_warner.h"
#include "yb/gutil/type_traits.h"
#include "yb/gutil/walltime.h"
|
681ad813873c21bfa134d5f4462edd8efa4d34f1 | 98a0ac4a9c67ae2e767f6220e1adcdaab8fb97d0 | /个人赛1/codes/A/26390117_3019244083_A.cpp | d1f2a25031f694253a604b2e4a6a21a45c6640b5 | [] | no_license | neverac/2020summer | 8fdc0e6a4c7047d754bf48d9e7f9822d7853fb5f | 673a493dbf736f1d33f791a254448e061ccd0b6b | refs/heads/master | 2022-12-04T21:54:24.688278 | 2020-08-25T09:37:55 | 2020-08-25T09:37:55 | 280,410,524 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 256 | cpp | 26390117_3019244083_A.cpp | #include <bits/stdc++.h>
using namespace std;
int a[1100];
int main()
{
int n,m;
int ans=0;
scanf("%d%d",&n,&m);
for(int i = 1; i <= n; ++i) scanf("%d",&a[i]);
sort(a+1,a+n+1);
for(int i = 1; i <= m; ++i) ans += a[i];
printf("%d",ans);
return 0;
} |
4e76f06337b3bc23b3e0192bb44cd09a8f8b0040 | 0eda31c5005912a6ae1652de0f4f48fb922ebcff | /CircleList/CircleList/CircleList.cpp | 60fcd108d015db3af3b4858ee8a43f6207933f29 | [] | no_license | rpotanic/my-labs | 491879015884879df0406803ddff8774f0a31080 | 03b34690d8c1a77fb41401d6c085a65547ed3a95 | refs/heads/master | 2020-05-23T16:23:07.988108 | 2019-05-15T14:53:02 | 2019-05-15T14:53:02 | 163,100,957 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,670 | cpp | CircleList.cpp | #include "CircleList.h"
#include <iostream>
CircleList::CircleList()
{
Head = new Monom();
}
CircleList::~CircleList()
{
Monom * cur = Head->getNext();
while (cur != Head)
{
Head->setNext(cur->getNext());
cur->setNext(nullptr);
delete cur;
cur = Head->getNext();
}
Head->setNext(nullptr);
delete Head;
}
CircleList::CircleList(const CircleList & op)
{
Head = new Monom();
Monom * last = Head;
Monom * cur = op.Head->getNext();
while (cur != op.Head)
{
Monom * tmp = new Monom(*cur);
tmp->setNext(Head);
last->setNext(tmp);
cur = cur->getNext();
last = tmp;
}
}
CircleList & CircleList::operator=(const CircleList & op)
{
Monom * cur = Head->getNext();
while (cur != Head)
{
Head->setNext(cur->getNext());
cur->setNext(nullptr);
delete cur;
cur = Head->getNext();
}
Head->setNext(nullptr);
Monom * last = Head;
cur = op.Head->getNext();
while (cur != op.Head)
{
Monom * tmp = new Monom(*cur);
tmp->setNext(Head);
last->setNext(tmp);
cur = cur->getNext();
last = tmp;
}
return *this;
}
void CircleList::AddMonom(int A, int SV)
{
Monom * m = new Monom(A, SV);
Monom * prev = Head;
Monom * cur = Head->getNext();
while (SV < cur->getSV())
{
prev = cur;
cur = cur->getNext();
}
if (cur->getSV() == SV)
{
int nA = cur->getA() + A;
if (nA != 0)
{
cur->setA(nA);
}
else
{
if (prev != cur)
{
prev->setNext(cur->getNext());
cur->setNext(nullptr);
delete cur;
}
}
}
else
{
prev->setNext(m);
m->setNext(cur);
}
}
void CircleList::AddMonom(std::string str, int maxSt, int n)
{
Monom * m = new Monom(str, maxSt, n);
int SV = m->getSV();
int A = m->getA();
Monom * prev = Head;
Monom * cur = Head->getNext();
while (SV < cur->getSV())
{
prev = cur;
cur = cur->getNext();
}
if (cur->getSV() == SV)
{
int nA = cur->getA() + A;
if (nA != 0)
{
cur->setA(nA); }
else
{
if (prev != cur)
{
prev->setNext(cur->getNext());
cur->setNext(nullptr);
delete cur;
}
}
}
else
{
prev->setNext(m);
m->setNext(cur);
}
}
CircleList CircleList::operator+(const CircleList & op)
{
CircleList res(*this);
Monom *cur = op.Head->getNext();
while (cur != op.Head)
{
res.AddMonom(cur->getA(), cur->getSV());
cur = cur->getNext();
}
return res;
}
CircleList CircleList::operator-(const CircleList & op)
{
CircleList res(*this);
Monom *cur = op.Head->getNext();
while (cur != op.Head)
{
res.AddMonom((-1)*cur->getA(), cur->getSV());
cur = cur->getNext();
}
return res;
}
CircleList CircleList::operator*(int n)
{
CircleList tmp = *this;
if (n == 0)
{
return CircleList();
}
Monom * cur = tmp.Head->getNext();
while (cur != Head)
{
cur->setA((cur->getA())*n);
cur = cur->getNext();
}
return tmp;
}
CircleList CircleList::multiply(CircleList & rhs, int maxSt, int n)
{
CircleList res;
Monom * cur = Head->getNext();
while (cur != Head)
{
Monom * m = rhs.Head->getNext();
while (m != rhs.Head)
{
Monom r = cur->multiply(*m, maxSt, n);
res.AddMonom(r.getA(), r.getSV());
m = m->getNext();
}
cur = cur->getNext();
}
return res;
}
std::string CircleList::toString(int maxSt, int n)
{
Monom * cur = Head->getNext();
std::string res = "";
while (cur != Head)
{
std::string tmp = cur->MonomToString(maxSt, n);
if (tmp[0] != '-')
{
res += ("+" + tmp);
}
else
{
res += tmp;
}
cur = cur->getNext();
}
return res;
}
void CircleList::show(int maxSt, int n)
{
Monom * cur = Head;
int i = 0;
do
{
std::cout << "Monom #" << i++ << ":" << std::endl;
cur->show(maxSt, n);
cur = cur->getNext();
} while (cur != Head);
}
|
76e1d0768e905a5cc0ec8ec17c9089ff4653c368 | 5e7b8bfa89225e03bc8cdc0723e8756b81b9e008 | /maxsubsum.cpp | 04c341fd70c4d13fe6bfaac02f4de6611a0d75b9 | [] | no_license | shashankch/DataStructures-Algorithms | 3e0137065f878c962a815d17cb7916487ebdeb0b | b6b447ebf4e1a18ec23b94172e844ce0d53f7a14 | refs/heads/master | 2020-09-11T13:55:21.068954 | 2020-05-06T07:24:07 | 2020-05-06T07:24:07 | 222,088,726 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 540 | cpp | maxsubsum.cpp |
#include <iostream>
#include <algorithm>
using namespace std;
int max_sum(int *arr, int n)
{
int cs = 0, ms = 0;
for (int i = 0; i < n; i++)
{
cs += arr[i];
if (cs < 0)
{
cs = 0;
}
ms = max(ms, cs);
}
return ms;
}
int main()
{
int t, n, arr[100000000];
cin >> t;
while (t--)
{
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << max_sum(arr, n) << endl;
}
return 0;
}
|
63c4768480be80c23f29d14d4a70c5ca297c4bbc | b61b94afc9a8c4c3aa1057d71095a48e53fe32f9 | /iot-project/src/lib/iot/modules/Utils/Utils.h | d529f0ecdff7fcd7fb34b54715a4cc92c7570ca3 | [] | no_license | wojtekpil/iot | cd4ebf0546d1057bd9b74faf0f704e27b068f983 | b5c7e502a8736f2aa55dcfd2f9598c8372b99d13 | refs/heads/master | 2016-09-14T18:53:39.043966 | 2016-06-08T10:18:05 | 2016-06-08T10:18:05 | 58,266,900 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 418 | h | Utils.h | /*
* Utils.h
*
* Created on: 6 maj 2016
* Author: wojtek
*/
#ifndef LIB_IOT_MODULES_UTILS_UTILS_H_
#define LIB_IOT_MODULES_UTILS_UTILS_H_
namespace iot {
/**
* Utils class containing some static method that are common in application
*/
class Utils {
public:
Utils();
void onStartup();
virtual ~Utils();
};
} /* namespace iot */
#endif /* LIB_IOT_MODULES_UTILS_UTILS_H_ */
|
07b547865156d0436191f1df40dfc585611dcf62 | cc17eb854019ceafb8b9d5a7a80d88b14363fee6 | /POJ - 1182 食物链(带权并查集).cpp | f89a480275a096e2d0181489fe6932a4120d26f4 | [] | no_license | kuronekonano/OJ_Problem | 76ec54f16c4711b0abbc7620df5519b3fff4e41b | ea728084575620538338368f4b6526dfdd6847db | refs/heads/master | 2021-06-23T02:19:59.735873 | 2020-12-30T03:52:59 | 2020-12-30T03:52:59 | 166,183,278 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,270 | cpp | POJ - 1182 食物链(带权并查集).cpp | #include<stdio.h>///将于父节点的关系用权值表示
int n,t,fa[50004],link[50004];
int finds(int x)
{
if(fa[x]!=x)///递归式查找
{
int tmp=finds(fa[x]);
link[x]=(link[x]+link[fa[x]])%3;///根据枚举规律推导出的公式,可以路径压缩计算出当前结点与父亲的父亲结点的关系权值
fa[x]=tmp;///更新结点的父亲变为原来的爷爷结点
}
return fa[x];
}
int main()
{
scanf("%d%d",&n,&t);
int flag,x,y,ans=0;
for(int i=1; i<=n; i++)fa[i]=i,link[i]=0;
while(t--)
{
scanf("%d%d%d",&flag,&x,&y);
if(x>n||y>n||(x==y&&flag==2))
{
ans++;
continue;
}
int fx=finds(x),fy=finds(y);
if(fx==fy&&(link[y]-link[x]+3)%3!=flag-1)ans++;///根据当前两堆的根节点相同时,说明两个节点已经被遍历过,已经合为一堆,直接检查两者关系,根据第一次真话,来判断现在这句话是否符合关系权值
else
{
fa[fy]=fx;
link[fy]=(link[x]-link[y]+flag-1+3)%3;///合并后计算出原根节点与新的父亲节点的关系,根据枚举推导出的公式
}
}
printf("%d\n",ans);
}
|
a0c50c2367c30103821b788caef1a9afb66f714e | 2ee5031aff86b406b7fb79c86cabae2b22158829 | /MyProject/Source/MyProject/Private/BasicFrame/Libs/DelayHandle/DelayAddParam.h | bba9e6ecaf8f553c1f8c92f14c4a5e1c078b2fba | [] | no_license | hackerlank/UE | fe5c07e67db577bbf90021e1ce59473efc4a87ee | 7899ff61023ce944b47b73987ee498d48f58dd54 | refs/heads/master | 2020-06-12T11:50:20.268224 | 2016-12-01T02:34:20 | 2016-12-01T02:34:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 207 | h | DelayAddParam.h | #ifndef __DelayAddParam_H
#define __DelayAddParam_H
#include "DelayHandleParamBase.h"
class DelayAddParam : public DelayHandleParamBase
{
public:
float m_priority;
public:
DelayAddParam();
};
#endif |
2f5121786ecd1b344d0be566d334dcf4a15f0313 | a26cd9b2094127c8bca5ae1563de63a139d917b0 | /test.cpp | 223a355bd6b1a5aa21ac0a4875cfdefef3ca1dc7 | [] | no_license | davekessener/initrd | 16e94adadddd58e50a58634f91cfb406402cebca | f9204605101d639ff6641a48bc9eb3dc80ca4046 | refs/heads/master | 2020-12-30T04:01:24.838711 | 2020-02-07T19:51:53 | 2020-02-07T19:51:53 | 238,853,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 860 | cpp | test.cpp | #include <iostream>
#include <vector>
#include <fstream>
#include <iterator>
#include "lib/rd.h"
using namespace dave::initrd;
void process(const Node *n, uint indent)
{
for(uint i = 0 ; i < indent ; ++i)
{
std::cout << " ";
}
std::cout << "/" << n->name() << " (" << (n->is_directory() ? "D" : "F") << "): ";
if(n->is_directory())
{
std::cout << n->children() << " children." << std::endl;
for(const auto& c : *n)
{
process(&c, indent + 1);
}
}
else
{
std::cout << n->size() << "B" << std::endl;
std::cout.write((const char *) n->content(), n->size());
}
}
int main(int argc, char **argv)
{
std::vector<std::string> args{argv + 1, argv + argc};
std::ifstream fin(args.at(0), std::ios::binary);
std::vector<u8> content(std::istreambuf_iterator<char>(fin), {});
process((const Node *) &content.at(0), 0);
return 0;
}
|
3485c780267c2b111912d5bf38fc5abec65820f7 | 48a05c269ce7a5d6337e212093a993359317555f | /Phase 2/include/InputParser.h | cdab882ac14ed537791a16b4aea93e7f3b9464e9 | [] | no_license | Mark-Mamdouh/Complier | 60c20875df1c70ca7843e296ec315490de0e7e71 | 1580f689356239e882c3404c9dae9e17b292b586 | refs/heads/main | 2023-01-29T04:08:30.597619 | 2020-12-15T23:52:11 | 2020-12-15T23:52:11 | 321,818,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 933 | h | InputParser.h | #ifndef INPUTPARSER_H
#define INPUTPARSER_H
#include "phase2.h"
using namespace std;
class InputParser
{
public:
// elements scaned from productions file
vector<struct PR_ELEM> elements ;
// each NT element will have its production rule by indeces
map<int , vector<vector<int>>> prod_rules_indexes;
// each NT element will have its production rule
map<string , vector<vector<string>>> prod_rules;
// handle flow of parsing
void parse_rules();
InputParser();
virtual ~InputParser();
private:
// global counter for elements
int elem_count;
// used to map each element to its index
map<string,int> elem_index_map;
// read rules
void read_file();
// init elem struct
void init_elem(string str);
// init production rules
void init_prod();
// print for check
void check();
};
#endif // INPUTPARSER_H
|
bd378ffab0b418f0d4e4ccc69bd4714e71760454 | a4a9ac3db0a57a4d5efa274067d3a40014b6c47f | /DXNetworking/DXNetworking/MenuInterface.cpp | 01633413e5190e02d8b6f309f6dfc849a5487469 | [] | no_license | rukamir/DxNetworking | b25a434658fc5ee9145b04fe53b2b76016ff4090 | 209dc839defee45e177c6235d53994138a68a98c | refs/heads/master | 2020-05-17T04:19:40.302124 | 2013-08-18T20:07:06 | 2013-08-18T20:07:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,896 | cpp | MenuInterface.cpp | #include "MenuInterface.h"
MenuInterface::MenuInterface()
{
m_pos = D3DXVECTOR2(0.0f, 0.0f);
m_active = true;
}
MenuInterface::~MenuInterface()
{
VectSprtElemShPtrs::iterator i = m_vSptElem.begin();
if(m_vSptElem.size())// != 0)
for(;i != m_vSptElem.end(); i++)
{
(*i) = 0;
}
}
void MenuInterface::AddElementToMenu(SprtElemShPtr menuItem)
{
D3DXVECTOR2 hold;
if (menuItem)
{
hold = menuItem->GetPosition();
//set value relative to menu position
//menuItem->SetPosition( hold + m_pos );
menuItem->SetParentPos(&this->m_pos);
m_vSptElem.push_back(menuItem);
}
}
void MenuInterface::Activate()
{
m_active = true;
VectSprtElemShPtrs::iterator i = m_vSptElem.begin();
for (; i != m_vSptElem.end(); i++)
{
(*i)->SetVisability(true);
}
this->m_pos = D3DXVECTOR2(100,100);
//this->m_velocity = D3DXVECTOR2(0,1000);
}
void MenuInterface::Unactivate()
{
m_active = false;
VectSprtElemShPtrs::iterator i = m_vSptElem.begin();
for (; i != m_vSptElem.end(); i++)
{
(*i)->SetVisability(false);
}
this->m_velocity = D3DXVECTOR2(0,-1000);
//this->m_pos = D3DXVECTOR2(-2000,-2000);
}
bool MenuInterface::IsActive()
{
return m_active;
}
//void MenuInterface::Draw(LPD3DXSPRITE SpriteObj, ID3DXFont* D3DFont)
//{
// static RECT* rect = new RECT();
// rect->top = 0;
// rect->left = 5;
// rect->bottom = 40;
// rect->right = 120;
//
// if(IsActive())
// {
// if (m_vSptElem.size() > 0)
// {
// VectSprtElemShPtrs::iterator i = m_vSptElem.begin();
// for (;i != m_vSptElem.end(); i++)
// {
// D3DXMATRIX mat2;
// D3DXMatrixTransformation2D(&mat2, &(*i)->GetCenter(), /*(*i)->GetScaleRotation()*/NULL, &(*i)->GetScale(),&(*i)->GetCenter(),(*i)->GetRotation(),
// &D3DXVECTOR2((*i)->GetPosition()+m_pos));
// SpriteObj->SetTransform(&mat2);
// SpriteObj->Draw((*i)->GetTexture(), (*i)->GetRect(), NULL/*(*i)->GetCenter()*/, NULL/*(*i)->GetPosition()*/, D3DCOLOR_XRGB(255, 255, 255));
// D3DFont->DrawText(SpriteObj, (*i)->GetText(),-1,rect,DT_CENTER|DT_VCENTER,D3DCOLOR_XRGB(0,0,0));
// }
// }
// }
// else
// {
// this->SetPosition(D3DXVECTOR2(-200,-200));
// }
//}
void MenuInterface::SetPosition(D3DXVECTOR2 pos)
{
m_pos = pos;
//VectSprtElemShPtrs::iterator i = m_vSptElem.begin();
//for (; i != m_vSptElem.end(); i++)
//{
// //(*i)->SetPosition()
//}
}
void MenuInterface::Update(float dt)
{
//VectSprtElemShPtrs::iterator i = m_vSptElem.begin();
//for (; i != m_vSptElem.end(); i++)
//{
// (*i)->Update(dt);
//}
if(!this->IsActive())
{
if(this->m_pos.y > -650)
{
//m_velocity = D3DXVECTOR2(0,-5);
static D3DXVECTOR2 move = m_velocity * dt;
m_pos += move;
}
else
m_velocity = D3DXVECTOR2(0,0);
}
else
{
if(this->m_pos.y < 150)
{
//m_velocity = D3DXVECTOR2(0,-5);
static D3DXVECTOR2 move = m_velocity * dt;
m_pos += move;
}
else
m_velocity = D3DXVECTOR2(0,0);
}
} |
d5a72fbd7cc7f1f1290b5d71b42187d917466360 | 1cc0d2dba257a586dbc179f7532a18f504c8e204 | /src/sorting.h | e5c1576fbc18e86926c759e74c912cc686a48425 | [] | no_license | Marvinsky/dsa_pooii_exercises | 3a152f7ae93adaa5fe7eb3a0ee37f8cf82c6edce | 0937683a5bd642d8f03eeaac067c04cbbb0b1733 | refs/heads/master | 2022-09-20T21:08:17.444636 | 2020-05-31T15:37:33 | 2020-05-31T15:37:33 | 268,300,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,488 | h | sorting.h |
#include "types.h"
//int INT_MAX = std::numeric_limits<int>::min();
//int INT_MIN = std::numeric_limits<int>::max();
void imprimir(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout<<arr[i];
if (i < n - 1) {
cout<<",\t";
}
}
cout<<"\n";
}
void selection_sort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int indexOfSmallest = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[indexOfSmallest]) {
indexOfSmallest = j;
}
}
int temp = arr[i];
arr[i] = arr[indexOfSmallest];
arr[indexOfSmallest] = temp;
}
}
void bubble_sort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j + 1 < n - i; j++) {
if (arr[j] > arr[j+1]) {
//swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bubble_sort_optimized(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
bool swapped = false;
for (int j = 0; j + 1 < n - i; j++) {
if (arr[j] > arr[j+1]) {
//swap
swap(&arr[j], &arr[j+1]);
swapped = true;
}
}
if (!swapped) {
break;
}
}
}
void merge(int arr[], int from, int middle, int to) {
int length_left = middle - from + 1;
int length_right = to - middle;
int *left = new int[length_left];
int *right = new int[length_right];
for (int i = 0; i < length_left; i++) {
left[i] = arr[from + i];
}
for (int i = 0; i < length_right; i++) {
right[i] = arr[middle + i + 1];
}
/*
left[length_left] = INT_MAX;
right[length_right] = INT_MAX;
int left_pointer = 0;
int right_pointer = 0;
for (int i = from; i <= to; i++) {
if (left[left_pointer] > right[right_pointer]) {
arr[i] = right[right_pointer];
right_pointer++;
} else {
arr[i] = left[left_pointer];
left_pointer++;
}
}*/
int left_pointer = 0;
int right_pointer = 0;
int k = from;
while (left_pointer < length_left && right_pointer < length_right) {
if (left[left_pointer] <= right[right_pointer]) {
arr[k] = left[left_pointer];
left_pointer++;
} else {
arr[k] = right[right_pointer];
right_pointer++;
}
k++;
}
while (left_pointer < length_left) {
arr[k] = left[left_pointer];
left_pointer++;
k++;
}
while (right_pointer < length_right) {
arr[k] = right[right_pointer];
right_pointer++;
k++;
}
}
void merge_sort(int arr[], int from, int to) {
if (from < to) {
int middle = (from + to)/2;
merge_sort(arr, from, middle);
merge_sort(arr, middle + 1, to);
merge(arr, from, middle, to);
}
}
void mergesort_executor(int arr[], int n) {
merge_sort(arr, 0, n - 1);
}
int partition(int arr[], int from, int to) {
int pivot = arr[to];
int wall = from;
for (int i = from; i < to; i++) {
if (arr[i] <= pivot) {
int temp = arr[wall];
arr[wall] = arr[i];
arr[i] = temp;
wall++;
}
}
arr[to] = arr[wall];
arr[wall] = pivot;
return wall;
}
void quicksort(int arr[], int from, int to) {
if (from < to) {
int index_pivot = partition(arr, from, to);
quicksort(arr, from, index_pivot - 1);
quicksort(arr, index_pivot + 1, to);
}
}
void quicksort_executor(int arr[], int n) {
quicksort(arr, 0, n - 1);
}
int median_of_three(int arr[], int first, int middle, int last) {
int array[] = {arr[first], arr[middle], arr[last]};
selection_sort(array, 3);
if (arr[1] == arr[first]) {
return first;
} else if (arr[1] == arr[middle]) {
return middle;
} else {
return last;
}
}
int partition_medium(int arr[], int from, int to) {
int index_of_pivot = median_of_three(arr, from, (from + to)/2, to);
int pivot = arr[index_of_pivot];
if (index_of_pivot != to) {
arr[index_of_pivot] = arr[to];
}
int wall = from;
for (int i = from; i < to; i++) {
if (arr[i] <= pivot) {
int temp = arr[wall];
arr[wall] = arr[i];
arr[i] = temp;
wall++;
}
}
arr[to] = arr[wall];
arr[wall] = pivot;
return wall;
}
void quicksort_medium(int arr[], int from, int to) {
if (from < to) {
int index_pivot = partition_medium(arr, from, to);
quicksort_medium(arr, from, index_pivot - 1);
quicksort_medium(arr, index_pivot + 1, to);
}
}
void quicksort_executor_medium(int arr[], int n) {
quicksort_medium(arr, 0, n - 1);
} |
4cb0520e2f4f82a49947d1a7fb6b0cf4625f38c4 | d50df974cb944eef1558942d7e120598417ef8c8 | /인터페이스까지합친 과제 최종제출물..cpp | 081f4ec07536e9617c5f843d5c740de1c1d9b774 | [] | no_license | ggoniggoni/ggoniggoni2 | f33b418a3b9155a31323f8c5be11d9a54e9e8672 | 8f526cebfe80285154d5580e3420ccc4deb8b343 | refs/heads/master | 2020-09-27T21:30:49.172347 | 2019-12-08T22:04:22 | 2019-12-08T22:04:22 | 226,614,146 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 6,915 | cpp | 인터페이스까지합친 과제 최종제출물..cpp | #include <iostream>
#include <ctime>
#include <queue>
#include <string>
#include <conio.h>
#include <Windows.h>
#define UP 1
#define DOWN 2
#define ENTER 3
using namespace std;
int keyControl();
int menuDraw();
void gotoxy(int, int);
void titleDraw();
queue<int> q;
struct park
{
int state;
clock_t start;
};
class Car
{
private:
int Total = 0;
park** p;
int a;
int b;
int c;//멤버 변수로
public:
void make_park(int a, int b);
void print();
void incoming();
void outcoming();
void All();
};
void Car::make_park(int a, int b)
{
int i, j;
this->a = a;
this->b = b;//주차장 초기화
p = new park *[a];
for (i = 0; i < a; i++)
{
p[i] = new park[b];
}
for (i = 0; i < a; i++)
{
for (j = 0; j < b; j++)
{
p[i][j].state = 1;
}
}
}
void Car::incoming()
{
int i, j;
char w;
int n = 0;
int esc = 0;
int k = 0;
int number;
int c;
for (i = 0; i < a; i++)
{
for (j = 0; j < b; j++) {
if (p[i][j].state != 1)//1은비어있음,0은주차중
c = 0;
else if (p[i][j].state != 0) {
c = 1;
esc = 1;
break;
}
}
if (esc == 1)
break;
}
if (c == 1) {
if (q.empty() == 1)
{
cout << "몇층의 몇번째자리에 주차하시겠습니까?" << endl;
cin >> i >> j;
cout << endl;
if (p[i - 1][j - 1].state == 1) {
p[i - 1][j - 1].start = clock();
p[i - 1][j - 1].state = 0;
cout << i << "층" << j << "번 째에 주차 되었습니다." << endl;
cout << endl;
}
else if (p[i - 1][j - 1].state == 0) {
cout << "이미 주차된 자리입니다" << endl;
}
}
else if (q.empty() == 0) {
q.pop();
if (q.empty() == 0) {
cout << "현재 주차 대기 1번 " << q.front() << endl;
cout << "현재 주차대기열" << q.size() << endl;
cout << "몇층의 몇번째자리에 주차하시겠습니까? " << endl;
cin >> i >> j;
cout << endl;
}
else {
cout << "현재 주차 대기열은 없습니다" << endl;
cout << "몇층의 몇번째자리에 주차하시겠습니까?" << endl;
cin >> i >> j;
cout << endl;
}
if (p[i - 1][j - 1].state == 1)
{
p[i - 1][j - 1].start = clock();
p[i - 1][j - 1].state = 0;
cout << i << "층" << j << " 번 째에 주차 되었습니다." << endl;
cout << endl;
}
else if (p[i - 1][j - 1].state == 0)
{
cout << "이미 주차된 자리입니다." << endl;
}
}
}
else if (c == 0) {
cout << "꽉 찼습니다. 주차대기를 하시겠나요?" << "(Y or N)";
cin >> w;
if (w == 'Y') {
cout << "차량번호를 입력하세요 ";
cin >> number;
q.push(number);
cout << "현재 주차 대기 1번" << q.front();
cout << "현재 주차대기열" << q.size();
}
else if (w == 'N') {
cout << "안녕히 가세요";
}
else {
cout << "잘못 입력하셨습니다";
}
}
}
void Car::outcoming()
{
int i, j;
int money = 0;
int end = clock();
cout << "몇층의 몇번째자리에서 나가시겠습니까?" << endl;
cin >> i >> j;
p[i - 1][j - 1].state = 1;
money = (end - p[i - 1][j - 1].start) / (CLK_TCK * 0.01);
cout << "요금 : " << money << "원 입니다" << endl;
cout << i << "층" << j << "번 째 자리에서 나갔습니다." << endl;
cout << endl;
if (q.empty() == 0) {
q.pop();
p[i - 1][j - 1].state = 0;
p[i - 1][j - 1].start = clock();
if (q.empty() == 0) {
cout << "현재 주차 대기 1번" << q.front() << endl;
cout << "현재 주차대기열" << q.size() << endl;
}
}
}
void Car::All()
{
int i, j;
clock_t end;
for (i = 0; i < a; i++)
{
cout << i + 1 << "층:";
for (j = 0; j < b; j++)
{
if (!p[i][j].state == 1)
{
printf("■");
}
else if (!p[i][j].state == 0)
{
printf("□");
}
}
cout << endl;
}
cout << "■:주차중 □:빈 자리" << endl;
for (i = 0; i < a; i++)
{
for (j = 0; j < b; j++)
{
if (!p[i][j].state == 1)
{
end = clock();
cout << i + 1 << "층 " << j + 1 << "번째 " << ")" << " 사용중인 시간 " << " " << (double)(end - p[i][j].start) / CLK_TCK << endl;
}
}
}
if (q.empty() == 0) {
cout << "현재 주차 대기 1번" << q.front() << endl;
cout << "현재 주차대기열" << q.size() << endl;
}
}
int main()
{
int a, b;
int n;
Car car;
car.make_park(2, 2);
while (1)
{
titleDraw();
int menuCode = menuDraw();
if (menuCode == 1)
{
system("cls");
car.All();//주차현황
cout << "--엔터키를 제외한 키를 누르면 메뉴로 돌아갑니다--" << endl;
cout << "--엔터키를 누르면 강제종료--" << endl;
if (keyControl() == ENTER)
break;
}
else if (menuCode == 2)
{
system("cls");
car.incoming(); //주차하기
cout << "--엔터키를 제외한 키를 누르면 메뉴로 돌아갑니다--" << endl;
cout << "--엔터키를 누르면 강제종료--" << endl;
if (keyControl() == ENTER)
break;
}
else if (menuCode == 3)
{
system("cls");
car.outcoming(); //출차하기
cout << "--엔터키를 제외한 키를 누르면 메뉴로 돌아갑니다--" << endl;
cout << "--엔터키를 누르면 강제종료--" << endl;
if (keyControl() == ENTER)
break;
}
system("cls");
}
return 0;
}
int keyControl() {
int temp = _getch();
if (temp == 224)
temp = _getch(); //224가 반환되면 다시한번 반환값을 얻는다
if (temp == 72)
return UP;
else if (temp == 80)
return DOWN;
else if (temp == 13)
return ENTER;
/*else if (temp == 's')
return DOWN;
else if (temp == 'd')
return RIGHT;
*/
}
void gotoxy(int x, int y)
{
HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);// 콘솔 핸들 가져오기
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(consoleHandle, pos);
}
int menuDraw() {
int x = 20;
int y = 12;
gotoxy(x - 2, y);
cout << "> 주차현황" << endl;
gotoxy(x, y + 1);
cout << "주차하기" << endl;
gotoxy(x, y + 2);
cout << "출차하기 " << endl;
while (1)
{
int num = keyControl();
switch (num)
{
case UP: {
if (y > 12)
{
gotoxy(x - 2, y);
cout << (" ") << endl;;
gotoxy(x - 2, --y);
printf(">");
}
break;
}
case DOWN: {
if (y < 14)
{
gotoxy(x - 2, y);
printf(" ");
gotoxy(x - 2, ++y);
printf(">");
}
break;
}
case ENTER: {
return y - 11;
}
}
}
}
void titleDraw()
{
cout << "\n" << endl;
cout << "\n" << endl;
cout << "\n" << endl;
cout << "\n" << endl;
cout << " 무인주차 시스템" << endl;
} |
e36a3ca14ab502b9d271a0e8df42edb06d619048 | 47e8a69d3d1b031eabc3ef44482ebb2b0ebf29aa | /progs/Plotter/TestXhardware/TestXhardware.ino | 5d2c6574da1141826a37e4a3273e98824b9d1261 | [] | no_license | mycode66/Arduino | d2cd963af8e8c92ab3a432f71a103e9599093c6d | b30ac367078562be8cdb565e0fc934adc6e37378 | refs/heads/master | 2020-09-10T17:18:08.805647 | 2020-01-07T00:24:19 | 2020-01-07T00:24:19 | 221,774,974 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,504 | ino | TestXhardware.ino | // https://github.com/svenhb/GRBL-Plotter
#include <Stepper.h>
// Stepper
#define SP_A1 8
#define SP_A2 9
#define SP_A3 10
#define SP_A4 11
// Stepper 28BYJ-48 spec.
#define STEPS 2038 // the number of steps in one revolution of your motor (28BYJ-48)
Stepper stepper(STEPS, SP_A1, SP_A2, SP_A3, SP_A4);
int st = 2003;
int sp = 5; // < --- Do no exceed more than 5
//---- Joystick -----------
int xPin = A1;
int yPin = A0;
int buttonPin = 2;
int xPosition = 0;
int yPosition = 0;
int buttonState = 0;
int x,y,b;
int i = 0;
int scale = 50; // this gives us from -10 to 10
int center = ( 1024 /2 ) / scale;
//-------------------------------------------------
void setup() {
Serial.begin(9600);
delay(1000);
stepper.setSpeed(sp);
Serial.println("Ready ... ");
}
void loop() {
i++;
xPosition = analogRead(xPin) /scale - center;
yPosition = analogRead(yPin) /scale - center;
buttonState = digitalRead(buttonPin) /scale;
if ( x != xPosition || y != yPosition || b != buttonState )
{
Serial.print(String(i) + '\t');
Serial.print("X: ");
Serial.print(xPosition);
Serial.print(" | Y: ");
Serial.print(yPosition);
Serial.print(" | Button: ");
Serial.println(buttonState);
}
x = xPosition ;
y = yPosition ;
b = buttonState ;
if ( x != 0 ) {
Serial.print("Stepping "); Serial.println(x);
stepper.step(x);
}
delay(100); // add some delay between reads
//stepper.step(st);
}
|
d2686f60d5dd3eb04386f86670d76d0b872bd3cb | 72f4b1e4a7ee2a38c4c09f62575e30fd735b447b | /src/foundation/Base32Decoder.cpp | 0ed579307fb756aaf5f84e1a3e2238e042d41533 | [] | no_license | ma-bo/lua-poco | 735ceb8c740810bc0e5ad0c6ae3a6ab9f4df1db3 | 7735233722f9e4f7e2054b05213f23320183da7c | refs/heads/master | 2023-01-24T01:44:02.786066 | 2023-01-12T19:07:02 | 2023-01-12T19:07:02 | 11,433,172 | 21 | 8 | null | 2016-08-12T16:02:59 | 2013-07-15T20:38:59 | C++ | UTF-8 | C++ | false | false | 2,710 | cpp | Base32Decoder.cpp | /// base32decoder
// An istream interface for inputting base32 encoded data.
// @module base32decoder
#include "Base32Decoder.h"
#include <Poco/Base32Encoder.h>
#include <Poco/Exception.h>
#include <cstring>
int luaopen_poco_base32decoder(lua_State* L)
{
LuaPoco::Base32DecoderUserdata::registerBase32Decoder(L);
return LuaPoco::loadConstructor(L, LuaPoco::Base32DecoderUserdata::Base32Decoder);
}
namespace LuaPoco
{
const char* POCO_BASE32DECODER_METATABLE_NAME = "Poco.Base32Decoder.metatable";
Base32DecoderUserdata::Base32DecoderUserdata(std::istream & istream, int ref)
: mBase32Decoder(istream)
, mUdReference(ref)
, mClosed(false)
{
}
Base32DecoderUserdata::~Base32DecoderUserdata()
{
}
std::istream& Base32DecoderUserdata::istream()
{
return mBase32Decoder;
}
// register metatable for this class
bool Base32DecoderUserdata::registerBase32Decoder(lua_State* L)
{
struct CFunctions methods[] =
{
{ "__gc", metamethod__gc },
{ "__tostring", metamethod__tostring },
{ "read", read },
{ "lines", lines },
{ "seek", seek },
{ NULL, NULL}
};
setupUserdataMetatable(L, POCO_BASE32DECODER_METATABLE_NAME, methods);
return true;
}
/// Constructs a new base32decoder userdata.
// @tparam userdata istream destination for base32 encoded data.
// @return userdata or nil. (error)
// @return error message.
// @function new
// @see istream
int Base32DecoderUserdata::Base32Decoder(lua_State* L)
{
int rv = 0;
int firstArg = lua_istable(L, 1) ? 2 : 1;
IStream* is = checkPrivateUserdata<IStream>(L, firstArg);
lua_pushvalue(L, firstArg);
int ref = luaL_ref(L, LUA_REGISTRYINDEX);
try
{
Base32DecoderUserdata* b32dud = new(lua_newuserdata(L, sizeof *b32dud))
Base32DecoderUserdata(is->istream(), ref);
setupPocoUserdata(L, b32dud, POCO_BASE32DECODER_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
// metamethod infrastructure
int Base32DecoderUserdata::metamethod__tostring(lua_State* L)
{
Base32DecoderUserdata* b32dud = checkPrivateUserdata<Base32DecoderUserdata>(L, 1);
lua_pushfstring(L, "Poco.Base32Decoder (%p)", static_cast<void*>(b32dud));
return 1;
}
int Base32DecoderUserdata::metamethod__gc(lua_State* L)
{
Base32DecoderUserdata* b32dud = checkPrivateUserdata<Base32DecoderUserdata>(L, 1);
luaL_unref(L, LUA_REGISTRYINDEX, b32dud->mUdReference);
b32dud->~Base32DecoderUserdata();
return 0;
}
///
// @type base32decoder
} // LuaPoco
|
3375ef8426760ff4576950d0fa8f16b1edf2b9a7 | 2ee540793f0a390d3f418986aa7e124083760535 | /Online Judges/Hackerrank/Practice/Mathematics/Number Theory/mehtaAndHisLaziness.cpp | 3ce6ac0d87fd5c48157e49ee08816389342d9e62 | [] | no_license | dickynovanto1103/CP | 6323d27c3aed4ffa638939f26f257530993401b7 | f1e5606904f22bb556b1d4dda4e574b409abc17c | refs/heads/master | 2023-08-18T10:06:45.241453 | 2023-08-06T23:58:54 | 2023-08-06T23:58:54 | 97,298,343 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,641 | cpp | mehtaAndHisLaziness.cpp | #include <bits/stdc++.h>
using namespace std;
#define inf 1000000000
#define unvisited -1
#define visited 1
#define eps 1e-9
#define mp make_pair
#define pb push_back
#define pi acos(-1.0)
#define uint64 unsigned long long
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector<ii> vii;
const int maxn = 1e6;
bool isprime[maxn+4];
int prime[78500];
ll numDiv(ll n){
ll pf_idx = 0, pf = prime[pf_idx], ans = 1;
while(pf*pf<=n){
int power = 0;
while(n%pf==0){n/=pf; power++;}
ans*=(power+1);
pf_idx++;
pf = prime[pf_idx];
}
if(n!=1){ans*=2;}
return ans;
}
void sieve(int n){
int i,j;
isprime[0] = isprime[1] = false;
for(i=2;i*i<=n;i++){
if(isprime[i]){
for(j=i*2;j<=n;j+=i){
isprime[j] = false;
}
}
}
}
int main(){
int tc,n,i,j;
scanf("%d",&tc);
memset(isprime,true,sizeof isprime);
sieve(maxn);
int cnt = 0;
for(i=2;i<=maxn;i++){
if(isprime[i]){prime[cnt] = i; cnt++;}
}
int square[1100];
for(i=2;i<1100;i+=2){
square[i] = i*i;
if(square[i]>maxn){break;}
}
int idxMaks = i;
while(tc--){
scanf("%d",&n);
ll numberOfDivisor = numDiv(n);
numberOfDivisor--;
// printf("numberOfDivisor: %lld\n",numberOfDivisor);
ll cnt = 0;
for(i=2;i<idxMaks;i+=2){
// printf("n: %d square[%d]: %d\n",n,i,square[i]);
if(n%square[i]==0){
// printf("suare[%d]: %d\n",i,square[i]);
if(square[i]==n){break;}
cnt++;
}
}
// printf("cnt: %lld\n",cnt);
if(cnt==0){printf("0\n"); continue;}
else{
ll gcd = __gcd(cnt,numberOfDivisor);
cnt/=gcd;
numberOfDivisor/=gcd;
printf("%lld/%lld\n",cnt,numberOfDivisor);
}
}
return 0;
}; |
2b2f46476da89601405364ecf299825343b4c123 | 81b70030247f842d2020bb1616860bde9598a936 | /practica5/partida.h | 7a4ab8703ef4e37ebdbf21ab2f4f4b06fad02c2e | [] | no_license | SalgadoWare/Gestor-de-partidas-online-dinamico- | 91cb03933e47bd2d850e91aa973c68bbf47cb0af | 32cb25414b346a4333b90030a6c8d45908741578 | refs/heads/master | 2020-12-02T16:27:00.820371 | 2017-07-07T16:19:29 | 2017-07-07T16:19:29 | 96,554,510 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,797 | h | partida.h |
//Alejandro Salgado Martin y Jorge Santos
#ifndef partida_h
#define partida_h
#include "conecta4.h"
#include "fecha.h"
typedef struct {
std::string Jug1, Jug2;
}tIdenJugadores; /*Los identificadores de los jugadores*/
typedef enum {
enCurso,
terminada,
}tEstadoPartida;
typedef struct {
std::string iden;
tIdenJugadores jugadores;
tConecta4 conecta4;
tEstadoPartida estadoPartida;
int fechaInicio, fechaActualizacion;
}tPartida;
typedef tPartida *tPntrPar; /*Creamos punteros a partidas (tipos de puntero tPartida)*/
bool carga(tPartida & partida, std::ifstream & archivo);
/* Dado un flujo de archivo de entrada (ya abierto), lee los datos que corresponden a una partida en partida.
Devuelve false si la partida no se ha podido cargar correctamente.*/
void guarda(const tPartida & partida, std::ofstream & archivo);
/*Dado un flujo de archivo de salida (ya abierto), escribe en el flujo los datos de la partida*/
void nueva(tPartida & partida, const std::string & jugador1, const std::string &jugador2);
//Recibe los identificadores de los adversarios y devuelve una partida con todos sus datos rellenos.
void abandonar(tPartida & partida);
//Modifica el estado de la partida a Terminada, y la fecha de la última actualización.
bool aplicarJugada(tPartida & partida, int col);
//Aplica la jugada col al juego, y si se pudo realizar, devuelve true y actualiza los demás campos de la partida.
bool esJugador(const tPartida & partida, const std::string & nombreUsuario);
//True: el usuario es jugador jugador de la partida recibida. False; viceversa.
bool devuelveTurno(const tPartida & partida, const std::string & nombre);
//Dada una partida y un nombre del jugador, devuelve true si es su turno
//y false si no
#endif
|
b4dbcc775ef8781b1ca360b1690171e6632d32ae | b92cc69032348afa1d6c830eb7746add8ef43849 | /MyFirstGame/SoundFX.cpp | 955c371aa89167e4918d19397ca495fbcd484542 | [] | no_license | vladcocis/Starfighters | 2082d18f955c24d788459f6c92d079c3d9be1e55 | 20716f7c4444b74ff2f0c0d9c546e68b58df0813 | refs/heads/master | 2023-08-04T23:56:17.763404 | 2021-10-05T10:22:33 | 2021-10-05T10:22:33 | 413,767,445 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,249 | cpp | SoundFX.cpp | #include "SoundFX.h"
SoundFX::SoundFX()
{
nextShipExplosion = 0;
nextAsteroidExplosion = 0;
ShipExplosions[0]=0;
AsteroidExplosions[0]=0;
Thruster = 0;
Shoot = 0;
EnemyShoot = 0;
BossExplosion = 0;
BossHit = 0;
BossShoot = 0;
Crunch = 0;
}
void SoundFX::LoadSounds()
{
nextShipExplosion = 0;
nextAsteroidExplosion = 0;
MySoundEngine* pSoundEngine = MySoundEngine::GetInstance();
Shoot = pSoundEngine->LoadWav(L"Assets/laser.wav");
EnemyShoot = pSoundEngine->LoadWav(L"Assets/shoot.wav");
BossShoot = pSoundEngine->LoadWav(L"Assets/shot3.wav");
Thruster = pSoundEngine->LoadWav(L"Assets/thrustloop2.wav");
Crunch = pSoundEngine->LoadWav(L"Assets/crunch.wav");
BossExplosion = pSoundEngine->LoadWav(L"Assets/explosion2.wav");
BossHit = pSoundEngine->LoadWav(L"Assets/shot2.wav");
for(int i=0;i<NUMEXPLOSIONS; i++)
ShipExplosions[i] = pSoundEngine->LoadWav(L"Assets/explosion1.wav");
for (int i = 0; i < NUMEXPLOSIONS; i++)
AsteroidExplosions[i] = pSoundEngine->LoadWav(L"Assets/explosion4.wav");
}
void SoundFX::PlayShoot()
{
MySoundEngine::GetInstance()->Play(Shoot);
}
void SoundFX::PlayEnemyShoot()
{
MySoundEngine::GetInstance()->Play(EnemyShoot);
}
void SoundFX::PlayBossShoot()
{
MySoundEngine::GetInstance()->Play(BossShoot);
}
void SoundFX::PlayBossHit()
{
MySoundEngine::GetInstance()->Play(BossHit);
}
void SoundFX::PlayBossExplosion()
{
MySoundEngine::GetInstance()->Play(BossExplosion);
}
void SoundFX::PlayCrunch()
{
MySoundEngine::GetInstance()->Play(Crunch);
}
void SoundFX::PlayShipExplosion()
{
MySoundEngine::GetInstance()->Play(ShipExplosions[nextShipExplosion]);
nextShipExplosion++;
if (nextShipExplosion >= NUMEXPLOSIONS)
nextShipExplosion = 0;
}
void SoundFX::PlayAsteroidExplosion()
{
MySoundEngine::GetInstance()->Play(AsteroidExplosions[nextAsteroidExplosion]);
nextAsteroidExplosion++;
if (nextAsteroidExplosion >= NUMEXPLOSIONS)
nextAsteroidExplosion = 0;
}
void SoundFX::StartThruster()
{
MySoundEngine::GetInstance()->Play(Thruster, true);
}
void SoundFX::StopThruster()
{
MySoundEngine::GetInstance()->Stop(Thruster);
}
void SoundFX::SetEngineVolume(int volume)
{
volume = (volume - 100) * 35;
MySoundEngine::GetInstance()->SetVolume(Thruster, volume);
}
|
228e483228e220a9d463165e938690bcc85ae0e3 | 9d31ba5aac1d7686d2ee3e017521a54356082bf3 | /epoch1/lab/job/job01/obj/obj.h | c8e9835ccc1f9c11a5334479bf04232e76d41d59 | [] | no_license | schwa423/Sketchy | 24bb0b2879af8200e778f6e0ebe8b6b560a676b9 | daa1dff85c1166529d2f9787545b25305702d7e0 | refs/heads/master | 2020-04-06T23:17:43.953723 | 2014-05-31T21:18:27 | 2014-05-31T21:18:27 | 3,026,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,794 | h | obj.h | //
// obj.h
// schwa::job01::obj
//
// Copyright (c) 2013 Schwaftwarez
// Licence: Apache v2.0
//
// Defines a trio of classes which work closely together:
// - Obj
// - ObjRef
// - ObjMaker
//
// More details about these classes can be found in obj_defs.h
//
// The purpose of this header file is to allow compile-time specification of
// multiple, disjoint object systems... in other words, the type-system
// statically prevents objects from one system to leak into another.
//
// This isn't possible quite yet (see TODO below), but here's an example
// scenario describing how it would work.
// - The programmer decides to create an in-process debugger which can
// control the application's job-system. This functionality will live
// in schwa::job::debugger.
// - To support this, a clone of this object-system (schwa::job01::obj) is
// desired... it will live in schwa::job01::debugger::obj.
// - To make this happen, a "debugger_obj.h" header is created which is very
// similar to this one, except instead of wrapping "obj_defs.h" in
// namespace schwa::job01::obj, it is instead wrapped in the namespace
// schwa::job01::debugger::obj.
//
// TODO:
// - cannot yet wrap the contents of obj.cc in different namespaces
//
///////////////////////////////////////////////////////////////////////////////
#ifndef __schwa__job01__obj__obj_______________________________________________
#define __schwa__job01__obj__obj_______________________________________________
#include "job01/obj/obj_includes.h"
namespace schwa { namespace job01 { namespace obj {
#include "job01/obj/obj_defs.h"
}}}
#endif // __schwa__job01__obj__obj____________________________________________
|
c3f02df62a966c9a6e633f0fa64fbb39eebcbc1d | 22fb1afd55fa92a98e87576aba4b66bec21655c1 | /Ps3sxMain.cpp | 41e18efd74e0f6f878a88f793f3de2c22b85f45d | [] | no_license | Zarh/ps3sx | 060940ce0593eb09bcc8e0d3b2ac86733ddc395f | 125ca47d6a29967adfb61eb60d226de5ea48ab83 | refs/heads/main | 2023-07-24T14:24:09.549625 | 2021-09-09T20:29:50 | 2021-09-09T20:29:50 | 404,862,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,746 | cpp | Ps3sxMain.cpp | #include "cell.h"
#include <vector>
#include "rom_list.h"
#include <math.h>
#include <sys/paths.h>
#include "ps3video.h"
#include "ps3audio.h"
#include "cellinput.h"
#include "ini.h"
#include <unistd.h>
#include <pthread.h>
#include <sysutil/sysutil_gamecontent.h>
SYS_PROCESS_PARAM(1001, 0x10000);
PS3Graphics* Graphics;
CellInputFacade* PS3input = 0;
FileIniConfig Iniconfig;
bool is_running = 0;
int boot_cdrom;
int RomType=0;
int CpuConfig = 0;
#define SAMPLERATE_44KHZ 44100
#define SB_SIZE 3840
static bool runbios = 0;
char rom_path[256];
void InitPS3()
{
Graphics = new PS3Graphics();
Graphics->Init();
// FIXME: Is this necessary?
if (Graphics->InitCg() != CELL_OK)
{
printf("Failed to InitCg: %d\n", __LINE__);
exit(0);
}
PS3input = new CellInputFacade();
Graphics->InitDbgFont();
}
extern "C"
{
#include "psxcommon.h"
#include "Sio.h"
#include "PlugCD.h"
#include "plugins.h"
#include "misc.h"
#include "R3000a.h"
void SysPrintf(char *fmt, ...);
int NeedReset = 0;
int Running =0;
long LoadCdBios = 0;
//Sound Function
unsigned long SoundGetBytesBuffered(void)
{
return cellAudioPortWriteAvail();
}
void SoundFeedStreamData(unsigned char *pSound, long lBytes)
{
cellAudioPortWrite((const audio_input_t*)pSound,lBytes / 2);
}
void SetupSound(void)
{
cellAudioPortInit(SAMPLERATE_44KHZ,SB_SIZE);
}
void RemoveSound(void)
{
cellAudioPortExit();
sys_ppu_thread_exit(0);
}
//end Sound
//Video Output Function
void ps3sxSwapBuffer(unsigned char *pixels,int w,int h)
{
Graphics->Draw(w,h,pixels);
Graphics->Swap();
}
//end Video
//Start PAD
long PAD__readPort1(PadDataS* pad)
{
static unsigned short pad_status = 0xffff;
PS3input->UpdateDevice(0);
if (PS3input->IsButtonPressed(0,CTRL_CIRCLE))
{
pad_status &= ~(1<<13);
}else{
pad_status |= (1<<13);
}
if (PS3input->IsButtonPressed(0,CTRL_CROSS))
{
pad_status &= ~(1<<14);
}else{
pad_status |= (1<<14);
}
if (PS3input->IsButtonPressed(0,CTRL_SELECT))
{
pad_status &= ~(1<<2);
}else{
pad_status |= (1<<2);
}
if (PS3input->IsButtonPressed(0,CTRL_START))
{
pad_status &= ~(1<<3);
}else{
pad_status |= (1<<3);
}
if (PS3input->IsButtonPressed(0,CTRL_DOWN))
{
pad_status &= ~(1<<6);
}else{
pad_status |= (1<<6);
}
if (PS3input->IsButtonPressed(0,CTRL_UP))
{
pad_status &= ~(1<<4);
}else{
pad_status |= (1<<4);
}
if (PS3input->IsButtonPressed(0,CTRL_RIGHT))
{
pad_status &= ~(1<<5);
}else{
pad_status |= (1<<5);
}
if (PS3input->IsButtonPressed(0,CTRL_LEFT))
{
pad_status &= ~(1<<7);
}else{
pad_status |= (1<<7);
}
if (PS3input->IsButtonPressed(0,CTRL_R1))
{
pad_status &= ~(1<<11);
}else{
pad_status |= (1<<11);
}
if (PS3input->IsButtonPressed(0,CTRL_L1))
{
pad_status &= ~(1<<10);
}else{
pad_status |= (1<<10);
}
if (PS3input->IsButtonPressed(0,CTRL_R2))
{
pad_status &= ~(1<<8);
}else{
pad_status |= (1<<8);
}
if (PS3input->IsButtonPressed(0,CTRL_L2))
{
pad_status &= ~(1<<9);
}else{
pad_status |= (1<<9);
}
if (PS3input->IsButtonPressed(0,CTRL_TRIANGLE))
{
pad_status &= ~(1<<12);
}else{
pad_status |= (1<<12);
}
if (PS3input->IsButtonPressed(0,CTRL_SQUARE))
{
pad_status &= ~(1<<15);
}else{
pad_status |= (1<<15);
}
pad->buttonStatus = pad_status;
if(Settings.PAD)
pad->controllerType = PSE_PAD_TYPE_ANALOGPAD;
else
pad->controllerType = PSE_PAD_TYPE_STANDARD;
return PSE_PAD_ERR_SUCCESS;
}
long PAD__readPort2(PadDataS* pad)
{
static unsigned short pad_status = 0xffff;
PS3input->UpdateDevice(1);
if (PS3input->IsButtonPressed(1,CTRL_CIRCLE))
{
pad_status &= ~(1<<13);
}else{
pad_status |= (1<<13);
}
if (PS3input->IsButtonPressed(1,CTRL_CROSS))
{
pad_status &= ~(1<<14);
}else{
pad_status |= (1<<14);
}
if (PS3input->IsButtonPressed(1,CTRL_SELECT))
{
pad_status &= ~(1<<2);
}else{
pad_status |= (1<<2);
}
if (PS3input->IsButtonPressed(1,CTRL_START))
{
pad_status &= ~(1<<3);
}else{
pad_status |= (1<<3);
}
if (PS3input->IsButtonPressed(1,CTRL_DOWN))
{
pad_status &= ~(1<<6);
}else{
pad_status |= (1<<6);
}
if (PS3input->IsButtonPressed(1,CTRL_UP))
{
pad_status &= ~(1<<4);
}else{
pad_status |= (1<<4);
}
if (PS3input->IsButtonPressed(1,CTRL_RIGHT))
{
pad_status &= ~(1<<5);
}else{
pad_status |= (1<<5);
}
if (PS3input->IsButtonPressed(1,CTRL_LEFT))
{
pad_status &= ~(1<<7);
}else{
pad_status |= (1<<7);
}
if (PS3input->IsButtonPressed(1,CTRL_R1))
{
pad_status &= ~(1<<11);
}else{
pad_status |= (1<<11);
}
if (PS3input->IsButtonPressed(1,CTRL_L1))
{
pad_status &= ~(1<<10);
}else{
pad_status |= (1<<10);
}
if (PS3input->IsButtonPressed(1,CTRL_R2))
{
pad_status &= ~(1<<8);
}else{
pad_status |= (1<<8);
}
if (PS3input->IsButtonPressed(1,CTRL_L2))
{
pad_status &= ~(1<<9);
}else{
pad_status |= (1<<9);
}
if (PS3input->IsButtonPressed(1,CTRL_TRIANGLE))
{
pad_status &= ~(1<<12);
}else{
pad_status |= (1<<12);
}
if (PS3input->IsButtonPressed(1,CTRL_SQUARE))
{
pad_status &= ~(1<<15);
}else{
pad_status |= (1<<15);
}
pad->buttonStatus = pad_status;
if(Settings.PAD)
pad->controllerType = PSE_PAD_TYPE_ANALOGPAD;
else
pad->controllerType = PSE_PAD_TYPE_STANDARD;
return PSE_PAD_ERR_SUCCESS;
}
//end Pad
void InitConfig()
{
memset(&Config, 0, sizeof(PcsxConfig));
Config.PsxAuto = 1; //Autodetect
Config.HLE = Settings.HLE; //Use HLE
Config.Xa = 0; //disable xa decoding (audio)
Config.Sio = 0; //disable sio interrupt ?
Config.Mdec = 0; //movie decode
Config.Cdda = 0; //diable cdda playback
Config.Cpu = Settings.CPU;// interpreter 1 : dynarec 0
Config.SpuIrq = 0;
Config.RCntFix = 0;//Parasite Eve 2, Vandal Hearts 1/2 Fix
Config.VSyncWA = 0; // interlaced /non ? something with the display timer
Config.PsxOut = 0; // on screen debug
Config.UseNet = 0;
strcpy(Config.Net, "Disabled");
strcpy(Config.Net, _("Disabled"));
strcpy(Config.BiosDir, Iniconfig.biospath);
//Set Bios
sprintf(Config.BiosDir, "%s/scph1001.bin",Iniconfig.biospath);
sprintf(Config.Mcd1, "%s/Mcd001.mcr",Iniconfig.savpath);
sprintf(Config.Mcd2, "%s/Mcd002.mcr",Iniconfig.savpath);
}
static int sysInited = 0;
int SysInit()
{
sysInited = 1;
SysPrintf("start SysInit()\n");
SysPrintf("psxInit()\n");
psxInit();
SysPrintf("LoadPlugins()\n");
LoadPlugins();
SysPrintf("LoadMcds()\n");
LoadMcds(Config.Mcd1, Config.Mcd2);
SysPrintf("end SysInit()\n");
return 0;
}
void SysReset() {
SysPrintf("start SysReset()\n");
psxReset();
SysPrintf("end SysReset()\n");
}
void SysPrintf(char *fmt, ...) {
va_list list;
char msg[512];
va_start(list, fmt);
vsprintf(msg, fmt, list);
va_end(list);
dprintf_console(msg);
if(emuLog == NULL) emuLog = fopen("/dev_hdd0/emuLog.txt","wb");
if(emuLog) {
fputs(msg, emuLog);
fflush(emuLog);
}
printf(msg);
}
void SysMessage(char *fmt, ...) {
va_list list;
char msg[512];
va_start(list, fmt);
vsprintf(msg, fmt, list);
va_end(list);
dprintf_console(msg);
if(emuLog == NULL) emuLog = fopen("/dev_hdd0/emuLog.txt","wb");
if(emuLog) {
fputs(msg, emuLog);
fflush(emuLog);
fclose(emuLog);
}
printf(msg);
}
void *SysLoadLibrary(char *lib) {
return lib;
}
void *SysLoadSym(void *lib, char *sym) {
return lib; //smhzc
}
const char *SysLibError() {
}
void SysCloseLibrary(void *lib) {
}
// Called periodically from the emu thread
void SysUpdate() {
}
// Returns to the Gui
void SysRunGui()
{
}
// Close mem and plugins
void SysClose() {
psxShutdown();
ReleasePlugins();
}
void OnFile_Exit() {
}
void RunCD(){ // run the cd, no bios
LoadCdBios = 0;
SysPrintf("RunCD\n");
newCD(rom_path);
SysReset();
CheckCdrom();
if (LoadCdrom() == -1) {
ClosePlugins();
exit(0);//epic fail
}
psxCpu->Execute();
}
void RunCDBIOS(){ // run the bios on the cd?
SysPrintf("RunCDBIOS\n");
LoadCdBios = 1;
newCD(rom_path);
CheckCdrom();
SysReset();
psxCpu->Execute();
}
void RunEXE(){
SysPrintf("RunEXE\n");
SysReset();
Load(rom_path);
psxCpu->Execute();
}
void RunBios(){
SysPrintf("RunBios\n");
SysReset();
SysMessage("Bios done!!!\n");
psxCpu->Execute();
}
void sysutil_callback (uint64_t status, uint64_t param, void *userdata) {
(void) param;
(void) userdata;
switch (status) {
case CELL_SYSUTIL_REQUEST_EXITGAME:
SysPrintf("exit from game\n");
is_running = 0;
break;
case CELL_SYSUTIL_DRAWING_BEGIN:
case CELL_SYSUTIL_DRAWING_END:
break;
}
}
//we parse our ini files
static int handler(void* user, const char* section, const char* name,const char* value)
{
FileIniConfig* pconfig = (FileIniConfig*)user;
#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0
if (MATCH("PS3SX", "version")) {
pconfig->version = strdup(value);
} else if (MATCH("psxrom", "rompath")) {
pconfig->rompath = strdup(value);
} else if (MATCH("psxsav", "savpath")) {
pconfig->savpath = strdup(value);
}else if (MATCH("psxsram", "srampath")) {
pconfig->sram_path = strdup(value);
}else if (MATCH("psxbios", "biospath")) {
pconfig->biospath = strdup(value);
}
}
void CreatFolder(char* folders)
{
struct stat st;
if( stat(folders,&st) == 0) return;
if(mkdir(folders,0777))
{
gl_dprintf(0.09f,0.05f,FontSize(),"Error folder cannot be created %s !!\nplease check your GenesisConf.ini\n",folders);
sys_timer_sleep(5);
sys_process_exit(0);
}
}
void RomBrowser()
{
SysPrintf("aspec ration 0x%X \n",(int)Graphics->GetDeviceAspectRatio());
//detection 16/9 or 4/3 Anonymous
if((int)Graphics->GetDeviceAspectRatio() == 0x1) //0x1 == 16:9
Graphics->SetAspectRatio(0); // 16:9
else
Graphics->SetAspectRatio(1); // 4:3
//browser with roms folder
MenuMainLoop(Iniconfig.rompath);
InitConfig();
if (Config.HLE){
strcpy(Config.Bios, "HLE");
}else{
strcpy(Config.Bios, "scph1001.bin");
}
SysInit();
OpenPlugins();
//clear screen to black
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
}
int main()
{
emuLog=NULL;
int i, ret;
struct stat st;
sys_spu_initialize(6, 1);
cellSysutilRegisterCallback(0, (CellSysutilCallback)sysutil_callback, NULL);
ret = cellSysmoduleLoadModule(CELL_SYSMODULE_FS);
if( ret != 0) printf("CELL_SYSMODULE_FS error %X\n", ret);
ret = cellSysmoduleLoadModule(CELL_SYSMODULE_IO);
if( ret != 0) printf("CELL_SYSMODULE_IO error %X\n", ret);
ret = cellSysmoduleLoadModule(CELL_SYSMODULE_SYSUTIL_GAME);
if( ret != 0) printf("CELL_SYSMODULE_SYSUTIL_GAME error %X\n", ret);
is_running = 1;
InitPS3();
PS3input->Init();
printf("InitPS3 done\n");
unsigned int type = 0;
unsigned int attributes = 0;
char usrdirPath[255];
char contentInfoPath[255];
// we must use cellGameBootCheck before cellGameContentPermit
ret = cellGameBootCheck(&type, &attributes, NULL, NULL);
if (ret != CELL_GAME_RET_OK) {
SysPrintf("cellGameBootCheck Error %X\n",ret);
}
printf("cellGameContentPermit\n");
ret = cellGameContentPermit(contentInfoPath, usrdirPath);
if (ret != CELL_GAME_RET_OK) {
SysPrintf("cellGameContentPermit failed %X\n",ret);
strcpy(usrdirPath, "/dev_hdd0/game/PCSX00001/USRDIR");
}
char ConfigPath[255];
sprintf(ConfigPath, "%s/Ps3sxConf.ini", usrdirPath);
SysPrintf("ini_parse\n");
//read the ini now
if (ini_parse(ConfigPath, handler, &Iniconfig) < 0)
{
gl_dprintf(0.09f,0.05f,FontSize(),"Can't load %s\n", ConfigPath);
sys_timer_sleep(1);
gl_dprintf(0.09f,0.05f,FontSize(),"Wtf where is the ini!!!!!!!!bye bye try again\nPath: %s", ConfigPath);
sys_timer_sleep(5);
sys_process_exit(0);
}
//main path Check if not present creat all folder and exit
CreatFolder(Iniconfig.rompath);
CreatFolder(Iniconfig.savpath);
CreatFolder(Iniconfig.sram_path);
CreatFolder(Iniconfig.biospath);
SysPrintf(" version %s \n",Iniconfig.version);
SysPrintf(" rompath %s \n",Iniconfig.rompath);
SysPrintf(" savpath %s \n",Iniconfig.savpath);
SysPrintf(" srampath %s \n",Iniconfig.sram_path);
SysPrintf(" biospath %s \n",Iniconfig.biospath);
SysPrintf("Run the emulator\n");
RomBrowser();
//clear screen to black
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
switch(RomType){
case 1:
RunEXE();
case 2:
RunCD();
default:
RunBios();
}
SysPrintf("done \n");
cellSysmoduleUnloadModule(CELL_SYSMODULE_IO);
cellSysmoduleUnloadModule(CELL_SYSMODULE_FS);
cellSysmoduleUnloadModule(CELL_SYSMODULE_SYSUTIL_GAME);
cellSysutilUnregisterCallback(0);
return(-1);
}
} |
5b3d9db927d945460200c99247c60cde4f9d63a2 | b57a3d99fa522fdca2a7d34fc36557073a93871f | /Source/Oscillator.h | 586a71ba3062a3347dcf76bf987b3c6e34abeaf5 | [] | no_license | nseaSeb/Sysex77 | 7915f6da54ea2d24856334bf29f0250f830b5277 | a804cd5b73dbcd21e43d783b606cb3d09201bd0f | refs/heads/master | 2023-06-21T06:24:00.531588 | 2023-06-18T11:21:32 | 2023-06-18T11:21:32 | 170,392,221 | 14 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 24,080 | h | Oscillator.h | /*
==============================================================================
Oscillator.h
Created: 25 Nov 2018 8:29:30pm
Author: Sébastien Portrait
==============================================================================
*/
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
//==============================================================================
/*
*/
class Oscillator : public ElementComponent, public TextButton::Listener
{
public:
Oscillator()
{
// In your constructor, you should add any child components, and
// initialise any special settings that your component needs.
// setBounds(getBoundsInParent());
addAndMakeVisible(groupOP1);
addAndMakeVisible(groupOP2);
addAndMakeVisible(groupOP3);
addAndMakeVisible(groupOP4);
addAndMakeVisible(groupOP5);
addAndMakeVisible(groupOP6);
setOscSliderStyle(sliderOsc1);
setOscSliderStyle(sliderOsc2);
setOscSliderStyle(sliderOsc3);
setOscSliderStyle(sliderOsc4);
setOscSliderStyle(sliderOsc5);
setOscSliderStyle(sliderOsc6);
setSliderStyle(sliderFine1);
labelFine1.attachToComponent(&sliderFine1, false);
setSliderDetune(sliderDetune1);
labelDetune1.attachToComponent(&sliderDetune1, false);
labelDetune1.setJustificationType(Justification::centred);
setSliderStyle(sliderPhase1);
labelPhase1.attachToComponent(&sliderPhase1, false);
setSliderStyle(sliderFine2);
labelFine2.attachToComponent(&sliderFine1, false);
setSliderDetune(sliderDetune2);
labelDetune2.attachToComponent(&sliderDetune2, false);
labelDetune2.setJustificationType(Justification::centred);
setSliderStyle(sliderPhase2);
labelPhase2.attachToComponent(&sliderPhase1, false);
setSliderStyle(sliderFine3);
labelFine3.attachToComponent(&sliderFine3, false);
setSliderDetune(sliderDetune3);
labelDetune3.attachToComponent(&sliderDetune3, false);
labelDetune3.setJustificationType(Justification::centred);
setSliderStyle(sliderPhase3);
labelPhase3.attachToComponent(&sliderPhase3, false);
setSliderStyle(sliderFine4);
labelFine4.attachToComponent(&sliderFine4, false);
setSliderDetune(sliderDetune4);
labelDetune4.attachToComponent(&sliderDetune4, false);
labelDetune4.setJustificationType(Justification::centred);
setSliderStyle(sliderPhase4);
labelPhase4.attachToComponent(&sliderPhase4, false);
setSliderStyle(sliderFine5);
labelFine5.attachToComponent(&sliderFine5, false);
setSliderDetune(sliderDetune5);
labelDetune5.attachToComponent(&sliderDetune5, false);
labelDetune5.setJustificationType(Justification::centred);
setSliderStyle(sliderPhase5);
labelPhase5.attachToComponent(&sliderPhase5, false);
setSliderStyle(sliderFine6);
labelFine6.attachToComponent(&sliderFine6, false);
setSliderDetune(sliderDetune6);
labelDetune6.attachToComponent(&sliderDetune6, false);
labelDetune6.setJustificationType(Justification::centred);
setSliderStyle(sliderPhase6);
labelPhase6.attachToComponent(&sliderPhase6, false);
// addAndMakeVisible(labelOsc1);
// labelOsc1.attachToComponent(&sliderOsc1, false);
addAndMakeVisible(btFix1);
addAndMakeVisible(btFix2);
addAndMakeVisible(btFix3);
addAndMakeVisible(btFix4);
addAndMakeVisible(btFix5);
addAndMakeVisible(btFix6);
btFix1.setTextOnOff("Fixed", "Ratio");
btFix2.setTextOnOff("Fixed", "Ratio");
btFix3.setTextOnOff("Fixed", "Ratio");
btFix4.setTextOnOff("Fixed", "Ratio");
btFix5.setTextOnOff("Fixed", "Ratio");
btFix6.setTextOnOff("Fixed", "Ratio");
addAndMakeVisible(btPhase1);
addAndMakeVisible(btPhase2);
addAndMakeVisible(btPhase3);
addAndMakeVisible(btPhase4);
addAndMakeVisible(btPhase5);
addAndMakeVisible(btPhase6);
btPhase1.setTextOnOff("Sync Off", "Sync On");
btPhase2.setTextOnOff("Sync Off", "Sync On");
btPhase3.setTextOnOff("Sync Off", "Sync On");
btPhase4.setTextOnOff("Sync Off", "Sync On");
btPhase5.setTextOnOff("Sync Off", "Sync On");
btPhase6.setTextOnOff("Sync Off", "Sync On");
}
~Oscillator()
{
}
void setSliderDetune (Slider& slider)
{
addAndMakeVisible(slider);
slider.setSliderStyle(Slider::SliderStyle::Rotary);
slider.setRange(-15, 15);
slider.setNumDecimalPlacesToDisplay(0);
slider.setLookAndFeel(&myLookAndFeel);
slider.setPopupDisplayEnabled(true, true,this);
}
void setSliderStyle (Slider& slider)
{
addAndMakeVisible(slider);
slider.setPopupDisplayEnabled(true, true, this);
slider.setRange(0, 127);
slider.setNumDecimalPlacesToDisplay(0);
// slider.setLookAndFeel(&OscLook);
slider.setSliderStyle(Slider::SliderStyle::LinearHorizontal);
// slider.setTextBoxStyle(Slider::TextBoxBelow, false, 40, 18);
}
void setOscSliderStyle (Slider& slider)
{
addAndMakeVisible(slider);
slider.setPopupDisplayEnabled(true, true, this);
slider.setRange(0, 15);
slider.setNumDecimalPlacesToDisplay(0);
slider.setLookAndFeel(&OscLook);
slider.setSliderStyle(Slider::SliderStyle::RotaryHorizontalVerticalDrag);
// slider.setTextBoxStyle(Slider::TextBoxBelow, false, 40, 18);
}
void setElementNumber ( int element, UndoManager& um) override
{
int sysexdata2[9] = { 0x43, 0X10, 0x34, 0x56, 0x00, 0x00, 0x26, 0x00, 0x00 };
int sysexdata[9] = { 0x43, 0X10, 0x34, 0x46, 0x00, 0x00, 0x17, 0x00, 0x00 };
if(element == 1)
{
sliderOsc1.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSC1, &um));
sliderOsc2.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSC2, &um));
sliderOsc3.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSC3, &um));
sliderOsc4.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSC4, &um));
sliderOsc5.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSC5, &um));
sliderOsc6.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSC6, &um));
btFix1.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSCFIX1, &um));
btFix2.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSCFIX2, &um));
btFix3.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSCFIX3, &um));
btFix4.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSCFIX4, &um));
btFix5.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSCFIX5, &um));
btFix6.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSCFIX6, &um));
btPhase1.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSCSYNC1, &um));
btPhase2.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSCSYNC2, &um));
btPhase3.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSCSYNC3, &um));
btPhase4.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSCSYNC4, &um));
btPhase5.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSCSYNC5, &um));
btPhase6.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT1OSCSYNC6, &um));
}
else if (element ==2)
{
sysexdata[4] = 0x20;
sysexdata2[4] = 0x20;
sliderOsc1.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSC1, &um));
sliderOsc2.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSC2, &um));
sliderOsc3.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSC3, &um));
sliderOsc4.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSC4, &um));
sliderOsc5.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSC5, &um));
sliderOsc6.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSC6, &um));
btFix1.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSCFIX1, &um));
btFix2.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSCFIX2, &um));
btFix3.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSCFIX3, &um));
btFix4.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSCFIX4, &um));
btFix5.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSCFIX5, &um));
btFix6.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSCFIX6, &um));
btPhase1.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSCSYNC1, &um));
btPhase2.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSCSYNC2, &um));
btPhase3.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSCSYNC3, &um));
btPhase4.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSCSYNC4, &um));
btPhase5.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSCSYNC5, &um));
btPhase6.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT2OSCSYNC6, &um));
}
else if (element == 3)
{
sysexdata[4] = 0x40;
sysexdata2[4] = 0x40;
sliderOsc1.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSC1, &um));
sliderOsc2.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSC2, &um));
sliderOsc3.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSC3, &um));
sliderOsc4.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSC4, &um));
sliderOsc5.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSC5, &um));
sliderOsc6.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSC6, &um));
btFix1.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSCFIX1, &um));
btFix2.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSCFIX2, &um));
btFix3.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSCFIX3, &um));
btFix4.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSCFIX4, &um));
btFix5.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSCFIX5, &um));
btFix6.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSCFIX6, &um));
btPhase1.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSCSYNC1, &um));
btPhase2.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSCSYNC2, &um));
btPhase3.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSCSYNC3, &um));
btPhase4.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSCSYNC4, &um));
btPhase5.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSCSYNC5, &um));
btPhase6.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT3OSCSYNC6, &um));
}
else if (element == 4)
{
sysexdata[4] = 0x60;
sysexdata2[4] = 0x60;
sliderOsc1.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSC1, &um));
sliderOsc2.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSC2, &um));
sliderOsc3.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSC3, &um));
sliderOsc4.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSC4, &um));
sliderOsc5.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSC5, &um));
sliderOsc6.getValueObject().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSC6, &um));
btFix1.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSCFIX1, &um));
btFix2.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSCFIX2, &um));
btFix3.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSCFIX3, &um));
btFix4.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSCFIX4, &um));
btFix5.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSCFIX5, &um));
btFix6.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSCFIX6, &um));
btPhase1.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSCSYNC1, &um));
btPhase2.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSCSYNC2, &um));
btPhase3.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSCSYNC3, &um));
btPhase4.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSCSYNC4, &um));
btPhase5.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSCSYNC5, &um));
btPhase6.getToggleStateValue().referTo(valueTreeVoice.getPropertyAsValue(IDs::AFMELEMENT4OSCSYNC6, &um));
}
sysexdata[3] = 0x56;
sliderOsc1.setMidiSysex(sysexdata);
sysexdata[3] = 0x46;
sliderOsc2.setMidiSysex(sysexdata);
sysexdata[3] = 0x36;
sliderOsc3.setMidiSysex(sysexdata);
sysexdata[3] = 0x26;
sliderOsc4.setMidiSysex(sysexdata);
sysexdata[3] = 0x16;
sliderOsc5.setMidiSysex(sysexdata);
sysexdata[3] = 0x06;
sliderOsc6.setMidiSysex(sysexdata);
sysexdata[6] = 0x18;
sysexdata[3] = 0x56;
btFix1.setMidiSysex(sysexdata);
sysexdata[3] = 0x46;
btFix2.setMidiSysex(sysexdata);
sysexdata[3] = 0x36;
btFix3.setMidiSysex(sysexdata);
sysexdata[3] = 0x26;
btFix4.setMidiSysex(sysexdata);
sysexdata[3] = 0x16;
btFix5.setMidiSysex(sysexdata);
sysexdata[3] = 0x06;
btFix6.setMidiSysex(sysexdata);
sysexdata[6] = 0x19;
sysexdata[3] = 0x56;
btPhase1.setMidiSysex(sysexdata);
sysexdata[3] = 0x46;
btPhase2.setMidiSysex(sysexdata);
sysexdata[3] = 0x36;
btPhase3.setMidiSysex(sysexdata);
sysexdata[3] = 0x26;
btPhase4.setMidiSysex(sysexdata);
sysexdata[3] = 0x16;
btPhase5.setMidiSysex(sysexdata);
sysexdata[3] = 0x06;
btPhase6.setMidiSysex(sysexdata);
sysexdata[7] = 0x01;
sysexdata[3] = 0x56;
sliderPhase1.setMidiSysex(sysexdata);
sysexdata[3] = 0x46;
sliderPhase2.setMidiSysex(sysexdata);
sysexdata[3] = 0x36;
sliderPhase3.setMidiSysex(sysexdata);
sysexdata[3] = 0x26;
sliderFine4.setMidiSysex(sysexdata);
sysexdata[3] = 0x16;
sliderPhase5.setMidiSysex(sysexdata);
sysexdata[3] = 0x06;
sliderPhase6.setMidiSysex(sysexdata);
sysexdata[7] = 0x00;
sysexdata[6] = 0x26;
sysexdata[3] = 0x56;
sliderFine1.setMidiSysex(sysexdata);
sysexdata[3] = 0x46;
sliderFine2.setMidiSysex(sysexdata);
sysexdata[3] = 0x36;
sliderFine3.setMidiSysex(sysexdata);
sysexdata[3] = 0x26;
sliderFine4.setMidiSysex(sysexdata);
sysexdata[3] = 0x16;
sliderFine5.setMidiSysex(sysexdata);
sysexdata[3] = 0x06;
sliderFine6.setMidiSysex(sysexdata);
sysexdata[6] = 0x1a;
sysexdata[3] = 0x56;
sliderDetune1.setMidiSysex(sysexdata);
sysexdata[3] = 0x46;
sliderDetune2.setMidiSysex(sysexdata);
sysexdata[3] = 0x36;
sliderDetune3.setMidiSysex(sysexdata);
sysexdata[3] = 0x26;
sliderDetune4.setMidiSysex(sysexdata);
sysexdata[3] = 0x16;
sliderDetune5.setMidiSysex(sysexdata);
sysexdata[3] = 0x06;
sliderDetune6.setMidiSysex(sysexdata);
}
void buttonClicked (Button* button) override
{
}
void paint (Graphics& g) override
{
/* This demo code just fills the component's background and
draws some placeholder text to get you started.
You should replace everything in this method with your own
drawing code..
*/
g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId)); // clear the background
//g.setColour (Colours::darkorange);
// g.drawText ("AFM a implementer", getLocalBounds(),
// Justification::centred, true); // draw some placeholder text
}
void resized() override
{
// This method is where you should set the bounds of any child
// components that your component contains..
groupOP1.setBoundsRelative(0.0f, 0.0f, 0.33f, 0.5f);
sliderOsc1.setBoundsRelative(0.2f, 0.04f, 0.12f, 1.0f);
sliderFine1.setBoundsRelative(0.01f, 0.1f, 0.18f, 0.06f);
sliderDetune1.setBoundsRelative(0.01f, 0.2f, 0.18f, 0.16f);
sliderPhase1.setBoundsRelative(0.01f, 0.4f, 0.18f, 0.06f);
roundSize(sliderOsc1);
btFix1.setBoundsRelative(0.2f, 0.3f, 0.12f, 0.06f);
btPhase1.setBoundsRelative(0.2f, 0.4f, 0.12f, 0.06f);
groupOP2.setBoundsRelative(0.33f, 0, 0.33f, 0.5f);
sliderOsc2.setBoundsRelative(0.53f, 0.04f, 0.12f, 1.0f);
sliderFine2.setBoundsRelative(0.34f, 0.1f, 0.18f, 0.06f);
sliderDetune2.setBoundsRelative(0.34f, 0.2f, 0.18f, 0.16f);
sliderPhase2.setBoundsRelative(0.34f, 0.4f, 0.18f, 0.06f);
roundSize(sliderOsc2);
btFix2.setBoundsRelative(0.53f, 0.3f, 0.12f, 0.06f);
btPhase2.setBoundsRelative(0.53f, 0.4f, 0.12f, 0.06f);
groupOP3.setBoundsRelative(0.66f, 0, 0.33f, 0.5f);
sliderOsc3.setBoundsRelative(0.86f, 0.04f, 0.12f, 1.0f);
sliderFine3.setBoundsRelative(0.67f, 0.1f, 0.18f, 0.06f);
sliderDetune3.setBoundsRelative(0.67f, 0.2f, 0.18f, 0.16f);
sliderPhase3.setBoundsRelative(0.67f, 0.4f, 0.18f, 0.06f);
roundSize(sliderOsc3);
btFix3.setBoundsRelative(0.86f, 0.3f, 0.12f, 0.06f);
btPhase3.setBoundsRelative(0.86f, 0.4f, 0.12f, 0.06f);
groupOP4.setBoundsRelative(0, 0.5f, 0.33f, 0.5f);
sliderOsc4.setBoundsRelative(0.2f, 0.54f, 0.12f, 1.0f);
sliderFine4.setBoundsRelative(0.01f, 0.6f, 0.18f, 0.06f);
sliderDetune4.setBoundsRelative(0.01f, 0.7f, 0.18f, 0.16f);
sliderPhase4.setBoundsRelative(0.01f, 0.9f, 0.18f, 0.06f);
roundSize(sliderOsc4);
btFix4.setBoundsRelative(0.2f, 0.8f, 0.12f, 0.06f);
btPhase4.setBoundsRelative(0.2f, 0.9f, 0.12f, 0.06f);
groupOP5.setBoundsRelative(0.33f, 0.5f, 0.33f, 0.5f);
sliderOsc5.setBoundsRelative(0.53f, 0.54f, 0.12f, 1.0f);
sliderFine5.setBoundsRelative(0.34f, 0.6f, 0.18f, 0.06f);
sliderDetune5.setBoundsRelative(0.34f, 0.7f, 0.18f, 0.16f);
sliderPhase5.setBoundsRelative(0.34f, 0.9f, 0.18f, 0.06f);
roundSize(sliderOsc5);
btFix5.setBoundsRelative(0.53f, 0.8f, 0.12f, 0.06f);
btPhase5.setBoundsRelative(0.53f, 0.9f, 0.12f, 0.06f);
groupOP6.setBoundsRelative(0.66f, 0.5f, 0.33f, 0.5f);
sliderOsc6.setBoundsRelative(0.86f, 0.54f, 0.12f, 1.0f);
sliderFine6.setBoundsRelative(0.67f, 0.6f, 0.18f, 0.06f);
sliderDetune6.setBoundsRelative(0.67f, 0.7f, 0.18f, 0.16f);
sliderPhase6.setBoundsRelative(0.67f, 0.9f, 0.18f, 0.06f);
roundSize(sliderOsc6);
btFix6.setBoundsRelative(0.86f, 0.8f, 0.12f, 0.06f);
btPhase6.setBoundsRelative(0.86f, 0.9f, 0.12f, 0.06f);
}
void roundSize (Slider& slider)
{
int w;
w = jmin(slider.getWidth(),slider.getHeight());
slider.setBounds(slider.getX(), slider.getY(), w, w);
}
private:
GroupComponent groupOP1 {"Op1", "OP1"};
GroupComponent groupOP2 {"Op1", "OP2"};
GroupComponent groupOP3 {"Op1", "OP3"};
GroupComponent groupOP4 {"Op1", "OP4"};
GroupComponent groupOP5 {"Op1", "OP5"};
GroupComponent groupOP6 {"Op1", "OP6"};
MidiSlider sliderOsc1;
MidiSlider sliderOsc2;
MidiSlider sliderOsc3;
MidiSlider sliderOsc4;
MidiSlider sliderOsc5;
MidiSlider sliderOsc6;
MidiSlider sliderFine1;
MidiSlider sliderDetune1;
MidiSlider sliderPhase1;
Label labelFine1 {"f1", "Coarse Fine"};
Label labelDetune1 {"f1", "Detune"};
Label labelPhase1 {"f1", "Phase"};
MidiSlider sliderFine2;
MidiSlider sliderDetune2;
MidiSlider sliderPhase2;
Label labelFine2 {"f1", "Coarse Fine"};
Label labelDetune2 {"f1", "Detune"};
Label labelPhase2 {"f1", "Phase"};
MidiSlider sliderFine3;
MidiSlider sliderDetune3;
MidiSlider sliderPhase3;
Label labelFine3 {"f1", "Coarse Fine"};
Label labelDetune3 {"f1", "Detune"};
Label labelPhase3 {"f1", "Phase"};
MidiSlider sliderFine4;
MidiSlider sliderDetune4;
MidiSlider sliderPhase4;
Label labelFine4 {"f1", "Coarse Fine"};
Label labelDetune4 {"f1", "Detune"};
Label labelPhase4 {"f1", "Phase"};
MidiSlider sliderFine5;
MidiSlider sliderDetune5;
MidiSlider sliderPhase5;
Label labelFine5 {"f1", "Coarse Fine"};
Label labelDetune5 {"f1", "Detune"};
Label labelPhase5 {"f1", "Phase"};
MidiSlider sliderFine6;
MidiSlider sliderDetune6;
MidiSlider sliderPhase6;
Label labelFine6 {"f1", "Coarse Fine"};
Label labelDetune6 {"f1", "Detune"};
Label labelPhase6 {"f1", "Phase"};
MidiButton btFix1;
MidiButton btFix2;
MidiButton btFix3;
MidiButton btFix4;
MidiButton btFix5;
MidiButton btFix6;
MidiButton btPhase1;
MidiButton btPhase2;
MidiButton btPhase3;
MidiButton btPhase4;
MidiButton btPhase5;
MidiButton btPhase6;
Label labelOsc1 {"Op1", "Afm Osc"};
CustomLookAndFeel myLookAndFeel;
AfmOscLookAndFeel OscLook;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Oscillator)
};
|
2fc6f8b7e8c4466f3277a07eda4e9276bf885dba | 1a2667191dc2bc037acacaa285fa76171667c500 | /Codeforces/A - Boboniu Likes to Color Balls/A - Boboniu Likes to Color Balls.cpp | 0275ca852abbecdbe49893431aaa17ebe5cff0dd | [] | no_license | hgihyks/DS_Algo | ccdc37d30e75a21799d36761ebc20790fe77a229 | 11ab04558ca40c1a15137e199bc85a4a8159f376 | refs/heads/master | 2023-02-16T01:10:10.298573 | 2021-01-15T14:42:20 | 2021-01-15T14:42:20 | 329,014,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,287 | cpp | A - Boboniu Likes to Color Balls.cpp | #include <bits/stdc++.h>
#define fa(i, a, b) for (int i = a; i < b; ++i)
#define f(i, n) fa(i, 0, n)
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define printv(v) f(i, v.size()) cout << v[i] << ' '; cout << '\n';
#define printa(a) f(i, sizeof(a)/sizeof(a[0])) cout << a[i] << ' '; cout << '\n';
#define printm(m) for(auto x:m) cout << x.fi << "--> " << x.se << '\n';
typedef long long int ll;
#define OJ \
freopen("input.txt", "r", stdin); \
freopen("output.txt", "w", stdout);
using namespace std;
const int mod=1e9+7;
const int inf = (1<<30);
bool check(int even,int odd)
{
if(odd <= 1) return true;
return false;
}
void solve()
{
int i, j, n=4;
int a[n];
f(i,n) cin >> a[i];
int odd=0,even=0;
f(i,n)
{
if(a[i]%2==0) even++;
else odd++;
}
if(*min_element(a,a+n-1) > 0)
{
if(check(even,odd) || check(odd,even)) cout << "Yes" << endl;
else cout << "No" << endl;
}
else
{
if(check(even,odd)) cout << "Yes" << endl;
else cout << "No" << endl;
}
}
int main(){
//ios_base::sync_with_stdio(false);
//cin.tie(NULL);
//OJ;
int t=1;
scanf("%d", &t);
while(t--){
solve();
}
return 0;
} |
b3e3d619f8ff5e307547fa84897cc299fd0aa33c | 5ba16a58a1f174a3cf7eb4972eb043feb8152787 | /src/localDensity.cpp | 88880a31e2680b2d6034ca1a215ba0fcb90fb5b8 | [] | no_license | melody-xiaomi/densityClust | 90061ad2cf639afff5396bad811abcbc329c6e1a | 419726501d7957f07e429d5b411fcae5d3c15b82 | refs/heads/master | 2020-12-30T13:29:25.519702 | 2017-05-09T19:33:54 | 2017-05-09T19:33:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,130 | cpp | localDensity.cpp | #include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector gaussianLocalDensity(NumericVector distance, int nrow, double dc) {
int size = distance.size();
NumericVector half(size);
for (int i = 0; i < size; i++) {
double combOver = distance[i] / dc;
double negSq = pow(combOver, 2) * -1;
half[i] = exp(negSq);
}
int ncol = nrow;
NumericVector result(nrow);
int i = 0;
for (int col = 0; col < ncol; col++) {
for (int row = col + 1; row < nrow; row++) {
double temp = half[i];
result[row] += temp;
result[col] += temp;
i++;
}
}
return result;
}
// [[Rcpp::export]]
NumericVector nonGaussianLocalDensity(NumericVector distance, int nrow, double dc) {
int ncol = nrow;
NumericVector result(nrow);
int i = 0;
for (int col = 0; col < ncol; col++) {
for (int row = col + 1; row < nrow; row++) {
if (distance[i] < dc) {
result[row] += 1;
result[col] += 1;
} else {
// do nothing
}
i++;
}
}
return result;
} |
2da5768e3ea197ccc8636beca746d1ef41fcca46 | d74daa1dfe1f4eac96ceb1d006c59ba19b55d37a | /CS325/mc4233_hw1/TestBed.h | a97b4de04608101ad25e712000701db9e819e6a6 | [] | no_license | muratcancicek/Assignment-Projects | 7aac0cced54f392e26b39f6bc46af813faddd628 | 41c7df2b60f20eb840d409f3fedb4ec6feeafdcc | refs/heads/master | 2021-06-06T17:27:11.616251 | 2017-09-06T12:17:40 | 2017-09-06T12:17:40 | 58,016,251 | 0 | 1 | null | null | null | null | ISO-8859-3 | C++ | false | false | 289 | h | TestBed.h | /* Coded by Muratcan Çiçek S004233 Computer Science */
#ifndef TESTBED_H
#define TESTBED_H
#include "SelectionAlgorithm.h"
class TestBed
{
public:
TestBed();
~TestBed();
SelectionAlgorithm* algorithm;
void execute();
void SetAlgorithm(int type, int k);
};
#endif
|
8b071093f69ac8764ea8a66e865aa1b18e55940f | e5e5e43423485340a25361420ed3bc8d2cfaa5d0 | /question_7/boysgirl.cpp | 2a74338529025ef89b461d276bc5a92d43177845 | [] | no_license | PPL-IIITA/ppl-assignment-pt97 | 39d216e8a10eaf709b384d78d0360a44624f5a22 | 7015713e751aad193e8c7354b162b7e1cd2b2000 | refs/heads/master | 2021-01-21T06:21:27.247313 | 2017-04-09T20:46:51 | 2017-04-09T20:46:51 | 83,219,125 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,191 | cpp | boysgirl.cpp | #include "boysgirl.h"
#include <iostream>
#include <string>
#include <bits/stdc++.h>
#include "jodi.h"
using namespace std;
void make2()
{
map <string,int> m;
fstream myfile;
Jodi jode[30];
int i,j;
string name1,name2,boy[10],commiboys[30];
myfile.open("couple.txt");
for(i=0;i<30;i++)
{
myfile>>name1>>name2;
jode[i].setname1(name1);
jode[i].setname2(name2);
m[name1]=1;
commiboys[i]=name1;
}
//getting the random string of boys
boy[0]="boy1",boy[1]="boy14",boy[2]="boy3",boy[3]="boy48",boy[4]="boy11",boy[5]="boy38",boy[6]="boy16",boy[7]="boy20",boy[8]="boy37",boy[9]="boy26";
int check=rand()%3+1;
sort(commiboys,commiboys+30);
//accordign to the linear search
if(check==1)
{
for(i=0;i<10;i++)
{
for(j=0;j<30;j++)
{
if(jode[j].getname1()==boy[i])
{
cout<<boy[i]<<" girlfriend is "<<jode[j].getname2()<<endl;
break;
}
}
}
}
//according to the binary search using the inbuilt binary search function
if(check==2)
{
for(i=0;i<10;i++)
{
if(binary_search(commiboys,commiboys+30,boy[i]))
{
for(j=0;j<30;j++)
{
if(jode[j].getname1()==boy[i])
{
cout<<boy[i]<<" girlfriend is "<<jode[j].getname2()<<endl;
break;
}
}
}
else
cout<<boy[i]<<" is not in relationship\n";
}
}
//according to the maping
if(check==3)
{
for(i=0;i<10;i++)
{
if(m[boy[i]]==1)
{
for(j=0;j<30;j++)
{
if(jode[j].getname1()==boy[i])
{
cout<<boy[i]<<" girlfriend is "<<jode[j].getname2()<<endl;
break;
}
}
}
else
cout<<boy[i]<<" is not in relationship\n";
}
}
} |
4345d948286a7e62f87c9edbc3e8554ddb1541a6 | 1deda48055f6ff3c4afb3d20c9c27ab78b403e70 | /src/classes/player/SWItem.cpp | 17ad45b2d6c0b527ea8a94771ef2d4ca846dbf30 | [] | no_license | Trogious/swmud | c5d60eb78bcdcbe9473db502a139285671cebcf1 | 93e0b40a69511b44d0175dcda6612a8ef79f3912 | refs/heads/master | 2021-07-24T14:25:48.787119 | 2020-04-13T16:54:01 | 2020-04-13T16:54:01 | 132,245,599 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,532 | cpp | SWItem.cpp | /*
* SWItem.cpp
*
* Created on: 2010-08-26
* Author: Trog
*/
#include "SWItem.h"
#include <SWPlayerCharacter.h>
namespace player
{
const SWInt SWItem::valueMaxElements = 6;
SWItem::SWItem() :
inflect(vector<SWString> (SWPlayerCharacter::inflectMaxElements)), value(vector<SWInt> (valueMaxElements)),
strValue(vector<SWString> (valueMaxElements))
{
}
SWItem::SWItem(const SWInt64 vnum) :
vnum(vnum), inflect(vector<SWString> (SWPlayerCharacter::inflectMaxElements)), value(vector<SWInt> (
valueMaxElements)), strValue(vector<SWString> (valueMaxElements))
{
}
SWItem::SWItem(const SWInt64 vnum, const SWInt &ownerEntityId) :
SWOwnerEntityId(ownerEntityId), vnum(vnum), inflect(vector<SWString> (SWPlayerCharacter::inflectMaxElements)),
value(vector<SWInt> (valueMaxElements)), strValue(vector<SWString> (valueMaxElements))
{
}
SWItem::~SWItem()
{
}
#define CREATE_PROXY(methodNamePart) CREATE_PROXY2(methodNamePart,SWItem)
SWDbEntityDataMapping SWItem::getDataMapping() const
{
SWDbEntityDataMapping mapping;
mapping.addMapping("vnum", getVnum(), CREATE_PROXY(Vnum));
mapping.addMapping("owner_vnum", getOwnerVnum(), CREATE_PROXY(OwnerVnum));
mapping.addMapping("count", getCount(), CREATE_PROXY(Count));
mapping.addMapping("name", getName(), CREATE_PROXY(Name));
mapping.addMapping("inflect", getInflect(), CREATE_PROXY(Inflect));
mapping.addMapping("description", getDescription(), CREATE_PROXY(Description));
mapping.addMapping("action_desc", getActionDescription(), CREATE_PROXY(ActionDescription));
mapping.addMapping("owner_name", getOwnerName(), CREATE_PROXY(OwnerName));
mapping.addMapping("in_room", getInRoom(), CREATE_PROXY(InRoom));
mapping.addMapping("extra_flags", getExtraFlags(), CREATE_PROXY(ExtraFlags));
mapping.addMapping("wear_flags", getWearFlags(), CREATE_PROXY(WearFlags));
mapping.addMapping("wear_loc", getWearLoc(), CREATE_PROXY(WearLoc));
mapping.addMapping("item_type", getItemType(), CREATE_PROXY(ItemType));
mapping.addMapping("weight", getWeight(), CREATE_PROXY(Weight));
mapping.addMapping("level", getLevel(), CREATE_PROXY(Level));
mapping.addMapping("timer", getTimer(), CREATE_PROXY(Timer));
mapping.addMapping("cost", getCost(), CREATE_PROXY(Cost));
mapping.addMapping("gender", getGender(), CREATE_PROXY(Gender));
mapping.addMapping("value", getValue(), CREATE_PROXY(Value));
mapping.addMapping("str_value", getStrValue(), CREATE_PROXY(StrValue));
mapping.addMapping("in_quest", getInQuest(), CREATE_PROXY(InQuest));
return mapping;
}
}
|
a3671f35f6ac3b40d1abe0cd150d7615ae252358 | 2877494ba357f8dd4907dccc851a02568429580c | /ThermostatGui/Arduino/MessageProcessor.h | 850352e5f370e77bae5b568abdec53e25a86c342 | [] | no_license | jnelso27/Thermostat | a18e900a73be00ff6cfd1926432b95ec20a5e3ed | caea4d4cd63f157dd33f60e1d2609ef88ae3f3f6 | refs/heads/master | 2021-01-10T09:13:26.016867 | 2015-11-16T02:01:03 | 2015-11-16T02:01:03 | 44,570,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,415 | h | MessageProcessor.h | // ***************************************************************************
//
// MessageProcessor.h - Library used for processing incoming messages from
// the host-side controller of the Thermostat System.
//
// ***************************************************************************
#ifndef MessageProcessor_h
#define MessageProcessor_h
//Arduino libraries
#include "Arduino.h"
//Project libaries
#include "TemperatureSensor.h"
#include "AlarmSensor.h"
class MessageProcessor
{
public:
MessageProcessor();
void processMessage(byte message[]);
private:
TemperatureSensor tmp102sensor;
AlarmSensor alarmSensor;
//
const byte REC_MSG_HEADER = '&';
const byte REC_MSG_TYPE = '0';
const byte REC_MSG_DATA_MSB = '0';
const byte REC_MSG_DATA_LSB = '0';
const byte REC_MSG_FOOTER = '$';
const int REC_MSG_HEADER_NDX = 0;
const int REC_MSG_TYPE_NDX = 1;
const int REC_MSG_DATA_MSB_NDX = 2;
const int REC_MSG_DATA_LSB_NDX = 3;
//const int REC_MSG_FOOTER_NDX = 4;
//Message used as a default message type
const byte DEFAULT_MSG = 0x50;
const byte TEMP_SENSOR_READING_REQUEST_MSG = 0x56;
const byte NORMAL_ALARM_SET_MSG = 0x53;
const byte WARNING_ALARM_SET_MSG = 0x54;
const byte DANGER_ALARM_SET_MSG = 0x55;
};
#endif
|
a34a7936efacb76eddf6c39b8e59129a1c706a23 | 5b84e30635015a7184e013444310bc1bf0d635b2 | /src/render/shader/shader.hpp | 6df63e692d8ef1983e7a43a5c72a985af4d8d178 | [] | no_license | hjwdzh/ShapeAlign | 0c91de05e1d3ecaecbd6907d24822dc574593d5e | b8e1bf05ae564295a9d139a29b1650881463f9dd | refs/heads/master | 2020-03-14T04:25:32.070936 | 2018-05-31T01:48:54 | 2018-05-31T01:48:54 | 131,441,608 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 210 | hpp | shader.hpp | #ifndef SHADER_H_
#define SHADER_H_
#include <nanogui_header.hpp>
class NanoShader
{
public:
NanoShader() {}
virtual void Draw() = 0;
~NanoShader() {
}
virtual void bind() = 0;
};
#endif
|
e594f48d610e548d9cce62850dec18257ff6a66c | 07f842cc0a65f14f23d3ff611b5ca2481de239d1 | /Good'ol Programs/Old School/coding/Yash/NDTC/string.cpp | 8a76a1a5d39b704a7a8812313161ae6e2655d537 | [] | no_license | AbhishekPrakash5/Cpp_Practice | f1aedc3f2f124af1d16d655e18e45e26a9167722 | b1bca35cbeb5e4ac87d2813ce398c5f4d29d1598 | refs/heads/main | 2023-05-26T06:57:20.214428 | 2021-06-13T12:05:22 | 2021-06-13T12:05:22 | 376,530,676 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 212 | cpp | string.cpp | #include<iostream>
using namespace std;
int main()
{ int count=0;
char str[100];
cout<<"enter string ";
gets(str);
for(int i=0;str[i]!='\0';i++)
{
if(str[i]=='a')
count++;
}
cout<<count;
return 0;
}
|
7bf7ee8b62b6d3ea05a51c211ce06d8655abb2fc | a6af28b2551fa2dad84060ae6b99fbc3a0ef9a2a | /round#93div1/A/A.cpp | 0a56c9986602bec0fd3b09b8eabd0f8f11b1cce5 | [] | no_license | blueyeq/codeforces | 894f8e11ce5d44b37df62238178b68ef06d78206 | 9cdc04bbb3cbafbfd92a604b373d1d3e3b11b3bd | refs/heads/master | 2016-09-06T04:54:00.474306 | 2013-07-20T15:42:39 | 2013-07-20T15:42:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,674 | cpp | A.cpp | #include <stdio.h>
#include <cstring>
#include <cmath>
#include <string>
using namespace std;
const double eps = 1e-15;
int main()
{
freopen("in", "r", stdin);
double t1, t2, t0;
int x1, x2;
while(scanf("%lf%lf%d%d%lf", &t1, &t2, &x1, &x2, &t0) != EOF)
{
double dis(1e10);
if(fabs(t1 - t0) < eps && fabs(t2 - t0) < eps)
{
printf("%d %d\n", x1, x2);
continue;
}
if(fabs(t2 - t0) < eps)
{
printf("%d %d\n", 0, x2);
continue;
}
if(fabs(t1 - t0) < eps)
{
printf("%d %d\n", x1, 0);
continue;
}
int ans, ans1, ans2;
for(int y1 = x1; y1 >= 0; --y1)
{
double tmp = (t0 * y1 - t1 * y1) / (t2 - t0);
for(int i = -1; i <= 1; ++i)
{
int y2 = (int) tmp + i;
double tt = (t1 * y1 + t2 * y2) / (double)(y1 + y2);
if(y2 < 0 || y2 > x2) continue;
if(tt - t0 >= eps || tt == t0)
{
if(tt - t0 < dis)
{
dis = tt - t0;
ans = y1 + y2;
ans1 = y1;
ans2 = y2;
}
else if(fabs(tt - t0 - dis) < eps && y1 + y2 > ans)
{
ans = y1 + y2;
ans1 = y1;
ans2 = y2;
}
}
}
}
if(ans1 == 0) ans2 = x2;
printf("%d %d\n", ans1, ans2);
}
return 0;
}
|
caed4708a40765fbee2d324d9e15bd4b1e88be93 | ddc00633d5c2a56deb69e539efe52c85cf81ea91 | /selection_sort.cpp | c434af885f12f9fbc0b0017d1ca2495ee38b3a02 | [] | no_license | B3ns44d/cpp_ex | 16c989b036a8f4e5a2c965007a9e44bba90d24fd | 27688389556c3f39bee14e4cede602d53ef1e310 | refs/heads/master | 2023-03-23T17:20:00.293718 | 2021-03-07T20:11:36 | 2021-03-07T20:11:36 | 344,165,724 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,581 | cpp | selection_sort.cpp | #include <iostream>
using namespace std;
class List {
private:
int * array;
int length;
public:
List() {
this -> array = NULL;
this -> length = 0;
}
void populate() {
do {
cout << "enter array size:" << endl;
cin >> this -> length;
} while (this -> length < 0);
this -> array = new int[this -> length];
for (int i = 0; i < this -> length; i++) {
cout << "enter " << i << "th item" << endl;
cin >> * (array + i);
}
}
void selectionSort() {
if (array == NULL) {
cout << "list is empty !" << endl;
return;
}
int minIndex, temp;
for (int i = 0; i < this -> length; i++) {
minIndex = i;
for (int j = (i + 1); j < this -> length; j++) {
if ( * (array + j) < * (array + minIndex)) {
minIndex = j;
}
}
temp = * (array + i);
*(array + i) = * (array + minIndex);
*(array + minIndex) = temp;
}
}
int length() {
return length;
}
void display() {
if (array == NULL) {
cout << "list is empty !" << endl;
return;
}
cout << "[";
for (int i = 0; i < this -> length; i++) {
if (i != length - 1) {
cout << * (array + i) << ", ";
} else {
cout << * (array + i);
}
}
cout << "]" << endl;
}
~List() {
delete array;
}
};
int main() {
List list;
list.populate();
cout << "unsorted list:";
list.display();
cout << "sorted list:";
list.selectionSort();
list.display();
return 0;
} |
ca4903e724a06a1df89746de71c11ca878a19f15 | 88c0e520e2389e676fea559f944109e1ee7e157b | /include/Windows.System.Preview_87dfc8ab.h | f414bc5dfee6e03d72f74a45b9fb624f2bc5c2ce | [] | no_license | jchoi2022/NtFuzz-HeaderData | fb4ecbd5399f4fac6a4982a0fb516dd7f9368118 | 6adc3d339e6cac072cde6cfef07eccafbc6b204c | refs/heads/main | 2023-08-03T02:26:10.666986 | 2021-09-17T13:35:26 | 2021-09-17T13:35:26 | 407,547,359 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,616 | h | Windows.System.Preview_87dfc8ab.h |
#include "winrt/base.h"
#include "winrt/Windows.Foundation.h"
#include "winrt/Windows.Foundation.Collections.h"
#include "winrt/impl/Windows.Devices.Sensors.2.h"
#include "winrt/impl/Windows.System.Preview.2.h"
#include "winrt/Windows.System.h"
namespace winrt::impl {
template <typename D> Windows::Foundation::IAsyncOperation<Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading> consume_Windows_System_Preview_ITwoPanelHingedDevicePosturePreview<D>::GetCurrentPostureAsync() const
{
Windows::Foundation::IAsyncOperation<Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading> value{ nullptr };
check_hresult(WINRT_SHIM(Windows::System::Preview::ITwoPanelHingedDevicePosturePreview)->GetCurrentPostureAsync(put_abi(value)));
return value;
}
template <typename D> winrt::event_token consume_Windows_System_Preview_ITwoPanelHingedDevicePosturePreview<D>::PostureChanged(Windows::Foundation::TypedEventHandler<Windows::System::Preview::TwoPanelHingedDevicePosturePreview, Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs> const& handler) const
{
winrt::event_token token{};
check_hresult(WINRT_SHIM(Windows::System::Preview::ITwoPanelHingedDevicePosturePreview)->add_PostureChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> typename consume_Windows_System_Preview_ITwoPanelHingedDevicePosturePreview<D>::PostureChanged_revoker consume_Windows_System_Preview_ITwoPanelHingedDevicePosturePreview<D>::PostureChanged(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::System::Preview::TwoPanelHingedDevicePosturePreview, Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs> const& handler) const
{
return impl::make_event_revoker<D, PostureChanged_revoker>(this, PostureChanged(handler));
}
template <typename D> void consume_Windows_System_Preview_ITwoPanelHingedDevicePosturePreview<D>::PostureChanged(winrt::event_token const& token) const noexcept
{
WINRT_VERIFY_(0, WINRT_SHIM(Windows::System::Preview::ITwoPanelHingedDevicePosturePreview)->remove_PostureChanged(get_abi(token)));
}
template <typename D> Windows::Foundation::DateTime consume_Windows_System_Preview_ITwoPanelHingedDevicePosturePreviewReading<D>::Timestamp() const
{
Windows::Foundation::DateTime value{};
check_hresult(WINRT_SHIM(Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReading)->get_Timestamp(put_abi(value)));
return value;
}
template <typename D> Windows::System::Preview::HingeState consume_Windows_System_Preview_ITwoPanelHingedDevicePosturePreviewReading<D>::HingeState() const
{
Windows::System::Preview::HingeState value{};
check_hresult(WINRT_SHIM(Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReading)->get_HingeState(put_abi(value)));
return value;
}
template <typename D> Windows::Devices::Sensors::SimpleOrientation consume_Windows_System_Preview_ITwoPanelHingedDevicePosturePreviewReading<D>::Panel1Orientation() const
{
Windows::Devices::Sensors::SimpleOrientation value{};
check_hresult(WINRT_SHIM(Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReading)->get_Panel1Orientation(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_System_Preview_ITwoPanelHingedDevicePosturePreviewReading<D>::Panel1Id() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReading)->get_Panel1Id(put_abi(value)));
return value;
}
template <typename D> Windows::Devices::Sensors::SimpleOrientation consume_Windows_System_Preview_ITwoPanelHingedDevicePosturePreviewReading<D>::Panel2Orientation() const
{
Windows::Devices::Sensors::SimpleOrientation value{};
check_hresult(WINRT_SHIM(Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReading)->get_Panel2Orientation(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_System_Preview_ITwoPanelHingedDevicePosturePreviewReading<D>::Panel2Id() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReading)->get_Panel2Id(put_abi(value)));
return value;
}
template <typename D> Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading consume_Windows_System_Preview_ITwoPanelHingedDevicePosturePreviewReadingChangedEventArgs<D>::Reading() const
{
Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading value{ nullptr };
check_hresult(WINRT_SHIM(Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReadingChangedEventArgs)->get_Reading(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::System::Preview::TwoPanelHingedDevicePosturePreview> consume_Windows_System_Preview_ITwoPanelHingedDevicePosturePreviewStatics<D>::GetDefaultAsync() const
{
Windows::Foundation::IAsyncOperation<Windows::System::Preview::TwoPanelHingedDevicePosturePreview> result{ nullptr };
check_hresult(WINRT_SHIM(Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewStatics)->GetDefaultAsync(put_abi(result)));
return result;
}
template <typename D>
struct produce<D, Windows::System::Preview::ITwoPanelHingedDevicePosturePreview> : produce_base<D, Windows::System::Preview::ITwoPanelHingedDevicePosturePreview>
{
int32_t WINRT_CALL GetCurrentPostureAsync(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
WINRT_ASSERT_DECLARATION(GetCurrentPostureAsync, WINRT_WRAP(Windows::Foundation::IAsyncOperation<Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading>));
*value = detach_from<Windows::Foundation::IAsyncOperation<Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading>>(this->shim().GetCurrentPostureAsync());
return 0;
}
catch (...) { return to_hresult(); }
}
int32_t WINRT_CALL add_PostureChanged(void* handler, winrt::event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
WINRT_ASSERT_DECLARATION(PostureChanged, WINRT_WRAP(winrt::event_token), Windows::Foundation::TypedEventHandler<Windows::System::Preview::TwoPanelHingedDevicePosturePreview, Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs> const&);
*token = detach_from<winrt::event_token>(this->shim().PostureChanged(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::System::Preview::TwoPanelHingedDevicePosturePreview, Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs> const*>(&handler)));
return 0;
}
catch (...) { return to_hresult(); }
}
int32_t WINRT_CALL remove_PostureChanged(winrt::event_token token) noexcept final
{
typename D::abi_guard guard(this->shim());
WINRT_ASSERT_DECLARATION(PostureChanged, WINRT_WRAP(void), winrt::event_token const&);
this->shim().PostureChanged(*reinterpret_cast<winrt::event_token const*>(&token));
return 0;
}
};
template <typename D>
struct produce<D, Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReading> : produce_base<D, Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReading>
{
int32_t WINRT_CALL get_Timestamp(Windows::Foundation::DateTime* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
WINRT_ASSERT_DECLARATION(Timestamp, WINRT_WRAP(Windows::Foundation::DateTime));
*value = detach_from<Windows::Foundation::DateTime>(this->shim().Timestamp());
return 0;
}
catch (...) { return to_hresult(); }
}
int32_t WINRT_CALL get_HingeState(Windows::System::Preview::HingeState* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
WINRT_ASSERT_DECLARATION(HingeState, WINRT_WRAP(Windows::System::Preview::HingeState));
*value = detach_from<Windows::System::Preview::HingeState>(this->shim().HingeState());
return 0;
}
catch (...) { return to_hresult(); }
}
int32_t WINRT_CALL get_Panel1Orientation(Windows::Devices::Sensors::SimpleOrientation* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
WINRT_ASSERT_DECLARATION(Panel1Orientation, WINRT_WRAP(Windows::Devices::Sensors::SimpleOrientation));
*value = detach_from<Windows::Devices::Sensors::SimpleOrientation>(this->shim().Panel1Orientation());
return 0;
}
catch (...) { return to_hresult(); }
}
int32_t WINRT_CALL get_Panel1Id(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
WINRT_ASSERT_DECLARATION(Panel1Id, WINRT_WRAP(hstring));
*value = detach_from<hstring>(this->shim().Panel1Id());
return 0;
}
catch (...) { return to_hresult(); }
}
int32_t WINRT_CALL get_Panel2Orientation(Windows::Devices::Sensors::SimpleOrientation* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
WINRT_ASSERT_DECLARATION(Panel2Orientation, WINRT_WRAP(Windows::Devices::Sensors::SimpleOrientation));
*value = detach_from<Windows::Devices::Sensors::SimpleOrientation>(this->shim().Panel2Orientation());
return 0;
}
catch (...) { return to_hresult(); }
}
int32_t WINRT_CALL get_Panel2Id(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
WINRT_ASSERT_DECLARATION(Panel2Id, WINRT_WRAP(hstring));
*value = detach_from<hstring>(this->shim().Panel2Id());
return 0;
}
catch (...) { return to_hresult(); }
}
};
template <typename D>
struct produce<D, Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReadingChangedEventArgs> : produce_base<D, Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReadingChangedEventArgs>
{
int32_t WINRT_CALL get_Reading(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
WINRT_ASSERT_DECLARATION(Reading, WINRT_WRAP(Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading));
*value = detach_from<Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading>(this->shim().Reading());
return 0;
}
catch (...) { return to_hresult(); }
}
};
template <typename D>
struct produce<D, Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewStatics> : produce_base<D, Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewStatics>
{
int32_t WINRT_CALL GetDefaultAsync(void** result) noexcept final
{
try
{
*result = nullptr;
typename D::abi_guard guard(this->shim());
WINRT_ASSERT_DECLARATION(GetDefaultAsync, WINRT_WRAP(Windows::Foundation::IAsyncOperation<Windows::System::Preview::TwoPanelHingedDevicePosturePreview>));
*result = detach_from<Windows::Foundation::IAsyncOperation<Windows::System::Preview::TwoPanelHingedDevicePosturePreview>>(this->shim().GetDefaultAsync());
return 0;
}
catch (...) { return to_hresult(); }
}
};
}
WINRT_EXPORT namespace winrt::Windows::System::Preview {
inline Windows::Foundation::IAsyncOperation<Windows::System::Preview::TwoPanelHingedDevicePosturePreview> TwoPanelHingedDevicePosturePreview::GetDefaultAsync()
{
return impl::call_factory<TwoPanelHingedDevicePosturePreview, Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewStatics>([&](auto&& f) { return f.GetDefaultAsync(); });
}
}
WINRT_EXPORT namespace std {
template<> struct hash<winrt::Windows::System::Preview::ITwoPanelHingedDevicePosturePreview> : winrt::impl::hash_base<winrt::Windows::System::Preview::ITwoPanelHingedDevicePosturePreview> {};
template<> struct hash<winrt::Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReading> : winrt::impl::hash_base<winrt::Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReading> {};
template<> struct hash<winrt::Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReadingChangedEventArgs> : winrt::impl::hash_base<winrt::Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewReadingChangedEventArgs> {};
template<> struct hash<winrt::Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewStatics> : winrt::impl::hash_base<winrt::Windows::System::Preview::ITwoPanelHingedDevicePosturePreviewStatics> {};
template<> struct hash<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreview> : winrt::impl::hash_base<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreview> {};
template<> struct hash<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading> : winrt::impl::hash_base<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReading> {};
template<> struct hash<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs> : winrt::impl::hash_base<winrt::Windows::System::Preview::TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs> {};
}
|
8fc15478f130f912466ebe6ae9eed6e7b4645568 | c4d62df533b2b55f81914a0675eae8b0361cf5d1 | /CS359 LAB/1801CS08_Assignment7/server.cpp | f3e9ac5a1e8233b5f36232982c911569dba7902c | [] | no_license | ammaarahmad1999/Computer-Networks | 1ccbf3376de8b7e22fa9189f815f524b5c6b0de4 | be2e0ab8e70cdcc4cf98d8517c48f5b97bd26cf9 | refs/heads/main | 2023-06-20T14:15:00.347024 | 2021-07-25T13:51:39 | 2021-07-25T13:51:39 | 345,340,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,114 | cpp | server.cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <openssl/md5.h>
#include <bits/stdc++.h>
#define SIZE 8192
using namespace std;
string divide;
string binary(int x)
{
string ans;
for (int i=0; i<8; i++)
{
ans = to_string(x%2) + ans;
x = x/2;
}
return ans;
}
string crc(string code)
{
int length = code.length();
int len = divide.length();
int pick = len;
string dividend = code.substr(0,pick);
while (pick < length)
{
if (dividend[0]=='1')
{
for (int i=0; i<len-1; i++)
dividend[i]=(dividend[i+1]^divide[i+1])+48;
dividend[len-1] = code[pick];
}
else
{
for (int i=0; i<len-1; i++)
dividend[i]=dividend[i+1];
dividend[len-1] = code[pick];
}
pick++;
}
if (dividend[0]=='1')
{
for (int i=0; i<len-1; i++)
dividend[i]=(dividend[i+1]^divide[i+1])+48;
}
else
{
for (int i=0; i<len-1; i++)
dividend[i]=dividend[i+1];
}
dividend.pop_back();
return dividend;
}
string encoder(string code)
{
int len = divide.length();
for (int i=1; i<len; i++)
code.push_back('0');
string dividend = crc(code);
return dividend;
}
int decimal(string s)
{
int x=0;
for (int i=0; i<s.length(); i++)
x = x*2+(s[i]-48);
return x;
}
string binary_to_char(string s)
{
int len = s.length();
string message;
for (int i=0; i<len; i+=8)
message += char(decimal(s.substr(i,8)));
return message;
}
string ascii_to_binary(string s)
{
int len = s.length();
string code;
for (int i=0; i<len; i++)
{
string bin = binary(s[i]);
code = code + bin;
}
return code;
}
bool isbinary(string s)
{
for (int i=0; i<s.length(); i++)
if(s[i]!='0' && s[i]!='1')
return false;
return true;
}
bool error(string rem)
{
for (int i=0; i<rem.length(); i++)
if(rem[i]=='1')
return true;
return false;
}
void connection(int sockfd)
{
string s, rem, sms;
int n;
char buffer[1024];
n = recv(sockfd, buffer, SIZE, 0);
if (n <= 0)
{
printf("[-]Error in recieving message\n");
exit(1);
}
else
{
divide = buffer;
cout<<"CRC checker is: "<<divide<<endl;
}
int len = divide.length();
//printf("Input should be strictly in binary format\n");
printf("In order to exit: 0\n");
while (1)
{
bzero(buffer, sizeof(buffer));
n = recv(sockfd, buffer, SIZE, 0);
if (n <= 0)
{
printf("[-]Error in recieving message\n");
break;
}
else
{
sms = buffer;
cout<<"CRC recieved: "<<sms<<endl;
rem = crc(sms);
if(error(rem))
cout<<"Error in code recieved\n";
else
{
int l = sms.length();
s = sms.substr(0,l-len+1);
s = binary_to_char(s);
cout<<"CLIENT: "<<s<<endl;
if(s=="0")
break;
}
}
getline(cin, s);
/*while(isbinary(s)==false)
{
cout<<"Input is not in binary format. Please Enter again"<<endl;
cin>>s;
}*/
bzero(buffer, sizeof(buffer));
s = ascii_to_binary(s);
rem = encoder(s);
sms = s + rem;
cout<<"CRC sending: "<<sms<<endl;
strcpy(buffer, sms.c_str());
if (send(sockfd, &buffer, sizeof(buffer), 0) == -1)
{
printf("[-]Error in sending message.\n");
exit(1);
}
if(s=="00110000")
break;
}
return;
}
int main()
{
int port = 8080;
int e;
int sockfd, new_sock;
struct sockaddr_in server_addr, new_addr;
socklen_t addr_size;
char buffer[SIZE];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0)
{
perror("[-]Error in socket");
exit(1);
}
printf("[+]Server socket created successfully.\n");
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = INADDR_ANY;
e = bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if(e < 0)
{
perror("[-]Error in bind\n");
exit(1);
}
printf("[+]Binding successfull.\n");
if(listen(sockfd, 10) == 0)
printf("[+]Listening....\n");
else
{
perror("[-]Error in listening\n");
exit(1);
}
addr_size = sizeof(new_addr);
new_sock = accept(sockfd, (struct sockaddr*)&new_addr, &addr_size);
connection(new_sock);
close(sockfd);
return 0;
}
|
10d4be5cb8228948b1a765a5b7e30dddfc044458 | 7105d97bb783629ff2b38df4f303ff515743a6b5 | /include/slang/ast/symbols/PortSymbols.h | c5424efae6f4dfae76f2063536bd7670356f5c2a | [
"MIT"
] | permissive | MikePopoloski/slang | b7dcd5e47702ef2f19af11fd169b9a3f1230ed9c | cada0eb18795ba6a8484d0a52fec5d20b6410e62 | refs/heads/master | 2023-08-28T16:23:03.408083 | 2023-08-27T01:44:26 | 2023-08-27T01:44:26 | 80,874,333 | 455 | 115 | MIT | 2023-09-14T11:03:37 | 2017-02-03T22:20:21 | C++ | UTF-8 | C++ | false | false | 8,016 | h | PortSymbols.h | //------------------------------------------------------------------------------
//! @file PortSymbols.h
//! @brief Contains port-related symbol definitions
//
// SPDX-FileCopyrightText: Michael Popoloski
// SPDX-License-Identifier: MIT
//------------------------------------------------------------------------------
#pragma once
#include "slang/ast/Expression.h"
#include "slang/ast/SemanticFacts.h"
#include "slang/numeric/ConstantValue.h"
#include "slang/syntax/SyntaxFwd.h"
namespace slang::ast {
class AttributeSymbol;
class Definition;
class InstanceSymbol;
class ModportSymbol;
/// Represents the public-facing side of a module / program / interface port.
/// The port symbol itself is not directly referenceable from within the instance;
/// it can however connect directly to a symbol that is.
class SLANG_EXPORT PortSymbol : public Symbol {
public:
/// An instance-internal symbol that this port connects to, if any.
/// Ports that do not connect directly to an internal symbol will have
/// this set to nullptr.
const Symbol* internalSymbol = nullptr;
/// The source location where the external name for the port is declared.
SourceLocation externalLoc;
/// The direction of data flowing across the port.
ArgumentDirection direction = ArgumentDirection::InOut;
/// Set to true for null ports, i.e. ports that don't connect to
/// anything internal to the instance.
bool isNullPort = false;
/// True if this port was declared using the ansi syntax, and
/// false if it was declared using the non-ansi syntax.
bool isAnsiPort = false;
PortSymbol(std::string_view name, SourceLocation loc, bool isAnsiPort);
const Type& getType() const;
void setType(const Type& newType) { type = &newType; }
bool hasInitializer() const { return initializer || initializerSyntax; }
const Expression* getInitializer() const;
void setInitializerSyntax(const syntax::ExpressionSyntax& syntax, SourceLocation loc) {
initializerSyntax = &syntax;
initializerLoc = loc;
}
const Expression* getInternalExpr() const;
struct NetTypeRange {
const NetType* netType = nullptr;
bitwidth_t width = 0;
};
void getNetTypes(SmallVectorBase<NetTypeRange>& ranges) const;
bool isNetPort() const;
void serializeTo(ASTSerializer& serializer) const;
static void fromSyntax(
const syntax::PortListSyntax& syntax, const Scope& scope,
SmallVectorBase<const Symbol*>& results,
SmallVectorBase<std::pair<Symbol*, const Symbol*>>& implicitMembers,
std::span<std::pair<const syntax::SyntaxNode*, const Symbol*> const> portDeclarations);
static bool isKind(SymbolKind kind) { return kind == SymbolKind::Port; }
using Symbol::setParent;
private:
mutable const Type* type = nullptr;
mutable const Expression* initializer = nullptr;
mutable const Expression* internalExpr = nullptr;
const syntax::ExpressionSyntax* initializerSyntax = nullptr;
SourceLocation initializerLoc;
};
/// Represents a multi-port, which is a port symbol that externally appears as
/// a single connection but internally connects to multiple names, potentially
/// with varying directions.
class SLANG_EXPORT MultiPortSymbol : public Symbol {
public:
std::span<const PortSymbol* const> ports;
/// The direction of data flowing across the various ports. This is the most
/// restrictive aggregated direction out of all the ports. You need to check
/// each individual port to know how the data actually flows.
ArgumentDirection direction;
/// Always set to false on multi-ports; included for parity for PortSymbols
/// so that generic code can work on both types.
bool isNullPort = false;
MultiPortSymbol(std::string_view name, SourceLocation loc,
std::span<const PortSymbol* const> ports, ArgumentDirection direction);
const Type& getType() const;
/// Placeholder functions to enable generic code. Multi-ports never have initializers.
bool hasInitializer() const { return false; }
const Expression* getInitializer() const { return nullptr; }
void serializeTo(ASTSerializer& serializer) const;
static bool isKind(SymbolKind kind) { return kind == SymbolKind::MultiPort; }
private:
mutable const Type* type = nullptr;
};
/// Represents the public-facing side of a module / program / interface port
/// that is also a connection to an interface instance (optionally with a modport restriction).
class SLANG_EXPORT InterfacePortSymbol : public Symbol {
public:
using IfaceConn = std::pair<const Symbol*, const ModportSymbol*>;
/// A pointer to the definition for the interface.
const Definition* interfaceDef = nullptr;
/// If non-empty, the name of the modport that restricts which interface signals are accessible.
std::string_view modport;
/// Set to true if this is a generic interface port, which allows connections
/// to any interface type. If true, @a interfaceDef will be nullptr.
bool isGeneric = false;
InterfacePortSymbol(std::string_view name, SourceLocation loc) :
Symbol(SymbolKind::InterfacePort, name, loc) {}
bool isInvalid() const { return !interfaceDef && !isGeneric; }
/// Gets the set of dimensions for specifying interface arrays.
/// Returns nullopt if an error occurs evaluating the dimensions.
std::optional<std::span<const ConstantRange>> getDeclaredRange() const;
/// Gets the interface instance that this port connects to.
IfaceConn getConnection() const;
const ModportSymbol* getModport(const ASTContext& context, const InstanceSymbol& instance,
syntax::DeferredSourceRange sourceRange) const;
void serializeTo(ASTSerializer& serializer) const;
static bool isKind(SymbolKind kind) { return kind == SymbolKind::InterfacePort; }
private:
mutable std::optional<std::span<const ConstantRange>> range;
};
class SLANG_EXPORT PortConnection {
public:
using IfaceConn = InterfacePortSymbol::IfaceConn;
const Symbol& port;
PortConnection(const Symbol& port);
PortConnection(const Symbol& port, const syntax::ExpressionSyntax& expr);
PortConnection(const Symbol& port, bool useDefault);
PortConnection(const InterfacePortSymbol& port, const Symbol* connectedSymbol,
const ModportSymbol* modport);
PortConnection(const Symbol& port, const Symbol* connectedSymbol,
SourceRange implicitNameRange);
IfaceConn getIfaceConn() const;
const Expression* getExpression() const;
void checkSimulatedNetTypes() const;
void serializeTo(ASTSerializer& serializer) const;
struct ConnMap {
using NamedConnMap = SmallMap<std::string_view,
std::pair<const syntax::NamedPortConnectionSyntax*, bool>, 8>;
SmallVector<const syntax::PortConnectionSyntax*> orderedConns;
NamedConnMap namedConns;
std::span<const AttributeSymbol* const> wildcardAttrs;
SourceRange wildcardRange;
bool usingOrdered = true;
bool hasWildcard = false;
ConnMap(const syntax::SeparatedSyntaxList<syntax::PortConnectionSyntax>& portConnections,
const Scope& scope, LookupLocation lookupLocation);
};
static void makeConnections(
const InstanceSymbol& instance, std::span<const Symbol* const> ports,
const syntax::SeparatedSyntaxList<syntax::PortConnectionSyntax>& portConnections,
SmallVector<const PortConnection*>& results);
private:
const InstanceSymbol& getParentInstance() const;
const Symbol* connectedSymbol = nullptr;
union {
mutable const Expression* expr = nullptr;
const ModportSymbol* modport;
};
union {
const syntax::ExpressionSyntax* exprSyntax = nullptr;
SourceRange implicitNameRange;
};
bool useDefault = false;
};
} // namespace slang::ast
|
73b69604d5b75537d8a524b71af4c9ba94a295a7 | b6d1df49c1ec621a02204b1100312ecbb3e76ad3 | /src/mains/grp94/dataviewer/dvDataConstraint.cpp | d1dc02fbb8cc6d8be8413be74d305c3dcd8ba808 | [] | no_license | flylong0204/projects | 5271acde325cf3947fac7433077353b52fa07bc4 | b1e5c918d4aeb34c36576dababc5509dbb89afd1 | refs/heads/master | 2017-12-06T06:35:20.926786 | 2017-01-24T23:53:13 | 2017-01-24T23:53:13 | 79,988,197 | 1 | 2 | null | 2017-01-25T06:11:23 | 2017-01-25T06:11:23 | null | UTF-8 | C++ | false | false | 1,824 | cpp | dvDataConstraint.cpp | /********************************************************************
*
*
* Name: dvDataConstraint.cpp
*
*
* Author: Luke Skelly
*
* Description:
* Bounding box for n dimensions. Used by dataviewer to determine
* color of data and when to update color info.
*
*
* --------------------------------------------------------------
* $Revision: 1.2 $
* ---------------------------------------------------------------
*********************************************************************/
#include "dvDataConstraint.h"
dvDataConstraint::dvDataConstraint()
{
fastmod=0;
modspeed=4;
}
void dvDataConstraint::modMin(long dim, float mod)
{
checkSize(dim);
constraint_min[dim]+=.1*mod*modspeed*(1+fastmod*4);
trackers[dim].touch();
}
void dvDataConstraint::modMax(long dim, float mod)
{
checkSize(dim);
constraint_max[dim]+=.1*mod*modspeed*(1+fastmod*4);
trackers[dim].touch();
}
void dvDataConstraint::setMin(long dim, float val)
{
checkSize(dim);
if(constraint_min[dim]!=val) trackers[dim].touch();
constraint_min[dim]=val;
}
void dvDataConstraint::setMax(long dim, float val)
{
checkSize(dim);
if(constraint_min[dim]!=val) trackers[dim].touch();
constraint_max[dim]=val;
}
float dvDataConstraint::getMax(long dim)
{
checkSize(dim);
return constraint_max[dim];
}
float dvDataConstraint::getMin(long dim)
{
checkSize(dim);
return constraint_min[dim];
}
bool dvDataConstraint::isChanged(long id,long dim)
{
checkSize(dim);
return !trackers[dim].isTracked(id); // value has changed if not tracked!
}
void dvDataConstraint::fastColor(int yes)
{
fastmod=yes;
}
void dvDataConstraint::checkSize(long d)
{
if(d>=constraint_min.size())
{
constraint_min.resize(d+1);
constraint_max.resize(d+1);
trackers.resize(d+1);
}
}
long dvDataConstraint::size() const
{
return constraint_min.size();
} |
4f33144abd75797317ec96a71066e4a46c58eaeb | 02082c2b94c6f041d67ba392b7c95b2c7180bb0f | /tb/sim_intToFloat.cpp | 609b189e4563cb38ab558cf28e78d5c7e375bfdb | [] | no_license | xygq163/CNRV-FPU | 540987d8af2786bd4164f5ceaf7eea8fd74e0122 | d6daa7243e5e58317952f85a9217d8b63d8a363a | refs/heads/master | 2022-03-16T04:29:02.252291 | 2019-12-04T07:23:07 | 2019-12-04T07:23:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 117 | cpp | sim_intToFloat.cpp |
#include <verilated.h>
#include "Vtb_intToFloat.h"
#define TYPE Vtb_intToFloat
#include "../tb/sim_main.hpp"
|
3a2f894d417263215ab17f7a837a8763e35f7901 | 2be49a395ff47d6cc3cc5ce7c7ba305691ce6147 | /src/ofApp.cpp | 0a9c9fc8f2b7d6cc634977b6453310c6ac767d6c | [] | no_license | joelleaeschlimann/02-DandelionInterface | 1a8a2d76e6f312d654a2e957c2fd4a6583f0e9c5 | 09d68abf759e94f829a1a9b4a003f5cf7a2a76e3 | refs/heads/master | 2021-01-11T23:52:14.043585 | 2017-01-11T12:52:44 | 2017-01-11T12:52:44 | 78,638,534 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,506 | cpp | ofApp.cpp | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetVerticalSync(true);
ofSetFrameRate(60);
ofSetCircleResolution(100);
//gravity.set(0,0);
//force.set(ofRandom(-1,2), ofRandom(-1,2));
debug = false;
press = 0;
isInitiate = true;
ofBackground(0);
startPoint.set( ofGetWidth()/2,ofGetHeight()/2);
rDandelionBulb = 50;
rSeedPosition = 50;
rSeedDandelion = 10;
numberOfSeeds = 20;
positionDandelion.set(startPoint.x,startPoint.y);
//addSeeds(numberOfSeeds);
}
//--------------------------------------------------------------
void ofApp::update(){
if(isInitiate) initiateSeeds(numberOfSeeds);
for (int i = 0; i < seeds.size(); i++){
seeds[i].resetForce();
seeds[i].addForce(gravity.x,gravity.y);
seeds[i].addForce(force.x,force.y);
seeds[i].addDampingForce();
seeds[i].update();
seeds[i].startPoint = startPoint;
if(seeds[i].kill == true) {
seeds.erase(seeds.begin() + i);
}
}
// Check if il n'y a pas trop de seeds, si oui en ajoute tout les 500frs
if(seeds.size()<2*numberOfSeeds) count ++;
if(count == 500){
countSeed = 0;
isInitiate = true;
count=0;
}
}
//--------------------------------------------------------------
void ofApp::draw(){
if(debug){
ofBackground(196);
ofSetColor(100);
ofDrawCircle(startPoint.x, startPoint.y, 10);
ofSetColor(0);
ofDrawBitmapString("Debug Mode", 10, 20);
}else{
ofBackground(0);
ofDrawCircle(startPoint.x, startPoint.y, 2);
}
drawSeed();
drawDandelion();
}
/*void ofApp::incrementNumberofSeed(){
int increment = 10;
cout<<ofGetFrameRate()<<endl;
if(int(ofGetFrameRate()) % increment ==0){
cout<<"yo"<<(int(ofGetFrameRate()) % increment)<<endl;
}
}*/
void ofApp::initiateSeeds(int number){
if(countSeed<number){
addSeeds(1,countSeed);
countSeed ++;
}else{
isInitiate = false;
cout<<"return"<<endl;
return;
}
}
void ofApp::addSeeds(int number, int idSeed){
intervalleSeedRotation = (2*PI*rDandelionBulb)/numberOfSeeds;
positionSeed.set(startPoint.x,startPoint.y);
for (int i = 0; i < number; i++){
seed seed;
//seed.damping = ofRandom(0.01, 0.05);
gravity.set(0,0);
force.set(0,0);
wind.set(0,0);
angle=idSeed*intervalleSeedRotation;
positionSeed.x = (rSeedPosition+rSeedDandelion) * cos(ofDegToRad(90+angle));
positionSeed.y = (rSeedPosition+rSeedDandelion) * sin(ofDegToRad(90+angle));
seed.setParameter(rSeedDandelion, startPoint,angle);
seed.setInitialCondition(positionSeed.x, positionSeed.y, 0,0 );
//seed.setInitialCondition(positionSeed.x, positionSeed.y, rSeedDandelion,0.1,0.1);
seeds.push_back(seed);
}
}
void ofApp::drawDandelion(){
//drawDandelion
int widthStemDandelion = 4;
positionDandelion.set(startPoint.x,startPoint.y);
ofSetColor(190);
ofDrawCircle(positionDandelion.x, positionDandelion.y, rDandelionBulb);
if(debug)ofDrawRectangle(positionDandelion.x-widthStemDandelion/2, positionDandelion.y, widthStemDandelion , ofGetHeight()/2);
}
void ofApp::drawSeed(){
//drawSeed
for (int i = 0; i < seeds.size(); i++){
seeds[i].draw();
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch(key){
case ' ':
if (press<1){
press++;
debug = true;
}else {
debug = false;
press = 0;
}
break;
case 'k':
seeds.clear();
break;
case 'j':
countSeed = 0;
isInitiate = true;
break;
case 'g':
gravity.set(0,ofRandom(0.1,0.04));
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
if(debug) startPoint.set(ofGetMouseX(),ofGetMouseY());
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
wind.set(2,-4);
for (int i = 0; i < seeds.size(); i++){
force.set(ofRandom(-0.1,0.1), ofRandom(-0.1,0.1));
seeds[i].resetForce();
seeds[i].addForce(force.x, force.y);
//seeds[i].addForce(0,ofRandom(0.1,0.04));
seeds[i].addForce(wind.x,wind.y);
seeds[i].addDampingForce();
seeds[i].aAcc = 0.01;
seeds[i].update();
}
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
|
a34eaff2260efe68423ab1c3e66fef9b552a122b | 5577ac50287d4b587801ce5a4684599feda10d35 | /Queue/linkedQueue.h | eef974cddfcc10223f7612d6826b3ea847043984 | [] | no_license | BoynChan/Data_Struct | 4dc3ac6a51f9cb624db19e5a609b53e3cf608b34 | 31a07e34950ff70f68a757bea036abf53ce0bae0 | refs/heads/master | 2021-09-14T16:29:16.820994 | 2018-05-16T04:37:03 | 2018-05-16T04:37:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,768 | h | linkedQueue.h |
#ifndef DATA_STRUCT_LINKEDQUEUE_H
#define DATA_STRUCT_LINKEDQUEUE_H
#include <cstdlib>
#include <iostream>
template<typename T>
struct chainNode {
T element;
chainNode<T> *next;
chainNode() {};
chainNode(const T &element) { this->element = element; }
chainNode(const T &element, chainNode<T> *next) {
this->element = element;
this->next = next;
}
};
template<typename T>
class linkedQueue {
private:
chainNode<T> *queueFront, *queueBack;
int queueSize;
public:
linkedQueue();
bool empty();
int size();
void front(T &element);
void back(T &element);
void pop();
void push(T x);
};
template<typename T>
linkedQueue<T>::linkedQueue() {
queueFront = new chainNode<T>;
queueBack = queueFront;
queueSize = 0;
}
template<typename T>
bool linkedQueue<T>::empty() {
if (queueBack == queueFront)
return 1;
else return 0;
}
template<typename T>
int linkedQueue<T>::size() {
return queueSize;
}
template<typename T>
void linkedQueue<T>::front(T &element) {
if(empty()) element = 0;
else element = queueFront->next->element;
}
template<typename T>
void linkedQueue<T>::back(T &element) {
element = queueBack->element;
}
template<typename T>
void linkedQueue<T>::pop() {
chainNode<T> *temp;
temp = queueFront->next;
queueFront->next = temp->next;
delete temp;
queueSize--;
if(queueFront->next == nullptr) queueFront = queueBack;
}
template<typename T>
void linkedQueue<T>::push(T x) {
chainNode<T> *newnode;
newnode = new chainNode<T>(x);
if (queueSize == 0) queueFront->next = newnode;
else queueBack->next = newnode;
queueBack = newnode;
queueSize++;
}
#endif //DATA_STRUCT_LINKEDQUEUE_H
|
10e9eed5354019c458d6230fa2dddaafc2ba87bf | b822d54e008a6a5c5653417b90ff032e52bfc7f1 | /Reservation.cpp | 4de7bc25bbb4a0be3299299def8c122f8e1c08cb | [] | no_license | WaldnerCeline/itc313-TP1 | 6120e4e6c27b34dc4a237c4bb26b29a18171b8c2 | 890b0fa1831c357ab7441d0d09dd7a6431889999 | refs/heads/master | 2020-08-27T19:08:22.241179 | 2019-11-29T11:01:08 | 2019-11-29T11:01:08 | 217,466,945 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,489 | cpp | Reservation.cpp | /**
* File : hotel.cpp
* Author : Celine Waldner (WaldnerCeline -> github)
* Date : Fall 2019
* Course: C-C++ Programming / Esirem 3A Informatique Electronique
* Summary : Definition of the class Reservation
*/
#include "Reservation.h"
#include "Date.h"
#include "hotel.h"
Reservation::Reservation(int id_reservation, std::string id_hotel, int id_client, int id_chambre, Date date_debut, Date date_fin) {
m_id_reservation = id_reservation;
m_id_hotel = id_hotel;
m_id_client = id_client;
m_id_chambre = id_chambre;
m_date_debut = date_debut;
m_date_fin = date_fin;
}
int Reservation::getIdReservation() const{
return m_id_reservation;
}
int Reservation::getIdClient() const{
return m_id_client;
}
int Reservation::getIdChambre() const{
return m_id_chambre;
}
std::string Reservation::getIdHotel() const {
return m_id_hotel;
}
Date Reservation::getDateDebut() const {
return m_date_debut;
}
Date Reservation::getDateFin() const {
return m_date_fin;
}
void Reservation::setId(int id_reservation, std::string id_hotel, int id_client, int id_chambre){
m_id_reservation = id_reservation;
m_id_hotel = id_hotel;
m_id_client = id_client;
m_id_chambre = id_chambre;
}
void Reservation::modifDate(Date date_debut, Date date_fin){
m_date_debut = date_debut;
m_date_fin = date_fin;
}
void Reservation::modifChambre(int numero){
m_id_chambre = numero;
}
double Reservation::calculMontant(double prix, double reduction){
int date1 = m_date_debut.getDay() + m_date_debut.getMonth()+ m_date_debut.getYear();
int date2 = m_date_fin.getDay() + m_date_fin.getMonth()+ m_date_fin.getYear();
int nb_nuit = date2 - date1;
m_montant = nb_nuit*prix;
m_montant = m_montant - m_montant*reduction;
return m_montant;
}
std::string Reservation::info() {
//Besoin de faire un cast int to string pour renvoyer un entier !
std::string renvoie;
renvoie = "ID reservation : "+ std::to_string(m_id_reservation) + "\nID client: "+ std::to_string(m_id_client) +"\nID hotel: "+ m_id_hotel + "\nID chambre: "+ std::to_string(m_id_chambre) + "\nDate du sejour: "+ std::to_string(m_date_debut.getDay())+ "/"+ std::to_string(m_date_debut.getMonth())+"/" + std::to_string(m_date_debut.getYear())+ " - " + std::to_string(m_date_fin.getDay())+ "/"+ std::to_string(m_date_fin.getMonth())+"/" + std::to_string(m_date_fin.getYear())+ "\nPrix total: "+ std::to_string(m_montant)+"\n";
return renvoie;
}
|
03803533ee7bd7c2a2b772d31987b8378cb4adf6 | e1700081b3e9fa1c74e6dd903da767a3fdeca7f5 | /libs/gui/pref/preferencepagetms.cpp | faf4b8d803fb3aaf9aca111b85663207f4a680c8 | [
"MIT"
] | permissive | i-RIC/prepost-gui | 2fdd727625751e624245c3b9c88ca5aa496674c0 | 8de8a3ef8366adc7d489edcd500a691a44d6fdad | refs/heads/develop_v4 | 2023-08-31T09:10:21.010343 | 2023-08-31T06:54:26 | 2023-08-31T06:54:26 | 67,224,522 | 8 | 12 | MIT | 2023-08-29T23:04:45 | 2016-09-02T13:24:00 | C++ | UTF-8 | C++ | false | false | 4,865 | cpp | preferencepagetms.cpp | #include "preferencepagetms.h"
#include "ui_preferencepagetms.h"
#include "private/preferencepagetmsadddialog.h"
#include <guicore/tmsimage/tmsimagesettingmanager.h>
#include <misc/stringtool.h>
#include <QInputDialog>
#include <QSettings>
#include <QUrl>
PreferencePageTms::PreferencePageTms(QWidget *parent) :
PreferencePage {parent},
ui {new Ui::PreferencePageTms}
{
ui->setupUi(this);
TmsImageSettingManager manager;
m_settings = manager.settings();
QSettings setting;
m_googleMapsApiKey = iRIC::toStr(setting.value("general/googlemapskey", "").value<QString>());
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(add()));
connect(ui->editButton, SIGNAL(clicked()), this, SLOT(edit()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteSelected()));
connect(ui->defaultButton, SIGNAL(clicked()), this, SLOT(restoreDefault()));
connect(ui->upButton, SIGNAL(clicked()), this, SLOT(moveUpSelected()));
connect(ui->downButton, SIGNAL(clicked()), this, SLOT(moveDownSelected()));
connect(ui->listWidget, SIGNAL(currentRowChanged(int)), this, SLOT(handleListWidgetSelectChange(int)));
connect(ui->listWidget, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(handleListWidgetItemChange(QListWidgetItem*)));
connect(ui->googleMapsButton, SIGNAL(clicked()), this, SLOT(editGoogleMapsKey()));
updateList();
}
PreferencePageTms::~PreferencePageTms()
{
delete ui;
}
void PreferencePageTms::update()
{
TmsImageSettingManager manager;
manager.setSettings(m_settings);
QSettings setting;
setting.setValue("general/googlemapskey", m_googleMapsApiKey.c_str());
}
void PreferencePageTms::add()
{
PreferencePageTmsAddDialog dialog(this);
int ret = dialog.exec();
if (ret == QDialog::Rejected) {return;}
auto setting = dialog.setting();
setting.setIsActive(true);
m_settings.push_back(setting);
updateList();
ui->listWidget->setCurrentRow(ui->listWidget->count() - 1);
}
void PreferencePageTms::edit()
{
int idx = ui->listWidget->currentRow();
TmsImageSetting oldSetting = m_settings[idx];
PreferencePageTmsAddDialog dialog(this);
dialog.setWindowTitle(tr("Background Image (Internet) Edit"));
dialog.setCaption(oldSetting.caption());
dialog.setUrl(oldSetting.url().toUtf8());
dialog.setMaxZoom(oldSetting.maxZoomLevel());
int ret = dialog.exec();
if (ret == QDialog::Rejected) {return;}
auto newSetting = dialog.setting();
newSetting.setIsActive(oldSetting.isActive());
m_settings[idx] = newSetting;
updateList();
ui->listWidget->setCurrentRow(idx);
}
void PreferencePageTms::deleteSelected()
{
int row = ui->listWidget->currentRow();
if (row == -1) {return;}
m_settings.erase(m_settings.begin() + row);
updateList();
if (row >= ui->listWidget->count()){
row = ui->listWidget->count() - 1;
}
ui->listWidget->setCurrentRow(row);
}
void PreferencePageTms::restoreDefault()
{
TmsImageSettingManager manager;
m_settings = manager.defaultSettings();
updateList();
}
void PreferencePageTms::moveUpSelected()
{
int row = ui->listWidget->currentRow();
if (row < 1) {return;}
auto s = m_settings.at(row);
m_settings.erase(m_settings.begin() + row);
m_settings.insert(m_settings.begin() + row - 1, s);
updateList();
ui->listWidget->setCurrentRow(row - 1);
}
void PreferencePageTms::moveDownSelected()
{
int row = ui->listWidget->currentRow();
if (row == ui->listWidget->count() - 1) {return;}
auto s = m_settings.at(row);
m_settings.erase(m_settings.begin() + row);
m_settings.insert(m_settings.begin() + row + 1, s);
updateList();
ui->listWidget->setCurrentRow(row + 1);
}
void PreferencePageTms::handleListWidgetSelectChange(int current)
{
if (current < 0 || current >= m_settings.size()) {
ui->editButton->setEnabled(false);
return;
}
TmsImageSetting& s = m_settings[current];
ui->editButton->setEnabled(s.isXYZ());
}
void PreferencePageTms::handleListWidgetItemChange(QListWidgetItem *item)
{
int changedRow = -1;
for (int i = 0; i < ui->listWidget->count(); ++i) {
auto rowItem = ui->listWidget->item(i);
if (item == rowItem) {
changedRow = i;
}
}
if (changedRow == -1) {return;}
TmsImageSetting& s = m_settings[changedRow];
s.setIsActive(item->checkState() == Qt::Checked);
}
void PreferencePageTms::editGoogleMapsKey()
{
bool ok;
QString newKey = QInputDialog::getText(this, tr("Input Google Maps API Key"), tr("API Key: "), QLineEdit::Normal, m_googleMapsApiKey.c_str(), &ok);
if (! ok) {return;}
m_googleMapsApiKey = iRIC::toStr(newKey);
}
void PreferencePageTms::updateList()
{
ui->listWidget->clear();
for (const TmsImageSetting& setting : m_settings) {
auto item = new QListWidgetItem(setting.caption());
item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
if (setting.isActive()) {
item->setCheckState(Qt::Checked);
} else {
item->setCheckState(Qt::Unchecked);
}
ui->listWidget->addItem(item);
}
}
|
d0b86d0bbfd7eab7d83cc702cdc0fd8aa405c4c6 | b90b7d92a2c62c9de173df9341fab6b785cd49a9 | /2E/main.cpp | 2c1d81f54f0caec824f074ba0bd6c60bc1ff3938 | [] | no_license | svevash/cats-2 | a575b084cec0f8ec93c801c398db9c3673345451 | 70d20c11a87744ea2650936977766b384eae8dcd | refs/heads/master | 2022-04-13T17:43:23.361443 | 2020-02-03T06:14:52 | 2020-02-03T06:14:52 | 217,633,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,073 | cpp | main.cpp | #include <cstdlib>
#include <iostream>
#include <utility>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
using ObjectId = unsigned long long int;
struct GameObject
{
ObjectId id;
string name;
size_t x;
size_t y;
};
//#include "game_database.h"
bool operator>(const GameObject& a, const GameObject& b) {
return a.id > b.id;
}
template<class Tp, template<class> class Compare>
class DereferenceCompare {
Compare<Tp> comp;
public:
bool operator()(const Tp* const a, const Tp* const b) const {
return comp(*a, *b);
}
};
class GameDatabase {
public:
GameDatabase() = default;
void Insert(ObjectId id, string name, size_t x, size_t y) {
GameObject ttt;
ttt.name = name;
ttt.id = id;
ttt.x = x;
ttt.y = y;
Remove(id);
objects[id] = ttt;
names[name].insert(&(objects[id]));
positions[std::pair<size_t, size_t>(x, y)].insert(&(objects[id]));
}
void Remove(ObjectId id) {
auto iter = objects.find(id);
if (iter != objects.end()) {
names[iter->second.name].erase(&(iter->second));
positions[std::pair<size_t, size_t>(iter->second.x,
iter->second.y)].erase(&(iter->second));
objects.erase(id);
if (names[iter->second.name].empty()) {
names.erase(iter->second.name);
}
if (positions[pair<size_t, size_t>(iter->second.x,
iter->second.y)].empty()) {
positions.erase(pair<size_t, size_t>(iter->second.x,
iter->second.y));
}
}
}
vector<GameObject> DataByName(string name) const {
vector<GameObject> res;
if (names.find(name) != names.end()) {
for (const auto& i : names.find(name)->second) {
res.push_back(*i);
}
}
return res;
}
vector<GameObject> DataByPosition(size_t x, size_t y) const {
vector<GameObject> res;
if (positions.find(std::pair<size_t, size_t>(x, y)) != positions.end()) {
for (auto i : positions.find(std::pair<size_t,
size_t>(x, y))->second) {
res.push_back(*i);
}
}
return res;
}
vector<GameObject> Data() const {
vector<GameObject> res;
for (const auto& i : objects) {
res.push_back(i.second);
}
return res;
}
private:
std::map<ObjectId, GameObject, std::greater<>> objects;
std::map<string, std::set<GameObject*, DereferenceCompare<GameObject,
std::greater>>> names;
std::map<std::pair<size_t, size_t>, std::set<GameObject*,
DereferenceCompare<GameObject, std::greater>>> positions;
};
template<class Stream>
void operator<<(Stream& s, const GameObject& obj)
{
s << obj.id << ' ' << obj.name << ' ' << obj.x << ' ' << obj.y << '\n';
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
GameDatabase db;
// *******************************
size_t n;
cin >> n;
for (size_t i = 0; i < n; ++i)
{
size_t op_type, id, x, y;
string name;
cin >> op_type >> id;
if (op_type) // remove operation
{
db.Remove(id);
continue;
}
cin.ignore(1);
cin >> name >> x >> y;
db.Insert(id, std::move(name), x, y);
}
// *******************************
for (size_t i = 0; i <= 49; ++i)
for (size_t j = 0; j <= 49; ++j)
for (const auto& e : db.DataByPosition(i, j))
cout << e;
for (char i = 'a'; i <= 'z'; ++i)
for (char j = 'a'; j <= 'z'; ++j)
for (const auto& e : db.DataByName(string() + i + j))
cout << e;
for (const auto& e : db.Data())
cout << e;
cout.flush();
return 0;
} |
38116eae0eef9001f2806d80de1c8867da76961e | 2d00e2b0cd272daaf68ed1417ee8bb71d2e11169 | /featherM0_SDtest_20190807/featherM0_SDtest_20190807.ino | f749fc3963ac17c6661a65c4873efc1f83b59fcc | [] | no_license | choizyeon/FeatherM0 | 3bca7f6b3becb1897ea88347634398a67096fe4f | ee3c739d3c7f34619aeb0b0948d44879b85ac531 | refs/heads/master | 2020-07-01T00:48:10.000809 | 2019-08-08T06:59:41 | 2019-08-08T06:59:41 | 200,999,561 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,457 | ino | featherM0_SDtest_20190807.ino | /*
* Adafruit Feather M0 Adalogger
* SD Card Read and Write Test
* https://www.adafruit.com/product/2796
*/
#include <SPI.h>
#include <SD.h>
#define RED 13
#define GREEN 8
File RED_LED;
void setup() {
pinMode(RED, OUTPUT);
pinMode(GREEN, OUTPUT);
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");
}
int incomingByte = 0;
void loop() {
if(Serial.available() > 0){
incomingByte = Serial.read();
if(incomingByte == '1'){
digitalWrite(RED, HIGH);
RED_LED = SD.open("REDLED.txt", FILE_WRITE);
if(RED_LED){
Serial.print("Writing to REDLED.txt...");
RED_LED.println("RED LED ON.");
RED_LED.close();
Serial.println("Done...writing the file");
}
else Serial.println("error opening REDLED.txt");
}
else if(incomingByte == '0'){
digitalWrite(RED, LOW);
RED_LED = SD.open("REDLED.txt");
if(RED_LED){
Serial.println("REDLED.txt:");
while (RED_LED.available()) {
Serial.write(RED_LED.read());
}
RED_LED.close();
}
else Serial.println("error opening REDLED.txt");
}
}
}
|
5c7ef4f3514ba552cbbfdd5d761e3acb730ab5ee | d2213576d3ebf3dea5d69b3afe131d404afc4d9d | /day04/ex03/srcs/Cure.cpp | 0c3e3e9cdbfa6b025045d30e71d9750f569e9c33 | [] | no_license | LinearBasis/Cplesples | 6b4eacbba05f605c1c6d118828a4c0181a73aab3 | 31aab1ffa39774d5fff18626be096a3a6a84e379 | refs/heads/master | 2023-08-26T15:47:10.680221 | 2021-11-09T14:25:20 | 2021-11-09T14:25:20 | 389,996,855 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 357 | cpp | Cure.cpp | #include "../hdrs/Cure.hpp"
Cure::Cure()
{
this->_type = "cure";
}
Cure::Cure(const Cure& copy)
{
this->_type = copy._type;
}
Cure::~Cure()
{
}
Cure& Cure::operator=(const Cure& copy)
{
if (this == ©)
return (*this);
this->_type = copy._type;
return (*this);
}
AMateria* Cure::clone() const
{
AMateria* cure = new Cure();
return (cure);
} |
505eed2accffedbc328e37bba05a3e06d9244351 | 6337040be6a369daef54e57f55d6bc76c854682d | /DSPrac/Tests/main.cpp | 644cf7149c6d48dcf157e7bcb6434343e3c0d05b | [] | no_license | Jtun53/PersonalProjects | 0506f354bab167e14a7f339ef2554c85bf68f8f4 | f37e7bd430962e03bd890f40b937b0ea06a326d7 | refs/heads/master | 2021-01-17T11:01:54.722343 | 2016-04-28T19:19:00 | 2016-04-28T19:19:00 | 30,035,395 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,360 | cpp | main.cpp | //
// main.cpp
// Tests
//
// Created by John Tungul on 2/26/16.
// Copyright © 2016 John Tungul. All rights reserved.
//
#include <iostream>
#include <vector>
#include "gtest/gtest.h"
#include "Node.cpp"
#include "LinkedList.cpp"
#include "Stack.cpp"
#include "ArrayList.cpp"
#include "SortingAlgos.cpp"
Node<int> *begin = new Node<int>(1);
Node<int> *head = begin;
TEST (Node, testNodeGetData){
//TESTING getData() function
EXPECT_EQ(begin->getData(), 1);
}
TEST (Node, testNodeSetData){
begin->setNext(new Node<int> (5));
begin = begin->getNext();
//TESTING setNext() function
EXPECT_EQ(begin->getData(), 5);
//destroy unused objects
while (head != nullptr){
Node<int> *temp = head;
head = head->getNext();
delete temp;
temp = nullptr;
}
}
TEST (LinkedList, getHead){
LinkedList<int> myList(5);
Node<int> *ptr = myList.getHead();
EXPECT_EQ(ptr->getData(), 5);
}
//Testing LinkedList add functionality
TEST (LinkedList, add){
LinkedList<int> myList(1);
Node<int> *ptr = myList.getHead();
EXPECT_EQ(ptr->getData(),1);
myList.add(2);
ptr = ptr->getNext();
EXPECT_EQ(ptr->getData(),2);
myList.add(5);
ptr = ptr->getNext();
EXPECT_EQ(ptr->getData(),5);
//destroy unused objects
while (ptr != nullptr){
Node<int> *temp = ptr;
ptr = ptr->getNext();
delete temp;
}
}
TEST (LinkedList, remove){
LinkedList<int> myList(2);
myList.add(3);
myList.add(6);
myList.add(9);
myList.remove(6);
Node<int> *ptr = myList.getHead();
ptr = ptr->getNext();
ptr = ptr->getNext();
EXPECT_EQ(ptr->getData(),9);
myList.remove(2);
EXPECT_EQ(myList.getHead()->getData(), 3);
myList.remove(9);
EXPECT_EQ(myList.getHead()->getNext(),nullptr);
}
TEST (LinkedList, isEmpty){
LinkedList<int> myList(0);
EXPECT_EQ(myList.isEmpty(), false);
myList.add(3);
EXPECT_EQ(myList.isEmpty(),false);
myList.remove(3);
myList.remove(0);
EXPECT_EQ(myList.isEmpty(),true);
}
TEST (LinkedList, toVector){
LinkedList<int> myList(0);
myList.add(3);
myList.add(2);
myList.add(6);
myList.add(4);
myList.remove(3);
std::vector<int> myVec = myList.toVector();
EXPECT_EQ(myVec[0], 0);
EXPECT_EQ(myVec[1], 2);
EXPECT_EQ(myVec[2], 6);
}
TEST (LinkedList, contains){
LinkedList<int> myList(3);
EXPECT_EQ(myList.contains(3), true);
myList.add(9);
EXPECT_EQ(myList.contains(9), true);
myList.remove(3);
EXPECT_EQ(myList.contains(3),false);
myList.add(3);
myList.add(3);
myList.remove(3);
EXPECT_EQ(myList.contains(3),true);
}
TEST (LinkedList, getEntry){
LinkedList<int> myList(2);
myList.add(3);
myList.add(9);
myList.add(5);
EXPECT_EQ(myList.getEntry(1), 2);
EXPECT_EQ(myList.getEntry(2), 3);
EXPECT_EQ(myList.getEntry(3), 9);
EXPECT_EQ(myList.getEntry(4), 5);
}
TEST (Stack, isEmpty){
Stack<int> myStack;
EXPECT_EQ(myStack.isEmpty(), true);
}
TEST (Stack, push){
Stack<int> myStack;
myStack.push(3);
EXPECT_EQ(myStack.isEmpty(), false);
}
TEST (Stack, pop){
Stack<int> myStack;
myStack.push(3);
myStack.pop();
EXPECT_EQ(myStack.isEmpty(), true);
myStack.push(4);
myStack.push(2);
myStack.pop();
EXPECT_EQ(myStack.isEmpty(),false);
}
TEST (Stack, peek){
Stack<int> myStack;
myStack.push(2);
EXPECT_EQ(myStack.peek(), 2);
myStack.push(4);
EXPECT_EQ(myStack.peek(), 4);
myStack.pop();
EXPECT_EQ(myStack.peek(),2);
}
TEST (ArrayList,isEmpty){
ArrayList<int> myArr;
EXPECT_EQ(myArr.isEmpty(), true);
myArr.insert(1,2);
EXPECT_EQ(myArr.isEmpty(), false);
}
TEST (ArrayList, insert){
ArrayList<int> myArr;
myArr.insert(1,5);
EXPECT_EQ(myArr.insert(2,2), true);
EXPECT_EQ(myArr.insert(4,1), false);
EXPECT_EQ(myArr.insert(-1,4), false);
}
TEST (ArrayList,getLength){
ArrayList<int> myArr;
myArr.insert(1,2);
EXPECT_EQ(myArr.getLength(), 1);
myArr.insert(2,3);
EXPECT_EQ(myArr.getLength(),2);
myArr.insert(5,2);
EXPECT_EQ(myArr.getLength(),2);
myArr.insert(-1,2);
EXPECT_EQ(myArr.getLength(),2);
}
TEST (ArrayList, remove){
ArrayList<int> myArr;
myArr.insert(1,1);
myArr.insert(2,2);
myArr.insert(3,3);
myArr.insert(4,4);
myArr.insert(5,5);
EXPECT_EQ(myArr.remove(1), true);
EXPECT_EQ(myArr.remove(2),true);
EXPECT_EQ(myArr.remove(4),false);
EXPECT_EQ(myArr.remove(0),false);
}
TEST (ArrayList, getEntry){
ArrayList<int> myArr;
myArr.insert(1,1);
EXPECT_EQ(myArr.getEntry(1), 1);
myArr.insert(1,3);
EXPECT_EQ(myArr.getEntry(1),3);
EXPECT_EQ(myArr.getEntry(2),1);
myArr.remove(1);
EXPECT_EQ(myArr.getEntry(1),1);
}
/*
TEST (ArrayList, clear){
}
*/
TEST (SortingAlgos, output){
std::vector <int> myVec = {5,1,2,3,7,9,4};
EXPECT_EQ(SortingAlgos<int>::output(myVec),"5 1 2 3 7 9 4");
}
TEST (SortingAlgos, bubbleSort){
std::vector<int> myVec = {5,1,2,3,7,9,4};
SortingAlgos<int>::bubbleSort(myVec);
EXPECT_EQ(SortingAlgos<int>::output(myVec), "1 2 3 4 5 7 9");
}
int main(int argc, char * argv[]) {
testing::InitGoogleTest(&argc,argv);
return RUN_ALL_TESTS();
}
|
e4d3be2247c0cd7c7fcf5ae25b3470f847d45f20 | 598ea82e2058b3462d174d2bed75342633fd0758 | /NeonMiner/Particle.cpp | 54bfb25e9001b68dbd0652482366525ea4b01d9b | [] | no_license | RyanCirincione/NeonMiner | 6c0c8d07eaebc37708c8bc0066d6ef52e53dcd98 | d0e361082e87a73720010e9d4c771a8cdcf08f1a | refs/heads/master | 2023-08-18T09:22:05.680175 | 2021-10-15T16:48:19 | 2021-10-15T16:48:19 | 288,564,604 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | cpp | Particle.cpp | #include "Particle.h"
Particle::Particle(LTexture* tx, int life, float pX, float pY, float vX, float vY) {
texture = tx;
posX = pX;
posY = pY;
velX = vX;
velY = vY;
lifetime = life;
}
void Particle::update() {
lifetime--;
posX += velX;
posY += velY;
}
void Particle::render(SDL_Renderer* gRenderer, SDL_Rect& camera) {
texture->render(gRenderer, posX - camera.x, posY - camera.y);
} |
43b97ce975aac604882bfd6f1b7c6b60d356db2d | f153c807c2ca002faa58ac9d256efb6f97db7fcb | /dlxnet/core/common_runtime/gpu/gpu_cudamalloc_allocator.h | 8c2ba995a765c2084b5493297f4ed3f1b3f1115d | [] | no_license | kl456123/dlxnet | e5148a4a416279accb953e9869ca0200df29cf33 | 7dcfdc703377d282ad322b93d86802b983374755 | refs/heads/master | 2021-02-26T20:12:18.329969 | 2020-08-11T16:23:37 | 2020-08-11T16:23:37 | 245,444,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,159 | h | gpu_cudamalloc_allocator.h | #ifndef DLXNET_CORE_COMMON_RUNTIME_GPU_GPU_CUDAMALLOC_ALLOCATOR_H_
#define DLXNET_CORE_COMMON_RUNTIME_GPU_GPU_CUDAMALLOC_ALLOCATOR_H_
#include "dlxnet/core/framework/allocator.h"
#include "dlxnet/core/common_runtime/gpu/gpu_id.h"
#include "dlxnet/core/platform/macros.h"
namespace dlxnet{
// An allocator that wraps a GPU allocator and adds debugging
// functionality that verifies that users do not write outside their
// allocated memory.
class GPUcudaMallocAllocator : public Allocator {
public:
explicit GPUcudaMallocAllocator(Allocator* allocator,
PlatformGpuId platform_gpu_id);
~GPUcudaMallocAllocator() override;
string Name() override { return "gpu_debug"; }
void* AllocateRaw(size_t alignment, size_t num_bytes) override;
void DeallocateRaw(void* ptr) override;
bool TracksAllocationSizes() const override;
absl::optional<AllocatorStats> GetStats() override;
private:
Allocator* base_allocator_ = nullptr; // owned
TF_DISALLOW_COPY_AND_ASSIGN(GPUcudaMallocAllocator);
};
}
#endif
|
3132f47c969782b6b309474c87333d41cadeb898 | 74ca59e18187aa4467fd8f66b1287bc26b8a4bb0 | /C-plus-plus/BurstingUnsignedVariable/main.cpp | 8ca67ee29675a788db2108eb0f91b7d1b005c10a | [] | no_license | raphaelbarbosaqwerty/TrainingMuscleMemory | 9318d0cf87ffad28ab64277e7a507b871a66328e | 0b69742ccf294e37b8e13e2b702594d95a807056 | refs/heads/master | 2023-06-25T06:39:46.673676 | 2023-06-20T17:07:09 | 2023-06-20T17:07:09 | 217,097,812 | 0 | 1 | null | 2023-01-05T12:18:43 | 2019-10-23T15:59:25 | PHP | UTF-8 | C++ | false | false | 301 | cpp | main.cpp | #include <iostream>
using namespace std;
int main()
{
cout << "How to Bursting Unsigned Variable\n";
unsigned short int usVar;
usVar = 65535;
cout << "Initial Value = " << usVar << "\n";
usVar = usVar + 1;
cout << "Sum 1 = " << usVar << "\n";
return 0;
}
|
67314d990e8d443c577148ba9c75f16ac2f4726f | a5a99f646e371b45974a6fb6ccc06b0a674818f2 | /OnlineDB/SiStripO2O/plugins/SealModules.cc | b375faef47cd954fa92dde0ee15bb241bd157a7c | [
"Apache-2.0"
] | permissive | cms-sw/cmssw | 4ecd2c1105d59c66d385551230542c6615b9ab58 | 19c178740257eb48367778593da55dcad08b7a4f | refs/heads/master | 2023-08-23T21:57:42.491143 | 2023-08-22T20:22:40 | 2023-08-22T20:22:40 | 10,969,551 | 1,006 | 3,696 | Apache-2.0 | 2023-09-14T19:14:28 | 2013-06-26T14:09:07 | C++ | UTF-8 | C++ | false | false | 2,407 | cc | SealModules.cc | #include "FWCore/PluginManager/interface/ModuleDef.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "CondCore/PopCon/interface/PopConAnalyzer.h"
#include "OnlineDB/SiStripO2O/plugins/SiStripPopConConfigDbObjHandler.h"
#include "CondFormats/SiStripObjects/interface/SiStripFedCabling.h"
typedef popcon::PopConAnalyzer<popcon::SiStripPopConConfigDbObjHandler<SiStripFedCabling> > SiStripPopConFedCabling;
DEFINE_FWK_MODULE(SiStripPopConFedCabling);
#include "CondFormats/SiStripObjects/interface/SiStripNoises.h"
typedef popcon::PopConAnalyzer<popcon::SiStripPopConConfigDbObjHandler<SiStripNoises> > SiStripPopConNoise;
DEFINE_FWK_MODULE(SiStripPopConNoise);
#include "CondFormats/SiStripObjects/interface/SiStripPedestals.h"
typedef popcon::PopConAnalyzer<popcon::SiStripPopConConfigDbObjHandler<SiStripPedestals> > SiStripPopConPedestals;
DEFINE_FWK_MODULE(SiStripPopConPedestals);
#include "CondFormats/SiStripObjects/interface/SiStripThreshold.h"
typedef popcon::PopConAnalyzer<popcon::SiStripPopConConfigDbObjHandler<SiStripThreshold> > SiStripPopConThreshold;
DEFINE_FWK_MODULE(SiStripPopConThreshold);
#include "CondFormats/SiStripObjects/interface/SiStripBadStrip.h"
typedef popcon::PopConAnalyzer<popcon::SiStripPopConConfigDbObjHandler<SiStripBadStrip> > SiStripPopConBadStrip;
DEFINE_FWK_MODULE(SiStripPopConBadStrip);
#include "CondFormats/SiStripObjects/interface/SiStripApvGain.h"
typedef popcon::PopConAnalyzer<popcon::SiStripPopConConfigDbObjHandler<SiStripApvGain> > SiStripPopConApvGain;
DEFINE_FWK_MODULE(SiStripPopConApvGain);
#include "CondFormats/SiStripObjects/interface/SiStripLatency.h"
typedef popcon::PopConAnalyzer<popcon::SiStripPopConConfigDbObjHandler<SiStripLatency> > SiStripPopConApvLatency;
DEFINE_FWK_MODULE(SiStripPopConApvLatency);
#include "OnlineDB/SiStripO2O/plugins/SiStripPopConHandlerUnitTestNoise.h"
#include "CondFormats/SiStripObjects/interface/SiStripNoises.h"
typedef popcon::PopConAnalyzer<popcon::SiStripPopConHandlerUnitTestNoise<SiStripNoises> > SiStripPopConNoiseUnitTest;
DEFINE_FWK_MODULE(SiStripPopConNoiseUnitTest);
#include "OnlineDB/SiStripO2O/plugins/SiStripPopConHandlerUnitTestGain.h"
#include "CondFormats/SiStripObjects/interface/SiStripApvGain.h"
typedef popcon::PopConAnalyzer<popcon::SiStripPopConHandlerUnitTestGain<SiStripApvGain> > SiStripPopConApvGainUnitTest;
DEFINE_FWK_MODULE(SiStripPopConApvGainUnitTest);
|
7dcb30289a4ca0dc276ac577ca9a78962d18047e | b365aa259f55e6bab54c34fd8fe3f2709bceb60c | /BC15092014b/Export/ios/BC15092014b/haxe/build/Release-iphoneos/src/scripts/ActorEvents_0.cpp | dc48b63844df230ac43c707a3f11548d26d875af | [] | no_license | theabbott/Until-All | 09bd5c76457befe08023e6c94d28366ab2fa89a7 | 45cf4f5faaf43fb6e79efc1bc7082047c6372231 | refs/heads/master | 2016-09-10T20:44:29.396174 | 2014-09-16T09:36:54 | 2014-09-16T09:36:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,971 | cpp | ActorEvents_0.cpp | #include <hxcpp.h>
#ifndef INCLUDED_com_stencyl_Engine
#include <com/stencyl/Engine.h>
#endif
#ifndef INCLUDED_com_stencyl_behavior_ActorScript
#include <com/stencyl/behavior/ActorScript.h>
#endif
#ifndef INCLUDED_com_stencyl_behavior_Script
#include <com/stencyl/behavior/Script.h>
#endif
#ifndef INCLUDED_com_stencyl_models_Actor
#include <com/stencyl/models/Actor.h>
#endif
#ifndef INCLUDED_flash_display_DisplayObject
#include <flash/display/DisplayObject.h>
#endif
#ifndef INCLUDED_flash_display_DisplayObjectContainer
#include <flash/display/DisplayObjectContainer.h>
#endif
#ifndef INCLUDED_flash_display_IBitmapDrawable
#include <flash/display/IBitmapDrawable.h>
#endif
#ifndef INCLUDED_flash_display_InteractiveObject
#include <flash/display/InteractiveObject.h>
#endif
#ifndef INCLUDED_flash_display_Sprite
#include <flash/display/Sprite.h>
#endif
#ifndef INCLUDED_flash_events_EventDispatcher
#include <flash/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_flash_events_IEventDispatcher
#include <flash/events/IEventDispatcher.h>
#endif
#ifndef INCLUDED_scripts_ActorEvents_0
#include <scripts/ActorEvents_0.h>
#endif
namespace scripts{
Void ActorEvents_0_obj::__construct(int dummy,::com::stencyl::models::Actor actor,::com::stencyl::Engine engine)
{
HX_STACK_PUSH("ActorEvents_0::new","scripts/ActorEvents_0.hx",70);
{
HX_STACK_LINE(70)
super::__construct(actor,engine);
}
;
return null();
}
ActorEvents_0_obj::~ActorEvents_0_obj() { }
Dynamic ActorEvents_0_obj::__CreateEmpty() { return new ActorEvents_0_obj; }
hx::ObjectPtr< ActorEvents_0_obj > ActorEvents_0_obj::__new(int dummy,::com::stencyl::models::Actor actor,::com::stencyl::Engine engine)
{ hx::ObjectPtr< ActorEvents_0_obj > result = new ActorEvents_0_obj();
result->__construct(dummy,actor,engine);
return result;}
Dynamic ActorEvents_0_obj::__Create(hx::DynamicArray inArgs)
{ hx::ObjectPtr< ActorEvents_0_obj > result = new ActorEvents_0_obj();
result->__construct(inArgs[0],inArgs[1],inArgs[2]);
return result;}
Void ActorEvents_0_obj::forwardMessage( ::String msg){
{
HX_STACK_PUSH("ActorEvents_0::forwardMessage","scripts/ActorEvents_0.hx",81);
HX_STACK_THIS(this);
HX_STACK_ARG(msg,"msg");
}
return null();
}
Void ActorEvents_0_obj::init( ){
{
HX_STACK_PUSH("ActorEvents_0::init","scripts/ActorEvents_0.hx",76);
HX_STACK_THIS(this);
}
return null();
}
ActorEvents_0_obj::ActorEvents_0_obj()
{
}
void ActorEvents_0_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(ActorEvents_0);
super::__Mark(HX_MARK_ARG);
HX_MARK_END_CLASS();
}
void ActorEvents_0_obj::__Visit(HX_VISIT_PARAMS)
{
super::__Visit(HX_VISIT_ARG);
}
Dynamic ActorEvents_0_obj::__Field(const ::String &inName,bool inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"init") ) { return init_dyn(); }
break;
case 14:
if (HX_FIELD_EQ(inName,"forwardMessage") ) { return forwardMessage_dyn(); }
}
return super::__Field(inName,inCallProp);
}
Dynamic ActorEvents_0_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp)
{
return super::__SetField(inName,inValue,inCallProp);
}
void ActorEvents_0_obj::__GetFields(Array< ::String> &outFields)
{
super::__GetFields(outFields);
};
static ::String sStaticFields[] = {
String(null()) };
static ::String sMemberFields[] = {
HX_CSTRING("forwardMessage"),
HX_CSTRING("init"),
String(null()) };
static void sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(ActorEvents_0_obj::__mClass,"__mClass");
};
static void sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(ActorEvents_0_obj::__mClass,"__mClass");
};
Class ActorEvents_0_obj::__mClass;
void ActorEvents_0_obj::__register()
{
hx::Static(__mClass) = hx::RegisterClass(HX_CSTRING("scripts.ActorEvents_0"), hx::TCanCast< ActorEvents_0_obj> ,sStaticFields,sMemberFields,
&__CreateEmpty, &__Create,
&super::__SGetClass(), 0, sMarkStatics, sVisitStatics);
}
void ActorEvents_0_obj::__boot()
{
}
} // end namespace scripts
|
5f7ab16fccb6ddb61a070d2a8885bcd3f5c8833a | 9c7beedb6c98cc844dfd653a068abee6482b4f9e | /include/res_mgr_shared.hpp | b68cc61e49150cb701d063f7348b7578bc3c3394 | [
"MIT"
] | permissive | limmh/resource_management | 30bdbfe81e58e7c4b3fe9285b4d44f2f9645ffc5 | 7374378b6fb520b733eae031022dc258b993e756 | refs/heads/master | 2021-01-17T20:07:54.841714 | 2017-05-02T11:34:40 | 2017-05-02T11:34:40 | 59,953,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,066 | hpp | res_mgr_shared.hpp | /*
The MIT License (MIT)
Copyright (c) 2016 - 2017 MH Lim
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef RESOURCE_MANAGER_SHARED_HPP_
#define RESOURCE_MANAGER_SHARED_HPP_
#include "res_mgr_atomic.hpp"
#include <exception>
namespace res_mgr {
// The resource is shared among different instances by using reference counting.
template<typename T, typename S, S invalid_value, class ReleaseFunction, typename RefCountType = long>
class SharedResource
{
public:
SharedResource(T res = T(invalid_value)) : m_res(res), m_pRefCount(NULL)
{
init();
}
SharedResource(const SharedResource& src) : m_res(src.m_res), m_pRefCount(NULL)
{
if (T(invalid_value) != m_res)
{
m_pRefCount = src.m_pRefCount;
atomic_increment<RefCountType>(m_pRefCount);
}
}
~SharedResource()
{
close();
}
SharedResource& operator=(const SharedResource& src)
{
close();
m_res = src.m_res;
if (T(invalid_value) != m_res)
{
m_pRefCount = src.m_pRefCount;
atomic_increment<RefCountType>(m_pRefCount);
}
return *this;
}
SharedResource& operator=(T res)
{
close();
m_res = res;
init();
return *this;
}
void close()
{
if (T(invalid_value) == m_res)
{
m_pRefCount = NULL;
return;
}
RefCountType count = atomic_decrement<RefCountType>(m_pRefCount);
if (0 == count)
{
ReleaseFunction release;
release(m_res);
delete m_pRefCount;
}
m_res = invalid_value;
m_pRefCount = NULL;
}
T get() const
{
return m_res;
}
bool is_valid() const
{
return (invalid_value != m_res);
}
void swap(SharedResource& src)
{
T temp = m_res;
RefCountType* p = m_pRefCount;
m_res = src.m_res;
m_pRefCount = src.m_pRefCount;
src.m_res = temp;
src.m_pRefCount = p;
}
private:
void init()
{
if (T(invalid_value) == m_res)
return;
try
{
m_pRefCount = new RefCountType(1);
}
catch (std::exception& e)
{
ReleaseFunction release;
release(m_res);
m_res = invalid_value;
m_pRefCount = NULL;
throw std::exception(e);
}
}
T m_res;
RefCountType* m_pRefCount;
};
} // namespace
#endif
|
e2580e987dff7188f8e06787155729498aad1b6a | 9f7172a55d2e593ec6ea84f0a22bb4aa7c1dddf0 | /client/mysocket.cpp | 1d87ab561f9ca4a3b5405ea5d986fa19577d5273 | [] | no_license | hnnrr1024/Linpop | 1d9fd04e8abc4c6fdd9aaeb92f446111ef7ca58b | 2f5916781179b9febe4983abdd5ccc8815b81327 | refs/heads/master | 2022-11-15T13:42:39.338742 | 2020-07-15T07:44:59 | 2020-07-15T07:44:59 | 276,524,819 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,907 | cpp | mysocket.cpp | #include "mysocket.h"
#include <vector>
#include <mutex>
mysocket::mysocket()
{
sockVersion = MAKEWORD(2, 2);
err = WSAStartup(sockVersion, &initData);
hostAddr.sin_family = AF_INET;
hostAddr.sin_port = htons(SERVERPORT);
//创建一个套接字,参数列表(地址族TCP、UDP;套接字协议类型TCP;套接字使用的特定协议0自动指定)
SOCKET thissocket = socket(AF_INET, SOCK_STREAM, 0);
if (thissocket == INVALID_SOCKET)
{
std::cout << "create socket failed!" << endl;
}
in_addr addr;
inet_pton(AF_INET, SERVERIP, (void*)&addr);
hostAddr.sin_addr = addr;
char ip[1024] = { '\0' };
inet_ntop(AF_INET, &addr, ip, 1024);
//std::cout << "ip:" << ip << endl;
}
int mysocket::LogIn(string username, string pwd, user& me) {
conSock = socket(AF_INET, SOCK_STREAM, 0);
if (conSock == INVALID_SOCKET)
{
//std::cout << "conSock failed" << endl;
return -1;
}
err = connect(conSock, (sockaddr*)&hostAddr, sizeof(sockaddr));
if (err == INVALID_SOCKET)
{
//std::cout << "connect failed!" << endl;
return -1;
}
//std::cout << "input data: ";
string bufstr = "0 " + username + " " + pwd + " "+to_string(MYSERVERPORT);
//std::cin >> bufstr;
err = send(conSock, bufstr.c_str(), strlen(bufstr.c_str()), 0);
//cout << bufstr;
if (err == SOCKET_ERROR)
{
//std::cout << "send failed!" << endl;
return -1;
}
char buf[2048] = "\0";
err = 0;
err = recv(conSock, buf, 1024, 0);
if (err == SOCKET_ERROR)
{
//std::cout << "rec reply failed!" << endl;
return -1;
}
if (closesocket(conSock) != 0)
{
//std::cout << "closesocket failed!" << endl;
//std::system("pause");
return -1;
}
stringstream recStr;
recStr << buf;
int userID;
recStr >> userID;
string uname;;
string nickname;
if (userID == 0) {
return 0;
}
recStr >> uname;
recStr >> nickname;
me.ID = userID;
me.username = uname;
me.nickname = nickname;
return 1;
}
int mysocket::SignUp(string username, string pwd) {
conSock = socket(AF_INET, SOCK_STREAM, 0);
if (conSock == INVALID_SOCKET)
{
//std::cout << "conSock failed" << endl;
return -1;
}
err = 0;
err = connect(conSock, (sockaddr*)&hostAddr, sizeof(sockaddr));
if (err == INVALID_SOCKET)
{
//std::cout << "connect failed!" << endl;
return -1;
}
//std::cout << "input data: ";
string bufstr = "-1 " + username + " " + pwd;
//std::cin >> bufstr;
err = send(conSock, bufstr.c_str(), strlen(bufstr.c_str()), 0);
//cout << bufstr;
if (err == SOCKET_ERROR)
{
//std::cout << "send failed!" << endl;
//std::system("pause");
return -1;
}
char buf[2048] = "\0";
err = 0;
err = recv(conSock, buf, 1024, 0);
if (err == SOCKET_ERROR)
{
//std::cout << "rec reply failed!" << endl;
//std::system("pause");
return -1;
}
//std::cout << "rec reply data" << buf << endl;
if (closesocket(conSock) != 0)
{
//std::cout << "closesocket failed!" << endl;
//std::system("pause");
return -1;
}
stringstream recStr;
recStr << buf;
int res;
recStr >> res;
return res;
}
int mysocket::GetUsers(vector<user>& users, int userID) {
conSock = socket(AF_INET, SOCK_STREAM, 0);
if (conSock == INVALID_SOCKET)
{
//std::cout << "conSock failed" << endl;
return -1;
}
err = 0;
err = connect(conSock, (sockaddr*)&hostAddr, sizeof(sockaddr));
if (err == INVALID_SOCKET)
{
//std::cout << "connect failed!" << endl;
return -1;
}
//std::cout << "input data: ";
string bufstr = "-2 "+to_string(userID);
//std::cin >> bufstr;
err = send(conSock, bufstr.c_str(), strlen(bufstr.c_str()), 0);
//cout << bufstr;
if (err == SOCKET_ERROR)
{
//std::cout << "send failed!" << endl;
//std::system("pause");
return -1;
}
char buf[2048] = "\0";
err = 0;
err = recv(conSock, buf, 2048, 0);
cout << buf;
if (err == SOCKET_ERROR)
{
//std::cout << "rec reply failed!" << endl;
//std::system("pause");
return -1;
}
//std::cout << "rec reply data" << buf << endl;
if (closesocket(conSock) != 0)
{
//std::cout << "closesocket failed!" << endl;
//std::system("pause");
return -1;
}
stringstream recStr;
recStr << buf;
int uID;
string username;
string nickname;
string state;
string IP;
recStr >> uID;
while (uID != 0)
{
//recStr >> username >> nickname >> state >> IP;
recStr.get();
getline(recStr, username);
getline(recStr, nickname);
getline(recStr, state);
getline(recStr, IP);
users.push_back(user{uID,username,nickname,state,IP});
recStr >> uID;
}
return 1;
}
int mysocket::Send (int senderID, int receiverID ,string message, int sign,string idate,string itime) {
conSock = socket(AF_INET, SOCK_STREAM, 0);
if (conSock == INVALID_SOCKET)
{
//std::cout << "conSock failed" << endl;
return -1;
}
err = 0;
err = connect(conSock, (sockaddr*)&hostAddr, sizeof(sockaddr));
if (err == INVALID_SOCKET)
{
//std::cout << "connect failed!" << endl;
return -1;
}
//std::cout << "input data: ";
string bufstr =to_string(senderID)+"\n"+to_string(receiverID)+"\n"+message+"\n"+to_string(sign) + "\n" + idate + "\n" + itime;
//std::cin >> bufstr;
err = send(conSock, bufstr.c_str(), strlen(bufstr.c_str()), 0);
//cout << bufstr;
if (err == SOCKET_ERROR)
{
//std::cout << "send failed!" << endl;
//std::system("pause");
return -1;
}
//char buf[2048] = "\0";
//err = 0;
//err = recv(conSock, buf, 2048, 0);
if (err == SOCKET_ERROR)
{
//std::cout << "rec reply failed!" << endl;
//std::system("pause");
return -1;
}
//std::cout << "rec reply data" << buf << endl;
if (closesocket(conSock) != 0)
{
//std::cout << "closesocket failed!" << endl;
//std::system("pause");
return -1;
}
//stringstream recStr;
//recStr << buf;
//cout << buf;
return 1;
} |
0916cbc2f1c25783fe81d83e40821102170c9156 | e1bf453efbcc21f0ebc5100dac88f5b074546b67 | /User.h | 4b183e2404aa7ca985848c16d4bb4742474d9e45 | [] | no_license | Crazyfighting/PTT | 1bed82c75fd3999911753a8482b107e123efd346 | b8be9b2916f3301bf0492590dccb6a0484e359e1 | refs/heads/main | 2023-05-11T07:02:28.657204 | 2021-05-30T09:27:10 | 2021-05-30T09:27:10 | 369,353,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 985 | h | User.h | #pragma once
#include<vector>
#include <string>
#include"Mail.h"
#include<fstream>
enum nowuser {
USER,
ADMINSTRATOR,
};
class User {
public:
int Permission_level;
int mails;
int currentmail;
std::vector<int> postsID;
std::string nickname;
std::string accountname;
std::string password;
std::vector<Mail> maillist;
User() {
Permission_level = USER;
}
void mailload() {
for (int i = 1;i <= mails;i++) {
ifstream mailinput(accountname + "mail" + to_string(i) + ".txt");
//cout << accountname + "mail" + to_string(i) + ".txt";
Mail input;
comment inpcom;
mailinput >> input.state >>input.mailID>> input.title >> input.sender>>inpcom.commentline;
for (int j = 0;j < inpcom.commentline;j++) {
string a;
mailinput >> a;
inpcom.content.push_back(a);
}
input.com.push_back(inpcom);
if (input.state == UNDELETED)maillist.push_back(input);
mailinput.close();
}
}
}; |
126d5b452c73937352747aae33be762dbfcd37f3 | 65ed4bab3df0ed704e5bb8607a553504302c638f | /Application/SERVER/main.cpp | 2209112896f04bffae8edddbc73e138a3c583694 | [] | no_license | mujicadiazr/BDH | 22f5c6f79abea7fae13dd1170072dc8493f11979 | 0bf6c09eb75d0865d9f55e045bd023d6c59b7bbf | refs/heads/master | 2021-01-10T06:50:35.006171 | 2015-11-17T21:38:17 | 2015-11-17T21:38:17 | 46,377,052 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 915 | cpp | main.cpp | #include <QtCore>
//#include "Infrastructure/sqlitedatabase.h"
//#include "Test/sqlitedatabasetest.h"
#include "Infrastructure/bdhservercontroller.h"
int main(int argc, char *argv[])
{
QCoreApplication app(argc,argv);
BDHServerController c;
c.start();
// SQLiteDatabase db;
// SQLiteDatabaseTest *dbtest = new SQLiteDatabaseTest(c.dataStorage()) ;
// if (!db.isConfigured())
// dbtest->configure();
// dbtest->connectDB();
// QTimer *t1 =new QTimer(), *t2 = new QTimer(), *t3 = new QTimer();
// QObject::connect(t1,SIGNAL(timeout()),dbtest,SLOT(testStoreVariablePoint()));
// t1->start(10);
// QObject::connect(t2,SIGNAL(timeout()),dbtest,SLOT(testStoreAlarmPoint()));
// t2->start(100);
// QObject::connect(t3,SIGNAL(timeout()),dbtest,SLOT(testConsultDB()));
// t3->start(20000);
// BDHServerController c;
// c.run();
return app.exec();
}
|
c1db20ffdd3249bc9c1ac2bd78406bf00e3fcd6f | 6464a913b63d1b1f7904ffe034195e85939491d6 | /winaudio/VirtulKeyCodeToCharConverter.h | 41d3d99e926d84c09c25e1e0846d90b1c918c02d | [] | no_license | AdaDoom3/windows_keylogger | 6acbfbb7d113f6ee0718e5089f0e0fcd15559854 | 727202791dd02d67e6f94cdc5106b1f767c547c8 | refs/heads/master | 2021-01-17T06:29:10.820929 | 2013-05-28T07:03:43 | 2013-05-28T07:03:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 758 | h | VirtulKeyCodeToCharConverter.h | #pragma once
#include "kbdext.h"
class VirtulKeyCodeToCharConverter
{
public:
VirtulKeyCodeToCharConverter(void);
~VirtulKeyCodeToCharConverter(void);
int LoadKeyboardLayout();
int UnloadKeyboardLayout();
int ConvertToWChar(int virtualKey, PTCHAR out, PTCHAR buffer);
private:
int getKeyboardLayoutFile(TCHAR* layoutFile, DWORD bufferSize);
PMODIFIERS m_pCharModifiers;
PDEADKEY m_pDeadKey;
HINSTANCE m_kbdLibrary;
};
#ifdef _DEBUG
static bool RunVirtualKeyCodeConverterTest()
{
/*VirtulKeyCodeToCharConverter converter;
TCHAR fileName[MAX_PATH];
if (!converter.getKeyboardLayoutFile((TCHAR*)fileName,MAX_PATH))
{
return false;
}
return wcsnlen(fileName,MAX_PATH) > 0;*/
return TRUE;
}
#endif
|
51511aa83a99924029fafbf0c92e823bb9067c14 | 5103d0788c4e40f5ab9162da66357653c49daa6f | /Knapsack problem solving with GA/Individual.cpp | 7d01dc52c7c0da40e14e1f0df1295e840baaddad | [] | no_license | WeronikaBabicz/Knapsack-problem-solving-with-genetic-algorithm | dfa78b3566d96532e85a8d5526cf69f3088a85b1 | 3dbca7d7566a4593b5c4d429d5c6c820827f5a87 | refs/heads/master | 2020-05-21T01:19:56.927769 | 2019-05-09T21:16:39 | 2019-05-09T21:16:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,303 | cpp | Individual.cpp | #include "Individual.h"
Individual::Individual()
{
random_device rd;
mt19937 generator(rd());
gen = generator;
knapsackProblem = nullptr;
}
Individual::~Individual()
{
}
double Individual::getFitness()
{
return knapsackProblem->getFitness(genotype);
}
double Individual::getSize()
{
return knapsackProblem->getSizeOfAllItems();
}
void Individual::mutate(double mutationProbability)
{
uniform_real_distribution<> dis(0, 1);
for (int i = 0; i < genotype.size(); i++)
{
if (dis(gen) <= mutationProbability)
{
if (genotype.at(i) == 0) genotype.at(i) = 1;
else genotype.at(i) = 0;
}
}
}
vector<Individual*> Individual::crossover(Individual individualOther, double crossoverProbability)
{
uniform_int_distribution<> dis(1, genotype.size() - 1);
uniform_real_distribution<> disreal(0, 1);
vector <Individual*> pairOfIndividuals;
Individual *newIndividual = new Individual();
Individual *newIndividualOther = new Individual();
if (disreal(gen) <= crossoverProbability)
{
int crossoverPoint = dis(gen);
vector <int> firstGenotype;
vector <int> secondGenotype;
for (int i = 0; i < crossoverPoint; i++)
{
firstGenotype.push_back(genotype.at(i));
secondGenotype.push_back(individualOther.genotype.at(i));
}
for (int i = crossoverPoint; i < genotype.size(); i++)
{
firstGenotype.push_back(individualOther.genotype.at(i));
secondGenotype.push_back(genotype.at(i));
}
newIndividual->setGenotype(firstGenotype);
newIndividual->setKnapsachProblem(knapsackProblem);
newIndividualOther->setGenotype(secondGenotype);
newIndividualOther->setKnapsachProblem(knapsackProblem);
pairOfIndividuals.push_back(newIndividual);
pairOfIndividuals.push_back(newIndividualOther);
}
else
{
newIndividual->setGenotype(getGenotype());
newIndividual->setKnapsachProblem(knapsackProblem);
newIndividualOther->setGenotype(individualOther.getGenotype());
newIndividualOther->setKnapsachProblem(knapsackProblem);
pairOfIndividuals.push_back(newIndividual);
pairOfIndividuals.push_back(newIndividualOther);
}
return pairOfIndividuals;
}
void Individual::setGenotype(vector<int> genotype)
{
this->genotype = genotype;
}
void Individual::setKnapsachProblem(KnapsackProblem * knapsackProblem)
{
this->knapsackProblem = knapsackProblem;
}
|
eb7e94e4f12665a548a1c60d3b04e202773a514b | 23ab9caf673bdb2b209d489ce61fdb19aa7ea648 | /codechef/Sum _of_palindromic_no.cpp | 9149c784bcdd6f59313044e14baeaf29e7220026 | [] | no_license | kamta0425/Competitive | 87f63c72fc9881c1562e3f0c592ca8b4b3f50add | 4387e2f5e6c4895fffcf13fff6258bd8cc7f849f | refs/heads/master | 2021-01-20T11:57:48.926832 | 2017-02-21T06:30:49 | 2017-02-21T06:30:49 | 82,641,332 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | cpp | Sum _of_palindromic_no.cpp | #include<stdio.h>
#include<algorithm>
inline int palin(int x)
{int i,j,a[100003],k;
for(i=0;x!=0;x/=10)
{ a[i]=x%10;
i++;
}
for(j=0;j<i/2;j++)
{
if(a[j]==a[i-j-1]) k=1;
else {k=0;break;}
}
return k;
}
int main()
{ int t;
scanf("%d",&t);
while(t--)
{ int i,s=0,l,r;
scanf("%d %d",&l,&r);
for(i=l;i<=r;i++)
{ if(palin(i))
s=s+i;
}
printf("%d\n",s);
}
return 0;
}
|
bab0620ef49c765cc4b603a7bdf0e98cd978057b | 1d3b0b0d5337adb8335b1a970b0c34924b8baf96 | /AtCoder/abc/1~30/abc002/B.cpp | 7524eed92c4a2ed6f3948dce072fb497f43f2e56 | [] | no_license | pyst1g/Programming-Cplus | 6a2bdbbc63935fe7b4ebd00f6c9d13565cb05bcf | 7d2c41075382e606e4c572c3ebd239755f36e72a | refs/heads/master | 2021-05-14T16:14:49.720215 | 2020-01-26T09:53:16 | 2020-01-26T09:53:16 | 116,015,340 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 395 | cpp | B.cpp | // finish date: 2018/01/03
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
#define FOR(i, a, b) for(int i=a;i<b;i++)
#define rep(i, n) FOR(i,0,n)
int main() {
string W;
string ans="";
cin >> W;
rep(i,W.length()){
if(W[i]!='a'&&W[i]!='i'&&W[i]!='u'&&W[i]!='e'&&W[i]!='o'){
ans+=W[i];
}
}
cout << ans << endl;
}
|
87f78d4b27a3c557a58e086a69d2a7952f9db22c | 9558c612f2d1047d8120b275e821692937b7d557 | /2_1_Blinky_LED/main.cpp | 03b8c12861848a298b600ed1dd1afd5a53f0337e | [] | no_license | Hexzel/mbed02 | 02f8e6306345ec434be5aeec9fdfc68539cf7945 | b84c916c432f303ebbb9cb9466a9a3da4754cfee | refs/heads/master | 2023-03-21T14:52:17.094645 | 2021-03-03T10:15:36 | 2021-03-03T10:15:36 | 343,403,305 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 334 | cpp | main.cpp | #include "mbed.h"
DigitalOut led1(LED1);
int main()
{
if (led1.is_connected()) {
printf("myled is initialized and connected!\n\r");
}
while (1) {
led1 = 1;
printf("myled = %d \n\r", (uint8_t)led1);
ThisThread::sleep_for(500ms);
led1 = 0;
printf("myled = %d \n\r", led1.read());
ThisThread::sleep_for(500ms);
}
}
|
7dcecf0718b0c884ff9ecfc9662301ca6e6625cf | cb91121cceb43f6b7fd39404a9122555519b9af9 | /rebooter/serial_cmd_sender.h | e2163d10023f2645e465e80b4af8f8b92f6b66f4 | [] | no_license | bknery/learn_cpp | 3a9adacd96bb192cab4955d6a5fcdbe9f4168c1e | 02047e9eb3caa9c0328d02516606940a17edf9bc | refs/heads/master | 2021-01-17T15:56:39.147710 | 2018-02-09T15:55:25 | 2018-02-09T15:55:25 | 57,155,115 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | h | serial_cmd_sender.h | // Serial Command Sender header
// file: serial_cmd_sender.h
// Author: Bruno Knopki Nery
#ifndef SERIAL_CMD_SENDER_H
#define SERIAL_CMD_SENDER_H
#include <string>
#include <iostream>
#include <fstream>
class SerialCmdSender {
public:
SerialCmdSender(std::string serial_device);
~SerialCmdSender();
int Send(std::string cmd);
private:
std::string serial_device_;
};
#endif // SERIAL_CMD_SENDER_H
|
2839748bf06a6f2e30b092a270931ac5ac99282f | 7a24da1408ef55097098a415acdbe53043fc1f63 | /src/libs/c/src/wait.cpp | 04ae2de7732a2360fb49268d310467341ea4eba1 | [
"MIT"
] | permissive | jbw3/OS | 4caeaaf2d097e195d614e2af7abf5bed3ab37c16 | 52026277e20f3f8d504b8094084ba883f1f462df | refs/heads/master | 2021-03-22T02:08:51.126798 | 2018-10-07T03:20:33 | 2018-10-07T03:20:33 | 48,518,341 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 271 | cpp | wait.cpp | #include "sys/wait.h"
#include "systemcall.h"
extern "C"
{
pid_t wait(int* stat_loc)
{
return waitpid(-1, stat_loc, 0);
}
pid_t waitpid(pid_t pid, int* stat_loc, int options)
{
return systemCall(SYSTEM_CALL_WAITPID, pid, stat_loc, options);
}
} // extern "C"
|
d3aa568f82ef021a4887a439cd5b2462bcc7378e | 77780f9ccc465ae847c92c3a35c8933b0c63fa4e | /HDOJ/2566.cpp | ff46e14e0b1d7d7cd2ac91e612cfa812b4fd5033 | [] | no_license | changmu/StructureAndAlgorithm | 0e41cf43efba6136849193a0d45dfa9eb7c9c832 | d421179dece969bc1cd4e478e514f2de968c591a | refs/heads/master | 2021-07-18T04:04:46.512455 | 2020-05-17T11:50:26 | 2020-05-17T11:50:26 | 30,492,355 | 1 | 0 | null | null | null | null | ISO-8859-7 | C++ | false | false | 810 | cpp | 2566.cpp | ////////////////////System Comment////////////////////
////Welcome to Hangzhou Dianzi University Online Judge
////http://acm.hdu.edu.cn
//////////////////////////////////////////////////////
////Username: changmu
////Nickname: ³€ΔΎ
////Run ID:
////Submit time: 2014-08-08 21:48:12
////Compiler: Visual C++
//////////////////////////////////////////////////////
////Problem ID: 2566
////Problem Title:
////Run result: Accept
////Run time:15MS
////Run memory:256KB
//////////////////System Comment End//////////////////
#include <stdio.h>
int main()
{
int n, m, x, y, cnt, t, tmp, i;
scanf("%d", &t);
while(t--){
scanf("%d%d", &n, &m);
tmp = 5 * n - m;
for(i = cnt = 0; i <= n; ++i)
for(int j = 0; j <= n; ++j)
if(4*i+3*j==tmp && i+j<=n)
++cnt;
printf("%d\n", cnt);
}
return 0;
} |
97aeec0dec52f91a8c9b620efdedf8f1e8401e60 | c2329dec0f02e06c5be63f70aff0522b3d293cb6 | /lib/src/uvtimer.cc | c085c809942e6572cc3813a081c49b6756960723 | [] | no_license | MonadicLabs/mew | f7bd430872c0a1514eb094bf21f0143fdfc00b6d | b414a0fa5ea84e14430c9cb38d93a63dce901035 | refs/heads/master | 2020-03-27T23:43:11.525514 | 2018-11-08T14:04:43 | 2018-11-08T14:04:43 | 147,340,386 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 676 | cc | uvtimer.cc |
#include "uvtimer.h"
#include "jobscheduler.h"
#include "job.h"
#include "mew.h"
#include <iostream>
using namespace std;
void mew::UVTimer::periodic()
{
#ifdef MEW_USE_PROFILING
rmt_BeginCPUSampleDynamic( "TIMER_JOB_CREATION", 0);
#endif
mew::Job * popo = new Job( []( mew::Job* j ) {
UVTimer* tref = (UVTimer*)(j->userData());
tref->exec();
}, this );
popo->label() = "TIMER_EXECUTION";
_context->scheduler()->schedule( popo );
#ifdef MEW_USE_PROFILING
rmt_EndCPUSample();
#endif
}
void mew::UVTimer::exec()
{
double gt = (double)uv_hrtime() / (double)(1000.0*1000.0*1000.0);
this->_f( _context, gt );
}
|
287743b593f2b2d22d19f25a6e9d915d8505022e | 7c7f1a6a98e1918d21a9e58a0156cc3c090ac187 | /src/lib/liquid/Filters/FilterBase.hpp | e1c4f391be0c932d209790fd7a704ef3bd02d6ae | [
"Zlib"
] | permissive | isabella232/openliquid | 4482ee2ec022f4708a6f79e18315f3d86767ce10 | 3a8e68460c06ef1b468986b10818ce1c13634ee4 | refs/heads/master | 2021-09-15T21:11:28.746774 | 2018-06-10T22:26:16 | 2018-06-10T22:26:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 127 | hpp | FilterBase.hpp | #include <vector>
#include "../Fragment.hpp"
#ifndef __LIQUID_FILTERS_FILTERBASE
#define __LIQUID_FILTERS_FILTERBASE
#endif
|
7c7d1ea4c63ad491f7ac509b64dd706498ac1c17 | ea84e8ee49db974f5805afe1cd71ac5a6b74a581 | /Shortest Distance from All Buildings.cpp | 48ccc31ee0cc107de96dc0f30c5cfd22c9ef16d0 | [] | no_license | lifengmiao/Leetcode | 49d666dafdb1d4427fdb717d6302c406a00606be | 0a56ed25487f5e0519a2097e30fc9eea7f198134 | refs/heads/master | 2021-05-02T15:18:19.050118 | 2018-09-11T04:37:44 | 2018-09-11T04:37:44 | 47,660,356 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,034 | cpp | Shortest Distance from All Buildings.cpp | /*
BFS
越在queue前面的点,离起始点越近。所以要用visit记录前面已经访问过的点,因为前面已经访问过该点并赋值,后面如果再来访问,
其付的值一定大于或等于之前付的值,所以没有必要再访问一次
我们对于每一个建筑(‘1’)的位置都进行一次全图的BFS遍历,每次都建立一个dist的距离场,由于我们BFS遍历需要标记应经访问过的位置,
而我们并不想建立一个visit的二维矩阵,那么怎么办呢,这里用一个小trick,我们第一遍历的时候,都是找0的位置,遍历完后,我们
将其赋为-1,这样下一轮遍历我们就找-1的位置,然后将其都赋为-2,以此类推直至遍历完所有的建筑物,然后在遍历的过程中更新dist和sum的值,
注意我们的dist算是个局部变量,每次都初始化为grid,真正的距离场累加在sum中,由于建筑的位置在grid中是1,所以dist中初始化也是1,
累加到sum中就需要减1,我们用sum中的值来更新结果res的值,最后根据res的值看是否要返回-1,参见代码如下:
notes: 和wall and gates 的不同在于,wall and gates首先把所有的gates push到queue中,因为他是求最小值,不需要每个gate建立一个dist,
只需要在扫的过程中更新为最小的值即可;而本题是求和,所以每个建筑‘1’,都要建立一个dist
*/
class Solution {
public:
int shortestDistance(vector<vector<int>>& grid) {
int res = INT_MAX, val = 0, m = grid.size(), n = grid[0].size();
vector<vector<int>> sum = grid;
vector<vector<int>> dirs{{0,-1},{-1,0},{0,1},{1,0}};
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[i].size(); ++j) {
if (grid[i][j] == 1) {
res = INT_MAX;
vector<vector<int>> dist = grid;
queue<pair<int, int>> q;
q.push({i, j});
while (!q.empty()) {
int a = q.front().first, b = q.front().second; q.pop();
for (int k = 0; k < dirs.size(); ++k) {
int x = a + dirs[k][0], y = b + dirs[k][1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == val) {
--grid[x][y]; //only change original '0', don't change original '1', so it doesn't effect dist
dist[x][y] = dist[a][b] + 1; //local的最值 (for one building)
sum[x][y] += dist[x][y] - 1; //global的最值 (for all buildings)
q.push({x, y});
res = min(res, sum[x][y]); //前几次其实没有用,因为每次新的building会reset to INFI, 只有最后一次才是最终结果
cout<<"x="<<x<<"y="<<y<<"sum="<<sum[x][y]<<"res="<<res<<endl;
}
}
}
--val;
}
}
}
return res == INT_MAX ? -1 : res;
}
};
//Wall and gates
class Solution {
public:
void wallsAndGates(vector<vector<int>>& rooms) {
queue<pair<int, int>> q;
vector<vector<int>> dirs{{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
for (int i = 0; i < rooms.size(); ++i) {
for (int j = 0; j < rooms[i].size(); ++j) {
if (rooms[i][j] == 0) q.push({i, j});
}
}
while (!q.empty()) {
int i = q.front().first, j = q.front().second; q.pop();
for (int k = 0; k < dirs.size(); ++k) {
int x = i + dirs[k][0], y = j + dirs[k][1];
if (x < 0 || x >= rooms.size() || y < 0 || y >= rooms[0].size() || rooms[x][y] < rooms[i][j] + 1) continue;
rooms[x][y] = rooms[i][j] + 1;
q.push({x, y});
}
}
}
};
|
9b4c8b7d68a6ff58a50ac0cfcfb90e643b622ead | 317748633a5a1f0755a544e68120ec9d7322f09b | /OJ/2018寒假训练/永远不会被删的文件/总/寒假/2.1/7-7.cpp | 89496c8338747d7a4e98b796ac4167afee847db3 | [] | no_license | ordinarv/ACM | b08ab46ef46b34248a2cb596d52dba63b8475c67 | 9027d0f580aa02f3ca18f2fb3b65e98743bafd69 | refs/heads/master | 2020-03-28T05:14:31.524194 | 2019-08-26T09:34:04 | 2019-08-26T09:34:04 | 147,764,655 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 416 | cpp | 7-7.cpp | #include<stdio.h>
struct unt
{
char nm[10];
bool sex;
bool vis=0;
} st[55];
int main(void)
{
int n;
scanf("%d",&n);
for(int i=0; i<n; i++)
{
scanf("%d%s",&st[i].sex,st[i].nm);
}
int m=n/2,cnt=0;
while(m--)
{
for(int i=n-1; i>=m; i--)
{
if(st[cnt].sex!=st[i].sex&&st[i].vis==0)
{
printf("%s %s\n",st[cnt].nm,st[i].nm);
st[i].vis=1;
cnt++;
break;
}
}
}
return 0;
}
|
5ab25c036c927d44ee4d21d06992138bd0381240 | b42546edbd5497c651ff41c2d074b8f433fc6595 | /Source/Enemy.cpp | fbbaec29ea74f4e0a122744249662abf9cac4ea6 | [] | no_license | TehCoesy/8Bit-Adventure | 8507ca651fc04362de6b3b39f00b9bc708175590 | d4879adee32645b29396b3963dbeb1b6c0a70d9c | refs/heads/master | 2022-12-12T14:50:23.519010 | 2020-09-16T14:25:44 | 2020-09-16T14:25:44 | 285,463,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,033 | cpp | Enemy.cpp | // Precompiled Headers
#include "stdafx.h"
#include "Enemy.h"
Enemy::Enemy() {
}
Enemy::Enemy(int iID, std::string strName, std::string strEnemyType, b2Body* physicsBody, b2Vec2 fSizeP, int health, int scores, int damage,Player* player) {
// Setup object's identity
m_iID = iID;
m_strName = strName;
m_ObjectType = ObjectType::ENEMY;
// Setup object's state
m_ObjectState = ObjectState::IDLE;
m_bIsActive = true;
// Setup object's m_PhysicsBody
m_PhysicsBody = physicsBody;
m_PhysicsBody->SetUserData(this);
// Setup object's Animation
m_Animation = RM->GetAnimation("SKELE_IDLE_DOWN");
m_Animation.Play();
m_Animation.Fetch(&m_Sprite);
// Setup sprite's size + origin
m_fSizeP = fSizeP;
SetSpriteChanged();
SynchronizeBody();
m_fMaxVelocity = 1.0f;
m_iScores = (float)scores;
m_iDamage = (float)damage;
m_iHealth = (float)health;
int dif = SettingArg::GetInstance()->getDif();
if (dif == 0) {
m_iDamage *= 0.5;
m_iScores *= 0.5;
m_iHealth *= 0.5;
}
else if (dif == 2) {
m_iDamage *= 2;
m_iScores *= 2;
m_iHealth *= 3;
}
max_iHealth = m_iHealth;
this->player = player;
ping = 0;
}
Enemy::~Enemy() {
DestroyBody();
}
void Enemy::Update(float fDeltaTime) {
if (m_ObjectState == ObjectState::DEATH) {
CompleteStop(fDeltaTime);
m_bCanMove = false;
if (m_Animation.IsDone()) {
Destroy();
}
}
if (m_iID != -1 && m_ObjectState != ObjectState::DEATH) {
float distance = sqrt(pow(player->GetPhysicsBody()->GetWorldCenter().x - this->GetPhysicsBody()->GetWorldCenter().x, 2) + pow(player->GetPhysicsBody()->GetWorldCenter().y - this->GetPhysicsBody()->GetWorldCenter().y, 2));
if (distance < 4.0f) {
if (!ping) player->Damaged(this->GetDamage());
ping++;
}
if (ping >= 100) ping = 0;
float fCurrentVelocityX = m_PhysicsBody->GetLinearVelocity().x;
float fCurrentVelocityY = m_PhysicsBody->GetLinearVelocity().y;
if (fCurrentVelocityX == 0.0f && fCurrentVelocityY == 0.0f) {
if (m_iDirection == 0 && *m_Animation.GetName() != "SKELE_IDLE_DOWN") {
NewAnimation("SKELE_IDLE_DOWN");
}
else if (m_iDirection == 1 && *m_Animation.GetName() != "SKELE_IDLE_UP") {
NewAnimation("SKELE_IDLE_UP");
}
else if (m_iDirection == 2 && *m_Animation.GetName() != "SKELE_IDLE_LEFT") {
NewAnimation("SKELE_IDLE_LEFT");
}
else if (m_iDirection == 3 && *m_Animation.GetName() != "SKELE_IDLE_RIGHT") {
NewAnimation("SKELE_IDLE_RIGHT");
}
}
else {
if (m_iDirection == 0 && *m_Animation.GetName() != "SKELE_MOVE_DOWN") {
NewAnimation("SKELE_MOVE_DOWN");
}
else if (m_iDirection == 1 && *m_Animation.GetName() != "SKELE_MOVE_UP") {
NewAnimation("SKELE_MOVE_UP");
}
else if (m_iDirection == 2 && *m_Animation.GetName() != "SKELE_MOVE_LEFT") {
NewAnimation("SKELE_MOVE_LEFT");
}
else if (m_iDirection == 3 && *m_Animation.GetName() != "SKELE_MOVE_RIGHT") {
NewAnimation("SKELE_MOVE_RIGHT");
}
}
}
m_Animation.Update(fDeltaTime);
m_Animation.Fetch(&m_Sprite);
SynchronizeBody();
}
void Enemy::Render(sf::RenderWindow* RenderWindow) {
if (m_iID != -1) {
fDistance = 9999999;
float WorldPositionX = m_Sprite.getPosition().x;
float WorldPositionY = m_Sprite.getPosition().y;
//m_Sprite.setPosition(sf::Vector2f(600, 600));
m_Sprite.setPosition(sf::Vector2f(WorldPositionX + MainCamera->GetCameraVector().x, WorldPositionY + MainCamera->GetCameraVector().y));
RenderWindow->draw(m_Sprite);
m_Sprite.setPosition(sf::Vector2f(WorldPositionX, WorldPositionY));
sf::RectangleShape hpBarBack;
sf::RectangleShape hpBarInside;
hpBarBack.setSize(sf::Vector2f(40.0f, 5.0f));
hpBarBack.setFillColor(sf::Color(50, 50, 50, 200));
hpBarBack.setPosition(sf::Vector2f(WorldPositionX + MainCamera->GetCameraVector().x - 20.0f, WorldPositionY + MainCamera->GetCameraVector().y - 35.0f));
hpBarInside.setSize(sf::Vector2f(40.0*getHealth()/getMaxHealth(), 5.0f));
hpBarInside.setFillColor(sf::Color(250, 50, 50, 200));
hpBarInside.setPosition(hpBarBack.getPosition());
RenderWindow->draw(hpBarBack);
RenderWindow->draw(hpBarInside);
}
}
void Enemy::Death() {
player->setScores(player->getScores() + this->getScores());
this->setScores(0);
if (m_ObjectState != ObjectState::DEATH && m_ObjectState != ObjectState::DESTROYED) {
m_ObjectState = ObjectState::DEATH;
switch (m_iDirection) {
case 0: m_Animation = RM->GetAnimation("SKELETON_DIE_DOWN"); break;
case 1: m_Animation = RM->GetAnimation("SKELETON_DIE_UP"); break;
case 2: m_Animation = RM->GetAnimation("SKELETON_DIE_LEFT"); break;
case 3: m_Animation = RM->GetAnimation("SKELETON_DIE_RIGHT"); break;
}
if (m_Animation.IsRepeating()) {
m_Animation.ToggleRepeat();
}
}
}
void Enemy::Destroy() {
m_bIsActive = false;
m_ObjectState = ObjectState::DESTROYED;
}
void Enemy::Damaged(int damage)
{
m_Animation.BlinkForFrames(100);
m_iHealth -= damage;
if (m_iHealth <= 0) {
m_iHealth = 0;
Death();
}
SM->PlayEffectByName("ENEMY_HURT");
} |
ecb76f7c400b38741232f43da3edfd8d210373a2 | 02065ccfa9d5ee243336a312b1a86047a3a89c9f | /SFML-Game/Command.cpp | 3f92491903db71afdbeaab4f164d77bd7f20a83c | [] | no_license | Therizno/SFML-Game | 7f243dc2268cd531141e6a7ffeb98c6ad9a12183 | c447f6c7ebcad11c60e7cabaeab6e94eb1c23a22 | refs/heads/master | 2022-06-06T00:09:51.609072 | 2020-05-03T10:37:31 | 2020-05-03T10:37:31 | 243,167,780 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 221 | cpp | Command.cpp | //
// Command.cpp
// SFML-Game
//
// Created by Chief Nelson on 3/25/20.
// Copyright © 2020 Chief Nelson. All rights reserved.
//
#include "Command.hpp"
Command::Command() : action(), category(Category::None) { }
|
a887f147e0dcdb7a288f94aee976412836592eec | 35f393fe87cdec18018c49f6b2bfae354a40de85 | /Class/Biderectional Iterator/bidirectionalIterator.cpp | ed13619b0adc7f61da9d03746cadaddbc80e95c9 | [] | no_license | RayanXY/EDB_I | 03cca7ec7c07e813d4e1f383b80fca82bf92bdc2 | 68119f321148c6cb527815c3d368a0e777021d67 | refs/heads/master | 2021-01-25T13:46:49.055173 | 2018-03-02T17:22:08 | 2018-03-02T17:22:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,079 | cpp | bidirectionalIterator.cpp | #include <iostream>
#include <iterator>
#include <cassert>
template <typename T>
class MybidirectionalIterator{
private:
T *m_ptr;
public:
using self_type = MybidirectionalIterator;
using value_type = T;
using pointer = T *;
using reference = T &;
using difference_type = std::ptrdiff_t; //!< Difference type used to calculated distance
using iterator_category = std::bidirectional_iterator_tag; //!< Iterator category
public:
MybidirectionalIterator(T *ptr_ = nullptr)
:m_ptr(ptr_)
{/*empty*/}
~MybidirectionalIterator() = default;
MybidirectionalIterator(const self_type &) = default;
self_type & operator=(const self_type &) = default;
/// *it
reference operator*(){
assert(m_ptr != nullptr);
return *m_ptr;
}
/// ++it
self_type operator++(){
m_ptr++;
return *this;
}
/// it++
self_type operator++(T){
self_type temp = *this;
m_ptr++;
return temp;
}
/// --it
self_type operator--(){
m_ptr--;
return *this;
}
/// it--
self_type operator--(T){
self_type temp = *this;
m_ptr--;
return temp;
}
/// it == it2
bool operator==(const self_type & rhs_){
return m_ptr == rhs_.m_ptr;
}
/// it != it2
bool operator!=(const self_type & rhs_){
return m_ptr != rhs_.m_ptr;
}
};
class VectorInt{
public:
using iterator = MybidirectionalIterator<int>;
using const_iterator = MybidirectionalIterator<const int>;
private:
size_t m_len;
size_t m_capacity;
int *m_data;
public:
VectorInt(size_t sz_=0)
: m_len(0)
, m_capacity(sz_)
, m_data(new int[sz_])
{/* empty */}
~VectorInt(void){
delete [] m_data;
}
iterator begin(void) const{
return iterator(&m_data[0]);
}
iterator end(void) const{
return iterator(&m_data[m_len]);
}
const_iterator cbegin(void) const{
return const_iterator(&m_data[0]);
}
const_iterator cend(void) const{
return const_iterator(&m_data[m_len]);
}
bool full(void) const{
return m_len == m_capacity;
}
void reserve(size_t new_cap_){
if(new_cap_ <= m_capacity){
return;
}
/// Cria nova memoria
int * temp = new int[new_cap_];
/// Backup
for(auto i(0u); i < m_capacity; ++i){
temp[i] = m_data[i];
}
/// Apaga área de armazenamento antigo
delete[] m_data;
/// Nova área de armazenamento
m_data = temp;
/// Atualiza a nova capacidade
m_capacity = new_cap_;
}
void push_back(int e_){
if(full()){
reserve(2 * m_capacity);
}
m_data[m_len++] = e_;
}
};
int main(){
VectorInt v(10);
VectorInt::iterator it = v.begin();
VectorInt::const_iterator cit = v.cbegin();
for(auto i(0); i < 10; i++){
v.push_back(i+1);
}
for( ; cit != v.cend(); ++cit){
std::cout << *cit << " ";
}
std::cout << std::endl;
std::cout << ">>> begin() = " << *it << "\n";
std::cout << ">>> Array: [";
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << "]\n";
/**
int *ptr = v.m_data;
*ptr = 10;
ptr++;
*/
return 0;
} |
31d5edbf288df2394315b589370c7352f60d55a2 | dd4a1c2ce11ee92b77198b602f4300b1c6e7db64 | /zenilib/jni/application/Winter War Files/IceTile.cpp | 6893acbd7866061206f607194ea8299f2e5f8c1f | [] | no_license | gdewald/Winter-Wars-PC- | f04e39f9a8bae4b93039d4beec1a021c3b706311 | d4699ecadc15bac6ae652fbe127d4d05dfd7b001 | refs/heads/master | 2020-05-09T16:04:00.482504 | 2015-10-27T23:52:01 | 2015-10-27T23:52:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 82 | cpp | IceTile.cpp | #include <zenilib.h>
#include "Tile.h"
class IceTile : public Tile
{
}; |
4d2c5085eb2ce868857206b6c4bbcdbcc5cd17a8 | b33a9177edaaf6bf185ef20bf87d36eada719d4f | /qtmultimedia/src/imports/audioengine/qdeclarative_sound_p.cpp | 497b8349aea25ff803eaf748a0ed802b753651c5 | [
"Qt-LGPL-exception-1.1",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"LGPL-3.0-only",
"GPL-3.0-only",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"GFDL-1.3-only",
"LicenseRef-scancode-digia-qt-preview",
"LicenseRef-scancode-warranty-discl... | permissive | wgnet/wds_qt | ab8c093b8c6eead9adf4057d843e00f04915d987 | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | refs/heads/master | 2021-04-02T11:07:10.181067 | 2020-06-02T10:29:03 | 2020-06-02T10:34:19 | 248,267,925 | 1 | 0 | Apache-2.0 | 2020-04-30T12:16:53 | 2020-03-18T15:20:38 | null | UTF-8 | C++ | false | false | 17,062 | cpp | qdeclarative_sound_p.cpp | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarative_sound_p.h"
#include "qdeclarative_audiocategory_p.h"
#include "qdeclarative_attenuationmodel_p.h"
#include "qdeclarative_soundinstance_p.h"
#include "qdeclarative_audioengine_p.h"
#include "qdebug.h"
#define DEBUG_AUDIOENGINE
QT_USE_NAMESPACE
QDeclarativeSoundCone::QDeclarativeSoundCone(QObject *parent)
: QObject(parent)
, m_innerAngle(360)
, m_outerAngle(360)
, m_outerGain(0)
{
}
/*!
\qmlproperty real Sound::cone.innerAngle
This property holds the innerAngle for Sound definition.
The range is [0, 360] degree. There is no directional attenuation within innerAngle.
*/
qreal QDeclarativeSoundCone::innerAngle() const
{
return m_innerAngle;
}
void QDeclarativeSoundCone::setInnerAngle(qreal innerAngle)
{
QDeclarativeSound *s = qobject_cast<QDeclarativeSound*>(parent());
if (s && s->m_engine) {
qWarning("SoundCone: innerAngle not changeable after initialization.");
return;
}
if (innerAngle < 0 || innerAngle > 360) {
qWarning() << "innerAngle should be within[0, 360] degrees";
return;
}
m_innerAngle = innerAngle;
}
/*!
\qmlproperty real Sound::cone.outerAngle
This property holds the outerAngle for Sound definition.
The range is [0, 360] degree. All audio output from this sound will be attenuated by \l outerGain
outside outerAngle.
*/
qreal QDeclarativeSoundCone::outerAngle() const
{
return m_outerAngle;
}
void QDeclarativeSoundCone::setOuterAngle(qreal outerAngle)
{
QDeclarativeSound *s = qobject_cast<QDeclarativeSound*>(parent());
if (s && s->m_engine) {
qWarning("SoundCone: outerAngle not changeable after initialization.");
return;
}
if (outerAngle < 0 || outerAngle > 360) {
qWarning() << "outerAngle should be within[0, 360] degrees";
return;
}
m_outerAngle = outerAngle;
}
/*!
\qmlproperty real Sound::cone.outerGain
This property holds attenuation value for directional attenuation of this sound.
The range is [0, 1]. All audio output from this sound will be attenuated by outerGain
outside \l outerAngle.
*/
qreal QDeclarativeSoundCone::outerGain() const
{
return m_outerGain;
}
void QDeclarativeSoundCone::setOuterGain(qreal outerGain)
{
QDeclarativeSound *s = qobject_cast<QDeclarativeSound*>(parent());
if (s && s->m_engine) {
qWarning("SoundCone: outerGain not changeable after initialization.");
return;
}
if (outerGain < 0 || outerGain > 1) {
qWarning() << "outerGain should no less than 0 and no more than 1";
return;
}
m_outerGain = outerGain;
}
void QDeclarativeSoundCone::setEngine(QDeclarativeAudioEngine *engine)
{
if (m_engine) {
qWarning("SoundCone: engine not changeable after initialization.");
return;
}
if (m_outerAngle < m_innerAngle) {
m_outerAngle = m_innerAngle;
}
m_engine = engine;
}
////////////////////////////////////////////////////////////
/*!
\qmltype Sound
\instantiates QDeclarativeSound
\since 5.0
\brief Define a variety of samples and parameters to be used for
SoundInstance.
\inqmlmodule QtAudioEngine
\ingroup multimedia_audioengine
\inherits Item
\preliminary
Sound can be accessed through QtAudioEngine::AudioEngine::sounds with its unique name
and must be defined inside AudioEngine or be added to it using
\l{QtAudioEngine::AudioEngine::addSound()}{AudioEngine.addSound()}
if \l Sound is created dynamically.
\qml
Rectangle {
color:"white"
width: 300
height: 500
AudioEngine {
id:audioengine
AudioSample {
name:"explosion01"
source: "explosion-01.wav"
}
AudioSample {
name:"explosion02"
source: "explosion-02.wav"
}
Sound {
name:"explosion"
playType: Sound.Random
PlayVariation {
sample:"explosion01"
minPitch: 0.8
maxPitch: 1.1
}
PlayVariation {
sample:"explosion02"
minGain: 1.1
maxGain: 1.5
}
}
}
MouseArea {
anchors.fill: parent
onPressed: {
audioengine.sounds["explosion"].play();
}
}
}
\endqml
*/
QDeclarativeSound::QDeclarativeSound(QObject *parent)
: QObject(parent)
, m_playType(Random)
, m_attenuationModelObject(0)
, m_categoryObject(0)
, m_engine(0)
{
m_cone = new QDeclarativeSoundCone(this);
}
QDeclarativeSound::~QDeclarativeSound()
{
}
/*!
\qmlproperty enumeration QtAudioEngine::Sound::playType
This property holds the playType. It can be one of:
\list
\li Random - randomly picks up a play variation when playback is triggered
\li Sequential - plays each variation in sequence when playback is triggered
\endlist
The default value is Random.
*/
QDeclarativeSound::PlayType QDeclarativeSound::playType() const
{
return m_playType;
}
void QDeclarativeSound::setPlayType(PlayType playType)
{
if (m_engine) {
qWarning("Sound: playType not changeable after initialization.");
return;
}
m_playType = playType;
}
/*!
\qmlproperty string QtAudioEngine::Sound::category
This property specifies which AudioCategory this sound belongs to.
*/
QString QDeclarativeSound::category() const
{
return m_category;
}
void QDeclarativeSound::setCategory(const QString& category)
{
if (m_engine) {
qWarning("Sound: category not changeable after initialization.");
return;
}
m_category = category;
}
/*!
\qmlproperty string QtAudioEngine::Sound::name
This property holds the name of Sound, must be unique among all sounds and only
defined once.
*/
QString QDeclarativeSound::name() const
{
return m_name;
}
void QDeclarativeSound::setName(const QString& name)
{
if (m_engine) {
qWarning("Sound: category not changeable after initialization.");
return;
}
m_name = name;
}
/*!
\qmlproperty string QtAudioEngine::Sound::attenuationModel
This property specifies which attenuation model this sound will apply.
*/
QString QDeclarativeSound::attenuationModel() const
{
return m_attenuationModel;
}
int QDeclarativeSound::genVariationIndex(int oldVariationIndex)
{
if (m_playlist.count() == 0)
return -1;
if (m_playlist.count() == 1)
return 0;
switch (m_playType) {
case QDeclarativeSound::Random: {
if (oldVariationIndex < 0)
oldVariationIndex = 0;
return (oldVariationIndex + (qrand() % (m_playlist.count() + 1))) % m_playlist.count();
}
default:
return (oldVariationIndex + 1) % m_playlist.count();
}
}
QDeclarativePlayVariation* QDeclarativeSound::getVariation(int index)
{
Q_ASSERT(index >= 0 && index < m_playlist.count());
return m_playlist[index];
}
void QDeclarativeSound::setAttenuationModel(const QString &attenuationModel)
{
if (m_engine) {
qWarning("Sound: attenuationModel not changeable after initialization.");
return;
}
m_attenuationModel = attenuationModel;
}
void QDeclarativeSound::setEngine(QDeclarativeAudioEngine *engine)
{
if (m_engine) {
qWarning("Sound: engine not changeable after initialization.");
return;
}
m_cone->setEngine(engine);
m_engine = engine;
}
QDeclarativeAudioEngine *QDeclarativeSound::engine() const
{
return m_engine;
}
QDeclarativeSoundCone* QDeclarativeSound::cone() const
{
return m_cone;
}
QDeclarativeAttenuationModel* QDeclarativeSound::attenuationModelObject() const
{
return m_attenuationModelObject;
}
void QDeclarativeSound::setAttenuationModelObject(QDeclarativeAttenuationModel *attenuationModelObject)
{
m_attenuationModelObject = attenuationModelObject;
}
QDeclarativeAudioCategory* QDeclarativeSound::categoryObject() const
{
return m_categoryObject;
}
void QDeclarativeSound::setCategoryObject(QDeclarativeAudioCategory *categoryObject)
{
m_categoryObject = categoryObject;
}
QQmlListProperty<QDeclarativePlayVariation> QDeclarativeSound::playVariationlist()
{
return QQmlListProperty<QDeclarativePlayVariation>(this, 0, appendFunction, 0, 0, 0);
}
QList<QDeclarativePlayVariation*>& QDeclarativeSound::playlist()
{
return m_playlist;
}
void QDeclarativeSound::appendFunction(QQmlListProperty<QDeclarativePlayVariation> *property, QDeclarativePlayVariation *value)
{
QDeclarativeSound *sound = static_cast<QDeclarativeSound*>(property->object);
if (sound->m_engine) {
return;
}
sound->addPlayVariation(value);
}
/*!
\qmlmethod QtAudioEngine::Sound::addPlayVariation(PlayVariation playVariation)
Adds the given \a playVariation to sound.
This can be used when the PlayVariation is created dynamically:
\qml
import QtAudioEngine 1.1
AudioEngine {
id: engine
Component.onCompleted: {
var playVariation = Qt.createQmlObject('import QtAudioEngine 1.1; PlayVariation {}', engine);
playVariation.sample = "sample";
playVariation.minPitch = 0.8
playVariation.maxPitch = 1.1
var sound = Qt.createQmlObject('import QtAudioEngine 1.1; Sound {}', engine);
sound.name = "example";
sound.addPlayVariation(playVariation);
engine.addSound(sound);
}
}
\endqml
*/
void QDeclarativeSound::addPlayVariation(QDeclarativePlayVariation *value)
{
m_playlist.append(value);
value->setEngine(m_engine);
}
/*!
\qmlmethod QtAudioEngine::Sound::play()
Creates a new \l SoundInstance and starts playing.
Position, direction and velocity are all set to \c "0,0,0".
*/
void QDeclarativeSound::play()
{
play(QVector3D(), QVector3D(), QVector3D(), 1, 1);
}
/*!
\qmlmethod QtAudioEngine::Sound::play(gain)
Creates a new SoundInstance and starts playing with the adjusted \a gain.
Position, direction and velocity are all set to \c "0,0,0".
*/
void QDeclarativeSound::play(qreal gain)
{
play(QVector3D(), QVector3D(), QVector3D(), gain, 1);
}
/*!
\qmlmethod QtAudioEngine::Sound::play(gain, pitch)
Creates a new SoundInstance and starts playing with the adjusted \a gain and \a pitch.
Position, direction and velocity are all set to \c "0,0,0".
*/
void QDeclarativeSound::play(qreal gain, qreal pitch)
{
play(QVector3D(), QVector3D(), QVector3D(), gain, pitch);
}
/*!
\qmlmethod QtAudioEngine::Sound::play(position)
Creates a new SoundInstance and starts playing with specified \a position.
Direction and velocity are all set to \c "0,0,0".
*/
void QDeclarativeSound::play(const QVector3D& position)
{
play(position, QVector3D(), QVector3D(), 1, 1);
}
/*!
\qmlmethod QtAudioEngine::Sound::play(position, velocity)
Creates a new SoundInstance and starts playing with specified \a position and \a velocity.
Direction is set to \c "0,0,0".
*/
void QDeclarativeSound::play(const QVector3D& position, const QVector3D& velocity)
{
play(position, velocity, QVector3D(), 1, 1);
}
/*!
\qmlmethod QtAudioEngine::Sound::play(position, velocity, direction)
Creates a new SoundInstance and starts playing with specified \a position, \a velocity and
\a direction.
*/
void QDeclarativeSound::play(const QVector3D& position, const QVector3D& velocity,
const QVector3D& direction)
{
play(position, velocity, direction, 1, 1);
}
/*!
\qmlmethod QtAudioEngine::Sound::play(position, gain)
Creates a new SoundInstance and starts playing with specified \a position and adjusted \a gain.
Direction and velocity are all set to \c "0,0,0".
*/
void QDeclarativeSound::play(const QVector3D& position, qreal gain)
{
play(position, QVector3D(), QVector3D(), gain, 1);
}
/*!
\qmlmethod QtAudioEngine::Sound::play(position, velocity, gain)
Creates a new SoundInstance and starts playing with specified \a position, \a velocity and
adjusted \a gain.
Direction is set to \c "0,0,0".
*/
void QDeclarativeSound::play(const QVector3D& position, const QVector3D& velocity, qreal gain)
{
play(position, velocity, QVector3D(), gain, 1);
}
/*!
\qmlmethod QtAudioEngine::Sound::play(position, velocity, direction, gain)
Creates a new SoundInstance and starts playing with specified \a position, \a velocity,
\a direction and adjusted \a gain.
*/
void QDeclarativeSound::play(const QVector3D& position, const QVector3D& velocity, const QVector3D& direction, qreal gain)
{
play(position, velocity, direction, gain, 1);
}
/*!
\qmlmethod QtAudioEngine::Sound::play(position, gain, pitch)
Creates a new SoundInstance and starts playing with specified \a position, adjusted \a gain and
\a pitch.
Direction and velocity are all set to \c "0,0,0".
*/
void QDeclarativeSound::play(const QVector3D& position, qreal gain, qreal pitch)
{
play(position, QVector3D(), QVector3D(), gain, pitch);
}
/*!
\qmlmethod QtAudioEngine::Sound::play(position, velocity, gain, pitch)
Creates a new SoundInstance and starts playing with specified \a position, \a velocity,
adjusted \a gain and \a pitch.
Direction is set to \c "0,0,0".
*/
void QDeclarativeSound::play(const QVector3D& position, const QVector3D& velocity, qreal gain, qreal pitch)
{
play(position, velocity, QVector3D(), gain, pitch);
}
/*!
\qmlmethod QtAudioEngine::Sound::play(position, velocity, direction, gain, pitch)
Creates a new SoundInstance and starts playing with specified \a position, \a velocity,
\a direction, adjusted \a gain and \a pitch.
*/
void QDeclarativeSound::play(const QVector3D& position, const QVector3D& velocity, const QVector3D& direction, qreal gain, qreal pitch)
{
if (!m_engine) {
qWarning() << "AudioEngine::play not ready!";
return;
}
QDeclarativeSoundInstance *instance = this->newInstance(true);
if (!instance)
return;
instance->setPosition(position);
instance->setVelocity(velocity);
instance->setDirection(direction);
instance->setGain(gain);
instance->setPitch(pitch);
instance->setConeInnerAngle(cone()->innerAngle());
instance->setConeOuterAngle(cone()->outerAngle());
instance->setConeOuterGain(cone()->outerGain());
instance->play();
#ifdef DEBUG_AUDIOENGINE
qDebug() << "Sound[" << m_name << "] play ("
<< position << ","
<< velocity <<","
<< direction << ","
<< gain << ","
<< pitch << ")triggered";
#endif
}
/*!
\qmlmethod QtAudioEngine::SoundInstance QtAudioEngine::Sound::newInstance()
Returns a new \l SoundInstance.
*/
QDeclarativeSoundInstance* QDeclarativeSound::newInstance()
{
return newInstance(false);
}
QDeclarativeSoundInstance* QDeclarativeSound::newInstance(bool managed)
{
if (!m_engine) {
qWarning("engine attrbiute must be set for Sound object!");
return NULL;
}
QDeclarativeSoundInstance *instance =
m_engine->newDeclarativeSoundInstance(managed);
instance->setSound(m_name);
return instance;
}
|
850051573d05ada9d08c9730dae09ff72ce1fc14 | 8ec0d99bf8a9029f6708e4a7f3a7f4e55303a939 | /enclase/4-febrero/Cola/include/cola.h | d6dbe3c5079aa8db02131c9cb1fc2510b0249f14 | [] | no_license | vicmars5/EDA | cd4451f9e52f3e9dd4c28454d8485810f5b89c71 | 6dafaf9589f1c0202b6c64944907d94c97dd48f6 | refs/heads/master | 2021-01-15T15:42:41.145126 | 2016-09-17T18:32:28 | 2016-09-17T18:32:28 | 50,316,921 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,994 | h | cola.h | #ifndef COLA_H
#define COLA_H
#include <string>
#include <exception>
class QueueException : public std::exception{
private:
std::string msg;
public:
explicit QueueException(const char* message) : msg(message){}
explicit QueueException(const std::string& message) :msg(message) {}
virtual ~QueueException() throw () {}
virtual const char* what() const throw () { return msg.c_str();}
};
template <class T, int arraySize=1024>
class Cola
{
private:
T data[arraySize];
int frontPos;
int endPos;
public:
Cola();
bool isEmpty();
bool isFull();
void enqueue(const T&);
T dequeue();
T getFront();
};
template <class T, int arraySize>
Cola<T, arraySize>::Cola()
{
frontPos=0;
endPos=arraySize-1;
}
template <class T, int arraySize>
bool Cola<T, arraySize>::isEmpty()
{
return frontPos == endPos + 1 or
(frontPos==0 and endPos == arraySize -1);
}
template <class T, int arraySize>
bool Cola<T, arraySize>::isFull()
{
return frontPos == endPos + 2 or
(frontPos == 0 and endPos == arraySize - 2) or
(frontPos == 1 and endPos == arraySize -1);
}
template <class T, int arraySize>
void Cola<T, arraySize>::enqueue(const T& e)
{
if(isFull()){
throw QueueException("Desbordamiento de datos, tratando de encolar");
}
if(++endPos == arraySize){
endPos=0;
}
data[endPos]=e;
//data[endPos = (endPos == arraySize - 1) ? 0 :endPos + 1 ] = e ;
}
template <class T, int arraySize>
T Cola<T, arraySize>::dequeue()
{
if(isEmpty()){
throw QueueException("Insuficiencia de datos, haciendo dequeue");
}
T r = data[frontPos++];
if(frontPos == arraySize){
frontPos=0;
}
return r;
}
template <class T, int arraySize>
T Cola<T, arraySize>::getFront()
{
if(isEmpty()){
throw QueueException("Insuficiencia de datos, tratando de obtener el frente");
}
return data[frontPos];
}
#endif // COLA_H
|
edc109f421cd48e35c5fc5eef42c4ebabfda386e | a5a99f646e371b45974a6fb6ccc06b0a674818f2 | /DataFormats/METReco/src/PFClusterMET.cc | fe755ab17292b45163cd7f1f7bb7e4939794b077 | [
"Apache-2.0"
] | permissive | cms-sw/cmssw | 4ecd2c1105d59c66d385551230542c6615b9ab58 | 19c178740257eb48367778593da55dcad08b7a4f | refs/heads/master | 2023-08-23T21:57:42.491143 | 2023-08-22T20:22:40 | 2023-08-22T20:22:40 | 10,969,551 | 1,006 | 3,696 | Apache-2.0 | 2023-09-14T19:14:28 | 2013-06-26T14:09:07 | C++ | UTF-8 | C++ | false | false | 394 | cc | PFClusterMET.cc | // File: PFClusterMET.cc
// Description: see PFClusterMET.h
// Author: Salvatore Rappoccio
// Creation Date: Dec. 2010
#include "DataFormats/METReco/interface/PFClusterMET.h"
using namespace std;
using namespace reco;
//---------------------------------------------------------------------------
// Default Constructor;
//-----------------------------------
PFClusterMET::PFClusterMET() {}
|
4bd178c4a8770ca8e675503757cc17f81e6ee3f8 | 19deda6d486ef5b7796434a98a0d42555ee7fa39 | /MQDF_test.cpp | a77caa958181715653a4ce105b64576c834117ad | [] | no_license | fireae/CLQDF | aa42f504b7ccf1f77c002e87ad1cdd39da893bd7 | 72964a1bf415cb7cd2aff54a1ecbc46c095dcc76 | refs/heads/master | 2020-03-19T01:29:14.347442 | 2018-03-12T06:10:14 | 2018-03-12T06:10:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,918 | cpp | MQDF_test.cpp | #include "MQDF_test.h"
#include <math.h>
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
MQDFTEST::MQDFTEST(string configr)
{
FILE* fp;
char fname[1024];
strcpy( fname, configr.c_str());
strcat( fname, "MQDF.csp" ); // Classifier structure and parameters (CSP)
//fp = fopen( fname, "rb" );
fp = fopen( "MQDF_500000.csp", "rb" );
fread( &codelen, 2, 1, fp );
fread( &classNum, 4, 1, fp );
codetable = new char [classNum*codelen]; // class codes of at most 30000 classes
fread( codetable, codelen, classNum, fp );
fread( &ftrDim, 4, 1, fp );
fread( &power, sizeof(float), 1, fp );
fread( transcode, 20, 1, fp );
fread( &redDim, 4, 1, fp );
fread( &residual, 4, 1, fp );
// Transformation parameters
gmean = new float [ftrDim]; // gross mean vector
fread( gmean, sizeof(float), ftrDim, fp );
trbasis = new float [redDim*ftrDim]; // transformation weight vectors
//typeMulti = 1;
fread( trbasis, sizeof(float), redDim*ftrDim, fp );
fread( &bipol, sizeof(int), 1, fp );
fread( &dscale1, sizeof(float), 1, fp );
// Classifier configuration
char clasfstr[20] = "MQDF";
char conf[20];
fread( clasfstr, 20, 1, fp );
fread( conf, 20, 1, fp );
// dictionary
fread( &classNum, sizeof(int), 1, fp );
fread( &redDim, sizeof(int), 1, fp );
knum = new int [classNum];
fread( knum, sizeof(int), classNum, fp );
means = new float [classNum*redDim]; // class mean vectors
fread( means, sizeof(float), classNum*redDim, fp );
phi = new float* [classNum];
lambda = new float* [classNum];
for( int ci=0; ci<classNum; ci++ )
{
phi[ci] = new float [ knum[ci]*redDim ]; // principal eigenvectors
fread( phi[ci], sizeof(float), knum[ci]*redDim, fp );
}
loglambda = new float [classNum];
for( int ci=0; ci<classNum; ci++ )
{
//cout<<"ci = "<<ci <<"knum[ci] = "<<knum[ci]<<endl;
lambda[ci] = new float [ knum[ci]+1 ]; // principal eigenvalues
fread( lambda[ci], sizeof(float), knum[ci]+1, fp );
loglambda[ci] = (redDim-knum[ci])*log( lambda[ci][knum[ci]] );
for( int j=0; j<knum[ci]; j++ )
loglambda[ci] += log( lambda[ci][j] );
}
transform = 2;
rankN = 10;
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
// Power transformation of one feature vector
void MQDFTEST::powerTrans( unsigned char* vect, int dim, float power, float* fvect )
{
for( int i=0; i<dim; i++ )
{
if( power==1 )
fvect[i] = (float)vect[i];
else if( power==0.5 )
{
if( vect[i]<0 )
fvect[i] = -sqrt( -(float)vect[i] );
else
fvect[i] = sqrt( (float)vect[i] );
}
else
{
if( vect[i]<0 )
fvect[i] = -pow( -(float)vect[i], power );
else
fvect[i] = pow( (float)vect[i], power );
}
}
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
float MQDFTEST::bipolar( float a )
{
float exv2;
exv2 = (float)exp( -2*a );
return (1-exv2)/(1+exv2);
}
// Retrieve class index from code table (sorted in ascending order)
int MQDFTEST::posInTable( char* label )
{
if( memcmp(label, codetable, codelen)<=0 )
return 0;
else if( memcmp(label, codetable+(classNum-1)*codelen, codelen)>0 )
return classNum;
int b1, b2, t;
b1 = 0;
b2 = classNum-1;
while( b2-b1>1 )
{
t = (b1+b2)/2;
if( memcmp(label, codetable+t*codelen, codelen)>0 )
b1 = t;
else
b2 = t;
}
return b2;
}
// Feature transformation to PCA, whitening or Fisher subspace
void MQDFTEST::featureTrans( unsigned char* ftr, int dim, float* input )
{
float *shx;
shx = new float [dim];
powerTrans( ftr, dim, power, shx );
int i;
for( i=0; i<dim; i++ )
shx[i] -= gmean[i]; // shift with respect to gross mean
int j;
float proj, euclid;
if( residual )
{
euclid = 0;
for( i=0; i<dim; i++ )
euclid += shx[i]*shx[i];
}
for( j=0; j<redDim; j++ )
{
proj = innerProd( shx, trbasis+j*dim, dim );
if( residual )
euclid -= proj*proj;
input[j] = proj*dscale1 ;
}
if( residual )
input[redDim] = euclid*dscale1*dscale1 ;
delete []shx;
}
float MQDFTEST::innerProd( float* v1, float* v2, int dim )
{
float sum = 0;
for( int i=0; i<dim; i++ )
sum += v1[i]*v2[i];
return sum;
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
void MQDFTEST::testClassifier( unsigned char* data, int sampNum, int ftrDim, char* labels)
{
unsigned char *ftr = new unsigned char[ftrDim];
float eudist[rankN1];
float* input = new float [redDim];
short index[RankNum] ;
short preIdx[rankN1] ;
float output[RankNum];
int topCorrect = 0 ,rankcorrect = 0 ;
for(int n = 0; n < sampNum; n++)
{
int cls = posInTable( labels+n*codelen );
featureTrans( data+n*ftrDim, ftrDim, input );
if(cls < 0) continue ;
//cout<<"cls = "<<cls<<endl;
nearSearch(input, redDim, eudist, preIdx, rankN1);
MQDF( input, redDim, eudist, preIdx, rankN1, output, index, RankNum );
if(index[0] == cls)topCorrect++;
for(int j = 0 ; j < RankNum ; j++)
{
if(index[j] == cls)
{
rankcorrect++;
break;
}
}
if(n%30000==0&&n!=0)
{
printf( "top correct: %6.2f, rank %d correct %6.2f\n", 100.*topCorrect/(n+1), RankNum, 100.*rankcorrect/(n+1) );
}
}
//featureTrans( data, ftrDim, input );
cout<<"sampNum = "<<sampNum<<endl;
cout<<"redDim = "<<redDim<<endl;
}
void MQDFTEST::MQDF( float* ftr, int dim, float* eudist, short* preIdx, int rank1, float* qdmin, short* index, int rankNum )
{
int k;
for( k=0; k<rankNum; k++ )
qdmin[k] = (float)1E12+k;
float euclid;
float* shx;
shx = new float [dim];
int cls, i, m;
float proj;
float qdist, tdist;
int pos, kt;
for( int ri=0; ri<rankN1; ri++ )
{
if( preIdx )
cls = preIdx[ri];
else
cls = ri;
for( i=0; i<dim; i++ )
shx[i] = (float)ftr[i]-means[cls*dim+i];
if( preIdx )
euclid = eudist[ri];
else
{
euclid = 0;
for( i=0; i<dim; i++ )
euclid += shx[i]*shx[i];
}
qdist = loglambda[cls];
kt = knum[cls]; // truncated knum
if( kt==dim )
kt -= 1;
for( m=0; m<kt; m++ )
{
proj = innerProd( shx, phi[cls]+m*dim, dim );
euclid -= proj*proj;
qdist += proj*proj/lambda[cls][m];
tdist = qdist+euclid/lambda[cls][m+1]; // increasing sequence
if( tdist>=qdmin[rankNum-1] )
break;
}
qdist = tdist;
if( qdist<qdmin[rankNum-1] )
{
pos = posAscd( qdist, qdmin, rankNum );
for( k=rankNum-1; k>pos; k-- )
{
qdmin[k] = qdmin[k-1];
index[k] = index[k-1];
}
qdmin[pos] = qdist;
index[pos] = cls;
}
}
delete shx;
}
void MQDFTEST::nearSearch( float* input, int dim, float* dmin, short* index, int rankNum )
{
int ri;
for( ri=0; ri<rankNum; ri++ )
dmin[ri] = (float)1E12+ri;
float dist, diff;
int ci, i;
int pos;
for( ci=0; ci<classNum; ci++ )
{
dist = 0;
for( i=0; i<dim; i++ )
{
diff = (float)input[i]-means[ci*dim+i];
//float T = means[ci*dim+i] ;
//float S = (REAL)input[i] ;
//printf("%3.8f , %3.8f\n",T,S);
dist += diff*diff; // square Euclidean distance
if( dist>=dmin[rankNum-1] )
break;
}
if( dist<dmin[rankNum-1] )
{
pos = posAscd( dist, dmin, rankNum );
for( ri=rankNum-1; ri>pos; ri-- )
{
dmin[ri] = dmin[ri-1];
index[ri] = index[ri-1];
}
dmin[pos] = dist;
index[pos] = ci;
}
}
}
// Rank position in an ordered array, by bisection search
int MQDFTEST::posAscd( float dist, float* dmin, int candiNum )
{
if( dist<dmin[0] || candiNum<=1 )
return 0;
int b1, b2, pos;
b1 = 0;
b2 = candiNum-1;
while( b2-b1>1 ) // bi-section search
{
pos = (b1+b2)/2;
if( dist<dmin[pos] )
b2 = pos;
else
b1 = pos;
}
return b2;
}
|
6bef4e9171dd7856264f0e02d75bcb4a600f8144 | ca157b2182ba62f0ff5e985ec4861743b72c8b6c | /sunhacks_helmet_code1.ino | 44e688d1772dd01365aad1d6e96c7c9fd2249f86 | [] | no_license | modestjuarez/Sunhacks_2019_Project1_Modest-Sam | b6652f6d53de64599f6a28ebf96f42e6bd896caf | 5c5c28fd6faf3d06b7f85b742ed41c75be0d3fa3 | refs/heads/master | 2020-07-30T08:29:15.981354 | 2019-09-22T14:49:24 | 2019-09-22T14:49:24 | 210,155,507 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,396 | ino | sunhacks_helmet_code1.ino | // Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain
// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor
#include "DHT.h"
#define DHTPIN1 2 // Digital pin connected to the DHT sensor
#define DHTPIN2 7
// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
// Pin 15 can work but DHT must be disconnected during program upload.
// Uncomment whatever type you're using!
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht1(DHTPIN1, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println(F("DHTxx test!"));
dht1.begin();
dht2.begin();
//fan pinout
pinMode(3,OUTPUT);
pinMode(5, OUTPUT);
//pin for led
pinMode(13, OUTPUT);
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h1 = dht1.readHumidity();
// Read temperature as Celsius (the default)
float t1 = dht1.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f1 = dht1.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h1) || isnan(t1) || isnan(f1)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht1.computeHeatIndex(f1, h1);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht1.computeHeatIndex(t1, h1, false);
Serial.print(F("Humidity @ Bottom (Pin2): "));
Serial.print(h1);
Serial.print(F("% Temperature @ Bottom (Pin2): "));
//Serial.print(t);
//Serial.print(F("°C "));
Serial.print(f1);
Serial.print(F("°F Heat index @ Bottom (Pin2): "));
// Serial.print(hic);
//Serial.print(F("°C "));
Serial.print(hif);
Serial.println(F("°F"));
//sensor 2 at top
float h2 = dht2.readHumidity();
// Read temperature as Celsius (the default)
float t2 = dht2.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f2 = dht2.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h2) || isnan(t2) || isnan(f2)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Compute heat index in Fahrenheit (the default)
float hif2 = dht2.computeHeatIndex(f2, h2);
// Compute heat index in Celsius (isFahreheit = false)
float hic2 = dht2.computeHeatIndex(t2, h2, false);
//double variable to calculate average temp
double averageTemp = ((f1+f2)/2);
Serial.print(F("Humidity @ Top (Pin7): "));
Serial.print(h2);
Serial.print(F("% Temperature @ Top (Pin7): "));
//Serial.print(t);
//Serial.print(F("°C "));
Serial.print(f2);
Serial.print(F("°F Heat index @ Top (Pin7): "));
// Serial.print(hic);
//Serial.print(F("°C "));
Serial.print(hif);
Serial.println(F("°F"));
Serial.print("Average Temp: ");
Serial.println(averageTemp);
Serial.println();
//code for fans
if(averageTemp > 75){
digitalWrite(3,HIGH);//turn on fan
delay(2000);//at 100%
digitalWrite(5,HIGH);//turn on fan
delay(2000);//at 100%
//led on
digitalWrite(13, HIGH);
delay(1000);
//digitalWrite(13, LOW);
//delay(1000);
}
else if(averageTemp < 75){
digitalWrite(3,LOW);//turn on fan
//delay(2000);//at 100%
digitalWrite(5,LOW);
digitalWrite(13, LOW);
delay(1000);
}
}
|
91285daf58e03b4bc6e67da1695869162e47d6c8 | 26608b730b55327a8c543bdd207a39f1f7def751 | /include/Engine/array.hpp | a54c4291a03fde1ca68ab2c5a7813ba159043819 | [] | no_license | jramirezcr/eMix3d | bdcc40d095b6f7fcec92671c3d404d61957fcab5 | 79571c0a1675482af7817aaa1951cbc29f3f1b9d | refs/heads/master | 2023-07-16T16:30:03.239008 | 2021-08-24T03:24:19 | 2021-08-24T03:24:19 | 399,313,422 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,888 | hpp | array.hpp | /*
Writen by Jorge Ramirez Cruz
jramirezcr@iingen.unam.mx
jramirezcr@gmail.com
Instituto de Ingenieria, UNAM
*/
#ifndef __ARRAY_H
#define __ARRAY_H
#include<iostream>
#include<cstdlib>
//TODO: resizing method
//TODO:
template<int N_rank>
struct selector{
enum{ value = N_rank};
};
template <typename Tprec, int N_rank>
class Array
{
private:
Tprec* data;
int dim[N_rank];
void store();
public:
//Constructors
Array()
:data(0)
{}
Array(int lenght1)
{
dim[0] = lenght1;
if(1 != N_rank){std::cout<< "ARRAY WRONG Rank\n";exit(0);}
store();
}
Array(int lenght1, int lenght2)
{
dim[0] = lenght1;
dim[1] = lenght2;
if(2 != N_rank){std::cout<< "ARRAY WRONG Rank\n";exit(0);}
store();
}
Array(int lenght1, int lenght2, int lenght3)
{
dim[0] = lenght1;
dim[1] = lenght2;
dim[2] = lenght3;
if(3 != N_rank){std::cout<< "ARRAY WRONG Rank\n";exit(0);}
store();
}
void resize(int lenght1)
{
dim[0] = lenght1;
if(1 != N_rank){std::cout<< "ARRAY WRONG Rank\n";exit(0);}
store();
}
void resize(int lenght1, int lenght2)
{
dim[0] = lenght1;
dim[1] = lenght2;
if(2 != N_rank){std::cout<< "ARRAY WRONG Rank\n";exit(0);}
store();
}
void resize(int lenght1, int lenght2, int lenght3)
{
dim[0] = lenght1;
dim[1] = lenght2;
dim[2] = lenght3;
if(3 != N_rank){std::cout<< "ARRAY WRONG Rank\n";exit(0);}
store();
}
Array(const Array<Tprec,1>& other){
dim[0] = other.dim[0];
store();
for(int i = 0; i < dim[0]; i++){
data[i] = other.data[i];
}
}
Array(const Array<Tprec,2>& other){
dim[0] = other.dim[0];
dim[1] = other.dim[1];
store();
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
data[dim[0]*j + i] = other.data[dim[0]*j + i];
}
}
}
Array(const Array<Tprec,3>& other){
dim[0] = other.dim[0];
dim[1] = other.dim[1];
dim[2] = other.dim[2];
store();
for(int k = 0; k < dim[2]; k++){
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
data[dim[0]*dim[1]*k + dim[0]*j + i] =
other.data[dim[0]*dim[1]*k + dim[0]*j + i];
}
}
}
}
~Array(){delete[] data;}
// Acces element data overloading
Tprec& operator()(int i,
selector<N_rank> dimType = selector<1>()){
return data[i];
}
Tprec& operator()(int i, int j,
selector<N_rank> dimType = selector<2>()){
return data[dim[0]*j + i];
}
Tprec& operator()(int i, int j, int k,
selector<N_rank> dimType = selector<3>()){
return data[dim[1]*dim[0]*k + dim[0]*j + i];
}
Array<Tprec, N_rank>& operator=(const Array<Tprec, 1>& other){
if(this != &other) {
for(int i = 0; i < dim[0]; i++){
data[i] = other.data[i];
}
}
return *this;
}
Array<Tprec, N_rank>& operator=(const Array<Tprec, 2>& other){
if(this != &other) {
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
data[dim[0]*j + i] = other.data[dim[0]*j + i];
}
}
}
return *this;
}
Array<Tprec, N_rank>& operator=(const Array<Tprec, 3>& other){
if(this != &other) {
for(int k = 0; k < dim[2]; k++){
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
data[dim[0]*dim[1]*k + dim[0]*j + i] =
other.data[dim[0]*dim[1]*k + dim[0]*j + i];
}
}
}
}
return *this;
}
void constantAsignation(Tprec value, selector<1>){
for(int i = 0; i < dim[0]; i++){
data[i] = value;
}
}
void constantAsignation(Tprec value, selector<2>){
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
data[dim[0]*j + i] = value;
}
}
}
void constantAsignation(Tprec value, selector<3>){
for(int k = 0; k < dim[2]; k++){
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
data[dim[0]*dim[1]*k + dim[0]*j + i] = value;
}
}
}
}
Array<Tprec, N_rank>& operator=(Tprec value){
constantAsignation(value, selector<N_rank>());
return *this;
}
//-----------------------------------------------------------------
Array<Tprec, N_rank> operator*(const Array<Tprec, 1>& other){
Array<Tprec, N_rank> result(other.dim[0]);
for(int i = 0; i < dim[0]; i++){
result.data[i] = data[i]*other.data[i];
}
return result;
}
Array<Tprec, N_rank> operator*(const Array<Tprec, 2>& other){
Array<Tprec, N_rank> result(dim[0], dim[1]);
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*j + i] =
data[dim[0]*j + i]*other.data[dim[0]*j + i];
}
}
return result;
}
Array<Tprec, N_rank> operator*(const Array<Tprec, 3>& other){
Array<Tprec, N_rank> result(dim[0], dim[1], dim[2]);
for(int k = 0; k < dim[2]; k++){
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*dim[1]*k + dim[0]*j + i] =
data[dim[0]*dim[1]*k + dim[0]*j + i]*
other.data[dim[0]*dim[1]*k + dim[0]*j + i];
}
}
}
return result;
}
Array<Tprec, N_rank> operator*(const Tprec value);
Array<Tprec, N_rank> operator/(const Tprec value);
Array<Tprec, N_rank> operator+(const Tprec value);
Array<Tprec, N_rank> operator-(const Tprec value);
//Sublayer multiply overloading
Array<Tprec, N_rank> constantMul(const Tprec value, selector<1>);
Array<Tprec, N_rank> constantMul(const Tprec value, selector<2>);
Array<Tprec, N_rank> constantMul(const Tprec value, selector<3>);
//Sublayer divisor overloading
Array<Tprec, N_rank> constantDiv(const Tprec value, selector<1>);
Array<Tprec, N_rank> constantDiv(const Tprec value, selector<2>);
Array<Tprec, N_rank> constantDiv(const Tprec value, selector<3>);
//Sublayer Plus overloading
Array<Tprec, N_rank> constantAdd(const Tprec value, selector<1>);
Array<Tprec, N_rank> constantAdd(const Tprec value, selector<2>);
Array<Tprec, N_rank> constantAdd(const Tprec value, selector<3>);
//Sublayer Plus overloading
Array<Tprec, N_rank> constantSub(const Tprec value, selector<1>);
Array<Tprec, N_rank> constantSub(const Tprec value, selector<2>);
Array<Tprec, N_rank> constantSub(const Tprec value, selector<3>);
//----------------------------------------------------------------
//-----------------------------------------------------------------
Array<Tprec, N_rank> operator/(const Array<Tprec, 1>& other){
Array<Tprec, N_rank> result(other.dim[0]);
for(int i = 0; i < dim[0]; i++){
result.data[i] = data[i]/other.data[i];
}
return result;
}
Array<Tprec, N_rank> operator/(const Array<Tprec, 2>& other){
Array<Tprec, N_rank> result(dim[0], dim[1]);
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*j + i] =
data[dim[0]*j + i]/other.data[dim[0]*j + i];
}
}
return result;
}
Array<Tprec, N_rank> operator/(const Array<Tprec, 3>& other){
Array<Tprec, N_rank> result(dim[0], dim[1], dim[2]);
for(int k = 0; k < dim[2]; k++){
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*dim[1]*k + dim[0]*j + i] =
data[dim[0]*dim[1]*k + dim[0]*j + i]/
other.data[dim[0]*dim[1]*k + dim[0]*j + i];
}
}
}
return result;
}
//----------------------------------------------------------------
//-----------------------------------------------------------------
Array<Tprec, N_rank> operator-(const Array<Tprec, 1>& other){
Array<Tprec, N_rank> result(other.dim[0]);
for(int i = 0; i < dim[0]; i++){
result.data[i] = data[i]-other.data[i];
}
return result;
}
Array<Tprec, N_rank> operator-(const Array<Tprec, 2>& other){
Array<Tprec, N_rank> result(dim[0], dim[1]);
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*j + i] =
data[dim[0]*j + i]-other.data[dim[0]*j + i];
}
}
return result;
}
Array<Tprec, N_rank> operator-(const Array<Tprec, 3>& other){
Array<Tprec, N_rank> result(dim[0], dim[1], dim[2]);
for(int k = 0; k < dim[2]; k++){
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*dim[1]*k + dim[0]*j + i] =
data[dim[0]*dim[1]*k + dim[0]*j + i]-
other.data[dim[0]*dim[1]*k + dim[0]*j + i];
}
}
}
return result;
}
//----------------------------------------------------------------
//-----------------------------------------------------------------
Array<Tprec, N_rank> operator+(const Array<Tprec, 1>& other){
Array<Tprec, N_rank> result(other.dim[0]);
for(int i = 0; i < dim[0]; i++){
result.data[i] = data[i]+other.data[i];
}
return result;
}
Array<Tprec, N_rank> operator+(const Array<Tprec, 2>& other){
Array<Tprec, N_rank> result(dim[0], dim[1]);
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*j + i] =
data[dim[0]*j + i]+other.data[dim[0]*j + i];
}
}
return result;
}
Array<Tprec, N_rank> operator+(const Array<Tprec, 3>& other){
Array<Tprec, N_rank> result(dim[0], dim[1], dim[2]);
for(int k = 0; k < dim[2]; k++){
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*dim[1]*k + dim[0]*j + i] =
data[dim[0]*dim[1]*k + dim[0]*j + i]+
other.data[dim[0]*dim[1]*k + dim[0]*j + i];
}
}
}
return result;
}
int getDim(int _dim){
//TODO: check dim for each dim type
return dim[_dim - 1];
}
};
template <typename Tprec, int N_rank>
void Array<Tprec,N_rank>::store()
{
int offset = 1;
for(int i = 0; i < N_rank; i++){
offset *= dim[i];
}
data = new Tprec[offset];
}
//---------------------------------------------------------------
// Overloading type A*value
//--------------------------------------------------------------
template <typename Tprec, int N_rank>
Array<Tprec, N_rank> Array<Tprec, N_rank>::operator*(const Tprec value)
{
return constantMul(value, selector<N_rank>());
}
template <typename Tprec, int N_rank> Array<Tprec, N_rank>
Array<Tprec, N_rank>::constantMul(const Tprec value, selector<1>){
Array<Tprec, N_rank> result(dim[0]);
for(int i = 0; i < dim[0]; i++){
result.data[i] = data[i]*value;
}
return result;
}
template <typename Tprec, int N_rank> Array<Tprec, N_rank>
Array<Tprec, N_rank>::constantMul(const Tprec value, selector<2>){
Array<Tprec, N_rank> result(dim[0], dim[1]);
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*j + i] =
data[dim[0]*j + i]*value;
}
}
return result;
}
template <typename Tprec, int N_rank> Array<Tprec, N_rank>
Array<Tprec, N_rank>::constantMul(const Tprec value, selector<3>){
Array<Tprec, N_rank> result(dim[0], dim[1], dim[2]);
for(int k = 0; k < dim[2]; k++){
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*dim[1]*k + dim[0]*j + i] =
data[dim[0]*dim[1]*k + dim[0]*j + i]*value;
}
}
}
return result;
}
//---------------------------------------------------------------
// Overloading type A/value
//--------------------------------------------------------------
template <typename Tprec, int N_rank>
Array<Tprec, N_rank> Array<Tprec, N_rank>::operator/(const Tprec value)
{
return constantDiv(value, selector<N_rank>());
}
template <typename Tprec, int N_rank> Array<Tprec, N_rank>
Array<Tprec, N_rank>::constantDiv(const Tprec value, selector<1>){
Array<Tprec, N_rank> result(dim[0]);
for(int i = 0; i < dim[0]; i++){
result.data[i] = data[i]/value;
}
return result;
}
template <typename Tprec, int N_rank> Array<Tprec, N_rank>
Array<Tprec, N_rank>::constantDiv(const Tprec value, selector<2>){
Array<Tprec, N_rank> result(dim[0], dim[1]);
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*j + i] =
data[dim[0]*j + i]/value;
}
}
return result;
}
template <typename Tprec, int N_rank> Array<Tprec, N_rank>
Array<Tprec, N_rank>::constantDiv(const Tprec value, selector<3>){
Array<Tprec, N_rank> result(dim[0], dim[1], dim[2]);
for(int k = 0; k < dim[2]; k++){
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*dim[1]*k + dim[0]*j + i] =
data[dim[0]*dim[1]*k + dim[0]*j + i]/value;
}
}
}
return result;
}
//---------------------------------------------------------------
// Overloading type A + value
//--------------------------------------------------------------
template <typename Tprec, int N_rank>
Array<Tprec, N_rank> Array<Tprec, N_rank>::operator+(const Tprec value)
{
return constantAdd(value, selector<N_rank>());
}
template <typename Tprec, int N_rank> Array<Tprec, N_rank>
Array<Tprec, N_rank>::constantAdd(const Tprec value, selector<1>){
Array<Tprec, N_rank> result(dim[0]);
for(int i = 0; i < dim[0]; i++){
result.data[i] = data[i]+value;
}
return result;
}
template <typename Tprec, int N_rank> Array<Tprec, N_rank>
Array<Tprec, N_rank>::constantAdd(const Tprec value, selector<2>){
Array<Tprec, N_rank> result(dim[0], dim[1]);
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*j + i] =
data[dim[0]*j + i]+value;
}
}
return result;
}
template <typename Tprec, int N_rank> Array<Tprec, N_rank>
Array<Tprec, N_rank>::constantAdd(const Tprec value, selector<3>){
Array<Tprec, N_rank> result(dim[0], dim[1], dim[2]);
for(int k = 0; k < dim[2]; k++){
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*dim[1]*k + dim[0]*j + i] =
data[dim[0]*dim[1]*k + dim[0]*j + i]+value;
}
}
}
return result;
}
//---------------------------------------------------------------
// Overloading type A - value
//--------------------------------------------------------------
template <typename Tprec, int N_rank>
Array<Tprec, N_rank> Array<Tprec, N_rank>::operator-(const Tprec value)
{
return constantSub(value, selector<N_rank>());
}
template <typename Tprec, int N_rank> Array<Tprec, N_rank>
Array<Tprec, N_rank>::constantSub(const Tprec value, selector<1>){
Array<Tprec, N_rank> result(dim[0]);
for(int i = 0; i < dim[0]; i++){
result.data[i] = data[i] - value;
}
return result;
}
template <typename Tprec, int N_rank> Array<Tprec, N_rank>
Array<Tprec, N_rank>::constantSub(const Tprec value, selector<2>){
Array<Tprec, N_rank> result(dim[0], dim[1]);
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*j + i] =
data[dim[0]*j + i] - value;
}
}
return result;
}
template <typename Tprec, int N_rank> Array<Tprec, N_rank>
Array<Tprec, N_rank>::constantSub(const Tprec value, selector<3>){
Array<Tprec, N_rank> result(dim[0], dim[1], dim[2]);
for(int k = 0; k < dim[2]; k++){
for(int j = 0; j < dim[1]; j++){
for(int i = 0; i < dim[0]; i++){
result.data[dim[0]*dim[1]*k + dim[0]*j + i] =
data[dim[0]*dim[1]*k + dim[0]*j + i] - value;
}
}
}
return result;
}
#endif
|
0d900c64335f4fb2c44d46fd1356157c1f7b26e8 | b326a0e61caebdff46b2e70781e35737142b0d0f | /include/NoduleSegmenationSupport/myImage.cpp | 4e25749ae442bce4e15923ab9536bfa7f0f550c5 | [] | no_license | toshirokubota/VentricleSegmentation | ef28dc8c4de9aecc8666c22ef9d7e0d2180b3f5f | b6aa9e7549975523b52c087e0f3dc5a6da5ab04e | refs/heads/master | 2021-01-20T07:54:28.849123 | 2017-07-09T23:23:10 | 2017-07-09T23:23:10 | 90,064,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,282 | cpp | myImage.cpp | #if !defined _myImage_cpp_
#define _myImage_cpp_
//#include "Stdafx.h"
//#include "Image.h"
//#include "mytype.h"
//#include <stdio.h>
template <class Item>
void myImage<Item>:: ResizeImage(int bands, int rows, int cols) {
if(pItem)
_resetItemPointers();
_setItemPointers(bands, rows, cols);
Bands = bands;
Rows = rows;
Cols = cols;
}
template <class Item>
void myImage<Item>:: _setItemPointers(int bands, int rows, int cols) {
pItem = new Item[bands*rows*cols];
assert(pItem);
pppItem = new ptr2D_Data[bands];
assert(pppItem);
int i;
for(i=0; i<bands; ++i) {
pppItem[i] = new ptr1D_Data [rows];
assert(pppItem[i]);
}
Item* ptr = &(pItem[0]);
for(i=0; i<bands; ++i) {
for(int j=0; j<rows; ++j) {
pppItem[i][j] = ptr;
ptr += cols;
}
}
#ifdef DEBUG_Image
cerr << "_setItemPointers: " << pItem << "," << pppItem << endl;
#endif
}
template <class Item>
void myImage<Item>:: _resetItemPointers() {
#ifdef DEBUG_Image
cerr << "_resetItemPointers: " << pItem << "," << pppItem << endl;
#endif
for(int i=0; i<Bands; ++i)
delete [] pppItem[i];
delete [] pppItem;
delete [] pItem;
}
//
// Default Constructor
//
template <class Item>
myImage<Item>:: myImage()
: pItem(0)
{
#ifdef DEBUG_Image
cout << "constructing an image..." << endl;
#endif
ResizeImage(1, 1, 1);
}
//
// this is kind of redundant. I wanted to make this as a
// default constructor, but I get weird compiling errors
// regarding >> and << operators...
//
template <class Item>
myImage<Item>:: myImage(int bands, int rows, int cols)
: pItem(0)
{
#ifdef DEBUG_Image
cout << "constructing an image..." << endl;
#endif
ResizeImage(bands, rows, cols);
}
//
// Constructor
//
template <class Item>
myImage<Item>:: myImage(int bands, int rows, int cols,
const Item& pixel)
: pItem(0)
{
#ifdef DEBUG_Image
cout << "constructing an image (" << rows << "x" << cols;
cout << ") with initial pixel value=" << pixel << endl;
#endif
ResizeImage(bands, rows, cols);
for(int i=0; i < Bands*Rows*Cols; ++i){
pItem[i] = pixel;
}
}
template <class Item>
myImage<Item>:: myImage(const myImage<Item>& image)
: pItem(0)
{
ResizeImage(image.NumBands(), image.NumRows(), image.NumCols());
memcpy(pItem,image.GetDataPointer(),sizeof(Item)*Bands*Rows*Cols);
/*for(int i=0; i < Bands*Rows*Cols; ++i){
pItem[i] = image.GetPixel(i);
}*/
}
//
// A Desctructor:
//
template <class Item>
myImage<Item>:: ~myImage()
{
#ifdef DEBUG_Image
cout << "destroying an image..." << endl;
#endif
_resetItemPointers();
}
//
// Assignment:
//
template <class Item>
const myImage<Item>& myImage<Item>:: operator =(const myImage<Item>& image)
{
if(&image != this) {
if(Cols != image.NumCols() || Rows != image.NumRows() ||
Bands != image.NumBands()) {
ResizeImage(image.NumBands(), image.NumRows(), image.NumCols());
}
memcpy(pItem,image.GetDataPointer(),sizeof(Item)*Bands*Rows*Cols);
/*for(int i=0; i < Bands*Cols*Rows; ++i)
pItem[i] = image.GetPixel(i);*/
}
return *this;
}
//
// Getting a pixel value and Setting a pixel value
//
/*
this routine implement GetPixel function with boundary extention.
Pixels outside boundaries are computed using pixel folding
*/
template <class Item>
Item
myImage<Item>:: GetPixelFold(int band_index, int row_index, int col_index) const
{
assert(Rows > 1 && Cols > 1); // the routie can fail in this condition...
row_index = (row_index<0) ? -row_index: \
((row_index>=Rows)? 2*Rows-row_index-2 : row_index);
col_index = (col_index<0) ? -col_index: \
((col_index>=Cols)? 2*Cols-col_index-2 : col_index);
return(pppItem[band_index][row_index][col_index]);
}
/*
this routine implement GetPixel function with boundary extention.
Pixels outside boundaries are computed using image wrapping
*/
template <class Item>
Item
myImage<Item>:: GetPixelWrap(int band_index, int row_index, int col_index) const
{
while(row_index < 0) {
row_index += Rows;
}
while(row_index >= Rows){
row_index -= Rows;
}
while(col_index < 0) {
col_index += Cols;
}
while(col_index >= Cols){
col_index -= Cols;
}
return(pppItem[band_index][row_index][col_index]);
}
/*
this routine implement GetPixel function with boundary extention.
Pixels outside boundaries are computed using pixel repeatition.
*/
template <class Item>
Item
myImage<Item>::GetPixelRepeat(int band_index, int row_index, int col_index)const
{
row_index = (row_index<0) ? 0: \
((row_index>=Rows)? Rows-1: row_index);
col_index = (col_index<0) ? 0: \
((col_index>=Cols)? Cols-1: col_index);
return(pppItem[band_index][row_index][col_index]);
}
/*
this routine implement GetPixel function with boundary extention.
Pixels outside boundaries are set to Zero.
Note: this may not work on some classes of Item such as Complex.
*/
template <class Item>
Item
myImage<Item>::GetPixelZero(int band_index, int row_index, int col_index)const
{
if(band_index>=0 && band_index < Bands &&\
row_index>=0 && row_index<Rows && \
col_index>=0 && col_index<Cols)
return(pppItem[band_index][row_index][col_index]);
else {
return 0;
}
}
/*
this routine implement GetPixel function with boundary extention.
Pixels outside boundaries are set so that the value is linearly
extrapolated.
Note: this may not work on some classes of Item such as Complex.
*/
template <class Item>
Item
myImage<Item>::GetPixelExtrap(int band_index, int row_index, int col_index)const
{
assert(band_index>=0 && band_index<Bands);
if(row_index>=0 && row_index<Rows && col_index>=0 && col_index<Cols)
return(pppItem[band_index][row_index][col_index]);
else {
int erow,brow,ecol,bcol;
if(row_index<0) {
erow=-row_index;
brow=0;
}
else if(row_index>=Rows) {
erow=2*Rows-row_index-2;
brow=row_index-1;
}
else {
erow=row_index;
brow=row_index;
}
if(col_index<0) {
ecol=-col_index;
bcol=0;
}
else if(col_index>=Cols) {
ecol=2*Cols-col_index-2;
bcol=col_index-1;
}
else {
ecol=col_index;
bcol=col_index;
}
real eval=pppItem[band_index][erow][ecol];
real bval=pppItem[band_index][brow][bcol];
return bval+(bval-eval);
}
}
/*
this routine implement GetPixel function with boundary extention.
Pixels outside boundaries are set to the given default value.
*/
template <class Item>
Item
myImage<Item>::GetPixelDefault(int band_index, int row_index,
int col_index, const Item& item)const
{
if(band_index>=0 && band_index < Bands &&\
row_index>=0 && row_index<Rows && \
col_index>=0 && col_index<Cols)
return(pppItem[band_index][row_index][col_index]);
else {
return item;
}
}
//
// Arithmetic operators for Images.
//
template <class Item>
myImage<Item>
myImage<Item>:: operator+(const myImage<Item>& image) const {
assert(Rows==image.NumRows()&&Cols==image.NumCols());
assert(Bands==image.NumBands() || Bands==1 || image.NumBands()==1);
myImage<Item> result;
if(Bands==image.NumBands()) {
result = image;
for(int m=0; m<Bands*Rows*Cols; ++m) {
result.SetPixel(m, pItem[m]+image.GetPixel(m));
}
}
else if(Bands==1) {
result = image;
for(int k=0, m=0; k<image.NumBands(); ++k) {
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m) {
result.SetPixel(m, pppItem[0][i][j]+image.GetPixel(m));
}
}
}
}
else if (image.NumBands()==1) {
result = *this;
for(int k=0, m=0; k<Bands; ++k) {
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m) {
result.SetPixel(m, GetPixel(m)+image.GetPixel(0,i,j));
}
}
}
}
return result;
}
template <class Item>
void
myImage<Item>:: operator+=(const myImage<Item>& image) {
assert(Rows==image.NumRows()&&Cols==image.NumCols());
assert(Bands==image.NumBands() || Bands==1 || image.NumBands()==1);
if(Bands == image.NumBands()) {
for(int m=0; m<Bands*Rows*Cols; ++m)
pItem[m] += image.GetPixel(m);
}
else if(Bands == 1) {
Item* oldPixel = new Item[Rows*Cols];
for(int i=0; i<Rows*Cols; ++i)
oldPixel[i] = pItem[i];
ResizeImage(image.NumBands(), Rows, Cols);
for(int k=0, m=0; k<image.NumBands(); ++k) {
int n=0;
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j,++n, ++m) {
pItem[m] = oldPixel[n]+image.GetPixel(m);
}
}
}
}
else if (image.NumBands()==1) {
int m=0;
for(int k=0; k<Bands; ++k) {
int n=0;
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m, ++n) {
pItem[m] += image.GetPixel(n);
}
}
}
}
}
//
// Arithmetic operators for Images.
//
template <class Item>
myImage<Item>
myImage<Item>:: operator-(const myImage<Item>& image) const {
assert(Rows==image.NumRows()&&Cols==image.NumCols());
assert(Bands==image.NumBands() || Bands==1 || image.NumBands()==1);
myImage<Item> result;
if(Bands==image.NumBands()) {
result = image;
for(int m=0; m<Bands*Rows*Cols; ++m) {
result.SetPixel(m, pItem[m]-image.GetPixel(m));
}
}
else if(Bands==1) {
result = image;
for(int k=0, m=0; k<image.NumBands(); ++k) {
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m) {
result.SetPixel(m, pppItem[0][i][j]-image.GetPixel(m));
}
}
}
}
else if (image.NumBands()==1) {
result = *this;
for(int k=0, m=0; k<Bands; ++k) {
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m) {
result.SetPixel(m, GetPixel(m)-image.GetPixel(0,i,j));
}
}
}
}
return result;
}
template <class Item>
void
myImage<Item>:: operator-=(const myImage<Item>& image) {
assert(Rows==image.NumRows()&&Cols==image.NumCols());
assert(Bands==image.NumBands() || Bands==1 || image.NumBands()==1);
if(Bands == image.NumBands()) {
for(int m=0; m<Bands*Rows*Cols; ++m)
pItem[m] -= image.GetPixel(m);
}
else if(Bands == 1) {
Item* oldPixel = new Item[Rows*Cols];
for(int i=0; i<Rows*Cols; ++i)
oldPixel[i] = pItem[i];
ResizeImage(image.NumBands(), Rows, Cols);
for(int k=0, m=0; k<image.NumBands(); ++k) {
int n=0;
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j,++n, ++m) {
pItem[m] = oldPixel[n]-image.GetPixel(m);
}
}
}
}
else if (image.NumBands()==1) {
int m=0;
for(int k=0; k<Bands; ++k) {
int n=0;
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m, ++n) {
pItem[m] -= image.GetPixel(n);
}
}
}
}
}
//
// Arithmetic operators for Images.
//
template <class Item>
myImage<Item>
myImage<Item>:: operator*(const myImage<Item>& image) const {
assert(Rows==image.NumRows()&&Cols==image.NumCols());
assert(Bands==image.NumBands() || Bands==1 || image.NumBands()==1);
myImage<Item> result;
if(Bands==image.NumBands()) {
result = image;
for(int m=0; m<Bands*Rows*Cols; ++m) {
result.SetPixel(m, pItem[m]*image.GetPixel(m));
}
}
else if(Bands==1) {
result = image;
for(int k=0, m=0; k<image.NumBands(); ++k) {
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m) {
result.SetPixel(m, pppItem[0][i][j]*image.GetPixel(m));
}
}
}
}
else if (image.NumBands()==1) {
result = *this;
for(int k=0, m=0; k<Bands; ++k) {
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m) {
result.SetPixel(m, GetPixel(m)*image.GetPixel(0,i,j));
}
}
}
}
return result;
}
template <class Item>
void
myImage<Item>:: operator*=(const myImage<Item>& image) {
assert(Rows==image.NumRows()&&Cols==image.NumCols());
assert(Bands==image.NumBands() || Bands==1 || image.NumBands()==1);
if(Bands == image.NumBands()) {
for(int m=0; m<Bands*Rows*Cols; ++m)
pItem[m] *= image.GetPixel(m);
}
else if(Bands == 1) {
Item* oldPixel = new Item[Rows*Cols];
for(int i=0; i<Rows*Cols; ++i)
oldPixel[i] = pItem[i];
ResizeImage(image.NumBands(), Rows, Cols);
for(int k=0, m=0; k<image.NumBands(); ++k) {
int n=0;
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j,++n, ++m) {
pItem[m] = oldPixel[n]*image.GetPixel(m);
}
}
}
}
else if (image.NumBands()==1) {
int m=0;
for(int k=0; k<Bands; ++k) {
int n=0;
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m, ++n) {
pItem[m] *= image.GetPixel(n);
}
}
}
}
}
//
// Arithmetic operators for Images.
//
template <class Item>
myImage<Item>
myImage<Item>:: operator/(const myImage<Item>& image) const {
assert(Rows==image.NumRows()&&Cols==image.NumCols());
assert(Bands==image.NumBands() || Bands==1 || image.NumBands()==1);
myImage<Item> result;
if(Bands==image.NumBands()) {
result = image;
for(int m=0; m<Bands*Rows*Cols; ++m) {
result.SetPixel(m, pItem[m]/image.GetPixel(m));
}
}
else if(Bands==1) {
result = image;
for(int k=0, m=0; k<image.NumBands(); ++k) {
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m) {
result.SetPixel(m, pppItem[0][i][j]/image.GetPixel(m));
}
}
}
}
else if (image.NumBands()==1) {
result = *this;
for(int k=0, m=0; k<Bands; ++k) {
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m) {
result.SetPixel(m, GetPixel(m)/image.GetPixel(0,i,j));
}
}
}
}
return result;
}
template <class Item>
void
myImage<Item>:: operator/=(const myImage<Item>& image) {
assert(Rows==image.NumRows()&&Cols==image.NumCols());
assert(Bands==image.NumBands() || Bands==1 || image.NumBands()==1);
if(Bands == image.NumBands()) {
for(int m=0; m<Bands*Rows*Cols; ++m)
pItem[m] /= image.GetPixel(m);
}
else if(Bands == 1) {
Item* oldPixel = new Item[Rows*Cols];
for(int i=0; i<Rows*Cols; ++i)
oldPixel[i] = pItem[i];
ResizeImage(image.NumBands(), Rows, Cols);
for(int k=0, m=0; k<image.NumBands(); ++k) {
int n=0;
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j,++n, ++m) {
pItem[m] = oldPixel[n]/image.GetPixel(m);
}
}
}
}
else if (image.NumBands()==1) {
int m=0;
for(int k=0; k<Bands; ++k) {
int n=0;
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m, ++n) {
pItem[m] /= image.GetPixel(n);
}
}
}
}
}
//
// Logic operators for Images.
//
template <class Item>
myImage<Item>
myImage<Item>:: operator|(const myImage<Item>& image) const {
assert(Rows==image.NumRows()&&Cols==image.NumCols());
assert(Bands==image.NumBands() || Bands==1 || image.NumBands()==1);
myImage<Item> result;
if(Bands==image.NumBands()) {
result = image;
for(int m=0; m<Bands*Rows*Cols; ++m) {
result.SetPixel(m, pItem[m]|image.GetPixel(m));
}
}
else if(Bands==1) {
result = image;
for(int k=0, m=0; k<image.NumBands(); ++k) {
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m) {
result.SetPixel(m, pppItem[0][i][j]|image.GetPixel(m));
}
}
}
}
else if (image.NumBands()==1) {
result = *this;
for(int k=0, m=0; k<Bands; ++k) {
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m) {
result.SetPixel(m, GetPixel(m)|image.GetPixel(0,i,j));
}
}
}
}
return result;
}
template <class Item>
void
myImage<Item>:: operator|=(const myImage<Item>& image) {
assert(Rows==image.NumRows()&&Cols==image.NumCols());
assert(Bands==image.NumBands() || Bands==1 || image.NumBands()==1);
if(Bands == image.NumBands()) {
for(int m=0; m<Bands*Rows*Cols; ++m)
pItem[m] |= image.GetPixel(m);
}
else if(Bands == 1) {
Item* oldPixel = new Item[Rows*Cols];
for(int i=0; i<Rows*Cols; ++i)
oldPixel[i] = pItem[i];
ResizeImage(image.NumBands(), Rows, Cols);
for(int k=0, m=0; k<image.NumBands(); ++k) {
int n=0;
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j,++n, ++m) {
pItem[m] = oldPixel[n]|image.GetPixel(m);
}
}
}
}
else if (image.NumBands()==1) {
int m=0;
for(int k=0; k<Bands; ++k) {
int n=0;
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m, ++n) {
pItem[m] |= image.GetPixel(n);
}
}
}
}
}
template <class Item>
myImage<Item>
myImage<Item>:: operator&(const myImage<Item>& image) const {
assert(Rows==image.NumRows()&&Cols==image.NumCols());
assert(Bands==image.NumBands() || Bands==1 || image.NumBands()==1);
myImage<Item> result;
if(Bands==image.NumBands()) {
result = image;
for(int m=0; m<Bands*Rows*Cols; ++m) {
result.SetPixel(m, pItem[m]&image.GetPixel(m));
}
}
else if(Bands==1) {
result = image;
for(int k=0, m=0; k<image.NumBands(); ++k) {
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m) {
result.SetPixel(m, pppItem[0][i][j]&image.GetPixel(m));
}
}
}
}
else if (image.NumBands()==1) {
result = *this;
for(int k=0, m=0; k<Bands; ++k) {
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m) {
result.SetPixel(m, GetPixel(m)&image.GetPixel(0,i,j));
}
}
}
}
return result;
}
template <class Item>
void
myImage<Item>:: operator&=(const myImage<Item>& image) {
assert(Rows==image.NumRows()&&Cols==image.NumCols());
assert(Bands==image.NumBands() || Bands==1 || image.NumBands()==1);
if(Bands == image.NumBands()) {
for(int m=0; m<Bands*Rows*Cols; ++m)
pItem[m] &= image.GetPixel(m);
}
else if(Bands == 1) {
Item* oldPixel = new Item[Rows*Cols];
for(int i=0; i<Rows*Cols; ++i)
oldPixel[i] = pItem[i];
ResizeImage(image.NumBands(), Rows, Cols);
for(int k=0, m=0; k<image.NumBands(); ++k) {
int n=0;
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j,++n, ++m) {
pItem[m] = oldPixel[n]&image.GetPixel(m);
}
}
}
}
else if (image.NumBands()==1) {
int m=0;
for(int k=0; k<Bands; ++k) {
int n=0;
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j, ++m, ++n) {
pItem[m] &= image.GetPixel(n);
}
}
}
}
}
//
// Scalar arithmetic operators for Images
//
template <class Item>
myImage<Item>
myImage<Item>:: operator+(const Item& value) const {
myImage<Item> result(*this);
for(int i=0; i<Bands*Rows*Cols; ++i)
result.SetPixel(i, pItem[i]+value);
return result;
}
template <class Item>
void
myImage<Item>:: operator+=(const Item& value) {
for(int i=0; i<Bands*Rows*Cols; ++i)
pItem[i] = pItem[i] + value;
}
template <class Item>
myImage<Item>
myImage<Item>:: operator-(const Item& value) const {
myImage<Item> result(*this);
for(int i=0; i<Bands*Rows*Cols; ++i)
result.SetPixel(i, pItem[i]-value);
return result;
}
template <class Item>
void
myImage<Item>:: operator-=(const Item& value) {
for(int i=0; i<Bands*Rows*Cols; ++i)
pItem[i] = pItem[i] - value;
}
template <class Item>
myImage<Item>
myImage<Item>:: operator*(const Item& value) const {
myImage<Item> result(*this);
for(int i=0; i<Bands*Rows*Cols; ++i)
result.SetPixel(i, pItem[i]*value);
return result;
}
template <class Item>
void
myImage<Item>:: operator*=(const Item& value) {
for(int i=0; i<Bands*Rows*Cols; ++i)
pItem[i] = pItem[i] * value;
}
template <class Item>
myImage<Item>
myImage<Item>:: operator^(const Item& value) const {
myImage<Item> result(*this);
for(int i=0; i<Bands*Rows*Cols; ++i)
result.SetPixel(i, value - pItem[i]);
return result;
}
template <class Item>
void
myImage<Item>:: operator^=(const Item& value) {
for(int i=0; i<Bands*Rows*Cols; ++i)
pItem[i] = value - pItem[i];
}
/*
the routine extracts Region of Interest (ROI) from the image.
the parameters specifies the region and they are taken as
inclusive.
*/
template <class Item>
void
myImage<Item>:: extractROI(int low_band, int up_band,
int low_row, int up_row,
int low_col, int up_col) {
//assertion takes care of unexpected conditions
assert(low_band<=up_band && low_row<=up_row && low_col<=up_col);
assert(up_band<Bands && up_row <Rows && up_col < Cols);
assert(low_band>=0 && low_row>= 0 && low_col>=0);
myImage<Item> tmp_im(*this);
ResizeImage(up_band-low_band+1, up_row-low_row+1, up_col-low_col+1);
//copy items with in the ROI
int k, index;
for(k=low_band, index=0; k<=up_band; ++k) {
for(int i=low_row; i<=up_row; ++i) {
for(int j=low_col; j<=up_col; ++j, ++index) {
pItem[index] = tmp_im.GetPixel(k,i,j);
}
}
}
}
template <class Item>
myImage<Item>
myImage<Item>:: ExtractROI(int low_band, int up_band,
int low_row, int up_row,
int low_col, int up_col) const {
//assertion takes care of unexpected conditions
assert(low_band<=up_band && low_row<=up_row && low_col<=up_col);
assert(up_band<Bands && up_row <Rows && up_col < Cols);
assert(low_band>=0 && low_row>= 0 && low_col>=0);
myImage<Item> result = myImage<Item>(up_band-low_band+1, up_row-low_row+1,
up_col-low_col+1);
//copy items with in the ROI
for(int k=low_band, index=0; k<=up_band; ++k) {
for(int i=low_row; i<=up_row; ++i) {
for(int j=low_col; j<=up_col; ++j, ++index) {
result.SetPixel(index, pppItem[k][i][j]);
}
}
}
return result;
}
/*
the routine expand an image with arbitrary offset.
*/
template <class Item>
void
myImage<Item>:: expand(int new_bands, int new_rows, int new_cols,
int band_offset, int row_offset, int col_offset,
Item pad_value) {
//assertion takes care of unexpected conditions
assert(band_offset<new_bands && row_offset<new_rows && col_offset<new_cols);
myImage<Item> temp_im = *this;
*this = myImage<Item>(new_bands, new_rows, new_cols, pad_value);
for(int k=band_offset,k2=0; k2<temp_im.NumBands()&&k<Bands; ++k,++k2) {
for(int i=row_offset,i2=0; i2<temp_im.NumRows()&&i<Rows; ++i,++i2) {
for(int j=col_offset,j2=0; j2<temp_im.NumCols()&&j<Cols; ++j,++j2) {
SetPixel(k,i,j,temp_im.GetPixel(k2,i2,j2));
}
}
}
}
template <class Item>
myImage<Item>
myImage<Item>:: Expand(int new_bands, int new_rows, int new_cols,
int band_offset, int row_offset, int col_offset,
Item pad_value) const {
//assertion takes care of unexpected conditions
assert(band_offset<new_bands && row_offset<new_rows && col_offset<new_cols);
myImage<Item> result(new_bands, new_rows, new_cols, pad_value);
for(int k=band_offset,k2=0; k2<result.NumBands()&&k<Bands; ++k,++k2) {
for(int i=row_offset,i2=0; i2<result.NumRows()&&i<Rows; ++i,++i2) {
for(int j=col_offset,j2=0; j2<result.NumCols()&&j<Cols; ++j,++j2) {
result.SetPixel(k2,i2,j2, pppItem[k][i][j]);
}
}
}
return result;
}
/*
the routine inserts another image into this image at an arbitrary offset
and return the new image.
*/
template <class Item>
myImage<Item>
myImage<Item>:: Insert(const myImage<Item>& insert,
int band_offset, int row_offset, int col_offset) {
//assertion takes care of unexpected conditions
assert(band_offset<Bands && row_offset<Rows && col_offset<Cols);
myImage<Item> res(Bands,Rows,Cols);
//copy items with in the ROI
for(int k=band_offset,k2=0; k2<insert.NumBands()&&k<Bands; ++k,++k2) {
for(int i=row_offset,i2=0; i2<insert.NumRows()&&i<Rows; ++i,++i2) {
for(int j=col_offset,j2=0; j2<insert.NumCols()&&j<Cols; ++j,++j2) {
res.SetPixel(k,i,j,insert.GetPixel(k2,i2,j2));
}
}
}
return res;
}
/*
the routine inserts another image into this image at an arbitrary offset
*/
template <class Item>
void
myImage<Item>:: insert(const myImage<Item>& insert,
int band_offset, int row_offset, int col_offset) {
//assertion takes care of unexpected conditions
assert(band_offset<Bands && row_offset<Rows && col_offset<Cols);
//copy items with in the ROI
for(int k=band_offset,k2=0; k2<insert.NumBands()&&k<Bands; ++k,++k2) {
for(int i=row_offset,i2=0; i2<insert.NumRows()&&i<Rows; ++i,++i2) {
for(int j=col_offset,j2=0; j2<insert.NumCols()&&j<Cols; ++j,++j2) {
pppItem[k][i][j] = insert.GetPixel(k2,i2,j2);
}
}
}
}
/*
the routine increases the size of the image by integer factors
with pixel duplication.
*/
template <class Item>
myImage<Item>
myImage<Item>:: ScaleUp(int scale_bands, int scale_rows, int scale_cols) const {
//assertion takes care of unexpected conditions
assert(scale_bands>0);
assert(scale_rows>0);
assert(scale_cols>0);
myImage<Item> res(Bands*scale_bands,Rows*scale_rows,Cols*scale_cols);
for(int k=0; k<res.NumBands(); ++k) {
for(int i=0; i<res.NumRows(); ++i) {
for(int j=0; j<res.NumCols(); ++j) {
res.SetPixel(k,i,j,GetPixel(k/scale_bands,i/scale_rows,j/scale_cols));
}
}
}
return res;
}
/*
the routine increases the size of the image by integer factors
with pixel duplication.
*/
template <class Item>
void
myImage<Item>:: scaleup(int scale_bands, int scale_rows, int scale_cols) {
//assertion takes care of unexpected conditions
assert(scale_bands>0);
assert(scale_rows>0);
assert(scale_cols>0);
myImage<Item> temp_im = *this;
*this = myImage<Item>(Bands*scale_bands,Rows*scale_rows,Cols*scale_cols);
for(int k=0; k<Bands; ++k) {
for(int i=0; i<Rows; ++i) {
for(int j=0; j<Cols; ++j) {
SetPixel(k,i,j,temp_im.GetPixel(k/scale_bands,i/scale_rows,j/scale_cols));
}
}
}
}
/*
the routine performs a circular shift on the image.
*/
template <class Item>
void
myImage<Item>:: circularShift(int band_shift, int row_shift, int col_shift) {
//assertion takes care of unexpected conditions
assert(band_shift<Bands && row_shift<Rows && col_shift<Cols);
assert(band_shift> -Bands && row_shift> -Rows && col_shift> -Cols);
band_shift = (band_shift<0) ? Bands+band_shift: band_shift;
row_shift = (row_shift<0) ? Rows+row_shift: row_shift;
col_shift = (col_shift<0) ? Cols+col_shift: col_shift;
myImage<Item> tmp_im(*this);
for(int k=0, k2=band_shift; k<Bands; ++k,++k2) {
for(int i=0, i2=row_shift; i<Rows; ++i,++i2) {
for(int j=0,j2=col_shift; j<Cols; ++j,++j2) {
pppItem[k][i][j] = tmp_im.GetPixel(k2%Bands,i2%Rows,j2%Cols);
}
}
}
}
/*
the routine performs a circular shift on the image.
*/
template <class Item>
myImage<Item>
myImage<Item>:: CircularShift(int band_shift, int row_shift, int col_shift) {
//assertion takes care of unexpected conditions
assert(band_shift<Bands && row_shift<Rows && col_shift<Cols);
assert(band_shift> -Bands && row_shift> -Rows && col_shift> -Cols);
band_shift = (band_shift<0) ? Bands+band_shift: band_shift;
row_shift = (row_shift<0) ? Rows+row_shift: row_shift;
col_shift = (col_shift<0) ? Cols+col_shift: col_shift;
myImage<Item> result(Bands, Rows, Cols);
for(int k=0, k2=band_shift; k<Bands; ++k,++k2) {
for(int i=0, i2=row_shift; i<Rows; ++i,++i2) {
for(int j=0,j2=col_shift; j<Cols; ++j,++j2) {
result.SetPixel(k,i,j,pppItem[k2%Bands][i2%Rows][j2%Cols]);
}
}
}
return result;
}
template <class Item>
Item**
myImage<Item>:: myImage2NRarray(int band) const {
Item** a;
a = new ptr1D_Data[Rows]-1;
for(int i=1; i<=Rows;++i)
a[i]=pItem+band*Rows*Cols+(i-1)*Cols-1;
return a;
}
template<class Item>
myImage<unsigned char>
myImage<Item>:: Threshold(Item low, Item high, bool inside, unsigned char val) {
myImage<unsigned char> binaryImage(Bands,Rows,Cols,0);
if(inside) {
for(int i=0; i<NumPixels(); ++i) {
if(pItem[i]>= low && pItem[i]<=high) {
binaryImage.SetPixel(i,val);
}
}
}
else {
for(int i=0; i<NumPixels(); ++i) {
if(pItem[i]< low || pItem[i]>high) {
binaryImage.SetPixel(i,val);
}
}
}
return binaryImage;
}
template<class Item>
vector<int>
myImage<Item>:: Histogram(int numbins, Item low, Item high) {
Item binWidth=(high-low)/numbins;
vector<int> histogram(numbins,0);
for(int i=0; i<Bands*Rows*Cols; ++i) {
int k = (pItem[i]-low)/binWidth;
if(k>=0 && k<histogram.size())
histogram[k]++;
}
return histogram;
}
template<class Item>
myImage<unsigned char>
myImage<Item>:: Normalize() {
myImage<unsigned char> nimage(Bands, Rows, Cols,(unsigned char)0);
Item minval=pItem[0];
Item maxval=minval;
int i;
for(i=0; i<Bands*Rows*Cols; ++i) {
Item val=pItem[i];
if(minval>val)
minval=val;
if(maxval<val)
maxval=val;
}
if(maxval>minval) {
for(i=0; i<Bands*Rows*Cols; ++i) {
Item val=pItem[i];
nimage.SetPixel(i,(unsigned char)(255*(val-minval)/(maxval-minval)));
}
}
return nimage;
}
template<class Item>
int
CompareImageSize(const myImage<Item>& image1, const myImage<Item>& image2) {
if (image1.NumBands() > image2.NumBands()) return 1;
else if (image1.NumBands() < image2.NumBands()) return -1;
else if (image1.NumRows() > image2.NumRows()) return 1;
else if (image1.NumRows() < image2.NumRows()) return -1;
else if (image1.NumCols() > image2.NumCols()) return 1;
else if (image1.NumCols() < image2.NumCols()) return -1;
else return 0;
}
template<class Item>
int
ComparePlaneSize(const myImage<Item>& image1, const myImage<Item>& image2) {
if (image1.NumRows() > image2.NumRows()) return 1;
else if (image1.NumRows() < image2.NumRows()) return -1;
else if (image1.NumCols() > image2.NumCols()) return 1;
else if (image1.NumCols() < image2.NumCols()) return -1;
else return 0;
}
#endif /* myImage_cpp */
|
852ed218ffe7e521d702fb4aef839225f1f5689e | 508b90a206b66e51a80aa09eb81340e46322ea81 | /attack/headers/sender/inputs/IInput.hh | 2f33ea455d2d96f15e102d1731186f8f73f7021f | [] | no_license | roggproject/ROGG | 7fe793de10527b8a945d44d912655b78d92d0f19 | 6532d9d1e20ca8024e300b636eabc54d3bf6a45e | refs/heads/master | 2016-09-06T10:36:50.258170 | 2015-09-09T17:25:23 | 2015-09-09T17:25:23 | 41,448,739 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 838 | hh | IInput.hh | #pragma once
/*
It's an interface for all inputs available in the client.
All inputs must inherit of this interface.
*/
#include <string>
#include <vector>
class IInput
{
public:
virtual ~IInput() {}
//Check the syntax of the input
virtual bool checkSyntax(std::vector<std::string> &) = 0;
//Accessor method for the name of the input
virtual const std::string &getName() const = 0;
//Accessor method for the data provided by the input
virtual void *getData() = 0;
//Accessor method for arguments format of the input
virtual const std::string &getArgFormat() const = 0;
//Accessor method for descritpion of the input
virtual const std::string &getDescription() const = 0;
//Return the size of the data provided by the input
virtual unsigned int getSizeData() const = 0;
};
|
41d5f2c2ade7c921747008011f677136b54f2d13 | ce6df5683d9d534b72289e0bf0c4e00c7c0fb886 | /boost/units_blas/result_of/value_at.hpp | ee76a5cab390eaf82d653e361388ff46631bcf93 | [] | no_license | tzlaine/Units-BLAS | 0c7e7238d9dbd87a38fcc82a41baa60ad0725c5e | 9455505aed51d924d1f08b584c1477ef4f75c071 | refs/heads/master | 2020-04-08T19:07:25.957701 | 2013-06-01T17:14:22 | 2013-06-01T17:14:22 | 1,804,983 | 4 | 1 | null | 2015-06-16T13:18:12 | 2011-05-26T15:16:24 | C++ | UTF-8 | C++ | false | false | 1,608 | hpp | value_at.hpp | // boost.units_blas
//
// Copyright (C) 2008 T. Zachary Laine
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_UNITS_BLAS_RESULT_OF_VALUE_AT_HPP
#define BOOST_UNITS_BLAS_RESULT_OF_VALUE_AT_HPP
#include <boost/units_blas/matrix_fwd.hpp>
#include <boost/fusion/sequence/intrinsic/value_at.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/less.hpp>
#include <boost/mpl/size_t.hpp>
namespace boost { namespace units_blas { namespace result_of {
/** Returns the type of the element at row @c I, column @c J of @c Matrix.
@c Matrix must be a @c matrix<>. */
template <typename Matrix, typename I, typename J>
struct value_at
{
#ifndef BOOST_UNITS_BLAS_DOXYGEN
BOOST_MPL_ASSERT((mpl::less<I, typename Matrix::num_rows_t>));
BOOST_MPL_ASSERT((mpl::less<J, typename Matrix::num_columns_t>));
#endif
typedef typename fusion::result_of::value_at<
typename fusion::result_of::value_at<
typename Matrix::value_types,
I
>::type,
J
>::type type;
};
/** Returns the type of the element at row @c I, column @c J of @c Matrix.
@c Matrix must be a @c matrix<>. */
template <typename Matrix, std::size_t I, std::size_t J>
struct value_at_c
{
typedef typename value_at<Matrix, mpl::size_t<I>, mpl::size_t<J> >::type type;
};
} } } // namespace boost::units_blas::result_of
#endif // BOOST_UNITS_BLAS_RESULT_OF_VALUE_AT_HPP
|
4305559319b5ec08b91efc2f570c97b6443cc91c | e10870724b002c1b51994dd535b0df552941bd03 | /switch_light/switch_light.ino | afb58e2e5fc5a6f6e5a52b1e08e232520e45e211 | [] | no_license | andrewcgaitskell/sensor_code | eecc694dffb939ab391e8a19bc84c49647baf0f8 | be4373f55372b140c641e00381e8011ff920ec8d | refs/heads/main | 2023-04-16T05:32:55.597136 | 2021-04-16T16:29:15 | 2021-04-16T16:29:15 | 352,959,603 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 739 | ino | switch_light.ino | /******************************************
Website: www.elegoo.com
Time:2017.12.12
******************************************/
int Led = 13; //define LED port
int buttonpin = 3; //define switch port
int val;//define digital variable val
int led_state = 0;
void setup()
{
Serial.begin(9600);
pinMode(Led, OUTPUT); //define LED as a output port
pinMode(buttonpin, INPUT); //define switch as a output port
digitalWrite(buttonpin, LOW);
}
void loop()
{
val = digitalRead(buttonpin); //read the value of the digital interface 3 assigned to val
if (val == LOW)
{
delay(20);
led_state = !led_state;
digitalWrite(Led, led_state);
// Serial.println("detect shock!");
}
}
|
ab7c0330e82777795381b7256a91a1988bc7e410 | 230f1e74f60deb8b2aeb180795f75822d4ad0738 | /gameengine/engine/GameEngine/Lab5/src/Game.cpp | c2b289c7737f712eb162a10209d4a3f355bf899a | [] | no_license | crabking/OpenGL-Component-Based-Engine | 01c3af5093aebbd41b5edfe791b6138f656066ba | 7c137e5bb14696ebf16d342047c3b2cf7f85ee7a | refs/heads/master | 2020-04-19T13:55:36.376802 | 2019-01-29T22:59:52 | 2019-01-29T22:59:52 | 168,228,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,610 | cpp | Game.cpp | #include "Game.h"
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include "FirstPersonCameraComponent.h"
#include "ThirdPersonCameraComponent.h"
using namespace std;
Game::Game()
{
DebugLog& log = log.getInstance(); //!< gets Debug instance.
factory = new Factory();
//m_currentScene = new Scene("0");
m_engineInterfacePtr = nullptr; //!< initialize engineinterfaceptr.
m_sceneHandler = new SceneHandler();
m_inputHandler = m_sceneHandler->getcurrentInputHandler();
//m_inputHandler = new InputHandler(getCurrentScene()->getControlledPlayerObject()); //! handles input on the 1 game object
}
Game::~Game()
{
delete m_inputHandler;
delete m_engineInterfacePtr;
delete factory;
delete m_sceneHandler;
}
void Game::update()
{
}
void Game::render()
{
FirstPersonCameraComponent* cam = getCurrentScene()->getControlledPlayerObject()->getComponent<FirstPersonCameraComponent>();
ThirdPersonCameraComponent* tpcam = getCurrentScene()->getControlledPlayerObject()->getComponent<ThirdPersonCameraComponent>();
if (getCurrentScene()->getControlledPlayerObject()->firstPerson)
{
m_engineInterfacePtr->setFirstPersonCamera(cam); //! gets players camera component from player object
}
if(!getCurrentScene()->getControlledPlayerObject()->firstPerson)
{
m_engineInterfacePtr->setThirdPersonCamera(tpcam); //! gets players camera component from player object
}
m_engineInterfacePtr->renderColouredBackground(0.2f,0.2f,0.2f); //! draw background
getCurrentScene()->render(m_engineInterfacePtr); //! render current scene
}
|
9d0d8b517028f9fd7c386b9ea35423c709c7f60a | 8f3469567609bbae36c65e09c54bf31bf332549d | /fixnum_lockable.h | f34f0517c22c434dbe3cc9776a7e1f2c744bc629 | [] | no_license | NocturnalShadow/DekkerLock | 2ff902eaaab8fac5b8e4e00aa7c8f77c3914aa75 | 4f1b9ba552a208628ef9dcd8ad315b59bdc236f4 | refs/heads/master | 2021-05-07T18:46:51.241565 | 2017-10-30T09:44:55 | 2017-10-30T09:44:55 | 108,831,016 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 487 | h | fixnum_lockable.h | #pragma once
#include <thread>
template <class T>
concept bool BasicLockable =
requires(T var) {
var.lock();
var.unlock();
};
template <class T>
concept bool Lockable =
requires(T var) {
requires BasicLockable<T>;
{ var.try_lock() } -> bool;
};
template <class T>
concept bool FixnumLockable =
requires(T var) {
requires Lockable<T>;
{ var.get_id() }->std::thread::id;
{ var.attach(std::this_thread::get_id()) } -> bool;
{ var.detach(std::this_thread::get_id()) } -> bool;
}; |
257a0bf44db1d60c5d593c8ba12d8f31f40db5d7 | 3c65a5f203f2d4b02ff9c1bdd999c9e3b18007e7 | /interp/additive_expr.cpp | 30692c263a5713d257297a0225be907e3624d09e | [
"BSL-1.0"
] | permissive | cristivlas/zerobugs | 07c81ceec27fd1191716e52b29825087baad39e4 | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | refs/heads/master | 2020-03-19T17:20:35.491229 | 2018-06-09T20:17:55 | 2018-06-09T20:17:55 | 136,754,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,778 | cpp | additive_expr.cpp | //
// $Id$
//
// -------------------------------------------------------------------------
// This file is part of ZeroBugs, Copyright (c) 2010 Cristian L. Vlasceanu
//
// 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)
// -------------------------------------------------------------------------
#include <stdexcept>
#include <string>
#include "zdk/check_ptr.h"
#include "zdk/shared_string_impl.h"
#include "zdk/types.h"
#include "zdk/type_system.h"
#include "context.h"
#include "debug_out.h"
#include "errors.h"
#include "interp.h"
#include "variant_assign.h"
#include "additive_expr.h"
#include "variant_impl.h"
using namespace std;
////////////////////////////////////////////////////////////////
AdditiveExpr::AdditiveExpr
(
Interp* interp,
Operator op,
RefPtr<Expr> lhs,
RefPtr<Expr> rhs
)
: BinaryExpr(interp, lhs, rhs), operator_(op)
{
}
////////////////////////////////////////////////////////////////
void AdditiveExpr::add_float_int(
const Variant& lval,
const Variant& rval,
Variant& result,
bool negate)
{
long double value = lval.long_double();
switch (operator_)
{
case AdditiveExpr::PLUS:
if (rval.type_tag() == Variant::VT_UINT64)
{
value += rval.uint64();
}
else
{
value += rval.int64();
}
break;
case AdditiveExpr::MINUS:
if (rval.type_tag() == Variant::VT_UINT64)
{
value -= rval.uint64();
}
else
{
value -= rval.int64();
}
if (negate)
{
value = -value;
}
break;
}
assert(type().get());
variant_assign(result, *type(), value);
}
////////////////////////////////////////////////////////////////
void AdditiveExpr::add_uint64_int(
const Variant& lval,
const Variant& rval,
Variant& result,
bool negate)
{
uint64_t value = lval.uint64();
switch (operator_)
{
case AdditiveExpr::PLUS:
if (rval.type_tag() == Variant::VT_UINT64)
{
value += rval.uint64();
}
else
{
value += rval.int64();
}
break;
case AdditiveExpr::MINUS:
if (rval.type_tag() == Variant::VT_UINT64)
{
value -= rval.uint64();
}
else
{
value -= rval.int64();
}
if (negate)
{
value = -value;
}
break;
}
assert(type().get());
variant_assign(result, *type(), value);
}
////////////////////////////////////////////////////////////////
void AdditiveExpr::add_integers(
const Variant& lval,
const Variant& rval,
Variant& result)
{
assert(is_integer(lval));
assert(is_integer(rval));
set_int_type(lval, rval);
assert(type().get());
int64_t value = lval.int64();
if (operator_ == PLUS)
{
value += rval.int64();
}
else
{
value -= rval.int64();
}
assert(type().get());
variant_assign(result, *type(), value);
}
////////////////////////////////////////////////////////////////
void AdditiveExpr::add_floats(
const Variant& lval,
const Variant& rval,
Variant& result)
{
assert(is_float(lval));
assert(is_float(rval));
if (lhs()->type()->size() > rhs()->type()->size())
{
set_type(lhs()->type());
}
else
{
set_type(rhs()->type());
}
long double value = lval.long_double();
if (operator_ == PLUS)
{
value += rval.long_double();
}
else
{
value -= rval.long_double();
}
variant_assign(result, *type(), value);
}
////////////////////////////////////////////////////////////////
void AdditiveExpr::add_pointer_int(
const Variant& lval,
const Variant& rval,
VariantImpl& result,
DataType& type)
{
assert(lval.type_tag() == Variant::VT_POINTER);
assert(is_integer(rval)
|| rval.type_tag() == Variant::VT_POINTER);
PointerType& ptrType = interface_cast<PointerType&>(type);
assert(ptrType.pointed_type());
const size_t size = ptrType.pointed_type()->size();
if (!size)
{
assert(interface_cast<VoidType*>(ptrType.pointed_type()));
throw runtime_error("pointer of type ‘void *’ used in arithmetic");
}
const int factor = (operator_ == PLUS) ? 1 : -1;
addr_t value = lval.pointer();
DEBUG_OUT << "value=" << (void*)value << endl;
if (rval.type_tag() == Variant::VT_POINTER)
{
assert(operator_ == MINUS);
assert(size);
value = (value - rval.pointer()) / size;
if (RefPtr<Interp> in = interp())
{
TypeSystem& typeSys = in->context().type_system();
RefPtr<DataType> diffType =
typeSys.get_int_type(shared_string("size_t").get(),
typeSys.word_size(),
false);
set_type(diffType);
variant_assign(result, *diffType, value);
}
}
else if (rval.type_tag() == Variant::VT_UINT64)
{
value += factor * rval.uint64() * size;
set_type(&type);
variant_assign(result, type, value);
}
else
{
value += factor * rval.int64() * size;
set_type(&type);
variant_assign(result, type, value);
}
result.set_encoding(lval.encoding());
}
////////////////////////////////////////////////////////////////
RefPtr<Variant> AdditiveExpr::eval_impl(Context& ctxt)
{
RefPtr<Variant> lval, rval;
eval_operands(ctxt, lval, rval);
RefPtr<VariantImpl> result = new VariantImpl;
//
// and now for an ugly display of brute-force...
//
if (lval->type_tag() == Variant::VT_POINTER)
{
if (rval->type_tag() == Variant::VT_POINTER)
{
// cannot add 2 pointers
if (operator_ != MINUS)
{
throw_invalid_types();
}
add_pointer_int(*lval, *rval, *result, *lhs()->type());
}
else if (is_integer(*rval))
{
add_pointer_int(*lval, *rval, *result, *lhs()->type());
}
else if (is_float(*rval))
{
// can't add/subtract float from pointer
throw_invalid_types();
}
}
else if (lval->type_tag() == Variant::VT_OBJECT)
{
try_overloaded_operator(ctxt);
}
else if (rval->type_tag() == Variant::VT_OBJECT)
{
try_standalone_operator(ctxt);
}
else if (is_integer(*lval))
{
if (rval->type_tag() == Variant::VT_POINTER)
{
if (operator_ == MINUS)
{
// cannot subtract pointer from integer
throw_invalid_types();
}
else
{
add_pointer_int(*rval, *lval, *result, *rhs()->type());
}
}
else if (is_integer(*rval))
{
if (lval->type_tag() == Variant::VT_UINT64)
{
// the resulting expression is of type uint64
set_type(lhs()->type());
add_uint64_int(*lval, *rval, *result);
}
else if (rval->type_tag() == Variant::VT_UINT64)
{
// the resulting expression is of type uint64
set_type(rhs()->type());
add_uint64_int(*rval, *lval, *result, true);
}
else
{
// none of the operands is uint64_t
add_integers(*lval, *rval, *result);
}
}
else if (is_float(*rval))
{
set_type(rhs()->type());
add_float_int(*rval, *lval, *result, true);
}
}
else if (is_float(*lval))
{
if (rval->type_tag() == Variant::VT_POINTER)
{
// can't do pointer arithmetic with floats
throw_invalid_types();
}
else if (is_integer(*rval))
{
set_type(lhs()->type());
add_float_int(*lval, *rval, *result);
}
else if (is_float(*rval))
{
add_floats(*lval, *rval, *result);
}
}
return result;
}
////////////////////////////////////////////////////////////////
const char* AdditiveExpr::operator_name() const
{
switch (operator_)
{
case MINUS: return "-";
case PLUS: return "+";
}
assert(false);
return "";
}
// vim: tabstop=4:softtabstop=4:expandtab:shiftwidth=4
|
9bf6e3951cad5947330f827611f615892e7041a1 | ef8df20641b85ed70d07602e13db5720499e2795 | /棚内土壤版_GS100/STM32_LORA_GS100_V3.0.0_beta/private_sensor.cpp | 7e46136998f2be8167723fa8816517c07b3c8b0f | [] | no_license | Arrogantyunya/LoRa_SensorV2.0 | 0a1538b96823176def1217f68530daf4cd8e5470 | c6bf18a3919dd13dae26ac945f4eb5559e2b7a36 | refs/heads/master | 2020-09-20T22:44:37.708282 | 2020-07-21T10:27:08 | 2020-07-21T10:27:08 | 224,607,027 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,285 | cpp | private_sensor.cpp | #include "private_sensor.h"
#include <Arduino.h>
#include "RS485.h"
#include "MODBUS_RTU_CRC16.h"
#include "MAX44009/i2c_MAX44009.h"
#include "SHT1x.h"
#include "fun_periph.h"
#include "Adafruit_ADS1015.h"
struct SENSOR_DATA Sensor_Data;
Sensor private_sensor;
void Sensor::Get_All_Sensor_Data(void)
{
int retry_num = 0; int retry = 3;
PWR_485_ON;
delay(1000);//经过测试,新版的PH的测量,为了使温湿度数据完整读出,需要等待温湿度传感器初始化完成。所以增加1s的延时,否则可能出现温度数据读取不出来。
Sensor_Data.g_Temp = sht10.readTemperatureC();
delay(100);
Sensor_Data.g_Humi = sht10.readHumidity();
delay(100);
while (private_sensor.Read_Solid_Humi_and_Temp(&Sensor_Data.g_Solid_Humi, &Sensor_Data.g_Solid_Temp, &Sensor_Data.g_Solid_Temp_Flag, 0x01) != 1 && retry_num < retry)
{
retry_num++;
}
retry_num = 0;
delay(100);
while ((private_sensor.Read_Salt_and_Cond(&Sensor_Data.g_Salt, &Sensor_Data.g_Cond, 0x01) != 1) && (retry_num < retry))
{
retry_num++;
}
retry_num = 0;
delay(100);
while ((private_sensor.Read_Soild_PH(&Sensor_Data.g_Solid_PH, 0x02) != 1) && (retry_num < retry))
{
retry_num++;
}
delay(100);
private_sensor.Read_Lux_and_UV(&Sensor_Data.g_Lux, &Sensor_Data.g_UV);
delay(100);
private_sensor.Read_Displacement(&Sensor_Data.g_Displacement);
delay(100);
// PWR_485_OFF;
Serial.print("temperature: ");//空气温度
Serial.println(String(Sensor_Data.g_Temp) + "℃");
Serial.print("humility: ");//空气湿度
Serial.println(String(Sensor_Data.g_Humi) + "%RH");
Serial.print("Lux: ");//光照强度
Serial.println(String(Sensor_Data.g_Lux) + "lux");
Serial.print("UV: ");//紫外线强度
Serial.println(String(Sensor_Data.g_UV) + "W/m2");
Serial.print("Solid temperature: ");//土壤温度
Serial.println(String(Sensor_Data.g_Solid_Temp / 100) + "℃");
Serial.print("Solid PH: ");//土壤酸碱度
Serial.println(String(float(Sensor_Data.g_Solid_PH)/100) + "");
Serial.print("Solid humility: ");//土壤湿度
Serial.println(String(Sensor_Data.g_Solid_Humi) + "%RH");
Serial.print("Solid salt: ");//土壤盐度
Serial.println(String(Sensor_Data.g_Salt) + "mg/L");
Serial.print("Solid cond: ");//土壤电导率
Serial.println(String(Sensor_Data.g_Cond) + "us/cm");
Serial.print("Displacement:");//植物杆径
Serial.println(String(Sensor_Data.g_Displacement) + "μm");
}
/*
*brief : Initialize UV and Illumination sensors.
*para : None
*return : None
*/
void Sensor::CJMCU6750_Init(void)
{
CJMCU6750.begin(PB15, PB14);
CJMCU6750.beginTransmission(UV_I2C_ADDR);
CJMCU6750.write((IT_1 << 2) | 0x02);//0x100|0x02 = 0x102
CJMCU6750.endTransmission();
delay(500);
if (max44009.initialize()) //Lux
Serial.println("Sensor MAX44009 found...");
else
Serial.println("Light Sensor missing !!!");
}
/*
*brief : Initialize UV and Illumination sensors.
*para : None
*return : None
*/
void Sensor::ADS115_Init(void)
{
// CJMCU6750.begin(PB15, PB14);
// CJMCU6750.beginTransmission(UVI2C_ADDR);
// CJMCU6750.write((IT_1 << 2) | 0x02);
// CJMCU6750.endTransmission();
// delay(500);
// if (max44009.initialize()) //Lux
// Serial.println("Sensor MAX44009 found...");
// else
// Serial.println("Light Sensor missing !!!");
}
/*
*brief : Read Lux and UV from sensor (I2C)
*para : Lux, UV
*return : None
*/
void Sensor::Read_Lux_and_UV(unsigned long* lux, unsigned int* uv)
{
unsigned char msb = 0, lsb = 0;
unsigned long mLux_value = 0;
CJMCU6750_Init();
#if LUX_UV
CJMCU6750.requestFrom(UV_I2C_ADDR + 1, 1); //MSB
delay(1);
if (CJMCU6750.available())
msb = CJMCU6750.read();
CJMCU6750.requestFrom(UV_I2C_ADDR + 0, 1); //LSB
delay(1);
if (CJMCU6750.available())
lsb = CJMCU6750.read();
*uv = (msb << 8) | lsb;
*uv *= 0.005625;
Serial.print("UV : "); //output in steps (16bit)
Serial.println(*uv);
#endif
max44009.getMeasurement(mLux_value);
*lux = mLux_value / 1000L;
Serial.print("light intensity value:");
Serial.print(*lux);
Serial.println(" Lux");
}
/*
*brief : According to the ID address and register(ModBus) address of the soil sensor, read temperature and humidity
*para : humidity, temperature, address
*return : None
*/
bool Sensor::Read_Solid_Humi_and_Temp(float* humi, unsigned int* temp, unsigned char* temp_flag, unsigned char addr)
{
#if PR_3000_ECTH_N01
unsigned char Send_Cmd[8] = { 0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00 };
#else
unsigned char Send_Cmd[8] = { 0x01, 0x03, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00 };
#endif
unsigned char Receive_Data[10] = { 0 };
unsigned char Length = 0;
unsigned int Send_CRC16 = 0, Receive_CRC16 = 0, Verify_CRC16 = 0;
float hum = 65535.0;
unsigned int humi_temp = 0xFFFF, tem_temp = 0xFFFF;
unsigned char temperature_flag = 0;
Send_Cmd[0] = addr; //Get sensor address
Send_CRC16 = N_CRC16(Send_Cmd, 6);
Send_Cmd[6] = Send_CRC16 >> 8;
Send_Cmd[7] = Send_CRC16 & 0xFF;
RS485_Serial.write(Send_Cmd, 8);
delay(300);
while (RS485_Serial.available() > 0)
{
if (Length >= 9)
{
Serial.println("土壤温湿度回执Length >= 9");
Length = 0;
break;
}
Receive_Data[Length++] = RS485_Serial.read();
}
//Serial.println(String("土壤温湿度回执Length = ") + Length);
Serial.println("---土壤温湿度回执---");
if (Length > 0)
{
for (size_t i = 0; i < Length; i++)
{
Serial.print(Receive_Data[i], HEX);
Serial.print(" ");
}
}
Serial.println("");
Serial.println("---土壤温湿度回执---");
if (Receive_Data[0] == 0) {
Verify_CRC16 = N_CRC16(&Receive_Data[1], 7);
Receive_CRC16 = Receive_Data[8] << 8 | Receive_Data[9];
}
else {
Verify_CRC16 = N_CRC16(Receive_Data, 7);
Receive_CRC16 = Receive_Data[7] << 8 | Receive_Data[8];
}
if (Receive_CRC16 == Verify_CRC16) {
if (Receive_Data[0] == 0) {
humi_temp = Receive_Data[4] << 8 | Receive_Data[5];
tem_temp = Receive_Data[6] << 8 | Receive_Data[7];
}
else {
humi_temp = Receive_Data[3] << 8 | Receive_Data[4];
tem_temp = Receive_Data[5] << 8 | Receive_Data[6];
}
#if PR_3000_ECTH_N01
hum = (float)humi_temp / 100.0;
#else
hum = (float)humi_temp / 10.0;
#endif
temperature_flag = ((tem_temp >> 15) & 0x01);
}
else
{
Serial.println("Read Solid Humi and Temp Error!!!<Read_Solid_Humi_and_Temp>");
return 0;
}
*humi = hum;
*temp = tem_temp;
*temp_flag = temperature_flag;
return 1;
}
/*
*brief : According to the ID address and register(ModBus) address of the soil sensor, read PH
*para : Solid_PH, address
*return : None
*/
bool Sensor::Read_Soild_PH(unsigned int * Solid_PH, unsigned char addr)
{
#if ST_500_Soil_PH
unsigned char Send_Cmd[8] = { 0x02, 0x03, 0x00, 0x08, 0x00, 0x01,0x00,0x00 };//02 03 0008 0001 05C8
#elif JXBS_3001_PH
unsigned char Send_Cmd[8] = { 0x02, 0x03, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00 };
#endif
unsigned char Receive_Data[9] = { 0 };
unsigned char Length = 0;
unsigned int Send_CRC16 = 0, Receive_CRC16 = 0, Verify_CRC16 = 0;
unsigned int ph_temp = 0xFFFF;
Send_Cmd[0] = addr; //Get sensor address
Send_CRC16 = N_CRC16(Send_Cmd, 6);
Send_Cmd[6] = Send_CRC16 >> 8;
Send_Cmd[7] = Send_CRC16 & 0xFF;
RS485_Serial.write(Send_Cmd, 8);
delay(300);
while (RS485_Serial.available() > 0)//02 03 02 02BC FC95就是0x2BC = 700,结果需要除以100,那么就是7
{
if (Length >= 8)
{
Serial.println("土壤酸碱度回执Length >= 8");
Length = 0;
break;
}
Receive_Data[Length++] = RS485_Serial.read();
}
//Serial.println(String("土壤酸碱度回执Length = ") + Length);
Serial.println("---土壤酸碱度回执---");
if (Length > 0)
{
for (size_t i = 0; i < Length; i++)
{
Serial.print(Receive_Data[i], HEX);
Serial.print(" ");
}
}
Serial.println("");
Serial.println("---土壤酸碱度回执---");
Verify_CRC16 = N_CRC16(Receive_Data, 5);
Receive_CRC16 = Receive_Data[5] << 8 | Receive_Data[6];
if (Receive_CRC16 == Verify_CRC16) {
//Serial.println("SUCCESS");
//delay(3000);
ph_temp = Receive_Data[3] << 8 | Receive_Data[4];
Serial.println(String("ph_temp = ")+ph_temp);
}
else
{
Serial.println("PH Read Error!!!<Read_Soild_PH>");
return 0;
}
#if ST_500_Soil_PH
*Solid_PH = ph_temp * 10;
return 1;
#elif JXBS_3001_PH
*Solid_PH = ph_temp;
return 1;
#endif
}
/*
*brief : According to the ID address and register(ModBus) address of the soil sensor, read salt and conductivity
*para : salt, conductivity, address
*return : None
*/
bool Sensor::Read_Salt_and_Cond(unsigned int* salt, unsigned int* cond, unsigned char addr)
{
#if PR_3000_ECTH_N01
unsigned char Send_Cmd[8] = { 0x01, 0x03, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00 };
#else
unsigned char Send_Cmd[8] = { 0x01, 0x03, 0x00, 0x14, 0x00, 0x02, 0x00, 0x00 };
#endif
unsigned char Receive_Data[10] = { 0 };
unsigned char Length = 0;
unsigned int Send_CRC16 = 0, Receive_CRC16 = 0, Verify_CRC16 = 0;
unsigned int salt_temp = 0xFFFF;
unsigned int cond_temp = 0xFFFF;
Send_Cmd[0] = addr; //Get sensor address
Send_CRC16 = N_CRC16(Send_Cmd, 6);
Send_Cmd[6] = Send_CRC16 >> 8;
Send_Cmd[7] = Send_CRC16 & 0xFF;
RS485_Serial.write(Send_Cmd, 8);
delay(300);
while (RS485_Serial.available() > 0)
{
if (Length >= 9)
{
Serial.println("土壤盐电导率回执Length >= 9");
Length = 0;
break;
}
Receive_Data[Length++] = RS485_Serial.read();
}
//Serial.println(String("土壤盐电导率回执Length = ") + Length);
Serial.println("---土壤盐电导率回执---");
if (Length > 0)
{
for (size_t i = 0; i < 9; i++)
{
Serial.print(Receive_Data[i], HEX);
Serial.print(" ");
}
}
Serial.println("");
Serial.println("---土壤盐电导率回执---");
Verify_CRC16 = N_CRC16(Receive_Data, 7);
Receive_CRC16 = Receive_Data[7] << 8 | Receive_Data[8];
if (Receive_CRC16 == Verify_CRC16) {
salt_temp = Receive_Data[5] << 8 | Receive_Data[6];
cond_temp = Receive_Data[3] << 8 | Receive_Data[4];
}
else
{
Serial.println("Read Salt and Cond Error!!!<Read_Salt_and_Cond>");
return 0;
}
*salt = salt_temp;
*cond = cond_temp;
return 1;
}
/*
*brief : Read Displacement from sensor (ADC)
*para : Displacement
*return : None
*/
void Sensor::Read_Displacement(unsigned int *Displacement)
{
int16_t adc0, adc1, adc2, adc3;
float Voltage = 0.0;//声明一个变量 用于存储检测到的电压值
unsigned int Displacement_temp = 0xFF;
adc0 = ads.readADC_SingleEnded(0);
adc1 = ads.readADC_SingleEnded(1);
adc2 = ads.readADC_SingleEnded(2);
adc3 = ads.readADC_SingleEnded(3);
// Serial.print("AIN0: "); Serial.println(adc0);
// Serial.print("AIN1: "); Serial.println(adc1);
// Serial.print("AIN2: "); Serial.println(adc2);
// Serial.print("AIN3: "); Serial.println(adc3);
if (adc3 < 0)
{
//读取错误,异常处理
adc3 = 0;
}
Voltage = (adc3 * 0.1875); //把数值转换成电压值,0.1875是电压因数
Serial.println(String("Voltage = ") + String(Voltage,2) + "mv");
//0-3300mv对应0-20mm ==> 0-3300000μv对应0-20000μm
//1mv对应0.006mm=6μm ==> 1μv对应0.006μm
Displacement_temp = int(Voltage*6);
Serial.println(String("Displacement_temp = ") + String(Displacement_temp) + "μm");
Serial.println("---------");Serial.flush();
*Displacement = Displacement_temp;
}
/**
* [ADS1115Configure description]
* @Author 叶鹏程
* @DateTime 2019-08-19T20:44:30+0800
* @discrption : 芯片初始化配置
*
* @param mux [输入通道配置]
* @param pga [量程设置]
* @param mode [单次或持续转换模式]
* @param dr [采样速率设置]
*/
void ADS1115Configure(ADS1115Conf mux, ADS1115Conf pga, ADS1115Conf mode, ADS1115Conf dr){
uint16_t conf;
ADS1115.beginTransmission(ADS1115_I2C_address);
ADS1115.write(0x01); //set Address Pointer Register as conf Register将地址指针寄存器设置为conf寄存器
ADS1115.endTransmission();
/*read chip's conf register data */
ADS1115.requestFrom(ADS1115_I2C_address, 2);
conf = 0;
conf = ADS1115.read();
conf = conf<<8;
conf |= ADS1115.read();
/*change it*/
conf = 0x8000;
conf &= (~(0x0007<< 12)); conf |= mux << 12;
conf &= (~(0x0007<< 9 )); conf |= pga << 9;
conf &= (~(0x0007<< 8 )); conf |= mode << 8;
conf &= (~(0x0007<< 5 )); conf |= dr << 5;
// conf = 0xf483;
/* trans back*/
ADS1115.beginTransmission(ADS1115_I2C_address);
ADS1115.write(0x01); //set Address Pointer Register as conf Register将地址指针寄存器设置为conf寄存器
ADS1115.write(uint8_t(conf>>8)); //conf MSB
ADS1115.write(uint8_t(conf)); //conf LSB
ADS1115.endTransmission();
/**/
ADS1115.beginTransmission(ADS1115_I2C_address);
ADS1115.write(0x00); //set Address Pointer Register as conf Register将地址指针寄存器设置为conf寄存器
ADS1115.endTransmission();
}
/**
* [ADS1115SetChannel description]
* @Author 叶鹏程
* @DateTime 2019-08-19T20:43:57+0800
* @discrption :芯片输入通道设置
*
* @param mux [description]
*/
void ADS1115SetChannel(ADS1115Conf mux){
uint16_t conf;
ADS1115.beginTransmission(ADS1115_I2C_address);
ADS1115.write(0x01); //set Address Pointer Register as conf Register
ADS1115.endTransmission();
/*read chip's conf register data */
ADS1115.requestFrom(ADS1115_I2C_address, 2);
conf = 0;
conf = ADS1115.read();
conf = conf<<8;
conf |= ADS1115.read();
/*change it*/
conf = conf & (~(0x0007<< 12)); conf |= mux << 12;
/* trans back*/
ADS1115.beginTransmission(ADS1115_I2C_address);
ADS1115.write(0x01); //set Address Pointer Register as conf Register
ADS1115.write(uint8_t(conf>>8)); //conf MSB
ADS1115.write(uint8_t(conf)); //conf LSB
ADS1115.endTransmission();
/**/
ADS1115.beginTransmission(ADS1115_I2C_address);
ADS1115.write(0x00); //set Address Pointer Register as conf Register
ADS1115.endTransmission();
}
long ADS1115ReadResult(void){
long ret;
ADS1115.requestFrom(ADS1115_I2C_address, 2);
ret = 0;
ret = ADS1115.read();
Serial.println(String("ret1 = ") + ret);
ret = ret<<8;
ret |= ADS1115.read();
Serial.println(String("ret12= ") + ret);
return ret;
} |
283f1578827ec3db942c79a6f63cf481cf94c612 | 162ecc77779289aeebac15cbd30537c08d52bf42 | /Math/floating_point.h | ebef4cfb15a5755857e4caec3d6537042c05c9f6 | [] | no_license | NIA/crash-and-squeeze | 7712efad3487a2dcc2795e24a536b06a9207fe58 | 226606f83d8251ddcd2d8e6f3079fc9052e57ed0 | refs/heads/master | 2020-12-24T08:18:10.329627 | 2017-08-17T14:37:49 | 2017-08-17T14:37:49 | 833,109 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,323 | h | floating_point.h | #pragma once
#include <cmath>
#include <cfloat>
// Helpers for 'proper' comparing floating point numbers: assuming equal those ones,
// whose difference is less than given epsilon
namespace CrashAndSqueeze
{
namespace Math
{
// floating-point type of internal calculations
typedef double Real;
const Real MAX_REAL = DBL_MAX;
const Real DEFAULT_REAL_PRECISION = 1e-9;
inline bool equal(Real a, Real b, Real epsilon = DEFAULT_REAL_PRECISION)
{
return fabs(a - b) <= epsilon;
}
inline bool less_or_equal(Real a, Real b, Real epsilon = DEFAULT_REAL_PRECISION)
{
return (a < b) || equal( a, b, epsilon );
}
inline bool greater_or_equal(Real a, Real b, Real epsilon = DEFAULT_REAL_PRECISION)
{
return (a > b) || equal( a, b, epsilon );
}
inline int sign(Real x)
{
return (x > 0) - (x < 0);
}
template <typename T> /* requires LessThanComparable<T> */
inline T minimum(T a, T b)
{
return (a < b) ? a : b;
}
inline Real cube_root(Real value)
{
return pow( abs(value), 1.0/3)*sign(value);
}
};
};
|
dabc6da863d7df6897df13d91eb81eb392accf2b | 55d9ebd8d099054890be28a9ffa3551d686e0744 | /examples/3-0-containers_algorithms/containters/main.cpp | 32484b2b33f242431fd099c2be65c33fb5f47159 | [] | no_license | PLLUG/CPPQT-Roadmap | 2b2ccdc00157cbd3fa5b3b4d9ce408b8d3d80a24 | ae68d9d6ee1e173b2c62ea14d513ab53f0f64724 | refs/heads/master | 2021-05-03T14:54:38.719228 | 2018-03-18T13:09:38 | 2018-03-18T13:09:38 | 69,292,293 | 0 | 1 | null | 2016-10-04T20:26:08 | 2016-09-26T20:58:56 | null | UTF-8 | C++ | false | false | 1,667 | cpp | main.cpp | #include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
using namespace std;
bool cmp(const std::string &a, const std::string &b)
{
const std::string vasaName = "vasa";
if (a == vasaName)
{
return true;
}
else if (b == vasaName)
{
return false;
}
return a < b;
}
int main(int argc, char *argv[])
{
std::string s = "s";
auto valueToExit = 0;
std::vector<decltype(valueToExit)> inputValues;
do
{
auto input = valueToExit;
std::cin >> input;
if (input != valueToExit)
{
inputValues.push_back(input);
}
else
{
break;
}
}
while (true);
std::cout << "-----------" << std::endl;
// for (int i = 0; i < inputValues.size(); ++i)
// {
// std::cout << inputValues.at(i) << std::endl;
// }
// for (auto value : inputValues)
// {
// std::cout << value << std::endl;
// }
// auto func1 = [](const std::string &a, const std::string &b) {
// const std::string vasaName = "vasa";
// if (a == vasaName)
// {
// return true;
// }
// else if (b == vasaName)
// {
// return false;
// }
// return a < b;
// };
std::sort(inputValues.begin(), inputValues.end()/*, func1*/);
auto mult = [](int &value){ value = value * 2; };
auto print = [](int &value){ std::cout << value << std::endl; };
std::for_each(inputValues.begin(), inputValues.end(), mult);
std::for_each(inputValues.begin(), inputValues.end(), print);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.