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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
68f5d2c560210342acf2fd0c0afb7fa5353f2e23 | 30e1dc84fe8c54d26ef4a1aff000a83af6f612be | /test/vega_renderer/log_proxy_tests.hpp | 445a74bfeab9deb459c698457c8c6867a434533e | [
"BSD-3-Clause"
] | permissive | Sitispeaks/turicreate | 0bda7c21ee97f5ae7dc09502f6a72abcb729536d | d42280b16cb466a608e7e723d8edfbe5977253b6 | refs/heads/main | 2023-05-19T17:55:21.938724 | 2021-06-14T17:53:17 | 2021-06-14T17:53:17 | 385,034,849 | 1 | 0 | BSD-3-Clause | 2021-07-11T19:23:21 | 2021-07-11T19:23:20 | null | UTF-8 | C++ | false | false | 383 | hpp | log_proxy_tests.hpp | /* Copyright © 2019 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
struct LogProxyTests {
static void test_wrap_unwrap();
static void test_expected_property_access();
static void test_unexpected_property_access();
}; |
322e7b2a3c5ad10263dbce089bbb8cd0688760ee | aa4ca4e730b49b99d0117d43a3d5ed42adc80bfb | /source/CIA.h | c242fd879f7197c8d9a2bdfc39d08ec04ec8b219 | [] | no_license | GotoHack/saleae_sdio | 9e98b21275f39268d833beb1cc3199f625357ade | c394cddbd4bf39428c7719a35fe28f759c6ab1b6 | refs/heads/master | 2021-01-14T13:22:22.890184 | 2015-05-07T15:55:28 | 2015-05-07T15:55:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,910 | h | CIA.h | #ifndef CIA_H
#define CIA_H
#include "LogicPublicTypes.h"
#include "SDIOParser.h"
#include "SdioCmd52.h"
#include <string.h>
#include <list>
#include <iterator>
#include <iostream>
#include <iomanip>
#include <map>
#include <string>
using namespace std;
#ifndef _MSC_VER
#define PACKED __attribute__ ((__packed__))
#else
#define PACKED
#pragma pack(push, 1)
#endif
#define PRINTF_BIT_PATTERN "| %x%x%x%x | %x%x%x%x |"
#define PRINTF_BIT(x) (1 & x >> 7), \
(1 & x >> 6), \
(1 & x >> 5), \
(1 & x >> 4), \
(1 & x >> 3), \
(1 & x >> 2), \
(1 & x >> 1), \
(1 & x )
// this is arbitrary -- just looking at the map in 6.7 of the simplified spec
#define CIS_MAX_SIZE 0xFFF
#define CIA_PTR_INIT_VAL 0xDEADBF
#define CIS_AREA_START 0x1000
#define CIS_AREA_END 0x7FFF
#define CISTPL_MANFID 0x20
#define CISTPL_FUNCID 0x21
#define CISTPL_FUNCE 0x22
typedef struct PACKED
{
unsigned char CCCR_SDIO_Revision;
unsigned char SD_Specification_Revision;
unsigned char IO_Enable;
unsigned char IO_Ready;
unsigned char Int_Enable;
unsigned char Int_Pending;
unsigned char IO_Abort;
unsigned char Bus_Interface_Control;
unsigned char Card_Capatility;
unsigned char Common_CIS_Pointer[3];
unsigned char Bus_Suspend;
unsigned char Function_Select;
unsigned char Exec_Flags;
unsigned char Ready_Flags;
unsigned char FN0_Block_Size[2];
unsigned char Power_Control;
unsigned char High_Speed;
unsigned char RFU[0xDC];
unsigned char Reserved_for_Vendors[0x0F];
} CCCR_t;
extern const char *CCCR_NAMES[];
#define CCCR_ADDRESS_START 0x00
#define CCCR_ADDRESS_END 0xFF
#define NUM_CCCR_ELEMENTS 0x14
// the FBR is an array of 256 bytes for functions 1-7, each function addressed at the next 100 (hex)
// comments for fn1, but they apply to all the fbr's
typedef struct PACKED
{
unsigned char FN_CSA; // 0x100
unsigned char FN_extended_SDIO_fn_interface_code; // 0x101
unsigned char RFU[7]; // 0x102--0x108
unsigned char CIS_ptr[3]; // 0x109-0x10b
unsigned char CSA_ptr[3]; // 0x10c--10e
unsigned char Data_Access_Window_To_CSA; // 0x10f
unsigned char IO_block_size_for_fn[2]; // 0x110--0x111
unsigned char RFU2[0xEE]; // 0x112--0x1ff
} FBR_t;;
extern const char* FBR_NAMES[];
#define FBR_ADDRESS_START 0x100
#define FBR_ADDRESS_END 0x7ff
#define NUM_FBR_ELEMENTS 0x12
class TUPLE
{
//private:
public:
U32 address;
U32 tplCode;
U32 size;
list <U32> body;
map <int, string> tupleNames;
public:
TUPLE(U32 addr=0);
void setAddress(U32 addr) {address = addr;}
void setTplCode(U32 code) {tplCode = code;}
void setSize(U32 sz) {size = sz;}
void addData(U32 data) { body.push_back(data);}
void dump(bool cisTupleFlag = false);
void dump(std::ostream &stream, bool cisTupleFlag = false);
private:
void dumpBody(std::ostream &stream, bool cisTupleFlag = false, int i=0);
void dumpBody_MANFID(std::ostream &stream, bool cisTupleFlag = false, int i=0);
void dumpBody_FUNCID(std::ostream &stream, bool cisTupleFlag = false, int i=0);
void dumpBody_FUNCE(std::ostream &stream, bool cisTupleFlag = false, int i=0);
void dumpBody_GENERIC(std::ostream &stream, bool cisTupleFlag = false, int i=0, char *strings[]=0, int maxStrings=0);
};
class CCCR
{
public:
static CCCR* BuildCCCR(U64 data);
static bool AddCmd52ToCCCR(U64 data);
static void DumpCCCRTable(void);
static void DumpCCCRTable(std::ostream &stream);
static void DumpFBRTable(void);
static void DumpFBRTable(std::ostream &stream);
static void CleanupCCCR();
U32 getCisAddress();
protected:
class TupleChain
{
private:
U32 lastTupleAddress;
U32 cisAddress;
bool newTuplePending;
bool tupleComplete;
list <TUPLE> tuples;
bool cisTupleFlag;
public:
TupleChain() :lastTupleAddress(0), newTuplePending(false), tupleComplete(false), cisTupleFlag(false), tuples() {};
void setCisAddress(U32 address);
void addDataToTuple(U64 data);
void dump();
void dump(std::ostream &stream);
void setCisTupleFlag() {cisTupleFlag = true;};
};
class FBR
{
public:
FBR(U32 number = 1);
void DumpFBR();
void DumpFBR(std::ostream &stream);
void addData(U64 data);
U32 getCisAddress(void);
private:
FBR_t fbr_data;
U32 functionNumber;
bool fbrDataPopulated;
TupleChain tupleChain;
};
private:
// variables
CCCR_t cccr_data;
// flags to indicate if data is populated,
// don't want to waste output space w/ unpopulated tables
bool cccrDataPopulated;
SdioCmd52 *lastHostCmd52;
static CCCR* theCCCR;
FBR fbr[7];
TupleChain tupleChain;
// functions
CCCR();
~CCCR() {};
CCCR(const CCCR& c) {};
CCCR& operator=(const CCCR&) {};
bool HandleCmd52Request(U64 data);
bool HandleCmd52Response(U64 data);
};
#ifdef _MSC_VER
#pragma pack(pop)
#endif
#endif /* CIA_H */
|
443931ebb2290935e31991b3052349126c93c18c | 641ccc0a50ceab71227b762f2596f86864e3bcf8 | /src/locationforecast/Document.h | e9283e91fa120a2be7aef2ce43fa3b0eee7c5da9 | [] | no_license | metno/wdb-locationforecastLoad | 86409eb8bbd645471e5848da0c33f72f5e67363b | 8af09af495bcda1769ffeeb349b09440a1b5bb48 | refs/heads/master | 2016-09-05T09:20:08.511702 | 2013-09-20T14:35:44 | 2013-09-20T14:35:44 | 3,325,668 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,918 | h | Document.h | /*
wdb-locationforecastLoad
Copyright (C) 2012 met.no
Contact information:
Norwegian Meteorological Institute
Box 43 Blindern
0313 OSLO
NORWAY
E-mail: post@met.no
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA
*/
#ifndef DOCUMENT_H_
#define DOCUMENT_H_
#include "DataElement.h"
#include "LocationForecastException.h"
#include "elementhandler/ElementHandler.h"
#include <boost/filesystem/path.hpp>
#include <iosfwd>
#include <string>
#include <exception>
#include <vector>
#include <map>
namespace xmlpp
{
class Node;
}
/**
* Functionality for reading a locationforecast document. For more information
* about these documents and their format, see
* http://api.met.no/weatherapi/locationforecast/1.8/documentation
*/
namespace locationforecast
{
class LocationforecastConfiguration;
/**
* A parsed version of a locationforecast document. Its contents may be
* traversed via a random-access iterator. Each of this class' element is an
* object of the class DataElement.
*
* Exactly what parameters to read, and how to read them is defined in the
* configuration file, which is given to the constructors, along with the xml
* document to read.
*/
class Document
{
typedef std::vector<DataElement> DataList;
public:
/**
* Construct document, based on data read from the given stream.
*
* @throw Document::Exception on error when reading document
*
* @param sin A locationforecast document is read from this stream
* @param configuration Path to a configuration file, for defining how to
* read what parameters.
*/
Document(std::istream & sin, LocationforecastConfiguration & configuration);
/**
* Construct document, based on data read from the given URL.
*
* @throw Document::Exception on error when reading document
*
* @param sin A locationforecast document is read from this stream
* @param configuration Path to a configuration file, for defining how to
* read what parameters.
*/
Document(const std::string & url, LocationforecastConfiguration & configuration);
/**
* Construct document, based on data read from the given file.
*
* @throw Document::Exception on error when reading document
*
* @param sin A locationforecast document is read from this stream
* @param configuration Path to a configuration file, for defining how to
* read what parameters.
*/
Document(const boost::filesystem::path & file, LocationforecastConfiguration & configuration);
Document(float longitude, float latitude, LocationforecastConfiguration & configuration);
~Document();
typedef DataList::const_iterator const_iterator;
typedef DataList::value_type value_type;
typedef DataList::size_type size_type;
const_iterator begin() const { return elements_.begin(); }
const_iterator end() const { return elements_.end(); }
const value_type & front() { return elements_.front(); }
size_type size() const { return elements_.size(); }
bool empty() const { return elements_.empty(); }
private:
void parse_(std::istream & s);
void parseFile_(const boost::filesystem::path & file);
void parseUrl_(const std::string & url);
LocationforecastConfiguration & configuration_;
DataList elements_;
};
}
#endif /* DOCUMENT_H_ */
|
0cf8d04d97935eaabc7acf3a4d6d4fec62c86887 | dbe1d5035800c829b2137ffda2259dee17ea1169 | /cppcache_server/src/ctrl/include/task_timer.h | fcf25fcb5668fc5113375d0366196577bdc48d1f | [] | no_license | chwangbjtu/urlcracker | d6fbf911b6026f705ac926e0a6c5dccc1a211902 | 51d6b99d837db45d831f3a2f10a682d42d36e85a | refs/heads/master | 2021-01-24T10:59:23.587133 | 2016-09-27T09:56:53 | 2016-09-27T09:56:53 | 69,342,847 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 237 | h | task_timer.h | #ifndef __TASK_TIMER_H
#define __TASK_TIMER_H
#include "ktimer.h"
class task_timer
{
public:
static task_timer* instance();
~task_timer();
int start();
private:
task_timer();
static task_timer* _inst;
};
#endif//__TASK_TIMER_H
|
54bd472e2e639477158b8da1b841f1adc18692ba | d3ced53dec5358cc9094ac1e14c6a31a94c84400 | /Tsand/Reflection/模板类的分离与实现/方法三/template_compile.h | 769c8a6e21d43a8a3849d7b87b767037c5ceec53 | [] | no_license | AustinDeng/ARTS | 725ed0da2466b8b6ffbafd52cb7a4bc073eca9e2 | 5586122af2cc51865d37bdf85068e055aa27a4e9 | refs/heads/master | 2020-05-09T12:38:07.902720 | 2019-07-04T03:01:55 | 2019-07-04T03:01:55 | 181,118,177 | 0 | 1 | null | 2019-04-15T06:41:06 | 2019-04-13T03:54:42 | null | UTF-8 | C++ | false | false | 104 | h | template_compile.h | template<class T>
class base
{
public:
base() {};
~base() {};
T add_base(T x,T y);
};
|
6d77981921f8d74bbe7eb85475b2c57895b35522 | 30b099e26837d0199138ea21e3f4de6376ca4c95 | /pnga.cpp | ef9193bc180368b9178b215072d51c833fe5f814 | [] | no_license | QtCurve/qtcurve-utils | 1656f18526cbaca54282ecf1679ac729646ba3ff | a2646f3fdf9d20292b42c23e2fc4ea90d5b3bd94 | refs/heads/master | 2021-01-01T15:44:57.379668 | 2011-10-14T21:32:43 | 2011-10-14T21:32:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,202 | cpp | pnga.cpp | /*
* Simple program to convert an RGB image where white=alpha, and black=colour into
* an RGBA image suitable for use by QtC.
*
* Compile with: g++ pnga.cpp -o pnga -I/usr/include/qt3 -lqt-mt
*/
#include <qimage.h>
static void qtc_adjust_pix(unsigned char *data, int numChannels, int w, int h, int stride)
{
int width=w*numChannels,
offset=0,
row;
for(row=0; row<h; ++row)
{
int column;
for(column=0; column<width; column+=numChannels)
{
int alpha=(int)data[offset+column+2];
data[offset+column] = data[offset+column+1] = data[offset+column+2] = 0;
data[offset+column+3] = 255-alpha;
}
offset+=stride;
}
}
int main(int argc, char *argv[])
{
if(2==argc)
{
QString fname(argv[1]);
QImage img(fname);
if (img.depth()<32)
img=img.convertDepth(32);
img.setAlphaBuffer(true);
qtc_adjust_pix(img.bits(), 4, img.width(), img.height(), img.bytesPerLine());
int pos=fname.findRev('.');
img.save(fname.left(pos)+"_a.png", "PNG");
}
else
printf("Usage: %s <img file>\n", argv[0]);
return 0;
}
|
b6b8a6472e4b2f621d7575c9b815f9261679adf3 | 27e78587d92a6b010fde8faa4110efec83c7861c | /finalists/Pol/challenge_16/p16.cc | 23d2141461fbc06636330410bc94dcd23cd6b737 | [] | no_license | magmax/programming-challenge-2 | 85f8916812af77bde3895b175a261041d279ff4b | 62e8fd0d2d2b3a149d6d5c0a0364db366df85525 | refs/heads/master | 2020-12-24T21:44:57.840107 | 2013-02-15T15:48:41 | 2013-02-15T15:48:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,649 | cc | p16.cc | #include <cmath>
#include <iostream>
#include <vector>
using namespace std;
// Let's consider each vector of calls as an n-dimensional vector in the space.
// We can calculate the angle between 2 vectors in order to determine how "similar" they are. The closer
// the angle is, the more similar the vectors are.
// Given an unknown vector, if the most similar one to it among the known vectors is SAFE, then we conclude
// the unkown vector is SAFE, and the same with MALWARE.
typedef long double ld;
typedef long long ll;
typedef vector<ll> Vi;
typedef vector<Vi> Mi;
typedef vector<ld> Vd;
typedef vector<Vd> Md;
typedef vector<char> Vc;
void normalize(Vd& v) {
int n = v.size();
ld m = 0;
for (int i = 0; i < n; ++i) m += v[i]*v[i];
m = sqrt(m);
for (int i = 0; i < n; ++i) v[i] /= m;
}
int main() {
int R, U, N;
cin >> R >> U >> N;
Vc type(R);
Mi vect(R, Vi(N));
Md norm(R, Vd(N));
for (int i = 0; i < R; ++i) {
cin >> type[i];
for (int j = 0; j < N; ++j) cin >> vect[i][j];
for (int j = 0; j < N; ++j) norm[i][j] = vect[i][j];
normalize(norm[i]);
}
ll res = 0;
for (int i = 0; i < U; ++i) {
Vi vec(N);
for (int j = 0; j < N; ++j) cin >> vec[j];
Vd nor(N);
for (int j = 0; j < N; ++j) nor[j] = vec[j];
normalize(nor);
ld maxi = -1;
char what = 'S';
for (int j = 0; j < R; ++j) {
ld t = 0;
for (int k = 0; k < N; ++k)
t += norm[j][k]*nor[k];
if (t > maxi) {
maxi = t;
what = type[j];
}
}
if (what == 'M') {
for (int j = 0; j < N; ++j) res += vec[j];
}
}
cout << res << endl;
}
|
d977483bd714a7d2fd7b830f63932300b3819218 | b78cdfafc87968a4908b2fb6f561ad00315aa61b | /test_class.cpp | d480f9bd2767287a0cb098be55260016c370bced | [] | no_license | bigpotato920/algorithm | b04e869be33fd2725572d50179cc7a957a18c3a4 | 913207d2c2417b2f2be2c5c9624ed12245704349 | refs/heads/master | 2020-05-16T23:03:10.395816 | 2014-06-05T00:45:21 | 2014-06-05T00:45:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 154 | cpp | test_class.cpp | #include <iostream>
class A
{
public:
A *next;
void func();
};
int main(int argc, const char *argv[])
{
A a,b;
return 0;
}
|
ffd93009ee0f48d04a99d3a5ea53e33f47f7cc7a | 265b0dca9924715a567a8b6adea0b2b8e2e98553 | /serial-receive-data/serial-receive-data.ino | f0a95428c41fb0f33bc35754c836acbcd8ab10bf | [
"MIT"
] | permissive | yohanes-erwin/esp8266-arduino | f00752fd32eded97a9ff84f89e8b39294629fa06 | 9bc96a4c775fc93a5b538479bfd1422bc7df6b18 | refs/heads/master | 2020-04-03T01:11:06.712793 | 2020-02-22T11:34:12 | 2020-02-22T11:34:12 | 154,923,008 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 511 | ino | serial-receive-data.ino | // *** File : /esp8266-arduino/serial-receive-data/
// serial-receive-data.ino
// *** Author : Erwin Ouyang
// *** Date : 17 Agt 2018
String serialInput;
void setup()
{
// Setup serial communication
Serial.begin(74880);
}
void loop()
{
// If there is data in receive buffer
if (Serial.available() > 0)
{
// Read string from receive buffer
serialInput = Serial.readString();
// Print to serial monitor
Serial.println(serialInput);
}
}
|
745285c5921ed5bc11d190cfa3326835f0d4334e | 53360319eaf69ff75f34e1c2c45cbcdfd12842c9 | /groups/bdl/bdlb/bdlb_randomdevice.t.cpp | 69dcc842f4d13f66f70a9f52b543afede06c5830 | [
"Apache-2.0"
] | permissive | bloomberg/bde | 229de23237d9cc0937ec2d0b69ef7dfcb1fa2154 | 7cc8e30c7218eaffbc31f518bd40794cc79f7282 | refs/heads/main | 2023-09-01T08:52:24.600136 | 2023-08-31T17:43:40 | 2023-08-31T17:43:40 | 6,619,178 | 1,429 | 338 | Apache-2.0 | 2023-05-20T13:33:26 | 2012-11-09T20:00:30 | C++ | UTF-8 | C++ | false | false | 24,348 | cpp | bdlb_randomdevice.t.cpp | // bdlb_randomdevice.t.cpp -*-C++-*-
#include <bdlb_randomdevice.h>
// Note the headers are in non-standard order. This was required to silence an
// error from clang 3.4.
//..
// /usr/include/unistd.h:449:12: error: declaration conflicts with target of
// using declaration already in scope
// extern int rename(const char *, const char *);
//..
// This is an acknowledged issue:
// <http://lists.cs.uiuc.edu/pipermail/llvmbugs/2012-May/023328.html>
#include <bslim_testutil.h>
#include <bsls_platform.h>
#include <bsls_stopwatch.h> // for benchmarking only
#if defined(BSLS_PLATFORM_OS_WINDOWS)
#include <windows.h> // 'Sleep'
#else
#include <unistd.h> // 'usleep'
#endif
#include <bsl_cstdio.h>
#include <bsl_iostream.h>
#include <bsl_vector.h> // for usage example
#include <bsl_string.h>
using namespace BloombergLP;
using namespace bsl;
// ============================================================================
// TEST PLAN
// ----------------------------------------------------------------------------
// Overview
// --------
// ----------------------------------------------------------------------------
// CLASS METHODS
// [-1] static int getRandomBytes(unsigned char *buf, size_t numB);
// [ 2] static int getRandomBytesNonBlocking(buf, numB);
// ----------------------------------------------------------------------------
// [ 1] BREATHING TEST
// [-2] PERFORMANCE: 'getRandomBytes'
// [-3] PERFORMANCE: 'getRandomBytesNonBlocking'
// [-4] PERFORMANCE: 'getRandomBytes'
// [-5] PERFORMANCE: 'getRandomBytes'
// [ 3] USAGE EXAMPLE
// ============================================================================
// STANDARD BDE ASSERT TEST FUNCTION
// ----------------------------------------------------------------------------
namespace {
int testStatus = 0;
void aSsErT(bool condition, const char *message, int line)
{
if (condition) {
printf("Error " __FILE__ "(%d): %s (failed)\n", line, message);
if (0 <= testStatus && testStatus <= 100) {
++testStatus;
}
}
}
} // close unnamed namespace
// ============================================================================
// STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT BSLIM_TESTUTIL_ASSERT
#define ASSERTV BSLIM_TESTUTIL_ASSERTV
#define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT
#define Q BSLIM_TESTUTIL_Q // Quote identifier literally.
#define P BSLIM_TESTUTIL_P // Print identifier and value.
#define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLIM_TESTUTIL_L_ // current Line number
// ============================================================================
// NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)
#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)
#define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR)
#define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)
#define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)
#define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)
//=============================================================================
// GLOBAL TYPEDEFS FOR TESTING
//-----------------------------------------------------------------------------
typedef bdlb::RandomDevice Util;
#if defined(BSLS_PLATFORM_OS_WINDOWS)
#define sleep(x) Sleep((x))
#else
#define sleep(x) usleep((x) * 100)
#endif
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
bool verbose = argc > 2;
bool veryVerbose = argc > 3;
cout << "TEST " << __FILE__ << " CASE " << test << endl;
switch (test) { case 0:
case 3: {
// --------------------------------------------------------------------
// USAGE EXAMPLE TEST
//
// Concerns:
// The usage example provided in the component header file must
// compile, link, and run on all platforms as shown.
//
// Plan:
// Incorporate usage example from header into driver, remove leading
// comment characters, and replace 'assert' with 'ASSERT'.
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) cout << endl << "USAGE EXAMPLE TEST" << endl
<< "==================" << endl;
///Usage
///-----
// This section illustrates intended use of this component.
//..
///Example 1: Seeding the Random-Number Generator
/// - - - - - - - - - - - - - - - - - - - - - - -
// System-provided random-number generators generally must be initialized with
// a seed value from which they go on to produce their stream of pseudo-random
// numbers. We can use 'RandomDevice' to provide such a seed.
//
// First, we obtain the results of invoking the random-number generator without
// having seeded it:
//..
int unseededR1 = rand();
int unseededR2 = rand();
//..
// Then, we obtain a random number:
//..
int seed = 0;
int status = bdlb::RandomDevice::getRandomBytes(
reinterpret_cast<unsigned char *>(&seed), sizeof(seed));
ASSERT(0 == status);
ASSERT(0 != seed); // This will fail every few billion attempts...
//..
// Next, we seed the random-number generator with our seed:
//..
srand(seed);
//..
// Finally, we observe that we obtain different numbers:
//..
ASSERT(unseededR1 != rand());
ASSERT(unseededR2 != rand());
//..
} break;
case 2: {
// --------------------------------------------------------------------
// 'int getRandomBytesNonBlocking(buf, numB)' TEST
//
// Concerns:
//: 1 If a number is passed, that many bytes are set.
//: 2 The random bytes are distributed uniformly (probabilistic).
//
// Plan:
//: 1 Request a large pool and random bytes from non-blocking random
//: number generator. Verify that each is unique. Verify that the
//: numbers approximate a uniform distribution.
//
// Testing:
// static int getRandomBytesNonBlocking(buf, numB);
// --------------------------------------------------------------------
const int NUM_ITERATIONS = 25;
const int NUM_TRIALS = 10;
int cnt = 0;
unsigned char buffer[NUM_ITERATIONS * 4] = { };
unsigned char or_buffer[NUM_ITERATIONS * 4] = { };
unsigned char and_buffer[NUM_ITERATIONS * 4] = { };
const unsigned NUM_BYTES = sizeof buffer;
if (verbose)
cout << endl
<< "'int getRandomBytesNonBlocking(buf, numB)' TEST" << endl
<< "===============================================" << endl;
// 1) If a number is passed, that many bytes are set.
if (veryVerbose) {
cout << "\nTesting the number of bytes set." << endl;
}
for (unsigned i = 0; i < 5; ++i) {
memset(buffer, 0, NUM_BYTES);
memset(or_buffer, 0, NUM_BYTES);
memset(and_buffer, 0xf, NUM_BYTES);
// Repeat the accession of random bytes 'NUM_TRIALS' times to
// prevent false negatives
for (int j = 0; j < NUM_TRIALS; ++j) {
if (veryVerbose) { P(j) }
ASSERT(0 == Util::getRandomBytesNonBlocking(buffer, i));
// '|' and '&' the bytes
for (unsigned k = 0; k < i; ++k) {
or_buffer[k] |= buffer[k];
and_buffer[k] &= buffer[k];
}
}
// Check that the bytes set are non-zero and non-0xf. Since
// 'NUM_TRIALS > 4', the is less than a 2^(-32) chance of these
// tests failing due to randomness. They are much more likely to
// fail on '1 == i' than later.
if (0 < i) {
int or_sum = 0, and_sum = 0;
for (unsigned j = 0; j < i; ++j) {
or_sum += or_buffer[j];
and_sum += ~and_buffer[j];
}
LOOP2_ASSERT(i, or_sum, 0 != or_sum);
LOOP2_ASSERT(i, and_sum, 0 != and_sum);
}
// check that remaining bytes are still unset.
for (unsigned j = i; j < NUM_BYTES; ++j) {
LOOP3_ASSERT(i, j, int(buffer[j]), 0 == buffer[j]);
}
}
if (veryVerbose) {
cout << "\nTesting the distribution of rand." << endl;
}
// 3) The random bytes are uniformly distributed (probabilistic)
int numbers[NUM_ITERATIONS] = { };
for (int i = 0; i< NUM_ITERATIONS; ++i) {
int rand;
if (veryVerbose) { P(i) }
ASSERT(0 == Util::getRandomBytesNonBlocking(
reinterpret_cast<unsigned char *>(&rand),
sizeof rand));
numbers[i] = rand;
if (veryVerbose) { P_(i) P(rand) }
for (int j = 0; j < i; ++j) {
ASSERT(numbers[j] != rand);
if (veryVerbose) { P_(j) P(numbers[j]) }
}
for (int b = 0; b < 15; ++b) {
cnt += rand & 1;
rand >>= 1;
if (veryVerbose) { P(cnt) }
}
}
double expected = (NUM_ITERATIONS * 15) / 2;
ASSERT(cnt < (expected * 1.3));
ASSERT(cnt > (expected * 0.7));
} break;
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST
//
// Concerns:
// Exercise a broad cross-section of the mechanism of reading random
// numbers from the system. Probe that functionality systematically
// and incrementally to discover basic errors in isolation.
//
// Plan:
// Request a large pool of random 'ints' from each of the system's
// random number generators. Verify the uniqueness, and the
// distribution.
//
// Testing:
// BREATHING TEST
// --------------------------------------------------------------------
const int NUM_ITERATIONS = 8;
if (verbose) cout << endl
<< "BREATHING TEST" << endl
<< "==============" << endl;
int rand;
int numbers [NUM_ITERATIONS];
// fill buffer with random bytes
for (int i = 0; i < NUM_ITERATIONS; ++i) {
unsigned char *p = reinterpret_cast<unsigned char *>(&rand);
ASSERT(0 == Util::getRandomBytes(p, sizeof rand));
numbers[i] = rand;
if (veryVerbose) { P_(i) P(rand) }
}
// verify uniqueness
for (int i = 0; i < NUM_ITERATIONS; ++i) {
for (int j = i + 1; j < NUM_ITERATIONS; ++j) {
LOOP2_ASSERT(i, j, numbers[i] != numbers[j]);
}
}
} break;
case -1: {
// --------------------------------------------------------------------
// 'int getRandomBytes(void *buf, int numBytes) TEST'
//
// Concerns:
// 1) If a number is passed, that many bytes are set.
// 2) The random bytes are distributed uniform (probabilistic)
//
// Plan:
// Request a large pool and random bytes from non-blocking random
// number generator. Verify that each is unique. Verify that the
// numbers approximate a uniform distribution.
//
// Testing:
// static int getRandomBytes(unsigned char *buf, size_t numB);
// --------------------------------------------------------------------
const int NUM_ITERATIONS = 25;
int cnt = 0;
int numbers[NUM_ITERATIONS] = { };
const unsigned NUM_BYTES = sizeof numbers;
if (verbose)
cout << endl
<< "'int getRandomBytes(void *buf, int numBytes) TEST'"
<< endl
<< "=================================================="
<< endl;
if (veryVerbose) {
cout << "\nTesting the number of bytes set." << endl;
}
// 2) If a number is passed, that many bytes are set.
for (unsigned i = 0; i < 5; ++i) {
unsigned j;
unsigned char *p = reinterpret_cast<unsigned char *>(numbers);
memset(numbers, 0, NUM_BYTES);
if (veryVerbose) { P(i) }
ASSERT(0 == Util::getRandomBytesNonBlocking(p, i));
for (j = 0; j < i; ++j) {
LOOP3_ASSERT(i, j, p[j], 0 != p[j]);
}
for (; j < NUM_BYTES; ++j) {
LOOP3_ASSERT(i, j, p[j], 0 == p[j]);
}
}
if (veryVerbose) {
cout << "\nTesting the distribution of rand." << endl;
}
// 3) The random bytes are distributed uniform (probabilistic)
for (int i = 0; i < NUM_ITERATIONS; ++i) {
int rand_int = 0;
unsigned char *p1 = reinterpret_cast<unsigned char *>(&rand_int);
if (veryVerbose) { P(i); }
ASSERT(0 == Util::getRandomBytesNonBlocking(p1, sizeof rand_int));
numbers[i] = rand_int;
for (int j = 0; j < i; ++j) {
LOOP5_ASSERT(i, j, rand_int, numbers[i], numbers[j],
numbers[j] != numbers[i]);
}
for (int b = 0; b < 15; ++b) {
cnt += rand_int & 1;
rand_int >>= 1;
if (veryVerbose) { P(cnt) }
}
}
double expected = (NUM_ITERATIONS * 15) / 2;
ASSERT(cnt < (expected * 1.2));
ASSERT(cnt > (expected * 0.8));
} break;
case -2: {
// --------------------------------------------------------------------
// PERFORMANCE: 'getRandomBytes'
//
// Concerns:
// Measure the effect of requesting larger random numbers per
// request from the blocking random generator.
//
// Plan:
// Request a large number of random numbers to consume the entropy
// on process start-up. Next, request the same total number of
// bytes, each time changing the size of the request, measure the
// time to complete each request.
//
// Testing:
// PERFORMANCE: 'getRandomBytes'
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "PERFORMANCE: 'getRandomBytes'" << endl
<< "=============================" << endl;
bsls::Stopwatch s;
const int NUM_ITERATIONS = 4;
const int MAX_GRANUALARITY = 1 << NUM_ITERATIONS;
unsigned char buffer[MAX_GRANUALARITY] = { };
unsigned char prev_buffer[MAX_GRANUALARITY] = { };
for (int granularity = 1;
granularity < MAX_GRANUALARITY;
granularity <<= 1) {
memcpy(prev_buffer, buffer, MAX_GRANUALARITY);
s.start(true);
int i;
for (i = 0; i <= MAX_GRANUALARITY; i += granularity) {
if (veryVerbose) { P(i) }
ASSERT(0 == Util::getRandomBytes(buffer + granularity,
granularity));
}
s.stop();
LOOP2_ASSERT(granularity,
i,
0 != memcmp(buffer, prev_buffer, MAX_GRANUALARITY));
double time = s.accumulatedUserTime() + s.accumulatedSystemTime() +
s.accumulatedWallTime();
P_(granularity) P(time);
s.reset();
}
} break;
case -3: {
// --------------------------------------------------------------------
// PERFORMANCE: 'getRandomBytesNonBlocking'
//
// Concerns:
// Measure the effect of requesting larger random numbers per
// request from the non-blocking random generator.
//
// Plan:
// Request a large number of random numbers to consume the entropy
// on process start-up. Next, request the same total number of
// bytes, each time changing the size of the request, measure the
// time to complete each request.
//
// Testing:
// PERFORMANCE: 'getRandomBytesNonBlocking'
//---------------------------------------------------------------------
if (verbose)
cout << endl
<< "PERFORMANCE: 'getRandomBytesNonBlocking'" << endl
<< "========================================" << endl;
int rand_int;
for (int i = 0; i < 15; ++i) {
if (veryVerbose) { P(i) }
ASSERT(0 == Util::getRandomBytesNonBlocking(
reinterpret_cast<unsigned char *>(&rand_int),
sizeof rand_int));
}
bsls::Stopwatch s;
const int NUM_ITERATIONS = 4;
const int MAX_GRANUALARITY = 1 << NUM_ITERATIONS;
unsigned char buffer [MAX_GRANUALARITY] = { };
unsigned char prev_buffer[MAX_GRANUALARITY] = { };
for (int granularity = 1;
granularity < MAX_GRANUALARITY;
granularity <<= 1) {
memcpy(prev_buffer, buffer, MAX_GRANUALARITY);
s.start(true);
int i;
for (i = 0; i <= MAX_GRANUALARITY; i += granularity) {
if (veryVerbose) { P(i) }
ASSERT(0 == Util::getRandomBytesNonBlocking(
buffer + granularity,
granularity));
}
s.stop();
LOOP2_ASSERT(granularity,
i,
0 != memcmp(buffer, prev_buffer, MAX_GRANUALARITY));
double time = s.accumulatedUserTime() + s.accumulatedSystemTime() +
s.accumulatedWallTime();
if (veryVerbose) { P_(granularity) P(time) }
s.reset();
}
} break;
case -4: {
// --------------------------------------------------------------------
// PERFORMANCE: 'getRandomBytes'
//
// Concerns:
// Measure the amount of time necessary to wait between successive
// request for random 'int'(s).
//
// Plan:
// Request a large number of random numbers to empty out the entropy
// source. Next request a random number and vary the delay before
// requesting another random number, each time measuring the time
// required to receive the next random number.
//
// Testing:
// PERFORMANCE: 'getRandomBytes'
//---------------------------------------------------------------------
if (verbose) cout << "PERFORMANCE: 'getRandomBytes'"
<< "=============================" << endl;
bsls::Stopwatch s;
const int MAX_SLEEP = 10;
int rand_int;
unsigned char *p1 = reinterpret_cast<unsigned char *>(&rand_int);
for (int i = 0; i < 15; ++i) {
if (veryVerbose) { P(i) }
ASSERT(0 == Util::getRandomBytes(p1, sizeof rand_int));
}
for (unsigned curr_sleep = 0; curr_sleep <= MAX_SLEEP; ++curr_sleep) {
if (veryVerbose) { P(curr_sleep) }
ASSERT(0 == Util::getRandomBytes(p1, sizeof rand_int));
sleep(curr_sleep);
s.start(true);
if (veryVerbose) { P(curr_sleep) }
ASSERT(0 == Util::getRandomBytes(p1, sizeof rand_int));
s.stop();
double time = s.accumulatedUserTime() + s.accumulatedSystemTime() +
s.accumulatedWallTime();
s.reset();
if (veryVerbose) {
cout << "Current Delay : " << curr_sleep
<< " ms" << endl
<< "Time to get next number: " << time * 100
<< " ms" << endl
<< "-------------------------" << endl << endl;
}
}
} break;
case -5: {
// --------------------------------------------------------------------
// PERFORMANCE: 'getRandomBytes'
//
// Concerns:
// Measure the amount of time required to acquire 'NUM_ITERATIONS'
// 'int'(s).
//
// Plan:
// Call 'RandomDevice::getRandomBytes' 'NUM_ITERATIONS' times, each
// time
// requesting a 'int'.
//
// Testing:
// PERFORMANCE: 'getRandomBytes'
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "PERFORMANCE: 'getRandomBytes'" << endl
<< "=============================" << endl;
bsls::Stopwatch s;
const int NUM_ITERATIONS = 15;
int rand_int;
unsigned char *p1 = reinterpret_cast<unsigned char *>(&rand_int);
s.start(true);
for (int i = 0; i < NUM_ITERATIONS; ++i) {
if (veryVerbose) { P(i) }
ASSERT(0 == Util::getRandomBytes(p1, sizeof rand_int));
}
s.stop();
double time = s.accumulatedUserTime() + s.accumulatedSystemTime() +
s.accumulatedWallTime();
s.reset();
if (verbose) {
cout << "Time to aquire " << NUM_ITERATIONS << " random ints: "
<< time << endl;
}
} break;
default: {
cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl;
testStatus = -1;
} break;
}
if (testStatus > 0) {
cerr << "Error, non-zero test status = " << testStatus << "." << endl;
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2014 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
|
f44aca4fbfe456950e7c978055e281106157c80d | 81e3c23c55a2197554baaf0a795eb15305586e83 | /src/SRECORD.CPP | a2ba09e300b4da6d2d1a32805e983b47909503bb | [] | no_license | palazzol/winwhyp | 7be21eb0805a0e5b60609f8497c7a1d9dfad7a7a | 7d108027d29f8600a3834699f56867d6d3d66f1d | refs/heads/main | 2023-09-01T06:20:41.402739 | 2021-10-30T02:26:20 | 2021-10-30T02:26:20 | 422,339,239 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,063 | cpp | SRECORD.CPP | // srecord.cpp
// member functions for s-record files
// Written by Richard E. Haskell -- February 1995
#include <stdio.h>
#include "srecord.h"
// s-record member functions
void srecord::make_srecord_file(FILE * filename, char* vseg,
int ix_start, int ix_end, int dest_addr)
{
int num_bytes, num_lines, i;
num_bytes = ix_end - ix_start + 1;
num_lines = (num_bytes + 31)/32;
for(i = 0; i < num_lines; i++)
send_32bytes(filename, vseg, ix_start, i, dest_addr);
send_s9_line(filename);
}
void srecord::send_32bytes(FILE * filename,
char* vseg, int start, int i, int dest_addr)
{
int j;
checksum = 0;
fprintf(filename, "%c", 'S'); // send S
fprintf(filename, "%c", '1'); // send 1
send_ascii_byte(filename, 35); // send #bytes
send_ascii_word(filename, dest_addr + i*32); // send addr
for(j = 0; j < 32; j++)
send_ascii_byte(filename, vseg[start + i*32 + j]); // send data
send_ascii_byte(filename, ~checksum);
fprintf(filename, "\n");
}
void srecord::send_s9_line(FILE * filename)
{
checksum = 0;
fprintf(filename, "%c", 'S'); // send S
fprintf(filename, "%c", '9'); // send 9
send_ascii_byte(filename, 3); // send #bytes
send_ascii_word(filename, 0); // send addr
send_ascii_byte(filename, ~checksum); // send checksum
fprintf(filename, "\n\n");
}
int srecord::hex2asc(int n)
{
if(n > 9) // if n > 9
n += 0x37; // add 37H
else
n += 0x30; // else add 30H
return n;
}
void srecord::send_ascii_byte(FILE * filename, int n)
{
int hi_nibble, lo_nibble;
checksum += n; // add to checksum
hi_nibble = (n >> 4) & 0x0f;
fprintf(filename, "%c", hex2asc(hi_nibble)); // send hi_nibble
lo_nibble = n & 0x0f;
fprintf(filename, "%c", hex2asc(lo_nibble)); // send lo_nibble
}
void srecord::send_ascii_word(FILE * filename, int n)
{
int hi_byte, lo_byte;
hi_byte = (n >> 8) & 0xff;
send_ascii_byte(filename, hi_byte);
lo_byte = n & 0xff;
send_ascii_byte(filename, lo_byte);
}
|
ad09d88f17be6c6d742ce4e20cf0067697eda533 | 21583026a7c1de0e443e09f1b7575010714c9144 | /include/engine/Physics/Emitter/VolumeParticleEmitter3.h | 3b11cfe733518722f1f8048d755789ce60b17d6d | [
"MIT"
] | permissive | nocis/Physzy | 23c7c7b6a3ba6fc7aaf88e7d010606d3180dd21c | 0421aa35ca5611c85b0e4ad1679bb161b57a555b | refs/heads/master | 2022-12-17T02:14:34.951330 | 2020-09-22T09:52:28 | 2020-09-22T09:52:59 | 294,249,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,060 | h | VolumeParticleEmitter3.h | //
// Created by jared on 9/19/20.
//
#ifndef PHYSZY_VOLUMEPARTICLEEMITTER3_H
#define PHYSZY_VOLUMEPARTICLEEMITTER3_H
#include "Physics/Emitter/ParticleEmitter3.h"
#include "Physics/PointGenerator/PointGenerator3.h"
#include "Physics/Surface/ImplicitSurface3.h"
#include <random>
namespace PHYSZY
{
class VolumeParticleEmitter3 final : public ParticleEmitter3
{
public:
class Builder;
static Builder GetBuilder();
VolumeParticleEmitter3(
const ImplicitSurface3Ptr& implicitSurface,
const BoundingBox3D& maxRegion, double spacing,
const Vector3D& initialVel = Vector3D(),
const Vector3D& linearVel = Vector3D(),
const Vector3D& angularVel = Vector3D(),
size_t maxNumberOfParticles = std::numeric_limits<size_t>::max(),
double jitter = 0.0, bool isOneShot = true,
bool allowOverlapping = false, uint32_t seed = 0);
virtual void test(){std::cout<<"VolumeParticleEmitter3"<<std::endl;}
private:
std::mt19937 _rng;
ImplicitSurface3Ptr _implicitSurface;
BoundingBox3D _maxRegion;
double _spacing;
Vector3D _initialVel;
Vector3D _linearVel;
Vector3D _angularVel;
PointGenerator3Ptr _pointsGen;
size_t _maxNumberOfParticles = std::numeric_limits<size_t>::max();
size_t _numberOfEmittedParticles = 0;
double _jitter = 0.0;
bool _isOneShot = true;
bool _allowOverlapping = false;
};
using VolumeParticleEmitter3Ptr = std::shared_ptr<VolumeParticleEmitter3>;
class VolumeParticleEmitter3::Builder final
{
public:
Builder& WithImplicitSurface(const ImplicitSurface3Ptr& implicitSurface);
//Builder& WithSurface(const Surface3Ptr& surface);
Builder& WithMaxRegion(const BoundingBox3D& maxRegion);
Builder& WithSpacing(double spacing);
//Builder& WithInitialVelocity(const Vector3D& initialVel);
//Builder& WithLinearVelocity(const Vector3D& linearVel);
//Builder& WithAngularVelocity(const Vector3D& angularVel);
//Builder& WithMaxNumberOfParticles(size_t maxNumberOfParticles);
//Builder& WithJitter(double jitter);
Builder& WithIsOneShot(bool isOneShot);
//Builder& WithAllowOverlapping(bool allowOverlapping);
Builder& WithRandomSeed(uint32_t seed);
VolumeParticleEmitter3 Build() const;
VolumeParticleEmitter3Ptr BuildMakeShared() const;
private:
ImplicitSurface3Ptr _implicitSurface;
bool _isBoundSet = false;
BoundingBox3D _maxRegion;
double _spacing = 0.1;
Vector3D _initialVel;
Vector3D _linearVel;
Vector3D _angularVel;
size_t _maxNumberOfParticles = std::numeric_limits<size_t>::max();
double _jitter = 0.0;
bool _isOneShot = true;
bool _allowOverlapping = false;
uint32_t _seed = 0;
};
}
#endif //PHYSZY_VOLUMEPARTICLEEMITTER3_H
|
fe9411b9cd4b3ab7f379a9622dacabc85cc90710 | 6a3ef9ad54bfc65a675a9a690f4a6439b9b11a57 | /src/hybrid_astar/nodes/ha_node.cpp | b24e88ee9dbba4b84de5c96c1851ef6ce7785206 | [] | no_license | TravisZhang/HybridAstar | 7f1a108987f7d8d923eecc724ff7aeed9de770c9 | da144e2e1486fd843a9829650ec2e36d24e44bb6 | refs/heads/master | 2022-11-22T20:37:14.473237 | 2020-07-27T03:24:42 | 2020-07-27T03:24:42 | 282,785,012 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,287 | cpp | ha_node.cpp | #include "ha_node.h"
namespace ha
{
Ha_node::Ha_node()
{
initialize();
}
void Ha_node::initialize(void)
{
particlecloud_pub_ = nh.advertise<geometry_msgs::PoseArray>("particlecloud", 1, true);
global_map_pub_ = nh.advertise<nav_msgs::OccupancyGrid>("gridmap", 1,true);
// ha_map.mapRequest();
path = ros::package::getPath("hybrid_astar");
ROS_INFO("Package path: %s\n",path.c_str());
obs_path = path+"/maps/map.png";
ha_map.mapFromPic(obs_path);
pub_obs_map = *(ha_map.pub_obs_map_ptr);
GRID_RES = ha_map.global_map->size_x/GX;
ROS_INFO("GRID_RES : %d\n",GRID_RES);
if(ha_map.global_map)
{
// start_pose.v[0] = 0 + (ha_map.global_map->size_x / 2) * ha_map.global_map->scale;
// start_pose.v[1] = 0 + (ha_map.global_map->size_y / 2) * ha_map.global_map->scale;
// start_pose.v[2] = 0;
// end_pose.v[0] = 3.2 + (ha_map.global_map->size_x / 2) * ha_map.global_map->scale;
// end_pose.v[1] = -3.6 + (ha_map.global_map->size_y / 2) * ha_map.global_map->scale;
// end_pose.v[2] = -65;
// coords in normal frame(y up x right)
start_pose.v[0] = 700 ;
start_pose.v[1] = 699 ; //100
start_pose.v[2] = 225; //135
end_pose.v[0] = 100 ;
end_pose.v[1] = 199 ; //600
end_pose.v[2] = 270; //90
}
ROS_INFO("start_pose: %.3f, %.3f, %.3f\n",start_pose.v[0],start_pose.v[1],start_pose.v[2]);
ROS_INFO("end_pose : %.3f, %.3f, %.3f\n",end_pose.v[0],end_pose.v[1],end_pose.v[2]);
// std::vector<Pose_vector> next_pose;
// next_pose = start_pose.getNextPose();
}
void Ha_node::process(void)
{
ros::Rate loop_rate(loop_freq);
while(nh.ok())
{
ROS_INFO("222");
ros::spinOnce();
hybridAstar();
particlecloud_publisher(particlecloud_pub_, final_path);
// particlecloud_publisher(particlecloud_pub_, current_set);
global_map_pub_.publish(pub_obs_map);
ROS_INFO("publish global map done!!!\n");
loop_rate.sleep();
break;
}
// ha_map.free_map(3);
}
void Ha_node::hybridAstar(void)
{
ROS_INFO("Begin obstacle update >>>>>>>>>>\n");
ha_map.obsUpdate();
ROS_INFO("Finish obstacle update >>>>>>>>>>\n");
ROS_INFO("Begin costmap init >>>>>>>>>>\n");
ha_map.cost_map_init();
ROS_INFO("Finish costmap init >>>>>>>>>>\n");
ROS_INFO("Begin costmap update >>>>>>>>>>\n");
ha_map.runAstar( start_pose, end_pose);
ROS_INFO("Finish costmap update >>>>>>>>>>\n");
global_cost_map = ha_map.cost_map;
global_obs_map = ha_map.global_map;
// global_cost_map(ha_map.cost_map);
// //display the cost map
Mat dist1(ha_map.cost_map->size_x, ha_map.cost_map->size_y, CV_8UC3, Scalar(255, 255, 255)); //CV_8UC3:8 Units 3 Channel Matrix
for(int j=0;j<ha_map.cost_map->size_y;j++)
for(int i=0;i<ha_map.cost_map->size_x;i++)
{
int index_temp = i + j * ha_map.cost_map->size_x;
int cost2d = int(ha_map.cost_map->cells[index_temp].cost);
if(cost2d > 9999) cost2d = 510;
dist1.at<Vec3b>((ha_map.cost_map->size_y-j-1),i)={255-0.5*cost2d, 255-0.5*cost2d, 255-0.5*cost2d};
}
// resize(dist1, dist1, Size(400, 400));
//uncomment to check if dijkstra ran properly
imshow("cost2d", dist1);
waitKey(0);
std::cout << "yyy" << std::endl;
std::priority_queue<Pose_vector, std::vector<Pose_vector>, cmp1> poseset;
start_pose.cost3d = 0;
std::cout << "xxx" << std::endl;
// vis = new int**[GX];
// for(int i = 0;i < GX;++i)
// {
// vis[i] = new int*[GY];
// for(int j = 0;j < GY;++j)
// {
// vis[i][j] = new int[THETA];
// // for(int k = 0;k < THETA;++k)
// // {
// // vis[i][j][k] = 0;
// // }
// }
// }
// memset(vis, 0, sizeof(int)*GX*GY*THETA);
vis.clear();
vis.resize(GX);
for(int i = 0;i < GX;++i)
{
vis[i].resize(GY);
for(int j = 0;j < GY;++j)
{
vis[i][j].resize(THETA,0);
}
}
// previous_set.clear();
// previous_set.resize(GX);
// for(int i = 0;i < GX;++i)
// {
// previous_set[i].resize(GY);
// for(int j = 0;j < GY;++j)
// {
// previous_set[i][j].resize(THETA);
// }
// }
Pose_vector current;
std::vector<Pose_vector> nextset;
current_set.clear();
// std::cout << "aaa" << std::endl;
// start_pose.gx = int((start_pose.v[0] - ha_map.global_map->origin_x) / GRID_RES);
// start_pose.gy = int((start_pose.v[1] - ha_map.global_map->origin_x) / GRID_RES);
start_pose.gx = int((start_pose.v[0] - ha_map.global_map->origin_x) / ha_map.global_map->scale / ha_map.global_map->size_x * GX );
start_pose.gy = int((start_pose.v[1] - ha_map.global_map->origin_x) / ha_map.global_map->scale / ha_map.global_map->size_y * GY );
start_pose.gtheta = int(start_pose.v[2]/THETA_RES);
while(start_pose.gtheta < 0)
{
start_pose.gtheta += THETA;
}
while(start_pose.gtheta > THETA)
{
start_pose.gtheta -= THETA;
}
start_pose.start_flag = 1;
// std::cout << "bbb" << std::endl;
// end_pose.gx = int((end_pose.v[0] - ha_map.global_map->origin_x) / GRID_RES);
// end_pose.gy = int((end_pose.v[1] - ha_map.global_map->origin_x) / GRID_RES);
end_pose.gx = int((end_pose.v[0] - ha_map.global_map->origin_x) / ha_map.global_map->scale / ha_map.global_map->size_x * GX );
end_pose.gy = int((end_pose.v[1] - ha_map.global_map->origin_x) / ha_map.global_map->scale / ha_map.global_map->size_y * GY );
end_pose.gtheta = int(end_pose.v[2]/THETA_RES);
while(end_pose.gtheta < 0)
{
end_pose.gtheta += THETA;
}
while(end_pose.gtheta > THETA)
{
end_pose.gtheta -= THETA;
}
ROS_INFO("start_pose g: %d, %d, %d\n",start_pose.gx,start_pose.gy,start_pose.gtheta);
ROS_INFO("end_pose g: %d, %d, %d\n",end_pose.gx,end_pose.gy,end_pose.gtheta);
// std::cout << "ccc" << std::endl;
poseset.push(start_pose);
int iter = 0;
ROS_WARN("Enter main loop >>>>>>>>>>>>>>>>>>>>>\n");
while(!poseset.empty())
{
ROS_INFO("************ iter : %d *************\n",iter);
current = poseset.top();
poseset.pop();
ROS_INFO("current g: %d, %d, %d\n",current.gx,current.gy,current.gtheta);
ROS_INFO("target g: %d, %d, %d\n",end_pose.gx,end_pose.gy,end_pose.gtheta);
if(abs(current.gx-end_pose.gx)<=1 && abs(current.gy-end_pose.gy)<=1 && abs(current.gtheta-end_pose.gtheta)<=2)
{
ROS_INFO("Goal Reached !!!!!!!\n");
path_valid = 1;
break;
}
// if(init_flag == 0)
// {
// head = &(current);
// head->previous = NULL;
// head->start_flag = 1;
// init_flag = 1;
// }
if(vis[current.gx][current.gy][current.gtheta] == 1)
{
if(poseset.size()<=0)
{
ROS_ERROR("no path found!!!!!!\n");
path_valid = 0;
break;
}
ROS_INFO("visited continue!!!!!!\n");
continue;
}
vis[current.gx][current.gy][current.gtheta] = 1;
ROS_INFO("current start_flag: %d\n", current.start_flag);
nextset.clear();
nextset = current.getNextPose();
ROS_INFO("---------- nextset size: %ld ----------\n",nextset.size());
// particlecloud_publisher(particlecloud_pub_, nextset);
current_set.push_back(current);
for(int i = 0;i < nextset.size();++i)
{
ROS_INFO("i: %d",i);
if(ha_map.checkCollision(nextset[i]))
{
ROS_WARN("collide with obs !!!!\n");
continue;
}
// nextset[i].gx = int((nextset[i].v[0] - ha_map.global_map->origin_x) / GRID_RES);
// nextset[i].gy = int((nextset[i].v[1] - ha_map.global_map->origin_x) / GRID_RES);
nextset[i].gx = int((nextset[i].v[0] - ha_map.global_map->origin_x) / ha_map.global_map->scale / ha_map.global_map->size_x * GX );
nextset[i].gy = int((nextset[i].v[1] - ha_map.global_map->origin_x) / ha_map.global_map->scale / ha_map.global_map->size_y * GX );
nextset[i].gtheta = int(nextset[i].v[2]/THETA_RES);
while(nextset[i].gtheta < 0)
{
nextset[i].gtheta += THETA;
}
while(nextset[i].gtheta > THETA)
{
nextset[i].gtheta -= THETA;
}
if(vis[nextset[i].gx][nextset[i].gy][nextset[i].gtheta])
{
ROS_WARN("evaluated continue !!!!\n");
continue;
}
if(i == floor(nextset.size()/2))
// if(i == 1)
{
nextset[i].cost3d = current.cost3d + 5;
}
else
{
nextset[i].cost3d = current.cost3d + 15;
}
ROS_INFO("heading_next: %.3f",nextset[i].v[2]);
ROS_INFO("x_next: %.3f, y_next: %.3f, h_next: %.3f\n",nextset[i].v[0],nextset[i].v[1],nextset[i].v[2]);
// previous_set[nextset[i].gx][nextset[i].gy][nextset[i].gtheta] = current;
// nextset[i].previous = &(current);
// nextset[i].After(&(current));
// nextset[i].pprevious = current;
// Insert(head, &(nextset[i]));
nextset[i].previous_num = current_set.size()-1;
nextset[i].dx = int((nextset[i].v[0] - ha_map.global_map->origin_x) / ha_map.cost_map->scale );
nextset[i].dy = int((nextset[i].v[1] - ha_map.global_map->origin_x) / ha_map.cost_map->scale );
ROS_INFO("x_next d: %d, y_next: %d\n",nextset[i].dx,nextset[i].dy);
poseset.push(nextset[i]);
}
ROS_INFO("************ iter end !!!!! poseset size: %ld ************\n",poseset.size());
iter++;
}
if(path_valid == 1)
{
ROS_INFO("Begin path reconstruct >>>>>>>>>>\n");
reconstruct_path(current);
ROS_INFO("Finish path reconstruct >>>>>>>>>>\n");
}
else
{
ROS_INFO("no path constructed!!!!!!\n");
}
// for(int i = 0;i < GX;++i)
// {
// for(int j = 0;j < GY;++j)
// {
// delete vis[i][j];
// }
// delete vis[i];
// }
// delete vis;
}
void Ha_node::reconstruct_path(Pose_vector current)
{
final_path.clear();
Pose_vector pose_temp;
final_path.push_back(current);
int counter = 0;
// while(current.gx!=start_pose.gx || current.gy!=start_pose.gy || current.gtheta!=start_pose.gtheta)
// while(current.start_flag != 1)
// while(current.previous != NULL)
while(current.previous_num != -1)
{
// pose_temp = previous_set[current.gx][current.gy][current.gtheta];
// pose_temp = *current.previous;
// pose_temp = current.pprevious;
pose_temp = current_set[current.previous_num];
current = pose_temp;
final_path.push_back(current);
ROS_INFO("counter: %d",counter);
counter++;
// if(counter>5) break;
}
}
void Ha_node::particlecloud_publisher(ros::Publisher particlecloud_pub_, std::vector<Pose_vector> sample_set){
// ros::Rate r(1/LOOP_DURATION);
ROS_INFO("Pointcloud publish Begin >>>>>>>>>>>>> \n");
geometry_msgs::PoseArray cloud_msg;
std::vector< Pose_vector > pub_set;
// if(sample_cloud_pub_flag == 0) pub_set = sample_set;
// else pub_set = resample_set;
cloud_msg.header.stamp = ros::Time::now();
cloud_msg.header.frame_id = "map";
cloud_msg.poses.resize(sample_set.size());
for(int i=0;i<sample_set.size();i++)
{
// tf::poseTFToMsg(tf::Pose(tf::createQuaternionFromYaw(sample_set[i].v[2]/180*M_PI),
// tf::Vector3(sample_set[i].v[0]-global_obs_map->size_x / 2 * global_obs_map->scale,
// sample_set[i].v[1]-global_obs_map->size_y / 2 * global_obs_map->scale, 0)),
// cloud_msg.poses[i]);
tf::poseTFToMsg(tf::Pose(tf::createQuaternionFromYaw(sample_set[i].v[2]/180*M_PI),
tf::Vector3(sample_set[i].v[0],
sample_set[i].v[1], 0)),
cloud_msg.poses[i]);
}
particlecloud_pub_.publish(cloud_msg);
ROS_INFO("Pointcloud publish Done >>>>>>>>>>>>> \n");
// r.sleep();
}
}
int main(int argc, char *argv[])
{
ros::init(argc, argv, "planner_node");
ha::Ha_node ha_node;
ha_node.process();
return 0;
} |
b4c6d78d631b7c2661231b811a0bb68a7cc7869a | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /components/autofill/core/browser/payments/local_card_migration_manager.h | 321e81cfc9f98a4135086810a90ee8fa164fcaf3 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 11,886 | h | local_card_migration_manager.h | // Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_PAYMENTS_LOCAL_CARD_MIGRATION_MANAGER_H_
#define COMPONENTS_AUTOFILL_CORE_BROWSER_PAYMENTS_LOCAL_CARD_MIGRATION_MANAGER_H_
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "base/gtest_prod_util.h"
#include "base/memory/raw_ptr.h"
#include "components/autofill/core/browser/autofill_client.h"
#include "components/autofill/core/browser/metrics/autofill_metrics.h"
#include "components/autofill/core/browser/metrics/payments/local_card_migration_metrics.h"
#include "components/autofill/core/browser/payments/legal_message_line.h"
#include "components/autofill/core/browser/payments/payments_client.h"
#include "components/autofill/core/browser/strike_databases/payments/local_card_migration_strike_database.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace autofill {
class CreditCard;
class PersonalDataManager;
// Server-side response can return SUCCESS, TEMPORARY_FAILURE, or
// PERMANENT_FAILURE (see SaveResult enum). Use these to extract migration
// result.
inline constexpr char kMigrationResultPermanentFailure[] = "PERMANENT_FAILURE";
inline constexpr char kMigrationResultTemporaryFailure[] = "TEMPORARY_FAILURE";
inline constexpr char kMigrationResultSuccess[] = "SUCCESS";
// MigratableCreditCard class is used as a data structure to work as an
// intermediary between the UI side and the migration manager. Besides the basic
// credit card information, it also includes a boolean that represents whether
// the card was chosen for upload. We use each card's guid to distinguish each
// credit card for upload request/response.
class MigratableCreditCard {
public:
// Possible states for the migratable local card.
enum class MigrationStatus {
// Set if the migratable card have not been uploaded.
UNKNOWN,
// Set if the migratable card was successfully uploaded to the server.
SUCCESS_ON_UPLOAD,
// Set if the migratable card encountered a failure during upload.
FAILURE_ON_UPLOAD,
};
explicit MigratableCreditCard(const CreditCard& credit_card);
MigratableCreditCard(const MigratableCreditCard&);
MigratableCreditCard(MigratableCreditCard&&);
MigratableCreditCard& operator=(const MigratableCreditCard&);
MigratableCreditCard& operator=(MigratableCreditCard&&);
~MigratableCreditCard();
CreditCard credit_card() const { return credit_card_; }
MigrationStatus migration_status() const { return migration_status_; }
void set_migration_status(MigrationStatus migration_status) {
migration_status_ = migration_status;
}
private:
// The main card information of the current migratable card.
CreditCard credit_card_;
// Migration status for this card.
MigrationStatus migration_status_ = MigrationStatus::UNKNOWN;
};
// Manages logic for determining whether migration of locally saved credit cards
// to Google Payments is available as well as multiple local card uploading.
// Owned by FormDataImporter.
class LocalCardMigrationManager {
public:
// An observer class used by browsertests that gets notified whenever
// particular actions occur.
class ObserverForTest {
public:
virtual void OnDecideToRequestLocalCardMigration() = 0;
virtual void OnReceivedGetUploadDetailsResponse() = 0;
virtual void OnSentMigrateCardsRequest() = 0;
virtual void OnReceivedMigrateCardsResponse() = 0;
};
// The parameters should outlive the LocalCardMigrationManager.
LocalCardMigrationManager(AutofillClient* client,
payments::PaymentsClient* payments_client,
const std::string& app_locale,
PersonalDataManager* personal_data_manager);
LocalCardMigrationManager(const LocalCardMigrationManager&) = delete;
LocalCardMigrationManager& operator=(const LocalCardMigrationManager&) =
delete;
virtual ~LocalCardMigrationManager();
// Returns true if all of the conditions for allowing local credit card
// migration are satisfied. Initializes the local card list for upload. Stores
// a local copy of `extracted_credit_card` and
// `credit_card_import_type` locally for later check whether
// the imported card is supported. `extracted_credit_card` might be
// null if a user used server card.
bool ShouldOfferLocalCardMigration(
const absl::optional<CreditCard>& extracted_credit_card,
int credit_card_import_type);
// Called from FormDataImporter or settings page when all migration
// requirements are met. Fetches legal documents and triggers the
// OnDidGetUploadDetails callback. |is_from_settings_page| to denote the user
// triggers the migration from settings page. It will trigger the main prompt
// directly if the get upload details call returns success.
void AttemptToOfferLocalCardMigration(bool is_from_settings_page);
// Callback function when user agrees to migration on the intermediate dialog.
// Pops up a larger, modal dialog showing the local cards to be uploaded.
// Exposed for testing.
virtual void OnUserAcceptedIntermediateMigrationDialog();
// Callback function when user confirms migration on the main migration
// dialog. Removes any MigratableCreditCard of which the guid is not in
// |selected_card_guids| from |migratable_credit_cards_|. Sets
// |user_accepted_main_migration_dialog_| and sends the migration request
// once risk data is available. Exposed for testing.
virtual void OnUserAcceptedMainMigrationDialog(
const std::vector<std::string>& selected_card_guids);
// Callback function when user clicks the trash can button in the
// action-required dialog to delete one credit card from Chrome.
// |deleted_card_guid| is the GUID of the card to be deleted.
virtual void OnUserDeletedLocalCardViaMigrationDialog(
const std::string& deleted_card_guid);
// Check that the user is signed in, syncing, and the proper experiment
// flags are enabled. Override in the test class.
virtual bool IsCreditCardMigrationEnabled();
// Determines what detected_values metadata to send (generally, cardholder
// name if it exists on all cards, and existence of Payments customer).
int GetDetectedValues() const;
// Fetch all migratable credit cards and store in |migratable_credit_cards_|.
// Migratable cards are cards whose card number passed luhn check and
// expiration date are valid. We do NOT filter unsupported cards here.
// Any other usage of this function other than ShouldOfferLocalCardMigration()
// and from settings page after OnDidGetUploadDetails, you should call
// FilterOutUnsupportedLocalCards right after this function to filter out
// unsupported cards. If so, the first OnDidGetUploadDetails() will need to
// store the supported ranges locally.
void GetMigratableCreditCards();
// For testing.
void SetAppLocaleForTesting(const std::string& app_locale) {
app_locale_ = app_locale;
}
protected:
// Callback after successfully getting the legal documents. On success,
// displays the offer-to-migrate dialog, which the user can accept or not.
// When |is_from_settings_page| is true, it will trigger the main prompt
// directly. If not, trigger the intermediate prompt. Exposed for testing.
virtual void OnDidGetUploadDetails(
bool is_from_settings_page,
AutofillClient::PaymentsRpcResult result,
const std::u16string& context_token,
std::unique_ptr<base::Value::Dict> legal_message,
std::vector<std::pair<int, int>> supported_card_bin_ranges);
// Callback after successfully getting the migration save results. Map
// migration save result to each card depending on the |save_result|. Will
// trigger a window showing the migration result together with display text to
// the user.
void OnDidMigrateLocalCards(
AutofillClient::PaymentsRpcResult result,
std::unique_ptr<std::unordered_map<std::string, std::string>> save_result,
const std::string& display_text);
const raw_ptr<AutofillClient> client_;
// Handles Payments service requests.
// Owned by BrowserAutofillManager.
raw_ptr<payments::PaymentsClient> payments_client_;
private:
friend class LocalCardMigrationBrowserTest;
FRIEND_TEST_ALL_PREFIXES(LocalCardMigrationManagerTest,
MigrateCreditCard_MigrateWhenHasSupportedLocalCard);
FRIEND_TEST_ALL_PREFIXES(LocalCardMigrationManagerTest,
MigrateCreditCard_MigrationPermanentFailure);
FRIEND_TEST_ALL_PREFIXES(LocalCardMigrationManagerTest,
MigrateCreditCard_MigrationTemporaryFailure);
FRIEND_TEST_ALL_PREFIXES(LocalCardMigrationManagerTest,
MigrateCreditCard_MigrationSuccess);
FRIEND_TEST_ALL_PREFIXES(LocalCardMigrationManagerTest,
MigrateCreditCard_ToggleIsChosen);
// Returns the LocalCardMigrationStrikeDatabase for |client_|.
LocalCardMigrationStrikeDatabase* GetLocalCardMigrationStrikeDatabase();
// Filter the |migratable_credit_cards_| with |supported_card_bin_ranges| and
// keep supported local cards in |migratable_credit_cards_|.
// Effective after one successful GetUploadDetails call where we fetch the
// |supported_card_bin_ranges|.
void FilterOutUnsupportedLocalCards(
const std::vector<std::pair<int, int>>& supported_card_bin_ranges);
// Pops up a larger, modal dialog showing the local cards to be uploaded.
void ShowMainMigrationDialog();
// Callback function when migration risk data is ready. Saves risk data in
// |migration_risk_data_| and calls SendMigrateLocalCardsRequest if the user
// has accepted the main migration dialog.
void OnDidGetMigrationRiskData(const std::string& risk_data);
// Finalizes the migration request and calls PaymentsClient.
void SendMigrateLocalCardsRequest();
// For testing.
void SetEventObserverForTesting(ObserverForTest* observer) {
observer_for_testing_ = observer;
}
// The parsed lines from the legal message return from GetUploadDetails.
LegalMessageLines legal_message_lines_;
std::string app_locale_;
// The personal data manager, used to save and load personal data to/from the
// web database. This is overridden by the BrowserAutofillManagerTest.
// Weak reference.
raw_ptr<PersonalDataManager> personal_data_manager_;
// The imported credit card number from the form submission.
absl::optional<std::u16string> extracted_credit_card_number_;
// The imported credit card record type from the form submission.
int credit_card_import_type_;
// Collected information about a pending migration request.
payments::PaymentsClient::MigrationRequestDetails migration_request_;
// The local credit cards to be uploaded. Owned by LocalCardMigrationManager.
// The order of cards should not be changed.
// TODO(crbug.com/867194): Currently we will not handle the case of local
// cards added/deleted during migration.
std::vector<MigratableCreditCard> migratable_credit_cards_;
// |true| if the user has accepted migrating their local cards to Google Pay
// on the main dialog.
bool user_accepted_main_migration_dialog_ = false;
// Record the triggering source of the local card migration.
autofill_metrics::LocalCardMigrationOrigin local_card_migration_origin_;
// Initialized only during tests.
raw_ptr<ObserverForTest> observer_for_testing_ = nullptr;
std::unique_ptr<LocalCardMigrationStrikeDatabase>
local_card_migration_strike_database_;
base::WeakPtrFactory<LocalCardMigrationManager> weak_ptr_factory_{this};
};
} // namespace autofill
#endif // COMPONENTS_AUTOFILL_CORE_BROWSER_PAYMENTS_LOCAL_CARD_MIGRATION_MANAGER_H_
|
2b89033ad01696f8e77c4081e184436ed146b7f1 | 8f8319785516b58eb5edb97cceb627cbc6181a1e | /Ejercicio14-.cpp | 5133becebbb94f80cc09f9cf11546e505826b225 | [] | no_license | AlexSias18/Asignacion16 | 3199bfe0bb4ee183a2bd12c95954de5a920b426d | 41e802b1bce3446fcc3309894b85830a5ea4e67f | refs/heads/master | 2020-05-26T06:51:01.652684 | 2019-05-23T01:43:04 | 2019-05-23T01:43:04 | 188,140,733 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 837 | cpp | Ejercicio14-.cpp | // Semana9.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void intercambiar(int *a, int *b) {
cout << "*a="<<*a << "*b="<<*b;
int aAux, bAux;
bAux = *b; //bAux = y
aAux = *a; //aAux = x
*a = bAux; //x = bAux
*b = aAux; //y = aAux
}
int main()
{
int x = 2;
int y = 4;
//Declarar los punteros
int *x1, *y1;
//Asignar la dirección de memoria
x1 = &x;//x1 = AB001
y1 = &y;//Y1 = AB002
//Imprimiendo los valores iniciales
cout << "Valor X: " << *x1 << " - Valor Y: " << *y1 << endl;
cout << "Valor X: " << x << " - Valor Y: " << y << endl;
//Llamo a la función
intercambiar(x1, y1);
cout<<"Valor X: " << *x1 << " - Valor Y: " << *y1 << endl;
cout<<"Valor X: " << x << " - Valor Y: " << y << endl;
cin.get();
cin.get();
}
|
1b11a45fb3394d7ebfa6f786566864179e5a5da2 | 14248aaedfa5f77c7fc5dd8c3741604fb987de5c | /luogu/P2915.cpp | d83510bb0353487b4cd72cc49a43c67c9af8e6e5 | [] | no_license | atubo/online-judge | fc51012465a1bd07561b921f5c7d064e336a4cd2 | 8774f6c608bb209a1ebbb721d6bbfdb5c1d1ce9b | refs/heads/master | 2021-11-22T19:48:14.279016 | 2021-08-29T23:16:16 | 2021-08-29T23:16:16 | 13,290,232 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,098 | cpp | P2915.cpp | // https://www.luogu.org/problemnew/show/P2915
// [USACO08NOV]奶牛混合起来Mixed Up Cows
#include <bits/stdc++.h>
using namespace std;
int N, K;
int S[16];
int64_t dp[1<<20];
int encode(int mask, int i) {
return (i << 16) | mask;
}
void decode(int c, int &mask, int &i) {
mask = c & (0xFFFF);
i = (c >> 16);
}
int main() {
scanf("%d%d", &N, &K);
queue<int> q;
for (int i = 0; i < N; i++) {
scanf("%d", &S[i]);
int code = encode(1<<i, i);
q.push(code);
dp[code] = 1;
}
while (!q.empty()) {
int code = q.front();
q.pop();
int64_t cnt = dp[code];
int p, mask;
decode(code, mask, p);
for (int i = 0; i < N; i++) {
if ((mask >> i) & 1 || abs(S[p] - S[i]) <= K) continue;
code = encode(mask|(1<<i), i);
if (!dp[code]) q.push(code);
dp[code] += cnt;
}
}
int64_t ans = 0;
for (int i = 0; i < N; i++) {
int code = encode((1<<N)-1, i);
ans += dp[code];
}
printf("%lld\n", ans);
return 0;
}
|
b8db0ddb2f83c45fad93e55a39a26fb1fd292ea5 | a7764174fb0351ea666faa9f3b5dfe304390a011 | /inc/TCollection_AVLBaseNode.hxx | b6934dc5d57460f0b9d16aa1be21712e953d8dd4 | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,060 | hxx | TCollection_AVLBaseNode.hxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#ifndef _TCollection_AVLBaseNode_HeaderFile
#define _TCollection_AVLBaseNode_HeaderFile
#ifndef _Standard_HeaderFile
#include <Standard.hxx>
#endif
#ifndef _Standard_DefineHandle_HeaderFile
#include <Standard_DefineHandle.hxx>
#endif
#ifndef _Handle_TCollection_AVLBaseNode_HeaderFile
#include <Handle_TCollection_AVLBaseNode.hxx>
#endif
#ifndef _TCollection_AVLBaseNodePtr_HeaderFile
#include <TCollection_AVLBaseNodePtr.hxx>
#endif
#ifndef _Standard_Integer_HeaderFile
#include <Standard_Integer.hxx>
#endif
#ifndef _MMgt_TShared_HeaderFile
#include <MMgt_TShared.hxx>
#endif
#ifndef _TCollection_Side_HeaderFile
#include <TCollection_Side.hxx>
#endif
class TCollection_AVLBaseNode : public MMgt_TShared {
public:
TCollection_AVLBaseNode(const TCollection_AVLBaseNodePtr& L,const TCollection_AVLBaseNodePtr& R);
void SetChild(const TCollection_AVLBaseNodePtr& theNode,const TCollection_Side theSide) ;
Standard_EXPORT static Standard_Integer Height(const TCollection_AVLBaseNodePtr& ANode) ;
Standard_EXPORT static Standard_Integer RecursiveExtent(const TCollection_AVLBaseNodePtr& ANode) ;
Standard_EXPORT static Standard_Integer RecursiveTotalExtent(const TCollection_AVLBaseNodePtr& ANode) ;
TCollection_AVLBaseNodePtr& Right() const;
TCollection_AVLBaseNodePtr& Left() const;
Standard_Integer& Count() const;
DEFINE_STANDARD_RTTI(TCollection_AVLBaseNode)
protected:
TCollection_AVLBaseNodePtr myLeft;
TCollection_AVLBaseNodePtr myRight;
Standard_Integer myCount;
private:
};
#include <TCollection_AVLBaseNode.lxx>
// other Inline functions and methods (like "C++: function call" methods)
#endif
|
8cf64c5afab064a01400de3afbc113addfb27831 | d10446d67262f7e8dd0c84a3f92ca0df35f8f440 | /include/Zen/Plugin/I_Plugin.hpp | 252207d2b1305fffa74936efbbb11ad632b20a7f | [
"MIT"
] | permissive | indie-zen/zen-plugin | 812aad6a969c0a4c15fa89b0c08ab215f8b6e7aa | af01e5675fb0a7ce822652d68ef216f707d42dee | refs/heads/master | 2020-12-25T15:28:47.167674 | 2018-08-04T12:25:47 | 2018-08-04T12:25:47 | 58,143,014 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 940 | hpp | I_Plugin.hpp | //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Zen Plugin Framework
//
// Copyright (C) 2001 - 2018 Raymond A. Richards
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#ifndef ZEN_PLUGIN_I_PLUGIN_HPP_INCLUDED
#define ZEN_PLUGIN_I_PLUGIN_HPP_INCLUDED
#include "Configuration.hpp"
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen::Plugin {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
class PLUGIN_DLL_LINK I_Plugin
{
protected:
I_Plugin() = default;
I_Plugin(const I_Plugin&) = delete;
virtual ~I_Plugin() = default;
};
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace Zen::Plugin
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#endif // ZEN_PLUGIN_I_PLUGIN_HPP_INCLUDED
|
11b367ab33016302123046eaab5f6f10cc5499ee | 3ac7015f1a21092326b785334cec0cf95dcd3839 | /toolboxes/core/cpu/math/hoNDImage_util.hxx | a6f4b80a438fdbd753934262778eb92457823550 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | bmswgnp/gadgetron | 068209db3dcc52d021ab8d3bd33e3c6d3bcfd49a | ba0b96476a03d91f89328c30814b95fb307bf292 | refs/heads/master | 2021-01-18T17:58:56.213800 | 2015-08-19T16:07:46 | 2015-08-19T16:07:46 | 41,292,861 | 1 | 0 | null | 2015-08-24T08:56:17 | 2015-08-24T08:56:17 | null | UTF-8 | C++ | false | false | 34,242 | hxx | hoNDImage_util.hxx | /** \file hoNDImage_util.hxx
\brief operations on the hoNDImage class.
*/
namespace Gadgetron
{
template <typename T, unsigned int D>
bool corrCoef(const hoNDImage<T, D>& a, const hoNDImage<T, D>& b, T& r)
{
try
{
GADGET_CHECK_RETURN_FALSE(a.dimensions_equal(&b));
r = -1;
T ma, mb;
ma = Gadgetron::mean( const_cast< hoNDImage<T, D>* >(&a) );
mb = Gadgetron::mean( const_cast< hoNDImage<T, D>* >(&b) );
size_t N = a.get_number_of_elements();
const T* pA = a.begin();
const T* pB = b.begin();
size_t n;
double x(0), y(0), z(0);
for ( n=0; n<N; n++ )
{
x += (pA[n]-ma)*(pA[n]-ma);
y += (pB[n]-mb)*(pB[n]-mb);
z += (pA[n]-ma)*(pB[n]-mb);
}
double p = std::sqrt(x*y);
if ( p > 0 )
{
r = (T)(z/p);
}
}
catch(...)
{
GERROR_STREAM("Errors happened in corrCoef(const hoNDImage<T, D>& a, const hoNDImage<T, D>& b, T& r) ... ");
return false;
}
return true;
}
template<typename T, typename InterpolatorType, unsigned int D>
bool downsampleImage(const hoNDImage<T, D>& in, InterpolatorType& interp, hoNDImage<T, D>& out, float ratio[])
{
try
{
std::vector<size_t> dim(D);
in.get_dimensions(dim);
std::vector<size_t> dim_out(D);
unsigned int ii;
for ( ii=0; ii<D; ii++ )
{
dim_out[ii] = (size_t)(dim[ii]/ratio[ii]);
}
return Gadgetron::resampleImage(in, interp, dim_out, out);
}
catch(...)
{
GERROR_STREAM("Errors happened in downsampleImage(const hoNDImage<T, D>& in, InterpolatorType& interp, hoNDImage<T, D>& out, float ratio[]) ... ");
return false;
}
return true;
}
template<typename T, typename InterpolatorType, unsigned int D>
bool upsampleImage(const hoNDImage<T, D>& in, InterpolatorType& interp, hoNDImage<T, D>& out, float ratio[])
{
try
{
std::vector<size_t> dim(D);
in.get_dimensions(dim);
std::vector<size_t> dim_out(D);
unsigned int ii;
for ( ii=0; ii<D; ii++ )
{
dim_out[ii] = (size_t)(dim[ii]*ratio[ii]);
}
return Gadgetron::resampleImage(in, interp, dim_out, out);
}
catch(...)
{
GERROR_STREAM("Errors happened in upsampleImage(const hoNDImage<T, D>& in, InterpolatorType& interp, hoNDImage<T, D>& out, float ratio[]) ... ");
return false;
}
return true;
}
template<typename T, typename InterpolatorType, unsigned int D>
bool resampleImage(const hoNDImage<T, D>& in, InterpolatorType& interp, const std::vector<size_t>& dim_out, hoNDImage<T, D>& out)
{
try
{
typedef typename hoNDImage<T, D>::coord_type coord_type;
/// get the coordinate parameters
std::vector<size_t> dim;
in.get_dimensions(dim);
std::vector<coord_type> pixelSize;
in.get_pixel_size(pixelSize);
std::vector<coord_type> origin;
in.get_origin(origin);
typename hoNDImage<T, D>::axis_type axis;
in.get_axis(axis);
/// compute new pixel sizes
std::vector<coord_type> pixelSize_out(D);
unsigned int ii;
for ( ii=0; ii<D; ii++ )
{
if ( dim_out[ii] > 1 )
{
pixelSize_out[ii] = (dim[ii]-1)*pixelSize[ii] / (dim_out[ii]-1);
}
else
{
pixelSize_out[ii] = (dim[ii]-1)*pixelSize[ii];
}
}
/// set up the out image
out.create(dim_out, pixelSize_out, origin, axis);
/// set up the interpolator
interp.setArray( const_cast< hoNDImage<T, D>& >(in) );
/// compute the out image
size_t N = out.get_number_of_elements();
if ( D == 2 )
{
long long ox = (long long)dim_out[0];
long long oy = (long long)dim_out[1];
long long x, y;
#pragma omp parallel default(none) private(x, y) shared(N, ox, oy, in, out, interp)
{
coord_type px, py, ix_in, iy_in;
#pragma omp for
for ( y=0; y<oy; y++ )
{
for ( x=0; x<ox; x++ )
{
out.image_to_world( (size_t)x, (size_t)y, px, py);
in.world_to_image(px, py, ix_in, iy_in);
out( (size_t)(x+y*ox) ) = interp(ix_in, iy_in);
}
}
}
}
else if ( D == 3 )
{
long long ox = (long long)dim_out[0];
long long oy = (long long)dim_out[1];
long long oz = (long long)dim_out[2];
long long x, y, z;
#pragma omp parallel default(none) private(x, y, z) shared(N, ox, oy, oz, in, out, interp)
{
coord_type ix_in, iy_in, iz_in;
coord_type px, py, pz;
#pragma omp for
for ( z=0; z<oz; z++ )
{
for ( y=0; y<oy; y++ )
{
size_t offset = y*ox + z*ox*oy;
for ( x=0; x<ox; x++ )
{
out.image_to_world( (size_t)x, (size_t)y, (size_t)z, px, py, pz);
in.world_to_image(px, py, pz, ix_in, iy_in, iz_in);
out( (size_t)(x+offset) ) = interp(ix_in, iy_in, iz_in);
}
}
}
}
}
else if ( D == 4 )
{
long long ox = (long long)dim_out[0];
long long oy = (long long)dim_out[1];
long long oz = (long long)dim_out[2];
long long ot = (long long)dim_out[3];
long long x, y, z, t;
#pragma omp parallel default(none) private(x, y, z, t) shared(N, ox, oy, oz, ot, in, out, interp)
{
coord_type ix_in, iy_in, iz_in, it_in;
coord_type px, py, pz, pt;
#pragma omp for
for ( t=0; t<ot; t++ )
{
for ( z=0; z<oz; z++ )
{
for ( y=0; y<oy; y++ )
{
size_t offset = y*ox + z*ox*oy + t*ox*oy*oz;
for ( x=0; x<ox; x++ )
{
out.image_to_world( (size_t)x, (size_t)y, (size_t)z, (size_t)t, px, py, pz, pt);
in.world_to_image(px, py, pz, pt, ix_in, iy_in, iz_in, it_in);
out( (size_t)(x+offset) ) = interp(ix_in, iy_in, iz_in, it_in);
}
}
}
}
}
}
else
{
long long n;
#pragma omp parallel default(none) private(n) shared(N, in, out, interp)
{
std::vector<size_t> ind_o(D);
std::vector<coord_type> ind_i(D);
std::vector<coord_type> pos(D);
#pragma omp for
for ( n=0; n<N; n++ )
{
out.calculate_index(n, ind_o);
out.image_to_world(ind_o, pos);
in.world_to_image(pos, ind_i);
out(n) = interp(ind_i);
}
}
}
}
catch(...)
{
GERROR_STREAM("Errors happened in resampleImage(const hoNDImage<T, D>& in, InterpolatorType& interp, hoNDImage<T, D>& out, size_t size_out[D]) ... ");
return false;
}
return true;
}
template<typename T, typename BoundaryHandlerType, unsigned int D>
bool downsampleImageBy2WithAveraging(const hoNDImage<T, D>& in, BoundaryHandlerType& bh, hoNDImage<T, D>& out)
{
try
{
typedef typename hoNDImage<T, D>::coord_type coord_type;
bh.setArray( const_cast< hoNDImage<T, D>& >(in) );
/// get the coordinate parameters
std::vector<size_t> dim;
in.get_dimensions(dim);
std::vector<coord_type> pixelSize;
in.get_pixel_size(pixelSize);
std::vector<coord_type> origin;
in.get_origin(origin);
typename hoNDImage<T, D>::axis_type axis;
in.get_axis(axis);
/// compute out image size and pixel size
std::vector<size_t> dim_out(D);
std::vector<coord_type> pixelSize_out(D);
unsigned int ii;
for ( ii=0; ii<D; ii++ )
{
dim_out[ii] = (dim[ii] >> 1);
pixelSize_out[ii] = 2*pixelSize[ii];
}
out.create(dim_out, pixelSize_out, origin, axis);
if ( D == 2 )
{
size_t sx = dim_out[0];
size_t sy = dim_out[1];
T weight = 1.0/5;
long long x, y;
#pragma omp parallel for default(none) private(x, y) shared(sx, sy, bh, out)
for ( y=0; y<(long long)sy; y++ )
{
long long iy = y<<1;
for ( x=0; x<(long long)sx; x++ )
{
long long ix = x<<1;
out( (size_t)(x+y*sx) ) = bh(ix, iy) + ( bh(ix+1, iy) + bh(ix-1, iy) ) + ( bh(ix, iy+1) + bh(ix, iy-1) );
}
}
Gadgetron::scal(weight, out);
}
else if ( D == 3 )
{
size_t sx = dim_out[0];
size_t sy = dim_out[1];
size_t sz = dim_out[2];
T weight = 1.0/7;
long long x, y, z;
#pragma omp parallel for default(none) private(x, y, z) shared(sx, sy, sz, bh, out)
for ( z=0; z<sz; z++ )
{
long long iz = z<<1;
for ( y=0; y<sy; y++ )
{
long long iy = y<<1;
size_t offset = y*sx + z*sx*sy;
for ( x=0; x<sx; x++ )
{
long long ix = x<<1;
out( (size_t)(x+offset) ) = bh(ix, iy, iz)
+ ( bh(ix+1, iy, iz) + bh(ix-1, iy, iz) )
+ ( bh(ix, iy+1, iz) + bh(ix, iy-1, iz) )
+ ( bh(ix, iy, iz+1) + bh(ix, iy, iz-1) );
}
}
}
Gadgetron::scal(weight, out);
}
else if ( D == 4 )
{
size_t sx = dim_out[0];
size_t sy = dim_out[1];
size_t sz = dim_out[2];
size_t st = dim_out[3];
T weight = 1.0/9;
long long x, y, z, t;
#pragma omp parallel for default(none) private(x, y, z, t) shared(sx, sy, sz, st, bh, out)
for ( t=0; t<st; t++ )
{
long long it = t<<1;
for ( z=0; z<sz; z++ )
{
long long iz = z<<1;
for ( y=0; y<sy; y++ )
{
long long iy = y<<1;
size_t offset = y*sx + z*sx*sy + t*sx*sy*sz;
for ( x=0; x<sx; x++ )
{
long long ix = x<<1;
out( (size_t)(x+offset) ) = bh(ix, iy, iz, it)
+ ( bh(ix+1, iy, iz, it) + bh(ix-1, iy, iz, it) )
+ ( bh(ix, iy+1, iz, it) + bh(ix, iy-1, iz, it) )
+ ( bh(ix, iy, iz+1, it) + bh(ix, iy, iz-1, it) )
+ ( bh(ix, iy, iz, it+1) + bh(ix, iy, iz, it-1) );
}
}
}
}
Gadgetron::scal(weight, out);
}
else
{
T weight = 1.0/(2*D+1);
size_t N = out.get_number_of_elements();
long long n;
#pragma omp parallel default(none) private(n) shared(N, bh, out, dim_out)
{
std::vector<size_t> ind_out(D);
std::vector<long long> ind_in(D);
#pragma omp for
for ( n=0; n<N; n++ )
{
out.calculate_index(n, ind_out);
unsigned int ii;
for ( ii=0; ii<D; ii++ )
{
ind_in[ii] = ind_out[ii]<<1;
}
T v = bh(ind_in);
for ( ii=0; ii<D; ii++ )
{
ind_in[ii]++;
v += bh(ind_in);
ind_in[ii]--;
ind_in[ii]--;
v += bh(ind_in);
ind_in[ii]++;
}
out(n) = v;
}
}
Gadgetron::scal(weight, out);
}
}
catch(...)
{
GERROR_STREAM("Errors happened in downsampleImageBy2WithAveraging(const hoNDImage<T, D>& in, hoNDImage<T, D>& out) ... ");
return false;
}
return true;
}
template<typename T, typename BoundaryHandlerType, unsigned int D>
bool expandImageBy2(const hoNDImage<T, D>& in, BoundaryHandlerType& bh, hoNDImage<T, D>& out)
{
try
{
typedef typename hoNDImage<T, D>::coord_type coord_type;
bh.setArray( const_cast< hoNDImage<T, D>& >(in) );
/// get the coordinate parameters
std::vector<size_t> dim;
in.get_dimensions(dim);
std::vector<coord_type> pixelSize;
in.get_pixel_size(pixelSize);
std::vector<coord_type> origin;
in.get_origin(origin);
typename hoNDImage<T, D>::axis_type axis;
in.get_axis(axis);
/// compute out pixel size
std::vector<coord_type> pixelSize_out(D);
unsigned int ii;
for ( ii=0; ii<D; ii++ )
{
pixelSize_out[ii] = pixelSize[ii]* (coord_type)0.5;
}
out.set_pixel_size(pixelSize_out);
out.set_origin(origin);
out.set_axis(axis);
if ( D == 2 )
{
size_t sx = dim[0];
size_t sy = dim[1];
long long x, y;
#pragma omp parallel for default(none) private(x, y) shared(sx, sy, bh, out)
for ( y=0; y<sy; y++ )
{
size_t oy = y<<1;
for ( x=0; x<sx; x++ )
{
size_t ox = x<<1;
T p00 = bh(x, y);
T p10 = bh(x+1, y);
T p01 = bh(x, y+1);
T p11 = bh(x+1, y+1);
out( ox, oy ) = p00;
out( ox+1, oy ) = 0.5*(p00 + p10);
out( ox, oy+1 ) = 0.5*(p00 + p01);
out( ox+1, oy+1 ) = 0.25*(p00+p10+p01+p11);
}
}
// if out has odd sizes
size_t sx_out = out.get_size(0);
size_t sy_out = out.get_size(1);
if ( (2*sx) < sx_out )
{
for ( y=0; y<sy_out; y++ )
{
size_t offset = y*sx_out + sx_out-1;
out(offset) = out(offset-1);
}
}
if ( (2*sy) < sy_out )
{
memcpy(out.begin()+(sy_out-1)*sx_out, out.begin()+(sy_out-2)*sx_out, sizeof(T)*sx_out);
}
}
else if ( D == 3 )
{
size_t sx = dim[0];
size_t sy = dim[1];
size_t sz = dim[2];
long long x, y, z;
#pragma omp parallel for default(none) private(x, y, z) shared(sx, sy, sz, bh, out)
for ( z=0; z<sz; z++ )
{
size_t oz = z<<1;
for ( y=0; y<sy; y++ )
{
size_t oy = y<<1;
for ( x=0; x<sx; x++ )
{
size_t ox = x<<1;
T p000 = bh(x, y, z);
T p100 = bh(x+1, y, z);
T p010 = bh(x, y+1, z);
T p110 = bh(x+1, y+1, z);
T p001 = bh(x, y, z+1);
T p101 = bh(x+1, y, z+1);
T p011 = bh(x, y+1, z+1);
T p111 = bh(x+1, y+1, z+1);
out( ox, oy, oz ) = p000;
out( ox+1, oy, oz ) = 0.5*(p000 + p100);
out( ox, oy+1, oz ) = 0.5*(p000 + p010);
out( ox+1, oy+1, oz ) = 0.25*(p000+p100+p010+p110);
out( ox, oy, oz+1 ) = 0.5*(p000 + p001);
out( ox+1, oy, oz+1 ) = 0.25*(p000 + p100 + p001 + p101);
out( ox, oy+1, oz+1 ) = 0.25*(p000 + p010 + p001 + p011);
out( ox+1, oy+1, oz+1 ) = 0.125*(p000+p100+p010+p110+p001+p101+p011+p111);
}
}
}
// if out has odd sizes
size_t sx_out = out.get_size(0);
size_t sy_out = out.get_size(1);
size_t sz_out = out.get_size(2);
if ( (2*sx) < sx_out )
{
for ( z=0; z<sz_out; z++ )
{
for ( y=0; y<sy_out; y++ )
{
size_t offset = y*sx_out + z*sx_out*sy_out;
out( size_t(sx_out-1+offset) ) = out( size_t(sx_out-2+offset) );
}
}
}
if ( (2*sy) < sy_out )
{
for ( z=0; z<sz_out; z++ )
{
size_t offset = z*sx_out*sy_out + (sy_out-1)*sx_out;
for ( x=0; x<sx_out; x++ )
{
out( (size_t)(x+offset) ) = out( (size_t)(x+offset-sx_out) );
}
}
}
if ( (2*sz) < sz_out )
{
memcpy(out.begin()+(sz_out-1)*sx_out*sy_out, out.begin()+(sz_out-2)*sx_out*sy_out, sizeof(T)*sx_out*sy_out);
}
}
else
{
hoNDInterpolatorLinear<hoNDImage<T, D> > interp(const_cast< hoNDImage<T, D>& >(in), bh);
size_t N = out.get_number_of_elements();
long long n;
#pragma omp parallel default(none) private(n) shared(N, bh, in, out, interp)
{
std::vector<size_t> ind_out(D);
std::vector<coord_type> ind_in(D);
#pragma omp for
for ( n=0; n<N; n++ )
{
out.calculate_index(n, ind_out);
unsigned int ii;
for ( ii=0; ii<D; ii++ )
{
ind_in[ii] = (coord_type)(ind_out[ii]*0.5);
}
out( (size_t)(n) ) = interp(ind_in);
}
}
}
}
catch(...)
{
GERROR_STREAM("Errors happened in expandImageBy2(const hoNDImage<T, D>& in, BoundaryHandlerType& bh, hoNDImage<T, D>& out) ... ");
return false;
}
return true;
}
template<class ArrayType>
bool filterMedian(const ArrayType& img, size_t w[], ArrayType& img_out)
{
try
{
typedef typename ArrayType::value_type T;
size_t D = img.get_number_of_dimensions();
img_out = img;
if ( D == 1 )
{
long long halfW = w[0]/2;
long long N = (long long)img.get_number_of_elements();
long long n, m, t;
#pragma omp parallel default(none) private(n, m, t) shared(halfW, N, img, img_out)
{
std::vector<T> buf(2*halfW+1);
#pragma omp for
for ( n=0; n<N; n++ )
{
for ( m=-halfW; m<=halfW; m++ )
{
t = n + m;
if ( t<0 ) t = 0;
if ( t > N-1 ) t = N-1;
buf[m+halfW] = img( (size_t)t );
}
std::sort(buf.begin(), buf.end());
img_out(n) = buf[halfW];
}
}
}
else if ( D == 2 )
{
long long halfX = w[0]/2;
long long halfY = w[1]/2;
long long sx = (long long)img.get_size(0);
long long sy = (long long)img.get_size(1);
const T* pImg = img.begin();
T* pImgOut = img_out.begin();
long long WX = 2*halfX+1;
long long WY = 2*halfY+1;
long long medianInd = WX*WY/2;
long long x, y, tx, ty, hx, hy;
#pragma omp parallel default(none) private(x, y, tx, ty, hx, hy) shared(halfX, halfY, sx, sy, WX, WY, pImg, pImgOut, medianInd)
{
std::vector<T> buf(WX*WY);
#pragma omp for
for ( y=halfY; y<sy-halfY; y++ )
{
for ( x=halfX; x<sx-halfX; x++ )
{
size_t ind(0);
for ( hy=-halfY; hy<=halfY; hy++ )
{
ty = hy + y;
for ( hx=-halfX; hx<=halfX; hx++ )
{
tx = hx + x;
buf[ind++] = pImg[tx + ty*sx];
}
}
std::sort(buf.begin(), buf.end());
pImgOut[x + y*sx] = buf[medianInd];
}
}
}
std::vector<T> buf(WX*WY);
for ( y=0; y<halfY; y++ )
{
for ( x=0; x<sx; x++ )
{
size_t ind(0);
for ( hy=-halfY; hy<=halfY; hy++ )
{
ty = hy + y;
if ( ty < 0 ) ty = 0;
for ( hx=-halfX; hx<=halfX; hx++ )
{
tx = hx + x;
if ( tx < 0 ) tx = 0;
if ( tx > sx-1 ) tx = sx-1;
buf[ind++] = pImg[tx + ty*sx];
}
}
std::sort(buf.begin(), buf.end());
pImgOut[x + y*sx] = buf[medianInd];
}
}
for ( y=sy-halfY; y<sy; y++ )
{
for ( x=0; x<sx; x++ )
{
size_t ind(0);
for ( hy=-halfY; hy<=halfY; hy++ )
{
ty = hy + y;
if ( ty > sy-1 ) ty = sy-1;
for ( hx=-halfX; hx<=halfX; hx++ )
{
tx = hx + x;
if ( tx < 0 ) tx = 0;
if ( tx > sx-1 ) tx = sx-1;
buf[ind++] = pImg[tx + ty*sx];
}
}
std::sort(buf.begin(), buf.end());
pImgOut[x + y*sx] = buf[medianInd];
}
}
}
else if ( D == 3 )
{
long long halfX = w[0]/2;
long long halfY = w[1]/2;
long long halfZ = w[2]/2;
long long sx = (long long)img.get_size(0);
long long sy = (long long)img.get_size(1);
long long sz = (long long)img.get_size(2);
const T* pImg = img.begin();
T* pImgOut = img_out.begin();
long long WX = 2*halfX+1;
long long WY = 2*halfY+1;
long long WZ = 2*halfZ+1;
long long medianInd = WX*WY*WZ/2;
long long x, y, z, tx, ty, tz, hx, hy, hz;
#pragma omp parallel default(none) private(x, y, z, tx, ty, tz, hx, hy, hz) shared(halfX, halfY, halfZ, sx, sy, sz, WX, WY, WZ, pImg, pImgOut, medianInd)
{
std::vector<T> buf(WX*WY*WZ);
#pragma omp for
for ( z=halfZ; z<sz-halfZ; z++ )
{
for ( y=halfY; y<sy-halfY; y++ )
{
for ( x=halfX; x<sx-halfX; x++ )
{
size_t ind(0);
for ( hz=-halfZ; hz<=halfZ; hz++ )
{
tz = hz + z;
for ( hy=-halfY; hy<=halfY; hy++ )
{
ty = hy + y;
for ( hx=-halfX; hx<=halfX; hx++ )
{
tx = hx + x;
buf[ind++] = pImg[tx + ty*sx + tz*sx*sy];
}
}
}
std::sort(buf.begin(), buf.end());
pImgOut[x + y*sx + z*sx*sy] = buf[medianInd];
}
}
}
}
std::vector<T> buf(WX*WY*WZ);
for ( z=0; z<halfZ; z++ )
{
for ( y=0; y<sy; y++ )
{
for ( x=0; x<sx; x++ )
{
size_t ind(0);
for ( hz=-halfZ; hz<=halfZ; hz++ )
{
tz = hz + z;
if ( tz < 0 ) tz = 0;
for ( hy=-halfY; hy<=halfY; hy++ )
{
ty = hy + y;
if ( ty < 0 ) ty = 0;
if ( ty > sy-1 ) ty = sy-1;
for ( hx=-halfX; hx<=halfX; hx++ )
{
tx = hx + x;
if ( tx < 0 ) tx = 0;
if ( tx > sx-1 ) tx = sx-1;
buf[ind++] = pImg[tx + ty*sx + tz*sx*sy];
}
}
}
std::sort(buf.begin(), buf.end());
pImgOut[x + y*sx + z*sx*sy] = buf[medianInd];
}
}
}
for ( z=sz-halfZ; z<sz; z++ )
{
for ( y=0; y<sy; y++ )
{
for ( x=0; x<sx; x++ )
{
size_t ind(0);
for ( hz=-halfZ; hz<=halfZ; hz++ )
{
tz = hz + z;
if ( tz > sz-1 ) tz = sz-1;
for ( hy=-halfY; hy<=halfY; hy++ )
{
ty = hy + y;
if ( ty < 0 ) ty = 0;
if ( ty > sy-1 ) ty = sy-1;
for ( hx=-halfX; hx<=halfX; hx++ )
{
tx = hx + x;
if ( tx < 0 ) tx = 0;
if ( tx > sx-1 ) tx = sx-1;
buf[ind++] = pImg[tx + ty*sx + tz*sx*sy];
}
}
}
std::sort(buf.begin(), buf.end());
pImgOut[x + y*sx + z*sx*sy] = buf[medianInd];
}
}
}
}
}
catch(...)
{
GERROR_STREAM("Errors happened in filterMedian(const ArrayType& img, size_t w[], ArrayType& img_out) ... ");
return false;
}
return true;
}
template<class ArrayType>
bool filter1D(const ArrayType& img, const hoNDArray<typename realType<typename ArrayType::value_type>::Type>& ker, GT_BOUNDARY_CONDITION bh, ArrayType& img_out)
{
try
{
typedef typename ArrayType::value_type T;
typedef typename realType<T>::Type real_value_type;
typedef hoNDImage<T, 1> Array1DType;
long long RO = (long long)img.get_size(0);
long long num = (long long)(img.get_number_of_elements()/RO);
img_out = img;
long long kerLen = (long long)ker.get_size(0);
long long kerHalfLen = kerLen/2;
const real_value_type* pKer = ker.begin();
long long ii;
#pragma omp parallel default(none) private(ii) shared(bh, num, RO, img, img_out, kerLen, kerHalfLen, pKer)
{
hoNDBoundaryHandler<Array1DType>* pBH = NULL;
hoNDBoundaryHandlerFixedValue<Array1DType> bhFixedValue;
hoNDBoundaryHandlerBorderValue<Array1DType> bhBorderValue;
hoNDBoundaryHandlerPeriodic<Array1DType> bhPeriodic;
hoNDBoundaryHandlerMirror<Array1DType> bhMirror;
pBH = &bhBorderValue;
if ( bh == GT_BOUNDARY_CONDITION_FIXEDVALUE )
{
pBH = &bhFixedValue;
}
else if ( bh == GT_BOUNDARY_CONDITION_BORDERVALUE )
{
pBH = &bhBorderValue;
}
else if ( bh == GT_BOUNDARY_CONDITION_PERIODIC )
{
pBH = &bhPeriodic;
}
else if ( bh == GT_BOUNDARY_CONDITION_MIRROR )
{
pBH = &bhMirror;
}
#pragma omp for
for ( ii=0; ii<num; ii++ )
{
Array1DType img1D(RO, const_cast<T*>(img.begin()+ii*RO));
pBH->setArray(img1D);
Array1DType img_out1D(RO, img_out.begin()+ii*RO);
long long k, j;
for ( k=0; k<RO; k++ )
{
T v = 0;
for ( j=0; j<kerLen; j++ )
{
v += (*pBH)(k+j-kerHalfLen) * pKer[kerLen-j-1];
}
img_out1D(k) = v;
}
}
}
}
catch(...)
{
GERROR_STREAM("Errors happened in filter1D(const ArrayType& img, const hoNDArray<T>& ker, GT_BOUNDARY_CONDITION bh, ArrayType& img_out) ... ");
return false;
}
return true;
}
}
|
aac5efdf009f66d046a6954ec600f00ad4431f76 | 8afdb2ce7a190d3f35c117f508d5417f60f49bff | /ShortestDistance.cpp | d31f69e0636ec32b312c0a5b16f3b675dd1363cd | [] | no_license | Shahid96/Programming-notes | cbe399304d65560bdb960c112c60014ab6a27504 | 5bc5c06c122dc0ffc1f77c5aadfdd83354f1c67d | refs/heads/master | 2023-08-20T22:32:16.759812 | 2021-10-31T13:21:13 | 2021-10-31T13:21:13 | 423,139,181 | 0 | 0 | null | 2021-10-31T12:16:27 | 2021-10-31T12:16:26 | null | UTF-8 | C++ | false | false | 1,012 | cpp | ShortestDistance.cpp | #include <iostream>
using namespace std;
int main()
{
char ch;
int x=0,y=0;
cin>>ch;
while(ch!='\n')
{
switch(ch)
{
case 'N': y+=1; break;
case 'S': y-=1;break;
case 'E': x+=1;break;
case 'W': x-=1; break;
}
ch=cin.get();
}
cout<<"Displacement is :"<<x<<" "<<y<<endl;
if(x >=0 && y>=0)
{
for(int i=1;i<=x;i++)
cout<<"E";
for(int j=1;j<=y;j++)
cout<<"N";
}
else if(x <=0 && y>=0)
{
for(int i=1;i<=-x;i++)
cout<<"W";
for(int j=1;j<=y;j++)
cout<<"N";
}
else if(x <=0 && y<=0)
{
for(int i=1;i<=-x;i++)
cout<<"W";
for(int j=1;j<=-y;j++)
cout<<"S";
}
else if(x >=0 && y<=0)
{
for(int i=1;i<=x;i++)
cout<<"E";
for(int j=1;j<=-y;j++)
cout<<"S";
}
else
cout<<"Stay here ! Don't move;";
}
|
35ab9677ba8db6ec8709e9915ead195be33c0f7e | 9a337aff4be7a27d7646ad731b163e5a682e2e3f | /HW10/token_struct.cpp | 5d8e94faff8e181cabe5e3761f09267efe123895 | [] | no_license | viacheslav-konstantinov/MADE-algo_advanced | 6489655c3e0d41fcdf84cab651a7f27fbfec1d43 | 42d8b9ab94fb81be2e0e0ad935a15800e26d9096 | refs/heads/master | 2022-07-30T01:09:41.241007 | 2020-05-17T20:39:05 | 2020-05-17T20:39:05 | 264,748,623 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,128 | cpp | token_struct.cpp | #include <string>
#include "token_struct.hpp"
void token_struct::set(const token_struct& lhs)
{
is_integer = lhs.is_integer;
int_value = lhs.int_value;
float_value = lhs.float_value;
}
void token_struct::set_negative()
{
int_value = -int_value;
float_value = -float_value;
}
void token_struct::set_not()
{
if(is_integer)
{
if(int_value)
{
int_value = 1;
}
else
{
int_value = 0;
}
}
else
{
is_integer = true;
if(float_value)
{
int_value = 1;
}
else
{
int_value = 0;
}
}
}
void token_struct::compare_and_set(const token_struct& lhs, const token_struct& rhs, const compare_type oper)
{
is_integer = true;
if(lhs.is_integer && rhs.is_integer)
{
switch(oper)
{
case compare_type::eq:
int_value = static_cast<int>(lhs.int_value == rhs.int_value);
break;
case compare_type::ne:
int_value = static_cast<int>(lhs.int_value != rhs.int_value);
break;
case compare_type::g:
int_value = static_cast<int>(lhs.int_value > rhs.int_value);
break;
case compare_type::l:
int_value = static_cast<int>(lhs.int_value < rhs.int_value);
break;
case compare_type::ge:
int_value = static_cast<int>(lhs.int_value >= rhs.int_value);
break;
case compare_type::le:
int_value = static_cast<int>(lhs.int_value <= rhs.int_value);
break;
}
}
else if (!lhs.is_integer && !rhs.is_integer)
{
switch(oper)
{
case compare_type::eq:
int_value = static_cast<int>(lhs.float_value == rhs.float_value);
break;
case compare_type::ne:
int_value = static_cast<int>(lhs.float_value != rhs.float_value);
break;
case compare_type::g:
int_value = static_cast<int>(lhs.float_value > rhs.float_value);
break;
case compare_type::l:
int_value = static_cast<int>(lhs.float_value < rhs.float_value);
break;
case compare_type::ge:
int_value = static_cast<int>(lhs.float_value >= rhs.float_value);
break;
case compare_type::le:
int_value = static_cast<int>(lhs.float_value <= rhs.float_value);
break;
}
}
else if(!lhs.is_integer)
{
switch(oper)
{
case compare_type::eq:
int_value = static_cast<int>(lhs.float_value == static_cast<float>(rhs.int_value));
break;
case compare_type::ne:
int_value = static_cast<int>(lhs.float_value != static_cast<float>(rhs.int_value));
break;
case compare_type::g:
int_value = static_cast<int>(lhs.float_value > static_cast<float>(rhs.int_value));
break;
case compare_type::l:
int_value = static_cast<int>(lhs.float_value < static_cast<float>(rhs.int_value));
break;
case compare_type::ge:
int_value = static_cast<int>(lhs.float_value >= static_cast<float>(rhs.int_value));
break;
case compare_type::le:
int_value = static_cast<int>(lhs.float_value <= static_cast<float>(rhs.int_value));
break;
}
}
else
{
switch(oper)
{
case compare_type::eq:
int_value = static_cast<int>(static_cast<float>(lhs.int_value) == rhs.float_value);
break;
case compare_type::ne:
int_value = static_cast<int>(static_cast<float>(lhs.int_value) != rhs.float_value);
break;
case compare_type::g:
int_value = static_cast<int>(static_cast<float>(lhs.int_value) > rhs.float_value);
break;
case compare_type::l:
int_value = static_cast<int>(static_cast<float>(lhs.int_value) < rhs.float_value);
break;
case compare_type::ge:
int_value = static_cast<int>(static_cast<float>(lhs.int_value) >= rhs.float_value);
break;
case compare_type::le:
int_value = static_cast<int>(static_cast<float>(lhs.int_value) <= rhs.float_value);
break;
}
}
}
void token_struct::set_new_value(const token_struct& lhs, const token_struct& rhs, const char oper)
{
is_integer = (lhs.is_integer && rhs.is_integer);
if(is_integer)
{
switch(oper)
{
case '+':
int_value = lhs.int_value + rhs.int_value;
break;
case '-':
int_value = lhs.int_value - rhs.int_value;
break;
case '*':
int_value = lhs.int_value * rhs.int_value;
break;
case '/':
int_value = lhs.int_value / rhs.int_value;
break;
}
}
else if (!lhs.is_integer && !rhs.is_integer)
{
switch(oper)
{
case '+':
float_value = lhs.float_value + rhs.float_value;
break;
case '-':
float_value = lhs.float_value - rhs.float_value;
break;
case '*':
float_value = lhs.float_value * rhs.float_value;
break;
case '/':
float_value = lhs.float_value / rhs.float_value;
break;
}
}
else if(!lhs.is_integer)
{
switch(oper)
{
case '+':
float_value = lhs.float_value + static_cast<float>(rhs.int_value);
break;
case '-':
float_value = lhs.float_value - static_cast<float>(rhs.int_value);
break;
case '*':
float_value = lhs.float_value * static_cast<float>(rhs.int_value);
break;
case '/':
float_value = lhs.float_value / static_cast<float>(rhs.int_value);
break;
}
}
else
{
switch(oper)
{
case '+':
float_value = static_cast<float>(lhs.int_value) + rhs.float_value;
break;
case '-':
float_value = static_cast<float>(lhs.int_value) - rhs.float_value;
break;
case '*':
float_value = static_cast<float>(lhs.int_value) * rhs.float_value;
break;
case '/':
float_value = static_cast<float>(lhs.int_value) / rhs.float_value;
break;
}
}
} |
9b412a355d8f83d76865dba4c51bba993e134ec2 | 803f0fbc5973ff31fd5faca5c0f2981b2c52a591 | /C++/CodeForces/R-439-div.2/pB.cpp | 3e9ec5773c3e3560bd16c4dec07b872cb01e5cbf | [] | no_license | MiohitoKiri5474/CodesBackUp | 00ab52bd55732b8164a42cffd664407878f4390e | 4247fa032c8e88259dcc3992a21c510b6f2e8850 | refs/heads/master | 2023-08-09T14:46:10.445697 | 2023-08-04T01:12:58 | 2023-08-04T01:12:58 | 126,162,563 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 300 | cpp | pB.cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio ( false );
cin.tie ( 0 );
#define int long long
int a, b, ans = 1;
cin >> a >> b;
if ( b - a >= 10 )
ans = 0;
else
for ( int i = a + 1 ; i <= b ; i++ ){
ans *= i;
ans %= 10;
}
cout << ans << '\n';
} |
0d5f510787e5809fa3cf8728e4b57f68156e29af | 660f25caf939daf0de0cbdb28c40f493b9894c25 | /Practice labs option 15 year2 term2/15_Pract_3/15_Pract_3_code/warehouse.cpp | b20c389b1442de449b31ae6c1b5d3b093bb8bda9 | [] | no_license | keptt/Uni | 0bb270632a8dd3e980632397d21b87ce11093fa5 | 20555abb5ccb68160c2ce147978dc297ce3dea97 | refs/heads/master | 2020-04-09T04:41:42.263994 | 2019-06-16T10:43:55 | 2019-06-16T10:43:55 | 160,032,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 534 | cpp | warehouse.cpp | #include "warehouse.h"
Warehouse::Warehouse(std::string address, std::string mission, std::string circs, double area)
:Facility (address, mission, area), m_circs(circs)
{
}
std::string Warehouse::class_name() const
{
return "Class name: Warehouse\n";
}
std::string Warehouse::obj_data() const
{
std::string base_info(Facility::obj_data());
char buffer[125];
sprintf(buffer, "Circumstances: %s\n", m_circs.c_str());
base_info += (std::string)buffer;
return base_info;
}
Warehouse::~Warehouse()
{
}
|
645dcdfb7350f2b9ffbef02499555f6ef46ec9ec | b6d1df49c1ec621a02204b1100312ecbb3e76ad3 | /src/osg/osgAnnotators/SphereSegmentsGroup.h | 72f83699cc55f251d07bf583aae8b4790a14efe2 | [] | 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 | 3,464 | h | SphereSegmentsGroup.h | // ==========================================================================
// Header file for SPHERESEGMENTSGROUP class
// ==========================================================================
// Last modified on 8/4/11; 8/24/11; 12/2/11
// ==========================================================================
#ifndef SPHERESEGMENTSGROUP_H
#define SPHERESEGMENTSGROUP_H
#include <iostream>
#include "osg/osgAnnotators/AnnotatorsGroup.h"
#include "osg/osgGeometry/GeometricalsGroup.h"
#include "osg/osgAnnotators/SphereSegment.h"
class Clock;
class Ellipsoid_model;
class threevector;
class SphereSegmentsGroup : public GeometricalsGroup, public AnnotatorsGroup
{
public:
// Initialization, constructor and destructor functions:
SphereSegmentsGroup(Pass* PI_ptr,threevector* GO_ptr,
bool display_spokes_flag=false,bool include_blast_flag=true);
SphereSegmentsGroup(
Pass* PI_ptr,Clock* clock_ptr,Ellipsoid_model* EM_ptr,
threevector* GO_ptr,bool display_spokes_flag=false,
bool include_blast_flag=true);
virtual ~SphereSegmentsGroup();
friend std::ostream& operator<<
(std::ostream& outstream,const SphereSegmentsGroup& f);
// Set & get methods:
SphereSegment* get_SphereSegment_ptr(int n) const;
SphereSegment* get_ID_labeled_SphereSegment_ptr(int ID) const;
// SphereSegment creation and manipulation methods:
SphereSegment* generate_new_canonical_SphereSegment(
double radius,double az_spread,double el_spread,int ID=-1);
SphereSegment* generate_new_SphereSegment(
double radius,double az_min,double az_max,double el_min,double el_max,
int ID=-1);
SphereSegment* generate_new_SphereSegment(
double radius,threevector posn,double az_min,double az_max,
double el_min,double el_max,int ID=-1);
SphereSegment* generate_new_hemisphere(
double radius,threevector& posn,int ID=-1);
// void generate_spheresegment_group(
// SphereSegment* spheresegment_ptr,
// bool display_spokes_flag=false,bool include_blast_flag=true);
void initialize_vertical_posn(SphereSegment* curr_SphereSegment_ptr);
bool erase_SphereSegment();
bool unerase_SphereSegment();
void change_size(double factor);
// void reset_colors();
// SphereSegment animation methods:
void update_display();
// Ascii feature file I/O methods
void save_info_to_file();
bool read_info_from_file();
// RF direction finding member functions:
void generate_RF_direction_segments(std::string rf_dir_filename);
private:
bool display_spokes_flag,include_blast_flag;
void allocate_member_objects();
void initialize_member_objects();
void docopy(const SphereSegmentsGroup& f);
void initialize_new_SphereSegment(
SphereSegment* curr_SphereSegment_ptr,int OSGsubPAT_number=0);
};
// ==========================================================================
// Inlined methods:
// ==========================================================================
// Set & get member functions:
inline SphereSegment* SphereSegmentsGroup::get_SphereSegment_ptr(int n) const
{
return dynamic_cast<SphereSegment*>(get_Graphical_ptr(n));
}
// --------------------------------------------------------------------------
inline SphereSegment* SphereSegmentsGroup::get_ID_labeled_SphereSegment_ptr(
int ID) const
{
return dynamic_cast<SphereSegment*>(get_ID_labeled_Graphical_ptr(ID));
}
#endif // SphereSegmentsGroup.h
|
2ddaef13103e2dcfeb380e088bb7bdf2724e94f0 | aa903ef99df7b688e2639f304550bb96a57ea7af | /Assignment2/Assignment2/PhoneDirectory.h | e66de969f78061d01bcc6a2cfc7b03c4b0429503 | [] | no_license | Ashish-Surve/Learn_C-CPP | f4a4f98b33d775362beebb4aeb91b7407124e18c | 9e7cd7239a96d7af70b10f5b3d19dac58a8ce7d5 | refs/heads/master | 2020-12-13T20:00:10.478308 | 2020-02-13T12:17:35 | 2020-02-13T12:17:35 | 234,510,149 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 366 | h | PhoneDirectory.h | #pragma once
#include<iostream>
#include<string>
#include<vector>
#include"Record.h"
using namespace std;
class PhoneDirectory
{
vector<Record> pDir;
public:
PhoneDirectory() :pDir(100) {};
void Search_Customer_Details();
void Write_to_file(string,string,Handling_Stage);
void Add_Customer_Details();
void Read_From_file(string, string, Handling_Stage);
}; |
8ad073001c440004121758de7d7b6b2ecb5ef83b | 8597d6434b56c1778ccb3c8adf9df28a4f99d1de | /SearchEngine/SearchEngine/abcde/cse535_falcon/Ranker/booleanModel.cpp | 10035dc36145ed80691fa47310e2a7dca984435a | [] | no_license | codeathon/SearchEngine | ea247a4d8b3e467c11e1b01b34a9b522fc9d35d8 | 5de9d45b230216d0e4b6c33a44d0ae1396ed6640 | refs/heads/master | 2016-09-06T21:49:30.414186 | 2012-05-21T15:29:26 | 2012-05-21T15:29:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,019 | cpp | booleanModel.cpp | /*
* booleanModel.cpp
*
* Created on: Oct 29, 2011
* Author: nishant
*/
#include "booleanModel.h"
#include "../Indexer/Config.h"
#include "../DocumentRepresentation/CDocument.h"
#include "../DocumentProcessor/CDocumentProcessor.h"
#include "../QueryRepresentation/CQuery.h"
#include "../include/CUtilities.h"
#include <math.h>
#include <algorithm>
#include <iomanip>
using namespace std;
booleanModel::booleanModel() {
// TODO Auto-generated constructor stub
final_docs.clear();
}
booleanModel::~booleanModel() {
// TODO Auto-generated destructor stub
}
bool booleanModel::get_doc_ids(CQuery *query)
{
vector<string>::iterator query_it;
vector<size_t>::iterator doc_id;
string qout = Config::getValue("query_out");
qout = qout +"/Query_Output.txt";
ofstream ofs;
ofs.open(qout.c_str(),fstream::app);
multimap<double, string> score_sort;
for (query_it = query->qtokens.begin(); query_it != query->qtokens.end(); query_it++)
{
vector<std::string>temp;
//cout<<"token:"<<*query_it<<"\n";
map<string, int>::iterator doc_freq_it;
map<string,int> doc_freq;
string doc_name;
if(CDocument::term_cnt_dict.find(*query_it) != CDocument::term_cnt_dict.end())
{
doc_freq = CDocument::term_cnt_dict[*query_it];
for(doc_freq_it = doc_freq.begin(); doc_freq_it != doc_freq.end(); doc_freq_it++)
{
doc_name = (*doc_freq_it).first;
temp.push_back(doc_name);
}
}
if(final_docs.size()==0)
final_docs = temp;
else
{
{
vector<string>temp2;
std::vector<std::string>::iterator it1;
std::vector<std::string>::iterator it2;
temp2 = final_docs;
final_docs.clear();
int x,y;
x = temp2.size();
y=temp.size();
if(x<y)
{
for(it1=temp2.begin();it1!=temp2.end();++it1)
for(it2=temp.begin();it2!=temp.end();++it2)
{
if(*it1==*it2)
final_docs.push_back(*it1);
}
}
else
{
for(it1=temp.begin();it1!=temp.end();++it1)
for(it2=temp2.begin();it2!=temp2.end();++it2)
{
if(*it1==*it2)
final_docs.push_back(*it1);
}
}
}
}
}
vector<string>::iterator its;
int counter = 0;
if(CUtilities::online_mode_enabled==1)
{
if(CUtilities::num_for_onlie_mode>final_docs.size())
CUtilities::num_for_onlie_mode = final_docs.size();
cout<<"The number of documents retrieved = "<<CUtilities::num_for_onlie_mode<<endl;
}
for(its=final_docs.begin();its!=final_docs.end();++its)
{
int w=0;
string file_contents,line;
counter++;
string str;
str = *its;
size_t last_pos = str.rfind('\/');
str = str.substr(last_pos, string::npos);
CUtilities::delete_character(str, '\/');
if(CUtilities::online_mode_enabled==1)
{
if(counter>CUtilities::num_for_onlie_mode)
return true;
string fname;
int docID = CDocument::doc_name_doc_id[*its];
//cout<<"id :"<<docID<<endl;
stringstream ss;
ss<<docID;
if((*its).find("wiki")!=string::npos)
{
fname= CUtilities::semwiki_dir_path +"/" + ss.str() +"_semwiki.txt";
w=1;
}
else
{
fname = *its;
}
ifstream ifs(fname.c_str());
int c=0;
while ( !ifs.eof() ) {
c++;
if(c>=11&&w==0)
break;
getline( ifs, line );
file_contents += line;
file_contents+='\n';
}
cout<<"Document :"<<*its<<endl;
cout<<"Contents:"<<file_contents<<endl;
}
else
ofs<<query->getQueryId() << "\t" << "0" << "\t" << str << "\t" << final_docs.size() << "\t" << "0" << "\t" << "backrub" << "\n";
}
return true;
}
|
42e07cf648d65789ff90df84f5df4020e912ca07 | 95ae7dfa9ee578f1b24a65986ff78bf77ceca0c5 | /Engine/source/assets/tamlAssetReferencedVisitor.h | c744a880c753594790850a5067e81327b546e376 | [
"MIT",
"LicenseRef-scancode-unknown"
] | permissive | TorqueGameEngines/Torque3D | 4e1f6a05cc0928980c8c7c20bcdd680eaa6dcee8 | a445a4364664e299196bd551d213844486080145 | refs/heads/development | 2023-09-03T12:40:40.658487 | 2023-08-24T14:44:43 | 2023-08-24T14:44:43 | 267,440,108 | 1,192 | 178 | MIT | 2023-09-13T14:28:16 | 2020-05-27T22:35:54 | C++ | UTF-8 | C++ | false | false | 3,544 | h | tamlAssetReferencedVisitor.h | //-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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 _TAML_ASSET_REFERENCED_VISITOR_H_
#define _TAML_ASSET_REFERENCED_VISITOR_H_
#ifndef _TAML_VISITOR_H_
#include "persistence/taml/tamlVisitor.h"
#endif
#ifndef _TAML_PARSER_H_
#include "persistence/taml/tamlParser.h"
#endif
#ifndef _ASSET_FIELD_TYPES_H_
#include "assets/assetFieldTypes.h"
#endif
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
class TamlAssetReferencedVisitor : public TamlVisitor
{
public:
typedef StringTableEntry typeAssetId;
typedef HashMap<typeAssetId, StringTableEntry> typeAssetReferencedHash;
private:
typeAssetReferencedHash mAssetReferenced;
public:
TamlAssetReferencedVisitor() {}
virtual ~TamlAssetReferencedVisitor() {}
const typeAssetReferencedHash& getAssetReferencedMap( void ) const { return mAssetReferenced; }
void clear( void ) { mAssetReferenced.clear(); }
virtual bool wantsPropertyChanges( void ) { return false; }
virtual bool wantsRootOnly( void ) { return false; }
virtual bool visit( const TamlParser& parser, TamlVisitor::PropertyState& propertyState )
{
// Debug Profiling.
PROFILE_SCOPE(TamlAssetReferencedVisitor_Visit);
// Fetch property value.
const char* pPropertyValue = propertyState.getPropertyValue();
// Fetch property word count.
const U32 propertyWordCount = StringUnit::getUnitCount( pPropertyValue, ASSET_ASSIGNMENT_TOKEN );
// Finish if there's not two words.
if ( propertyWordCount != 2 )
return true;
// Finish if the first word is not an asset signature.
if ( StringTable->insert( StringUnit::getUnit( pPropertyValue, 0, ASSET_ASSIGNMENT_TOKEN ) ) != assetLooseIdSignature )
return true;
// Get asset Id.
typeAssetId assetId = StringTable->insert( StringUnit::getUnit( pPropertyValue, 1, ASSET_ASSIGNMENT_TOKEN ) );
// Finish if we already have this asset Id.
if ( mAssetReferenced.contains( assetId ) )
return true;
// Insert asset reference.
mAssetReferenced.insert( assetId, StringTable->EmptyString() );
return true;
}
};
#endif // _TAML_ASSET_REFERENCED_VISITOR_H_
|
7d89c78c447a9ce2bb90776b62039cdb424d25d5 | f4892c12c0e2ffdfbd678176dc8fa03f051314c4 | /tiledb/sm/filter/filter_storage.h | 97e2923fc078e0e45a5d7332c6c4310cb1d8a5fa | [
"MIT"
] | permissive | TileDB-Inc/TileDB | 06c15bcf6e3c62b191a6daa40fb33b41af2bdcdc | fddbe978d50ea7c9706fb0b7ca403c47986a4909 | refs/heads/dev | 2023-09-04T01:18:20.642838 | 2023-08-31T19:23:04 | 2023-09-02T14:36:02 | 86,868,560 | 1,779 | 204 | MIT | 2023-09-14T14:40:20 | 2017-03-31T23:44:23 | C++ | UTF-8 | C++ | false | false | 3,057 | h | filter_storage.h | /**
* @file filter_storage.h
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2017-2021 TileDB, Inc.
*
* 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.
*
* @section DESCRIPTION
*
* This file declares class FilterStorage.
*/
#ifndef TILEDB_FILTER_STORAGE_H
#define TILEDB_FILTER_STORAGE_H
#include <list>
#include <memory>
#include <unordered_map>
#include "tiledb/common/common.h"
#include "tiledb/common/heap_memory.h"
#include "tiledb/common/status.h"
using namespace tiledb::common;
namespace tiledb {
namespace sm {
class Buffer;
/**
* Manages a ref-counted pool of buffers, used for filter I/O.
*/
class FilterStorage {
public:
/**
* Return a buffer from the pool, allocating a new one if necessary. The
* buffer returned by this function will not be available for reuse until it
* is reclaimed by this instance via the reclaim() method.
*
* @return Buffer from the pool
*/
shared_ptr<Buffer> get_buffer();
/** Return the number of buffers in the internal available list. */
uint64_t num_available() const;
/** Return the number of buffers in the internal in-use list. */
uint64_t num_in_use() const;
/**
* Reclaims the given buffer, marking it as available to return with a
* subsequent call to get_buffer().
*
* If the given buffer is not managed by this instance, reclaiming it is a
* no-op.
*
* @param buffer Pointer to underlying buffer to reclaim.
* @return Status
*/
Status reclaim(Buffer* buffer);
private:
/** List of buffers that are available to be used (may be empty). */
std::list<shared_ptr<Buffer>> available_;
/** List of buffers that are currently in use (may be empty). */
std::list<shared_ptr<Buffer>> in_use_;
/**
* Mapping of underlying Buffer pointer to linked list node in the in_use_
* list.
*/
std::unordered_map<Buffer*, std::list<shared_ptr<Buffer>>::iterator>
in_use_list_map_;
};
} // namespace sm
} // namespace tiledb
#endif // TILEDB_FILTER_STORAGE_H
|
b714f846b6763ff37cc1264ea6a87484c00888ca | e51693dce1f3f6d61d951b585b0e088cf397bfe3 | /src/objLoader.cpp | c9f3528189ab3edd84e37d043f3ee60ad17f0226 | [] | no_license | sora-M31/rayTracer | 2ab117cf51cfed8b333a6b1a92f256cffaa7a3a6 | baedabc2dc3f18207be085f6f9d39edcf84b2440 | refs/heads/master | 2021-01-02T22:58:37.222852 | 2012-08-09T17:01:50 | 2012-08-09T17:01:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,468 | cpp | objLoader.cpp | #include "objLoader.h"
namespace rayTracer
{
//------------------------------------------------------------------------------
bool ObjLoader::ParseFile( const std::string& _fileName )
{
std::ifstream fileIn;
fileIn.open( _fileName.c_str() );
std::string lineBuffer;
if ( fileIn.is_open() )
{
while ( !fileIn.eof() )
{
//parse each line into a string
getline( fileIn, lineBuffer, '\n' );
//parse string to tokens with delimiter
StringList tokens;
Tokenize(lineBuffer, " ", tokens);
//put value in different array according to their type
StringList::iterator iter = tokens.begin();
if ( iter!= tokens.end())
{
if ( *iter == "v")
{
tokens.pop_front();
TokenToArray( tokens, m_vertexBuffer );
}
else if (*iter == "vn")
{
tokens.pop_front();
TokenToArray( tokens, m_normalBuffer );
}
else if ( *iter == "vt")
{
tokens.pop_front();
TokenToArray( tokens, m_textureBuffer );
}
else if ( *iter == "f")
{
StringList faceToken;
for(++iter;iter!= tokens.end();++iter)
{
Tokenize( *iter, "/", faceToken );
}
TokenToArray( faceToken, m_faceBuffer );
}
}
}
fileIn.close();
Serialize();
return true;
}
else
return false;
}
//------------------------------------------------------------------------------
void ObjLoader::PrintLoadedInfo()
{
for(uint32_t i=0; i<m_vertexBuffer.size(); ++i)
{
if (i%3 ==2)
std::cout<<m_vertexBuffer[i]<<" \n";
else if (i%3 ==0)
std::cout<<"v "<<m_vertexBuffer[i]<<" ";
else
std::cout<<m_vertexBuffer[i]<<" ";
}
for(uint32_t i=0; i<m_textureBuffer.size(); ++i)
{
if (i%2 ==1)
std::cout<<m_textureBuffer[i]<<" \n";
else
std::cout<<"vt "<<m_textureBuffer[i]<<" ";
}
for(uint32_t i=0; i<m_normalBuffer.size(); ++i)
{
if ( i%3 ==2)
std::cout<<m_normalBuffer[i]<<" \n";
else if (i%3 ==0)
std::cout<<"vn "<<m_normalBuffer[i]<<" ";
else
std::cout<<m_normalBuffer[i]<<" ";
}
for(uint32_t i=0; i<m_faceBuffer.size(); ++i)
{
if (i%9==8)
std::cout<<m_faceBuffer[i]<<"\n";
else if (i%9 ==0)
std::cout<<"f "<<m_faceBuffer[i]<<"/";
else if ( i%3 ==2)
std::cout<<m_faceBuffer[i]<<" ";
else
std::cout<<m_faceBuffer[i]<<"/";
}
}
//------------------------------------------------------------------------------
void ObjLoader::ClearData()
{
m_vertexBuffer.clear();
m_normalBuffer.clear();
m_textureBuffer.clear();
m_faceBuffer.clear();
}
//------------------------------------------------------------------------------
void ObjLoader::TokenToArray( const StringList& _tokens, std::vector<float>& o_array)
{
StringList::const_iterator iter = _tokens.begin();
while ( iter!=_tokens.end() )
{
o_array.push_back( atof( (*iter).c_str() ) );
++iter;
}
}
//------------------------------------------------------------------------------
/*from[http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html]*/
void ObjLoader::Tokenize( const std::string& _str,
const std::string& _delimiters,
StringList& o_tokens )
{
std::string::size_type lastPos = _str.find_first_not_of( _delimiters, 0);
std::string::size_type pos = _str.find_first_of( _delimiters, lastPos);
while ( pos != std::string::npos || lastPos != std::string::npos )
{
o_tokens.push_back( _str.substr( lastPos, pos-lastPos ) );
lastPos = _str.find_first_not_of( _delimiters,pos );
pos = _str.find_first_of( _delimiters, lastPos );
}
}
//------------------------------------------------------------------------------
void ObjLoader::Serialize()
{
if ( m_textureBuffer.size()!=0)
{
uint32_t size = m_faceBuffer.size();
for( uint32_t i=0; i<size; i+=3)
{
//vertex
uint32_t vertexIndex = ( m_faceBuffer[i] -1)*3;
m_vertexArray.push_back( Vector(m_vertexBuffer[vertexIndex], m_vertexBuffer[vertexIndex+1], m_vertexBuffer[vertexIndex+2], 1.0f));
//normal
uint32_t normalIndex = ( m_faceBuffer[i+2]-1)*3;
m_normalArray.push_back( Vector(m_normalBuffer[normalIndex], m_normalBuffer[normalIndex+1], m_normalBuffer[normalIndex+2], 0.0f));
//texture
uint32_t textureIndex = ( m_faceBuffer[i+1]-1)*2;
//std::cout<<textureIndex<<" textureIndex\n";
m_textureArray.push_back( Vector2D(m_textureBuffer[textureIndex], m_textureBuffer[textureIndex+1]) );
}
}
else
{
std::cout<<"no texture\n";
uint32_t size = m_faceBuffer.size();
for( uint32_t i=0; i<size; i+=2)
{
//vertex
uint32_t vertexIndex = ( m_faceBuffer[i] -1)*3;
//std::cout<<m_faceBuffer[i] -1<<" ";
// std::cout<<vertexIndex<<" ";
// std::cout<<vertexIndex+1<<" ";
// std::cout<<vertexIndex+2<<"\n";
m_vertexArray.push_back( Vector(m_vertexBuffer[vertexIndex], m_vertexBuffer[vertexIndex+1], m_vertexBuffer[vertexIndex+2], 1.0f));
//normal
uint32_t normalIndex = (m_faceBuffer[i+1]-1)*3;
m_normalArray.push_back( Vector(m_normalBuffer[normalIndex], m_normalBuffer[normalIndex+1], m_normalBuffer[normalIndex+2], 0.0f));
}
}
}
void ObjLoader::PrintSerializedInfo()
{
for(uint32_t i=0; i<m_vertexArray.size(); ++i)
{
std::cout<<"vertex "<<m_vertexArray[i]<<" \n";
}
for(uint32_t i=0; i<m_textureArray.size(); ++i)
{
std::cout<<"texture "<<m_textureArray[i]<<" \n";
}
for(uint32_t i=0; i<m_normalArray.size(); ++i)
{
std::cout<<"normal "<<m_normalArray[i]<<" \n";
}
}
}//end of space
|
d34cf37613b92405120520bc6ea2aae25c76acdb | c150efd9213c3bc864f2035432d4ffb908d2544d | /backjoon/17825.cpp | fe2ae49d39ed4a41f3add4656496754254fe8dd8 | [] | no_license | yeoneei/algorithm | d1b4df453a575a317cda599981779e743e6d8700 | 3779e163547c7c6b05d33d38a5069db9b94a3ba4 | refs/heads/master | 2020-11-28T09:03:29.514593 | 2020-05-05T07:26:56 | 2020-05-05T07:26:56 | 229,764,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,033 | cpp | 17825.cpp | //
// 17825.cpp
// backjoon
//
// Created by 조연희 on 26/03/2020.
// Copyright © 2020 조연희. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
int score[33]={2,4,6,8,10,12,14,16,18,20,13,
16,19,22,24,25,22,24,26,28,30,
28,27,26,32,34,36,38,30,35,40,0,0
};
int map[32][5]={
{1,2,3,4,5},
{2,3,4,5,6},{3,4,5,6,7},{4,5,6,7,8},{10,11,12,15,28},{6,7,8,9,16},
{7,8,9,16,17},{8,9,16,17,18},{9,16,17,18,19},{13,14,15,28,29},{11,12,15,28,29},
//11번
{12,15,28,29,30},{15,28,29,30,31},{14,15,28,29,30},{15,28,29,30,31},{28,29,30,31,31},
//16번
{17,18,19,20,24},{18,19,20,24,25},{19,20,24,25,26},{20,24,25,26,27},{21,22,23,15,28},
//21번
{22,23,15,28,29},{23,15,28,29,30},{15,28,29,30,31},{25,26,27,30,31},{26,27,30,31,31},
//26번
{27,30,31,31,31},{30,31,31,31,31},{29,30,31,31,31},{30,31,31,31,31},{31,31,31,31,31},{31,31,31,31,31},
};
int arr[10];
int answer=0;
int mar[10];
int marCheck(int i, vector<int>& Mar){
int x;
if(Mar[mar[i]]==-1){
x= Mar[mar[i]]+arr[i];
}else{
x = map[Mar[mar[i]]][arr[i]-1];
}
if(x>=31) return x;
for(int i=0; i<4;i++){
if(Mar[i]>=31) continue;
//이거 집어 넣으면 왜 안돼지?
if(mar[i]==i)continue;
if(Mar[i]==x) return -1;
}
return x;
}
void dfs(int cnt){
if(cnt==10){
//Mar : 현재 말위치 mar:이번엔 어떤 말 차례인지 arr: 주사위 몇번인지
int sum=0;
vector<int> Mar(4,-1);
for(int i=0; i<10;i++){
if(Mar[mar[i]]>=31) return;
int x = marCheck(i, Mar);
if(x==-1) return;
Mar[mar[i]]=x;
if(Mar[mar[i]]>=31)continue;
sum+=score[Mar[mar[i]]];
}
answer = max(answer,sum);
return;
}
for(int i=0; i<=3;i++){
mar[cnt]=i;
dfs(cnt+1);
}
}
int main(){
for(int i=0; i<10;i++){
cin>>arr[i];
}
dfs(0);
cout<<answer;
}
|
3bdefae5aa70046177dfab024854b9c083d815d1 | 9cc4df41d0a5921486e557c8870adf9f8863a443 | /network/Thread.h | 0ce7c44443c298ee604b6b59021584643d308f9d | [] | no_license | euiseo80/JasterEmbeddedServer | a32251ccb6662bc05808513a5286ad537ea2dba2 | 4d44c6af499f7cad558a79af7715533bd9b33da0 | refs/heads/master | 2021-01-16T00:22:39.058979 | 2012-10-29T04:42:50 | 2012-10-29T04:42:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,736 | h | Thread.h | #ifndef _THREAD_H //
#define _THREAD_H
#include "Runnable.h"
#include "ScopeMutex.h"
#include "condition.h"
#include "./Task.h"
#include <pthread.h>
///Boolean type
#ifndef BOOL
typedef enum BoolEnum{
FALSE,
TRUE
} BOOL;
#endif
//Create Thread constructor be created firstly before child
class Thread: public Runnable { // Runnable
public:
Thread();
//Thread& operator=(const Thread&);
Thread(Runnable* pRunnable);
virtual ~Thread();
int Start();
int Wait();
virtual void Run(); //
const int getThreadId(){return _threadId;};
void setThreadId(const int id){_threadId = id;};
ScopeMutex* getInitLocker(){return _init_singnal_Mutex;};
void setInitLocker(ScopeMutex* event){_init_singnal_Mutex = event;};
ScopeMutex* getLocker(){return _wait_singnal_Mutex;};
void setLocker(ScopeMutex* event){_wait_singnal_Mutex = event;};
Condition& getCondition(){return _singnal_Condition;};
bool getClosedSignalFlg() {
return _being_closed_signal;
};
int getStatusCanWork() const {
return _status_canWork;
};
void setStatusCanWork(int statusCanWork) {
_status_canWork = statusCanWork;
};
private:
Task _task;
int _threadId; // opt. number of thread
pthread_t _thread;
Runnable* _runnable;
pthread_attr_t _thread_attr; // thread attributes
bool _running; // true if thread is running
int _status_canWork; //The status of thread is it waiting,thead ready for work.
bool _being_closed_signal; //Thread should be close.
/// Event is recived from mainStack .
ScopeMutex * _init_singnal_Mutex;
ScopeMutex * _wait_singnal_Mutex;
Condition _singnal_Condition;
static void* Main(void* pInst);
};
#endif
|
11806b96a766dc0ba0f7bbb69d3f5fa5bde91786 | eb3178d5e7227c881e1cb0df1c811fe78296986c | /benchmark/core/lex/lexer_legacy_benchmark.cpp | 34e984857b10c9a68814c6cad380585661c7e0f9 | [] | no_license | JamesYang007/Docgen | 18e4ca4d852b69d8d2f4b9dbbc0f4a10ba866dab | 7e78c67acdc9cc9d8c789441135271cbd649104f | refs/heads/master | 2020-11-28T02:27:59.007810 | 2020-08-15T00:07:13 | 2020-08-15T00:07:13 | 229,680,399 | 5 | 0 | null | 2020-01-19T19:32:11 | 2019-12-23T05:07:10 | C++ | UTF-8 | C++ | false | false | 1,409 | cpp | lexer_legacy_benchmark.cpp | #include <core/lex/legacy/lexer.hpp>
#include "lexer_base_fixture.hpp"
namespace docgen {
namespace core {
namespace lex {
namespace legacy {
struct lexer_legacy_fixture : lexer_base_fixture
{};
BENCHMARK_F(lexer_legacy_fixture, data_1_test)(benchmark::State& st)
{
for (auto _ : st) {
FILE* file = fopen(data_1_path, "r");
Lexer lexer(file);
lexer.process();
benchmark::DoNotOptimize(lexer.get_tokens()[0]);
fclose(file);
}
}
BENCHMARK_F(lexer_legacy_fixture, data_2_test)(benchmark::State& st)
{
for (auto _ : st) {
FILE* file = fopen(data_2_path, "r");
Lexer lexer(file);
lexer.process();
benchmark::DoNotOptimize(lexer.get_tokens()[0]);
fclose(file);
}
}
BENCHMARK_F(lexer_legacy_fixture, data_3_test)(benchmark::State& st)
{
for (auto _ : st) {
FILE* file = fopen(data_3_path, "r");
Lexer lexer(file);
lexer.process();
benchmark::DoNotOptimize(lexer.get_tokens()[0]);
fclose(file);
}
}
BENCHMARK_F(lexer_legacy_fixture, data_4_test)(benchmark::State& st)
{
for (auto _ : st) {
FILE* file = fopen(data_4_path, "r");
Lexer lexer(file);
lexer.process();
benchmark::DoNotOptimize(lexer.get_tokens()[0]);
fclose(file);
}
}
} // namespace legacy
} // namespace lex
} // namespace core
} // namespace docgen
|
f808de9b0e4f73a37ca2ba8995553b532e3f1639 | f70e0d692a6f865de0f20dfb8e976cbb7be23506 | /src/src/inventory_system/block.cpp | 227bd4ead11d67164874dd8a4f7a922fd5cac7df | [] | no_license | enoch-solano/mini_minecraft | 1c3850e55fa70063c5988204f6abc744575bba9e | c71cbd89a4cd253849f65cec701cd4b03dcef095 | refs/heads/master | 2023-07-11T05:40:19.057553 | 2021-08-24T20:02:03 | 2021-08-24T20:02:03 | 396,045,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,337 | cpp | block.cpp | #include "block.h"
Block::Block(OpenGLContext *context, BlockType type)
: Drawable(context),
m_type(type),
m_len(0.06f),
m_time(0.f),
m_is_spinning(false) {}
void Block::create() {
std::vector<vertexAttribute> vboData;
std::vector<GLuint> idxData;
FaceDirection dir[6] = { TOP, RIGHT, FRONT, BOTTOM, LEFT, BACK };
for (int i = 0; i < 6; i++) {
addFace(vboData, idxData, dir[i]);
}
m_count = static_cast<int>(idxData.size());
// send index data to the GPU
generateIdxOpq();
mp_context->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_bufIdxOpq);
mp_context->glBufferData(GL_ELEMENT_ARRAY_BUFFER, idxData.size() * sizeof(GLuint), idxData.data(), GL_STATIC_DRAW);
// send VBO data to the GPU
generateOpq();
mp_context->glBindBuffer(GL_ARRAY_BUFFER, m_bufOpq);
mp_context->glBufferData(GL_ARRAY_BUFFER, vboData.size() * sizeof(vertexAttribute), vboData.data(), GL_STATIC_DRAW);
}
void Block::addFace(std::vector<vertexAttribute> &vboData,
std::vector<GLuint> &idxData, FaceDirection dir)
{
if (m_type == EMPTY) {
return;
}
// adds the appropriate vertex indices for new vertices
GLuint prev_num_verts = vboData.size();
for (GLuint i = 0; i < 2; i++) {
idxData.push_back(prev_num_verts);
idxData.push_back(prev_num_verts + i+1);
idxData.push_back(prev_num_verts + i+2);
}
// holds vertex VBO data of THIS face
std::array<vertexAttribute, 4> faceVBOData;
//////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////// DETERMINES ATTRIBUTES BASED on TYPE of BLOCK //////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
glm::vec2 offset; // determines offset in texture map for each block
float face_cos_pow; // the cosine power for the Blinn-Phong reflection model
float face_is_animateable = -1.f; // the animateable flag
switch(m_type) {
case GRASS:
offset = dir == TOP ? glm::vec2(8, 13) : (dir == BOTTOM ? glm::vec2(2, 15) : glm::vec2(3, 15));
break;
case DIRT:
offset = glm::vec2(2, 15);
break;
case STONE:
offset = glm::vec2(1, 15);
break;
case SNOW:
offset = glm::vec2(2, 11);
break;
case SAND:
offset = glm::vec2(2, 14);
break;
case SPONGE:
offset = glm::vec2(0, 12);
break;
case RED_CLAY:
offset = glm::vec2(8, 5);
break;
default:
offset = dir == TOP ? glm::vec2(8, 13) : (dir == BOTTOM ? glm::vec2(2, 15) : glm::vec2(3, 15));
face_cos_pow = 2.f;
break;
}
// adds the appropriate uv coordinates for this face
faceVBOData[0].uv = (glm::vec2(1.f, 1.f) + offset) / 16.f;
faceVBOData[1].uv = (glm::vec2(0.f, 1.f) + offset) / 16.f;
faceVBOData[2].uv = (glm::vec2(0.f, 0.f) + offset) / 16.f;
faceVBOData[3].uv = (glm::vec2(1.f, 0.f) + offset) / 16.f;
//////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////// DETERMINES ATTRIBUTES BASED on DIR. of BLOCK //////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
// determines appropriate face normal to attach to face, along with positions
glm::vec4 face_nor;
switch(dir) {
case RIGHT:
face_nor = glm::vec4(1.f, 0.f, 0.f, 0.f);
faceVBOData[0].pos = glm::vec4(m_len, m_len, m_len, 1.f);
faceVBOData[1].pos = glm::vec4(m_len, m_len, -m_len, 1.f);
faceVBOData[2].pos = glm::vec4(m_len, -m_len, -m_len, 1.f);
faceVBOData[3].pos = glm::vec4(m_len, -m_len, m_len, 1.f);
break;
case LEFT:
face_nor = glm::vec4(-1.f, 0.f, 0.f, 0.f);
faceVBOData[0].pos = glm::vec4(-m_len, m_len, -m_len, 1.f);
faceVBOData[1].pos = glm::vec4(-m_len, m_len, m_len, 1.f);
faceVBOData[2].pos = glm::vec4(-m_len, -m_len, m_len, 1.f);
faceVBOData[3].pos = glm::vec4(-m_len, -m_len, -m_len, 1.f);
break;
case TOP:
face_nor = glm::vec4(0.f, 1.f, 0.f, 0.f);
faceVBOData[0].pos = glm::vec4(-m_len, m_len, -m_len, 1.f);
faceVBOData[1].pos = glm::vec4( m_len, m_len, -m_len, 1.f);
faceVBOData[2].pos = glm::vec4( m_len, m_len, m_len, 1.f);
faceVBOData[3].pos = glm::vec4(-m_len, m_len, m_len, 1.f);
break;
case BOTTOM:
face_nor = glm::vec4(0.f, -1.f, 0.f, 0.f);
faceVBOData[0].pos = glm::vec4(-m_len, -m_len, -m_len, 1.f);
faceVBOData[1].pos = glm::vec4(-m_len, -m_len, m_len, 1.f);
faceVBOData[2].pos = glm::vec4( m_len, -m_len, m_len, 1.f);
faceVBOData[3].pos = glm::vec4( m_len, -m_len, -m_len, 1.f);
break;
case FRONT:
face_nor = glm::vec4(0.f, 0.f, 1.f, 0.f);
faceVBOData[0].pos = glm::vec4(-m_len, m_len, m_len, 1.f);
faceVBOData[1].pos = glm::vec4( m_len, m_len, m_len, 1.f);
faceVBOData[2].pos = glm::vec4( m_len, -m_len, m_len, 1.f);
faceVBOData[3].pos = glm::vec4(-m_len, -m_len, m_len, 1.f);
break;
case BACK:
face_nor = glm::vec4(0.f, 0.f, -1.f, 0.f);
faceVBOData[0].pos = glm::vec4( m_len, m_len, -m_len, 1.f);
faceVBOData[1].pos = glm::vec4(-m_len, m_len, -m_len, 1.f);
faceVBOData[2].pos = glm::vec4(-m_len, -m_len, -m_len, 1.f);
faceVBOData[3].pos = glm::vec4( m_len, -m_len, -m_len, 1.f);
break;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
float yaw = yaw_angle;
if (m_is_spinning) {
yaw += m_time;
m_time += 1 / spin_rate;
}
glm::mat4 rot = glm::rotate(glm::mat4(), roll_angle, glm::vec3(1,0,0)) * glm::rotate(glm::mat4(), yaw, glm::vec3(0,1,0));
for (int i = 0; i < 4; i++) {
faceVBOData[i].pos = rot * faceVBOData[i].pos;
}
// ensures all vertices have the same attribute
for (int i = 0; i < 4; i++) {
faceVBOData[i].nor = face_nor;
faceVBOData[i].cosPos = face_cos_pow;
faceVBOData[i].animFlag = face_is_animateable;
faceVBOData[i].pos.x *= 3.f / 4.f;
faceVBOData[i].pos.z *= 3.f / 4.f;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
// appends NEW face-vertex information
vboData.insert(vboData.end(), faceVBOData.data(), faceVBOData.data() + 4);
}
void Block::change_type(BlockType type) {
m_type = type;
}
BlockType Block::get_type() {
return m_type;
}
void Block::give_it_a_spin() {
m_is_spinning = true;
}
void Block::remove_spin() {
m_is_spinning = false;
m_time = 0.f;
}
|
4cda321031abe281a9a26c9d56f0330ce0abf596 | 356a3ced7502c34b510bcd786f565bdf2a4c9492 | /ACM-ICPC/水题 cf 330a.cpp | 417b9d51875994021aa3c95530ff610c90a32e4d | [] | no_license | philokey/Algorithm-Problems | bb1872b50a0d9ef4bc27fd40e5775ffb872eb858 | 774d515661647748372a1a1b6850063e04d37c03 | refs/heads/master | 2020-12-24T14:09:50.828232 | 2015-06-30T13:29:54 | 2015-06-30T13:29:54 | 38,310,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,031 | cpp | 水题 cf 330a.cpp | #include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <iostream>
#include <map>
#include <cmath>
using namespace std;
const int maxn = 100005;
const int inf = 1111111111;
int a[maxn];
int main()
{
//freopen("in.txt","r",stdin);
int n,m;
int cnt= 0;
char g[50][50];
scanf("%d%d",&n,&m);
for(int i = 0; i < n; i++)
scanf("%s",g[i]);
bool c[50]={0},r[50]={0};
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
if(g[i][j]=='S'){c[i]=1;break;}
}
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
if(g[j][i]=='S'){r[i]=1;break;}
}
for(int i = 0; i < n; i++)
{
if(c[i]) continue;
for(int j = 0; j < m;j++)
g[i][j]='a',cnt++;
}
for(int i = 0; i < m; i++)
{
if(r[i]) continue;
for(int j = 0; j < n; j++)
if(g[j][i]=='.') cnt++;
}
printf("%d\n",cnt);
return 0;
}
|
8904ddf04955cb9d7667582ee4ae4052ca37b0e1 | 761edd39dd74aca01efa60eb6948c12b3edf560e | /Digit Queries.cpp | 5df3318ee6c66c2f936ea36755d31a3f3406c6cb | [] | no_license | nduchuyvp123/Hamic-Algo | 9cbabca41c4ded8efe2b52b14e92a81d06061203 | 08452f0fe5e26e798c1b4476312baeabcd33215d | refs/heads/master | 2023-05-07T17:17:12.170644 | 2021-05-31T17:26:25 | 2021-05-31T17:26:25 | 324,581,769 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,420 | cpp | Digit Queries.cpp | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define read freopen("input.txt", "r", stdin)
#define write freopen("output.txt", "w", stdout)
#define pb push_back
#define ll long long
#define ull unsigned long long
#define ld long double
#define pii pair<int, int>
#define vi vector<int>
#define vii vector<pii>
#define mpi map<int, int>
#define si set<int>
#define vt vector
#define getline cout << '\n'
#define all(x) x.begin(), x.end()
#define FOR(i, a, b) for (long long int i = a; (b - i) * (a - i) <= 0 && (b > a ? b != i : b != a); b > a ? i++ : i--)
#define FOREACHR(it, m) for (auto it = m.rbegin(); it != m.rend(); it++)
#define FOREACH(it, m) for (auto it = m.begin(); it != m.end(); it++)
// #define FOREACH(it, m) for (auto it : m)
// #define IOS ios_base::sync_with_stdio(false)
#define scanset(s, n) \
FOR(i, 0, n) \
{ \
int x; \
cin >> x; \
s.insert(x); \
}
template <class T, size_t size>
// scan array
void scan(T (&array)[size])
{
for (size_t i = 0; i < size; ++i)
cin >> array[i];
}
template <class T, size_t size>
// print array
void print(const T (&array)[size])
{
for (size_t i = 0; i < size; ++i)
cout << array[i] << " ";
}
template <class T, size_t size>
void println(const T (&array)[size])
{
print(array);
cout << endl;
}
template <class T>
// scan vector with size
void scan(T &x)
{
for (size_t i = 0; i < x.size(); i++)
{
cin >> x[i];
}
}
template <class T>
// print vector
void print(const T &t)
{
for (size_t i = 0; i < t.size(); i++)
cout << t[i] << endl;
}
template <class T>
void println(const T &t)
{
print(t);
cout << endl;
}
template <class T>
// print vector, set, ...
void __print_collection(T const &container)
{
for (auto pos : container)
cout << pos << " ";
}
void __print_pair(pair<int, int> p)
{
cout << p.first << " " << p.second << "\n";
}
string next_string(string s)
{
bool b = false;
int i = s.size() - 1;
while (i >= 0)
{
if (s[i] != '9')
{
s[i]++;
b = true;
break;
}
i--;
}
if (b)
return s;
else
{
string a = "1";
for (int i = 0; i < s.size(); i++)
{
a += "0";
}
return a;
}
}
unsigned long long int p(unsigned long long int n, unsigned long long int m)
{
if (m == 1)
return n;
return n * p(n, m - 1);
}
int main()
{
// read;
// write;
string s = "";
unsigned long long int n;
cin >> n;
unsigned long long int x;
unsigned long long int y;
unsigned long long int z;
unsigned long long int t;
while (n--)
{
x = 9;
y = 1;
z = 0;
cin >> t;
while (t > z + x * y)
{
z += x * y;
x *= 10;
y++;
}
t -= z;
if (t % y)
{
s = to_string(p(10, y - 1) + t / y);
cout << s[t % y - 1] << endl;
continue;
}
else
{
if (y == 1)
s = to_string(0 + t / y);
else
s = to_string(p(10, y - 1) + t / y - 1);
cout << s[s.size() - 1] << endl;
}
}
} |
ab102d71a4ae3b29e1ff4f1ba9d20773f6fef16d | 91bbe0007ab047233f6fa15234494b38f4608298 | /Pong/Pong/main.cpp | 7b01947df6502707c9feed7b365dc73aa852d59a | [] | no_license | WeatherlightStudios/FireligthTestGames | 9d5758e1e232d3b2270d118a3f35a31ecf6d0a47 | aaa1b0228f2f79d9fb6c8a005be6a2180631964d | refs/heads/master | 2020-03-21T19:04:07.560492 | 2018-10-11T14:47:24 | 2018-10-11T14:47:24 | 138,929,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 210 | cpp | main.cpp | #include <FireLight.h>
#include "Game.h"
#include <memory.h>
int main() {
std::unique_ptr<Game> Pong(new Game);
Pong->setWindowDimension(800, 600);
Pong->setWindowName("Pong");
Pong->Start();
return 0;
} |
71d701c6afa0b308e5d03046e737eed76f1464e0 | fc88739d37b84554258de6d8057bed3c3b037103 | /algorithms/hacker-rank/cpp/deque-stl.cpp | 80c873b8f97746bb01329148f4d9fd51d8e81690 | [
"MIT"
] | permissive | alexhausen/examples | e6be67ffeac2b595e05eb2009b089fd7bd948fc6 | 2c6f365a18579e40897d840a149e73620d201cf8 | refs/heads/master | 2023-06-25T14:50:55.395902 | 2023-06-24T15:20:29 | 2023-06-24T15:20:29 | 30,794,944 | 0 | 0 | MIT | 2022-06-06T21:02:55 | 2015-02-14T11:37:32 | C++ | UTF-8 | C++ | false | false | 2,058 | cpp | deque-stl.cpp | // https://www.hackerrank.com/challenges/deque-stl/problem?isFullScreen=true
// https://www.geeksforgeeks.org/sliding-window-maximum-maximum-of-all-subarrays-of-size-k/
#include <deque>
#include <iostream>
using namespace std;
// remove indexes of the smaller elements (back to front)
// until we find an element > current
void remove_smaller_elements(deque<int>& d,
int current_element,
const int arr[]) {
while (!d.empty() && current_element >= arr[d.back()]) {
d.pop_back();
}
}
// remove indexes that fall out of the windows (front to back)
void remove_indexes_out_of_window(deque<int>& d,
int current_index,
int window_size) {
int min_index = current_index - window_size;
while (!d.empty() && d.front() <= min_index) {
d.pop_front();
}
}
void printKMax(int arr[], int n, int k) {
deque<int> d; // window (deque) with indexes of interest (larger at front)
// initialize deque with the window of index of the elements,
// keeping only the (index of the) larger ones (in the front)
for (int i = 0; i < k; i++) {
remove_smaller_elements(d, arr[i], arr);
d.push_back(i);
}
for (int i = k; i < n; i++) {
// the larger is always in the front of the deque
int max = arr[d.front()];
cout << max << " ";
// remove indexes out of the window
remove_indexes_out_of_window(d, i, k);
// remove smaller elements again
remove_smaller_elements(d, arr[i], arr);
d.push_back(i);
}
// last maximum element of the last window
cout << arr[d.front()] << endl;
}
int main() {
int t;
cin >> t;
while (t > 0) {
int n, k;
cin >> n >> k;
int i;
int arr[n];
for (i = 0; i < n; i++)
cin >> arr[i];
printKMax(arr, n, k);
t--;
}
return 0;
}
/*stdin:
2
5 2
3 4 6 3 4
7 4
3 4 5 8 1 4 10
*/
|
a0ec389fae72ba7b662d1d1fbf283e918fe97668 | ab987622db27ba44e3b6ba0bd94d14561e92a20b | /block.h | 7e9b87a5924b258e8cbc393be429f3b8697d15f2 | [] | no_license | VidurK/Quadris | 26550285aa45d2379e8589cdeca0a3864a797fd5 | 14da9abd85aee8d7aee491ab76790803b1a10928 | refs/heads/master | 2021-01-21T01:46:51.047357 | 2014-07-30T19:53:12 | 2014-07-30T19:53:12 | 22,441,655 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,125 | h | block.h | #ifndef BLOCK_H
#define BLOCK_H
#include <iostream>
#include "textdisplay.h"
// UP = 1 RIGHT = 2 DOWN = 3 LEFT = 4
struct BlockPos {
int x;
int y;
};
class Block {
protected:
int BlockX;
int BlockY;
char typeBlock;
int level;
int totalCellsLeft;
int pos; // 1, 2, 3, 4
BlockPos allCells[4];
public:
bool notify(int *score, int nx, int ny); // when this is called, it'll decrease totalCells left by 1, and
// if it's 0 it'll update score accordingly and return true (which will prompt grid to delete the block using the pointer)
// it'll also render the block's pieces that are cleared to be defunct (-1)
void notifyDisplay(TextDisplay &td, int x, int y);
Block(); // constructor for a block
virtual ~Block(); // destructor
virtual void allPos() = 0; // must be created from each block.
int getRotation();
void RotateClock();
void RotateCountClock();
char getTypeBlock();
void setBlockPos(int x, int y);
BlockPos* getBlockPos();
int getLevel();
void incLevel();
void decLevel();
int returnCellsLeft();
void moveLeft();
void moveRight();
void moveDown();
};
#endif
|
a65c1389042b4b2b48ec476e6cea5942f3f2b8fd | e1bc46edbe00f261282cb798eb59a25ad5227eff | /devmand/gateway/src/devmand/devices/cli/translation/GrpcCliHandler.cpp | e6a11db36e652f2027c55a190cf7fd68a72d29d2 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | 119Vik/magma-1 | 57f9a69036c742fcfcb97e84c59be78dec650609 | 107a7b374466a837fc0a49b283ba9d6ff1d702e3 | refs/heads/master | 2022-12-14T14:03:53.841221 | 2020-07-24T10:46:09 | 2020-07-24T11:29:37 | 279,833,292 | 0 | 0 | BSD-3-Clause | 2020-07-15T12:12:30 | 2020-07-15T10:05:13 | Go | UTF-8 | C++ | false | false | 1,812 | cpp | GrpcCliHandler.cpp | // Copyright (c) 2019-present, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include <devmand/devices/cli/translation/GrpcCliHandler.h>
namespace devmand {
namespace devices {
namespace cli {
// TODO: reconnect, error handling - connection issues, wrong services
// provided etc
GrpcCliHandler::GrpcCliHandler(const string _id, shared_ptr<Executor> _executor)
: id(_id), executor(_executor) {}
CliResponse* GrpcCliHandler::handleCliRequest(
const DeviceAccess& device,
const CliRequest& cliRequest,
bool writingAllowed) const {
if (not writingAllowed && cliRequest.write()) {
MLOG(MWARNING) << "[" << id << "] "
<< "Plugin requested to write command which is forbidden: "
<< cliRequest.cmd();
throw runtime_error("Forbidden to execute write commands");
}
string cliOutput;
if (cliRequest.write()) {
const WriteCommand& command = WriteCommand::create(cliRequest.cmd());
MLOG(MDEBUG) << "[" << id << "] "
<< "Got cli request: " << command;
cliOutput = device.cli()->executeWrite(command).via(executor.get()).get();
} else {
const ReadCommand& command = ReadCommand::create(cliRequest.cmd());
MLOG(MDEBUG) << "[" << id << "] "
<< "Got cli request: " << command;
cliOutput = device.cli()->executeRead(command).via(executor.get()).get();
}
CliResponse* cliResponse = new CliResponse();
cliResponse->set_output(cliOutput);
cliResponse->set_id(cliRequest.id());
return cliResponse;
}
} // namespace cli
} // namespace devices
} // namespace devmand
|
7d5975b35a8fd3c52a82af8e54239cfe2a108e01 | e84f63ceacb4a5e5177593833eaddfcb2f49a9e6 | /TP1/tp1e09.cxx | 8bb38070d9491cec931ffd665942e0ae5766800c | [] | no_license | AleNuez/TPsISFT177 | 08898871fdf2cd91478afd1ad40932390f2d4151 | 4e251e07e40d9f54b39fcd2f27743fbe73c7e575 | refs/heads/master | 2020-07-03T16:29:44.929148 | 2019-09-29T02:01:37 | 2019-09-29T02:01:37 | 201,968,078 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 716 | cxx | tp1e09.cxx | #include <iostream>
using namespace std;
int main()
{
int array[10] = {};
int mayores =0;
cout << "Ingrese una edad:";
cin >> array[0];
cout << "Ingrese otra edad:";
cin >> array[1];
cout << "Ingrese otra edad:";
cin >> array[2];
cout << "Ingrese otra edad:";
cin >> array[3];
cout << "Ingrese otra edad:";
cin >> array[4];
cout << "Ingrese otra edad:";
cin >> array[5];
cout << "Ingrese otra edad:";
cin >> array[6];
cout << "Ingrese otra edad:";
cin >> array[7];
cout << "Ingrese otra edad:";
cin >> array[8];
cout << "Ingrese otra edad:";
cin >> array[9];
for (int x=0;x<=9;x++){
if (array[x]>18){
mayores = mayores + 1;
}
}
cout << "La lista posee " << mayores << " mayores de edad.";
} |
b1cfc97e5b2b8db40ff521bd9129aed01aca805c | fd4b4fb798cf81ff3b36e562bd180dfa0c955baa | /gl/gl/Rectangle.cpp | c3d5f4f67846e6cd2818f911241c0fb408572699 | [] | no_license | fsxfreak/glfun | 5e3428fe710155875078929f17f539111994af5a | e78d524bb733df472fbad3034f1ca50ce59d2b01 | refs/heads/master | 2021-01-17T09:15:05.085658 | 2016-03-27T22:26:08 | 2016-03-27T22:26:08 | 38,176,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,914 | cpp | Rectangle.cpp | #include "Rectangle.hpp"
#include "Engine.hpp"
#include <iostream>
Rectangle::Rectangle(const glm::vec3& p1
, const glm::vec3& p2
, const glm::vec3& p3
, const glm::vec3& p4, const glm::vec3& rgb = { 1.0f, 1.0f, 1.0f })
: Rectangle({ p1, p2, p3, p4 }, rgb)
{
}
Rectangle::Rectangle(const std::array<glm::vec3, NUM_VERTS>& pos, glm::vec3 rgb)
: Primitive(NUM_VERTS, STRIDE, SIZE)
{
for (unsigned int i = 0; i < pos.size(); i++)
{
vertData[STRIDE * i] = pos[i].x;
vertData[STRIDE * i + 1] = pos[i].y;
vertData[STRIDE * i + 2] = pos[i].z;
vertData[STRIDE * i + 3] = rgb.x;
vertData[STRIDE * i + 4] = rgb.y;
vertData[STRIDE * i + 5] = rgb.z;
}
indices = { 0, 1, 2, 2, 3, 0 };
glGenVertexArrays(1, &vaoID);
glGenBuffers(1, &vboID);
glGenBuffers(1, &eboID);
glBindVertexArray(vaoID);
glBindBuffer(GL_ARRAY_BUFFER, vboID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, eboID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * indices.size(), indices.data(), GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * vertData.size(), vertData.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, STRIDE * sizeof(float), (GLvoid*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_TRUE, STRIDE * sizeof(float), (GLvoid*)(3 * sizeof(float)));
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
modelUniform = glGetUniformLocation(program.getID(), "model");
viewUniform = glGetUniformLocation(program.getID(), "view");
projectionUniform = glGetUniformLocation(program.getID(), "projection");
}
Rectangle::~Rectangle()
{
glDeleteBuffers(1, &eboID);
glDeleteBuffers(1, &vboID);
glDeleteVertexArrays(1, &vaoID);
}
void Rectangle::draw(glm::mat4 view) const
{
glm::mat4 projection;
projection = glm::perspective(60.0f, static_cast<float>(Engine::width) / Engine::height, 0.1f, 100.0f);
glUniformMatrix4fv(modelUniform, 1, GL_FALSE, glm::value_ptr(modelTransform));
glUniformMatrix4fv(viewUniform, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(projectionUniform, 1, GL_FALSE, glm::value_ptr(projection));
program.use();
glBindVertexArray(vaoID);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
void Rectangle::translate(const glm::vec3& amount)
{
for (int i = 0; i < NUM_VERTS; i++)
{
glm::vec3 offsetPosition{
vertData[STRIDE * i + 0] + amount.x
, vertData[STRIDE * i + 1] + amount.y
, vertData[STRIDE * i + 2] + amount.z
};
setPosition(offsetPosition, i);
}
} |
3d1a159d726b3fe3a2231e1d8cc513586118dc2a | 3cbd27002b8a041da0afab8d15bbc505ce829385 | /module/support/logging/DataLogging/src/DataLogging.h | 0d5ce435ef021399fc863bc9d6f7f2391fd8a834 | [] | no_license | David-UON/NUbots | 79596086f6722e187171b22cbaee7e9f5d9d0bcb | d403ae5bf4b19bd5978491dfea5326b5f000ba8c | refs/heads/master | 2020-06-15T17:54:38.973167 | 2019-07-05T02:30:23 | 2019-07-05T02:30:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,113 | h | DataLogging.h | #ifndef MODULE_SUPPORT_LOGGING_DATALOGGING_H
#define MODULE_SUPPORT_LOGGING_DATALOGGING_H
#include <fstream>
#include <nuclear>
namespace module {
namespace support {
namespace logging {
class DataLogging : public NUClear::Reactor {
private:
// FILE FORMAT
// TYPE DATA
// char[3] RADIATION SYMBOL {{ 0xE2, 0x98, 0xA2 }}
// uint32_t SIZE OF NEXT PACKET
// uint64_t TIMESTAMP DATA WAS EMITTED IN MICROSECONDS
// uint64_t DATA TYPE HASH
int fd = -1;
std::string log_dir = "";
std::ofstream output_file;
std::map<std::string, ReactionHandle> handles;
struct DataLog {
NUClear::clock::time_point timestamp;
uint64_t hash;
std::vector<char> data;
DataLog() : timestamp(NUClear::clock::now()), hash(), data() {}
};
template <typename T>
std::unique_ptr<DataLog> log_encode(const T& data) {
auto log = std::make_unique<DataLog>();
// We get the timestamp here from the time the message was emitted
// (or now if we can't access the current reaction)
auto task = NUClear::threading::ReactionTask::get_current_task();
log->timestamp =
task ? task->stats ? task->stats->emitted : NUClear::clock::now() : NUClear::clock::now();
// Serialise the data and get the hash for it
log->data = NUClear::util::serialise::Serialise<T>::serialise(data);
log->hash = NUClear::util::serialise::Serialise<T>::hash();
return std::move(log);
}
public:
/// @brief Called by the powerplant to build and setup the DataLogging reactor.
explicit DataLogging(std::unique_ptr<NUClear::Environment> environment);
};
} // namespace logging
} // namespace support
} // namespace module
#endif // MODULE_SUPPORT_LOGGING_DATALOGGING_H
|
6454bc3f97a9867c3a13f82eb80322756fa65782 | 5a6b57d77128fc5356de31a465931c0a17d7f403 | /src/Utils/PrintUtils.cpp | 955aadc0dcbb13468f63d157fb06217cf4c27944 | [
"MIT"
] | permissive | majabojarska/TravellingSalesmanProblem | 4a4e8ef6b2974e1b04937d74418bbf6eaff8301a | 3b2efdb08dce186aa169b086ac3b704abb25710a | refs/heads/master | 2020-09-14T16:29:23.915637 | 2019-11-21T14:02:01 | 2019-11-21T14:02:01 | 223,184,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 947 | cpp | PrintUtils.cpp | #include "PrintUtils.h"
using namespace utils;
void PrintUtils::printAligned(string content, short targetLength, char paddingChar, short alignDir) {
uint16_t contentLen = content.length();
uint16_t singlePaddingLen = (targetLength - (contentLen + 2)) / 2;
string paddingString = string(paddingChar, singlePaddingLen * 2);
if (alignDir == AlignDir::LEFT) {
cout << paddingString << paddingString;
cout << ' ' << content << ' ';
} else if (alignDir == AlignDir::CENTER) {
cout << paddingString;
cout << ' ' << content << ' ';
cout << paddingString;
} else if (alignDir == AlignDir::RIGHT) {
cout << ' ' << content << ' ';
cout << paddingString << paddingString;
}
cout << flush;
}
void PrintUtils::printAligned(int content, short targetLength, char paddingChar, short alignDir) {
printAligned(to_string(content), targetLength, paddingChar, alignDir);
}
|
5e0c93fd0d71e23659de1303ac206b7652e49736 | e0f08f8cc9f0547a55b2263bd8b9ee17dcb6ed8c | /SPOJ/IITWPC4H_brute.cpp | 50a66299fcc454483d7cdd8d167231fd85bde9b5 | [
"MIT"
] | permissive | aqfaridi/Competitve-Programming-Codes | 437756101f45d431e4b4a14f4d461e407a7df1e9 | d055de2f42d3d6bc36e03e67804a1dd6b212241f | refs/heads/master | 2021-01-10T13:56:04.424041 | 2016-02-15T08:03:51 | 2016-02-15T08:03:51 | 51,711,974 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,074 | cpp | IITWPC4H_brute.cpp | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <sstream>
#include <vector>
#include <iomanip>
#include <cmath>
using namespace std;
typedef long long LL;
typedef pair<int,int> pii;
#define MAX 30
#define MOD 1000000007
int sarr[MAX],tarr[MAX];
void max_cons(string str,int arr[])
{
int l1 = str.length(),cnt;
for(int i=0;i<l1;i++)
{
cnt = 1;
while((i+1<l1) && str[i]==str[i+1])
{
cnt++;
i++;
}
if((str[i]-'a'<=25) && (str[i]-'a' >=0))
{
if(arr[str[i]-'a'] < cnt)
arr[str[i]-'a'] = cnt;
}
}
}
int main()
{
ios::sync_with_stdio(false);
int test,n,maxx;
string s,t;
cin>>test;
while(test--)
{
memset(sarr,0,sizeof(sarr));
memset(tarr,0,sizeof(tarr));
maxx = -1;
cin>>s>>t;
max_cons(s,sarr);
max_cons(t,tarr);
for(int i=0;i<26;i++)
maxx = max(maxx,sarr[i]+tarr[i]);
cout<<maxx<<endl;
}
return 0;
}
|
b93f603d108109baeb1f571a84075995b981a509 | 4e8d0a92f6058f0635610fa8bf390f29bbe7c9a4 | /Game/Game/SaveAndLoad.h | 4c566e1d445dc40ff48f2ccff23ccac7c9e450ef | [] | no_license | anasawad/The_Invaders | 5e69f3854a67eaa2c25665e955778088a95abd55 | ed9ec9439a8952aa578a532d3f6febbc4296093a | refs/heads/master | 2021-01-02T08:19:30.126292 | 2012-07-17T03:48:30 | 2012-07-17T03:48:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,980 | h | SaveAndLoad.h | enum FLAG{_drawQuest,_drawStatus,_isDoubleKey,_isMouseRightClick,_isChestOpen,_showDoorLocked,_showKeyFound,_OpenDoor1,_OpenDoor2,_Door1Opened,_Door2Opened,_Unprison,_free,_MissionComplete,_isMDone,_bossInc,_waveDone,_gameStarted};
class SaveAndLoad
{
public:
bool flags[18];
int lvl;
NormalEnemy *e;
Hero *hero;
FinalBoss *fboss;
Boss *boss;
ThirdPersonCamera *camera;
GLubyte *pixels;
int Timer;
int numberOfEnemyKilled;
int monstersCounter;
int Divider;
int waveNumber;
char *FileName;
void SetAttributes(bool flags[18],int lvl,NormalEnemy e[],Hero &hero,FinalBoss fboss,Boss &boss,ThirdPersonCamera &camera,GLubyte *pixels,int Timer,int numberOfEnemyKilled,int monstersCounter,int Divider,int waveNumber)
{
for(int i = 0 ; i < 18 ; i++)
this->flags[i] = flags[i];
this->lvl = lvl;
this->e = e;
this->hero = &hero;
this->fboss = &fboss;
this->boss = &boss;
this->camera = &camera;
this->pixels = pixels;
this->Timer = Timer;
this->numberOfEnemyKilled = numberOfEnemyKilled;
this->monstersCounter = monstersCounter;
this->Divider = Divider;
this->waveNumber = waveNumber;
}
void SaveGame()
{
char fileName[64];
SaveTGA(pixels);
int i = 0;
while(!(FileName[i] <= '9' && FileName[i] >= '1'))
{
fileName[i] = FileName[i];
i++;
}
fileName[i++] = FileName[i];
fileName[i++] = '.';
fileName[i++] = 't';
fileName[i++] = 'x';
fileName[i++] = 't';
fileName[i] = 0;
FILE *saveFile;
saveFile = fopen(fileName,"wb");
ofstream o(saveFile);
o << lvl << endl;
for(int j = 0 ; j < 18 ;j++)
o << flags[j] << endl;
o << hero->Dead << endl;
o << hero->HP << endl;
o << hero->MP << endl;
o << hero->Position.x << endl;
o << hero->Position.y << endl;
o << hero->Position.z << endl;
o << hero->Rotation << endl;
o << hero->weaponNumber << endl;
o << hero->EXP << endl;
o << hero->EXPincreased << endl;
o << hero->HealthPointDecreased << endl;
o << hero->ManaPointDecreased << endl;
o << hero->CurrentLevel << endl;
int size = hero->Skills.size();
o << size << endl;
string skills[] = {"SN","SM","L","H","U","B"};
if(size != 0)
{
for(int j = 0 ; j < 6; j++)
{
if(hero->SearchForSkill(skills[j]))
{
o << skills[j] << endl;
}
}
}
o << hero->damage << endl;
o << hero->Speed << endl;
o << hero->MaxHP << endl;
o << hero->MaxMP << endl;
o << camera->N.x << endl;
o << camera->N.y << endl;
o << camera->N.z << endl;
o << camera->R.x << endl;
o << camera->R.y << endl;
o << camera->R.z << endl;
o << camera->U.x << endl;
o << camera->U.y << endl;
o << camera->U.z << endl;
o << camera->P.x << endl;
o << camera->P.y << endl;
o << camera->P.z << endl;
o << camera->T.x << endl;
o << camera->T.y << endl;
o << camera->T.z << endl;
o << camera->Rot.x << endl;
o << camera->Rot.y << endl;
o << camera->Rot.z << endl;
o << boss->Dead << endl;
o << boss->EnemyDepth << endl;
o << boss->EnemyRight << endl;
o << boss->HP << endl;
o << boss->Position.x << endl;
o << boss->Position.y << endl;
o << boss->Position.z << endl;
o << fboss->Dead << endl;
o << fboss->EnemyDepth << endl;
o << fboss->EnemyRight << endl;
o << fboss->HP << endl;
o << fboss->Position.x << endl;
o << fboss->Position.y << endl;
o << fboss->Position.z << endl;
o << Timer << endl;
o << numberOfEnemyKilled << endl;
o << monstersCounter << endl;
o << Divider << endl;
o << waveNumber << endl;
int MobsNumber;
if(lvl == 1)
MobsNumber = 14;
if(lvl == 2)
MobsNumber = 20;
for(int i = 0 ; i < MobsNumber ; i++)
{
o << e[i].Dead << endl;
o << e[i].EnemyDepth << endl;
o << e[i].EnemyRight << endl;
o << e[i].HP << endl;
o << e[i].Position.x << endl;
o << e[i].Position.y << endl;
o << e[i].Position.z << endl;
}
////remember to save the keys
}
char* SaveTGA(GLubyte *pixels)
{
char cFileName[64];
FILE *fScreenshot;
int nSize = 1024 * 1024 * 3;
//GLubyte *pixels = new GLubyte [nSize];
if (pixels == NULL) return "";
/*int nShot = 0;
while (nShot < 64)
{
sprintf(cFileName,"Save_%d.tga",nShot);
fScreenshot = fopen(cFileName,"rb");
if (fScreenshot == NULL) break;
else fclose(fScreenshot);
++nShot;
} */
sprintf(cFileName,"%s.tga",FileName);
fScreenshot = fopen(cFileName,"wb");
//glReadPixels(0, 0, 1024, 800, GL_RGB,
// GL_UNSIGNED_BYTE, pixels);
//convert to BGR format
unsigned char temp;
int i = 0;
while (i < nSize)
{
temp = pixels[i]; //grab blue
pixels[i] = pixels[i+2];//assign red to blue
pixels[i+2] = temp; //assign blue to red
i += 3; //skip to next blue byte
}
unsigned char TGAheader[12]={0,0,2,0,0,0,0,0,0,0,0,0};
unsigned char header[6] = {1024%256,1024/256,
800%256,800/256,24,0};
fwrite(TGAheader, sizeof(unsigned char), 12, fScreenshot);
fwrite(header, sizeof(unsigned char), 6, fScreenshot);
fwrite(pixels, sizeof(GLubyte), nSize, fScreenshot);
fclose(fScreenshot);
delete [] pixels;
return cFileName;
}
NormalEnemy *re;
Hero rhero;
Boss rboss;
FinalBoss rfboss;
ThirdPersonCamera rcamera;
void LoadGame(char *FileName)
{
FILE *loadFile;
loadFile = fopen(FileName,"rb");
ifstream i(loadFile);
char x[1000];
//char z[1000];
//char c[1000];
i >> x;
lvl = atoi(x);
/*i >> x;
int q = 0;
while((z[q]=x[q++]) != 0);
world = z;
i >> x;
q = 0;
while((c[q]=x[q++]) != 0);
worldTexture = c;
*/
for(int j = 0 ; j < 18;j++)
{
i >> x;
flags[j] = atoi(x);
}
i >> x;
rhero.Dead = atoi(x);
i >> x;
rhero.HP = atoi(x);
i >> x;
rhero.MP = atoi(x);
i >> x;
rhero.Position.x = atof(x);
i >> x;
rhero.Position.y = atof(x);
i >> x;
rhero.Position.z = atof(x);
i >> x;
rhero.Rotation = atof(x);
i >> x;
rhero.weaponNumber = atof(x);
i >> x;
rhero.EXP = atof(x);
i >> x;
rhero.EXPincreased = atof(x);
i >> x;
rhero.HealthPointDecreased = atof(x);
i >> x;
rhero.ManaPointDecreased = atof(x);
i >> x;
rhero.CurrentLevel = atof(x);
i >> x;
int size = atof(x);
i >> x;
Skill *s;
if(size != 0 )
{
for(int j = 0 ; j < size ; j++)
{
if(x == "SN")
{
s = new SniperSkill();
rhero.Skills.push_back(s);
}
if(x == "SM")
{
s = new SlowMotionSkill();
rhero.Skills.push_back(s);
}
if(x == "L")
{
s = new LightningSkill();
rhero.Skills.push_back(s);
}
if(x == "H")
{
s = new HiddenSkill();
rhero.Skills.push_back(s);
}
if(x == "U")
{
s = new UpgradeSkill();
rhero.Skills.push_back(s);
}
if(x == "B")
{
s = new BuffSkill();
rhero.Skills.push_back(s);
}
if(x == "V")
{
s = new VampireAuraSkill();
rhero.Skills.push_back(s);
}
if(x == "S")
{
s = new StormSkill();
rhero.Skills.push_back(s);
}
i >> x;
}
}
rhero.damage = atof(x);
i >> x;
rhero.Speed = atof(x);
i >> x;
rhero.MaxHP = atof(x);
i >> x;
rhero.MaxMP = atof(x);
i >> x;
rcamera.N.x = atof(x);
i >> x;
rcamera.N.y = atof(x);
i >> x;
rcamera.N.z = atof(x);
i >> x;
rcamera.R.x = atof(x);
i >> x;
rcamera.R.y = atof(x);
i >> x;
rcamera.R.z = atof(x);
i >> x;
rcamera.U.x = atof(x);
i >> x;
rcamera.U.y = atof(x);
i >> x;
rcamera.U.z = atof(x);
i >> x;
rcamera.P.x = atof(x);
i >> x;
rcamera.P.y = atof(x);
i >> x;
rcamera.P.z = atof(x);
i >> x;
rcamera.T.x = atof(x);
i >> x;
rcamera.T.y = atof(x);
i >> x;
rcamera.T.z = atof(x);
i >> x;
rcamera.Rot.x = atof(x);
i >> x;
rcamera.Rot.y = atof(x);
i >> x;
rcamera.Rot.z = atof(x);
i >> x;
rboss.Dead = atoi(x);
i >> x;
rboss.EnemyDepth = atoi(x);
i >> x;
rboss.EnemyRight = atoi(x);
i >> x;
rboss.HP = atoi(x);
i >> x;
rboss.Position.x = atof(x);
i >> x;
rboss.Position.y = atof(x);
i >> x;
rboss.Position.z = atof(x);
i >> x;
rfboss.Dead = atoi(x);
i >> x;
rfboss.EnemyDepth = atoi(x);
i >> x;
rfboss.EnemyRight = atoi(x);
i >> x;
rfboss.HP = atoi(x);
i >> x;
rfboss.Position.x = atof(x);
i >> x;
rfboss.Position.y = atof(x);
i >> x;
rfboss.Position.z = atof(x);
i >> x;
Timer = atoi(x);
i >> x;
numberOfEnemyKilled = atof(x);
i >> x;
monstersCounter = atof(x);
i >> x;
Divider = atof(x);
i >> x;
waveNumber = atof(x);
int MobsNumber;
if(lvl == 1)
{
re = new NormalEnemy[14];
MobsNumber = 14;
}
if(lvl == 2)
{
re = new NormalEnemy[20];
MobsNumber = 20;
}
for(int a = 0 ; a < MobsNumber ; a++)
{
i >> x;
re[a].Dead = atoi(x);
i >> x;
re[a].EnemyDepth = atoi(x);
i >> x;
re[a].EnemyRight = atoi(x);
i >> x;
re[a].HP = atoi(x);
i >> x;
re[a].Position.x = atof(x);
i >> x;
re[a].Position.y = atof(x);
i >> x;
re[a].Position.z = atof(x);
}
}
};
//make a copy constructor for hero and enemy and boss and fboss |
0b51d6ac9755288cd2032e2e5efde3b587256be2 | 8a8888bde6f563bfe1a3fc877bc0537875c7c675 | /deps_leveldb_db_version_edit.cc | 4a34f3c3d71c6672665bf64ec02b5a73d41c6ff2 | [
"MIT"
] | permissive | DataDog/leveldb | 66c826e477fc16bc56bb0bfda6e060c5fe9a9e80 | 0631e62f1233ef6b823a5ab19a28dc8cd6d229d2 | refs/heads/master | 2023-08-25T11:31:10.125661 | 2021-01-22T15:40:18 | 2021-01-22T15:40:18 | 66,093,652 | 4 | 1 | MIT | 2023-04-08T10:35:21 | 2016-08-19T15:46:24 | Go | UTF-8 | C++ | false | false | 31 | cc | deps_leveldb_db_version_edit.cc | deps/leveldb/db/version_edit.cc |
cab8546c2fd12266892845b4f0c5ff0b2b88e324 | f9872393e2c43fc6dacb1d2c0ded509328de981e | /Sistema-Embarcado/0. Sensores/hc-sr04/HC-SR04.ino | 3e35090b4b386e0156f97ae7ee04f32de54e2ce0 | [] | no_license | Turma3DT/1_BackEnd | 4085c4d3a381d6c1c9d51811d56728a020cc3016 | 9281661bbb61c9f21f4baaec354fac1de3355b70 | refs/heads/main | 2023-06-19T04:10:57.128956 | 2021-07-20T20:16:19 | 2021-07-20T20:16:19 | 371,801,632 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 726 | ino | HC-SR04.ino | //Programa: Conectando Sensor Ultrassonico HC-SR04 ao Arduino Uno
//Carrega a biblioteca do sensor ultrassonico
#include <Ultrasonic.h>
//Define os pinos para o trigger e echo
#define pino_trigger D1
#define pino_echo D2
//Inicializa o sensor nos pinos definidos acima
Ultrasonic ultrasonic(pino_trigger, pino_echo);
void setup()
{
Serial.begin(115200);
Serial.println("Lendo dados do sensor...");
}
void loop()
{
//Le as informacoes do sensor, em cm
float cmMsec;
long microsec = ultrasonic.timing();
cmMsec = ultrasonic.convert(microsec, Ultrasonic::CM);
//Exibe informacoes no serial monitor
Serial.print("Distancia em cm: ");
Serial.println(cmMsec);
delay(500);
}
|
16d0b0458b7e4fe07a6ba2d4b748b961858cde48 | 1b4ef06460dee1faa27ef5568fb6e3d8b3db7cfb | /0119bu/X/main.cpp | 3489c4a7ac44ce1432fccfd75fd25eefdad9351b | [] | no_license | imoverflow/mycode | 3efb4d3663334ca7d96feaefbaa07cac4b4e2076 | 6ca89e1df775dbf351b5a7590f6a6af5167a46e9 | refs/heads/master | 2020-04-01T23:06:39.017093 | 2018-12-02T04:40:02 | 2018-12-02T04:40:02 | 153,742,417 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,664 | cpp | main.cpp | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
vector<int>g[200005];
int d[200005];
int pre[200005];
void dfs(int now,int fa,int dis)
{
pre[now]=fa;
d[now]=dis;
for(int i=0;i<g[now].size();i++)
{
if(g[now][i]!=fa)
dfs(g[now][i],now,dis+1);
}
}
tuple<int,int,int>ans[200005];
bool vis[200005];
long long sum;
int cnt;
int leaf=1;
int root=1;
void Find(int now,int ld,int rd,bool isfirst)
{
for(int i=0;i<g[now].size();i++)
{
if(!vis[g[now][i]]&&g[now][i]!=pre[now])
Find(g[now][i],ld+1,rd+1,false);
}
if(!isfirst)
{
if(ld>rd)
{
ans[cnt++]=make_tuple(root,now,now);
sum+=ld;
}else{
ans[cnt++]=make_tuple(leaf,now,now);
sum+=rd;
}
}
}
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n-1;i++)
{
int a,b;
scanf("%d%d",&a,&b);
g[a].push_back(b);
g[b].push_back(a);
}
dfs(root,0,0);
for(int i=1;i<=n;i++)
{
if(d[root]<d[i])
root=i;
}
dfs(root,0,0);
for(int i=1;i<=n;i++)
{
if(d[leaf]<d[i])
leaf=i;
}
cnt=0;
sum=0;
int p=leaf;
while(1)
{
vis[p]=1;
Find(p,d[p],d[leaf]-d[p],1);
if(p==root)
break;
p=pre[p];
}
p=leaf;
while(p!=root)
{
ans[cnt++]=make_tuple(root,p,p);
sum+=d[p];
p=pre[p];
}
printf("%I64d\n",sum);
for(int i=0;i<cnt;i++)
{
int a,b,c;
tie(a,b,c)=ans[i];
printf("%d %d %d\n",a,b,c);
}
return 0;
}
|
f46bc7004c3408516659b8602de6fc1939127def | 9325e8133fe8c00c6538415d5a8d21589ad6c63f | /datastructures/trees/inorder_linked_list.cpp | b4f500212dd3455fe374ddc4ff28b36d9e95e838 | [] | no_license | nskprasanth/practice | 91fc14d7d62451f96d4212679da805f1934e4136 | 8283cfe4880998d59bace2fc5a4fd7c44492fd4e | refs/heads/master | 2021-01-10T05:49:22.425097 | 2015-11-16T02:10:20 | 2015-11-16T02:10:20 | 45,445,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,191 | cpp | inorder_linked_list.cpp | /**
* Given a binary search tree, converts the inorder traversal of
* the tree into a linked list
*
* Prasanth Kalapatapu
* Nov 6, 2015
*/
#include <iostream>
#include "bst.h"
using namespace std;
// struct representing a node in a linked list of integers
struct list_node {
list_node(int val) : data(val), next(NULL) {}
int data;
list_node* next;
};
// Reverses the given linked list and returns the head of the reversed list
list_node* reverse(list_node* node) {
if (!node || !node->next) {
return node;
}
list_node* nn = node->next;
node->next = NULL;
while(nn) {
list_node* temp = nn->next;
nn->next = node;
node = nn;
nn = temp;
}
return node;
}
// Prints the linked list with the head as node
void print(list_node* node) {
while(node) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
// Prepend a new node with value 'val' to the given linked list 'node'
list_node* prepend_to_list(list_node* node, int val) {
list_node* new_node = new list_node(val);
if (node == NULL) {
return new_node;
}
new_node->next = node;
return new_node;
}
// Populates the inorder traversal of given tree_node into the given list_node
list_node* populate_inorder_to_list(binary_node<int>* tree_node, list_node* node) {
if (tree_node == NULL) {
return node;
}
node = populate_inorder_to_list(tree_node->left, node);
node = prepend_to_list(node, tree_node->data);
return populate_inorder_to_list(tree_node->right, node);
}
// Returns a linked list that represents the inorder traversal of given tree
list_node* get_inorder_as_list(bst<int> tree) {
// pass an empty list to populate_inorder_to_list
list_node* node = populate_inorder_to_list(tree.get_root(), NULL);
// the populated list is in reverse inorder traversal, so reverse the list
list_node* reversed = reverse(node);
return reversed;
}
int main() {
int n;
bst<int> tree;
cin >> n;
for (int i=0;i<n;++i) {
int cur;cin >> cur;
tree.insert(cur);
}
// print the inorder traversal of the tree
tree.print_inorder();
list_node* head = get_inorder_as_list(tree);
print(head);
return 0;
}
|
b04ff0a3997aa53abe9f38d9a390e74e844c1066 | 731ee38ff16d1abaa04bf65682eaddae3c795a36 | /RecognizeLanguage.h | 2389c161b03a9f9038fb71192880f4f1bc016205 | [] | no_license | sz-p/Print3DBraille | 549659d46f2c04d1bb81e9fd21064210b08c9e95 | bf9291d1c5e58ee922cd3fc2c3676a23e32bc712 | refs/heads/master | 2021-05-31T09:55:00.951536 | 2016-04-12T10:18:58 | 2016-04-12T10:18:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 195 | h | RecognizeLanguage.h | #pragma once
#include "string"
using namespace std;
class RecognizeLanguage
{
public:
RecognizeLanguage();
~RecognizeLanguage();
int RecWord(char buffer);
int RecDoubleWord(int buffer);
};
|
a77edcb83c6c154a6dcf2ef111e3ea42926e694f | 3f41ff4599446c60d1b2006c4188ba0f0deb3a4a | /返回栈中最小元素.cpp | e5552d2e4875d0a4c2c248dd8bb4248a74d2a2be | [] | no_license | 912679520/Mycodes | 6e9f3e40b9a298d8d77d3b8c3a8ea8bd820dafa3 | ecd4c8e53af0cc07e51d28625f336a1b62fbf00e | refs/heads/master | 2023-06-11T15:18:26.799209 | 2021-07-06T14:13:07 | 2021-07-06T14:13:07 | 307,394,975 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 906 | cpp | 返回栈中最小元素.cpp | #include<iostream>
#include<stack>
using namespace std;
class MyStack
{
public:
stack<int> StackMin;
stack<int> StackData;
public:
MyStack()
{
}
void push(int data)
{
StackData.push(data);
if (StackMin.empty())
{
StackMin.push(data);
}
else if (data < getMin())
{
StackMin.push(data);
}
else
{
int newMin = StackMin.top();
StackMin.push(newMin);
}
}
int top()
{
return StackData.top();
}
void pop()
{
if (StackData.empty())
{
return;
}
StackMin.pop();
StackData.pop();
}
int getMin()
{
if (StackMin.empty())
{
return NULL;
}
return StackMin.top();
}
};
//int main()
//{
// MyStack stack1;
// stack1.push(3);
// cout << stack1.getMin() << endl;
// stack1.push(4);
// cout << stack1.getMin() << endl;
// stack1.push(1);
// cout << stack1.getMin() << endl;
// stack1.push(6);
// cout << stack1.getMin() << endl;
// return 0;
//} |
66f3e147cfe7cde88d6b7c4470bd7bc1aafc1bf3 | bd79465bda3cb63682e19d7181bab48fb95ea7cb | /InfiniteRunner/InfiniteRunner/HealthHud.cpp | a0850dfb2d439b09fd56e33c335397a3f0a515e0 | [] | no_license | mbise1993/GameEngine | e45cd95c343fe16d2f6a404200d4fa06f7c18a51 | 8ead12353bec8f4492772af7ff63b2802ccd59c5 | refs/heads/master | 2021-01-10T07:31:59.321465 | 2015-12-11T00:12:22 | 2015-12-11T00:14:14 | 47,790,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,950 | cpp | HealthHud.cpp | #include "HealthHud.h"
#include "HealthChangedEventArgs.h"
#include <boost\lexical_cast.hpp>
#define CHAR_WIDTH_PERCENTAGE 0.14285f
#define CHAR_HEIGHT_PERCENTAGE 0.66666f
HealthHud::HealthHud( float width, float height, float posX, float posY, RGBA color, int initialHealth ) :
OGLHudObject( "HealthHud", width, height, posX, posY, color )
{
OGLHudObject::setHeader( "Health" );
// Calculate character dimensions
float charWidth = width * CHAR_WIDTH_PERCENTAGE;
float charHeight = height * CHAR_HEIGHT_PERCENTAGE;
this->healthDisplay = new OGL2DTextDisplay( charWidth, charHeight );
setHealth( initialHealth );
}
HealthHud::~HealthHud()
{
delete this->healthDisplay;
}
void HealthHud::setTextTexture( OGL2DTexture* texture )
{
this->healthDisplay->setTexture( texture );
OGLHudObject::setTextTexture( texture );
}
void HealthHud::setTextShaderProgram( GLuint shaderProgram )
{
this->healthDisplay->setShaderProgram( shaderProgram );
OGLHudObject::setTextShaderProgram( shaderProgram );
}
void HealthHud::setHealth( int health )
{
this->healthDisplay->clear();
std::string healthStr = boost::lexical_cast<std::string>(health);
// Calculate where to position health so it is center aligned
float healthWidth = healthStr.size() * (this->width * CHAR_WIDTH_PERCENTAGE);
float healthPosX = (this->width - healthWidth) / 2;
healthPosX += this->posX;
float healthPosY = (this->posY - this->height) + (this->height * CHAR_HEIGHT_PERCENTAGE);
this->healthDisplay->addText( healthStr, healthPosX, healthPosY );
}
void HealthHud::render()
{
OGLHudObject::render();
this->healthDisplay->render();
}
void HealthHud::eventHandler( EventArgs* eventArgs )
{
if ( eventArgs->getEventType() != HEALTH_CHANGED_EVENT ) return;
HealthChangedEventArgs* healthChangedEventArgs = dynamic_cast<HealthChangedEventArgs*>(eventArgs);
if ( healthChangedEventArgs != nullptr )
{
setHealth( healthChangedEventArgs->getHealthDelta() );
}
} |
8a5716cc7888a3b07042424132fd07946a96afe2 | 80f8938061bf02d1c819cc222e5670669eaf09c9 | /test/cpp/service/service_test2.cpp | b68376e5aed764c04bdd168c8fb559c39e2450a8 | [
"Apache-2.0"
] | permissive | johnwason/robotraconteur | b253a2ab5e5462bdc9751192a455b4d0129ecac6 | d29157a19da67b5050677855e0e92cc0ba164bcc | refs/heads/v0.16-dev | 2023-07-19T10:12:19.458284 | 2022-06-07T20:50:24 | 2022-06-07T20:50:24 | 158,881,644 | 1 | 1 | Apache-2.0 | 2022-05-28T21:04:43 | 2018-11-23T22:03:21 | C++ | UTF-8 | C++ | false | false | 4,243 | cpp | service_test2.cpp | #include <boost/shared_array.hpp>
#include <gtest/gtest.h>
#include <RobotRaconteur/ServiceDefinition.h>
#include <RobotRaconteur/RobotRaconteurNode.h>
#include "ServiceTestClient2.h"
#include "robotraconteur_generated.h"
#include "service_test_utils.h"
using namespace RobotRaconteur;
using namespace RobotRaconteur::test;
using namespace RobotRaconteurTest;
static std::string service2_url;
TEST(RobotRaconteurService, WirePeekPokeTest)
{
RobotRaconteurNode::s()->SetLogLevelFromEnvVariable();
ServiceTestClient2 c;
ASSERT_NO_THROW(c.Connect(service2_url));
ASSERT_NO_THROW(c.TestWirePeekPoke());
ASSERT_NO_THROW(c.Disconnect());
}
TEST(RobotRaconteurService, EnumsTest)
{
RobotRaconteurNode::s()->SetLogLevelFromEnvVariable();
ServiceTestClient2 c;
ASSERT_NO_THROW(c.Connect(service2_url));
ASSERT_NO_THROW(c.TestEnums());
ASSERT_NO_THROW(c.Disconnect());
}
TEST(RobotRaconteurService, PodsTest)
{
RobotRaconteurNode::s()->SetLogLevelFromEnvVariable();
ServiceTestClient2 c;
ASSERT_NO_THROW(c.Connect(service2_url));
ASSERT_NO_THROW(c.TestPods());
ASSERT_NO_THROW(c.Disconnect());
}
TEST(RobotRaconteurService, MemoriesTest)
{
RobotRaconteurNode::s()->SetLogLevelFromEnvVariable();
ServiceTestClient2 c;
ASSERT_NO_THROW(c.Connect(service2_url));
ASSERT_NO_THROW(c.TestMemories());
ASSERT_NO_THROW(c.Disconnect());
}
TEST(RobotRaconteurService, GeneratorsTest)
{
RobotRaconteurNode::s()->SetLogLevelFromEnvVariable();
ServiceTestClient2 c;
ASSERT_NO_THROW(c.Connect(service2_url));
ASSERT_NO_THROW(c.TestGenerators());
ASSERT_NO_THROW(c.Disconnect());
}
TEST(RobotRaconteurService, NamedArraysTest)
{
RobotRaconteurNode::s()->SetLogLevelFromEnvVariable();
ServiceTestClient2 c;
ASSERT_NO_THROW(c.Connect(service2_url));
ASSERT_NO_THROW(c.TestNamedArrays());
ASSERT_NO_THROW(c.Disconnect());
}
TEST(RobotRaconteurService, NamedArrayMemoriesTest)
{
RobotRaconteurNode::s()->SetLogLevelFromEnvVariable();
ServiceTestClient2 c;
ASSERT_NO_THROW(c.Connect(service2_url));
ASSERT_NO_THROW(c.TestNamedArrayMemories());
ASSERT_NO_THROW(c.Disconnect());
}
TEST(RobotRaconteurService, ComplexTest)
{
RobotRaconteurNode::s()->SetLogLevelFromEnvVariable();
ServiceTestClient2 c;
ASSERT_NO_THROW(c.Connect(service2_url));
ASSERT_NO_THROW(c.TestComplex());
ASSERT_NO_THROW(c.Disconnect());
}
TEST(RobotRaconteurService, ComplexMemoriesTest)
{
RobotRaconteurNode::s()->SetLogLevelFromEnvVariable();
ServiceTestClient2 c;
ASSERT_NO_THROW(c.Connect(service2_url));
ASSERT_NO_THROW(c.TestComplexMemories());
ASSERT_NO_THROW(c.Disconnect());
}
TEST(RobotRaconteurService, NoLockTest)
{
RobotRaconteurNode::s()->SetLogLevelFromEnvVariable();
ServiceTestClient2 c;
ASSERT_NO_THROW(c.Connect(service2_url));
ASSERT_NO_THROW(c.TestNoLock());
ASSERT_NO_THROW(c.Disconnect());
}
TEST(RobotRaconteurService, BoolsTest)
{
RobotRaconteurNode::s()->SetLogLevelFromEnvVariable();
ServiceTestClient2 c;
ASSERT_NO_THROW(c.Connect(service2_url));
ASSERT_NO_THROW(c.TestBools());
ASSERT_NO_THROW(c.Disconnect());
}
TEST(RobotRaconteurService, BoolMemoriesTest)
{
RobotRaconteurNode::s()->SetLogLevelFromEnvVariable();
ServiceTestClient2 c;
ASSERT_NO_THROW(c.Connect(service2_url));
ASSERT_NO_THROW(c.TestBoolMemories());
ASSERT_NO_THROW(c.Disconnect());
}
TEST(RobotRaconteurService, ExceptionParamsTest)
{
RobotRaconteurNode::s()->SetLogLevelFromEnvVariable();
ServiceTestClient2 c;
ASSERT_NO_THROW(c.Connect(service2_url));
ASSERT_NO_THROW(c.TestExceptionParams());
ASSERT_NO_THROW(c.Disconnect());
}
int main(int argc, char* argv[])
{
testing::InitGoogleTest(&argc, argv);
TestServerNodeConfig server("unit_service_test2");
service2_url = server.GetServiceURL("RobotRaconteurTestService2");
ClientNodeSetup setup(ROBOTRACONTEUR_SERVICE_TYPES, argc, argv);
int ret = RUN_ALL_TESTS();
return ret;
} |
f8655d226b01cfedb35506466658fb0ba5c1aa52 | 6ecf4c7beaf3c7f12a826ead3ba3529808e31014 | /include/database.hpp | 780cf8b22c7aeb8d6f78804f24a1b1946cd518e5 | [] | no_license | KoaLaYT/Learn-The-Art-of-PostgreSQL | 99cbc792e79b5e040b8f3a4a0aec2514bb340e96 | 4503454a12da24087efa70ff71076bb456063609 | refs/heads/master | 2023-02-03T16:09:23.022073 | 2020-12-15T10:38:29 | 2020-12-15T10:38:29 | 316,478,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,184 | hpp | database.hpp | #ifndef DATABASE_HPP_20201127
#define DATABASE_HPP_20201127
#include <fmt/core.h>
#include <filesystem>
#include <fstream>
#include <pqxx/pqxx>
#include <string>
using namespace std;
extern const string CHINOOKDB_CONN_STR;
extern const string F1DB_CONN_STR;
extern const string BASE_DIR;
class Database {
public:
explicit Database(
const string& connect_str,
const string& search_path) : c{connect_str}
{
prepare_sql(search_path);
}
/**
* @brief exec sql from file
*
* @param file the sql file
* @return pqxx::result
*/
pqxx::result exec_sql(const string& file);
/**
* @brief exec prepared sql with args
*
* @tparam Args
* @param sql the prepared sql statement
* @param args the sql required arguments
* @return pqxx::result
*/
template <typename... Args>
pqxx::result exec_prepared(const string& sql, Args&&... args)
{
pqxx::work w{c};
pqxx::result r{w.exec_prepared(sql, forward<Args>(args)...)};
w.commit();
return r;
}
private:
pqxx::connection c;
void prepare_sql(const string& search_path);
};
#endif |
6a86db302377feeb302189ca6a5847e8882adc43 | 86a5607a5ff83f3a40a6bc498aa7ba2235897933 | /SDiZO1/SDiZO1/DrzewoCzCz.h | 025944312826d802de876651196bd85ba97f3424 | [] | no_license | klimczak-michal/DataStructures | e1b28de33e109f4713c52f605c9508298fc2e7eb | a95fbb144d6427f37646be337046ed04b542b9ab | refs/heads/master | 2021-07-07T01:04:31.682786 | 2017-10-03T14:28:09 | 2017-10-03T14:28:09 | 105,660,903 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 1,256 | h | DrzewoCzCz.h | #pragma once
#include <iostream>
#include <string>
using namespace std;
struct Wezel
{
Wezel * gora;
Wezel * lewy;
Wezel * prawy;
int wartosc;
char kolor; //R - czerwony, B - czarny
};
class DrzewoCzCz
{
private:
Wezel straznik; //Pusty wezel, bedzie sluzyl za wszystkie liscie w drzewie
Wezel *korzen;
string cr, cl, cp; //wyswietlanie
public:
DrzewoCzCz();
DrzewoCzCz(string nazwa_pliku); //Odczyt z pliku
DrzewoCzCz(int N); //Losowe generowanie
~DrzewoCzCz();
void Wyswietl(string sp, string sn, Wezel * podany); // Wypisuje drzewo od podanego
void print(); // Wypisuje cale drzewo
void UsunDrzewo(Wezel * podany); // Usuwa drzewo
Wezel * Znajdz(int wartosc); // Wyszukuje węzeł o podanej wartości
bool CzyJest(int warotsc); //Wyszukuje i zwraca czy istnieje węzeł o zadanym kluczu
Wezel * NajmniejszyWezel(Wezel * podany); // Wyszukuje najmniejszy węzeł dla podanego poddrzewa
Wezel * Nastepnik(Wezel * podany);// Wyszukuje następnik podanego węzła
void Rotacja_L(Wezel * A); // Rotacja w lewo względem A
void Rotacja_R(Wezel * A); // Rotacja w prawo względem A
void Wstaw(int wartosc); // Wstawia węzeł o zadanej wartosci
void Usun(Wezel * podany); // Usuwa podany
};
|
4dd8c888915d040555a88a01aa04668b5b82d175 | 73febba4847914c9d05bb3becc25801d5a0d9881 | /MotorGoto/MotorGoto.ino | b7655f50afec4d82cc8c679cc1a2fc5b8df23e7a | [
"MIT"
] | permissive | compugician/express-motion | 67e09099c3644c54cc44afa4685633ac2165f2b1 | ee20c872518a81bdd8447d41a4ace804fc64aaea | refs/heads/master | 2021-01-10T13:14:52.640907 | 2016-02-24T20:29:35 | 2016-02-24T20:29:35 | 51,694,616 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,512 | ino | MotorGoto.ino | //brown - GND
const byte STEP_PIN = 12; //black - Input B
const byte DIRECTION_PIN = 11; //white - Input A
const byte ENABLE_PIN = 10; //blue - Enable
const int HLFB_PIN = 2; //green -HLFB //needs to support interrupts (on UNO this means 2 or 3)
const int STEPS_PER_ROTATION = 800;
const float INCHES_OF_TRAVEL = 24.25;
const float INCHES_PER_ROTATION = 2.0;
const int MAX_PULSE_COUNT = (INCHES_OF_TRAVEL/INCHES_PER_ROTATION*STEPS_PER_ROTATION);
//10 uSec total pulse width = 100khz
const int ON_PULSE_WIDTH_MICROS = 5;
const int OFF_PULSE_WIDTH_MICROS = 5;
//CW = move towards motor
//CCW = move away from motor
//motor homes away.
//vars
int destination = 0;
int queuedDestination = 0;
bool newMoveAvailable = false;
void setup() {
Serial.begin(9600);
Serial.write("Power On! ");
Serial.println(MAX_PULSE_COUNT);
pinMode(STEP_PIN,OUTPUT);
pinMode(DIRECTION_PIN,OUTPUT);
pinMode(ENABLE_PIN,OUTPUT);
pinMode(HLFB_PIN,INPUT_PULLUP);
goHome();
}
void goHome() {
Serial.println("Homing");
destination = 0;
digitalWrite(ENABLE_PIN,LOW);
delay(100);
digitalWrite(ENABLE_PIN,HIGH);
delay(10);
while (isInMotion()) {
//nop
}
Serial.println("@home");
}
boolean isInMotion() {
return (digitalRead(HLFB_PIN)==HIGH);
}
void setDir(bool cw) {
if (cw) {
digitalWrite(DIRECTION_PIN,LOW);
Serial.println("Setting Direction CW");
} else {
digitalWrite(DIRECTION_PIN,HIGH);
Serial.println("Setting Direction CCW");
}
}
void makeAMove() {
newMoveAvailable = false;
int pos = destination;
destination = queuedDestination;
int delta = destination - pos;
int pulse_count = abs(delta);
if (pulse_count>0) {
Serial.println(pulse_count);
setDir(delta>0); //if delta is positive, move CW
for (int i=0; i<pulse_count; i++) {
digitalWrite(STEP_PIN,HIGH);
delayMicroseconds(ON_PULSE_WIDTH_MICROS);
digitalWrite(STEP_PIN,LOW);
delayMicroseconds(OFF_PULSE_WIDTH_MICROS);
}
}
}
void loop() {
if (Serial.available() > 0) {
// look for the next valid integer in the incoming serial stream:
int input = Serial.parseInt();
if (input>=0 && input<=MAX_PULSE_COUNT) {
queuedDestination = input;
newMoveAvailable = true;
Serial.print("moving to: ");
Serial.println(queuedDestination);
} else {
Serial.println("Out of bounds.");
goHome();
}
}
if (!isInMotion() && newMoveAvailable) {
makeAMove();
}
}
|
949eefe27facb9cb6e1fa35361f1398acf17cf62 | bbf5dcaa617432fb7eac707b9cb65ecaa73e4eca | /module01/ex00/randomChump.cpp | b6e03b6e8aca83a8060bf6b0136c6885af322f54 | [
"Apache-2.0"
] | permissive | ASM717/cpp_intensive | 01bd6769715bbda6a3cbbd1ec8e1cf8706239241 | de888b92f8e1d00eb8a0045a2f788be3c3810aee | refs/heads/main | 2023-08-13T23:45:53.916431 | 2021-10-15T19:02:14 | 2021-10-15T19:02:14 | 397,139,745 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 998 | cpp | randomChump.cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* randomChump.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: amuriel <amuriel@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/25 16:16:21 by amuriel #+# #+# */
/* Updated: 2021/08/25 16:16:22 by amuriel ### ########.fr */
/* */
/* ************************************************************************** */
#include "Zombie.hpp"
void randomChump(std::string name)
{
Zombie randomZ(name);
randomZ.announce();
}
|
546ef622e15b014728438b3b8fe24c054e69c025 | 49f7616d386a445139b89db50328883fbdf01c90 | /MidTerm2/Code/main.cpp | 30e0fc1983751fc2d92a7d43e220f0657d930b1e | [] | no_license | brucdarc/CS253 | 708ca4009bc9deb4b5b8ecf0fad581f400db6723 | 95d1ac5af8b2acbe0783e2f69693add2bdc35ee3 | refs/heads/master | 2020-04-18T04:10:58.584854 | 2019-01-23T18:02:15 | 2019-01-23T18:02:15 | 167,228,575 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 590 | cpp | main.cpp | #include <Quagga.h>
#include <ZooProperty.h>
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
int ID::global_identifier = 0;
int Animal::animal_ctr = 0;
int Mammal::mammal_ctr = 0;
bool Animal::debug_flag = false;
int main(int argc, char** argv)
{
Equine* eptr = new Equine;
Mammal* mptr = reinterpret_cast<Mammal*>(eptr);
Quagga* qptr = reinterpret_cast<Quagga*>(eptr);
if(mptr) cout << mptr->WarmUp() << endl;
else cout << "mptr is null" << endl;
if(qptr) cout << qptr->WarmUp() << endl;
else cout << "qptr is null" << endl;
return 0;
}
|
30a8b7133e12c02c1d9d0d322206f1d83867f428 | 89654c35f52a5b14e2f7ac5b2edaca3e05126a65 | /Travel-Simulation-Query-System/ws_server.cpp | de6f2a61995b5e28577ead827fb1c46e011ecfcd | [
"MIT"
] | permissive | dachr8/Travel-Simulation-Query-System | 0179c80b14b3a66dc33e751c058a7276a4f9b68e | afbf44b09697c7d7bfc7a4f20f3e61f9044203cb | refs/heads/master | 2020-05-04T19:43:24.195881 | 2019-05-31T16:08:43 | 2019-05-31T16:08:43 | 179,319,098 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,867 | cpp | ws_server.cpp | #include "Simple-WebSocket-Server/server_ws.hpp"
#include "nlohmann/json.hpp"
#include <chrono>
#include <cstdint>
#include <iostream>
#include "transmission_protocol.h"
#include "ws_server.h"
namespace fdt {
using WsServer = SimpleWeb::SocketServer<SimpleWeb::WS>;
using json = nlohmann::json;
std::thread server_thread;
WsServer server;
json parse_total_transportation_plan(fdt::TotalTransportationPlan plan) {
// std::cout << "result" << std::endl;
json total_transportation_plan;
total_transportation_plan["display_info"] = plan.get_display_info();
// std::cout << "display_info ok" << std::endl;
total_transportation_plan["passenger"] = plan.get_passenger().get_id();
// std::cout << "passenger ok" << std::endl;
json json_array = json::array();
//std::vector<json> json_array = std::vector<json>();
std::vector<PlanSingleTransportation> v = plan.get_single_transportation_plan_vector();
for (auto it = v.begin(); it != v.end(); ++it) {
// std::cout << "it value " << it->get_from_vertex_display_name() << ", " <<
// it->get_to_vertex_display_name() << ", " << it->get_start_time() << ", "<<
// it->get_end_time() << std::endl;
json single_plan;
single_plan["from"] = it->get_from_vertex_display_name();
single_plan["to"] = it->get_to_vertex_display_name();
single_plan["start_time"] = it->get_start_time();
single_plan["end_time"] = it->get_end_time();
single_plan["display_info"] = it->get_transportation_display_info();
// std::cout << single_plan.dump() << std::endl;
json_array.emplace_back(single_plan);
}
total_transportation_plan["single_transportation_plans"] = json_array;
return total_transportation_plan;
}
long long get_system_timemill() {
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
}
int handle_message(const std::string &in, std::string &back) {
json j = json::parse(in);
auto function = j["function"];
if (function == "get_all_vertex") {
std::vector<fdt::Vertex> all_vertex = fdt::get_all_vertex();
json json_array = json::array();
for (auto it = all_vertex.begin(); it != all_vertex.end(); ++it) {
json vertx = json::object();
vertx["id"] = it->get_display_name();
// std::cout << "vertex_display_name" << it->get_display_name() << std::endl;
json_array.emplace_back(vertx);
}
// std::cout << "vertex_json" << json_array.dump() << std::endl;
json r_json;
r_json["function"] = "get_all_vertex";
r_json["vertex"] = json_array;
back = r_json.dump();
// back = "{\"function\": \"get_all_vertex\", \"vertex\": [{\"id\": \"id1\"}, {\"id\": \"id2\"}]}";
return 0;
}
if (function == "get_all_display_edge") {
std::vector<fdt::Edge> all_edges = fdt::get_all_display_edge();
json json_array = json::array();
for (auto it = all_edges.begin(); it != all_edges.end(); ++it) {
json vertx = json::object();
vertx["source"] = it->get_source_vertex_display_name();
vertx["target"] = it->get_destination_vertex_display_name();
// length is omitted
json_array.emplace_back(vertx);
}
json r_json;
r_json["function"] = "get_all_display_edge";
r_json["edges"] = json_array;
back = r_json.dump();
// back = "{\"function\": \"get_all_display_edge\", \"edges\": [{\"source\": \"id1\", \"target\": \"id2\"}]}";
return 0;
}
if (function == "sync_time") {
// timev = fdt::get_system_timemill();
time_t timev = fdt::sync_time();
back = "{\"function\": \"sync_time\", \"time\": " + std::to_string(timev) + "}";
return 0;
}
if (function == "submit_passenger_requirement") {
std::cout << "submit_passenger_requirement_function_called" << std::endl;
fdt::Passenger passenger = fdt::Passenger(j["passenger"]);
std::cout << "passenger normal" << std::endl;
std::vector<std::string> pass_by_vertex = std::vector<std::string>();
strategy s;
if (j["travel_strategy"] == "min_cost") {
s = minCost;
} else if (j["travel_strategy"] == "min_time") {
s = minTime;
} else if (j["travel_strategy"] == "limited_time") {
s = limitedTime;
}
// std::cout << "strategy ok" << std::endl;
auto pass_by_vertex_display_name_json_array = j["pass_by_vertex_display_name"];
for (auto it = pass_by_vertex_display_name_json_array.begin();
it != pass_by_vertex_display_name_json_array.end(); ++it) {
pass_by_vertex.emplace_back(*it);
}
// std::cout << "pass_by_vertex ok" << std::endl;
fdt::PassengerRequirement requirement = fdt::PassengerRequirement(j["from"], j["to"], j["start_time"],
pass_by_vertex, s, j["total_time_limit"]);
// std::cout << "requirement build success" << std::endl;
fdt::TotalTransportationPlan plan = fdt::submit_passenger_requirement(passenger, requirement);
json total_transportation_plan = parse_total_transportation_plan(plan);
// std::cout << __FILE__ << ":" << __LINE__ << ":" << "array_added" << std::endl;
// std::cout << __FILE__ << ":" << __LINE__ << ":" << total_transportation_plan.dump() << std::endl;
json r_json = json::object();
r_json["total_transportation_plan"] = total_transportation_plan;
// std::cout << __FILE__ << ":" << __LINE__ << ":" << r_json.dump() << std::endl;
r_json["function"] = "submit_passenger_requirement";
// std::cout << __FILE__ << ":" << __LINE__ << ";" << plan.get_passenger().get_id() << std::endl;
/*back = "{"
"\"function\": \"submit_passenger_requirement\", "
"\"total_transportation_plan\": {"
" \"passenger\": \""+ plan.get_passenger().get_id() +"\", "
"\"display_info\": \""+plan.get_display_info()+"\", "
"\"single_transportation_plans\": "+json_array.dump()+
"}"
"}";*/
std::cout << r_json.dump() << std::endl;
back = r_json.dump();
return 0;
// long long timev = fdt::get_system_timemill();
// back = "{"
// "\"function\": \"submit_passenger_requirement\", "
// "\"total_transportation_plan\": {"
// " \"passenger\": \"Mark_A\", "
// "\"display_info\": \"display_info\", "
// "\"single_transportation_plans\": [ "
// "{"
// "\"from\": \"id1\", "
// "\"to\": \"id2\", "
// "\"start_time\": " + std::to_string(timev + 1000) + ", "
// "\"end_time\": " + std::to_string(timev + 6000) +
// "}, "
// "{"
// "\"from\": \"id2\", "
// "\"to\": \"id1\", "
// "\"start_time\": " + std::to_string(timev + 6000) + ", "
// "\"end_time\": " + std::to_string(timev + 11000) +
// "}"
// "]"
// "}"
// "}";
}
if (function == "sync_total_transportation_plans") {
std::vector<TotalTransportationPlan> v = sync_total_transportation_plans();
json r_json;
r_json["function"] = "sync_total_transportation_plans";
json json_array = json::array();
for (auto it = v.begin(); it != v.end(); ++it) {
json parsed_plan = parse_total_transportation_plan(*it);
json_array.emplace_back(parsed_plan);
}
r_json["plans"] = json_array;
back = r_json.dump();
return 0;
}
if (function == "set_simulation_time_flow") {
bool flow = set_simulation_time_flow(j["flow"]);
json r_json;
r_json["function"] = "set_simulation_time_flow";
r_json["flow"] = flow;
back = r_json.dump();
return 0;
}
return 0;
}
int start_ws_server() {
server.config.port = 8145;
// Example 1: echo WebSocket endpoint
// Added debug messages for example use of the callbacks
// Test with the following JavaScript:
// var ws=new WebSocket("ws://localhost:8080/echo");
// ws.onmessage=function(evt){console.log(evt.data);};
// ws.send("test");
auto &echo = server.endpoint["^/?$"];
echo.on_message = [](std::shared_ptr<WsServer::Connection> connection,
std::shared_ptr<WsServer::Message> message) {
std::string message_str = message->string();
//std::cout << "Server: Message received: \"" << message_str << "\" from " << connection.get() << std::endl;
std::string r_message_str;
handle_message(message_str, r_message_str);
//std::cout << "Server: Sending message \"" << r_message_str << "\" to " << connection.get() << std::endl;
auto send_stream = std::make_shared<WsServer::SendStream>();
*send_stream << r_message_str;
// connection->send is an asynchronous function
connection->send(send_stream, [](const SimpleWeb::error_code &ec) {
if (ec) {
std::cout << "Server: Error sending message. " <<
// See http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html, Error Codes for error code meanings
"Error: " << ec << ", error message: " << ec.message() << std::endl;
}
});
};
echo.on_open = [](std::shared_ptr<WsServer::Connection> connection) {
std::cout << "Server: Opened connection " << connection.get() << std::endl;
};
// See RFC 6455 7.4.1. for status codes
echo.on_close = [](std::shared_ptr<WsServer::Connection> connection, int status,
const std::string & /*reason*/) {
std::cout << "Server: Closed connection " << connection.get() << " with status code " << status
<< std::endl;
};
// See http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html, Error Codes for error code meanings
echo.on_error = [](std::shared_ptr<WsServer::Connection> connection, const SimpleWeb::error_code &ec) {
std::cout << "Server: Error in connection " << connection.get() << ". "
<< "Error: " << ec << ", error message: " << ec.message() << std::endl;
};
server_thread = std::thread([&server]() {
// Start WS-server
server.start();
});
server_thread.detach();
return 0;
}
} |
86a92d214c85cdaf3e116cb388728c40bac0dcd3 | db8dfd7ef00432842d187335ca6598341edc1922 | /escher/src/input_event_handler.cpp | dd9800361feb77207e10f560cbb922c73a11a836 | [] | no_license | EmilieNumworks/epsilon | a60746285ede5a603916e5dc9361a689926f0fbd | bb3baa7466f39f32b285f2d14b6dc1f28e22e7a5 | refs/heads/master | 2023-01-28T20:49:55.903580 | 2022-09-02T13:15:05 | 2022-09-02T13:15:05 | 102,631,554 | 1 | 0 | null | 2017-09-06T16:20:48 | 2017-09-06T16:20:48 | null | UTF-8 | C++ | false | false | 839 | cpp | input_event_handler.cpp | #include <escher/input_event_handler.h>
#include <escher/input_event_handler_delegate.h>
#include <escher/container.h>
#include <escher/toolbox.h>
#include <escher/metric.h>
namespace Escher {
bool InputEventHandler::handleBoxEvent(Ion::Events::Event event) {
if (m_inputEventHandlerDelegate == nullptr) {
return false;
}
NestedMenuController * box = nullptr;
if (event == Ion::Events::Toolbox) {
box = m_inputEventHandlerDelegate->toolboxForInputEventHandler(this);
} else if (event == Ion::Events::Var) {
box = m_inputEventHandlerDelegate->variableBoxForInputEventHandler(this);
}
if (box) {
box->setSender(this);
Container::activeApp()->displayModalViewController(box, 0.f, 0.f, Metric::PopUpTopMargin, Metric::PopUpLeftMargin, 0, Metric::PopUpRightMargin);
return true;
}
return false;
}
}
|
f3420d921f0a8d87f06b84922e82b7df76a6325c | f26ef5f176c2e9d9fe3fbbc9a04e4e17a2189a48 | /C++/LIBRAS.CyberGlove/include/vhandtk/vhtDebugUtility.h | ee40df7b6e729a5dbd3b1243e9ca2a10cc1d42dd | [] | no_license | haroldogtf/LIBRAS.CyberGlove | 9df17fee91a3d318d0eb4161d9702eeea23fa4c8 | a1f7fc92efce0a9221bfc2037c37b9b926bc9f0e | refs/heads/master | 2021-01-15T10:06:51.297507 | 2016-05-09T02:19:32 | 2016-05-09T02:19:32 | 53,633,766 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 707 | h | vhtDebugUtility.h | #ifndef VHT_DEBUG_UTILITY_H
#define VHT_DEBUG_UTILITY_H
#if defined(BUILD_WIN32_VH_DLL)
#if defined __BUILD_VH_CORE_DLL__
#define VH_CORE_DLL_EXPORT __declspec(dllexport)
#else
#define VH_CORE_DLL_EXPORT __declspec(dllimport)
#endif
#else
#define VH_CORE_DLL_EXPORT
#endif
#include <vhtNode.h>
//: Debug utility.
// Various debugging utilities.
//!vhtmodule: Core
class VH_CORE_DLL_EXPORT vhtDebugUtility
{
public:
static void printSubTree( vhtNode *subTree, int indentLength = 0 );
//: Print a sub-tree to stdout.
//!param: subTree - Subtree to print.
//!param: indentLength - Number of spaces to prepend.
static void printHSGToFile( vhtNode *hsg, const char *filename );
};
#endif
|
ba2151a63d3c291857db68a55004f730ac63b544 | e68c1cc8b6a86de7e571bfb09424e58f3ddb2a26 | /src/main.cpp | 619b3d082f0a1cbf077982aa72ed13dca35715ed | [] | no_license | pschild/esp-lib-tester | 42dca78c0bc439dc3acc11859ddc24371fd8feb5 | 482b23eb28cf1d573d05332a39ddc02b42738b5e | refs/heads/master | 2022-11-06T09:04:25.793241 | 2020-06-16T20:19:47 | 2020-06-16T20:19:47 | 272,799,820 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,301 | cpp | main.cpp | #include <Arduino.h>
#include <ESP8266WiFi.h>
#include <MqttHandler.h>
#include <OTAUpdateHandler.h>
#ifndef WIFI_SSID
#error "Missing WIFI_SSID"
#endif
#ifndef WIFI_PASSWORD
#error "Missing WIFI_PASSWORD"
#endif
#ifndef VERSION
#error "Missing VERSION"
#endif
MqttHandler mqttHandler("192.168.178.28", String("ESP_") + String(ESP.getChipId()));
OTAUpdateHandler updateHandler("192.168.178.28:9042", VERSION);
void connectToWifi() {
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
unsigned long wifiConnectStart = millis();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
if (millis() - wifiConnectStart > 5000) {
return;
}
}
}
void onFooBar(char* payload) {
Serial.print("onFooBar");
if (strcmp(payload, "on") == 0) {
digitalWrite(LED_BUILTIN, LOW);
} else if (strcmp(payload, "off") == 0) {
digitalWrite(LED_BUILTIN, HIGH);
}
}
void cb() {
Serial.println("connected callback");
mqttHandler.subscribe("/foo/bar", onFooBar);
}
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
connectToWifi();
mqttHandler.setOnConnectedCallback(cb);
mqttHandler.setup();
updateHandler.setInterval(30 * 1000);
}
void loop() {
mqttHandler.loop();
updateHandler.loop();
} |
74cd7e84e083518418dd85bf865316956c94f267 | ab2bde2ea02c5ad234c6d27b5a821125b7a9c83b | /src/app/sample_bank.cpp | 7fc170d3ad45ff3ea64cda0e79d0b7dc45180c71 | [
"BSD-3-Clause"
] | permissive | flit/modular | b4badd2463466feb271355199558b2c27dd6925f | c568b2fadf30a9c790733573658fa70a2c9608f3 | refs/heads/master | 2021-01-11T16:51:01.048309 | 2019-03-03T00:56:18 | 2019-03-03T00:56:18 | 79,678,785 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,731 | cpp | sample_bank.cpp | /*
* Copyright (c) 2017-2018 Immo Software
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* o Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "sample_bank.h"
#include "debug_log.h"
#include "wav_file.h"
#include "samplbaer.h"
using namespace slab;
//------------------------------------------------------------------------------
// Code
//------------------------------------------------------------------------------
SampleBank::SampleBank()
{
}
void SampleBank::reset()
{
uint32_t i;
for (i = 0; i < kVoiceCount; ++i)
{
_samples[i].reset();
}
}
bool SampleBank::is_valid() const
{
uint32_t i;
for (i = 0; i < kVoiceCount; ++i)
{
if (_samples[i].is_valid())
{
return true;
}
}
return false;
}
void SampleBank::load_params()
{
fs::Path settingsPath(_dirPath);
settingsPath.append("/settings.bin");
fs::File settingsFile(settingsPath.get());
if (settingsFile.open() != fs::kSuccess)
{
return;
}
uint32_t version;
BinaryArchive archive(settingsFile);
if (!archive.open(&version)
|| version != kSettingsFileDataVersion)
{
return;
}
uint32_t i;
for (i = 0; i < kVoiceCount; ++i)
{
if (!_samples[i].is_valid())
{
continue;
}
uint32_t voiceNumber;
if (!archive.read("voice-number", &voiceNumber))
{
return;
}
if (voiceNumber != i)
{
return;
}
char path[_MAX_LFN + 1];
if (!archive.read("path", &path, sizeof(path)))
{
return;
}
if (strncmp(path, _samples[i].get_path().get(), strlen(path)) != 0)
{
return;
}
if (!_samples[i].load_params(archive))
{
return;
}
}
}
void SampleBank::save_params()
{
fs::Path settingsPath(_dirPath);
settingsPath.append("/settings.bin");
fs::File settingsFile(settingsPath.get());
settingsFile.remove();
if (settingsFile.open(true, true) != fs::kSuccess)
{
return;
}
BinaryArchive archive(settingsFile);
if (!archive.init(kSettingsFileDataVersion))
{
return;
}
uint32_t i;
for (i = 0; i < kVoiceCount; ++i)
{
if (!_samples[i].is_valid())
{
continue;
}
if (!archive.write("voice-number", i))
{
return;
}
if (!archive.write("path", _samples[i].get_path().get(), _MAX_LFN + 1))
{
return;
}
if (!_samples[i].save_params(archive))
{
return;
}
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SampleBank::Sample::Sample()
: _isValid(false),
_params()
{
}
void SampleBank::Sample::reset()
{
_isValid = false;
_path = fs::Path("");
_params.reset();
}
void SampleBank::Sample::set_path(const fs::Path & path)
{
_path = path;
if (_path.get()[0] != 0)
{
_isValid = true;
}
}
bool SampleBank::Sample::load_to_voice(SamplerVoice & voice)
{
if (!_isValid)
{
voice.clear_file();
return false;
}
// Open and parse .wav file.
WaveFile wav(_path.get());
fs::error_t err = wav.parse();
if (err != fs::kSuccess)
{
DEBUG_PRINTF(ERROR_MASK, "Failed to parse %s\r\n", _path.get());
voice.clear_file();
return false;
}
// Only support 16-bit format files with 1 or 2 channels. If the sample rate is not
// 48k then it will be played off-pitch.
if (!(wav.get_channels() <= 2
&& wav.get_sample_size() == 16))
{
DEBUG_PRINTF(ERROR_MASK, "File %s is an unsupported format\r\n", _path.get());
voice.clear_file();
return false;
}
// Set sample file in voice.
voice.set_file(wav);
voice.set_params(_params);
DEBUG_PRINTF(INIT_MASK, "%s: %lu ch; %lu frames\r\n",
_path.get(),
wav.get_channels(),
voice.get_audio_stream().get_frames());
return true;
}
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
|
29f5e0a254505ef716f5033ce76f464163a698ef | ab03f6cd8f25ec67a0777ad8c653440dbdd23a11 | /Algorithms/RabinKarp.cpp | d26ff4148e0cd9dcd44f1884ef55960b7c5688a3 | [] | no_license | Arkaim/ADS | d9e4d99a3b71dd55058f6d61576f2d0e13701db4 | e900f31d6ad5c2555481665d25cf5db722ddff45 | refs/heads/master | 2020-07-10T19:07:37.420526 | 2016-12-09T06:40:59 | 2016-12-09T06:40:59 | 74,010,733 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | cpp | RabinKarp.cpp | #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
static int RabinKarp (string p, string t) {
int M = p.length();
int N = t.length();
int dM = 1, h1 = 0, h2 = 0;
int q = 17111997;
int d = 256;
for (int j = 1; j< M; j++) {
dM = (d * dM) % q;
}
for (int j = 0; j < M; j++) {
h1= (h1*d +p.at(j)) %q;
h1= (h2*d +p.at(j)) %q;
}
if (h1 == h2) {
return (j - M);
}
for (int i = M; i<N; i++) {
h2 = (h2 - t.at(i-M)) % q;
h2 = (h2*d + t.at(i)) % q;
if (h1 == h2)
{
return i-M;
}
}
return -1;
}
int main(int argc, char const *argv[])
{
string f = "ababababaaca";
string b = "aba";
int p = RabinKarp(f,b);
cout<<p;
return 0;
} |
60abfd294474862fd8b8345ed89e03ff8a6b9d6a | d2006e6957e94e45c7ac94ce367db9fe7d505eeb | /Array/longest_repeated_substring.cpp | 5182e25f8f18f8f4e216b17afbc3dcdc5c590b54 | [] | no_license | JoaoDanielRufino/Algorithms | f4b81ea1518b7cf3404f2f93ecaa9cf4d1a6f51a | 34928bbcb24c8f28beb174005318243d2c201513 | refs/heads/master | 2023-07-09T02:23:44.996374 | 2023-07-05T01:05:06 | 2023-07-05T01:05:06 | 102,634,890 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 900 | cpp | longest_repeated_substring.cpp | // Comprexity: O(n^2logn)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
string longestCommonPrefix(string s, string p) {
int len = min(s.size(), p.size());
for(int i = 0; i < len; i++) {
if(s[i] != p[i])
return s.substr(0, i);
}
return s.substr(0, len);
}
string longestRepeatedSubstring(string s) {
vector<string> suffix;
for(int i = 0; i < s.size(); i++)
suffix.push_back(s.substr(i, s.size())); // Building the suffix array
sort(suffix.begin(), suffix.end());
string lrs;
for(int i = 0; i < s.size()-1; i++) {
string len = longestCommonPrefix(suffix[i], suffix[i+1]);
if(len.size() > lrs.size())
lrs = len;
}
return lrs;
}
int main() {
string s = "abracadrabra";
string p = "banana";
cout << longestRepeatedSubstring(s) << endl;
cout << longestRepeatedSubstring(p) << endl;
return 0;
}
|
04b917f545017ab6b9de7c36761a6d323c3ca5f7 | ef8c41d9aa92151f402cff705a4bac872e4e2383 | /simple-middleware/bt-connectivity/src/main/arduino/multiple_resources/MsgService.h | 13ffc95aa19f1691d85875df8b5e826250ce42be | [] | no_license | puccife/pslab-middleware | 9e30b81f59421c26790150587f7b16095232ad8d | 5747182952a9ddf7489493ddb2b467de5cea8e3a | refs/heads/master | 2021-04-03T08:17:04.992092 | 2018-03-11T13:01:21 | 2018-03-11T13:01:21 | 124,756,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 525 | h | MsgService.h | #ifndef __MSGSERVICE__
#define __MSGSERVICE__
#include <ArduinoJson.h>
#include <Stream.h>
class Msg {
public:
Msg(const String& content);
String getContent(void) const;
private:
String mContent;
};
class MsgService {
public:
MsgService(Stream *stream);
bool isMsgAvailable(void) const;
Msg* receiveMsg(void);
void sendMsg(const String& message) const;
void sendMsg(const Msg& message) const;
private:
Stream *mStream;
String mContent;
};
#endif /* __MSGSERVICE__ */
|
a8094245f4775fb09c5ecc73e4402d75a1f90264 | e9556bdc5de2360f9db12aa6162d20a09a14dee9 | /src/anki/gr/vulkan/Texture.cpp | 9293df5f6a64ce1b34ce000187caaa4775bd408d | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | Chainsawkitten/anki-3d-engine | e390638f71c833608a29765b21812343708b8af1 | 0c6b9ef3d9ff3c276f067543fcd6c6bf251f26b2 | refs/heads/master | 2021-05-14T01:15:38.405207 | 2017-12-20T20:10:02 | 2017-12-20T20:10:02 | 116,559,250 | 0 | 0 | null | 2018-01-07T11:19:28 | 2018-01-07T11:19:27 | null | UTF-8 | C++ | false | false | 460 | cpp | Texture.cpp | // Copyright (C) 2009-2017, Panagiotis Christopoulos Charitos and contributors.
// All rights reserved.
// Code licensed under the BSD License.
// http://www.anki3d.org/LICENSE
#include <anki/gr/Texture.h>
#include <anki/gr/vulkan/TextureImpl.h>
#include <anki/gr/GrManager.h>
namespace anki
{
Texture* Texture::newInstance(GrManager* manager, const TextureInitInfo& init)
{
return TextureImpl::newInstanceHelper(manager, init);
}
} // end namespace anki
|
bc5b6cd02a44088d98fdb7915c72edee334a5424 | 573c547711b37c129374f1911d7924cbaf88d4c0 | /lib/Target/M68k/M68kISelDAGToDAG.cpp | bf61a7371d5c7d13f77e6c9708c7ae7167a9d245 | [
"NCSA"
] | permissive | mntmn/llvm-m68k | c938431ace129a1502bf7e278a1d677a8aecb6b4 | 9391e3e1cab24da98bc3919ecbf180d65544409e | refs/heads/m68k | 2021-01-12T17:22:05.717093 | 2016-09-28T17:18:34 | 2016-09-28T17:18:34 | 69,486,376 | 5 | 0 | null | 2016-09-28T17:17:28 | 2016-09-28T17:17:28 | null | UTF-8 | C++ | false | false | 2,368 | cpp | M68kISelDAGToDAG.cpp | //===-- M68kISelDAGToDAG.cpp - M68k Instruction Selector --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "m68k-isel"
#include "M68k.h"
#include "M68kTargetMachine.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <stdio.h>
using namespace llvm;
namespace {
class M68kDAGToDAGISel : public SelectionDAGISel {
M68kTargetMachine &TM;
public:
explicit M68kDAGToDAGISel(M68kTargetMachine &TM)
: SelectionDAGISel(TM),
TM(TM) { }
virtual bool runOnMachineFunction(MachineFunction &MF) {
bool res = SelectionDAGISel::runOnMachineFunction(MF);
return res;
}
virtual SDNode *Select(SDNode *Node);
private:
uint64_t invertValue(const ConstantSDNode *N) const {
const uint64_t mask = (1 << N->getConstantIntValue()->getBitWidth()) - 1;
return N->getZExtValue() ^ mask;
}
// Tablegenerated selector
#include "M68kGenDAGISel.inc"
// Complex Patterns.
bool SelectAddr(SDNode *Parent, SDValue N, SDValue &Base, SDValue &Offset);
};
} // end anonymous namespace
SDNode *M68kDAGToDAGISel::Select(SDNode *Node) {
// const unsigned Opcode = Node->getOpcode();
if (Node->isMachineOpcode()) {
return NULL;
}
// Default selection
SDNode *ResNode = SelectCode(Node);
return ResNode;
}
bool M68kDAGToDAGISel::SelectAddr(SDNode *Parent, SDValue Addr, SDValue &Base,
SDValue &Offset) {
DEBUG(dbgs() << "SelectAddr\n");
DEBUG(Addr->dump());
EVT ValTy = Addr.getValueType();
// Frame index matcher
if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
Offset = CurDAG->getTargetConstant(0, MVT::i16);
return true;
}
// TODO other memory matching
Base = Addr;
Offset = CurDAG->getTargetConstant(0, MVT::i16);
return true;
}
FunctionPass *llvm::createM68kISelDag(M68kTargetMachine &TM) {
return new M68kDAGToDAGISel(TM);
}
|
35b0a8f760618384868bc854086d768c41873483 | 10e0e4a6021587a032317ef62d94cae56b44d6d6 | /sources/CMarkInfoParameters.h | cccfccd5b85eb537136c9fee92c6c3707f97b8ae | [] | no_license | jamiepg1/veris6 | 8cb52122d26438f192644506a1a6fb289ba7cecd | e1639d3b79388b6dfa6fb055f419ed41ee615a21 | refs/heads/master | 2018-03-26T16:45:01.203355 | 2014-08-06T00:30:09 | 2014-08-06T00:30:09 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,630 | h | CMarkInfoParameters.h | // =======================================================================
// CMarkInfoParameters.h ©2008-2014 EDI
// =======================================================================
#pragma once
#include "CGraphParameters.h"
class CMarkInfoParameters: public CGraphParameters
{
public:
CMarkInfoParameters (CAnalysisSettings *inAnalysisSettings);
virtual ~CMarkInfoParameters (){}
virtual void Load (LStream& inStream);
virtual void LoadDone ();
virtual void Save (LStream& inStream);
virtual void Validate (CSetupData *inSetupData);
virtual EPlotType GetPlotType ();
virtual void CopyTo (CPlotParameters *outPlotParameters);
virtual void SynchronizeWith (CPlotParameters *oldParameters, CPlotParameters *newParameters);
virtual bool IsEqualTo (CPlotParameters *inPlotParameters);
virtual bool HasOverlay1Source1Changed(CPlotParameters *inOldPlotParameters);
virtual bool HasOverlay2Source1Changed(CPlotParameters *inOldPlotParameters);
virtual EGraphType GetGraphType (long inGraphNum);
long NumGraphsNeeded (long inNumOverlays);
long GraphNumToOverlay (long inGraphNum, long inNumOverlays, long inFirstOverlayNum);
bool AreSTDValuesReusable(CPlotParameters *oldParameters);
long mVersion;
//
// parameters
//
EMarkInfoType mDisplayType;
bool mShowSTDBand;
double mNumSTDInBand;
double mCentralAreaRadius;
//
// temporary
//
long mNumOverlays;
private:
void LoadOldVersion (LStream& inStream);
};
inline EPlotType CMarkInfoParameters::GetPlotType()
{
return plotType_MarkInfo;
}
|
fb9965fe0d2638786c1f1652ea4127b78fe41420 | e90b372c96445d3ae22846913c40706cc70453c2 | /Huffman.cpp | a6dc04a52af7948abc68709b250fd85371887a72 | [] | no_license | octopus0110/Products | 9a013ffe5eed8dfabd6143260207399db2a2f15d | e8d4fb8e85bdd38aa3f214441604a245aaf4697d | refs/heads/master | 2023-06-19T22:57:55.840819 | 2021-07-07T09:24:12 | 2021-07-07T09:24:12 | 277,852,438 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,833 | cpp | Huffman.cpp | #include <iostream>
#include <vector>
#include <unordered_map>
#include <cmath>
#include <algorithm>
using namespace std;
#define INF 1000000000
template<class T>
void p(vector<T> A)
{
for (auto a: A) cout << a << " ";
cout << endl;
}
struct Huffman
{
int len_bit, len_code;
string text, code;
double compression_rate;
vector<char> appeared_alp;
vector<int> count_alp, tree, parent, left, right;
vector<bool> fixed;
unordered_map<char, string> encodealp;
unordered_map<string, char> decodebi;
void get_len();
void count_appear(const string&);
void init_tree();
void make_tree(const int);
pair<int, int> find_nodes();
void encode_alp(const int, const string&);
string Encode(const string&);
string Decode(const string&);
};
void Huffman::get_len()
{
len_bit = (int)ceil(log2(appeared_alp.size()));
len_bit *= text.size();
len_code = code.size();
}
void Huffman::count_appear(const string& S)
{
appeared_alp.clear();
count_alp.clear();
unordered_map<char, int> M;
for (char c: S) ++M[c];
for (pair<char, int> p: M)
{
appeared_alp.emplace_back(p.first);
count_alp.emplace_back(p.second);
}
}
void Huffman::init_tree()
{
for (int i: count_alp)
{
tree.emplace_back(i);
parent.push_back(-1);
left.push_back(-1);
right.push_back(-1);
fixed.push_back(false);
}
}
void Huffman::make_tree(const int depth)
{
if (depth == 0) init_tree();
pair<int, int> nodes;
nodes = find_nodes();
if (nodes.second == -1) return;
int n1, n2;
n1 = nodes.first;
n2 = nodes.second;
tree.emplace_back(tree[n1]+tree[n2]);
left.emplace_back(n1);
right.emplace_back(n2);
parent.emplace_back(-1);
fixed.emplace_back(false);
parent[n1] = tree.size()-1;
parent[n2] = tree.size()-1;
fixed[n1] = true;
fixed[n2] = true;
make_tree(depth+1);
}
pair<int, int> Huffman::find_nodes()
{
pair<int, int> nodes = {-1, -1};
int min1 = INF, min2 = INF;
for (int i = 0; i < tree.size(); ++i)
{
if (fixed[i]) continue;
if (min1 > tree[i])
{
min2 = min1;
nodes.second = nodes.first;
min1 = tree[i];
nodes.first = i;
}
else if (min2 > tree[i])
{
min2 = tree[i];
nodes.second = i;
}
}
return nodes;
}
void Huffman::encode_alp(const int node, const string& code)
{
int l, r;
string code_l, code_r;
l = left[node];
r = right[node];
code_l = code + "0";
code_r = code + "1";
if (left[l] == -1 && right[l] == -1)
{
encodealp[appeared_alp[l]] = code_l;
decodebi[code_l] = appeared_alp[l];
}
else encode_alp(l, code_l);
if (left[r] == -1 && right[r] == -1)
{
encodealp[appeared_alp[r]] = code_r;
decodebi[code_r] = appeared_alp[r];
}
else encode_alp(r, code_r);
return;
}
string Huffman::Encode(const string& _text)
{
text = _text;
code = "";
count_appear(text);
make_tree(0);
encode_alp(tree.size()-1, "");
for (char c: text) code += encodealp[c];
get_len();
compression_rate = (double)len_code / (double)len_bit;
return code;
}
string Huffman::Decode(const string& _code)
{
string _text = "", key = "";
for (char c: _code)
{
key += c;
if (decodebi[key] != 0)
{
_text += decodebi[key];
key = "";
}
}
return _text;
}
int main()
{
Huffman H;
string text, code, decode;
cout << "text : ";
getline(cin, text);
cout << "text : " << text << endl;
code = H.Encode(text);
decode = H.Decode(code);
printf("Encode : %s\n", code.c_str());
printf("Decode : %s\n", decode.c_str());
printf("Commpression Rate : %lf\n", H.compression_rate);
printf("Code Length : %d\n", H.len_code);
vector<char> appeared_alp = H.appeared_alp;
sort(appeared_alp.begin(), appeared_alp.end());
for (char c: appeared_alp) printf("%c : %s\n", c, H.encodealp[c].c_str());
return 0;
}
|
980d3aa8c2339ca7b8e789f779f4ef5d661280a7 | bd00fd5c1f9aeef8ddf89922d67978fa9a1954a2 | /QtCode/JiSuanQi/simple_edit.cpp | 29833717455700d2f87e25768e37ad28f5f37e50 | [] | no_license | jrdlovell/Package | d541cdeaa33f12d9de44450fa364f651f408f959 | 2bcbad6030db1dc8e298d6c70cc52934a600a934 | refs/heads/master | 2021-01-16T13:44:38.733253 | 2018-07-12T06:34:10 | 2018-07-12T06:34:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 495 | cpp | simple_edit.cpp | #include "simple_edit.h"
SimpleEdit::SimpleEdit(QWidget *parent) : QLineEdit(parent)
{
connect(this,&QLineEdit::textChanged,this,&SimpleEdit::changeFontSize);
//改变文本-->改变字体大小。
}
void SimpleEdit::changeFontSize()
{
QFont font;
if (text().size() <= 10) {
font.setPointSize(20);
} else if (text().size() > 10) {
font.setPointSize(15);
} else if (text().size() > 15) {
font.setPointSize(10);
}
this->setFont(font);
}
|
4bf82781344b2ea4fc80d87554a59deab8d8bf2d | a7d7267ebb6bf627737004c17250d2ae75d6ea08 | /dali-csharp-binder/src/capabilities.cpp | 3bffd79d08a8786abb66a72f4b438b119fb3a048 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | elishateng/dali-csharp-binder | 8c03a25ea2aa1513f0a0f71f37bc1136eeba81b6 | 5a58c26dc0b295216aac9e2b5eb472eb84e6b17d | refs/heads/master | 2023-04-25T07:23:30.669132 | 2021-05-21T09:18:01 | 2021-05-21T09:18:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,629 | cpp | capabilities.cpp | #ifndef CSHARP_CAPABILITIES
#define CSHARP_CAPABILITIES
/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "common.h"
#include <dali/devel-api/common/capabilities.h>
#ifdef __cplusplus
extern "C" {
#endif
SWIGEXPORT bool SWIGSTDCALL CSharp_Dali_IsBlendEquationSupported( int blendEquation ) {
bool jresult;
{
try {
jresult = Dali::Capabilities::IsBlendEquationSupported( static_cast<Dali::DevelBlendEquation::Type>(blendEquation) );
}
catch (std::out_of_range & e) {
{
SWIG_CSharpException(SWIG_IndexError, const_cast<char*>(e.what())); return 0;
};
}
catch (std::exception & e) {
{
SWIG_CSharpException(SWIG_RuntimeError, const_cast<char*>(e.what())); return 0;
};
}
catch (Dali::DaliException e) {
{
SWIG_CSharpException(SWIG_UnknownError, e.condition); return 0;
};
}
catch (...) {
{
SWIG_CSharpException(SWIG_UnknownError, "unknown error"); return 0;
};
}
}
return jresult;
}
#ifdef __cplusplus
}
#endif
#endif |
71affe0828f9162bd048865aab21a256123c4d4d | 3f3095dbf94522e37fe897381d9c76ceb67c8e4f | /Current/Cheat_SpawnGems.hpp | 92633dfc7cef5b0094ca805ec7eb3b79317cdf01 | [] | no_license | DRG-Modding/Header-Dumps | 763c7195b9fb24a108d7d933193838d736f9f494 | 84932dc1491811e9872b1de4f92759616f9fa565 | refs/heads/main | 2023-06-25T11:11:10.298500 | 2023-06-20T13:52:18 | 2023-06-20T13:52:18 | 399,652,576 | 8 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 595 | hpp | Cheat_SpawnGems.hpp | #ifndef UE4SS_SDK_Cheat_SpawnGems_HPP
#define UE4SS_SDK_Cheat_SpawnGems_HPP
class UCheat_SpawnGems_C : public UUserWidget
{
FPointerToUberGraphFrame UberGraphFrame;
class UButton* Button_0;
class UComboBoxString* ComboBoxString_0;
TArray<class UGemResourceData*> Gems;
void OnRep_CurrentDrink();
void OnLoaded_BE285B9A4EF0300DE4DE55BE5B655D0B(UClass* Loaded);
void Construct();
void BndEvt__Cheat_SpawnBeers_Button_0_K2Node_ComponentBoundEvent_1_OnButtonClickedEvent__DelegateSignature();
void ExecuteUbergraph_Cheat_SpawnGems(int32 EntryPoint);
};
#endif
|
3479ae62d7e6332886fc6dfded8069df6806266c | 6e131dda5d27f451f9a00e36c98155102f473725 | /rlscontrol.h | eb6c1ea7ed9d9289b03607c85ce168478c94a02e | [] | no_license | bobreg/asku-gui | ff200095dd21536aa03b8336974fdcfa632fd11c | 31b68e8098b3f012520199cabbb9c0e15c76a890 | refs/heads/master | 2022-12-14T05:46:01.139220 | 2020-09-15T06:37:04 | 2020-09-15T06:37:04 | 295,638,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,154 | h | rlscontrol.h | #ifndef __RLSCONTROL_H__
#define __RLSCONTROL_H__
#include <QObject>
#include <QHostAddress>
#include "config.h"
//----------------------------------------------------------------------------------------------------------------
enum AskuRlsIds {
idRlsIdUnknown = -1
};
//----------------------------------------------------------------------------------------------------------------
class AskuRls
{
QString m_name;
QString m_scheme;
QString m_title;
QString m_litera;
quint32 m_index;
QHostAddress m_ip_gpr1;
QHostAddress m_ip_gpr2;
quint16 m_port_gpr1;
quint16 m_port_gpr2;
public:
AskuRls();
AskuRls(QString name, QString scheme, QString title = QString(), QString litera = QString(), quint32 index = 0);
void setName(QString name);
void setSchemeFile(QString scheme);
void setTitle(QString title);
void setLitera(QString litera);
void setIndex(quint32 index);
void setNetwork(QString ip1, quint16 port1, QString ip2, quint16 port2);
void setNetworkGpr1(QString ip, quint16 port);
void setNetworkGpr2(QString ip, quint16 port);
QString name();
QString scheme();
QString title();
QString litera();
quint32 index();
QHostAddress ipGpr1();
QHostAddress ipGpr2();
quint16 portGpr1();
quint16 portGpr2();
};
//----------------------------------------------------------------------------------------------------------------
typedef QMap<quint32, AskuRls*> AskuRlsList;
//----------------------------------------------------------------------------------------------------------------
class AskuRlsControl : public QObject
{
Q_OBJECT
AskuRlsList m_rlsList;
AskuConfig *m_config;
public:
AskuRlsControl(QObject * parent = 0);
AskuRls * appendRls(QString name, QString config, QString title = QString(), QString litera = QString(), quint32 index = 0);
void appendRls(AskuRls * rls);
void clear();
void setConfig(AskuConfig * config);
AskuRlsList getRlsList();
qint32 getRlsIdByPeer(QHostAddress address, quint16 port);
public slots:
void applyConfig();
};
//----------------------------------------------------------------------------------------------------------------
#endif // __RLSCONTROL_H__
|
18148f898a02180239a7b5f947b66eff77f3deb9 | 17e937c04116a24edaea43a99ae04b1c32e6850c | /Ebook/Ebook/fig03_01.cpp | 2b2d850c987e0810887dba183aed957df4d78a84 | [] | no_license | OccupyDuna/Ebook | c8105102a98a5d47a07a2ddbed9180e15814f75d | 2c1cc93583f9a649f8cf124e0454854401f752bf | refs/heads/master | 2021-01-21T17:06:31.226130 | 2017-05-22T12:13:53 | 2017-05-22T12:13:53 | 91,930,715 | 0 | 0 | null | 2017-05-22T12:13:54 | 2017-05-21T03:27:01 | C++ | UTF-8 | C++ | false | false | 546 | cpp | fig03_01.cpp | // Fig. 3.1
// Define class GradeBook with a member function displayMessage
// create a GradeBook object, and call its diaplayMessage function.
#include <iostream>
using namespace std;
// GradeBook class definition
class GradeBook
{
public:
// Display Welcome message
void displayMessage()
{
cout << "Welcome to the Grade Book!" << endl;
}
};
int main()
{
GradeBook myGradeBook; // create a GradeBook Object named myGradeBook
myGradeBook.displayMessage(); // call object's displayMesssage function
} // end main |
6aa64d91c9d407a811a10b3ac6a1c0abcdaa0986 | 45b286742deac8638ec06e00c888e9554f5637d4 | /libraries/libym_bdd/bmc/bmc_sup.cc | 46e021e29d608d87251f0e95d0751ec569e2f976 | [] | no_license | yusuke-matsunaga/minimaleda | 0800200f42474a2dbe08d94d977678d67ee085d1 | e0619bfd34baf3ca27c23d2f705067297209104a | refs/heads/master | 2021-01-20T20:03:15.199896 | 2016-08-02T03:43:11 | 2016-08-02T03:43:11 | 64,721,871 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,524 | cc | bmc_sup.cc |
/// @file libym_bdd/bmc/bmc_sup.cc
/// @brief サポート変数を求める関数の実装ファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// $Id: bmc_sup.cc 2507 2009-10-17 16:24:02Z matsunaga $
///
/// Copyright (C) 2005-2006 Yusuke Matsunaga
/// All rights reserved.
#if HAVE_CONFIG_H
#include <ymconfig.h>
#endif
#include "BddMgrClassic.h"
#include "BmcCompTbl.h"
BEGIN_NAMESPACE_YM_BDD
// eを根とするBDDのサポートに印をつける.
tVarSize
BddMgrClassic::mark_support(tBddEdge e)
{
clear_varmark();
sup_step(e);
clear_pnmark(e);
return mVarSet.size();
}
// edge_list に含まれる枝を根とするBDDのサポートに印をつける.
tVarSize
BddMgrClassic::mark_support(const list<tBddEdge>& edge_list)
{
clear_varmark();
// サポート変数にマークをつける.
for (list<tBddEdge>::const_iterator p = edge_list.begin();
p != edge_list.end(); ++ p) {
sup_step(*p);
}
for (list<tBddEdge>::const_iterator p = edge_list.begin();
p != edge_list.end(); ++ p) {
clear_pnmark(*p);
}
return mVarSet.size();
}
// サポート変数に印をつける.
void
BddMgrClassic::sup_step(tBddEdge e)
{
for ( ; ; ) {
Node* vp = get_node(e);
if ( vp == 0 || vp->pmark() ) {
return;
}
vp->pmark(1);
Var* v = vp->var();
if ( !v->mMark ) {
v->mMark = 1;
mVarSet.push_back(v);
}
sup_step(vp->edge0());
e = vp->edge1();
}
}
// var_mark を列挙してマークのついた変数を vars に入れる.
tVarSize
BddMgrClassic::mark_to_vector(VarVector& vars)
{
tVarSize n = mVarSet.size();
vars.clear();
vars.reserve(n);
for (list<Var*>::iterator p = mVarSet.begin(); p != mVarSet.end(); ++ p) {
Var* v = *p;
tVarId varid = v->varid();
vars.push_back(varid);
}
clear_varmark();
sort(vars.begin(), vars.end());
return vars.size();
}
// var_mark を列挙してマークのついた変数を vars に入れる.
tVarSize
BddMgrClassic::mark_to_list(VarList& vars)
{
vars.clear();
for (list<Var*>::iterator p = mVarSet.begin(); p != mVarSet.end(); ++ p) {
Var* v = *p;
tVarId varid = v->varid();
vars.push_back(varid);
}
clear_varmark();
vars.sort();
return vars.size();
}
// var_mark を列挙してマークのついた変数を vars に入れる.
tBddEdge
BddMgrClassic::mark_to_bdd()
{
if ( mVarSet.empty() ) {
return kEdge1;
}
list<Var*>::iterator p = mVarSet.begin();
tBddEdge tmp = make_posiliteral((*p)->varid());
for (++ p; p != mVarSet.end(); ++ p) {
tmp = and_op(tmp, make_posiliteral((*p)->varid()));
}
clear_varmark();
return tmp;
}
// Smallest Cube Containing F を求める.
// メモリ不足のためにエラーとなる可能性がある.
tBddEdge
BddMgrClassic::SCC(tBddEdge e)
{
if ( check_error(e) ) {
return kEdgeError;
}
if ( check_overflow(e) ) {
return kEdgeOverflow;
}
if ( check_one(e) ) {
return kEdge1;
}
if ( check_zero(e) ) {
return kEdge0;
}
// まずサポートを求める.
mark_support(e);
tBddEdge sup = mark_to_bdd();
// サポートを用いて SCC を計算する.
clear_varmark();
scc_step(e, sup);
clear_pnmark(e);
tBddEdge ans = kEdge1;
for (list<Var*>::iterator p = mVarSet.begin(); p != mVarSet.end(); ++ p) {
Var* v = *p;
if ( v->mMark == 1 ) {
ans = and_op(ans, make_negaliteral(v->varid()));
}
else if ( v->mMark == 2 ) {
ans = and_op(ans, make_posiliteral(v->varid()));
}
}
return ans;
}
// Smallest Cube Containing F を求めるためのサブルーティン.
void
BddMgrClassic::scc_step(tBddEdge e,
tBddEdge s)
{
if ( check_one(e) ) {
while ( !check_one(s) ) {
assert_cond(!check_zero(s), __FILE__, __LINE__);
Node* svp = get_node(s);
Var* svar = svp->var();
svar->mMark |= 3;
s = svp->edge1();
}
return;
}
Node* vp = get_node(e);
if ( vp && !mark(e) ) {
setmark(e);
Var* var = vp->var();
Node* svp = get_node(s);
Var* svar = svp->var();
tBddEdge s2 = svp->edge1();
if ( svar->level() < var->level() ) {
svar->mMark |= 3;
scc_step(e, s2);
}
else {
tPol pol = get_pol(e);
tBddEdge e0 = vp->edge0(pol);
tBddEdge e1 = vp->edge1(pol);
if ( !var->mMark ) {
mVarSet.push_back(var);
}
if ( !check_zero(e0) ) {
var->mMark |= 1;
scc_step(e0, s2);
}
if ( !check_zero(e1) ) {
var->mMark |= 2;
scc_step(e1, s2);
}
}
}
}
// existential quntification(smoothing)
// svars に含まれる変数を消去する.
// メモリ不足のためにエラーとなる可能性がある.
tBddEdge
BddMgrClassic::esmooth(tBddEdge e1,
tBddEdge e2)
{
if ( check_error(e1) || check_error(e2) ) {
return kEdgeError;
}
if ( check_overflow(e1) || check_overflow(e2) ) {
return kEdgeOverflow;
}
clear_varmark();
mLastLevel = 0;
{
Node* vp = get_node(e2);
while ( vp != 0 ) {
Var* v = vp->var();
mLastLevel = v->level();
v->mMark = 1;
vp = get_node(vp->edge1());
}
}
tBddEdge ans = esmooth_step(e1);
mSmTable->clear();
clear_varmark();
return ans;
}
tBddEdge
BddMgrClassic::esmooth_step(tBddEdge e)
{
if ( check_leaf(e) ) {
return e;
}
Node* vp = get_node(e);
Var* var = vp->var();
tLevel level = var->level();
if ( level > mLastLevel ) {
return e;
}
tBddEdge result = mSmTable->get(e);
if ( result == kEdgeInvalid ) {
tPol pol = get_pol(e);
tBddEdge e0 = vp->edge0(pol);
tBddEdge e1 = vp->edge1(pol);
if ( var->mMark ) {
// 消去対象の変数だった.
tBddEdge tmp = or_op(e0, e1);
result = esmooth_step(tmp);
}
else {
tBddEdge r_0 = esmooth_step(e0);
tBddEdge r_1 = esmooth_step(e1);
result = new_node(var, r_0, r_1);
}
mSmTable->put(e, result);
}
return result;
}
// src1 と src2 との論理積を計算しつつスムージングを行う.
tBddEdge
BddMgrClassic::and_exist(tBddEdge e1,
tBddEdge e2,
tBddEdge e3)
{
if ( check_error(e1) || check_error(e2) || check_error(e3) ) {
return kEdgeError;
}
if ( check_overflow(e1) || check_overflow(e2) || check_overflow(e3) ) {
return kEdgeOverflow;
}
clear_varmark();
mLastLevel = 0;
{
Node* vp = get_node(e3);
while ( vp != 0 ) {
Var* v = vp->var();
mLastLevel = v->level();
v->mMark = 1;
vp = get_node(vp->edge1());
}
}
tBddEdge ans = andexist_step(e1, e2);
mSmTable->clear();
mAeTable->clear();
clear_varmark();
return ans;
}
tBddEdge
BddMgrClassic::andexist_step(tBddEdge f,
tBddEdge g)
{
if ( check_zero(f) || check_zero(g) ) {
return kEdge0;
}
if ( check_one(f) && check_one(g) ) {
return kEdge1;
}
if ( check_one(f) ) {
return esmooth_step(g);
}
if ( check_one(g) ) {
return esmooth_step(f);
}
if ( f > g ) {
tBddEdge tmp = f;
f = g;
g = tmp;
}
Node* f_vp = get_node(f);
Node* g_vp = get_node(g);
tPol f_pol = get_pol(f);
tPol g_pol = get_pol(g);
Var* f_var = f_vp->var();
Var* g_var = g_vp->var();
tLevel f_level = f_var->level();
tLevel g_level = g_var->level();
tLevel level = f_level;
Var* var = f_var;
if ( level > g_level ) {
level = g_level;
var = g_var;
}
if ( level > mLastLevel ) {
return and_op(f, g);
}
tBddEdge result = mAeTable->get(f, g);
if ( result == kEdgeInvalid ) {
tBddEdge f_0, f_1;
tBddEdge g_0, g_1;
if ( var->mMark ) {
if ( f_level > level ) {
g_0 = g_vp->edge0(g_pol);
g_1 = g_vp->edge1(g_pol);
tBddEdge tmp = or_op(g_0, g_1);
result = andexist_step(f, tmp);
}
else if ( g_level > level ) {
f_0 = f_vp->edge0(f_pol);
f_1 = f_vp->edge1(f_pol);
tBddEdge tmp = or_op(f_0, f_1);
result = andexist_step(tmp, g);
}
else {
f_0 = f_vp->edge0(f_pol);
f_1 = f_vp->edge1(f_pol);
g_0 = g_vp->edge0(g_pol);
g_1 = g_vp->edge1(g_pol);
tBddEdge tmp1 = andexist_step(f_0, g_0);
tBddEdge tmp2 = andexist_step(f_1, g_1);
result = or_op(tmp1, tmp2);
}
}
else {
f_0 = f_vp->edge0(f_pol);
f_1 = f_vp->edge1(f_pol);
g_0 = g_vp->edge0(g_pol);
g_1 = g_vp->edge1(g_pol);
tBddEdge r_0 = andexist_step(f_0, g_0);
tBddEdge r_1 = andexist_step(f_1, g_1);
result = new_node(var, r_0, r_1);
}
mAeTable->put(f, g, result);
}
return result;
}
END_NAMESPACE_YM_BDD
|
026abfd4db60ec5f28e4127a0b84c96b10b3737f | 04dc7cc05f9b33585228e649706dcb2fc1eb797b | /ASC Series/37/check.cpp | 875f08fa0c19ac1d65acdaaf4750e0c3f04fc6ff | [
"Apache-2.0"
] | permissive | henviso/contests | 4fc34cc86a42a3ff15e23e457a21bba10913f419 | aa8a5ce9ed4524e6c3130ee73af7640e5a86954c | refs/heads/master | 2016-09-14T19:14:29.266088 | 2016-05-12T00:02:59 | 2016-05-12T00:02:59 | 58,590,566 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,007 | cpp | check.cpp | #include <iostream>
#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
#include <cstring>
#include <bitset>
#include <cstring>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector< ii > vii;
///////////////////////////////UTIL/////////////////////////////////
#define ALL(x) (x).begin(),x.end()
#define CLEAR0(v) memset(v, 0, sizeof(v))
#define CLEAR(v, x) memset(v, x, sizeof(v))
#define COPY(a, b) memcpy(a, b, sizeof(a))
#define CMP(a, b) memcmp(a, b, sizeof(a))
#define REP(i,n) for(int i = 0; i<n; i++)
#define REPP(i,a,n) for(int i = a; i<n; i++)
#define REPD(i,n) for(int i = n-1; i>-1; i--)
#define REPDP(i,a,n) for(int i = n-1; i>=a; i--)
#define MOD 1000000007LL
#define PI 3.1415926535897932384626
#define MAX_PRIME 11111
int n;
int main(){
vi v;
bool problem = false;
int y = 2;
while(scanf(" %d", &n) != EOF){
v.clear();
int x;
scanf(" %d", &x); v.push_back(x);
while(cin.peek() != EOF && cin.peek() != '\n'){
scanf(" %d", &x); v.push_back(x);
}
bool pares[n+10][n+10];
CLEAR0(pares);
for(int i = 0; i<v.size(); i++){
int x = v[i], y = v[(i+1)%v.size()];
if(x == y){
cout << " COLORACAO NAO PROPRIA ENCONTRADA VERTICES ADJACENTES: " << x << " " << y << endl;
problem = true;
break;
}
pares[x][y] = pares[y][x] = true;
}
if(problem) break;
for(int i = 1; i<=n; i++)
for(int j = i+1; j<=n; j++){
if(!pares[i][j]){
cout << "COLORACAO NAO EH PROPRIA O PAR " << i << " " << j << " ESTA FALTANDO\n";
problem = true;
break;
}
}
if(problem) break;
if(v.size() != y+1){
problem = true;
cout << " NUMERO DE ARESTAS ERRADO DEVERIA SER " << x+1 << endl;
break;
}
y = v.size();
}
if(problem){
cout << "PROBLEMA NA COLORAÇÃO\n";
cout << "COLORACAO DE " << n << " CORES: ";
REP(i, v.size()) cout << v[i] << " ";
cout << endl;
}
}
|
9bf6d46b5c89d27383fee17228588251acde44be | 05a422c000ef347b7b649615d56b9f1f4a80f4eb | /CS 162/lab 9/lab9.cpp | b03e5ef5003c6e65082d51a1b9dc22fb1c9eb928 | [] | no_license | nguyminh/CS-162 | d531417a36dacf1a8e47e51b28f91d035a4dfae6 | 1efc987cc125741e3c778ce8c069abd93e5b9f29 | refs/heads/master | 2016-09-06T12:37:07.926614 | 2014-12-04T06:13:59 | 2014-12-04T06:13:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | cpp | lab9.cpp | //Minh Nguyen
//Lab 9
#include <iostream>
using namespace std;
struct node
{
int number;
node *next;
};
bool empty(node *head)
{
if (head == NULL)
return true;
else
return false;
}
void first(node *&head, node *&last, int number)
{
node *temp = new node;
temp->number = number;
temp->next = NULL;
head = temp;
last = temp;
}
void insert(node *&head, node *&last, int number)
{
if(empty(head))
first(head,last, number);
else
{
node *temp = new node;
temp->number = number;
temp->next = NULL;
last->next = temp;
last = temp;
}
}
void remove(node *&head, node *&last)
{
if(empty(head))
cout << "empty" << endl;
else if(head == last)
{
delete head;
head == NULL;
last == NULL;
}
else
{
node *temp = head;
head = head->next;
delete temp;
}
}
void print_out(node *print)
{
while (print != NULL)
{
cout << print->number << endl;
print = print->next;
}
}
int main()
{
int choice, run;
node *head = NULL;
node *last = NULL;
run = 1;
cout << "Enter number of suitors: ";
cin >> choice;
while (run >= 0)
{
if (run == 1)
first(head, last, run);
else
insert(head, last, run);
run++;
if (run > choice)
break;
}
for (int i = 1; i < choice; i++)
remove(head,last);
print_out(head);
return 0;
}
|
1c22acba9c86f40e0bd744dd34aaee7fe372f553 | 2cec0711443e8ac1ea92664ece86abe07ba457c5 | /proj2-UVA11351-ACS105111/proj2new-UVA11351-ACS105111.cpp | 0b337da81c6a4c9b50124c13851d55ff39149d5f | [] | no_license | YamatoAl/UVA_Practice | 877d5676095c10769e49edb6145e8250b66ad2ac | 34cc833e12eb14e9023d9e55c8dbd5bfec4ff636 | refs/heads/master | 2020-08-06T12:43:18.885175 | 2019-10-05T10:06:41 | 2019-10-05T10:06:41 | 212,978,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 373 | cpp | proj2new-UVA11351-ACS105111.cpp | //UVA11351 Last Man Standing
#include<iostream>
#include<vector>
using namespace std;
int main(){
long long int survivor,kill,CASE;
cin>>CASE;
for(int T=1;T<=CASE;T++){
cin>>survivor>>kill;
long long int count=0;
for(int i=2;i<=survivor;i++){
count=(count+kill)%i;
// cout<<count<<endl;
}
cout<<"Case "<<T<<": "<<count+1<<endl;
}
} |
9919bf8cd1667674a2b8b782d73d3c7842546c62 | dbaeafe6aec511edb2935eadec5b38880f2d209a | /environment.cpp | 399c28beeac0fe9792ef719d768199d584621b80 | [] | no_license | nelfin/mc-aixi-ctw | b6628ea6a3a467f8ba6bc367390687631574015c | 3c41cb12550b5076489ff27444465c3d639bdb90 | refs/heads/master | 2021-06-02T04:02:37.467530 | 2018-06-13T07:17:01 | 2018-06-13T07:17:01 | 5,774,994 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 25,655 | cpp | environment.cpp | #include "environment.hpp"
#include <cassert>
#include <fstream>
#include <iostream>
#include <string>
#include <stdlib.h>
#include "util.hpp"
#include "environment.hpp"
// Coin Flip
CoinFlip::CoinFlip(options_t &options) {
// Determine the probability of the coin landing on heads
p = 1.0;
if (options.count("coin-flip-p") > 0) {
strExtract(options["coin-flip-p"], p);
}
assert(0.0 <= p);
assert(p <= 1.0);
// Set up the initial observation
m_observation = rand01() < p ? 1 : 0;
m_reward = 0;
}
// Observes 1 (heads) with probability p and 0 (tails) with probability 1 - p.
// Observations are independent of the agent's actions. Gives a reward of 1 if
// the agent correctly predicts the next observation and 0 otherwise.
void CoinFlip::performAction(action_t action) {
m_observation = rand01() < p ? 1 : 0;
m_reward = action == m_observation ? 1 : 0;
}
/* Tiger:
actions
open left - 0
open right - 1
listen - 2
observation
tiger behind left - 0
tiger behind right - 1
no observation - 2
m_gold_door
0 - gold behind left
1 - gold behind right
*/
Tiger::Tiger(options_t &options) {
p = 1.0;
if (options.count("left-door-p") > 0) {
strExtract(options["left-door-p"], p);
}
assert(0.0 <= p);
assert(p <= 1.0);
m_listen_chance = 0.85;
if (options.count("listen-p") > 0) {
strExtract(options["listen-p"], m_listen_chance);
}
assert(0.0 <= m_listen_chance);
assert(m_listen_chance <= 1.0);
m_gold_door = rand01() < p ? 1 : 0;
m_signed_reward = 0;
m_observation = 2;
//behindLeftDoor = true;
}
void Tiger::performAction(action_t action) {
if (action == 2) { // Listen
m_signed_reward = -1;
if (rand01() < m_listen_chance) { //Hears the tiger behind the correct door.
m_observation = !m_gold_door;
} else { //Hears the tiger behind the incorrect door.
m_observation = m_gold_door;
}
} else {
if (action == m_gold_door) { // Chooses the door with the gold
m_signed_reward = 10;
} else {
m_signed_reward = -100;
}
m_observation = 2;
m_gold_door = rand01() < p ? 1 : 0;
}
}
// Grid World Environment
#define SIZE 4
#define DESTX 4
#define DESTY 4
#define GUP 0
#define GRIGHT 1
#define GDOWN 2
#define GLEFT 3
#define NOTHING 0
GridWorld::GridWorld(options_t &options) {
m_x = randRange(SIZE+1);
m_y = randRange(SIZE+1);
// Set up the initial observation
m_observation = 0;
m_reward = 0;
}
void GridWorld::performAction(action_t action) {
m_reward = 0;
m_observation = NOTHING;
if (m_x == DESTX && m_y == DESTY){
m_reward = 1;
m_x = randRange(SIZE+1);
m_y = randRange(SIZE+1);
}
//move player based on action
switch (action){
case GUP:
m_x++;
break;
case GRIGHT:
m_x++;
m_y++;
break;
case GDOWN:
m_y--;
break;
case GLEFT:
m_y--;
m_x--;
break;
default:
printf("Error: Unhandled action case");
}
//reset player back into field if they stray too far
if (m_x>SIZE){
m_x = SIZE;
} else if (m_x<0){
m_x = 0;
} else if (m_y>SIZE){
m_y = SIZE;
} else if (m_y<0){
m_y = 0;
}
logFile << "position: " << m_x << "," << m_y << std::endl;
}
//biased rock paper scissors Environment
//Keeps the m_reward value at zero and uses m_signed_reward instead
#define ROCK 0
#define SCISSORS 1
#define PAPER 2
RPS::RPS(options_t &options) {
// Set up the initial observation
m_observation = 0;
m_signed_reward = 0;
m_previous_rock_win = false;
}
void RPS::performAction(action_t action) {
//if previously won with a rock, play rock again
if(m_previous_rock_win){
m_observation = ROCK;
m_previous_rock_win = false;
}else{
m_observation = randRange(3);
}
if((action+1)%3 == m_observation){
m_signed_reward = 1;
logFile << "result: Agent won with " << action << " (reward " << m_signed_reward<< ")" << std::endl;
}else if (action == m_observation){
m_signed_reward = 0;
logFile << "result: Draw with " << action << " (reward " << m_signed_reward<< ")" << std::endl;
}else{
m_signed_reward = -1;
logFile << "result: Environment won with " << m_observation << " (reward " << m_signed_reward << ")" << std::endl;
if (m_observation == ROCK){
m_previous_rock_win = true;
}
}
}
/* Kuhn Poker environment:
actions
Pass: 0
Bet: 1
observation (Player Card, Opponent Action)
Player Card
Jack: 0
Queen: 1
King: 2
Opponent Action
Pass: 0
Bet: 1
reward: (Pot - Investment)
NOTE:
Add an alternate environment which includes as an observation the
outcome of the previous round (Opponent Reveal, Player Card, Opponent Action)
Opponent Reveal
Jack: 0
Queen: 1
King: 2
Fold: 3 (no showdown)
*/
#define JACK 0
#define QUEEN 1
#define KING 2
KuhnPoker::KuhnPoker(options_t &options) {
gamma = 0.5;
if (options.count("gamma") > 0) {
strExtract(options["gamma"], gamma);
}
alpha = gamma / 3.0;
beta = (1+gamma) / 3.0;
dealCards();
// Implement strategy for opponent (bet|pass given m_opponent_card)
m_opponent_action = getFirstNashAction();
assert(m_opponent_action >= 0);
m_observation = 2*m_player_card + m_opponent_action;
m_signed_reward = 0;
}
//Implement Nash strategy
int KuhnPoker::getFirstNashAction() {
switch(m_opponent_card){
case JACK:
return rand01() < alpha ? 1 : 0;
case QUEEN:
return 0;
case KING:
return rand01() < gamma ? 1 : 0;
default:
return -1;
}
}
int KuhnPoker::getSecondNashAction() {
switch(m_opponent_card){
case JACK:
return 0;
case QUEEN:
return rand01() < beta ? 1 : 0;
case KING:
return 1;
default:
return -1;
}
}
void KuhnPoker::dealCards() {
m_opponent_card = randRange(3); // Random number 0 = Jack, 1 = Queen, 2 = King
if (randRange(2) == 1){ // 50-50 chance of getting the either of the remaining cards
m_player_card = (m_opponent_card + 1) % 3;
} else {
m_player_card = (m_opponent_card + 2) % 3;
}
//std::cout << "Player has card "<< m_player_card <<std::endl;
}
void KuhnPoker::performAction(action_t action) {
// Initialise temporary variables
m_win_flag = false;
m_pot = 2;
m_investment = 1;
// Action is either bet (1) or pass (0)
if (m_opponent_action == 0){ // opponent passes
if (action == 0){ // player pass (investment = blind = 1)
// SHOWDOWN
m_win_flag = (m_player_card > m_opponent_card);
} else { // player bet (investment = 2)
m_pot++;
m_investment++;
// Opponent gets to bet
int opponent_second_action = getSecondNashAction();
assert(opponent_second_action >= 0);
if (opponent_second_action == 0) { // Opponent passes again
// Player wins - NO SHOWDOWN
m_win_flag = true;
} else { // Opponent bets
m_pot++;
// SHOWDOWN
m_win_flag = (m_player_card > m_opponent_card);
}
}
} else { // Opponent bets
m_pot++;
if (action == 0){ // player pass (investment = blind = 1)
// Opponent wins - NO SHOWDOWN
m_win_flag = false;
} else { // player bet
m_pot++;
m_investment++;
// SHOWDOWN
m_win_flag = (m_player_card > m_opponent_card);
}
}
// REWARD
if (m_win_flag){ // Player wins
m_signed_reward = m_pot - m_investment;
} else {
m_signed_reward = 0 - m_investment;
}
dealCards();
m_opponent_action = getFirstNashAction();
assert(m_opponent_action >= 0);
//std::cout << "Opponent chose action "<< m_opponent_action <<std::endl;
// OBSERVE
// Player Card = m_player_card
// Opponent Action = m_opponent_action
// m_observation = (m_player_card, m_opponent_action);
m_observation = 2*m_player_card + m_opponent_action; // Does this operation seem correct?
}
//Pacman environment
Pacman::Pacman(options_t &options) {
reset();
// Initial observation setup
m_observation = setObservation();
m_signed_reward = 0;
}
//Debug method to show the map
//Also fun
void Pacman::printMap(){
printf("\n");
for (int cury = 0; cury < dimy; cury++){
for (int curx = 0; curx < dimx; curx++){
switch (map[curx][cury]){
case WALL:
printf("\033[42m ");
break;
case EMPTY:
printf("\033[47m ");
break;
case FOOD:
printf("\033[46m ");
break;
case PACMAN:
if (power){
printf("\033[45m ");
} else {
printf("\033[43m ");
}
break;
case GHOST:
case PILLANDGHOST:
case FOODANDGHOST:
printf("\033[41m ");
break;
case PILL:
printf("\033[44m ");
break;
default:
printf("%d", map[curx][cury]);
}
}
printf("\033[0m\n");
}
}
void Pacman::reset(){
//Read map in from file
std::ifstream pacmap ("pacman.map");
std::string nextline;
getline(pacmap,nextline);
dimx = atoi(nextline.c_str());
getline(pacmap,nextline);
dimy = atoi(nextline.c_str());
getline(pacmap,nextline);
numghosts = atoi(nextline.c_str());
// Allocate and clear memory for map
map = new tile_t*[dimx];
for (int i = 0; i < dimx; i++){
map[i] = new tile_t[dimy];
}
// Allocate memory for ghosts
ghosts = new ghostinfo_t[numghosts];
//Read in map tiles
foodleft = 0;
powertime = 0;
int ghostcount = 0;
char curtile = 0;
for (int cury = 0; cury < dimy; cury++){
getline(pacmap,nextline);
for (int curx = 0; curx < dimx; curx++){
curtile = nextline[curx];
// Convert from char to tile_t
map[curx][cury] = (tile_t) (curtile - '0');
if (map[curx][cury] == EMPTY){
//50% chance to be food in empty square
if (randRange(2) == 1){
map[curx][cury] = FOOD;
foodleft++;
}
}
else if (map[curx][cury] == PACMAN){
pacman.x = curx;
pacman.y = cury;
}
else if (map[curx][cury] == GHOST){
//Initialise ghost information
ghosts[ghostcount].pos.x = curx;
ghosts[ghostcount].pos.y = cury;
ghosts[ghostcount].pursue = 0;
ghosts[ghostcount].cooldown = 0;
ghosts[ghostcount].alive = true;
ghostcount++;
}
}
}
//printMap();
//Other initial variables
power = false;
}
//walls
#define W_UP 0
#define W_RIGHT 1
#define W_DOWN 2
#define W_LEFT 3
//food line of sight
#define F_UP 4
#define F_RIGHT 5
#define F_DOWN 6
#define F_LEFT 7
//pill
#define POWERED 8
//smells
#define S_2 9
#define S_3 10
#define S_4 11
//ghost line of sight
#define G_UP 12
#define G_RIGHT 13
#define G_DOWN 14
#define G_LEFT 15
percept_t Pacman::setObservation(){
short observation = 0;
//walls
observation = observation | ((validSquare(makeMove(pacman,UP)) ? 1 : 0) << W_UP);
observation = observation | ((validSquare(makeMove(pacman,RIGHT)) ? 1 : 0) << W_RIGHT);
observation = observation | ((validSquare(makeMove(pacman,DOWN)) ? 1 : 0) << W_DOWN);
observation = observation | ((validSquare(makeMove(pacman,LEFT)) ? 1 : 0) << W_LEFT);
//food line of sight
observation = observation | ((lineOfSight(pacman,UP,FOOD) ? 1 : 0) << W_UP);
observation = observation | ((lineOfSight(pacman,RIGHT,FOOD) ? 1 : 0) << W_RIGHT);
observation = observation | ((lineOfSight(pacman,DOWN,FOOD) ? 1 : 0) << W_DOWN);
observation = observation | ((lineOfSight(pacman,LEFT,FOOD) ? 1 : 0) << W_LEFT);
//pill
observation = observation | ((power ? 1 : 0) << POWERED);
//smells (for distances 2,3,4)
if (manhattanSearch(pacman,NONE,NONE, 2, FOOD)){
//push up binary 111
observation = observation | (5 << S_2);
} else if (manhattanSearch(pacman,NONE,NONE, 3, FOOD)){
//push up binary 11
observation = observation | (3 << S_3);
} else if (manhattanSearch(pacman,NONE,NONE, 4, FOOD)){
//push up binary 1
observation = observation | (1 << S_4);
}
//ghost line of sight
observation = observation | ((lineOfSight(pacman,UP,GHOST) ? 1 : 0) << G_UP);
observation = observation | ((lineOfSight(pacman,RIGHT,GHOST) ? 1 : 0) << G_RIGHT);
observation = observation | ((lineOfSight(pacman,DOWN,GHOST) ? 1 : 0) << G_DOWN);
observation = observation | ((lineOfSight(pacman,LEFT,GHOST) ? 1 : 0) << G_LEFT);
return (percept_t) observation;
}
Pacman::direction_t Pacman::manhattanSearch(coord_t curcoord, direction_t camefrom, direction_t wentto, int dist, tile_t seeking){
//check if found it
if (testSquare(curcoord,seeking)){
return wentto;
}
//check if max depth
if (dist == 0){
return NONE;
}
direction_t searchresult;
//Check each direction, if there is a move which sees the target, return it
if (validSquare(makeMove(curcoord, UP)) && (camefrom != UP)){
searchresult = manhattanSearch(makeMove(curcoord, UP), DOWN, UP, dist-1, seeking);
if (searchresult != NONE){
return UP;
}
}
if (validSquare(makeMove(curcoord, RIGHT)) && camefrom != RIGHT){
searchresult = manhattanSearch(makeMove(curcoord, RIGHT), LEFT, RIGHT, dist-1, seeking);
if (searchresult != NONE){
return RIGHT;
}
}
if (validSquare(makeMove(curcoord, DOWN)) && camefrom != DOWN){
searchresult = manhattanSearch(makeMove(curcoord, DOWN), UP, DOWN, dist-1, seeking);
if (searchresult != NONE){
return DOWN;
}
}
if (validSquare(makeMove(curcoord, LEFT)) && camefrom != LEFT){
searchresult = manhattanSearch(makeMove(curcoord, LEFT), RIGHT, LEFT, dist-1, seeking);
if (searchresult != NONE){
return LEFT;
}
}
return NONE;
}
bool Pacman::lineOfSight(coord_t curcoord, direction_t direction, tile_t seeking){
coord_t sightcoord;
sightcoord.x = curcoord.x;
sightcoord.y = curcoord.y;
//Keep moving in direction until we see what we're after or hit a wall
sightcoord = makeMove(sightcoord,direction);
while (validSquare(sightcoord)){
if (testSquare(sightcoord, seeking))
return true;
sightcoord = makeMove(sightcoord,direction);
}
return false;
}
Pacman::coord_t Pacman::makeMove(coord_t coord, direction_t move){
coord_t result;
//Move and return coord
switch (move){
case UP:
result.x = coord.x;
result.y = coord.y-1;
break;
case RIGHT:
result.x = coord.x+1;
result.y = coord.y;
break;
case DOWN:
result.x = coord.x;
result.y = coord.y+1;
break;
case LEFT:
result.x = coord.x-1;
result.y = coord.y;
break;
default:
printf("Error: makeMove unhandled case");
assert(false);
}
//Modulus wraps numbers which are too large
result.x = result.x % dimx;
//Add dimension to disallow negative numbers
//(Modulus does not always take care of this in C)
if (result.x < 0)
result.x = result.x + dimx;
result.y = result.y % dimy;
if (result.y < 0)
result.y = result.y + dimy;
return result;
}
//Valid/walkable square if not wall
bool Pacman::validSquare(coord_t coord){
return map[coord.x][coord.y] != WALL;
}
//Test if square contains the object sought
bool Pacman::testSquare(coord_t coord, tile_t seeking){
switch(seeking){
case(FOOD):
return (map[coord.x][coord.y] == FOOD || map[coord.x][coord.y] == FOODANDGHOST);
case(GHOST):
return (map[coord.x][coord.y] == GHOST || map[coord.x][coord.y] == FOODANDGHOST
|| map[coord.x][coord.y] == PILLANDGHOST);
case(PILL):
return (map[coord.x][coord.y] == PILL || map[coord.x][coord.y] == PILLANDGHOST);
case(PACMAN):
return (map[coord.x][coord.y] == PACMAN);
default:
return (map[coord.x][coord.y] == seeking);
}
}
//Reward constants
#define COMPLETE 100
#define FOODREWARD 10
#define GHOSTEATREWARD 30
#define MOVEREWARD -1
#define WALLREWARD -10
#define GHOSTREWARD -50
//Behavioural constants
#define SHORT_DURATION 10
#define COOLDOWN 10
#define AGRESSIVEDIST 5
#define PILLDURATION 40
void Pacman::performAction(action_t action) {
direction_t newaction = (direction_t) action;
m_signed_reward = 0;
//Make pacman's move
coord_t newsquare = makeMove(pacman,newaction);
if (!(validSquare(newsquare))){
m_signed_reward += WALLREWARD;
} else {
//Perform the move
m_signed_reward += MOVEREWARD;
map[pacman.x][pacman.y] = EMPTY;
pacman.x = newsquare.x;
pacman.y = newsquare.y;
//Check landing square
//Running into a ghost
if(testSquare(newsquare, GHOST)){
if (power){
//Pacman kills ghost
for (int i = 0; i < numghosts; i++){
if (ghosts[i].alive && ghosts[i].pos.x == pacman.x && ghosts[i].pos.y == pacman.y){
ghosts[i].alive = false;
m_signed_reward += GHOSTEATREWARD;
}
}
} else {
//Ghost kills pacman
m_signed_reward += GHOSTREWARD;
reset();
return;
}
}
//Eating food
if(testSquare(newsquare, FOOD)){
m_signed_reward += FOODREWARD;
foodleft--;
if (foodleft == 0){
//Eaten everything, gameover
m_signed_reward += COMPLETE;
reset();
return;
}
//Eating power pill
} else if(testSquare(newsquare, PILL)){
power = true;
powertime = PILLDURATION;
}
map[pacman.x][pacman.y] = PACMAN;
}
//Make ghost moves
for (int i = 0; i < numghosts; i++){
if (ghosts[i].alive){
direction_t ghostmove = NONE;
//If not on cooldown
if (ghosts[i].cooldown == 0){
//Search for pacman
//Ghostmove will become NONE or a move towards pacman
ghostmove = manhattanSearch(ghosts[i].pos, NONE, NONE, AGRESSIVEDIST, PACMAN);
//Manage pursuit time and cooldown
if (ghosts[i].pursue > 0){
ghosts[i].pursue--;
if (ghosts[i].pursue == 0){
ghosts[i].cooldown = COOLDOWN;
}
} else if (ghostmove != NONE){
ghosts[i].pursue = SHORT_DURATION;
}
} else ghosts[i].cooldown--;
//If can't smell pacman
if (ghostmove == NONE){
//Make a random move
ghostmove = randomMove(ghosts[i].pos);
}
//Advance position
coord_t newcoord = makeMove(ghosts[i].pos, ghostmove);
//Check if ghost lands on pacman
if (newcoord.x == pacman.x && newcoord.y == pacman.y){
if (power){
//Pacman kills ghost
ghosts[i].alive = false;
} else {
//Pacman dies
m_signed_reward += GHOSTREWARD;
reset();
return;
}
}
//Perform move
ghostMove(ghosts[i].pos, newcoord);
//Update ghost info
ghosts[i].pos.x = newcoord.x;
ghosts[i].pos.y = newcoord.y;
}
}
//End of action power ticks
if (power){
powertime--;
if (powertime == 0)
power = false;
}
//printMap();
m_observation = setObservation();
}
Pacman::direction_t Pacman::randomMove(coord_t coord){
direction_t possiblemoves[4];
int nummoves = 0;
//Add all valid directions to an array
if (validSquare(makeMove(coord,UP))){
possiblemoves[nummoves] = UP;
nummoves++;
}
if (validSquare(makeMove(coord,RIGHT))){
possiblemoves[nummoves] = RIGHT;
nummoves++;
}
if (validSquare(makeMove(coord,DOWN))){
possiblemoves[nummoves] = DOWN;
nummoves++;
}
if (validSquare(makeMove(coord,LEFT))){
possiblemoves[nummoves] = LEFT;
nummoves++;
}
//Returns a random filled element of the array
return possiblemoves[randRange(nummoves)];
}
void Pacman::ghostMove(coord_t from, coord_t to){
switch(map[from.x][from.y]){
case GHOST:
map[from.x][from.y] = EMPTY;
break;
case PILLANDGHOST:
map[from.x][from.y] = PILL;
break;
case FOODANDGHOST:
map[from.x][from.y] = FOOD;
break;
case WALL:
printf("Error: Trying to move ghost out of square where there is a wall!\n");
printf("%d, %d has a %d\n", from.x, from.y, map[from.x][from.y]);
case EMPTY:
default:
//unlikely but possible that two ghosts occupied the same square
//do nothing
break;
}
switch(map[to.x][to.y]){
case PILL:
map[to.x][to.y] = PILLANDGHOST;
break;
case FOOD:
map[to.x][to.y] = FOODANDGHOST;
break;
case FOODANDGHOST:
map[to.x][to.y] = FOODANDGHOST;
break;
case PILLANDGHOST:
map[to.x][to.y] = PILLANDGHOST;
break;
case PACMAN:
//if we reach this spot, this ghost must be dead (otherwise the game would've ended)
break;
case WALL:
printf("Error: Ghost trying to move into a wall!\n");
printf("%d, %d has a %d\n", to.x, to.y, map[to.x][to.y]);
default:
map[to.x][to.y] = GHOST;
}
}
/*
Composite Environments
*/
// Generic Composite Constructor
Composite::Composite(options_t &options) {
m_minimum_reward = 0; // default
// Extract environment sequence and changeover times
int i;
for (i = 0; options.count(environmentCode(i)) > 0 && options.count(startCode(i)) > 0; i++){
strExtract(options[environmentCode(i)], m_environment[i]);
strExtract(options[startCode(i)], m_start[i]);
if (m_environment[i] == 2) {
m_minimum_reward = -100;
}
}
m_last_environment = i - 1;
// The options must be stored for use in dynamically initialising the second environment
m_options = options;
// Initialise the first environment
m_current_environment = 0;
initialise(m_options, m_environment[m_current_environment]);
// Initialise the current cycle number - for calculating changeover
m_current_cycle = 1;
}
// These two functions should use integer to string conversion instead
// but C++ is bogus
// The arrays are defined statically too, so whatever
std::string Composite::environmentCode(int i){
switch(i){
case 0:
return "environment1";
break;
case 1:
return "environment2";
break;
case 2:
return "environment3";
break;
case 3:
return "environment4";
break;
case 4:
return "environment5";
break;
case 5:
return "environment6";
break;
case 6:
return "environment7";
break;
case 7:
return "environment8";
break;
case 8:
return "environment9";
break;
case 9:
return "environment10";
break;
default:
return "do_not_use_this_option";
break;
}
}
std::string Composite::startCode(int i){
switch(i){
case 0:
return "start1";
break;
case 1:
return "start2";
break;
case 2:
return "start3";
break;
case 3:
return "start4";
break;
case 4:
return "start5";
break;
case 5:
return "start6";
break;
case 6:
return "start7";
break;
case 7:
return "start8";
break;
case 8:
return "start9";
break;
case 9:
return "start10";
break;
default:
return "do_not_use_this_option";
break;
}
}
// Generic Composite Action Resolution
void Composite::performAction(action_t action){
// Resolve action for first environment
resolveAction(action, m_environment[m_current_environment]);
// Check for changeover in next cycle
if (m_current_environment != m_last_environment) { // Cannot change if on the last environment
m_current_cycle++; // Keep track of the current cycle until the last environment starts
if (m_current_cycle == m_start[m_current_environment + 1]){ // If the next environment should start next cycle
// Initialise the next environment
m_current_environment++;
initialise(m_options, m_environment[m_current_environment]);
}
}
}
// Generic initialiser
void Composite::initialise(options_t &options, int environment){
switch(environment){
case 0:
// Initialise coinflip1
// Determine the probability of the coin landing on heads
p = 1.0;
if (options.count("coin-flip-p") > 0) {
strExtract(options["coin-flip-p"], p);
}
assert(0.0 <= p);
assert(p <= 1.0);
std::cout << "Initialisation Coinflip p = " << p <<std::endl;
// Set up the initial observation
m_observation = rand01() < p ? 1 : 0;
m_signed_reward = 0;
break;
case 1:
// Initialise coinflip2
// Determine the probability of the coin landing on heads
p = 1.0;
if (options.count("coin-flip-p2") > 0) {
strExtract(options["coin-flip-p2"], p);
}
assert(0.0 <= p);
assert(p <= 1.0);
std::cout << "Initialisation Coinflip p = " << p <<std::endl;
// Set up the initial observation
m_observation = rand01() < p ? 1 : 0;
m_signed_reward = 0;
break;
case 2:
// Initialise Environment 2: Tiger
p = 1.0;
if (options.count("left-door-p") > 0) {
strExtract(options["left-door-p"], p);
}
assert(0.0 <= p);
assert(p <= 1.0);
std::cout << "Initialisation Tiger, p = " << p <<std::endl;
m_listen_chance = 0.85;
if (options.count("listen-p") > 0) {
strExtract(options["listen-p"], m_listen_chance);
}
assert(0.0 <= m_listen_chance);
assert(m_listen_chance <= 1.0);
std::cout << "Initialisation Tiger, listen = " << p <<std::endl;
m_gold_door = rand01() < p ? 1 : 0;
m_signed_reward = 0;
m_observation = 2;
break;
case 3:
// Initialise Environment 3
break;
case 4:
// Initialise Environment 4
break;
default:
// Initialise coinflip1 by default
// Determine the probability of the coin landing on heads
p = 1.0;
if (options.count("coin-flip-p") > 0) {
strExtract(options["coin-flip-p"], p);
}
assert(0.0 <= p);
assert(p <= 1.0);
// Set up the initial observation
m_observation = rand01() < p ? 1 : 0;
m_signed_reward = 0;
break;
}
}
void Composite::resolveAction(action_t action, int environment){
switch(environment){
case 0:
// Resolve action for coinflip1
m_observation = rand01() < p ? 1 : 0;
m_signed_reward = action == m_observation ? 1 : 0;
if (action >= 2) {
m_signed_reward = m_minimum_reward;
}
break;
case 1:
// Resolve action for coinflip2
m_observation = rand01() < p ? 1 : 0;
m_signed_reward = action == m_observation ? 1 : 0;
break;
case 2:
// Resolve action for Environment 2: Tiger
if (action == 2) { // Listen
m_signed_reward = -1;
if (rand01() < m_listen_chance) { //Hears the tiger behind the correct door.
m_observation = !m_gold_door;
} else { //Hears the tiger behind the incorrect door.
m_observation = m_gold_door;
}
} else {
if (action == m_gold_door) { // Chooses the door with the gold
m_signed_reward = 10;
} else {
m_signed_reward = -100;
}
// Reselect the door for next trial
m_observation = 2;
m_gold_door = rand01() < p ? 1 : 0;
}
break;
case 3:
// Resolve action for Environment 3
break;
case 4:
// Resolve action for Environment 4
break;
default:
// Resolve action for coinflip by default
m_observation = rand01() < p ? 1 : 0;
m_signed_reward = action == m_observation ? 1 : 0;
break;
}
} |
e60a94c53d98f694540694364b65845718f5c5e4 | 4b69e936449960ff2563f2ac843e73a858963ee8 | /src/event/EventManager.cpp | 07df5bac96273d42fe37e8fedcd375541587d7e5 | [] | no_license | noobtwk/SimpleEngine | c24bba7bc1d5b2ab9690609e9d8769a229d31c9b | 17f44982366edf93ebd2eb61397c0c26a7d758c1 | refs/heads/master | 2020-12-25T14:23:48.493499 | 2016-10-14T15:45:41 | 2016-10-14T15:45:41 | 67,853,925 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,657 | cpp | EventManager.cpp | #include "EventManager.h"
#include"SceneManager.h"
EventManager * EventManager::instance = nullptr;
EventManager::EventManager()
{
}
EventManager * EventManager::share()
{
if (!instance)
{
instance = new EventManager();
}
return instance;
}
void EventManager::addListener(EventListener * l)
{
eventList.push_back(l);
sortFixedListener();
}
void EventManager::addNodeListener(Node * node, EventListener * l)
{
auto res = nodeListMap.find(node);
if (res != nodeListMap.end())
return;
nodeListMap[node] = l;
l->setLinkNode(node);
}
void EventManager::handleOnkeyPress(int keycode)
{
info i;
i.type = KEY_PRESS;
i.keycode = keycode;
eventDeque.push_back(i);
}
void EventManager::handleOnkeyRelease(int keycode)
{
info i;
i.keycode = keycode;
i.type = KEY_RELEASE;
eventDeque.push_back(i);
}
void EventManager::handleOnMousePress(int bottom, vec2 pos)
{
info i;
i.pos = pos;
i.type = MOUSE_PRESS;
i.button = bottom;
eventDeque.push_back(i);
}
void EventManager::handleOnMouseMove(vec2 pos)
{
info i;
i.type = MOUSE_MOVE;
i.pos = pos;
eventDeque.push_back(i);
}
void EventManager::handleOnMouseRelease(int bottom, vec2 pos)
{
info i;
i.pos = pos;
i.button = bottom;
i.type = MOUSE_RELEASE;
eventDeque.push_back(i);
}
void EventManager::handleOnScroll(int x, int y)
{
info i;
i.type = SCROLL;
i.y = y;
eventDeque.push_back(i);
}
void EventManager::handleOnCharInput(unsigned int c)
{
info i;
i.c = c;
i.type = CHAR_INPUT;
eventDeque.push_back(i);
}
void EventManager::use()
{
sortNodeListener();
while (!eventDeque.empty())
{
auto i = eventDeque.front();
switch (i.type)
{
case KEY_PRESS:
useKeyPress(i.keycode);
break;
case KEY_RELEASE:
useKeyRelease(i.keycode);
break;
case MOUSE_PRESS:
useMousePress(i.button, i.pos);
break;
case MOUSE_RELEASE:
useMouseRelease(i.button, i.pos);
break;
case MOUSE_MOVE:
useMouseMove(i.pos);
break;
case SCROLL:
useScroll(i.y);
break;
case CHAR_INPUT:
useCharInput(i.c);
break;
default:
break;
}
eventDeque.pop_front();
}
}
bool EventManager::sortByPiority(EventListener * a, EventListener * b)
{
return a->getFixedPiority() >=b->getFixedPiority();
}
void EventManager::sortFixedListener()
{
std::stable_sort(eventList.begin(), eventList.end(), sortByPiority);
}
bool EventManager::sortByNodePiority(EventListener * a, EventListener * b)
{
auto na = a->getLinkNode();
auto nb = b->getLinkNode();
return na->getGlobalPriority()>nb->getGlobalPriority();
}
void EventManager::sortNodeListener()
{
auto root = SceneManager::share()->getCurScene()->getRoot();
nodeListener.clear();
visit(root);
std::stable_sort(nodeListener.begin(), nodeListener.end(), sortByNodePiority);
}
void EventManager::visit(Node * n)
{
if (!n->getIsDrawable())
{
return;
}
if (nodeListMap.find(n) != nodeListMap.end())
{
nodeListener.push_front(nodeListMap[n]);
}
if (n->getChildAmount() != 0)
{
for (int i = 0; i < n->getChildAmount(); ++i)
{
auto node = n->getChildByIndex(i);
visit(node);
}
}
}
void EventManager::useKeyPress(int keycode)
{
for (auto i : eventList)
{
if (i->onkeyPress(keycode) && i->isSwallow()) break;
}
for (auto i : nodeListener)
{
if (i->onkeyPress(keycode) && i->isSwallow())break;
}
}
void EventManager::useKeyRelease(int keycode)
{
for (auto i : eventList)
{
if (i->onkeyRelease(keycode) && i->isSwallow()) break;
}
for (auto i : nodeListener)
{
if (i->onkeyRelease(keycode) && i->isSwallow()) break;
}
}
void EventManager::useMousePress(int button, vec2 p)
{
for (auto i : eventList)
{
if (i->onMousePress(button, p) && i->isSwallow()) break;
}
for (auto i : nodeListener)
{
if (i->onMousePress(button, p) && i->isSwallow()) break;
}
}
void EventManager::useMouseRelease(int button, vec2 p)
{
for (auto i : eventList)
{
if (i->onMouseRelease(button, p) && i->isSwallow()) break;
}
for (auto i : nodeListener)
{
if (i->onMouseRelease(button, p) && i->isSwallow()) break;
}
}
void EventManager::useMouseMove(vec2 p)
{
for (auto i : eventList)
{
if (i->onMouseMove(p) && i->isSwallow()) break;
}
for (auto i : nodeListener)
{
if (i->onMouseMove(p) && i->isSwallow()) break;
}
}
void EventManager::useScroll(int y)
{
for (auto i : eventList)
{
if (i->onScroll(0, y) && i->isSwallow()) break;
}
for (auto i : nodeListener)
{
if (i->onScroll(0, y) && i->isSwallow()) break;
}
}
void EventManager::useCharInput(unsigned int c)
{
for (auto i : eventList)
{
if (i->onCharInput(c) && i->isSwallow()) break;
}
for (auto i : nodeListener)
{
if (i->onCharInput(c) && i->isSwallow()) break;
}
}
|
210771704e5f97dc173f6858a1837b559e133cb3 | 4bdc55169bd0949dc89cff2d008a9bc18b52635b | /animation/AnimLayer.h | bab81eeecb13808af6548f1bec3ffb7f4c0ebe99 | [] | no_license | yazici/animation_system | fcfceaed9daabd1d17ebbde986a639ee7894cde4 | 9f9512f9c5532f8c0671019d986341c4aa2099cc | refs/heads/master | 2020-04-29T14:50:29.909880 | 2013-05-05T14:12:05 | 2013-05-05T14:12:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,345 | h | AnimLayer.h | #pragma once
#include "engine/animation/AnimationClip.h"
#include "engine/animation/AnimBlendTree.h"
//---------------------------------------------------------------------------------------
namespace Engine{
//---------------------------------------------------------------------------------------
class AnimStates;
//---------------------------------------------------------------------------------------
// enumerates type of animation layer.
// defines how a layer pose gets blended with previously generated pose.
namespace LayerType{
enum Enum{
Additive,
Lerp
};
}
// enumerates type of cross fade.
// deines how blend factor changes during animation cross fade.
namespace BlendType{
enum Enum{
None = -1,
Linear,
EaseIn, //todo: support
EaseOut //todo: support
};
}
//---------------------------------------------------------------------------------------
class AnimLayer
{
public:
AnimLayer();
~AnimLayer();
// looks for named state in state data and transitions with specified blend time.
bool Play( StringId state_name, float blend_ms );
// looks for named transition in state data and transitions to specified blend tree.
bool Transition( StringId transition_name );
inline void Pause() { m_paused = true; }
inline void Resume() { m_paused = false; }
void Stop();
inline bool Active() { return m_current_tree.IsValid(); }
bool Paused() const { return m_paused; }
bool GetJointPose( u32 joint_idx, AnimationClip::JointPose& pose );
void Update( float fDeltaMs );
inline LayerType::Enum GetType() const { return m_type; }
inline void SetType( LayerType::Enum t ) { m_type = t; }
bool SetNodeFactor( StringId name, float value );
bool GetNodeFactor( StringId name, float& value ) const;
inline float GetBlendFactor() const { return m_blend_factor; }
inline void SetBlendFactor( float f ) { m_blend_factor = f; }
void SetStateData( AnimStates* data );
private:
bool Play( const AnimBlendTree& tree, float blend_ms, float start_time_ms );
private:
// layer state and transition data.
AnimStates* m_state_data;
// current state played.
StringId m_current_state;
// layer timer.
float m_global_clock;
// layer animation pause state.
bool m_paused;
// root node of animation blend tree.
AnimBlendTree m_current_tree;
// used while cross-blending.
AnimBlendTree m_previous_tree;
private:
// type of layer, used while blending layers.
LayerType::Enum m_type;
// layer blend factor (used when blending between layers occur).
float m_blend_factor;
private:
// duration of tree cross fading.
float m_crossfade_duration;
// crossfade timer.
float m_crossfade_timer;
// type of current crossfade.
BlendType::Enum m_crossfade_type;
};
//---------------------------------------------------------------------------------------
} // namespace Engine
//--------------------------------------------------------------------------------------- |
5e28bca9385c6ff0b74521bd1ed10d543c578dec | 86df6f8f4f3c03cccc96459ad82bcdf3bf942492 | /misc/google/shuffle.cc | a7f3c14fb897893db0fa4c7ba18c22b4c213b4d9 | [] | no_license | bdliyq/algorithm | 369d1fd2ae3925a559ebae3fa8f5deab233daab1 | e1c993a5d1531e1fb10cd3c8d686f533c9a5cbc8 | refs/heads/master | 2016-08-11T21:49:31.259393 | 2016-04-05T11:10:30 | 2016-04-05T11:10:30 | 44,576,582 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 418 | cc | shuffle.cc | // Question: 写一个shuffle算法,使得A[0]<=A[1]>=A[2]<=A[3]...
#include "headers.h"
void solve(vector<int>& nums) {
sort(nums.begin(), nums.end());
for (int i = 2; i < nums.size(); i += 2) {
swap(nums[i-1], nums[i]);
}
}
int main(int argc, char** argv) {
vector<int> nums{1,2,3,4,5,6,7,8,9};
solve(nums);
for (auto n : nums) {
cout << n << " ";
}
return 0;
}
|
5de4c2b92f04bf4d1c44a891e2d12c094724a0ac | 75d75b18c96ec0212974728fd7041bce568965b2 | /practice/ctag/src/main.cc | eba7d1bb5c373ce262d8a59bfb4131872b276c8f | [] | no_license | ohsolution/week4 | 1b03ec1cd662ed68c6736a6770e526124eace3ca | 6284bd1adb303b88dde4764088191d7d77702ead | refs/heads/master | 2023-08-10T23:29:31.142216 | 2021-09-20T08:29:21 | 2021-09-20T08:29:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 743 | cc | main.cc | //main.cc
#include <iostream>
#include "addr_decoder.h"
#include <string>
#define STUDENT_ID "2021312034"
using namespace std;
int main (int argc, char *argv[]) {
//Argument Check
if (argc != 2) {
cout << "Argument Error!" << endl;
cout << "./addr_decoder [address]" << endl;
cout << "Exit The Program!" << endl;
return 1;
}
ADDR input_addr = stoull(argv[1]);
ADDR_INFO decode_result = get_addr_info(input_addr);
ADDR restore_addr = get_addr(decode_result);
cout << "My Student ID is " << STUDENT_ID << endl;
cout << "Input Address : " << input_addr << endl;
print_addr_info(decode_result);
cout << "Restore Address : " << restore_addr << endl;
return 0;
}
|
1297ffb68a508847676f5a27bf0566765bdc91a0 | de7e771699065ec21a340ada1060a3cf0bec3091 | /replicator/src/test/org/apache/lucene/replicator/nrt/TestNRTReplication.cpp | 1f0c4b3b654bc7d84b568fe6805a11aed62e1b8f | [] | no_license | sraihan73/Lucene- | 0d7290bacba05c33b8d5762e0a2a30c1ec8cf110 | 1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3 | refs/heads/master | 2020-03-31T07:23:46.505891 | 2018-12-08T14:57:54 | 2018-12-08T14:57:54 | 152,020,180 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,719 | cpp | TestNRTReplication.cpp | using namespace std;
#include "TestNRTReplication.h"
namespace org::apache::lucene::replicator::nrt
{
using Document = org::apache::lucene::document::Document;
using IndexWriter = org::apache::lucene::index::IndexWriter;
using FSDirectory = org::apache::lucene::store::FSDirectory;
using LockObtainFailedException =
org::apache::lucene::store::LockObtainFailedException;
using IOUtils = org::apache::lucene::util::IOUtils;
using LineFileDocs = org::apache::lucene::util::LineFileDocs;
using org::apache::lucene::util::LuceneTestCase::SuppressCodecs;
using org::apache::lucene::util::LuceneTestCase::SuppressSysoutChecks;
using LuceneTestCase = org::apache::lucene::util::LuceneTestCase;
using org::apache::lucene::util::SuppressForbidden;
using TestUtil = org::apache::lucene::util::TestUtil;
using com::carrotsearch::randomizedtesting::SeedUtils;
// C++ TODO: Most Java annotations will not have direct C++ equivalents:
// ORIGINAL LINE: @SuppressForbidden(reason = "ProcessBuilder requires
// java.io.File for CWD") private NodeProcess startNode(int primaryTCPPort, final
// int id, java.nio.file.Path indexPath, long forcePrimaryVersion, bool
// willCrash) throws java.io.IOException
shared_ptr<NodeProcess> TestNRTReplication::startNode(
int primaryTCPPort, int const id, shared_ptr<Path> indexPath,
int64_t forcePrimaryVersion, bool willCrash)
{
deque<wstring> cmd = deque<wstring>();
cmd.push_back(System::getProperty(L"java.home") +
System::getProperty(L"file.separator") + L"bin" +
System::getProperty(L"file.separator") + L"java");
cmd.push_back(L"-Xmx512m");
int64_t myPrimaryGen;
if (primaryTCPPort != -1) {
// I am a replica
cmd.push_back(L"-Dtests.nrtreplication.primaryTCPPort=" +
to_wstring(primaryTCPPort));
myPrimaryGen = lastPrimaryGen;
} else {
myPrimaryGen = nextPrimaryGen++;
lastPrimaryGen = myPrimaryGen;
}
cmd.push_back(L"-Dtests.nrtreplication.primaryGen=" +
to_wstring(myPrimaryGen));
cmd.push_back(L"-Dtests.nrtreplication.closeorcrash=false");
cmd.push_back(L"-Dtests.nrtreplication.node=true");
cmd.push_back(L"-Dtests.nrtreplication.nodeid=" + to_wstring(id));
cmd.push_back(L"-Dtests.nrtreplication.startNS=" +
to_wstring(Node::globalStartNS));
cmd.push_back(L"-Dtests.nrtreplication.indexpath=" + indexPath);
cmd.push_back(L"-Dtests.nrtreplication.checkonclose=true");
if (primaryTCPPort == -1) {
// We are the primary node
cmd.push_back(L"-Dtests.nrtreplication.isPrimary=true");
cmd.push_back(L"-Dtests.nrtreplication.forcePrimaryVersion=" +
to_wstring(forcePrimaryVersion));
}
// Mixin our own counter because this is called from a fresh thread which
// means the seed otherwise isn't changing each time we spawn a new node:
int64_t seed = random()->nextLong() * nodeStartCounter->incrementAndGet();
cmd.push_back(L"-Dtests.seed=" + SeedUtils::formatSeed(seed));
cmd.push_back(L"-ea");
cmd.push_back(L"-cp");
cmd.push_back(System::getProperty(L"java.class.path"));
cmd.push_back(L"org.junit.runner.JUnitCore");
cmd.push_back(
getClassName()->replace(getClass().getSimpleName(), L"SimpleServer"));
message(L"child process command: " + cmd);
shared_ptr<ProcessBuilder> pb = make_shared<ProcessBuilder>(cmd);
pb->redirectErrorStream(true);
// Important, so that the scary looking hs_err_<pid>.log appear under our test
// temp dir:
pb->directory(childTempDir->toFile());
shared_ptr<Process> p = pb->start();
shared_ptr<BufferedReader> r;
try {
r = make_shared<BufferedReader>(
make_shared<InputStreamReader>(p->getInputStream(), IOUtils::UTF_8));
} catch (const UnsupportedEncodingException &uee) {
throw runtime_error(uee);
}
int tcpPort = -1;
int64_t initCommitVersion = -1;
int64_t initInfosVersion = -1;
shared_ptr<Pattern> logTimeStart = Pattern::compile(L"^[0-9\\.]+s .*");
bool sawExistingSegmentsFile = false;
while (true) {
wstring l = r->readLine();
if (l == L"") {
message(L"top: node=" + to_wstring(id) + L" failed to start");
try {
p->waitFor();
} catch (const InterruptedException &ie) {
throw runtime_error(ie);
}
message(L"exit value=" + p->exitValue());
message(L"top: now fail test replica R" + to_wstring(id) +
L" failed to start");
throw runtime_error(L"replica R" + to_wstring(id) + L" failed to start");
}
if (logTimeStart->matcher(l).matches()) {
// Already a well-formed log output:
wcout << l << endl;
} else {
message(l);
}
if (StringHelper::startsWith(l, L"PORT: ")) {
tcpPort = stoi(l.substr(6)->trim());
} else if (StringHelper::startsWith(l, L"COMMIT VERSION: ")) {
initCommitVersion = stoi(l.substr(16)->trim());
} else if (StringHelper::startsWith(l, L"INFOS VERSION: ")) {
initInfosVersion = stoi(l.substr(15)->trim());
} else if (l.find(L"will crash after") != wstring::npos) {
willCrash = true;
} else if (StringHelper::startsWith(l, L"NODE STARTED")) {
break;
} else if (l.find(L"replica cannot start: existing segments file=") !=
wstring::npos) {
sawExistingSegmentsFile = true;
}
}
constexpr bool finalWillCrash = willCrash;
// Baby sits the child process, pulling its stdout and printing to our stdout:
shared_ptr<AtomicBoolean> nodeClosing = make_shared<AtomicBoolean>();
shared_ptr<Thread> pumper = ThreadPumper::start(
[&]() {
message(L"now wait for process " + p);
try {
p->waitFor();
} catch (const runtime_error &t) {
throw runtime_error(t);
}
message(L"done wait for process " + p);
int exitValue = p->exitValue();
message(L"exit value=" + to_wstring(exitValue) + L" willCrash=" +
StringHelper::toString(finalWillCrash));
if (exitValue != 0 && finalWillCrash == false) {
// should fail test
throw runtime_error(L"node " + to_wstring(id) +
L" process had unexpected non-zero exit status=" +
to_wstring(exitValue));
}
},
r, System::out, nullptr, nodeClosing);
pumper->setName(L"pump" + to_wstring(id));
message(L"top: node=" + to_wstring(id) + L" started at tcpPort=" +
to_wstring(tcpPort) + L" initCommitVersion=" +
to_wstring(initCommitVersion) + L" initInfosVersion=" +
to_wstring(initInfosVersion));
return make_shared<NodeProcess>(p, id, tcpPort, pumper, primaryTCPPort == -1,
initCommitVersion, initInfosVersion,
nodeClosing);
}
void TestNRTReplication::setUp()
{
LuceneTestCase::setUp();
Node::globalStartNS = System::nanoTime();
childTempDir = createTempDir(L"child");
docs = make_shared<LineFileDocs>(random());
}
void TestNRTReplication::tearDown()
{
LuceneTestCase::tearDown();
delete docs;
}
// C++ TODO: Most Java annotations will not have direct C++ equivalents:
// ORIGINAL LINE: @Nightly public void testReplicateDeleteAllDocuments() throws
// Exception
void TestNRTReplication::testReplicateDeleteAllDocuments()
{
shared_ptr<Path> primaryPath = createTempDir(L"primary");
shared_ptr<NodeProcess> primary = startNode(-1, 0, primaryPath, -1, false);
shared_ptr<Path> replicaPath = createTempDir(L"replica");
shared_ptr<NodeProcess> replica =
startNode(primary->tcpPort, 1, replicaPath, -1, false);
// Tell primary current replicas:
sendReplicasToPrimary(primary, {replica});
// Index 10 docs into primary:
shared_ptr<LineFileDocs> docs = make_shared<LineFileDocs>(random());
shared_ptr<Connection> primaryC = make_shared<Connection>(primary->tcpPort);
primaryC->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(primaryC, doc, false);
}
// Nothing in replica index yet
assertVersionAndHits(replica, 0, 0);
// Refresh primary, which also pushes to replica:
int64_t primaryVersion1 = primary->flush(0);
assertTrue(primaryVersion1 > 0);
// Wait for replica to show the change
waitForVersionAndHits(replica, primaryVersion1, 10);
// Delete all docs from primary
if (random()->nextBoolean()) {
// Inefficiently:
for (int id = 0; id < 10; id++) {
// C++ TODO: There is no native C++ equivalent to 'toString':
primary->deleteDocument(primaryC, Integer::toString(id));
}
} else {
// Efficiently:
primary->deleteAllDocuments(primaryC);
}
// Replica still shows 10 docs:
assertVersionAndHits(replica, primaryVersion1, 10);
// Refresh primary, which also pushes to replica:
int64_t primaryVersion2 = primary->flush(0);
assertTrue(primaryVersion2 > primaryVersion1);
// Wait for replica to show the change
waitForVersionAndHits(replica, primaryVersion2, 0);
// Index 10 docs again:
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(primaryC, doc, false);
}
// Refresh primary, which also pushes to replica:
int64_t primaryVersion3 = primary->flush(0);
assertTrue(primaryVersion3 > primaryVersion2);
// Wait for replica to show the change
waitForVersionAndHits(replica, primaryVersion3, 10);
delete primaryC;
delete replica;
delete primary;
}
// C++ TODO: Most Java annotations will not have direct C++ equivalents:
// ORIGINAL LINE: @Nightly public void testReplicateForceMerge() throws
// Exception
void TestNRTReplication::testReplicateForceMerge()
{
shared_ptr<Path> primaryPath = createTempDir(L"primary");
shared_ptr<NodeProcess> primary = startNode(-1, 0, primaryPath, -1, false);
shared_ptr<Path> replicaPath = createTempDir(L"replica");
shared_ptr<NodeProcess> replica =
startNode(primary->tcpPort, 1, replicaPath, -1, false);
sendReplicasToPrimary(primary, {replica});
// Index 10 docs into primary:
shared_ptr<LineFileDocs> docs = make_shared<LineFileDocs>(random());
shared_ptr<Connection> primaryC = make_shared<Connection>(primary->tcpPort);
primaryC->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(primaryC, doc, false);
}
// Refresh primary, which also pushes to replica:
int64_t primaryVersion1 = primary->flush(0);
assertTrue(primaryVersion1 > 0);
// Index 10 more docs into primary:
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(primaryC, doc, false);
}
// Refresh primary, which also pushes to replica:
int64_t primaryVersion2 = primary->flush(0);
assertTrue(primaryVersion2 > primaryVersion1);
primary->forceMerge(primaryC);
// Refresh primary, which also pushes to replica:
int64_t primaryVersion3 = primary->flush(0);
assertTrue(primaryVersion3 > primaryVersion2);
// Wait for replica to show the change
waitForVersionAndHits(replica, primaryVersion3, 20);
delete primaryC;
delete replica;
delete primary;
}
// C++ TODO: Most Java annotations will not have direct C++ equivalents:
// ORIGINAL LINE: @Nightly public void testReplicaCrashNoCommit() throws
// Exception
void TestNRTReplication::testReplicaCrashNoCommit()
{
shared_ptr<Path> primaryPath = createTempDir(L"primary");
shared_ptr<NodeProcess> primary = startNode(-1, 0, primaryPath, -1, false);
shared_ptr<Path> replicaPath = createTempDir(L"replica");
shared_ptr<NodeProcess> replica =
startNode(primary->tcpPort, 1, replicaPath, -1, true);
sendReplicasToPrimary(primary, {replica});
// Index 10 docs into primary:
shared_ptr<LineFileDocs> docs = make_shared<LineFileDocs>(random());
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
// Refresh primary, which also pushes to replica:
int64_t primaryVersion1 = primary->flush(0);
assertTrue(primaryVersion1 > 0);
// Wait for replica to sync up:
waitForVersionAndHits(replica, primaryVersion1, 10);
// Crash replica:
replica->crash();
// Restart replica:
replica = startNode(primary->tcpPort, 1, replicaPath, -1, false);
// On startup the replica searches the last commit (empty here):
assertVersionAndHits(replica, 0, 0);
// Ask replica to sync:
replica->newNRTPoint(primaryVersion1, 0, primary->tcpPort);
waitForVersionAndHits(replica, primaryVersion1, 10);
delete replica;
delete primary;
}
// C++ TODO: Most Java annotations will not have direct C++ equivalents:
// ORIGINAL LINE: @Nightly public void testReplicaCrashWithCommit() throws
// Exception
void TestNRTReplication::testReplicaCrashWithCommit()
{
shared_ptr<Path> primaryPath = createTempDir(L"primary");
shared_ptr<NodeProcess> primary = startNode(-1, 0, primaryPath, -1, false);
shared_ptr<Path> replicaPath = createTempDir(L"replica");
shared_ptr<NodeProcess> replica =
startNode(primary->tcpPort, 1, replicaPath, -1, true);
sendReplicasToPrimary(primary, {replica});
// Index 10 docs into primary:
shared_ptr<LineFileDocs> docs = make_shared<LineFileDocs>(random());
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
// Refresh primary, which also pushes to replica:
int64_t primaryVersion1 = primary->flush(0);
assertTrue(primaryVersion1 > 0);
// Wait for replica to sync up:
waitForVersionAndHits(replica, primaryVersion1, 10);
// Commit and crash replica:
replica->commit();
replica->crash();
// Restart replica:
replica = startNode(primary->tcpPort, 1, replicaPath, -1, false);
// On startup the replica searches the last commit:
assertVersionAndHits(replica, primaryVersion1, 10);
delete replica;
delete primary;
}
// C++ TODO: Most Java annotations will not have direct C++ equivalents:
// ORIGINAL LINE: @Nightly public void testIndexingWhileReplicaIsDown() throws
// Exception
void TestNRTReplication::testIndexingWhileReplicaIsDown()
{
shared_ptr<Path> primaryPath = createTempDir(L"primary");
shared_ptr<NodeProcess> primary = startNode(-1, 0, primaryPath, -1, false);
shared_ptr<Path> replicaPath = createTempDir(L"replica");
shared_ptr<NodeProcess> replica =
startNode(primary->tcpPort, 1, replicaPath, -1, true);
sendReplicasToPrimary(primary, {replica});
// Index 10 docs into primary:
shared_ptr<LineFileDocs> docs = make_shared<LineFileDocs>(random());
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
// Refresh primary, which also pushes to replica:
int64_t primaryVersion1 = primary->flush(0);
assertTrue(primaryVersion1 > 0);
// Wait for replica to sync up:
waitForVersionAndHits(replica, primaryVersion1, 10);
// Commit and crash replica:
replica->commit();
replica->crash();
sendReplicasToPrimary(primary);
// Index 10 more docs, while replica is down
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
// And flush:
int64_t primaryVersion2 = primary->flush(0);
assertTrue(primaryVersion2 > primaryVersion1);
// Now restart replica:
replica = startNode(primary->tcpPort, 1, replicaPath, -1, false);
sendReplicasToPrimary(primary, {replica});
// On startup the replica still searches its last commit:
assertVersionAndHits(replica, primaryVersion1, 10);
// Now ask replica to sync:
replica->newNRTPoint(primaryVersion2, 0, primary->tcpPort);
waitForVersionAndHits(replica, primaryVersion2, 20);
delete replica;
delete primary;
}
// C++ TODO: Most Java annotations will not have direct C++ equivalents:
// ORIGINAL LINE: @Nightly public void testCrashPrimary1() throws Exception
void TestNRTReplication::testCrashPrimary1()
{
shared_ptr<Path> path1 = createTempDir(L"1");
shared_ptr<NodeProcess> primary = startNode(-1, 0, path1, -1, true);
shared_ptr<Path> path2 = createTempDir(L"2");
shared_ptr<NodeProcess> replica =
startNode(primary->tcpPort, 1, path2, -1, true);
sendReplicasToPrimary(primary, {replica});
// Index 10 docs into primary:
shared_ptr<LineFileDocs> docs = make_shared<LineFileDocs>(random());
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
// Refresh primary, which also pushes to replica:
int64_t primaryVersion1 = primary->flush(0);
assertTrue(primaryVersion1 > 0);
// Wait for replica to sync up:
waitForVersionAndHits(replica, primaryVersion1, 10);
// Crash primary:
primary->crash();
// Promote replica:
replica->commit();
delete replica;
primary = startNode(-1, 1, path2, -1, false);
// Should still see 10 docs:
assertVersionAndHits(primary, primaryVersion1, 10);
delete primary;
}
// C++ TODO: Most Java annotations will not have direct C++ equivalents:
// ORIGINAL LINE: @Nightly public void testCrashPrimary2() throws Exception
void TestNRTReplication::testCrashPrimary2()
{
shared_ptr<Path> path1 = createTempDir(L"1");
shared_ptr<NodeProcess> primary = startNode(-1, 0, path1, -1, true);
shared_ptr<Path> path2 = createTempDir(L"2");
shared_ptr<NodeProcess> replica =
startNode(primary->tcpPort, 1, path2, -1, true);
sendReplicasToPrimary(primary, {replica});
// Index 10 docs into primary:
shared_ptr<LineFileDocs> docs = make_shared<LineFileDocs>(random());
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
// Refresh primary, which also pushes to replica:
int64_t primaryVersion1 = primary->flush(0);
assertTrue(primaryVersion1 > 0);
// Wait for replica to sync up:
waitForVersionAndHits(replica, primaryVersion1, 10);
primary->commit();
// Index 10 docs, but crash before replicating or committing:
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
// Crash primary:
primary->crash();
// Restart it:
primary = startNode(-1, 0, path1, -1, true);
sendReplicasToPrimary(primary, {replica});
// Index 10 more docs
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
int64_t primaryVersion2 = primary->flush(0);
assertTrue(primaryVersion2 > primaryVersion1);
// Wait for replica to sync up:
waitForVersionAndHits(replica, primaryVersion2, 20);
delete primary;
delete replica;
}
// C++ TODO: Most Java annotations will not have direct C++ equivalents:
// ORIGINAL LINE: @Nightly public void testCrashPrimary3() throws Exception
void TestNRTReplication::testCrashPrimary3()
{
shared_ptr<Path> path1 = createTempDir(L"1");
shared_ptr<NodeProcess> primary = startNode(-1, 0, path1, -1, true);
shared_ptr<Path> path2 = createTempDir(L"2");
shared_ptr<NodeProcess> replica =
startNode(primary->tcpPort, 1, path2, -1, true);
sendReplicasToPrimary(primary, {replica});
// Index 10 docs into primary:
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
// Refresh primary, which also pushes to replica:
int64_t primaryVersion1 = primary->flush(0);
assertTrue(primaryVersion1 > 0);
// Wait for replica to sync up:
waitForVersionAndHits(replica, primaryVersion1, 10);
replica->commit();
delete replica;
primary->crash();
// At this point replica is "in the future": it has 10 docs committed, but the
// primary crashed before committing so it has 0 docs
// Restart primary:
primary = startNode(-1, 0, path1, -1, true);
// Index 20 docs into primary:
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 20; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
// Flush primary, but there are no replicas to sync to:
int64_t primaryVersion2 = primary->flush(0);
// Now restart replica, which on init should detect on a "lost branch" because
// its 10 docs that were committed came from a different primary node:
replica = startNode(primary->tcpPort, 1, path2, -1, true);
assertVersionAndHits(replica, primaryVersion2, 20);
delete primary;
delete replica;
}
// C++ TODO: Most Java annotations will not have direct C++ equivalents:
// ORIGINAL LINE: @Nightly public void testCrashPrimaryWhileCopying() throws
// Exception
void TestNRTReplication::testCrashPrimaryWhileCopying()
{
shared_ptr<Path> path1 = createTempDir(L"1");
shared_ptr<NodeProcess> primary = startNode(-1, 0, path1, -1, true);
shared_ptr<Path> path2 = createTempDir(L"2");
shared_ptr<NodeProcess> replica =
startNode(primary->tcpPort, 1, path2, -1, true);
sendReplicasToPrimary(primary, {replica});
// Index 100 docs into primary:
shared_ptr<LineFileDocs> docs = make_shared<LineFileDocs>(random());
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 100; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
// Refresh primary, which also pushes (async) to replica:
int64_t primaryVersion1 = primary->flush(0);
assertTrue(primaryVersion1 > 0);
delay(TestUtil::nextInt(random(), 1, 30));
// Crash primary, likely/hopefully while replica is still copying
primary->crash();
// Could see either 100 docs (replica finished before crash) or 0 docs:
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(replica.tcpPort))
{
Connection c = Connection(replica->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_SEARCH_ALL);
c->flush();
int64_t version = c->in_->readVLong();
int hitCount = c->in_->readVInt();
if (version == 0) {
TestUtil::assertEquals(0, hitCount);
} else {
TestUtil::assertEquals(primaryVersion1, version);
TestUtil::assertEquals(100, hitCount);
}
}
delete primary;
delete replica;
}
void TestNRTReplication::assertWriteLockHeld(shared_ptr<Path> path) throw(
runtime_error)
{
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (org.apache.lucene.store.FSDirectory dir =
// org.apache.lucene.store.FSDirectory.open(path))
{
org::apache::lucene::store::FSDirectory dir =
org::apache::lucene::store::FSDirectory::open(path);
expectThrows(LockObtainFailedException::typeid,
[&]() { dir->obtainLock(IndexWriter::WRITE_LOCK_NAME); });
}
}
void TestNRTReplication::testCrashReplica()
{
shared_ptr<Path> path1 = createTempDir(L"1");
shared_ptr<NodeProcess> primary = startNode(-1, 0, path1, -1, true);
shared_ptr<Path> path2 = createTempDir(L"2");
shared_ptr<NodeProcess> replica =
startNode(primary->tcpPort, 1, path2, -1, true);
assertWriteLockHeld(path2);
sendReplicasToPrimary(primary, {replica});
// Index 10 docs into primary:
shared_ptr<LineFileDocs> docs = make_shared<LineFileDocs>(random());
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
// Refresh primary, which also pushes to replica:
int64_t primaryVersion1 = primary->flush(0);
assertTrue(primaryVersion1 > 0);
// Wait for replica to sync up:
waitForVersionAndHits(replica, primaryVersion1, 10);
// Crash replica
replica->crash();
sendReplicasToPrimary(primary);
// Lots of new flushes while replica is down:
int64_t primaryVersion2 = 0;
for (int iter = 0; iter < 10; iter++) {
// Index 10 docs into primary:
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
primaryVersion2 = primary->flush(0);
}
// Start up replica again:
replica = startNode(primary->tcpPort, 1, path2, -1, true);
sendReplicasToPrimary(primary, {replica});
// Now ask replica to sync:
replica->newNRTPoint(primaryVersion2, 0, primary->tcpPort);
// Make sure it sees all docs that were indexed while it was down:
assertVersionAndHits(primary, primaryVersion2, 110);
delete replica;
delete primary;
}
// C++ TODO: Most Java annotations will not have direct C++ equivalents:
// ORIGINAL LINE: @Nightly public void testFullClusterCrash() throws Exception
void TestNRTReplication::testFullClusterCrash()
{
shared_ptr<Path> path1 = createTempDir(L"1");
shared_ptr<NodeProcess> primary = startNode(-1, 0, path1, -1, true);
shared_ptr<Path> path2 = createTempDir(L"2");
shared_ptr<NodeProcess> replica1 =
startNode(primary->tcpPort, 1, path2, -1, true);
shared_ptr<Path> path3 = createTempDir(L"3");
shared_ptr<NodeProcess> replica2 =
startNode(primary->tcpPort, 2, path3, -1, true);
sendReplicasToPrimary(primary, {replica1, replica2});
// Index 50 docs into primary:
shared_ptr<LineFileDocs> docs = make_shared<LineFileDocs>(random());
int64_t primaryVersion1 = 0;
for (int iter = 0; iter < 5; iter++) {
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
// Refresh primary, which also pushes to replicas:
primaryVersion1 = primary->flush(0);
assertTrue(primaryVersion1 > 0);
}
// Wait for replicas to sync up:
waitForVersionAndHits(replica1, primaryVersion1, 50);
waitForVersionAndHits(replica2, primaryVersion1, 50);
primary->commit();
replica1->commit();
replica2->commit();
// Index 10 more docs, but don't sync to replicas:
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_INDEXING);
for (int i = 0; i < 10; i++) {
shared_ptr<Document> doc = docs->nextDoc();
primary->addOrUpdateDocument(c, doc, false);
}
}
// Full cluster crash
primary->crash();
replica1->crash();
replica2->crash();
// Full cluster restart
primary = startNode(-1, 0, path1, -1, true);
replica1 = startNode(primary->tcpPort, 1, path2, -1, true);
replica2 = startNode(primary->tcpPort, 2, path3, -1, true);
// Only 50 because we didn't commit primary before the crash:
// It's -1 because it's unpredictable how IW changes segments version on init:
assertVersionAndHits(primary, -1, 50);
assertVersionAndHits(replica1, primary->initInfosVersion, 50);
assertVersionAndHits(replica2, primary->initInfosVersion, 50);
delete primary;
delete replica1;
delete replica2;
}
void TestNRTReplication::sendReplicasToPrimary(
shared_ptr<NodeProcess> primary,
deque<NodeProcess> &replicas)
{
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new
// Connection(primary.tcpPort))
{
Connection c = Connection(primary->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_SET_REPLICAS);
c->out->writeVInt(replicas->length);
for (int id = 0; id < replicas->length; id++) {
shared_ptr<NodeProcess> replica = replicas[id];
c->out->writeVInt(replica->id);
c->out->writeVInt(replica->tcpPort);
}
c->flush();
c->in_->readByte();
}
}
void TestNRTReplication::assertVersionAndHits(
shared_ptr<NodeProcess> node, int64_t expectedVersion,
int expectedHitCount)
{
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new Connection(node.tcpPort))
{
Connection c = Connection(node->tcpPort);
c->out->writeByte(SimplePrimaryNode::CMD_SEARCH_ALL);
c->flush();
int64_t version = c->in_->readVLong();
int hitCount = c->in_->readVInt();
if (expectedVersion != -1) {
assertEquals(L"wrong searcher version, with hitCount=" +
to_wstring(hitCount),
expectedVersion, version);
}
TestUtil::assertEquals(expectedHitCount, hitCount);
}
}
void TestNRTReplication::waitForVersionAndHits(
shared_ptr<NodeProcess> node, int64_t expectedVersion,
int expectedHitCount)
{
// C++ NOTE: The following 'try with resources' block is replaced by its C++
// equivalent: ORIGINAL LINE: try (Connection c = new Connection(node.tcpPort))
{
Connection c = Connection(node->tcpPort);
while (true) {
c->out->writeByte(SimplePrimaryNode::CMD_SEARCH_ALL);
c->flush();
int64_t version = c->in_->readVLong();
int hitCount = c->in_->readVInt();
if (version == expectedVersion) {
TestUtil::assertEquals(expectedHitCount, hitCount);
break;
}
assertTrue(version < expectedVersion);
delay(10);
}
}
}
void TestNRTReplication::message(const wstring &message)
{
int64_t now = System::nanoTime();
wcout << wstring::format(Locale::ROOT, L"%5.3fs : parent [%11s] %s",
(now - Node::globalStartNS) / 1000000000.0,
Thread::currentThread().getName(), message)
<< endl;
}
} // namespace org::apache::lucene::replicator::nrt |
ac06790880a178da5187e908806ade35e20ce4eb | a3e213d7fba19c666141ae4b2492b5b73243ac6f | /GammaTime_Offsets_LP.cpp | d7a3ed981b9dd0a203cdf704387765a7515e163b | [] | no_license | KingKallis/scripts | 447e223f97c20cfa7d78a4a5a4cd0f4a46ad81be | 5bbccdbc00dc75209b090baee0f0aa30c933b256 | refs/heads/master | 2021-01-14T16:43:40.392766 | 2020-02-24T08:18:03 | 2020-02-24T08:18:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,214 | cpp | GammaTime_Offsets_LP.cpp | ///////////////////////////////////////////////////////////////////////////
// Calculate the Gamma time offsets //
///////////////////////////////////////////////////////////////////////////
#include <TF1.h>
//defining fit function
double Gaus_2sigma( double *x, double*par )
{
double xx = x[0];
double height = par[0];
double mean = par[1];
double sigma_1 = par[2];
double sigma_2 = par[3];
//double Pol = par[4] + xx*(par[5] + xx*par[6] );
if( xx < mean )
{
return height*exp( -(xx - mean)*(xx - mean)/(2*sigma_1*sigma_1) );
}
else
{
return height*exp( -(xx - mean)*(xx - mean)/(2*sigma_2*sigma_2) );
}
}
int main()
{
//Parameters
bool Mg24_NoCol = false;
bool Mg24_Col = true;
char *histname = new char[32];
char *histname = new char[2];
char *DetectorOption = new char[256];
Float_t peakposition[32];
Float_t sigma[32];
Double_t Clover_par[3];
Float_t LaBr_peakposition[2];
Float_t LaBr_sigma[2];
Double_t LaBr_par[3];
TCanvas *C = new TCanvas;
//Read in Cuts for PID selection
if(Mg24_NoCol)
{
gROOT->ProcessLine(".x /home/luna/codes/PR251-analysis/sortedfiles/gates/Alphas_24Mg_NoCol.C");
gROOT->ProcessLine(".x /home/luna/codes/PR251-analysis/sortedfiles/gates/Cut_pad1X1_24Mg_NoCol.C");
cout << "----------------> using cuts for 24Mg No Collimator data" << endl;
}
else if(Mg24_Col)
{
gROOT->ProcessLine(".x /home/luna/codes/PR251-analysis/sortedfiles/gates/Alphas_24Mg_Col.C");
gROOT->ProcessLine(".x /home/luna/codes/PR251-analysis/sortedfiles/gates/Cut_pad1X1_24Mg_Col.C");
cout << "----------------> using cuts for 24Mg Collimator data" << endl;
}
//read in file
char buffer[256];
sprintf(buffer,"sorted0%d.root",2227);
TFile *f = TFile::Open(buffer);
c1 = new TCanvas("c1","Checks GammaTime",10,10,900,600);
//defining fit
TF1 *f_Gaus_2sigma = new TF1("f_Gaus_2sigma", Gaus_2sigma, 4000, 7000, 4 );
f_Gaus_2sigma->SetParameters(70, 4500, 20, 60);
//Create gammaTime plot for each clover segment
for(int i=1;i<9;i++)
{
for(int j=1;j<5;j++)
{
sprintf(histname,"Clover_%d_Segm_%d",i,j);
TH1F *hGammaTime = new TH1F("hGamTime",histname,400,3000,7000); //Check range
sprintf(DetectorOption,"Alphas_24Mg_Col && Cut_pad1X1_24Mg_Col && X1flag==0 && U1flag==0 && Y1>-20 && Y1<20 && GammaDetectorType==\"Clover\" && GammaDetectorLabel==%d && GammaDetectorSegm==%d",i,j);
DATAch->Draw("GammaTime>>hGamTime",DetectorOption,"");
//fit
hGammaTime->Fit("f_Gaus_2sigma","R","",4000,5200);
/* Gaus_2sigmas->GetParameters(par);
peakposition[(i-1)*4+j] = Clover_par[1];
sigma[(i-1)*4+j] = Clover_par[2];
*/
c1->Modified(); c1->Update();
c1->WaitPrimitive();
cout << "Det num " << (i-1)*4+j << endl; //check
hGammaTime->Clear();
if(j<5)c1->Clear();
}
if(i<9)c1->Clear();
}
/*
//Check offset values
for(Int_t k=1;k<33;i++)
{
cout << " "<< k <<" "<< peakposition[k] <<" "<< sigma[k] << endl;
}
for(Int_t k=1;k<9;i++)
{
cout << ""<< k <<" Difference compared with Gamma detector 1 " <<" "<< peakposition[k]-peakposition[1] << endl;
}
//Create gammaTime plot for each LaBr Scintillator
for(int i=1;i<3;i++)
{
sprintf(histname2,"LaBr_%d",i);
TH1F *hGammaTime = new TH1F("hGamTime",histname2,200,4000,6000); //Check range for peak
sprintf(DetectorOption,"Alphas_24Mg_Col && Cut_pad1X1_24Mg_Col && X1flag==0 && U1flag==0 &&Y1>-20 &&Y1<20 &&GammaDetectorType==\"Scintillator\" && GammaDetectorLabel==%d",i);
DATAch->Draw("GammaTime>>hGamTime",DetectorOption,"");
//fit
hGammaTime->Fit("gaus","R","",4500,5500);
gaus->GetParameters(LaBr_par);
LaBr_peakposition[i] = LaBr_par[1];
LaBr_sigma[i] = LaBr_par[2];
C->Modified(); C->Update();
C->WaitPrimitive();
cout << "NEXT" << endl; //check
if(i<2)C->Clear();
}
//Check offset values
for(Int_t i=1;i<3;i++)
{
cout << " "<< i <<" "<< LaBr_peakposition[i] <<" "<< LaBr_sigma[i] << endl;
}
for(Int_t i=1;i<3;i++)
{
cout << ""<< i <<" Difference compared with LaBr detector 1 " <<" "<< LaBr_peakposition[i]-LaBr_peakposition[1] << endl;
}
//Creates file with the offsets in the current folder. Then move it to the analyser folder and remove _new to be able to use it
ofstream outputFile;
outputFile.open("GammaTimeOffsetsPR251_new.dat");
for(Int_t k=1;k<33;i++)
{
cout << k <<" "<< int(peakposition[k]-peakposition[1]) << endl;
outputFile << k <<" "<< int(peakposition[k]-peakposition[1]) << endl;
}
for(Int_t i=1;i<3;i++)
{
cout << i+100 <<" "<< int(LaBr_peakposition[i]-LaBr_peakposition[1]) << endl;
outputFile << i+100 <<" "<< int(LaBr_peakposition[i]-LaBr_peakposition[1]) << endl;
}
for(Int_t i=1;i<3;i++)
{
cout << i+102 <<" "<< int(LaBr_peakposition[i]-LaBr_peakposition[1]) << endl;
outputFile << i+102 <<" "<< int(LaBr_peakposition[i]-LaBr_peakposition[1]) << endl;
}
outputFile << "eof" << endl;
outputFile.close();
cout << "File Offsets Created!\n";
*/
}
|
e5ec0cb751cfd04972c7418d8ee7e9b9f818d4c3 | 94f19581493a8a97d1e400fe3609cf6c86416166 | /kraGraphicsDX/include/kraD3D11InputLayout.h | bef0fdd025811b3fef03e565ddd68c1a99ff8a83 | [] | no_license | Evey92/KrakenEngine | cecb7849a4f265c30060f84a3c7515a344497b5e | d173050d0413eab09eaedfef655f1aca3774fdc9 | refs/heads/master | 2020-04-02T15:55:43.140650 | 2019-12-13T01:15:17 | 2019-12-13T01:15:17 | 154,589,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 791 | h | kraD3D11InputLayout.h | #pragma once
#include <kraInputLayout.h>
#include "kraPrerequisitesGFX.h"
namespace kraEngineSDK {
class Device;
class VertexShader;
class KRA_UTILGFX_EXPORT InputLayoutDX :
public InputLayout {
public:
InputLayoutDX() = default;
~InputLayoutDX() {}
/**
* @brief Function that creates an input layout by reflecting the shader
* @param The graphics API device, and a shader
*/
bool
createInputLayout(const Device& pd3dDevice, const VertexShader& pVShader);
void
setInputLayout(const Device& pDevice);
void
cleanInputLayout();
void
setNullInputLayout(const Device& pDevice) override;
ID3D11InputLayout* m_pVertexLayout = nullptr;
std::vector<D3D11_INPUT_ELEMENT_DESC> m_layoutDescVector;
};
}
|
6f8edd3942afbb2b3e6ff667450107f1bbc97edd | 10153a535050a9bd2c2bee92551588b000a4eebf | /Stas/Point.h | be0245feea24119d59dc4ab0697ef08b1c1f0393 | [] | no_license | nishoni/Clusters | 92e95424181e202c3c68fb5bd0905d820e21af80 | c14a321d0af67113067ac09305f0026c5ad2a5ec | refs/heads/master | 2023-04-18T08:23:38.428371 | 2021-05-02T07:05:17 | 2021-05-02T07:05:17 | 363,585,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 468 | h | Point.h | #pragma once
class Point {
private:
double x, y;
long long int cluster_label;
public:
Point();
Point(double _x, double _y);
Point(double _x, double _y, long long int _cluster_label);
double GetX();
double GetY();
long long int GetLabel();
void SetX(double _x);
void SetY(double _y);
void SetLabel(long long int _label);
void MoveX(double dx);
void MoveY(double dy);
Point& operator=(const Point& point);
};
|
57cdf0c54e3d32c9b5f7e5b5e526411c8a0fd8d9 | 0fd8047156cc4ab541b72d72f1f9dfd591c12124 | /2015_30_11/reverseLLRecursion.cpp | 01fdf45fe00761340005c0fbd1283a2cd316c6ba | [] | no_license | sravya-kanagarla/MissionRnD_extra_problems | 7b46df1d8cef6206de9bb517b0279b2248d44e32 | 943bb0fad9fc2972c3c178de374c0eec5b1855bb | refs/heads/master | 2021-05-30T08:48:15.445268 | 2015-12-11T18:21:33 | 2015-12-11T18:21:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,356 | cpp | reverseLLRecursion.cpp | // reverseLLRecursion.cpp : Defines the entry point for the console application.
//
/* 4.Reverse an Linked list , using recursion */
#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct node {
int num;
struct node *next;
};
struct node * create(struct node *head) {
struct node *temp;
struct node *last;
char c;
fflush(stdin);
printf("Do you want to continue(y/n): ");
scanf("%c", &c);
while (c == 'y') {
temp = (struct node *)malloc(sizeof(struct node));
printf("Enter element: ");
scanf("%d", &(temp -> num));
if (head == NULL) {
head = temp;
last = head;
} else {
last -> next = temp;
last = last -> next;
}
fflush(stdin);
printf("Do you want to continue(y/n): ");
scanf("%c", &c);
}
last -> next = NULL;
return head;
}
void display(struct node *head) {
struct node *temp = head;
while (temp != NULL) {
printf("%d\t", temp -> num);
temp = temp -> next;
}
printf("\n");
}
struct node * reverse1(struct node * head) {
struct node *revHead;
if (head == NULL || head -> next == NULL) {
return head;
}
revHead = reverse1(head -> next);
head -> next -> next = head;
head -> next = NULL;
return revHead;
}
int _tmain(int argc, _TCHAR* argv[])
{
struct node *head = create(NULL);
display(head);
head = reverse1(head);
display(head);
getch();
return 0;
}
|
8ca54f4f34bebe046c1d1a76cc4d0587940de94f | 507935181c2fb56654ea781ecc2dea18c4f8de20 | /CkMath/util.h | 5808bcaf832cac8f0772749c9e50674dbd06687e | [
"Unlicense"
] | permissive | chronokun/CkMath | 6bb014fa9d442b0491e77f94f370c7c498e0520b | 0cc1030342a79ea191c8069d1fdf81296e89de6d | refs/heads/master | 2020-05-20T02:31:00.846364 | 2015-05-28T09:04:49 | 2015-05-28T09:04:49 | 28,178,429 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | h | util.h | //
// Author: Michael Cameron
// Email: chronokun@hotmail.com
//
#pragma once
#ifndef __UTIL_H__
#define __UTIL_H__
#include <Windows.h>
#include <cstdint>
#include <cstdlib>
static int64_t s_TicksPerSecond;
static int64_t s_StartTicks;
static int64_t s_StopTicks;
static double s_dTicksPerSecond;
void InitTimer()
{
QueryPerformanceFrequency((LARGE_INTEGER*)&s_TicksPerSecond);
s_dTicksPerSecond = (double)s_TicksPerSecond;
}
void StartTimer()
{
QueryPerformanceCounter((LARGE_INTEGER*)&s_StartTicks);
}
void StopTimer()
{
QueryPerformanceCounter((LARGE_INTEGER*)&s_StopTicks);
}
double GetTime()
{
return((double)(s_StopTicks - s_StartTicks) / s_dTicksPerSecond);
}
const double Random(const double _kdMin, const double _kdMax)
{
const double kdValue = (double)rand() / (double)RAND_MAX;
const double kdScale = _kdMax - _kdMin;
const double kdResult = _kdMin + (kdValue * kdScale);
return(kdResult);
}
const float Random(const float _kfMin, const float _kfMax)
{
const float kfValue = (float)rand() / (float)RAND_MAX;
const float kfScale = _kfMax - _kfMin;
const float kfResult = _kfMin + (kfValue * kfScale);
return(kfResult);
}
#endif |
11c365616b8817559bcd0cf4ad84c5c9a1bfe7bc | e39ccb685504df5160d320f37fb3aebde5893be7 | /src/util/CLog.cpp | ad04e3a604169157b9199cc3f640b92a2c73fffc | [] | no_license | goodgo/nat_proxy | c0f1890c39f1024ee2a385e200e82da9befc7b68 | e9297079d1a5d846bb8981738801f257af77e2f7 | refs/heads/master | 2020-04-04T09:44:49.859138 | 2018-11-22T03:27:13 | 2018-11-22T03:27:13 | 155,830,174 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,843 | cpp | CLog.cpp | #include "CLog.h"
#include "CConfig.h"
namespace util{
const char prefix[8][20] = {"[SYS_CRI]", "[SYS_IMP]", "[SYS_INF]", "[USR_CRI]",
"[USR_IMP]", "[USR_INF]", "[DBG_INF]","[USR_WAR]"};
LogModule::LogModule()
: _backlog(false)
{
for (int i = 0; i < 7; ++i)
_logSwitch[i] = true;
}
bool LogModule::onInit(const char* file, const char* section)
{
_path = "/usr/local/log/";
return true;
CIniFile inifile;
if (!inifile.Load(file))
{
return false;
}
_path = inifile.GetStrValue("Path", section, "/usr/local/log/");
_logSwitch[SYS_CRI] = (inifile.GetIntValue("SystemCritial", section, 1) == 1);
_logSwitch[SYS_IMP] = (inifile.GetIntValue("SystemCImportent", section, 1) == 1);
_logSwitch[SYS_INF] = (inifile.GetIntValue("SystemInfo", section, 1) == 1);
_logSwitch[USR_CRI] = (inifile.GetIntValue("UserCritial", section, 1) == 1);
_logSwitch[USR_IMP] = (inifile.GetIntValue("UserImportent", section, 1) == 1);
_logSwitch[USR_INF] = (inifile.GetIntValue("UserInfo", section, 1) == 1);
_logSwitch[DBG_INF] = (inifile.GetIntValue("DebugInfo", section, 1) == 1);
_logSwitch[USR_WARN] = (inifile.GetIntValue("WarningInfo", section, 1) == 1);
return true;
}
void LogModule::onRelease()
{
}
void LogModule::Log(const char* logfile, const char* content)
{
if ( _backlog)
{
}
else
{
if(gCConfig->onGetserverData().onGetbStd())
{
std::cout << content << std::endl;
}
std::string filename = getFileName(logfile);
if (!filename.empty())
{
std::ofstream outfile(filename.c_str(), std::ios_base::out | std::ios_base::app);
outfile << content << std::endl;
outfile.flush();
outfile.close();
}
}
}
void LogModule::FixLog(const char* logfile, const char* content)
{
std::cout << content << std::endl;
std::string filename = getFileName(logfile);
if (!filename.empty())
{
ofstream outfile(filename.c_str(), std::ios_base::out | std::ios_base::app);
outfile << content << std::endl;
outfile.flush();
outfile.close();
}
}
std::string LogModule::getFileName(const char* logfile)
{
char szPath[256];
memset(szPath,0,sizeof(szPath));
snprintf(szPath, 255, "%s/%s/",
_path.empty() ? "." : _path.c_str(),
logfile);
if (!isDirectory(szPath))
{
if (mkdir(szPath, S_IRWXU) < 0)
{
return "";
}
}
time_t tNow = time(NULL);
//tm* lt = localtime(&tNow);
struct tm lt;
localtime_r(&tNow, <);
char datebuf[100] = {0};
sprintf(datebuf, "%s_%4d-%02d-%02d.log", "ddnat",lt.tm_year+1900, lt.tm_mon+1, lt.tm_mday);
strcat(szPath, datebuf);
return szPath;
}
bool LogModule::isDirectory(const char* path)
{
struct stat buf;
if(stat(path, &buf) < 0)
return false;
if(S_ISDIR(buf.st_mode))
return true;
return false;
}
};
|
d9356479d4f6d279c54f9b5e9695dcdaa4d99cd2 | 54179c8facb26ba0b0283f8a422dcfcb3074af5e | /USACO/Section 2.3/Money Systems/money.cpp | 57e152820e213ebaaf1761aa8a64f7dfc529495f | [
"MIT"
] | permissive | 2719896135/- | c67ba64d743e6bcc9d7032e64e2cc0f6e4719b27 | add9bf759bfb62493f6bcb74d867e022baa6c3d4 | refs/heads/master | 2020-04-12T01:59:00.211484 | 2018-12-22T07:54:17 | 2018-12-22T07:54:17 | 162,234,131 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | cpp | money.cpp | /*
ID: cloudzf2
PROG: money
LANG: C++11
*/
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <unordered_map>
#include <cstring>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <queue>
#include <unordered_set>
#include <set>
#include <map>
using namespace std;
int main(int argc, const char * argv[]) {
ifstream fin ("money.in");
ofstream fout ("money.out");
int V, N, coin;
fin >> V >> N;
vector<long long> dp(N + 1, 0);
dp[0] = 1;
for (int i = 0; i < V; i++) {
fin >> coin;
for (int j = 0; j + coin <= N; j++) {
dp[j + coin] += dp[j];
}
}
fout << dp[N] << endl;
return 0;
}
|
4eac07473396fca32349890a2d10c97876907ddb | 245b51cb96afa951df49ecc2758ba32921bc29fd | /171860522沈天琪_ex6_2.cpp | c41dab38b0554e73375262cbcffe374e62acbe66 | [] | no_license | Price1999a/ProgramDesign | 587c6a47801a1283f56ea0b2e8dda840c6f6e4d6 | c7b6c9bf9c8b74d95769086863bbf2a5c11160fd | refs/heads/master | 2021-09-14T01:23:51.018186 | 2018-05-07T04:52:46 | 2018-05-07T04:52:46 | 107,058,735 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 430 | cpp | 171860522沈天琪_ex6_2.cpp | #include<cstdio>
#include<iostream>
using namespace std;
int n = 0;
int Houzi(int i)
{
if (n == 5)
{
n = 0; return i;
}
else if ((i - 1) % 5 != 0||i<=0)
{
n = 0; return -1;
}
else if ((i - 1) % 5 == 0)
{
i = (i - 1) / 5 * 4;
++n;
return Houzi(i);
}
}
int main()
{
int i = 6,b = 0;
for (;; i += 5)
{
if (Houzi(i) == -1);
else
{
b = Houzi(i);
break;
}
}
cout << i << " " << b;
return 0;
}
|
eb945c4b156902ece538f5d8db3537adc3668ab3 | 6289d2bc026a09c2c019cef03e2240fa400369d7 | /include/kimera-vio/pipeline/PipelinePayload.h | 08d8ada309fe29d5055efcaa8dcbf0120ceb8246 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | ManuelKugelmann/Kimera-VIO | 114e12363a54e2fbabb4dad6c0048ffaf57f59d6 | a4df3f0d503ba31065f9556d655dd993b75e5aa0 | refs/heads/master | 2022-11-22T03:52:53.343822 | 2020-06-19T20:42:29 | 2020-06-19T20:42:29 | 279,585,286 | 1 | 0 | BSD-2-Clause | 2020-07-14T12:56:51 | 2020-07-14T12:56:50 | null | UTF-8 | C++ | false | false | 1,066 | h | PipelinePayload.h | /**
* @file PipelinePayload.h
* @brief Base class for the payloads shared between pipeline modules.
* @author Antoni Rosinol
*/
#pragma once
#include "kimera-vio/common/vio_types.h"
#include "kimera-vio/utils/Macros.h"
namespace VIO {
struct PipelinePayload {
KIMERA_POINTER_TYPEDEFS(PipelinePayload);
KIMERA_DELETE_COPY_CONSTRUCTORS(PipelinePayload);
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
explicit PipelinePayload(const Timestamp& timestamp);
virtual ~PipelinePayload() = default;
// Untouchable timestamp of the payload.
const Timestamp timestamp_;
};
/**
* @brief The NullPipelinePayload is an empty payload, used for those modules
* that do not return a payload, such as the display module, which only
* displays images and returns nothing.
*/
struct NullPipelinePayload : public PipelinePayload {
KIMERA_POINTER_TYPEDEFS(NullPipelinePayload);
KIMERA_DELETE_COPY_CONSTRUCTORS(NullPipelinePayload);
explicit NullPipelinePayload() : PipelinePayload(Timestamp()) {}
virtual ~NullPipelinePayload() = default;
};
} // namespace VIO
|
ed859aa98ed2d5cade2e8a5b807a7cd7b4951a2c | f42dd0e2471c03600f890b2c769e57b24aaa08e3 | /FrameWork/Tool/Default/ToolGameStaticMeshObject.h | 5cb8948341cdecf86cd172eacc495711869a9b35 | [] | no_license | zeldie/- | 1722f777fbe870e9ccef9e1eed49bb07e2ce1dd7 | 658225e7ead91839750f8024593ed67b059d8923 | refs/heads/master | 2022-12-22T02:34:30.128966 | 2020-09-14T07:56:25 | 2020-09-14T07:56:25 | 295,115,224 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,208 | h | ToolGameStaticMeshObject.h | #pragma once
#include "ToolGameObject.h"
#include "StaticMesh.h"
class CToolGameStaticMeshObject : public CToolGameObject
{
protected:
explicit CToolGameStaticMeshObject(LPDIRECT3DDEVICE9 pGraphicDev);
virtual ~CToolGameStaticMeshObject();
protected:
// CToolGameObject을(를) 통해 상속됨
virtual HRESULT Ready_GameObject(wstring wstrObjectKey, _vec3* pPos, _vec3* pAngle, _vec3* pScale, _vec3* vSelfRotate, _uint iSect);
virtual _int Update_GameObject(const _double& dTimeDelta) override;
virtual _int LateUpdate_GameObject(const _double& dTimeDelta) override;
virtual void Render_Geometry(const _double& dTimeDelta) override;
protected:
HRESULT Clone_Component(wstring wstrObjectKey);
HRESULT Setup_ShaderProps(LPD3DXEFFECT& pEffect);
HRESULT Self_Rotation();
public:
_uint Get_Sect() { return m_iSect; }
void Set_iSect(_uint iSect) { m_iSect = iSect; }
protected:
Engine::CStaticMesh* m_pStaticMeshCom;
_uint m_iSect;
public:
static CToolGameStaticMeshObject* Create(LPDIRECT3DDEVICE9 pGraphicDev, wstring wstrObjectKey, _vec3* pPos, _vec3* pAngle, _vec3* pScale, _vec3* vSelfRotate = &_vec3(0.f, 0.f, 0.f), _uint iSect = 0);
virtual void Free();
};
|
9c9c626f84815fe64817f0d86f99c773162eb616 | 455d7fd3dd4c695ccfa89e00e22ff0fd0e3bd9cd | /main.cpp | 6fd3b6a4c17bcd326bf3e807365e2f0934ef46b3 | [] | no_license | mlamin1/LLSR | 2f3c13619e8f4ccc64718179801014600dc66021 | f3cc0df36a875664a45aa53de4d4496e023d8d56 | refs/heads/master | 2020-05-04T22:47:43.632052 | 2019-04-04T15:10:31 | 2019-04-04T15:10:31 | 179,522,850 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,260 | cpp | main.cpp | #include <iostream>
#include "matrix.h"
#include <stdlib.h>
#include <chrono>
#include <cmath>
#include <time.h>
#include "matrix.cpp"
int main(int agrc, char **argv)
{
int option;
do{
printf("Menu Option \n");
printf("Input 1 to run the linear least squares output \n");
printf("input 2 to test different matrix subroutines \n");
printf("Input 3 to end program: ");
std::cin>> option;
if(option == 1)
{
printf("Linear Least Squares Output \n");
printf("Based on the file: %s", argv[1]);
printf(" Your Optimal Vector Beta: \n");
Matrix<double> J(1, 1);
J = J.GetMatrix(argv[1]);
auto start = std::chrono::system_clock::now();
J = J.GetBeta();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << "s\n";
J.printMatrix();
}
else if(option == 2)
{
int choice;
do{
printf("Matrix Subroutines \n");
printf("Matrix Option \n");
printf("Input 1 for Adding Matrix \n");
printf("Input 2 for Subtracting Matrix \n");
printf("Input 3 for Multipling Matrix \n");
printf("Input 4 for Transpose Matrix \n");
printf("Input 5 for Inverse Matrix \n");
printf("Input 6 to End the test: ");
std::cin >> choice;
if(choice == 1)
{
printf("%s\n", "Addition matrix");
int row1;
int row2;
int col1;
int col2;
int matchoice;
int mat2choice;
printf("%s", "input the size of the row of your first matrix: ");
std::cin >> row1;
printf("%s", "input the size of the column of your first matrix: ");
std::cin >> col1;
Matrix<double> A(row1, col1);
printf("%s", "input 1 for sorted matrix, 2 for rand matrix: ");
std::cin >> matchoice;
switch(matchoice)
{
case 1: A = A.SortedMatrix();
break;
case 2: A = A.RandMatrix();
}
// printf("%s\n", "This is your first matrix");
//A.printMatrix();
std::cout << std::endl;
printf("%s", "input the size of the row of your second matrix: ");
std::cin >> row2;
printf("%s", "input the size of the column of your second matrix: ");
std::cin >> col2;
Matrix<double> B(row2, col2);
printf("%s", "input 1 for sorted matrix, 2 for rand matrix, 3 for Descending matrix: ");
std::cin >> mat2choice;
switch(mat2choice)
{
case 1: B = B.SortedMatrix();
break;
case 2: B = B.RandMatrix();
}
// printf("%s\n", "This is your second matrix");
//B.printMatrix();
std::cout << std::endl;
Matrix<double> C(row1, col1);
auto start = std::chrono::system_clock::now();
C = A + B;
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << "s\n";
printf("%s\n", "This is your final matrix");
C.printMatrix();
}
if(choice == 2)
{
printf("%s\n", "Subtraction matrix");
int row1;
int row2;
int col1;
int col2;
int matchoice;
int mat2choice;
printf("%s", "input the size of the row of your first matrix: ");
std::cin >> row1;
printf("%s", "input the size of the column of your first matrix: ");
std::cin >> col1;
Matrix<double> A(row1, col1);
printf("%s", "input 1 for sorted matrix, 2 for rand matrix: ");
std::cin >> matchoice;
switch(matchoice)
{
case 1: A = A.SortedMatrix();
break;
case 2: A = A.RandMatrix();
}
// printf("%s\n", "This is your first matrix");
//A.printMatrix();
std::cout << std::endl;
printf("%s", "input the size of the row of your second matrix: ");
std::cin >> row2;
printf("%s", "input the size of the column of your second matrix: ");
std::cin >> col2;
Matrix<double> B(row2, col2);
printf("%s", "input 1 for sorted matrix, 2 for rand matrix: ");
std::cin >> mat2choice;
switch(mat2choice)
{
case 1: B = B.SortedMatrix();
break;
case 2: B = B.RandMatrix();
}
// printf("%s\n", "This is your second matrix");
//B.printMatrix();
std::cout << std::endl;
Matrix<double> C(row1, col1);
auto start = std::chrono::system_clock::now();
C = A - B;
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << "s\n";
printf("%s\n", "This is your final matrix");
C.printMatrix();
}
if(choice == 3)
{
printf("%s\n", "Multiplication matrix");
int row1;
int row2;
int col1;
int col2;
int matchoice;
int mat2choice;
printf("%s", "input the size of the row of your first matrix: ");
std::cin >> row1;
printf("%s", "input the size of the column of your first matrix: ");
std::cin >> col1;
Matrix<double> A(row1, col1);
printf("%s", "input 1 for sorted matrix, 2 for rand matrix: ");
std::cin >> matchoice;
switch(matchoice)
{
case 1: A = A.SortedMatrix();
break;
case 2: A = A.RandMatrix();
}
// printf("%s\n", "This is your first matrix");
//A.printMatrix();
std::cout << std::endl;
printf("%s", "input the size of the row of your second matrix \n");
printf("REMEMBER!! the number columns of the first matrix needs to match the number of rows of second matrix: ");
std::cin >> row2;
printf("%s", "input the size of the column of your second matrix: ");
std::cin >> col2;
Matrix<double> B(row2, col2);
printf("%s", "input 1 for sorted matrix, 2 for rand matrix: ");
std::cin >> mat2choice;
switch(mat2choice)
{
case 1: B = B.SortedMatrix();
break;
case 2: B = B.RandMatrix();
}
// printf("%s\n", "This is your second matrix");
//B.printMatrix();
std::cout << std::endl;
Matrix<double> C(row1, col2);
auto start = std::chrono::system_clock::now();
C = A * B;
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << "s\n";
printf("%s\n", "This is your final matrix");
C.printMatrix();
}
if(choice == 4)
{
printf("Transpose Matrix \n");
int row;
int col;
printf("%s", "Input the size of the row: ");
std::cin >> row;
printf("%s", "Input the size of the column: ");
std::cin >> col;
Matrix<double> A(row, col);
int matrix;
printf("%s", "Input 1 for sorted matrix, 2 for rand matrix: ");
std::cin >> matrix;
switch(matrix)
{
case 1: A = A.SortedMatrix();
break;
case 2: A = A.RandMatrix();
}
printf("This is the original matrix \n");
A.printMatrix();
A = A.Transpose();
printf("This is the transpose of the matrix \n");
A.printMatrix();
}
if(choice == 5)
{
printf("Inverse Matrix test \n");
int row;
int col;
printf("%s", "Input the size of the row: ");
std::cin >> row;
printf("%s", "Input the size of the column: ");
std::cin >> col;
Matrix<double> A(row, col);
int matrix;
printf("%s", "Input 1 for sorted matrix, 2 for rand matrix: ");
std::cin >> matrix;
switch(matrix)
{
case 1: A = A.SortedMatrix();
break;
case 2: A = A.RandMatrix();
}
printf("This is the original matrix \n");
A.printMatrix();
A = A.Inverse();
printf("This is the transpose of the matrix \n");
A.printMatrix();
}
}while(choice != 6);
}
}while(option != 3);
return 0;
}
|
87385ab4e6d38f79b8210c49c259ca97dc74252f | 2561d4be89aaa8612eae00c0464e48f3e62e3ad8 | /workspace/AGC015/A.cpp | 7ee96688f36d2bf3ce533f9f5f0211585bf1c5f4 | [] | no_license | oirom/atcoder | c9e6791236a75b0efc83868f3356dd4d6768a726 | acba483a55451a8bd9808dbe4188ee12fdd1e374 | refs/heads/master | 2022-03-05T07:30:58.897174 | 2022-02-20T11:42:13 | 2022-02-20T11:42:13 | 249,957,741 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 600 | cpp | A.cpp | #include <bits/stdc++.h>
#define REP(i,n) for (int i=0; i<(n); ++i)
#define REPR(i,n,m) for (int i=(n); i>=(m); --i)
using namespace std;
using LL = long long;
using LD = long double;
using PLL = pair<long long, long long>;
using PLD = pair<long double, long double>;
using VLL = vector<long long>;
using VLD = vector<long double>;
using VPLD = vector<PLD>;
const int INF = numeric_limits<int>::max();
int main() {
LL N, A, B;
cin >> N >> A >> B;
LL rest = N - 2;
LL ans = (A + B + rest * B) - (A + B + rest * A) + 1;
cout << (ans <= 0 ? 0 : ans )<< endl;
return 0;
}
|
64d0872968dce8dfe0b49d1f20e104ade596bf63 | 1a147769cf914f9fa69b0e3df0d3a1f4c73ff13e | /interview_qtn15.cpp | c6deed901507d828ac6a1f68a24165290290d119 | [] | no_license | savitansh/Contest-Programs | ae4c47ba0585eb8771a0013fca50739ca7789371 | 9bedeefe86324566ff736e9bcf3196a87402407b | refs/heads/master | 2021-01-11T11:01:09.811632 | 2015-03-23T00:14:13 | 2015-03-23T00:14:13 | 32,152,472 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 218 | cpp | interview_qtn15.cpp | /*
a sorted array has a subarray reversed. fix the array
*/
#include <iostream>
using namespace std;
int main(){
int arr[10000];
for(int i=1; i<n; i++){
if(arr[i-1] > arr[i]){
while(arr[i-1] > arr[i])
}
}
} |
8041fa46331f0508e710cf27252792365fc36020 | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /dnspod/src/v20210323/model/DescribeRecordFilterListRequest.cpp | 45c9d1cf690e596fc098055ed8e3f751fde97ea1 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 17,330 | cpp | DescribeRecordFilterListRequest.cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/dnspod/v20210323/model/DescribeRecordFilterListRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Dnspod::V20210323::Model;
using namespace std;
DescribeRecordFilterListRequest::DescribeRecordFilterListRequest() :
m_domainHasBeenSet(false),
m_domainIdHasBeenSet(false),
m_subDomainHasBeenSet(false),
m_recordTypeHasBeenSet(false),
m_recordLineHasBeenSet(false),
m_groupIdHasBeenSet(false),
m_keywordHasBeenSet(false),
m_sortFieldHasBeenSet(false),
m_sortTypeHasBeenSet(false),
m_offsetHasBeenSet(false),
m_limitHasBeenSet(false),
m_recordValueHasBeenSet(false),
m_recordStatusHasBeenSet(false),
m_weightBeginHasBeenSet(false),
m_weightEndHasBeenSet(false),
m_mXBeginHasBeenSet(false),
m_mXEndHasBeenSet(false),
m_tTLBeginHasBeenSet(false),
m_tTLEndHasBeenSet(false),
m_updatedAtBeginHasBeenSet(false),
m_updatedAtEndHasBeenSet(false),
m_remarkHasBeenSet(false),
m_isExactSubDomainHasBeenSet(false),
m_projectIdHasBeenSet(false)
{
}
string DescribeRecordFilterListRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_domainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Domain";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_domain.c_str(), allocator).Move(), allocator);
}
if (m_domainIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DomainId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_domainId, allocator);
}
if (m_subDomainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SubDomain";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_subDomain.c_str(), allocator).Move(), allocator);
}
if (m_recordTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RecordType";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_recordType.begin(); itr != m_recordType.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_recordLineHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RecordLine";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_recordLine.begin(); itr != m_recordLine.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_groupIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "GroupId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_groupId.begin(); itr != m_groupId.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetUint64(*itr), allocator);
}
}
if (m_keywordHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Keyword";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_keyword.c_str(), allocator).Move(), allocator);
}
if (m_sortFieldHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SortField";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_sortField.c_str(), allocator).Move(), allocator);
}
if (m_sortTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SortType";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_sortType.c_str(), allocator).Move(), allocator);
}
if (m_offsetHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Offset";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_offset, allocator);
}
if (m_limitHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Limit";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_limit, allocator);
}
if (m_recordValueHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RecordValue";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_recordValue.c_str(), allocator).Move(), allocator);
}
if (m_recordStatusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RecordStatus";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_recordStatus.begin(); itr != m_recordStatus.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_weightBeginHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "WeightBegin";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_weightBegin, allocator);
}
if (m_weightEndHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "WeightEnd";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_weightEnd, allocator);
}
if (m_mXBeginHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "MXBegin";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_mXBegin, allocator);
}
if (m_mXEndHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "MXEnd";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_mXEnd, allocator);
}
if (m_tTLBeginHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TTLBegin";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_tTLBegin, allocator);
}
if (m_tTLEndHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TTLEnd";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_tTLEnd, allocator);
}
if (m_updatedAtBeginHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UpdatedAtBegin";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_updatedAtBegin.c_str(), allocator).Move(), allocator);
}
if (m_updatedAtEndHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UpdatedAtEnd";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_updatedAtEnd.c_str(), allocator).Move(), allocator);
}
if (m_remarkHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Remark";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_remark.c_str(), allocator).Move(), allocator);
}
if (m_isExactSubDomainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "IsExactSubDomain";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_isExactSubDomain, allocator);
}
if (m_projectIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ProjectId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_projectId, allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string DescribeRecordFilterListRequest::GetDomain() const
{
return m_domain;
}
void DescribeRecordFilterListRequest::SetDomain(const string& _domain)
{
m_domain = _domain;
m_domainHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::DomainHasBeenSet() const
{
return m_domainHasBeenSet;
}
uint64_t DescribeRecordFilterListRequest::GetDomainId() const
{
return m_domainId;
}
void DescribeRecordFilterListRequest::SetDomainId(const uint64_t& _domainId)
{
m_domainId = _domainId;
m_domainIdHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::DomainIdHasBeenSet() const
{
return m_domainIdHasBeenSet;
}
string DescribeRecordFilterListRequest::GetSubDomain() const
{
return m_subDomain;
}
void DescribeRecordFilterListRequest::SetSubDomain(const string& _subDomain)
{
m_subDomain = _subDomain;
m_subDomainHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::SubDomainHasBeenSet() const
{
return m_subDomainHasBeenSet;
}
vector<string> DescribeRecordFilterListRequest::GetRecordType() const
{
return m_recordType;
}
void DescribeRecordFilterListRequest::SetRecordType(const vector<string>& _recordType)
{
m_recordType = _recordType;
m_recordTypeHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::RecordTypeHasBeenSet() const
{
return m_recordTypeHasBeenSet;
}
vector<string> DescribeRecordFilterListRequest::GetRecordLine() const
{
return m_recordLine;
}
void DescribeRecordFilterListRequest::SetRecordLine(const vector<string>& _recordLine)
{
m_recordLine = _recordLine;
m_recordLineHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::RecordLineHasBeenSet() const
{
return m_recordLineHasBeenSet;
}
vector<uint64_t> DescribeRecordFilterListRequest::GetGroupId() const
{
return m_groupId;
}
void DescribeRecordFilterListRequest::SetGroupId(const vector<uint64_t>& _groupId)
{
m_groupId = _groupId;
m_groupIdHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::GroupIdHasBeenSet() const
{
return m_groupIdHasBeenSet;
}
string DescribeRecordFilterListRequest::GetKeyword() const
{
return m_keyword;
}
void DescribeRecordFilterListRequest::SetKeyword(const string& _keyword)
{
m_keyword = _keyword;
m_keywordHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::KeywordHasBeenSet() const
{
return m_keywordHasBeenSet;
}
string DescribeRecordFilterListRequest::GetSortField() const
{
return m_sortField;
}
void DescribeRecordFilterListRequest::SetSortField(const string& _sortField)
{
m_sortField = _sortField;
m_sortFieldHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::SortFieldHasBeenSet() const
{
return m_sortFieldHasBeenSet;
}
string DescribeRecordFilterListRequest::GetSortType() const
{
return m_sortType;
}
void DescribeRecordFilterListRequest::SetSortType(const string& _sortType)
{
m_sortType = _sortType;
m_sortTypeHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::SortTypeHasBeenSet() const
{
return m_sortTypeHasBeenSet;
}
uint64_t DescribeRecordFilterListRequest::GetOffset() const
{
return m_offset;
}
void DescribeRecordFilterListRequest::SetOffset(const uint64_t& _offset)
{
m_offset = _offset;
m_offsetHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::OffsetHasBeenSet() const
{
return m_offsetHasBeenSet;
}
uint64_t DescribeRecordFilterListRequest::GetLimit() const
{
return m_limit;
}
void DescribeRecordFilterListRequest::SetLimit(const uint64_t& _limit)
{
m_limit = _limit;
m_limitHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::LimitHasBeenSet() const
{
return m_limitHasBeenSet;
}
string DescribeRecordFilterListRequest::GetRecordValue() const
{
return m_recordValue;
}
void DescribeRecordFilterListRequest::SetRecordValue(const string& _recordValue)
{
m_recordValue = _recordValue;
m_recordValueHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::RecordValueHasBeenSet() const
{
return m_recordValueHasBeenSet;
}
vector<string> DescribeRecordFilterListRequest::GetRecordStatus() const
{
return m_recordStatus;
}
void DescribeRecordFilterListRequest::SetRecordStatus(const vector<string>& _recordStatus)
{
m_recordStatus = _recordStatus;
m_recordStatusHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::RecordStatusHasBeenSet() const
{
return m_recordStatusHasBeenSet;
}
uint64_t DescribeRecordFilterListRequest::GetWeightBegin() const
{
return m_weightBegin;
}
void DescribeRecordFilterListRequest::SetWeightBegin(const uint64_t& _weightBegin)
{
m_weightBegin = _weightBegin;
m_weightBeginHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::WeightBeginHasBeenSet() const
{
return m_weightBeginHasBeenSet;
}
uint64_t DescribeRecordFilterListRequest::GetWeightEnd() const
{
return m_weightEnd;
}
void DescribeRecordFilterListRequest::SetWeightEnd(const uint64_t& _weightEnd)
{
m_weightEnd = _weightEnd;
m_weightEndHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::WeightEndHasBeenSet() const
{
return m_weightEndHasBeenSet;
}
uint64_t DescribeRecordFilterListRequest::GetMXBegin() const
{
return m_mXBegin;
}
void DescribeRecordFilterListRequest::SetMXBegin(const uint64_t& _mXBegin)
{
m_mXBegin = _mXBegin;
m_mXBeginHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::MXBeginHasBeenSet() const
{
return m_mXBeginHasBeenSet;
}
uint64_t DescribeRecordFilterListRequest::GetMXEnd() const
{
return m_mXEnd;
}
void DescribeRecordFilterListRequest::SetMXEnd(const uint64_t& _mXEnd)
{
m_mXEnd = _mXEnd;
m_mXEndHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::MXEndHasBeenSet() const
{
return m_mXEndHasBeenSet;
}
uint64_t DescribeRecordFilterListRequest::GetTTLBegin() const
{
return m_tTLBegin;
}
void DescribeRecordFilterListRequest::SetTTLBegin(const uint64_t& _tTLBegin)
{
m_tTLBegin = _tTLBegin;
m_tTLBeginHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::TTLBeginHasBeenSet() const
{
return m_tTLBeginHasBeenSet;
}
uint64_t DescribeRecordFilterListRequest::GetTTLEnd() const
{
return m_tTLEnd;
}
void DescribeRecordFilterListRequest::SetTTLEnd(const uint64_t& _tTLEnd)
{
m_tTLEnd = _tTLEnd;
m_tTLEndHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::TTLEndHasBeenSet() const
{
return m_tTLEndHasBeenSet;
}
string DescribeRecordFilterListRequest::GetUpdatedAtBegin() const
{
return m_updatedAtBegin;
}
void DescribeRecordFilterListRequest::SetUpdatedAtBegin(const string& _updatedAtBegin)
{
m_updatedAtBegin = _updatedAtBegin;
m_updatedAtBeginHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::UpdatedAtBeginHasBeenSet() const
{
return m_updatedAtBeginHasBeenSet;
}
string DescribeRecordFilterListRequest::GetUpdatedAtEnd() const
{
return m_updatedAtEnd;
}
void DescribeRecordFilterListRequest::SetUpdatedAtEnd(const string& _updatedAtEnd)
{
m_updatedAtEnd = _updatedAtEnd;
m_updatedAtEndHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::UpdatedAtEndHasBeenSet() const
{
return m_updatedAtEndHasBeenSet;
}
string DescribeRecordFilterListRequest::GetRemark() const
{
return m_remark;
}
void DescribeRecordFilterListRequest::SetRemark(const string& _remark)
{
m_remark = _remark;
m_remarkHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::RemarkHasBeenSet() const
{
return m_remarkHasBeenSet;
}
bool DescribeRecordFilterListRequest::GetIsExactSubDomain() const
{
return m_isExactSubDomain;
}
void DescribeRecordFilterListRequest::SetIsExactSubDomain(const bool& _isExactSubDomain)
{
m_isExactSubDomain = _isExactSubDomain;
m_isExactSubDomainHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::IsExactSubDomainHasBeenSet() const
{
return m_isExactSubDomainHasBeenSet;
}
int64_t DescribeRecordFilterListRequest::GetProjectId() const
{
return m_projectId;
}
void DescribeRecordFilterListRequest::SetProjectId(const int64_t& _projectId)
{
m_projectId = _projectId;
m_projectIdHasBeenSet = true;
}
bool DescribeRecordFilterListRequest::ProjectIdHasBeenSet() const
{
return m_projectIdHasBeenSet;
}
|
81429ca6c157220302eb53a709b4c22d0c2b040d | 95b2e0ec3fabae7b3483748e583b72dfe8b77063 | /Source/Libraries/Core/String.cpp | 2503b91c01b2c8aa800918b289350f653f43fa7c | [] | no_license | chrrs/core | db215d4c7a4d358025a1ad43d8139b5e82f7b5bd | 3ff67185d8c61996ea485f6cd0da0731c51ece8c | refs/heads/master | 2023-01-13T23:36:44.682912 | 2020-11-17T19:54:33 | 2020-11-17T19:54:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,632 | cpp | String.cpp | #include <Core/Assert.h>
#include <Core/String.h>
#include <Core/StringView.h>
#include <string.h>
String::String()
: m_inner(nullptr)
, m_length(0)
{
}
String::String(const char* c_string)
: m_length(strlen(c_string))
{
m_inner = new char[m_length];
memcpy(m_inner, c_string, m_length);
}
String::String(const char* c_string, size_t length)
: m_inner(new char[length])
, m_length(length)
{
memcpy(m_inner, c_string, m_length);
}
String::String(const StringView& string_view)
: m_length(string_view.length())
{
m_inner = new char[m_length];
memcpy(m_inner, string_view.data(), m_length);
}
String::String(const String& other)
: m_length(other.m_length)
{
if (other.m_inner != nullptr) {
m_inner = new char[m_length];
memcpy(m_inner, other.m_inner, m_length);
} else {
m_inner = nullptr;
}
}
String::String(String&& other)
{
m_inner = other.m_inner;
m_length = other.m_length;
other.m_inner = nullptr;
other.m_length = 0;
}
String& String::operator=(const String& other)
{
if (&other == this) {
return *this;
}
delete[] m_inner;
m_length = other.m_length;
if (other.m_inner != nullptr) {
m_inner = new char[m_length];
memcpy(m_inner, other.m_inner, m_length);
} else {
m_inner = nullptr;
}
return *this;
}
String& String::operator=(String&& other)
{
if (&other == this) {
return *this;
}
delete[] m_inner;
m_inner = other.m_inner;
m_length = other.m_length;
other.m_inner = nullptr;
other.m_length = 0;
return *this;
}
String& String::operator=(const char* c_string)
{
delete[] m_inner;
m_length = strlen(c_string);
m_inner = new char[m_length];
memcpy(m_inner, c_string, m_length);
return *this;
}
String::~String()
{
delete[] m_inner;
}
bool String::operator==(const char* other) const
{
if (m_length != strlen(other)) {
return false;
}
return !strncmp(m_inner, other, m_length);
}
bool String::operator!=(const char* other) const
{
return !(*this == other);
}
bool String::operator==(const StringView& other) const
{
if (m_length != other.length()) {
return false;
}
return !strncmp(m_inner, other.data(), m_length);
}
bool String::operator!=(const StringView& other) const
{
return !(*this == other);
}
bool String::operator==(const String& other) const
{
if (m_length != other.length()) {
return false;
}
return !strncmp(m_inner, other.data(), m_length);
}
bool String::operator!=(const String& other) const
{
return !(*this == other);
}
size_t String::length() const
{
return m_length;
}
bool String::is_null() const
{
return m_inner == nullptr;
}
const char* String::data() const
{
return m_inner;
}
String String::substring(size_t start, size_t length) const
{
ASSERT(!is_null(), "can't take substring of a null string");
ASSERT(start + length <= m_length, "substring out of range");
return String(m_inner + start, length);
}
StringView String::substring_view(size_t start, size_t length) const
{
ASSERT(start + length <= m_length, "substring out of range");
return StringView(m_inner + start, length);
}
Vector<String> String::split(char delim, bool ignore_empty) const
{
(void)ignore_empty;
Vector<String> out;
// FIXME: Change this to a for each loop sometime?
size_t start = 0;
for (size_t i = 0; i < m_length; ++i) {
char current = m_inner[i];
if (current == delim) {
if (!ignore_empty || start != i) {
out.append(substring(start, i - start));
}
start = i + 1;
}
}
out.append(substring(start, m_length - start));
return out;
}
Vector<StringView> String::split_view(char delim, bool ignore_empty) const
{
(void)ignore_empty;
Vector<StringView> out;
// FIXME: Change this to a for each loop sometime?
size_t start = 0;
for (size_t i = 0; i < m_length; ++i) {
char current = m_inner[i];
if (current == delim) {
if (!ignore_empty || start != i) {
out.append(substring_view(start, i - start));
}
start = i + 1;
}
}
if (!ignore_empty || start != m_length) {
out.append(substring_view(start, m_length - start));
}
return out;
}
std::ostream& operator<<(std::ostream& stream, const String& string)
{
for (size_t i = 0; i < string.length(); ++i) {
stream << string.m_inner[i];
}
return stream;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.