blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905 values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 115 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
404d6c32fd83d186299a0bf7d2ef761ddb2bbd6f | b58bdf4f49514654c68cbf8f297c87b3230161b3 | /serial.cpp | 2025dc771b1e368dd17aa638f727cf16839612f7 | [] | no_license | ekoeppen/serial-legacy | f8cec3682fbb9a949d6da066b87fa1b2ccb60463 | 4caa27772010b2989b3a970395ae87b1a76504f7 | refs/heads/master | 2021-05-26T12:26:49.921234 | 2013-03-06T19:38:57 | 2013-03-06T19:38:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,290 | cpp | // On Windows under cygwin, try /dev/comNN, where NN is 0, 1, 2, etc
// GUC-232A came up as /dev/com4 just now (I think)
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <stdlib.h>
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <errno.h> /* Error number definitions */
#include <sys/types.h>
#include <sys/time.h>
unsigned char buf[512];
unsigned baudMapping[][2] = {
{0 , B0 },
{50 , B50 },
{75 , B75 },
{110 , B110 },
{134 , B134 },
{150 , B150 },
{200 , B200 },
{300 , B300 },
{600 , B600 },
{1200 , B1200 },
{1800 , B1800 },
{2400 , B2400 },
{4800 , B4800 },
{9600 , B9600 },
{19200 , B19200 },
{38400 , B38400 },
{57600 , B57600 },
{115200 , B115200 },
{230400 , B230400 },
};
int baudMappingCount = sizeof(baudMapping) / sizeof(baudMapping[0]);
char presetNames[10][512];
char presetStrings[10][16384]; // should probably use std::string
void usage(char *progname)
{
fprintf(stderr, "\n");
fprintf(stderr, "serial v1.0 by Brad Grantham, grantham@plunk.org\n\n");
fprintf(stderr, "usage: %s serialportfile baud\n", progname);
fprintf(stderr, "e.g.: %s /dev/ttyS0 38400\n", progname);
fprintf(stderr, "\n\nThe file $HOME/.serial (%s/.serial in your specific case) can also\n", getenv("HOME"));
fprintf(stderr, "contain 10 string presets which are emitted when pressing \"~\" (tilde)\n");
fprintf(stderr, "followed by one of the keys \"1\" through \"0\".\n");
fprintf(stderr, "This file contains one preset per line, of the format:\n");
fprintf(stderr, "\n name-of-preset preset-string-here\n");
fprintf(stderr, "\nThe preset string itself can contain spaces and also can contain embedded\n");
fprintf(stderr, "newlines in the form \"\\n\". Here's a short example file:\n");
fprintf(stderr, "\n restart-device reboot\\n\n");
fprintf(stderr, " initiate-connection telnet distant-machine\\nexport DISPLAY=flebbenge:0\\n\n");
fprintf(stderr, "\nPressing \"~\" then 1 will send \"reboot\" and a newline over the serial port.\n");
fprintf(stderr, "Pressing \"~\" then 2 will send \"telnet distant-machine\" over the serial\n");
fprintf(stderr, "port, then a newline, then \"export DISPLAY=flebbenge:0\", and then\n");
fprintf(stderr, "another newline.\n");
fprintf(stderr, "When running, press \"~\" (tilde) and then \"h\" for some help.\n");
fprintf(stderr, "\n");
}
void readPresetStrings(void)
{
FILE *presetFile;
char presetName[FILENAME_MAX];
char stringbuf[16384];
for(int i = 0; i < 10; i++)
presetStrings[i][0] = '\0';
sprintf(presetName, "%s/.serial", getenv("HOME"));
presetFile = fopen(presetName, "r");
if(presetFile == NULL) {
fprintf(stderr, "couldn't open preset strings file \"%s\"\n", presetName);
fprintf(stderr, "proceeding without preset strings.\n");
} else {
for(int i = 0; i < 10; i++) {
int which = (i + 1) % 10;
if(fscanf(presetFile, "%s ", presetNames[which]) != 1)
break;
if(fgets(stringbuf, sizeof(stringbuf) - 1, presetFile) == NULL) {
fprintf(stderr, "preset for %d (\"%s\") had a name but no string. Ignored.\n", which, presetNames[which]);
break;
}
stringbuf[strlen(stringbuf) - 1] = '\0';
char *dst = presetStrings[which], *src = stringbuf;
while(*src) {
if(src[0] == '\\' && src[1] == 'n') {
*dst++ = '\n';
src += 2;
} else
*dst++ = *src++;
}
*dst++ = '\0';
}
fclose(presetFile);
}
}
int main(int argc, char **argv)
{
int speed;
int duplex = 0, crnl = 0;
int serial;
int tty_in, tty_out;
struct termios options;
struct termios old_termios;
unsigned int baud;
bool done = false;
fd_set reads;
struct timeval timeout;
bool saw_tilde = false;
if(argc < 3) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
if(argv[2][0] < '0' || argv[2][0] > '9') {
usage(argv[0]);
exit(EXIT_FAILURE);
}
readPresetStrings();
baud = (unsigned int) atoi(argv[2]);
int which;
for(which = 0; which < baudMappingCount; which++){
if(baudMapping[which][0] == baud) {
baud = baudMapping[which][1];
break;
}
}
if(which == baudMappingCount) {
fprintf(stderr, "Didn't understand baud rate \"%s\"\n", argv[2]);
exit(EXIT_FAILURE);
}
if(false) printf("baud mapping chosen: %d (0x%X)\n", baud, baud);
tty_in = dup(0);
if(tty_in == -1) {
fprintf(stderr, "Can't open dup of stdin\n");
exit(EXIT_FAILURE);
}
if(fcntl(tty_in, F_SETFL, O_NONBLOCK) == -1) {
fprintf(stderr, "Failed to set nonblocking stdin\n");
exit(EXIT_FAILURE);
}
tty_out = dup(1);
if(tty_out == -1) {
fprintf(stderr, "Can't open dup of stdout\n");
exit(EXIT_FAILURE);
}
serial = open(argv[1], O_RDWR | O_NOCTTY | O_NONBLOCK);
if(serial == -1) {
fprintf(stderr, "Can't open serial port \"%s\"\n", argv[1]);
exit(EXIT_FAILURE);
}
/*
* get the current options of the input tty
*/
tcgetattr(tty_in, &old_termios);
tcgetattr(tty_in, &options);
/*
* set raw input, 1 second timeout
*/
options.c_cflag |= (CLOCAL | CREAD);
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_iflag &= ~INLCR;
options.c_iflag &= ~ICRNL;
/*
* Miscellaneous stuff
*/
options.c_cflag |= (CLOCAL | CREAD); /* Enable receiver, set
* local */
/*
* Linux seems to have problem with the following ??!!
*/
options.c_cflag |= (IXON | IXOFF); /* Software flow control */
options.c_lflag = 0; /* no local flags */
options.c_cflag |= HUPCL; /* Drop DTR on close */
/*
* Clear the line
*/
tcflush(tty_in, TCIFLUSH);
/*
* Update the options synchronously
*/
if (tcsetattr(tty_in, TCSANOW, &options) != 0) {
perror("setting stdin tc");
goto restore;
}
/*
* get the current options of the output tty
*/
tcgetattr(serial, &options);
/*
* set raw input, 1 second timeout
*/
options.c_cflag |= (CLOCAL | CREAD);
options.c_oflag &= ~OPOST;
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;
options.c_iflag &= ~INPCK; /* Enable parity checking */
options.c_iflag |= IGNPAR;
options.c_cflag &= ~PARENB; /* Clear parity enable */
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~CRTSCTS;
options.c_oflag &= ~(IXON | IXOFF | IXANY); /* no flow control */
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST; /* No output processing */
options.c_iflag &= ~INLCR; /* Don't convert linefeeds */
options.c_iflag &= ~ICRNL; /* Don't convert linefeeds */
/*
* Miscellaneous stuff
*/
options.c_cflag |= (CLOCAL | CREAD); /* Enable receiver, set
* local */
/*
* Linux seems to have problem with the following ??!!
*/
options.c_oflag &= ~(IXON | IXOFF | IXANY); /* no flow control */
options.c_lflag = 0; /* no local flags */
options.c_cflag |= HUPCL; /* Drop DTR on close */
cfsetispeed(&options, baud);
speed = cfgetispeed(&options);
if(false) printf("set tty input to speed %d, expected %d\n", speed, baud);
cfsetospeed(&options, baud);
speed = cfgetospeed(&options);
if(false) printf("set tty output to speed %d, expected %d\n", speed, baud);
/*
* Clear the line
*/
tcflush(serial, TCIFLUSH);
if (tcsetattr(serial, TCSANOW, &options) != 0) {
perror("setting serial tc");
goto restore;
}
tcflush(serial, TCIFLUSH);
printf("press \"~\" (tilde) and then \"h\" for some help.\n");
while(!done) {
FD_ZERO(&reads);
FD_SET(serial, &reads);
FD_SET(tty_in, &reads);
timeout.tv_sec = 0;
timeout.tv_usec = 500000;
int result = select(FD_SETSIZE, &reads, NULL, NULL, &timeout);
if(result < 0) {
perror("select");
done = true;
continue;
} else if(result == 0) {
if(false) printf("select timed out.\n");
} else {
for(int i = 0 ; i < FD_SETSIZE; i++) {
if(FD_ISSET(i, &reads)) {
if(false) printf("read on %d\n", i);
}
}
if(FD_ISSET(serial, &reads)) {
if(false) printf("Read from serial\n");
int byte_count = read(serial, buf, sizeof(buf));
if(byte_count == 0) {
fprintf(stderr, "unknown read of 0 bytes!\n");
done = true;
continue;
}
write(tty_out, buf, byte_count);
}
if(FD_ISSET(tty_in, &reads)) {
if(false) printf("Read from TTY\n");
int byte_count = read(tty_in, buf, sizeof(buf));
if(saw_tilde) {
if(buf[0] == 'h' || buf[0] == '?') {
printf("key help:\n");
printf(" . - exit\n");
printf(" d - toggle duplex\n");
printf(" n - toggle whether to send CR with NL\n");
printf(" 0-9 - send preset strings from ~/.serial\n");
int i;
for(i = 0; i < 10; i++) {
int which = (i + 1) % 10;
if(presetStrings[which][0] == '\0')
break;
printf(" %d : \"%s\"\n", which, presetNames[which]);
}
if(i == 0)
printf(" (no preset strings)\n");
printf(" p - print contents of presets\n");
saw_tilde = false;
continue;
} else if(buf[0] >= '0' && buf[0] <= '9') {
int which = buf[0] - '0';
write(serial, presetStrings[which], strlen(presetStrings[which]));
saw_tilde = false;
continue;
} else if(buf[0] == 'p') {
printf("preset strings from ~/.serial:\n");
int i;
for(i = 0; i < 10; i++) {
int which = (i + 1) % 10;
if(presetStrings[which][0] == '\0')
break;
printf(" %d, \"%15s\", : \"%s\"\n", which, presetNames[which], presetStrings[which]);
}
if(i == 0)
printf(" (no preset strings)\n");
saw_tilde = false;
continue;
} else if(buf[0] == '.') {
done = true;
saw_tilde = false;
continue;
} else if(buf[0] == 'd') {
duplex = !duplex;
saw_tilde = false;
continue;
} else if(buf[0] == 'n') {
crnl = !crnl;
tcgetattr(serial, &options);
if(crnl)
options.c_iflag |= ICRNL;
else
options.c_iflag &= ~ICRNL;
tcsetattr(serial, TCSANOW, &options);
tcgetattr(tty_out, &options);
if(crnl)
options.c_oflag |= OCRNL;
else
options.c_oflag &= ~OCRNL;
tcsetattr(tty_out, TCSANOW, &options);
continue;
saw_tilde = false;
}
} else if(buf[0] == '~') {
saw_tilde = true;
continue; /* ick */
} else
saw_tilde = false;
if(byte_count == 0) {
fprintf(stderr, "unknown read of 0 bytes!\n");
done = true;
continue;
}
if(false) printf("writing %d bytes: '%c', %d\n", byte_count, buf[0], buf[0]);
write(serial, buf, byte_count);
if(duplex)
write(tty_out, buf, byte_count);
}
}
}
restore:
if (tcsetattr(tty_in, TCSANOW, &old_termios) != 0) {
perror("restoring stdin");
return (0);
}
close(serial);
close(tty_in);
close(tty_out);
return 0;
}
| [
"eck@40hz.org"
] | eck@40hz.org |
2dbc0d214ce64cabe291b67304188d534750e63c | 2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0 | /fuzzedpackages/multinet/src/eigen3/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceThreadPool.h | 635cbe1cb3bcc944c099798584fb2d4da96b6c0c | [] | no_license | akhikolla/testpackages | 62ccaeed866e2194652b65e7360987b3b20df7e7 | 01259c3543febc89955ea5b79f3a08d3afe57e95 | refs/heads/master | 2023-02-18T03:50:28.288006 | 2021-01-18T13:23:32 | 2021-01-18T13:23:32 | 329,981,898 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,928 | h | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#if defined(EIGEN_USE_THREADS) && !defined(EIGEN_CXX11_TENSOR_TENSOR_DEVICE_THREAD_POOL_H)
#define EIGEN_CXX11_TENSOR_TENSOR_DEVICE_THREAD_POOL_H
namespace Eigen {
// Use the SimpleThreadPool by default. We'll switch to the new non blocking
// thread pool later.
#ifndef EIGEN_USE_SIMPLE_THREAD_POOL
template <typename Env> using ThreadPoolTempl = NonBlockingThreadPoolTempl<Env>;
typedef NonBlockingThreadPool ThreadPool;
#else
template <typename Env> using ThreadPoolTempl = SimpleThreadPoolTempl<Env>;
typedef SimpleThreadPool ThreadPool;
#endif
// Barrier is an object that allows one or more threads to wait until
// Notify has been called a specified number of times.
class Barrier
{
public:
Barrier(unsigned int count) : state_(count << 1), notified_(false)
{
eigen_assert(((count << 1) >> 1) == count);
}
~Barrier()
{
eigen_assert((state_>>1) == 0);
}
void
Notify()
{
unsigned int v = state_.fetch_sub(2, std::memory_order_acq_rel) - 2;
if (v != 1)
{
eigen_assert(((v + 2) & ~1) != 0);
return; // either count has not dropped to 0, or waiter is not waiting
}
std::unique_lock<std::mutex> l(mu_);
eigen_assert(!notified_);
notified_ = true;
cv_.notify_all();
}
void
Wait()
{
unsigned int v = state_.fetch_or(1, std::memory_order_acq_rel);
if ((v >> 1) == 0)
{
return;
}
std::unique_lock<std::mutex> l(mu_);
while (!notified_)
{
cv_.wait(l);
}
}
private:
std::mutex mu_;
std::condition_variable cv_;
std::atomic<unsigned int> state_; // low bit is waiter flag
bool notified_;
};
// Notification is an object that allows a user to to wait for another
// thread to signal a notification that an event has occurred.
//
// Multiple threads can wait on the same Notification object,
// but only one caller must call Notify() on the object.
struct Notification : Barrier
{
Notification() : Barrier(1) {};
};
// Runs an arbitrary function and then calls Notify() on the passed in
// Notification.
template <typename Function, typename... Args> struct FunctionWrapperWithNotification
{
static void
run(Notification* n, Function f, Args... args)
{
f(args...);
if (n)
{
n->Notify();
}
}
};
template <typename Function, typename... Args> struct FunctionWrapperWithBarrier
{
static void
run(Barrier* b, Function f, Args... args)
{
f(args...);
if (b)
{
b->Notify();
}
}
};
template <typename SyncType>
static EIGEN_STRONG_INLINE void
wait_until_ready(SyncType* n)
{
if (n)
{
n->Wait();
}
}
// Build a thread pool device on top the an existing pool of threads.
struct ThreadPoolDevice
{
// The ownership of the thread pool remains with the caller.
ThreadPoolDevice(ThreadPoolInterface* pool, int num_cores) : pool_(pool), num_threads_(num_cores) { }
EIGEN_STRONG_INLINE void*
allocate(size_t num_bytes) const
{
return internal::aligned_malloc(num_bytes);
}
EIGEN_STRONG_INLINE void
deallocate(void* buffer) const
{
internal::aligned_free(buffer);
}
EIGEN_STRONG_INLINE void
memcpy(void* dst, const void* src, size_t n) const
{
::memcpy(dst, src, n);
}
EIGEN_STRONG_INLINE void
memcpyHostToDevice(void* dst, const void* src, size_t n) const
{
memcpy(dst, src, n);
}
EIGEN_STRONG_INLINE void
memcpyDeviceToHost(void* dst, const void* src, size_t n) const
{
memcpy(dst, src, n);
}
EIGEN_STRONG_INLINE void
memset(void* buffer, int c, size_t n) const
{
::memset(buffer, c, n);
}
EIGEN_STRONG_INLINE int
numThreads() const
{
return num_threads_;
}
EIGEN_STRONG_INLINE size_t
firstLevelCacheSize() const
{
return l1CacheSize();
}
EIGEN_STRONG_INLINE size_t
lastLevelCacheSize() const
{
// The l3 cache size is shared between all the cores.
return l3CacheSize() / num_threads_;
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int
majorDeviceVersion() const
{
// Should return an enum that encodes the ISA supported by the CPU
return 1;
}
template <class Function, class... Args>
EIGEN_STRONG_INLINE Notification*
enqueue(Function&& f, Args&&... args) const
{
Notification* n = new Notification();
pool_->Schedule(std::bind(&FunctionWrapperWithNotification<Function, Args...>::run, n, f, args...));
return n;
}
template <class Function, class... Args>
EIGEN_STRONG_INLINE void
enqueue_with_barrier(Barrier* b,
Function&& f,
Args&&... args) const
{
pool_->Schedule(std::bind(
&FunctionWrapperWithBarrier<Function, Args...>::run, b, f, args...));
}
template <class Function, class... Args>
EIGEN_STRONG_INLINE void
enqueueNoNotification(Function&& f, Args&&... args) const
{
pool_->Schedule(std::bind(f, args...));
}
// Returns a logical thread index between 0 and pool_->NumThreads() - 1 if
// called from one of the threads in pool_. Returns -1 otherwise.
EIGEN_STRONG_INLINE int
currentThreadId() const
{
return pool_->CurrentThreadId();
}
// parallelFor executes f with [0, n) arguments in parallel and waits for
// completion. F accepts a half-open interval [first, last).
// Block size is choosen based on the iteration cost and resulting parallel
// efficiency. If block_align is not nullptr, it is called to round up the
// block size.
void
parallelFor(Index n, const TensorOpCost& cost,
std::function<Index(Index)> block_align,
std::function<void(Index, Index)> f) const
{
typedef TensorCostModel<ThreadPoolDevice> CostModel;
if (n <= 1 || numThreads() == 1 ||
CostModel::numThreads(n, cost, static_cast<int>(numThreads())) == 1)
{
f(0, n);
return;
}
// Calculate block size based on (1) the iteration cost and (2) parallel
// efficiency. We want blocks to be not too small to mitigate
// parallelization overheads; not too large to mitigate tail
// effect and potential load imbalance and we also want number
// of blocks to be evenly dividable across threads.
double block_size_f = 1.0 / CostModel::taskSize(1, cost);
Index block_size = numext::mini(n, numext::maxi<Index>(1, block_size_f));
const Index max_block_size =
numext::mini(n, numext::maxi<Index>(1, 2 * block_size_f));
if (block_align)
{
Index new_block_size = block_align(block_size);
eigen_assert(new_block_size >= block_size);
block_size = numext::mini(n, new_block_size);
}
Index block_count = divup(n, block_size);
// Calculate parallel efficiency as fraction of total CPU time used for
// computations:
double max_efficiency =
static_cast<double>(block_count) /
(divup<int>(block_count, numThreads()) * numThreads());
// Now try to increase block size up to max_block_size as long as it
// doesn't decrease parallel efficiency.
for (Index prev_block_count = block_count; prev_block_count > 1;)
{
// This is the next block size that divides size into a smaller number
// of blocks than the current block_size.
Index coarser_block_size = divup(n, prev_block_count - 1);
if (block_align)
{
Index new_block_size = block_align(coarser_block_size);
eigen_assert(new_block_size >= coarser_block_size);
coarser_block_size = numext::mini(n, new_block_size);
}
if (coarser_block_size > max_block_size)
{
break; // Reached max block size. Stop.
}
// Recalculate parallel efficiency.
const Index coarser_block_count = divup(n, coarser_block_size);
eigen_assert(coarser_block_count < prev_block_count);
prev_block_count = coarser_block_count;
const double coarser_efficiency =
static_cast<double>(coarser_block_count) /
(divup<int>(coarser_block_count, numThreads()) * numThreads());
if (coarser_efficiency + 0.01 >= max_efficiency)
{
// Taking it.
block_size = coarser_block_size;
block_count = coarser_block_count;
if (max_efficiency < coarser_efficiency)
{
max_efficiency = coarser_efficiency;
}
}
}
// Recursively divide size into halves until we reach block_size.
// Division code rounds mid to block_size, so we are guaranteed to get
// block_count leaves that do actual computations.
Barrier barrier(static_cast<unsigned int>(block_count));
std::function<void(Index, Index)> handleRange;
handleRange = [=, &handleRange, &barrier, &f](Index first, Index last)
{
if (last - first <= block_size)
{
// Single block or less, execute directly.
f(first, last);
barrier.Notify();
return;
}
// Split into halves and submit to the pool.
Index mid = first + divup((last - first) / 2, block_size) * block_size;
pool_->Schedule([=, &handleRange]()
{
handleRange(mid, last);
});
pool_->Schedule([=, &handleRange]()
{
handleRange(first, mid);
});
};
handleRange(0, n);
barrier.Wait();
}
// Convenience wrapper for parallelFor that does not align blocks.
void
parallelFor(Index n, const TensorOpCost& cost,
std::function<void(Index, Index)> f) const
{
parallelFor(n, cost, nullptr, std::move(f));
}
private:
ThreadPoolInterface* pool_;
int num_threads_;
};
} // end namespace Eigen
#endif // EIGEN_CXX11_TENSOR_TENSOR_DEVICE_THREAD_POOL_H
| [
"akhilakollasrinu424jf@gmail.com"
] | akhilakollasrinu424jf@gmail.com |
8b91c9c88a3c5f0dcfc5f1635bd225e4f490fc4e | fcb52aa59832f7db99ae516f50bd89ab65e35fbb | /zjw_pcsRLGR.cpp | 409fa35dde8e2b0140f7da337efbc4b0b3d71371 | [] | no_license | kingzjw/pcs | 1716380c3e89822d36725beda880f6e870fbadd1 | a8decb17b8b7150c175ce0a0d38a1f52b1202bae | refs/heads/master | 2020-03-16T15:23:08.444984 | 2018-10-06T04:11:16 | 2018-10-06T04:11:16 | 132,741,388 | 5 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,551 | cpp | #include "zjw_pcsRLGR.h"
PCS_RLGR::PCS_RLGR(VectorXd * mvSignal, Eigen::SparseMatrix<double>* lapMat)
{
//RLGR论文中有提到 stepSize deta from 0.01 - 1 范围。越低,保真度越高。
stepSize = 0.001;
this->mvSignal = mvSignal;
this->spLaplacian = lapMat;
}
PCS_RLGR::~PCS_RLGR()
{
}
void PCS_RLGR::rlgr_mv_compress()
{
inputList.clear();
separateMotionVector();
#ifdef ZJW_DEBUG
cout << "=========================================" << endl;
cout << "start RLGR motion vector compress ...." << endl;
cout << "start gft (include the compute eigen vector )..." << endl;
#endif // ZJW_DEBUG
//mv信号的x,y,z三种信号,分别通过gft处理成gft信号,然后合并
MatrixXd lapMat = MatrixXd(*(spLaplacian));
GFT g = GFT(lapMat);
//---三种信号的结果
//VectorXcd signalGFTTotal;
VectorXcd signalGFTTemp[3];
for (int signal_type = 0; signal_type < 3; signal_type++)
{
VectorXcd signal(mvSignalXYZ[signal_type]);
g.gft(signal, signalGFTTemp[signal_type]);
}
//round stepsize的处理 signalGFT中的内容,转化到numsList中。
for (int i = 0; i < mvSignal->rows() / 3; i++)
{
/*signalGFTTotal(i * 3 + 0) = signalGFTTemp[0](i);
signalGFTTotal(i * 3 + 1) = signalGFTTemp[1](i);
signalGFTTotal(i * 3 + 2) = signalGFTTemp[2](i);*/
//实部和虚部都进行压缩
// 3 * 0
inputList.push_back((int)(signalGFTTemp[0](i).real() / stepSize + 0.5));
inputList.push_back((int)(signalGFTTemp[0](i).imag() / stepSize + 0.5));
// 3 * 1
inputList.push_back((int)(signalGFTTemp[1](i).real() / stepSize + 0.5));
inputList.push_back((int)(signalGFTTemp[1](i).imag() / stepSize + 0.5));
// 3 * 2
inputList.push_back((int)(signalGFTTemp[2](i).real() / stepSize + 0.5));
inputList.push_back((int)(signalGFTTemp[2](i).imag() / stepSize + 0.5));
}
//处理负数
PCS_RLGR::positiveNum(inputList, inputList_u);
#ifdef ZJW_DEBUG
cout << "start encode signal of gft and decode get the signal ....." << endl;
#endif // ZJW_DEBUG
//然后gft信号经过 rlgb处理成 压缩内容。存储在文件中
//rlgr encode and compress to the file
RLGR rlgr = RLGR(&inputList_u, &resList_u);
rlgr.encode();
#ifdef ZJW_DEBUG
cout << "end RLGR motion vector compress !!" << endl;
cout << "=========================================" << endl;
#endif // ZJW_DEBUG
}
VectorXcd PCS_RLGR::rlgr_mv_decompress()
{
resList.clear();
#ifdef ZJW_DEBUG
cout << "=========================================" << endl;
cout << "start RLGR motion vector decompress ...." << endl;
cout << "start RLGR decoding ....." << endl;
#endif // ZJW_DEBUG
//解压数据,恢复成gft信号。解压之后数据再resList中了
RLGR rlgr2 = RLGR(&inputList_u, &resList_u);
rlgr2.decode();
//回复成负数
PCS_RLGR::restoreNum(resList_u, resList);
#ifdef ZJW_DEBUG
cout << "start inverse quantization and igft ....." << endl;
#endif // ZJW_DEBUG
//解压数据,吸纳打包成规定gft signal 的形式,然后gft解析成 原始mv信号
VectorXcd gftDecodeSignal[3];
//x 2表示实部和虚部,3表示三种信号
gftDecodeSignal[0].resize(resList.size() / 2 / 3);
//y
gftDecodeSignal[1].resize(resList.size() / 2 / 3);
//z
gftDecodeSignal[2].resize(resList.size() / 2 / 3);
for (int i = 0; i < gftDecodeSignal[0].size(); i++)
{
gftDecodeSignal[0](i) = complex<double>(resList[(i * 3 + 0) * 2] * stepSize, resList[(i * 3 + 0) * 2 + 1] * stepSize);
gftDecodeSignal[1](i) = complex<double>(resList[(i * 3 + 1) * 2] * stepSize, resList[(i * 3 + 1) * 2 + 1] * stepSize);
gftDecodeSignal[2](i) = complex<double>(resList[(i * 3 + 2) * 2] * stepSize, resList[(i * 3 + 2) * 2 + 1] * stepSize);
}
//存放,igft出来的三种信号结果
VectorXcd mvDecodeSignal[3];
MatrixXd lapMat(*spLaplacian);
GFT g = GFT(lapMat);
//x,y,z三种信号
for (int i = 0; i < 3; i++)
{
g.igft(gftDecodeSignal[i], mvDecodeSignal[i]);
}
//合并三种xyz信号,f_Result的result可能已经从系数变成复数的形式了
VectorXcd mvDecodeResult;
mvDecodeResult.resize(mvDecodeSignal[0].rows() * 3);
for (int i = 0; i < mvDecodeSignal[0].rows(); i++)
{
mvDecodeResult(3 * i + 0) = mvDecodeSignal[0](i);
mvDecodeResult(3 * i + 1) = mvDecodeSignal[1](i);
mvDecodeResult(3 * i + 2) = mvDecodeSignal[2](i);
}
#ifdef ZJW_DEBUG
cout << "end RLGR motion vector compress !!" << endl;
cout << "=========================================" << endl;
#endif // ZJW_DEBUG
return mvDecodeResult;
}
VectorXcd PCS_RLGR::testPCS_RLGR()
{
inputList.clear();
separateMotionVector();
#ifdef ZJW_DEBUG
cout << "=========================================" << endl;
cout << "start RLGR motion vector compress ...." << endl;
cout << "start gft (include the compute eigen vector )..." << endl;
#endif // ZJW_DEBUG
//mv信号的x,y,z三种信号,分别通过gft处理成gft信号,然后合并
MatrixXd lapMat = MatrixXd(*(spLaplacian));
GFT g = GFT(lapMat);
//---三种信号的结果
//VectorXcd signalGFTTotal;
VectorXcd signalGFTTemp[3];
for (int signal_type = 0; signal_type < 3; signal_type++)
{
VectorXcd signal(mvSignalXYZ[signal_type]);
g.gft(signal, signalGFTTemp[signal_type]);
}
//round stepsize的处理 signalGFT中的内容,转化到numsList中。
for (int i = 0; i < mvSignal->rows() / 3; i++)
{
/*signalGFTTotal(i * 3 + 0) = signalGFTTemp[0](i);
signalGFTTotal(i * 3 + 1) = signalGFTTemp[1](i);
signalGFTTotal(i * 3 + 2) = signalGFTTemp[2](i);*/
//实部和虚部都进行压缩
// 3 * 0
inputList.push_back((int)(signalGFTTemp[0](i).real() / stepSize + 0.5));
inputList.push_back((int)(signalGFTTemp[0](i).imag() / stepSize + 0.5));
// 3 * 1
inputList.push_back((int)(signalGFTTemp[1](i).real() / stepSize + 0.5));
inputList.push_back((int)(signalGFTTemp[1](i).imag() / stepSize + 0.5));
// 3 * 2
inputList.push_back((int)(signalGFTTemp[2](i).real() / stepSize + 0.5));
inputList.push_back((int)(signalGFTTemp[2](i).imag() / stepSize + 0.5));
}
//处理负数
PCS_RLGR::positiveNum(inputList, inputList_u);
#ifdef ZJW_DEBUG
cout << "start encode signal of gft and decode get the signal ....." << endl;
#endif // ZJW_DEBUG
//然后gft信号经过 rlgb处理成 压缩内容。存储在文件中
//rlgr encode and compress to the file
RLGR rlgr = RLGR(&inputList_u, &resList_u);
rlgr.encode();
#ifdef ZJW_DEBUG
cout << "end RLGR motion vector compress !!" << endl;
cout << "=========================================" << endl;
#endif // ZJW_DEBUG
resList.clear();
#ifdef ZJW_DEBUG
cout << "=========================================" << endl;
cout << "start RLGR motion vector decompress ...." << endl;
cout << "start RLGR decoding ....." << endl;
#endif // ZJW_DEBUG
//解压数据,恢复成gft信号。解压之后数据再resList中了
RLGR rlgr2 = RLGR(&inputList_u, &resList_u);
rlgr2.decode();
//回复成负数
PCS_RLGR::restoreNum(resList_u, resList);
#ifdef ZJW_DEBUG
cout << "start inverse quantization and igft ....." << endl;
#endif // ZJW_DEBUG
//解压数据,吸纳打包成规定gft signal 的形式,然后gft解析成 原始mv信号
VectorXcd gftDecodeSignal[3];
//x 2表示实部和虚部,3表示三种信号
gftDecodeSignal[0].resize(resList.size() / 2 / 3);
//y
gftDecodeSignal[1].resize(resList.size() / 2 / 3);
//z
gftDecodeSignal[2].resize(resList.size() / 2 / 3);
for (int i = 0; i < gftDecodeSignal[0].size(); i++)
{
gftDecodeSignal[0](i) = complex<double>(resList[(i * 3 + 0) * 2] * stepSize, resList[(i * 3 + 0) * 2 + 1] * stepSize);
gftDecodeSignal[1](i) = complex<double>(resList[(i * 3 + 1) * 2] * stepSize, resList[(i * 3 + 1) * 2 + 1] * stepSize);
gftDecodeSignal[2](i) = complex<double>(resList[(i * 3 + 2) * 2] * stepSize, resList[(i * 3 + 2) * 2 + 1] * stepSize);
}
//存放,igft出来的三种信号结果
VectorXcd mvDecodeSignal[3];
//x,y,z三种信号
for (int i = 0; i < 3; i++)
{
g.igft(gftDecodeSignal[i], mvDecodeSignal[i]);
}
//合并三种xyz信号,f_Result的result可能已经从系数变成复数的形式了
VectorXcd mvDecodeResult;
mvDecodeResult.resize(mvDecodeSignal[0].rows() * 3);
for (int i = 0; i < mvDecodeSignal[0].rows(); i++)
{
mvDecodeResult(3 * i + 0) = mvDecodeSignal[0](i);
mvDecodeResult(3 * i + 1) = mvDecodeSignal[1](i);
mvDecodeResult(3 * i + 2) = mvDecodeSignal[2](i);
}
#ifdef ZJW_DEBUG
cout << "end RLGR motion vector compress !!" << endl;
cout << "=========================================" << endl;
#endif // ZJW_DEBUG
return mvDecodeResult;
}
void PCS_RLGR::positiveNum(vector<int>& sourceDataNegativeList)
{
//RLGR中的论文中有提到,如何处理对有负数的数据。
for (int i = 0; i < sourceDataNegativeList.size(); i++)
{
if (sourceDataNegativeList[i] >= 0)
{
sourceDataNegativeList[i] *= 2;
}
else
{
sourceDataNegativeList[i] *= (-2);
sourceDataNegativeList[i] -= -1;
}
}
}
void PCS_RLGR::restoreNum(vector<int>& resDecodeData)
{
//RLGR中的论文中有提到,如何处理对有负数的数据。
for (int i = 0; i < resDecodeData.size(); i++)
{
if (resDecodeData[i] % 2 == 0)
{
resDecodeData[i] /= 2;
}
else
{
resDecodeData[i] += 1;
resDecodeData[i] /= -2;
}
}
}
void PCS_RLGR::positiveNum(vector<int>& sourceDataNegativeList, vector<uint64_t>& codeData_out)
{
//RLGR中的论文中有提到,如何处理对有负数的数据。
codeData_out.clear();
for (int i = 0; i < sourceDataNegativeList.size(); i++)
{
if (sourceDataNegativeList[i] >= 0)
{
codeData_out.push_back(sourceDataNegativeList[i] * 2);
}
else
{
codeData_out.push_back(sourceDataNegativeList[i] * (-2) - 1);
}
}
}
void PCS_RLGR::restoreNum(vector<uint64_t>& sourceDecodeData, vector<int>& resDecodeData_out)
{
resDecodeData_out.clear();
//RLGR中的论文中有提到,如何处理对有负数的数据。
for (int i = 0; i < sourceDecodeData.size(); i++)
{
if (sourceDecodeData[i] % 2 == 0)
{
resDecodeData_out.push_back(sourceDecodeData[i] / 2);
}
else
{
resDecodeData_out.push_back((sourceDecodeData[i] + 1) / -2);
}
}
}
bool PCS_RLGR::separateMotionVector()
{
//x
mvSignalXYZ[0].resize(mvSignal->rows() / 3);
//y
mvSignalXYZ[1].resize(mvSignal->rows() / 3);
//z
mvSignalXYZ[2].resize(mvSignal->rows() / 3);
for (int i = 0; i < mvSignal->rows() / 3; i++)
{
mvSignalXYZ[0](i) = (*mvSignal)(3 * i);
mvSignalXYZ[1](i) = (*mvSignal)(3 * i + 1);
mvSignalXYZ[2](i) = (*mvSignal)(3 * i + 2);
}
return true;
} | [
"zjwking258@163.com"
] | zjwking258@163.com |
414a28e0887532952ec2aaf56146f2af64a6dbc9 | 98a112e0577d63a48fd826d14d00420e58479a03 | /ejercicios/semaforo_temporizador_funcion/semaforo_temporizador_funcion.ino | 696236e170ceffa98697c4fbfd6fb6cb751bccf4 | [] | no_license | mundostr/itec_arduino2019_c1 | d22b823d30f75ba9577a0707c51cde087761ba65 | 8bd0812b6a37f9acf090603c9955634a2f1e7e63 | refs/heads/master | 2020-05-19T03:24:49.802004 | 2020-02-17T12:25:21 | 2020-02-17T12:25:21 | 184,799,627 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,111 | ino | /*
Reescritura ejercicio semáforo, manteniendo el uso de una función para el manejo de las luces,
pero agregando temporizadores para atender varias tareas al mismo tiempo (por ejemplo, ciclar luces
y estar atentos a la pulsación de un botón).
*/
// Incluimos la librería elapsedMillis, para manejar los temporizadores con una sintaxis más limpia
#include <elapsedMillis.h>
// Definimos las constantes para indicar los pines a utilizar y los tiempos de encendido de cada luz
const byte PIN_RJO = 3;
const byte PIN_VDE = 4;
const byte PIN_AMA = 5;
const int INTERVALO_RJO = 5000;
const int INTERVALO_VDE = 5000;
const int INTERVALO_AMA = 3000;
// Agregamos un par de variables que nos servirán en el loop() para llevar
// un control de qué luz encender, y poder cambiar dinámicamente el tiempo que aguarda el temporizador
byte etapa = 1;
int intervalo = INTERVALO_RJO;
// Creamos un objeto de tipo elapsedMillis para manejar el temporizador
elapsedMillis timer1;
// Esta función simplemente apaga todas las luces y enciende por último la que indiquemos en el argumento "luz"
void gestionarLuz(byte luz) {
digitalWrite(PIN_RJO, LOW);
digitalWrite(PIN_VDE, LOW);
digitalWrite(PIN_AMA, LOW);
digitalWrite(luz, HIGH);
}
void setup() {
// En este caso solo inicializamos los pines de las luces como salida
// no estamos habilitando la consola serial ya que los mismos leds nos
// indican visualmente si el código se está ejecutando de forma correcta.
pinMode(PIN_RJO, OUTPUT);
pinMode(PIN_VDE, OUTPUT);
pinMode(PIN_AMA, OUTPUT);
}
void loop() {
// Continuamente chequeamos si ha transcurrido un intervalo para cambio de luces
// y dentro del propio if(), ajustamos la variable "intervalo" según se necesite.
if (timer1 >= intervalo) {
// "etapa" comienza en 1, nos permite llevar un control de si estamos en la
// etapa del rojo, el verde o el amarillo.
switch (etapa) {
case 1:
// Si etapa está en 1, significa que debemos encender el rojo, por ende
// hacemos un llamado a la función "gestionarLuz()", pasándolo como argumento PIN_RJO
gestionarLuz(PIN_RJO);
// y luego cambiamos intervalo y etapa, para que la próxima vez que el if() genere una
// condición verdadera, el switch() ejecute el case siguiente.
intervalo = INTERVALO_VDE;
etapa = 2;
break;
case 2:
// idem anterior y actualizamos "etapa" e "intervalo" para el amarillo.
gestionarLuz(PIN_VDE);
intervalo = INTERVALO_AMA;
etapa = 3;
break;
case 3:
// idem anterior y actualizamos para retornar a la etapa 1 (rojo).
gestionarLuz(PIN_AMA);
intervalo = INTERVALO_RJO;
etapa = 1;
}
// MUY IMPORTANTE, independientemente de cuál case se ejecute en cada momento, siempre
// que el if() genera una condición verdadera, corremos el código y volvemos el timer
// a cero para dejarlo listo para la próxima iteracción.
timer1 = 0;
}
}
| [
"idux.net@gmail.com"
] | idux.net@gmail.com |
3629132ed27318e7cde173bca215b20be25afb9b | 7f1f2d028a0faa297617a4e2070714891df11688 | /practice/1104ex/mytime3.cpp | 3c92458da1987bcf02e38d78a6c0b2dd7ac4b172 | [] | no_license | mallius/CppPrimerPlus | 3487058a82d74ef0dd0c51b19c9f082b89c0c3f3 | 2a1ca08b4cdda542bb5cda35c8c5cfd903f969eb | refs/heads/master | 2021-01-01T04:12:16.783696 | 2018-03-08T13:49:17 | 2018-03-08T13:49:17 | 58,808,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,162 | cpp | #include <iostream>
#include "mytime3.h"
Time::Time()
{
hours = minutes = 0;
}
Time::Time(int h, int m)
{
hours = h;
minutes = m;
}
void Time::AddMin(int m)
{
minutes+=m;
hours+=minutes / 60;
minutes %=60;
}
void Time::AddHr(int h)
{
hours+=h;
}
void Time::Reset(int h, int m)
{
hours = h;
minutes = m;
}
Time operator+(const Time & t1, const Time & t2)
{
Time sum;
sum.minutes = t1.minutes + t2.minutes;
sum.hours = t1.hours + t2.hours + sum.minutes / 60;
sum.minutes %= 60;
return sum;
}
Time operator-(const Time & t1, const Time & t2)
{
Time diff;
int tot1, tot2;
tot1 = t1.minutes + 60 * t1.hours;
tot2 = t2.minutes + 60 * t2.hours;
diff.minutes = (tot2 - tot1) % 60;
diff.hours = (tot2 - tot1) / 60;
return diff;
}
Time operator*(double mult, const Time & t)
{
Time result;
long totalminutes = t.hours * mult * 60 + t.minutes * mult;
result.hours = totalminutes / 60;
result.minutes = totalminutes % 60;
return result;
}
Time operator*(const Time & t, double mult)
{
return (mult * t);
}
std::ostream & operator<<(std::ostream & os, const Time & t)
{
os << t.hours << " hrs, " << t.minutes << " mins";
return os;
}
| [
"mallius@qq.com"
] | mallius@qq.com |
3920385be3fd5a28ad8284769b5684348fc2d383 | f5243a2ee19c0499444993ba363a8e6703b0b78b | /system/utest/crashlogger/crashlogger-test.cpp | ce66a079c301b3fa8cdb1fb78293f3bb7d6cce23 | [
"BSD-3-Clause",
"MIT"
] | permissive | shreks7/magenta | a5f3d58b12763ee389522303801d950178c41e4b | a6b2c4933b26595631c6e2cf25709b4803a3e7ff | refs/heads/master | 2021-01-01T20:04:39.732925 | 2017-07-29T01:21:50 | 2017-07-29T17:11:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,793 | cpp | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdio.h>
#include <regex.h>
#include <unistd.h>
#include <magenta/processargs.h>
#include <mxtl/unique_ptr.h>
#include <launchpad/launchpad.h>
#include <unittest/unittest.h>
// This should match the value used by crashlogger.
static const uint64_t kSysExceptionKey = 1166444u;
// Helper class for using POSIX regular expressions.
class RegEx {
public:
RegEx(const char* regex_str) {
int err = regcomp(®ex_, regex_str, REG_EXTENDED);
if (err != 0) {
char msg[100];
msg[0] = '\0';
regerror(err, ®ex_, msg, sizeof(msg));
fprintf(stderr, "Regex compilation failed: %s\n", msg);
abort();
}
}
~RegEx() {
regfree(®ex_);
}
bool Matches(const char* str) {
return regexec(®ex_, str, 0, NULL, 0) == 0;
}
private:
regex_t regex_;
};
// This tests the output of crashlogger given a process that crashes. It
// launches a test instance of crashlogger in order to capture its output.
bool test_crash(const char* crasher_arg) {
const char* argv[] = { "/boot/bin/crasher", crasher_arg };
launchpad_t* crasher_lp;
launchpad_create(0, "crash-test", &crasher_lp);
// Make sure we bind an exception port to the process before we start
// it running.
mx_handle_t crasher_proc = launchpad_get_process_handle(crasher_lp);
mx_handle_t exception_port;
ASSERT_EQ(mx_port_create(0, &exception_port), MX_OK);
ASSERT_EQ(mx_task_bind_exception_port(crasher_proc, exception_port,
kSysExceptionKey, 0), MX_OK);
// Launch the crasher process.
launchpad_load_from_file(crasher_lp, argv[0]);
launchpad_clone(crasher_lp, LP_CLONE_ALL);
launchpad_set_args(crasher_lp, countof(argv), argv);
const char* errmsg;
ASSERT_EQ(launchpad_go(crasher_lp, &crasher_proc, &errmsg), MX_OK);
// Launch a test instance of crashlogger.
const char* crashlogger_argv[] = { "/boot/bin/crashlogger" };
launchpad_t* crashlogger_lp;
launchpad_create(0, "crashlogger-test-instance", &crashlogger_lp);
launchpad_load_from_file(crashlogger_lp, crashlogger_argv[0]);
launchpad_clone(crasher_lp, LP_CLONE_ALL);
launchpad_set_args(crashlogger_lp, countof(crashlogger_argv),
crashlogger_argv);
mx_handle_t handles[] = { exception_port };
uint32_t handle_types[] = { PA_HND(PA_USER0, 0) };
launchpad_add_handles(crashlogger_lp, countof(handles), handles,
handle_types);
int pipe_fd;
launchpad_add_pipe(crashlogger_lp, &pipe_fd, STDOUT_FILENO);
mx_handle_t crashlogger_proc;
ASSERT_EQ(launchpad_go(crashlogger_lp, &crashlogger_proc, &errmsg), MX_OK);
// Read crashlogger's output into a buffer. Stop reading when we get
// an end-of-backtrace line which matches the following regular
// expression.
RegEx end_regex("^bt#\\d+: end");
FILE* fp = fdopen(pipe_fd, "r");
uint32_t output_size = 10000;
uint32_t size_read = 0;
mxtl::unique_ptr<char[]> output(new char[output_size]);
for (;;) {
char* line_buf = &output[size_read];
int32_t size_remaining = output_size - size_read;
ASSERT_GT(size_remaining, 1);
if (!fgets(line_buf, size_remaining, fp))
break;
size_read += (uint32_t)strlen(line_buf);
if (end_regex.Matches(line_buf))
break;
}
fclose(fp);
// Check that the output contains backtrace info.
RegEx overall_regex(
"arch: .*\n"
"(dso: id=.* base=.* name=.*\n)+"
"(bt#\\d+: pc 0x.* sp 0x.* \\(.*,0x.*\\))+");
ASSERT_TRUE(overall_regex.Matches(output.get()));
// Clean up.
ASSERT_EQ(mx_object_wait_one(crasher_proc, MX_PROCESS_TERMINATED,
MX_TIME_INFINITE, NULL), MX_OK);
ASSERT_EQ(mx_handle_close(crasher_proc), MX_OK);
ASSERT_EQ(mx_task_kill(crashlogger_proc), MX_OK);
ASSERT_EQ(mx_object_wait_one(crashlogger_proc, MX_PROCESS_TERMINATED,
MX_TIME_INFINITE, NULL), MX_OK);
ASSERT_EQ(mx_handle_close(crashlogger_proc), MX_OK);
return true;
}
bool test_crash_write0() {
BEGIN_TEST;
test_crash("write0");
END_TEST;
}
bool test_crash_stack_overflow() {
BEGIN_TEST;
test_crash("stackov");
END_TEST;
}
BEGIN_TEST_CASE(crashlogger_tests)
RUN_TEST(test_crash_write0)
RUN_TEST(test_crash_stack_overflow)
END_TEST_CASE(crashlogger_tests)
int main(int argc, char** argv) {
bool success = unittest_run_all_tests(argc, argv);
return success ? 0 : -1;
}
| [
"mseaborn@google.com"
] | mseaborn@google.com |
79c593e08994157b33dd24c743d7a3652b3dfa30 | aa646aeef6ffcb0356c91dc97a1cca8b029d94ef | /src/iksdl/Renderer.cpp | ce955d4bcc6bd15db19b0f8269338eda4c626d55 | [
"Zlib"
] | permissive | InternationalKoder/iksdl | 3562ff4322c7da0c85f30a2efd4198dc50c95cde | 066a60b405bab5310a500132b0bd4d82c6476f24 | refs/heads/main | 2023-05-13T16:27:29.203552 | 2021-05-29T21:20:23 | 2021-05-29T21:20:23 | 349,504,332 | 0 | 0 | NOASSERTION | 2021-05-29T21:20:24 | 2021-03-19T17:30:37 | C++ | UTF-8 | C++ | false | false | 2,310 | cpp | /*
* IKSDL - C++ wrapper for SDL
* Copyright (C) 2021 InternationalKoder
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
*/
#include "iksdl/Renderer.hpp"
#include "iksdl/SdlException.hpp"
#include <SDL.h>
#include <string>
namespace iksdl
{
Renderer::Renderer(SDL_Window& window, const RendererOptions& options) :
m_renderer(nullptr)
{
m_renderer = SDL_CreateRenderer(&window, -1, options.m_sdlFlags);
if(m_renderer == nullptr)
throw SdlException(std::string(CREATE_RENDERER_ERROR) + SDL_GetError());
}
Renderer::Renderer(Renderer&& other) :
m_renderer(std::exchange(other.m_renderer, nullptr)),
m_viewport(std::move(other.m_viewport))
{}
Renderer::~Renderer()
{
SDL_DestroyRenderer(m_renderer);
}
Renderer& Renderer::operator=(Renderer&& other)
{
if(this == &other)
return *this;
SDL_DestroyRenderer(m_renderer);
m_renderer = std::exchange(other.m_renderer, nullptr);
m_viewport = std::move(other.m_viewport);
return *this;
}
void Renderer::clear(const Color& clearColor) const
{
SDL_SetRenderDrawColor(m_renderer, clearColor.getRed(), clearColor.getGreen(),
clearColor.getBlue(), clearColor.getAlpha());
SDL_RenderClear(m_renderer);
}
void Renderer::setViewport(const Recti& viewport)
{
m_viewport = { .x = viewport.getX(), .y = viewport.getY(),
.w = viewport.getWidth(), .h = viewport.getHeight() };
SDL_RenderSetViewport(m_renderer, &m_viewport);
}
}
| [
"international_koder@yahoo.com"
] | international_koder@yahoo.com |
49c4c2fefa23371d2f93d7131d87c5c296eb698e | cf8ddfc720bf6451c4ef4fa01684327431db1919 | /SDK/ARKSurvivalEvolved_DinoAttackStateMelee_parameters.hpp | 4893fb174e6231f8610106b14dc8a6b5bb109f96 | [
"MIT"
] | permissive | git-Charlie/ARK-SDK | 75337684b11e7b9f668da1f15e8054052a3b600f | c38ca9925309516b2093ad8c3a70ed9489e1d573 | refs/heads/master | 2023-06-20T06:30:33.550123 | 2021-07-11T13:41:45 | 2021-07-11T13:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 722 | hpp | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_DinoAttackStateMelee_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function DinoAttackStateMelee.DinoAttackStateMelee_C.ExecuteUbergraph_DinoAttackStateMelee
struct UDinoAttackStateMelee_C_ExecuteUbergraph_DinoAttackStateMelee_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
0735e7072e6e2e32dbda8f1e39f0ecbeac626286 | efd67fa3fdac58fd2bf6be94cd52d720f0cd2f25 | /src/parser/Parser.cpp | b2e64ce3920be29f335ebeb0174aacb929ceb186 | [] | no_license | pik694/TKOM-rasph | 22cd129776e836c2217e9eb9f88ba95b8b51e619 | a983cc2a77e8056bc20e4bb58d23cacc72295802 | refs/heads/master | 2020-03-09T03:00:56.247171 | 2018-06-05T21:51:47 | 2018-06-05T21:51:47 | 128,554,959 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,150 | cpp | //
// Created by Piotr Żelazko on 06.05.2018.
//
#include <common/ast/nodes.hpp>
#include "NodesFactory.hpp"
#include "TokenTypesAcceptor.hpp"
using namespace rasph::common::ast;
using namespace rasph::common::tokens;
using namespace rasph::parser;
template<TokenType ... types>
using Acceptor = TokenTypesAcceptor<false, types ...>;
template<TokenType ... types>
using AcceptorErr = TokenTypesAcceptor<true, types ...>;
/// Declatations of specializations
template<>
node_ptr_t Parser::tryParse<nodes::BlockNode>();
template<>
node_ptr_t Parser::tryParse<nodes::ForStatementNode>();
template<>
node_ptr_t Parser::tryParse<nodes::AssignableNode>();
template<>
node_ptr_t Parser::tryParse<nodes::AssignStatementNode>();
template<>
node_ptr_t Parser::tryParse<nodes::IfStatementNode>();
template<>
node_ptr_t Parser::tryParse<nodes::ConditionNode>();
template<>
node_ptr_t Parser::tryParse<nodes::ExpressionNode>();
template<>
node_ptr_t Parser::tryParse<nodes::LiteralNode>();
template<>
node_ptr_t Parser::tryParse<nodes::VariableAssignableNode>();
template<>
node_ptr_t Parser::tryParse<nodes::PeriodicStatement>();
/// PARSING METHODS
template<typename ... Args>
rasph::parser::node_ptr_t rasph::parser::Parser::tryParse() {
return NodesFactory<Args...>(*this)();
}
template<>
rasph::parser::node_ptr_t rasph::parser::Parser::tryParse<>() {
return nullptr;
}
template<>
node_ptr_t Parser::tryParse<nodes::ClassMemberCall>() {
auto ident = Acceptor<TokenType::IDENTIFIER>(*this)();
if (!ident) return nullptr;
if (!Acceptor<TokenType::DOT>(*this)()) {
tokensBuffer_.push_front(ident);
return nullptr;
}
auto memberName = AcceptorErr<TokenType::IDENTIFIER>(*this)();
if (Acceptor<TokenType::PARENTHESIS_LEFT>(*this)()) {
auto methodCall = new nodes::MethodCall(ident->getTextValue(), memberName->getTextValue());
node_ptr_t node = tryParse < nodes::AssignableNode > ();
if (node) {
auto param = cast<nodes::AssignableNode>(std::move(node));
methodCall->addParameter(std::move(param));
while (Acceptor<TokenType::COMMA>(*this)()) {
param = cast<nodes::AssignableNode>(tryParse < nodes::AssignableNode > ());
methodCall->addParameter(std::move(param));
}
}
AcceptorErr<TokenType::PARENTHESIS_RIGHT>(*this)();
return node_ptr_t(methodCall);
}
return node_ptr_t(new nodes::ClassMemberCall(ident->getTextValue(), memberName->getTextValue()));
}
template<>
node_ptr_t Parser::tryParse<nodes::PrimaryExpressionNode>() {
std::unique_ptr<nodes::AssignableNode> node;
node_ptr_t tmp_node;
if (Acceptor<TokenType::PARENTHESIS_LEFT>(*this)()) {
node = cast<nodes::AssignableNode>(tryParse < nodes::ExpressionNode > ());
AcceptorErr<TokenType::PARENTHESIS_RIGHT>(*this)();
} else {
tmp_node = tryParse < nodes::ClassMemberCall, nodes::LiteralNode, nodes::VariableAssignableNode > ();
if (tmp_node) node = cast<nodes::AssignableNode>(std::move(tmp_node));
}
return node ? node_ptr_t(new nodes::PrimaryExpressionNode(std::move(node))) : nullptr;
}
template<>
node_ptr_t Parser::tryParse<nodes::MultiplicativeExpressionNode>() {
auto node = tryParse < nodes::PrimaryExpressionNode > ();
if (!node) return nullptr;
auto expression = new nodes::MultiplicativeExpressionNode(cast<nodes::PrimaryExpressionNode>(std::move(node)));
auto acceptor = Acceptor<TokenType::DIVIDE, TokenType::MULTIPLY>(*this);
std::shared_ptr<Token> token;
while ((token = acceptor())) {
expression->addExpression(token->getType(),
cast<nodes::PrimaryExpressionNode>(tryParse < nodes::PrimaryExpressionNode > ()));
}
return node_ptr_t(expression);
}
template<>
node_ptr_t Parser::tryParse<nodes::ExpressionNode>() {
auto node = tryParse < nodes::MultiplicativeExpressionNode > ();
if (!node) return nullptr;
auto expression = new nodes::ExpressionNode(cast<nodes::MultiplicativeExpressionNode>(std::move(node)));
auto acceptor = Acceptor<TokenType::PLUS, TokenType::MINUS>(*this);
std::shared_ptr<Token> token;
while ((token = acceptor())) {
expression->addExpression(token->getType(), cast<nodes::MultiplicativeExpressionNode>(
tryParse < nodes::MultiplicativeExpressionNode > ()));
}
return node_ptr_t(expression);
}
template<>
node_ptr_t Parser::tryParse<nodes::LiteralNode>() {
auto token = Acceptor<TokenType::TEXT_LITERAL, TokenType::NUM_LITERAL, TokenType::FALSE, TokenType::TRUE>(*this)();
if (!token) return nullptr;
return node_ptr_t(new nodes::LiteralNode(*token));
}
template<>
node_ptr_t Parser::tryParse<nodes::StatementNode>() {
return tryParse < nodes::ClassMemberCall, nodes::BlockNode, nodes::ForStatementNode, nodes::IfStatementNode,
nodes::AssignStatementNode, nodes::PeriodicStatement>
();
}
template<>
node_ptr_t Parser::tryParse<nodes::BlockNode>() {
auto tmpToken = Acceptor<TokenType::CBRACKET_LEFT>(*this)();
if (!tmpToken) return nullptr;
auto block = new nodes::BlockNode();
node_ptr_t node;
while ((node = tryParse < nodes::StatementNode > ())) {
auto statement = cast<nodes::StatementNode>(std::move(node));
block->addStatement(std::move(statement));
}
AcceptorErr<TokenType::CBRACKET_RIGHT>(*this)();
return node_ptr_t(block);
}
template<>
node_ptr_t Parser::tryParse<nodes::ForStatementNode>() {
auto tmpToken = Acceptor<TokenType::FOR>(*this)();
if (!tmpToken) return nullptr;
tmpToken = AcceptorErr<TokenType::IDENTIFIER>(*this)();
std::string iterator = tmpToken->getTextValue();
AcceptorErr<TokenType::IN>(*this)();
auto assignable = cast<nodes::AssignableNode>(tryParse < nodes::AssignableNode > ());
auto block = cast<nodes::BlockNode>(std::move(tryParse < nodes::BlockNode > ()));
return node_ptr_t(new nodes::ForStatementNode(iterator, std::move(assignable), std::move(block)));
}
template<>
node_ptr_t Parser::tryParse<nodes::AssignStatementNode>() {
auto token = Acceptor<TokenType::IDENTIFIER>(*this)();
if (!token) return nullptr;
const std::string ident = token->getTextValue();
AcceptorErr<TokenType::ASSIGN>(*this)();
auto node = cast<nodes::AssignableNode>(tryParse < nodes::AssignableNode > ());
return node_ptr_t(new nodes::AssignStatementNode(ident, std::move(node)));
}
template<>
node_ptr_t Parser::tryParse<nodes::PrimaryConditionNode>() {
bool inverted = false;
auto unary = Acceptor<TokenType::NOT>(*this)();
if (unary) inverted = true;
std::unique_ptr<nodes::AssignableNode> node;
if (Acceptor<TokenType::PARENTHESIS_LEFT>(*this)()) {
node = cast<nodes::AssignableNode>(tryParse < nodes::ConditionNode > ());
AcceptorErr<TokenType::PARENTHESIS_RIGHT>(*this)();
} else {
node = cast<nodes::AssignableNode>(tryParse < nodes::AssignableNode > ());
}
return node_ptr_t(new nodes::PrimaryConditionNode(inverted, std::move(node)));
}
template<>
node_ptr_t Parser::tryParse<nodes::RelationalConditionNode>() {
auto node = tryParse < nodes::PrimaryConditionNode > ();
if (!node) return nullptr;
auto condition = new nodes::RelationalConditionNode(cast<nodes::PrimaryConditionNode>(std::move(node)));
auto token = Acceptor<TokenType::GEQUAL, TokenType::LEQUAL, TokenType::LESS, TokenType::GREATER>(*this)();
if (token) {
condition->addCondition(token->getType(),
cast<nodes::PrimaryConditionNode>(tryParse < nodes::PrimaryConditionNode > ()));
}
return node_ptr_t(condition);
}
template<>
node_ptr_t Parser::tryParse<nodes::EqualityConditionNode>() {
auto node = tryParse < nodes::RelationalConditionNode > ();
if (!node) return nullptr;
auto condition = new nodes::EqualityConditionNode(cast<nodes::RelationalConditionNode>(std::move(node)));
auto token = Acceptor<TokenType::EQUAL, TokenType::NEQUAL>(*this)();
if (token) {
condition->addCondition(token->getType(),
cast<nodes::RelationalConditionNode>(tryParse < nodes::RelationalConditionNode > ()));
}
return node_ptr_t(condition);
}
template<>
node_ptr_t Parser::tryParse<nodes::AndConditionNode>() {
auto node = tryParse < nodes::EqualityConditionNode > ();
if (!node) return nullptr;
auto condition = new nodes::AndConditionNode(cast<nodes::EqualityConditionNode>(std::move(node)));
auto acceptor = Acceptor<TokenType::AND>(*this);
while (acceptor()) {
condition->addCondition(cast<nodes::EqualityConditionNode>(tryParse < nodes::EqualityConditionNode > ()));
}
return node_ptr_t(condition);
}
template<>
node_ptr_t Parser::tryParse<nodes::ConditionNode>() {
auto node = tryParse < nodes::AndConditionNode > ();
if (!node) return nullptr;
auto condition = new nodes::ConditionNode(cast<nodes::AndConditionNode>(std::move(node)));
auto acceptor = Acceptor<TokenType::OR>(*this);
while (acceptor()) {
condition->addCondition(cast<nodes::AndConditionNode>(tryParse < nodes::AndConditionNode > ()));
}
return node_ptr_t(condition);
}
template<>
node_ptr_t Parser::tryParse<nodes::IfStatementNode>() {
if (!Acceptor<TokenType::IF>(*this)()) return nullptr;
auto condition = cast<nodes::ConditionNode>(tryParse < nodes::ConditionNode > ());
auto ifBlock = cast<nodes::BlockNode>(tryParse < nodes::BlockNode > ());
if (!Acceptor<TokenType::ELSE>(*this)())
return node_ptr_t(new nodes::IfStatementNode(std::move(ifBlock), std::move(condition)));
auto elseBlock = cast<nodes::BlockNode>(tryParse < nodes::BlockNode > ());
return node_ptr_t(new nodes::IfStatementNode(std::move(ifBlock), std::move(condition), std::move(elseBlock)));
}
template<>
node_ptr_t Parser::tryParse<nodes::ClassNode>() {
// class
auto tmpToken = peekToken();
if (tmpToken->getType() != TokenType::CLASS) {
unpeekTokens();
return nullptr;
}
// identifier
tmpToken = peekToken();
if (tmpToken->getType() != TokenType::IDENTIFIER) {
throw std::invalid_argument("Could not find class identifier");
}
auto classNode = new nodes::ClassNode(tmpToken->getTextValue());
// {
tmpToken = peekToken();
if (tmpToken->getType() != TokenType::CBRACKET_LEFT) {
throw std::invalid_argument("Could not find \"{\" ");
}
// members
node_ptr_t node;
while ((node = tryParse < nodes::EventMemberNode, nodes::AttributeMemberNode, nodes::MethodMemberNode > ())) {
auto member = std::unique_ptr<nodes::ClassMemberNode>(dynamic_cast<nodes::ClassMemberNode *>(node.get()));
if (!member) throw std::bad_cast();
node.release();
classNode->addNode(std::move(member));
}
tmpToken = peekToken();
if (tmpToken->getType() != TokenType::CBRACKET_RIGHT) {
throw std::invalid_argument("Could not find \"}\" ");
}
popTokens(4);
return std::unique_ptr<ProgramNode>(classNode);
}
template<>
node_ptr_t Parser::tryParse<nodes::EventMemberNode>() {
auto tmpToken = peekToken();
if (tmpToken->getType() != TokenType::EVENT) {
unpeekTokens();
return nullptr;
}
tmpToken = peekToken();
if (tmpToken->getType() != TokenType::IDENTIFIER)
throw std::invalid_argument("Could not find event's identifier");
popTokens(2);
return std::unique_ptr<ProgramNode>(new nodes::EventMemberNode(tmpToken->getTextValue()));
}
template<>
node_ptr_t Parser::tryParse<nodes::AttributeMemberNode>() {
auto tmpToken = peekToken();
if (tmpToken->getType() != TokenType::VAR) {
unpeekTokens();
return nullptr;
}
tmpToken = peekToken();
if (tmpToken->getType() != TokenType::IDENTIFIER)
throw std::invalid_argument("Could not find variable's identifier");
popTokens(2);
return std::unique_ptr<ProgramNode>(new nodes::AttributeMemberNode(tmpToken->getTextValue()));
}
template<>
node_ptr_t Parser::tryParse<nodes::MethodMemberNode>() {
auto tmpToken = peekToken();
if (tmpToken->getType() != TokenType::FUNC) {
unpeekTokens();
return nullptr;
}
tmpToken = peekToken();
if (tmpToken->getType() != TokenType::IDENTIFIER)
throw std::invalid_argument("Could not find functions's identifier");
auto method = new nodes::MethodMemberNode(tmpToken->getTextValue());
tmpToken = peekToken();
if (tmpToken->getType() != TokenType::PARENTHESIS_LEFT)
throw std::invalid_argument("Could not find list of parameters");
tmpToken = peekToken();
if (tmpToken->getType() == TokenType::IDENTIFIER) {
while (true) {
method->addParameter(tmpToken->getTextValue());
popTokens();
tmpToken = peekToken();
if (tmpToken->getType() != TokenType::COMMA) {
unpeekTokens();
break;
}
popTokens();
tmpToken = peekToken();
if (tmpToken->getType() != TokenType::IDENTIFIER) {
throw std::invalid_argument("Expected identifier");
}
}
} else {
unpeekTokens();
}
tmpToken = peekToken();
if (tmpToken->getType() != TokenType::PARENTHESIS_RIGHT)
throw std::invalid_argument("Could not find list of parameters");
tmpToken = peekToken();
if (tmpToken->getType() != TokenType::CBRACKET_LEFT)
throw std::invalid_argument("Could not find method body");
// method body
node_ptr_t node;
while ((node = tryParse < nodes::StatementNode > ())) {
auto statement = std::unique_ptr<nodes::StatementNode>(dynamic_cast<nodes::StatementNode *>(node.get()));
if (!statement) throw std::bad_cast();
node.release();
method->addStatement(std::move(statement));
}
tmpToken = peekToken();
if (tmpToken->getType() == TokenType::RETURN) {
popTokens();
method->setReturnStatement(cast<nodes::AssignableNode>(tryParse < nodes::AssignableNode > ()));
} else unpeekTokens();
tmpToken = peekToken();
if (tmpToken->getType() != TokenType::CBRACKET_RIGHT)
throw std::invalid_argument("Could not find method body");
popTokens(6);
return std::unique_ptr<ProgramNode>(method);
}
template<>
node_ptr_t Parser::tryParse<nodes::VariableAssignableNode>() {
//TODO : object member
auto token = Acceptor<TokenType::IDENTIFIER>(*this)();
if (!token) return nullptr;
return node_ptr_t(new nodes::VariableAssignableNode(token->getTextValue()));
}
template<>
node_ptr_t Parser::tryParse<nodes::AssignableNode>() {
return tryParse < nodes::ExpressionNode > ();
}
template<>
node_ptr_t Parser::tryParse<nodes::PeriodicStatement>() {
if (!Acceptor<TokenType::EVERY>(*this)()){
return nullptr;
}
auto time = AcceptorErr<TokenType::NUM_LITERAL>(*this)();
auto specifier = AcceptorErr<TokenType::SEC, TokenType::MIN, TokenType::MS>(*this)();
auto block = cast<nodes::BlockNode>(tryParse<nodes::BlockNode>());
if (!block)
throw std::runtime_error("Invalid every statement");
return node_ptr_t(new nodes::PeriodicStatement(*time, *specifier, std::move(block)));
}
/// OTHER MEMBERS
rasph::parser::Parser::Parser(std::unique_ptr<rasph::lexer::Lexer> lexer) : lexer_(std::move(lexer)) {}
std::shared_ptr<rasph::common::ast::ProgramTree> rasph::parser::Parser::parse() {
auto programTree = std::make_shared<ProgramTree>();
node_ptr_t node;
while ((node = tryParse<nodes::ClassNode, nodes::StatementNode>()))
programTree->add(std::move(node));
auto item = peekedTokens_.size();
auto size1 = tokensBuffer_.size();
auto token = tokensBuffer_.front();
if (!peekedTokens_.empty() || tokensBuffer_.front()->getType() != TokenType::END)
throw std::runtime_error("Invalid buffers state");
return programTree;
}
void Parser::popTokens(size_t count) {
for (int i = 0; i < count; ++i) {
if (peekedTokens_.empty())
break;
peekedTokens_.pop_front();
}
}
void Parser::unpeekTokens(size_t count) {
for (int i = 0; i < count; ++i) {
if (peekedTokens_.empty())
throw std::out_of_range("Peeked tokens buffer is empty");
tokensBuffer_.push_front(peekedTokens_.front());
peekedTokens_.pop_front();
};
}
std::shared_ptr<rasph::common::tokens::Token> Parser::peekToken() {
std::shared_ptr<rasph::common::tokens::Token> token;
if (!tokensBuffer_.empty()) {
token = tokensBuffer_.front();
tokensBuffer_.pop_front();
} else {
token = std::move(lexer_->getNextToken());
}
if (!token) {
throw std::invalid_argument("There are no more tokens");
}
peekedTokens_.push_front(token);
return token;
}
| [
"piotr.zelazko@icloud.com"
] | piotr.zelazko@icloud.com |
c0b973c54697463f4fbfb99932084888c8bde25c | 83b760ac2f72d08f46c424917ebbf4424f7531be | /src/ExpTest.h | e0de409ba7e0603d077092a2fe01f3cd1a491185 | [] | no_license | elyawy/stepping_stone1 | 96582517883d458a7136d57db832f650abd5fe73 | 8ac70c372105f4f583e5ded5c0fc2082fabadbc2 | refs/heads/master | 2020-04-11T04:33:01.479821 | 2018-12-29T21:38:21 | 2018-12-29T21:38:21 | 161,515,934 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | h | //
// Created by ziv_t on 12/16/18.
//
#ifndef STEPPING_STONE1_EXPTEST_H
#define STEPPING_STONE1_EXPTEST_H
#include "test.h"
#include "Expression.h"
#include "Number.h"
#include "BinaryExpression.h"
#include "Plus.h"
#include "Minus.h"
#include "Mul.h"
#include "Div.h"
class ExpTest : public test {
public:
void run() override;
};
#endif //STEPPING_STONE1_EXPTEST_H
| [
"ziv.tzur@live.biu.ac.il"
] | ziv.tzur@live.biu.ac.il |
4084f354a97f9a90b15059f2a6ea480d2ccf4a70 | a1df45487531b511fc32dd2b5352e7b701436781 | /Exams/mid17extra/isBalanced.cpp | bf1224e1e9d9652907793f0935c49e0df5a3b54e | [] | no_license | TarekkMA/FEE-First-Data-Structure-Algorithms | a7b0886ea48fbefc499a0a99c134c9455f11e3d1 | b0e92230f2a2ca83134909f8448cfe095f87a786 | refs/heads/master | 2021-09-04T07:47:52.680847 | 2018-01-17T05:44:43 | 2018-01-17T05:44:43 | 110,882,196 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,730 | cpp | #include <iostream>
#define SIZE 100
using namespace std;
struct Stack{
char data[SIZE];
int top = -1;
};
bool isEmpty(Stack s){
if(s.top == -1)
return true;
else
return false;
}
bool isFull(Stack s){
if(s.top == SIZE-1)
return true;
else
return false;
}
void push(Stack&s,char c){
if(isFull(s)){
cout << "FULL" << endl;
return;
}
s.top++;
s.data[s.top] = c;
}
char pop(Stack&s){
if(isEmpty(s)){
cout << "EMPTY" << endl;
return 0;//if empty return char which assci value is 0
}
char val = s.data[s.top];
s.top--;
return val;
}
bool isBalanced(char expression[]){
Stack s;
char c = expression[0]; //starting value
int i = 0;
//while to loop over the string
//string have '\0' ending
while(c!='\0'){
if(c == '('){
push(s,'(');
}else if(c == ')'){
if(s.top == -1)
return false;
else
pop(s);
}
i++;
c = expression[i];
}
//check if there is '(' still not removed
if(isEmpty(s)){
return true;
}else{
//stack is not empty and expression is not balanced
return false;
}
}
int main() {
char exp1[] = "(3+4)*(2+5-6)";
char exp2[] = "((5-2)/(7+4)";
if(isBalanced(exp1)){
cout << exp1 << " is balanced" << endl;
}else{
cout << exp1 << " is not balanced" << endl;
}
if(isBalanced(exp2)){
cout << exp2 << " is balanced" << endl;
}else{
cout << exp2 << " is not balanced" << endl;
}
return 0;
}
| [
"tarekkma@gmail.com"
] | tarekkma@gmail.com |
4461b819f4d4f481f49536b7ebd0807b39e4b990 | 21f5356e9fd0b3ab9ee7a5c54e30fd94bb660ee4 | /win32/src/PyDEVMODE.cpp | a1bc2566e3e9adcc6f3658b4eba6d6ba9289cb66 | [] | no_license | chevah/pywin32 | 90850232a557ecf054bc316e324aaf60188f2cca | d4ff0b440147ab65f1945991e81163fb1cf1ceaf | refs/heads/master | 2020-03-29T09:46:04.465546 | 2014-10-24T09:11:17 | 2014-10-24T09:11:17 | 25,680,336 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 33,618 | cpp | // @doc - This file contains autoduck documentation
#include "PyWinTypes.h"
#include "structmember.h"
#include "PyWinObjects.h"
#ifdef MS_WINCE
#define DM_SPECVERSION 0
#endif
// @object PyDEVMODE|Python object wrapping a DEVMODE structure
struct PyMethodDef PyDEVMODEA::methods[] = {
{"Clear", PyDEVMODEA::Clear, 1}, // @pymeth Clear|Resets all members of the structure
{NULL}
};
#define OFF(e) offsetof(PyDEVMODEA, e)
struct PyMemberDef PyDEVMODEA::members[] = {
// @prop int|SpecVersion|Should always be set to DM_SPECVERSION
{"SpecVersion", T_USHORT, OFF(devmode.dmSpecVersion), 0, "Should always be set to DM_SPECVERSION"},
// @prop int|DriverVersion|Version nbr assigned to printer driver by vendor
{"DriverVersion", T_USHORT, OFF(devmode.dmDriverVersion), 0, "Version nbr assigned to printer driver by vendor"},
// @prop int|Size|Size of structure
{"Size", T_USHORT, OFF(devmode.dmSize), READONLY, "Size of structure"},
// @prop int|DriverExtra|Number of extra bytes allocated for driver data, can only be set when new object is created
{"DriverExtra", T_USHORT, OFF(devmode.dmDriverExtra), READONLY,
"Number of extra bytes allocated for driver data, can only be set when new object is created"},
// @prop int|Fields|Bitmask of win32con.DM_* constants indicating which members are set
{"Fields", T_ULONG, OFF(devmode.dmFields), 0, "Bitmask of win32con.DM_* constants indicating which members are set"},
// @prop int|Orientation|Only applies to printers, DMORIENT_PORTRAIT or DMORIENT_LANDSCAPE
{"Orientation", T_SHORT, OFF(devmode.dmOrientation), 0, "Only applies to printers, DMORIENT_PORTRAIT or DMORIENT_LANDSCAPE"},
// @prop int|PaperSize|Use 0 if PaperWidth and PaperLength are set, otherwise win32con.DMPAPER_* constant
{"PaperSize", T_SHORT, OFF(devmode.dmPaperSize), 0, "Use 0 if PaperWidth and PaperLength are set, otherwise win32con.DMPAPER_* constant"},
// @prop int|PaperLength|Specified in 1/10 millimeters
{"PaperLength", T_SHORT, OFF(devmode.dmPaperLength), 0, "Specified in 1/10 millimeters"},
// @prop int|PaperWidth|Specified in 1/10 millimeters
{"PaperWidth", T_SHORT, OFF(devmode.dmPaperWidth), 0, "Specified in 1/10 millimeters"},
#ifndef MS_WINCE
// @prop int|Position_x|Position of display relative to desktop
{"Position_x", T_LONG, OFF(devmode.dmPosition.x), 0, "Position of display relative to desktop"},
// @prop int|Position_y|Position of display relative to desktop
{"Position_y", T_LONG, OFF(devmode.dmPosition.y), 0, "Position of display relative to desktop"},
#endif
// @prop int|DisplayOrientation|Display rotation: DMDO_DEFAULT,DMDO_90, DMDO_180, DMDO_270
{"DisplayOrientation",T_ULONG,OFF(devmode.dmDisplayOrientation), 0, "Display rotation: DMDO_DEFAULT,DMDO_90, DMDO_180, DMDO_270"},
// @prop int|DisplayFixedOutput|DMDFO_DEFAULT, DMDFO_CENTER, DMDFO_STRETCH
{"DisplayFixedOutput",T_ULONG,OFF(devmode.dmDisplayFixedOutput), 0, "DMDFO_DEFAULT, DMDFO_CENTER, DMDFO_STRETCH"},
// @prop int|Scale|Specified as percentage, eg 50 means half size of original
{"Scale", T_SHORT, OFF(devmode.dmScale), 0, "Specified as percentage, eg 50 means half size of original"},
// @prop int|Copies|Nbr of copies to print
{"Copies", T_SHORT, OFF(devmode.dmCopies), 0, "Nbr of copies to print"},
// @prop int|DefaultSource|DMBIN_* constant, or can be a printer-specific value
{"DefaultSource", T_SHORT, OFF(devmode.dmDefaultSource), 0, "DMBIN_* constant, or can be a printer-specific value"},
// @prop int|PrintQuality|DMRES_* constant, interpreted as DPI if positive
{"PrintQuality", T_SHORT, OFF(devmode.dmPrintQuality), 0, "DMRES_* constant, interpreted as DPI if positive"},
// @prop int|Color|DMCOLOR_COLOR or DMCOLOR_MONOCHROME
{"Color", T_SHORT, OFF(devmode.dmColor), 0, "DMCOLOR_COLOR or DMCOLOR_MONOCHROME"},
// @prop int|Duplex|For printers that do two-sided printing: DMDUP_SIMPLEX, DMDUP_HORIZONTAL, DMDUP_VERTICAL
{"Duplex", T_SHORT, OFF(devmode.dmDuplex), 0, "For printers that do two-sided printing: DMDUP_SIMPLEX, DMDUP_HORIZONTAL, DMDUP_VERTICAL"},
// @prop int|YResolution|Vertical printer resolution in DPI - if this is set, PrintQuality indicates horizontal DPI
{"YResolution", T_SHORT, OFF(devmode.dmYResolution), 0, "Vertical printer resolution in DPI - if this is set, PrintQuality indicates horizontal DPI"},
// @prop int|TTOption|TrueType options: DMTT_BITMAP, DMTT_DOWNLOAD, DMTT_DOWNLOAD_OUTLINE, DMTT_SUBDEV
{"TTOption", T_SHORT, OFF(devmode.dmTTOption), 0, "TrueType options: DMTT_BITMAP, DMTT_DOWNLOAD, DMTT_DOWNLOAD_OUTLINE, DMTT_SUBDEV"},
// @prop int|Collate|DMCOLLATE_TRUE or DMCOLLATE_FALSE
{"Collate", T_SHORT, OFF(devmode.dmCollate), 0, "DMCOLLATE_TRUE or DMCOLLATE_FALSE"},
// @prop int|LogPixels|Pixels per inch (only for display devices
{"LogPixels", T_USHORT, OFF(devmode.dmLogPixels), 0, "Pixels per inch (only for display devices)"},
// @prop int|BitsPerPel|Color resolution in bits per pixel
{"BitsPerPel", T_ULONG, OFF(devmode.dmBitsPerPel), 0, "Color resolution in bits per pixel"},
// @prop int|PelsWidth|Pixel width of display
{"PelsWidth", T_ULONG, OFF(devmode.dmPelsWidth), 0, "Pixel width of display"},
// @prop int|PelsHeight|Pixel height of display
{"PelsHeight", T_ULONG, OFF(devmode.dmPelsHeight), 0, "Pixel height of display"},
// @prop int|DisplayFlags|Combination of DM_GRAYSCALE and DM_INTERLACED
{"DisplayFlags", T_ULONG, OFF(devmode.dmDisplayFlags), 0, "Combination of DM_GRAYSCALE and DM_INTERLACED"},
// @prop int|DisplayFrequency|Refresh rate
{"DisplayFrequency",T_ULONG, OFF(devmode.dmDisplayFrequency), 0, "Refresh rate"},
#ifdef MS_WINCE
// @prop int|DisplayOrientation|Display rotation: DMDO_DEFAULT,DMDO_90, DMDO_180, DMDO_270
{"DisplayOrientation",T_ULONG,OFF(devmode.dmDisplayOrientation), 0, "Display rotation: DMDO_DEFAULT,DMDO_90, DMDO_180, DMDO_270"},
#else
// @prop int|ICMMethod|Indicates where ICM is performed, one of win32con.DMICMMETHOD_* values
{"ICMMethod", T_ULONG, OFF(devmode.dmICMMethod), 0, "Indicates where ICM is performed, one of win32con.DMICMMETHOD_* values"},
// @prop int|ICMIntent|Intent of ICM, one of win32con.DMICM_* values
{"ICMIntent", T_ULONG, OFF(devmode.dmICMIntent), 0, "Intent of ICM, one of win32con.DMICM_* values"},
// @prop int|MediaType|win32con.DMMEDIA_*, can also be a printer-specific value greater then DMMEDIA_USER
{"MediaType", T_ULONG, OFF(devmode.dmMediaType), 0, "win32con.DMMEDIA_*, can also be a printer-specific value greater then DMMEDIA_USER"},
// @prop int|DitherType|Dithering option, win32con.DMDITHER_*
{"DitherType", T_ULONG, OFF(devmode.dmDitherType), 0, "Dithering options, win32con.DMDITHER_*"},
// @prop int|Reserved1|Reserved, use only 0
{"Reserved1", T_ULONG, OFF(devmode.dmReserved1), 0, "Reserved, use only 0"},
// @prop int|Reserved2|Reserved, use only 0
{"Reserved2", T_ULONG, OFF(devmode.dmReserved2), 0, "Reserved, use only 0"},
#if WINVER >= 0x0500
// @prop int|Nup|Controls printing of multiple logical pages per physical page, DMNUP_SYSTEM or DMNUP_ONEUP
{"Nup", T_ULONG, OFF(devmode.dmNup), 0, "Controls printing of multiple logical pages per physical page, DMNUP_SYSTEM or DMNUP_ONEUP"},
// @prop int|PanningWidth|Not used, leave as 0
{"PanningWidth", T_ULONG, OFF(devmode.dmPanningWidth), 0, "Not used, leave as 0"},
// @prop int|PanningHeight|Not used, leave as 0
{"PanningHeight", T_ULONG, OFF(devmode.dmPanningHeight), 0, "Not used, leave as 0"},
#endif // WINVER >= 0x0500
#endif // !MS_WINCE
{NULL}
};
// @prop str|DeviceName|String of at most 32 chars
PyObject *PyDEVMODEA::get_DeviceName(PyObject *self, void *unused)
{
PDEVMODEA pdevmode=((PyDEVMODEA *)self)->pdevmode;
if (pdevmode->dmDeviceName[CCHDEVICENAME-1]==0) // in case DeviceName fills space and has no trailing NULL
return PyString_FromString((char *)&pdevmode->dmDeviceName);
else
return PyString_FromStringAndSize((char *)&pdevmode->dmDeviceName, CCHDEVICENAME);
}
int PyDEVMODEA::set_DeviceName(PyObject *self, PyObject *v, void *unused)
{
if(v==NULL){
PyErr_SetString(PyExc_AttributeError, "Attributes of PyDEVMODE can't be deleted");
return -1;
}
char *value;
Py_ssize_t valuelen;
if (PyString_AsStringAndSize(v, &value, &valuelen)==-1)
return -1;
if (valuelen > CCHDEVICENAME){
PyErr_Format(PyExc_ValueError,"DeviceName must be a string of length %d or less", CCHDEVICENAME);
return -1;
}
PDEVMODEA pdevmode=&((PyDEVMODEA *)self)->devmode;
ZeroMemory(&pdevmode->dmDeviceName, CCHDEVICENAME);
memcpy(&pdevmode->dmDeviceName, value, valuelen);
// update variable length DEVMODE with same value
memcpy(((PyDEVMODEA *)self)->pdevmode, pdevmode, pdevmode->dmSize);
return 0;
}
// @prop str|FormName|Name of form as returned by <om win32print.EnumForms>, at most 32 chars
PyObject *PyDEVMODEA::get_FormName(PyObject *self, void *unused)
{
PDEVMODEA pdevmode=((PyDEVMODEA *)self)->pdevmode;
if (pdevmode->dmFormName[CCHFORMNAME-1]==0) // If dmFormName occupies whole 32 chars, trailing NULL not present
return PyString_FromString((char *)&pdevmode->dmFormName);
else
return PyString_FromStringAndSize((char *)&pdevmode->dmFormName, CCHFORMNAME);
}
int PyDEVMODEA::set_FormName(PyObject *self, PyObject *v, void *unused)
{
if(v==NULL){
PyErr_SetString(PyExc_AttributeError, "Attributes of PyDEVMODE can't be deleted");
return -1;
}
char *value;
Py_ssize_t valuelen;
if (PyString_AsStringAndSize(v, &value, &valuelen)==-1)
return -1;
if (valuelen > CCHFORMNAME){
PyErr_Format(PyExc_ValueError,"FormName must be a string of length %d or less", CCHFORMNAME);
return -1;
}
PDEVMODEA pdevmode=&((PyDEVMODEA *)self)->devmode;
ZeroMemory(&pdevmode->dmFormName, CCHFORMNAME);
memcpy(&pdevmode->dmFormName, value, valuelen);
// update variable length PDEVMODE with same value
memcpy(((PyDEVMODEA *)self)->pdevmode, pdevmode, pdevmode->dmSize);
return 0;
}
// @prop str|DriverData|Driver data appended to end of structure
PyObject *PyDEVMODEA::get_DriverData(PyObject *self, void *unused)
{
PDEVMODEA pdevmode=((PyDEVMODEA *)self)->pdevmode;
if (pdevmode->dmDriverExtra==0){ // No extra space allocated
Py_INCREF(Py_None);
return Py_None;
}
return PyString_FromStringAndSize((char *)((ULONG_PTR)pdevmode + pdevmode->dmSize), pdevmode->dmDriverExtra);
}
int PyDEVMODEA::set_DriverData(PyObject *self, PyObject *v, void *unused)
{
if(v==NULL){
PyErr_SetString(PyExc_AttributeError, "Attributes of PyDEVMODE can't be deleted");
return -1;
}
char *value;
Py_ssize_t valuelen;
if (PyString_AsStringAndSize(v, &value, &valuelen)==-1)
return -1;
PDEVMODEA pdevmode=((PyDEVMODEA *)self)->pdevmode;
if (valuelen > pdevmode->dmDriverExtra){
PyErr_Format(PyExc_ValueError,"Length of DriverData cannot be longer that DriverExtra (%d bytes)", pdevmode->dmDriverExtra);
return -1;
}
// This is not a real struct member, calculate address after end of fixed part of structure
char *driverdata=(char *)((ULONG_PTR)pdevmode + pdevmode->dmSize);
ZeroMemory(driverdata, pdevmode->dmDriverExtra);
memcpy(driverdata, value, valuelen);
return 0;
}
PyGetSetDef PyDEVMODEA::getset[] = {
{"DeviceName", PyDEVMODEA::get_DeviceName, PyDEVMODEA::set_DeviceName,
"String of at most 32 chars"},
{"FormName", PyDEVMODEA::get_FormName, PyDEVMODEA::set_FormName,
"Name of form as returned by EnumForms, at most 32 chars"},
{"DriverData", PyDEVMODEA::get_DriverData, PyDEVMODEA::set_DriverData,
"Driver data appended to end of structure"},
{NULL}
};
PYWINTYPES_EXPORT PyTypeObject PyDEVMODEAType =
{
PYWIN_OBJECT_HEAD
"PyDEVMODEA",
sizeof(PyDEVMODEA),
0,
PyDEVMODEA::deallocFunc,
0, // tp_print;
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags;
0, // tp_doc; /* Documentation string */
0, // traverseproc tp_traverse;
0, // tp_clear;
0, // tp_richcompare;
0, // tp_weaklistoffset;
0, // tp_iter
0, // iternextfunc tp_iternext
PyDEVMODEA::methods,
PyDEVMODEA::members,
PyDEVMODEA::getset, // tp_getset;
0, // tp_base;
0, // tp_dict;
0, // tp_descr_get;
0, // tp_descr_set;
0, // tp_dictoffset;
0, // tp_init;
0, // tp_alloc;
PyDEVMODEA::tp_new // newfunc tp_new;
};
PyDEVMODEA::PyDEVMODEA(PDEVMODEA pdm)
{
ob_type = &PyDEVMODEAType;
memcpy(&devmode, pdm, pdm->dmSize);
pdevmode=(PDEVMODEA)malloc(pdm->dmSize + pdm->dmDriverExtra);
if (pdevmode==NULL)
PyErr_Format(PyExc_MemoryError, "PyDEVMODEA::PyDEVMODE - Unable to allocate DEVMODE of size %d",
pdm->dmSize + pdm->dmDriverExtra);
else
memcpy(pdevmode, pdm, pdm->dmSize + pdm->dmDriverExtra);
_Py_NewReference(this);
}
PyDEVMODEA::PyDEVMODEA(void)
{
ob_type = &PyDEVMODEAType;
static WORD dmSize=sizeof(DEVMODEA);
pdevmode=(PDEVMODEA)malloc(dmSize);
ZeroMemory(pdevmode,dmSize);
pdevmode->dmSize=dmSize;
pdevmode->dmSpecVersion=DM_SPECVERSION;
ZeroMemory(&devmode,dmSize);
devmode.dmSize=dmSize;
devmode.dmSpecVersion=DM_SPECVERSION;
_Py_NewReference(this);
}
PyDEVMODEA::PyDEVMODEA(USHORT dmDriverExtra)
{
ob_type = &PyDEVMODEAType;
static WORD dmSize=sizeof(DEVMODEA);
pdevmode=(PDEVMODEA)malloc(dmSize+dmDriverExtra);
ZeroMemory(pdevmode,dmSize+dmDriverExtra);
pdevmode->dmSize=dmSize;
pdevmode->dmSpecVersion=DM_SPECVERSION;
pdevmode->dmDriverExtra=dmDriverExtra;
ZeroMemory(&devmode,dmSize);
devmode.dmSize=dmSize;
devmode.dmSpecVersion=DM_SPECVERSION;
devmode.dmDriverExtra=dmDriverExtra;
_Py_NewReference(this);
}
PyDEVMODEA::~PyDEVMODEA()
{
if (pdevmode!=NULL)
free(pdevmode);
}
BOOL PyDEVMODE_Check(PyObject *ob)
{
if (ob->ob_type!=&PyDEVMODEAType){
PyErr_SetString(PyExc_TypeError,"Object must be a PyDEVMODE");
return FALSE;
}
return TRUE;
}
void PyDEVMODEA::deallocFunc(PyObject *ob)
{
delete (PyDEVMODEA *)ob;
}
PDEVMODEA PyDEVMODEA::GetDEVMODE(void)
{
// Propagate any changes made by python attribute logic from the fixed length DEVMODE
// to the externally visible variable length DEVMODE before handing it off to anyone else
memcpy(pdevmode, &devmode, devmode.dmSize);
return pdevmode;
}
// @pymethod |PyDEVMODE|Clear|Resets all members of the structure
PyObject *PyDEVMODEA::Clear(PyObject *self, PyObject *args)
{
PDEVMODEA pdevmode=((PyDEVMODEA *)self)->pdevmode;
USHORT dmDriverExtra=pdevmode->dmDriverExtra;
WORD dmSize=pdevmode->dmSize;
DWORD totalsize=dmSize + dmDriverExtra;
ZeroMemory(pdevmode, totalsize);
pdevmode->dmDriverExtra=dmDriverExtra;
pdevmode->dmSize=dmSize;
pdevmode->dmSpecVersion=DM_SPECVERSION;
pdevmode=&((PyDEVMODEA *)self)->devmode;
ZeroMemory(pdevmode, dmSize);
pdevmode->dmDriverExtra=dmDriverExtra;
pdevmode->dmSize=dmSize;
pdevmode->dmSpecVersion=DM_SPECVERSION;
Py_INCREF(Py_None);
return Py_None;
}
PyObject *PyDEVMODEA::tp_new(PyTypeObject *typ, PyObject *args, PyObject *kwargs)
{
USHORT DriverExtra=0;
static char *keywords[]={"DriverExtra", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|H", keywords, &DriverExtra))
return NULL;
return new PyDEVMODEA(DriverExtra);
}
// If pywintypes is compiled with UNICODE defined, all modules that use these
// objects will also need to be UNICODE
#ifndef UNICODE
BOOL PyWinObject_AsDEVMODE(PyObject *ob, PDEVMODE *ppDEVMODE, BOOL bNoneOk)
{
if (ob==Py_None)
if (bNoneOk){
*ppDEVMODE=NULL;
return TRUE;
}
else{
PyErr_SetString(PyExc_ValueError,"PyDEVMODE cannot be None in this context");
return FALSE;
}
if (!PyDEVMODE_Check(ob))
return FALSE;
*ppDEVMODE=((PyDEVMODEA *)ob)->GetDEVMODE();
return TRUE;
}
PyObject *PyWinObject_FromDEVMODE(PDEVMODEA pdevmode)
{
static WORD dmSize=sizeof(DEVMODE);
if (pdevmode==NULL){
Py_INCREF(Py_None);
return Py_None;
}
// make sure we can't overflow the fixed size DEVMODE in PyDEVMODE
if (pdevmode->dmSize>dmSize){
PyErr_Format(PyExc_WindowsError,"DEVMODE structure of size %d greater than supported size of %d", pdevmode->dmSize, dmSize);
return NULL;
}
PyObject *ret=new PyDEVMODEA(pdevmode);
// check that variable sized pdevmode is allocated
if (((PyDEVMODEA *)ret)->GetDEVMODE()==NULL){
Py_DECREF(ret);
ret=NULL;
}
return ret;
}
#endif
// DEVMODEW support
// @object PyDEVMODEW|Unicode version of <o PyDEVMODE> object
/* PyDEVMODEW is only needed when win32api, win32gui, or win32print
are built with UNICODE defined. Currently, you must explicitely ask
for the unicode version.
*/
struct PyMethodDef PyDEVMODEW::methods[] = {
{"Clear", PyDEVMODEW::Clear, 1}, // @pymeth Clear|Resets all members of the structure
{NULL}
};
#define OFFW(e) offsetof(PyDEVMODEW, e)
struct PyMemberDef PyDEVMODEW::members[] = {
// @prop int|SpecVersion|Should always be set to DM_SPECVERSION
{"SpecVersion", T_USHORT, OFFW(devmode.dmSpecVersion), 0, "Should always be set to DM_SPECVERSION"},
// @prop int|DriverVersion|Version nbr assigned to printer driver by vendor
{"DriverVersion", T_USHORT, OFFW(devmode.dmDriverVersion), 0, "Version nbr assigned to printer driver by vendor"},
// @prop int|Size|Size of structure
{"Size", T_USHORT, OFFW(devmode.dmSize), READONLY, "Size of structure"},
// @prop int|DriverExtra|Number of extra bytes allocated for driver data, can only be set when new object is created
{"DriverExtra", T_USHORT, OFFW(devmode.dmDriverExtra), READONLY,
"Number of extra bytes allocated for driver data, can only be set when new object is created"},
// @prop int|Fields|Bitmask of win32con.DM_* constants indicating which members are set
{"Fields", T_ULONG, OFFW(devmode.dmFields), 0, "Bitmask of win32con.DM_* constants indicating which members are set"},
// @prop int|Orientation|Only applies to printers, DMORIENT_PORTRAIT or DMORIENT_LANDSCAPE
{"Orientation", T_SHORT, OFFW(devmode.dmOrientation), 0, "Only applies to printers, DMORIENT_PORTRAIT or DMORIENT_LANDSCAPE"},
// @prop int|PaperSize|Use 0 if PaperWidth and PaperLength are set, otherwise win32con.DMPAPER_* constant
{"PaperSize", T_SHORT, OFFW(devmode.dmPaperSize), 0, "Use 0 if PaperWidth and PaperLength are set, otherwise win32con.DMPAPER_* constant"},
// @prop int|PaperLength|Specified in 1/10 millimeters
{"PaperLength", T_SHORT, OFFW(devmode.dmPaperLength), 0, "Specified in 1/10 millimeters"},
// @prop int|PaperWidth|Specified in 1/10 millimeters
{"PaperWidth", T_SHORT, OFFW(devmode.dmPaperWidth), 0, "Specified in 1/10 millimeters"},
#ifndef MS_WINCE
// @prop int|Position_x|Position of display relative to desktop
{"Position_x", T_LONG, OFFW(devmode.dmPosition.x), 0, "Position of display relative to desktop"},
// @prop int|Position_y|Position of display relative to desktop
{"Position_y", T_LONG, OFFW(devmode.dmPosition.y), 0, "Position of display relative to desktop"},
#endif
// @prop int|DisplayOrientation|Display rotation: DMDO_DEFAULT,DMDO_90, DMDO_180, DMDO_270
{"DisplayOrientation",T_ULONG,OFFW(devmode.dmDisplayOrientation), 0, "Display rotation: DMDO_DEFAULT,DMDO_90, DMDO_180, DMDO_270"},
// @prop int|DisplayFixedOutput|DMDFO_DEFAULT, DMDFO_CENTER, DMDFO_STRETCH
{"DisplayFixedOutput",T_ULONG,OFFW(devmode.dmDisplayFixedOutput), 0, "DMDFO_DEFAULT, DMDFO_CENTER, DMDFO_STRETCH"},
// @prop int|Scale|Specified as percentage, eg 50 means half size of original
{"Scale", T_SHORT, OFFW(devmode.dmScale), 0, "Specified as percentage, eg 50 means half size of original"},
// @prop int|Copies|Nbr of copies to print
{"Copies", T_SHORT, OFFW(devmode.dmCopies), 0, "Nbr of copies to print"},
// @prop int|DefaultSource|DMBIN_* constant, or can be a printer-specific value
{"DefaultSource", T_SHORT, OFFW(devmode.dmDefaultSource), 0, "DMBIN_* constant, or can be a printer-specific value"},
// @prop int|PrintQuality|DMRES_* constant, interpreted as DPI if positive
{"PrintQuality", T_SHORT, OFFW(devmode.dmPrintQuality), 0, "DMRES_* constant, interpreted as DPI if positive"},
// @prop int|Color|DMCOLOR_COLOR or DMCOLOR_MONOCHROME
{"Color", T_SHORT, OFFW(devmode.dmColor), 0, "DMCOLOR_COLOR or DMCOLOR_MONOCHROME"},
// @prop int|Duplex|For printers that do two-sided printing: DMDUP_SIMPLEX, DMDUP_HORIZONTAL, DMDUP_VERTICAL
{"Duplex", T_SHORT, OFFW(devmode.dmDuplex), 0, "For printers that do two-sided printing: DMDUP_SIMPLEX, DMDUP_HORIZONTAL, DMDUP_VERTICAL"},
// @prop int|YResolution|Vertical printer resolution in DPI - if this is set, PrintQuality indicates horizontal DPI
{"YResolution", T_SHORT, OFFW(devmode.dmYResolution), 0, "Vertical printer resolution in DPI - if this is set, PrintQuality indicates horizontal DPI"},
// @prop int|TTOption|TrueType options: DMTT_BITMAP, DMTT_DOWNLOAD, DMTT_DOWNLOAD_OUTLINE, DMTT_SUBDEV
{"TTOption", T_SHORT, OFFW(devmode.dmTTOption), 0, "TrueType options: DMTT_BITMAP, DMTT_DOWNLOAD, DMTT_DOWNLOAD_OUTLINE, DMTT_SUBDEV"},
// @prop int|Collate|DMCOLLATE_TRUE or DMCOLLATE_FALSE
{"Collate", T_SHORT, OFFW(devmode.dmCollate), 0, "DMCOLLATE_TRUE or DMCOLLATE_FALSE"},
// @prop int|LogPixels|Pixels per inch (only for display devices
{"LogPixels", T_USHORT, OFFW(devmode.dmLogPixels), 0, "Pixels per inch (only for display devices)"},
// @prop int|BitsPerPel|Color resolution in bits per pixel
{"BitsPerPel", T_ULONG, OFFW(devmode.dmBitsPerPel), 0, "Color resolution in bits per pixel"},
// @prop int|PelsWidth|Pixel width of display
{"PelsWidth", T_ULONG, OFFW(devmode.dmPelsWidth), 0, "Pixel width of display"},
// @prop int|PelsHeight|Pixel height of display
{"PelsHeight", T_ULONG, OFFW(devmode.dmPelsHeight), 0, "Pixel height of display"},
// @prop int|DisplayFlags|Combination of DM_GRAYSCALE and DM_INTERLACED
{"DisplayFlags", T_ULONG, OFFW(devmode.dmDisplayFlags), 0, "Combination of DM_GRAYSCALE and DM_INTERLACED"},
// @prop int|DisplayFrequency|Refresh rate
{"DisplayFrequency",T_ULONG, OFFW(devmode.dmDisplayFrequency), 0, "Refresh rate"},
#ifdef MS_WINCE
// @prop int|DisplayOrientation|Display rotation: DMDO_DEFAULT,DMDO_90, DMDO_180, DMDO_270
{"DisplayOrientation",T_ULONG,OFFW(devmode.dmDisplayOrientation), 0, "Display rotation: DMDO_DEFAULT,DMDO_90, DMDO_180, DMDO_270"},
#else
// @prop int|ICMMethod|Indicates where ICM is performed, one of win32con.DMICMMETHOD_* values
{"ICMMethod", T_ULONG, OFFW(devmode.dmICMMethod), 0, "Indicates where ICM is performed, one of win32con.DMICMMETHOD_* values"},
// @prop int|ICMIntent|Intent of ICM, one of win32con.DMICM_* values
{"ICMIntent", T_ULONG, OFFW(devmode.dmICMIntent), 0, "Intent of ICM, one of win32con.DMICM_* values"},
// @prop int|MediaType|win32con.DMMEDIA_*, can also be a printer-specific value greater then DMMEDIA_USER
{"MediaType", T_ULONG, OFFW(devmode.dmMediaType), 0, "win32con.DMMEDIA_*, can also be a printer-specific value greater then DMMEDIA_USER"},
// @prop int|DitherType|Dithering option, win32con.DMDITHER_*
{"DitherType", T_ULONG, OFFW(devmode.dmDitherType), 0, "Dithering options, win32con.DMDITHER_*"},
// @prop int|Reserved1|Reserved, use only 0
{"Reserved1", T_ULONG, OFFW(devmode.dmReserved1), 0, "Reserved, use only 0"},
// @prop int|Reserved2|Reserved, use only 0
{"Reserved2", T_ULONG, OFFW(devmode.dmReserved2), 0, "Reserved, use only 0"},
#if WINVER >= 0x0500
// @prop int|Nup|Controls printing of multiple logical pages per physical page, DMNUP_SYSTEM or DMNUP_ONEUP
{"Nup", T_ULONG, OFFW(devmode.dmNup), 0, "Controls printing of multiple logical pages per physical page, DMNUP_SYSTEM or DMNUP_ONEUP"},
// @prop int|PanningWidth|Not used, leave as 0
{"PanningWidth", T_ULONG, OFFW(devmode.dmPanningWidth), 0, "Not used, leave as 0"},
// @prop int|PanningHeight|Not used, leave as 0
{"PanningHeight", T_ULONG, OFFW(devmode.dmPanningHeight), 0, "Not used, leave as 0"},
#endif // WINVER >= 0x0500
#endif // !MS_WINCE
{NULL}
};
// @prop <o PyUnicode>|DeviceName|String of at most 32 chars
PyObject *PyDEVMODEW::get_DeviceName(PyObject *self, void *unused)
{
PDEVMODEW pdevmode=((PyDEVMODEW *)self)->pdevmode;
if (pdevmode->dmDeviceName[CCHDEVICENAME-1]==0) // in case DeviceName fills space and has no trailing NULL
return PyWinObject_FromWCHAR(pdevmode->dmDeviceName);
return PyWinObject_FromWCHAR(pdevmode->dmDeviceName, CCHDEVICENAME);
}
int PyDEVMODEW::set_DeviceName(PyObject *self, PyObject *v, void *unused)
{
if(v==NULL){
PyErr_SetString(PyExc_AttributeError, "Attributes of PyDEVMODEW can't be deleted");
return -1;
}
WCHAR *devicename;
DWORD cch;
if (!PyWinObject_AsWCHAR(v, &devicename, FALSE, &cch))
return -1;
if (cch > CCHDEVICENAME){
PyErr_Format(PyExc_ValueError,"DeviceName must be a string of length %d or less", CCHDEVICENAME);
PyWinObject_FreeWCHAR(devicename);
return -1;
}
PDEVMODEW pdevmode=&((PyDEVMODEW *)self)->devmode;
ZeroMemory(&pdevmode->dmDeviceName, sizeof(pdevmode->dmDeviceName));
memcpy(&pdevmode->dmDeviceName, devicename, cch * sizeof(WCHAR));
// update variable length DEVMODE with same value
memcpy(((PyDEVMODEW *)self)->pdevmode, pdevmode, pdevmode->dmSize);
PyWinObject_FreeWCHAR(devicename);
return 0;
}
// @prop str|FormName|Name of form as returned by <om win32print.EnumForms>, at most 32 chars
PyObject *PyDEVMODEW::get_FormName(PyObject *self, void *unused)
{
PDEVMODEW pdevmode=((PyDEVMODEW *)self)->pdevmode;
if (pdevmode->dmFormName[CCHFORMNAME-1]==0) // If dmFormName occupies whole 32 chars, trailing NULL not present
return PyWinObject_FromWCHAR(pdevmode->dmFormName);
return PyWinObject_FromWCHAR(pdevmode->dmFormName, CCHFORMNAME);
}
int PyDEVMODEW::set_FormName(PyObject *self, PyObject *v, void *unused)
{
if(v==NULL){
PyErr_SetString(PyExc_AttributeError, "Attributes of PyDEVMODEW can't be deleted");
return -1;
}
WCHAR *formname;
DWORD cch;
if (!PyWinObject_AsWCHAR(v, &formname, FALSE, &cch))
return -1;
if (cch > CCHFORMNAME){
PyErr_Format(PyExc_ValueError,"FormName must be a string of length %d or less", CCHFORMNAME);
PyWinObject_FreeWCHAR(formname);
return -1;
}
PDEVMODEW pdevmode=&((PyDEVMODEW *)self)->devmode;
ZeroMemory(&pdevmode->dmFormName, sizeof(pdevmode->dmFormName));
memcpy(&pdevmode->dmFormName, formname, cch * sizeof(WCHAR));
// update variable length PDEVMODE with same value
memcpy(((PyDEVMODEW *)self)->pdevmode, pdevmode, pdevmode->dmSize);
PyWinObject_FreeWCHAR(formname);
return 0;
}
// @prop str|DriverData|Driver data appended to end of structure
PyObject *PyDEVMODEW::get_DriverData(PyObject *self, void *unused)
{
PDEVMODEW pdevmode=((PyDEVMODEW *)self)->pdevmode;
if (pdevmode->dmDriverExtra==0){ // No extra space allocated
Py_INCREF(Py_None);
return Py_None;
}
return PyString_FromStringAndSize((char *)((ULONG_PTR)pdevmode + pdevmode->dmSize), pdevmode->dmDriverExtra);
}
int PyDEVMODEW::set_DriverData(PyObject *self, PyObject *v, void *unused)
{
if(v==NULL){
PyErr_SetString(PyExc_AttributeError, "Attributes of PyDEVMODEW can't be deleted");
return -1;
}
char *value;
Py_ssize_t valuelen;
if (PyString_AsStringAndSize(v, &value, &valuelen)==-1)
return -1;
PDEVMODEW pdevmode=((PyDEVMODEW *)self)->pdevmode;
if (valuelen > pdevmode->dmDriverExtra){
PyErr_Format(PyExc_ValueError,"Length of DriverData cannot be longer that DriverExtra (%d bytes)", pdevmode->dmDriverExtra);
return -1;
}
// This is not a real struct member, calculate address after end of fixed part of structure
char *driverdata=(char *)((ULONG_PTR)pdevmode + pdevmode->dmSize);
ZeroMemory(driverdata, pdevmode->dmDriverExtra);
memcpy(driverdata, value, valuelen);
return 0;
}
PyGetSetDef PyDEVMODEW::getset[] = {
{"DeviceName", PyDEVMODEW::get_DeviceName, PyDEVMODEW::set_DeviceName,
"String of at most 32 chars"},
{"FormName", PyDEVMODEW::get_FormName, PyDEVMODEW::set_FormName,
"Name of form as returned by EnumForms, at most 32 chars"},
{"DriverData", PyDEVMODEW::get_DriverData, PyDEVMODEW::set_DriverData,
"Driver data appended to end of structure"},
{NULL}
};
PYWINTYPES_EXPORT PyTypeObject PyDEVMODEWType =
{
PYWIN_OBJECT_HEAD
"PyDEVMODEW",
sizeof(PyDEVMODEW),
0,
PyDEVMODEW::deallocFunc,
0, // tp_print;
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags;
0, // tp_doc
0, // traverseproc tp_traverse;
0, // tp_clear;
0, // tp_richcompare;
0, // tp_weaklistoffset;
0, // tp_iter
0, // iternextfunc tp_iternext
PyDEVMODEW::methods,
PyDEVMODEW::members,
PyDEVMODEW::getset, // tp_getset;
0, // tp_base;
0, // tp_dict;
0, // tp_descr_get;
0, // tp_descr_set;
0, // tp_dictoffset;
0, // tp_init;
0, // tp_alloc;
PyDEVMODEW::tp_new // newfunc tp_new;
};
PyDEVMODEW::PyDEVMODEW(PDEVMODEW pdm)
{
ob_type = &PyDEVMODEWType;
memcpy(&devmode, pdm, pdm->dmSize);
pdevmode=(PDEVMODEW)malloc(pdm->dmSize + pdm->dmDriverExtra);
if (pdevmode==NULL)
PyErr_Format(PyExc_MemoryError, "PyDEVMODEA::PyDEVMODE - Unable to allocate DEVMODE of size %d",
pdm->dmSize + pdm->dmDriverExtra);
else
memcpy(pdevmode, pdm, pdm->dmSize + pdm->dmDriverExtra);
_Py_NewReference(this);
}
PyDEVMODEW::PyDEVMODEW(void)
{
ob_type = &PyDEVMODEWType;
static WORD dmSize=sizeof(DEVMODEW);
pdevmode=(PDEVMODEW)malloc(dmSize);
ZeroMemory(pdevmode,dmSize);
pdevmode->dmSize=dmSize;
pdevmode->dmSpecVersion=DM_SPECVERSION;
ZeroMemory(&devmode,dmSize);
devmode.dmSize=dmSize;
devmode.dmSpecVersion=DM_SPECVERSION;
_Py_NewReference(this);
}
PyDEVMODEW::PyDEVMODEW(USHORT dmDriverExtra)
{
ob_type = &PyDEVMODEWType;
static WORD dmSize=sizeof(DEVMODEW);
pdevmode=(PDEVMODEW)malloc(dmSize+dmDriverExtra);
ZeroMemory(pdevmode,dmSize+dmDriverExtra);
pdevmode->dmSize=dmSize;
pdevmode->dmSpecVersion=DM_SPECVERSION;
pdevmode->dmDriverExtra=dmDriverExtra;
ZeroMemory(&devmode,dmSize);
devmode.dmSize=dmSize;
devmode.dmSpecVersion=DM_SPECVERSION;
devmode.dmDriverExtra=dmDriverExtra;
_Py_NewReference(this);
}
PyDEVMODEW::~PyDEVMODEW()
{
if (pdevmode!=NULL)
free(pdevmode);
}
BOOL PyDEVMODEW_Check(PyObject *ob)
{
if (ob->ob_type!=&PyDEVMODEWType){
PyErr_SetString(PyExc_TypeError,"Object must be a PyDEVMODEW");
return FALSE;
}
return TRUE;
}
void PyDEVMODEW::deallocFunc(PyObject *ob)
{
delete (PyDEVMODEW *)ob;
}
PDEVMODEW PyDEVMODEW::GetDEVMODE(void)
{
// Propagate any changes made by python attribute logic from the fixed length DEVMODE
// to the externally visible variable length DEVMODE before handing it off to anyone else
memcpy(pdevmode, &devmode, devmode.dmSize);
return pdevmode;
}
// @pymethod |PyDEVMODE|Clear|Resets all members of the structure
PyObject *PyDEVMODEW::Clear(PyObject *self, PyObject *args)
{
PDEVMODEW pdevmode=((PyDEVMODEW *)self)->pdevmode;
USHORT dmDriverExtra=pdevmode->dmDriverExtra;
WORD dmSize=pdevmode->dmSize;
DWORD totalsize=dmSize + dmDriverExtra;
ZeroMemory(pdevmode, totalsize);
pdevmode->dmDriverExtra=dmDriverExtra;
pdevmode->dmSize=dmSize;
pdevmode->dmSpecVersion=DM_SPECVERSION;
pdevmode=&((PyDEVMODEW *)self)->devmode;
ZeroMemory(pdevmode, dmSize);
pdevmode->dmDriverExtra=dmDriverExtra;
pdevmode->dmSize=dmSize;
pdevmode->dmSpecVersion=DM_SPECVERSION;
Py_INCREF(Py_None);
return Py_None;
}
PyObject *PyDEVMODEW::tp_new(PyTypeObject *typ, PyObject *args, PyObject *kwargs)
{
USHORT DriverExtra=0;
static char *keywords[]={"DriverExtra", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|H", keywords, &DriverExtra))
return NULL;
return new PyDEVMODEW(DriverExtra);
}
BOOL PyWinObject_AsDEVMODE(PyObject *ob, PDEVMODEW *ppDEVMODE, BOOL bNoneOk)
{
if (ob==Py_None)
if (bNoneOk){
*ppDEVMODE=NULL;
return TRUE;
}
else{
PyErr_SetString(PyExc_ValueError,"PyDEVMODE cannot be None in this context");
return FALSE;
}
if (!PyDEVMODEW_Check(ob))
return FALSE;
*ppDEVMODE=((PyDEVMODEW *)ob)->GetDEVMODE();
return TRUE;
}
PyObject *PyWinObject_FromDEVMODE(PDEVMODEW pDEVMODE)
{
static WORD dmSize=sizeof(DEVMODEW);
if (pDEVMODE==NULL){
Py_INCREF(Py_None);
return Py_None;
}
// make sure we can't overflow the fixed size DEVMODE in PyDEVMODE
if (pDEVMODE->dmSize>dmSize){
PyErr_Format(PyExc_WindowsError,"DEVMODE structure of size %d greater than supported size of %d", pDEVMODE->dmSize, dmSize);
return NULL;
}
PyObject *ret=new PyDEVMODEW(pDEVMODE);
// check that variable sized pdevmode is allocated
if (((PyDEVMODEW *)ret)->GetDEVMODE()==NULL){
Py_DECREF(ret);
ret=NULL;
}
return ret;
}
| [
"adi.roiban@chevah.com"
] | adi.roiban@chevah.com |
69ec5591ec882ccf7637b6ba5ee54f7a123be744 | dccb136394c3c7f4a636f17f444ebaf95e24ab66 | /Programmers/Lv_1/programmers_콜라츠 추측.cpp | 02bb4b87b4f3f88df6c815bdb31c196c7e9c7d5e | [] | no_license | Oh-kyung-tak/Algorithm | e2b88f6ae8e97130259dedfc30bb48591ae5b2fd | be63f972503170eb8ce06002a2eacd365ade7787 | refs/heads/master | 2020-04-25T22:37:41.799025 | 2020-01-19T08:55:42 | 2020-01-19T08:55:42 | 173,117,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 359 | cpp | #include <string>
#include <vector>
using namespace std;
int solution(int num) {
int answer = 0;
int cnt = 0;
long long int temp = num;
while (1)
{
if (temp == 1)
{
answer = cnt;
break;
}
if (cnt > 500)
{
answer = -1;
break;
}
if (temp % 2 == 0)
temp /= 2;
else
temp = (temp * 3) + 1;
cnt++;
}
return answer;
} | [
"38690587+Oh-kyung-tak@users.noreply.github.com"
] | 38690587+Oh-kyung-tak@users.noreply.github.com |
326151aa0b85f77b9eeeaae62159a449eca8a3c6 | e1e756097a338ac7ed026de4ec825821a6653ea3 | /boost_net/deps.h | 87817d9352fe9c7797f587b98849091b26a4ae48 | [] | no_license | killgxlin/boost_network | 43a8c2753a9cf5b796f6c0aa7d846347c128ff1c | 6ae91543919c68e66b95f7da3501e7c9f4ed515f | refs/heads/master | 2021-01-22T03:08:41.855916 | 2013-07-10T15:11:27 | 2013-07-10T15:11:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 604 | h | #ifndef DEPS_H
#define DEPS_H
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/lockfree/queue.hpp>
#include <boost/lockfree/stack.hpp>
#include <boost/asio.hpp>
#include <boost/atomic.hpp>
#include <set>
#include <vector>
#include <list>
#include <map>
#include <functional>
#include <stdint.h>
#include <stdio.h>
namespace asio = boost::asio;
namespace lockfree = boost::lockfree;
namespace this_thread = boost::this_thread;
namespace posix_time = boost::posix_time;
#endif | [
"killgxlin@hotmail.com"
] | killgxlin@hotmail.com |
cc05420a258a33d21be60dafb1b6ebf9b6645828 | 9c9003f4912e2065c3901f1f51ef5b398f999a10 | /projectb/client/game_xxx/newProtocol/game_fourcolorball_def.pb.cc | 0806ae59f850b01543f9feaffcd6d61dd49ed1ac | [] | no_license | PHDaozhang/recharge_h5 | 41424d5725eae69cc6a921cd1ef954b255a0ca65 | 7d5e63d97e731ea860d927c37612fe35f7d3bd61 | refs/heads/master | 2020-08-11T21:57:49.842525 | 2019-10-15T07:32:40 | 2019-10-15T07:32:40 | 214,632,134 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | true | 6,424 | cc | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: game_fourcolorball_def.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "game_fourcolorball_def.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace game_fourcolorball_protocols {
namespace {
const ::google::protobuf::EnumDescriptor* e_server_msg_type_descriptor_ = NULL;
const ::google::protobuf::EnumDescriptor* e_game_state_descriptor_ = NULL;
} // namespace
void protobuf_AssignDesc_game_5ffourcolorball_5fdef_2eproto() {
protobuf_AddDesc_game_5ffourcolorball_5fdef_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"game_fourcolorball_def.proto");
GOOGLE_CHECK(file != NULL);
e_server_msg_type_descriptor_ = file->enum_type(0);
e_game_state_descriptor_ = file->enum_type(1);
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_game_5ffourcolorball_5fdef_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
}
} // namespace
void protobuf_ShutdownFile_game_5ffourcolorball_5fdef_2eproto() {
}
void protobuf_AddDesc_game_5ffourcolorball_5fdef_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\034game_fourcolorball_def.proto\022\034game_fou"
"rcolorball_protocols*\275\n\n\021e_server_msg_ty"
"pe\022\024\n\017e_mst_start_c2l\020\220N\022\034\n\027e_mst_c2l_ge"
"t_room_info\020\221N\022\031\n\024e_mst_c2l_enter_room\020\222"
"N\022\031\n\024e_mst_c2l_leave_room\020\223N\022\026\n\021e_mst_c2"
"l_add_bet\020\224N\022\031\n\024e_mst_c2l_repeat_bet\020\225N\022"
"\030\n\023e_mst_c2l_clear_bet\020\226N\022\"\n\035e_mst_c2l_g"
"et_room_scene_info\020\227N\022\032\n\025e_mst_c2l_check"
"_state\020\230N\022\021\n\014e_mst_c2l_gm\020\231N\022\035\n\030e_mst_c2"
"l_ask_for_banker\020\232N\022\033\n\026e_mst_c2l_leave_b"
"anker\020\233N\022#\n\036e_mst_c2l_ask_first_for_bank"
"er\020\234N\022\036\n\031e_mst_c2l_ask_player_list\020\235N\022\036\n"
"\031e_mst_c2l_ask_banker_list\020\236N\022\037\n\032e_mst_c"
"2l_ask_history_list\020\237N\022$\n\037e_mst_c2l_cont"
"rol_change_result\020\240N\022\024\n\017e_mst_start_l2c\020"
"\230u\022#\n\036e_mst_l2c_get_room_info_result\020\231u\022"
" \n\033e_mst_l2c_enter_room_result\020\232u\022 \n\033e_m"
"st_l2c_leave_room_result\020\233u\022\026\n\021e_mst_l2c"
"_add_bet\020\234u\022\031\n\024e_mst_l2c_repeat_bet\020\235u\022\030"
"\n\023e_mst_l2c_clear_bet\020\236u\022\033\n\026e_mst_l2c_bc"
"_begin_bet\020\237u\022\035\n\030e_mst_l2c_bc_begin_awar"
"d\020\240u\022 \n\033e_mst_l2c_bc_total_bet_info\020\241u\022\""
"\n\035e_mst_l2c_get_room_scene_info\020\242u\022!\n\034e_"
"mst_l2c_check_state_result\020\245u\022\035\n\030e_mst_l"
"2c_bc_accept_gift\020\247u\022\035\n\030e_mst_l2c_ask_fo"
"r_banker\020\250u\022\033\n\026e_mst_l2c_leave_banker\020\251u"
"\022#\n\036e_mst_l2c_ask_first_for_banker\020\252u\022\037\n"
"\032e_mst_l2c_bc_change_banker\020\253u\022\036\n\031e_mst_"
"l2c_ask_player_list\020\254u\022\036\n\031e_mst_l2c_ask_"
"banker_list\020\255u\022\037\n\032e_mst_l2c_ask_history_"
"list\020\256u\022!\n\034e_mst_l2c_bc_rob_banker_info\020"
"\257u\022 \n\033e_mst_l2c_bc_every_bet_info\020\214y\022$\n\037"
"e_mst_l2c_control_change_result\020\216y\022\033\n\026e_"
"mst_l2c_bc_debuginfo\020\221y\022\"\n\035e_mst_l2c_not"
"ice_gm_bank_info\020\222y\022\027\n\021e_mst_clend_index"
"\020\240\234\001*T\n\014e_game_state\022\026\n\022e_state_game_beg"
"in\020\000\022\024\n\020e_state_game_bet\020\001\022\026\n\022e_state_ga"
"me_award\020\002", 1490);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"game_fourcolorball_def.proto", &protobuf_RegisterTypes);
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_game_5ffourcolorball_5fdef_2eproto);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_game_5ffourcolorball_5fdef_2eproto {
StaticDescriptorInitializer_game_5ffourcolorball_5fdef_2eproto() {
protobuf_AddDesc_game_5ffourcolorball_5fdef_2eproto();
}
} static_descriptor_initializer_game_5ffourcolorball_5fdef_2eproto_;
const ::google::protobuf::EnumDescriptor* e_server_msg_type_descriptor() {
protobuf_AssignDescriptorsOnce();
return e_server_msg_type_descriptor_;
}
bool e_server_msg_type_IsValid(int value) {
switch(value) {
case 10000:
case 10001:
case 10002:
case 10003:
case 10004:
case 10005:
case 10006:
case 10007:
case 10008:
case 10009:
case 10010:
case 10011:
case 10012:
case 10013:
case 10014:
case 10015:
case 10016:
case 15000:
case 15001:
case 15002:
case 15003:
case 15004:
case 15005:
case 15006:
case 15007:
case 15008:
case 15009:
case 15010:
case 15013:
case 15015:
case 15016:
case 15017:
case 15018:
case 15019:
case 15020:
case 15021:
case 15022:
case 15023:
case 15500:
case 15502:
case 15505:
case 15506:
case 20000:
return true;
default:
return false;
}
}
const ::google::protobuf::EnumDescriptor* e_game_state_descriptor() {
protobuf_AssignDescriptorsOnce();
return e_game_state_descriptor_;
}
bool e_game_state_IsValid(int value) {
switch(value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
// @@protoc_insertion_point(namespace_scope)
} // namespace game_fourcolorball_protocols
// @@protoc_insertion_point(global_scope)
| [
"czh850109@gmail.com"
] | czh850109@gmail.com |
65b779a2a6e0f530770b7ae19fa4ad7caa66e6d6 | 2b7b4f2f174d01b0f2445e2e2275e6a1a8f143c6 | /HDU/1864[dp].cpp | c042f97f06e60b43014bd7ba020ae3d88beb6598 | [] | no_license | lilyht/OJ_code | 34220c6d0dbd36984af0fae69dce8427742b1eac | eb589194c109fdc5ed24ea99f2b0f5108964a72c | refs/heads/master | 2022-12-27T09:10:17.911928 | 2020-10-12T08:45:08 | 2020-10-12T08:45:08 | 303,328,850 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,981 | cpp | #include <iostream>
#include <string.h>
#include <iomanip>
using namespace std;
/*
* 最大报销额
* 现有一笔经费可以报销一定额度的发票。允许报销的发票类型包括买图书(A类)、文具(B类)、差旅(C类)
* 要求每张发票的总额不得超过1000元,每张发票上,单项物品的价值不得超过600元。
* 现请你编写程序,在给出的一堆发票中找出可以报销的、不超过给定额度的最大报销额。
*/
int check[35];
int dp[3000050]; //因为dp数组的下标必须是整数,而输入的价格为两位小数,所以扩大100倍变整数,最后输出的时候再变回去 30 * 1000 * 100
int main() {
double Q = 0.0;
while(cin>>Q) {
int N = 0;
cin>>N;
memset(check, 0, sizeof(check));
memset(dp, 0, sizeof(dp));
int index = 0;
if(N == 0) {
break;
}
for(int i=0; i<N; i++) {
int m;
cin>>m;
if(m != 0) {
double a = 0.0, b = 0.0, c = 0.0;
double aprice = 0.0, bprice = 0.0, cprice = 0.0;
bool flag = 1;
double total = 0.0;
for(int j=0; j<m; j++) {
char type, colon;
double price = 0.0;
cin>>type>>colon>>price;
if(type == 'A') {
aprice += price;
}
else if (type == 'B') {
bprice += price;
}
else if (type == 'C') {
cprice += price;
}
else {
flag = 0;
}
total += price;
}
if(aprice > 600.0 || bprice > 600.0 || cprice > 600.0 ) flag = 0;
if(total > 1000.0) flag = 0;
if(flag == 1) {
//有效发票
check[index] = (int)(total * 100);
index++ ;
}
}
}
dp[0] = 0;
int intQ = (int)(Q * 100);
for(int i=0; i<index; i++) {
for(int j=intQ; j>=check[i]; j--) {
dp[j] = max(dp[j], dp[j-check[i]] + check[i]);
}
}
cout<<fixed<<setprecision(2); // 固定输出两位小数,所有后面的输出均可以这种格式输出
cout<<dp[intQ] * 1.0 / 100<<endl;
}
return 0;
}
| [
"295808612@qq.com"
] | 295808612@qq.com |
47807127c3fb34099a030ec43addd11c37a9d3ad | 19555fc7ebb58e6d915b78a22b9b8a29de4fabe0 | /examples/TerrainDemo/terrain.cpp | f58b2d013a742b90ae39e669a9f5499023f07d7d | [
"Unlicense"
] | permissive | wyrover/freeimage-PhotoViewer | 1713a79d0f4a98b0b0ee7cca31aadc6e88c476a6 | 9d8fa6024e81e50904bab941501c639716cf26e0 | refs/heads/master | 2021-05-27T18:05:11.281823 | 2013-09-03T03:20:54 | 2013-09-03T03:20:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,530 | cpp | #include "stdafx.h"
#include "terrain.h"
#include "viewer.h"
#include "texture.h"
#include "quaternion.h"
#include "options.h"
#include <math.h>
#include "platform/log.h"
#include "platform/imageloader.h"
using namespace Platform;
#define MORPH_RANGE .025f
////////////////////////////////////////////////////////////////////////////
// Public: Terrain()
// Params:
// No params.
// Initialises a few variables...
////////////////////////////////////////////////////////////////////////////
Terrain::Terrain()
{
heightmap = NULL;
camznear = 0;
opt_terrain_wireframe = false;
//set to .1 to see little pops...
varthreshold = .05f;
opt_global_debug = false;
placename = NULL;
range = 200;
vertices = new Vector[maxvertices];
}
Terrain::~Terrain()
{
delete [] texturemap; texturemap = 0;
delete [] colormap; colormap = 0;
delete [] varianceTree1; varianceTree1 = 0;
delete [] varianceTree2; varianceTree2 = 0;
delete [] bintritree; bintritree = 0;
delete [] vertices; vertices = 0;
}
////////////////////////////////////////////////////////////////////////////
// Public: load()
// Params: charactor array to a tga file repesenting the height array.
// Returns: true if ok, false if failed.
////////////////////////////////////////////////////////////////////////////
bool Terrain::load(const std::wstring& filePath)
{
// load in a image, brightness repesents the height of the terrain.
Image* image = ImageLoader::LoadImage(filePath, Image::GRAYSCALE);
if (!image) {
Log::print(L"Couldnt load the terrain height map.");
return false;
}
heightmap = image->getWritableData();
width = image->getWidth();
height = image->getHeight();
if (height != 256 && width != 256) {
Log::print(L"Terrain image needs to be 256 * 256 at the moment.(sorry)");
return false;
}
CalcVarianceTree();
CalcLight();
CalcTexture();
// maximum number of bintrees that we could ever need
// is allocated, so no error checking has to be done.
bintritree = new BinTriTree[256*256*4]; //(n^2 + n^2) * 2
location.load(L"data/location.pcx", L"data/location.txt");
return true;
}
////////////////////////////////////////////////////////////////////////////
// Public: Draw()
// Params: Pointer to Viewer class, uses position and rotations values
////////////////////////////////////////////////////////////////////////////
void Terrain::Draw(Viewer *viewer)
{
starttime = timeGetTime();
BuildTree(viewer);
endtime = timeGetTime();
Log::printf(L"Split count: %d in %dms", tricount, endtime - starttime);
glBindTexture(GL_TEXTURE_2D, gltexture);
tricount = 0;
starttime = endtime;
RenderTree();
endtime = timeGetTime();
Log::printf(L"Render Count: %d in %dms", tricount, endtime - starttime);
}
////////////////////////////////////////////////////////////////////////////
// Private: RenderTree()
////////////////////////////////////////////////////////////////////////////
void Terrain::RenderTree(void)
{
if (!opt_terrain_wireframe)
glBegin(GL_TRIANGLES);
vertexindex = 0;
RenderTree2(0, 0, (float)getHeight(0, 0),
height, width, (float)getHeight(height, width),
0, width, (float)getHeight(0, width),
&bintritree[1]);
RenderTree2(height, width, (float)getHeight(height, width),
0, 0, (float)getHeight(0, 0),
height, 0, (float)getHeight(height, 0),
&bintritree[2]);
if (!opt_terrain_wireframe) {
glEnd();
}
}
////////////////////////////////////////////////////////////////////////////
// Private: RenderTree2()
// Params: Vertices of current triangle with their morph valuse.
////////////////////////////////////////////////////////////////////////////
void Terrain::RenderTree2(UINT16 x1, UINT16 y1, float morph1,
UINT16 x2, UINT16 y2, float morph2,
UINT16 x3, UINT16 y3, float morph3,
BinTriTree *tri)
{
if (tri->leftChild != 0 && tri->rightChild != 0) {
int hx = (x1 + x2) / 2;
int hy = (y1 + y2) / 2;
float realHeight = (float)getHeight(hx, hy);
float avgHeight = (morph1 + morph2) / 2;
float v = realHeight - avgHeight;
float tmorph = tri->morph;
if (tri->bottomNeighbour != 0) {
tmorph = (tmorph + tri->bottomNeighbour->morph) / 2;
}
float morphheight = avgHeight + (v * tmorph);
RenderTree2(x2, y2, morph2,
x3, y3, morph3,
hx, hy, morphheight,
tri->leftChild);
RenderTree2(x3, y3, morph3,
x1, y1, morph1,
hx, hy, morphheight,
tri->rightChild);
}
else {
tricount++;
if (opt_terrain_wireframe) {
#ifdef NICE_WIREFRAME
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDisable(GL_TEXTURE_2D);
glColor3f(0.3f, 0.5f, 1.0f);
glBegin(GL_TRIANGLES);
glVertex3f((GLfloat)x1 - 128, morph1*0.1f, (GLfloat)y1 - 128);
glVertex3f((GLfloat)x2 - 128, morph2*0.1f, (GLfloat)y2 - 128);
glVertex3f((GLfloat)x3 - 128, morph3*0.1f, (GLfloat)y3 - 128);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(1.0f, 1.0f);
glEnable(GL_TEXTURE_2D);
glColor3f(1, 1, 1);
glBegin(GL_TRIANGLES);
glTexCoord2f(x1 / 256.0f, y1 / 256.0f);
glVertex3f((GLfloat)x1 - 128, morph1*0.1f, (GLfloat)y1 - 128);
glTexCoord2f(x2 / 256.0f, y2 / 256.0f);
glVertex3f((GLfloat)x2 - 128, morph2*0.1f, (GLfloat)y2 - 128);
glTexCoord2f(x3 / 256.0f, y3 / 256.0f);
glVertex3f((GLfloat)x3 - 128, morph3*0.1f, (GLfloat)y3 - 128);
glDisable(GL_POLYGON_OFFSET_FILL);
glEnd();
#else
// BASIC WIREFRAME
glDisable(GL_TEXTURE_2D); // shouldn't be here really
glBegin(GL_LINE_LOOP);
glVertex3f((GLfloat)x1 - 128, morph1*0.1f, (GLfloat)y1 - 128);
glVertex3f((GLfloat)x2 - 128, morph2*0.1f, (GLfloat)y2 - 128);
glVertex3f((GLfloat)x3 - 128, morph3*0.1f, (GLfloat)y3 - 128);
glEnd();
#endif
}
else {
glTexCoord2f(x1 / 256.0f, y1 / 256.0f);
glVertex3f((GLfloat)x1 - 128, morph1*0.1f, (GLfloat)y1 - 128);
glTexCoord2f(x2 / 256.0f, y2 / 256.0f);
glVertex3f((GLfloat)x2 - 128, morph2*0.1f, (GLfloat)y2 - 128);
glTexCoord2f(x3 / 256.0f, y3 / 256.0f);
glVertex3f((GLfloat)x3 - 128, morph3*0.1f, (GLfloat)y3 - 128);
}
}
}
////////////////////////////////////////////////////////////////////////////
// Private: BuildTree()
// Params: Pointer to the viewer class.
////////////////////////////////////////////////////////////////////////////
void Terrain::BuildTree(Viewer *viewer)
{
bintritree[1].leftChild = 0;
bintritree[1].rightChild = 0;
bintritree[1].leftNeighbour = 0;
bintritree[1].rightNeighbour = 0;
bintritree[1].bottomNeighbour = &bintritree[2];
bintritree[1].leaf = 1;
bintritree[2].leftChild = 0;
bintritree[2].rightChild = 0;
bintritree[2].leftNeighbour = 0;
bintritree[2].rightNeighbour = 0;
bintritree[2].bottomNeighbour = &bintritree[1];
bintritree[2].leaf = 1;
nextfreebintree = 3;
Vector d1, d2, d3, d4;
DistanceTo(d1, -128, -128, viewer->pos, viewer->rot);
DistanceTo(d2, -128, 128, viewer->pos, viewer->rot);
DistanceTo(d3, 128, 128, viewer->pos, viewer->rot);
DistanceTo(d4, 128, -128, viewer->pos, viewer->rot);
DistanceTo(aoipos, -viewer->aoipos[2], -viewer->aoipos[0],
viewer->pos, viewer->rot);
tricount = 0;
if (!aoi) {
aoipos[0] = 20000;
aoipos[2] = 20000;
}
cvarianceTree = varianceTree1;
ctreedepth = 17;
// BuildTree2(&bintritree[1], d1[2], d3[2], d2[2]);
BuildTree3(&bintritree[1], d1[0], d1[2], d3[0], d3[2], d2[0], d2[2]);
cvarianceTree = varianceTree2;
ctreedepth = 17;
// BuildTree2(&bintritree[2], d3[2], d1[2], d4[2]);
BuildTree3(&bintritree[2], d3[0], d3[2], d1[0], d1[2], d4[0], d4[2]);
}
////////////////////////////////////////////////////////////////////////////
// Private: DistanceTo()
// Params: Vector: a vector to hold the result
// float, float: a 2d point on the terrain.
// Vector: the view position.
// Vector: the view direction.(Given in degrees)
//
// Side effects: Vector result is changed.
////////////////////////////////////////////////////////////////////////////
void Terrain::DistanceTo(Vector result, float x, float y,
Vector view, Vector viewrot)
{
Vector rot;
Matrix matrix;
rot[0] = -view[0];
rot[1] = 0;
rot[2] = -view[2];
zeroVector(result);
identityMatrix(matrix);
translateMatrix(matrix, rot);
rotateMatrixY(matrix, ((viewrot[1] - 180) / 360)*2*M_PI);
rot[0] = -y;
rot[2] = -x;
multVertexMatrix(rot, matrix, result);
}
////////////////////////////////////////////////////////////////////////////
// Private: BuildTree3()
// Params: BinTriTree: actually a node, but hey.
// float, float: right vertex
// float, float: left vertex
// float, float: apex vertex
// Side effects: BinTriTree is built.
// ctreedepth changes by only relevant to recursion.
////////////////////////////////////////////////////////////////////////////
void Terrain::BuildTree3(BinTriTree *tri, float x1, float z1,
float x2, float z2, float x3, float z3)
{
// get our split point
float zh = (z1 + z2) / 2;
float xh = (x1 + x2) / 2;
float variance;
// Are we the lowest triangle in tree
if (ctreedepth < 1)
return;
int cullstate = TriCull2D(x1, z1, x2, z2, x3, z3);
// Are we in view fustrum?
if (cullstate == 2)
return;
variance = ((float)cvarianceTree[tri->leaf]) / abs(zh);
// AOI calculation
float d = ((aoipos[0] - xh) * (aoipos[0] - xh) + (aoipos[2] - zh) * (aoipos[2] - zh));
if (d < range) {
// Scale the variance
variance = variance * (1 + ((range - d) * invrange));
}
if ( variance > varthreshold) {
// Split triangle
float t = variance - varthreshold;
if (t < MORPH_RANGE) {
// Geomorphing
tri->morph = t / MORPH_RANGE;
}
else {
tri->morph = 1.0f;
}
if (tri->leftChild == 0 && tri->rightChild == 0) {
// Has not been split, so split it
Split(tri);
}
ctreedepth--;
if (cullstate == 1) {
// Triangle totally inside view fustrum
BuildTree2(tri->rightChild, x2, z2, x3, z3, xh, zh);
BuildTree2(tri->leftChild, x3, z3, x1, z1, xh, zh);
}
else {
// Needs further checking
BuildTree3(tri->rightChild, x2, z2, x3, z3, xh, zh);
BuildTree3(tri->leftChild, x3, z3, x1, z1, xh, zh);
}
ctreedepth++;
}
}
////////////////////////////////////////////////////////////////////////////
// Private: BuildTree2()
// Params: BinTriTree: actually a node, but hey.
// float, float: right vertex
// float, float: left vertex
// float, float: apex vertex
// Side effects: BinTriTree is built.
// ctreedepth changes by only relevant to recursion.
////////////////////////////////////////////////////////////////////////////
void Terrain::BuildTree2(BinTriTree *tri, float x1, float z1,
float x2, float z2, float x3, float z3)
{
// get our split point
float zh = (z1 + z2) / 2;
float xh = (x1 + x2) / 2;
float variance;
// Are we the lowest triangle in tree
if (ctreedepth < 1)
return;
variance = ((float)cvarianceTree[tri->leaf]) / abs(zh);
// AOI calculation
float d = ((aoipos[0] - xh) * (aoipos[0] - xh) + (aoipos[2] - zh) * (aoipos[2] - zh));
if (d < range) {
// Scale the variance
variance = variance * (1 + ((range - d) * invrange));
}
if ( variance > varthreshold) {
// Split triangle
float t = variance - varthreshold;
if (t < MORPH_RANGE) {
// Geomorphing
tri->morph = t / MORPH_RANGE;
}
else {
tri->morph = 1.0;
}
if (tri->leftChild == 0 && tri->rightChild == 0) {
// Has not been split, so split it
Split(tri);
}
ctreedepth--;
BuildTree2(tri->rightChild, x2, z2, x3, z3, xh, zh);
BuildTree2(tri->leftChild, x3, z3, x1, z1, xh, zh);
ctreedepth++;
}
}
////////////////////////////////////////////////////////////////////////////
// Private: Split()
// Params: BinTriTree: triangle to be split.
//
// Side effects: BinTriTree is split the mesh kept coherent.
////////////////////////////////////////////////////////////////////////////
void Terrain::Split(BinTriTree *tri)
{
if (tri->bottomNeighbour != 0) {
if (tri->bottomNeighbour->bottomNeighbour != tri) {
Split(tri->bottomNeighbour);
}
Split2(tri);
Split2(tri->bottomNeighbour);
tri->leftChild->rightNeighbour = tri->bottomNeighbour->rightChild;
tri->rightChild->leftNeighbour = tri->bottomNeighbour->leftChild;
tri->bottomNeighbour->leftChild->rightNeighbour = tri->rightChild;
tri->bottomNeighbour->rightChild->leftNeighbour = tri->leftChild;
}
else {
Split2(tri);
tri->leftChild->rightNeighbour = 0;
tri->rightChild->leftNeighbour = 0;
}
}
////////////////////////////////////////////////////////////////////////////
// Private: Split2()
// Params: BinTriTree: triangle to be split.
//
// Side effects: BinTriTree is split.
////////////////////////////////////////////////////////////////////////////
void Terrain::Split2(BinTriTree *tri)
{
tri->leftChild = &bintritree[nextfreebintree++];
tri->rightChild = &bintritree[nextfreebintree++];
tri->leftChild->leaf = tri->leaf * 2;
tri->rightChild->leaf = (tri->leaf * 2) + 1;
tri->leftChild->morph = 0;
tri->rightChild->morph = 0;
tri->leftChild->leftNeighbour = tri->rightChild;
tri->rightChild->rightNeighbour = tri->leftChild;
tri->leftChild->bottomNeighbour = tri->leftNeighbour;
if (tri->leftNeighbour != 0) {
if (tri->leftNeighbour->bottomNeighbour == tri) {
tri->leftNeighbour->bottomNeighbour = tri->leftChild;
}
else {
if (tri->leftNeighbour->leftNeighbour == tri) {
tri->leftNeighbour->leftNeighbour = tri->leftChild;
}
else {
tri->leftNeighbour->rightNeighbour = tri->leftChild;
}
}
}
tri->rightChild->bottomNeighbour = tri->rightNeighbour;
if (tri->rightNeighbour != 0) {
if (tri->rightNeighbour->bottomNeighbour == tri) {
tri->rightNeighbour->bottomNeighbour = tri->rightChild;
}
else {
if (tri->rightNeighbour->rightNeighbour == tri) {
tri->rightNeighbour->rightNeighbour = tri->rightChild;
}
else {
tri->rightNeighbour->leftNeighbour = tri->rightChild;
}
}
}
tri->leftChild->leftChild = 0;
tri->leftChild->rightChild = 0;
tri->rightChild->leftChild = 0;
tri->rightChild->rightChild = 0;
tricount++;
}
////////////////////////////////////////////////////////////////////////////
// Private: insideTri()
// Params: float, float: left vertex of triangle.
// float, float: right vertex of triangle.
// float, float: apex of triangle.
// float, float: point tob checked.
// Return: Is point inside triangle.
// Side effects: None.
////////////////////////////////////////////////////////////////////////////
inline bool Terrain::insideTri(float x1, float y1, float x2, float y2,
float x3, float y3, float a, float b)
{
//FIXME: faster(?) if you get orientation of 1,2,ab and 1,3,ab
float d;
float c;
c = ((x2 - x1) * y1) - ((y2 - y1) * x1);
d = (((x2 - x1) * b) - ((y2 - y1) * a)) - c;
if (d > 0)
return false;
c = ((x3 - x2) * y2) - ((y3 - y2) * x2);
d = (((x3 - x2) * b) - ((y3 - y2) * a)) - c;
if (d > 0)
return false;
c = ((x1 - x3) * y3) - ((y1 - y3) * x3);
d = (((x1 - x3) * b) - ((y1 - y3) * a)) - c;
if (d > 0)
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////
// Private: CalcVarianceTree()
//
// Side effects: Built variance tree. varianceTree1 and varianceTree2
////////////////////////////////////////////////////////////////////////////
void Terrain::CalcVarianceTree()
{
int v;
varianceTree1 = new UINT8[256*256*2];
varianceTree2 = new UINT8[256*256*2];
// a level more than this makes no sence... i think...
maxtreedepth = 15;
ctreedepth = 0;
cvarianceTree = varianceTree1;
v = CalcVarianceTreeTM(0, 0, height, width, 0, width, 1);
Log::printf(L"max variance: %d.", v);
cvarianceTree = varianceTree2;
v = CalcVarianceTreeTM(height, width, 0, 0, height, 0, 1);
Log::printf(L"max variance: %d.", v);
}
////////////////////////////////////////////////////////////////////////////
// Private: CalcVarianceTreeTM()
// Params: UINT16, UINT16: right vertex
// UINT16, UINT16: left vertex
// UINT16, UINT16: apex vertex
// int: leaf number in variance tree.
// Return: variance of leaf.
////////////////////////////////////////////////////////////////////////////
int Terrain::CalcVarianceTreeTM(UINT16 x1, UINT16 y1, UINT16 x2,
UINT16 y2, UINT16 x3, UINT16 y3, int leaf)
{
int hx = (x1 + x2) / 2;
int hy = (y1 + y2) / 2;
int realHeight = getHeight(hx, hy);
int avgHeight = (getHeight(x1, y1) + getHeight(x2, y2)) / 2;
int v = abs(realHeight - avgHeight);
//stop recursion when grid size is less than 1
if (ctreedepth < 14) {
ctreedepth++;
int v1 = CalcVarianceTreeTM(x2, y2, x3, y3, hx, hy, leaf * 2);
if (v1 > v) v = v1;
ctreedepth++;
v1 = CalcVarianceTreeTM(x3, y3, x1, y1, hx, hy, (leaf * 2) + 1);
if (v1 > v) v = v1;
}
else if (ctreedepth < maxtreedepth) {
ctreedepth++;
int v1 = CalcVarianceTree((float)x2, (float)y2,
(float)x3, (float)y3,
(float)hx, (float)hy,
leaf * 2);
if (v1 > v) v = v1;
ctreedepth++;
v1 = CalcVarianceTree((float)x3, (float)y3,
(float)x1, (float)y1,
(float)hx, (float)hy,
(leaf * 2) + 1);
if (v1 > v) v = v1;
}
ctreedepth--;
cvarianceTree[leaf] = (UINT8)v;
return v;
}
////////////////////////////////////////////////////////////////////////////
// Private: CalcVarianceTree()
// Params: float, float: right vertex
// float, float: left vertex
// float, float: apex vertex
// int: leaf number in variance tree.
// Return: variance of leaf.
// Comments: used for small triagles - greater accuracy
////////////////////////////////////////////////////////////////////////////
int Terrain::CalcVarianceTree(float x1, float y1, float x2,
float y2, float x3, float y3, int leaf)
{
Vector v1;
Vector v2;
Vector v3;
Vector normal;
float hx = (x1 + x2) / 2;
float hy = (y1 + y2) / 2;
float realHeight = (float)getHeight((UINT16)hx, (UINT16)hy);
float avgHeight = (getHeight((UINT16)x1, (UINT16)y1) +
getHeight((UINT16)x2, (UINT16)y2)) / 2.0f;
float v = abs(realHeight - avgHeight);
v1[0] = x1;
v1[1] = getHeight((UINT16)x1, (UINT16)y1) * 0.1f;
v1[2] = y1;
v2[0] = x2;
v2[1] = getHeight((UINT16)x2, (UINT16)y2) * 0.1f;
v2[2] = y2;
v3[0] = x3;
v3[1] = getHeight((UINT16)x3, (UINT16)y3) * 0.1f;
v3[2] = y3;
getPlaneNormal(v1, v2, v3, normal);
normal[1] = abs(normal[1]);
normal[1] += (1 - normal[1]) / 2;
v = v * abs(normal[1]);
//stop recursion when grid size is less than 1;
if (ctreedepth < maxtreedepth) {
ctreedepth++;
float v1 = (float)
CalcVarianceTree((float)x2, (float)y2,
(float)x3, (float)y3,
(float)hx, (float)hy,
leaf * 2);
if (v1 > v) v = v1;
ctreedepth++;
v1 = (float)
CalcVarianceTree((float)x3, (float)y3,
(float)x1, (float)y1,
(float)hx, (float)hy,
(leaf * 2) + 1);
if (v1 > v) v = v1;
}
ctreedepth--;
cvarianceTree[leaf] = (UINT8)v;
return (int)v;
}
////////////////////////////////////////////////////////////////////////////
// Private: getHeight()
// Params: UINT16, UINT16: location on terrain
// Return: height value
// Comments: wraps.
////////////////////////////////////////////////////////////////////////////
inline int Terrain::getHeight(UINT16 x, UINT16 y)
{
x = x & 255;
y = y & 255;
return (int)heightmap[x+(y*256)];
}
////////////////////////////////////////////////////////////////////////////
// Private: getColor()
// Params: UINT16, UINT16: location on terrain
// Return: colour value
// Comments: wraps.
////////////////////////////////////////////////////////////////////////////
inline int Terrain::getColor(UINT16 x, UINT16 y)
{
x = x & 255;
y = y & 255;
return (int)colormap[x+(y*256)];
}
////////////////////////////////////////////////////////////////////////////
// Private: TriCull2D()
// Params: float, float: right vertex of triangle
// float, float: left vertex of triangle
// float, float: apex vertex of triangle
// Comments: the triangle is previously rotated, fov is 90, and in 2d
// Return: 1 if fully inside.
// 2 if fully outside.
// 0 if partly inside.
////////////////////////////////////////////////////////////////////////////
inline int Terrain::TriCull2D(float x1, float y1, float x2, float y2, float x3, float y3)
{
int a = PointCull2D(x1, y1);
int b = PointCull2D(x2, y2);
int c = PointCull2D(x3, y3);
//if fully inside
if (a == 0 && b == 0 && c == 0)
return 1;
// if partly inside
if (a == 0 || b == 0 || c == 0)
return 0;
if (LineCull2D(a, b, x1, y1, x2, y2))
return 0;
if (LineCull2D(b, c, x2, y2, x3, y3))
return 0;
if (LineCull2D(c, a, x3, y3, x1, y1))
return 0;
// else tri outside view
return 2;
}
////////////////////////////////////////////////////////////////////////////
// Private: LineCull2D();
// Params: ini, int: values from point cull, related to the other params
// float, float: start of line
// float, float: end of line
// Return: 1 if inside or maybe inside(!)
// 0 if outside.
////////////////////////////////////////////////////////////////////////////
inline int Terrain::LineCull2D(int a, int b, float x1, float y1, float x2, float y2)
{
// behind
if ((a&b) == 4)
return 0;
// infront and oppisite
if ((a | b) == 3)
return 1;
if ((a + b) == 7)
return 1; // need more checks...
else
return 0;
}
////////////////////////////////////////////////////////////////////////////
// Private: PointCull2D()
//
// Is point in view fustrum?
////////////////////////////////////////////////////////////////////////////
inline int Terrain::PointCull2D(float x, float y)
{
// if behind camera
if (y < camznear) {
// if to the left
if ((y - camznear) < x) {
return 5;
}
// if to the right
if ((y - camznear) < -x) {
return 6;
}
return 4;
}
else {
// if to the left
if ((y - camznear) < x) {
return 1;
}
// if to the right
if ((y - camznear) < -x) {
return 2;
}
// else point inside so..
return 0;
}
}
////////////////////////////////////////////////////////////////////////////
// Private: Collision()
//
// Comments: 'Slide' collision is done.
////////////////////////////////////////////////////////////////////////////
int Terrain::Collision(Vector oldpos, Vector pos, Vector newpos)
{
Vector diff, normal, v1, v2, v3;
int x = (int)oldpos[0] + 128;
int y = (int)oldpos[2] + 128;
newpos[0] = pos[0];
newpos[1] = pos[1];
newpos[2] = pos[2];
if ((x < 0) || (x > 254) || (y < 0) || (y > 254))
return 0;
if ( (pos[0] - (x - 128)) < (pos[2] - (y - 128)) ) {
v1[0] = x - 128.0f;
v1[1] = getHeight(x, y) * 0.1f;
v1[2] = y - 128.0f;
v2[0] = x - 127.0f;
v2[1] = getHeight(x + 1, y + 1) * 0.1f;
v2[2] = y - 127.0f;
v3[0] = x - 127.0f;
v3[1] = getHeight(x + 1, y) * 0.1f;
v3[2] = y - 128.0f;
}
else {
v1[0] = x - 128.0f;
v1[1] = getHeight(x, y) * 0.1f;
v1[2] = y - 128.0f;
v2[0] = x - 128.0f;
v2[1] = getHeight(x, y + 1) * 0.1f;
v2[2] = y - 127.0f;
v3[0] = x - 127.0f;
v3[1] = getHeight(x + 1, y + 1) * 0.1f;
v3[2] = y - 127.0f;
}
getPlaneNormal(v1, v2, v3, normal);
subtractVector(pos, v1, diff);
float d = scalerProduct(normal, diff);
if (d < 1.2f) {
newpos[0] -= normal[0] * (d - 1.2f);
newpos[1] -= normal[1] * (d - 1.2f);
newpos[2] -= normal[2] * (d - 1.2f);
}
return -1;
}
////////////////////////////////////////////////////////////////////////////
// Private: CalcLight()
//
// Comments: Cacluates a lightmap for the texture.
// The light is at infinity.
////////////////////////////////////////////////////////////////////////////
void Terrain::CalcLight()
{
float d, d1, d2;
Vector light, normal, v1, v2, v3;
light[0] = 0.7f;
light[1] = 0.5f;
light[2] = -0.5f;
colormap = new UINT8[256*256];
for (int y = 0; y < 256; y++) {
for (int x = 0; x < 256; x += 1) {
v1[0] = x - 128.0f;
v1[1] = getHeight(x, y) * 0.1f;
v1[2] = y - 128.0f;
v2[0] = x - 127.0f;
v2[1] = getHeight(x + 1, y + 1) * 0.1f;
v2[2] = y - 127.0f;
v3[0] = x - 127.0f;
v3[1] = getHeight(x + 1, y) * 0.1f;
v3[2] = y - 128.0f;
getPlaneNormal(v1, v2, v3, normal);
d1 = scalerProduct(normal, light);
v1[0] = x - 128.0f;
v1[1] = getHeight(x, y) * 0.1f;
v1[2] = y - 128.0f;
v2[0] = x - 128.0f;
v2[1] = getHeight(x, y + 1) * 0.1f;
v2[2] = y - 127.0f;
v3[0] = x - 127.0f;
v3[1] = getHeight(x + 1, y + 1) * 0.1f;
v3[2] = y - 127.0f;
getPlaneNormal(v1, v2, v3, normal);
d2 = scalerProduct(normal, light);
d = (d1 + d2) / 2;
if (d > 0.2f) {
colormap[(y*256)+x] = (UINT8)(d * 255.0f);
}
else {
colormap[(y*256)+x] = (UINT8)(0.2f * 255.0f);
}
}
}
}
////////////////////////////////////////////////////////////////////////////
// Private: CalcTexture()
//
// Comments: Generates a texture for the terrain.
////////////////////////////////////////////////////////////////////////////
void Terrain::CalcTexture()
{
texturemap = new UINT8[256*256*3];
for (int y = 0; y < 256; y++) {
for (int x = 0; x < 256; x++) {
if (getHeight(x, y) == 0) {
texturemap[((y*256)+x)*3] = 0;
texturemap[(((y*256)+x)*3)+1] = 100;
texturemap[(((y*256)+x)*3)+2] = 180;
}
else {
texturemap[((y*256)+x)*3] = 32;
texturemap[(((y*256)+x)*3)+1] = getColor(x, y);
texturemap[(((y*256)+x)*3)+2] = getHeight(x, y);
}
}
}
glGenTextures(1, &gltexture);
glBindTexture(GL_TEXTURE_2D, gltexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, 3, 256, 256, 0, GL_RGB, GL_UNSIGNED_BYTE, texturemap);
}
////////////////////////////////////////////////////////////////////////////
// Private: CalcAreaOfInterest()
//
// Comments: Calculates where the viewer is looking on the terrain.
////////////////////////////////////////////////////////////////////////////
void Terrain::CalcAreaOfInterest(Viewer *viewer)
{
aoipos[0] = viewer->pos[0] + 128;
aoipos[1] = viewer->pos[1];
aoipos[2] = viewer->pos[2] + 128;
aoi = false;
placename = "Void";
if (aoipos[1] > 25.6f) {
if (viewer->aoidir[1] >= 0.0f) return;
float s = (aoipos[1] - 25.6f) / viewer->aoidir[1];
aoipos[0] -= s * viewer->aoidir[0];
aoipos[1] -= s * viewer->aoidir[1];
aoipos[2] -= s * viewer->aoidir[2];
}
else if (aoipos[1] < 0.0f) {
if (viewer->aoidir[1] < 0.0f) return;
float s = (aoipos[1]) / viewer->aoidir[1];
aoipos[0] -= s * viewer->aoidir[0];
aoipos[1] -= s * viewer->aoidir[1];
aoipos[2] -= s * viewer->aoidir[2];
}
bool bDone = false;
while (!bDone) {
if (aoipos[0] < 0 && viewer->aoidir[0] < 0) {
return;
}
if (aoipos[0] > 256 && viewer->aoidir[0] > 0) {
return;
}
if (aoipos[2] < 0 && viewer->aoidir[2] < 0) {
return;
}
if (aoipos[2] > 256 && viewer->aoidir[2] > 0) {
return;
}
if (aoipos[1] < (getHeight((UINT16)aoipos[0], (UINT16)aoipos[2]) / 10)) {
bDone = true;
break;
}
aoipos[0] += viewer->aoidir[0];
aoipos[1] += viewer->aoidir[1];
aoipos[2] += viewer->aoidir[2];
}
placename = location.getPlaceName((int)aoipos[0],
255 - (int)aoipos[2]);
aoipos[0] += -128;
aoipos[1] += 0;
aoipos[2] += -128;
viewer->aoipos[0] = aoipos[0];
viewer->aoipos[1] = aoipos[1];
viewer->aoipos[2] = aoipos[2];
range = sqrt(((aoipos[0] - viewer->pos[0]) * (aoipos[0] - viewer->pos[0])) +
((aoipos[1] - viewer->pos[1]) * (aoipos[1] - viewer->pos[1])) +
((aoipos[2] - viewer->pos[2]) * (aoipos[2] - viewer->pos[2])));
range = range * 10;
invrange = 3 / range;
aoi = true;
}
| [
"watsonmw@gmail.com"
] | watsonmw@gmail.com |
e062d6f4d40808db7328067db2a03f02888f9816 | a96f0a36ffd4b91dd059420b79856931b5e0f5e3 | /SolveConnect2/MoveInstructionsExit.cpp | 4a8e1c5d5d2fff366c060a82622e988ba27cfb1b | [
"Unlicense"
] | permissive | rothor/Connect2Solver | 5163e8a8e21f40cd5bc2bf15df297a17a249e87c | eca13bfb374443e5877ece3266f874dcacaab5d6 | refs/heads/master | 2022-09-17T16:45:11.003015 | 2020-05-27T05:49:34 | 2020-05-27T05:49:34 | 267,188,047 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 317 | cpp | #include "MoveInstructionsExit.h"
MoveInstructionsExit::MoveInstructionsExit(bool isForced,
bool mustTeleport,
Point teleportPoint,
bool resetIfOnlyForcedMovesAfter) :
isForced(isForced),
mustTeleport(mustTeleport),
teleportPoint(teleportPoint),
resetIfOnlyForcedMovesAfter(resetIfOnlyForcedMovesAfter)
{
}
| [
"warm.juice@yahoo.com"
] | warm.juice@yahoo.com |
e9a66c9b45349acf8f03b599f2f20ced652a34b9 | 5a8168174356adbdf8c95a6c493e03e14e568079 | /src/shapely.cpp | 634bfee7d1d95beb4a0cb6f5296cfa073f74ed01 | [
"Apache-2.0"
] | permissive | UTNuclearRobotics/descartes_tutorials | 133f9edc7861f4ca8aa7a7ed08f6af66f844e799 | 3245e2b262818563c017af8788936f64c1869f2e | refs/heads/master | 2021-01-01T04:23:37.419903 | 2018-07-12T21:25:15 | 2018-07-12T21:25:15 | 97,168,045 | 0 | 0 | null | 2017-07-13T21:58:01 | 2017-07-13T21:58:01 | null | UTF-8 | C++ | false | false | 8,914 | cpp | // Core ros functionality like ros::init and spin
#include <ros/ros.h>
// ROS Trajectory Action server definition
#include <control_msgs/FollowJointTrajectoryAction.h>
// Means by which we communicate with above action-server
#include <actionlib/client/simple_action_client.h>
// Includes the descartes robot model we will be using
#include <descartes_moveit/moveit_state_adapter.h>
// Includes the descartes trajectory type we will be using
#include <descartes_trajectory/axial_symmetric_pt.h>
#include <descartes_trajectory/cart_trajectory_pt.h>
// Includes the planner we will be using
#include <descartes_planner/dense_planner.h>
#include <tf/tf.h>
#include <eigen_conversions/eigen_msg.h>
#include <geometry_msgs/Pose.h>
#include "move_interface/move_interface.h"
#include <moveit/move_group_interface/move_group_interface.h>
#include <moveit/planning_interface/planning_interface.h>
#include <moveit_msgs/PlanningScene.h>
#include <moveit/robot_model_loader/robot_model_loader.h>
#include <moveit/robot_state/robot_state.h>
#include <moveit/robot_state/conversions.h>
#include <string>
#include <vector>
std::vector<double> getCurrentJointState(const std::string& topic)
{
sensor_msgs::JointStateConstPtr state = ros::topic::waitForMessage<sensor_msgs::JointState>(topic, ros::Duration(0.0));
if (!state) throw std::runtime_error("Joint state message capture failed");
return state->position;
}
int main(int argc, char** argv)
{
// Initialize ROS
ros::init(argc, argv, "descartes_tutorial");
ros::NodeHandle nh;
// Required for communication with moveit components
ros::AsyncSpinner spinner (2);
spinner.start();
float xPos;
float yPos;
float zPos;
std::string moveGroup, fixedFrame;
if(nh.getParam("/config_data/move_group", moveGroup) &&
nh.getParam("/config_data/fixed_frame", fixedFrame) &&
nh.getParam("/config_data/x_pos", xPos) &&
nh.getParam("/config_data/y_pos", yPos) &&
nh.getParam("/config_data/z_pos", zPos))
{
}
else
{
ROS_ERROR("Unable to get config data from param server. Ending demo.");
return false;
}
moveit::planning_interface::MoveGroupInterface group(moveGroup);
EigenSTL::vector_Affine3d poses;
// 1. Define sequence of points
/* geometry_msgs::Pose target_pose1;
target_pose1.orientation.w = 1.0;
target_pose1.position.x = 0.0;
target_pose1.position.y = 0.5;
target_pose1.position.z = 0.5;
Eigen::Quaterniond quat;
Eigen::Quaterniond quat1;
double rotationRadians = 3.14195/2;
Eigen::Vector3d rotationVector = Eigen::Vector3d(0,0,1);
quat = Eigen::AngleAxisd(rotationRadians, rotationVector);
rotationVector = Eigen::Vector3d(0,1,0);
quat1 = Eigen::AngleAxisd(rotationRadians, rotationVector);
quat = quat*quat1;
tf::quaternionEigenToMsg(quat, target_pose1.orientation);
group.setPoseTarget(target_pose1);
moveit::planning_interface::MoveGroupInterface::Plan my_plan;
bool success = group.plan(my_plan);
ROS_INFO("Visualizing plan 1 (pose goal) %s",success?"":"FAILED");
*/
/* Sleep to give Rviz time to visualize the plan. */
ros::Duration(1.0).sleep();
double R = 0.04;
double angle = 2*3.14195/21;
double offset = (R-0.005)/3;
for (unsigned int i = 0; i < 1; ++i)
{
Eigen::Affine3d pose;
double o = offset*i;
double r = sqrt(R*R-o*o);
for (unsigned int j = 0; j < 20; j++) // j = 21
{
pose = Eigen::Translation3d((xPos+r*cos(angle*j)), (yPos+(r)*sin(angle*j)), zPos +(o));
Eigen::Quaterniond quat;
double rotationRadians = 3.14195;
Eigen::Vector3d rotationVector = Eigen::Vector3d(0,1,0);
quat = Eigen::AngleAxisd(rotationRadians, rotationVector);
Eigen::Matrix3d rotMat; rotMat = quat;
pose.linear() *= rotMat;
/*
rotationRadians = 3.14195/2;
rotationVector = Eigen::Vector3d(0,1,0);
quat = Eigen::AngleAxisd(rotationRadians, rotationVector);
rotMat = quat;
pose.linear() *= rotMat;
rotationRadians = 3.14195/2;
rotationVector = Eigen::Vector3d(0,1,0);
quat = Eigen::AngleAxisd(rotationRadians, rotationVector);
rotMat = quat;
pose.linear() *= rotMat;
*/
poses.push_back(pose);
ros::Duration(0.1).sleep();
}
}
/*
Eigen::Quaterniond quat;
double rotationRadians = 3.14195/2;
Eigen::Vector3d rotationVector = Eigen::Vector3d(0,0,1);
quat = Eigen::AngleAxisd(rotationRadians, rotationVector);
Eigen::Matrix3d rotMat; rotMat = quat;
pose.linear() *= rotMat;
rotationRadians = 3.14195/2;
rotationVector = Eigen::Vector3d(0,1,0);
quat = Eigen::AngleAxisd(rotationRadians, rotationVector);
rotMat = quat;
pose.linear() *= rotMat;
*/
/*
descartes_core::TrajectoryPtPtr pt = makeTolerancedCartesianPoint(pose);
points.push_back(pt);
poses.push_back(pose);
*/
ros::Duration(0.1).sleep();
ros::Duration(0.5).sleep();
MoveInterface mi = MoveInterface();
mi.initialize(moveGroup);
// creating rviz markers
visualization_msgs::Marker z_axes, y_axes, x_axes, line;
visualization_msgs::MarkerArray markers_msg;
float AXIS_LINE_WIDTH = 0.02;
float AXIS_LINE_LENGTH = 0.02;
ros::Publisher marker_publisher_ = nh.advertise<visualization_msgs::MarkerArray>("chatter", 1000);
z_axes.type = y_axes.type = x_axes.type = visualization_msgs::Marker::LINE_LIST;
z_axes.ns = y_axes.ns = x_axes.ns = "axes";
z_axes.action = y_axes.action = x_axes.action = visualization_msgs::Marker::ADD;
z_axes.lifetime = y_axes.lifetime = x_axes.lifetime = ros::Duration(0);
z_axes.header.frame_id = y_axes.header.frame_id = x_axes.header.frame_id = fixedFrame;
z_axes.scale.x = y_axes.scale.x = x_axes.scale.x = AXIS_LINE_WIDTH;
// z properties
z_axes.id = 0;
z_axes.color.r = 0;
z_axes.color.g = 0;
z_axes.color.b = 1;
z_axes.color.a = 1;
// y properties
y_axes.id = 1;
y_axes.color.r = 0;
y_axes.color.g = 1;
y_axes.color.b = 0;
y_axes.color.a = 1;
// x properties
x_axes.id = 2;
x_axes.color.r = 1;
x_axes.color.g = 0;
x_axes.color.b = 0;
x_axes.color.a = 1;
// line properties
line.type = visualization_msgs::Marker::LINE_STRIP;
line.ns = "line";
line.action = visualization_msgs::Marker::ADD;
line.lifetime = ros::Duration(0);
line.header.frame_id = fixedFrame;
line.scale.x = AXIS_LINE_WIDTH;
line.id = 0;
line.color.r = 1;
line.color.g = 0;
line.color.b = 0;
line.color.a = 0;
// creating axes markers
z_axes.points.reserve(2*poses.size());
y_axes.points.reserve(2*poses.size());
x_axes.points.reserve(2*poses.size());
line.points.reserve(poses.size());
geometry_msgs::Point p_start,p_end;
double distance = 0;
Eigen::Affine3d prev = poses[0];
for(unsigned int i = 0; i < poses.size(); i++)
{
const Eigen::Affine3d& pose = poses[i];
distance = (pose.translation() - prev.translation()).norm();
tf::pointEigenToMsg(pose.translation(),p_start);
geometry_msgs::Pose pose_request;
tf::poseEigenToMsg(pose,pose_request);
geometry_msgs::PoseStamped pose_test;
pose_test.header.frame_id = fixedFrame;
pose_test.pose = pose_request;
bool success = mi.planMove(pose_test, 1.0, false);
// mi.moveArm(pose_test, 1.0, false);
if(success==0)
{
Eigen::Affine3d moved_along_x = pose * Eigen::Translation3d(AXIS_LINE_LENGTH,0,0);
tf::pointEigenToMsg(moved_along_x.translation(),p_end);
x_axes.points.push_back(p_start);
x_axes.points.push_back(p_end);
}
else
{
Eigen::Affine3d moved_along_y = pose * Eigen::Translation3d(0,AXIS_LINE_LENGTH,0);
tf::pointEigenToMsg(moved_along_y.translation(),p_end);
y_axes.points.push_back(p_start);
y_axes.points.push_back(p_end);
}
if(distance > 0.01)
{
Eigen::Affine3d moved_along_z = pose * Eigen::Translation3d(0,0,AXIS_LINE_LENGTH);
tf::pointEigenToMsg(moved_along_z.translation(),p_end);
z_axes.points.push_back(p_start);
z_axes.points.push_back(p_end);
// saving previous
prev = pose;
}
line.points.push_back(p_start);
}
markers_msg.markers.push_back(x_axes);
markers_msg.markers.push_back(y_axes);
markers_msg.markers.push_back(z_axes);
markers_msg.markers.push_back(line);
while(marker_publisher_.getNumSubscribers() < 1)
{
ros::Duration(1.0).sleep();
ROS_INFO_THROTTLE(5,"Check RViz to make sure you are subscribed to the marker array /chatter.");
}
marker_publisher_.publish(markers_msg);
ros::spinOnce();
ros::Duration(1.0).sleep();
ros::Duration(0.5).sleep();
/* for (unsigned int i = 0; i < 5; ++i)
{
Eigen::Affine3d pose;
pose = Eigen::Translation3d(0.0, 0.04 * i, 1.3);
descartes_core::TrajectoryPtPtr pt = makeTolerancedCartesianPoint(pose);
points.push_back(pt);
}
*/
// Wait till user kills the process (Control-C)
return 0;
}
| [
"cpetlowany@gmail.com"
] | cpetlowany@gmail.com |
2d5ab229aa9e25afb5cc5b78ad06656459b99879 | 5cb82722442bb6e888f1cea59544d0d6fd01bf2f | /Source/Renderer/Public/Resource/Material/MaterialResource.cpp | 6c145a61c8a68e048b912e298a440edce0ea931d | [
"MIT"
] | permissive | RobertoMalatesta/unrimp | d9a137c5041adcc5e8b9f075586effec70eda2c6 | 90310657f106eb83f3a9688329b78619255a1042 | refs/heads/master | 2023-07-28T08:31:36.699889 | 2021-09-09T18:24:26 | 2021-09-09T19:03:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,513 | cpp | /*********************************************************\
* Copyright (c) 2012-2021 The Unrimp Team
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "Renderer/Public/Resource/Material/MaterialResource.h"
#include "Renderer/Public/Resource/Material/MaterialTechnique.h"
#include "Renderer/Public/Resource/Material/MaterialResourceManager.h"
#include "Renderer/Public/RenderQueue/RenderableManager.h"
#include <algorithm>
//[-------------------------------------------------------]
//[ Anonymous detail namespace ]
//[-------------------------------------------------------]
namespace
{
namespace detail
{
//[-------------------------------------------------------]
//[ Structures ]
//[-------------------------------------------------------]
struct OrderByMaterialResourceId final
{
[[nodiscard]] inline bool operator()(Renderer::MaterialResourceId left, Renderer::MaterialResourceId right) const
{
return (left < right);
}
};
struct OrderByMaterialTechniqueId final
{
[[nodiscard]] inline bool operator()(const Renderer::MaterialTechnique* left, Renderer::MaterialTechniqueId right) const
{
return (left->getMaterialTechniqueId() < right);
}
[[nodiscard]] inline bool operator()(Renderer::MaterialTechniqueId left, const Renderer::MaterialTechnique* right) const
{
return (left < right->getMaterialTechniqueId());
}
};
//[-------------------------------------------------------]
//[ Anonymous detail namespace ]
//[-------------------------------------------------------]
} // detail
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace Renderer
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
Context& MaterialResource::getContext() const
{
return getResourceManager<MaterialResourceManager>().getRenderer().getContext();
}
void MaterialResource::setParentMaterialResourceId(MaterialResourceId parentMaterialResourceId)
{
if (mParentMaterialResourceId != parentMaterialResourceId)
{
const MaterialResourceId materialResourceId = getId();
// Destroy all material techniques
destroyAllMaterialTechniques();
// Unregister from previous parent material resource
const MaterialResourceManager& materialResourceManager = getResourceManager<MaterialResourceManager>();
if (isValid(mParentMaterialResourceId))
{
MaterialResource& parentMaterialResource = materialResourceManager.getById(mParentMaterialResourceId);
SortedChildMaterialResourceIds::const_iterator iterator = std::lower_bound(parentMaterialResource.mSortedChildMaterialResourceIds.cbegin(), parentMaterialResource.mSortedChildMaterialResourceIds.cend(), materialResourceId, ::detail::OrderByMaterialResourceId());
RHI_ASSERT(getContext(), iterator != parentMaterialResource.mSortedChildMaterialResourceIds.end() && *iterator == materialResourceId, "Invalid material resource ID")
parentMaterialResource.mSortedChildMaterialResourceIds.erase(iterator);
}
// Set new parent material resource ID
mParentMaterialResourceId = parentMaterialResourceId;
if (isValid(mParentMaterialResourceId))
{
// Register to new parent material resource
MaterialResource& parentMaterialResource = materialResourceManager.getById(mParentMaterialResourceId);
RHI_ASSERT(getContext(), parentMaterialResource.getLoadingState() == IResource::LoadingState::LOADED, "Invalid parent material resource loading state")
SortedChildMaterialResourceIds::const_iterator iterator = std::lower_bound(parentMaterialResource.mSortedChildMaterialResourceIds.cbegin(), parentMaterialResource.mSortedChildMaterialResourceIds.cend(), materialResourceId, ::detail::OrderByMaterialResourceId());
RHI_ASSERT(getContext(), iterator == parentMaterialResource.mSortedChildMaterialResourceIds.end() || *iterator != materialResourceId, "Invalid material resource ID")
parentMaterialResource.mSortedChildMaterialResourceIds.insert(iterator, materialResourceId);
// Setup material resource
setAssetId(parentMaterialResource.getAssetId());
mMaterialProperties = parentMaterialResource.mMaterialProperties;
for (MaterialTechnique* materialTechnique : parentMaterialResource.mSortedMaterialTechniqueVector)
{
mSortedMaterialTechniqueVector.push_back(new MaterialTechnique(materialTechnique->getMaterialTechniqueId(), *this, materialTechnique->getMaterialBlueprintResourceId()));
}
}
else
{
// Don't touch the child material resources, but reset everything else
mMaterialProperties.removeAllProperties();
}
}
}
MaterialTechnique* MaterialResource::getMaterialTechniqueById(MaterialTechniqueId materialTechniqueId) const
{
SortedMaterialTechniqueVector::const_iterator iterator = std::lower_bound(mSortedMaterialTechniqueVector.cbegin(), mSortedMaterialTechniqueVector.cend(), materialTechniqueId, ::detail::OrderByMaterialTechniqueId());
return (iterator != mSortedMaterialTechniqueVector.end() && (*iterator)->getMaterialTechniqueId() == materialTechniqueId) ? *iterator : nullptr;
}
void MaterialResource::destroyAllMaterialTechniques()
{
for (MaterialTechnique* materialTechnique : mSortedMaterialTechniqueVector)
{
delete materialTechnique;
}
mSortedMaterialTechniqueVector.clear();
}
void MaterialResource::releaseTextures()
{
// TODO(co) Cleanup
for (MaterialTechnique* materialTechnique : mSortedMaterialTechniqueVector)
{
materialTechnique->clearTextures();
}
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
MaterialResource::~MaterialResource()
{
// Sanity checks
RHI_ASSERT(getContext(), isInvalid(mParentMaterialResourceId), "Invalid parent material resource ID")
RHI_ASSERT(getContext(), mSortedChildMaterialResourceIds.empty(), "Invalid sorted child material resource IDs")
RHI_ASSERT(getContext(), mSortedMaterialTechniqueVector.empty(), "Invalid sorted material technique vector")
RHI_ASSERT(getContext(), mMaterialProperties.getSortedPropertyVector().empty(), "Invalid material properties")
RHI_ASSERT(getContext(), mAttachedRenderables.empty(), "Invalid attached renderables")
// Avoid crash in case of failed sanity check
while (!mAttachedRenderables.empty())
{
mAttachedRenderables[0]->unsetMaterialResourceId();
}
}
MaterialResource& MaterialResource::operator=(MaterialResource&& materialResource)
{
// Call base implementation
IResource::operator=(std::move(materialResource));
// Swap data
// -> Lucky us that we're usually not referencing by using raw-pointers, so a simple swap does the trick
std::swap(mParentMaterialResourceId, materialResource.mParentMaterialResourceId);
std::swap(mSortedChildMaterialResourceIds, materialResource.mSortedChildMaterialResourceIds);
std::swap(mSortedMaterialTechniqueVector, materialResource.mSortedMaterialTechniqueVector);
std::swap(mMaterialProperties, materialResource.mMaterialProperties);
std::swap(mAttachedRenderables, materialResource.mAttachedRenderables);
// Done
return *this;
}
void MaterialResource::deinitializeElement()
{
// Sanity check
RHI_ASSERT(getContext(), mAttachedRenderables.empty(), "Invalid attached renderables")
// Avoid crash in case of failed sanity check
while (!mAttachedRenderables.empty())
{
mAttachedRenderables[0]->unsetMaterialResourceId();
}
// Unset parent material resource ID
setParentMaterialResourceId(getInvalid<MaterialResourceId>());
// Inform child material resources, if required
if (!mSortedChildMaterialResourceIds.empty())
{
const MaterialResourceManager& materialResourceManager = static_cast<MaterialResourceManager&>(getResourceManager());
while (!mSortedChildMaterialResourceIds.empty())
{
const MaterialResourceId materialResourceId = mSortedChildMaterialResourceIds.front();
materialResourceManager.getById(materialResourceId).setParentMaterialResourceId(getInvalid<MaterialResourceId>());
}
mSortedChildMaterialResourceIds.clear();
}
// Cleanup
destroyAllMaterialTechniques();
mMaterialProperties.removeAllProperties();
// Call base implementation
IResource::deinitializeElement();
}
bool MaterialResource::setPropertyByIdInternal(MaterialPropertyId materialPropertyId, const MaterialPropertyValue& materialPropertyValue, MaterialProperty::Usage materialPropertyUsage, bool changeOverwrittenState)
{
// Call the base implementation
MaterialProperty* materialProperty = mMaterialProperties.setPropertyById(materialPropertyId, materialPropertyValue, materialPropertyUsage, changeOverwrittenState);
if (nullptr != materialProperty)
{
// Perform derived work, if required to do so
switch (materialProperty->getUsage())
{
case MaterialProperty::Usage::SHADER_UNIFORM:
for (MaterialTechnique* materialTechnique : mSortedMaterialTechniqueVector)
{
materialTechnique->scheduleForShaderUniformUpdate();
}
break;
case MaterialProperty::Usage::SHADER_COMBINATION:
// Handled by "Renderer::MaterialProperties::setPropertyById()"
break;
case MaterialProperty::Usage::RASTERIZER_STATE:
case MaterialProperty::Usage::DEPTH_STENCIL_STATE:
case MaterialProperty::Usage::BLEND_STATE:
// TODO(co) Optimization: The calculation of the FNV1a hash of "Rhi::SerializedGraphicsPipelineState" is pretty fast, but maybe it makes sense to schedule the calculation in case many material properties are changed in a row?
for (MaterialTechnique* materialTechnique : mSortedMaterialTechniqueVector)
{
materialTechnique->calculateSerializedGraphicsPipelineStateHash();
}
break;
case MaterialProperty::Usage::TEXTURE_REFERENCE:
for (MaterialTechnique* materialTechnique : mSortedMaterialTechniqueVector)
{
materialTechnique->clearTextures();
}
break;
case MaterialProperty::Usage::STATIC:
// Initial cached material data gathering is performed inside "Renderer::Renderable::setMaterialResourceId()"
// Optional "RenderQueueIndex" (e.g. compositor materials usually don't need this property)
if (RENDER_QUEUE_INDEX_PROPERTY_ID == materialPropertyId)
{
const int renderQueueIndex = materialProperty->getIntegerValue();
// Sanity checks
RHI_ASSERT(getContext(), renderQueueIndex >= 0, "Invalid render queue index")
RHI_ASSERT(getContext(), renderQueueIndex <= 255, "Invalid render queue index")
// Update the cached material data of all attached renderables
for (Renderable* renderable : mAttachedRenderables)
{
renderable->mRenderQueueIndex = static_cast<uint8_t>(renderQueueIndex);
// In here we don't care about the fact that one and the same renderable manager instance might
// update cached renderables data. It's not performance critical in here and resolving this will
// require additional logic which itself has an performance impact. So keep it simple.
renderable->getRenderableManager().updateCachedRenderablesData();
}
}
// Optional "CastShadows" (e.g. compositor materials usually don't need this property)
else if (CAST_SHADOWS_PROPERTY_ID == materialPropertyId)
{
// Update the cached material data of all attached renderables
const bool castShadows = materialProperty->getBooleanValue();
for (Renderable* renderable : mAttachedRenderables)
{
renderable->mCastShadows = castShadows;
// In here we don't care about the fact that one and the same renderable manager instance might
// update cached renderables data. It's not performance critical in here and resolving this will
// require additional logic which itself has an performance impact. So keep it simple.
renderable->getRenderableManager().updateCachedRenderablesData();
}
}
// Optional "UseAlphaMap"
else if (USE_ALPHA_MAP_PROPERTY_ID == materialPropertyId)
{
// Update the cached material data of all attached renderables
const bool useAlphaMap = materialProperty->getBooleanValue();
for (Renderable* renderable : mAttachedRenderables)
{
renderable->mUseAlphaMap = useAlphaMap;
// In here we don't care about the fact that one and the same renderable manager instance might
// update cached renderables data. It's not performance critical in here and resolving this will
// require additional logic which itself has an performance impact. So keep it simple.
renderable->getRenderableManager().updateCachedRenderablesData();
}
}
break;
case MaterialProperty::Usage::UNKNOWN:
case MaterialProperty::Usage::SAMPLER_STATE:
case MaterialProperty::Usage::GLOBAL_REFERENCE:
case MaterialProperty::Usage::UNKNOWN_REFERENCE:
case MaterialProperty::Usage::PASS_REFERENCE:
case MaterialProperty::Usage::MATERIAL_REFERENCE:
case MaterialProperty::Usage::INSTANCE_REFERENCE:
case MaterialProperty::Usage::GLOBAL_REFERENCE_FALLBACK:
default:
// Nothing here
break;
}
// Inform child material resources, if required
const MaterialResourceManager& materialResourceManager = static_cast<MaterialResourceManager&>(getResourceManager());
for (MaterialResourceId materialResourceId : mSortedChildMaterialResourceIds)
{
materialResourceManager.getById(materialResourceId).setPropertyByIdInternal(materialPropertyId, materialPropertyValue, materialPropertyUsage, false);
}
// Material property change detected
return true;
}
// No material property change detected
return false;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // Renderer
| [
"cofenberg@gmail.com"
] | cofenberg@gmail.com |
6a1abca18f7b099e259a48b2411c3266066ed802 | a1091ad42e6a07b6fbb6fe876feb03547a8da1eb | /MITK-superbuild/ep/include/ITK-4.7/itkAffineTransform.hxx | 80ddcc40ddf04aaf085c1081143d76e71f5141d9 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | Sotatek-TuyenLuu/DP2 | bc61866fe5d388dd11209f4d02744df073ec114f | a48dd0a41c788981009c5ddd034b0e21644c8077 | refs/heads/master | 2020-03-10T04:59:52.461184 | 2018-04-12T07:19:27 | 2018-04-12T07:19:27 | 129,206,578 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,602 | hxx | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkAffineTransform_hxx
#define __itkAffineTransform_hxx
#include "itkNumericTraits.h"
#include "itkAffineTransform.h"
#include "vnl/algo/vnl_matrix_inverse.h"
namespace itk
{
/** Constructor with default arguments */
template< typename TScalar, unsigned int NDimensions >
AffineTransform< TScalar, NDimensions >::AffineTransform():Superclass(ParametersDimension)
{}
/** Constructor with default arguments */
template< typename TScalar, unsigned int NDimensions >
AffineTransform< TScalar, NDimensions >::AffineTransform(unsigned int parametersDimension):
Superclass(parametersDimension)
{}
/** Constructor with explicit arguments */
template< typename TScalar, unsigned int NDimensions >
AffineTransform< TScalar, NDimensions >::AffineTransform(const MatrixType & matrix,
const OutputVectorType & offset):
Superclass(matrix, offset)
{}
/** Destructor */
template< typename TScalar, unsigned int NDimensions >
AffineTransform< TScalar, NDimensions >::
~AffineTransform()
{
}
/** Print self */
template< typename TScalar, unsigned int NDimensions >
void
AffineTransform< TScalar, NDimensions >::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
/** Compose with a translation */
template< typename TScalar, unsigned int NDimensions >
void
AffineTransform< TScalar, NDimensions >::Translate(const OutputVectorType & trans, bool pre)
{
OutputVectorType newTranslation = this->GetTranslation();
if ( pre )
{
newTranslation += this->GetMatrix() * trans;
}
else
{
newTranslation += trans;
}
this->SetVarTranslation(newTranslation);
this->ComputeOffset();
this->Modified();
}
/** Compose with isotropic scaling */
template< typename TScalar, unsigned int NDimensions >
void
AffineTransform< TScalar, NDimensions >
::Scale(const TScalar & factor, bool pre)
{
if ( pre )
{
MatrixType newMatrix = this->GetMatrix();
newMatrix *= factor;
this->SetVarMatrix(newMatrix);
}
else
{
MatrixType newMatrix = this->GetMatrix();
newMatrix *= factor;
this->SetVarMatrix(newMatrix);
OutputVectorType newTranslation = this->GetTranslation();
newTranslation *= factor;
this->SetVarTranslation(newTranslation);
}
this->ComputeMatrixParameters();
this->ComputeOffset();
this->Modified();
}
/** Compose with anisotropic scaling */
template< typename TScalar, unsigned int NDimensions >
void
AffineTransform< TScalar, NDimensions >
::Scale(const OutputVectorType & factor, bool pre)
{
MatrixType trans;
unsigned int i, j;
for ( i = 0; i < NDimensions; i++ )
{
for ( j = 0; j < NDimensions; j++ )
{
trans[i][j] = 0.0;
}
trans[i][i] = factor[i];
}
if ( pre )
{
this->SetVarMatrix(this->GetMatrix() * trans);
}
else
{
this->SetVarMatrix( trans * this->GetMatrix() );
this->SetVarTranslation( trans * this->GetTranslation() );
}
this->ComputeMatrixParameters();
this->ComputeOffset();
this->Modified();
}
/** Compose with elementary rotation */
template< typename TScalar, unsigned int NDimensions >
void
AffineTransform< TScalar, NDimensions >
::Rotate(int axis1, int axis2, TScalar angle, bool pre)
{
MatrixType trans;
unsigned int i, j;
for ( i = 0; i < NDimensions; i++ )
{
for ( j = 0; j < NDimensions; j++ )
{
trans[i][j] = 0.0;
}
trans[i][i] = 1.0;
}
trans[axis1][axis1] = std::cos(angle);
trans[axis1][axis2] = std::sin(angle);
trans[axis2][axis1] = -std::sin(angle);
trans[axis2][axis2] = std::cos(angle);
if ( pre )
{
this->SetVarMatrix(this->GetMatrix() * trans);
}
else
{
this->SetVarMatrix( trans * this->GetMatrix() );
this->SetVarTranslation( trans * this->GetTranslation() );
}
this->ComputeMatrixParameters();
this->ComputeOffset();
this->Modified();
}
/** Compose with 2D rotation
* \todo Find a way to generate a compile-time error
* is this is used with NDimensions != 2. */
template< typename TScalar, unsigned int NDimensions >
void
AffineTransform< TScalar, NDimensions >
::Rotate2D(TScalar angle, bool pre)
{
MatrixType trans;
trans[0][0] = std::cos(angle);
trans[0][1] = -std::sin(angle);
trans[1][0] = std::sin(angle);
trans[1][1] = std::cos(angle);
if ( pre )
{
this->SetVarMatrix(this->GetMatrix() * trans);
}
else
{
this->SetVarMatrix( trans * this->GetMatrix() );
this->SetVarTranslation( trans * this->GetTranslation() );
}
this->ComputeMatrixParameters();
this->ComputeOffset();
this->Modified();
}
/** Compose with 3D rotation
* \todo Find a way to generate a compile-time error
* is this is used with NDimensions != 3. */
template< typename TScalar, unsigned int NDimensions >
void
AffineTransform< TScalar, NDimensions >
::Rotate3D(const OutputVectorType & axis, TScalar angle, bool pre)
{
MatrixType trans;
ScalarType r, x1, x2, x3;
ScalarType q0, q1, q2, q3;
// Convert the axis to a unit vector
r = std::sqrt(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]);
x1 = axis[0] / r;
x2 = axis[1] / r;
x3 = axis[2] / r;
// Compute quaternion elements
q0 = std::cos(angle / 2.0);
q1 = x1 * std::sin(angle / 2.0);
q2 = x2 * std::sin(angle / 2.0);
q3 = x3 * std::sin(angle / 2.0);
// Compute elements of the rotation matrix
trans[0][0] = q0 * q0 + q1 * q1 - q2 * q2 - q3 * q3;
trans[0][1] = 2.0 * ( q1 * q2 - q0 * q3 );
trans[0][2] = 2.0 * ( q1 * q3 + q0 * q2 );
trans[1][0] = 2.0 * ( q1 * q2 + q0 * q3 );
trans[1][1] = q0 * q0 + q2 * q2 - q1 * q1 - q3 * q3;
trans[1][2] = 2.0 * ( q2 * q3 - q0 * q1 );
trans[2][0] = 2.0 * ( q1 * q3 - q0 * q2 );
trans[2][1] = 2.0 * ( q2 * q3 + q0 * q1 );
trans[2][2] = q0 * q0 + q3 * q3 - q1 * q1 - q2 * q2;
// Compose rotation matrix with the existing matrix
if ( pre )
{
this->SetVarMatrix(this->GetMatrix() * trans);
}
else
{
this->SetVarMatrix( trans * this->GetMatrix() );
this->SetVarTranslation( trans * this->GetTranslation() );
}
this->ComputeMatrixParameters();
this->ComputeOffset();
this->Modified();
}
/** Compose with elementary rotation */
template< typename TScalar, unsigned int NDimensions >
void
AffineTransform< TScalar, NDimensions >
::Shear(int axis1, int axis2, TScalar coef, bool pre)
{
MatrixType trans;
unsigned int i, j;
for ( i = 0; i < NDimensions; i++ )
{
for ( j = 0; j < NDimensions; j++ )
{
trans[i][j] = 0.0;
}
trans[i][i] = 1.0;
}
trans[axis1][axis2] = coef;
if ( pre )
{
this->SetVarMatrix(this->GetMatrix() * trans);
}
else
{
this->SetVarMatrix( trans * this->GetMatrix() );
this->SetVarTranslation( trans * this->GetTranslation() );
}
this->ComputeMatrixParameters();
this->ComputeOffset();
this->Modified();
}
/** Get an inverse of this transform. */
template< typename TScalar, unsigned int NDimensions >
bool
AffineTransform< TScalar, NDimensions >
::GetInverse(Self *inverse) const
{
return this->Superclass::GetInverse(inverse);
}
/** Return an inverse of this transform. */
template< typename TScalar, unsigned int NDimensions >
typename AffineTransform< TScalar, NDimensions >::InverseTransformBasePointer
AffineTransform< TScalar, NDimensions >
::GetInverseTransform() const
{
Pointer inv = New();
return this->GetInverse(inv) ? inv.GetPointer() : ITK_NULLPTR;
}
/** Compute a distance between two affine transforms */
template< typename TScalar, unsigned int NDimensions >
typename AffineTransform< TScalar, NDimensions >::ScalarType
AffineTransform< TScalar, NDimensions >
::Metric(const Self *other) const
{
ScalarType result = 0.0, term;
for ( unsigned int i = 0; i < NDimensions; i++ )
{
for ( unsigned int j = 0; j < NDimensions; j++ )
{
term = this->GetMatrix()[i][j] - other->GetMatrix()[i][j];
result += term * term;
}
term = this->GetOffset()[i] - other->GetOffset()[i];
result += term * term;
}
return std::sqrt(result);
}
/** Compute a distance between self and the identity transform */
template< typename TScalar, unsigned int NDimensions >
typename AffineTransform< TScalar, NDimensions >::ScalarType
AffineTransform< TScalar, NDimensions >
::Metric(void) const
{
ScalarType result = 0.0, term;
for ( unsigned int i = 0; i < NDimensions; i++ )
{
for ( unsigned int j = 0; j < NDimensions; j++ )
{
if ( i == j )
{
term = this->GetMatrix()[i][j] - 1.0;
}
else
{
term = this->GetMatrix()[i][j];
}
result += term * term;
}
term = this->GetOffset()[i];
result += term * term;
}
return std::sqrt(result);
}
} // namespace
#endif
| [
"tuyen.luu@sotatek.com"
] | tuyen.luu@sotatek.com |
ef54862e9b292111e173b6984a08f51a0632a2c5 | 37cca16f12e7b1d4d01d6f234da6d568c318abee | /src/rice/pastry/join/JoinRequest.cpp | 4800078c4930f901273844ca2f14c01f5f557daf | [] | no_license | subhash1-0/thirstyCrow | e48155ce68fc886f2ee8e7802567c1149bc54206 | 78b7e4e3d2b9a9530ad7d66b44eacfe73ceea582 | refs/heads/master | 2016-09-06T21:25:54.075724 | 2015-09-21T17:21:15 | 2015-09-21T17:21:15 | 42,881,521 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,593 | cpp | // Generated from /pastry-2.1/src/rice/pastry/join/JoinRequest.java
#include <rice/pastry/join/JoinRequest.hpp>
#include <java/io/IOException.hpp>
#include <java/io/Serializable.hpp>
#include <java/lang/ArrayStoreException.hpp>
#include <java/lang/ClassCastException.hpp>
#include <java/lang/Cloneable.hpp>
#include <java/lang/Iterable.hpp>
#include <java/lang/NullPointerException.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <java/lang/StringBuilder.hpp>
#include <java/util/Date.hpp>
#include <java/util/Observer.hpp>
#include <rice/p2p/commonapi/NodeHandleSet.hpp>
#include <rice/p2p/commonapi/rawserialization/InputBuffer.hpp>
#include <rice/p2p/commonapi/rawserialization/OutputBuffer.hpp>
#include <rice/pastry/Id.hpp>
#include <rice/pastry/NodeHandle.hpp>
#include <rice/pastry/NodeHandleFactory.hpp>
#include <rice/pastry/NodeSetI.hpp>
#include <rice/pastry/join/JoinAddress.hpp>
#include <rice/pastry/leafset/LeafSet.hpp>
#include <rice/pastry/routing/RouteSet.hpp>
#include <SubArray.hpp>
#include <ObjectArray.hpp>
template<typename ComponentType, typename... Bases> struct SubArray;
namespace java
{
namespace io
{
typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray;
} // io
namespace lang
{
typedef ::SubArray< ::java::lang::Cloneable, ObjectArray > CloneableArray;
typedef ::SubArray< ::java::lang::Iterable, ObjectArray > IterableArray;
} // lang
namespace util
{
typedef ::SubArray< ::java::util::Observer, ::java::lang::ObjectArray > ObserverArray;
} // util
} // java
namespace rice
{
namespace p2p
{
namespace commonapi
{
typedef ::SubArray< ::rice::p2p::commonapi::NodeHandleSet, ::java::lang::ObjectArray, ::java::io::SerializableArray > NodeHandleSetArray;
} // commonapi
} // p2p
namespace pastry
{
typedef ::SubArray< ::rice::pastry::NodeSetI, ::java::lang::ObjectArray, ::rice::p2p::commonapi::NodeHandleSetArray > NodeSetIArray;
namespace routing
{
typedef ::SubArray< ::rice::pastry::routing::RouteSet, ::java::lang::ObjectArray, ::rice::pastry::NodeSetIArray, ::java::io::SerializableArray, ::java::util::ObserverArray, ::java::lang::IterableArray > RouteSetArray;
typedef ::SubArray< ::rice::pastry::routing::RouteSetArray, ::java::lang::CloneableArray, ::java::io::SerializableArray > RouteSetArrayArray;
} // routing
} // pastry
} // rice
template<typename T, typename U>
static T java_cast(U* u)
{
if(!u) return static_cast<T>(nullptr);
auto t = dynamic_cast<T>(u);
if(!t) throw new ::java::lang::ClassCastException();
return t;
}
template<typename T>
static T* npc(T* t)
{
if(!t) throw new ::java::lang::NullPointerException();
return t;
}
rice::pastry::join::JoinRequest::JoinRequest(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
rice::pastry::join::JoinRequest::JoinRequest(::rice::pastry::NodeHandle* nh, int8_t rtBaseBitLength)
: JoinRequest(*static_cast< ::default_init_tag* >(0))
{
ctor(nh,rtBaseBitLength);
}
rice::pastry::join::JoinRequest::JoinRequest(::rice::pastry::NodeHandle* nh, int8_t rtBaseBitLength, int64_t timestamp)
: JoinRequest(*static_cast< ::default_init_tag* >(0))
{
ctor(nh,rtBaseBitLength,timestamp);
}
rice::pastry::join::JoinRequest::JoinRequest(::rice::pastry::NodeHandle* nh, ::java::util::Date* stamp, int8_t rtBaseBitLength)
: JoinRequest(*static_cast< ::default_init_tag* >(0))
{
ctor(nh,stamp,rtBaseBitLength);
}
rice::pastry::join::JoinRequest::JoinRequest(::rice::p2p::commonapi::rawserialization::InputBuffer* buf, ::rice::pastry::NodeHandleFactory* nhf, ::rice::pastry::NodeHandle* sender, ::rice::pastry::PastryNode* localNode) /* throws(IOException) */
: JoinRequest(*static_cast< ::default_init_tag* >(0))
{
ctor(buf,nhf,sender,localNode);
}
constexpr int8_t rice::pastry::join::JoinRequest::HAS_HANDLE;
constexpr int8_t rice::pastry::join::JoinRequest::HAS_JOIN_HANDLE;
constexpr int8_t rice::pastry::join::JoinRequest::HAS_LEAFSET;
constexpr int64_t rice::pastry::join::JoinRequest::serialVersionUID;
constexpr int16_t rice::pastry::join::JoinRequest::TYPE;
void rice::pastry::join::JoinRequest::ctor(::rice::pastry::NodeHandle* nh, int8_t rtBaseBitLength)
{
ctor(nh, static_cast< ::java::util::Date* >(nullptr), rtBaseBitLength);
}
void rice::pastry::join::JoinRequest::ctor(::rice::pastry::NodeHandle* nh, int8_t rtBaseBitLength, int64_t timestamp)
{
ctor(nh, static_cast< ::java::util::Date* >(nullptr), rtBaseBitLength);
this->timestamp = timestamp;
}
void rice::pastry::join::JoinRequest::ctor(::rice::pastry::NodeHandle* nh, ::java::util::Date* stamp, int8_t rtBaseBitLength)
{
super::ctor(JoinAddress::getCode(), stamp);
handle = nh;
initialize(rtBaseBitLength);
setPriority(MAX_PRIORITY);
}
rice::pastry::NodeHandle* rice::pastry::join::JoinRequest::getHandle()
{
return handle;
}
rice::pastry::NodeHandle* rice::pastry::join::JoinRequest::getJoinHandle()
{
return joinHandle;
}
rice::pastry::leafset::LeafSet* rice::pastry::join::JoinRequest::getLeafSet()
{
return leafSet;
}
bool rice::pastry::join::JoinRequest::accepted()
{
return joinHandle != nullptr;
}
void rice::pastry::join::JoinRequest::acceptJoin(::rice::pastry::NodeHandle* nh, ::rice::pastry::leafset::LeafSet* ls)
{
joinHandle = nh;
leafSet = ls;
}
int32_t rice::pastry::join::JoinRequest::lastRow()
{
return rowCount;
}
void rice::pastry::join::JoinRequest::pushRow(::rice::pastry::routing::RouteSetArray* row)
{
rows->set(--rowCount, row);
}
rice::pastry::routing::RouteSetArray* rice::pastry::join::JoinRequest::getRow(int32_t i)
{
return (*rows)[i];
}
int32_t rice::pastry::join::JoinRequest::numRows()
{
return npc(rows)->length;
}
void rice::pastry::join::JoinRequest::initialize(int8_t rtBaseBitLength)
{
joinHandle = nullptr;
this->rtBaseBitLength = rtBaseBitLength;
rowCount = static_cast< int16_t >((::rice::pastry::Id::IdBitLength / rtBaseBitLength));
rows = new ::rice::pastry::routing::RouteSetArrayArray(rowCount);
}
java::lang::String* rice::pastry::join::JoinRequest::toString()
{
return ::java::lang::StringBuilder().append(u"JoinRequest("_j)->append(static_cast< ::java::lang::Object* >((handle != nullptr ? npc(handle)->getNodeId() : static_cast< ::rice::pastry::Id* >(nullptr))))
->append(u","_j)
->append(static_cast< ::java::lang::Object* >((joinHandle != nullptr ? npc(joinHandle)->getNodeId() : static_cast< ::rice::pastry::Id* >(nullptr))))
->append(u","_j)
->append(timestamp)
->append(u")"_j)->toString();
}
int16_t rice::pastry::join::JoinRequest::getType()
{
return TYPE;
}
void rice::pastry::join::JoinRequest::serialize(::rice::p2p::commonapi::rawserialization::OutputBuffer* buf) /* throws(IOException) */
{
npc(buf)->writeByte(static_cast< int8_t >(int32_t(1)));
npc(buf)->writeLong(timestamp);
npc(buf)->writeByte(static_cast< int8_t >(rtBaseBitLength));
npc(handle)->serialize(buf);
if(joinHandle != nullptr) {
npc(buf)->writeBoolean(true);
npc(joinHandle)->serialize(buf);
} else {
npc(buf)->writeBoolean(false);
}
npc(buf)->writeShort(static_cast< int16_t >(rowCount));
auto maxIndex = ::rice::pastry::Id::IdBitLength / rtBaseBitLength;
for (auto i = int32_t(0); i < maxIndex; i++) {
auto thisRow = (*rows)[i];
if(thisRow != nullptr) {
npc(buf)->writeBoolean(true);
for (auto j = int32_t(0); j < npc(thisRow)->length; j++) {
if((*thisRow)[j] != nullptr) {
npc(buf)->writeBoolean(true);
npc((*thisRow)[j])->serialize(buf);
} else {
npc(buf)->writeBoolean(false);
}
}
} else {
npc(buf)->writeBoolean(false);
}
}
if(leafSet != nullptr) {
npc(buf)->writeBoolean(true);
npc(leafSet)->serialize(buf);
} else {
npc(buf)->writeBoolean(false);
}
}
void rice::pastry::join::JoinRequest::ctor(::rice::p2p::commonapi::rawserialization::InputBuffer* buf, ::rice::pastry::NodeHandleFactory* nhf, ::rice::pastry::NodeHandle* sender, ::rice::pastry::PastryNode* localNode) /* throws(IOException) */
{
super::ctor(JoinAddress::getCode());
auto version = npc(buf)->readByte();
{
int32_t numRows;
int32_t numCols;
switch (version) {
case int32_t(1):
timestamp = npc(buf)->readLong();
case int32_t(0):
setSender(sender);
rtBaseBitLength = npc(buf)->readByte();
initialize(rtBaseBitLength);
handle = java_cast< ::rice::pastry::NodeHandle* >(npc(nhf)->readNodeHandle(buf));
if(npc(buf)->readBoolean())
joinHandle = java_cast< ::rice::pastry::NodeHandle* >(npc(nhf)->readNodeHandle(buf));
rowCount = npc(buf)->readShort();
numRows = ::rice::pastry::Id::IdBitLength / rtBaseBitLength;
numCols = int32_t(1) << rtBaseBitLength;
for (auto i = int32_t(0); i < numRows; i++) {
::rice::pastry::routing::RouteSetArray* thisRow;
if(npc(buf)->readBoolean()) {
thisRow = new ::rice::pastry::routing::RouteSetArray(numCols);
for (auto j = int32_t(0); j < numCols; j++) {
if(npc(buf)->readBoolean()) {
thisRow->set(j, new ::rice::pastry::routing::RouteSet(buf, nhf, localNode));
} else {
thisRow->set(j, nullptr);
}
}
} else {
thisRow = nullptr;
}
rows->set(i, thisRow);
}
if(npc(buf)->readBoolean())
leafSet = ::rice::pastry::leafset::LeafSet::build(buf, nhf);
break;
default:
throw new ::java::io::IOException(::java::lang::StringBuilder().append(u"Unknown Version: "_j)->append(version)->toString());
}
}
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* rice::pastry::join::JoinRequest::class_()
{
static ::java::lang::Class* c = ::class_(u"rice.pastry.join.JoinRequest", 28);
return c;
}
java::lang::Class* rice::pastry::join::JoinRequest::getClass0()
{
return class_();
}
| [
"sgurjar@adobe.com"
] | sgurjar@adobe.com |
5dcfe57f8b3cda88ba78e70bd1fb51130dfb23a6 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/multimedia/dshow/filters/dv/dvenc/encprop.cpp | 8457e8c68b93c86b993935d3abeecb3c6f954395 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 4,595 | cpp | //==========================================================================;
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//
// Copyright (c) 1992 - 1999 Microsoft Corporation. All Rights Reserved.
//
//--------------------------------------------------------------------------;
#include <windows.h>
#include <windowsx.h>
#include <streams.h>
#include <commctrl.h>
#include <olectl.h>
#include <memory.h>
#include <stdlib.h>
#include <stdio.h>
#include <tchar.h>
#include <dv.h>
#include "EncProp.h"
#include "resource.h"
//
// CreateInstance
//
// Used by the ActiveMovie base classes to create instances
//
CUnknown *CDVEncProperties::CreateInstance(LPUNKNOWN lpunk, HRESULT *phr)
{
CUnknown *punk = new CDVEncProperties(lpunk, phr);
if (punk == NULL) {
*phr = E_OUTOFMEMORY;
}
return punk;
} // CreateInstance
//
// Constructor
//
CDVEncProperties::CDVEncProperties(LPUNKNOWN pUnk, HRESULT *phr) :
CBasePropertyPage (NAME("DVenc Property Page"),
pUnk,IDD_DVEnc,IDS_TITLE),
m_pIDVEnc(NULL),
m_bIsInitialized(FALSE)
{
ASSERT(phr);
} // (Constructor)
//
// OnReceiveMessage
//
// Handles the messages for our property window
//
INT_PTR CDVEncProperties::OnReceiveMessage(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
switch (uMsg)
{
case WM_COMMAND:
{
if (m_bIsInitialized)
{
m_bDirty = TRUE;
if (m_pPageSite)
{
m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY);
}
}
return (LRESULT) 1;
}
}
return CBasePropertyPage::OnReceiveMessage(hwnd,uMsg,wParam,lParam);
} // OnReceiveMessage
//
// OnConnect
//
// Called when we connect to a transform filter
//
HRESULT CDVEncProperties::OnConnect(IUnknown *pUnknown)
{
ASSERT(m_pIDVEnc == NULL);
HRESULT hr = pUnknown->QueryInterface(IID_IDVEnc, (void **) &m_pIDVEnc);
if (FAILED(hr)) {
return E_NOINTERFACE;
}
ASSERT(m_pIDVEnc);
// Get the initial property
m_pIDVEnc->get_IFormatResolution(&m_iPropVidFormat,&m_iPropDVFormat, &m_iPropResolution, FALSE, NULL);
m_bIsInitialized = FALSE ;
return NOERROR;
} // OnConnect
//
// OnDisconnect
//
// Likewise called when we disconnect from a filter
//
HRESULT CDVEncProperties::OnDisconnect()
{
// Release of Interface after setting the appropriate old effect value
if (m_pIDVEnc == NULL) {
return E_UNEXPECTED;
}
m_pIDVEnc->Release();
m_pIDVEnc = NULL;
return NOERROR;
} // OnDisconnect
//
// OnActivate
//
// We are being activated
//
HRESULT CDVEncProperties::OnActivate()
{
//Button_Enable(hwndCtl, fEnable);
CheckRadioButton(m_Dlg, IDC_NTSC, IDC_PAL, m_iPropVidFormat);
CheckRadioButton(m_Dlg, IDC_dvsd, IDC_dvsl, m_iPropDVFormat);
CheckRadioButton(m_Dlg, IDC_720x480, IDC_88x60, m_iPropResolution);
m_bIsInitialized = TRUE;
return NOERROR;
} // OnActivate
//
// OnDeactivate
//
// We are being deactivated
//
HRESULT CDVEncProperties::OnDeactivate(void)
{
ASSERT(m_pIDVEnc);
m_bIsInitialized = FALSE;
GetControlValues();
return NOERROR;
} // OnDeactivate
//
// OnApplyChanges
//
// Apply any changes so far made
//
HRESULT CDVEncProperties::OnApplyChanges()
{
GetControlValues();
return ( m_pIDVEnc->put_IFormatResolution(m_iPropVidFormat, m_iPropDVFormat, m_iPropResolution, FALSE, NULL ) );
} // OnApplyChanges
void CDVEncProperties::GetControlValues()
{
int i;
ASSERT(m_pIDVEnc);
for (i = IDC_720x480; i <= IDC_88x60; i++) {
if (IsDlgButtonChecked(m_Dlg, i)) {
m_iPropResolution = i;
break;
}
}
for ( i = IDC_dvsd; i <= IDC_dvsl; i++) {
if (IsDlgButtonChecked(m_hwnd, i)) {
m_iPropDVFormat = i;
break;
}
}
for ( i = IDC_NTSC; i <= IDC_PAL; i++) {
if (IsDlgButtonChecked(m_hwnd, i)){
m_iPropVidFormat = i;
break;
}
}
}
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
61a82e52305e2e61a97596d3feffac7509d13418 | fafdf1e62cf622035ee82666ba6ae7108127d140 | /gameswf/gameswf/plugins/sysinfo/sysinfo.h | 98679b0f826e8fc91ff86aff160424899c28f7f7 | [] | no_license | saerich/RaiderZ-Evolved-SDK | 7f18942ddc6c566d47c3a6222c03fad7543738a4 | b576e6757b6a781a656be7ba31eb0cf5e8a23391 | refs/heads/master | 2023-02-12T03:21:26.442348 | 2020-08-30T15:39:54 | 2020-08-30T15:39:54 | 281,213,173 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 885 | h | // sysinfo.cpp -- Vitaly Alexeev <tishka92@yahoo.com> 2007
// This source code has been donated to the Public Domain. Do
// whatever you want with it.
// gameSWF plugin, gets dir entity
#ifndef GAMESWF_SYSINFO_PLUGIN_H
#define GAMESWF_SYSINFO_PLUGIN_H
#include "gameswf/gameswf_object.h"
using namespace gameswf;
namespace sysinfo_plugin
{
struct sysinfo : public as_object
{
// Unique id of a gameswf resource
enum { m_class_id = AS_PLUGIN_SYSINFO };
virtual bool is(int class_id) const
{
if (m_class_id == class_id) return true;
else return as_object::is(class_id);
}
sysinfo(player* player);
exported_module void get_dir(as_object* info, const tu_string& path);
exported_module bool get_hdd_serno(tu_string* sn, const char* dev);
exported_module int get_freemem();
};
}
#endif // GAMESWF_SYSINFO_PLUGIN_H
| [
"fabs1996@live.co.uk"
] | fabs1996@live.co.uk |
5281ce41cfbb5c3a9e8ba6e720e00cf2eb26ea00 | c0ac6fe0a4a03245e034b296800156eaba01ad2e | /SDL2_Standardproject/SDL/SDLMusic.h | e7b8d6e2d839238da3e8d402b90bcce18bcf0c4d | [] | no_license | TorsteinA/snake-plusplus | 1a325d648f81f384c50b10defe9493d7d5087929 | 1dfd5628a76c2f7c0d4af913e57dd189448ee2a0 | refs/heads/master | 2021-01-25T04:35:38.190577 | 2017-06-04T19:44:13 | 2017-06-04T19:44:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 524 | h | //
// Created by torstein on 03.06.17.
//
#ifndef SNAKE_PLUSPLUS_SDLMUSIC_H
#define SNAKE_PLUSPLUS_SDLMUSIC_H
#include <string>
#include <SDL2/SDL_mixer.h>
class SDLMusic {
public:
/* Loads the given file on construction */
SDLMusic(const std::string& file);
/* Free's the memory consumed by the sound data */
~SDLMusic();
/* Play sound effect */
void playMusic();
void PauseUnpauseMusic();
void StopMusic();
private:
Mix_Music *gameMusic;
};
#endif //SNAKE_PLUSPLUS_SDLMUSIC_H
| [
"alvtor15@student.westerdals.no"
] | alvtor15@student.westerdals.no |
e0d27f358bb3393b65f71dc8a93640ef8c5103f5 | 20482a4f7571a81f9e0e0aa2021d48cd1826571e | /White/Week 4/block_3/Calculator/RatCalc.cpp | d9f6d8cc7e3c044be1ea9d7bd4ceaf036543189f | [] | no_license | intelek2al/Coursera | c0bb155d99853c449c479a4ff1217955edd17e09 | d16476c4ed0046e9f30b5f5a6999c4923af6b4e4 | refs/heads/master | 2022-12-05T22:42:32.527351 | 2020-08-16T15:57:52 | 2020-08-16T15:57:52 | 283,719,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,115 | cpp | #include <iostream>
#include <numeric>
#include <sstream>
#include <string.h>
#include <map>
#include <set>
#include <vector>
#include <exception>
using namespace std;
class Rational
{
public:
Rational()
{
num = 0;
den = 1;
}
Rational(int numerator, int denominator)
{
if (denominator == 0)
{
throw invalid_argument("Invalid argument");
}
if (denominator < 0)
{
numerator *= -1;
denominator *= -1;
}
num = numerator / gcd(abs(numerator), abs(denominator));
den = denominator / gcd(abs(numerator), abs(denominator));
}
int Numerator() const
{
return num;
}
int Denominator() const
{
return den;
}
private:
int num;
int den;
};
Rational operator+(const Rational &a, const Rational &b)
{
int den = lcm(a.Denominator(), b.Denominator());
int num = a.Numerator() * den / a.Denominator() + b.Numerator() * den / b.Denominator();
return Rational(num, den);
}
Rational operator-(const Rational &a, const Rational &b)
{
int den = lcm(a.Denominator(), b.Denominator());
int num = a.Numerator() * den / a.Denominator() - b.Numerator() * den / b.Denominator();
return Rational(num, den);
}
bool operator==(const Rational &a, const Rational &b)
{
return (a.Denominator() == b.Denominator() && a.Numerator() == b.Numerator());
}
Rational operator*(const Rational &a, const Rational &b)
{
return Rational(a.Numerator() * b.Numerator(), a.Denominator() * b.Denominator());
}
Rational operator/(const Rational &a, const Rational &b)
{
if (b.Numerator() == 0)
{
throw domain_error("Division by zero");
}
return Rational(a.Numerator() * b.Denominator(), a.Denominator() * b.Numerator());
}
ostream &operator<<(ostream &stream, const Rational &a)
{
if (stream)
stream << a.Numerator() << "/" << a.Denominator();
return stream;
}
istream &operator>>(istream &stream, Rational &a)
{
int n, d;
char c;
if (stream)
{
stream >> n >> c >> d;
if (stream && c == '/')
{
a = Rational(n, d);
}
}
return stream;
}
bool operator<(const Rational &a, const Rational &b)
{
int den = lcm(a.Denominator(), b.Denominator());
int num1 = a.Numerator() * den / a.Denominator();
int num2 = b.Numerator() * den / b.Denominator();
return num1 < num2;
}
class Calculator
{
private:
Rational left;
Rational right;
char oper;
public:
Calculator()
{
left = Rational();
right = Rational();
oper = '+';
}
Calculator(const Rational &l, const Rational &r, const char &o)
{
left = l;
right = r;
oper = o;
}
Rational Accept()
{
switch (oper)
{
case '+':
return (left + right);
case '-':
return (left - right);
case '*':
return (left * right);
case '/':
return (left / right);
}
return Rational();
}
};
istream &operator>>(istream &stream, Calculator &calc)
{
Rational t_left = Rational();
Rational t_right = Rational();
char t_oper = '+';
stream >> t_left >> t_oper >> t_right;
calc = Calculator(t_left, t_right, t_oper);
return stream;
}
int main()
{
Calculator calc;
try
{
cin >> calc;
cout << calc.Accept() << endl;
}
catch (exception &ex)
{
cout << ex.what() << endl;
}
return 0;
}
| [
"nikita96511@gmail.com"
] | nikita96511@gmail.com |
7386567c8ec7748c7634d8a503f5f871cbbb7f12 | 7a138fa71d3e08958d8443992e2d57d504bb593a | /peg/assignments/mirrored_pairs.cpp | f6f88493370492c1582720b1192b5481d6ecbfb2 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | sustcoderboy/competitive-programming-archive | 8a254e7542d9f616df73d8aaa9ca23d6242dec9b | 2cd3237f376c609b7c4e87804e36a8cac7ec3402 | refs/heads/master | 2021-01-22T17:38:41.565826 | 2015-11-22T03:50:00 | 2015-11-22T03:50:00 | 46,705,756 | 1 | 0 | null | 2015-11-23T08:10:07 | 2015-11-23T08:10:07 | null | UTF-8 | C++ | false | false | 576 | cpp | #include <iostream>
#include <set>
#include <string>
using namespace std;
const set<string> mirrored_pairs {"pq", "qp", "bd", "db"};
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
int main()
{
use_io_optimizations();
cout << "Ready\n";
for (string pair; getline(cin, pair) && pair != " "; )
{
if (mirrored_pairs.count(pair))
{
cout << "Mirrored";
}
else
{
cout << "Ordinary";
}
cout << " pair\n";
}
return 0;
}
| [
"gsshopov@gmail.com"
] | gsshopov@gmail.com |
116e141da1f82a0a8957bf1f433722efb4ef0ce1 | 107d79f2c1802a3ff66d300d5d1ab2d413bac375 | /src/eepp/window/backend/SDL/cbackendsdl.hpp | b30e185f4a2bf0abd7a7704f612c134be24425cb | [
"MIT"
] | permissive | weimingtom/eepp | 2030ab0b2a6231358f8433304f90611499b6461e | dd672ff0e108ae1e08449ca918dc144018fb4ba4 | refs/heads/master | 2021-01-10T01:36:39.879179 | 2014-06-02T02:46:33 | 2014-06-02T02:46:33 | 46,509,734 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 412 | hpp | #ifndef EE_WINDOWCBACKENDSDL_HPP
#define EE_WINDOWCBACKENDSDL_HPP
#include <eepp/window/cbackend.hpp>
#include <eepp/window/backend/SDL/base.hpp>
#ifdef EE_BACKEND_SDL_1_2
#include <eepp/window/backend/SDL/cwindowsdl.hpp>
namespace EE { namespace Window { namespace Backend { namespace SDL {
class EE_API cBackendSDL : public cBackend {
public:
cBackendSDL();
~cBackendSDL();
};
}}}}
#endif
#endif
| [
"spartanj@gmail.com"
] | spartanj@gmail.com |
9b1511e659db97e3ba491f5e6f8445d6e5071d7c | ee1423adcd4bfeb2703464996171d103542bad09 | /dali-core/automated-tests/dali-test-suite/events/utc-Dali-LongPressGestureDetector.cpp | fc06ce2363b2b9d80aad701f18350b692c74c7b0 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-flora-1.1"
] | permissive | sak0909/Dali | 26ac61a521ab1de26a7156c51afd3cc839cb705a | 0b383fc316b8b57afcf9a9e8bac6e24a4ba36e49 | refs/heads/master | 2020-12-30T12:10:51.930311 | 2017-05-16T21:56:24 | 2017-05-16T21:57:14 | 91,505,804 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 48,570 | cpp | //
// Copyright (c) 2014 Samsung Electronics Co., Ltd.
//
// Licensed under the Flora License, Version 1.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://floralicense.org/license/
//
// 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 <iostream>
#include <stdlib.h>
#include <tet_api.h>
#include <dali/public-api/dali-core.h>
#include <dali/integration-api/events/touch-event-integ.h>
#include <dali/integration-api/events/long-press-gesture-event.h>
#include <dali/integration-api/system-overlay.h>
#include <dali-test-suite-utils.h>
using namespace Dali;
static void Startup();
static void Cleanup();
extern "C" {
void (*tet_startup)() = Startup;
void (*tet_cleanup)() = Cleanup;
}
enum {
POSITIVE_TC_IDX = 0x01,
NEGATIVE_TC_IDX,
};
#define MAX_NUMBER_OF_TESTS 10000
extern "C" {
struct tet_testlist tet_testlist[MAX_NUMBER_OF_TESTS];
}
// Add test functionality for all APIs in the class (Positive and Negative)
TEST_FUNCTION( UtcDaliLongPressGestureDetectorConstructor, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureDetectorNew, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureDetectorDownCast, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureSetTouchesRequired01, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureSetTouchesRequired02, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureGetMinimumTouchesRequired, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureGetMaximumTouchesRequired, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureSignalReceptionNegative, NEGATIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureSignalReceptionPositive, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureSignalReceptionDetach, NEGATIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureSignalReceptionActorDestroyedDuringLongPress, NEGATIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureSignalReceptionRotatedActor, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureSignalReceptionChildHit, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureSignalReceptionAttachDetachMany, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureSignalReceptionActorBecomesUntouchable, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureSignalReceptionMultipleGestureDetectors, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureSignalReceptionMultipleDetectorsOnActor, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureSignalReceptionDifferentPossible, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureEmitIncorrectStateClear, NEGATIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureEmitIncorrectStateContinuing, NEGATIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureDetectorTypeRegistry, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureRepeatedState, NEGATIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGesturePossibleCancelled, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureDetachAfterStarted, POSITIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureActorUnstaged, NEGATIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureActorStagedAndDestroyed, NEGATIVE_TC_IDX );
TEST_FUNCTION( UtcDaliLongPressGestureSystemOverlay, POSITIVE_TC_IDX );
// Called only once before first test is run.
static void Startup()
{
}
// Called only once after last test is run
static void Cleanup()
{
}
///////////////////////////////////////////////////////////////////////////////
// Stores data that is populated in the callback and will be read by the TET cases
struct SignalData
{
SignalData()
: functorCalled( false ),
voidFunctorCalled( false ),
receivedGesture( Gesture::Clear ),
pressedActor()
{}
void Reset()
{
functorCalled = false;
voidFunctorCalled = false;
receivedGesture.numberOfTouches = 0u;
receivedGesture.screenPoint = Vector2(0.0f, 0.0f);
receivedGesture.localPoint = Vector2(0.0f, 0.0f);
pressedActor = NULL;
}
bool functorCalled;
bool voidFunctorCalled;
LongPressGesture receivedGesture;
Actor pressedActor;
};
// Functor that sets the data when called
struct GestureReceivedFunctor
{
GestureReceivedFunctor(SignalData& data) : signalData(data) { }
void operator()(Actor actor, LongPressGesture longPress)
{
signalData.functorCalled = true;
signalData.receivedGesture = longPress;
signalData.pressedActor = actor;
}
void operator()()
{
signalData.voidFunctorCalled = true;
}
SignalData& signalData;
};
// Functor that removes the gestured actor from stage
struct UnstageActorFunctor : public GestureReceivedFunctor
{
UnstageActorFunctor( SignalData& data, Gesture::State& stateToUnstage )
: GestureReceivedFunctor( data ),
stateToUnstage( stateToUnstage )
{
}
void operator()( Actor actor, LongPressGesture longPress )
{
GestureReceivedFunctor::operator()( actor, longPress );
if ( longPress.state == stateToUnstage )
{
Stage::GetCurrent().Remove( actor );
}
}
Gesture::State& stateToUnstage;
};
// Functor for receiving a touch event
struct TouchEventFunctor
{
bool operator()(Actor actor, const TouchEvent& touch)
{
//For line coverage
unsigned int points = touch.GetPointCount();
if( points > 0)
{
const TouchPoint& touchPoint = touch.GetPoint(0);
tet_printf("Touch Point state = %d\n", touchPoint.state);
}
return false;
}
};
// Generate a LongPressGestureEvent to send to Core
Integration::LongPressGestureEvent GenerateLongPress(
Gesture::State state,
unsigned int numberOfTouches,
Vector2 point)
{
Integration::LongPressGestureEvent longPress( state );
longPress.numberOfTouches = numberOfTouches;
longPress.point = point;
return longPress;
}
///////////////////////////////////////////////////////////////////////////////
// Positive test case for a method
static void UtcDaliLongPressGestureDetectorConstructor()
{
TestApplication application;
LongPressGestureDetector detector;
DALI_TEST_CHECK(!detector);
}
static void UtcDaliLongPressGestureDetectorNew()
{
TestApplication application;
LongPressGestureDetector detector = LongPressGestureDetector::New();
DALI_TEST_CHECK(detector);
DALI_TEST_EQUALS(1u, detector.GetMinimumTouchesRequired(), TEST_LOCATION);
DALI_TEST_EQUALS(1u, detector.GetMaximumTouchesRequired(), TEST_LOCATION);
LongPressGestureDetector detector2 = LongPressGestureDetector::New(5u);
DALI_TEST_CHECK(detector2);
DALI_TEST_EQUALS(5u, detector2.GetMinimumTouchesRequired(), TEST_LOCATION);
DALI_TEST_EQUALS(5u, detector2.GetMaximumTouchesRequired(), TEST_LOCATION);
LongPressGestureDetector detector3 = LongPressGestureDetector::New(5u, 7u);
DALI_TEST_CHECK(detector2);
DALI_TEST_EQUALS(5u, detector3.GetMinimumTouchesRequired(), TEST_LOCATION);
DALI_TEST_EQUALS(7u, detector3.GetMaximumTouchesRequired(), TEST_LOCATION);
//Scoped test to test destructor
{
LongPressGestureDetector detector4 = LongPressGestureDetector::New();
DALI_TEST_CHECK(detector4);
}
// Attach an actor and emit a touch event on the actor to ensure complete line coverage
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
detector.Attach(actor);
TouchEventFunctor touchFunctor;
actor.TouchedSignal().Connect(&application, touchFunctor);
Integration::TouchEvent touchEvent(1);
TouchPoint point(1, TouchPoint::Down, 20.0f, 20.0f);
touchEvent.AddPoint(point);
application.ProcessEvent(touchEvent);
// Render and notify
application.SendNotification();
application.Render();
// For line coverage, Initialise default constructor
TouchEvent touchEvent2;
}
static void UtcDaliLongPressGestureDetectorDownCast()
{
TestApplication application;
tet_infoline("Testing Dali::LongPressGestureDetector::DownCast()");
LongPressGestureDetector detector = LongPressGestureDetector::New();
BaseHandle object(detector);
LongPressGestureDetector detector2 = LongPressGestureDetector::DownCast(object);
DALI_TEST_CHECK(detector2);
LongPressGestureDetector detector3 = DownCast< LongPressGestureDetector >(object);
DALI_TEST_CHECK(detector3);
BaseHandle unInitializedObject;
LongPressGestureDetector detector4 = LongPressGestureDetector::DownCast(unInitializedObject);
DALI_TEST_CHECK(!detector4);
LongPressGestureDetector detector5 = DownCast< LongPressGestureDetector >(unInitializedObject);
DALI_TEST_CHECK(!detector5);
GestureDetector detector6 = LongPressGestureDetector::New();
LongPressGestureDetector detector7 = LongPressGestureDetector::DownCast(detector6);
DALI_TEST_CHECK(detector7);
}
static void UtcDaliLongPressGestureSetTouchesRequired01()
{
TestApplication application;
LongPressGestureDetector detector = LongPressGestureDetector::New();
unsigned int touches = 3;
DALI_TEST_CHECK(touches != detector.GetMinimumTouchesRequired());
DALI_TEST_CHECK(touches != detector.GetMaximumTouchesRequired());
detector.SetTouchesRequired(touches);
DALI_TEST_EQUALS(touches, detector.GetMinimumTouchesRequired(), TEST_LOCATION);
DALI_TEST_EQUALS(touches, detector.GetMaximumTouchesRequired(), TEST_LOCATION);
// Attach an actor and change the required touches
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
SignalData data;
GestureReceivedFunctor functor(data);
detector.Attach(actor);
detector.DetectedSignal().Connect(&application, functor);
TestGestureManager& gestureManager = application.GetGestureManager();
gestureManager.Initialize();
detector.SetTouchesRequired(4);
// Gesture detection should have been updated only
DALI_TEST_EQUALS(true, gestureManager.WasCalled(TestGestureManager::UpdateType), TEST_LOCATION);
DALI_TEST_EQUALS(false, gestureManager.WasCalled(TestGestureManager::RegisterType), TEST_LOCATION);
DALI_TEST_EQUALS(false, gestureManager.WasCalled(TestGestureManager::UnregisterType), TEST_LOCATION);
// Reset values
gestureManager.Initialize();
// Create a second gesture detector that requires even less maximum touches
LongPressGestureDetector secondDetector = LongPressGestureDetector::New();
secondDetector.Attach(actor);
// Gesture detection should have been updated
DALI_TEST_EQUALS(true, gestureManager.WasCalled(TestGestureManager::UpdateType), TEST_LOCATION);
DALI_TEST_EQUALS(false, gestureManager.WasCalled(TestGestureManager::RegisterType), TEST_LOCATION);
DALI_TEST_EQUALS(false, gestureManager.WasCalled(TestGestureManager::UnregisterType), TEST_LOCATION);
}
static void UtcDaliLongPressGestureSetTouchesRequired02()
{
TestApplication application;
LongPressGestureDetector detector = LongPressGestureDetector::New();
unsigned int min = 3;
unsigned int max = 5;
DALI_TEST_CHECK(min != detector.GetMinimumTouchesRequired());
DALI_TEST_CHECK(max != detector.GetMaximumTouchesRequired());
detector.SetTouchesRequired(min, max);
DALI_TEST_EQUALS(min, detector.GetMinimumTouchesRequired(), TEST_LOCATION);
DALI_TEST_EQUALS(max, detector.GetMaximumTouchesRequired(), TEST_LOCATION);
// Attach an actor and change the maximum touches
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
SignalData data;
GestureReceivedFunctor functor(data);
detector.Attach(actor);
detector.DetectedSignal().Connect(&application, functor);
TestGestureManager& gestureManager = application.GetGestureManager();
gestureManager.Initialize();
detector.SetTouchesRequired(4, 5);
// Gesture detection should have been updated only
DALI_TEST_EQUALS(true, gestureManager.WasCalled(TestGestureManager::UpdateType), TEST_LOCATION);
DALI_TEST_EQUALS(false, gestureManager.WasCalled(TestGestureManager::RegisterType), TEST_LOCATION);
DALI_TEST_EQUALS(false, gestureManager.WasCalled(TestGestureManager::UnregisterType), TEST_LOCATION);
// Reset values
gestureManager.Initialize();
// Create a second gesture detector that requires even less maximum touches
LongPressGestureDetector secondDetector = LongPressGestureDetector::New();
secondDetector.Attach(actor);
// Gesture detection should have been updated
DALI_TEST_EQUALS(true, gestureManager.WasCalled(TestGestureManager::UpdateType), TEST_LOCATION);
DALI_TEST_EQUALS(false, gestureManager.WasCalled(TestGestureManager::RegisterType), TEST_LOCATION);
DALI_TEST_EQUALS(false, gestureManager.WasCalled(TestGestureManager::UnregisterType), TEST_LOCATION);
}
static void UtcDaliLongPressGestureGetMinimumTouchesRequired()
{
TestApplication application;
LongPressGestureDetector detector = LongPressGestureDetector::New();
DALI_TEST_EQUALS(1u, detector.GetMinimumTouchesRequired(), TEST_LOCATION);
}
static void UtcDaliLongPressGestureGetMaximumTouchesRequired()
{
TestApplication application;
LongPressGestureDetector detector = LongPressGestureDetector::New();
DALI_TEST_EQUALS(1u, detector.GetMaximumTouchesRequired(), TEST_LOCATION);
}
static void UtcDaliLongPressGestureSignalReceptionNegative()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
SignalData data;
GestureReceivedFunctor functor(data);
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(actor);
detector.DetectedSignal().Connect(&application, functor);
// Do a long press outside actor's area
application.ProcessEvent( GenerateLongPress( Gesture::Possible, 1u, Vector2(112.0f, 112.0f ) ) );
application.ProcessEvent( GenerateLongPress( Gesture::Started, 1u, Vector2(112.0f, 112.0f ) ) );
application.ProcessEvent( GenerateLongPress( Gesture::Finished, 1u, Vector2(112.0f, 112.0f ) ) );
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
}
static void UtcDaliLongPressGestureSignalReceptionPositive()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
SignalData data;
GestureReceivedFunctor functor(data);
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(actor);
detector.DetectedSignal().Connect(&application, functor);
// Do a long press inside actor's area
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 50.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 50.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
DALI_TEST_EQUALS(1u, data.receivedGesture.numberOfTouches, TEST_LOCATION);
DALI_TEST_EQUALS( Vector2(50.0f, 50.0f), data.receivedGesture.localPoint, 0.1, TEST_LOCATION);
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 50.0f)));
}
static void UtcDaliLongPressGestureSignalReceptionDetach()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
SignalData data;
GestureReceivedFunctor functor(data);
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(actor);
detector.DetectedSignal().Connect(&application, functor);
// Start long press within the actor's area
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(20.0f, 20.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(20.0f, 20.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
DALI_TEST_EQUALS(1u, data.receivedGesture.numberOfTouches, TEST_LOCATION);
DALI_TEST_EQUALS( Vector2(20.0f, 20.0f), data.receivedGesture.localPoint, 0.1, TEST_LOCATION);
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(20.0f, 20.0f)));
// repeat the long press within the actor's area - we should still receive the signal
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 50.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 50.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
DALI_TEST_EQUALS(1u, data.receivedGesture.numberOfTouches, TEST_LOCATION);
DALI_TEST_EQUALS( Vector2(50.0f, 50.0f), data.receivedGesture.localPoint, 0.1, TEST_LOCATION);
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 50.0f)));
// Detach actor
detector.DetachAll();
// Ensure we are no longer signalled
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(20.0f, 20.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(20.0f, 20.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 50.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
}
static void UtcDaliLongPressGestureSignalReceptionActorDestroyedDuringLongPress()
{
TestApplication application;
SignalData data;
GestureReceivedFunctor functor(data);
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.DetectedSignal().Connect(&application, functor);
// Actor lifetime is scoped
{
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
detector.Attach(actor);
// Start long press within the actor's area
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(20.0f, 20.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(20.0f, 20.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
// Remove the actor from stage and reset the data
Stage::GetCurrent().Remove(actor);
// Render and notify
application.SendNotification();
application.Render();
}
// Actor should now have been destroyed
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(20.0f, 20.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
}
static void UtcDaliLongPressGestureSignalReceptionRotatedActor()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetRotation(Dali::Degree(90.0f), Vector3::ZAXIS);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
SignalData data;
GestureReceivedFunctor functor(data);
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(actor);
detector.DetectedSignal().Connect(&application, functor);
// Do a long press
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(5.0f, 5.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(5.0f, 5.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(5.0f, 5.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
DALI_TEST_EQUALS(1u, data.receivedGesture.numberOfTouches, TEST_LOCATION);
DALI_TEST_EQUALS( Vector2(5.0f, 5.0f), data.receivedGesture.screenPoint, 0.1, TEST_LOCATION);
// Rotate actor again and render
actor.SetRotation(Dali::Degree(180.0f), Vector3::ZAXIS);
application.SendNotification();
application.Render();
// Do another long press, should still receive event
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(5.0f, 5.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(5.0f, 5.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(5.0f, 5.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
DALI_TEST_EQUALS(1u, data.receivedGesture.numberOfTouches, TEST_LOCATION);
DALI_TEST_EQUALS( Vector2(5.0f, 5.0f), data.receivedGesture.screenPoint, 0.1, TEST_LOCATION);
// Rotate actor again and render
actor.SetRotation(Dali::Degree(90.0f), Vector3::YAXIS);
application.SendNotification();
application.Render();
// Do a long press, inside where the actor used to be, Should not receive the event
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(70.0f, 70.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(70.0f, 70.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(70.0f, 70.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
}
static void UtcDaliLongPressGestureSignalReceptionChildHit()
{
TestApplication application;
Actor parent = Actor::New();
parent.SetSize(100.0f, 100.0f);
parent.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(parent);
// Set child to completely cover parent.
// Change rotation of child to be different from parent so that we can check if our local coordinate
// conversion of the parent actor is correct.
Actor child = Actor::New();
child.SetSize(100.0f, 100.0f);
child.SetAnchorPoint(AnchorPoint::CENTER);
child.SetParentOrigin(ParentOrigin::CENTER);
child.SetRotation(Dali::Degree(90.0f), Vector3::ZAXIS);
parent.Add(child);
TouchEventFunctor touchFunctor;
child.TouchedSignal().Connect(&application, touchFunctor);
// Render and notify
application.SendNotification();
application.Render();
SignalData data;
GestureReceivedFunctor functor(data);
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(parent);
detector.DetectedSignal().Connect(&application, functor);
// Do long press - hits child area but parent should still receive it
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 50.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 50.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 50.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
DALI_TEST_EQUALS(true, parent == data.pressedActor, TEST_LOCATION);
DALI_TEST_EQUALS(Vector2(50.0f, 50.0f), data.receivedGesture.screenPoint, 0.01f, TEST_LOCATION);
// Attach child and generate same touch points
// (Also proves that you can detach and then re-attach another actor)
detector.Attach(child);
detector.Detach(parent);
// Do an entire long press, only check finished value
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(51.0f, 51.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(51.0f, 51.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(51.0f, 51.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
DALI_TEST_EQUALS(true, child == data.pressedActor, TEST_LOCATION);
DALI_TEST_EQUALS(Vector2(51.0f, 51.0f), data.receivedGesture.screenPoint, 0.01f, TEST_LOCATION);
}
static void UtcDaliLongPressGestureSignalReceptionAttachDetachMany()
{
TestApplication application;
Actor first = Actor::New();
first.SetSize(100.0f, 100.0f);
first.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(first);
Actor second = Actor::New();
second.SetSize(100.0f, 100.0f);
second.SetX(100.0f);
second.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(second);
// Render and notify
application.SendNotification();
application.Render();
SignalData data;
GestureReceivedFunctor functor(data);
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(first);
detector.Attach(second);
detector.DetectedSignal().Connect(&application, functor);
// LongPress within second actor's area
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(120.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(120.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(120.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
DALI_TEST_EQUALS(true, second == data.pressedActor, TEST_LOCATION);
// LongPress within first actor's area
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(20.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(20.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(20.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
DALI_TEST_EQUALS(true, first == data.pressedActor, TEST_LOCATION);
// Detach the second actor
detector.Detach(second);
// second actor shouldn't receive event
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(120.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(120.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(120.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
// first actor should continue receiving event
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(20.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(20.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(20.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
}
static void UtcDaliLongPressGestureSignalReceptionActorBecomesUntouchable()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
SignalData data;
GestureReceivedFunctor functor(data);
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(actor);
detector.DetectedSignal().Connect(&application, functor);
// LongPress in actor's area
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
// Actor becomes invisible - actor should not receive the next long press
actor.SetVisible(false);
// Render and notify
application.SendNotification();
application.Render();
// LongPress in the same area, shouldn't receive event
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
}
static void UtcDaliLongPressGestureSignalReceptionMultipleGestureDetectors()
{
TestApplication application;
Dali::TestGestureManager& gestureManager = application.GetGestureManager();
Actor first = Actor::New();
first.SetSize(100.0f, 100.0f);
first.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(first);
Actor second = Actor::New();
second.SetSize(100.0f, 100.0f);
second.SetAnchorPoint(AnchorPoint::TOP_LEFT);
second.SetX(100.0f);
first.Add(second);
// Render and notify
application.SendNotification();
application.Render();
SignalData data;
GestureReceivedFunctor functor(data);
LongPressGestureDetector firstDetector = LongPressGestureDetector::New();
firstDetector.Attach(first);
firstDetector.DetectedSignal().Connect(&application, functor);
// secondDetector is scoped
{
// Reset gestureManager statistics
gestureManager.Initialize();
LongPressGestureDetector secondDetector = LongPressGestureDetector::New();
secondDetector.SetTouchesRequired(2);
secondDetector.Attach(second);
secondDetector.DetectedSignal().Connect(&application, functor);
DALI_TEST_EQUALS(true, gestureManager.WasCalled(TestGestureManager::UpdateType), TEST_LOCATION);
DALI_TEST_EQUALS(false, gestureManager.WasCalled(TestGestureManager::RegisterType), TEST_LOCATION);
DALI_TEST_EQUALS(false, gestureManager.WasCalled(TestGestureManager::UnregisterType), TEST_LOCATION);
// LongPress within second actor's area
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 2u, Vector2(150.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 2u, Vector2(150.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 2u, Vector2(150.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
DALI_TEST_EQUALS(true, second == data.pressedActor, TEST_LOCATION);
// LongPress continues as single touch gesture - we should not receive any gesture
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(150.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(150.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(150.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
// Single touch long press starts - first actor should receive gesture
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
DALI_TEST_EQUALS(true, first == data.pressedActor, TEST_LOCATION);
// long press changes to double-touch - we shouldn't receive event
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 2u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 2u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 2u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
// Reset gesture manager statistics
gestureManager.Initialize();
}
// secondDetector has now been deleted. Gesture detection should have been updated only
DALI_TEST_EQUALS(true, gestureManager.WasCalled(TestGestureManager::UpdateType), TEST_LOCATION);
DALI_TEST_EQUALS(false, gestureManager.WasCalled(TestGestureManager::RegisterType), TEST_LOCATION);
DALI_TEST_EQUALS(false, gestureManager.WasCalled(TestGestureManager::UnregisterType), TEST_LOCATION);
}
void UtcDaliLongPressGestureSignalReceptionMultipleDetectorsOnActor()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
// Attach actor to one detector
SignalData firstData;
GestureReceivedFunctor firstFunctor(firstData);
LongPressGestureDetector firstDetector = LongPressGestureDetector::New();
firstDetector.Attach(actor);
firstDetector.DetectedSignal().Connect(&application, firstFunctor);
// Attach actor to another detector
SignalData secondData;
GestureReceivedFunctor secondFunctor(secondData);
LongPressGestureDetector secondDetector = LongPressGestureDetector::New();
secondDetector.Attach(actor);
secondDetector.DetectedSignal().Connect(&application, secondFunctor);
// LongPress in actor's area - both detector's functors should be called
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(true, firstData.functorCalled, TEST_LOCATION);
DALI_TEST_EQUALS(true, secondData.functorCalled, TEST_LOCATION);
}
void UtcDaliLongPressGestureSignalReceptionDifferentPossible()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
// Attach actor to detector
SignalData data;
GestureReceivedFunctor functor( data );
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(actor);
detector.DetectedSignal().Connect( &application, functor );
// LongPress possible in actor's area.
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
// Move actor somewhere else
actor.SetPosition( 100.0f, 100.0f );
// Render and notify
application.SendNotification();
application.Render();
// Emit Started event, we should not receive the long press.
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
// LongPress possible in empty area.
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
// Move actor in to the long press position.
actor.SetPosition( 0.0f, 0.0f );
// Render and notify
application.SendNotification();
application.Render();
// Emit Started event, we should not receive the long press.
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
// Normal long press in actor's area for completeness.
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
}
void UtcDaliLongPressGestureEmitIncorrectStateClear()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
// Attach actor to detector
SignalData data;
GestureReceivedFunctor functor( data );
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(actor);
detector.DetectedSignal().Connect( &application, functor );
// Try a Clear state
try
{
application.ProcessEvent(GenerateLongPress(Gesture::Clear, 1u, Vector2(50.0f, 10.0f)));
tet_result(TET_FAIL);
}
catch ( Dali::DaliException& e )
{
DALI_TEST_ASSERT( e, "false", TEST_LOCATION );
}
}
void UtcDaliLongPressGestureEmitIncorrectStateContinuing()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
// Attach actor to detector
SignalData data;
GestureReceivedFunctor functor( data );
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(actor);
detector.DetectedSignal().Connect( &application, functor );
// Try a Continuing state
try
{
application.ProcessEvent(GenerateLongPress(Gesture::Continuing, 1u, Vector2(50.0f, 10.0f)));
tet_result(TET_FAIL);
}
catch ( Dali::DaliException& e )
{
DALI_TEST_ASSERT( e, "false", TEST_LOCATION );
}
}
void UtcDaliLongPressGestureDetectorTypeRegistry()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Register Type
TypeInfo type;
type = TypeRegistry::Get().GetTypeInfo( "LongPressGestureDetector" );
DALI_TEST_CHECK( type );
BaseHandle handle = type.CreateInstance();
DALI_TEST_CHECK( handle );
LongPressGestureDetector detector = LongPressGestureDetector::DownCast( handle );
DALI_TEST_CHECK( detector );
// Attach actor to detector
SignalData data;
GestureReceivedFunctor functor( data );
detector.Attach(actor);
// Connect to signal through type
handle.ConnectSignal( &application, LongPressGestureDetector::SIGNAL_LONG_PRESS_DETECTED, functor );
// Render and notify
application.SendNotification();
application.Render();
// Emit gesture
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.voidFunctorCalled, TEST_LOCATION);
}
void UtcDaliLongPressGestureRepeatedState()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
// Attach actor to detector
SignalData data;
GestureReceivedFunctor functor( data );
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(actor);
detector.DetectedSignal().Connect( &application, functor );
// Two possibles
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
// ... Send some finished states, still no signal
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
// Send two Started states, should be signalled
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
data.Reset();
// Send two cancelled states, should not be signalled
application.ProcessEvent(GenerateLongPress(Gesture::Cancelled, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
application.ProcessEvent(GenerateLongPress(Gesture::Cancelled, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
}
void UtcDaliLongPressGesturePossibleCancelled()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
// Attach actor to detector
SignalData data;
GestureReceivedFunctor functor( data );
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(actor);
detector.DetectedSignal().Connect( &application, functor );
// Send a possible followed by a cancel, we should not be signalled
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
application.ProcessEvent(GenerateLongPress(Gesture::Cancelled, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
}
void UtcDaliLongPressGestureDetachAfterStarted()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
// Attach actor to detector
SignalData data;
GestureReceivedFunctor functor( data );
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(actor);
detector.DetectedSignal().Connect( &application, functor );
// Emit initial signal
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
data.Reset();
// Detach actor
detector.Detach(actor);
// Emit Finished, no signal
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
}
void UtcDaliLongPressGestureActorUnstaged()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
// State to remove actor in.
Gesture::State stateToUnstage( Gesture::Started );
// Attach actor to detector
SignalData data;
UnstageActorFunctor functor( data, stateToUnstage );
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(actor);
detector.DetectedSignal().Connect( &application, functor );
// Emit signals
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
// Render and notify
application.SendNotification();
application.Render();
// Re-add actor to stage
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
// Change state to Gesture::Continuing to remove
stateToUnstage = Gesture::Finished;
// Emit signals
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
data.Reset();
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
tet_result( TET_PASS ); // If we get here then we have handled actor stage removal gracefully.
}
void UtcDaliLongPressGestureActorStagedAndDestroyed()
{
TestApplication application;
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(actor);
// Create and add a second actor so that GestureDetector destruction does not come into play.
Actor dummyActor( Actor::New() );
dummyActor.SetSize( 100.0f, 100.0f );
dummyActor.SetPosition( 100.0f, 100.0f );
dummyActor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
Stage::GetCurrent().Add(dummyActor);
// Render and notify
application.SendNotification();
application.Render();
// State to remove actor in.
Gesture::State stateToUnstage( Gesture::Started );
// Attach actor to detector
SignalData data;
UnstageActorFunctor functor( data, stateToUnstage );
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(actor);
detector.Attach(dummyActor);
detector.DetectedSignal().Connect( &application, functor );
// Here we are testing a Started actor which is removed in the Started callback, but then added back
// before we get a finished state. As we were removed from the stage, even if we're at the same
// position, we should still not be signalled.
// Emit signals
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
data.Reset();
// Render and notify
application.SendNotification();
application.Render();
// Re add to the stage, we should not be signalled
Stage::GetCurrent().Add(actor);
// Render and notify
application.SendNotification();
application.Render();
// Continue signal emission
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
data.Reset();
// Here we delete an actor in started, we should not receive any subsequent signalling.
// Emit signals
application.ProcessEvent(GenerateLongPress(Gesture::Possible, 1u, Vector2(50.0f, 10.0f)));
application.ProcessEvent(GenerateLongPress(Gesture::Started, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(true, data.functorCalled, TEST_LOCATION);
data.Reset();
// Render and notify
application.SendNotification();
application.Render();
// Delete actor as well
actor = NULL;
// Render and notify
application.SendNotification();
application.Render();
// Continue signal emission
application.ProcessEvent(GenerateLongPress(Gesture::Finished, 1u, Vector2(50.0f, 10.0f)));
DALI_TEST_EQUALS(false, data.functorCalled, TEST_LOCATION);
}
void UtcDaliLongPressGestureSystemOverlay()
{
TestApplication application;
Dali::Integration::SystemOverlay& systemOverlay( application.GetCore().GetSystemOverlay() );
systemOverlay.GetOverlayRenderTasks().CreateTask();
Actor actor = Actor::New();
actor.SetSize(100.0f, 100.0f);
actor.SetAnchorPoint(AnchorPoint::TOP_LEFT);
systemOverlay.Add(actor);
// Render and notify
application.SendNotification();
application.Render();
SignalData data;
GestureReceivedFunctor functor(data);
LongPressGestureDetector detector = LongPressGestureDetector::New();
detector.Attach(actor);
detector.DetectedSignal().Connect(&application, functor);
// Do a long press inside actor's area
Vector2 screenCoords( 50.0f, 50.0f );
application.ProcessEvent( GenerateLongPress( Gesture::Possible, 1u, screenCoords ) );
application.ProcessEvent( GenerateLongPress( Gesture::Started, 1u, screenCoords ) );
DALI_TEST_EQUALS( false, data.functorCalled, TEST_LOCATION );
}
| [
"sak0909@outlook.com"
] | sak0909@outlook.com |
5b457fd284b8d4a5f7c80a1f2f680da1d1d0e3c3 | 9afbec90ab8a66ad58160f037e5f6a88d135608f | /src/compat/glibc_compat.cpp | d0817fb4f43368a5546a4276d9212fb4cd11e3d5 | [] | no_license | campuscoindev/CC | 8b96151e93562d33855b58723b96e5785cc72fcb | 7d6f586e458558199c68e9d47fe36a416cc6a07b | refs/heads/master | 2023-08-03T09:38:11.470626 | 2023-07-20T15:36:45 | 2023-07-20T15:36:45 | 165,657,914 | 7 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 827 | cpp | // Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/cc-config.h"
#endif
#include <cstddef>
#if defined(HAVE_SYS_SELECT_H)
#include <sys/select.h>
#endif
// Prior to GLIBC_2.14, memcpy was aliased to memmove.
extern "C" void* memmove(void* a, const void* b, size_t c);
extern "C" void* memcpy(void* a, const void* b, size_t c)
{
return memmove(a, b, c);
}
extern "C" void __chk_fail(void) __attribute__((__noreturn__));
extern "C" FDELT_TYPE __fdelt_warn(FDELT_TYPE a)
{
if (a >= FD_SETSIZE)
__chk_fail();
return a / __NFDBITS;
}
extern "C" FDELT_TYPE __fdelt_chk(FDELT_TYPE) __attribute__((weak, alias("__fdelt_warn")));
| [
"webframes@gmail.com"
] | webframes@gmail.com |
cf7f539047488e3056324559d2ca21c0b801fcaa | 2ddc2dbf5340a56d7a9edf969ff430edf0461326 | /Triangle Types_1045.cpp | c507e458be374b99e7bc8757ff797a215c5c76dc | [] | no_license | babu12f/uri_problem_solved | 791df063744bf4319014779f68d9264f5bb6461f | 768c6f4ed7a31f361fba1843f1a5707b12476644 | refs/heads/master | 2021-05-08T07:13:03.025964 | 2017-10-16T18:08:59 | 2017-10-16T18:08:59 | 106,715,047 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 935 | cpp | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <iomanip>
#include <stdio.h>
#include <functional>
#define pf printf
#define sf scanf
using namespace std;
int main()
{
double a, b, c, arr[3];
int i, j, n;
cin>>arr[0]>>arr[1]>>arr[2];
sort(arr, arr+3, greater<double>());
a = arr[0];
b = arr[1];
c = arr[2];
if( a >= b+c )
cout<<"NAO FORMA TRIANGULO"<<endl;
else if( ( a * a ) == ( b * b ) + ( c * c ) )
cout<<"TRIANGULO RETANGULO"<<endl;
else if( ( a * a ) > ( b * b ) + ( c * c ) )
cout<<"TRIANGULO OBTUSANGULO"<<endl;
else if( ( a * a ) < ( b * b ) + ( c * c ) )
cout<<"TRIANGULO ACUTANGULO"<<endl;
if( a==b && a==c && b==c )
cout<<"TRIANGULO EQUILATERO"<<endl;
else if( ( a==b && a != c ) || ( b==c && b != a ) || ( c==a && a != b ) )
cout<<"TRIANGULO ISOSCELES"<<endl;
return 0;
}
| [
"babu_12f@yahoo.com"
] | babu_12f@yahoo.com |
944c0218f95274c77b5f0f62dda22a61d1b35b6d | ec2560aaa143f1d6c7920f7ce426edc3590755a3 | /src/main.cpp | bd4da616b0311d2c427a77bf01e560ab2c2966a4 | [] | no_license | shionn/Lamp9900K | 7ec37a5cee8c0980375e8192c1518e6843598329 | 2d4e679f1ef7ac142cf69d70622a96a9638fcf04 | refs/heads/master | 2022-10-20T15:47:57.435091 | 2020-07-26T16:41:54 | 2020-07-26T16:41:54 | 280,657,733 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,499 | cpp | #include <Arduino.h>
#include <Adafruit_NeoPixel.h>
#define PIXEL_COUNT 40
#define PIXEL_PIN 6
#define BUTTON 4
Adafruit_NeoPixel strip(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800);
int mode = 0;
int state = 0;
int buttonState = 1;
void setup() {
strip.begin(); // Initialize NeoPixel strip object (REQUIRED)
strip.show(); // Initialize all pixels to 'off'
pinMode(BUTTON, INPUT_PULLUP);
Serial.begin(9600);
}
uint32_t Wheel(byte WheelPos) {
WheelPos = 255 - WheelPos;
if(WheelPos < 85) {
return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
}
if(WheelPos < 170) {
WheelPos -= 85;
return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
}
WheelPos -= 170;
return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}
void displayColor(uint32_t color) {
for(int i = 0; i < PIXEL_COUNT; i++) {
strip.setPixelColor(i, color);
}
}
void chenille(int step) {
for(uint8_t i=0; i<PIXEL_COUNT; i++) {
uint8_t d = (step + PIXEL_COUNT - i) % (PIXEL_COUNT);
strip.setPixelColor(i, 255 >> d, 255 >> d, 255 >> d);
}
}
void doubleChenille(int step) {
for(uint8_t i=0; i<PIXEL_COUNT; i++) {
uint8_t d = (step + PIXEL_COUNT - i) % (PIXEL_COUNT /2);
strip.setPixelColor(i, 255 >> d, 255 >> d, 255 >> d);
}
}
void randFlash(int state) {
if (!state) {
uint8_t pos = random(PIXEL_COUNT);
for(uint8_t i=0; i<PIXEL_COUNT; i++) {
if (pos == i && state == 0) {
strip.setPixelColor(i,255,255,255);
} else {
uint32_t color = strip.getPixelColor(i);
strip.setPixelColor(i,
color >> 17 ,
(color & 0x0000ff00) >> 9,
(color & 0x000000ff) >> 1);
}
}
}
}
void loop() {
int value = analogRead(A0);
if (mode == 0) {
displayColor(strip.Color(0,0,0));
}
if (mode == 1) {
uint8_t a = pow(2,value/128);
displayColor(strip.Color(a,a,a));
}
if (mode == 2) {
displayColor(Wheel(value/8));
}
if (mode == 3) {
uint8_t a = pow(2,abs(map(state, 0, 1023, -8, 8)));
displayColor(strip.Color(a,a,a));
}
if (mode == 4) {
chenille(map(state, 0, 1024, 0, 39));
}
if (mode == 5) {
doubleChenille(map(state, 0, 1024, 0, 39));
}
if (mode == 6) {
randFlash(state%8);
}
state += value/16 + 1;
if ( state >= 1024) {
state -= 1024;
}
strip.show();
delay(10);
if (digitalRead(BUTTON) == 0 && buttonState) {
mode++;
if (mode == 7) {
mode = 0;
}
}
buttonState = digitalRead(BUTTON);
} | [
"shionn@gmail.com"
] | shionn@gmail.com |
279c3ab66a21e3e833f312f2a3476c5f650b7a67 | 285b4638f208afcb523feeea18bc5c6ad1ff0adc | /Backjoon/Dynamic Programming/(11055)가장_큰_증가_부분_수열.cpp | 441b56fa927d9f0344791d7c3513a29798a7193c | [] | no_license | Kuril951/ICPC_Study | 8941b8b86e3c12eef3858e2cbf880f84523bac7a | 78cd99b50fe05983e459672ae2f1c5ec6011cd17 | refs/heads/master | 2018-10-21T12:42:44.542883 | 2018-10-04T07:05:18 | 2018-10-04T07:05:18 | 116,656,800 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 401 | cpp | #include<iostream>
using namespace std;
int main()
{
int N, dp[1001] = { 0 }, res = 0;
int num[1001];
scanf("%d", &N);
for (int i = 0; i < N; i++) {
int maxN = 0, tmp;
scanf("%d", &tmp);
num[i] = dp[i] = tmp;
for (int j = 0; j < i; j++) {
if (num[j] < tmp && maxN < dp[j])
maxN = dp[j];
}
dp[i] += maxN;
if (dp[i] > res)
res = dp[i];
}
printf("%d", res);
return 0;
} | [
"viodle238@naver.com"
] | viodle238@naver.com |
6b5f4339f3a738dfcc79194ea90f1b2ff8a2cd12 | 142620600b8fb59f3b38079e7703c28c55eeac65 | /lib/Parallelization/Tasks/JunkDetectionTask.cpp | faa62198017a062f2d0d812fa25ba897cf668dcd | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | dmark1021/mull | 289d7b17b93c3999e870297bbefc89fb49ffbd4a | 0eac81abd7efaf2a793e6586a2d1c0c79271b388 | refs/heads/master | 2020-04-20T04:39:29.563988 | 2019-01-29T22:19:09 | 2019-01-29T22:19:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 566 | cpp | #include "Parallelization/Tasks/JunkDetectionTask.h"
#include "Parallelization/Progress.h"
#include "JunkDetection/JunkDetector.h"
using namespace mull;
JunkDetectionTask::JunkDetectionTask(JunkDetector &detector)
: detector(detector) {}
void JunkDetectionTask::operator()(iterator begin, iterator end,
Out &storage, progress_counter &counter) {
for (auto it = begin; it != end; ++it, counter.increment()) {
auto point = *it;
if (detector.isJunk(point)) {
continue;
}
storage.push_back(point);
}
}
| [
"1101.debian@gmail.com"
] | 1101.debian@gmail.com |
44f5d6893236a1fb6ff716204a4dfe521cd9b3ed | 5838cf8f133a62df151ed12a5f928a43c11772ed | /NT/inetsrv/iis/config/src/core/catutil/precomp.hxx | e171741e5158679bf57dc3cad5495c959f08b998 | [] | no_license | proaholic/Win2K3 | e5e17b2262f8a2e9590d3fd7a201da19771eb132 | 572f0250d5825e7b80920b6610c22c5b9baaa3aa | refs/heads/master | 2023-07-09T06:15:54.474432 | 2021-08-11T09:09:14 | 2021-08-11T09:09:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,727 | hxx | /*++
Copyright (c) 1996 Microsoft Corporation
Module Name:
precomp.hxx
Abstract:
Master include file for the schemagen
Author:
Ivan Pashov (IvanPash) 02-Apr-2002
Revision History:
--*/
#pragma once
#include <windows.h>
#include <stdio.h>
#include <olectl.h>
#include <xmlparser.h>
#include <iiscnfg.h>
#include <catalog.h>
#include <catmeta.h>
#include <CoreMacros.h>
#define _ATL_NO_DEBUG_CRT
#define ATLASSERT(expr) ASSERT(expr)
#include <atlbase.h>
#include <safecs.h>
#include <Hash.h>
#include <MetaTableStructs.h>
#include <FixedTableHeap.h>
#include <TableSchema.h>
#include <SmartPointer.h>
#include <TMSXMLBase.h>
#include <TFileMapping.h>
#include <Unknown.hxx>
#include <TXmlParsedFile.h>
#include <wstring.h>
#include "..\schemagen\XMLUtility.h"
#include "..\schemagen\Output.h"
#include "..\schemagen\TException.h"
#include "..\schemagen\THeap.h"
#include "..\schemagen\TPEFixup.h"
#include "..\schemagen\TFixupHeaps.h"
#include "..\schemagen\TIndexMeta.h"
#include "..\schemagen\TTagMeta.h"
#include "..\schemagen\TColumnMeta.h"
#include "..\schemagen\TRelationMeta.h"
#include "TXmlFile.h"
#include "..\schemagen\ICompilationPlugin.h"
#include "..\schemagen\TTableMeta.h"
#include "..\schemagen\TFixedTableHeapBuilder.h"
#include "TSchemaGeneration.h"
#include "..\schemagen\TCom.h"
#include "..\schemagen\TFile.h"
#include "..\schemagen\THashedUniqueIndexes.h"
#include "TTableInfoGeneration.h"
#include "TComCatMetaXmlFile.h"
#include "TFixupDLL.h"
#include "TComCatDataXmlFile.h"
#include "TPopulateTableSchema.h"
#include "..\schemagen\TDatabaseMeta.h"
#include "..\schemagen\TMetaInferrence.h"
#include "..\schemagen\THashedPKIndexes.h"
#include "TLateSchemaValidate.h"
| [
"blindtiger@foxmail.com"
] | blindtiger@foxmail.com |
281c70e7c2ca7a0d7271d91f467dba9ff9597b05 | 28dba754ddf8211d754dd4a6b0704bbedb2bd373 | /Ural/P1277.cpp | d1d918f48d3aa712a21c2ec0db9d1a9e87e7593d | [] | no_license | zjsxzy/algo | 599354679bd72ef20c724bb50b42fce65ceab76f | a84494969952f981bfdc38003f7269e5c80a142e | refs/heads/master | 2023-08-31T17:00:53.393421 | 2023-08-19T14:20:31 | 2023-08-19T14:20:31 | 10,140,040 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,310 | cpp | #include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 200 + 10;
const int inf = 0x3f3f3f3f;
struct SAP
{
int cap[MAXN][MAXN], flow[MAXN][MAXN], g[MAXN][MAXN];
int n;
int h[MAXN], vh[MAXN], source, sink;
int mk[MAXN];
void init(int n)
{
this->n = n;
memset(cap, 0, sizeof(cap));
memset(g, 0, sizeof(g));
memset(mk, 0, sizeof(mk));
}
void addCap(int i, int j, int val)
{
cap[i][j] += val;
g[i][j] = 1;
}
int sap(const int idx, const int maxCap)
{
if (idx == sink)
return maxCap;
int l = maxCap, d, minH = n;
for (int i = 0; i < n; i++)
{
if (cap[idx][i] - flow[idx][i] > 0)
{
if (h[idx] == h[i] + 1)
{
d = sap(i, min(l, cap[idx][i] - flow[idx][i]));
flow[idx][i] += d;
flow[i][idx] -= d;
l -= d;
if (h[source] == n || l == 0) return maxCap - l;
}
minH = min(minH, h[i] + 1);
}
}
if (l == maxCap)
{
vh[h[idx]]--;
vh[minH]++;
if (vh[h[idx]] == 0)
h[source] = n;
h[idx] = minH;
}
return maxCap - l;
}
int solve(int source, int sink)
{
if (source == sink) return inf;
this->sink = sink;
this->source = source;
memset(flow, 0, sizeof(flow));
memset(h, 0, sizeof(h));
memset(vh, 0, sizeof(vh));
int ans = 0;
while (h[source] != n)
ans += sap(source, inf);
return ans;
}
}sap;
int K, N, M, S, F;
int main()
{
freopen("in.txt", "r", stdin);
cin >> K;
cin >> N >> M >> S >> F;
S--; F--;
sap.init(2 * N);
for (int i = 0; i < N; i++) {
int x;
cin >> x;
sap.addCap(2 * i, 2 * i + 1, x);
sap.addCap(2 * i + 1, 2 * i, x);
}
while (M--) {
int u, v;
cin >> u >> v;
u--; v--;
sap.addCap(2 * u + 1, 2 * v, inf);
sap.addCap(2 * v + 1, 2 * u, inf);
}
int source = 2 * S + 1, sink = 2 * F;
int ret = sap.solve(source, sink);
if (ret > K || S == F)
puts("NO");
else puts("YES");
return 0;
}
| [
"zjsxzy@gmail.com"
] | zjsxzy@gmail.com |
80569f4edda4541973f452a5a57caf2f2faf59f5 | 9f5289c0bb0d3d7a91d1003a4ae7564576cb169e | /Source/SBansheeEngine/Source/BsScriptResourceManager.cpp | a73c6b30c3f5f11e6f0eec4be46efff3e4c63a58 | [] | no_license | linuxaged/BansheeEngine | 59fa82828ba0e38841ac280ea1878c9f1e9bf9bd | 12cb86711cc98847709f702e11a577cc7c2f7913 | refs/heads/master | 2021-01-11T00:04:23.661733 | 2016-10-10T13:18:44 | 2016-10-10T13:18:44 | 70,758,880 | 3 | 3 | null | 2016-10-13T01:57:56 | 2016-10-13T01:57:55 | null | UTF-8 | C++ | false | false | 17,585 | cpp | //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
//**************** Copyright (c) 2016 Marko Pintera (marko.pintera@gmail.com). All rights reserved. **********************//
#include "BsScriptResourceManager.h"
#include "BsMonoManager.h"
#include "BsMonoAssembly.h"
#include "BsMonoClass.h"
#include "BsResources.h"
#include "BsScriptTexture2D.h"
#include "BsScriptTexture3D.h"
#include "BsScriptTextureCube.h"
#include "BsScriptSpriteTexture.h"
#include "BsScriptPlainText.h"
#include "BsScriptScriptCode.h"
#include "BsScriptShader.h"
#include "BsScriptShaderInclude.h"
#include "BsScriptMaterial.h"
#include "BsScriptMesh.h"
#include "BsScriptFont.h"
#include "BsScriptPrefab.h"
#include "BsScriptStringTable.h"
#include "BsScriptGUISkin.h"
#include "BsScriptPhysicsMaterial.h"
#include "BsScriptPhysicsMesh.h"
#include "BsScriptAudioClip.h"
#include "BsScriptAnimationClip.h"
#include "BsScriptManagedResource.h"
#include "BsScriptAssemblyManager.h"
using namespace std::placeholders;
namespace BansheeEngine
{
ScriptResourceManager::ScriptResourceManager()
{
mResourceDestroyedConn = gResources().onResourceDestroyed.connect(std::bind(&ScriptResourceManager::onResourceDestroyed, this, _1));
}
ScriptResourceManager::~ScriptResourceManager()
{
mResourceDestroyedConn.disconnect();
}
template<class RetType, class InType>
void ScriptResourceManager::createScriptResource(MonoObject* instance, const ResourceHandle<InType>& resourceHandle, RetType** out)
{
const String& uuid = resourceHandle.getUUID();
#if BS_DEBUG_MODE
_throwExceptionIfInvalidOrDuplicate(uuid);
#endif
RetType* scriptResource = new (bs_alloc<RetType>()) RetType(instance, resourceHandle);
mScriptResources[uuid] = scriptResource;
*out = scriptResource;
}
template<class RetType, class InType>
void ScriptResourceManager::getScriptResource(const ResourceHandle<InType>& resourceHandle, RetType** out, bool create)
{
String uuid = resourceHandle.getUUID();
if (!uuid.empty())
{
*out = static_cast<RetType*>(getScriptResource(uuid));
if (*out == nullptr && create)
createScriptResource(resourceHandle, out);
}
else
*out = nullptr;
}
namespace Detail
{
template<class RetType, class InType>
void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<InType>& resourceHandle, RetType** out)
{
MonoObject* monoInstance = RetType::createInstance();
thisPtr->createScriptResource(monoInstance, resourceHandle, out);
}
template<>
void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<StringTable>& resourceHandle, ScriptStringTable** out)
{
MonoClass* resourceClass = ScriptStringTable::getMetaData()->scriptClass;
bool dummy = true;
void* params = { &dummy };
MonoObject* monoInstance = resourceClass->createInstance(¶ms, 1);
thisPtr->createScriptResource(monoInstance, resourceHandle, out);
}
template<>
void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<Texture>& resourceHandle, ScriptTextureBase** out)
{
TextureType type = resourceHandle->getProperties().getTextureType();
if (type == TEX_TYPE_3D)
return ScriptResourceManager_createScriptResource(thisPtr, resourceHandle, (ScriptTexture3D**)out);
else if (type == TEX_TYPE_CUBE_MAP)
return ScriptResourceManager_createScriptResource(thisPtr, resourceHandle, (ScriptTextureCube**)out);
else
return ScriptResourceManager_createScriptResource(thisPtr, resourceHandle, (ScriptTexture2D**)out);
}
template<>
void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const HResource& resourceHandle, ScriptResourceBase** out)
{
#if BS_DEBUG_MODE
thisPtr->_throwExceptionIfInvalidOrDuplicate(resourceHandle.getUUID());
#endif
UINT32 resTypeID = resourceHandle->getTypeId();
switch (resTypeID)
{
case TID_Texture:
{
HTexture texture = static_resource_cast<Texture>(resourceHandle);
TextureType type = texture->getProperties().getTextureType();
if (type == TEX_TYPE_3D)
return ScriptResourceManager_createScriptResource(thisPtr, texture, (ScriptTexture3D**)out);
else if (type == TEX_TYPE_CUBE_MAP)
return ScriptResourceManager_createScriptResource(thisPtr, texture, (ScriptTextureCube**)out);
else
return ScriptResourceManager_createScriptResource(thisPtr, texture, (ScriptTexture2D**)out);
}
case TID_SpriteTexture:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<SpriteTexture>(resourceHandle), (ScriptSpriteTexture**)out);
case TID_Font:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<Font>(resourceHandle), (ScriptFont**)out);
case TID_PlainText:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<PlainText>(resourceHandle), (ScriptPlainText**)out);
case TID_ScriptCode:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<ScriptCode>(resourceHandle), (ScriptScriptCode**)out);
case TID_Shader:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<Shader>(resourceHandle), (ScriptShader**)out);
case TID_ShaderInclude:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<ShaderInclude>(resourceHandle), (ScriptShaderInclude**)out);
case TID_Prefab:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<Prefab>(resourceHandle), (ScriptPrefab**)out);
case TID_StringTable:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<StringTable>(resourceHandle), (ScriptStringTable**)out);
case TID_Material:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<Material>(resourceHandle), (ScriptMaterial**)out);
case TID_Mesh:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<Mesh>(resourceHandle), (ScriptMesh**)out);
case TID_GUISkin:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<GUISkin>(resourceHandle), (ScriptGUISkin**)out);
case TID_PhysicsMaterial:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<PhysicsMaterial>(resourceHandle), (ScriptPhysicsMaterial**)out);
case TID_PhysicsMesh:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<PhysicsMesh>(resourceHandle), (ScriptPhysicsMesh**)out);
case TID_AudioClip:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<AudioClip>(resourceHandle), (ScriptAudioClip**)out);
case TID_AnimationClip:
return ScriptResourceManager_createScriptResource(thisPtr, static_resource_cast<AnimationClip>(resourceHandle), (ScriptAnimationClip**)out);
case TID_ManagedResource:
BS_EXCEPT(InternalErrorException, "Managed resources must have a managed instance by default, this call is invalid.")
break;
default:
BS_EXCEPT(NotImplementedException, "Attempting to load a resource type that is not supported. Type ID: " + toString(resTypeID));
break;
}
}
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<Texture>&, ScriptTexture2D**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<Texture>&, ScriptTexture3D**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<Texture>&, ScriptTextureCube**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<Texture>&, ScriptTextureBase**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<SpriteTexture>&, ScriptSpriteTexture**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<Mesh>&, ScriptMesh**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<Material>&, ScriptMaterial**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<Shader>&, ScriptShader**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<ShaderInclude>&, ScriptShaderInclude**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<Prefab>&, ScriptPrefab**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<Font>&, ScriptFont**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<PlainText>&, ScriptPlainText**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<ScriptCode>&, ScriptScriptCode**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<StringTable>&, ScriptStringTable**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<GUISkin>&, ScriptGUISkin**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<PhysicsMesh>&, ScriptPhysicsMesh**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<PhysicsMaterial>&, ScriptPhysicsMaterial**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<AudioClip>&, ScriptAudioClip**);
template void ScriptResourceManager_createScriptResource(ScriptResourceManager* thisPtr, const ResourceHandle<AnimationClip>&, ScriptAnimationClip**);
}
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<Texture>&, ScriptTexture2D**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<Texture>&, ScriptTexture3D**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<Texture>&, ScriptTextureCube**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<SpriteTexture>&, ScriptSpriteTexture**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<Mesh>&, ScriptMesh**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<Material>&, ScriptMaterial**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<Shader>&, ScriptShader**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<ShaderInclude>&, ScriptShaderInclude**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<Prefab>&, ScriptPrefab**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<Font>&, ScriptFont**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<PlainText>&, ScriptPlainText**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<ScriptCode>&, ScriptScriptCode**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<StringTable>&, ScriptStringTable**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<GUISkin>&, ScriptGUISkin**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<PhysicsMesh>&, ScriptPhysicsMesh**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<PhysicsMaterial>&, ScriptPhysicsMaterial**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<AudioClip>&, ScriptAudioClip**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<AnimationClip>&, ScriptAnimationClip**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::createScriptResource(MonoObject*, const ResourceHandle<ManagedResource>&, ScriptManagedResource**);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<Texture>& resourceHandle, ScriptTexture2D** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<Texture>& resourceHandle, ScriptTexture3D** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<Texture>& resourceHandle, ScriptTextureCube** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<Texture>& resourceHandle, ScriptTextureBase** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<SpriteTexture>& resourceHandle, ScriptSpriteTexture** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<Mesh>& resourceHandle, ScriptMesh** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<Material>& resourceHandle, ScriptMaterial** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<Shader>& resourceHandle, ScriptShader** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<ShaderInclude>& resourceHandle, ScriptShaderInclude** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<Prefab>& resourceHandle, ScriptPrefab** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<Font>& resourceHandle, ScriptFont** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<PlainText>& resourceHandle, ScriptPlainText** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<ScriptCode>& resourceHandle, ScriptScriptCode** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<StringTable>& resourceHandle, ScriptStringTable** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<GUISkin>& resourceHandle, ScriptGUISkin** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<PhysicsMesh>& resourceHandle, ScriptPhysicsMesh** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<PhysicsMaterial>& resourceHandle, ScriptPhysicsMaterial** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<AudioClip>& resourceHandle, ScriptAudioClip** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<AnimationClip>& resourceHandle, ScriptAnimationClip** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<ManagedResource>& resourceHandle, ScriptManagedResource** out, bool create);
template BS_SCR_BE_EXPORT void ScriptResourceManager::getScriptResource(const ResourceHandle<Resource>& resourceHandle, ScriptResourceBase** out, bool create);
ScriptResourceBase* ScriptResourceManager::getScriptResource(const String& uuid)
{
if (uuid == "")
return nullptr;
auto findIter = mScriptResources.find(uuid);
if(findIter != mScriptResources.end())
return findIter->second;
return nullptr;
}
void ScriptResourceManager::destroyScriptResource(ScriptResourceBase* resource)
{
HResource resourceHandle = resource->getGenericHandle();
const String& uuid = resourceHandle.getUUID();
if(uuid == "")
BS_EXCEPT(InvalidParametersException, "Provided resource handle has an undefined resource UUID.");
(resource)->~ScriptResourceBase();
MemoryAllocator<GenAlloc>::free(resource);
mScriptResources.erase(uuid);
}
void ScriptResourceManager::onResourceDestroyed(const String& UUID)
{
auto findIter = mScriptResources.find(UUID);
if (findIter != mScriptResources.end())
{
findIter->second->notifyResourceDestroyed();
mScriptResources.erase(findIter);
}
}
void ScriptResourceManager::_throwExceptionIfInvalidOrDuplicate(const String& uuid) const
{
if(uuid == "")
BS_EXCEPT(InvalidParametersException, "Provided resource handle has an undefined resource UUID.");
auto findIter = mScriptResources.find(uuid);
if(findIter != mScriptResources.end())
{
BS_EXCEPT(InvalidStateException, "Provided resource handle already has a script resource. \
Retrieve the existing instance instead of creating a new one.");
}
}
} | [
"bearishsun@gmail.com"
] | bearishsun@gmail.com |
b41122e6588fbf460da1a54840c13540644f09f2 | 0dc243cf9828bd1ca3acdefe02acf7febd7817fe | /src/Geometry_GeometricTests/GeometricPrimitives.cpp | 3d268a261d660eb8cfece2b10e5340dd609b3b8c | [
"BSD-3-Clause"
] | permissive | Akranar/daguerreo | c8b38eb43cf4f59497c2d2d13ced92911bd3cc5a | 20999144d2c62e54837cd60462cf0db2cfb2d5c8 | refs/heads/master | 2020-05-22T12:38:22.550303 | 2011-10-05T22:55:26 | 2011-10-05T22:55:26 | 2,337,599 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34 | cpp | #include "GeometricPrimitives.h"
| [
"akranar@gmail.com"
] | akranar@gmail.com |
62bbf01038639d94938b8490447c838dfb620c03 | 7e0ab9f52aa73962260411656903e217ccc34757 | /src/Analysis.hpp | 7e178ad2962317c9430f824d0dbe08a1fed32907 | [
"Apache-2.0"
] | permissive | vishalbelsare/OpenABL | 5a46f1e6d61e6317c905f82cc5bd6d7e318abbac | eb08ef86df0b9c0532cb8fd6b714bde5e8551923 | refs/heads/master | 2021-06-05T14:55:52.644766 | 2019-08-12T09:03:53 | 2019-08-12T09:03:53 | 141,203,558 | 0 | 0 | Apache-2.0 | 2021-04-04T17:43:16 | 2018-07-16T22:57:37 | C++ | UTF-8 | C++ | false | false | 5,847 | hpp | /* Copyright 2017 OpenABL Contributors
*
* 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. */
#pragma once
#include <map>
#include <vector>
#include <functional>
#include <cassert>
#include "Type.hpp"
#include "Value.hpp"
namespace OpenABL {
// Globally unique variable id, to distinguish
// different variables that have the same name.
struct VarId {
static VarId make() {
return VarId { ++max_id };
}
bool operator==(const VarId &other) const {
return id == other.id;
}
bool operator!=(const VarId &other) const {
return id != other.id;
}
bool operator<(const VarId &other) const {
return id < other.id;
}
VarId() : id{0} {}
void reset() { id = 0; }
private:
VarId(uint32_t id) : id{id} {}
static uint32_t max_id;
uint32_t id;
};
struct ScopeEntry {
Type type;
bool isConst;
bool isGlobal;
Value val;
};
struct Scope {
void add(VarId var, Type type, bool isConst, bool isGlobal, Value val) {
vars.insert({ var, ScopeEntry { type, isConst, isGlobal, val } });
}
bool has(VarId var) const {
return vars.find(var) != vars.end();
}
const ScopeEntry &get(VarId var) const {
auto it = vars.find(var);
return it->second;
}
private:
std::map<VarId, ScopeEntry> vars;
};
struct FunctionSignature {
static const unsigned MAIN_ONLY = 1 << 0;
static const unsigned STEP_ONLY = 1 << 1;
static const unsigned SEQ_STEP_ONLY = 1 << 2;
static const unsigned MAIN_STEP_ONLY = MAIN_ONLY | STEP_ONLY;
FunctionSignature()
: origName(""), name(""), paramTypes(), returnType(), flags(0), decl(nullptr) {}
FunctionSignature(const std::string &origName, const std::string &name,
const std::vector<Type> ¶mTypes, Type returnType,
unsigned flags, const AST::FunctionDeclaration *decl)
: origName(origName), name(name),
paramTypes(paramTypes), returnType(returnType),
flags(flags), decl(decl) {}
bool isCompatibleWith(const std::vector<Type> &argTypes) const {
if (customIsCompatibleWith) {
return customIsCompatibleWith(argTypes);
}
if (argTypes.size() != paramTypes.size()) {
return false;
}
for (size_t i = 0; i < argTypes.size(); i++) {
if (!argTypes[i].isPromotableTo(paramTypes[i])) {
return false;
}
}
return true;
}
bool isConflictingWith(const std::vector<Type> &newParamTypes) const {
if (newParamTypes.size() != paramTypes.size()) {
// Always allow arity overloading
return false;
}
// Don't allow overloading between bool, int and float
bool haveDiff = false;
for (size_t i = 0; i < newParamTypes.size(); i++) {
Type newParamType = newParamTypes[i], paramType = paramTypes[i];
if (newParamType != paramType) {
haveDiff = true;
if ((paramType.isBool() || paramType.isInt() || paramType.isFloat())
&& (newParamType.isBool() || newParamType.isInt() || newParamType.isFloat())) {
return true;
}
}
}
return !haveDiff;
}
// Concrete signature with any generic agent types replaced
FunctionSignature getConcreteSignature(const std::vector<Type> &argTypes) const;
std::string origName;
std::string name;
std::vector<Type> paramTypes;
Type returnType;
unsigned flags;
const AST::FunctionDeclaration *decl;
std::function<bool(const std::vector<Type> &)> customIsCompatibleWith = {};
std::function<FunctionSignature(const std::vector<Type> &)> customGetConcreteSignature = {};
};
struct Function {
const FunctionSignature *getCompatibleSignature(const std::vector<Type> &argTypes) const {
for (const FunctionSignature &sig : signatures) {
if (sig.isCompatibleWith(argTypes)) {
return &sig;
}
}
return nullptr;
}
// Get signature that conflicts for the purpose of overloading
const FunctionSignature *getConflictingSignature(const std::vector<Type> ¶mTypes) const {
for (const FunctionSignature &sig : signatures) {
if (sig.isConflictingWith(paramTypes)) {
return &sig;
}
}
return nullptr;
}
std::string name;
std::vector<FunctionSignature> signatures;
};
struct FunctionList {
std::map<std::string, Function> funcs;
void add(FunctionSignature sig) {
funcs[sig.origName].signatures.push_back(sig);
}
void add(const std::string &name, const std::string &sigName,
std::vector<Type> argTypes, Type returnType, unsigned flags = 0) {
add({ name, sigName, argTypes, returnType, flags, nullptr });
}
void add(const std::string &name, std::vector<Type> argTypes,
Type returnType, unsigned flags = 0) {
add(name, name, argTypes, returnType, flags);
}
Function *getByName(const std::string &name) {
auto it = funcs.find(name);
if (it == funcs.end()) {
return nullptr;
}
return &it->second;
}
};
/* Supported types of reductions across all agents */
enum class ReductionKind {
COUNT_TYPE,
COUNT_MEMBER,
SUM_MEMBER,
};
using ReductionInfo = std::pair<ReductionKind, Type>;
}
namespace std {
template<> struct hash<OpenABL::ReductionInfo> {
size_t operator()(const OpenABL::ReductionInfo &t) const {
return std::hash<int>()(static_cast<int>(t.first))
^ std::hash<OpenABL::Type>()(t.second);
}
};
}
| [
"nikita.ppv@gmail.com"
] | nikita.ppv@gmail.com |
ea3724c52872965a0ea4acf2a6f2bdf880266333 | 456551bbf0c752075d23e2dd348d9bf09533c40f | /ABC/146/c.cpp | 5ede690b89b03ad52025de6bc22f279bc03acb31 | [] | no_license | skjmp/ProCon | 5bed08c6efdc202d5f7d6038cd7a99d9c59d58f0 | b9971b374d45499f22e6eb0107473ca37ca46591 | refs/heads/master | 2020-03-27T20:12:38.044762 | 2020-03-01T11:42:03 | 2020-03-01T13:49:31 | 147,048,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,858 | cpp | #include <bits/stdc++.h>
#define REP(i, a, n) for (long long i = (a); i < (long long)(n); ++i)
#define REPC(i, a, n) for (long long i = (a); i <= (long long)(n); ++i)
#define ALL(t) t.begin(), t.end()
#define RALL(t) t.rbegin(), t.rend()
#define MATINIT(type, row, col, init) \
vector<vector<type>>(row, vector<type>(col, init));
#define Yes(cond) cout << (cond ? "Yes" : "No") << endl;
#define YES(cond) cout << (cond ? "YES" : "NO") << endl;
using namespace std;
using LL = long long;
using ULL = unsigned long long;
template <class T>
using VEC = std::vector<T>;
template <class T>
using MAT = std::vector<std::vector<T>>;
void DUMP() { cerr << endl; }
template <class Head, class... Tail>
void DUMP(Head &&head, Tail &&... tail) {
cerr << head << ", ";
DUMP(std::move(tail)...);
}
template <typename T>
ostream &operator<<(ostream &os, vector<T> &vec) {
os << "{";
for (auto v : vec) os << v << ",";
os << "}";
return os;
}
template <typename T>
ostream &operator<<(ostream &os, set<T> &s) {
os << "{";
for (auto p : s) os << p << ",";
os << "}";
return os;
}
template <typename T1, typename T2>
ostream &operator<<(ostream &os, map<T1, T2> &m) {
os << "{";
for (auto p : m) os << p << ",";
os << "}";
return os;
}
template <typename T1, typename T2>
ostream &operator<<(ostream &os, pair<T1, T2> p) {
os << "[" << p.first << " " << p.second << "]";
return os;
}
int main() {
LL A, B, X;
cin >> A >> B >> X;
int left = 0;
int right = 1e9 + 1;
auto f = [&](LL N) -> LL {
int keta = 0;
LL M = N;
while (M > 0) {
M /= 10;
keta++;
}
return A * N + B * keta;
};
while (right - left > 1) {
LL mid = (left + right) / 2;
// DUMP(left, right, f(mid));
if (f(mid) <= X) {
left = mid;
} else {
right = mid;
}
}
cout << left << endl;
return 0;
}
| [
"2036oshmkufafg36@gmail.com"
] | 2036oshmkufafg36@gmail.com |
d3442873e65e3cf548e6a539cd4918ccfec402a3 | 5d334d89e22028b95d4924a42bc0623fe013316d | /modules/util/source/Color.cpp | 0cc04e61ab009e51762b62f8ee81268f233c833b | [] | no_license | alxarsenault/axlib | e2369e20664c01f004e989e24e595475bdf85e5d | b4b4241ffc9b58849925fe4e8b966e8199990c35 | refs/heads/master | 2021-06-18T12:23:08.901204 | 2017-07-13T17:26:40 | 2017-07-13T17:26:40 | 64,876,596 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,565 | cpp | /*
* Copyright (c) 2016 Alexandre Arsenault.
*
* This file is part of axLib.
*
* axLib is free or commercial software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 or any later version of the
* License or use a commercial axFrameworks License.
*
* axLib 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 axLib. If not, see <http://www.gnu.org/licenses/>.
*
* To release a closed-source product which uses axLib, commercial
* licenses are available, email alx.arsenault@gmail.com for more information.
*/
#include "Color.hpp"
namespace ax {
namespace util {
ColorVector CreateHeatColors(const int& n)
{
ColorVector colors;
float incr = 1.0 / float(n);
float v = 0.0;
float r = 1.0;
float g = 0.0;
float b = 0.0;
for (int i = 0; i < n; i++) {
g = v;
v += incr;
if (v > 1.0)
v = 1.0;
if (g > 1.0)
g = 1.0;
colors.emplace_back(Color<float>(r, g, b, 1.0));
}
return colors;
}
ColorVector CreateRainbowColors(const int& n)
{
ColorVector colors;
float separation = 1.0 / 6.0;
float incr = 1.0 / float(n);
float v = 0.0;
for (int i = 0; i < n; i++) {
float r = 0.0;
float g = 0.0;
float b = 0.0;
float ratio = 0.0;
float t = v;
if (t > 5 * separation) {
ratio = (t - (5.0 * separation)) / (separation);
r = 1.0;
g = 0.0;
b = 1.0 - ratio;
}
else if (t > 4 * separation) {
ratio = (t - (4.0 * separation)) / (separation);
r = ratio;
g = 0.0;
b = 1.0;
}
else if (t > 3 * separation) {
ratio = (t - (3.0 * separation)) / (separation);
r = 0.0;
g = 1.0 - ratio;
b = 1.0;
}
else if (t > 2 * separation) {
ratio = (t - (2.0 * separation)) / (separation);
r = 0.0;
g = 1.0;
b = ratio;
}
else if (t > separation) {
ratio = (t - separation) / (separation);
r = 1.0 - ratio;
g = 1.0;
b = 0.0;
}
else {
ratio = t / (separation);
r = 1.0;
g = ratio;
b = 0.0;
}
v += incr;
if (v > 1.0)
v = 1.0;
if (r > 1.0)
r = 1.0;
if (g > 1.0)
g = 1.0;
if (b > 1.0)
b = 1.0;
colors.emplace_back(Color<float>(r, g, b, 1.0));
}
return colors;
}
}
}
| [
"aarsenault@erftcomposites.com"
] | aarsenault@erftcomposites.com |
c6936538f8af030df34c7847894f8d81f92cb120 | 992c8fa8d4b881e9ffd2055d6d42b98f8ea85b9d | /bodymaxIndex.cpp | 5cb0d4d59470becda35fed8a3e262f5d20f5636d | [] | no_license | jonadiazz/time-well-wasted | 6ebdcd937a04a506c19c924e45346c20f8aea8e2 | 8cdc8eaa60ceb54bdbb9045f8f5028cd64e418ef | refs/heads/master | 2021-01-01T18:29:12.758876 | 2015-01-30T00:55:27 | 2015-01-30T00:55:27 | 29,946,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 149 | cpp | #include <iostream>
int main (void) {
std::cout << "Enter your weight: " << std::endl;
std::cout << "Enter your height: " << std::endl;
}
| [
"jonadiazz@hotmail.com"
] | jonadiazz@hotmail.com |
15419330440fd257f86d1382598aa93972373ac0 | 87febda1eb6c6d1f28374414f3485f4ac7bc7b90 | /i2c/i2c.h | 4d08ce0d5c3816b78de0f1e41218fa5f34b71a9c | [
"BSD-2-Clause"
] | permissive | pgbaum/bbExamples | 3e7a72d5edc4a8ee9e709449bd94769db306381e | 9c90dedd6e993f6c13114e0973913b66f83e8787 | refs/heads/master | 2020-05-19T10:52:09.943913 | 2014-03-11T20:25:10 | 2014-03-11T20:25:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | h | #ifndef I2C_H_INCLUDED
#define I2C_H_INCLUDED
#include <cstdint>
class I2C
{
private:
int dev;
void registerClient( int addr );
public:
// TODO: allow more than one device
I2C( const char *device, int address );
~I2C( );
void write1( uint8_t cmd, uint8_t val )
{
write( cmd, &val, 1 );
}
void write( uint8_t cmd, uint8_t *p, int n );
};
#endif
| [
"peter@dr-baum.net"
] | peter@dr-baum.net |
5a9d8a99ec74562f9aa8b8ef4170ff28407c32f6 | ce497b404b38bdf2e2708fdfb870edcdef81866b | /cpp/ProjectQServer/Desu3/GState.cpp | 5ee656ddebe6f8d1189f1c447f126ab00da815ac | [] | no_license | rjrivera/code-dojo | 00e8c9ef5e2d3b1912c74c3afa0de66624eaa0e7 | 083bf5a4a41e9055dd78bc9be0a2d3b6f29651c3 | refs/heads/master | 2020-04-06T05:42:06.276739 | 2020-03-08T20:57:30 | 2020-03-08T20:57:30 | 28,792,381 | 0 | 3 | null | 2017-02-01T07:17:18 | 2015-01-05T01:35:42 | C++ | UTF-8 | C++ | false | false | 648 | cpp | #include "GState.h"
#include "Event.cpp"
#include "Point.cpp"
GState::GState() : GPoint(new Point()){ // INFO: Point() defaults to X->0, Y->0;
}
//public
void GState::eventHandler(Event * curEvent){
switch(curEvent->eventType){
case 0:
GPoint->X(GPoint->X() + 1); // set the Point->X to Point->X + 1 via the public api of Point.h
break;
default:
std::cout << curEvent->eventType << " is not a recognized eventType\n";
}
// std::cout << GPoint->X() << ", " << GPoint->Y() << std::endl;
}
void GState::iterateAI(){
// no AI Behavior currently defined.
}
//private
void GState::eventProcessor(Event * curEvent){
}
| [
"riveratyrant@gmail.com"
] | riveratyrant@gmail.com |
11a57f0b69c78ae8acc7dfbf1dc48e3e84f23c81 | 99778425ab9564302e48e7acbd6cb27a3c93a7dc | /src/qt/sendcoinsdialog.cpp | c7bd80d092705190b0a4bfe8e6c25bde4eb452e3 | [
"MIT"
] | permissive | Tastigernet/thor-core | d5b4e48e9b38e7c61c36785bbc662e3a9d03e88b | dc60b5dfa97f382d138a38edb1fecb85d5baf0c2 | refs/heads/master | 2022-04-21T03:10:21.610332 | 2020-04-20T02:45:54 | 2020-04-20T02:45:54 | 256,633,996 | 0 | 0 | MIT | 2020-04-17T23:54:32 | 2020-04-17T23:54:31 | null | UTF-8 | C++ | false | false | 34,741 | cpp | // Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/sendcoinsdialog.h>
#include <qt/forms/ui_sendcoinsdialog.h>
#include <qt/addresstablemodel.h>
#include <qt/bitcoinunits.h>
#include <qt/clientmodel.h>
#include <qt/coincontroldialog.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <qt/sendcoinsentry.h>
#include <base58.h>
#include <chainparams.h>
#include <wallet/coincontrol.h>
#include <validation.h> // mempool and minRelayTxFee
#include <ui_interface.h>
#include <txmempool.h>
#include <policy/fees.h>
#include <wallet/fees.h>
#include <QFontMetrics>
#include <QScrollBar>
#include <QSettings>
#include <QTextDocument>
static const std::array<int, 9> confTargets = { {2, 4, 6, 12, 24, 48, 144, 504, 1008} };
int getConfTargetForIndex(int index) {
if (index+1 > static_cast<int>(confTargets.size())) {
return confTargets.back();
}
if (index < 0) {
return confTargets[0];
}
return confTargets[index];
}
int getIndexForConfTarget(int target) {
for (unsigned int i = 0; i < confTargets.size(); i++) {
if (confTargets[i] >= target) {
return i;
}
}
return confTargets.size() - 1;
}
SendCoinsDialog::SendCoinsDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
clientModel(0),
model(0),
fNewRecipientAllowed(true),
fFeeMinimized(true),
platformStyle(_platformStyle)
{
ui->setupUi(this);
if (!_platformStyle->getImagesOnButtons()) {
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
} else {
ui->addButton->setIcon(_platformStyle->SingleColorIcon(":/icons/add"));
ui->clearButton->setIcon(_platformStyle->SingleColorIcon(":/icons/remove"));
ui->sendButton->setIcon(_platformStyle->SingleColorIcon(":/icons/send"));
}
GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this);
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// Coin Control
connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked()));
connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int)));
connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &)));
// Coin Control: clipboard actions
QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);
QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this);
QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount()));
connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee()));
connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee()));
connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes()));
connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput()));
connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
// init transaction fee section
QSettings settings;
if (!settings.contains("fFeeSectionMinimized"))
settings.setValue("fFeeSectionMinimized", true);
if (!settings.contains("nFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility
settings.setValue("nFeeRadio", 1); // custom
if (!settings.contains("nFeeRadio"))
settings.setValue("nFeeRadio", 0); // recommended
if (!settings.contains("nSmartFeeSliderPosition"))
settings.setValue("nSmartFeeSliderPosition", 0);
if (!settings.contains("nTransactionFee"))
settings.setValue("nTransactionFee", (qint64)DEFAULT_TRANSACTION_FEE);
if (!settings.contains("fPayOnlyMinFee"))
settings.setValue("fPayOnlyMinFee", false);
ui->groupFee->setId(ui->radioSmartFee, 0);
ui->groupFee->setId(ui->radioCustomFee, 1);
ui->groupFee->button((int)std::max(0, std::min(1, settings.value("nFeeRadio").toInt())))->setChecked(true);
ui->customFee->setValue(settings.value("nTransactionFee").toLongLong());
ui->checkBoxMinimumFee->setChecked(settings.value("fPayOnlyMinFee").toBool());
minimizeFeeSection(settings.value("fFeeSectionMinimized").toBool());
}
void SendCoinsDialog::setClientModel(ClientModel *_clientModel)
{
this->clientModel = _clientModel;
if (_clientModel) {
connect(_clientModel, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(updateSmartFeeLabel()));
}
}
void SendCoinsDialog::setModel(WalletModel *_model)
{
this->model = _model;
if(_model && _model->getOptionsModel())
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(_model);
}
}
setBalance(_model->getBalance(), _model->getUnconfirmedBalance(), _model->getImmatureBalance(),
_model->getWatchBalance(), _model->getWatchUnconfirmedBalance(), _model->getWatchImmatureBalance());
connect(_model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)));
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
updateDisplayUnit();
// Coin Control
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels()));
connect(_model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool)));
ui->frameCoinControl->setVisible(_model->getOptionsModel()->getCoinControlFeatures());
coinControlUpdateLabels();
// fee section
for (const int n : confTargets) {
ui->confTargetSelector->addItem(tr("%1 (%2 blocks)").arg(GUIUtil::formatNiceTimeOffset(n*Params().GetConsensus().nPowTargetSpacing)).arg(n));
}
connect(ui->confTargetSelector, SIGNAL(currentIndexChanged(int)), this, SLOT(updateSmartFeeLabel()));
connect(ui->confTargetSelector, SIGNAL(currentIndexChanged(int)), this, SLOT(coinControlUpdateLabels()));
connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(updateFeeSectionControls()));
connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(coinControlUpdateLabels()));
connect(ui->customFee, SIGNAL(valueChanged()), this, SLOT(coinControlUpdateLabels()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(setMinimumFee()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateFeeSectionControls()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels()));
// Thor: Disable RBF
// connect(ui->optInRBF, SIGNAL(stateChanged(int)), this, SLOT(updateSmartFeeLabel()));
// connect(ui->optInRBF, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels()));
ui->customFee->setSingleStep(GetRequiredFee(1000));
updateFeeSectionControls();
updateMinFeeLabel();
updateSmartFeeLabel();
// set default rbf checkbox state
// Thor: Disable RBF
// ui->optInRBF->setCheckState(Qt::Checked);
// set the smartfee-sliders default value (wallets default conf.target or last stored value)
QSettings settings;
if (settings.value("nSmartFeeSliderPosition").toInt() != 0) {
// migrate nSmartFeeSliderPosition to nConfTarget
// nConfTarget is available since 0.15 (replaced nSmartFeeSliderPosition)
int nConfirmTarget = 25 - settings.value("nSmartFeeSliderPosition").toInt(); // 25 == old slider range
settings.setValue("nConfTarget", nConfirmTarget);
settings.remove("nSmartFeeSliderPosition");
}
if (settings.value("nConfTarget").toInt() == 0)
ui->confTargetSelector->setCurrentIndex(getIndexForConfTarget(model->getDefaultConfirmTarget()));
else
ui->confTargetSelector->setCurrentIndex(getIndexForConfTarget(settings.value("nConfTarget").toInt()));
}
}
SendCoinsDialog::~SendCoinsDialog()
{
QSettings settings;
settings.setValue("fFeeSectionMinimized", fFeeMinimized);
settings.setValue("nFeeRadio", ui->groupFee->checkedId());
settings.setValue("nConfTarget", getConfTargetForIndex(ui->confTargetSelector->currentIndex()));
settings.setValue("nTransactionFee", (qint64)ui->customFee->value());
settings.setValue("fPayOnlyMinFee", ui->checkBoxMinimumFee->isChecked());
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
if(!model || !model->getOptionsModel())
return;
QList<SendCoinsRecipient> recipients;
bool valid = true;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
{
recipients.append(entry->getValue());
}
else
{
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
fNewRecipientAllowed = false;
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
// prepare transaction for getting txFee earlier
WalletModelTransaction currentTransaction(recipients);
WalletModel::SendCoinsReturn prepareStatus;
// Always use a CCoinControl instance, use the CoinControlDialog instance if CoinControl has hammern enabled
CCoinControl ctrl;
if (model->getOptionsModel()->getCoinControlFeatures())
ctrl = *CoinControlDialog::coinControl();
updateCoinControlState(ctrl);
prepareStatus = model->prepareTransaction(currentTransaction, ctrl);
// process prepareStatus and on error generate message shown to user
processSendCoinsReturn(prepareStatus,
BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee()));
if(prepareStatus.status != WalletModel::OK) {
fNewRecipientAllowed = true;
return;
}
CAmount txFee = currentTransaction.getTransactionFee();
// Format confirmation message
QStringList formatted;
for (const SendCoinsRecipient &rcp : currentTransaction.getRecipients())
{
// generate bold amount string
QString amount = "<b>" + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount);
amount.append("</b>");
// generate monospace address string
QString address = "<span style='font-family: monospace;'>" + rcp.address;
address.append("</span>");
QString recipientElement;
if (!rcp.paymentRequest.IsInitialized()) // normal payment
{
if(rcp.label.length() > 0) // label with address
{
recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.label));
recipientElement.append(QString(" (%1)").arg(address));
}
else // just address
{
recipientElement = tr("%1 to %2").arg(amount, address);
}
}
else if(!rcp.authenticatedMerchant.isEmpty()) // authenticated payment request
{
recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.authenticatedMerchant));
}
else // unauthenticated payment request
{
recipientElement = tr("%1 to %2").arg(amount, address);
}
formatted.append(recipientElement);
}
QString questionString = tr("Are you sure you want to send?");
questionString.append("<br /><br />%1");
if(txFee > 0)
{
// append fee string if a fee is required
questionString.append("<hr /><span style='color:#aa0000;'>");
questionString.append(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), txFee));
questionString.append("</span> ");
questionString.append(tr("added as transaction fee"));
// append transaction size
questionString.append(" (" + QString::number((double)currentTransaction.getTransactionSize() / 1000) + " kB)");
}
// add total amount in all subdivision units
questionString.append("<hr />");
CAmount totalAmount = currentTransaction.getTotalTransactionAmount() + txFee;
QStringList alternativeUnits;
for (BitcoinUnits::Unit u : BitcoinUnits::availableUnits())
{
if(u != model->getOptionsModel()->getDisplayUnit())
alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount));
}
questionString.append(tr("Total Amount %1")
.arg(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), totalAmount)));
questionString.append(QString("<span style='font-size:10pt;font-weight:normal;'><br />(=%1)</span>")
.arg(alternativeUnits.join(" " + tr("or") + "<br />")));
/* Thor: Disable RBF
questionString.append("<hr /><span>");
if (ui->optInRBF->isChecked()) {
questionString.append(tr("You can increase the fee later (signals Replace-By-Fee, BIP-125)."));
} else {
questionString.append(tr("Not signalling Replace-By-Fee, BIP-125."));
}
questionString.append("</span>");
*/
SendConfirmationDialog confirmationDialog(tr("Confirm send coins"),
questionString.arg(formatted.join("<br />")), SEND_CONFIRM_DELAY, this);
confirmationDialog.exec();
QMessageBox::StandardButton retval = (QMessageBox::StandardButton)confirmationDialog.result();
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
// now send the prepared transaction
WalletModel::SendCoinsReturn sendStatus = model->sendCoins(currentTransaction);
// process sendStatus and on error generate message shown to user
processSendCoinsReturn(sendStatus);
if (sendStatus.status == WalletModel::OK)
{
accept();
CoinControlDialog::coinControl()->UnSelectAll();
coinControlUpdateLabels();
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
{
ui->entries->takeAt(0)->widget()->deleteLater();
}
addEntry();
updateTabsAndLabels();
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry *SendCoinsDialog::addEntry()
{
SendCoinsEntry *entry = new SendCoinsEntry(platformStyle, this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
connect(entry, SIGNAL(useAvailableBalance(SendCoinsEntry*)), this, SLOT(useAvailableBalance(SendCoinsEntry*)));
connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels()));
connect(entry, SIGNAL(subtractFeeFromAmountChanged()), this, SLOT(coinControlUpdateLabels()));
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
qApp->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
updateTabsAndLabels();
return entry;
}
void SendCoinsDialog::updateTabsAndLabels()
{
setupTabChain(0);
coinControlUpdateLabels();
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
entry->hide();
// If the last entry is about to be removed add an empty one
if (ui->entries->count() == 1)
addEntry();
entry->deleteLater();
updateTabsAndLabels();
}
QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->sendButton);
QWidget::setTabOrder(ui->sendButton, ui->clearButton);
QWidget::setTabOrder(ui->clearButton, ui->addButton);
return ui->addButton;
}
void SendCoinsDialog::setAddress(const QString &address)
{
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setAddress(address);
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
updateTabsAndLabels();
}
bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient &rv)
{
// Just paste the entry, all pre-checks
// are done in paymentserver.cpp.
pasteEntry(rv);
return true;
}
void SendCoinsDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance,
const CAmount& watchBalance, const CAmount& watchUnconfirmedBalance, const CAmount& watchImmatureBalance)
{
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
Q_UNUSED(watchBalance);
Q_UNUSED(watchUnconfirmedBalance);
Q_UNUSED(watchImmatureBalance);
if(model && model->getOptionsModel())
{
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), balance));
}
}
void SendCoinsDialog::updateDisplayUnit()
{
setBalance(model->getBalance(), 0, 0, 0, 0, 0);
ui->customFee->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
updateMinFeeLabel();
updateSmartFeeLabel();
}
void SendCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn &sendCoinsReturn, const QString &msgArg)
{
QPair<QString, CClientUIInterface::MessageBoxFlags> msgParams;
// Default to a warning message, override if error message is needed
msgParams.second = CClientUIInterface::MSG_WARNING;
// This comment is specific to SendCoinsDialog usage of WalletModel::SendCoinsReturn.
// WalletModel::TransactionCommitFailed is used only in WalletModel::sendCoins()
// all others are used only in WalletModel::prepareTransaction()
switch(sendCoinsReturn.status)
{
case WalletModel::InvalidAddress:
msgParams.first = tr("The recipient address is not valid. Please recheck.");
break;
case WalletModel::InvalidAmount:
msgParams.first = tr("The amount to pay must be larger than 0.");
break;
case WalletModel::AmountExceedsBalance:
msgParams.first = tr("The amount exceeds your balance.");
break;
case WalletModel::AmountWithFeeExceedsBalance:
msgParams.first = tr("The total exceeds your balance when the %1 transaction fee is included.").arg(msgArg);
break;
case WalletModel::DuplicateAddress:
msgParams.first = tr("Duplicate address found: addresses should only be used once each.");
break;
case WalletModel::TransactionCreationFailed:
msgParams.first = tr("Transaction creation failed!");
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
case WalletModel::TransactionCommitFailed:
msgParams.first = tr("The transaction was rejected with the following reason: %1").arg(sendCoinsReturn.reasonCommitFailed);
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
case WalletModel::AbsurdFee:
msgParams.first = tr("A fee higher than %1 is considered an absurdly high fee.").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), maxTxFee));
break;
case WalletModel::PaymentRequestDestroyed:
msgParams.first = tr("Payment request destroyed.");
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
// included to prevent a compiler warning.
case WalletModel::OK:
default:
return;
}
Q_EMIT message(tr("Send Coins"), msgParams.first, msgParams.second);
}
void SendCoinsDialog::minimizeFeeSection(bool fMinimize)
{
ui->labelFeeMinimized->setVisible(fMinimize);
ui->buttonChooseFee ->setVisible(fMinimize);
ui->buttonMinimizeFee->setVisible(!fMinimize);
ui->frameFeeSelection->setVisible(!fMinimize);
ui->horizontalLayoutSmartFee->setContentsMargins(0, (fMinimize ? 0 : 6), 0, 0);
fFeeMinimized = fMinimize;
}
void SendCoinsDialog::on_buttonChooseFee_clicked()
{
minimizeFeeSection(false);
}
void SendCoinsDialog::on_buttonMinimizeFee_clicked()
{
updateFeeMinimizedLabel();
minimizeFeeSection(true);
}
void SendCoinsDialog::useAvailableBalance(SendCoinsEntry* entry)
{
// Get CCoinControl instance if CoinControl is enabled or create a new one.
CCoinControl coin_control;
if (model->getOptionsModel()->getCoinControlFeatures()) {
coin_control = *CoinControlDialog::coinControl();
}
// Calculate available amount to send.
CAmount amount = model->getBalance(&coin_control);
for (int i = 0; i < ui->entries->count(); ++i) {
SendCoinsEntry* e = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if (e && !e->isHidden() && e != entry) {
amount -= e->getValue().amount;
}
}
if (amount > 0) {
entry->checkSubtractFeeFromAmount();
entry->setAmount(amount);
} else {
entry->setAmount(0);
}
}
void SendCoinsDialog::setMinimumFee()
{
ui->customFee->setValue(GetRequiredFee(1000));
}
void SendCoinsDialog::updateFeeSectionControls()
{
ui->confTargetSelector ->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFee ->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFee2 ->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFee3 ->setEnabled(ui->radioSmartFee->isChecked());
ui->labelFeeEstimation ->setEnabled(ui->radioSmartFee->isChecked());
ui->checkBoxMinimumFee ->setEnabled(ui->radioCustomFee->isChecked());
ui->labelMinFeeWarning ->setEnabled(ui->radioCustomFee->isChecked());
ui->labelCustomPerKilobyte ->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked());
ui->customFee ->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked());
}
void SendCoinsDialog::updateFeeMinimizedLabel()
{
if(!model || !model->getOptionsModel())
return;
if (ui->radioSmartFee->isChecked())
ui->labelFeeMinimized->setText(ui->labelSmartFee->text());
else {
ui->labelFeeMinimized->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ui->customFee->value()) + "/kB");
}
}
void SendCoinsDialog::updateMinFeeLabel()
{
if (model && model->getOptionsModel())
ui->checkBoxMinimumFee->setText(tr("Pay only the required fee of %1").arg(
BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), GetRequiredFee(1000)) + "/kB")
);
}
void SendCoinsDialog::updateCoinControlState(CCoinControl& ctrl)
{
if (ui->radioCustomFee->isChecked()) {
ctrl.m_feerate = CFeeRate(ui->customFee->value());
} else {
ctrl.m_feerate.reset();
}
// Avoid using global defaults when sending money from the GUI
// Either custom fee will be used or if not selected, the confirmation target from dropdown box
ctrl.m_confirm_target = getConfTargetForIndex(ui->confTargetSelector->currentIndex());
// Thor: Disabled RBF UI
//ctrl.signalRbf = ui->optInRBF->isChecked();
}
void SendCoinsDialog::updateSmartFeeLabel()
{
if(!model || !model->getOptionsModel())
return;
CCoinControl coin_control;
updateCoinControlState(coin_control);
coin_control.m_feerate.reset(); // Explicitly use only fee estimation rate for smart fee labels
FeeCalculation feeCalc;
CFeeRate feeRate = CFeeRate(GetMinimumFee(1000, coin_control, ::mempool, ::feeEstimator, &feeCalc));
ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB");
if (feeCalc.reason == FeeReason::FALLBACK) {
ui->labelSmartFee2->show(); // (Smart fee not initialized yet. This usually takes a few blocks...)
ui->labelFeeEstimation->setText("");
ui->fallbackFeeWarningLabel->setVisible(true);
int lightness = ui->fallbackFeeWarningLabel->palette().color(QPalette::WindowText).lightness();
QColor warning_colour(255 - (lightness / 5), 176 - (lightness / 3), 48 - (lightness / 14));
ui->fallbackFeeWarningLabel->setStyleSheet("QLabel { color: " + warning_colour.name() + "; }");
ui->fallbackFeeWarningLabel->setIndent(QFontMetrics(ui->fallbackFeeWarningLabel->font()).width("x"));
}
else
{
ui->labelSmartFee2->hide();
ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", feeCalc.returnedTarget));
ui->fallbackFeeWarningLabel->setVisible(false);
}
updateFeeMinimizedLabel();
}
// Coin Control: copy label "Quantity" to clipboard
void SendCoinsDialog::coinControlClipboardQuantity()
{
GUIUtil::setClipboard(ui->labelCoinControlQuantity->text());
}
// Coin Control: copy label "Amount" to clipboard
void SendCoinsDialog::coinControlClipboardAmount()
{
GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// Coin Control: copy label "Fee" to clipboard
void SendCoinsDialog::coinControlClipboardFee()
{
GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// Coin Control: copy label "After fee" to clipboard
void SendCoinsDialog::coinControlClipboardAfterFee()
{
GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// Coin Control: copy label "Bytes" to clipboard
void SendCoinsDialog::coinControlClipboardBytes()
{
GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace(ASYMP_UTF8, ""));
}
// Coin Control: copy label "Dust" to clipboard
void SendCoinsDialog::coinControlClipboardLowOutput()
{
GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text());
}
// Coin Control: copy label "Change" to clipboard
void SendCoinsDialog::coinControlClipboardChange()
{
GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// Coin Control: settings menu - coin control enabled/disabled by user
void SendCoinsDialog::coinControlFeatureChanged(bool checked)
{
ui->frameCoinControl->setVisible(checked);
if (!checked && model) // coin control features disabled
CoinControlDialog::coinControl()->SetNull();
coinControlUpdateLabels();
}
// Coin Control: button inputs -> show actual coin control dialog
void SendCoinsDialog::coinControlButtonClicked()
{
CoinControlDialog dlg(platformStyle);
dlg.setModel(model);
dlg.exec();
coinControlUpdateLabels();
}
// Coin Control: checkbox custom change address
void SendCoinsDialog::coinControlChangeChecked(int state)
{
if (state == Qt::Unchecked)
{
CoinControlDialog::coinControl()->destChange = CNoDestination();
ui->labelCoinControlChangeLabel->clear();
}
else
// use this to re-validate an already entered address
coinControlChangeEdited(ui->lineEditCoinControlChange->text());
ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked));
}
// Coin Control: custom change address changed
void SendCoinsDialog::coinControlChangeEdited(const QString& text)
{
if (model && model->getAddressTableModel())
{
// Default to no change address until verified
CoinControlDialog::coinControl()->destChange = CNoDestination();
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}");
const CTxDestination dest = DecodeDestination(text.toStdString());
if (text.isEmpty()) // Nothing entered
{
ui->labelCoinControlChangeLabel->setText("");
}
else if (!IsValidDestination(dest)) // Invalid address
{
ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid Thor address"));
}
else // Valid address
{
if (!model->IsSpendable(dest)) {
ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address"));
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm custom change address"), tr("The address you selected for change is not part of this wallet. Any or all funds in your wallet may be sent to this address. Are you sure?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if(btnRetVal == QMessageBox::Yes)
CoinControlDialog::coinControl()->destChange = dest;
else
{
ui->lineEditCoinControlChange->setText("");
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}");
ui->labelCoinControlChangeLabel->setText("");
}
}
else // Known change address
{
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}");
// Query label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(text);
if (!associatedLabel.isEmpty())
ui->labelCoinControlChangeLabel->setText(associatedLabel);
else
ui->labelCoinControlChangeLabel->setText(tr("(no label)"));
CoinControlDialog::coinControl()->destChange = dest;
}
}
}
}
// Coin Control: update labels
void SendCoinsDialog::coinControlUpdateLabels()
{
if (!model || !model->getOptionsModel())
return;
updateCoinControlState(*CoinControlDialog::coinControl());
// set pay amounts
CoinControlDialog::payAmounts.clear();
CoinControlDialog::fSubtractFeeFromAmount = false;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry && !entry->isHidden())
{
SendCoinsRecipient rcp = entry->getValue();
CoinControlDialog::payAmounts.append(rcp.amount);
if (rcp.fSubtractFeeFromAmount)
CoinControlDialog::fSubtractFeeFromAmount = true;
}
}
if (CoinControlDialog::coinControl()->HasSelected())
{
// actual coin control calculation
CoinControlDialog::updateLabels(model, this);
// show coin control stats
ui->labelCoinControlAutomaticallySelected->hide();
ui->widgetCoinControl->show();
}
else
{
// hide coin control stats
ui->labelCoinControlAutomaticallySelected->show();
ui->widgetCoinControl->hide();
ui->labelCoinControlInsuffFunds->hide();
}
}
SendConfirmationDialog::SendConfirmationDialog(const QString &title, const QString &text, int _secDelay,
QWidget *parent) :
QMessageBox(QMessageBox::Question, title, text, QMessageBox::Yes | QMessageBox::Cancel, parent), secDelay(_secDelay)
{
setDefaultButton(QMessageBox::Cancel);
yesButton = button(QMessageBox::Yes);
updateYesButton();
connect(&countDownTimer, SIGNAL(timeout()), this, SLOT(countDown()));
}
int SendConfirmationDialog::exec()
{
updateYesButton();
countDownTimer.start(1000);
return QMessageBox::exec();
}
void SendConfirmationDialog::countDown()
{
secDelay--;
updateYesButton();
if(secDelay <= 0)
{
countDownTimer.stop();
}
}
void SendConfirmationDialog::updateYesButton()
{
if(secDelay > 0)
{
yesButton->setEnabled(false);
yesButton->setText(tr("Yes") + " (" + QString::number(secDelay) + ")");
}
else
{
yesButton->setEnabled(true);
yesButton->setText(tr("Yes"));
}
}
| [
"antoinebrulenew@gmail.com"
] | antoinebrulenew@gmail.com |
6f17c6b5f24d51bc2676dae2c0cd7cd8757c00b8 | 792e697ba0f9c11ef10b7de81edb1161a5580cfb | /tools/clang/test/CodeGen/temporary-lifetime.cpp | af1907cb99158dc8b691c438dffcf8bfc60441f6 | [
"Apache-2.0",
"LLVM-exception",
"NCSA"
] | permissive | opencor/llvmclang | 9eb76cb6529b6a3aab2e6cd266ef9751b644f753 | 63b45a7928f2a8ff823db51648102ea4822b74a6 | refs/heads/master | 2023-08-26T04:52:56.472505 | 2022-11-02T04:35:46 | 2022-11-03T03:55:06 | 115,094,625 | 0 | 1 | Apache-2.0 | 2021-08-12T22:29:21 | 2017-12-22T08:29:14 | LLVM | UTF-8 | C++ | false | false | 6,262 | cpp | // RUN: %clang_cc1 -disable-noundef-analysis %s -std=c++11 -O1 -DWITH_DTOR -triple x86_64 -emit-llvm -o - | FileCheck -check-prefix=CHECK-DTOR %s
// RUN: %clang_cc1 -disable-noundef-analysis %s -std=c++11 -O1 -triple x86_64 -emit-llvm -o - | FileCheck -check-prefix=CHECK-NO-DTOR %s
struct A {
A();
#ifdef WITH_DTOR
~A();
#endif
char a[1024];
operator bool() const;
};
template <typename T>
void Foo(T &&);
template <typename T>
void Bar(T &&);
template <typename T>
T Baz();
void Test1() {
// CHECK-DTOR-LABEL: Test1
// CHECK-DTOR: call void @llvm.lifetime.start.p0i8(i64 1024, i8* nonnull %[[ADDR:[0-9]+]])
// CHECK-DTOR: call void @_ZN1AC1Ev(%struct.A* nonnull {{[^,]*}} %[[VAR:[^ ]+]])
// CHECK-DTOR: call void @_Z3FooIRK1AEvOT_
// CHECK-DTOR: call void @_ZN1AD1Ev(%struct.A* nonnull {{[^,]*}} %[[VAR]])
// CHECK-DTOR: call void @llvm.lifetime.end.p0i8(i64 1024, i8* nonnull %[[ADDR]])
// CHECK-DTOR: call void @llvm.lifetime.start.p0i8(i64 1024, i8* nonnull %[[ADDR:[0-9]+]])
// CHECK-DTOR: call void @_ZN1AC1Ev(%struct.A* nonnull {{[^,]*}} %[[VAR:[^ ]+]])
// CHECK-DTOR: call void @_Z3FooIRK1AEvOT_
// CHECK-DTOR: call void @_ZN1AD1Ev(%struct.A* nonnull {{[^,]*}} %[[VAR]])
// CHECK-DTOR: call void @llvm.lifetime.end.p0i8(i64 1024, i8* nonnull %[[ADDR]])
// CHECK-DTOR: }
// CHECK-NO-DTOR-LABEL: Test1
// CHECK-NO-DTOR: call void @llvm.lifetime.start.p0i8(i64 1024, i8* nonnull %[[ADDR:[0-9]+]])
// CHECK-NO-DTOR: call void @_ZN1AC1Ev(%struct.A* nonnull {{[^,]*}} %[[VAR:[^ ]+]])
// CHECK-NO-DTOR: call void @_Z3FooIRK1AEvOT_
// CHECK-NO-DTOR: call void @llvm.lifetime.end.p0i8(i64 1024, i8* nonnull %[[ADDR]])
// CHECK-NO-DTOR: call void @llvm.lifetime.start.p0i8(i64 1024, i8* nonnull %[[ADDR:[0-9]+]])
// CHECK-NO-DTOR: call void @_ZN1AC1Ev(%struct.A* nonnull {{[^,]*}} %[[VAR:[^ ]+]])
// CHECK-NO-DTOR: call void @_Z3FooIRK1AEvOT_
// CHECK-NO-DTOR: call void @llvm.lifetime.end.p0i8(i64 1024, i8* nonnull %[[ADDR]])
// CHECK-NO-DTOR: }
{
const A &a = A{};
Foo(a);
}
{
const A &a = A{};
Foo(a);
}
}
void Test2() {
// CHECK-DTOR-LABEL: Test2
// CHECK-DTOR: call void @llvm.lifetime.start.p0i8(i64 1024, i8* nonnull %[[ADDR1:[0-9]+]])
// CHECK-DTOR: call void @_ZN1AC1Ev(%struct.A* nonnull {{[^,]*}} %[[VAR1:[^ ]+]])
// CHECK-DTOR: call void @_Z3FooIRK1AEvOT_
// CHECK-DTOR: call void @llvm.lifetime.start.p0i8(i64 1024, i8* nonnull %[[ADDR2:[0-9]+]])
// CHECK-DTOR: call void @_ZN1AC1Ev(%struct.A* nonnull {{[^,]*}} %[[VAR2:[^ ]+]])
// CHECK-DTOR: call void @_Z3FooIRK1AEvOT_
// CHECK-DTOR: call void @_ZN1AD1Ev(%struct.A* nonnull {{[^,]*}} %[[VAR2]])
// CHECK-DTOR: call void @llvm.lifetime.end.p0i8(i64 1024, i8* nonnull %[[ADDR2]])
// CHECK-DTOR: call void @_ZN1AD1Ev(%struct.A* nonnull {{[^,]*}} %[[VAR1]])
// CHECK-DTOR: call void @llvm.lifetime.end.p0i8(i64 1024, i8* nonnull %[[ADDR1]])
// CHECK-DTOR: }
// CHECK-NO-DTOR-LABEL: Test2
// CHECK-NO-DTOR: call void @llvm.lifetime.start.p0i8(i64 1024, i8* nonnull %[[ADDR1:[0-9]+]])
// CHECK-NO-DTOR: call void @_ZN1AC1Ev(%struct.A* nonnull {{[^,]*}} %[[VAR1:[^ ]+]])
// CHECK-NO-DTOR: call void @_Z3FooIRK1AEvOT_
// CHECK-NO-DTOR: call void @llvm.lifetime.start.p0i8(i64 1024, i8* nonnull %[[ADDR2:[0-9]+]])
// CHECK-NO-DTOR: call void @_ZN1AC1Ev(%struct.A* nonnull {{[^,]*}} %[[VAR2:[^ ]+]])
// CHECK-NO-DTOR: call void @_Z3FooIRK1AEvOT_
// CHECK-NO-DTOR: call void @llvm.lifetime.end.p0i8(i64 1024, i8* nonnull %[[ADDR2]])
// CHECK-NO-DTOR: call void @llvm.lifetime.end.p0i8(i64 1024, i8* nonnull %[[ADDR1]])
// CHECK-NO-DTOR: }
const A &a = A{};
Foo(a);
const A &b = A{};
Foo(b);
}
void Test3() {
// CHECK-DTOR-LABEL: Test3
// CHECK-DTOR: call void @llvm.lifetime.start
// CHECK-DTOR: call void @llvm.lifetime.start
// if.then:
// CHECK-DTOR: call void @llvm.lifetime.end
// cleanup:
// CHECK-DTOR: call void @llvm.lifetime.end
// cleanup:
// CHECK-DTOR: call void @llvm.lifetime.end
// CHECK-DTOR: }
const A &a = A{};
if (const A &b = A(a)) {
Foo(b);
return;
}
Bar(a);
}
void Test4() {
// CHECK-DTOR-LABEL: Test4
// CHECK-DTOR: call void @llvm.lifetime.start
// for.cond.cleanup:
// CHECK-DTOR: call void @llvm.lifetime.end
// for.body:
// CHECK-DTOR: }
for (const A &a = A{}; a;) {
Foo(a);
}
}
int Test5() {
// CHECK-DTOR-LABEL: Test5
// CHECK-DTOR: call void @llvm.lifetime.start
// CHECK-DTOR: call i32 @_Z3BazIiET_v()
// CHECK-DTOR: store
// CHECK-DTOR: call void @_Z3FooIRKiEvOT_
// CHECK-DTOR: load
// CHECK-DTOR: call void @llvm.lifetime.end
// CHECK-DTOR: }
const int &a = Baz<int>();
Foo(a);
return a;
}
void Test6() {
// CHECK-DTOR-LABEL: Test6
// CHECK-DTOR: call void @llvm.lifetime.start.p0i8(i64 {{[0-9]+}}, i8* nonnull %[[ADDR:[0-9]+]])
// CHECK-DTOR: call i32 @_Z3BazIiET_v()
// CHECK-DTOR: store
// CHECK-DTOR: call void @_Z3FooIiEvOT_
// CHECK-DTOR: call void @llvm.lifetime.end.p0i8(i64 {{[0-9]+}}, i8* nonnull %[[ADDR]])
// CHECK-DTOR: call void @llvm.lifetime.start.p0i8(i64 {{[0-9]+}}, i8* nonnull %[[ADDR:[0-9]+]])
// CHECK-DTOR: call i32 @_Z3BazIiET_v()
// CHECK-DTOR: store
// CHECK-DTOR: call void @_Z3FooIiEvOT_
// CHECK-DTOR: call void @llvm.lifetime.end.p0i8(i64 {{[0-9]+}}, i8* nonnull %[[ADDR]])
// CHECK-DTOR: }
Foo(Baz<int>());
Foo(Baz<int>());
}
void Test7() {
// CHECK-DTOR-LABEL: Test7
// CHECK-DTOR: call void @llvm.lifetime.start.p0i8(i64 1024, i8* nonnull %[[ADDR:[0-9]+]])
// CHECK-DTOR: call void @_Z3BazI1AET_v({{.*}} %[[SLOT:[^ ]+]])
// CHECK-DTOR: call void @_Z3FooI1AEvOT_({{.*}} %[[SLOT]])
// CHECK-DTOR: call void @_ZN1AD1Ev(%struct.A* nonnull {{[^,]*}} %[[SLOT]])
// CHECK-DTOR: call void @llvm.lifetime.end.p0i8(i64 1024, i8* nonnull %[[ADDR]])
// CHECK-DTOR: call void @llvm.lifetime.start.p0i8(i64 1024, i8* nonnull %[[ADDR:[0-9]+]])
// CHECK-DTOR: call void @_Z3BazI1AET_v({{.*}} %[[SLOT:[^ ]+]])
// CHECK-DTOR: call void @_Z3FooI1AEvOT_({{.*}} %[[SLOT]])
// CHECK-DTOR: call void @_ZN1AD1Ev(%struct.A* nonnull {{[^,]*}} %[[SLOT]])
// CHECK-DTOR: call void @llvm.lifetime.end.p0i8(i64 1024, i8* nonnull %[[ADDR]])
// CHECK-DTOR: }
Foo(Baz<A>());
Foo(Baz<A>());
}
| [
"agarny@hellix.com"
] | agarny@hellix.com |
5c075fd54d136b145d6fac45fcba3612f098d37b | b7f1b4df5d350e0edf55521172091c81f02f639e | /chrome/services/media_gallery_util/media_gallery_util_service.cc | ce3c337ab58cec5e331f3c743c933e19215883e6 | [
"BSD-3-Clause"
] | permissive | blusno1/chromium-1 | f13b84547474da4d2702341228167328d8cd3083 | 9dd22fe142b48f14765a36f69344ed4dbc289eb3 | refs/heads/master | 2023-05-17T23:50:16.605396 | 2018-01-12T19:39:49 | 2018-01-12T19:39:49 | 117,339,342 | 4 | 2 | NOASSERTION | 2020-07-17T07:35:37 | 2018-01-13T11:48:57 | null | UTF-8 | C++ | false | false | 1,526 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/services/media_gallery_util/media_gallery_util_service.h"
#include "build/build_config.h"
#include "chrome/services/media_gallery_util/media_parser.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
namespace {
void OnMediaParserRequest(
service_manager::ServiceContextRefFactory* ref_factory,
chrome::mojom::MediaParserRequest request) {
mojo::MakeStrongBinding(
std::make_unique<MediaParser>(ref_factory->CreateRef()),
std::move(request));
}
} // namespace
MediaGalleryUtilService::MediaGalleryUtilService() = default;
MediaGalleryUtilService::~MediaGalleryUtilService() = default;
std::unique_ptr<service_manager::Service>
MediaGalleryUtilService::CreateService() {
return std::make_unique<MediaGalleryUtilService>();
}
void MediaGalleryUtilService::OnStart() {
ref_factory_ = std::make_unique<service_manager::ServiceContextRefFactory>(
base::Bind(&service_manager::ServiceContext::RequestQuit,
base::Unretained(context())));
registry_.AddInterface(base::Bind(&OnMediaParserRequest, ref_factory_.get()));
}
void MediaGalleryUtilService::OnBindInterface(
const service_manager::BindSourceInfo& source_info,
const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe) {
registry_.BindInterface(interface_name, std::move(interface_pipe));
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
e0215a98eb838cdf62f2c8d092dc032bbd8fe1f5 | 68931b5729575ee9cd236f33fa9b604867aff705 | /code/cli/buffer.cpp | 924fa22cd08e2098a35a5106e5f45ee61d87c59f | [] | no_license | zorggn/zcdt | fc7d9d0fc898234c365b26c7551f7458b0fac9d7 | dad9e4abd1640a11992ad1877b3ce4cd14adb86a | refs/heads/master | 2016-08-07T09:38:04.382254 | 2012-11-14T19:10:58 | 2012-11-14T19:10:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,645 | cpp | //implementation of the Atom buffer
#include "buffer.h";
//constructor: allocates length Atoms for a buffer
Buffer::Buffer(uint length) {
this.length = length;
this.index = 0;
this.buffer = new (nothrow) Atom[this.length];
if (this.buffer == 0)
{
cerr << "Error: Cannot allocate memory block length " << this.length << " for buffer." << endl;
//call Exit() or implement a try-catch block in the routines calling this and propagate an exception to those?
}
else
{
cout << "Created buffer; length of " << this.length << "Atoms." << endl; //only if one of the -w flags are checked; which? that's a todo.
}
}
//destructor: deletes the buffer
Buffer::~Buffer() {
delete[] this.buffer;
}
//return the Atom from the list specified by the internal index
Atom Buffer::getAtom() {
return this.buffer[this.index];
}
//return an Atom from the list specified by index
Atom Buffer::getAtom(uint index) {
return this.buffer[index % this.length];
}
//set the current element at index as atom
void Buffer::setAtom(Atom* atom) {
this.buffer[this.index] = atom;
}
// get the length of the buffer
void Buffer::getLength() {
return length;
}
//set the length of the buffer
void Buffer:setLength(uint length) {
//check if the new and current lengths are the same or not
if (this.length != length)
{
Buffer temp = Buffer(length);
Buffer::swapBuffers(this,temp);
temp.~Buffer(); //necessary? good practice?
}
}
// get the current index of the buffer
uint Buffer::getIndex() {
return this.index;
}
// set the index to an integer (bounds-checked)
void Buffer::setIndex(uint index) {
this.index = index % this.length;
} | [
"zorg@atw.hu"
] | zorg@atw.hu |
a0d880b2b88fd407f1e2d54855d71d6a3c1f6d42 | a7c4aca213a2a6450b37609d395a887c6a96e049 | /monsterbreaker/Classes/DoubleBrick.cpp | 4224b875b951715336c35d3fa43108b6f42bf472 | [] | no_license | ilhaeYe/MB | ba6172fbde53d1ca03b11e2243b6f4c797df29a7 | 9d4d6e9aa8fdfb6205ba5a6ebca7b6ec8f24e9e5 | refs/heads/master | 2020-12-25T17:56:14.480060 | 2018-07-15T20:45:27 | 2018-07-15T20:45:27 | 38,498,603 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,024 | cpp | #include "DoubleBrick.h"
USING_NS_CC;
DoubleBrick::DoubleBrick(const char * mapType, cocos2d::Layer * layer, int brickTypeID) : Brick(mapType, brickTypeID)
{
this->layer = layer;
b = false;
}
DoubleBrick::~DoubleBrick()
{
}
DoubleBrick* DoubleBrick::create(const char * mapType, cocos2d::Layer * layer, int brickTypeID)
{
auto pSprite = new DoubleBrick(mapType, layer, brickTypeID);
SpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Block/Block.plist", "Block/Block.png");
if (pSprite->initWithSpriteFrameName(String::createWithFormat("Block/Block%s2.png", mapType, brickTypeID)->getCString()))
{
pSprite->autorelease();
pSprite->InitSprite();
return pSprite;
}
CC_SAFE_DELETE(pSprite);
return NULL;
}
void DoubleBrick::DestroyBlock()
{
if (!b)
{
b = true;
auto sBrick = SingleBrick::create(getMapType().c_str(), BRICK_SINGLE_ID);
sBrick->setPosition(this->getPosition());
layer->addChild(sBrick, ZINDEX_BRICK_SPRITE, myEnum::kMyTag::kBlockTag);
Brick::DestroyBlock();
}
}
| [
"yeaih89@gmail.com"
] | yeaih89@gmail.com |
0a536f4a3bfc55e0c17a548a6ab2d8d5154d9d58 | 045ad86b79d87f501cfd8252ecd8cc3c1ac960dd | /DCPS/Discovery/DiscoveryController.h | 77f11d2d82087eda2ff65b81875905e064de65b3 | [
"MIT"
] | permissive | intact-software-systems/cpp-software-patterns | 9513e4d988342d88c100e4d85a0e58a3dbd9909e | e463fc7eeba4946b365b5f0b2eecf3da0f4c895b | refs/heads/master | 2020-04-08T08:22:25.073672 | 2018-11-26T14:19:49 | 2018-11-26T14:19:49 | 159,176,259 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,569 | h | #ifndef DCPS_Discovery_DiscoveryController_h_IsIncluded
#define DCPS_Discovery_DiscoveryController_h_IsIncluded
#include"DCPS/CommonDefines.h"
#include"DCPS/Discovery/EndpointDiscoveryController.h"
#include"DCPS/Discovery/ParticipantDiscoveryController.h"
#include"DCPS/Export.h"
namespace DCPS { namespace Discovery
{
/**
* @brief The DiscoveryControllerState class
*/
class DLL_STATE DiscoveryControllerState
{
public:
DiscoveryControllerState();
virtual ~DiscoveryControllerState();
ParticipantDiscoveryController *ParticipantDiscovery() const;
EndpointDiscoveryController *EndpointDiscovery() const;
private:
ParticipantDiscoveryController *participantDiscovery_;
EndpointDiscoveryController *endpointDiscovery_;
};
/**
* @brief The DiscoveryController class
*
* TODO:
* - Define topics:
* - TopicBuiltinTopicData with data needed to establish pub/sub, see RTPS specification
* - TODO: Rename, already a class Policy::TopicBuiltinTopicData
* - DCPSParticipant,
* - PublicationBuiltinTopicData,
* - DCPSSubscription,
*
* TODO:
* - DiscoveryController is an observer to the data-reader, data-writer, topic and participant caches/objectmanagers.
* - For every creation add a dds topic data instance to discovery cache writer.
*
* - DiscoveryController for all domains
* - Keep a map of domainId and Pair(ParticipantDiscovery, EndpointDiscovery)
*
* - DiscoveryController for each domain, in which case I need a DiscoveryFactory
* - Keep one ParticipantDiscovery and one EndpointDiscovery
*
* TODO Refactor:
* - Move the discovery topics to a different module DCPSShared
*
* - DomainParticipantFactory writes to cache DomainParticipantAccess containing all domains and participants
*
* - Two approaches to link to RTPS:
* - 1. Create a separate module DCPSShared and move topics and QoS to it, let DCPS and RTPS link it
* - 2. Create an "interceptor" that serializes the topics before adding it to a new cache, which RTPS HistoryCache listens to.
*
* - 2 is the preferred choice for now. This makes it identical to all other topic handling (from DCPS point of view). Use a cache-writer approach.
*/
class DLL_STATE DiscoveryController
: public Templates::ContextData<DiscoveryControllerState>
, public RxData::ObjectObserver<Domain::DomainParticipantPtr>
, public Runnable
, public Templates::Lockable<Mutex>
{
private:
DiscoveryController();
virtual ~DiscoveryController();
friend class Singleton<DiscoveryController>;
public:
static DiscoveryController& Instance();
void ObserveDomainCaches(DDS::Elements::DomainId domainId);
private:
/**
* @brief run
*/
virtual void run();
public:
virtual bool OnObjectCreated(Domain::DomainParticipantPtr data);
virtual bool OnObjectDeleted(Domain::DomainParticipantPtr data);
virtual bool OnObjectModified(Domain::DomainParticipantPtr data);
private:
void addDomainCacheObservers(const DDS::Elements::DomainId &domainId);
void removeDomainCacheObservers(const DDS::Elements::DomainId &domainId);
private:
static Singleton<DiscoveryController> discoveryController_;
//private:
// BaseLib::Concurrent::ObserverConnector<RxData::CacheObserver, Cache> cacheObserverConnector_;
};
//template <typename T>
//class DCPSObjectManager : public RxData::ObjectObserver<T>
//{
//public:
// virtual bool OnObjectCreated(T data);
// virtual bool OnObjectDeleted(T data);
// virtual bool OnObjectModified(T data);
//};
}}
#endif
| [
"intact.software.systems@gmail.com"
] | intact.software.systems@gmail.com |
c8e1a4b43eb56a31287e5dcdc569f1237db0fd5d | eaf717be88ef3c0186b2a765ff4ad68610cbe270 | /File.cpp | 95df7e7b357b0d6b8d769da314d2b279cf639602 | [
"MIT"
] | permissive | MMagueta/BackupSystem | a417a2ed45376c95daa8df9f4f6ab1c83684c391 | f9116a3ed46fcc47396e868e75df533a5589442a | refs/heads/master | 2020-04-04T22:12:52.347574 | 2018-11-10T16:07:16 | 2018-11-10T16:07:16 | 156,314,721 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 360 | cpp | #include "File.h"
File::File(std::string path){
stat(path.c_str() , &this->Stat);
int div = this->Stat.st_size/BLOCO;
int block_1 = 0;
int block_2 = BLOCO;
for(int i = 0; i <= div; i++){
this->Blocks.push_back(std::vector<int>{block_1, block_2});
this->Flags.push_back(false);
block_1 += BLOCO;
block_2 += BLOCO;
}
this->Path = path;
}
| [
"maguetamarcos@gmail.com"
] | maguetamarcos@gmail.com |
efc5fb1eb3497eed78d59a2db8c748df2a85ae33 | 52ca17dca8c628bbabb0f04504332c8fdac8e7ea | /rocksdb-3.10/util/murmurhash.cc | b4563f7957235bb510cedcfcaaf0dc643e081605 | [
"BSD-3-Clause"
] | permissive | qinzuoyan/thirdparty | f610d43fe57133c832579e65ca46e71f1454f5c4 | bba9e68347ad0dbffb6fa350948672babc0fcb50 | refs/heads/master | 2021-01-16T17:47:57.121882 | 2015-04-21T06:59:19 | 2015-04-21T06:59:19 | 33,612,579 | 0 | 0 | null | 2015-04-08T14:39:51 | 2015-04-08T14:39:51 | null | UTF-8 | C++ | false | false | 4,067 | cc | // Copyright (c) 2013, 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.
//
/*
Murmurhash from http://sites.google.com/site/murmurhash/
All code is released to the public domain. For business purposes, Murmurhash is
under the MIT license.
*/
#include "thirdparty/rocksdb-3.10/util/murmurhash.h"
#if defined(__x86_64__)
// -------------------------------------------------------------------
//
// The same caveats as 32-bit MurmurHash2 apply here - beware of alignment
// and endian-ness issues if used across multiple platforms.
//
// 64-bit hash for 64-bit platforms
uint64_t MurmurHash64A ( const void * key, int len, unsigned int seed )
{
const uint64_t m = 0xc6a4a7935bd1e995;
const int r = 47;
uint64_t h = seed ^ (len * m);
const uint64_t * data = (const uint64_t *)key;
const uint64_t * end = data + (len/8);
while(data != end)
{
uint64_t k = *data++;
k *= m;
k ^= k >> r;
k *= m;
h ^= k;
h *= m;
}
const unsigned char * data2 = (const unsigned char*)data;
switch(len & 7)
{
case 7: h ^= ((uint64_t)data2[6]) << 48;
case 6: h ^= ((uint64_t)data2[5]) << 40;
case 5: h ^= ((uint64_t)data2[4]) << 32;
case 4: h ^= ((uint64_t)data2[3]) << 24;
case 3: h ^= ((uint64_t)data2[2]) << 16;
case 2: h ^= ((uint64_t)data2[1]) << 8;
case 1: h ^= ((uint64_t)data2[0]);
h *= m;
};
h ^= h >> r;
h *= m;
h ^= h >> r;
return h;
}
#elif defined(__i386__)
// -------------------------------------------------------------------
//
// Note - This code makes a few assumptions about how your machine behaves -
//
// 1. We can read a 4-byte value from any address without crashing
// 2. sizeof(int) == 4
//
// And it has a few limitations -
//
// 1. It will not work incrementally.
// 2. It will not produce the same results on little-endian and big-endian
// machines.
unsigned int MurmurHash2 ( const void * key, int len, unsigned int seed )
{
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
const unsigned int m = 0x5bd1e995;
const int r = 24;
// Initialize the hash to a 'random' value
unsigned int h = seed ^ len;
// Mix 4 bytes at a time into the hash
const unsigned char * data = (const unsigned char *)key;
while(len >= 4)
{
unsigned int k = *(unsigned int *)data;
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
data += 4;
len -= 4;
}
// Handle the last few bytes of the input array
switch(len)
{
case 3: h ^= data[2] << 16;
case 2: h ^= data[1] << 8;
case 1: h ^= data[0];
h *= m;
};
// Do a few final mixes of the hash to ensure the last few
// bytes are well-incorporated.
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return h;
}
#else
// -------------------------------------------------------------------
//
// Same as MurmurHash2, but endian- and alignment-neutral.
// Half the speed though, alas.
unsigned int MurmurHashNeutral2 ( const void * key, int len, unsigned int seed )
{
const unsigned int m = 0x5bd1e995;
const int r = 24;
unsigned int h = seed ^ len;
const unsigned char * data = (const unsigned char *)key;
while(len >= 4)
{
unsigned int k;
k = data[0];
k |= data[1] << 8;
k |= data[2] << 16;
k |= data[3] << 24;
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
data += 4;
len -= 4;
}
switch(len)
{
case 3: h ^= data[2] << 16;
case 2: h ^= data[1] << 8;
case 1: h ^= data[0];
h *= m;
};
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return h;
}
#endif
| [
"qinzuoyan@gmail.com"
] | qinzuoyan@gmail.com |
eacca4277594a975518cdc4b0e9098e07eb9be1e | 2b46f6f8143912a2992773f11f032eca5e794ddf | /3rdparty/stout/include/stout/os/windows/read.hpp | cb0abf70307f0dbba0b8f68e884df199b0359186 | [
"Apache-2.0",
"PSF-2.0",
"BSD-3-Clause",
"MIT",
"GPL-2.0-or-later",
"BSL-1.0",
"LicenseRef-scancode-protobuf",
"BSD-2-Clause"
] | permissive | cloudflare/mesos | 58fa931856afb2c7a6503d70e170f19736b3940e | e5358ed1c132923d5fa357d1e337e037d1f29c8a | refs/heads/master | 2023-08-13T04:14:31.024391 | 2016-06-07T01:05:15 | 2016-06-07T16:14:22 | 42,358,969 | 3 | 1 | Apache-2.0 | 2022-07-22T09:14:56 | 2015-09-12T14:02:06 | C++ | UTF-8 | C++ | false | false | 1,485 | hpp | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_OS_WINDOWS_READ_HPP__
#define __STOUT_OS_WINDOWS_READ_HPP__
#include <io.h>
#include <stout/result.hpp>
#include <stout/windows.hpp> // For order-dependent networking headers.
#include <stout/os/socket.hpp>
namespace os {
// Forward declaration for an OS-agnostic `read`.
inline Result<std::string> read(int fd, size_t size);
inline ssize_t read(int fd, void* data, size_t size)
{
if (net::is_socket(fd)) {
return ::recv(fd, (char*) data, size, 0);
}
return ::_read(fd, data, size);
}
inline ssize_t read(HANDLE handle, void* data, size_t size)
{
return ::os::read(
_open_osfhandle(reinterpret_cast<intptr_t>(handle), O_RDONLY),
data,
size);
}
inline Result<std::string> read(HANDLE handle, size_t size)
{
return ::os::read(
_open_osfhandle(reinterpret_cast<intptr_t>(handle), O_RDONLY),
size);
}
} // namespace os {
#endif // __STOUT_OS_WINDOWS_READ_HPP__
| [
"joris.van.remoortere@gmail.com"
] | joris.van.remoortere@gmail.com |
5c1fb0ce858062b6f984f7c6e59171610946aed7 | 53fa0759b46ff7493df721a874bd8ce6c2d6e3b8 | /catkin_ws/install/include/beginner_tutorials/AddTwoIntsRequest.h | 99dae067a0b12db6ee6e00e147aef6ab8750a8fc | [
"MIT"
] | permissive | allenwxf/ROS-TUTORIAL | 3367093da76f157be6b8516dc67ee6d90365c99f | 9dfee042ea90cf3d6a6ae7f7200aa0c8f1a6b000 | refs/heads/master | 2020-04-07T02:07:52.204874 | 2019-01-15T13:04:01 | 2019-01-15T13:04:01 | 157,964,901 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,417 | h | // Generated by gencpp from file beginner_tutorials/AddTwoIntsRequest.msg
// DO NOT EDIT!
#ifndef BEGINNER_TUTORIALS_MESSAGE_ADDTWOINTSREQUEST_H
#define BEGINNER_TUTORIALS_MESSAGE_ADDTWOINTSREQUEST_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace beginner_tutorials
{
template <class ContainerAllocator>
struct AddTwoIntsRequest_
{
typedef AddTwoIntsRequest_<ContainerAllocator> Type;
AddTwoIntsRequest_()
: a(0)
, b(0) {
}
AddTwoIntsRequest_(const ContainerAllocator& _alloc)
: a(0)
, b(0) {
(void)_alloc;
}
typedef int64_t _a_type;
_a_type a;
typedef int64_t _b_type;
_b_type b;
typedef boost::shared_ptr< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> const> ConstPtr;
}; // struct AddTwoIntsRequest_
typedef ::beginner_tutorials::AddTwoIntsRequest_<std::allocator<void> > AddTwoIntsRequest;
typedef boost::shared_ptr< ::beginner_tutorials::AddTwoIntsRequest > AddTwoIntsRequestPtr;
typedef boost::shared_ptr< ::beginner_tutorials::AddTwoIntsRequest const> AddTwoIntsRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace beginner_tutorials
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'beginner_tutorials': ['/home/wxf/Workspace/catkin_ws/src/beginner_tutorials/msg'], 'std_msgs': ['/opt/ros/lunar/share/std_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
{
static const char* value()
{
return "36d09b846be0b371c5f190354dd3153e";
}
static const char* value(const ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x36d09b846be0b371ULL;
static const uint64_t static_value2 = 0xc5f190354dd3153eULL;
};
template<class ContainerAllocator>
struct DataType< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
{
static const char* value()
{
return "beginner_tutorials/AddTwoIntsRequest";
}
static const char* value(const ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
{
static const char* value()
{
return "int64 a\n\
int64 b\n\
";
}
static const char* value(const ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.a);
stream.next(m.b);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct AddTwoIntsRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::beginner_tutorials::AddTwoIntsRequest_<ContainerAllocator>& v)
{
s << indent << "a: ";
Printer<int64_t>::stream(s, indent + " ", v.a);
s << indent << "b: ";
Printer<int64_t>::stream(s, indent + " ", v.b);
}
};
} // namespace message_operations
} // namespace ros
#endif // BEGINNER_TUTORIALS_MESSAGE_ADDTWOINTSREQUEST_H
| [
"wxf@hdp-test.com"
] | wxf@hdp-test.com |
a4dc085b41d0cda7aa949d23c5e6b5ce44b8c07a | 23819413de400fa78bb813e62950682e57bb4dc0 | /Rounds/Round-688/d.cpp | a665dc3c7142488e5b8e92cddca711834786cd11 | [] | no_license | Manzood/CodeForces | 56144f36d73cd35d2f8644235a1f1958b735f224 | 578ed25ac51921465062e4bbff168359093d6ab6 | refs/heads/master | 2023-08-31T16:09:55.279615 | 2023-08-20T13:42:49 | 2023-08-20T13:42:49 | 242,544,327 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,188 | cpp | #include "bits/stdc++.h"
using namespace std;
#define debug(x) cout << #x << " = " << x << endl;
int main() {
int t;
cin >> t;
while (t--) {
long long k;
scanf("%lld", &k);
if (k < 2) {
printf("-1\n");
continue;
}
k -= 2;
vector <int> b;
long long cur = 1;
for (int i = 0; i < 63 && cur <= k; i++) {
if (k & cur) b.push_back(1);
else b.push_back(0);
cur = cur << 1;
}
vector <int> ans;
ans.push_back(1);
// printf("Printing binary\n");
// for (auto x: b) {
// printf("%d ", x);
// }
// printf("\nDone\n");
for (int i = 1; i < (int)b.size(); i++) {
if (b[i] == 1) {
for (int j = 0; j < i-1; j++) {
ans.push_back(0);
}
ans.push_back(1);
}
}
if ((int)ans.size() > 2000) printf("-1\n");
else {
printf("%d\n", (int)ans.size());
for (auto x: ans) {
printf("%d ", x);
}
printf("\n");
}
}
}
| [
"manzood.naqvi@gmail.com"
] | manzood.naqvi@gmail.com |
9ee23ea1657d393e9d641eb83fce14b4ea544f55 | 3d4e859c1f15cc8a142026c9562a92ab4c28cf25 | /include/cppystruct/pack.h | e9fa462db61ab5be3515d78e19343c4c326ba421 | [] | no_license | houyawei-NO1/falldetection | cb99e8547e3cf29e300c24f75a049babb325e8aa | 362ee14a03e41846cb36b951b6ae7881802f6402 | refs/heads/main | 2023-07-04T22:44:07.855482 | 2021-08-25T10:22:10 | 2021-08-25T10:22:10 | 397,207,099 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,665 | h | #pragma once
#include <array>
#include "include/cppystruct/calcsize.h"
#include "include/cppystruct/data_view.h"
namespace pystruct {
template <typename Fmt, typename... Args>
constexpr auto pack(Fmt formatString, Args&&... args);
// Impl
namespace internal {
template <typename RepType>
constexpr int packElement(char* data, bool bigEndian, FormatType format, RepType elem)
{
if constexpr (std::is_same_v<RepType, std::string_view>) {
// Trim the string size to the repeat count specified in the format
elem = std::string_view(elem.data(), std::min(elem.size(), format.size));
} else {
(void)format; // Unreferenced if constexpr RepType != string_view
}
data_view<char> view(data, bigEndian);
data::store(view, elem);
return 0;
}
template <typename RepType, typename T>
constexpr RepType convert(const T& val)
{
// If T is char[], and RepType is string_view - construct directly with std::size(val)
// because std::string_view doesn't have a constructor taking a char(&)[]
if constexpr(std::is_array_v<T> && std::is_same_v<std::remove_extent_t<T>, char>
&& std::is_same_v<RepType, std::string_view>) {
return RepType(std::data(val), std::size(val));
} else {
return static_cast<RepType>(val);
}
}
template <typename Fmt, size_t... Items, typename... Args>
constexpr auto pack(std::index_sequence<Items...>, Args&&... args)
{
static_assert(sizeof...(args) == sizeof...(Items), "pack expected items for packing != sizeof...(args) passed");
constexpr auto formatMode = pystruct::getFormatMode(Fmt{});
using ArrayType = std::array<char, pystruct::calcsize(Fmt{})>;
ArrayType output{};
constexpr FormatType formats[] = { pystruct::getTypeOfItem<Items>(Fmt{})... };
using Types = std::tuple<typename pystruct::RepresentedType<
decltype(formatMode),
formats[Items].formatChar
> ...>;
// Convert args to a tuple of the represented types
Types t = std::make_tuple(convert<std::tuple_element_t<Items, Types>>(std::forward<Args>(args))...);
constexpr size_t offsets[] = { getBinaryOffset<Items>(Fmt{})... };
int _[] = { 0, packElement(output.data() + offsets[Items], formatMode.isBigEndian(), formats[Items], std::get<Items>(t))... };
(void)_; // _ is a dummy for pack expansion
return output;
}
} // namespace internal
template <typename Fmt, typename... Args>
constexpr auto pack(Fmt, Args&&... args)
{
constexpr size_t itemCount = countItems(Fmt{});
return internal::pack<Fmt>(std::make_index_sequence<itemCount>(), std::forward<Args>(args)...);
}
} // namespace pystruct
| [
"30817974+houyawei-NO1@users.noreply.github.com"
] | 30817974+houyawei-NO1@users.noreply.github.com |
1fce500be0a045485266b38e5a15ca4773cba23a | 4a8c93591269fba8e7f87ffacf2d1e18f049a682 | /Uva/10034.cpp | 636b95ff8cf160a68aab32acbf8b2040a5e79a20 | [] | no_license | Pooh1223/Online-Judge | fd3c237b21bd07396e841b4d077a997c51383d8a | afb208ccc5ecc6f3fa42693d190dc64e19195ff6 | refs/heads/master | 2020-07-25T19:28:30.163074 | 2020-06-29T15:15:32 | 2020-06-29T15:15:32 | 208,401,769 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | cpp | #include <bits/stdc++.h>
using namespace std;
double x[103];
double y[103];
vector<>
int main(){
cin.tie(0);
int t;
cin >> t;
while(t--){
int n;
cin >> n;
memset(x,0,sizeof(x));
memset(y,0,sizeof(y));
for(int i = 0;i < n;++i){
cin >> x[i] >> y[i];
}
}
return 0;
} | [
"leo891223@gmail.com"
] | leo891223@gmail.com |
1de7363d3fb3fa5c793c4a2112360599f723c900 | 948df734bc05a4b816160067597f749913859340 | /include/G2PField.hh | 0070f7ea4b4004029d9c3f30d10a0d5d1cda0c70 | [] | no_license | zhupengjia/g2prec | 92c8f69eb27c6f99adadd72e5faacd3e9aba3b94 | 8c7d41705e1a2017ff25b1f595b25a6da042a949 | refs/heads/master | 2021-01-23T16:29:57.546245 | 2014-12-19T20:30:24 | 2014-12-19T20:30:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,529 | hh | // -*- C++ -*-
/* class G2PField
* Generate field map for HallB magnets.
* Calculate field strength of a particular point from the field map using Lagrange polynomial interpolation, default is 2nd order.
*
* Field map may have an angle respect to the lab coordinates.
* Use SetEulerAngle() to set this angle and the program will rotate the field map to correct direction.
*/
// History:
// Mar 2013, C. Gu, First public version.
// Sep 2013, C. Gu, Put HallB field map into G2PField.
// Feb 2014, C. Gu, Modified for G2PRec.
//
#ifndef G2P_FIELD_H
#define G2P_FIELD_H
#include <vector>
#include "G2PAppBase.hh"
using namespace std;
class G2PField : public G2PAppBase {
public:
G2PField();
virtual ~G2PField();
virtual void GetField(const double* x, double* b);
protected:
virtual int Initialize();
virtual void Clear(Option_t* /*option*/ = "");
void SetRotationMatrix();
virtual int ReadMap();
virtual int CreateMap();
virtual int Interpolate(const double* x, double* b, int order);
void TransLab2Field(const double* x, double* xout);
void TransField2Lab(const double* b, double* bout);
virtual int Configure();
const char* fMapFile;
vector<vector<vector<double> > > fBField;
double fOrigin[3];
double fZMin, fZMax;
double fRMin, fRMax;
double fZStep, fRStep;
int nZ, nR;
bool fRotation;
double fEulerAngle[3];
double fRotationMatrix[2][3][3];
double fRatio;
private:
ClassDef(G2PField, 1)
};
#endif | [
"guchao.pku@gmail.com"
] | guchao.pku@gmail.com |
a7878c5924be11d6f4b9abdc6bbc71562afbfdc5 | bf569e5b23eb4799a540ff6765411c31ce1bccfa | /lab3/Constructor/Decorador herencia/Plantilla.h | 55cd51201c1b465cc8d56cd1040e4c33dbe98aa7 | [] | no_license | sebastianVUCR/LabsDiseno | af56f8efba3e474bb2f51e598d5debf5832b9b14 | 1da9651871b693bd7e64b26a7940ac8977c65c18 | refs/heads/master | 2022-11-13T06:25:49.128182 | 2020-07-14T06:11:24 | 2020-07-14T06:11:24 | 259,193,331 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 228 | h | #pragma once
#include "Valor.h"
template <class T>
class Plantilla : public Valor
{
public:
Plantilla() {}
virtual ~Plantilla() {}
virtual T getValor() = 0;
virtual void setValor(T valor) = 0;
protected:
private:
};
| [
"sebastian.vargas.99@gmail.com"
] | sebastian.vargas.99@gmail.com |
6d16a4019fdcdf96202a3a651409991cae6da7e0 | 21b3663aaae0f7c5ab8c2c9d523bf23bc3d013e8 | /sketch_nov20a/sketch_nov20a.ino | 2c7a34ef7462fe0b2271618b83a1564a3242626e | [] | no_license | patpending/Arduino | 394218fdcca010d18309902195f95fc281f1a85e | 62151686fd6862231227a44e5d3e0f9800779c9c | refs/heads/master | 2020-12-14T09:54:24.002089 | 2018-11-05T20:31:01 | 2018-11-05T20:31:01 | 95,476,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 186 | ino | void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.print("dsdasda");
delay(10000);
}
| [
"patrick.strobel@gmail.com"
] | patrick.strobel@gmail.com |
042b4bd35302dccf3366a32cc6f8ff5e347fad53 | 9100a962129d21f9f61a27339d9220d11130db55 | /playground/function/function.cpp | 452bc7afc38b4a0aac214e7691c79e3dd30fd176 | [
"MIT"
] | permissive | llHoYall/Cpp_Playground | 55aa03b1cd94542a4ca232839e8b792a610bf2bb | 3f50237c7530e31be571e67ad2a627d1f33bbf51 | refs/heads/master | 2020-03-28T15:57:28.759632 | 2019-06-27T03:36:17 | 2019-06-27T03:36:17 | 148,643,106 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 704 | cpp | /*******************************************************************************
* @brief Function in modern C++
* @author llHoYall <hoya128@gmail.com>
* @version v1.0
* @history
* 2018.12.23 Created.
******************************************************************************/
/* Include Headers -----------------------------------------------------------*/
#include <iostream>
#include "first-class_function.h"
#include "higher-order_function.h"
#include "pure_function.h"
#include "currying.h"
/* Main Routine --------------------------------------------------------------*/
auto main() -> int {
FirstClassFunction();
HigherOrderFunction();
PureFunction();
Currying();
return 0;
}
| [
"hoya128@gmail.com"
] | hoya128@gmail.com |
00863f99989db7d6a89c457fee03a35f601827d4 | 64e25c9d67db2ce4b5abe1a980a070fb59a2f938 | /clang/compute_sdk/docs/cmtutorial/linear_walker1.cpp | 305ce0ee96e9e6d7d92b5bc30b93f165e4ff5f85 | [
"NCSA",
"MIT"
] | permissive | intel/cm-compiler | 22d8b56baefc26d5576572f5aab6b3ecb3033300 | 9b2e628b788344088d8fcfd97d406db576f608af | refs/heads/cmc_monorepo_80 | 2023-08-28T13:09:41.523730 | 2023-08-04T23:23:23 | 2023-08-04T23:23:23 | 111,158,121 | 141 | 60 | null | 2023-05-01T21:17:30 | 2017-11-17T22:50:46 | C++ | UTF-8 | C++ | false | false | 10,249 | cpp | /*========================== begin_copyright_notice ============================
Copyright (C) 2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#include <string>
// The only CM runtime header file that you need is cm_rt.h.
// It includes all of the CM runtime.
#include "cm_rt.h"
#include "cm_loadprogram.h"
// Includes bitmap_helpers.h for bitmap file open/save/compare operations.
#include "common/bitmap_helpers.h"
// Include cm_rt_helpers.h to convert the integer return code returned from
// the CM runtime to a meaningful string message.
#include "common/cm_rt_helpers.h"
// Includes isa_helpers.h to load the ISA file generated by the CM compiler.
#include "common/isa_helpers.h"
int main(int argc, char* argv[]) {
// Loads an input image named "image_in.bmp".
auto input_image = cm::util::bitmap::BitMap::load("linear_in.bmp");
// Gets the width and height of the input image.
unsigned int width = input_image.getWidth();
unsigned int height = input_image.getHeight();
// Checks the value of width, height and bpp(bits per pixel) of the image.
// Only images in 8-bit RGB format are supported.
// Only images with width and height a multiple of 8 are supported.
if (width&7 || height&7 || input_image.getBPP() != 24) {
std::cerr << "Error: Only images in 8-bit RGB format with width and "
<< "height a multiple of 8 are supported.\n";
exit(1);
}
// Copies input image to output except for the data.
auto output_image = input_image;
// Sets image size in bytes. There are a total of width*height pixels and
// each pixel occupies (out.getBPP()/8) bytes.
unsigned int img_size = width*height*output_image.getBPP()/8;
// Sets output to blank image.
output_image.setData(new unsigned char[img_size]);
// Creates a CmDevice from scratch.
// Param device: pointer to the CmDevice object.
// Param version: CM API version supported by the runtime library.
CmDevice *device = nullptr;
unsigned int version = 0;
cm_result_check(::CreateCmDevice(device, version));
// The file linear_walker1_genx.isa is generated when the kernels in the file
// linear_walker1_genx.cpp are compiled by the CM compiler.
// Reads in the virtual ISA from "linear_walker1_genx.isa" to the code
// buffer.
std::string isa_code = cm::util::isa::loadFile("linear_walker1_genx.isa");
if (isa_code.size() == 0) {
std::cerr << "Error: empty ISA binary.\n";
exit(1);
}
// Creates a CmProgram object consisting of the kernels loaded from the code
// buffer.
// Param isa_code.data(): Pointer to the code buffer containing the virtual
// ISA.
// Param isa_code.size(): Size in bytes of the code buffer containing the
// virtual ISA.
CmProgram *program = nullptr;
cm_result_check(CmDevLoadProgram(device, const_cast<char*>(isa_code.data()),
isa_code.size(),
program));
// Creates the linear kernel.
// Param program: CM Program from which the kernel is created.
// Param "linear": The kernel name which should be no more than 256 bytes
// including the null terminator.
CmKernel *kernel = nullptr;
cm_result_check(device->CreateKernel(program,
"linear",
kernel));
// Creates input surface with given width and height in pixels and format.
// Sets surface format as CM_SURFACE_FORMAT_A8R8G8B8. For this format, each
// pixel occupies 32 bits.
// The input image is RGB format with 24 bits per pixel, and the surface
// format is A8R8G8B8 with 32 bits per pixel. Therefore, the surface width
// is (width*3/4) in pixels.
CmSurface2D *input_surface = nullptr;
cm_result_check(device->CreateSurface2D(width*3/4,
height,
CM_SURFACE_FORMAT_A8R8G8B8,
input_surface));
// Copies system memory content to the input surface using the CPU. The
// system memory content is the data of the input image. The size of data
// copied is the size of data in the surface.
cm_result_check(input_surface->WriteSurface(input_image.getData(), nullptr));
// Creates the output surface. The width, height and format is the same as
// the input surface.
CmSurface2D *output_surface = nullptr;
cm_result_check(device->CreateSurface2D(width*3/4,
height,
CM_SURFACE_FORMAT_A8R8G8B8,
output_surface));
// Each CmKernel can be executed by multiple concurrent threads.
// Here, for "linear" kernel, each thread works on a block of 6x8 pixels.
// The thread width is equal to input image width divided by 8.
// The thread height is equal to input image height divided by 6.
int thread_width = width/8;
int thread_height = height/6;
// Creates a CmThreadSpace object.
// There are two usage models for the thread space. One is to define the
// dependency between threads to run in the GPU. The other is to define a
// thread space where each thread can get a pair of coordinates during
// kernel execution. For this example, we use the latter usage model.
CmThreadSpace *thread_space = nullptr;
cm_result_check(device->CreateThreadSpace(thread_width,
thread_height,
thread_space));
// When a surface is created by the CmDevice a SurfaceIndex object is
// created. This object contains a unique index value that is mapped to the
// surface.
// Gets the input surface index.
SurfaceIndex *input_surface_idx = nullptr;
cm_result_check(input_surface->GetIndex(input_surface_idx));
// Sets a per kernel argument.
// Sets input surface index as the first argument of linear kernel.
cm_result_check(kernel->SetKernelArg(0,
sizeof(SurfaceIndex),
input_surface_idx));
// Gets the output surface index.
SurfaceIndex *output_surface_idx = nullptr;
cm_result_check(output_surface->GetIndex(output_surface_idx));
// Sets output surface index as the second argument of linear kernel.
cm_result_check(kernel->SetKernelArg(1,
sizeof(SurfaceIndex),
output_surface_idx));
// Creates a task queue.
// The CmQueue is an in-order queue. Tasks get executed according to the
// order they are enqueued. The next task does not start execution until the
// current task finishes.
CmQueue *cmd_queue = nullptr;
cm_result_check(device->CreateQueue(cmd_queue));
// Creates a CmTask object.
// The CmTask object is a container for CmKernel pointers. It is used to
// enqueue the kernels for execution.
CmTask *task = nullptr;
cm_result_check(device->CreateTask(task));
// Adds a CmKernel pointer to CmTask.
// This task has one kernel, "linear".
cm_result_check(task->AddKernel(kernel));
// Launches the task on the GPU. Enqueue is a non-blocking call, i.e. the
// function returns immediately without waiting for the GPU to start or
// finish execution of the task. The runtime will query the HW status. If
// the hardware is not busy, the runtime will submit the task to the
// driver/HW; otherwise, the runtime will submit the task to the driver/HW
// at another time.
// An event, "sync_event", is created to track the status of the task.
CmEvent *sync_event = nullptr;
cm_result_check(cmd_queue->Enqueue(task,
sync_event,
thread_space));
// Destroys a CmTask object.
// CmTask will be destroyed when CmDevice is destroyed.
// Here, the application destroys the CmTask object by itself.
cm_result_check(device->DestroyTask(task));
// Destroy a CmThreadSpace object.
// CmThreadSpace will be destroyed when CmDevice is destroyed.
// Here, the application destroys the CmThreadSpace object by itself.
cm_result_check(device->DestroyThreadSpace(thread_space));
// Reads the output surface content to the system memory using the CPU.
// The size of data copied is the size of data in Surface.
// It is a blocking call. The function will not return until the copy
// operation is completed.
// The dependent event "sync_event" ensures that the reading of the surface
// will not happen until its state becomes CM_STATUS_FINISHED.
cm_result_check(output_surface->ReadSurface(output_image.getData(),
sync_event));
// Queries the execution time of a task in the unit of nanoseconds.
// The execution time is measured from the time the task started execution
// in the GPU to the time when the task finished execution.
UINT64 execution_time = 0;
cm_result_check(sync_event->GetExecutionTime(execution_time));
std::cout << "Kernel linear execution time is " << execution_time
<< " nanoseconds" << std::endl;
// Destroys the CmEvent.
// CmEvent must be destroyed by the user explicitly.
cm_result_check(cmd_queue->DestroyEvent(sync_event));
// Destroys the CmDevice.
// Also destroys surfaces, kernels, tasks, thread spaces, and queues that
// were created using this device instance that have not explicitly been
// destroyed by calling the respective destroy functions.
cm_result_check(::DestroyCmDevice(device));
// Saves the output image data into the file "linear_out.bmp".
output_image.save("linear_out.bmp");
// Compares each pixel of output image with gold image. Set the tolerence of
// each pixel difference as 5. If the difference of all pixel is within this
// tolerance, the result is correct. Or else there is something wrong.
bool passed = cm::util::bitmap::BitMap::checkResult("linear_out.bmp",
"linear_gold_hw.bmp",
5);
std::cout << (passed ? "PASSED" : "FAILED") << std::endl;
return (passed ? 0 : -1);
}
| [
"konstantin.vladimirov@intel.com"
] | konstantin.vladimirov@intel.com |
72fb7e9b743de162b4cd127f5d02d1755fbed4cf | eab87b164a2e44e23df9935dcb1563a00f8f0221 | /QController/comcpp/src/qqmlreadonlypropertymap.cpp | 7578b5317f20142928d33f472b64c8eeb0f7f4cb | [] | no_license | BMValeev/science | 6f140171c330fe535bdf5a8111757b8e384fb155 | 9f9bae33764bfc3afad96ab397f27525c25e1b28 | refs/heads/master | 2021-07-03T22:54:27.055596 | 2020-09-02T15:26:41 | 2020-09-02T15:26:41 | 161,135,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 313 | cpp | #include "qqmlreadonlypropertymap.h"
QQmlReadonlyPropertyMap::QQmlReadonlyPropertyMap(QObject *parent)
: QQmlPropertyMap(this, parent)
{ }
QVariant QQmlReadonlyPropertyMap::updateValue(const QString &key, const QVariant &input)
{
// Prevent updates from QML
Q_UNUSED(input)
return value(key);
}
| [
"you@example.com"
] | you@example.com |
2071be5f20b72ff9959f49c579b2295dca33e77c | 0342fe0e71b63481ffa104eb0f2d127409021bae | /export/mac64/cpp/obj/src/flixel/group/FlxTypedSpriteGroup.cpp | 0ac67c69b8c112438e392644b8b0cec507e6e639 | [] | no_license | azlen/LD36 | a063027afe49a219eb0a3711e12a3a9f553bc410 | 2b800e01ee491631974a6abd28a12f5019cb430a | refs/heads/master | 2020-12-02T17:10:09.618613 | 2016-08-29T02:02:00 | 2016-08-29T02:02:00 | 66,799,278 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | true | 99,378 | cpp | // Generated by Haxe 3.3.0
#include <hxcpp.h>
#include "hxMath.h"
#ifndef INCLUDED_flixel_FlxBasic
#include <flixel/FlxBasic.h>
#endif
#ifndef INCLUDED_flixel_FlxCamera
#include <flixel/FlxCamera.h>
#endif
#ifndef INCLUDED_flixel_FlxObject
#include <flixel/FlxObject.h>
#endif
#ifndef INCLUDED_flixel_FlxSprite
#include <flixel/FlxSprite.h>
#endif
#ifndef INCLUDED_flixel_graphics_frames_FlxFrame
#include <flixel/graphics/frames/FlxFrame.h>
#endif
#ifndef INCLUDED_flixel_graphics_frames_FlxFramesCollection
#include <flixel/graphics/frames/FlxFramesCollection.h>
#endif
#ifndef INCLUDED_flixel_group_FlxTypedGroup
#include <flixel/group/FlxTypedGroup.h>
#endif
#ifndef INCLUDED_flixel_group_FlxTypedGroupIterator
#include <flixel/group/FlxTypedGroupIterator.h>
#endif
#ifndef INCLUDED_flixel_group_FlxTypedSpriteGroup
#include <flixel/group/FlxTypedSpriteGroup.h>
#endif
#ifndef INCLUDED_flixel_math_FlxCallbackPoint
#include <flixel/math/FlxCallbackPoint.h>
#endif
#ifndef INCLUDED_flixel_math_FlxPoint
#include <flixel/math/FlxPoint.h>
#endif
#ifndef INCLUDED_flixel_util_FlxDestroyUtil
#include <flixel/util/FlxDestroyUtil.h>
#endif
#ifndef INCLUDED_flixel_util_FlxPool_flixel_math_FlxPoint
#include <flixel/util/FlxPool_flixel_math_FlxPoint.h>
#endif
#ifndef INCLUDED_flixel_util_IFlxDestroyable
#include <flixel/util/IFlxDestroyable.h>
#endif
#ifndef INCLUDED_flixel_util_IFlxPool
#include <flixel/util/IFlxPool.h>
#endif
#ifndef INCLUDED_flixel_util_IFlxPooled
#include <flixel/util/IFlxPooled.h>
#endif
#ifndef INCLUDED_openfl__legacy_display_BitmapData
#include <openfl/_legacy/display/BitmapData.h>
#endif
#ifndef INCLUDED_openfl__legacy_display_BlendMode
#include <openfl/_legacy/display/BlendMode.h>
#endif
#ifndef INCLUDED_openfl__legacy_display_IBitmapDrawable
#include <openfl/_legacy/display/IBitmapDrawable.h>
#endif
namespace flixel{
namespace group{
void FlxTypedSpriteGroup_obj::__construct(hx::Null< Float > __o_X,hx::Null< Float > __o_Y,hx::Null< Int > __o_MaxSize){
Float X = __o_X.Default(0);
Float Y = __o_Y.Default(0);
Int MaxSize = __o_MaxSize.Default(0);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","new",0x9fa77753,"flixel.group.FlxTypedSpriteGroup.new","flixel/group/FlxSpriteGroup.hx",26,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(X,"X")
HX_STACK_ARG(Y,"Y")
HX_STACK_ARG(MaxSize,"MaxSize")
HXLINE( 52) this->_skipTransformChildren = false;
HXLINE( 74) super::__construct(X,Y,null());
HXLINE( 75) this->group = ::flixel::group::FlxTypedGroup_obj::__new(MaxSize);
HXLINE( 76) this->_sprites = this->group->members;
}
Dynamic FlxTypedSpriteGroup_obj::__CreateEmpty() { return new FlxTypedSpriteGroup_obj; }
hx::ObjectPtr< FlxTypedSpriteGroup_obj > FlxTypedSpriteGroup_obj::__new(hx::Null< Float > __o_X,hx::Null< Float > __o_Y,hx::Null< Int > __o_MaxSize)
{
hx::ObjectPtr< FlxTypedSpriteGroup_obj > _hx_result = new FlxTypedSpriteGroup_obj();
_hx_result->__construct(__o_X,__o_Y,__o_MaxSize);
return _hx_result;
}
Dynamic FlxTypedSpriteGroup_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< FlxTypedSpriteGroup_obj > _hx_result = new FlxTypedSpriteGroup_obj();
_hx_result->__construct(inArgs[0],inArgs[1],inArgs[2]);
return _hx_result;
}
void FlxTypedSpriteGroup_obj::transformChildren_openfl__legacy_display_BlendMode( ::Dynamic Function,::hx::EnumBase Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","transformChildren_openfl__legacy_display_BlendMode",0x65952a52,"flixel.group.FlxTypedSpriteGroup.transformChildren_openfl__legacy_display_BlendMode","flixel/group/FlxSpriteGroup.hx",552,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Function,"Function")
HX_STACK_ARG(Value,"Value")
HXLINE( 553) Bool _hx_tmp = hx::IsNull( this->group );
HXDLIN( 553) if (_hx_tmp) {
HXLINE( 555) return;
}
HXLINE( 558) {
HXLINE( 558) HX_VARI( Int,_g) = (int)0;
HXDLIN( 558) HX_VARI( ::Array< ::Dynamic>,_g1) = this->_sprites;
HXDLIN( 558) while((_g < _g1->length)){
HXLINE( 558) HX_VARI( ::flixel::FlxSprite,sprite) = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >();
HXDLIN( 558) ++_g;
HXLINE( 560) Bool _hx_tmp1 = hx::IsNotNull( sprite );
HXDLIN( 560) if (_hx_tmp1) {
HXLINE( 562) Function(sprite,Value);
}
}
}
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,transformChildren_openfl__legacy_display_BlendMode,(void))
void FlxTypedSpriteGroup_obj::transformChildren_Int( ::Dynamic Function,Int Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","transformChildren_Int",0x8f3579ce,"flixel.group.FlxTypedSpriteGroup.transformChildren_Int","flixel/group/FlxSpriteGroup.hx",552,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Function,"Function")
HX_STACK_ARG(Value,"Value")
HXLINE( 553) Bool _hx_tmp = hx::IsNull( this->group );
HXDLIN( 553) if (_hx_tmp) {
HXLINE( 555) return;
}
HXLINE( 558) {
HXLINE( 558) HX_VARI( Int,_g) = (int)0;
HXDLIN( 558) HX_VARI( ::Array< ::Dynamic>,_g1) = this->_sprites;
HXDLIN( 558) while((_g < _g1->length)){
HXLINE( 558) HX_VARI( ::flixel::FlxSprite,sprite) = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >();
HXDLIN( 558) ++_g;
HXLINE( 560) Bool _hx_tmp1 = hx::IsNotNull( sprite );
HXDLIN( 560) if (_hx_tmp1) {
HXLINE( 562) Function(sprite,Value);
}
}
}
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,transformChildren_Int,(void))
void FlxTypedSpriteGroup_obj::transformChildren_Float( ::Dynamic Function,Float Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","transformChildren_Float",0x2758683b,"flixel.group.FlxTypedSpriteGroup.transformChildren_Float","flixel/group/FlxSpriteGroup.hx",552,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Function,"Function")
HX_STACK_ARG(Value,"Value")
HXLINE( 553) Bool _hx_tmp = hx::IsNull( this->group );
HXDLIN( 553) if (_hx_tmp) {
HXLINE( 555) return;
}
HXLINE( 558) {
HXLINE( 558) HX_VARI( Int,_g) = (int)0;
HXDLIN( 558) HX_VARI( ::Array< ::Dynamic>,_g1) = this->_sprites;
HXDLIN( 558) while((_g < _g1->length)){
HXLINE( 558) HX_VARI( ::flixel::FlxSprite,sprite) = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >();
HXDLIN( 558) ++_g;
HXLINE( 560) Bool _hx_tmp1 = hx::IsNotNull( sprite );
HXDLIN( 560) if (_hx_tmp1) {
HXLINE( 562) Function(sprite,Value);
}
}
}
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,transformChildren_Float,(void))
void FlxTypedSpriteGroup_obj::transformChildren_Bool( ::Dynamic Function,Bool Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","transformChildren_Bool",0xbaf55a6b,"flixel.group.FlxTypedSpriteGroup.transformChildren_Bool","flixel/group/FlxSpriteGroup.hx",552,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Function,"Function")
HX_STACK_ARG(Value,"Value")
HXLINE( 553) Bool _hx_tmp = hx::IsNull( this->group );
HXDLIN( 553) if (_hx_tmp) {
HXLINE( 555) return;
}
HXLINE( 558) {
HXLINE( 558) HX_VARI( Int,_g) = (int)0;
HXDLIN( 558) HX_VARI( ::Array< ::Dynamic>,_g1) = this->_sprites;
HXDLIN( 558) while((_g < _g1->length)){
HXLINE( 558) HX_VARI( ::flixel::FlxSprite,sprite) = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >();
HXDLIN( 558) ++_g;
HXLINE( 560) Bool _hx_tmp1 = hx::IsNotNull( sprite );
HXDLIN( 560) if (_hx_tmp1) {
HXLINE( 562) Function(sprite,Value);
}
}
}
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,transformChildren_Bool,(void))
void FlxTypedSpriteGroup_obj::transformChildren_Array_flixel_FlxCamera( ::Dynamic Function,::Array< ::Dynamic> Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","transformChildren_Array_flixel_FlxCamera",0x8df728db,"flixel.group.FlxTypedSpriteGroup.transformChildren_Array_flixel_FlxCamera","flixel/group/FlxSpriteGroup.hx",552,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Function,"Function")
HX_STACK_ARG(Value,"Value")
HXLINE( 553) Bool _hx_tmp = hx::IsNull( this->group );
HXDLIN( 553) if (_hx_tmp) {
HXLINE( 555) return;
}
HXLINE( 558) {
HXLINE( 558) HX_VARI( Int,_g) = (int)0;
HXDLIN( 558) HX_VARI( ::Array< ::Dynamic>,_g1) = this->_sprites;
HXDLIN( 558) while((_g < _g1->length)){
HXLINE( 558) HX_VARI( ::flixel::FlxSprite,sprite) = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >();
HXDLIN( 558) ++_g;
HXLINE( 560) Bool _hx_tmp1 = hx::IsNotNull( sprite );
HXDLIN( 560) if (_hx_tmp1) {
HXLINE( 562) Function(sprite,Value);
}
}
}
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,transformChildren_Array_flixel_FlxCamera,(void))
void FlxTypedSpriteGroup_obj::multiTransformChildren_Float(::Array< ::Dynamic> FunctionArray,::Array< Float > ValueArray){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","multiTransformChildren_Float",0x31c44efc,"flixel.group.FlxTypedSpriteGroup.multiTransformChildren_Float","flixel/group/FlxSpriteGroup.hx",575,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(FunctionArray,"FunctionArray")
HX_STACK_ARG(ValueArray,"ValueArray")
HXLINE( 576) Bool _hx_tmp = hx::IsNull( this->group );
HXDLIN( 576) if (_hx_tmp) {
HXLINE( 578) return;
}
HXLINE( 581) HX_VARI( Int,numProps) = FunctionArray->length;
HXLINE( 582) if ((numProps > ValueArray->length)) {
HXLINE( 584) return;
}
HXLINE( 587) HX_VAR( ::Dynamic,lambda);
HXLINE( 588) {
HXLINE( 588) HX_VARI( Int,_g) = (int)0;
HXDLIN( 588) HX_VARI( ::Array< ::Dynamic>,_g1) = this->_sprites;
HXDLIN( 588) while((_g < _g1->length)){
HXLINE( 588) HX_VARI( ::flixel::FlxSprite,sprite) = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >();
HXDLIN( 588) ++_g;
HXLINE( 590) Bool _hx_tmp1;
HXDLIN( 590) Bool _hx_tmp2 = hx::IsNotNull( sprite );
HXDLIN( 590) if (_hx_tmp2) {
HXLINE( 590) _hx_tmp1 = sprite->exists;
}
else {
HXLINE( 590) _hx_tmp1 = false;
}
HXDLIN( 590) if (_hx_tmp1) {
HXLINE( 592) HX_VARI( Int,_g3) = (int)0;
HXDLIN( 592) while((_g3 < numProps)){
HXLINE( 592) HX_VARI( Int,i) = _g3++;
HXLINE( 594) lambda = FunctionArray->__get(i);
HXLINE( 595) Float _hx_tmp3 = ValueArray->__get(i);
HXDLIN( 595) lambda(sprite,_hx_tmp3);
}
}
}
}
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,multiTransformChildren_Float,(void))
void FlxTypedSpriteGroup_obj::transformChildren_flixel_math_FlxPoint( ::Dynamic Function, ::flixel::math::FlxPoint Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","transformChildren_flixel_math_FlxPoint",0xcdc8d2f3,"flixel.group.FlxTypedSpriteGroup.transformChildren_flixel_math_FlxPoint","flixel/group/FlxSpriteGroup.hx",552,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Function,"Function")
HX_STACK_ARG(Value,"Value")
HXLINE( 553) Bool _hx_tmp = hx::IsNull( this->group );
HXDLIN( 553) if (_hx_tmp) {
HXLINE( 555) return;
}
HXLINE( 558) {
HXLINE( 558) HX_VARI( Int,_g) = (int)0;
HXDLIN( 558) HX_VARI( ::Array< ::Dynamic>,_g1) = this->_sprites;
HXDLIN( 558) while((_g < _g1->length)){
HXLINE( 558) HX_VARI( ::flixel::FlxSprite,sprite) = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >();
HXDLIN( 558) ++_g;
HXLINE( 560) Bool _hx_tmp1 = hx::IsNotNull( sprite );
HXDLIN( 560) if (_hx_tmp1) {
HXLINE( 562) Function(sprite,Value);
}
}
}
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,transformChildren_flixel_math_FlxPoint,(void))
void FlxTypedSpriteGroup_obj::initVars(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","initVars",0xad6ba309,"flixel.group.FlxTypedSpriteGroup.initVars","flixel/group/FlxSpriteGroup.hx",85,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 86) this->flixelType = (int)4;
HXLINE( 88) this->offset = ::flixel::math::FlxCallbackPoint_obj::__new(this->offsetCallback_dyn(),null(),null());
HXLINE( 89) this->origin = ::flixel::math::FlxCallbackPoint_obj::__new(this->originCallback_dyn(),null(),null());
HXLINE( 90) this->scale = ::flixel::math::FlxCallbackPoint_obj::__new(this->scaleCallback_dyn(),null(),null());
HXLINE( 91) this->scrollFactor = ::flixel::math::FlxCallbackPoint_obj::__new(this->scrollFactorCallback_dyn(),null(),null());
HXLINE( 93) this->scale->set((int)1,(int)1);
HXLINE( 94) this->scrollFactor->set((int)1,(int)1);
HXLINE( 96) {
HXLINE( 96) HX_VARI( ::flixel::math::FlxPoint,point) = ::flixel::math::FlxPoint_obj::_pool->get()->set((int)0,(int)0);
HXDLIN( 96) point->_inPool = false;
HXDLIN( 96) this->velocity = point;
HXDLIN( 96) HX_VARI_NAME( ::flixel::math::FlxPoint,point1,"point") = ::flixel::math::FlxPoint_obj::_pool->get()->set((int)0,(int)0);
HXDLIN( 96) point1->_inPool = false;
HXDLIN( 96) this->acceleration = point1;
HXDLIN( 96) HX_VARI_NAME( ::flixel::math::FlxPoint,point2,"point") = ::flixel::math::FlxPoint_obj::_pool->get()->set((int)0,(int)0);
HXDLIN( 96) point2->_inPool = false;
HXDLIN( 96) this->drag = point2;
HXDLIN( 96) HX_VARI_NAME( ::flixel::math::FlxPoint,point3,"point") = ::flixel::math::FlxPoint_obj::_pool->get()->set((int)10000,(int)10000);
HXDLIN( 96) point3->_inPool = false;
HXDLIN( 96) this->maxVelocity = point3;
}
}
void FlxTypedSpriteGroup_obj::destroy(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","destroy",0xd803c96d,"flixel.group.FlxTypedSpriteGroup.destroy","flixel/group/FlxSpriteGroup.hx",104,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 106) this->offset = ( ( ::flixel::math::FlxPoint)(::flixel::util::FlxDestroyUtil_obj::destroy(this->offset)) );
HXLINE( 107) this->origin = ( ( ::flixel::math::FlxPoint)(::flixel::util::FlxDestroyUtil_obj::destroy(this->origin)) );
HXLINE( 108) this->scale = ( ( ::flixel::math::FlxPoint)(::flixel::util::FlxDestroyUtil_obj::destroy(this->scale)) );
HXLINE( 109) this->scrollFactor = ( ( ::flixel::math::FlxPoint)(::flixel::util::FlxDestroyUtil_obj::destroy(this->scrollFactor)) );
HXLINE( 111) this->group = ( ( ::flixel::group::FlxTypedGroup)(::flixel::util::FlxDestroyUtil_obj::destroy(this->group)) );
HXLINE( 112) this->_sprites = null();
HXLINE( 114) this->super::destroy();
}
::flixel::FlxSprite FlxTypedSpriteGroup_obj::clone(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","clone",0x21249d10,"flixel.group.FlxTypedSpriteGroup.clone","flixel/group/FlxSpriteGroup.hx",122,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 123) HX_VARI( ::flixel::group::FlxTypedSpriteGroup,newGroup) = ::flixel::group::FlxTypedSpriteGroup_obj::__new(this->x,this->y,this->group->maxSize);
HXLINE( 124) {
HXLINE( 124) HX_VARI( Int,_g) = (int)0;
HXDLIN( 124) HX_VARI( ::cpp::VirtualArray,_g1) = this->group->members;
HXDLIN( 124) while((_g < _g1->get_length())){
HXLINE( 124) HX_VARI( ::Dynamic,sprite) = _g1->__get(_g);
HXDLIN( 124) ++_g;
HXLINE( 126) Bool _hx_tmp = hx::IsNotNull( sprite );
HXDLIN( 126) if (_hx_tmp) {
HXLINE( 128) newGroup->add(( ( ::flixel::FlxSprite)(sprite) )->clone());
}
}
}
HXLINE( 131) return newGroup;
}
Bool FlxTypedSpriteGroup_obj::isOnScreen( ::flixel::FlxCamera Camera){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","isOnScreen",0xe3a8b162,"flixel.group.FlxTypedSpriteGroup.isOnScreen","flixel/group/FlxSpriteGroup.hx",141,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Camera,"Camera")
HXLINE( 142) {
HXLINE( 142) HX_VARI( Int,_g) = (int)0;
HXDLIN( 142) HX_VARI( ::Array< ::Dynamic>,_g1) = this->_sprites;
HXDLIN( 142) while((_g < _g1->length)){
HXLINE( 142) HX_VARI( ::flixel::FlxSprite,sprite) = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >();
HXDLIN( 142) ++_g;
HXLINE( 144) Bool _hx_tmp;
HXDLIN( 144) Bool _hx_tmp1;
HXDLIN( 144) Bool _hx_tmp2;
HXDLIN( 144) Bool _hx_tmp3 = hx::IsNotNull( sprite );
HXDLIN( 144) if (_hx_tmp3) {
HXLINE( 144) _hx_tmp2 = sprite->exists;
}
else {
HXLINE( 144) _hx_tmp2 = false;
}
HXDLIN( 144) if (_hx_tmp2) {
HXLINE( 144) _hx_tmp1 = sprite->visible;
}
else {
HXLINE( 144) _hx_tmp1 = false;
}
HXDLIN( 144) if (_hx_tmp1) {
HXLINE( 144) _hx_tmp = sprite->isOnScreen(Camera);
}
else {
HXLINE( 144) _hx_tmp = false;
}
HXDLIN( 144) if (_hx_tmp) {
HXLINE( 146) return true;
}
}
}
HXLINE( 150) return false;
}
Bool FlxTypedSpriteGroup_obj::overlapsPoint( ::flixel::math::FlxPoint point,hx::Null< Bool > __o_InScreenSpace, ::flixel::FlxCamera Camera){
Bool InScreenSpace = __o_InScreenSpace.Default(false);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","overlapsPoint",0xe77cba57,"flixel.group.FlxTypedSpriteGroup.overlapsPoint","flixel/group/FlxSpriteGroup.hx",162,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(point,"point")
HX_STACK_ARG(InScreenSpace,"InScreenSpace")
HX_STACK_ARG(Camera,"Camera")
HXLINE( 163) HX_VARI( Bool,result) = false;
HXLINE( 164) {
HXLINE( 164) HX_VARI( Int,_g) = (int)0;
HXDLIN( 164) HX_VARI( ::Array< ::Dynamic>,_g1) = this->_sprites;
HXDLIN( 164) while((_g < _g1->length)){
HXLINE( 164) HX_VARI( ::flixel::FlxSprite,sprite) = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >();
HXDLIN( 164) ++_g;
HXLINE( 166) Bool _hx_tmp;
HXDLIN( 166) Bool _hx_tmp1;
HXDLIN( 166) Bool _hx_tmp2 = hx::IsNotNull( sprite );
HXDLIN( 166) if (_hx_tmp2) {
HXLINE( 166) _hx_tmp1 = sprite->exists;
}
else {
HXLINE( 166) _hx_tmp1 = false;
}
HXDLIN( 166) if (_hx_tmp1) {
HXLINE( 166) _hx_tmp = sprite->visible;
}
else {
HXLINE( 166) _hx_tmp = false;
}
HXDLIN( 166) if (_hx_tmp) {
HXLINE( 168) if (!(result)) {
HXLINE( 168) result = sprite->overlapsPoint(point,InScreenSpace,Camera);
}
else {
HXLINE( 168) result = true;
}
}
}
}
HXLINE( 172) return result;
}
Bool FlxTypedSpriteGroup_obj::pixelsOverlapPoint( ::flixel::math::FlxPoint point,hx::Null< Int > __o_Mask, ::flixel::FlxCamera Camera){
Int Mask = __o_Mask.Default(255);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","pixelsOverlapPoint",0xc3b2a483,"flixel.group.FlxTypedSpriteGroup.pixelsOverlapPoint","flixel/group/FlxSpriteGroup.hx",185,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(point,"point")
HX_STACK_ARG(Mask,"Mask")
HX_STACK_ARG(Camera,"Camera")
HXLINE( 186) HX_VARI( Bool,result) = false;
HXLINE( 187) {
HXLINE( 187) HX_VARI( Int,_g) = (int)0;
HXDLIN( 187) HX_VARI( ::Array< ::Dynamic>,_g1) = this->_sprites;
HXDLIN( 187) while((_g < _g1->length)){
HXLINE( 187) HX_VARI( ::flixel::FlxSprite,sprite) = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >();
HXDLIN( 187) ++_g;
HXLINE( 189) Bool _hx_tmp;
HXDLIN( 189) Bool _hx_tmp1;
HXDLIN( 189) Bool _hx_tmp2 = hx::IsNotNull( sprite );
HXDLIN( 189) if (_hx_tmp2) {
HXLINE( 189) _hx_tmp1 = sprite->exists;
}
else {
HXLINE( 189) _hx_tmp1 = false;
}
HXDLIN( 189) if (_hx_tmp1) {
HXLINE( 189) _hx_tmp = sprite->visible;
}
else {
HXLINE( 189) _hx_tmp = false;
}
HXDLIN( 189) if (_hx_tmp) {
HXLINE( 191) if (!(result)) {
HXLINE( 191) result = sprite->pixelsOverlapPoint(point,Mask,Camera);
}
else {
HXLINE( 191) result = true;
}
}
}
}
HXLINE( 195) return result;
}
void FlxTypedSpriteGroup_obj::update(Float elapsed){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","update",0x579c78f6,"flixel.group.FlxTypedSpriteGroup.update","flixel/group/FlxSpriteGroup.hx",199,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(elapsed,"elapsed")
HXLINE( 200) this->group->update(elapsed);
HXLINE( 202) Bool _hx_tmp = this->moves;
HXDLIN( 202) if (_hx_tmp) {
HXLINE( 204) this->updateMotion(elapsed);
}
}
void FlxTypedSpriteGroup_obj::draw(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","draw",0x0c4e99b1,"flixel.group.FlxTypedSpriteGroup.draw","flixel/group/FlxSpriteGroup.hx",210,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 210) this->group->draw();
}
::Array< ::Dynamic> FlxTypedSpriteGroup_obj::replaceColor(Int _tmp_Color,Int _tmp_NewColor,hx::Null< Bool > __o_FetchPositions){
Bool FetchPositions = __o_FetchPositions.Default(false);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","replaceColor",0x6ca2bf3c,"flixel.group.FlxTypedSpriteGroup.replaceColor","flixel/group/FlxSpriteGroup.hx",225,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(_tmp_Color,"_tmp_Color")
HX_STACK_ARG(_tmp_NewColor,"_tmp_NewColor")
HX_STACK_ARG(FetchPositions,"FetchPositions")
HXLINE( 226) HX_VARI( Int,Color) = _tmp_Color;
HXDLIN( 226) HX_VARI( Int,NewColor) = _tmp_NewColor;
HXDLIN( 226) HX_VARI( ::Array< ::Dynamic>,positions) = null();
HXLINE( 227) if (FetchPositions) {
HXLINE( 229) positions = ::Array_obj< ::Dynamic>::__new();
}
HXLINE( 232) HX_VAR( ::Array< ::Dynamic>,spritePositions);
HXLINE( 233) {
HXLINE( 233) HX_VARI( Int,_g) = (int)0;
HXDLIN( 233) HX_VARI( ::Array< ::Dynamic>,_g1) = this->_sprites;
HXDLIN( 233) while((_g < _g1->length)){
HXLINE( 233) HX_VARI( ::flixel::FlxSprite,sprite) = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >();
HXDLIN( 233) ++_g;
HXLINE( 235) Bool _hx_tmp = hx::IsNotNull( sprite );
HXDLIN( 235) if (_hx_tmp) {
HXLINE( 237) spritePositions = sprite->replaceColor(Color,NewColor,FetchPositions);
HXLINE( 238) if (FetchPositions) {
HXLINE( 240) positions = positions->concat(spritePositions);
}
}
}
}
HXLINE( 245) return positions;
}
::Dynamic FlxTypedSpriteGroup_obj::add( ::Dynamic Sprite){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","add",0x9f9d9914,"flixel.group.FlxTypedSpriteGroup.add","flixel/group/FlxSpriteGroup.hx",255,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HXLINE( 256) HX_VARI( ::flixel::FlxSprite,sprite) = ( ( ::flixel::FlxSprite)(Sprite) );
HXLINE( 257) {
HXLINE( 257) Float _hx_tmp = (sprite->x + this->x);
HXDLIN( 257) sprite->set_x(_hx_tmp);
}
HXLINE( 258) {
HXLINE( 258) Float _hx_tmp1 = (sprite->y + this->y);
HXDLIN( 258) sprite->set_y(_hx_tmp1);
}
HXLINE( 259) {
HXLINE( 259) Float _hx_tmp2 = (sprite->alpha * this->alpha);
HXDLIN( 259) sprite->set_alpha(_hx_tmp2);
}
HXLINE( 260) {
HXLINE( 260) HX_VARI( ::flixel::math::FlxPoint,_this) = sprite->scrollFactor;
HXDLIN( 260) HX_VARI( ::flixel::math::FlxPoint,point) = this->scrollFactor;
HXDLIN( 260) _this->set_x(point->x);
HXDLIN( 260) _this->set_y(point->y);
HXDLIN( 260) Bool _hx_tmp3 = point->_weak;
HXDLIN( 260) if (_hx_tmp3) {
HXLINE( 260) point->put();
}
}
HXLINE( 261) sprite->set_cameras(this->_cameras);
HXLINE( 262) return this->group->add(Sprite);
}
HX_DEFINE_DYNAMIC_FUNC1(FlxTypedSpriteGroup_obj,add,return )
::Dynamic FlxTypedSpriteGroup_obj::recycle(hx::Class ObjectClass, ::Dynamic ObjectFactory,hx::Null< Bool > __o_Force){
Bool Force = __o_Force.Default(false);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","recycle",0xeb09ac86,"flixel.group.FlxTypedSpriteGroup.recycle","flixel/group/FlxSpriteGroup.hx",275,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(ObjectClass,"ObjectClass")
HX_STACK_ARG(ObjectFactory,"ObjectFactory")
HX_STACK_ARG(Force,"Force")
HXLINE( 275) return this->group->recycle(ObjectClass,ObjectFactory,Force,null());
}
HX_DEFINE_DYNAMIC_FUNC3(FlxTypedSpriteGroup_obj,recycle,return )
::Dynamic FlxTypedSpriteGroup_obj::remove( ::Dynamic Sprite,hx::Null< Bool > __o_Splice){
Bool Splice = __o_Splice.Default(false);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","remove",0xd51f8f31,"flixel.group.FlxTypedSpriteGroup.remove","flixel/group/FlxSpriteGroup.hx",286,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Splice,"Splice")
HXLINE( 287) HX_VARI( ::flixel::FlxSprite,sprite) = ( ( ::flixel::FlxSprite)(Sprite) );
HXLINE( 288) {
HXLINE( 288) Float _hx_tmp = (sprite->x - this->x);
HXDLIN( 288) sprite->set_x(_hx_tmp);
}
HXLINE( 289) {
HXLINE( 289) Float _hx_tmp1 = (sprite->y - this->y);
HXDLIN( 289) sprite->set_y(_hx_tmp1);
}
HXLINE( 291) sprite->set_cameras(null());
HXLINE( 292) return this->group->remove(Sprite,Splice);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,remove,return )
::Dynamic FlxTypedSpriteGroup_obj::replace( ::Dynamic OldObject, ::Dynamic NewObject){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","replace",0x5ea5e4a7,"flixel.group.FlxTypedSpriteGroup.replace","flixel/group/FlxSpriteGroup.hx",304,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(OldObject,"OldObject")
HX_STACK_ARG(NewObject,"NewObject")
HXLINE( 304) return this->group->replace(OldObject,NewObject);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,replace,return )
void FlxTypedSpriteGroup_obj::sort( ::Dynamic Function,hx::Null< Int > __o_Order){
HX_BEGIN_LOCAL_FUNC_S2(hx::LocalFunc,_hx_Closure_0, ::Dynamic,f,Int,a1) HXARGC(2)
Int _hx_run( ::Dynamic a2, ::Dynamic a3){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","sort",0x1636950b,"flixel.group.FlxTypedSpriteGroup.sort","flixel/group/FlxSpriteGroup.hx",316,0xeb1fa7f3)
HX_STACK_ARG(a2,"a2")
HX_STACK_ARG(a3,"a3")
HXLINE( 316) return ( (Int)(f(a1,a2,a3)) );
}
HX_END_LOCAL_FUNC2(return)
Int Order = __o_Order.Default(-1);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","sort",0x1636950b,"flixel.group.FlxTypedSpriteGroup.sort","flixel/group/FlxSpriteGroup.hx",316,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Function,"Function")
HX_STACK_ARG(Order,"Order")
HXLINE( 316) ::Dynamic f = Function;
HXDLIN( 316) Int a1 = Order;
HXDLIN( 316) ::Dynamic _hx_tmp = ::Dynamic(new _hx_Closure_0(f,a1));
HXDLIN( 316) this->group->members->sort(_hx_tmp);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,sort,(void))
::Dynamic FlxTypedSpriteGroup_obj::getFirstAvailable(hx::Class ObjectClass,hx::Null< Bool > __o_Force){
Bool Force = __o_Force.Default(false);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","getFirstAvailable",0x44b6b4e2,"flixel.group.FlxTypedSpriteGroup.getFirstAvailable","flixel/group/FlxSpriteGroup.hx",329,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(ObjectClass,"ObjectClass")
HX_STACK_ARG(Force,"Force")
HXLINE( 329) return this->group->getFirstAvailable(ObjectClass,Force);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,getFirstAvailable,return )
Int FlxTypedSpriteGroup_obj::getFirstNull(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","getFirstNull",0x3deb1a0e,"flixel.group.FlxTypedSpriteGroup.getFirstNull","flixel/group/FlxSpriteGroup.hx",340,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 340) return this->group->getFirstNull();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTypedSpriteGroup_obj,getFirstNull,return )
::Dynamic FlxTypedSpriteGroup_obj::getFirstExisting(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","getFirstExisting",0x25cf6192,"flixel.group.FlxTypedSpriteGroup.getFirstExisting","flixel/group/FlxSpriteGroup.hx",351,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 351) return this->group->getFirstExisting();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTypedSpriteGroup_obj,getFirstExisting,return )
::Dynamic FlxTypedSpriteGroup_obj::getFirstAlive(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","getFirstAlive",0x6da0fe66,"flixel.group.FlxTypedSpriteGroup.getFirstAlive","flixel/group/FlxSpriteGroup.hx",362,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 362) return this->group->getFirstAlive();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTypedSpriteGroup_obj,getFirstAlive,return )
::Dynamic FlxTypedSpriteGroup_obj::getFirstDead(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","getFirstDead",0x3742ca2b,"flixel.group.FlxTypedSpriteGroup.getFirstDead","flixel/group/FlxSpriteGroup.hx",373,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 373) return this->group->getFirstDead();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTypedSpriteGroup_obj,getFirstDead,return )
Int FlxTypedSpriteGroup_obj::countLiving(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","countLiving",0xa01b2b4b,"flixel.group.FlxTypedSpriteGroup.countLiving","flixel/group/FlxSpriteGroup.hx",383,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 383) return this->group->countLiving();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTypedSpriteGroup_obj,countLiving,return )
Int FlxTypedSpriteGroup_obj::countDead(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","countDead",0x17fab246,"flixel.group.FlxTypedSpriteGroup.countDead","flixel/group/FlxSpriteGroup.hx",393,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 393) return this->group->countDead();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTypedSpriteGroup_obj,countDead,return )
::Dynamic FlxTypedSpriteGroup_obj::getRandom(hx::Null< Int > __o_StartIndex,hx::Null< Int > __o_Length){
Int StartIndex = __o_StartIndex.Default(0);
Int Length = __o_Length.Default(0);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","getRandom",0xf7598a6c,"flixel.group.FlxTypedSpriteGroup.getRandom","flixel/group/FlxSpriteGroup.hx",405,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(StartIndex,"StartIndex")
HX_STACK_ARG(Length,"Length")
HXLINE( 405) return this->group->getRandom(StartIndex,Length);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,getRandom,return )
::flixel::group::FlxTypedGroupIterator FlxTypedSpriteGroup_obj::iterator( ::Dynamic filter){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","iterator",0xee05921b,"flixel.group.FlxTypedSpriteGroup.iterator","flixel/group/FlxSpriteGroup.hx",415,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(filter,"filter")
HXLINE( 415) return ::flixel::group::FlxTypedGroupIterator_obj::__new(this->group->members,filter);
}
HX_DEFINE_DYNAMIC_FUNC1(FlxTypedSpriteGroup_obj,iterator,return )
void FlxTypedSpriteGroup_obj::forEach( ::Dynamic Function,hx::Null< Bool > __o_Recurse){
Bool Recurse = __o_Recurse.Default(false);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","forEach",0x783bc61d,"flixel.group.FlxTypedSpriteGroup.forEach","flixel/group/FlxSpriteGroup.hx",426,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Function,"Function")
HX_STACK_ARG(Recurse,"Recurse")
HXLINE( 426) this->group->forEach(Function,Recurse);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,forEach,(void))
void FlxTypedSpriteGroup_obj::forEachAlive( ::Dynamic Function,hx::Null< Bool > __o_Recurse){
Bool Recurse = __o_Recurse.Default(false);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","forEachAlive",0xc86ec470,"flixel.group.FlxTypedSpriteGroup.forEachAlive","flixel/group/FlxSpriteGroup.hx",437,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Function,"Function")
HX_STACK_ARG(Recurse,"Recurse")
HXLINE( 437) this->group->forEachAlive(Function,Recurse);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,forEachAlive,(void))
void FlxTypedSpriteGroup_obj::forEachDead( ::Dynamic Function,hx::Null< Bool > __o_Recurse){
Bool Recurse = __o_Recurse.Default(false);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","forEachDead",0xe8751361,"flixel.group.FlxTypedSpriteGroup.forEachDead","flixel/group/FlxSpriteGroup.hx",448,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Function,"Function")
HX_STACK_ARG(Recurse,"Recurse")
HXLINE( 448) this->group->forEachDead(Function,Recurse);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,forEachDead,(void))
void FlxTypedSpriteGroup_obj::forEachExists( ::Dynamic Function,hx::Null< Bool > __o_Recurse){
Bool Recurse = __o_Recurse.Default(false);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","forEachExists",0x1ab74bd9,"flixel.group.FlxTypedSpriteGroup.forEachExists","flixel/group/FlxSpriteGroup.hx",459,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Function,"Function")
HX_STACK_ARG(Recurse,"Recurse")
HXLINE( 459) this->group->forEachExists(Function,Recurse);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,forEachExists,(void))
void FlxTypedSpriteGroup_obj::forEachOfType(hx::Class ObjectClass, ::Dynamic Function,hx::Null< Bool > __o_Recurse){
Bool Recurse = __o_Recurse.Default(false);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","forEachOfType",0xaf35856e,"flixel.group.FlxTypedSpriteGroup.forEachOfType","flixel/group/FlxSpriteGroup.hx",471,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(ObjectClass,"ObjectClass")
HX_STACK_ARG(Function,"Function")
HX_STACK_ARG(Recurse,"Recurse")
HXLINE( 471) this->group->forEachOfType(ObjectClass,Function,Recurse);
}
HX_DEFINE_DYNAMIC_FUNC3(FlxTypedSpriteGroup_obj,forEachOfType,(void))
void FlxTypedSpriteGroup_obj::clear(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","clear",0x211cfb40,"flixel.group.FlxTypedSpriteGroup.clear","flixel/group/FlxSpriteGroup.hx",480,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 480) this->group->clear();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTypedSpriteGroup_obj,clear,(void))
void FlxTypedSpriteGroup_obj::kill(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","kill",0x10e84d4b,"flixel.group.FlxTypedSpriteGroup.kill","flixel/group/FlxSpriteGroup.hx",488,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 489) this->super::kill();
HXLINE( 490) this->group->kill();
}
void FlxTypedSpriteGroup_obj::revive(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","revive",0xdb0ded42,"flixel.group.FlxTypedSpriteGroup.revive","flixel/group/FlxSpriteGroup.hx",497,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 498) this->super::revive();
HXLINE( 499) this->group->revive();
}
void FlxTypedSpriteGroup_obj::reset(Float X,Float Y){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","reset",0xbf89d382,"flixel.group.FlxTypedSpriteGroup.reset","flixel/group/FlxSpriteGroup.hx",510,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(X,"X")
HX_STACK_ARG(Y,"Y")
HXLINE( 511) this->revive();
HXLINE( 512) this->setPosition(X,Y);
HXLINE( 514) {
HXLINE( 514) HX_VARI( Int,_g) = (int)0;
HXDLIN( 514) HX_VARI( ::Array< ::Dynamic>,_g1) = this->_sprites;
HXDLIN( 514) while((_g < _g1->length)){
HXLINE( 514) HX_VARI( ::flixel::FlxSprite,sprite) = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >();
HXDLIN( 514) ++_g;
HXLINE( 516) Bool _hx_tmp = hx::IsNotNull( sprite );
HXDLIN( 516) if (_hx_tmp) {
HXLINE( 518) sprite->reset(X,Y);
}
}
}
}
void FlxTypedSpriteGroup_obj::setPosition(hx::Null< Float > __o_X,hx::Null< Float > __o_Y){
Float X = __o_X.Default(0);
Float Y = __o_Y.Default(0);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","setPosition",0x6aebbc5e,"flixel.group.FlxTypedSpriteGroup.setPosition","flixel/group/FlxSpriteGroup.hx",531,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(X,"X")
HX_STACK_ARG(Y,"Y")
HXLINE( 533) HX_VARI( Float,dx) = (X - this->x);
HXLINE( 534) HX_VARI( Float,dy) = (Y - this->y);
HXLINE( 535) this->multiTransformChildren_Float(::Array_obj< ::Dynamic>::__new(2)->init(0,this->xTransform_dyn())->init(1,this->yTransform_dyn()),::Array_obj< Float >::__new(2)->init(0,dx)->init(1,dy));
HXLINE( 538) this->_skipTransformChildren = true;
HXLINE( 539) this->set_x(X);
HXLINE( 540) this->set_y(Y);
HXLINE( 541) this->_skipTransformChildren = false;
}
::Array< ::Dynamic> FlxTypedSpriteGroup_obj::set_cameras(::Array< ::Dynamic> Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_cameras",0xe3294344,"flixel.group.FlxTypedSpriteGroup.set_cameras","flixel/group/FlxSpriteGroup.hx",604,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 605) ::Array< ::Dynamic> _hx_tmp = this->get_cameras();
HXDLIN( 605) if (hx::IsNotEq( _hx_tmp,Value )) {
HXLINE( 606) this->transformChildren_Array_flixel_FlxCamera(this->camerasTransform_dyn(),Value);
}
HXLINE( 607) return this->super::set_cameras(Value);
}
Bool FlxTypedSpriteGroup_obj::set_exists(Bool Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_exists",0xf5d49986,"flixel.group.FlxTypedSpriteGroup.set_exists","flixel/group/FlxSpriteGroup.hx",611,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 612) Bool _hx_tmp = (this->exists != Value);
HXDLIN( 612) if (_hx_tmp) {
HXLINE( 613) this->transformChildren_Bool(this->existsTransform_dyn(),Value);
}
HXLINE( 614) return this->super::set_exists(Value);
}
Bool FlxTypedSpriteGroup_obj::set_visible(Bool Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_visible",0xa31c3188,"flixel.group.FlxTypedSpriteGroup.set_visible","flixel/group/FlxSpriteGroup.hx",618,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 619) Bool _hx_tmp;
HXDLIN( 619) if (this->exists) {
HXLINE( 619) _hx_tmp = (this->visible != Value);
}
else {
HXLINE( 619) _hx_tmp = false;
}
HXDLIN( 619) if (_hx_tmp) {
HXLINE( 620) this->transformChildren_Bool(this->visibleTransform_dyn(),Value);
}
HXLINE( 621) return this->super::set_visible(Value);
}
Bool FlxTypedSpriteGroup_obj::set_active(Bool Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_active",0x4c3abd70,"flixel.group.FlxTypedSpriteGroup.set_active","flixel/group/FlxSpriteGroup.hx",625,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 626) Bool _hx_tmp;
HXDLIN( 626) if (this->exists) {
HXLINE( 626) _hx_tmp = (this->active != Value);
}
else {
HXLINE( 626) _hx_tmp = false;
}
HXDLIN( 626) if (_hx_tmp) {
HXLINE( 627) this->transformChildren_Bool(this->activeTransform_dyn(),Value);
}
HXLINE( 628) return this->super::set_active(Value);
}
Bool FlxTypedSpriteGroup_obj::set_alive(Bool Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_alive",0x0bff8b63,"flixel.group.FlxTypedSpriteGroup.set_alive","flixel/group/FlxSpriteGroup.hx",632,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 633) Bool _hx_tmp;
HXDLIN( 633) if (this->exists) {
HXLINE( 633) _hx_tmp = (this->alive != Value);
}
else {
HXLINE( 633) _hx_tmp = false;
}
HXDLIN( 633) if (_hx_tmp) {
HXLINE( 634) this->transformChildren_Bool(this->aliveTransform_dyn(),Value);
}
HXLINE( 635) return this->super::set_alive(Value);
}
Float FlxTypedSpriteGroup_obj::set_x(Float Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_x",0x52f1250e,"flixel.group.FlxTypedSpriteGroup.set_x","flixel/group/FlxSpriteGroup.hx",639,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 640) Bool _hx_tmp;
HXDLIN( 640) Bool _hx_tmp1;
HXDLIN( 640) if (!(this->_skipTransformChildren)) {
HXLINE( 640) _hx_tmp1 = this->exists;
}
else {
HXLINE( 640) _hx_tmp1 = false;
}
HXDLIN( 640) if (_hx_tmp1) {
HXLINE( 640) _hx_tmp = (this->x != Value);
}
else {
HXLINE( 640) _hx_tmp = false;
}
HXDLIN( 640) if (_hx_tmp) {
HXLINE( 642) HX_VARI( Float,offset) = (Value - this->x);
HXLINE( 643) this->transformChildren_Float(this->xTransform_dyn(),offset);
}
HXLINE( 646) return (this->x = Value);
}
Float FlxTypedSpriteGroup_obj::set_y(Float Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_y",0x52f1250f,"flixel.group.FlxTypedSpriteGroup.set_y","flixel/group/FlxSpriteGroup.hx",650,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 651) Bool _hx_tmp;
HXDLIN( 651) Bool _hx_tmp1;
HXDLIN( 651) if (!(this->_skipTransformChildren)) {
HXLINE( 651) _hx_tmp1 = this->exists;
}
else {
HXLINE( 651) _hx_tmp1 = false;
}
HXDLIN( 651) if (_hx_tmp1) {
HXLINE( 651) _hx_tmp = (this->y != Value);
}
else {
HXLINE( 651) _hx_tmp = false;
}
HXDLIN( 651) if (_hx_tmp) {
HXLINE( 653) HX_VARI( Float,offset) = (Value - this->y);
HXLINE( 654) this->transformChildren_Float(this->yTransform_dyn(),offset);
}
HXLINE( 657) return (this->y = Value);
}
Float FlxTypedSpriteGroup_obj::set_angle(Float Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_angle",0x0d506b69,"flixel.group.FlxTypedSpriteGroup.set_angle","flixel/group/FlxSpriteGroup.hx",661,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 662) Bool _hx_tmp;
HXDLIN( 662) if (this->exists) {
HXLINE( 662) _hx_tmp = (this->angle != Value);
}
else {
HXLINE( 662) _hx_tmp = false;
}
HXDLIN( 662) if (_hx_tmp) {
HXLINE( 664) HX_VARI( Float,offset) = (Value - this->angle);
HXLINE( 665) this->transformChildren_Float(this->angleTransform_dyn(),offset);
}
HXLINE( 667) return (this->angle = Value);
}
Float FlxTypedSpriteGroup_obj::set_alpha(Float Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_alpha",0x0c04cef4,"flixel.group.FlxTypedSpriteGroup.set_alpha","flixel/group/FlxSpriteGroup.hx",671,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 672) HX_VAR( Float,lowerBound);
HXDLIN( 672) if ((Value < (int)0)) {
HXLINE( 672) lowerBound = (int)0;
}
else {
HXLINE( 672) lowerBound = Value;
}
HXDLIN( 672) ::Dynamic _hx_tmp;
HXDLIN( 672) if ((lowerBound > (int)1)) {
HXLINE( 672) _hx_tmp = (int)1;
}
else {
HXLINE( 672) _hx_tmp = lowerBound;
}
HXDLIN( 672) Value = _hx_tmp;
HXLINE( 674) Bool _hx_tmp1;
HXDLIN( 674) if (this->exists) {
HXLINE( 674) _hx_tmp1 = (this->alpha != Value);
}
else {
HXLINE( 674) _hx_tmp1 = false;
}
HXDLIN( 674) if (_hx_tmp1) {
HXLINE( 676) HX_VAR( Float,factor);
HXDLIN( 676) if ((this->alpha > (int)0)) {
HXLINE( 676) factor = ((Float)Value / (Float)this->alpha);
}
else {
HXLINE( 676) factor = (int)0;
}
HXLINE( 677) this->transformChildren_Float(this->alphaTransform_dyn(),factor);
}
HXLINE( 679) return (this->alpha = Value);
}
Int FlxTypedSpriteGroup_obj::set_facing(Int Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_facing",0x19f9bac4,"flixel.group.FlxTypedSpriteGroup.set_facing","flixel/group/FlxSpriteGroup.hx",683,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 684) Bool _hx_tmp;
HXDLIN( 684) if (this->exists) {
HXLINE( 684) _hx_tmp = (this->facing != Value);
}
else {
HXLINE( 684) _hx_tmp = false;
}
HXDLIN( 684) if (_hx_tmp) {
HXLINE( 685) this->transformChildren_Int(this->facingTransform_dyn(),Value);
}
HXLINE( 686) return (this->facing = Value);
}
Bool FlxTypedSpriteGroup_obj::set_flipX(Bool Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_flipX",0xed006ca1,"flixel.group.FlxTypedSpriteGroup.set_flipX","flixel/group/FlxSpriteGroup.hx",690,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 691) Bool _hx_tmp;
HXDLIN( 691) if (this->exists) {
HXLINE( 691) _hx_tmp = (this->flipX != Value);
}
else {
HXLINE( 691) _hx_tmp = false;
}
HXDLIN( 691) if (_hx_tmp) {
HXLINE( 692) this->transformChildren_Bool(this->flipXTransform_dyn(),Value);
}
HXLINE( 693) return (this->flipX = Value);
}
Bool FlxTypedSpriteGroup_obj::set_flipY(Bool Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_flipY",0xed006ca2,"flixel.group.FlxTypedSpriteGroup.set_flipY","flixel/group/FlxSpriteGroup.hx",697,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 698) Bool _hx_tmp;
HXDLIN( 698) if (this->exists) {
HXLINE( 698) _hx_tmp = (this->flipY != Value);
}
else {
HXLINE( 698) _hx_tmp = false;
}
HXDLIN( 698) if (_hx_tmp) {
HXLINE( 699) this->transformChildren_Bool(this->flipYTransform_dyn(),Value);
}
HXLINE( 700) return (this->flipY = Value);
}
Bool FlxTypedSpriteGroup_obj::set_moves(Bool Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_moves",0xf6d3f3d8,"flixel.group.FlxTypedSpriteGroup.set_moves","flixel/group/FlxSpriteGroup.hx",704,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 705) Bool _hx_tmp;
HXDLIN( 705) if (this->exists) {
HXLINE( 705) _hx_tmp = (this->moves != Value);
}
else {
HXLINE( 705) _hx_tmp = false;
}
HXDLIN( 705) if (_hx_tmp) {
HXLINE( 706) this->transformChildren_Bool(this->movesTransform_dyn(),Value);
}
HXLINE( 707) return (this->moves = Value);
}
Bool FlxTypedSpriteGroup_obj::set_immovable(Bool Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_immovable",0xdf98d1a0,"flixel.group.FlxTypedSpriteGroup.set_immovable","flixel/group/FlxSpriteGroup.hx",711,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 712) Bool _hx_tmp;
HXDLIN( 712) if (this->exists) {
HXLINE( 712) _hx_tmp = (this->immovable != Value);
}
else {
HXLINE( 712) _hx_tmp = false;
}
HXDLIN( 712) if (_hx_tmp) {
HXLINE( 713) this->transformChildren_Bool(this->immovableTransform_dyn(),Value);
}
HXLINE( 714) return (this->immovable = Value);
}
Bool FlxTypedSpriteGroup_obj::set_solid(Bool Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_solid",0x6b33dbc1,"flixel.group.FlxTypedSpriteGroup.set_solid","flixel/group/FlxSpriteGroup.hx",718,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 719) Bool _hx_tmp;
HXDLIN( 719) if (this->exists) {
HXLINE( 719) _hx_tmp = ((((int)this->allowCollisions & (int)(int)4369) > (int)0) != Value);
}
else {
HXLINE( 719) _hx_tmp = false;
}
HXDLIN( 719) if (_hx_tmp) {
HXLINE( 720) this->transformChildren_Bool(this->solidTransform_dyn(),Value);
}
HXLINE( 721) return this->super::set_solid(Value);
}
Int FlxTypedSpriteGroup_obj::set_color(Int _tmp_Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_color",0x34ca98f9,"flixel.group.FlxTypedSpriteGroup.set_color","flixel/group/FlxSpriteGroup.hx",725,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(_tmp_Value,"_tmp_Value")
HXLINE( 726) HX_VARI( Int,Value) = _tmp_Value;
HXDLIN( 726) Bool _hx_tmp;
HXDLIN( 726) if (this->exists) {
HXLINE( 726) _hx_tmp = (this->color != Value);
}
else {
HXLINE( 726) _hx_tmp = false;
}
HXDLIN( 726) if (_hx_tmp) {
HXLINE( 727) this->transformChildren_Int(this->gColorTransform_dyn(),Value);
}
HXLINE( 728) return (this->color = Value);
}
::hx::EnumBase FlxTypedSpriteGroup_obj::set_blend(::hx::EnumBase Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_blend",0x9f630fe7,"flixel.group.FlxTypedSpriteGroup.set_blend","flixel/group/FlxSpriteGroup.hx",732,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 733) Bool _hx_tmp;
HXDLIN( 733) if (this->exists) {
HXLINE( 733) _hx_tmp = hx::IsNotEq( this->blend,Value );
}
else {
HXLINE( 733) _hx_tmp = false;
}
HXDLIN( 733) if (_hx_tmp) {
HXLINE( 734) this->transformChildren_openfl__legacy_display_BlendMode(this->blendTransform_dyn(),Value);
}
HXLINE( 735) return (this->blend = Value);
}
Bool FlxTypedSpriteGroup_obj::set_pixelPerfectRender(Bool Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_pixelPerfectRender",0x5163ac87,"flixel.group.FlxTypedSpriteGroup.set_pixelPerfectRender","flixel/group/FlxSpriteGroup.hx",739,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 740) Bool _hx_tmp;
HXDLIN( 740) if (this->exists) {
HXLINE( 740) _hx_tmp = hx::IsNotEq( this->pixelPerfectRender,Value );
}
else {
HXLINE( 740) _hx_tmp = false;
}
HXDLIN( 740) if (_hx_tmp) {
HXLINE( 741) this->transformChildren_Bool(this->pixelPerfectTransform_dyn(),Value);
}
HXLINE( 742) return this->super::set_pixelPerfectRender(Value);
}
Float FlxTypedSpriteGroup_obj::set_width(Float Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_width",0xb4d0dd9c,"flixel.group.FlxTypedSpriteGroup.set_width","flixel/group/FlxSpriteGroup.hx",750,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 750) return Value;
}
Float FlxTypedSpriteGroup_obj::get_width(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","get_width",0xd17ff190,"flixel.group.FlxTypedSpriteGroup.get_width","flixel/group/FlxSpriteGroup.hx",754,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 755) if ((this->group->length == (int)0)) {
HXLINE( 756) return (int)0;
}
HXLINE( 758) HX_VARI( Float,minX) = ::Math_obj::POSITIVE_INFINITY;
HXLINE( 759) HX_VARI( Float,maxX) = ::Math_obj::NEGATIVE_INFINITY;
HXLINE( 761) {
HXLINE( 761) HX_VARI( Int,_g) = (int)0;
HXDLIN( 761) HX_VARI( ::Array< ::Dynamic>,_g1) = this->_sprites;
HXDLIN( 761) while((_g < _g1->length)){
HXLINE( 761) HX_VARI( ::flixel::FlxSprite,member) = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >();
HXDLIN( 761) ++_g;
HXLINE( 763) Bool _hx_tmp = hx::IsNull( member );
HXDLIN( 763) if (_hx_tmp) {
HXLINE( 763) continue;
}
HXLINE( 764) HX_VARI( Float,minMemberX) = member->x;
HXLINE( 765) Float _hx_tmp1 = member->get_width();
HXDLIN( 765) HX_VARI( Float,maxMemberX) = (minMemberX + _hx_tmp1);
HXLINE( 767) Bool _hx_tmp2 = (maxMemberX > maxX);
HXDLIN( 767) if (_hx_tmp2) {
HXLINE( 769) maxX = maxMemberX;
}
HXLINE( 771) Bool _hx_tmp3 = (minMemberX < minX);
HXDLIN( 771) if (_hx_tmp3) {
HXLINE( 773) minX = minMemberX;
}
}
}
HXLINE( 776) return (maxX - minX);
}
Float FlxTypedSpriteGroup_obj::set_height(Float Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_height",0x38408391,"flixel.group.FlxTypedSpriteGroup.set_height","flixel/group/FlxSpriteGroup.hx",784,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 784) return Value;
}
Float FlxTypedSpriteGroup_obj::get_height(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","get_height",0x34c2e51d,"flixel.group.FlxTypedSpriteGroup.get_height","flixel/group/FlxSpriteGroup.hx",788,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 789) if ((this->group->length == (int)0)) {
HXLINE( 791) return (int)0;
}
HXLINE( 794) HX_VARI( Float,minY) = ::Math_obj::POSITIVE_INFINITY;
HXLINE( 795) HX_VARI( Float,maxY) = ::Math_obj::NEGATIVE_INFINITY;
HXLINE( 797) {
HXLINE( 797) HX_VARI( Int,_g) = (int)0;
HXDLIN( 797) HX_VARI( ::Array< ::Dynamic>,_g1) = this->_sprites;
HXDLIN( 797) while((_g < _g1->length)){
HXLINE( 797) HX_VARI( ::flixel::FlxSprite,member) = _g1->__get(_g).StaticCast< ::flixel::FlxSprite >();
HXDLIN( 797) ++_g;
HXLINE( 799) Bool _hx_tmp = hx::IsNull( member );
HXDLIN( 799) if (_hx_tmp) {
HXLINE( 799) continue;
}
HXLINE( 800) HX_VARI( Float,minMemberY) = member->y;
HXLINE( 801) Float _hx_tmp1 = member->get_height();
HXDLIN( 801) HX_VARI( Float,maxMemberY) = (minMemberY + _hx_tmp1);
HXLINE( 803) Bool _hx_tmp2 = (maxMemberY > maxY);
HXDLIN( 803) if (_hx_tmp2) {
HXLINE( 805) maxY = maxMemberY;
}
HXLINE( 807) Bool _hx_tmp3 = (minMemberY < minY);
HXDLIN( 807) if (_hx_tmp3) {
HXLINE( 809) minY = minMemberY;
}
}
}
HXLINE( 812) return (maxY - minY);
}
Int FlxTypedSpriteGroup_obj::get_length(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","get_length",0xd17e721c,"flixel.group.FlxTypedSpriteGroup.get_length","flixel/group/FlxSpriteGroup.hx",819,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 819) return this->group->length;
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTypedSpriteGroup_obj,get_length,return )
Int FlxTypedSpriteGroup_obj::get_maxSize(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","get_maxSize",0xc20eab8f,"flixel.group.FlxTypedSpriteGroup.get_maxSize","flixel/group/FlxSpriteGroup.hx",824,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 824) return this->group->maxSize;
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTypedSpriteGroup_obj,get_maxSize,return )
Int FlxTypedSpriteGroup_obj::set_maxSize(Int Size){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_maxSize",0xcc7bb29b,"flixel.group.FlxTypedSpriteGroup.set_maxSize","flixel/group/FlxSpriteGroup.hx",829,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Size,"Size")
HXLINE( 829) return this->group->set_maxSize(Size);
}
HX_DEFINE_DYNAMIC_FUNC1(FlxTypedSpriteGroup_obj,set_maxSize,return )
::cpp::VirtualArray FlxTypedSpriteGroup_obj::get_members(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","get_members",0x0ffadee3,"flixel.group.FlxTypedSpriteGroup.get_members","flixel/group/FlxSpriteGroup.hx",834,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 834) return this->group->members;
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTypedSpriteGroup_obj,get_members,return )
void FlxTypedSpriteGroup_obj::xTransform( ::flixel::FlxSprite Sprite,Float X){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","xTransform",0x4c3dab41,"flixel.group.FlxTypedSpriteGroup.xTransform","flixel/group/FlxSpriteGroup.hx",839,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(X,"X")
HXLINE( 839) Float _hx_tmp = (Sprite->x + X);
HXDLIN( 839) Sprite->set_x(_hx_tmp);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,xTransform,(void))
void FlxTypedSpriteGroup_obj::yTransform( ::flixel::FlxSprite Sprite,Float Y){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","yTransform",0x0c882320,"flixel.group.FlxTypedSpriteGroup.yTransform","flixel/group/FlxSpriteGroup.hx",840,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Y,"Y")
HXLINE( 840) Float _hx_tmp = (Sprite->y + Y);
HXDLIN( 840) Sprite->set_y(_hx_tmp);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,yTransform,(void))
void FlxTypedSpriteGroup_obj::angleTransform( ::flixel::FlxSprite Sprite,Float Angle){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","angleTransform",0x285b5f06,"flixel.group.FlxTypedSpriteGroup.angleTransform","flixel/group/FlxSpriteGroup.hx",841,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Angle,"Angle")
HXLINE( 841) Float _hx_tmp = (Sprite->angle + Angle);
HXDLIN( 841) Sprite->set_angle(_hx_tmp);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,angleTransform,(void))
void FlxTypedSpriteGroup_obj::alphaTransform( ::flixel::FlxSprite Sprite,Float Alpha){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","alphaTransform",0xe7f1b21b,"flixel.group.FlxTypedSpriteGroup.alphaTransform","flixel/group/FlxSpriteGroup.hx",842,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Alpha,"Alpha")
HXLINE( 842) Float _hx_tmp = (Sprite->alpha * Alpha);
HXDLIN( 842) Sprite->set_alpha(_hx_tmp);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,alphaTransform,(void))
void FlxTypedSpriteGroup_obj::facingTransform( ::flixel::FlxSprite Sprite,Int Facing){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","facingTransform",0x8cbce265,"flixel.group.FlxTypedSpriteGroup.facingTransform","flixel/group/FlxSpriteGroup.hx",843,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Facing,"Facing")
HXLINE( 843) Sprite->set_facing(Facing);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,facingTransform,(void))
void FlxTypedSpriteGroup_obj::flipXTransform( ::flixel::FlxSprite Sprite,Bool FlipX){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","flipXTransform",0x2d6d76ce,"flixel.group.FlxTypedSpriteGroup.flipXTransform","flixel/group/FlxSpriteGroup.hx",844,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(FlipX,"FlipX")
HXLINE( 844) Sprite->set_flipX(FlipX);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,flipXTransform,(void))
void FlxTypedSpriteGroup_obj::flipYTransform( ::flixel::FlxSprite Sprite,Bool FlipY){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","flipYTransform",0xedb7eead,"flixel.group.FlxTypedSpriteGroup.flipYTransform","flixel/group/FlxSpriteGroup.hx",845,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(FlipY,"FlipY")
HXLINE( 845) Sprite->set_flipY(FlipY);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,flipYTransform,(void))
void FlxTypedSpriteGroup_obj::movesTransform( ::flixel::FlxSprite Sprite,Bool Moves){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","movesTransform",0x6670d0b7,"flixel.group.FlxTypedSpriteGroup.movesTransform","flixel/group/FlxSpriteGroup.hx",846,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Moves,"Moves")
HXLINE( 846) Sprite->set_moves(Moves);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,movesTransform,(void))
void FlxTypedSpriteGroup_obj::pixelPerfectTransform( ::flixel::FlxSprite Sprite,Bool PixelPerfect){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","pixelPerfectTransform",0x21312cf8,"flixel.group.FlxTypedSpriteGroup.pixelPerfectTransform","flixel/group/FlxSpriteGroup.hx",847,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(PixelPerfect,"PixelPerfect")
HXLINE( 847) Sprite->set_pixelPerfectRender(PixelPerfect);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,pixelPerfectTransform,(void))
void FlxTypedSpriteGroup_obj::gColorTransform( ::flixel::FlxSprite Sprite,Int Color){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","gColorTransform",0x1fbe79c3,"flixel.group.FlxTypedSpriteGroup.gColorTransform","flixel/group/FlxSpriteGroup.hx",848,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Color,"Color")
HXLINE( 848) Sprite->set_color(Color);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,gColorTransform,(void))
void FlxTypedSpriteGroup_obj::blendTransform( ::flixel::FlxSprite Sprite,::hx::EnumBase Blend){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","blendTransform",0x1d7b3ac8,"flixel.group.FlxTypedSpriteGroup.blendTransform","flixel/group/FlxSpriteGroup.hx",849,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Blend,"Blend")
HXLINE( 849) Sprite->set_blend(Blend);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,blendTransform,(void))
void FlxTypedSpriteGroup_obj::immovableTransform( ::flixel::FlxSprite Sprite,Bool Immovable){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","immovableTransform",0x108fd76f,"flixel.group.FlxTypedSpriteGroup.immovableTransform","flixel/group/FlxSpriteGroup.hx",850,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Immovable,"Immovable")
HXLINE( 850) Sprite->set_immovable(Immovable);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,immovableTransform,(void))
void FlxTypedSpriteGroup_obj::visibleTransform( ::flixel::FlxSprite Sprite,Bool Visible){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","visibleTransform",0x807eb3c7,"flixel.group.FlxTypedSpriteGroup.visibleTransform","flixel/group/FlxSpriteGroup.hx",851,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Visible,"Visible")
HXLINE( 851) Sprite->set_visible(Visible);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,visibleTransform,(void))
void FlxTypedSpriteGroup_obj::activeTransform( ::flixel::FlxSprite Sprite,Bool Active){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","activeTransform",0x51542a39,"flixel.group.FlxTypedSpriteGroup.activeTransform","flixel/group/FlxSpriteGroup.hx",852,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Active,"Active")
HXLINE( 852) Sprite->set_active(Active);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,activeTransform,(void))
void FlxTypedSpriteGroup_obj::solidTransform( ::flixel::FlxSprite Sprite,Bool Solid){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","solidTransform",0x242323ae,"flixel.group.FlxTypedSpriteGroup.solidTransform","flixel/group/FlxSpriteGroup.hx",853,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Solid,"Solid")
HXLINE( 853) Sprite->set_solid(Solid);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,solidTransform,(void))
void FlxTypedSpriteGroup_obj::aliveTransform( ::flixel::FlxSprite Sprite,Bool Alive){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","aliveTransform",0x29096fcc,"flixel.group.FlxTypedSpriteGroup.aliveTransform","flixel/group/FlxSpriteGroup.hx",854,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Alive,"Alive")
HXLINE( 854) Sprite->set_alive(Alive);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,aliveTransform,(void))
void FlxTypedSpriteGroup_obj::existsTransform( ::flixel::FlxSprite Sprite,Bool Exists){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","existsTransform",0xb2051b63,"flixel.group.FlxTypedSpriteGroup.existsTransform","flixel/group/FlxSpriteGroup.hx",855,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Exists,"Exists")
HXLINE( 855) Sprite->set_exists(Exists);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,existsTransform,(void))
void FlxTypedSpriteGroup_obj::camerasTransform( ::flixel::FlxSprite Sprite,::Array< ::Dynamic> Cameras){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","camerasTransform",0x7f778a8b,"flixel.group.FlxTypedSpriteGroup.camerasTransform","flixel/group/FlxSpriteGroup.hx",856,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Cameras,"Cameras")
HXLINE( 856) Sprite->set_cameras(Cameras);
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,camerasTransform,(void))
void FlxTypedSpriteGroup_obj::offsetTransform( ::flixel::FlxSprite Sprite, ::flixel::math::FlxPoint Offset){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","offsetTransform",0x35aa32cc,"flixel.group.FlxTypedSpriteGroup.offsetTransform","flixel/group/FlxSpriteGroup.hx",858,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Offset,"Offset")
HXLINE( 858) HX_VARI( ::flixel::math::FlxPoint,_this) = Sprite->offset;
HXDLIN( 858) _this->set_x(Offset->x);
HXDLIN( 858) _this->set_y(Offset->y);
HXDLIN( 858) Bool _hx_tmp = Offset->_weak;
HXDLIN( 858) if (_hx_tmp) {
HXLINE( 858) Offset->put();
}
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,offsetTransform,(void))
void FlxTypedSpriteGroup_obj::originTransform( ::flixel::FlxSprite Sprite, ::flixel::math::FlxPoint Origin){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","originTransform",0x93cd4e19,"flixel.group.FlxTypedSpriteGroup.originTransform","flixel/group/FlxSpriteGroup.hx",859,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Origin,"Origin")
HXLINE( 859) HX_VARI( ::flixel::math::FlxPoint,_this) = Sprite->origin;
HXDLIN( 859) _this->set_x(Origin->x);
HXDLIN( 859) _this->set_y(Origin->y);
HXDLIN( 859) Bool _hx_tmp = Origin->_weak;
HXDLIN( 859) if (_hx_tmp) {
HXLINE( 859) Origin->put();
}
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,originTransform,(void))
void FlxTypedSpriteGroup_obj::scaleTransform( ::flixel::FlxSprite Sprite, ::flixel::math::FlxPoint Scale){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","scaleTransform",0x4ec9456f,"flixel.group.FlxTypedSpriteGroup.scaleTransform","flixel/group/FlxSpriteGroup.hx",860,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(Scale,"Scale")
HXLINE( 860) HX_VARI( ::flixel::math::FlxPoint,_this) = Sprite->scale;
HXDLIN( 860) _this->set_x(Scale->x);
HXDLIN( 860) _this->set_y(Scale->y);
HXDLIN( 860) Bool _hx_tmp = Scale->_weak;
HXDLIN( 860) if (_hx_tmp) {
HXLINE( 860) Scale->put();
}
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,scaleTransform,(void))
void FlxTypedSpriteGroup_obj::scrollFactorTransform( ::flixel::FlxSprite Sprite, ::flixel::math::FlxPoint ScrollFactor){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","scrollFactorTransform",0x4d8808c3,"flixel.group.FlxTypedSpriteGroup.scrollFactorTransform","flixel/group/FlxSpriteGroup.hx",861,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HX_STACK_ARG(ScrollFactor,"ScrollFactor")
HXLINE( 861) HX_VARI( ::flixel::math::FlxPoint,_this) = Sprite->scrollFactor;
HXDLIN( 861) _this->set_x(ScrollFactor->x);
HXDLIN( 861) _this->set_y(ScrollFactor->y);
HXDLIN( 861) Bool _hx_tmp = ScrollFactor->_weak;
HXDLIN( 861) if (_hx_tmp) {
HXLINE( 861) ScrollFactor->put();
}
}
HX_DEFINE_DYNAMIC_FUNC2(FlxTypedSpriteGroup_obj,scrollFactorTransform,(void))
void FlxTypedSpriteGroup_obj::offsetCallback( ::flixel::math::FlxPoint Offset){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","offsetCallback",0xeadd6065,"flixel.group.FlxTypedSpriteGroup.offsetCallback","flixel/group/FlxSpriteGroup.hx",864,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Offset,"Offset")
HXLINE( 864) this->transformChildren_flixel_math_FlxPoint(this->offsetTransform_dyn(),Offset);
}
HX_DEFINE_DYNAMIC_FUNC1(FlxTypedSpriteGroup_obj,offsetCallback,(void))
void FlxTypedSpriteGroup_obj::originCallback( ::flixel::math::FlxPoint Origin){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","originCallback",0xfa35edb8,"flixel.group.FlxTypedSpriteGroup.originCallback","flixel/group/FlxSpriteGroup.hx",865,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Origin,"Origin")
HXLINE( 865) this->transformChildren_flixel_math_FlxPoint(this->originTransform_dyn(),Origin);
}
HX_DEFINE_DYNAMIC_FUNC1(FlxTypedSpriteGroup_obj,originCallback,(void))
void FlxTypedSpriteGroup_obj::scaleCallback( ::flixel::math::FlxPoint Scale){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","scaleCallback",0xf9e6b322,"flixel.group.FlxTypedSpriteGroup.scaleCallback","flixel/group/FlxSpriteGroup.hx",866,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Scale,"Scale")
HXLINE( 866) this->transformChildren_flixel_math_FlxPoint(this->scaleTransform_dyn(),Scale);
}
HX_DEFINE_DYNAMIC_FUNC1(FlxTypedSpriteGroup_obj,scaleCallback,(void))
void FlxTypedSpriteGroup_obj::scrollFactorCallback( ::flixel::math::FlxPoint ScrollFactor){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","scrollFactorCallback",0x26aab64e,"flixel.group.FlxTypedSpriteGroup.scrollFactorCallback","flixel/group/FlxSpriteGroup.hx",867,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(ScrollFactor,"ScrollFactor")
HXLINE( 867) this->transformChildren_flixel_math_FlxPoint(this->scrollFactorTransform_dyn(),ScrollFactor);
}
HX_DEFINE_DYNAMIC_FUNC1(FlxTypedSpriteGroup_obj,scrollFactorCallback,(void))
::flixel::FlxSprite FlxTypedSpriteGroup_obj::loadGraphicFromSprite( ::flixel::FlxSprite Sprite){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","loadGraphicFromSprite",0x6f12dc84,"flixel.group.FlxTypedSpriteGroup.loadGraphicFromSprite","flixel/group/FlxSpriteGroup.hx",881,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Sprite,"Sprite")
HXLINE( 881) return hx::ObjectPtr<OBJ_>(this);
}
::flixel::FlxSprite FlxTypedSpriteGroup_obj::loadGraphic( ::Dynamic Graphic,hx::Null< Bool > __o_Animated,hx::Null< Int > __o_Width,hx::Null< Int > __o_Height,hx::Null< Bool > __o_Unique,::String Key){
Bool Animated = __o_Animated.Default(false);
Int Width = __o_Width.Default(0);
Int Height = __o_Height.Default(0);
Bool Unique = __o_Unique.Default(false);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","loadGraphic",0xb4356b15,"flixel.group.FlxTypedSpriteGroup.loadGraphic","flixel/group/FlxSpriteGroup.hx",890,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Graphic,"Graphic")
HX_STACK_ARG(Animated,"Animated")
HX_STACK_ARG(Width,"Width")
HX_STACK_ARG(Height,"Height")
HX_STACK_ARG(Unique,"Unique")
HX_STACK_ARG(Key,"Key")
HXLINE( 890) return hx::ObjectPtr<OBJ_>(this);
}
::flixel::FlxSprite FlxTypedSpriteGroup_obj::loadRotatedGraphic( ::Dynamic Graphic,hx::Null< Int > __o_Rotations,hx::Null< Int > __o_Frame,hx::Null< Bool > __o_AntiAliasing,hx::Null< Bool > __o_AutoBuffer,::String Key){
Int Rotations = __o_Rotations.Default(16);
Int Frame = __o_Frame.Default(-1);
Bool AntiAliasing = __o_AntiAliasing.Default(false);
Bool AutoBuffer = __o_AutoBuffer.Default(false);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","loadRotatedGraphic",0x45e23732,"flixel.group.FlxTypedSpriteGroup.loadRotatedGraphic","flixel/group/FlxSpriteGroup.hx",902,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Graphic,"Graphic")
HX_STACK_ARG(Rotations,"Rotations")
HX_STACK_ARG(Frame,"Frame")
HX_STACK_ARG(AntiAliasing,"AntiAliasing")
HX_STACK_ARG(AutoBuffer,"AutoBuffer")
HX_STACK_ARG(Key,"Key")
HXLINE( 902) return hx::ObjectPtr<OBJ_>(this);
}
::flixel::FlxSprite FlxTypedSpriteGroup_obj::makeGraphic(Int Width,Int Height,hx::Null< Int > __o__tmp_Color,hx::Null< Bool > __o_Unique,::String Key){
Int _tmp_Color = __o__tmp_Color.Default(-1);
Bool Unique = __o_Unique.Default(false);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","makeGraphic",0x27a1d44d,"flixel.group.FlxTypedSpriteGroup.makeGraphic","flixel/group/FlxSpriteGroup.hx",914,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Width,"Width")
HX_STACK_ARG(Height,"Height")
HX_STACK_ARG(_tmp_Color,"_tmp_Color")
HX_STACK_ARG(Unique,"Unique")
HX_STACK_ARG(Key,"Key")
HXLINE( 914) HX_VARI( Int,Color) = _tmp_Color;
HXDLIN( 914) return hx::ObjectPtr<OBJ_>(this);
}
::openfl::_legacy::display::BitmapData FlxTypedSpriteGroup_obj::set_pixels( ::openfl::_legacy::display::BitmapData Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_pixels",0xc29e6ad7,"flixel.group.FlxTypedSpriteGroup.set_pixels","flixel/group/FlxSpriteGroup.hx",923,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 923) return Value;
}
::flixel::graphics::frames::FlxFrame FlxTypedSpriteGroup_obj::set_frame( ::flixel::graphics::frames::FlxFrame Value){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_frame",0xf0f19fc3,"flixel.group.FlxTypedSpriteGroup.set_frame","flixel/group/FlxSpriteGroup.hx",932,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Value,"Value")
HXLINE( 932) return Value;
}
::openfl::_legacy::display::BitmapData FlxTypedSpriteGroup_obj::get_pixels(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","get_pixels",0xbf20cc63,"flixel.group.FlxTypedSpriteGroup.get_pixels","flixel/group/FlxSpriteGroup.hx",941,0xeb1fa7f3)
HX_STACK_THIS(this)
HXLINE( 941) return null();
}
void FlxTypedSpriteGroup_obj::calcFrame(hx::Null< Bool > __o_RunOnCpp){
Bool RunOnCpp = __o_RunOnCpp.Default(false);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","calcFrame",0xbd00728b,"flixel.group.FlxTypedSpriteGroup.calcFrame","flixel/group/FlxSpriteGroup.hx",950,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(RunOnCpp,"RunOnCpp")
}
void FlxTypedSpriteGroup_obj::resetHelpers(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","resetHelpers",0x60f4ebe3,"flixel.group.FlxTypedSpriteGroup.resetHelpers","flixel/group/FlxSpriteGroup.hx",957,0xeb1fa7f3)
HX_STACK_THIS(this)
}
void FlxTypedSpriteGroup_obj::stamp( ::flixel::FlxSprite Brush,hx::Null< Int > __o_X,hx::Null< Int > __o_Y){
Int X = __o_X.Default(0);
Int Y = __o_Y.Default(0);
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","stamp",0x5cccf9b6,"flixel.group.FlxTypedSpriteGroup.stamp","flixel/group/FlxSpriteGroup.hx",962,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Brush,"Brush")
HX_STACK_ARG(X,"X")
HX_STACK_ARG(Y,"Y")
}
::flixel::graphics::frames::FlxFramesCollection FlxTypedSpriteGroup_obj::set_frames( ::flixel::graphics::frames::FlxFramesCollection Frames){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","set_frames",0xe27a2b50,"flixel.group.FlxTypedSpriteGroup.set_frames","flixel/group/FlxSpriteGroup.hx",969,0xeb1fa7f3)
HX_STACK_THIS(this)
HX_STACK_ARG(Frames,"Frames")
HXLINE( 969) return Frames;
}
void FlxTypedSpriteGroup_obj::updateColorTransform(){
HX_STACK_FRAME("flixel.group.FlxTypedSpriteGroup","updateColorTransform",0x64df671f,"flixel.group.FlxTypedSpriteGroup.updateColorTransform","flixel/group/FlxSpriteGroup.hx",975,0xeb1fa7f3)
HX_STACK_THIS(this)
}
FlxTypedSpriteGroup_obj::FlxTypedSpriteGroup_obj()
{
}
void FlxTypedSpriteGroup_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(FlxTypedSpriteGroup);
HX_MARK_MEMBER_NAME(group,"group");
HX_MARK_MEMBER_NAME(members,"members");
HX_MARK_MEMBER_NAME(length,"length");
HX_MARK_MEMBER_NAME(_skipTransformChildren,"_skipTransformChildren");
HX_MARK_MEMBER_NAME(_sprites,"_sprites");
::flixel::FlxSprite_obj::__Mark(HX_MARK_ARG);
HX_MARK_END_CLASS();
}
void FlxTypedSpriteGroup_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(group,"group");
HX_VISIT_MEMBER_NAME(members,"members");
HX_VISIT_MEMBER_NAME(length,"length");
HX_VISIT_MEMBER_NAME(_skipTransformChildren,"_skipTransformChildren");
HX_VISIT_MEMBER_NAME(_sprites,"_sprites");
::flixel::FlxSprite_obj::__Visit(HX_VISIT_ARG);
}
hx::Val FlxTypedSpriteGroup_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"add") ) { return hx::Val( add_dyn()); }
break;
case 4:
if (HX_FIELD_EQ(inName,"draw") ) { return hx::Val( draw_dyn()); }
if (HX_FIELD_EQ(inName,"sort") ) { return hx::Val( sort_dyn()); }
if (HX_FIELD_EQ(inName,"kill") ) { return hx::Val( kill_dyn()); }
break;
case 5:
if (HX_FIELD_EQ(inName,"group") ) { return hx::Val( group); }
if (HX_FIELD_EQ(inName,"clone") ) { return hx::Val( clone_dyn()); }
if (HX_FIELD_EQ(inName,"clear") ) { return hx::Val( clear_dyn()); }
if (HX_FIELD_EQ(inName,"reset") ) { return hx::Val( reset_dyn()); }
if (HX_FIELD_EQ(inName,"set_x") ) { return hx::Val( set_x_dyn()); }
if (HX_FIELD_EQ(inName,"set_y") ) { return hx::Val( set_y_dyn()); }
if (HX_FIELD_EQ(inName,"stamp") ) { return hx::Val( stamp_dyn()); }
break;
case 6:
if (HX_FIELD_EQ(inName,"length") ) { return hx::Val( inCallProp == hx::paccAlways ? get_length() : length); }
if (HX_FIELD_EQ(inName,"update") ) { return hx::Val( update_dyn()); }
if (HX_FIELD_EQ(inName,"remove") ) { return hx::Val( remove_dyn()); }
if (HX_FIELD_EQ(inName,"revive") ) { return hx::Val( revive_dyn()); }
break;
case 7:
if (HX_FIELD_EQ(inName,"members") ) { return hx::Val( inCallProp == hx::paccAlways ? get_members() : members); }
if (HX_FIELD_EQ(inName,"maxSize") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_maxSize()); }
if (HX_FIELD_EQ(inName,"destroy") ) { return hx::Val( destroy_dyn()); }
if (HX_FIELD_EQ(inName,"recycle") ) { return hx::Val( recycle_dyn()); }
if (HX_FIELD_EQ(inName,"replace") ) { return hx::Val( replace_dyn()); }
if (HX_FIELD_EQ(inName,"forEach") ) { return hx::Val( forEach_dyn()); }
break;
case 8:
if (HX_FIELD_EQ(inName,"_sprites") ) { return hx::Val( _sprites); }
if (HX_FIELD_EQ(inName,"initVars") ) { return hx::Val( initVars_dyn()); }
if (HX_FIELD_EQ(inName,"iterator") ) { return hx::Val( iterator_dyn()); }
break;
case 9:
if (HX_FIELD_EQ(inName,"countDead") ) { return hx::Val( countDead_dyn()); }
if (HX_FIELD_EQ(inName,"getRandom") ) { return hx::Val( getRandom_dyn()); }
if (HX_FIELD_EQ(inName,"set_alive") ) { return hx::Val( set_alive_dyn()); }
if (HX_FIELD_EQ(inName,"set_angle") ) { return hx::Val( set_angle_dyn()); }
if (HX_FIELD_EQ(inName,"set_alpha") ) { return hx::Val( set_alpha_dyn()); }
if (HX_FIELD_EQ(inName,"set_flipX") ) { return hx::Val( set_flipX_dyn()); }
if (HX_FIELD_EQ(inName,"set_flipY") ) { return hx::Val( set_flipY_dyn()); }
if (HX_FIELD_EQ(inName,"set_moves") ) { return hx::Val( set_moves_dyn()); }
if (HX_FIELD_EQ(inName,"set_solid") ) { return hx::Val( set_solid_dyn()); }
if (HX_FIELD_EQ(inName,"set_color") ) { return hx::Val( set_color_dyn()); }
if (HX_FIELD_EQ(inName,"set_blend") ) { return hx::Val( set_blend_dyn()); }
if (HX_FIELD_EQ(inName,"set_width") ) { return hx::Val( set_width_dyn()); }
if (HX_FIELD_EQ(inName,"get_width") ) { return hx::Val( get_width_dyn()); }
if (HX_FIELD_EQ(inName,"set_frame") ) { return hx::Val( set_frame_dyn()); }
if (HX_FIELD_EQ(inName,"calcFrame") ) { return hx::Val( calcFrame_dyn()); }
break;
case 10:
if (HX_FIELD_EQ(inName,"isOnScreen") ) { return hx::Val( isOnScreen_dyn()); }
if (HX_FIELD_EQ(inName,"set_exists") ) { return hx::Val( set_exists_dyn()); }
if (HX_FIELD_EQ(inName,"set_active") ) { return hx::Val( set_active_dyn()); }
if (HX_FIELD_EQ(inName,"set_facing") ) { return hx::Val( set_facing_dyn()); }
if (HX_FIELD_EQ(inName,"set_height") ) { return hx::Val( set_height_dyn()); }
if (HX_FIELD_EQ(inName,"get_height") ) { return hx::Val( get_height_dyn()); }
if (HX_FIELD_EQ(inName,"get_length") ) { return hx::Val( get_length_dyn()); }
if (HX_FIELD_EQ(inName,"xTransform") ) { return hx::Val( xTransform_dyn()); }
if (HX_FIELD_EQ(inName,"yTransform") ) { return hx::Val( yTransform_dyn()); }
if (HX_FIELD_EQ(inName,"set_pixels") ) { return hx::Val( set_pixels_dyn()); }
if (HX_FIELD_EQ(inName,"get_pixels") ) { return hx::Val( get_pixels_dyn()); }
if (HX_FIELD_EQ(inName,"set_frames") ) { return hx::Val( set_frames_dyn()); }
break;
case 11:
if (HX_FIELD_EQ(inName,"countLiving") ) { return hx::Val( countLiving_dyn()); }
if (HX_FIELD_EQ(inName,"forEachDead") ) { return hx::Val( forEachDead_dyn()); }
if (HX_FIELD_EQ(inName,"setPosition") ) { return hx::Val( setPosition_dyn()); }
if (HX_FIELD_EQ(inName,"set_cameras") ) { return hx::Val( set_cameras_dyn()); }
if (HX_FIELD_EQ(inName,"set_visible") ) { return hx::Val( set_visible_dyn()); }
if (HX_FIELD_EQ(inName,"get_maxSize") ) { return hx::Val( get_maxSize_dyn()); }
if (HX_FIELD_EQ(inName,"set_maxSize") ) { return hx::Val( set_maxSize_dyn()); }
if (HX_FIELD_EQ(inName,"get_members") ) { return hx::Val( get_members_dyn()); }
if (HX_FIELD_EQ(inName,"loadGraphic") ) { return hx::Val( loadGraphic_dyn()); }
if (HX_FIELD_EQ(inName,"makeGraphic") ) { return hx::Val( makeGraphic_dyn()); }
break;
case 12:
if (HX_FIELD_EQ(inName,"replaceColor") ) { return hx::Val( replaceColor_dyn()); }
if (HX_FIELD_EQ(inName,"getFirstNull") ) { return hx::Val( getFirstNull_dyn()); }
if (HX_FIELD_EQ(inName,"getFirstDead") ) { return hx::Val( getFirstDead_dyn()); }
if (HX_FIELD_EQ(inName,"forEachAlive") ) { return hx::Val( forEachAlive_dyn()); }
if (HX_FIELD_EQ(inName,"resetHelpers") ) { return hx::Val( resetHelpers_dyn()); }
break;
case 13:
if (HX_FIELD_EQ(inName,"overlapsPoint") ) { return hx::Val( overlapsPoint_dyn()); }
if (HX_FIELD_EQ(inName,"getFirstAlive") ) { return hx::Val( getFirstAlive_dyn()); }
if (HX_FIELD_EQ(inName,"forEachExists") ) { return hx::Val( forEachExists_dyn()); }
if (HX_FIELD_EQ(inName,"forEachOfType") ) { return hx::Val( forEachOfType_dyn()); }
if (HX_FIELD_EQ(inName,"set_immovable") ) { return hx::Val( set_immovable_dyn()); }
if (HX_FIELD_EQ(inName,"scaleCallback") ) { return hx::Val( scaleCallback_dyn()); }
break;
case 14:
if (HX_FIELD_EQ(inName,"angleTransform") ) { return hx::Val( angleTransform_dyn()); }
if (HX_FIELD_EQ(inName,"alphaTransform") ) { return hx::Val( alphaTransform_dyn()); }
if (HX_FIELD_EQ(inName,"flipXTransform") ) { return hx::Val( flipXTransform_dyn()); }
if (HX_FIELD_EQ(inName,"flipYTransform") ) { return hx::Val( flipYTransform_dyn()); }
if (HX_FIELD_EQ(inName,"movesTransform") ) { return hx::Val( movesTransform_dyn()); }
if (HX_FIELD_EQ(inName,"blendTransform") ) { return hx::Val( blendTransform_dyn()); }
if (HX_FIELD_EQ(inName,"solidTransform") ) { return hx::Val( solidTransform_dyn()); }
if (HX_FIELD_EQ(inName,"aliveTransform") ) { return hx::Val( aliveTransform_dyn()); }
if (HX_FIELD_EQ(inName,"scaleTransform") ) { return hx::Val( scaleTransform_dyn()); }
if (HX_FIELD_EQ(inName,"offsetCallback") ) { return hx::Val( offsetCallback_dyn()); }
if (HX_FIELD_EQ(inName,"originCallback") ) { return hx::Val( originCallback_dyn()); }
break;
case 15:
if (HX_FIELD_EQ(inName,"facingTransform") ) { return hx::Val( facingTransform_dyn()); }
if (HX_FIELD_EQ(inName,"gColorTransform") ) { return hx::Val( gColorTransform_dyn()); }
if (HX_FIELD_EQ(inName,"activeTransform") ) { return hx::Val( activeTransform_dyn()); }
if (HX_FIELD_EQ(inName,"existsTransform") ) { return hx::Val( existsTransform_dyn()); }
if (HX_FIELD_EQ(inName,"offsetTransform") ) { return hx::Val( offsetTransform_dyn()); }
if (HX_FIELD_EQ(inName,"originTransform") ) { return hx::Val( originTransform_dyn()); }
break;
case 16:
if (HX_FIELD_EQ(inName,"getFirstExisting") ) { return hx::Val( getFirstExisting_dyn()); }
if (HX_FIELD_EQ(inName,"visibleTransform") ) { return hx::Val( visibleTransform_dyn()); }
if (HX_FIELD_EQ(inName,"camerasTransform") ) { return hx::Val( camerasTransform_dyn()); }
break;
case 17:
if (HX_FIELD_EQ(inName,"getFirstAvailable") ) { return hx::Val( getFirstAvailable_dyn()); }
break;
case 18:
if (HX_FIELD_EQ(inName,"pixelsOverlapPoint") ) { return hx::Val( pixelsOverlapPoint_dyn()); }
if (HX_FIELD_EQ(inName,"immovableTransform") ) { return hx::Val( immovableTransform_dyn()); }
if (HX_FIELD_EQ(inName,"loadRotatedGraphic") ) { return hx::Val( loadRotatedGraphic_dyn()); }
break;
case 20:
if (HX_FIELD_EQ(inName,"scrollFactorCallback") ) { return hx::Val( scrollFactorCallback_dyn()); }
if (HX_FIELD_EQ(inName,"updateColorTransform") ) { return hx::Val( updateColorTransform_dyn()); }
break;
case 21:
if (HX_FIELD_EQ(inName,"transformChildren_Int") ) { return hx::Val( transformChildren_Int_dyn()); }
if (HX_FIELD_EQ(inName,"pixelPerfectTransform") ) { return hx::Val( pixelPerfectTransform_dyn()); }
if (HX_FIELD_EQ(inName,"scrollFactorTransform") ) { return hx::Val( scrollFactorTransform_dyn()); }
if (HX_FIELD_EQ(inName,"loadGraphicFromSprite") ) { return hx::Val( loadGraphicFromSprite_dyn()); }
break;
case 22:
if (HX_FIELD_EQ(inName,"transformChildren_Bool") ) { return hx::Val( transformChildren_Bool_dyn()); }
if (HX_FIELD_EQ(inName,"_skipTransformChildren") ) { return hx::Val( _skipTransformChildren); }
if (HX_FIELD_EQ(inName,"set_pixelPerfectRender") ) { return hx::Val( set_pixelPerfectRender_dyn()); }
break;
case 23:
if (HX_FIELD_EQ(inName,"transformChildren_Float") ) { return hx::Val( transformChildren_Float_dyn()); }
break;
case 28:
if (HX_FIELD_EQ(inName,"multiTransformChildren_Float") ) { return hx::Val( multiTransformChildren_Float_dyn()); }
break;
case 38:
if (HX_FIELD_EQ(inName,"transformChildren_flixel_math_FlxPoint") ) { return hx::Val( transformChildren_flixel_math_FlxPoint_dyn()); }
break;
case 40:
if (HX_FIELD_EQ(inName,"transformChildren_Array_flixel_FlxCamera") ) { return hx::Val( transformChildren_Array_flixel_FlxCamera_dyn()); }
break;
case 50:
if (HX_FIELD_EQ(inName,"transformChildren_openfl__legacy_display_BlendMode") ) { return hx::Val( transformChildren_openfl__legacy_display_BlendMode_dyn()); }
}
return super::__Field(inName,inCallProp);
}
hx::Val FlxTypedSpriteGroup_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"group") ) { group=inValue.Cast< ::flixel::group::FlxTypedGroup >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"length") ) { length=inValue.Cast< Int >(); return inValue; }
break;
case 7:
if (HX_FIELD_EQ(inName,"members") ) { members=inValue.Cast< ::cpp::VirtualArray >(); return inValue; }
if (HX_FIELD_EQ(inName,"maxSize") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_maxSize(inValue) ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"_sprites") ) { _sprites=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; }
break;
case 22:
if (HX_FIELD_EQ(inName,"_skipTransformChildren") ) { _skipTransformChildren=inValue.Cast< Bool >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void FlxTypedSpriteGroup_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("group","\x3f","\xb3","\xf4","\x99"));
outFields->push(HX_HCSTRING("members","\xd9","\x2c","\x70","\x1a"));
outFields->push(HX_HCSTRING("length","\xe6","\x94","\x07","\x9f"));
outFields->push(HX_HCSTRING("maxSize","\x85","\xf9","\x83","\xcc"));
outFields->push(HX_HCSTRING("_skipTransformChildren","\x8d","\x52","\xb5","\x7c"));
outFields->push(HX_HCSTRING("_sprites","\x4f","\x02","\x43","\x99"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo FlxTypedSpriteGroup_obj_sMemberStorageInfo[] = {
{hx::fsObject /*::flixel::group::FlxTypedGroup*/ ,(int)offsetof(FlxTypedSpriteGroup_obj,group),HX_HCSTRING("group","\x3f","\xb3","\xf4","\x99")},
{hx::fsObject /*cpp::ArrayBase*/ ,(int)offsetof(FlxTypedSpriteGroup_obj,members),HX_HCSTRING("members","\xd9","\x2c","\x70","\x1a")},
{hx::fsInt,(int)offsetof(FlxTypedSpriteGroup_obj,length),HX_HCSTRING("length","\xe6","\x94","\x07","\x9f")},
{hx::fsBool,(int)offsetof(FlxTypedSpriteGroup_obj,_skipTransformChildren),HX_HCSTRING("_skipTransformChildren","\x8d","\x52","\xb5","\x7c")},
{hx::fsObject /*Array< ::Dynamic >*/ ,(int)offsetof(FlxTypedSpriteGroup_obj,_sprites),HX_HCSTRING("_sprites","\x4f","\x02","\x43","\x99")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *FlxTypedSpriteGroup_obj_sStaticStorageInfo = 0;
#endif
static ::String FlxTypedSpriteGroup_obj_sMemberFields[] = {
HX_HCSTRING("transformChildren_openfl__legacy_display_BlendMode","\xe5","\x33","\xca","\x25"),
HX_HCSTRING("transformChildren_Int","\x1b","\x1a","\x96","\x58"),
HX_HCSTRING("transformChildren_Float","\xc8","\x75","\x5b","\x82"),
HX_HCSTRING("transformChildren_Bool","\x7e","\xfd","\x20","\x26"),
HX_HCSTRING("transformChildren_Array_flixel_FlxCamera","\xae","\x0c","\xc0","\xd3"),
HX_HCSTRING("multiTransformChildren_Float","\x4f","\x02","\xe4","\x0f"),
HX_HCSTRING("transformChildren_flixel_math_FlxPoint","\x06","\x0c","\xc3","\x75"),
HX_HCSTRING("group","\x3f","\xb3","\xf4","\x99"),
HX_HCSTRING("members","\xd9","\x2c","\x70","\x1a"),
HX_HCSTRING("length","\xe6","\x94","\x07","\x9f"),
HX_HCSTRING("_skipTransformChildren","\x8d","\x52","\xb5","\x7c"),
HX_HCSTRING("_sprites","\x4f","\x02","\x43","\x99"),
HX_HCSTRING("initVars","\xdc","\x5a","\x00","\x53"),
HX_HCSTRING("destroy","\xfa","\x2c","\x86","\x24"),
HX_HCSTRING("clone","\x5d","\x13","\x63","\x48"),
HX_HCSTRING("isOnScreen","\xf5","\x43","\xb9","\xa1"),
HX_HCSTRING("overlapsPoint","\xa4","\xc5","\xbd","\x35"),
HX_HCSTRING("pixelsOverlapPoint","\x16","\x82","\x44","\xe0"),
HX_HCSTRING("update","\x09","\x86","\x05","\x87"),
HX_HCSTRING("draw","\x04","\x2c","\x70","\x42"),
HX_HCSTRING("replaceColor","\x8f","\x5c","\xeb","\x3d"),
HX_HCSTRING("add","\x21","\xf2","\x49","\x00"),
HX_HCSTRING("recycle","\x13","\x10","\x8c","\x37"),
HX_HCSTRING("remove","\x44","\x9c","\x88","\x04"),
HX_HCSTRING("replace","\x34","\x48","\x28","\xab"),
HX_HCSTRING("sort","\x5e","\x27","\x58","\x4c"),
HX_HCSTRING("getFirstAvailable","\xaf","\xea","\xb3","\x05"),
HX_HCSTRING("getFirstNull","\x61","\xb7","\x33","\x0f"),
HX_HCSTRING("getFirstExisting","\x65","\xa4","\x6c","\xee"),
HX_HCSTRING("getFirstAlive","\xb3","\x09","\xe2","\xbb"),
HX_HCSTRING("getFirstDead","\x7e","\x67","\x8b","\x08"),
HX_HCSTRING("countLiving","\x58","\xd9","\x8a","\x30"),
HX_HCSTRING("countDead","\x13","\xd3","\x86","\x54"),
HX_HCSTRING("getRandom","\x39","\xab","\xe5","\x33"),
HX_HCSTRING("iterator","\xee","\x49","\x9a","\x93"),
HX_HCSTRING("forEach","\xaa","\x29","\xbe","\xc4"),
HX_HCSTRING("forEachAlive","\xc3","\x61","\xb7","\x99"),
HX_HCSTRING("forEachDead","\x6e","\xc1","\xe4","\x78"),
HX_HCSTRING("forEachExists","\x26","\x57","\xf8","\x68"),
HX_HCSTRING("forEachOfType","\xbb","\x90","\x76","\xfd"),
HX_HCSTRING("clear","\x8d","\x71","\x5b","\x48"),
HX_HCSTRING("kill","\x9e","\xdf","\x09","\x47"),
HX_HCSTRING("revive","\x55","\xfa","\x76","\x0a"),
HX_HCSTRING("reset","\xcf","\x49","\xc8","\xe6"),
HX_HCSTRING("setPosition","\x6b","\x6a","\x5b","\xfb"),
HX_HCSTRING("set_cameras","\x51","\xf1","\x98","\x73"),
HX_HCSTRING("set_exists","\x19","\x2c","\xe5","\xb3"),
HX_HCSTRING("set_visible","\x95","\xdf","\x8b","\x33"),
HX_HCSTRING("set_active","\x03","\x50","\x4b","\x0a"),
HX_HCSTRING("set_alive","\x30","\xac","\x8b","\x48"),
HX_HCSTRING("set_x","\x5b","\x9b","\x2f","\x7a"),
HX_HCSTRING("set_y","\x5c","\x9b","\x2f","\x7a"),
HX_HCSTRING("set_angle","\x36","\x8c","\xdc","\x49"),
HX_HCSTRING("set_alpha","\xc1","\xef","\x90","\x48"),
HX_HCSTRING("set_facing","\x57","\x4d","\x0a","\xd8"),
HX_HCSTRING("set_flipX","\x6e","\x8d","\x8c","\x29"),
HX_HCSTRING("set_flipY","\x6f","\x8d","\x8c","\x29"),
HX_HCSTRING("set_moves","\xa5","\x14","\x60","\x33"),
HX_HCSTRING("set_immovable","\xed","\xdc","\xd9","\x2d"),
HX_HCSTRING("set_solid","\x8e","\xfc","\xbf","\xa7"),
HX_HCSTRING("set_color","\xc6","\xb9","\x56","\x71"),
HX_HCSTRING("set_blend","\xb4","\x30","\xef","\xdb"),
HX_HCSTRING("set_pixelPerfectRender","\x9a","\x4f","\x8f","\xbc"),
HX_HCSTRING("set_width","\x69","\xfe","\x5c","\xf1"),
HX_HCSTRING("get_width","\x5d","\x12","\x0c","\x0e"),
HX_HCSTRING("set_height","\x24","\x16","\x51","\xf6"),
HX_HCSTRING("get_height","\xb0","\x77","\xd3","\xf2"),
HX_HCSTRING("get_length","\xaf","\x04","\x8f","\x8f"),
HX_HCSTRING("get_maxSize","\x9c","\x59","\x7e","\x52"),
HX_HCSTRING("set_maxSize","\xa8","\x60","\xeb","\x5c"),
HX_HCSTRING("get_members","\xf0","\x8c","\x6a","\xa0"),
HX_HCSTRING("xTransform","\xd4","\x3d","\x4e","\x0a"),
HX_HCSTRING("yTransform","\xb3","\xb5","\x98","\xca"),
HX_HCSTRING("angleTransform","\x19","\x37","\x04","\x53"),
HX_HCSTRING("alphaTransform","\x2e","\x8a","\x9a","\x12"),
HX_HCSTRING("facingTransform","\xf2","\x1a","\xd1","\xb5"),
HX_HCSTRING("flipXTransform","\xe1","\x4e","\x16","\x58"),
HX_HCSTRING("flipYTransform","\xc0","\xc6","\x60","\x18"),
HX_HCSTRING("movesTransform","\xca","\xa8","\x19","\x91"),
HX_HCSTRING("pixelPerfectTransform","\x45","\xcd","\x91","\xea"),
HX_HCSTRING("gColorTransform","\x50","\xb2","\xd2","\x48"),
HX_HCSTRING("blendTransform","\xdb","\x12","\x24","\x48"),
HX_HCSTRING("immovableTransform","\x02","\xb5","\x21","\x2d"),
HX_HCSTRING("visibleTransform","\x9a","\xf6","\x1b","\x49"),
HX_HCSTRING("activeTransform","\xc6","\x62","\x68","\x7a"),
HX_HCSTRING("solidTransform","\xc1","\xfb","\xcb","\x4e"),
HX_HCSTRING("aliveTransform","\xdf","\x47","\xb2","\x53"),
HX_HCSTRING("existsTransform","\xf0","\x53","\x19","\xdb"),
HX_HCSTRING("camerasTransform","\x5e","\xcd","\x14","\x48"),
HX_HCSTRING("offsetTransform","\x59","\x6b","\xbe","\x5e"),
HX_HCSTRING("originTransform","\xa6","\x86","\xe1","\xbc"),
HX_HCSTRING("scaleTransform","\x82","\x1d","\x72","\x79"),
HX_HCSTRING("scrollFactorTransform","\x10","\xa9","\xe8","\x16"),
HX_HCSTRING("offsetCallback","\x78","\x38","\x86","\x15"),
HX_HCSTRING("originCallback","\xcb","\xc5","\xde","\x24"),
HX_HCSTRING("scaleCallback","\x6f","\xbe","\x27","\x48"),
HX_HCSTRING("scrollFactorCallback","\xa1","\x5e","\x9d","\xf1"),
HX_HCSTRING("loadGraphicFromSprite","\xd1","\x7c","\x73","\x38"),
HX_HCSTRING("loadGraphic","\x22","\x19","\xa5","\x44"),
HX_HCSTRING("loadRotatedGraphic","\xc5","\x14","\x74","\x62"),
HX_HCSTRING("makeGraphic","\x5a","\x82","\x11","\xb8"),
HX_HCSTRING("set_pixels","\x6a","\xfd","\xae","\x80"),
HX_HCSTRING("set_frame","\x90","\xc0","\x7d","\x2d"),
HX_HCSTRING("get_pixels","\xf6","\x5e","\x31","\x7d"),
HX_HCSTRING("calcFrame","\x58","\x93","\x8c","\xf9"),
HX_HCSTRING("resetHelpers","\x36","\x89","\x3d","\x32"),
HX_HCSTRING("stamp","\x03","\x70","\x0b","\x84"),
HX_HCSTRING("set_frames","\xe3","\xbd","\x8a","\xa0"),
HX_HCSTRING("updateColorTransform","\x72","\x0f","\xd2","\x2f"),
::String(null()) };
static void FlxTypedSpriteGroup_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(FlxTypedSpriteGroup_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void FlxTypedSpriteGroup_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(FlxTypedSpriteGroup_obj::__mClass,"__mClass");
};
#endif
hx::Class FlxTypedSpriteGroup_obj::__mClass;
void FlxTypedSpriteGroup_obj::__register()
{
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("flixel.group.FlxTypedSpriteGroup","\xe1","\xd1","\x86","\xf9");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = FlxTypedSpriteGroup_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(FlxTypedSpriteGroup_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< FlxTypedSpriteGroup_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = FlxTypedSpriteGroup_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = FlxTypedSpriteGroup_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = FlxTypedSpriteGroup_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace flixel
} // end namespace group
| [
"azlen@livingcode.org"
] | azlen@livingcode.org |
61f150e40f02cfaad57a55e21928151a04dd6b4f | ce18cf6bdb1a85a65a509597b4c0ec046b855186 | /斐波那契数.cpp | 9e7b3db09149123cea52e01ee33a5588ea9bb222 | [] | no_license | elssm/leetcode | e12e39faff1da5afb234be08e7d9db85fbee58f8 | a38103d2d93b34bc8bcf09f87c7ea698f99c4e36 | refs/heads/master | 2021-06-11T06:44:44.993905 | 2021-04-28T06:14:23 | 2021-04-28T06:14:23 | 171,072,054 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 160 | cpp | #include<stdio.h>
int fib(int N) {
if(N<=1)
return N;
else
return fib(N-1)+fib(N-2);
}
int main(void){
int t=10;
int s=fib(t);
printf("%d\n",s);
}
| [
"329847986@qq.com"
] | 329847986@qq.com |
9a54907fb8bb5314c0402b819e8afd130c13851b | 4a19b7c7c3f06fb166d6f8ba3c08ac10cf20c601 | /Source/HeadsUpDisplay.cpp | ab40dbd70e02a57e21ef5acd4897d80fbf8bdcb9 | [
"MIT"
] | permissive | Trevor-Dych/The-God-Core | f3c6dd99cdb5acfab104c7147607837075e7d367 | 29b40cba0eab0608acd3ff6a4aff3435a2f71471 | refs/heads/master | 2021-01-18T05:17:25.077372 | 2015-09-09T23:03:56 | 2015-09-09T23:03:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,676 | cpp | /*************************************************************\
* HeadsUpDisplay.cpp *
* This file was created by Jeremy Greenburg *
* As part of The God Core game for the University of *
* Tennessee at Martin's University Scholars Organization *
* *
* This file contains the definition of the HeadsUpDisplay *
* Class. For more information, see HeadsUpDisplay.h *
\*************************************************************/
// Class Declaration
#include "HeadsUpDisplay.h"
// OpenGL API
#include <gl\glew.h>
#include <gl\glut.h>
// For counting seconds
#include <ctime>
// For displaying Rectangles
#include "Rectangle.h"
// For displaying triangles
#include "Triangle.h"
using namespace std;
void HeadsUpDisplay::prepare2D()
{
// Disable writing to the z buffer
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
// Disables lighting
glDisable(GL_LIGHTING);
// Create an orthogonal matrix to write on
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(SCREENTOP, SCREENBOTTOM, SCREENRIGHT, SCREENLEFT, -1, 1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
}
void HeadsUpDisplay::prepare3D()
{
// Discards the orthogonal matrices
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
// Enables writing to the z buffer
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
// Renable lighting
glEnable(GL_LIGHTING);
}
void HeadsUpDisplay::drawHelmetBounds()
{
// Helmet bounds are black
float colors[4] = { 0, 0, 0, 1 };
// The top of the helmet
float top_vertices[9] =
{
SCREENRIGHT / 5, SCREENTOP, -1,
SCREENRIGHT / 2, 30, -1,
4 * SCREENRIGHT / 5, SCREENTOP, -1
};
// The left of the hemlet
float left_vertices[9] =
{
SCREENLEFT, SCREENBOTTOM, -1,
SCREENLEFT, SCREENBOTTOM / 2, -1,
SCREENRIGHT / 20, 3 * SCREENBOTTOM / 4, -1
};
// The back of the helmet
float right_vertices[9] =
{
SCREENRIGHT, SCREENBOTTOM, -1,
SCREENRIGHT, SCREENBOTTOM / 2, -1,
19 * SCREENRIGHT / 20, 3 * SCREENBOTTOM / 4, -1
};
Triangle top_helm{ top_vertices, colors };
Triangle left_helm{ left_vertices, colors };
Triangle right_helm{ right_vertices, colors };
top_helm.Display2D();
left_helm.Display2D();
right_helm.Display2D();
}
void HeadsUpDisplay::DisplayAlerts()
{
helmet.openFile(.5 * SCREENRIGHT, .5 * SCREENBOTTOM,
1, 1, 1,
"suitAlerts.log", currentAlert);
}
void HeadsUpDisplay::dim()
{
static int startTime;
static bool timeSet = false;
if (dimNow)
{
if (!timeSet)
{
startTime = time(NULL);
timeSet = true;
}
int currentTime = time(NULL);
int timeElapsed = currentTime - startTime;
if (timeElapsed < dimTime)
{
// A black square that grows more transparent as time passes
float colors[4] = { 0, 0, 0, (float)(dimTime - timeElapsed) / dimTime };
float dimVert[12] =
{
SCREENLEFT, SCREENTOP, -1,
SCREENLEFT, SCREENBOTTOM, -1,
SCREENRIGHT, SCREENBOTTOM, -1,
SCREENRIGHT, SCREENTOP, -1
};
Rectangle black{ dimVert, colors };
black.Display2D();
}
else
{
dimNow = false;
timeSet = false;
}
}
}
void HeadsUpDisplay::dark()
{
static int startTime;
static bool timeSet = false;
if (darkNow)
{
if (!timeSet)
{
startTime = time(NULL);
timeSet = true;
}
int currentTime = time(NULL);
int timeElapsed = currentTime - startTime;
if (timeElapsed < darkTime)
{
// A black square that obscures vision
float colors[4] = { 0, 0, 0, 1 };
float dimVert[12] =
{
SCREENLEFT, SCREENTOP, -1,
SCREENLEFT, SCREENBOTTOM, -1,
SCREENRIGHT, SCREENBOTTOM, -1,
SCREENRIGHT, SCREENTOP, -1
};
Rectangle black{ dimVert, colors };
black.Display2D();
}
else
{
darkNow = false;
timeSet = false;
}
}
}
void HeadsUpDisplay::drawConsole()
{
float colors[4] = { .1, .1, .1, .9 };
float vertices[12] =
{
SCREENLEFT, SCREENTOP, -1,
SCREENLEFT, SCREENBOTTOM / 5, -1,
SCREENRIGHT, SCREENBOTTOM / 5, -1,
SCREENRIGHT, SCREENTOP, -1
};
Rectangle console_tab{ vertices, colors };
console_tab.Display2D();
if (currentInput != "")
{
dev.activate(currentInput, currentText);
currentInput.clear();
}
else
{
dev.activate(currentText);
}
}
void HeadsUpDisplay::drawInfoBox()
{
float colors[4] = { 0, 1, 1, .5 };
float vertices[12] =
{
SCREENLEFT, SCREENTOP, -1,
SCREENLEFT, 40, -1,
50, 40, -1,
50, SCREENTOP, -1
};
Rectangle info{ vertices, colors };
info.Display2D();
}
void HeadsUpDisplay::displayInfo(char* tag)
{
helmet.openFile(SCREENLEFT, SCREENTOP + 10, 1, 1, 1,
"suitAlerts.log", "INFO-WELL");
}
void HeadsUpDisplay::goDim(int time)
{
dimTime = time;
dimNow = true;
}
void HeadsUpDisplay::goDark(int time)
{
darkTime = time;
darkNow = true;
}
void HeadsUpDisplay::displayWarning(std::string warning)
{
currentAlert = warning;
}
void HeadsUpDisplay::printToConsole(std::string text)
{
currentText = text;
}
void HeadsUpDisplay::inputString(std::string text)
{
currentInput = text;
}
void HeadsUpDisplay::toggleConsole()
{
devConsole = !devConsole;
}
void HeadsUpDisplay::drawHUD()
{
drawHelmetBounds();
if (dimNow)
{
dim();
}
else if (darkNow)
{
dark();
}
drawInfoBox();
displayInfo("SUIT-WELL");
if (devConsole)
{
drawConsole();
}
if (currentAlert != "")
{
DisplayAlerts();
}
}
string HeadsUpDisplay::getHist(int count)
{
return dev.getHist(count);
}
int HeadsUpDisplay::getHistNum()
{
return dev.getHistNum();
}
void HeadsUpDisplay::DisplayHUD()
{
prepare2D();
drawHUD();
prepare3D();
} | [
"jrggb@yahoo.com"
] | jrggb@yahoo.com |
19964d9c87feea7f93783576bcf9e3220b9fdd51 | e7be6f7963140443172518f8e0fd2a89056df3f7 | /cocos2dx-store/Soomla/data/CCVirtualCurrencyStorage.cpp | 1fdbfa0c7065fe0807fd9ac43d71799c690df44e | [
"Apache-2.0"
] | permissive | iscoolent/soomla-bundle | 1a0e9dd8a6e64a032e1370078b68a2f17cd09d86 | 75e5da7fc1c44d7bc4f75a9eb55aca6ac23ad341 | refs/heads/master | 2022-12-08T06:27:19.271918 | 2020-08-28T15:05:56 | 2020-08-28T16:37:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,497 | cpp | /*
Copyright (C) 2012-2014 Soomla Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "data/CCVirtualCurrencyStorage.h"
#include "CCStoreEventDispatcher.h"
#include "CCSoomlaUtils.h"
#include "NativeImpl/CCNativeVirtualCurrencyStorage.h"
namespace soomla {
#define TAG "SOOMLA VirtualCurrencyStorage"
static CCVirtualCurrencyStorage *s_SharedVirtualCurrencyStorage = NULL;
CCVirtualCurrencyStorage *CCVirtualCurrencyStorage::getInstance() {
if (!s_SharedVirtualCurrencyStorage)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
s_SharedVirtualCurrencyStorage = new CCNativeVirtualCurrencyStorage();
#else
s_SharedVirtualCurrencyStorage = new CCVirtualCurrencyStorage();
#endif
// s_SharedVirtualCurrencyStorage->retain();
}
return s_SharedVirtualCurrencyStorage;
}
CCVirtualCurrencyStorage::CCVirtualCurrencyStorage() {
}
CCVirtualCurrencyStorage::~CCVirtualCurrencyStorage() {
}
const char* CCVirtualCurrencyStorage::keyBalance(const char *itemId) const {
return keyCurrencyBalance(itemId);
}
void CCVirtualCurrencyStorage::postBalanceChangeEvent(CCVirtualItem *item, int balance, int amountAdded) {
CCVirtualCurrency *virtualCurrency = dynamic_cast<CCVirtualCurrency *>(item);
if (virtualCurrency == NULL) {
CCSoomlaUtils::logError(TAG, cocos2d::__String::createWithFormat("Trying to post currency balance changed with a non VirtualCurrency item %s", item->getId()->getCString())->getCString());
return;
}
CCStoreEventDispatcher::getInstance()->onCurrencyBalanceChanged(virtualCurrency, balance, amountAdded);
}
const char *CCVirtualCurrencyStorage::keyCurrencyBalance(const char *itemId) {
return cocos2d::__String::createWithFormat("currency.%s.balance", itemId)->getCString();
}
#undef TAG
}
| [
"julien.jorge@stuff-o-matic.com"
] | julien.jorge@stuff-o-matic.com |
1d0ec7ad0ceaaf0cef3b0e73f53a924f7e4ad43b | 1490797b49fbadcdc17d6ebf4463535e3aee55f4 | /JS16_Bootloader/src/ApplicationFiles.cpp | 485ad58469da326c8f10c70dda16f0a68fb1f03a | [] | no_license | qiaozhou/usbdm-applications | 23347aa7a0aa101ac4cd30d88d4ce59f30de5c41 | 596a2a217f2ccc156890aa60540ec4423532e302 | refs/heads/master | 2020-05-20T09:46:38.162826 | 2012-08-20T00:20:02 | 2012-08-20T00:20:02 | 5,520,103 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,808 | cpp | /*! \file
\brief Provides Access to Application files
ApplicationFiles.cpp
\verbatim
USBDM
Copyright (C) 2009 Peter O'Donoghue
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\endverbatim
\verbatim
Change History
-================================================================================
| 16 Nov 2009 | Changes to allow wxWidgets dependencies to be localised - pgo
+-------------+------------------------------------------------------------------
| 16 Nov 2009 | Created - pgo
+================================================================================
\endverbatim
*/
#include <stdio.h>
#include <sys/stat.h>
#include "ICP.h"
#ifdef useWxWidgets
#include <wx/wx.h>
#include <wx/stdpaths.h>
#include <wx/filename.h>
#ifdef _WIN32
#include <wx/msw/registry.h>
#endif
#else
#include "wxPlugin.h"
#endif
#include "Log.h"
#include "Common.h"
#include "ApplicationFiles.h"
using namespace std;
#ifdef _WIN32
string getInstallationDir(void) {
#ifdef useWxWidgets
wxString path;
wxRegKey key(wxRegKey::HKLM, "Software\\pgo\\USBDM");
if (key.Exists() && key.QueryValue("InstallationDirectory", path))
return string(path.c_str());
return string();
#else
char buff[1000];
getInstallationDir(buff, sizeof(buff));
return string(buff);
#endif
}
#endif
string getDataDir(void) {
#ifdef useWxWidgets
return string(wxStandardPaths::Get().GetDataDir().ToAscii());
#else
char buff[1000];
getDataDir(buff, sizeof(buff));
return string(buff);
#endif
}
string getUserDataDir(void) {
#ifdef useWxWidgets
return string(wxStandardPaths::Get().GetUserDataDir().ToAscii());
#else
char buff[1000];
getUserDataDir(buff, sizeof(buff));
return string(buff);
#endif
}
#ifdef useWxWidgets
char getPathSeparator(void) {
return (char)(wxFileName::GetPathSeparator());
}
#endif
#ifdef WIN32
bool fileExists(string filePath) {
DWORD attrib = GetFileAttributesA(filePath.c_str());
print("fileExists(%s) => attr=%X\n", filePath.c_str(), attrib);
return (attrib != INVALID_FILE_ATTRIBUTES) &&
((attrib & FILE_ATTRIBUTE_DIRECTORY) == 0);
}
bool dirExists(string filePath) {
DWORD attrib = GetFileAttributesA(filePath.c_str());
return (attrib != INVALID_FILE_ATTRIBUTES) &&
((attrib & FILE_ATTRIBUTE_DIRECTORY) != 0);
}
#else
bool fileExists(string strFilename) {
struct stat stFileInfo;
int intStat;
// Attempt to get the file attributes
intStat = stat(strFilename.c_str(),&stFileInfo);
return ((intStat == 0) && S_ISREG(stFileInfo.st_mode));
}
bool dirExists(string filePath) {
struct stat stFileInfo;
int intStat;
// Attempt to get the file attributes
intStat = stat(filePath.c_str(),&stFileInfo);
return ((intStat == 0) && S_ISDIR(stFileInfo.st_mode));
}
#endif
//! Opens configuration file
//!
//! @param filename - Name of file (without path)
//! @param attributes - Attributes to use when opening the file.
//! This should be one of "r", "w", "rt" or "wt"
//!
//! @return file handle or NULL on error
//!
//! @note Attempts to open readonly files from two locations:
//! - Application directory (where the .exe is)
//! - Application data directory (e.g. %APPDATA%/usbdm, $HOME/.usbdm)
//! Files opened for writing only use the last directory.
//!
FILE *openApplicationFile(const string &filename, const string &attributes) {
string configFilePath;
FILE *configFile = NULL;
// Try the Executable directory for readonly files
if (attributes[0] == 'r') {
configFilePath = getDataDir();
if (!configFilePath.empty()) {
// Append filename
configFilePath += getPathSeparator() + filename;
// Open the file
configFile = fopen(configFilePath.c_str(), attributes.c_str());
}
}
#ifdef WIN32
// Try the Path indicated by registry key if necessary
if ((attributes[0] == 'r') && (configFile == NULL )) {
configFilePath = getInstallationDir();
// fprintf(stderr, "openApplicationFile() - \"%s\"\n", (const char *)configFilePath.ToAscii());
if (!configFilePath.empty()) {
// Append filename
configFilePath += filename;
// Open the file
configFile = fopen(configFilePath.c_str(), attributes.c_str());
}
}
#endif
// Try the Application Data directory if necessary
if (configFile == NULL ) {
configFilePath = getUserDataDir();
// fprintf(stderr, "openApplicationFile() - \"%s\"\n", (const char *)configFilePath.ToAscii());
if (!configFilePath.empty()) {
if (!dirExists(configFilePath)) {
// Doesn't exist - create it
#ifdef WIN32
mkdir(configFilePath.c_str());
#else
mkdir(configFilePath.c_str(), S_IRWXU|S_IRWXG|S_IRWXO);
#endif
}
// Append filename
configFilePath += getPathSeparator() + filename;
// Open the file
configFile = fopen(configFilePath.c_str(), attributes.c_str());
}
}
if (configFile != NULL) {
print("openApplicationFile() - Opened \'%s\'\n", configFilePath.c_str());
}
return configFile;
}
//! Check for existence of a configuration file
//!
//! @param filename - Name of file (without path)
//! @param attributes - Attributes to use when opening the file.
//! This should be one of "r", "w", "rt" or "wt"
//!
//! @return ICP_RC_OK if file exists
//!
//! @note Attempts to locate the file in two locations:
//! - Application data directory (e.g. %APPDATA%/usbdm, $HOME/.usbdm)
//! - Application directory (where the .exe is)
//!
int checkExistsApplicationFile(const string &filename, const string &attributes) {
string configFilePath;
// Try the Executable directory for readonly files
if (attributes[0] == 'r') {
configFilePath = getDataDir() + getPathSeparator() + filename;
if (fileExists(configFilePath))
return ICP_RC_OK;
}
#ifdef WIN32
// Try the Path indicated by registry key if necessary
if (attributes[0] == 'r') {
configFilePath = getInstallationDir();
// fprintf(stderr, "openApplicationFile() - \"%s\"\n", (const char *)configFilePath.ToAscii());
if (!configFilePath.empty()) {
// Append filename
configFilePath += filename;
if (fileExists(configFilePath))
return ICP_RC_OK;
}
}
#endif
// Try the Application Data directory
configFilePath = getUserDataDir() + getPathSeparator() + filename;;
if (fileExists(configFilePath))
return ICP_RC_OK;
return ICP_RC_FILE_NOT_FOUND;
}
//! Returns the path to a configuration file
//!
//! @param filename - Name of file (without path)
//! @param attributes - Attributes to use when opening the file.
//! This should be one of "r", "w", "rt" or "wt"
//!
//! @return ICP_RC_OK if file exists
//!
//! @note Attempts to locate the file in two locations:
//! - Application data directory (e.g. %APPDATA%/usbdm, $HOME/.usbdm)
//! - Application directory (where the .exe is)
//!
string getApplicationFilePath(const string &filename, const string &attributes) {
string configFilePath;
// Try the Executable directory for readonly files
if (attributes[0] == 'r') {
configFilePath = getDataDir() + getPathSeparator() + filename;
print("getApplicationFilePath() - trying %s\n", configFilePath.c_str());
if (fileExists(configFilePath))
return configFilePath;
}
#ifdef WIN32
// Try the Path indicated by registry key if necessary
if (attributes[0] == 'r') {
configFilePath = getInstallationDir()+ filename;
print("getApplicationFilePath() - trying %s\n", configFilePath.c_str());
if (fileExists(configFilePath))
return configFilePath;
}
#endif
// Try the Application Data directory
configFilePath = getUserDataDir() + getPathSeparator() + filename;;
print("getApplicationFilePath() - trying %s\n", configFilePath.c_str());
if (fileExists(configFilePath))
return configFilePath;
return string();
}
| [
"podonoghue@swin.edu.au"
] | podonoghue@swin.edu.au |
075a2e8d7835c3556d1b659589404e319b1f281d | 198ab1db1be319ca3b1438cee13483bdb06e752f | /tags/iris-0.1.17/src/core/AcceptSignalWatcher.cpp | 4d70a9db65f971dc8e8304681cec91a58835b04e | [] | no_license | CommunicoPublic/iris | b11b366e244707d017ff55d6c952b7247d5ea1dc | b412f5db97ba7305f0b946e628709c1c6f976953 | refs/heads/master | 2020-05-30T10:04:24.953824 | 2015-06-30T10:02:39 | 2015-06-30T10:02:39 | 26,064,979 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,123 | cpp | /*-
* Copyright (c) Iris Dev. team. All rights reserved.
* See http://www.communico.pro/license for details.
*
*/
#include "AcceptSignalWatcher.hpp"
#include "AcceptLoopContext.hpp"
#include "GlobalContext.hpp"
#include "Logger.hpp"
#include "MainLoopContext.hpp"
#include "NetworkHandler.hpp"
#include "NetworkEventWatcher.hpp"
#include "ServiceConfig.hpp"
#include "ServerClientTCPSSLSocket.hpp"
namespace IRIS
{
//
// Constructor
//
AcceptSignalWatcher::AcceptSignalWatcher(AcceptLoopContext * pIContext): IOAsyncWatcher(&(pIContext -> thread_loop)),
pContext(pIContext)
{
StartWatch();
}
#ifdef IRIS_TLS_SUPPORT
//
// Setup SSL
//
INT_32 AcceptSignalWatcher::SetupSSL()
{
STLW::vector<ServiceConfig> & oServiceConfig = pContext -> main_context.global_context.config.services;
STLW::vector<ServiceConfig>::iterator itvServices = oServiceConfig.begin();
while (itvServices != oServiceConfig.end())
{
// Check for SSL support
if (itvServices -> enable_ssl_tls)
{
SSL_CTX * pSSLContext = NULL;
for (UINT_32 iPos = 0; iPos < itvServices -> tls_cert_file.size(); ++iPos)
{
pContext -> main_context.global_context.error_log -> Debug("Adding certificate { `%s` `%s` } for service `%s`",
itvServices -> tls_cert_file[iPos].c_str(),
itvServices -> tls_key_file[iPos].c_str(),
itvServices -> name.c_str());
pSSLContext = oSSLCore.AddContext(itvServices -> tls_cert_file[iPos],
itvServices -> tls_key_file[iPos],
itvServices -> dh_file,
itvServices -> ciphers,
itvServices -> name,
itvServices -> use_tls,
itvServices -> prefer_server_ciphers,
*(pContext -> main_context.global_context.error_log));
if (pSSLContext == NULL)
{
pContext -> main_context.global_context.error_log -> Error("Setup of SSL/TLS data for service `%s` aborted", itvServices -> name.c_str());
return -1;
}
}
mSSLServiceMap[itvServices -> name] = pSSLContext;
}
++itvServices;
}
return 0;
}
#endif // IRIS_TLS_SUPPORT
//
// Watcher callback
//
void AcceptSignalWatcher::Callback(const UINT_32 iREvents)
{
STLW::vector<MainLoopContext::EventEntry> vClients;
CRITICAL
{
MutexLocker oLocker(pContext -> main_context.mutex);
// Copy all pending connections to internal vector
STLW::queue<MainLoopContext::EventEntry> & oClients = pContext -> main_context.client_sockets;
vClients.reserve(oClients.size());
while (!oClients.empty())
{
MainLoopContext::EventEntry & oEntry = oClients.front();
vClients.push_back(oEntry);
oClients.pop();
}
}
// Handle all new pending connections
STLW::vector<MainLoopContext::EventEntry>::iterator itvClients = vClients.begin();
while (itvClients != vClients.end())
{
MainLoopContext::EventEntry & oEntry = *itvClients;
// Get network handler
NetworkHandler * pHandler = static_cast<NetworkHandler *>(oEntry.service_config -> handler);
// Setup SSL connection
STLW::map<STLW::string, SSL_CTX *>::iterator itmSSLServiceMap = mSSLServiceMap.find(oEntry.service_config -> name);
if (itmSSLServiceMap != mSSLServiceMap.end() && oEntry.socket -> IsSSL())
{
dynamic_cast<ServerClientTCPSSLSocket *>(oEntry.socket) -> SetSSLContext(itmSSLServiceMap -> second);
}
// Create new connection watcher
NetworkEventWatcher * pNetworkWatcher = pHandler -> NewConnection(pContext, oEntry.service_config, oEntry.socket);
// Add new watcher
pContext -> clients.AddWatcher(pNetworkWatcher);
// And start watch
pNetworkWatcher -> StartWatch();
++itvClients;
}
}
//
// A destructor
//
AcceptSignalWatcher::~AcceptSignalWatcher() throw() { ;; }
} // namespace IRIS
// End.
| [
"root@ubuntu.communco.pro"
] | root@ubuntu.communco.pro |
fac94be6c765f1100728978eba6f9b59ff3f79c4 | 6267120efd229c7d20dec7de0795bdb472a927dd | /LogicLayer/CasualGame/SFSendDBRequest.h | fde91a68d06fe89d3db9aacd7599cb72f97b8cd4 | [] | no_license | wkawkfk/CGSF | 77a1e643f164998772b371aaac777a30da1af9dd | 919c68bcf27996f06dc25017cf003b4aa7b8785b | refs/heads/master | 2020-12-25T12:17:22.557411 | 2012-11-30T13:08:33 | 2012-11-30T13:08:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | h | #pragma once
class SFPlayer;
class BasePacket;
class SFSendDBRequest
{
public:
static BOOL RequestLogin(SFPlayer* pPlayer);
static BOOL SendRequest(int RequestMsg, DWORD PlayerSerial, BasePacket* pPacket);
static SFMessage* GetInitMessage(int RequestMsg, DWORD PlayerSerial);
static BOOL Send(SFMessage* pMessage);
static void SendToLogic(BasePacket* pMessage);
private:
SFSendDBRequest(void){}
~SFSendDBRequest(void){}
};
| [
"juhang3@daum.net"
] | juhang3@daum.net |
de092a4ef3b7b450deeab404127625e27b073fd0 | d73974bcf6836de3a481f1452c2624c18094a539 | /src/Particle.hpp | 86fc5e7959747bc8b258089f022364f8097292d9 | [] | no_license | SexyParabola/Oscillo | 8e4d78a5b9288b520565ade0fa0c9258604da311 | e5ce9539e98a2cc165fb9ca28588f50aaf1c3360 | refs/heads/master | 2023-08-04T08:21:13.448953 | 2021-09-16T19:39:51 | 2021-09-16T19:39:51 | 249,865,757 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 517 | hpp | #pragma once
#include <SFML/Graphics.hpp>
class Particle {
private:
public:
sf::Vector2f vel;
sf::Vector2f acc;
sf::CircleShape cir;
double mass = 1.0f;
Particle(sf::Vector2f P) { cir.setPosition( P ); }
void tick() {
// This here is the "BUG"..
cir.setPosition( cir.getPosition().x + vel.x, cir.getPosition().y + vel.y );
// Swap these line of code to "fix"
vel.x += acc.x;
vel.y += acc.y;
acc.x = 0;
acc.y = 0;
}
void draw(sf::RenderWindow &window) {
window.draw(cir);
}
}; | [
"ultrahoodsense@gmail.com"
] | ultrahoodsense@gmail.com |
5e7a35cde49e2eb20f760eed48091a153b9287bb | f3b5c4a5ce869dee94c3dfa8d110bab1b4be698b | /third_party/boost_1_48_0/boost/asio/local/connect_pair.hpp | a1a4d28bf0695efba678cec04019557a90842760 | [
"BSL-1.0"
] | permissive | pan2za/ctrl | 8f808fb4da117fce346ff3d54f80b4e3d6b86b52 | 1d49df03ec4577b014b7d7ef2557d76e795f6a1c | refs/heads/master | 2021-01-22T23:16:48.002959 | 2015-06-17T06:13:36 | 2015-06-17T06:13:36 | 37,454,161 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,426 | hpp | //
// local/connect_pair.hpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_LOCAL_CONNECT_PAIR_HPP
#define BOOST_ASIO_LOCAL_CONNECT_PAIR_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) \
|| defined(GENERATING_DOCUMENTATION)
#include <boost/asio/basic_socket.hpp>
#include <boost/asio/detail/socket_ops.hpp>
#include <boost/asio/detail/throw_error.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/local/basic_endpoint.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace local {
/// Create a pair of connected sockets.
template <typename Protocol, typename SocketService1, typename SocketService2>
void connect_pair(
basic_socket<Protocol, SocketService1>& socket1,
basic_socket<Protocol, SocketService2>& socket2);
/// Create a pair of connected sockets.
template <typename Protocol, typename SocketService1, typename SocketService2>
boost::system::error_code connect_pair(
basic_socket<Protocol, SocketService1>& socket1,
basic_socket<Protocol, SocketService2>& socket2,
boost::system::error_code& ec);
#ifndef BOOST_NO_EXCEPTIONS
template <typename Protocol, typename SocketService1, typename SocketService2>
inline void connect_pair(
basic_socket<Protocol, SocketService1>& socket1,
basic_socket<Protocol, SocketService2>& socket2)
{
boost::system::error_code ec;
connect_pair(socket1, socket2, ec);
boost::asio::detail::throw_error(ec, "connect_pair");
}
#endif
template <typename Protocol, typename SocketService1, typename SocketService2>
inline boost::system::error_code connect_pair(
basic_socket<Protocol, SocketService1>& socket1,
basic_socket<Protocol, SocketService2>& socket2,
boost::system::error_code& ec)
{
// Check that this function is only being used with a UNIX domain socket.
boost::asio::local::basic_endpoint<Protocol>* tmp
= static_cast<typename Protocol::endpoint*>(0);
(void)tmp;
Protocol protocol;
boost::asio::detail::socket_type sv[2];
if (boost::asio::detail::socket_ops::socketpair(protocol.family(),
protocol.type(), protocol.protocol(), sv, ec)
== boost::asio::detail::socket_error_retval)
return ec;
if (socket1.assign(protocol, sv[0], ec))
{
boost::system::error_code temp_ec;
boost::asio::detail::socket_ops::state_type state[2] = { 0, 0 };
boost::asio::detail::socket_ops::close(sv[0], state[0], true, temp_ec);
boost::asio::detail::socket_ops::close(sv[1], state[1], true, temp_ec);
return ec;
}
if (socket2.assign(protocol, sv[1], ec))
{
boost::system::error_code temp_ec;
socket1.close(temp_ec);
boost::asio::detail::socket_ops::state_type state = 0;
boost::asio::detail::socket_ops::close(sv[1], state, true, temp_ec);
return ec;
}
return ec;
}
} // namespace local
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
// || defined(GENERATING_DOCUMENTATION)
#endif // BOOST_ASIO_LOCAL_CONNECT_PAIR_HPP
| [
"pan2za@live.com"
] | pan2za@live.com |
df47736a6eebf57f80868d1e2ba600c79bed4ec8 | 5041bdc8ce649616b6dcf32aeade9ae27075ae2b | /net/http/mock_http_cache.h | 917aa20db15d8cbe471da5a54fe079e3e18b43c3 | [
"BSD-3-Clause"
] | permissive | aSeijiNagai/Readium-Chromium | a15a1ea421c797fab6e0876785f9ce4afb784e60 | 404328b0541dd3da835b288785aed080f73d85dd | refs/heads/master | 2021-01-16T22:00:32.748245 | 2012-09-24T07:57:13 | 2012-09-24T07:57:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,310 | h | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This is a mock of the http cache and related testing classes. To be fair, it
// is not really a mock http cache given that it uses the real implementation of
// the http cache, but it has fake implementations of all required components,
// so it is useful for unit tests at the http layer.
#ifndef NET_HTTP_MOCK_HTTP_CACHE_H_
#define NET_HTTP_MOCK_HTTP_CACHE_H_
#include "base/hash_tables.h"
#include "net/disk_cache/disk_cache.h"
#include "net/http/http_cache.h"
#include "net/http/http_transaction_unittest.h"
//-----------------------------------------------------------------------------
// Mock disk cache (a very basic memory cache implementation).
class MockDiskEntry : public disk_cache::Entry,
public base::RefCounted<MockDiskEntry> {
public:
MockDiskEntry();
explicit MockDiskEntry(const std::string& key);
bool is_doomed() const { return doomed_; }
virtual void Doom() OVERRIDE;
virtual void Close() OVERRIDE;
virtual std::string GetKey() const OVERRIDE;
virtual base::Time GetLastUsed() const OVERRIDE;
virtual base::Time GetLastModified() const OVERRIDE;
virtual int32 GetDataSize(int index) const OVERRIDE;
virtual int ReadData(int index, int offset, net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) OVERRIDE;
virtual int WriteData(int index, int offset, net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback,
bool truncate) OVERRIDE;
virtual int ReadSparseData(int64 offset, net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) OVERRIDE;
virtual int WriteSparseData(
int64 offset, net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) OVERRIDE;
virtual int GetAvailableRange(
int64 offset, int len, int64* start,
const net::CompletionCallback& callback) OVERRIDE;
virtual bool CouldBeSparse() const OVERRIDE;
virtual void CancelSparseIO() OVERRIDE;
virtual int ReadyForSparseIO(
const net::CompletionCallback& completion_callback) OVERRIDE;
// Fail most subsequent requests.
void set_fail_requests() { fail_requests_ = true; }
// If |value| is true, don't deliver any completion callbacks until called
// again with |value| set to false. Caution: remember to enable callbacks
// again or all subsequent tests will fail.
static void IgnoreCallbacks(bool value);
private:
friend class base::RefCounted<MockDiskEntry>;
struct CallbackInfo;
virtual ~MockDiskEntry();
// Unlike the callbacks for MockHttpTransaction, we want this one to run even
// if the consumer called Close on the MockDiskEntry. We achieve that by
// leveraging the fact that this class is reference counted.
void CallbackLater(const net::CompletionCallback& callback, int result);
void RunCallback(const net::CompletionCallback& callback, int result);
// When |store| is true, stores the callback to be delivered later; otherwise
// delivers any callback previously stored.
static void StoreAndDeliverCallbacks(bool store, MockDiskEntry* entry,
const net::CompletionCallback& callback,
int result);
static const int kNumCacheEntryDataIndices = 3;
std::string key_;
std::vector<char> data_[kNumCacheEntryDataIndices];
int test_mode_;
bool doomed_;
bool sparse_;
bool fail_requests_;
bool busy_;
bool delayed_;
static bool cancel_;
static bool ignore_callbacks_;
};
class MockDiskCache : public disk_cache::Backend {
public:
MockDiskCache();
virtual ~MockDiskCache();
virtual int32 GetEntryCount() const OVERRIDE;
virtual int OpenEntry(const std::string& key, disk_cache::Entry** entry,
const net::CompletionCallback& callback) OVERRIDE;
virtual int CreateEntry(const std::string& key, disk_cache::Entry** entry,
const net::CompletionCallback& callback) OVERRIDE;
virtual int DoomEntry(const std::string& key,
const net::CompletionCallback& callback) OVERRIDE;
virtual int DoomAllEntries(const net::CompletionCallback& callback) OVERRIDE;
virtual int DoomEntriesBetween(
const base::Time initial_time,
const base::Time end_time,
const net::CompletionCallback& callback) OVERRIDE;
virtual int DoomEntriesSince(
const base::Time initial_time,
const net::CompletionCallback& callback) OVERRIDE;
virtual int OpenNextEntry(void** iter, disk_cache::Entry** next_entry,
const net::CompletionCallback& callback) OVERRIDE;
virtual void EndEnumeration(void** iter) OVERRIDE;
virtual void GetStats(
std::vector<std::pair<std::string, std::string> >* stats) OVERRIDE;
virtual void OnExternalCacheHit(const std::string& key) OVERRIDE;
// Returns number of times a cache entry was successfully opened.
int open_count() const { return open_count_; }
// Returns number of times a cache entry was successfully created.
int create_count() const { return create_count_; }
// Fail any subsequent CreateEntry and OpenEntry.
void set_fail_requests() { fail_requests_ = true; }
// Return entries that fail some of their requests.
void set_soft_failures(bool value) { soft_failures_ = value; }
// Makes sure that CreateEntry is not called twice for a given key.
void set_double_create_check(bool value) { double_create_check_ = value; }
void ReleaseAll();
private:
typedef base::hash_map<std::string, MockDiskEntry*> EntryMap;
void CallbackLater(const net::CompletionCallback& callback, int result);
EntryMap entries_;
int open_count_;
int create_count_;
bool fail_requests_;
bool soft_failures_;
bool double_create_check_;
};
class MockBackendFactory : public net::HttpCache::BackendFactory {
public:
virtual int CreateBackend(net::NetLog* net_log,
disk_cache::Backend** backend,
const net::CompletionCallback& callback) OVERRIDE;
};
class MockHttpCache {
public:
MockHttpCache();
explicit MockHttpCache(net::HttpCache::BackendFactory* disk_cache_factory);
net::HttpCache* http_cache() { return &http_cache_; }
MockNetworkLayer* network_layer() {
return static_cast<MockNetworkLayer*>(http_cache_.network_layer());
}
MockDiskCache* disk_cache();
// Helper function for reading response info from the disk cache.
static bool ReadResponseInfo(disk_cache::Entry* disk_entry,
net::HttpResponseInfo* response_info,
bool* response_truncated);
// Helper function for writing response info into the disk cache.
static bool WriteResponseInfo(disk_cache::Entry* disk_entry,
const net::HttpResponseInfo* response_info,
bool skip_transient_headers,
bool response_truncated);
// Helper function to synchronously open a backend entry.
bool OpenBackendEntry(const std::string& key, disk_cache::Entry** entry);
// Helper function to synchronously create a backend entry.
bool CreateBackendEntry(const std::string& key, disk_cache::Entry** entry,
net::NetLog* net_log);
// Returns the test mode after considering the global override.
static int GetTestMode(int test_mode);
// Overrides the test mode for a given operation. Remember to reset it after
// the test! (by setting test_mode to zero).
static void SetTestMode(int test_mode);
private:
net::HttpCache http_cache_;
};
// This version of the disk cache doesn't invoke CreateEntry callbacks.
class MockDiskCacheNoCB : public MockDiskCache {
virtual int CreateEntry(const std::string& key, disk_cache::Entry** entry,
const net::CompletionCallback& callback) OVERRIDE;
};
class MockBackendNoCbFactory : public net::HttpCache::BackendFactory {
public:
virtual int CreateBackend(net::NetLog* net_log,
disk_cache::Backend** backend,
const net::CompletionCallback& callback) OVERRIDE;
};
// This backend factory allows us to control the backend instantiation.
class MockBlockingBackendFactory : public net::HttpCache::BackendFactory {
public:
MockBlockingBackendFactory();
virtual ~MockBlockingBackendFactory();
virtual int CreateBackend(net::NetLog* net_log,
disk_cache::Backend** backend,
const net::CompletionCallback& callback) OVERRIDE;
// Completes the backend creation. Any blocked call will be notified via the
// provided callback.
void FinishCreation();
disk_cache::Backend** backend() { return backend_; }
void set_fail(bool fail) { fail_ = fail; }
const net::CompletionCallback& callback() { return callback_; }
private:
int Result() { return fail_ ? net::ERR_FAILED : net::OK; }
disk_cache::Backend** backend_;
net::CompletionCallback callback_;
bool block_;
bool fail_;
};
#endif // NET_HTTP_MOCK_HTTP_CACHE_H_
| [
"kerz@chromium.org@4ff67af0-8c30-449e-8e8b-ad334ec8d88c"
] | kerz@chromium.org@4ff67af0-8c30-449e-8e8b-ad334ec8d88c |
aa52362135346c8b8b1b26733e846a33128649af | ae0f1fff140e24076442a26ad6236b3c5527e601 | /NV8/bai1.cpp | ee59ae3aeddb2fd4bbbc9a1cf02102cf9a7c11e5 | [] | no_license | jackychun2002/T2008M-LBEP | cd61ca8a04e92d7722d449b5d30b8b325bdff357 | b2bfaf221d694c91654ddb42d5818b718c2909b5 | refs/heads/master | 2022-12-30T23:41:22.522590 | 2020-10-02T03:17:12 | 2020-10-02T03:17:12 | 293,971,004 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | #include<stdio.h>
int t(int n,int s=0){
if(n<2)
return false;
for(int i=2;i<=(n-1);i++){
if(n%i ==0){
return false;
}
return true;
}
}
void C(int n){
int i=n+1;
while(t(i)==false){
i++;
}
printf("%d",i);
}
int main(){
int n;
do{
printf("nhap n :");
scanf("%d",&n);
}while(n<=0);
printf("So nguyen to lon hon n va gan n nhat: ");
C(n);
return 0;
}
| [
"chienbody2002@gmail.com"
] | chienbody2002@gmail.com |
bd762580596c86ab6d496220bbf0074bfa6c442a | 15f1b1e98f99531c7f286ddf854b776ee140e14d | /Sort/BubblingSort.cpp | 11fbeb3b7badc4f8d30b0d1b1a746d9821205bc9 | [] | no_license | bright-dusty/lintcode- | 7a59e5f341684e851fa2340dad81e63f5bed02f9 | 718bfd95fc0a0b6c42bc7acbbfc43b12ceebedd7 | refs/heads/master | 2021-04-27T04:37:15.114470 | 2018-03-11T05:06:07 | 2018-03-11T05:06:07 | 122,581,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 252 | cpp | #include <cstdlib>
#include "swap.hpp"
template <typename T>
void _sort (T arr[], size_t n) {
for (size_t i=0; i < n-1; i++)
for (size_t j=0; j < n-1-i; j++)
if (arr[j] > arr[j+1])
swap<T>(arr[j], arr[j+1]);
}
| [
"qj p"
] | qj p |
9026da2258e1cdc8fd8a7d80badd0af0f68b16c9 | 785df77400157c058a934069298568e47950e40b | /TnbSectPx/TnbLib/SectPx/Entities/Shape/Profile/SectPx_ProfileShape.hxx | 8f2a1770ae21c8a68cd24e839fc439b288380e63 | [] | no_license | amir5200fx/Tonb | cb108de09bf59c5c7e139435e0be008a888d99d5 | ed679923dc4b2e69b12ffe621fc5a6c8e3652465 | refs/heads/master | 2023-08-31T08:59:00.366903 | 2023-08-31T07:42:24 | 2023-08-31T07:42:24 | 230,028,961 | 9 | 3 | null | 2023-07-20T16:53:31 | 2019-12-25T02:29:32 | C++ | UTF-8 | C++ | false | false | 914 | hxx | #pragma once
#ifndef _SectPx_ProfileShape_Header
#define _SectPx_ProfileShape_Header
#include <SectPx_Shape.hxx>
namespace tnbLib
{
// Forward Declarations
class SectPx_TopoSegment;
class SectPx_ProfileShape
: public SectPx_Shape
{
/*Private Data*/
std::shared_ptr<SectPx_TopoSegment> theSegment_;
public:
SectPx_ProfileShape()
{}
SectPx_ProfileShape(const Standard_Integer theIndex, const word& theName);
SectPx_ProfileShape(const std::shared_ptr<SectPx_TopoSegment>& theSegment);
SectPx_ProfileShape(const Standard_Integer theIndex, const word& theName, const std::shared_ptr<SectPx_TopoSegment>& theSegment);
const auto& Segment() const
{
return theSegment_;
}
void SetSegment(const std::shared_ptr<SectPx_TopoSegment>& theSegment)
{
theSegment_ = theSegment;
}
Standard_Boolean IsProfile() const override;
};
}
#endif // !_SectPx_ProfileShape_Header
| [
"aasoleimani86@gmail.com"
] | aasoleimani86@gmail.com |
b8d0dd5864d4ba541b9bd71486d3ce01b5bf766e | c8fc2703cce588d28dd9583e523f7f78378e3fd3 | /practise/bfs_implementation.cpp | bae74fe03ebfdf534e28508da3d2548b0d098a17 | [] | no_license | ngangwar962/C_and_Cpp_Programs | e4da2951b1a8c0091df26e363227488e279a9caa | 396d4313d2451e073811c0657f068829db10bcd5 | refs/heads/master | 2020-06-19T14:20:19.749116 | 2019-08-10T16:54:09 | 2019-08-10T16:54:09 | 196,741,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,086 | cpp | #include<bits/stdc++.h>
using namespace std;
#define MAX 10000
bool visited[MAX]={0};
int level[MAX]={0};
int vertices;
void addedge(vector<int> adj[],int v1,int v2)
{
adj[v1].push_back(v2);
adj[v2].push_back(v1);
return;
}
void printg(vector<int> adj[],int v)
{
cout<<v;
int i;
for(i=0;i<adj[v].size();i++)
{
cout<<"->"<<adj[v][i];
}
cout<<"\n";
return;
}
void bfs(vector<int> adj[],int s)
{
int i;
for(i=0;i<vertices;i++)
{
visited[i]=0;
level[i]=-1;
}
queue<int> q;
q.push(s);
visited[s]=true;
level[s]=0;
while(!q.empty())
{
int p=q.front();
q.pop();
vector<int>::iterator it;
for(it=adj[p].begin();it!=adj[p].end();it++)
{
if(!visited[*it])
{
q.push(*it);
visited[*it]=true;
level[*it]=level[p]+1;
}
}
}
return;
}
int main()
{
int i,j,k,edges;
cin>>vertices;
vector<int> adj[vertices];
cin>>edges;
int v1,v2;
for(i=0;i<edges;i++)
{
cin>>v1>>v2;
addedge(adj,v1,v2);
}
for(i=0;i<vertices;i++)
{
printg(adj,i);
}
bfs(adj,0);
for(i=0;i<vertices;i++)
{
cout<<level[i]<<" ";
}
cout<<"\n";
return 0;
}
| [
"ngangwar962@gmail.com"
] | ngangwar962@gmail.com |
87ad8882e20fa6a698d0eb09f83b95d88fb46b30 | da3459735ac22f4dcee124a25d5527bad909fca5 | /src/qt/rpcconsole.cpp | eb3b37e981b544aeadb8a14f80c38878597b3d19 | [
"MIT"
] | permissive | bitfawkes/sannacoin | 0cb15ac6fa3738c797844606b0b3f7d1d0d4d990 | 94ae22141a183d5ae1442e8589fc55b18136ebb3 | refs/heads/master | 2021-01-13T05:25:52.997635 | 2017-02-09T13:47:08 | 2017-02-09T13:47:08 | 81,370,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,287 | cpp | #include "rpcconsole.h"
#include "ui_rpcconsole.h"
#include "clientmodel.h"
#include "bitcoinrpc.h"
#include "guiutil.h"
#include <QTime>
#include <QTimer>
#include <QThread>
#include <QTextEdit>
#include <QKeyEvent>
#include <QUrl>
#include <QScrollBar>
#include <boost/tokenizer.hpp>
#include <openssl/crypto.h>
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_SCROLLBACK = 50;
const int CONSOLE_HISTORY = 50;
const QSize ICON_SIZE(24, 24);
const struct {
const char *url;
const char *source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{NULL, NULL}
};
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor: public QObject
{
Q_OBJECT
public slots:
void start();
void request(const QString &command);
signals:
void reply(int category, const QString &command);
};
#include "rpcconsole.moc"
void RPCExecutor::start()
{
// Nothing to do
}
void RPCExecutor::request(const QString &command)
{
// Parse shell-like command line into separate arguments
std::string strMethod;
std::vector<std::string> strParams;
try {
boost::escaped_list_separator<char> els('\\',' ','\"');
std::string strCommand = command.toStdString();
boost::tokenizer<boost::escaped_list_separator<char> > tok(strCommand, els);
int n = 0;
for(boost::tokenizer<boost::escaped_list_separator<char> >::iterator beg=tok.begin(); beg!=tok.end();++beg,++n)
{
if(n == 0) // First parameter is the command
strMethod = *beg;
else
strParams.push_back(*beg);
}
}
catch(boost::escaped_list_error &e)
{
emit reply(RPCConsole::CMD_ERROR, QString("Parse error"));
return;
}
try {
std::string strPrint;
json_spirit::Value result = tableRPC.execute(strMethod, RPCConvertValues(strMethod, strParams));
// Format result reply
if (result.type() == json_spirit::null_type)
strPrint = "";
else if (result.type() == json_spirit::str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
}
catch (json_spirit::Object& objError)
{
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false)));
}
catch (std::exception& e)
{
emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
RPCConsole::RPCConsole(QWidget *parent) :
QDialog(parent),
ui(new Ui::RPCConsole),
historyPtr(0)
{
ui->setupUi(this);
#ifndef Q_WS_MAC
ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
ui->showCLOptionsButton->setIcon(QIcon(":/icons/options"));
#endif
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// set OpenSSL version label
ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
startExecutor();
clear();
}
RPCConsole::~RPCConsole()
{
emit stopExecutor();
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
{
if(obj == ui->lineEdit)
{
if(event->type() == QEvent::KeyPress)
{
QKeyEvent *key = static_cast<QKeyEvent*>(event);
switch(key->key())
{
case Qt::Key_Up: browseHistory(-1); return true;
case Qt::Key_Down: browseHistory(1); return true;
}
}
}
return QDialog::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel *model)
{
this->clientModel = model;
if(model)
{
// Subscribe to information, replies, messages, errors
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientName->setText(model->clientName());
ui->buildDate->setText(model->formatBuildDate());
ui->startupTime->setText(model->formatClientStartupTime());
setNumConnections(model->getNumConnections());
ui->isTestNet->setChecked(model->isTestNet());
setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers());
}
}
static QString categoryClass(int category)
{
switch(category)
{
case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
case RPCConsole::CMD_ERROR: return "cmd-error"; break;
default: return "misc";
}
}
void RPCConsole::clear()
{
ui->messagesWidget->clear();
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for(int i=0; ICON_MAPPING[i].url; ++i)
{
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
ui->messagesWidget->document()->setDefaultStyleSheet(
"table { }"
"td.time { color: #808080; padding-top: 3px; } "
"td.message { font-family: Monospace; font-size: 12px; } "
"td.cmd-request { color: #006060; } "
"td.cmd-error { color: red; } "
"b { color: #006060; } "
);
message(CMD_REPLY, (tr("Welcome to the SannaCoin RPC console.") + "<br>" +
tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")), true);
}
void RPCConsole::message(int category, const QString &message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if(html)
out += message;
else
out += GUIUtil::HtmlEscape(message, true);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::setNumConnections(int count)
{
ui->numberOfConnections->setText(QString::number(count));
}
void RPCConsole::setNumBlocks(int count, int countOfPeers)
{
ui->numberOfBlocks->setText(QString::number(count));
ui->totalBlocks->setText(QString::number(countOfPeers));
if(clientModel)
{
// If there is no current number available display N/A instead of 0, which can't ever be true
ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers()));
ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
}
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
ui->lineEdit->clear();
if(!cmd.isEmpty())
{
message(CMD_REQUEST, cmd);
emit cmdRequest(cmd);
// Truncate history from current position
history.erase(history.begin() + historyPtr, history.end());
// Append command to history
history.append(cmd);
// Enforce maximum history size
while(history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
historyPtr += offset;
if(historyPtr < 0)
historyPtr = 0;
if(historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if(historyPtr < history.size())
cmd = history.at(historyPtr);
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
QThread* thread = new QThread;
RPCExecutor *executor = new RPCExecutor();
executor->moveToThread(thread);
// Notify executor when thread started (in executor thread)
connect(thread, SIGNAL(started()), executor, SLOT(start()));
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
// Requests from this object must go to executor
connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
// On stopExecutor signal
// - queue executor for deletion (in execution thread)
// - quit the Qt event loop in the execution thread
connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
// Queue the thread for deletion (in this thread) when it is finished
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread->start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if(ui->tabWidget->widget(index) == ui->tab_console)
{
ui->lineEdit->setFocus();
}
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_showCLOptionsButton_clicked()
{
GUIUtil::HelpMessageBox help;
help.exec();
}
| [
"bitfawkes@gmail.com"
] | bitfawkes@gmail.com |
eff3f1499c7bb4de6960b41387829e21eaf85fdc | 3aa028649f6e9a26454a1caa4d0b89cbe341d660 | /GTRACT/Cmdline/gtractCoRegAnatomy.cxx | 58011354bcd488fb9255e5018f630c0abeb1c580 | [] | no_license | jcfr/BRAINSStandAlone | 2738b83213235c35148f291ad57d07bdeb30de07 | db8a912bbd19734968e4cf83752cb1facdba10eb | refs/heads/master | 2021-01-16T21:03:02.734435 | 2011-10-26T18:30:54 | 2011-10-26T18:30:54 | 2,634,574 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,453 | cxx | /*=========================================================================
Program: GTRACT (Guided Tensor Restore Anatomical Connectivity Tractography)
Module: $RCSfile: $
Language: C++
Date: $Date: 2010/05/03 14:53:40 $
Version: $Revision: 1.9 $
Copyright (c) University of Iowa Department of Radiology. All rights reserved.
See GTRACT-Copyright.txt or http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt
for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <iostream>
#include <fstream>
#include <itkImage.h>
#include <itkVectorIndexSelectionCastImageFilter.h>
#include <itkThresholdImageFilter.h>
#include <itkOrientImageFilter.h>
#include "itkGtractImageIO.h"
#include "BRAINSFitHelper.h"
#include "gtractCoRegAnatomyCLP.h"
#include "BRAINSThreadControl.h"
int main(int argc, char *argv[])
{
PARSE_ARGS;
BRAINSUtils::SetThreadCount(numberOfThreads);
itk::TransformFactory<itk::ScaleVersor3DTransform<double> >::RegisterTransform();
itk::TransformFactory<itk::ScaleVersor3DTransform<float> >::RegisterTransform();
std::vector<int> GridSize;
GridSize.push_back( gridSize[0] );
GridSize.push_back( gridSize[1] );
GridSize.push_back( gridSize[2] );
bool debug = true;
if( debug )
{
std::cout << "=====================================================" << std::endl;
std::cout << "Input Image: " << inputVolume << std::endl;
std::cout << "Output Transform: " << outputTransformName << std::endl;
std::cout << "Anatomical Image: " << inputAnatomicalVolume << std::endl;
std::cout << "Iterations: " << numberOfIterations << std::endl;
if( transformType == "Bspline" )
{
std::cout << "Input Rigid Transform: " << inputRigidTransform << std::endl;
// std::cout << "Grid Size: " << GridSize <<std::endl;
// std::cout << "Border Size: " << borderSize <<std::endl;
// std::cout << "Corrections: " << numberOfCorrections <<std::endl;
// std::cout << "Evaluations: " << numberOfEvaluations <<std::endl;
std::cout << "Histogram: " << numberOfHistogramBins << std::endl;
std::cout << "Scale: " << spatialScale << std::endl;
std::cout << "Convergence: " << convergence << std::endl;
std::cout << "Gradient Tolerance: " << gradientTolerance << std::endl;
std::cout << "Index: " << vectorIndex << std::endl;
}
else if( transformType == "Rigid" )
{
std::cout << "Translation Scale: " << translationScale << std::endl;
std::cout << "Maximum Step Length: " << maximumStepSize << std::endl;
std::cout << "Minimum Step Length: " << minimumStepSize << std::endl;
std::cout << "Relaxation Factor: " << relaxationFactor << std::endl;
std::cout << "Samples: " << numberOfSamples << std::endl;
std::cout << "Index: " << vectorIndex << std::endl;
}
// std::cout << "Bound X: " << boundX <<std::endl;
// std::cout << "\tLower X Bound: " << xLowerBound <<std::endl;
// std::cout << "\tUpper X Bound: " << xUpperBound <<std::endl;
// std::cout << "Bound Y: " << boundY <<std::endl;
// std::cout << "\tLower Y Bound: " << yLowerBound <<std::endl;
// std::cout << "\tUpper Y Bound: " << yUpperBound <<std::endl;
// std::cout << "Bound Z: " << boundZ <<std::endl;
// std::cout << "\tLower Z Bound: " << zLowerBound <<std::endl;
// std::cout << "\tUpper Z Bound: " << zUpperBound <<std::endl;
std::cout << "=====================================================" << std::endl;
}
bool violated = false;
if( inputVolume.size() == 0 )
{
violated = true; std::cout << " --inputVolume Required! " << std::endl;
}
if( inputAnatomicalVolume.size() == 0 )
{
violated = true; std::cout << " --inputAnatomicalVolume Required! " << std::endl;
}
if( transformType == "Bspline" )
{
if( inputRigidTransform.size() == 0 )
{
violated = true; std::cout << " --inputRigidTransform Required! " << std::endl;
}
}
if( outputTransformName.size() == 0 )
{
violated = true; std::cout << " --outputTransform Required! " << std::endl;
}
if( violated )
{
exit(1);
}
// typedef signed short PixelType;
typedef float PixelType;
typedef itk::VectorImage<PixelType, 3> VectorImageType;
typedef itk::ImageFileReader<VectorImageType,
itk::DefaultConvertPixelTraits<PixelType> > VectorImageReaderType;
VectorImageReaderType::Pointer vectorImageReader = VectorImageReaderType::New();
vectorImageReader->SetFileName( inputVolume );
try
{
vectorImageReader->Update();
}
catch( itk::ExceptionObject & ex )
{
std::cout << ex << std::endl;
throw;
}
typedef itk::Image<PixelType, 3> AnatomicalImageType;
typedef itk::ImageFileReader<AnatomicalImageType> AnatomicalImageReaderType;
AnatomicalImageReaderType::Pointer anatomicalReader = AnatomicalImageReaderType::New();
anatomicalReader->SetFileName( inputAnatomicalVolume );
try
{
anatomicalReader->Update();
}
catch( itk::ExceptionObject & ex )
{
std::cout << ex << std::endl;
throw;
}
/* Extract the Vector Image Index for Registration */
typedef itk::VectorIndexSelectionCastImageFilter<VectorImageType, AnatomicalImageType> VectorSelectFilterType;
typedef VectorSelectFilterType::Pointer VectorSelectFilterPointer;
VectorSelectFilterPointer selectIndexImageFilter = VectorSelectFilterType::New();
selectIndexImageFilter->SetIndex( vectorIndex );
selectIndexImageFilter->SetInput( vectorImageReader->GetOutput() );
try
{
selectIndexImageFilter->Update();
}
catch( itk::ExceptionObject e )
{
std::cout << e << std::endl;
throw;
}
std::string localInitializeTransformMode = "Off";
if( ( (useCenterOfHeadAlign == true) + (useGeometryAlign == true) + (useMomentsAlign == true) ) > 1 )
{
std::cout << "ERROR: Can only specify one of [useCenterOfHeadAlign | useGeometryAlign | useMomentsAlign ]"
<< std::endl;
}
if( useCenterOfHeadAlign == true )
{
localInitializeTransformMode = "useCenterOfHeadAlign";
}
if( useGeometryAlign == true )
{
localInitializeTransformMode = "useGeometryAlign";
}
if( useMomentsAlign == true )
{
localInitializeTransformMode = "useMomentsAlign";
}
typedef itk::BRAINSFitHelper RegisterFilterType;
RegisterFilterType::Pointer registerImageFilter = RegisterFilterType::New();
if( transformType == "Rigid" )
{
/* The Threshold Image Filter is used to produce the brain clipping mask. */
typedef itk::ThresholdImageFilter<AnatomicalImageType> ThresholdFilterType;
const PixelType imageThresholdBelow = 100;
ThresholdFilterType::Pointer brainOnlyFilter = ThresholdFilterType::New();
brainOnlyFilter->SetInput( selectIndexImageFilter->GetOutput() );
brainOnlyFilter->ThresholdBelow( imageThresholdBelow );
try
{
brainOnlyFilter->Update();
}
catch( itk::ExceptionObject e )
{
std::cout << e << std::endl;
throw;
}
registerImageFilter->SetMovingVolume( brainOnlyFilter->GetOutput() );
}
if( transformType == "Bspline" )
{
typedef itk::OrientImageFilter<AnatomicalImageType, AnatomicalImageType> OrientFilterType;
OrientFilterType::Pointer orientImageFilter = OrientFilterType::New();
// orientImageFilter->SetInput(brainOnlyFilter->GetOutput() );
orientImageFilter->SetInput( selectIndexImageFilter->GetOutput() );
orientImageFilter->SetDesiredCoordinateDirection( anatomicalReader->GetOutput()->GetDirection() );
orientImageFilter->UseImageDirectionOn();
try
{
orientImageFilter->Update();
}
catch( itk::ExceptionObject e )
{
std::cout << e << std::endl;
throw;
}
registerImageFilter->SetMovingVolume( orientImageFilter->GetOutput() );
}
std::vector<std::string> transformTypes;
std::vector<int> iterations;
iterations.push_back(numberOfIterations);
if( transformType == "Bspline" )
{
transformTypes.push_back("BSpline");
registerImageFilter->SetNumberOfSamples(
anatomicalReader->GetOutput()->GetBufferedRegion().GetNumberOfPixels() / spatialScale);
registerImageFilter->SetNumberOfHistogramBins(numberOfHistogramBins);
registerImageFilter->SetSplineGridSize( gridSize );
registerImageFilter->SetCostFunctionConvergenceFactor( convergence );
registerImageFilter->SetProjectedGradientTolerance( gradientTolerance );
registerImageFilter->SetMaxBSplineDisplacement(maxBSplineDisplacement);
registerImageFilter->SetInitializeTransformMode(localInitializeTransformMode);
if( inputRigidTransform.size() > 0 )
{
registerImageFilter->SetCurrentGenericTransform(itk::ReadTransformFromDisk(inputRigidTransform) );
}
}
if( transformType == "Rigid" )
{
transformTypes.push_back("ScaleVersor3D");
std::vector<double> minStepLength;
minStepLength.push_back( (double)minimumStepSize);
registerImageFilter->SetTranslationScale( translationScale );
registerImageFilter->SetMaximumStepLength( maximumStepSize );
registerImageFilter->SetMinimumStepLength(minStepLength );
registerImageFilter->SetRelaxationFactor( relaxationFactor );
registerImageFilter->SetNumberOfSamples( numberOfSamples );
registerImageFilter->SetInitializeTransformMode(localInitializeTransformMode);
}
registerImageFilter->SetFixedVolume( anatomicalReader->GetOutput() );
registerImageFilter->SetTransformType(transformTypes);
registerImageFilter->SetNumberOfIterations(iterations);
try
{
registerImageFilter->StartRegistration();
}
catch( itk::ExceptionObject & ex )
{
std::cout << ex << std::endl;
throw;
}
GenericTransformType::Pointer outputTransform = registerImageFilter->GetCurrentGenericTransform();
// WriteTransformToDisk(outputTransform.GetPointer(), outputTransformName);
WriteTransformToDisk(outputTransform, outputTransformName);
return EXIT_SUCCESS;
}
| [
"hans-johnson@uiowa.edu"
] | hans-johnson@uiowa.edu |
6675e010cf62cc622aaa1feb1d3030509b31d27c | 60b040d794f1501085dbf78884ebb7f47e0fd61b | /DxEngine/source/TextureClass.h | 98a972d8dbada5a3c6de4d5d3478a131b54c4d50 | [] | no_license | Grave/DxEngine | 08807836103727377d231e435e95d3282a240cc4 | 6f532c96ff9db04210244bee49b0dd4d7653aa6c | refs/heads/master | 2021-01-19T04:50:54.330800 | 2014-07-30T19:21:41 | 2014-07-30T19:21:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 668 | h | ////////////////////////////////////////////////////////////////////////////////
// Filename: TextureClass.h
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "stdafx.h"
////////////////////////////////////////////////////////////////////////////////
// Class name: TextureClass
////////////////////////////////////////////////////////////////////////////////
class TextureClass
{
public:
TextureClass();
TextureClass(const TextureClass&);
~TextureClass();
bool Initialize(ID3D11Device*, WCHAR*);
void Shutdown();
ID3D11ShaderResourceView* GetTexture();
private:
ID3D11ShaderResourceView* m_texture;
};
| [
"guilhermecsrodrigues@gmail.com"
] | guilhermecsrodrigues@gmail.com |
b736caaf70e4776819b343281a4b9e18b25af284 | 8fabbfa6ca7763588554073c406f50a2a19a710d | /HelloDave.cpp | 0ab1fb40a1cb450937ba856bc76793b57159d843 | [] | no_license | SamiSousa/EC327 | c8e85d7634fd79d894ac0100af76d9a9d445e705 | 423151f98aedcac67e46aaf3ef0277b4f1aa4949 | refs/heads/master | 2016-08-12T13:26:05.806027 | 2015-10-01T05:38:08 | 2015-10-01T05:38:08 | 43,347,103 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 250 | cpp | #include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
//testing Dev-C++
//press F9 to compile and run in one go
cout << "Hello Dave" << endl;
//this for seeing result
system("PAUSE");
return 0;
}
| [
"dr.wisper@gmail.com"
] | dr.wisper@gmail.com |
93e1bde93d50c752226de08e2071e77c34ef2f6a | 15ae3c07d969f1e75bc2af9555cf3e952be9bfff | /analysis/pragma_before/pragma_719.hpp | 958f49e784d8e32a0f2730c9d0389e5e60fba1e7 | [] | no_license | marroko/generators | d2d1855d9183cbc32f9cd67bdae8232aba2d1131 | 9e80511155444f42f11f25063c0176cb3b6f0a66 | refs/heads/master | 2023-02-01T16:55:03.955738 | 2020-12-12T14:11:17 | 2020-12-12T14:11:17 | 316,802,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 62 | hpp | #ifndef FALYNYC_HPP
#define FALYNYC_HPP
#endif // FALYNYC_HPP | [
"marcus1.2.3@wp.pl"
] | marcus1.2.3@wp.pl |
fb654d15e2d0e513c8c7eda2b63811d4a496762d | cd697db374f06422b53f2319000f6591ed92e809 | /JoystickInput.h | e38bb2b0ef29375c6681050d1b9ca37112317f21 | [] | no_license | CML-lab/Utility_Task_cpp | d00b44104c07a9824415e7589a4e6a140873c73b | ea7a9dc830ed3d446ab0c930a5940fd8e1193df1 | refs/heads/master | 2023-07-15T13:23:32.918294 | 2021-08-25T18:02:51 | 2021-08-25T18:02:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 750 | h | #ifndef JOYSTICKINPUT_H
#define JOYSTICKINPUT_H
#pragma once
#include "SDL.h"
#include "InputDevice.h"
static GLfloat jx;
static GLfloat jy;
static GLfloat jradius;
static GLfloat jangle;
// Handles joystick actions
class JoystickInput : public InputDevice
{
public:
JoystickInput() { }
~JoystickInput() { }
//Initialize Joystick
//bool InitJoystick();
// Gets the most recent frame of data from the joystick
InputFrame GetFrame();
// Updates JoystickInput with new axes information.
// event is an SDL_Event containing the updated information.
static void ProcessEvent(SDL_Event event,SDL_Joystick *joystick);
//close the joystick when done
static void CloseJoystick(SDL_Joystick *joystick);
};
#endif
| [
"cognitivemotorlab@gmail.com"
] | cognitivemotorlab@gmail.com |
d4bfd69333bd935d49645a4c05cf117763bdb878 | a28af655fbfcd2939fe50e30f8f5294f07c106d2 | /Source/AudiusLib/Player/Playlist.h | 611a0289347baaebffa5fb0acf1b3e01865b4a8f | [] | no_license | cnsuhao/Audius | d365dac2f0be7fcc844c913901013d3a8b47ca1e | 22c3c61af6efdeb0ac92cc8fbad571e1694d4887 | refs/heads/master | 2021-05-26T16:59:25.928600 | 2012-10-06T14:51:20 | 2012-10-06T14:51:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,868 | h | #pragma once
////////////////////////////////////////////////////////////////////////////////////////
// File: Playlist.h
////////////////////////////////////////////////////////////////////////////////////////
// Description:
//
// A thread safe list of songs to play. The music player has a reference to this list
// and the player thread uses it as well to know what to play.
//
////////////////////////////////////////////////////////////////////////////////////////
#include "juce.h"
#include "PlaylistEntry.h"
class Playlist
{
public:
Playlist(void) :
_currentPosition(0)
{
}
~Playlist(void)
{
}
// Add an entry to the play list
void add(std::shared_ptr<PlaylistEntry> entry)
{
const ScopedLock l(_lock);
_entries.push_back(entry);
}
// Clears the entire play list
void clear()
{
const ScopedLock l(_lock);
_entries.clear();
_currentPosition = 0;
}
// Retrieves the number of entries in the play list
uint32 getCount()
{
const ScopedLock l(_lock);
return _entries.size();
}
// Advances the counter to the next entry if possible, or returns false if at end of list
bool gotoNextEntry()
{
const ScopedLock l(_lock);
if(_currentPosition >= _entries.size() - 1)
return false;
_currentPosition++;
return true;
}
bool gotoPreviousEntry()
{
const ScopedLock l(_lock);
if(_currentPosition <= 0)
return false;
_currentPosition--;
return true;
}
// Inserts the entry at a certain position in the play list
void insert(uint32 position, std::shared_ptr<PlaylistEntry> entry)
{
const ScopedLock l(_lock);
jassert(position >= 0 && position <= _entries.size());
std::vector< std::shared_ptr<PlaylistEntry> >::iterator it = _entries.begin() + position;
_entries.insert(it, entry);
// Adjust current play position
if(position <= _currentPosition)
_currentPosition++;
}
// Gets the current play list entry
std::shared_ptr<PlaylistEntry> getCurrentEntry()
{
const ScopedLock l(_lock);
if(_currentPosition >= _entries.size())
return std::shared_ptr<PlaylistEntry>();
return _entries[_currentPosition];
}
// Gets the current play list position
uint32 getCurrentPosition()
{
return _currentPosition;
}
// Sets the current position of the playlist
bool setCurrentPosition(uint32 position)
{
const ScopedLock l(_lock);
if(position < 0 || position >= _entries.size())
return false;
_currentPosition = position;
return true;
}
std::shared_ptr<PlaylistEntry> getEntry(uint32 position)
{
const ScopedLock l(_lock);
jassert(position >= 0 && position < _entries.size());
return _entries[position];
}
private:
std::vector< std::shared_ptr<PlaylistEntry> > _entries;
uint32 _currentPosition;
CriticalSection _lock;
};
| [
"pontus.munck@gmail.com"
] | pontus.munck@gmail.com |
622dd8fc926551a0a1f20501895de6eadaf24b1a | c65801f6dd31b0d4e30197266d60a6867f1e4459 | /源.cpp | 5f8d6dfbb23418a24ac33391c83da9fbcacc053e | [] | no_license | asLong72/afd | bcff0f01a2153ba418df4e3c18d8fabab869c9c8 | b3f4f3e8d35aa33fef833924465883f3db6da4c6 | refs/heads/master | 2020-09-02T22:21:30.384550 | 2019-11-03T15:12:33 | 2019-11-03T15:12:33 | 219,319,682 | 0 | 0 | null | null | null | null | ISO-8859-3 | C++ | false | false | 4,096 | cpp | #include <stdio.h>
#include <math.h>
int a, b, c, d, e;
long l;
char ch;
double z, y, x, w;
int T1(void)
{
scanf_s("%d%d%d", &a, &b, &c);
if (a <= b && a <= c)
{
printf("%d\n", a);
}
else if (b <= a && b <= c)
{
printf("%d\n", b);
}
else
{
printf("%d\n", c);
}
return 0;
}
int T2(void)
{
int a;
scanf_s("%d", &a);
if (a < 0 || a>100)
{
printf("error!");
}
else
{
a /= 10;
switch (a)
{
case 10:
putchar('A');
break;
case 9:
putchar('A');
break;
case 8:
putchar('B');
break;
case 7:
putchar('C');
break;
case 6:
putchar('D');
break;
default:
putchar('E');
break;
}
}
return 0;
}
int T3(void)
{
scanf_s("%d", &a);
if (a < 0)
{
printf("error!");
}
if (0 != (a % 10))
{
printf("%d", a % 10);
}
if (0 != (a % 100))
{
printf("%d", (a % 100) / 10);
}
if (0 != (a % 1000))
{
printf("%d", (a % 1000) / 100);
}
return 0;
}
int T4(void)
{
scanf_s("%d", &a);
if (100000 >= a)
{
z = a * 0.1;
}
if (100000 >= a - 100000 && a - 100000 > 0)
{
a = a - 100000;
z = (100000 * 0.1) + (a * 0.075);
}
if (200000 >= a - 200000 && a - 200000 > 0)
{
a = a - 200000;
z = (100000 * 0.1) + (1000000 * 0.075) + (a * 0.05);
}
if (200000 >= a - 400000 && a - 400000 > 0)
{
a = a - 400000;
z = (100000 * 0.1) + 1000000 * 0.075 + 200000 * 0.05 + a * 0.03;
}
if (400000 >= a - 600000 && a - 600000 > 0)
{
a = a - 600000;
z = (100000 * 0.1) + 1000000 * 0.075 + 200000 * 0.05 + 20000 * 0.03 + a * 0.015;
}
if (a > 1000000)
{
l = a - 1000000;
z = (100000 * 0.1) + 1000000 * 0.075 + 200000 * 0.05 + 20000 * 0.03 + 400000 * 0.015 + (l - 1000000) * 0.01;
}
printf("%.2f", z);
return 0;
}
int T5(void)
{
scanf_s("&lf", &x);
if (x < 1)
{
y = x * x + 2 * x + sin(x);
}
else if (x >= 1 && x <= 10)
{
y = 2 * x + 1;
}
else if (x > 10)
{
y = sqrt(x * x * x * 2 + 11);
}
printf("%.2f", y);
return 0;
}
int T6(void)
{
scanf_s("%c", &ch);
if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))
{
printf("It is an alphabetic character.");
}
else if (ch >= 48 && ch <= 89)
{
printf("It is a digit.");
}
else
{
printf("£şIt is other character.");
}
return 0;
}
int T7(void)
{
start:
scanf_s("%d%d%d", &a, &b, &c);
if (a + b > c&& a + c > b&& c + b > a)
{
if (a == b && a == c)
{
printf("1\n");
}
else if ((a == b && a != c) || (a == c && a != b) || (c == b && c != a))
{
printf("2\n");
}
else if ((a * a + b * b == c * c) || (a * a + c * c == b * b) || (c * c + b * b == a * a))
{
printf("3\n");
}
else
{
printf("0\n");
}
}
else
{
printf("error!\n");
}
goto start;
return 0;
}
int T8(void)
{
scanf_s("%lf", &z);
if (a >= 0 && a <= 100)
{
printf("%d", (int)pow(z, 2.0));
}
else
{
printf("-1");
}
return 0;
}
int T9(void)
{
scanf_s("%lf", &z);
if (a >= 0 && a <= 20)
{
printf("%d", (int)pow(z, 3.0));
}
else
{
printf("-1");
}
return 0;
}
int T10(void)
{
scanf_s("%d", &a);
if (0 == (a % 4))
{
if (0 == (a % 400))
printf("1\n");
else if ((0 == a % 4) && (0 != a % 100))
printf("1\n");
else if ((0 != a % 400) == (0 == a % 100))
printf("1\n");
}
else
{
printf("0\n");
}
return 0;
}
int T11(void)
{
scanf_s("%d", &a);
if (a >= 1 && a <= 12)
{
if (a == 2)
{
printf("28\n");
}
else if (a <= 7 && (a % 2) == 1)
{
printf("31\n");
}
else if (a <= 7 && (a % 2) == 0)
{
printf("30\n");
}
else if (a >= 8 && (a % 2) == 0)
{
printf("31\n");
}
else if (a >= 8 && (a % 2) == 1)
{
printf("30\n");
}
}
else
{
printf("error!\n");
}
return 0;
}
int T12(void)
{
float a, b, c;
scanf_s("%f%f%f",&a,&b,&c);
if (a!=0)
{
}
return 0;
}
int T13(void)
{
return 0;
}
int T14(void)
{
return 0;
}
int T15(void)
{
return 0;
}
int T16(void)
{
return 0;
}
int T17(void)
{
return 0;
}
int T18(void)
{
return 0;
}
int T19(void)
{
return 0;
}
int T20(void)
{
return 0;
}
int main()
{
start:
//T1();
//T2();
//T3();
//T4();
//T5();
//T6();
//T7();
//T8();
//T9();
//T10();
T11();
T12();
goto start;
return 0;
} | [
"1494854781@qq.com"
] | 1494854781@qq.com |
1efb8eadd478c066d4f3dab23a2b07aa6d1867fb | 71ef8e94ca186e048e900f0e0d1401b25245bbfb | /Queue (array-based)/Queue.cpp | 9aba1e67f3ecb790598d876969abbfa79402341e | [] | no_license | AmrBumadian/Data-Structures-Implementation | 7c3cbf027c637b1a2d6ec56ffae8c167d9721372 | 814ad3d37fd2840cfbca097b3687d88e56507b7d | refs/heads/master | 2023-02-11T05:01:57.388522 | 2021-01-09T05:59:41 | 2021-01-09T05:59:41 | 267,096,161 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,759 | cpp | #include <assert.h>
#include <iostream>
#include "Queue.h"
using namespace std;
template<class T>
void Queue<T>::copy(const Queue<T> &other) {
f = other.f;
b = other.b;
length = other.length;
capacity = other.capacity;
array = new T[capacity];
for (int i = 0; i < capacity; ++i) {
array[i] = other.array[i];
}
}
template<class T>
Queue<T>::Queue(int size) : length(0), capacity(size) {
f = 0;
b = capacity - 1;
array = new T[capacity];
}
template<class T>
Queue<T>::Queue(const Queue<T> &other) {
copy(other);
}
template<class T>
Queue<T> &Queue<T>::operator=(const Queue<T> &other) {
if (this != &other) {
delete[] array;
copy(other);
}
return *this;
}
template<class T>
Queue<T>::~Queue() {
delete[] array;
}
template<class T>
void Queue<T>::push(T value) {
if (length != capacity) {
b = (b + 1) % capacity; // if b + 1 = capacity, go to the empty space in the front b = 0
array[b] = value;
} else {
cerr << "\nQueue is full" << endl;
return;
}
++length;
}
template<class T>
T Queue<T>::pop() {
if (length == 0) {
cerr << "\nCannot remove from empty Queue" << endl;
} else {
T value = array[f];
f = (f + 1) %
capacity; // discard this element and point to the next, if the next index == capacity point to the front of the array
--length;
return value;
}
}
template<class T>
T Queue<T>::front() {
assert(length != 0);
return array[f];
}
template<class T>
T Queue<T>::back() {
assert(length != 0);
return array[b];
}
template<class T>
int Queue<T>::size() {
return length;
}
template<class T>
bool Queue<T>::empty() {
return (length == 0);
}
template<class T>
void Queue<T>::clear() {
delete[] array;
capacity = 1;
length = 0;
array = new T[capacity];
}
template<class T>
bool Queue<T>::resize(int size) { // resize to bigger size only so elements won't be lost
if (size < capacity) {
cerr << "\ncannot make the Queue smaller\n";
return false; // cannot resize
}
T *temp = new T[size]; // allocate new capacity
int i = 0, j = f; // pointers to copy the elements i for the new and j for the old
while (j != b) {
temp[i] = array[j];
++i;
j = (j + 1) % capacity; // make the pointer cycle through the array till it reach b
}
temp[i] = array[b]; // copy the element at b
delete[] array; // delete the old array
array = temp; // point the array pointer to the new array
capacity = size;
f = 0; // front is now the first index
b = length - 1; // back is the last occupied index
return true; // successfully resized;
}
| [
"35141856+AmrBumadian@users.noreply.github.com"
] | 35141856+AmrBumadian@users.noreply.github.com |
7f89b3fcb65bc173e543671fa9bde639650dce28 | ccf9b152ef277495ad927b51e8c22c675e9f883b | /Interview_Practice/Linked Lists/removeKFromList.cpp | 1dc6c0ce8d21ce7d0e9590c4e39de0ac89416509 | [] | no_license | Andruxa0125/CodeFights | 62025d2e1ff80fc3413d1268c08ebbf395f74aac | c17caaeeebffca262c2a6a9d0b2f28503947a810 | refs/heads/master | 2021-09-10T21:36:39.091010 | 2018-04-02T17:52:25 | 2018-04-02T17:52:25 | 125,555,998 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | cpp | // Definition for singly-linked list:
// template<typename T>
// struct ListNode {
// ListNode(const T &v) : value(v), next(nullptr) {}
// T value;
// ListNode *next;
// };
//
ListNode<int> * removeKFromList(ListNode<int> * l, int k)
{
ListNode<int>* start = l;
ListNode<int>* prev = new ListNode<int>();
prev->next = start;
ListNode<int>* result = prev;
while(start != NULL)
{
if(start->value == k)
{
prev->next = start->next;
start = prev->next;
}
else
{
prev = start;
start = start->next;
}
}
return result->next;
}
| [
"andruxa0125@gmail.com"
] | andruxa0125@gmail.com |
fa77b9a5ded5b70b26211eb1ccb699d3b9cc1052 | e6652252222ce9e4ff0664e539bf450bc9799c50 | /d0706/7.6/source/厦门一中黎学丞/ah.cpp | e1a9f4909b5819351ad674fcdd03a1b8e91c57ed | [] | no_license | cjsoft/inasdfz | db0cea1cf19cf6b753353eda38d62f1b783b8f76 | 3690e76404b9189e4dd52de3770d59716c81a4df | refs/heads/master | 2021-01-17T23:13:51.000569 | 2016-07-12T07:21:19 | 2016-07-12T07:21:19 | 62,596,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,664 | cpp | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#define ll long long
using namespace std;
int i,j,k,m,n,s,t;
int read()
{
int x=0;char ch=getchar();
while (ch<'0'||ch>'9') ch=getchar();
while (ch>='0'&&ch<='9') {x=x*10+ch-'0';ch=getchar();}
return x;
}
int sum,m1,a[201000],next[201000],zhi[201000],first[201000],fa[201000],du[200100],d[201000],c[201000];
void insert(int u,int v)
{
next[++m1]=first[u];
first[u]=m1;
zhi[m1]=v;
}
void dfs(int x)
{
if (!du[x]) d[x]++;
for (int k=first[x];k;k=next[k])
dfs(zhi[k]),d[x]+=d[zhi[k]];
}
struct dat{
int s,i;
};
bool cmp(dat a,dat b)
{
return a.s<b.s;
}
void solve(int x)
{
dat b[1100];
int b1=0;
for (int k=first[x];k;k=next[k])
b[++b1].s=d[zhi[k]],b[b1].i=zhi[k];
sort(b+1,b+b1+1,cmp);
for (int i=1;i<=b1;i++)
{
int s=b[i].i;
if (!du[s]) c[s]=i&1?1:-1; else
solve(s);
c[x]+=c[s];
}
if (c[x]>0) c[x]=1; else c[x]=-1;
printf("%d %d\n",x,c[x]);
}
int main()
{
freopen("ah.in","r",stdin);
freopen("ah.out","w",stdout);
int T=read();
while (T--)
{
n=read();
for (i=1;i<=n;i++)
du[i]=0,first[i]=0;
sum=0;
m1=0;
for (i=1;i<=n;i++)
fa[i]=read(),du[fa[i]]++;
for (i=2;i<=n;i++)
insert(fa[i],i);
for (i=1;i<=n;i++)
if (!du[i]) sum++;
for (i=1;i<=n;i++)
{
s=0;
t=0;
for (k=first[i];k;k=next[k])
{
s++;
if (!du[zhi[k]]) t++;
}
// printf("%d %d\n",s,t);
}
for (i=1;i<=n;i++)
a[i]=read();
//rintf("%d\n",sum);
puts("0");
// dfs(1);
// solve(1);
}
}
| [
"egwcyh@qq.com"
] | egwcyh@qq.com |
9f0c3f208f91128db39318228a838f3b0f09c77e | dd39c678bfb14fc437a0469f95c37183bdbb19a4 | /src/src/vocation.h | 6874f2b0060fed16415e916adb1630148c84edfe | [] | no_license | LeandroPerrotta/DarghosTFS04_v4 | ea14d06066f5fc1480ccc8007019bbd6b33bd58f | 173d9ec26011b17dd4102b3539de65ab3ea15017 | refs/heads/master | 2023-06-17T03:24:02.913872 | 2021-07-17T21:10:19 | 2021-07-17T21:10:19 | 387,035,938 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,252 | h | ////////////////////////////////////////////////////////////////////////
// OpenTibia - an opensource roleplaying game
////////////////////////////////////////////////////////////////////////
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////
#ifndef __OTSERV_VOCATION__
#define __OTSERV_VOCATION__
#include "otsystem.h"
#include "enums.h"
enum multiplier_t
{
MULTIPLIER_FIRST = 0,
MULTIPLIER_MELEE = MULTIPLIER_FIRST,
MULTIPLIER_DISTANCE = 1,
MULTIPLIER_DEFENSE = 2,
MULTIPLIER_MAGICDEFENSE = 3,
MULTIPLIER_ARMOR = 4,
MULTIPLIER_MAGIC = 5,
MULTIPLIER_HEALING = 6,
MULTIPLIER_WAND = 7,
MULTIPLIER_MANA = 8,
MULTIPLIER_LAST = MULTIPLIER_MANA
};
enum gain_t
{
GAIN_FIRST = 0,
GAIN_HEALTH = GAIN_FIRST,
GAIN_MANA = 1,
GAIN_SOUL = 2,
GAIN_LAST = GAIN_SOUL
};
class Vocation
{
public:
virtual ~Vocation();
Vocation() {reset();}
Vocation(uint32_t _id): id(_id) {reset();}
void reset();
uint32_t getId() const {return id;}
void setId(int32_t v) {id = v;}
uint32_t getFromVocation() const {return fromVocation;}
void setFromVocation(int32_t v) {fromVocation = v;}
const std::string& getName() const {return name;}
void setName(const std::string& v) {name = v;}
const std::string& getDescription() const {return description;}
void setDescription(const std::string& v) {description = v;}
bool isAttackable() const {return attackable;}
void setAttackable(bool v) {attackable = v;}
bool isPremiumNeeded() const {return needPremium;}
void setNeedPremium(bool v) {needPremium = v;}
uint32_t getAttackSpeed() const {return attackSpeed;}
void setAttackSpeed(uint32_t v) {attackSpeed = v;}
uint32_t getBaseSpeed() const {return baseSpeed;}
void setBaseSpeed(uint32_t v) {baseSpeed = v;}
int32_t getLessLoss() const {return lessLoss;}
void setLessLoss(int32_t v) {lessLoss = v;}
int32_t getGainCap() const {return capGain;}
void setGainCap(int32_t v) {capGain = v;}
uint32_t getGain(gain_t type) const {return gain[type];}
void setGain(gain_t type, uint32_t v) {gain[type] = v;}
uint32_t getGainTicks(gain_t type) const {return gainTicks[type];}
void setGainTicks(gain_t type, uint32_t v) {gainTicks[type] = v;}
uint32_t getGainAmount(gain_t type) const {return gainAmount[type];}
void setGainAmount(gain_t type, uint32_t v) {gainAmount[type] = v;}
float getMultiplier(multiplier_t type) const {return formulaMultipliers[type];}
void setMultiplier(multiplier_t type, float v) {formulaMultipliers[type] = v;}
#ifdef __DARGHOS_CUSTOM__
uint32_t getCriticalChance() const {return m_criticalChance;}
void setCriticalChance(uint32_t chance) {m_criticalChance = chance;}
#endif
int16_t getAbsorb(CombatType_t combat) const {return absorb[combat];}
void increaseAbsorb(CombatType_t combat, int16_t v) {absorb[combat] += v;}
int16_t getReflect(CombatType_t combat) const;
void increaseReflect(Reflect_t type, CombatType_t combat, int16_t v) {reflect[type][combat] += v;}
double getExperienceMultiplier() const {return skillMultipliers[SKILL__LEVEL];}
void setSkillMultiplier(skills_t s, float v) {skillMultipliers[s] = v;}
void setSkillBase(skills_t s, uint32_t v) {skillBase[s] = v;}
uint32_t getReqSkillTries(int32_t skill, int32_t level);
uint64_t getReqMana(uint32_t magLevel);
private:
typedef std::map<uint32_t, uint32_t> cacheMap;
cacheMap cacheSkill[SKILL_LAST + 1];
cacheMap cacheMana;
bool attackable, needPremium;
int32_t lessLoss, capGain;
uint32_t id, fromVocation, baseSpeed, attackSpeed;
std::string name, description;
#ifdef __DARGHOS_CUSTOM__
uint32_t m_criticalChance;
#endif
int16_t absorb[COMBAT_LAST + 1], reflect[REFLECT_LAST + 1][COMBAT_LAST + 1];
uint32_t gain[GAIN_LAST + 1], gainTicks[GAIN_LAST + 1], gainAmount[GAIN_LAST + 1], skillBase[SKILL_LAST + 1];
float skillMultipliers[SKILL__LAST + 1], formulaMultipliers[MULTIPLIER_LAST + 1];
};
typedef std::map<uint32_t, Vocation*> VocationsMap;
class Vocations
{
public:
virtual ~Vocations() {clear();}
static Vocations* getInstance()
{
static Vocations instance;
return &instance;
}
bool reload();
bool loadFromXml();
bool parseVocationNode(xmlNodePtr p);
Vocation* getVocation(uint32_t vocId);
int32_t getVocationId(const std::string& name);
int32_t getPromotedVocation(uint32_t vocationId);
VocationsMap::iterator getFirstVocation() {return vocationsMap.begin();}
VocationsMap::iterator getLastVocation() {return vocationsMap.end();}
private:
static Vocation defVoc;
VocationsMap vocationsMap;
Vocations() {}
void clear();
};
#endif
| [
"leandro_perrotta@hotmail.com"
] | leandro_perrotta@hotmail.com |
35a28677b2574911084d32ca974c7d7019cd68a1 | 00d4aca628e46fc06c597c19ba0d919a580815eb | /core/Processor/ProcessBase.cxx | be2ce1c4971a5aac0dc53c3600d60bdfe0a3fb7b | [] | no_license | yeonjaej/LArCV | a9f1d706c12f1e183378e38268e2a4ee3b9060d9 | c92117bffea0c8ec89cff305e3def5385497e805 | refs/heads/master | 2020-03-25T00:58:25.318085 | 2016-08-24T20:15:19 | 2016-08-24T20:15:19 | 143,215,231 | 0 | 0 | null | 2018-08-01T22:37:08 | 2018-08-01T22:37:08 | null | UTF-8 | C++ | false | false | 881 | cxx | #ifndef PROCESSBASE_CXX
#define PROCESSBASE_CXX
#include "ProcessBase.h"
namespace larcv {
ProcessBase::ProcessBase(const std::string name)
: larcv_base ( name )
, _proc_time ( 0. )
, _proc_count ( 0 )
, _id ( kINVALID_SIZE )
, _profile ( false )
, _fout ( nullptr )
{}
void ProcessBase::_configure_(const PSet& cfg)
{
_profile = cfg.get<bool>("Profile",_profile);
set_verbosity((msg::Level_t)(cfg.get<unsigned short>("Verbosity",logger().level())));
_event_creator=cfg.get<bool>("EventCreator",false);
configure(cfg);
}
bool ProcessBase::_process_(IOManager& mgr)
{
bool status=false;
if(_profile) {
_watch.Start();
status = this->process(mgr);
_proc_time += _watch.WallTime();
++_proc_count;
}else status = this->process(mgr);
return status;
}
}
#endif
| [
"kazuhiro@nevis.columbia.edu"
] | kazuhiro@nevis.columbia.edu |
da8bda37f4028d8803ce565df028d9ec6e5b8c41 | 176eb09d1895c3e18dc27dc5bac53c1ff2fa9245 | /leach/leach.ino | 067d1ef2e58b5b3c32c5ae2ea46c988b29eb1b02 | [] | no_license | giripranay/Embeddedsystems | bc558037d28571d0ec737b8540731ca1500860d0 | af161ddac2d3cdc0042f3a904bc7e0b19599cec0 | refs/heads/master | 2020-07-30T23:01:50.456227 | 2019-09-23T15:49:22 | 2019-09-23T15:49:22 | 210,389,515 | 0 | 0 | null | 2019-10-22T02:24:12 | 2019-09-23T15:27:47 | C++ | UTF-8 | C++ | false | false | 2,809 | ino | #include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#define MASTER // Comment this define to compile sketch on slave device
const int8_t ledPin = LED_BUILTIN;
const char* const ssid = "green"; // Your network SSID (name)
const char* const pass = "12345678"; // Your network password
const uint16_t localPort = 54321; // Local port to listen for UDP packets
#ifdef MASTER
const uint32_t stepDuration = 2000;
IPAddress broadcastAddress;
#endif
WiFiUDP udp;
bool sendPacket(const IPAddress& address, const char* buf, uint8_t bufSize);
void receivePacket();
void setup() {
Serial.begin(115200);
Serial.println();
pinMode(ledPin, OUTPUT);
Serial.print(F("Connecting to "));
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(ledPin, ! digitalRead(ledPin));
delay(500);
Serial.print('.');
}
digitalWrite(ledPin, HIGH);
Serial.println();
Serial.println(F("WiFi connected"));
Serial.println(F("IP address: "));
Serial.println(WiFi.localIP());
#ifdef MASTER
broadcastAddress = (uint32_t)WiFi.localIP() | ~((uint32_t)WiFi.subnetMask());
Serial.print(F("Broadcast address: "));
Serial.println(broadcastAddress);
Serial.print(F("SubnetMAsk address: "));
Serial.println(WiFi.subnetMask());
#endif
Serial.println(F("Starting UDP"));
udp.begin(localPort);
Serial.print(F("Local port: "));
Serial.println(udp.localPort());
}
void loop() {
#ifdef MASTER
static uint32_t nextTime = 0;
if (millis() >= nextTime) {
const char* const info="broadcasting msg";
// bool led = ! digitalRead(ledPin);
//digitalWrite(ledPin, led);
//Serial.print(F("Turn led "));
//Serial.println(led ? F("off") : F("on"));
if (! sendPacket(broadcastAddress, (char*)info, sizeof(info)))
Serial.println(F("Error sending broadcast UDP packet!"));
nextTime = millis() + stepDuration;
}
#endif
if (udp.parsePacket())
receivePacket();
delay(1);
}
bool sendPacket(const IPAddress& address, const char* buf, uint8_t bufSize) {
udp.beginPacket(address, localPort);
udp.write(buf, bufSize);
return (udp.endPacket() == 1);
}
void receivePacket() {
bool led;
udp.read((char*)&led, sizeof(led));
udp.flush();
#ifdef MASTER
if (udp.destinationIP() != broadcastAddress) {
Serial.print(F("Client with IP "));
Serial.print(udp.remoteIP());
// Serial.print(F(" turned led "));
// Serial.println(led ? F("off") : F("on"));
} else {
// Serial.println(F("Skip broadcast packet"));
}
#else
//digitalWrite(ledPin, led);
//led = digitalRead(ledPin);
// Serial.print(F("Turn led "));
// Serial.println(led ? F("off") : F("on"));
//if (! sendPacket(udp.remoteIP(), (uint8_t*)&led, sizeof(led)))
// Serial.println(F("Error sending answering UDP packet!"));
#endif
}
| [
"giripranay.k@dvara.com"
] | giripranay.k@dvara.com |
9a22a4512f9e1f7427347f8d34ab42b4b4994bde | ed9393909378b8c54911a144429953bc237aadb7 | /e-footbot/simulator/battery_sensor.cpp | 1f44ac3b33cdace46eeea19f8c0576f6c7fe7ffb | [] | no_license | isvogor-foi/argos-customizations | 714736175fa33aa7da850911f6c4a10890c8e54e | 71425e63788d9f42a3274dea562325705137ad39 | refs/heads/master | 2021-01-01T06:16:07.996225 | 2017-08-18T19:32:57 | 2017-08-18T19:32:57 | 97,398,276 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,629 | cpp | #include "battery_sensor.h"
#include <argos3/core/simulator/simulator.h>
#include <argos3/core/simulator/entity/composable_entity.h>
#include <argos3/core/simulator/entity/embodied_entity.h>
#include <argos3/plugins/simulator/entities/wheeled_entity.h>
#include <argos3/plugins/simulator/entities/led_equipped_entity.h>
namespace argos {
CBatterySensor::CBatterySensor() :
//m_pcRNG(NULL),
m_sDischargeType("non-linear"),
m_pcBatteryEntity(NULL),
m_pcEmbodiedEntity(NULL),
m_pcLEDs(NULL),
fStartingCapacity(0),
simulation_tick_factor(0),
m_cSpace(CSimulator::GetInstance().GetSpace())
{ }
void CBatterySensor::SetRobot(CComposableEntity& c_entity) {
try {
m_pcEmbodiedEntity = &(c_entity.GetComponent<CEmbodiedEntity>("body"));
m_pcControllableEntity = &(c_entity.GetComponent<CControllableEntity> ("controller"));
m_pcBatteryEntity = &(c_entity.GetComponent<CBatterySensorEquippedEntity>("battery"));
m_pcWheels = &(c_entity.GetComponent<CWheeledEntity>("wheels"));
m_pcLEDs = &(c_entity.GetComponent<CLEDEquippedEntity>("leds"));
}
catch(CARGoSException& ex) {
THROW_ARGOSEXCEPTION_NESTED("Error setting differential steering actuator to entity \"" << c_entity.GetId() << "\"", ex);
}
}
void CBatterySensor::InitCapacity()
{
m_bChargingState = false;
m_bProcessingState = false;
pcRNG = CRandom::CreateRNG("argos"); // default random instance
// min * sec * simulation tick to convert from Ah to Atick
simulation_tick_factor = 60 * 60 * CPhysicsEngine::GetInverseSimulationClockTick();
// for linear doesn't matter (only fConsumedCapacity matters)
m_fSOC = m_pcBatteryEntity->GetStartingCapacity();
fNominalCapacity = m_pcBatteryEntity->GetNominalCapacity() * simulation_tick_factor;
// for linear ok
fStartingCapacity = fNominalCapacity * m_pcBatteryEntity->GetStartingCapacity();
fConsumedCapacity = fNominalCapacity - fStartingCapacity;
if(m_pcBatteryEntity->GetRandomizeInitialSOC()){
float random = (float)(GetRandomInteger(m_pcBatteryEntity->GetStartingCapacityJitterMin(), m_pcBatteryEntity->GetStartingCapacityJitterMax(), pcRNG)) / 100.0f;
fStartingCapacity = (m_pcBatteryEntity->GetNominalCapacity() * random) * simulation_tick_factor;
fConsumedCapacity = fNominalCapacity - fStartingCapacity;
}
// add random jitter to battery consumption elements (idle, driving, processing)
m_pcBatteryEntity->SetIdleCurrent(m_pcBatteryEntity->GetIdleCurrent() *
(float)(GetRandomInteger(m_pcBatteryEntity->GetJitterPercentageMin(), m_pcBatteryEntity->GetJitterPercentageMax(), pcRNG)) / 100.0f);
m_pcBatteryEntity->SetDriveCurrent(m_pcBatteryEntity->GetDriveCurrent() *
(float)(GetRandomInteger(m_pcBatteryEntity->GetJitterPercentageMin(), m_pcBatteryEntity->GetJitterPercentageMax(), pcRNG)) / 100.0f);
m_pcBatteryEntity->SetProcessingCurrent(m_pcBatteryEntity->GetProcessingCurrent() *
(float)(GetRandomInteger(m_pcBatteryEntity->GetJitterPercentageMin(), m_pcBatteryEntity->GetJitterPercentageMax(), pcRNG)) / 100.0f);
}
void CBatterySensor::Init(TConfigurationNode & t_tree)
{
try {
CCI_BatterySensor::Init(t_tree);
m_pcBatteryEntity->Init(t_tree);
CBatterySensor::InitCapacity();
// read XML attributes
GetNodeAttributeOrDefault(t_tree, "discharge_type", m_sDischargeType, m_sDischargeType);
m_bConvertCharge = false;
m_bConvertDischarge = false;
if(m_sDischargeType.compare("non-linear") == 0){
m_bConvertCharge = true;
}
// parameter cheatsheet (hardcoded voltages -> 1cell battery)
// https://www.desmos.com/calculator/hycpcbwtbq
std::vector<double> Xd(4), Yd(4);
// normalize Ah to [0,1] range
Xd[0]= 0.0 * fNominalCapacity; Yd[0]=4.2;
Xd[1]= 0.25 * fNominalCapacity; Yd[1]=3.7;
Xd[2]= 0.75 * fNominalCapacity; Yd[2]=3.2;
Xd[3]= 1.0 * fNominalCapacity; Yd[3]=2.2;
dischargeSplineFunction.set_points(Xd, Yd);
std::vector<double> Xc(4), Yc(4);
Xc[0]= 0.0 * fNominalCapacity; Yc[0]=4.2;
Xc[1]= 0.1 * fNominalCapacity; Yc[1]=4.15;
Xc[2]= 0.4 * fNominalCapacity; Yc[2]=3.8;
Xc[3]= 1.0 * fNominalCapacity; Yc[3]=2.2;
chargeSplineFunction.set_points(Xc,Yc);
} catch (CARGoSException& ex) {
THROW_ARGOSEXCEPTION_NESTED("Initialization error in default battery sensor", ex);
}
}
void CBatterySensor::Update()
{
if(m_bChargingState){
Charging();
}else{
Discharging();
}
CBatterySensor::UpdateLEDs();
}
/*
* Update LED Colors
* The beacon color will is automatically updated to color between red and green gradient (from 0 to 100 respectively).
* Depending on the robot actions, the surrounding LEDs will glow:
* - WHITE default
* - BLUE if robot is processing (regardless of it driving or not)
* - YELLOW if robot is charging
*/
void CBatterySensor::UpdateLEDs()
{
if(m_bChargingState){
m_pcLEDs->SetAllLEDsColors(CColor::YELLOW);
} else if (m_bProcessingState){
m_pcLEDs->SetAllLEDsColors(CColor::BLUE);
} else {
m_pcLEDs->SetAllLEDsColors(CColor::WHITE);
}
int accent_parameter = 0;
if(m_fSOC >= 80){
accent_parameter = 20;
}else
if(m_fSOC <= 40){
accent_parameter = -15;
}
if(m_fSOC - 15 <= 0){
hsv_color = new HSVColor(0, 1.0f, 0.3f);
}else{
hsv_color = new HSVColor(m_fSOC + accent_parameter, 1.0f, 0.3f);
}
RGBColor rgb_color = HSVColorToRGB(hsv_color);
const CColor *color = new CColor((UInt8)(rgb_color.red), (UInt8)(rgb_color.green), (UInt8)(rgb_color.blue));
m_pcLEDs->GetLED(12).SetColor(*color);
}
void CBatterySensor::Charging()
{
if(m_sDischargeType.compare("linear") == 0){
//fConsumedCapacity -= charging_current / 60 / 60 / CPhysicsEngine::GetInverseSimulationClockTick();
fConsumedCapacity -= m_pcBatteryEntity->GetChargingCurrent();
m_fSOC = (1 - fConsumedCapacity / fNominalCapacity) * 100;
}else{
fConsumedCapacity -= m_pcBatteryEntity->GetChargingCurrent();
if(m_bConvertCharge){
fConsumedCapacity = CBatterySensor::FindCapacity(fConsumedCapacity);
m_bConvertCharge = false;
m_bConvertDischarge = true;
}
m_fSOC = (chargeSplineFunction(fConsumedCapacity) - m_pcBatteryEntity->GetEmptyVoltage()) /
(m_pcBatteryEntity->GetVoltage() - m_pcBatteryEntity->GetEmptyVoltage()) * 100;
}
if(m_fSOC >= 100){
m_fSOC = 100;
fConsumedCapacity = 0;
}
}
Real CBatterySensor::FindCapacity(Real capacity){
float TOLERANCE = 0.001;
for(float i = 0.0; i <= fNominalCapacity; i+= 0.1){
float diff = 0;
if(m_bConvertCharge){
diff = dischargeSplineFunction(capacity) - chargeSplineFunction(i);
} else {
diff = chargeSplineFunction(capacity) - dischargeSplineFunction(i);
}
if(diff < TOLERANCE && -diff < TOLERANCE){
return i;
}
}
return 0;
}
void CBatterySensor::Discharging()
{
float totalCurrent = 0;
Real driveCurrent = m_pcBatteryEntity->GetDriveCurrent();
// if wheels are spinning, add driving current consumption
if(m_pcWheels->GetWheelVelocity(0) == 0 || m_pcWheels->GetWheelVelocity(1) == 0){
driveCurrent = driveCurrent / 2.0f;
}else
if(m_pcWheels->GetWheelVelocity(0) == 0 && m_pcWheels->GetWheelVelocity(1) == 0){
driveCurrent = 0.0f;
}
// check if processing, add processing current consumption
if(m_bProcessingState){
totalCurrent = driveCurrent + m_pcBatteryEntity->GetIdleCurrent() + m_pcBatteryEntity->GetProcessingCurrent();
}else{
totalCurrent = driveCurrent + m_pcBatteryEntity->GetIdleCurrent();
}
// calculate SOC based on one of two methods available (linear / non-linear)
// this should be reprogrammed to use voltage only
if(m_fSOC > 0){
fConsumedCapacity += totalCurrent;
if(m_sDischargeType.compare("linear") == 0){
m_fSOC = (1 - fConsumedCapacity / fNominalCapacity) * 100;
}else{
if(m_bConvertDischarge){
fConsumedCapacity = CBatterySensor::FindCapacity(fConsumedCapacity);
m_bConvertDischarge = false;
m_bConvertCharge = true;
}
m_fSOC = (dischargeSplineFunction(fConsumedCapacity) - m_pcBatteryEntity->GetEmptyVoltage()) / (m_pcBatteryEntity->GetVoltage() - m_pcBatteryEntity->GetEmptyVoltage()) * 100;
}
}
else{
m_fSOC = 0;
}
}
CBatterySensor::RGBColor CBatterySensor::HSVColorToRGB(CBatterySensor::HSVColor *color)
{
double red = 0;
double green = 0;
double blue = 0;
if(color->saturation == 0){
red = color->value;
green = color->value;
blue = color->value;
}else{
int hue_truncated = 0;
double f, p, q, t;
// get quarter in which the color is
if(color->hue == 360){
color->hue = 0;
}else{
color->hue /= 60;
}
hue_truncated = (int)(trunc(color->hue));
f = color->hue - hue_truncated;
p = color->value * (1.0 - color->saturation);
q = color->value * (1.0 - (color->saturation * f));
t = color->value * (1.0 - (color->saturation * (1.0 - f)));
switch (hue_truncated){
case 0:
red = color->value;
green = t;
blue = p;
break;
case 1:
red = q;
green = color->value;
blue = p;
break;
case 2:
red = p;
green = color->value;
blue = t;
break;
case 3:
red = p;
green = q;
blue = color->value;
break;
case 4:
red = t;
green = p;
blue = color->value;
break;
default:
red = color->value;
green = p;
blue = q;
break;
}
}
return CBatterySensor::RGBColor((unsigned char)((red * 255)), (unsigned char)((green * 255)), (unsigned char)((blue * 255)));
};
int CBatterySensor::GetRandomInteger(int min, int max, CRandom::CRNG* pcRNG){
CRange < UInt32 > cRange(min, max);
int random = pcRNG->Uniform(cRange);
return random;
}
void CBatterySensor::Reset() {
}
REGISTER_SENSOR(CBatterySensor,
"battery", "default",
"Ivan Svogor",
"0.3",
"Battery sensor for e-footbot (footbot copy with battery extensions)",
"Currently some concerns are not separated, e.g. sensor enables setting state of charge and processing."
"parameters should be in amp-hours (Ah) for capacity, and amps (A) for current",
"Under development"
);
} // end namespace
| [
"isvogor@gmail.com"
] | isvogor@gmail.com |
48d56141115acf7df1a9ca41e3c616140aab453f | 262d93a5a33237268c90788ff141c4504e7f18d3 | /src/functions/div.cpp | 6c27fad24785c0b3056b1984068e4227726e5afa | [] | no_license | chadac/cppgp | 41240b634181252e525e19332a61aa9931daa37d | 24d797d762d3c3b04280970ef83a3518f162069d | refs/heads/master | 2021-06-01T03:25:51.157478 | 2016-04-04T22:12:59 | 2016-04-04T22:12:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | cpp | #include "div.h"
gpf_div = new FunctionDiv();
FunctionDiv::FunctionDiv() : Function(2, GPTYPE_REAL) {}
int FunctionDiv::get_arg_type(int index) {
return GPTYPE_REAL;
}
GPValue FunctionDiv::evaluate(GPValue* args) {
double arg1 = *((double*)(args[0]->value));
double arg2 = *((double*)(args[1]->value));
double* r = new double;
*r = arg1 / arg2;
return GPValue(GPTYPE_REAL, (int*) r);
}
| [
"chad-crawford@utulsa.edu"
] | chad-crawford@utulsa.edu |
89fb4e6fe00e5a5ebc6c51a5df1a5b1c08d61ebe | 09d881298342dbb1be3f83e5f314e2d5946969b9 | /cc3k/character.h | ce0972ed5903d25373296ffe77f0471d5da0d73f | [] | no_license | BryanSun-24/cc3k | cf88eb930d675c33f4fa3c2dbe22ac34557e0288 | cc0e67e0ffb7ac4de9fc00d283eaa321f913755b | refs/heads/master | 2022-12-04T02:49:43.804765 | 2020-08-16T03:28:55 | 2020-08-16T03:28:55 | 285,062,167 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | h | #ifndef CHARACTER_H
#define CHARACTER_H
#include <string>
#include "state.h"
class Character: public State {
int health;
int attack;
int defense;
int gold;
bool Alive;
std::string race;
public:
Character(int x, int y, int health, int attack, int defense, int gold, std::string race);
virtual ~Character() {};
void addHealth(int health);
void setMaxHealth(int health);
void addGold(int gold);
int getGold();
int getAttack();
int getHealth();
int getDefense();
bool isAlive();
std::string getRaceType();
};
#endif
| [
"bryant.kai1227@gmail.com"
] | bryant.kai1227@gmail.com |
728c2fb264c157b0065a532265f7d046dfe257ce | a02c2866eea844057ea6750d44ecedac8ef53dca | /ClassExamples/IoT-AR/NodeMCU_Board/ButtonLED/ButtonLED.ino | c861d7e3f73238804e5fba6d229a8bdee23438e8 | [] | no_license | sarwansingh/IoT | a076f7b6a5fcd6557a59c88712fa3cf032178a9e | 290970ea6d5d1c17a5fcffcd804d9d2065273a53 | refs/heads/master | 2023-07-18T16:44:23.650685 | 2021-09-24T09:04:36 | 2021-09-24T09:04:36 | 125,970,428 | 1 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 810 | ino |
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 16; // the number of the pushbutton pin
const int ledPin = 2; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
| [
"sarwan_singh@yahoo.com"
] | sarwan_singh@yahoo.com |
f85d2007389739f77e74a542550486b8035fda8c | 9d6f8dfe3f74390e35d43f2f6d072a71d2237828 | /grid_path.cpp | c35bb72a667424cbc94340aceb875bbddfd7c826 | [] | no_license | wanghw1003/EBAStar | 35bbe1d98c124b72c513d87cb840490ff711f015 | 814075cd25c2ac4c25f9d59b0d40c3d335abc60e | refs/heads/master | 2023-07-17T14:12:55.912465 | 2021-08-30T11:15:14 | 2021-08-30T11:15:14 | 401,306,381 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,863 | cpp | /*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, 2013, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Eitan Marder-Eppstein
* David V. Lu!!
*********************************************************************/
#include <global_planner/grid_path.h>
#include <algorithm>
#include <stdio.h>
namespace global_planner {
bool GridPath::getPath(float* potential, double start_x, double start_y, double end_x, double end_y, std::vector<std::pair<float, float> >& path) {
std::pair<float, float> current;
current.first = end_x;
current.second = end_y;
int start_index = getIndex(start_x, start_y);
path.push_back(current);
int c = 0;
int ns = xs_ * ys_;
while (getIndex(current.first, current.second) != start_index) {
float min_val = 1e10;
int min_x = 0, min_y = 0;
for (int xd = -1; xd <= 1; xd++) {
for (int yd = -1; yd <= 1; yd++) {
if (xd == 0 && yd == 0)
continue;
//8个方向
int x = current.first + xd, y = current.second + yd;
int index = getIndex(x, y);
//判断潜力值最小的
if (potential[index] < min_val) {
min_val = potential[index];
min_x = x;
min_y = y;
}
}
}
if (min_x == 0 && min_y == 0)
return false;
//在此处对生成路径进行平滑化处理//
if ( (path[1].first == min_x) || (( path[1].second == (min_y+2) ) && ( path[1].second == (min_y-2) )) ){
path.pop_back();
current.first = min_x;
path.push_back(current);
}
if ( (path[1].second == min_y) || (( path[1].first == (min_x+2) ) && ( path[1].first == (min_x-2) )) ){
path.pop_back();
current.second = min_y;
path.push_back(current);
}
//***************************//
current.first = min_x;
current.second = min_y;
path.push_back(current);
if(c++>ns*4){
return false;
}
}
return true;
}
} //end namespace global_planner
| [
"210271138@qq.com"
] | 210271138@qq.com |
80dd3909f27f40b83729bab1b975f2c3e655358c | c863dc53ac78d3634eb9ef164ae4cb5d93726a04 | /openFrameworks/game/Bush.h | 8fb0cd7dcc6d2ff2b6b3c398279b2c21847bfa91 | [] | no_license | atbaird/CSE5390_GraphicsLibraryStuff | 543dfe694846e8d9c3595a295a41f4e1fbea3caa | a9bc68ed61f1193e8e850cb3eb84838fd0b8b53b | refs/heads/master | 2020-12-30T10:10:49.131407 | 2014-06-30T17:54:29 | 2014-06-30T17:54:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | h | #include "Animation.h"
#ifndef BUSH_H
#define BUSH_H
class Bush {
public:
Bush();
~Bush();
void setLocation(float, float);
void draw();
void setScale(float, float);
float getYSize();
float getXSize();
float getX();
float getY();
private:
Animation anim;
float x, y;
};
#endif | [
"atbaird@smu.edu"
] | atbaird@smu.edu |
34fa439c3ed8ed751371c9577f6771545bbc99d3 | 93b83850891b8445ebab39d81da8fd1abdcd9358 | /tablemodel.h | 24b575892fb61c6be09c90c30fdb4a906d7a2f1a | [] | no_license | stevexu/casher-app | a00d00afba268ccf5ff794c7eff9fbc2c5fc61dc | f0ff2ed8102eb8968bd88363f7f763ad1dbb798a | refs/heads/master | 2021-01-18T16:22:52.983233 | 2009-10-29T16:40:04 | 2009-10-29T16:40:04 | 354,257 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,217 | h | #ifndef DEPTABLEMODEL_H
#define DEPTABLEMODEL_H
#include <QAbstractTableModel>
#include <qlist.h>
#include <qvector>
class QStringList;
typedef QVector<QString> TableRow;
typedef QList<TableRow> TableRecords;
typedef TableRow TableHeader;
class TableModel : public QAbstractTableModel
{
Q_OBJECT
public:
TableModel(QObject *parent = 0);
TableModel(TableRecords& listOfDep, QWidget* parent = 0);
int rowCount(const QModelIndex &parent /* = QModelIndex */) const;
int columnCount(const QModelIndex &parent /* = QModelIndex */) const;
QVariant data(const QModelIndex &index, int role /* = Qt::DisplayRole */) const;
QVariant headerData(int section, Qt::Orientation orientation, int role /* = Qt::DisplayRole */) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole );
bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex());
bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex() );
TableRecords getList();
void setHeader(const QStringList& headers);
~TableModel();
private:
TableRecords m_listOfDep;
TableHeader m_header;
};
#endif // DEPTABLEMODEL_H
| [
"xy@.(none)"
] | xy@.(none) |
3fb74d584e2e162f0fb26b540dfc2ebe390cef65 | cecfc49fb9254498c3b885ae947cd0d9339f2f9a | /pro.cpp | bdf1b7b505b2bd70d31d559f7e06b188441fcb24 | [
"Unlicense"
] | permissive | t3nsor/SPOJ | f6e4755fe08654c9a166e5aaf16f6dcbb6fc5099 | 03145e8bf2cefb3e49a0cd0da5ec908e924d4728 | refs/heads/master | 2023-04-28T19:04:32.529674 | 2023-04-17T23:49:49 | 2023-04-17T23:49:49 | 24,963,181 | 279 | 130 | Unlicense | 2020-10-30T00:33:57 | 2014-10-08T22:07:33 | C++ | UTF-8 | C++ | false | false | 419 | cpp | // 2009-05-05
#include <iostream>
#include <set>
using namespace std;
int main()
{
int N,n,x;
scanf("%d",&N);
long long res=0;
multiset<int> S;
while (N--)
{
scanf("%d",&n);
while (n--)
{
scanf("%d",&x);
S.insert(x);
}
multiset<int>::iterator begin=S.begin();
multiset<int>::iterator end=S.end(); end--;
res+=*end-*begin;
S.erase(begin); S.erase(end);
}
printf("%lld\n",res);
return 0;
}
| [
"bbi5291@gmail.com"
] | bbi5291@gmail.com |
38acf433c29df03feb7eeabe81a2044663c3ed70 | 290b4c7ca63a975b38e55018cc38bd2766e14639 | /ORC_app/jni-build/jni/include/external/eigen_archive/eigen-eigen-4c94692de3e5/Eigen/src/Core/ProductEvaluators.h | d9fd888cfd801291b8ea9af6cccbaa1a87c89b62 | [
"MIT",
"Minpack",
"MPL-2.0",
"LGPL-2.1-only",
"GPL-3.0-only",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LGPL-2.1-or-later"
] | permissive | luoabd/EMNIST-ORC | 1233c373abcc3ed237c2ec86491b29c0b9223894 | 8c2d633a9b4d5214e908550812f6a2489ba9eb72 | refs/heads/master | 2022-12-27T14:03:55.046933 | 2020-01-16T15:20:04 | 2020-01-16T15:20:04 | 234,325,497 | 0 | 1 | MIT | 2022-12-11T13:32:42 | 2020-01-16T13:25:23 | C++ | UTF-8 | C++ | false | false | 46,234 | h | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2011 Jitse Niesen <jitse@maths.leeds.ac.uk>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PRODUCTEVALUATORS_H
#define EIGEN_PRODUCTEVALUATORS_H
namespace Eigen {
namespace internal {
/** \internal
* Evaluator of a product expression.
* Since products require special treatments to handle all possible cases,
* we simply deffer the evaluation logic to a product_evaluator class
* which offers more partial specialization possibilities.
*
* \sa class product_evaluator
*/
template<typename Lhs, typename Rhs, int Options>
struct evaluator<Product<Lhs, Rhs, Options> >
: public product_evaluator<Product<Lhs, Rhs, Options> >
{
typedef Product<Lhs, Rhs, Options> XprType;
typedef product_evaluator<XprType> Base;
EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) : Base(xpr) {}
};
// Catch scalar * ( A * B ) and transform it to (A*scalar) * B
// TODO we should apply that rule only if that's really helpful
template<typename Lhs, typename Rhs, typename Scalar>
struct evaluator_assume_aliasing<CwiseUnaryOp<internal::scalar_multiple_op<Scalar>, const Product<Lhs, Rhs, DefaultProduct> > >
{
static const bool value = true;
};
template<typename Lhs, typename Rhs, typename Scalar>
struct evaluator<CwiseUnaryOp<internal::scalar_multiple_op<Scalar>, const Product<Lhs, Rhs, DefaultProduct> > >
: public evaluator<Product<CwiseUnaryOp<internal::scalar_multiple_op<Scalar>,const Lhs>, Rhs, DefaultProduct> >
{
typedef CwiseUnaryOp<internal::scalar_multiple_op<Scalar>, const Product<Lhs, Rhs, DefaultProduct> > XprType;
typedef evaluator<Product<CwiseUnaryOp<internal::scalar_multiple_op<Scalar>,const Lhs>, Rhs, DefaultProduct> > Base;
EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr)
: Base(xpr.functor().m_other * xpr.nestedExpression().lhs() * xpr.nestedExpression().rhs())
{}
};
template<typename Lhs, typename Rhs, int DiagIndex>
struct evaluator<Diagonal<const Product<Lhs, Rhs, DefaultProduct>, DiagIndex> >
: public evaluator<Diagonal<const Product<Lhs, Rhs, LazyProduct>, DiagIndex> >
{
typedef Diagonal<const Product<Lhs, Rhs, DefaultProduct>, DiagIndex> XprType;
typedef evaluator<Diagonal<const Product<Lhs, Rhs, LazyProduct>, DiagIndex> > Base;
EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr)
: Base(Diagonal<const Product<Lhs, Rhs, LazyProduct>, DiagIndex>(
Product<Lhs, Rhs, LazyProduct>(xpr.nestedExpression().lhs(), xpr.nestedExpression().rhs()),
xpr.index() ))
{}
};
// Helper class to perform a matrix product with the destination at hand.
// Depending on the sizes of the factors, there are different evaluation strategies
// as controlled by internal::product_type.
template< typename Lhs, typename Rhs,
typename LhsShape = typename evaluator_traits<Lhs>::Shape,
typename RhsShape = typename evaluator_traits<Rhs>::Shape,
int ProductType = internal::product_type<Lhs,Rhs>::value>
struct generic_product_impl;
template<typename Lhs, typename Rhs>
struct evaluator_assume_aliasing<Product<Lhs, Rhs, DefaultProduct> > {
static const bool value = true;
};
// This is the default evaluator implementation for products:
// It creates a temporary and call generic_product_impl
template<typename Lhs, typename Rhs, int Options, int ProductTag, typename LhsShape, typename RhsShape>
struct product_evaluator<Product<Lhs, Rhs, Options>, ProductTag, LhsShape, RhsShape>
: public evaluator<typename Product<Lhs, Rhs, Options>::PlainObject>
{
typedef Product<Lhs, Rhs, Options> XprType;
typedef typename XprType::PlainObject PlainObject;
typedef evaluator<PlainObject> Base;
enum {
Flags = Base::Flags | EvalBeforeNestingBit
};
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
explicit product_evaluator(const XprType& xpr)
: m_result(xpr.rows(), xpr.cols())
{
::new (static_cast<Base*>(this)) Base(m_result);
// FIXME shall we handle nested_eval here?,
// if so, then we must take care at removing the call to nested_eval in the specializations (e.g., in permutation_matrix_product, transposition_matrix_product, etc.)
// typedef typename internal::nested_eval<Lhs,Rhs::ColsAtCompileTime>::type LhsNested;
// typedef typename internal::nested_eval<Rhs,Lhs::RowsAtCompileTime>::type RhsNested;
// typedef typename internal::remove_all<LhsNested>::type LhsNestedCleaned;
// typedef typename internal::remove_all<RhsNested>::type RhsNestedCleaned;
//
// const LhsNested lhs(xpr.lhs());
// const RhsNested rhs(xpr.rhs());
//
// generic_product_impl<LhsNestedCleaned, RhsNestedCleaned>::evalTo(m_result, lhs, rhs);
generic_product_impl<Lhs, Rhs, LhsShape, RhsShape, ProductTag>::evalTo(m_result, xpr.lhs(), xpr.rhs());
}
protected:
PlainObject m_result;
};
// Dense = Product
template< typename DstXprType, typename Lhs, typename Rhs, int Options, typename Scalar>
struct Assignment<DstXprType, Product<Lhs,Rhs,Options>, internal::assign_op<Scalar>, Dense2Dense,
typename enable_if<(Options==DefaultProduct || Options==AliasFreeProduct),Scalar>::type>
{
typedef Product<Lhs,Rhs,Options> SrcXprType;
static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op<Scalar> &)
{
// FIXME shall we handle nested_eval here?
generic_product_impl<Lhs, Rhs>::evalTo(dst, src.lhs(), src.rhs());
}
};
// Dense += Product
template< typename DstXprType, typename Lhs, typename Rhs, int Options, typename Scalar>
struct Assignment<DstXprType, Product<Lhs,Rhs,Options>, internal::add_assign_op<Scalar>, Dense2Dense,
typename enable_if<(Options==DefaultProduct || Options==AliasFreeProduct),Scalar>::type>
{
typedef Product<Lhs,Rhs,Options> SrcXprType;
static void run(DstXprType &dst, const SrcXprType &src, const internal::add_assign_op<Scalar> &)
{
// FIXME shall we handle nested_eval here?
generic_product_impl<Lhs, Rhs>::addTo(dst, src.lhs(), src.rhs());
}
};
// Dense -= Product
template< typename DstXprType, typename Lhs, typename Rhs, int Options, typename Scalar>
struct Assignment<DstXprType, Product<Lhs,Rhs,Options>, internal::sub_assign_op<Scalar>, Dense2Dense,
typename enable_if<(Options==DefaultProduct || Options==AliasFreeProduct),Scalar>::type>
{
typedef Product<Lhs,Rhs,Options> SrcXprType;
static void run(DstXprType &dst, const SrcXprType &src, const internal::sub_assign_op<Scalar> &)
{
// FIXME shall we handle nested_eval here?
generic_product_impl<Lhs, Rhs>::subTo(dst, src.lhs(), src.rhs());
}
};
// Dense ?= scalar * Product
// TODO we should apply that rule if that's really helpful
// for instance, this is not good for inner products
template< typename DstXprType, typename Lhs, typename Rhs, typename AssignFunc, typename Scalar, typename ScalarBis>
struct Assignment<DstXprType, CwiseUnaryOp<internal::scalar_multiple_op<ScalarBis>,
const Product<Lhs,Rhs,DefaultProduct> >, AssignFunc, Dense2Dense, Scalar>
{
typedef CwiseUnaryOp<internal::scalar_multiple_op<ScalarBis>,
const Product<Lhs,Rhs,DefaultProduct> > SrcXprType;
static void run(DstXprType &dst, const SrcXprType &src, const AssignFunc& func)
{
call_assignment_no_alias(dst, (src.functor().m_other * src.nestedExpression().lhs())*src.nestedExpression().rhs(), func);
}
};
//----------------------------------------
// Catch "Dense ?= xpr + Product<>" expression to save one temporary
// FIXME we could probably enable these rules for any product, i.e., not only Dense and DefaultProduct
// TODO enable it for "Dense ?= xpr - Product<>" as well.
template<typename OtherXpr, typename Lhs, typename Rhs>
struct evaluator_assume_aliasing<CwiseBinaryOp<internal::scalar_sum_op<typename OtherXpr::Scalar>, const OtherXpr,
const Product<Lhs,Rhs,DefaultProduct> >, DenseShape > {
static const bool value = true;
};
template<typename DstXprType, typename OtherXpr, typename ProductType, typename Scalar, typename Func1, typename Func2>
struct assignment_from_xpr_plus_product
{
typedef CwiseBinaryOp<internal::scalar_sum_op<Scalar>, const OtherXpr, const ProductType> SrcXprType;
static void run(DstXprType &dst, const SrcXprType &src, const Func1& func)
{
call_assignment_no_alias(dst, src.lhs(), func);
call_assignment_no_alias(dst, src.rhs(), Func2());
}
};
template< typename DstXprType, typename OtherXpr, typename Lhs, typename Rhs, typename Scalar>
struct Assignment<DstXprType, CwiseBinaryOp<internal::scalar_sum_op<Scalar>, const OtherXpr,
const Product<Lhs,Rhs,DefaultProduct> >, internal::assign_op<Scalar>, Dense2Dense>
: assignment_from_xpr_plus_product<DstXprType, OtherXpr, Product<Lhs,Rhs,DefaultProduct>, Scalar, internal::assign_op<Scalar>, internal::add_assign_op<Scalar> >
{};
template< typename DstXprType, typename OtherXpr, typename Lhs, typename Rhs, typename Scalar>
struct Assignment<DstXprType, CwiseBinaryOp<internal::scalar_sum_op<Scalar>, const OtherXpr,
const Product<Lhs,Rhs,DefaultProduct> >, internal::add_assign_op<Scalar>, Dense2Dense>
: assignment_from_xpr_plus_product<DstXprType, OtherXpr, Product<Lhs,Rhs,DefaultProduct>, Scalar, internal::add_assign_op<Scalar>, internal::add_assign_op<Scalar> >
{};
template< typename DstXprType, typename OtherXpr, typename Lhs, typename Rhs, typename Scalar>
struct Assignment<DstXprType, CwiseBinaryOp<internal::scalar_sum_op<Scalar>, const OtherXpr,
const Product<Lhs,Rhs,DefaultProduct> >, internal::sub_assign_op<Scalar>, Dense2Dense>
: assignment_from_xpr_plus_product<DstXprType, OtherXpr, Product<Lhs,Rhs,DefaultProduct>, Scalar, internal::sub_assign_op<Scalar>, internal::sub_assign_op<Scalar> >
{};
//----------------------------------------
template<typename Lhs, typename Rhs>
struct generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,InnerProduct>
{
template<typename Dst>
static inline void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
dst.coeffRef(0,0) = (lhs.transpose().cwiseProduct(rhs)).sum();
}
template<typename Dst>
static inline void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
dst.coeffRef(0,0) += (lhs.transpose().cwiseProduct(rhs)).sum();
}
template<typename Dst>
static void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{ dst.coeffRef(0,0) -= (lhs.transpose().cwiseProduct(rhs)).sum(); }
};
/***********************************************************************
* Implementation of outer dense * dense vector product
***********************************************************************/
// Column major result
template<typename Dst, typename Lhs, typename Rhs, typename Func>
EIGEN_DONT_INLINE void outer_product_selector_run(Dst& dst, const Lhs &lhs, const Rhs &rhs, const Func& func, const false_type&)
{
evaluator<Rhs> rhsEval(rhs);
typename nested_eval<Lhs,Rhs::SizeAtCompileTime>::type actual_lhs(lhs);
// FIXME if cols is large enough, then it might be useful to make sure that lhs is sequentially stored
// FIXME not very good if rhs is real and lhs complex while alpha is real too
const Index cols = dst.cols();
for (Index j=0; j<cols; ++j)
func(dst.col(j), rhsEval.coeff(0,j) * actual_lhs);
}
// Row major result
template<typename Dst, typename Lhs, typename Rhs, typename Func>
EIGEN_DONT_INLINE void outer_product_selector_run(Dst& dst, const Lhs &lhs, const Rhs &rhs, const Func& func, const true_type&)
{
evaluator<Lhs> lhsEval(lhs);
typename nested_eval<Rhs,Lhs::SizeAtCompileTime>::type actual_rhs(rhs);
// FIXME if rows is large enough, then it might be useful to make sure that rhs is sequentially stored
// FIXME not very good if lhs is real and rhs complex while alpha is real too
const Index rows = dst.rows();
for (Index i=0; i<rows; ++i)
func(dst.row(i), lhsEval.coeff(i,0) * actual_rhs);
}
template<typename Lhs, typename Rhs>
struct generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,OuterProduct>
{
template<typename T> struct is_row_major : internal::conditional<(int(T::Flags)&RowMajorBit), internal::true_type, internal::false_type>::type {};
typedef typename Product<Lhs,Rhs>::Scalar Scalar;
// TODO it would be nice to be able to exploit our *_assign_op functors for that purpose
struct set { template<typename Dst, typename Src> void operator()(const Dst& dst, const Src& src) const { dst.const_cast_derived() = src; } };
struct add { template<typename Dst, typename Src> void operator()(const Dst& dst, const Src& src) const { dst.const_cast_derived() += src; } };
struct sub { template<typename Dst, typename Src> void operator()(const Dst& dst, const Src& src) const { dst.const_cast_derived() -= src; } };
struct adds {
Scalar m_scale;
explicit adds(const Scalar& s) : m_scale(s) {}
template<typename Dst, typename Src> void operator()(const Dst& dst, const Src& src) const {
dst.const_cast_derived() += m_scale * src;
}
};
template<typename Dst>
static inline void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
internal::outer_product_selector_run(dst, lhs, rhs, set(), is_row_major<Dst>());
}
template<typename Dst>
static inline void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
internal::outer_product_selector_run(dst, lhs, rhs, add(), is_row_major<Dst>());
}
template<typename Dst>
static inline void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
internal::outer_product_selector_run(dst, lhs, rhs, sub(), is_row_major<Dst>());
}
template<typename Dst>
static inline void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha)
{
internal::outer_product_selector_run(dst, lhs, rhs, adds(alpha), is_row_major<Dst>());
}
};
// This base class provides default implementations for evalTo, addTo, subTo, in terms of scaleAndAddTo
template<typename Lhs, typename Rhs, typename Derived>
struct generic_product_impl_base
{
typedef typename Product<Lhs,Rhs>::Scalar Scalar;
template<typename Dst>
static void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{ dst.setZero(); scaleAndAddTo(dst, lhs, rhs, Scalar(1)); }
template<typename Dst>
static void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{ scaleAndAddTo(dst,lhs, rhs, Scalar(1)); }
template<typename Dst>
static void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{ scaleAndAddTo(dst, lhs, rhs, Scalar(-1)); }
template<typename Dst>
static void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha)
{ Derived::scaleAndAddTo(dst,lhs,rhs,alpha); }
};
template<typename Lhs, typename Rhs>
struct generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,GemvProduct>
: generic_product_impl_base<Lhs,Rhs,generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,GemvProduct> >
{
typedef typename Product<Lhs,Rhs>::Scalar Scalar;
enum { Side = Lhs::IsVectorAtCompileTime ? OnTheLeft : OnTheRight };
typedef typename internal::conditional<int(Side)==OnTheRight,Lhs,Rhs>::type MatrixType;
template<typename Dest>
static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha)
{
internal::gemv_dense_selector<Side,
(int(MatrixType::Flags)&RowMajorBit) ? RowMajor : ColMajor,
bool(internal::blas_traits<MatrixType>::HasUsableDirectAccess)
>::run(lhs, rhs, dst, alpha);
}
};
template<typename Lhs, typename Rhs>
struct generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,CoeffBasedProductMode>
{
typedef typename Product<Lhs,Rhs>::Scalar Scalar;
template<typename Dst>
static inline void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
// Same as: dst.noalias() = lhs.lazyProduct(rhs);
// but easier on the compiler side
call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::assign_op<Scalar>());
}
template<typename Dst>
static inline void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
// dst.noalias() += lhs.lazyProduct(rhs);
call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::add_assign_op<Scalar>());
}
template<typename Dst>
static inline void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
// dst.noalias() -= lhs.lazyProduct(rhs);
call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::sub_assign_op<Scalar>());
}
// template<typename Dst>
// static inline void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha)
// { dst.noalias() += alpha * lhs.lazyProduct(rhs); }
};
// This specialization enforces the use of a coefficient-based evaluation strategy
template<typename Lhs, typename Rhs>
struct generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,LazyCoeffBasedProductMode>
: generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,CoeffBasedProductMode> {};
// Case 2: Evaluate coeff by coeff
//
// This is mostly taken from CoeffBasedProduct.h
// The main difference is that we add an extra argument to the etor_product_*_impl::run() function
// for the inner dimension of the product, because evaluator object do not know their size.
template<int Traversal, int UnrollingIndex, typename Lhs, typename Rhs, typename RetScalar>
struct etor_product_coeff_impl;
template<int StorageOrder, int UnrollingIndex, typename Lhs, typename Rhs, typename Packet, int LoadMode>
struct etor_product_packet_impl;
template<typename Lhs, typename Rhs, int ProductTag>
struct product_evaluator<Product<Lhs, Rhs, LazyProduct>, ProductTag, DenseShape, DenseShape>
: evaluator_base<Product<Lhs, Rhs, LazyProduct> >
{
typedef Product<Lhs, Rhs, LazyProduct> XprType;
typedef typename XprType::Scalar Scalar;
typedef typename XprType::CoeffReturnType CoeffReturnType;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
explicit product_evaluator(const XprType& xpr)
: m_lhs(xpr.lhs()),
m_rhs(xpr.rhs()),
m_lhsImpl(m_lhs), // FIXME the creation of the evaluator objects should result in a no-op, but check that!
m_rhsImpl(m_rhs), // Moreover, they are only useful for the packet path, so we could completely disable them when not needed,
// or perhaps declare them on the fly on the packet method... We have experiment to check what's best.
m_innerDim(xpr.lhs().cols())
{
EIGEN_INTERNAL_CHECK_COST_VALUE(NumTraits<Scalar>::MulCost);
EIGEN_INTERNAL_CHECK_COST_VALUE(NumTraits<Scalar>::AddCost);
EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost);
}
// Everything below here is taken from CoeffBasedProduct.h
typedef typename internal::nested_eval<Lhs,Rhs::ColsAtCompileTime>::type LhsNested;
typedef typename internal::nested_eval<Rhs,Lhs::RowsAtCompileTime>::type RhsNested;
typedef typename internal::remove_all<LhsNested>::type LhsNestedCleaned;
typedef typename internal::remove_all<RhsNested>::type RhsNestedCleaned;
typedef evaluator<LhsNestedCleaned> LhsEtorType;
typedef evaluator<RhsNestedCleaned> RhsEtorType;
enum {
RowsAtCompileTime = LhsNestedCleaned::RowsAtCompileTime,
ColsAtCompileTime = RhsNestedCleaned::ColsAtCompileTime,
InnerSize = EIGEN_SIZE_MIN_PREFER_FIXED(LhsNestedCleaned::ColsAtCompileTime, RhsNestedCleaned::RowsAtCompileTime),
MaxRowsAtCompileTime = LhsNestedCleaned::MaxRowsAtCompileTime,
MaxColsAtCompileTime = RhsNestedCleaned::MaxColsAtCompileTime
};
typedef typename find_best_packet<Scalar,RowsAtCompileTime>::type LhsVecPacketType;
typedef typename find_best_packet<Scalar,ColsAtCompileTime>::type RhsVecPacketType;
enum {
LhsCoeffReadCost = LhsEtorType::CoeffReadCost,
RhsCoeffReadCost = RhsEtorType::CoeffReadCost,
CoeffReadCost = InnerSize==0 ? NumTraits<Scalar>::ReadCost
: InnerSize == Dynamic ? HugeCost
: InnerSize * (NumTraits<Scalar>::MulCost + LhsCoeffReadCost + RhsCoeffReadCost)
+ (InnerSize - 1) * NumTraits<Scalar>::AddCost,
Unroll = CoeffReadCost <= EIGEN_UNROLLING_LIMIT,
LhsFlags = LhsEtorType::Flags,
RhsFlags = RhsEtorType::Flags,
LhsRowMajor = LhsFlags & RowMajorBit,
RhsRowMajor = RhsFlags & RowMajorBit,
LhsVecPacketSize = unpacket_traits<LhsVecPacketType>::size,
RhsVecPacketSize = unpacket_traits<RhsVecPacketType>::size,
// Here, we don't care about alignment larger than the usable packet size.
LhsAlignment = EIGEN_PLAIN_ENUM_MIN(LhsEtorType::Alignment,LhsVecPacketSize*int(sizeof(typename LhsNestedCleaned::Scalar))),
RhsAlignment = EIGEN_PLAIN_ENUM_MIN(RhsEtorType::Alignment,RhsVecPacketSize*int(sizeof(typename RhsNestedCleaned::Scalar))),
SameType = is_same<typename LhsNestedCleaned::Scalar,typename RhsNestedCleaned::Scalar>::value,
CanVectorizeRhs = RhsRowMajor && (RhsFlags & PacketAccessBit)
&& (ColsAtCompileTime == Dynamic || ((ColsAtCompileTime % RhsVecPacketSize) == 0) ),
CanVectorizeLhs = (!LhsRowMajor) && (LhsFlags & PacketAccessBit)
&& (RowsAtCompileTime == Dynamic || ((RowsAtCompileTime % LhsVecPacketSize) == 0) ),
EvalToRowMajor = (MaxRowsAtCompileTime==1&&MaxColsAtCompileTime!=1) ? 1
: (MaxColsAtCompileTime==1&&MaxRowsAtCompileTime!=1) ? 0
: (RhsRowMajor && !CanVectorizeLhs),
Flags = ((unsigned int)(LhsFlags | RhsFlags) & HereditaryBits & ~RowMajorBit)
| (EvalToRowMajor ? RowMajorBit : 0)
// TODO enable vectorization for mixed types
| (SameType && (CanVectorizeLhs || CanVectorizeRhs) ? PacketAccessBit : 0)
| (XprType::IsVectorAtCompileTime ? LinearAccessBit : 0),
LhsOuterStrideBytes = int(LhsNestedCleaned::OuterStrideAtCompileTime) * int(sizeof(typename LhsNestedCleaned::Scalar)),
RhsOuterStrideBytes = int(RhsNestedCleaned::OuterStrideAtCompileTime) * int(sizeof(typename RhsNestedCleaned::Scalar)),
Alignment = CanVectorizeLhs ? (LhsOuterStrideBytes<0 || (int(LhsOuterStrideBytes) % EIGEN_PLAIN_ENUM_MAX(1,LhsAlignment))!=0 ? 0 : LhsAlignment)
: CanVectorizeRhs ? (RhsOuterStrideBytes<0 || (int(RhsOuterStrideBytes) % EIGEN_PLAIN_ENUM_MAX(1,RhsAlignment))!=0 ? 0 : RhsAlignment)
: 0,
/* CanVectorizeInner deserves special explanation. It does not affect the product flags. It is not used outside
* of Product. If the Product itself is not a packet-access expression, there is still a chance that the inner
* loop of the product might be vectorized. This is the meaning of CanVectorizeInner. Since it doesn't affect
* the Flags, it is safe to make this value depend on ActualPacketAccessBit, that doesn't affect the ABI.
*/
CanVectorizeInner = SameType
&& LhsRowMajor
&& (!RhsRowMajor)
&& (LhsFlags & RhsFlags & ActualPacketAccessBit)
&& (InnerSize % packet_traits<Scalar>::size == 0)
};
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CoeffReturnType coeff(Index row, Index col) const
{
return (m_lhs.row(row).transpose().cwiseProduct( m_rhs.col(col) )).sum();
}
/* Allow index-based non-packet access. It is impossible though to allow index-based packed access,
* which is why we don't set the LinearAccessBit.
* TODO: this seems possible when the result is a vector
*/
EIGEN_DEVICE_FUNC const CoeffReturnType coeff(Index index) const
{
const Index row = RowsAtCompileTime == 1 ? 0 : index;
const Index col = RowsAtCompileTime == 1 ? index : 0;
return (m_lhs.row(row).transpose().cwiseProduct( m_rhs.col(col) )).sum();
}
template<int LoadMode, typename PacketType>
const PacketType packet(Index row, Index col) const
{
PacketType res;
typedef etor_product_packet_impl<bool(int(Flags)&RowMajorBit) ? RowMajor : ColMajor,
Unroll ? int(InnerSize) : Dynamic,
LhsEtorType, RhsEtorType, PacketType, LoadMode> PacketImpl;
PacketImpl::run(row, col, m_lhsImpl, m_rhsImpl, m_innerDim, res);
return res;
}
template<int LoadMode, typename PacketType>
const PacketType packet(Index index) const
{
const Index row = RowsAtCompileTime == 1 ? 0 : index;
const Index col = RowsAtCompileTime == 1 ? index : 0;
return packet<LoadMode,PacketType>(row,col);
}
protected:
const LhsNested m_lhs;
const RhsNested m_rhs;
LhsEtorType m_lhsImpl;
RhsEtorType m_rhsImpl;
// TODO: Get rid of m_innerDim if known at compile time
Index m_innerDim;
};
template<typename Lhs, typename Rhs>
struct product_evaluator<Product<Lhs, Rhs, DefaultProduct>, LazyCoeffBasedProductMode, DenseShape, DenseShape>
: product_evaluator<Product<Lhs, Rhs, LazyProduct>, CoeffBasedProductMode, DenseShape, DenseShape>
{
typedef Product<Lhs, Rhs, DefaultProduct> XprType;
typedef Product<Lhs, Rhs, LazyProduct> BaseProduct;
typedef product_evaluator<BaseProduct, CoeffBasedProductMode, DenseShape, DenseShape> Base;
enum {
Flags = Base::Flags | EvalBeforeNestingBit
};
EIGEN_DEVICE_FUNC explicit product_evaluator(const XprType& xpr)
: Base(BaseProduct(xpr.lhs(),xpr.rhs()))
{}
};
/****************************************
*** Coeff based product, Packet path ***
****************************************/
template<int UnrollingIndex, typename Lhs, typename Rhs, typename Packet, int LoadMode>
struct etor_product_packet_impl<RowMajor, UnrollingIndex, Lhs, Rhs, Packet, LoadMode>
{
static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet &res)
{
etor_product_packet_impl<RowMajor, UnrollingIndex-1, Lhs, Rhs, Packet, LoadMode>::run(row, col, lhs, rhs, innerDim, res);
res = pmadd(pset1<Packet>(lhs.coeff(row, UnrollingIndex-1)), rhs.template packet<LoadMode,Packet>(UnrollingIndex-1, col), res);
}
};
template<int UnrollingIndex, typename Lhs, typename Rhs, typename Packet, int LoadMode>
struct etor_product_packet_impl<ColMajor, UnrollingIndex, Lhs, Rhs, Packet, LoadMode>
{
static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet &res)
{
etor_product_packet_impl<ColMajor, UnrollingIndex-1, Lhs, Rhs, Packet, LoadMode>::run(row, col, lhs, rhs, innerDim, res);
res = pmadd(lhs.template packet<LoadMode,Packet>(row, UnrollingIndex-1), pset1<Packet>(rhs.coeff(UnrollingIndex-1, col)), res);
}
};
template<typename Lhs, typename Rhs, typename Packet, int LoadMode>
struct etor_product_packet_impl<RowMajor, 1, Lhs, Rhs, Packet, LoadMode>
{
static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index /*innerDim*/, Packet &res)
{
res = pmul(pset1<Packet>(lhs.coeff(row, 0)),rhs.template packet<LoadMode,Packet>(0, col));
}
};
template<typename Lhs, typename Rhs, typename Packet, int LoadMode>
struct etor_product_packet_impl<ColMajor, 1, Lhs, Rhs, Packet, LoadMode>
{
static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index /*innerDim*/, Packet &res)
{
res = pmul(lhs.template packet<LoadMode,Packet>(row, 0), pset1<Packet>(rhs.coeff(0, col)));
}
};
template<typename Lhs, typename Rhs, typename Packet, int LoadMode>
struct etor_product_packet_impl<RowMajor, 0, Lhs, Rhs, Packet, LoadMode>
{
static EIGEN_STRONG_INLINE void run(Index /*row*/, Index /*col*/, const Lhs& /*lhs*/, const Rhs& /*rhs*/, Index /*innerDim*/, Packet &res)
{
res = pset1<Packet>(0);
}
};
template<typename Lhs, typename Rhs, typename Packet, int LoadMode>
struct etor_product_packet_impl<ColMajor, 0, Lhs, Rhs, Packet, LoadMode>
{
static EIGEN_STRONG_INLINE void run(Index /*row*/, Index /*col*/, const Lhs& /*lhs*/, const Rhs& /*rhs*/, Index /*innerDim*/, Packet &res)
{
res = pset1<Packet>(0);
}
};
template<typename Lhs, typename Rhs, typename Packet, int LoadMode>
struct etor_product_packet_impl<RowMajor, Dynamic, Lhs, Rhs, Packet, LoadMode>
{
static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet& res)
{
res = pset1<Packet>(0);
for(Index i = 0; i < innerDim; ++i)
res = pmadd(pset1<Packet>(lhs.coeff(row, i)), rhs.template packet<LoadMode,Packet>(i, col), res);
}
};
template<typename Lhs, typename Rhs, typename Packet, int LoadMode>
struct etor_product_packet_impl<ColMajor, Dynamic, Lhs, Rhs, Packet, LoadMode>
{
static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet& res)
{
res = pset1<Packet>(0);
for(Index i = 0; i < innerDim; ++i)
res = pmadd(lhs.template packet<LoadMode,Packet>(row, i), pset1<Packet>(rhs.coeff(i, col)), res);
}
};
/***************************************************************************
* Triangular products
***************************************************************************/
template<int Mode, bool LhsIsTriangular,
typename Lhs, bool LhsIsVector,
typename Rhs, bool RhsIsVector>
struct triangular_product_impl;
template<typename Lhs, typename Rhs, int ProductTag>
struct generic_product_impl<Lhs,Rhs,TriangularShape,DenseShape,ProductTag>
: generic_product_impl_base<Lhs,Rhs,generic_product_impl<Lhs,Rhs,TriangularShape,DenseShape,ProductTag> >
{
typedef typename Product<Lhs,Rhs>::Scalar Scalar;
template<typename Dest>
static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha)
{
triangular_product_impl<Lhs::Mode,true,typename Lhs::MatrixType,false,Rhs, Rhs::ColsAtCompileTime==1>
::run(dst, lhs.nestedExpression(), rhs, alpha);
}
};
template<typename Lhs, typename Rhs, int ProductTag>
struct generic_product_impl<Lhs,Rhs,DenseShape,TriangularShape,ProductTag>
: generic_product_impl_base<Lhs,Rhs,generic_product_impl<Lhs,Rhs,DenseShape,TriangularShape,ProductTag> >
{
typedef typename Product<Lhs,Rhs>::Scalar Scalar;
template<typename Dest>
static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha)
{
triangular_product_impl<Rhs::Mode,false,Lhs,Lhs::RowsAtCompileTime==1, typename Rhs::MatrixType, false>::run(dst, lhs, rhs.nestedExpression(), alpha);
}
};
/***************************************************************************
* SelfAdjoint products
***************************************************************************/
template <typename Lhs, int LhsMode, bool LhsIsVector,
typename Rhs, int RhsMode, bool RhsIsVector>
struct selfadjoint_product_impl;
template<typename Lhs, typename Rhs, int ProductTag>
struct generic_product_impl<Lhs,Rhs,SelfAdjointShape,DenseShape,ProductTag>
: generic_product_impl_base<Lhs,Rhs,generic_product_impl<Lhs,Rhs,SelfAdjointShape,DenseShape,ProductTag> >
{
typedef typename Product<Lhs,Rhs>::Scalar Scalar;
template<typename Dest>
static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha)
{
selfadjoint_product_impl<typename Lhs::MatrixType,Lhs::Mode,false,Rhs,0,Rhs::IsVectorAtCompileTime>::run(dst, lhs.nestedExpression(), rhs, alpha);
}
};
template<typename Lhs, typename Rhs, int ProductTag>
struct generic_product_impl<Lhs,Rhs,DenseShape,SelfAdjointShape,ProductTag>
: generic_product_impl_base<Lhs,Rhs,generic_product_impl<Lhs,Rhs,DenseShape,SelfAdjointShape,ProductTag> >
{
typedef typename Product<Lhs,Rhs>::Scalar Scalar;
template<typename Dest>
static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha)
{
selfadjoint_product_impl<Lhs,0,Lhs::IsVectorAtCompileTime,typename Rhs::MatrixType,Rhs::Mode,false>::run(dst, lhs, rhs.nestedExpression(), alpha);
}
};
/***************************************************************************
* Diagonal products
***************************************************************************/
template<typename MatrixType, typename DiagonalType, typename Derived, int ProductOrder>
struct diagonal_product_evaluator_base
: evaluator_base<Derived>
{
typedef typename scalar_product_traits<typename MatrixType::Scalar, typename DiagonalType::Scalar>::ReturnType Scalar;
public:
enum {
CoeffReadCost = NumTraits<Scalar>::MulCost + evaluator<MatrixType>::CoeffReadCost + evaluator<DiagonalType>::CoeffReadCost,
MatrixFlags = evaluator<MatrixType>::Flags,
DiagFlags = evaluator<DiagonalType>::Flags,
_StorageOrder = MatrixFlags & RowMajorBit ? RowMajor : ColMajor,
_ScalarAccessOnDiag = !((int(_StorageOrder) == ColMajor && int(ProductOrder) == OnTheLeft)
||(int(_StorageOrder) == RowMajor && int(ProductOrder) == OnTheRight)),
_SameTypes = is_same<typename MatrixType::Scalar, typename DiagonalType::Scalar>::value,
// FIXME currently we need same types, but in the future the next rule should be the one
//_Vectorizable = bool(int(MatrixFlags)&PacketAccessBit) && ((!_PacketOnDiag) || (_SameTypes && bool(int(DiagFlags)&PacketAccessBit))),
_Vectorizable = bool(int(MatrixFlags)&PacketAccessBit) && _SameTypes && (_ScalarAccessOnDiag || (bool(int(DiagFlags)&PacketAccessBit))),
_LinearAccessMask = (MatrixType::RowsAtCompileTime==1 || MatrixType::ColsAtCompileTime==1) ? LinearAccessBit : 0,
Flags = ((HereditaryBits|_LinearAccessMask) & (unsigned int)(MatrixFlags)) | (_Vectorizable ? PacketAccessBit : 0),
Alignment = evaluator<MatrixType>::Alignment
};
diagonal_product_evaluator_base(const MatrixType &mat, const DiagonalType &diag)
: m_diagImpl(diag), m_matImpl(mat)
{
EIGEN_INTERNAL_CHECK_COST_VALUE(NumTraits<Scalar>::MulCost);
EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost);
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index idx) const
{
return m_diagImpl.coeff(idx) * m_matImpl.coeff(idx);
}
protected:
template<int LoadMode,typename PacketType>
EIGEN_STRONG_INLINE PacketType packet_impl(Index row, Index col, Index id, internal::true_type) const
{
return internal::pmul(m_matImpl.template packet<LoadMode,PacketType>(row, col),
internal::pset1<PacketType>(m_diagImpl.coeff(id)));
}
template<int LoadMode,typename PacketType>
EIGEN_STRONG_INLINE PacketType packet_impl(Index row, Index col, Index id, internal::false_type) const
{
enum {
InnerSize = (MatrixType::Flags & RowMajorBit) ? MatrixType::ColsAtCompileTime : MatrixType::RowsAtCompileTime,
DiagonalPacketLoadMode = EIGEN_PLAIN_ENUM_MIN(LoadMode,((InnerSize%16) == 0) ? int(Aligned16) : int(evaluator<DiagonalType>::Alignment)) // FIXME hardcoded 16!!
};
return internal::pmul(m_matImpl.template packet<LoadMode,PacketType>(row, col),
m_diagImpl.template packet<DiagonalPacketLoadMode,PacketType>(id));
}
evaluator<DiagonalType> m_diagImpl;
evaluator<MatrixType> m_matImpl;
};
// diagonal * dense
template<typename Lhs, typename Rhs, int ProductKind, int ProductTag>
struct product_evaluator<Product<Lhs, Rhs, ProductKind>, ProductTag, DiagonalShape, DenseShape>
: diagonal_product_evaluator_base<Rhs, typename Lhs::DiagonalVectorType, Product<Lhs, Rhs, LazyProduct>, OnTheLeft>
{
typedef diagonal_product_evaluator_base<Rhs, typename Lhs::DiagonalVectorType, Product<Lhs, Rhs, LazyProduct>, OnTheLeft> Base;
using Base::m_diagImpl;
using Base::m_matImpl;
using Base::coeff;
typedef typename Base::Scalar Scalar;
typedef Product<Lhs, Rhs, ProductKind> XprType;
typedef typename XprType::PlainObject PlainObject;
enum {
StorageOrder = int(Rhs::Flags) & RowMajorBit ? RowMajor : ColMajor
};
EIGEN_DEVICE_FUNC explicit product_evaluator(const XprType& xpr)
: Base(xpr.rhs(), xpr.lhs().diagonal())
{
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index row, Index col) const
{
return m_diagImpl.coeff(row) * m_matImpl.coeff(row, col);
}
#ifndef __CUDACC__
template<int LoadMode,typename PacketType>
EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const
{
// FIXME: NVCC used to complain about the template keyword, but we have to check whether this is still the case.
// See also similar calls below.
return this->template packet_impl<LoadMode,PacketType>(row,col, row,
typename internal::conditional<int(StorageOrder)==RowMajor, internal::true_type, internal::false_type>::type());
}
template<int LoadMode,typename PacketType>
EIGEN_STRONG_INLINE PacketType packet(Index idx) const
{
return packet<LoadMode,PacketType>(int(StorageOrder)==ColMajor?idx:0,int(StorageOrder)==ColMajor?0:idx);
}
#endif
};
// dense * diagonal
template<typename Lhs, typename Rhs, int ProductKind, int ProductTag>
struct product_evaluator<Product<Lhs, Rhs, ProductKind>, ProductTag, DenseShape, DiagonalShape>
: diagonal_product_evaluator_base<Lhs, typename Rhs::DiagonalVectorType, Product<Lhs, Rhs, LazyProduct>, OnTheRight>
{
typedef diagonal_product_evaluator_base<Lhs, typename Rhs::DiagonalVectorType, Product<Lhs, Rhs, LazyProduct>, OnTheRight> Base;
using Base::m_diagImpl;
using Base::m_matImpl;
using Base::coeff;
typedef typename Base::Scalar Scalar;
typedef Product<Lhs, Rhs, ProductKind> XprType;
typedef typename XprType::PlainObject PlainObject;
enum { StorageOrder = int(Lhs::Flags) & RowMajorBit ? RowMajor : ColMajor };
EIGEN_DEVICE_FUNC explicit product_evaluator(const XprType& xpr)
: Base(xpr.lhs(), xpr.rhs().diagonal())
{
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index row, Index col) const
{
return m_matImpl.coeff(row, col) * m_diagImpl.coeff(col);
}
#ifndef __CUDACC__
template<int LoadMode,typename PacketType>
EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const
{
return this->template packet_impl<LoadMode,PacketType>(row,col, col,
typename internal::conditional<int(StorageOrder)==ColMajor, internal::true_type, internal::false_type>::type());
}
template<int LoadMode,typename PacketType>
EIGEN_STRONG_INLINE PacketType packet(Index idx) const
{
return packet<LoadMode,PacketType>(int(StorageOrder)==ColMajor?idx:0,int(StorageOrder)==ColMajor?0:idx);
}
#endif
};
/***************************************************************************
* Products with permutation matrices
***************************************************************************/
/** \internal
* \class permutation_matrix_product
* Internal helper class implementing the product between a permutation matrix and a matrix.
* This class is specialized for DenseShape below and for SparseShape in SparseCore/SparsePermutation.h
*/
template<typename ExpressionType, int Side, bool Transposed, typename ExpressionShape>
struct permutation_matrix_product;
template<typename ExpressionType, int Side, bool Transposed>
struct permutation_matrix_product<ExpressionType, Side, Transposed, DenseShape>
{
typedef typename nested_eval<ExpressionType, 1>::type MatrixType;
typedef typename remove_all<MatrixType>::type MatrixTypeCleaned;
template<typename Dest, typename PermutationType>
static inline void run(Dest& dst, const PermutationType& perm, const ExpressionType& xpr)
{
MatrixType mat(xpr);
const Index n = Side==OnTheLeft ? mat.rows() : mat.cols();
// FIXME we need an is_same for expression that is not sensitive to constness. For instance
// is_same_xpr<Block<const Matrix>, Block<Matrix> >::value should be true.
//if(is_same<MatrixTypeCleaned,Dest>::value && extract_data(dst) == extract_data(mat))
if(is_same_dense(dst, mat))
{
// apply the permutation inplace
Matrix<bool,PermutationType::RowsAtCompileTime,1,0,PermutationType::MaxRowsAtCompileTime> mask(perm.size());
mask.fill(false);
Index r = 0;
while(r < perm.size())
{
// search for the next seed
while(r<perm.size() && mask[r]) r++;
if(r>=perm.size())
break;
// we got one, let's follow it until we are back to the seed
Index k0 = r++;
Index kPrev = k0;
mask.coeffRef(k0) = true;
for(Index k=perm.indices().coeff(k0); k!=k0; k=perm.indices().coeff(k))
{
Block<Dest, Side==OnTheLeft ? 1 : Dest::RowsAtCompileTime, Side==OnTheRight ? 1 : Dest::ColsAtCompileTime>(dst, k)
.swap(Block<Dest, Side==OnTheLeft ? 1 : Dest::RowsAtCompileTime, Side==OnTheRight ? 1 : Dest::ColsAtCompileTime>
(dst,((Side==OnTheLeft) ^ Transposed) ? k0 : kPrev));
mask.coeffRef(k) = true;
kPrev = k;
}
}
}
else
{
for(Index i = 0; i < n; ++i)
{
Block<Dest, Side==OnTheLeft ? 1 : Dest::RowsAtCompileTime, Side==OnTheRight ? 1 : Dest::ColsAtCompileTime>
(dst, ((Side==OnTheLeft) ^ Transposed) ? perm.indices().coeff(i) : i)
=
Block<const MatrixTypeCleaned,Side==OnTheLeft ? 1 : MatrixTypeCleaned::RowsAtCompileTime,Side==OnTheRight ? 1 : MatrixTypeCleaned::ColsAtCompileTime>
(mat, ((Side==OnTheRight) ^ Transposed) ? perm.indices().coeff(i) : i);
}
}
}
};
template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape>
struct generic_product_impl<Lhs, Rhs, PermutationShape, MatrixShape, ProductTag>
{
template<typename Dest>
static void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs)
{
permutation_matrix_product<Rhs, OnTheLeft, false, MatrixShape>::run(dst, lhs, rhs);
}
};
template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape>
struct generic_product_impl<Lhs, Rhs, MatrixShape, PermutationShape, ProductTag>
{
template<typename Dest>
static void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs)
{
permutation_matrix_product<Lhs, OnTheRight, false, MatrixShape>::run(dst, rhs, lhs);
}
};
template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape>
struct generic_product_impl<Inverse<Lhs>, Rhs, PermutationShape, MatrixShape, ProductTag>
{
template<typename Dest>
static void evalTo(Dest& dst, const Inverse<Lhs>& lhs, const Rhs& rhs)
{
permutation_matrix_product<Rhs, OnTheLeft, true, MatrixShape>::run(dst, lhs.nestedExpression(), rhs);
}
};
template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape>
struct generic_product_impl<Lhs, Inverse<Rhs>, MatrixShape, PermutationShape, ProductTag>
{
template<typename Dest>
static void evalTo(Dest& dst, const Lhs& lhs, const Inverse<Rhs>& rhs)
{
permutation_matrix_product<Lhs, OnTheRight, true, MatrixShape>::run(dst, rhs.nestedExpression(), lhs);
}
};
/***************************************************************************
* Products with transpositions matrices
***************************************************************************/
// FIXME could we unify Transpositions and Permutation into a single "shape"??
/** \internal
* \class transposition_matrix_product
* Internal helper class implementing the product between a permutation matrix and a matrix.
*/
template<typename ExpressionType, int Side, bool Transposed, typename ExpressionShape>
struct transposition_matrix_product
{
typedef typename nested_eval<ExpressionType, 1>::type MatrixType;
typedef typename remove_all<MatrixType>::type MatrixTypeCleaned;
template<typename Dest, typename TranspositionType>
static inline void run(Dest& dst, const TranspositionType& tr, const ExpressionType& xpr)
{
MatrixType mat(xpr);
typedef typename TranspositionType::StorageIndex StorageIndex;
const Index size = tr.size();
StorageIndex j = 0;
if(!is_same_dense(dst,mat))
dst = mat;
for(Index k=(Transposed?size-1:0) ; Transposed?k>=0:k<size ; Transposed?--k:++k)
if(Index(j=tr.coeff(k))!=k)
{
if(Side==OnTheLeft) dst.row(k).swap(dst.row(j));
else if(Side==OnTheRight) dst.col(k).swap(dst.col(j));
}
}
};
template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape>
struct generic_product_impl<Lhs, Rhs, TranspositionsShape, MatrixShape, ProductTag>
{
template<typename Dest>
static void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs)
{
transposition_matrix_product<Rhs, OnTheLeft, false, MatrixShape>::run(dst, lhs, rhs);
}
};
template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape>
struct generic_product_impl<Lhs, Rhs, MatrixShape, TranspositionsShape, ProductTag>
{
template<typename Dest>
static void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs)
{
transposition_matrix_product<Lhs, OnTheRight, false, MatrixShape>::run(dst, rhs, lhs);
}
};
template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape>
struct generic_product_impl<Transpose<Lhs>, Rhs, TranspositionsShape, MatrixShape, ProductTag>
{
template<typename Dest>
static void evalTo(Dest& dst, const Transpose<Lhs>& lhs, const Rhs& rhs)
{
transposition_matrix_product<Rhs, OnTheLeft, true, MatrixShape>::run(dst, lhs.nestedExpression(), rhs);
}
};
template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape>
struct generic_product_impl<Lhs, Transpose<Rhs>, MatrixShape, TranspositionsShape, ProductTag>
{
template<typename Dest>
static void evalTo(Dest& dst, const Lhs& lhs, const Transpose<Rhs>& rhs)
{
transposition_matrix_product<Lhs, OnTheRight, true, MatrixShape>::run(dst, rhs.nestedExpression(), lhs);
}
};
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_PRODUCT_EVALUATORS_H
| [
"abdellah.lahnaoui@gmail.com"
] | abdellah.lahnaoui@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.