hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ee1ecca359fa54dde1bee94d93f2c071771ad0c4 | 22,690 | cpp | C++ | src/strpp.cpp | cjheath/strpp | 5de24ecdfbbb8aeb70a4144f50c5e7a13eb5711f | [
"MIT"
] | 4 | 2022-01-12T08:41:19.000Z | 2022-03-08T15:36:05.000Z | src/strpp.cpp | cjheath/strpp | 5de24ecdfbbb8aeb70a4144f50c5e7a13eb5711f | [
"MIT"
] | null | null | null | src/strpp.cpp | cjheath/strpp | 5de24ecdfbbb8aeb70a4144f50c5e7a13eb5711f | [
"MIT"
] | null | null | null | /*
* Unicode Strings
*
* String Value library:
* - By-value semantics with mutation
* - Thread-safe content sharing and garbage collection using atomic reference counting
* - Substring support using "slices" (substrings using shared content)
* - Unicode support using UTF-8
* - Character indexing, not byte offsets
* - Efficient forward and backward scanning using bookmarks to assist
*
* A shared string is never mutated. Mutation is allowed when only one reference exists.
* Mutating methods clone (unshare) a shared string before making changes.
*
* (c) Copyright Clifford Heath 2022. See LICENSE file for usage rights.
*/
#include <strpp.h>
#include <string.h>
#include <limits.h>
#include <stdio.h>
StrBody StrBody::nullBody("", false, 0, 0);
const StrVal StrVal::null;
// Empty string
StrVal::StrVal()
: body(&StrBody::nullBody)
, offset(0)
, num_chars(0)
{
}
// Normal copy constructor
StrVal::StrVal(const StrVal& s1)
: body(s1.body)
, offset(s1.offset)
, num_chars(s1.num_chars)
{
}
// A new reference to the same StrBody
StrVal::StrVal(StrBody* s1)
: body(s1)
, offset(0)
, num_chars(s1->numChars())
{
}
StrVal::StrVal(StrBody* s1, CharNum offs, CharNum len)
: body(s1)
, offset(offs)
, num_chars(len)
{
}
// Assignment operator
StrVal& StrVal::operator=(const StrVal& s1)
{
body = s1.body;
offset = s1.offset;
num_chars = s1.num_chars;
return *this;
}
// Null-terminated UTF8 data
// Don't allocate a new StrBody for an empty string
StrVal::StrVal(const UTF8* data)
: body(data == 0 || data[0] == '\0' ? &StrBody::nullBody : new StrBody(data, true, strlen((const char*)data)))
, offset(0)
, num_chars(body->numChars())
{
}
// Length-terminated UTF8 data
StrVal::StrVal(const UTF8* data, CharBytes length, size_t allocate)
: body(0)
, offset(0)
, num_chars(0)
, mark()
{
if (allocate < length)
allocate = length;
body = new StrBody(data, true, length, allocate);
num_chars = body->numChars();
}
// Single-character string
StrVal::StrVal(UCS4 character)
: body(0)
, offset(0)
, num_chars(0)
{
UTF8 one_char[7];
UTF8* op = one_char; // Pack it into our local buffer
UTF8Put(op, character);
*op = '\0';
body = new StrBody(one_char, true, op-one_char, 1);
num_chars = 1;
}
// Get our own copy of StrBody that we can safely mutate
void
StrVal::Unshare()
{
if (body->GetRefCount() <= 1)
return;
// Copy only this slice of the body's data, and reset our offset to zero
Bookmark savemark(mark); // copy the bookmark
const UTF8* cp = nthChar(0); // start of this substring
const UTF8* ep = nthChar(num_chars); // end of this substring
CharBytes prefix_bytes = cp - body->startChar(); // How many leading bytes of the body we are eliding
body = new StrBody(cp, true, ep-cp, 0);
mark.char_num = savemark.char_num - offset; // Restore the bookmark
mark.byte_num = savemark.byte_num - prefix_bytes;
offset = 0;
}
// Access characters:
UCS4
StrVal::operator[](int charNum) const
{
const UTF8* cp = nthChar(charNum);
return cp ? UTF8Get(cp) : UCS4_NONE;
}
const UTF8*
StrVal::asUTF8() // Must unshare data if it's a substring with elided suffix
{
const UTF8* ep = nthChar(num_chars);
if (ep < body->endChar())
{
Unshare();
// If we are the last reference and a substring, we might not be terminated
*body->nthChar(num_chars, mark) = '\0';
}
return nthChar(0);
}
const UTF8*
StrVal::asUTF8(CharBytes& bytes) const
{
const UTF8* cp = nthChar(0);
const UTF8* ep = nthChar(num_chars);
bytes = ep-cp;
return cp;
}
// Compare strings using different styles
int
StrVal::compare(const StrVal& comparand, CompareStyle style) const
{
int cmp;
switch (style)
{
case CompareRaw:
cmp = memcmp(nthChar(0), comparand.nthChar(0), numBytes());
if (cmp == 0)
cmp = numBytes() - comparand.numBytes();
return cmp;
case CompareCI:
assert(!"REVISIT: Case-independent comparison is not implemented");
case CompareNatural:
assert(!"REVISIT: Natural comparison is not implemented");
default:
return 0;
}
}
// Delete a substring from the middle:
void
StrVal::remove(CharNum at, int len)
{
if (at >= num_chars || len == 0)
return; // Nothing to do
Unshare();
body->remove(at, len);
}
StrVal
StrVal::substr(CharNum at, int len) const
{
assert(len >= -1);
// Quick check for a null substring:
if (at < 0 || at >= num_chars || len == 0)
return StrVal();
// Clamp substring length:
if (len == -1)
len = num_chars-at;
else if (len > num_chars-at)
len = num_chars-at;
return StrVal(body, offset+at, len);
}
int
StrVal::find(UCS4 ch, int after) const
{
CharNum n = after+1; // First CharNum we'll look at
const UTF8* up;
while ((up = nthChar(n)) != 0)
{
if (ch == UTF8Get(up))
return n; // Found at n
n++;
}
return -1; // Not found
}
int
StrVal::rfind(UCS4 ch, int before) const
{
CharNum n = before == -1 ? num_chars-1 : before-1; // First CharNum we'll look at
const UTF8* bp;
while ((bp = nthChar(n)) != 0)
{
if (ch == UTF8Get(bp))
return n; // Found at n
n--;
}
return -1; // Not found
}
// Search for substrings:
int
StrVal::find(const StrVal& s1, int after) const
{
CharNum n = after+1; // First CharNum we'll look at
CharNum last_start = num_chars-s1.length(); // Last possible start position
const UTF8* s1start = s1.nthChar(0);
const UTF8* up;
while (n <= last_start && (up = nthChar(n)) != 0)
{
if (memcmp(up, s1start, s1.numBytes()) == 0)
return n;
n++;
}
return -1;
}
int
StrVal::rfind(const StrVal& s1, int before) const
{
CharNum n = before == -1 ? num_chars-s1.length() : before-1; // First CharNum we'll look at
if (n > num_chars-s1.length())
n = num_chars-s1.length();
const UTF8* s1start = s1.nthChar(0);
const UTF8* bp;
while ((bp = nthChar(n)) != 0)
{
if (memcmp(bp, s1start, s1.numBytes()) == 0)
return n;
n--;
}
return -1;
}
// Search for characters in set:
int
StrVal::findAny(const StrVal& s1, int after) const
{
CharNum n = after+1; // First CharNum we'll look at
const UTF8* s1start = s1.nthChar(0);
const UTF8* ep = s1.nthChar(s1.length()); // Byte after the last char in s1
const UTF8* up;
while ((up = nthChar(n)) != 0)
{
UCS4 ch = UTF8Get(up);
for (const UTF8* op = s1start; op < ep; n++)
if (ch == UTF8Get(op))
return n; // Found at n
n++;
}
return -1; // Not found
}
int
StrVal::rfindAny(const StrVal& s1, int before) const
{
CharNum n = before == -1 ? num_chars-1 : before-1; // First CharNum we'll look at
const UTF8* s1start = s1.nthChar(0);
const UTF8* ep = s1.nthChar(s1.length()); // Byte after the last char in s1
const UTF8* bp;
while ((bp = nthChar(n)) != 0)
{
UCS4 ch = UTF8Get(bp);
for (const UTF8* op = s1start; op < ep; n++)
if (ch == UTF8Get(op))
return n;
n--;
}
return -1;
}
// Search for characters not in set:
int
StrVal::findNot(const StrVal& s1, int after) const
{
CharNum n = after+1; // First CharNum we'll look at
const UTF8* s1start = s1.nthChar(0);
const UTF8* ep = s1.nthChar(s1.length()); // Byte after the last char in s1
const UTF8* up;
while ((up = nthChar(n)) != 0)
{
UCS4 ch = UTF8Get(up);
for (const UTF8* op = s1start; op < ep; n++)
if (ch == UTF8Get(op))
goto next; // Found at n
return n;
next:
n++;
}
return -1; // Not found
}
int
StrVal::rfindNot(const StrVal& s1, int before) const
{
CharNum n = before == -1 ? num_chars-1 : before-1; // First CharNum we'll look at
const UTF8* s1start = s1.nthChar(0);
const UTF8* ep = s1.nthChar(s1.length()); // Byte after the last char in s1
const UTF8* bp;
while ((bp = nthChar(n)) != 0)
{
UCS4 ch = UTF8Get(bp);
for (const UTF8* op = s1start; op < ep; n++)
if (ch == UTF8Get(op))
goto next; // Found at n
return n;
next:
n--;
}
return -1;
}
// Add, producing a new StrVal:
StrVal
StrVal::operator+(const StrVal& addend) const
{
// Handle the rare but important case of extending a slice with a contiguous slice of the same body
if ((StrBody*)body == (StrBody*)addend.body // From the same body
&& offset+num_chars == addend.offset) // And this ends where the addend starts
return StrVal(body, offset, num_chars+addend.num_chars);
const UTF8* cp = nthChar(0);
CharBytes len = numBytes();
StrVal str(cp, len, len+addend.numBytes());
str += addend;
return str;
}
StrVal
StrVal::operator+(UCS4 addend) const
{
// Convert addend using a stack-local buffer to save allocation here.
UTF8 buf[7]; // Enough for 6-byte content plus a NUL
UTF8* cp = buf;
UTF8Put(cp, addend);
*cp = '\0';
StrBody body(buf, false, cp-buf, 1);
return operator+(StrVal(&body));
}
// Add, StrVal is modified:
StrVal&
StrVal::operator+=(const StrVal& addend)
{
if (num_chars == 0 && !addend.noCopy())
return *this = addend; // Just assign, we were empty anyhow
append(addend);
return *this;
}
StrVal&
StrVal::operator+=(UCS4 addend)
{
// Convert addend using a stack-local buffer to save allocation here.
UTF8 buf[7]; // Enough for 6-byte content plus a NUL
UTF8* cp = buf;
UTF8Put(cp, addend);
*cp = '\0';
StrBody body(buf, false, cp-buf, 1);
operator+=(StrVal(&body));
return *this;
}
void
StrVal::insert(CharNum pos, const StrVal& addend)
{
// Handle the rare but important case of extending a slice with a contiguous slice of the same body
if (pos == num_chars // Appending at the end
&& (StrBody*)body == (StrBody*)addend.body // From the same body
&& offset+pos == addend.offset) // And addend starts where we end
{
num_chars += addend.length();
return;
}
Unshare();
body->insert(pos, addend);
num_chars += addend.length();
}
void
StrVal::toLower()
{
Unshare();
body->toLower();
num_chars = body->numChars();
}
void
StrVal::toUpper()
{
Unshare();
body->toUpper();
num_chars = body->numChars();
}
static inline int
HexAlpha(UCS4 ch)
{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
? (int)((ch & ~('a'-'A')) - 'A' + 10)
: -1;
}
static inline int
Digit(UCS4 ch, int radix)
{
int d;
if ((d = UCS4Digit(ch)) < 0) // Not decimal digit
{
if (radix > 10
&& (d = HexAlpha(ch)) < 0) // Not ASCII a-z, A-Z either
return -1; // ditch it
}
if (d < radix || (d == 1 && radix == 1))
return d;
else
return -1;
}
int32_t
StrVal::asInt32(
int* err_return, // error return
int radix, // base for conversion
CharNum* scanned // characters scanned
) const
{
size_t len = length(); // length of string
size_t i = 0; // position of next character
UCS4 ch = 0; // current character
int d; // current digit value
bool negative = false; // Was a '-' sign seen?
unsigned long l = 0; // Number being converted
unsigned long last;
unsigned long max;
if (err_return)
*err_return = 0;
// Check legal radix
if (radix < 0 || radix > 36)
{
if (err_return)
*err_return = STRERR_ILLEGAL_RADIX;
if (scanned)
*scanned = 0;
return 0;
}
// Skip leading white-space
while (i < len && UCS4IsWhite(ch = (*this)[i]))
i++;
if (i == len)
goto no_digits;
// Check for sign character
if (ch == '+' || ch == '-')
{
i++;
negative = ch == '-';
while (i < len && UCS4IsWhite(ch = (*this)[i]))
i++;
if (i == len)
goto no_digits;
}
if (radix == 0) // Auto-detect radix (octal, decimal, binary)
{
if (UCS4Digit(ch) == 0 && i+1 < len)
{
// ch is the digit zero, look ahead
switch ((*this)[i+1])
{
case 'b': case 'B':
if (radix == 0 || radix == 2)
{
radix = 2;
ch = (*this)[i += 2];
if (i == len)
goto no_digits;
}
break;
case 'x': case 'X':
if (radix == 0 || radix == 16)
{
radix = 16;
ch = (*this)[i += 2];
if (i == len)
goto no_digits;
}
break;
default:
if (radix == 0)
radix = 8;
break;
}
}
else
radix = 10;
}
// Check there's at least one digit:
if ((d = Digit(ch, radix)) < 0)
goto not_number;
max = (ULONG_MAX-1)/radix + 1;
// Convert digits
do {
i++; // We're definitely using this char
last = l;
if (l > max // Detect *unsigned* long overflow
|| (l = l*radix + d) < last)
{
// Overflowed unsigned long!
if (err_return)
*err_return = STRERR_NUMBER_OVERFLOW;
if (scanned)
*scanned = i;
return 0;
}
} while (i < len && (d = Digit((*this)[i], radix)) >= 0);
if (err_return)
*err_return = 0;
// Check for trailing non-white characters
while (i < len && UCS4IsWhite((*this)[i]))
i++;
if (i != len && err_return)
*err_return = STRERR_TRAIL_TEXT;
// Return number of digits scanned
if (scanned)
*scanned = i;
if (l > (unsigned long)LONG_MAX+(negative ? 1 : 0))
{
if (err_return)
*err_return = STRERR_NUMBER_OVERFLOW;
// Try anyway, they might have wanted unsigned!
}
/*
* Casting unsigned long down to long doesn't clear the high bit
* on a twos-complement architecture:
*/
return negative ? -(long)l : (long)l;
no_digits:
if (err_return)
*err_return = STRERR_NO_DIGITS;
if (scanned)
*scanned = i;
return 0;
not_number:
if (err_return)
*err_return = STRERR_NOT_NUMBER;
if (scanned)
*scanned = i;
return 0;
}
// Return a pointer to the start of the nth character, using our bookmark to help
const UTF8*
StrVal::nthChar(CharNum char_num)
{
if (char_num < 0 || char_num > num_chars)
return 0;
return body->nthChar(offset+char_num, mark);
}
// Return a pointer to the start of the nth character, without using a bookmark
const UTF8*
StrVal::nthChar(CharNum char_num) const
{
if (char_num < 0 || char_num > num_chars)
return 0;
Bookmark useless;
return body->nthChar(offset+char_num, useless);
}
bool
StrVal::noCopy() const
{
return body->noCopy();
}
StrBody::~StrBody()
{
if (start && num_alloc > 0)
delete[] start;
}
StrBody::StrBody()
: start(0)
, num_chars(0)
, num_bytes(0)
, num_alloc(0)
{
}
StrBody::StrBody(const UTF8* data, bool copy, CharBytes length, size_t allocate)
: start(0)
, num_chars(0)
, num_bytes(0)
, num_alloc(0)
{
if (copy)
{
if (allocate < length)
allocate = length;
resize(allocate+1); // Include space for a trailing NUL
if (length)
memcpy(start, data, length);
start[length] = '\0';
}
else
{
start = (UTF8*)data; // Cast const away; copy==false implies no change will occur
if (length == 0)
length = strlen(data);
AddRef(); // Cannot be deleted or resized
}
num_bytes = length;
}
StrBody&
StrBody::operator=(const StrBody& s1) // Assignment operator; ONLY for no-copy bodies
{
assert(s1.num_alloc == 0); // Must not do this if we would make two references to allocated data
start = s1.start;
num_chars = s1.num_chars;
num_bytes = s1.num_bytes;
num_alloc = 0;
return *this;
}
/*
* Counting the characters in a string also checks for valid UTF-8.
* If the string is allocated (not static) but unshared,
* it also compacts non-minimal UTF-8 coding.
*/
void
StrBody::countChars()
{
if (num_chars > 0 || num_bytes == 0)
return;
const UTF8* cp = start; // Progress pointer when reading data
UTF8* op = start; // Output for compacted data
UTF8* ep = start+num_bytes; // Marker for end of data
while (cp < ep)
{
const UTF8* char_start = cp; // Save the start of this character, for rewriting
UCS4 ch = UTF8Get(cp);
// We don't hold by Postel’s Law here. We really should throw an exception, but I'm feeling kind. N'yah!
if (ch == UCS4_NONE // Illegal encoding
|| cp > ep) // Overlaps the end of data
break; // An error occurred before the end of the data; truncate it.
if (num_alloc > 0 // Not a static string, so we can rewrite it
&& ref_count <= 1 // Not currently shared, so not breaking any Bookmarks
&& (UTF8Len(ch) < cp-char_start // Optimal length is shorter than this encoding. Start compacting
|| op < char_start)) // We were already compacting
UTF8Put(op, ch); // Rewrite the character in compact form
else
op = (UTF8*)cp; // Keep up
num_chars++;
}
if (op < cp)
{ // We were rewriting, or there was a coding eror, so we now have fewer bytes
num_bytes = op-start;
if (num_alloc > 0)
*op = '\0';
}
}
// Resize the memory allocation to make room for a larger string (size includes the trailing NUL)
void
StrBody::resize(size_t minimum)
{
if (minimum <= num_alloc)
return;
minimum = ((minimum-1)|0x7)+1; // round up to multiple of 8
if (num_alloc) // Minimum growth 50% rounded up to nearest 32
num_alloc = ((num_alloc*3/2) | 0x1F) + 1;
if (num_alloc < minimum)
num_alloc = minimum; // Still not enough, get enough
UTF8* newdata = new UTF8[num_alloc];
if (start)
{
memcpy(newdata, start, num_bytes);
newdata[num_bytes] = '\0';
delete[] start;
}
start = newdata;
}
// Return a pointer to the start of the nth character
UTF8*
StrBody::nthChar(CharNum char_num, StrVal::Bookmark& mark)
{
UTF8* up; // starting pointer for forward search
int start_char; // starting char number for forward search
UTF8* ep; // starting pointer for backward search
int end_char; // starting char number for backward search
if (char_num < 0 || char_num > (end_char = numChars())) // numChars() counts the string if necessary
return (UTF8*)0;
if (num_chars == num_bytes) // ASCII data only, use direct index!
return start+char_num;
up = start; // Set initial starting point for forward search
start_char = 0;
ep = start+num_bytes; // and for backward search (end_char is set above)
// If we have a bookmark, move either the forward or backward search starting point to it.
if (mark.char_num > 0)
{
if (char_num >= mark.char_num)
{ // forget about starting from the start
up += mark.byte_num;
start_char = mark.char_num;
}
else
{ // Don't search past here, maybe back from here
ep = start+mark.byte_num;
end_char = mark.char_num;
}
}
/*
* Decide whether to search forwards from up/start_char or backwards from ep/end_char.
*/
if (char_num-start_char < end_char-char_num)
{ // Forwards search is shorter
end_char = char_num-start_char; // How far forward should we search?
while (start_char < char_num && up < ep)
{
up += UTF8Len(up);
start_char++;
}
}
else
{ // Search back from end_char to char_num
while (end_char > char_num && ep && ep > up)
{
ep = (UTF8*)UTF8Backup(ep, start);
end_char--;
}
up = ep;
}
// Save the bookmark if it looks likely to be helpful.
if (up && char_num > 3 && char_num < num_chars-3)
{
mark.byte_num = up-start;
mark.char_num = char_num;
}
return up;
}
void
StrBody::insert(CharNum pos, const StrVal& addend)
{
CharBytes addend_bytes;
const UTF8* addend_data = addend.asUTF8(addend_bytes);
resize(num_bytes + addend_bytes + 1); // Include space for a trailing NUL
StrVal::Bookmark nullmark;
UTF8* insert_position = nthChar(pos, nullmark);
CharBytes unmoved = insert_position-start;
// Move data up, including the trailing NUL
memmove(insert_position+addend_bytes, insert_position, num_bytes-unmoved+1);
memcpy(insert_position, addend_data, addend_bytes);
num_bytes += addend_bytes;
num_chars += addend.length();
}
// Delete a substring from the middle
void
StrBody::remove(CharNum at, int len)
{
assert(ref_count <= 1);
assert(len >= -1);
StrVal::Bookmark nullmark;
UTF8* cp = (UTF8*)nthChar(at, nullmark); // Cast away the const
const UTF8* ep = (len == -1 ? start + num_bytes : nthChar(at + len, nullmark));
if (start+num_bytes+1 > ep) // Move trailing data down. include the '\0'!
memmove(cp, ep, start+num_bytes-ep+1);
num_bytes -= ep-cp;
num_chars -= len; // len says how many we deleted.
}
void
StrBody::toLower()
{
UTF8 one_char[7];
StrBody body; // Any StrVal that references this must have a shorter lifetime. transform() guarantees this.
transform(
[&](const UTF8*& cp, const UTF8* ep) -> StrVal
{
UCS4 ch = UTF8Get(cp); // Get UCS4 character
ch = UCS4ToLower(ch); // Transform it
UTF8* op = one_char; // Pack it into our local buffer
UTF8Put(op, ch);
*op = '\0';
// Assign this to the body in our closure
body = StrBody(one_char, false, op-one_char, 1);
return StrVal(&body);
}
);
}
void
StrBody::toUpper()
{
UTF8 one_char[7];
StrBody body; // Any StrVal that references this must have a shorter lifetime. transform() guarantees this.
transform(
[&](const UTF8*& cp, const UTF8* ep) -> StrVal
{
UCS4 ch = UTF8Get(cp); // Get UCS4 character
ch = UCS4ToUpper(ch); // Transform it
UTF8* op = one_char; // Pack it into our local buffer
UTF8Put(op, ch);
*op = '\0';
// Assign this to the body in our closure
body = StrBody(one_char, false, op-one_char, 1);
return StrVal(&body);
}
);
}
void
StrVal::transform(const std::function<StrVal(const UTF8*& cp, const UTF8* ep)> xform, int after)
{
Unshare();
body->transform(xform, after);
num_chars = body->numChars();
mark = Bookmark();
}
/*
* At every character position after the given point, the passed transform function
* can extract any number of chars (limited by ep) and return a replacement StrVal for those chars.
* To leave the remainder untransformed, return without advancing cp
* (but a returned StrVal will still be inserted)
*/
void
StrBody::transform(const std::function<StrVal(const UTF8*& cp, const UTF8* ep)> xform, int after)
{
assert(ref_count <= 1);
UTF8* old_start = start;
size_t old_num_bytes = num_bytes;
// Allocate new data, preserving the old
start = 0;
num_chars = 0;
num_bytes = 0;
num_alloc = 0;
resize(old_num_bytes+6+1); // Start with same allocation plus one character space and NUL
const UTF8* up = old_start; // Input pointer
const UTF8* ep = old_start+old_num_bytes; // Termination guard
CharNum processed_chars = 0; // Total input chars transformed
bool stopped = false; // Are we done yet?
UTF8* op = start; // Output pointer
while (up < ep)
{
const UTF8* next = up;
if (processed_chars+1 > after+1 // Not yet reached the point to start transforming
&& !stopped) // We have stopped transforming
{
StrVal replacement = xform(next, ep);
CharBytes replaced_bytes = next-up; // How many bytes were consumed?
CharNum replaced_chars = replacement.length(); // Replaced by how many chars?
// Advance 'up' over the replaced characters
while (up < next)
{
up += UTF8Len(up);
processed_chars++;
}
stopped |= (replaced_bytes == 0);
insert(num_chars, replacement);
op = start+num_bytes;
}
else
{ // Just copy one character and move on
UCS4 ch = UTF8Get(up); // Get UCS4 character
processed_chars++;
if (num_alloc < (op-start+6+1))
{
resize((op-start)+6+1); // Room for any char and NUL
op = start+num_bytes; // Reset our output pointer in case start has changed
}
UTF8Put(op, ch);
num_bytes = op-start;
num_chars++;
}
}
*op = '\0';
delete [] old_start;
}
| 23.709509 | 110 | 0.652975 | cjheath |
ee21efbdea5cdfb86caa639599d978d1ace03122 | 23,457 | cpp | C++ | src/SoyH264.cpp | SoylentGraham/ofxSoylent | 69ed35ba58e51f381c6ddccbdbd7148da32507a2 | [
"MIT"
] | 16 | 2016-03-04T02:44:11.000Z | 2021-08-08T18:48:37.000Z | src/SoyH264.cpp | SoylentGraham/ofxSoylent | 69ed35ba58e51f381c6ddccbdbd7148da32507a2 | [
"MIT"
] | 2 | 2015-11-19T11:28:43.000Z | 2020-05-05T09:25:50.000Z | src/SoyH264.cpp | SoylentGraham/ofxSoylent | 69ed35ba58e51f381c6ddccbdbd7148da32507a2 | [
"MIT"
] | 4 | 2017-01-06T06:09:34.000Z | 2019-06-25T17:12:29.000Z | #include "SoyH264.h"
size_t H264::GetNaluLengthSize(SoyMediaFormat::Type Format)
{
switch ( Format )
{
case SoyMediaFormat::H264_8: return 1;
case SoyMediaFormat::H264_16: return 2;
case SoyMediaFormat::H264_32: return 4;
case SoyMediaFormat::H264_ES:
case SoyMediaFormat::H264_SPS_ES:
case SoyMediaFormat::H264_PPS_ES:
return 0;
default:
break;
}
std::stringstream Error;
//Error << __func__ << " unhandled format " << Format;
Error << __func__ << " unhandled format ";
throw Soy::AssertException( Error.str() );
}
bool H264::IsNalu(const ArrayBridge<uint8>& Data,size_t& NaluSize,size_t& HeaderSize)
{
// too small to be nalu3
if ( Data.GetDataSize() < 4 )
return false;
// read magic
uint32 Magic;
memcpy( &Magic, Data.GetArray(), sizeof(Magic) );
// test for nalu sizes
// gr: big endian!
if ( (Magic & 0xffffffff) == 0x01000000 )
{
NaluSize = 4;
}
else if ( (Magic & 0xffffff) == 0x010000 )
{
NaluSize = 3;
}
else
{
return false;
}
// missing next byte
if ( Data.GetDataSize() < NaluSize+1 )
return false;
// eat nalu byte
H264NaluContent::Type Content;
H264NaluPriority::Type Priority;
uint8 NaluByte = Data[NaluSize];
try
{
H264::DecodeNaluByte( NaluByte, Content, Priority );
}
catch(...)
{
return false;
}
// +nalubyte
HeaderSize = NaluSize+1;
// eat another spare byte...
// todo: verify this is the proper way of doing things...
if ( Content == H264NaluContent::AccessUnitDelimiter )
{
// eat the AUD type value
HeaderSize += 1;
}
// real data should follow now
return true;
}
void H264::RemoveHeader(SoyMediaFormat::Type Format,ArrayBridge<uint8>&& Data,bool KeepNaluByte)
{
switch ( Format )
{
case SoyMediaFormat::H264_ES:
case SoyMediaFormat::H264_SPS_ES:
case SoyMediaFormat::H264_PPS_ES:
{
// gr: CMVideoFormatDescriptionCreateFromH264ParameterSets requires the byte!
size_t NaluSize,HeaderSize;
if ( IsNalu( Data, NaluSize, HeaderSize ) )
{
if ( KeepNaluByte )
Data.RemoveBlock( 0, NaluSize );
else
Data.RemoveBlock( 0, HeaderSize );
return;
}
throw Soy::AssertException("Tried to trim header from h264 ES data but couldn't find nalu header");
}
// gr: is there more to remove than the length?
case SoyMediaFormat::H264_8:
Data.RemoveBlock( 0, 1 );
return;
case SoyMediaFormat::H264_16:
Data.RemoveBlock( 0, 2 );
return;
case SoyMediaFormat::H264_32:
Data.RemoveBlock( 0, 4 );
return;
default:
break;
}
std::stringstream Error;
Error << __func__ << " trying to trim header from non h264 format ";// << Format;
throw Soy::AssertException( Error.str() );
}
bool H264::ResolveH264Format(SoyMediaFormat::Type& Format,ArrayBridge<uint8>& Data)
{
size_t NaluSize = 0;
size_t HeaderSize = 0;
// todo: could try and decode length size from Data size...
if ( !IsNalu( Data, NaluSize, HeaderSize ) )
return false;
uint8 NaluByte = Data[NaluSize];
H264NaluContent::Type Content;
H264NaluPriority::Type Priority;
try
{
DecodeNaluByte( NaluByte, Content, Priority );
}
catch(std::exception&e)
{
std::Debug << __func__ << " exception: " << e.what() << std::endl;
throw;
}
if ( Content == H264NaluContent::SequenceParameterSet )
Format = SoyMediaFormat::H264_SPS_ES;
else if ( Content == H264NaluContent::PictureParameterSet )
Format = SoyMediaFormat::H264_PPS_ES;
else
Format = SoyMediaFormat::H264_ES;
return true;
}
size_t H264::FindNaluStartIndex(ArrayBridge<uint8>&& Data,size_t& NaluSize,size_t& HeaderSize)
{
// look for start of nalu
for ( ssize_t i=0; i<Data.GetSize(); i++ )
{
auto ChunkPart = GetRemoteArray( &Data[i], Data.GetSize()-i );
if ( !H264::IsNalu( GetArrayBridge(ChunkPart), NaluSize, HeaderSize ) )
continue;
return i;
}
throw Soy::AssertException("Failed to find NALU start");
}
uint8 H264::EncodeNaluByte(H264NaluContent::Type Content,H264NaluPriority::Type Priority)
{
// uint8 Idc_Important = 0x3 << 5; // 0x60
// uint8 Idc = Idc_Important; // 011 XXXXX
uint8 Idc = Priority;
Idc <<= 5;
uint8 Type = Content;
uint8 Byte = Idc|Type;
return Byte;
}
void H264::DecodeNaluByte(uint8 Byte,H264NaluContent::Type& Content,H264NaluPriority::Type& Priority)
{
uint8 Zero = (Byte >> 7) & 0x1;
uint8 Idc = (Byte >> 5) & 0x3;
uint8 Content8 = (Byte >> 0) & (0x1f);
Soy::Assert( Zero==0, "Nalu zero bit non-zero");
// catch bad cases. look out for genuine cases, but if this is zero, NALU delin might have been read wrong
Soy::Assert( Content8!=0, "Nalu content type is invalid (zero)");
// swich this for magic_enum
//Priority = H264NaluPriority::Validate( Idc );
//Content = H264NaluContent::Validate( Content8 );
Priority = static_cast<H264NaluPriority::Type>( Idc );
Content = static_cast<H264NaluContent::Type>( Content8 );
}
void H264::DecodeNaluByte(SoyMediaFormat::Type Format,const ArrayBridge<uint8>&& Data,H264NaluContent::Type& Content,H264NaluPriority::Type& Priority)
{
size_t NaluSize;
size_t HeaderSize;
if ( !IsNalu( Data, NaluSize, HeaderSize ) )
{
Content = H264NaluContent::Invalid;
return;
}
DecodeNaluByte( Data[HeaderSize], Content, Priority );
}
class TBitReader
{
public:
TBitReader(const ArrayBridge<uint8>& Data) :
mData ( Data ),
mBitPos ( 0 )
{
}
TBitReader(const ArrayBridge<uint8>&& Data) :
mData ( Data ),
mBitPos ( 0 )
{
}
void Read(uint32& Data,size_t BitCount);
void Read(uint64& Data,size_t BitCount);
void Read(uint8& Data,size_t BitCount);
size_t BitPosition() const { return mBitPos; }
template<int BYTECOUNT,typename STORAGE>
void ReadBytes(STORAGE& Data,size_t BitCount);
void ReadExponentialGolombCode(uint32& Data);
void ReadExponentialGolombCodeSigned(sint32& Data);
private:
const ArrayBridge<uint8>& mData;
size_t mBitPos; // current bit-to-read/write-pos (the tail)
};
/*
unsigned int ReadBit()
{
ATLASSERT(m_nCurrentBit <= m_nLength * 8);
int nIndex = m_nCurrentBit / 8;
int nOffset = m_nCurrentBit % 8 + 1;
m_nCurrentBit ++;
return (m_pStart[nIndex] >> (8-nOffset)) & 0x01;
}
*/
void TBitReader::ReadExponentialGolombCode(uint32& Data)
{
int i = 0;
while( true )
{
uint8 Bit;
Read( Bit, 1 );
if ( (Bit == 0) && (i < 32) )
i++;
else
break;
}
Read( Data, i );
Data += (1 << i) - 1;
}
void TBitReader::ReadExponentialGolombCodeSigned(sint32& Data)
{
uint32 r;
ReadExponentialGolombCode(r);
if (r & 0x01)
{
Data = (r+1)/2;
}
else
{
Data = -size_cast<sint32>(r/2);
}
}
template<int BYTECOUNT,typename STORAGE>
void TBitReader::ReadBytes(STORAGE& Data,size_t BitCount)
{
// gr: definitly correct
Data = 0;
BufferArray<uint8,BYTECOUNT> Bytes;
int ComponentBitCount = size_cast<int>(BitCount);
while ( ComponentBitCount > 0 )
{
Read( Bytes.PushBack(), std::min<size_t>(8,ComponentBitCount) );
ComponentBitCount -= 8;
}
// gr: should we check for mis-aligned bitcount?
Data = 0;
for ( int i=0; i<Bytes.GetSize(); i++ )
{
int Shift = (i * 8);
Data |= static_cast<STORAGE>(Bytes[i]) << Shift;
}
STORAGE DataBackwardTest = 0;
for ( int i=0; i<Bytes.GetSize(); i++ )
{
auto Shift = (Bytes.GetSize()-1-i) * 8;
DataBackwardTest |= static_cast<STORAGE>(Bytes[i]) << Shift;
}
// turns out THIS is the right way
Data = DataBackwardTest;
}
void TBitReader::Read(uint32& Data,size_t BitCount)
{
// break up data
if ( BitCount <= 8 )
{
uint8 Data8;
Read( Data8, BitCount );
Data = Data8;
return;
}
if ( BitCount <= 8 )
{
ReadBytes<1>( Data, BitCount );
return;
}
if ( BitCount <= 16 )
{
ReadBytes<2>( Data, BitCount );
return;
}
if ( BitCount <= 32 )
{
ReadBytes<4>( Data, BitCount );
return;
}
std::stringstream Error;
Error << __func__ << " not handling bit count > 32; " << BitCount;
throw Soy::AssertException( Error.str() );
}
void TBitReader::Read(uint64& Data,size_t BitCount)
{
if ( BitCount <= 8 )
{
ReadBytes<1>( Data, BitCount );
return;
}
if ( BitCount <= 16 )
{
ReadBytes<2>( Data, BitCount );
return;
}
if ( BitCount <= 32 )
{
ReadBytes<4>( Data, BitCount );
return;
}
if ( BitCount <= 64 )
{
ReadBytes<8>( Data, BitCount );
return;
}
std::stringstream Error;
Error << __func__ << " not handling bit count > 32; " << BitCount;
throw Soy::AssertException( Error.str() );
}
void TBitReader::Read(uint8& Data,size_t BitCount)
{
if ( BitCount <= 0 )
return;
Soy::Assert( BitCount <= 8, "trying to read>8 bits to 8bit value");
// current byte
auto CurrentByte = mBitPos / 8;
auto CurrentBit = mBitPos % 8;
// out of range
Soy::Assert( CurrentByte < mData.GetSize(), "Reading byte out of range");
// move along
mBitPos += BitCount;
// get byte
Data = mData[CurrentByte];
// pick out certain bits
// gr: reverse endianess to what I thought...
//Data >>= CurrentBit;
Data >>= 8-CurrentBit-BitCount;
Data &= (1<<BitCount)-1;
}
/*
const unsigned char * m_pStart;
unsigned short m_nLength;
int m_nCurrentBit;
unsigned int ReadBit()
{
assert(m_nCurrentBit <= m_nLength * 8);
int nIndex = m_nCurrentBit / 8;
int nOffset = m_nCurrentBit % 8 + 1;
m_nCurrentBit ++;
return (m_pStart[nIndex] >> (8-nOffset)) & 0x01;
}
unsigned int ReadBits(int n)
{
int r = 0;
int i;
for (i = 0; i < n; i++)
{
r |= ( ReadBit() << ( n - i - 1 ) );
}
return r;
}
unsigned int ReadExponentialGolombCode()
{
int r = 0;
int i = 0;
while( (ReadBit() == 0) && (i < 32) )
{
i++;
}
r = ReadBits(i);
r += (1 << i) - 1;
return r;
}
unsigned int ReadSE()
{
int r = ReadExponentialGolombCode();
if (r & 0x01)
{
r = (r+1)/2;
}
else
{
r = -(r/2);
}
return r;
}
void Parse(const unsigned char * pStart, unsigned short nLen)
{
m_pStart = pStart;
m_nLength = nLen;
m_nCurrentBit = 0;
int frame_crop_left_offset=0;
int frame_crop_right_offset=0;
int frame_crop_top_offset=0;
int frame_crop_bottom_offset=0;
int profile_idc = ReadBits(8);
int constraint_set0_flag = ReadBit();
int constraint_set1_flag = ReadBit();
int constraint_set2_flag = ReadBit();
int constraint_set3_flag = ReadBit();
int constraint_set4_flag = ReadBit();
int constraint_set5_flag = ReadBit();
int reserved_zero_2bits = ReadBits(2);
int level_idc = ReadBits(8);
int seq_parameter_set_id = ReadExponentialGolombCode();
if( profile_idc == 100 || profile_idc == 110 ||
profile_idc == 122 || profile_idc == 244 ||
profile_idc == 44 || profile_idc == 83 ||
profile_idc == 86 || profile_idc == 118 )
{
int chroma_format_idc = ReadExponentialGolombCode();
if( chroma_format_idc == 3 )
{
int residual_colour_transform_flag = ReadBit();
}
int bit_depth_luma_minus8 = ReadExponentialGolombCode();
int bit_depth_chroma_minus8 = ReadExponentialGolombCode();
int qpprime_y_zero_transform_bypass_flag = ReadBit();
int seq_scaling_matrix_present_flag = ReadBit();
if (seq_scaling_matrix_present_flag)
{
int i=0;
for ( i = 0; i < 8; i++)
{
int seq_scaling_list_present_flag = ReadBit();
if (seq_scaling_list_present_flag)
{
int sizeOfScalingList = (i < 6) ? 16 : 64;
int lastScale = 8;
int nextScale = 8;
int j=0;
for ( j = 0; j < sizeOfScalingList; j++)
{
if (nextScale != 0)
{
int delta_scale = ReadSE();
nextScale = (lastScale + delta_scale + 256) % 256;
}
lastScale = (nextScale == 0) ? lastScale : nextScale;
}
}
}
}
}
int log2_max_frame_num_minus4 = ReadExponentialGolombCode();
int pic_order_cnt_type = ReadExponentialGolombCode();
if( pic_order_cnt_type == 0 )
{
int log2_max_pic_order_cnt_lsb_minus4 = ReadExponentialGolombCode();
}
else if( pic_order_cnt_type == 1 )
{
int delta_pic_order_always_zero_flag = ReadBit();
int offset_for_non_ref_pic = ReadSE();
int offset_for_top_to_bottom_field = ReadSE();
int num_ref_frames_in_pic_order_cnt_cycle = ReadExponentialGolombCode();
int i;
for( i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++ )
{
ReadSE();
//sps->offset_for_ref_frame[ i ] = ReadSE();
}
}
int max_num_ref_frames = ReadExponentialGolombCode();
int gaps_in_frame_num_value_allowed_flag = ReadBit();
int pic_width_in_mbs_minus1 = ReadExponentialGolombCode();
int pic_height_in_map_units_minus1 = ReadExponentialGolombCode();
int frame_mbs_only_flag = ReadBit();
if( !frame_mbs_only_flag )
{
int mb_adaptive_frame_field_flag = ReadBit();
}
int direct_8x8_inference_flag = ReadBit();
int frame_cropping_flag = ReadBit();
if( frame_cropping_flag )
{
frame_crop_left_offset = ReadExponentialGolombCode();
frame_crop_right_offset = ReadExponentialGolombCode();
frame_crop_top_offset = ReadExponentialGolombCode();
frame_crop_bottom_offset = ReadExponentialGolombCode();
}
int vui_parameters_present_flag = ReadBit();
pStart++;
int Width = ((pic_width_in_mbs_minus1 +1)*16) - frame_crop_bottom_offset*2 - frame_crop_top_offset*2;
int Height = ((2 - frame_mbs_only_flag)* (pic_height_in_map_units_minus1 +1) * 16) - (frame_crop_right_offset * 2) - (frame_crop_left_offset * 2);
printf("\n\nWxH = %dx%d\n\n",Width,Height);
}
*/
H264::TSpsParams H264::ParseSps(const ArrayBridge<uint8>&& Data)
{
return ParseSps( Data );
}
H264::TSpsParams H264::ParseSps(const ArrayBridge<uint8>& Data)
{
// test against the working version from stackoverflow
//Parse( Data.GetArray(), Data.GetDataSize() );
TSpsParams Params;
auto _DataSkipNaluByte = GetRemoteArray( Data.GetArray()+1, Data.GetDataSize()-1 );
auto DataSkipNaluByte = GetArrayBridge( _DataSkipNaluByte );
bool SkipNaluByte = false;
try
{
H264NaluContent::Type Content;
H264NaluPriority::Type Priority;
DecodeNaluByte( Data[0], Content, Priority );
SkipNaluByte = true;
}
catch (...)
{
}
TBitReader Reader( SkipNaluByte ? DataSkipNaluByte : Data );
// http://stackoverflow.com/questions/12018535/get-the-width-height-of-the-video-from-h-264-nalu
uint8 Param8;
Reader.Read( Param8, 8 );
Params.mProfile = H264Profile::Validate( Param8 );
Reader.Read( Params.mConstraintFlag[0], 1 );
Reader.Read( Params.mConstraintFlag[1], 1 );
Reader.Read( Params.mConstraintFlag[2], 1 );
Reader.Read( Params.mConstraintFlag[3], 1 );
Reader.Read( Params.mConstraintFlag[4], 1 );
Reader.Read( Params.mConstraintFlag[5], 1 );
Reader.Read( Params.mReservedZero, 2 );
uint8 Level;
Reader.Read( Level, 8 );
Params.mLevel = H264::DecodeLevel( Level );
Reader.ReadExponentialGolombCode( Params.seq_parameter_set_id );
if( Params.mProfile == H264Profile::High ||
Params.mProfile == H264Profile::High10Intra ||
Params.mProfile == H264Profile::High422Intra ||
Params.mProfile == H264Profile::High4 ||
Params.mProfile == H264Profile::High5 ||
Params.mProfile == H264Profile::High6 ||
Params.mProfile == H264Profile::High7 ||
Params.mProfile == H264Profile::High8 ||
Params.mProfile == H264Profile::High9 ||
Params.mProfile == H264Profile::HighMultiviewDepth )
{
Reader.ReadExponentialGolombCode( Params.chroma_format_idc );
if( Params.chroma_format_idc == 3 )
{
Reader.Read( Params.residual_colour_transform_flag, 1 );
}
Reader.ReadExponentialGolombCode(Params.bit_depth_luma_minus8 );
Reader.ReadExponentialGolombCode(Params.bit_depth_chroma_minus8 );
Reader.ReadExponentialGolombCode(Params.qpprime_y_zero_transform_bypass_flag );
Reader.ReadExponentialGolombCode(Params.seq_scaling_matrix_present_flag );
if (Params.seq_scaling_matrix_present_flag)
{
int i=0;
for ( i = 0; i < 8; i++)
{
Reader.Read(Params.seq_scaling_list_present_flag,1);
if (Params.seq_scaling_list_present_flag)
{
int sizeOfScalingList = (i < 6) ? 16 : 64;
int lastScale = 8;
int nextScale = 8;
int j=0;
for ( j = 0; j < sizeOfScalingList; j++)
{
if (nextScale != 0)
{
Soy_AssertTodo();
//int delta_scale = ReadSE();
//nextScale = (lastScale + delta_scale + 256) % 256;
}
lastScale = (nextScale == 0) ? lastScale : nextScale;
}
}
}
}
}
Reader.ReadExponentialGolombCode( Params.log2_max_frame_num_minus4 );
Reader.ReadExponentialGolombCode( Params.pic_order_cnt_type );
if ( Params.pic_order_cnt_type == 0 )
{
Reader.ReadExponentialGolombCode( Params.log2_max_pic_order_cnt_lsb_minus4 );
}
else if ( Params.pic_order_cnt_type == 1 )
{
Reader.Read( Params.delta_pic_order_always_zero_flag, 1 );
Reader.ReadExponentialGolombCodeSigned( Params.offset_for_non_ref_pic );
Reader.ReadExponentialGolombCodeSigned( Params.offset_for_top_to_bottom_field );
Reader.ReadExponentialGolombCode( Params.num_ref_frames_in_pic_order_cnt_cycle );
for( int i = 0; i <Params.num_ref_frames_in_pic_order_cnt_cycle; i++ )
{
sint32 Dummy;
Reader.ReadExponentialGolombCodeSigned( Dummy );
//sps->offset_for_ref_frame[ i ] = ReadSE();
}
}
Reader.ReadExponentialGolombCode( Params.num_ref_frames );
Reader.Read( Params.gaps_in_frame_num_value_allowed_flag, 1 );
Reader.ReadExponentialGolombCode( Params.pic_width_in_mbs_minus_1 );
Reader.ReadExponentialGolombCode( Params.pic_height_in_map_units_minus_1 );
Reader.Read( Params.frame_mbs_only_flag, 1 );
if( !Params.frame_mbs_only_flag )
{
Reader.Read( Params.mb_adaptive_frame_field_flag, 1 );
}
Reader.Read( Params.direct_8x8_inference_flag, 1 );
Reader.Read( Params.frame_cropping_flag, 1 );
if( Params.frame_cropping_flag )
{
Reader.ReadExponentialGolombCode( Params.frame_crop_left_offset );
Reader.ReadExponentialGolombCode( Params.frame_crop_right_offset );
Reader.ReadExponentialGolombCode( Params.frame_crop_top_offset );
Reader.ReadExponentialGolombCode( Params.frame_crop_bottom_offset );
}
Reader.Read( Params.vui_prameters_present_flag, 1 );
Reader.Read( Params.rbsp_stop_one_bit, 1 );
Params.mWidth = ((Params.pic_width_in_mbs_minus_1 +1)*16) - Params.frame_crop_bottom_offset*2 - Params.frame_crop_top_offset*2;
Params.mHeight = ((2 - Params.frame_mbs_only_flag)* (Params.pic_height_in_map_units_minus_1 +1) * 16) - (Params.frame_crop_right_offset * 2) - (Params.frame_crop_left_offset * 2);
return Params;
}
void H264::SetSpsProfile(ArrayBridge<uint8>&& Data,H264Profile::Type Profile)
{
Soy::Assert( Data.GetSize() > 0, "Not enough SPS data");
auto& ProfileByte = Data[0];
// simple byte
ProfileByte = size_cast<uint8>( Profile );
}
Soy::TVersion H264::DecodeLevel(uint8 Level8)
{
// show level
// https://github.com/ford-prefect/gst-plugins-bad/blob/master/sys/applemedia/vtdec.c
// http://stackoverflow.com/questions/21120717/h-264-video-wont-play-on-ios
// value is decimal * 10. Even if the data is bad, this should still look okay
int Minor = Level8 % 10;
int Major = (Level8-Minor) / 10;
return Soy::TVersion( Major, Minor );
}
bool H264::IsKeyframe(H264NaluContent::Type Content) __noexcept
{
// gr: maybe we should take priority into effect too?
switch ( Content )
{
case H264NaluContent::Slice_CodedIDRPicture:
return true;
default:
return false;
}
}
bool H264::IsKeyframe(SoyMediaFormat::Type Format,const ArrayBridge<uint8>&& Data) __noexcept
{
try
{
H264NaluContent::Type Content;
H264NaluPriority::Type Priority;
DecodeNaluByte( Format, GetArrayBridge(Data), Content, Priority );
return IsKeyframe( Content );
}
catch(...)
{
return false;
}
}
void H264::ConvertNaluPrefix(ArrayBridge<uint8_t>& Nalu,H264::NaluPrefix::Type NaluPrefixType)
{
// assuming annexb, this will throw if not
auto PrefixLength = H264::GetNaluAnnexBLength(Nalu);
// quick implementation for now
if ( NaluPrefixType != H264::NaluPrefix::ThirtyTwo )
Soy_AssertTodo();
auto NewPrefixSize = static_cast<int>(NaluPrefixType);
// pad if prefix was 3 bytes
if ( PrefixLength == 3 )
Nalu.InsertAt(0,0);
else if ( PrefixLength != 4)
throw Soy::AssertException("Expecting nalu size of 4");
// write over prefix
uint32_t Size32 = Nalu.GetDataSize() - NewPrefixSize;
uint8_t* Size8s = reinterpret_cast<uint8_t*>(&Size32);
Nalu[0] = Size8s[3];
Nalu[1] = Size8s[2];
Nalu[2] = Size8s[1];
Nalu[3] = Size8s[0];
}
size_t H264::GetNextNaluOffset(const ArrayBridge<uint8_t>&& Data, size_t StartFrom)
{
if ( Data.GetDataSize() < 4 )
return 0;
// detect 001
auto* DataPtr = Data.GetArray();
for (int i = StartFrom; i < Data.GetDataSize()-3; i++)
{
if (DataPtr[i + 0] != 0) continue;
if (DataPtr[i + 1] != 0) continue;
if (DataPtr[i + 2] != 1) continue;
// check i-1 for 0 in case it's 0001 rather than 001
if (DataPtr[i - 1] == 0)
return i - 1;
return i;
}
return 0;
}
void H264::SplitNalu(const ArrayBridge<uint8_t>& Data,std::function<void(const ArrayBridge<uint8_t>&&)> OnNalu)
{
// gr: this was happening in android test app, GetSubArray() will throw, so catch it
if ( Data.IsEmpty() )
{
std::Debug << "Unexpected " << __PRETTY_FUNCTION__ << " Data.Size=" << Data.GetDataSize() << std::endl;
return;
}
// split up packet if there are multiple nalus
size_t PrevNalu = 0;
while (true)
{
auto PacketData = GetArrayBridge(Data).GetSubArray(PrevNalu);
auto NextNalu = H264::GetNextNaluOffset(GetArrayBridge(PacketData));
if (NextNalu == 0)
{
// everything left
OnNalu(GetArrayBridge(PacketData));
break;
}
else
{
auto SubArray = GetArrayBridge(PacketData).GetSubArray(0, NextNalu);
OnNalu(GetArrayBridge(SubArray));
PrevNalu += NextNalu;
}
}
}
size_t H264::GetNaluLength(const ArrayBridge<uint8_t>& Packet)
{
// todo: test for u8/u16/u32 size prefix
if ( Packet.GetSize() < 4 )
return 0;
auto p0 = Packet[0];
auto p1 = Packet[1];
auto p2 = Packet[2];
auto p3 = Packet[3];
if ( p0 == 0 && p1 == 0 && p2 == 1 )
return 3;
if ( p0 == 0 && p1 == 0 && p2 == 0 && p3 == 1)
return 4;
// couldn't detect, possibly no prefx and it's raw data
// could parse packet type to verify
return 0;
}
size_t H264::GetNaluAnnexBLength(const ArrayBridge<uint8_t>& Packet)
{
// todo: test for u8/u16/u32 size prefix
if ( Packet.GetSize() < 4 )
throw Soy::AssertException("Packet not long enough for annexb");
auto Data0 = Packet[0];
auto Data1 = Packet[1];
auto Data2 = Packet[2];
auto Data3 = Packet[3];
if (Data0 != 0 || Data1 != 0)
throw Soy::AssertException("Data is not bytestream NALU header (leading zeroes)");
if (Data2 == 1)
return 3;
if (Data2 == 0 && Data3 == 1)
return 4;
throw Soy::AssertException("Data is not bytestream NALU header (suffix)");
}
H264NaluContent::Type H264::GetPacketType(const ArrayBridge<uint8_t>&& Data)
{
auto HeaderLength = GetNaluLength(Data);
auto TypeAndPriority = Data[HeaderLength];
auto Type = TypeAndPriority & 0x1f;
auto Priority = TypeAndPriority >> 5;
auto TypeEnum = static_cast<H264NaluContent::Type>(Type);
return TypeEnum;
}
void ReformatDeliminator(ArrayBridge<uint8>& Data,
std::function<size_t(ArrayBridge<uint8>& Data,size_t Position)> ExtractChunk,
std::function<void(size_t ChunkLength,ArrayBridge<uint8>& Data,size_t& Position)> InsertChunk)
{
size_t Position = 0;
while ( true )
{
auto ChunkLength = ExtractChunk( Data, Position );
if ( ChunkLength == 0 )
break;
{
std::stringstream Error;
Error << "Extracted NALU length of " << ChunkLength << "/" << Data.GetDataSize();
Soy::Assert( ChunkLength <= Data.GetDataSize(), Error.str() );
}
InsertChunk( ChunkLength, Data, Position );
Position += ChunkLength;
}
}
| 24.613851 | 180 | 0.689432 | SoylentGraham |
ee21f0cae9e347454c2aa5d8b983bdcf05f4ed7e | 3,403 | hpp | C++ | native/Vendor/vmmlib/matrix_functors.hpp | aholkner/bacon | edf3810dcb211942d392a8637945871399b0650d | [
"MIT"
] | 37 | 2015-01-29T17:42:11.000Z | 2021-12-14T22:11:33.000Z | include/vmmlib/matrix_functors.hpp | rballester/vmmlib | f27d907a0eb81ffaef5bf177796b642f10e96ed3 | [
"BSD-3-Clause"
] | 3 | 2015-08-13T17:38:05.000Z | 2020-09-25T17:21:31.000Z | include/vmmlib/matrix_functors.hpp | rballester/vmmlib | f27d907a0eb81ffaef5bf177796b642f10e96ed3 | [
"BSD-3-Clause"
] | 7 | 2015-02-12T17:54:35.000Z | 2022-01-31T14:50:09.000Z | #ifndef __VMML__MATRIX_FUNCTORS__HPP__
#define __VMML__MATRIX_FUNCTORS__HPP__
#include <vmmlib/enable_if.hpp>
#include <cstddef>
#include <functional>
namespace vmml
{
template< typename T >
struct set_to_zero_functor
{
inline void operator()( T& matrix_ ) const
{
matrix_ = static_cast< typename T::value_type >( 0.0 );
}
}; // struct set_to_zero
template< typename T >
struct set_to_identity_functor
{
inline
typename enable_if< T::ROWS == T::COLS >::type*
operator()( T& matrix_ )
{
set_to_zero_functor< T >()( matrix_ );
for( size_t index = 0; index < T::ROWS; ++index )
{
matrix_( index, index ) = static_cast< typename T::value_type >( 1.0 );
}
return 0; // for sfinae
}
}; // struct set_to_identity
// this functor compares to matrices, and also returns true/equal if
// the matrices have the same values but some rows/columns are inverted
template< typename T >
struct matrix_equals_allow_inverted_rows : std::binary_function< const T&, const T&, bool >
{
bool operator()( const T& matrix0, const T& matrix1 )
{
const size_t r = matrix0.get_number_of_rows();
bool ok = true;
for( size_t index = 0; ok && index < r; ++index )
{
if ( matrix0.get_row( index ) != matrix1.get_row( index )
&& matrix0.get_row( index ) != - matrix1.get_row( index ) )
{
ok = false;
}
}
return ok;
}
bool operator()( const T& matrix0, const T& matrix1, typename T::value_type tolerance )
{
const size_t r = matrix0.get_number_of_rows();
bool ok = true;
for( size_t index = 0; ok && index < r; ++index )
{
if (
! matrix0.get_row( index ).equals( matrix1.get_row( index ), tolerance )
&& ! matrix0.get_row( index ).equals( - matrix1.get_row( index ), tolerance )
)
{
ok = false;
}
}
return ok;
}
}; // struct matrix_equals_allow_inverted_rows
template< typename T >
struct matrix_equals_allow_inverted_columns : std::binary_function< const T&, const T&, bool >
{
bool operator()( const T& matrix0, const T& matrix1 )
{
const size_t r = matrix0.get_number_of_columns();
bool ok = true;
for( size_t index = 0; ok && index < r; ++index )
{
if ( matrix0.get_column( index ) != matrix1.get_column( index )
&& matrix0.get_column( index ) != - matrix1.get_column( index ) )
{
ok = false;
}
}
return ok;
}
bool operator()( const T& matrix0, const T& matrix1, typename T::value_type tolerance )
{
const size_t r = matrix0.get_number_of_columns();
bool ok = true;
for( size_t index = 0; ok && index < r; ++index )
{
if (
! matrix0.get_column( index ).equals( matrix1.get_column( index ), tolerance )
&& ! matrix0.get_column( index ).equals( - matrix1.get_column( index ), tolerance )
)
{
ok = false;
}
}
return ok;
}
}; // struct matrix_equals_allow_inverted_columns
} // namespace vmml
#endif
| 26.379845 | 99 | 0.550984 | aholkner |
ee247eda72fe11875ef120074658af1025ff76d0 | 430 | cpp | C++ | screenbot/Version.cpp | daemon/monkeybot | 50bf65674daefa12bfc002771243360bb1d07481 | [
"Unlicense"
] | null | null | null | screenbot/Version.cpp | daemon/monkeybot | 50bf65674daefa12bfc002771243360bb1d07481 | [
"Unlicense"
] | null | null | null | screenbot/Version.cpp | daemon/monkeybot | 50bf65674daefa12bfc002771243360bb1d07481 | [
"Unlicense"
] | null | null | null | #include "Version.h"
#include <sstream>
namespace {
const int Major = 4;
const int Minor = 2;
const int Revision = 2;
} // ns
int Version::GetMajor() {
return Major;
}
int Version::GetMinor() {
return Minor;
}
int Version::GetRevision() {
return Revision;
}
std::string Version::GetString() {
std::stringstream ss;
ss << GetMajor() << "." << GetMinor() << "." << GetRevision();
return ss.str();
}
| 13.870968 | 66 | 0.604651 | daemon |
ee2558736f67f98320f4a67ae05e011c302fc1ea | 7,724 | cpp | C++ | src/repast_hpc/GridComponents.cpp | etri/dtsim | 927c8e05c08c74ed376ec233ff677cd35b29e6f0 | [
"BSD-3-Clause"
] | null | null | null | src/repast_hpc/GridComponents.cpp | etri/dtsim | 927c8e05c08c74ed376ec233ff677cd35b29e6f0 | [
"BSD-3-Clause"
] | null | null | null | src/repast_hpc/GridComponents.cpp | etri/dtsim | 927c8e05c08c74ed376ec233ff677cd35b29e6f0 | [
"BSD-3-Clause"
] | null | null | null | /*
* Repast for High Performance Computing (Repast HPC)
*
* Copyright (c) 2010 Argonne National Laboratory
* All rights reserved.
*
* Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that the following
* conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the Argonne National Laboratory 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 TRUSTEES 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.
*
*
* GridComponents.cpp
*
* Created on: Jun 23, 2009
* Author: nick
*/
#include "GridComponents.h"
#include "RepastErrors.h"
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <limits.h>
#include <math.h>
using namespace std;
namespace repast {
// Borders (parent class for border implementations with fixed boundaries
Borders::Borders(GridDimensions d): _dimensions(d){ }
void Borders::boundsCheck(const vector<int>& pt) const {
if (!_dimensions.contains(pt)) throw Repast_Error_12<GridDimensions>(pt, _dimensions); // Point is out of dimension range
}
void Borders::boundsCheck(const vector<double>& pt) const {
if (!_dimensions.contains(pt)) throw std::out_of_range("Point is out of dimension range"); // !
}
void Borders::transform(const std::vector<double>& in, std::vector<double>& out) const {
boundsCheck(in);
if (out.size() != in.size()) out.insert(out.begin(), in.size(), 0);
std::copy(in.begin(), in.end(), out.begin());
}
void Borders::transform(const std::vector<int>& in, std::vector<int>& out) const {
boundsCheck(in);
if (out.size() != in.size()) out.insert(out.begin(), in.size(), 0);
std::copy(in.begin(), in.end(), out.begin());
}
// Strict Borders (translations outside the borders throw error
StrictBorders::StrictBorders(GridDimensions d): Borders(d) { }
void StrictBorders::translate(const std::vector<double>& oldPos, std::vector<double>& newPos, const std::vector<double>& displacement) const {
if (displacement.size() != oldPos.size() || displacement.size() != newPos.size())
throw Repast_Error_13(oldPos, newPos, displacement); // Position and displacement vectors must be of the same size
for (int i = 0, n = displacement.size(); i < n; ++i) newPos[i] = oldPos[i] + displacement[i];
boundsCheck(newPos);
}
void StrictBorders::translate(const std::vector<int>& oldPos, std::vector<int>& newPos,
const std::vector<int>& displacement) const {
if (displacement.size() != oldPos.size() || displacement.size() != newPos.size())
throw Repast_Error_14(oldPos, newPos, displacement); // Position and displacement vectors must be of the same size
for (int i = 0, n = displacement.size(); i < n; ++i) newPos[i] = oldPos[i] + displacement[i];
boundsCheck(newPos);
}
// Sticky Borders: Translations outside the border are fixed to the border
StickyBorders::StickyBorders(GridDimensions d): Borders(d) {
for (size_t i = 0, n = _dimensions.dimensionCount(); i < n; ++i) {
mins.push_back(_dimensions.origin(i));
maxs.push_back(_dimensions.origin(i) + _dimensions.extents(i)); // Originally - 1
}
}
void StickyBorders::translate(const std::vector<double>& oldPos, std::vector<double>& newPos,
const std::vector<double>& displacement) const {
if (displacement.size() != oldPos.size() || displacement.size() != newPos.size())
throw Repast_Error_17(oldPos, newPos, displacement); // Position and displacement vectors must be of the same size
for (size_t i = 0, n = displacement.size(); i < n; ++i) newPos[i] = calcCoord<double>(oldPos[i] + displacement[i], i);
}
void StickyBorders::translate(const std::vector<int>& oldPos, std::vector<int>& newPos,
const std::vector<int>& displacement) const {
if (displacement.size() != oldPos.size() || displacement.size() != newPos.size())
throw Repast_Error_18(oldPos, newPos, displacement); // Position and displacement vectors must be of the same size
for (size_t i = 0, n = displacement.size(); i < n; ++i) newPos[i] = calcCoord<int>(oldPos[i] + displacement[i], i);
}
// Wrap-around Borders
WrapAroundBorders::WrapAroundBorders(GridDimensions dimensions): _dimensions(dimensions) {
for (size_t i = 0; i < dimensions.dimensionCount(); ++i) {
mins.push_back(dimensions.origin(i));
maxs.push_back(dimensions.origin(i) + dimensions.extents(i)); // Originally - 1
}
}
void WrapAroundBorders::transform(const std::vector<int>& in, std::vector<int>& out) const {
if (out.size() < in.size()) out.insert(out.begin(), in.size(), 0);
for (size_t i = 0, n = in.size(); i < n; ++i){
int coord = in[i];
if(coord >= mins[i] && coord < maxs[i])
out[i] = coord;
else
out[i] = fmod((double)(coord-_dimensions.origin(i)), (double)_dimensions.extents(i)) +
(coord < _dimensions.origin(i) ? _dimensions.extents(i) : 0) +
_dimensions.origin(i);
}
}
void WrapAroundBorders::transform(const std::vector<double>& in, std::vector<double>& out) const {
if (out.size() < in.size()) out.insert(out.begin(), in.size(), 0);
for (size_t i = 0, n = in.size(); i < n; ++i){
double coord = in[i];
if(coord >= mins[i] && coord < maxs[i])
out[i] = coord;
else{
out[i] = fmod((coord-_dimensions.origin(i)), _dimensions.extents(i)) +
(coord < _dimensions.origin(i) ? _dimensions.extents(i) : 0) +
_dimensions.origin(i);
if(out[i] >= maxs[i]) out[i] = nextafter(maxs[i], -DBL_MAX);
else if(out[i] < mins[i]) out[i] = nextafter(mins[i], DBL_MAX);
}
}
}
void WrapAroundBorders::translate(const std::vector<double>& oldPos, std::vector<double>& newPos, const std::vector<
double>& displacement) const {
if (displacement.size() != oldPos.size() || displacement.size() != newPos.size())
throw Repast_Error_15(oldPos, newPos, displacement); // Position and displacement vectors must be of the same size
for (int i = 0, n = displacement.size(); i < n; ++i) newPos[i] = oldPos[i] + displacement[i];
transform(newPos, newPos);
}
void WrapAroundBorders::translate(const std::vector<int>& oldPos, std::vector<int>& newPos,
const std::vector<int>& displacement) const {
if (displacement.size() != oldPos.size() || displacement.size() != newPos.size())
throw Repast_Error_16(oldPos, newPos, displacement); // Position and displacement vectors must be of the same size
for (int i = 0, n = displacement.size(); i < n; ++i) newPos[i] = oldPos[i] + displacement[i];
transform(newPos, newPos);
}
}
| 39.814433 | 142 | 0.684878 | etri |
ee270da9bd3331a6f82ae623113725a2f3c02b10 | 4,359 | cpp | C++ | src/interpolation.cpp | NChechulin/spline-interpolation | 34333b885c435d5dfd1ab892a9cc8a79e016c448 | [
"MIT"
] | 1 | 2021-04-26T14:15:20.000Z | 2021-04-26T14:15:20.000Z | src/interpolation.cpp | NChechulin/spline-interpolation | 34333b885c435d5dfd1ab892a9cc8a79e016c448 | [
"MIT"
] | null | null | null | src/interpolation.cpp | NChechulin/spline-interpolation | 34333b885c435d5dfd1ab892a9cc8a79e016c448 | [
"MIT"
] | null | null | null | #include "interpolation.h"
#include <QTextStream>
#include <cmath>
#include <fstream>
#include <vector>
#include "polynomial.h"
const double EPS = 1e-6;
Interpolation Interpolation::FromFile(QString path) {
Interpolation result;
QFile file(path);
if (!file.open(QIODevice::ReadOnly)) {
throw std::runtime_error(file.errorString().toStdString());
}
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(' ');
if (fields.length() == 2) {
QPointF point(fields[0].toDouble(), fields[1].toDouble());
result.points.push_back(point);
}
}
file.close();
std::sort(result.points.begin(), result.points.end(),
[](QPointF a, QPointF b) { return (a.x() < b.x()); });
result.check_points();
return result;
}
void Interpolation::check_points() const {
if (this->points.size() <= 2) {
throw std::length_error("Less than 3 points were provided");
}
for (size_t i = 0; i < this->points.size() - 1; ++i) {
if (std::abs(points[i].x() - points[i + 1].x()) < EPS) {
throw std::range_error(
"There are at least 2 points with the same X coordinate");
}
}
}
void RREF(std::vector<std::vector<double>>& mat) {
size_t lead = 0;
for (size_t r = 0; r < mat.size(); r++) {
if (mat[0].size() <= lead) {
return;
}
size_t i = r;
while (mat[i][lead] == 0) {
i++;
if (mat.size() == i) {
i = r;
lead++;
if (mat[0].size() == lead) {
return;
}
}
}
std::swap(mat[i], mat[r]);
double val = mat[r][lead];
for (size_t j = 0; j < mat[0].size(); j++) {
mat[r][j] /= val;
}
for (size_t i = 0; i < mat.size(); i++) {
if (i == r) continue;
val = mat[i][lead];
for (size_t j = 0; j < mat[0].size(); j++) {
mat[i][j] = mat[i][j] - val * mat[r][j];
}
}
lead++;
}
}
std::vector<Polynomial> Interpolation::Interpolate() {
size_t size = this->points.size();
size_t solution_index = (size - 1) * 4;
size_t row = 0;
std::vector<std::vector<double>> matrix(
solution_index, std::vector<double>(solution_index + 1, 0));
// splines through equations
for (size_t functionNr = 0; functionNr < size - 1; functionNr++, row++) {
QPointF p0 = this->points[functionNr], p1 = this->points[functionNr + 1];
matrix[row][functionNr * 4 + 0] = std::pow(p0.x(), 3);
matrix[row][functionNr * 4 + 1] = std::pow(p0.x(), 2);
matrix[row][functionNr * 4 + 2] = p0.x();
matrix[row][functionNr * 4 + 3] = 1;
matrix[row][solution_index] = p0.y();
matrix[++row][functionNr * 4 + 0] = std::pow(p1.x(), 3);
matrix[row][functionNr * 4 + 1] = std::pow(p1.x(), 2);
matrix[row][functionNr * 4 + 2] = p1.x();
matrix[row][functionNr * 4 + 3] = 1;
matrix[row][solution_index] = p1.y();
}
// first derivative
for (size_t functionNr = 0; functionNr < size - 2; functionNr++, row++) {
QPointF p1 = this->points[functionNr + 1];
matrix[row][functionNr * 4 + 0] = std::pow(p1.x(), 2) * 3;
matrix[row][functionNr * 4 + 1] = p1.x() * 2;
matrix[row][functionNr * 4 + 2] = 1;
matrix[row][functionNr * 4 + 4] = std::pow(p1.x(), 2) * -3;
matrix[row][functionNr * 4 + 5] = p1.x() * -2;
matrix[row][functionNr * 4 + 6] = -1;
}
// second derivative
for (size_t functionNr = 0; functionNr < size - 2; functionNr++, row++) {
QPointF p1 = this->points[functionNr + 1];
matrix[row][functionNr * 4 + 0] = p1.x() * 6;
matrix[row][functionNr * 4 + 1] = 2;
matrix[row][functionNr * 4 + 4] = p1.x() * -6;
matrix[row][functionNr * 4 + 5] = -2;
}
matrix[row][0 + 0] = this->points[0].x() * 6;
matrix[row++][0 + 1] = 2;
matrix[row][solution_index - 4 + 0] = this->points[size - 1].x() * 6;
matrix[row][solution_index - 4 + 1] = 2;
RREF(matrix);
std::vector<double> coefficients;
coefficients.reserve(matrix.size());
for (auto& i : matrix) {
coefficients.push_back(i[i.size() - 1]);
}
std::vector<Polynomial> functions;
for (size_t i = 0; i < coefficients.size(); i += 4) {
Polynomial p = Polynomial::GetCoefficientsFromVector(coefficients.begin() + i);
p.from = this->points[i / 4].x();
p.to = this->points[i / 4 + 1].x();
functions.push_back(p);
}
return functions;
}
| 28.677632 | 83 | 0.561367 | NChechulin |
ee28152ca589510f65d2def7dd44083bfdc1b6d9 | 6,022 | hpp | C++ | file/Json.hpp | CltKitakami/MyLib | d2dc4fb06ea5c3379a1818b49b0ecf13f8cd2b36 | [
"MIT"
] | null | null | null | file/Json.hpp | CltKitakami/MyLib | d2dc4fb06ea5c3379a1818b49b0ecf13f8cd2b36 | [
"MIT"
] | null | null | null | file/Json.hpp | CltKitakami/MyLib | d2dc4fb06ea5c3379a1818b49b0ecf13f8cd2b36 | [
"MIT"
] | null | null | null | #ifndef _JSON_HPP_
#define _JSON_HPP_
#include <string>
#include <vector>
#include <list>
#include <map>
#include "common/Exception.hpp"
class JsonArray;
class JsonArrayAst;
class JsonObject;
class JsonObjectAst;
class JsonValue
{
public:
typedef enum Type
{
NULL_VALUE,
STRING,
NUMBER,
OBJECT,
ARRAY,
BOOLEAN
} Type;
typedef struct Object
{
JsonObject *obj;
JsonObjectAst *ast;
} Object;
typedef struct Array
{
JsonArray *arr;
JsonArrayAst *ast;
} Array;
JsonValue() : value(nullptr), refCount(new int(1)), type(NULL_VALUE) {}
JsonValue(const JsonValue &v) { copy(v); }
~JsonValue() { release(); }
static std::string typeToString(Type type);
void assertType(Type type) const;
Type getType() const { return this->type; }
static JsonValue create(const char *str, size_t length);
static JsonValue create(const std::string &str) { return create(str.data(), str.length()); }
static JsonValue create(bool value);
static JsonValue create(double value);
void createString(const char *str, size_t length);
void createString(const std::string &str) { createString(str.data(), str.length()); }
void setString(const std::string &str)
{
assertType(STRING);
*(std::string *)this->value = str;
}
std::string & getString() const
{
assertType(STRING);
return *(std::string *)this->value;
}
void createBoolean(bool value);
void setBoolean(bool value)
{
assertType(BOOLEAN);
this->value = value ? (void *)1 : nullptr;
}
bool getBoolean() const
{
assertType(BOOLEAN);
return this->value != nullptr;
}
void createNumber(double value);
void setNumber(double value)
{
assertType(NUMBER);
*(double *)this->value = value;
}
double getNumber() const
{
assertType(NUMBER);
return *(double *)this->value;
}
void createArray();
const JsonArray * getArray() const
{
assertType(ARRAY);
return ((Array *)this->value)->arr;
}
JsonArray * getArray()
{
assertType(ARRAY);
return ((Array *)this->value)->arr;
}
JsonArrayAst * getArrayAst()
{
assertType(ARRAY);
return ((Array *)this->value)->ast;
}
void createObject();
JsonObject * getObject() const
{
assertType(OBJECT);
return ((Object *)this->value)->obj;
}
JsonObjectAst * getObjectAst()
{
assertType(OBJECT);
return ((Object *)this->value)->ast;
}
std::string toString() const;
void assign(const JsonValue &v);
JsonValue & operator = (const JsonValue &v)
{ this->assign(v); return *this; }
private:
void release();
void copy(const JsonValue &v);
void *value;
int *refCount;
Type type;
};
class JsonArray
{
std::vector<JsonValue> array;
public:
void put(const JsonValue &v) { this->array.push_back(v); }
JsonValue & get(int index) { return this->array[(unsigned)index]; }
const JsonValue & get(int index) const { return this->array[(unsigned)index]; }
size_t getSize() const { return this->array.size(); }
JsonValue & operator [] (int index) { return this->get(index); }
const JsonValue & operator [] (int index) const { return this->get(index); }
};
class JsonPair
{
public:
JsonPair(const std::string &name) : name(name) {}
void setName(const std::string &name) { this->name = name; }
std::string getName() const { return this->name; }
void setValue(const JsonValue &value) { this->value = value; }
JsonValue getValue() const { return this->value; }
JsonValue * getReferenceValue() { return &this->value; }
bool equals(const std::string &name) const { return this->name == name; }
private:
std::string name;
JsonValue value;
};
class JsonObject
{
public:
typedef std::list<JsonPair> Pairs;
typedef std::map<std::string, JsonValue *> PairMap;
void addPair(const JsonPair &p) { pairs.push_back(p); }
void removePair(const std::string &name);
PairMap buildMap();
Pairs::iterator begin() { return pairs.begin(); }
Pairs::iterator end() { return pairs.end(); }
Pairs::const_iterator begin() const { return pairs.begin(); }
Pairs::const_iterator end() const { return pairs.end(); }
JsonPair & front() { return pairs.front(); }
const JsonPair & front() const { return pairs.front(); }
JsonPair & back() { return pairs.back(); }
const JsonPair & back() const { return pairs.back(); }
size_t getPairsSize() const { return pairs.size(); }
private:
Pairs pairs;
};
class Json
{
JsonObject object;
static void newLineToString(std::string &buffer, int tabDepth);
static void appendSpace(std::string &buffer);
static void valueToString(std::string &buffer, const JsonValue &value, int tabDepth);
static void arrayToString(std::string &buffer, const JsonArray &array, int tabDepth);
static void objectToString(std::string &buffer, const JsonObject &object, int tabDepth);
public:
typedef JsonObject::Pairs Pairs;
typedef JsonObject::PairMap PairMap;
Json() {}
Json(const char *fileName) { (void)open(fileName); }
Json(const std::string &fileName) { (void)open(fileName.data()); }
Json(const void *data, size_t length) { (void)openFromMemory(data, length); }
Json(const Json &json) : object(json.object) {}
Json(const JsonObject &object) : object(object) {}
bool open(const char *fileName);
bool openFromMemory(const void *data, size_t length);
void save(const char *fileName);
std::string toString() const;
void addPair(const JsonPair &p) { this->object.addPair(p); }
void removePair(const std::string &name) { this->object.removePair(name); }
Json & operator = (const Json &json) { this->object = json.object; return *this; }
PairMap buildMap() { return this->object.buildMap(); }
Pairs::iterator begin() { return this->object.begin(); }
Pairs::iterator end() { return this->object.end(); }
Pairs::const_iterator begin() const { return this->object.begin(); }
Pairs::const_iterator end() const { return this->object.end(); }
JsonPair & front() { return this->object.front(); }
const JsonPair & front() const { return this->object.front(); }
JsonPair & back() { return this->object.back(); }
const JsonPair & back() const { return this->object.back(); }
};
#endif
| 23.615686 | 93 | 0.688808 | CltKitakami |
ee292895582131c9ff656d470b7f901ba9b47436 | 7,004 | cc | C++ | components/data_reduction_proxy/core/browser/data_reduction_proxy_settings_test_utils.cc | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/data_reduction_proxy/core/browser/data_reduction_proxy_settings_test_utils.cc | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/data_reduction_proxy/core/browser/data_reduction_proxy_settings_test_utils.cc | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-04-04T13:34:56.000Z | 2020-11-04T07:17:52.000Z | // Copyright 2014 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 "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings_test_utils.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "base/strings/string_number_conversions.h"
#include "base/time/time.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_config_test_utils.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_configurator_test_utils.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_statistics_prefs.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_test_utils.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_headers_test_utils.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_params_test_utils.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_switches.h"
using testing::_;
using testing::AnyNumber;
using testing::Return;
namespace {
const char kProxy[] = "proxy";
} // namespace
namespace data_reduction_proxy {
DataReductionProxySettingsTestBase::DataReductionProxySettingsTestBase()
: testing::Test() {
}
DataReductionProxySettingsTestBase::~DataReductionProxySettingsTestBase() {}
// testing::Test implementation:
void DataReductionProxySettingsTestBase::SetUp() {
test_context_.reset(new DataReductionProxyTestContext(
DataReductionProxyParams::kAllowed |
DataReductionProxyParams::kFallbackAllowed |
DataReductionProxyParams::kPromoAllowed,
TestDataReductionProxyParams::HAS_EVERYTHING &
~TestDataReductionProxyParams::HAS_DEV_ORIGIN &
~TestDataReductionProxyParams::HAS_DEV_FALLBACK_ORIGIN,
DataReductionProxyTestContext::USE_MOCK_CONFIG |
DataReductionProxyTestContext::SKIP_SETTINGS_INITIALIZATION));
PrefRegistrySimple* registry = test_context_->pref_service()->registry();
registry->RegisterListPref(prefs::kDailyHttpOriginalContentLength);
registry->RegisterListPref(prefs::kDailyHttpReceivedContentLength);
registry->RegisterInt64Pref(prefs::kDailyHttpContentLengthLastUpdateDate,
0L);
registry->RegisterDictionaryPref(kProxy);
registry->RegisterBooleanPref(prefs::kDataReductionProxyEnabled, false);
registry->RegisterBooleanPref(prefs::kDataReductionProxyAltEnabled, false);
registry->RegisterBooleanPref(prefs::kDataReductionProxyWasEnabledBefore,
false);
//AddProxyToCommandLine();
ResetSettings(true, true, false, true, false);
ListPrefUpdate original_update(test_context_->pref_service(),
prefs::kDailyHttpOriginalContentLength);
ListPrefUpdate received_update(test_context_->pref_service(),
prefs::kDailyHttpReceivedContentLength);
for (int64 i = 0; i < kNumDaysInHistory; i++) {
original_update->Insert(0,
new base::StringValue(base::Int64ToString(2 * i)));
received_update->Insert(0, new base::StringValue(base::Int64ToString(i)));
}
last_update_time_ = base::Time::Now().LocalMidnight();
settings_->data_reduction_proxy_service()->statistics_prefs()->SetInt64(
prefs::kDailyHttpContentLengthLastUpdateDate,
last_update_time_.ToInternalValue());
}
template <class C>
void DataReductionProxySettingsTestBase::ResetSettings(bool allowed,
bool fallback_allowed,
bool alt_allowed,
bool promo_allowed,
bool holdback) {
int flags = 0;
if (allowed)
flags |= DataReductionProxyParams::kAllowed;
if (fallback_allowed)
flags |= DataReductionProxyParams::kFallbackAllowed;
if (alt_allowed)
flags |= DataReductionProxyParams::kAlternativeAllowed;
if (promo_allowed)
flags |= DataReductionProxyParams::kPromoAllowed;
if (holdback)
flags |= DataReductionProxyParams::kHoldback;
MockDataReductionProxySettings<C>* settings =
new MockDataReductionProxySettings<C>();
settings->config_ = test_context_->config();
settings->data_reduction_proxy_service_ =
test_context_->CreateDataReductionProxyService();
test_context_->config()->ResetParamFlagsForTest(flags);
settings->UpdateConfigValues();
EXPECT_CALL(*settings, GetOriginalProfilePrefs())
.Times(AnyNumber())
.WillRepeatedly(Return(test_context_->pref_service()));
EXPECT_CALL(*settings, GetLocalStatePrefs())
.Times(AnyNumber())
.WillRepeatedly(Return(test_context_->pref_service()));
settings_.reset(settings);
}
// Explicitly generate required instantiations.
template void
DataReductionProxySettingsTestBase::ResetSettings<DataReductionProxySettings>(
bool allowed,
bool fallback_allowed,
bool alt_allowed,
bool promo_allowed,
bool holdback);
void DataReductionProxySettingsTestBase::ExpectSetProxyPrefs(
bool expected_enabled,
bool expected_alternate_enabled,
bool expected_at_startup) {
MockDataReductionProxyConfig* config =
static_cast<MockDataReductionProxyConfig*>(test_context_->config());
EXPECT_CALL(*config,
SetProxyPrefs(expected_enabled, expected_alternate_enabled,
expected_at_startup));
}
void DataReductionProxySettingsTestBase::CheckOnPrefChange(
bool enabled,
bool expected_enabled,
bool managed) {
ExpectSetProxyPrefs(expected_enabled, false, false);
if (managed) {
test_context_->pref_service()->SetManagedPref(
prefs::kDataReductionProxyEnabled, new base::FundamentalValue(enabled));
} else {
test_context_->pref_service()->SetBoolean(prefs::kDataReductionProxyEnabled,
enabled);
}
test_context_->RunUntilIdle();
// Never expect the proxy to be restricted for pref change tests.
}
void DataReductionProxySettingsTestBase::CheckInitDataReductionProxy(
bool enabled_at_startup) {
settings_->InitDataReductionProxySettings(
test_context_->pref_service(), test_context_->io_data(),
test_context_->CreateDataReductionProxyService());
settings_->SetOnDataReductionEnabledCallback(
base::Bind(&DataReductionProxySettingsTestBase::
RegisterSyntheticFieldTrialCallback,
base::Unretained(this)));
test_context_->RunUntilIdle();
EXPECT_EQ(enabled_at_startup, proxy_enabled_);
}
} // namespace data_reduction_proxy
| 42.192771 | 102 | 0.740148 | hefen1 |
0c52afb65946ecefbb56205bb4925d7ef3b1745b | 7,371 | cpp | C++ | interpreter/assert.cpp | istvan-vonfedak/TuringMachines | 8a8b5f40349974d43a4b608b105162a984316746 | [
"MIT"
] | 1 | 2019-03-13T14:03:30.000Z | 2019-03-13T14:03:30.000Z | interpreter/assert.cpp | istvan-vonfedak/TuringMachines | 8a8b5f40349974d43a4b608b105162a984316746 | [
"MIT"
] | null | null | null | interpreter/assert.cpp | istvan-vonfedak/TuringMachines | 8a8b5f40349974d43a4b608b105162a984316746 | [
"MIT"
] | null | null | null | #include "assert.hpp"
// assert arguments
void assertArguments(const int & argc, char * argv[])
{ if( argc < 3 || argc > 4 || ( argc == 4 && strncmp("-f", argv[2], 2) != 0) )
{ fprintf(stderr, MAG "Usage" RST ": %s ", argv[0]);
fprintf(stderr, CYN "<TM-file-name> <input-string>\n" RST);
fprintf(stderr, MAG " or" RST ": %s ", argv[0]);
fprintf(stderr, CYN "<TM-file-name>" RST " -f ");
fprintf(stderr, CYN "<input-file-name>\n" RST);
exit(1); } }
// check if file opened
void assertFileOpen(const std::ifstream & fin, const std::string fileName)
{ if ( fin.fail() )
{ fprintf(stderr, RED "Failed" RST " to open file: ");
fprintf(stderr, RED "'%s'" RST ".\n\n", fileName.c_str());
exit(1); } }
// check the state is of proper size
void assertStateSize(const int & lineNumber, const int & tokenCount,
const std::string tokens[], const int & size)
{ if ( tokenCount < size -1 )
{ fprintf(stderr, RED "Error" RST " on " MAG "line %d" RST, lineNumber);
fprintf(stderr, ": table entry has " MAG "not enough" RST " arguments.\n");
fprintf(stderr, " Please provide: stateName, charOnTape, ");
fprintf(stderr, "newStateName, newCharOnTape, direction\n\n");
exit(1); }
// this allows comments at the end of a line
if ( tokenCount == size && tokens[5] != "//" )
{ fprintf(stderr, RED "Error" RST " on " MAG "line %d" RST, lineNumber);
fprintf(stderr, ": table entry has " MAG "too many" RST " arguments.\n");
fprintf(stderr, " Please provide: stateName, charOnTape, ");
fprintf(stderr, "newStateName, newCharOnTape, direction\n\n");
exit(1); } }
// check that the currect character to be read from tape is a character
void assertCurChar(const int & lineNumber, std::string tokens[])
{ if ( tokens[1].size() > 1 )
{ fprintf(stderr, RED "Error" RST " on " MAG "line %d" RST, lineNumber);
fprintf(stderr, "," MAG " entry %d" RST ": Character", 2);
fprintf(stderr, RED " '%s'" RST, tokens[1].c_str());
fprintf(stderr, " to be read from tape\n is");
fprintf(stderr, MAG " not a character" RST ".\n\n");
exit(1); } }
// check that the new character to be written on tape is a character
void assertNewChar(const int & lineNumber, std::string tokens[])
{ if ( tokens[3].size() > 1 )
{ fprintf(stderr, RED "Error" RST " on " MAG "line %d" RST, lineNumber);
fprintf(stderr, "," MAG " entry %d" RST ": Character", 4);
fprintf(stderr, RED " '%s'" RST, tokens[3].c_str());
fprintf(stderr, " to be written on tape\n is");
fprintf(stderr, MAG " not a character" RST ".\n\n");
exit(1); } }
// check that direction is one of the predefined characters
void assertDirection(const int & lineNumber, std::string tokens[])
{ if ( tokens[4].size() > 1 )
{ fprintf(stderr, RED "Error" RST " on " MAG "line %d" RST, lineNumber);
fprintf(stderr, "," MAG " entry %d" RST ":", 5);
fprintf(stderr, RED " '%s'" RST, tokens[4].c_str());
fprintf(stderr, " is not a character.\n");
fprintf(stderr, " Please use " GRN "R" RST ", " GRN "r" RST );
fprintf(stderr, ", " GRN "L" RST ", " GRN "l" RST ", or " GRN "-" RST);
fprintf(stderr, " to specify direction.\n\n");
exit(1); }
if ( tokens[4][0] != 'r' && tokens[4][0] != 'l' && tokens[4][0] != '-')
{ fprintf(stderr, RED "Error" RST " on " MAG "line %d" RST, lineNumber);
fprintf(stderr, "," MAG " entry %d" RST ":", 5);
fprintf(stderr, RED " '%c'" RST " invalid ", tokens[4][0]);
fprintf(stderr, "character for direction.\n");
fprintf(stderr, " Please use " GRN "R" RST ", " GRN "r" RST );
fprintf(stderr, ", " GRN "L" RST ", " GRN "l" RST ", or " GRN "-" RST);
fprintf(stderr, " to specify direction.\n\n");
exit(1); } }
// check that the state has proper size and the direction is correct
void assertState(const int & lineNumber, const int & tokenCount,
std::string tokens[], const int & size)
{ assertStateSize(lineNumber, tokenCount, tokens, size);
assertDirection(lineNumber, tokens); }
// check if states are separated by commas
void assertSeparation(const int & lineNumber,
const int & tokenIndex, const char & ending)
{ if ( ending == ',' )
return;
fprintf(stderr, RED "Error" RST " on " MAG "line %d" RST, lineNumber);
fprintf(stderr, "," MAG " entry %d" RST ":", tokenIndex+1);
fprintf(stderr, " Invalid ending" RED " '%c' " RST "for ", ending);
switch (tokenIndex)
{ case 0:
fprintf(stderr, "current state name."); break;
case 1:
fprintf(stderr, "character to be seen on tape."); break;
case 2:
fprintf(stderr, "next state name."); break;
case 3:
fprintf(stderr, "character to be written on tape."); break;
case 4:
fprintf(stderr, "tape dirrection."); break;
default: break; }
fprintf(stderr, "\n Please use commas " GRN "','" RST "\n\n");
exit(1); }
// used to print state errors
void _statePrint(const int & lineNumber,
const State & state, bool highlight = false)
{ // if line is result set color to magenta
if ( highlight ) fprintf(stderr, MAG);
// print the line number
fprintf(stderr, "%4u", lineNumber + 1);
// if line is result set reset color
if ( highlight ) fprintf(stderr, RST);
// print current state
fprintf(stderr, ": %15s ", state.curState.c_str());
// if line is result set color to magenta
if ( highlight ) fprintf(stderr, MAG);
// print current character using printTable lib
fprintChar(stderr, state.curChar);
// if line is result set reset color
if ( highlight ) fprintf(stderr, RST);
// print arrow
fprintf(stderr, " ---> ");
// print next state name
fprintf(stderr, "%15s ", state.newState.c_str());
// print next character using printTable lib
fprintChar(stderr, state.newChar);
// print direction
fprintf(stderr, " %3c\n", state.direction); }
// prints a character correctly for error
void _charPrint(const char & chr)
{ const int litSize = 4;
std::string strLiterals[litSize] = { "\\n", "\\r", "\\t", "\\0" };
char literals[] = { '\n', '\r', '\t', '\0' };
for (int i = 0; i < litSize; i += 1)
{ if(chr == literals[i])
{ fprintf(stderr, "%s", strLiterals[i].c_str());
return; } }
fprintf(stderr, "%c", chr); }
// check if the state table tried to add a repeated state
void assertStateAddition(const StateTable & stateTable,
const State & state, const int & result,
const int & lineNumber, const std::vector<int> & lineNum)
{ // if instertion is valid, return
if(result == VALID) return;
// print a portion of the table to inform user
int i = ( result < 4 ) ? 0 : result - 4;
while ( i < (signed int) stateTable.size() && i < result + 5)
{ // print current state
_statePrint(lineNum[i], stateTable[i], ( i == result));
i += 1; }
// print ... for spacing
fprintf(stderr, " %*c \n %*c \n %*c \n", 31, '.', 31, '.', 31, '.');
_statePrint(lineNumber, state, true);
fprintf(stderr, "\n");
// print the error message
fprintf(stderr, RED "Error" RST " on " MAG "line %d" RST ":", lineNumber + 1);
fprintf(stderr, " current character to be seen on tape " RED "'");
_charPrint(state.curChar);
fprintf(stderr, "'" RST " duplicates ");
fprintf(stderr, MAG "line %d" RST ".\n\n", lineNum[result] + 1);
exit(1); }
| 41.644068 | 82 | 0.609144 | istvan-vonfedak |
0c5387e3cc3b310ac61a54a682a74767df2ea966 | 4,385 | hpp | C++ | Tools/RegistersGenerator/GD32VF103/timer6registers.hpp | snorkysnark/CortexLib | 0db035332ebdfbebf21ca36e5e04b78a5a908a49 | [
"MIT"
] | 22 | 2019-09-07T22:38:01.000Z | 2022-01-31T21:35:55.000Z | Tools/RegistersGenerator/GD32VF103/timer6registers.hpp | snorkysnark/CortexLib | 0db035332ebdfbebf21ca36e5e04b78a5a908a49 | [
"MIT"
] | null | null | null | Tools/RegistersGenerator/GD32VF103/timer6registers.hpp | snorkysnark/CortexLib | 0db035332ebdfbebf21ca36e5e04b78a5a908a49 | [
"MIT"
] | 9 | 2019-09-22T11:26:24.000Z | 2022-03-21T10:53:15.000Z | /*******************************************************************************
* Filename : timer6registers.hpp
*
* Details : Basic-timers. This header file is auto-generated for GD32VF103
* device.
*
*
*******************************************************************************/
#if !defined(TIMER6REGISTERS_HPP)
#define TIMER6REGISTERS_HPP
#include "timer6fieldvalues.hpp" //for Bits Fields defs
#include "registerbase.hpp" //for RegisterBase
#include "register.hpp" //for Register
#include "accessmode.hpp" //for ReadMode, WriteMode, ReadWriteMode
struct TIMER6
{
struct TIMER6CTL0Base {} ;
struct CTL0 : public RegisterBase<0x40001400, 16, ReadWriteMode>
{
using ARSE = TIMER6_CTL0_ARSE_Values<TIMER6::CTL0, 7, 1, ReadWriteMode, TIMER6CTL0Base> ;
using SPM = TIMER6_CTL0_SPM_Values<TIMER6::CTL0, 3, 1, ReadWriteMode, TIMER6CTL0Base> ;
using UPS = TIMER6_CTL0_UPS_Values<TIMER6::CTL0, 2, 1, ReadWriteMode, TIMER6CTL0Base> ;
using UPDIS = TIMER6_CTL0_UPDIS_Values<TIMER6::CTL0, 1, 1, ReadWriteMode, TIMER6CTL0Base> ;
using CEN = TIMER6_CTL0_CEN_Values<TIMER6::CTL0, 0, 1, ReadWriteMode, TIMER6CTL0Base> ;
using FieldValues = TIMER6_CTL0_CEN_Values<TIMER6::CTL0, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using CTL0Pack = Register<0x40001400, 16, ReadWriteMode, TIMER6CTL0Base, T...> ;
struct TIMER6CTL1Base {} ;
struct CTL1 : public RegisterBase<0x40001404, 16, ReadWriteMode>
{
using MMC = TIMER6_CTL1_MMC_Values<TIMER6::CTL1, 4, 3, ReadWriteMode, TIMER6CTL1Base> ;
using FieldValues = TIMER6_CTL1_MMC_Values<TIMER6::CTL1, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using CTL1Pack = Register<0x40001404, 16, ReadWriteMode, TIMER6CTL1Base, T...> ;
struct TIMER6DMAINTENBase {} ;
struct DMAINTEN : public RegisterBase<0x4000140C, 16, ReadWriteMode>
{
using UPDEN = TIMER6_DMAINTEN_UPDEN_Values<TIMER6::DMAINTEN, 8, 1, ReadWriteMode, TIMER6DMAINTENBase> ;
using UPIE = TIMER6_DMAINTEN_UPIE_Values<TIMER6::DMAINTEN, 0, 1, ReadWriteMode, TIMER6DMAINTENBase> ;
using FieldValues = TIMER6_DMAINTEN_UPIE_Values<TIMER6::DMAINTEN, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using DMAINTENPack = Register<0x4000140C, 16, ReadWriteMode, TIMER6DMAINTENBase, T...> ;
struct TIMER6INTFBase {} ;
struct INTF : public RegisterBase<0x40001410, 16, ReadWriteMode>
{
using UPIF = TIMER6_INTF_UPIF_Values<TIMER6::INTF, 0, 1, ReadWriteMode, TIMER6INTFBase> ;
using FieldValues = TIMER6_INTF_UPIF_Values<TIMER6::INTF, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using INTFPack = Register<0x40001410, 16, ReadWriteMode, TIMER6INTFBase, T...> ;
struct TIMER6SWEVGBase {} ;
struct SWEVG : public RegisterBase<0x40001414, 16, WriteMode>
{
using UPG = TIMER6_SWEVG_UPG_Values<TIMER6::SWEVG, 0, 1, WriteMode, TIMER6SWEVGBase> ;
using FieldValues = TIMER6_SWEVG_UPG_Values<TIMER6::SWEVG, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using SWEVGPack = Register<0x40001414, 16, WriteMode, TIMER6SWEVGBase, T...> ;
struct TIMER6CNTBase {} ;
struct CNT : public RegisterBase<0x40001424, 16, ReadWriteMode>
{
using CNTField = TIMER6_CNT_CNT_Values<TIMER6::CNT, 0, 16, ReadWriteMode, TIMER6CNTBase> ;
using FieldValues = TIMER6_CNT_CNT_Values<TIMER6::CNT, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using CNTPack = Register<0x40001424, 16, ReadWriteMode, TIMER6CNTBase, T...> ;
struct TIMER6PSCBase {} ;
struct PSC : public RegisterBase<0x40001428, 16, ReadWriteMode>
{
using PSCField = TIMER6_PSC_PSC_Values<TIMER6::PSC, 0, 16, ReadWriteMode, TIMER6PSCBase> ;
using FieldValues = TIMER6_PSC_PSC_Values<TIMER6::PSC, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using PSCPack = Register<0x40001428, 16, ReadWriteMode, TIMER6PSCBase, T...> ;
struct TIMER6CARBase {} ;
struct CAR : public RegisterBase<0x4000142C, 16, ReadWriteMode>
{
using CARL = TIMER6_CAR_CARL_Values<TIMER6::CAR, 0, 16, ReadWriteMode, TIMER6CARBase> ;
using FieldValues = TIMER6_CAR_CARL_Values<TIMER6::CAR, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using CARPack = Register<0x4000142C, 16, ReadWriteMode, TIMER6CARBase, T...> ;
} ;
#endif //#if !defined(TIMER6REGISTERS_HPP)
| 37.801724 | 107 | 0.692132 | snorkysnark |
0c55e9e51ffaac383d022c1369ed85c421e1fac6 | 1,049 | cpp | C++ | C++/InfoArena/Arhiva probleme/Proc2/proc2.cpp | Nicu-Ducal/Competitive-Programming | c84126a4cb701b0764664db490b7e594495c8592 | [
"MIT"
] | null | null | null | C++/InfoArena/Arhiva probleme/Proc2/proc2.cpp | Nicu-Ducal/Competitive-Programming | c84126a4cb701b0764664db490b7e594495c8592 | [
"MIT"
] | null | null | null | C++/InfoArena/Arhiva probleme/Proc2/proc2.cpp | Nicu-Ducal/Competitive-Programming | c84126a4cb701b0764664db490b7e594495c8592 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define debug(x) cerr << #x << " = " << x << "\n"
#define all(x) (x).begin(),(x).end()
#define len length()
#define sz size()
#define pb push_back
#define fi first
#define se second
#define pii pair<int,int>
#define pll pair<ll,ll>
using ull = unsigned long long;
using ll = long long;
using namespace std;
const int MAXN = 1e6 + 5;
const int INF = INT_MAX;
ll t, n, m, st, timp;
priority_queue<ll, vector<ll>, greater<ll>> disp;
priority_queue<pll, vector<pll>, greater<pll>> task;
int main(){
ios_base::sync_with_stdio(0); cin.tie(); cout.tie();
ifstream cin("proc2.in");
ofstream cout("proc2.out");
cin >> n >> m;
for (ll i = 1; i <= n; i++){
disp.push(i);
}
for (ll i = 1; i <= m; i++){
cin >> st >> timp;
while(!task.empty() and task.top().fi <= st){
disp.push(task.top().se);
task.pop();
}
cout << disp.top() << "\n";
task.emplace(st + timp, disp.top());
disp.pop();
}
return 0;
}
| 23.840909 | 56 | 0.540515 | Nicu-Ducal |
0c59ba46535808e6bd217c32f0bb21881cff3fe2 | 1,397 | cpp | C++ | 28. Codechef Problems/CodeChef/CCSTART2/CodeChef_Is Both Or Not_Solved.cpp | Ujjawalgupta42/Hacktoberfest2021-DSA | eccd9352055085973e3d6a1feb10dd193905584b | [
"MIT"
] | 225 | 2021-10-01T03:09:01.000Z | 2022-03-11T11:32:49.000Z | 28. Codechef Problems/CodeChef/CCSTART2/CodeChef_Is Both Or Not_Solved.cpp | Ujjawalgupta42/Hacktoberfest2021-DSA | eccd9352055085973e3d6a1feb10dd193905584b | [
"MIT"
] | 252 | 2021-10-01T03:45:20.000Z | 2021-12-07T18:32:46.000Z | 28. Codechef Problems/CodeChef/CCSTART2/CodeChef_Is Both Or Not_Solved.cpp | Ujjawalgupta42/Hacktoberfest2021-DSA | eccd9352055085973e3d6a1feb10dd193905584b | [
"MIT"
] | 911 | 2021-10-01T02:55:19.000Z | 2022-02-06T09:08:37.000Z | /* -------------------------------------------------------------------------- */
/* Is Both Or Not Problem Code: ISBOTH */
/* -------------------------------------------------------------------------- */
/**You're given a number N. If N is divisible by 5 or 11 but not both then print "ONE"(without quotes).
* If N is divisible by both 5 and 11 then print "BOTH"(without quotes).
* If N is not divisible by 5 or 11 then print "NONE"(without quotes).
*/
/*
Input:
First-line will contain the number N.
Output:
Print the answer in a newline.
Constraints
1≤N≤103
Sample Input 1:
50
Sample Output 1:
ONE
Sample Input 2:
110
Sample Output 2:
BOTH
Sample Input 2:
16
Sample Output 2:
NONE
EXPLANATION:
In the first example, 50 is divisible by 5, but not 11.
In the second example, 110 is divisible by both 5 and 11.
In the third example, 16 is not divisible by 5 or 11.
*/
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
if (N % 5 == 0 && N % 11 == 0)
cout << "BOTH";
else if (N % 5 == 0 || N % 11 == 0)
cout << "ONE";
else if (N % 5 != 0 || N % 11 != 0)
cout << "NONE";
return 0;
} | 24.086207 | 105 | 0.448103 | Ujjawalgupta42 |
0c5e0e1cdf9b55d1890f9b0dd80b2c34c550d4e7 | 4,139 | cpp | C++ | src-qt5/gui_client/NewConnectionWizard.cpp | yamajun/sysadm-ui-qt | e472d2ead74b3ea1774ae53ba486becc2fd0ba8c | [
"BSD-2-Clause"
] | null | null | null | src-qt5/gui_client/NewConnectionWizard.cpp | yamajun/sysadm-ui-qt | e472d2ead74b3ea1774ae53ba486becc2fd0ba8c | [
"BSD-2-Clause"
] | null | null | null | src-qt5/gui_client/NewConnectionWizard.cpp | yamajun/sysadm-ui-qt | e472d2ead74b3ea1774ae53ba486becc2fd0ba8c | [
"BSD-2-Clause"
] | null | null | null | //===========================================
// PC-BSD source code
// Copyright (c) 2016, PC-BSD Software/iXsystems
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "NewConnectionWizard.h"
#include "ui_NewConnectionWizard.h"
NewConnectionWizard::NewConnectionWizard(QWidget *parent, QString nickname) : QDialog(parent), ui(new Ui::NewConnectionWizard){
ui->setupUi(this);
nick = nickname;
core = new sysadm_client();
success = false;
ui->push_finished->setVisible(false);
ui->label_results->setVisible(false);
//Setup connections
connect(core, SIGNAL(clientConnected()), this, SLOT(coreConnected()) );
connect(core, SIGNAL(clientDisconnected()), this, SLOT(coreDisconnected()) );
connect(core, SIGNAL(clientAuthorized()), this, SLOT(coreAuthenticated()) );
//Line edit connections
connect(ui->line_host, SIGNAL(textEdited(const QString&)), this, SLOT(checkInputs()) );
connect(ui->line_user, SIGNAL(textEdited(const QString&)), this, SLOT(checkInputs()) );
connect(ui->line_pass, SIGNAL(textEdited(const QString&)), this, SLOT(checkInputs()) );
connect(ui->radio_server, SIGNAL(toggled(bool)), this, SLOT(checkInputs()) );
}
NewConnectionWizard::~NewConnectionWizard(){
}
void NewConnectionWizard::LoadPrevious(QString host, QString user){
ui->line_host->setText(host);
ui->line_host->setEnabled(false); //when loading a previous connection - don't allow changing the host
ui->line_user->setText(user);
}
// === PRIVATE SLOTS ===
void NewConnectionWizard::checkInputs(){
bool typeok = !ui->radio_server->isChecked();
ui->line_user->setVisible(!typeok);
ui->line_pass->setVisible(!typeok);
ui->label_user->setVisible(!typeok);
ui->label_pass->setVisible(!typeok);
if(!typeok){ typeok = (!ui->line_user->text().isEmpty() && !ui->line_pass->text().isEmpty()); }
ui->push_start_test->setEnabled( !ui->line_host->text().isEmpty() && typeok );
}
//core signals/slots
void NewConnectionWizard::coreConnected(){
ui->label_results->setText( tr("Host Valid") );
qDebug() << "CoreConnected:" << host;
}
void NewConnectionWizard::coreAuthenticated(){
ui->label_results->setText( tr("Test Successful") );
ui->label_results->setVisible(true);
ui->push_cancel->setVisible(false);
ui->push_finished->setVisible(true);
//Now do any post-auth first-time setup
success = true;
host = core->currentHost();
//Save the good info to the settings file
settings->setValue("Hosts/"+host, nick); //save the nickname
settings->setValue("Hosts/"+host+"/username", ui->line_user->text());
qDebug() << "CoreAuthenticated:" << host << nick;
//Clean up any core interactions (but leave it running for later)
disconnect(core, 0, this, 0);
}
void NewConnectionWizard::coreDisconnected(){
//Test was a failure - leave the results label visible so the user can see how far it got
qDebug() << "CoreDisconnected:" << host << nick;
ui->group_host->setEnabled(true);
ui->label_results->setVisible(true);
ui->push_cancel->setVisible(true);
ui->push_finished->setVisible(false);
}
//Buttons
void NewConnectionWizard::on_push_start_test_clicked(){
ui->group_host->setEnabled(false); //de-activate for the moment
ui->label_results->setText( tr("Host Invalid") );
if(ui->radio_server->isChecked()){
core->openConnection(ui->line_user->text(), ui->line_pass->text(), ui->line_host->text());
}else{
//SSL Auth only - keys need to have already been imported onto the server
//Verify that the port is specified for a bridge - otherwise use the default
bool hasport = false;
QString url = ui->line_host->text();
url.section(":",-1).toInt(&hasport); //check if the last piece of the url is a valid number
//Could add a check for a valid port number as well - but that is a bit overkill right now
if(!hasport){ url.append(":12149"); }
//Now start the connection
core->openConnection(url);
}
}
void NewConnectionWizard::on_push_finished_clicked(){
this->close();
}
void NewConnectionWizard::on_push_cancel_clicked(){
this->close();
}
| 38.682243 | 127 | 0.695095 | yamajun |
0c5e3aa49b9a7c1215e16b15156836dbc2b0291e | 2,547 | tpp | C++ | util/vecs.tpp | Mogami95/GMiner | d80c0fbad2f860d8cf1585440b57a2637993fb42 | [
"Apache-2.0"
] | 64 | 2018-05-15T01:57:55.000Z | 2021-12-14T01:49:18.000Z | util/vecs.tpp | Mogami95/GMiner | d80c0fbad2f860d8cf1585440b57a2637993fb42 | [
"Apache-2.0"
] | 3 | 2019-11-28T12:10:09.000Z | 2021-11-03T15:16:06.000Z | util/vecs.tpp | Mogami95/GMiner | d80c0fbad2f860d8cf1585440b57a2637993fb42 | [
"Apache-2.0"
] | 24 | 2018-05-15T01:57:22.000Z | 2021-11-24T14:09:14.000Z | //Copyright 2018 Husky Data Lab, CUHK
//Authors: Hongzhi Chen, Miao Liu
template <class KeyT, class MessageT>
MsgPair<KeyT, MessageT>::MsgPair()
{
}
template <class KeyT, class MessageT>
MsgPair<KeyT, MessageT>::MsgPair(KeyT v1, MessageT v2)
{
key = v1;
msg = v2;
}
template <class KeyT, class MessageT>
inline bool MsgPair<KeyT, MessageT>::operator < (const MsgPair<KeyT, MessageT>& rhs) const
{
return key < rhs.key;
}
template <class KeyT, class MessageT>
ibinstream& operator<<(ibinstream& m, const MsgPair<KeyT, MessageT>& v)
{
m << v.key;
m << v.msg;
return m;
}
template <class KeyT, class MessageT>
obinstream& operator>>(obinstream& m, MsgPair<KeyT, MessageT>& v)
{
m >> v.key;
m >> v.msg;
return m;
}
//===============================================
template <class KeyT, class MessageT, class HashT>
Vecs<KeyT, MessageT, HashT>::Vecs()
{
np_ = _num_workers;
vecs_.resize(_num_workers);
}
template <class KeyT, class MessageT, class HashT>
void Vecs<KeyT, MessageT, HashT>::append(const KeyT key, const MessageT msg)
{
MsgPair<KeyT, MessageT> item(key, msg);
vecs_[hash_(key)].push_back(item);
}
template <class KeyT, class MessageT, class HashT>
typename Vecs<KeyT, MessageT, HashT>::Vec& Vecs<KeyT, MessageT, HashT>::get_buf(int pos)
{
return vecs_[pos];
}
template <class KeyT, class MessageT, class HashT>
typename Vecs<KeyT, MessageT, HashT>::VecGroup& Vecs<KeyT, MessageT, HashT>::get_bufs()
{
return vecs_;
}
template <class KeyT, class MessageT, class HashT>
void Vecs<KeyT, MessageT, HashT>::clear()
{
for (int i = 0; i < np_; i++)
{
vecs_[i].clear();
}
}
//============================
//apply combiner logic
template <class KeyT, class MessageT, class HashT>
void Vecs<KeyT, MessageT, HashT>::combine()
{
Combiner<MessageT>* combiner = (Combiner<MessageT>*)get_combiner();
for (int i = 0; i < np_; i++)
{
sort(vecs_[i].begin(), vecs_[i].end());
Vec new_vec;
int size = vecs_[i].size();
if (size > 0)
{
new_vec.push_back(vecs_[i][0]);
KeyT preKey = vecs_[i][0].key;
for (int j = 1; j < size; j++)
{
MsgPair<KeyT, MessageT>& cur = vecs_[i][j];
if (cur.key != preKey)
{
new_vec.push_back(cur);
preKey = cur.key;
}
else
{
combiner->combine(new_vec.back().msg, cur.msg);
}
}
}
new_vec.swap(vecs_[i]);
}
}
template <class KeyT, class MessageT, class HashT>
long long Vecs<KeyT, MessageT, HashT>::get_total_msg()
{
long long sum = 0;
for (int i = 0; i < vecs_.size(); i++)
{
sum += vecs_[i].size();
}
return sum;
}
| 21.403361 | 90 | 0.638398 | Mogami95 |
0c5f4788784a52924e4bb52b314a86844da55221 | 4,448 | cpp | C++ | src/trashboy3k.cpp | nlang/tb3k | 6e19b47147081f2a68443e5b29861faee67dbe09 | [
"MIT"
] | null | null | null | src/trashboy3k.cpp | nlang/tb3k | 6e19b47147081f2a68443e5b29861faee67dbe09 | [
"MIT"
] | null | null | null | src/trashboy3k.cpp | nlang/tb3k | 6e19b47147081f2a68443e5b29861faee67dbe09 | [
"MIT"
] | null | null | null | #include "trashboy3k.h"
#define FLASH_LED_PIN 10
#define SPEAKER_PIN 9
#define OLED_DISPLAY_TYPE &SH1106_128x64
#define OLED_I2C_ADDRESS 0x3C // I2C address of OLED display
#define EEPROM_DATE_AREA_START 512
#define MAX_NUMBER_OF_DATES_IN_MEMORY 10
#define ACK_TRASHOUT_DATE_INTERRUPT_PIN 3
#define ACK_TRASHOUT_DATE_INTERRUPT_ID 1
#define BTLE_POWER_PIN 6
#define BTLE_SERIAL_RX_PIN 7
#define BTLE_SERIAL_TX_PIN 8
// TODO put into EEPROM as config
#define ALARM_ENABLED_FROM_HOUR 10
#define ALARM_ENABLED_TO_HOUR 22
DataStore dataStore = DataStore(EEPROM_DATE_AREA_START);
Display display = Display(OLED_DISPLAY_TYPE, OLED_I2C_ADDRESS);
SoftwareSerial btSerial(BTLE_SERIAL_RX_PIN, BTLE_SERIAL_TX_PIN);
int numberOfChannels = 0;
char channelNames[5][22];
int numberOfDates = 0;
TrashOutDate dates[MAX_NUMBER_OF_DATES_IN_MEMORY];
BLECommunication ble(&btSerial, &dataStore);
volatile unsigned long debounceLastAckBtnAction = 0;
volatile bool performAck = false;
volatile bool performingAck = false;
long lastAlaramMillis = 0;
bool lockMidnight = false;
void setup() {
Now::init();
Serial.begin(9600);
pinMode(BTLE_POWER_PIN, OUTPUT);
digitalWrite(BTLE_POWER_PIN, LOW);
pinMode(ACK_TRASHOUT_DATE_INTERRUPT_PIN, INPUT);
attachInterrupt(ACK_TRASHOUT_DATE_INTERRUPT_ID, ackButtonInterruptTriggered, RISING); // interrupt for ack button
char lines[][22] = {
"Hello!",
"I'm TrashBoy 3000",
"Happy birthday!",
};
if (isDanisBirthday()) {
display.showIntro(lines, 3);
SoundEffects::playHappyBirthday(SPEAKER_PIN);
} else {
display.showIntro(lines, 2);
delay(2000);
}
// TODO do something on first run?
// h min sec day mon y
//Now::setDateTime(23, 59, 40, 8, 8, 18);
//dataStore.eepromWrite();
numberOfChannels = dataStore.readChannelNames(channelNames);
numberOfDates = dataStore.readDates(dates, MAX_NUMBER_OF_DATES_IN_MEMORY);
ble.setCurrentList(&dates[0], numberOfDates);
// enable BTLE
digitalWrite(BTLE_POWER_PIN, HIGH);
ble.start();
}
void loop() {
ble.readDataIfAvailable();
if (true == performAck) {
performingAck = true;
performAck = false;
doPerformAck();
performingAck = false;
}
if (Now::isMidnight() && !lockMidnight) {
lockMidnight = true;
int numberOfAckDates = 0;
TrashOutDate ackDates[MAX_NUMBER_OF_DATES_IN_MEMORY];
for (int i = 0; i < numberOfDates; i++) {
TrashOutDate *date = dates + i;
if (date->isAck()) {
memcpy(&ackDates[i], date, sizeof(TrashOutDate));
numberOfAckDates++;
}
}
numberOfDates = dataStore.readDates(dates, MAX_NUMBER_OF_DATES_IN_MEMORY);
for (int i = 0; i < numberOfDates; i++) {
TrashOutDate *date = dates + i;
for (int j = 0; j < numberOfAckDates; j++) {
TrashOutDate *ackDate = ackDates + j;
if (date->isSameDate(ackDate)) {
date->ack();
break;
}
}
}
}
if (!Now::isMidnight() && lockMidnight) {
lockMidnight = false;
}
display.drawDateTimeLine();
if (hasActiveDate() && millis() - lastAlaramMillis > 2000) {
display.drawNextDates(dates, numberOfDates, channelNames, numberOfChannels, true);
digitalWrite(FLASH_LED_PIN, HIGH);
if (Now::getHour() >= ALARM_ENABLED_FROM_HOUR && Now::getHour() < ALARM_ENABLED_TO_HOUR) {
SoundEffects::playAlarmSignal(SPEAKER_PIN);
} else {
delay(60);
}
delay(140);
digitalWrite(FLASH_LED_PIN, LOW);
lastAlaramMillis = millis();
} else {
display.drawNextDates(dates, numberOfDates, channelNames, numberOfChannels, false);
}
}
bool isDanisBirthday(void) {
if (24 >= Now::getDay() && 8 == Now::getMonth() && 18 == Now::getYear2kBased()) {
return true;
}
return false;
}
bool hasActiveDate(void) {
for (int i = 0; i < numberOfDates; i++) {
TrashOutDate *date = dates + i;
if (!date->isAck() && (Now::isToday(date) || Now::isTomorrow(date))) {
return true;
}
}
return false;
}
void ackButtonInterruptTriggered() {
if ((millis() - debounceLastAckBtnAction) > 500) {
debounceLastAckBtnAction = millis();
if (!performingAck) {
performAck = true;
}
}
}
void doPerformAck(void) {
for (int i = 0; i < numberOfDates; i++) {
TrashOutDate *date = dates + i;
if (!date->isAck() && (Now::isToday(date) || Now::isTomorrow(date))) {
date->ack();
return;
}
}
SoundEffects::playErrorTone(SPEAKER_PIN);
}
| 26.634731 | 115 | 0.682554 | nlang |
0c5f7371a6b527095e8d56194ab87a6669ddf256 | 9,057 | cpp | C++ | examples/qmag/qmag.cpp | sandsmark/qt1 | e62eef42291be80065a7f824530aa42b79917a8d | [
"Xnet",
"X11"
] | 18 | 2018-02-16T16:57:26.000Z | 2022-02-10T21:23:47.000Z | examples/qmag/qmag.cpp | sandsmark/qt1 | e62eef42291be80065a7f824530aa42b79917a8d | [
"Xnet",
"X11"
] | 2 | 2018-08-12T12:46:38.000Z | 2020-06-19T16:30:06.000Z | examples/qmag/qmag.cpp | sandsmark/qt1 | e62eef42291be80065a7f824530aa42b79917a8d | [
"Xnet",
"X11"
] | 7 | 2018-06-22T01:17:58.000Z | 2021-09-02T21:05:28.000Z | /****************************************************************************
** $Id: qmag.cpp,v 2.16 1998/06/16 11:39:34 warwick Exp $
**
** Copyright (C) 1992-1998 Troll Tech AS. All rights reserved.
**
** This file is part of an example program for Qt. This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/
#include <qcombobox.h>
#include <qpushbutton.h>
#include <qpixmap.h>
#include <qimage.h>
#include <qlabel.h>
#include <qfiledialog.h>
#include <qregexp.h>
#include <qapplication.h>
#include <qpainter.h>
#include <qwmatrix.h>
class MagWidget : public QWidget
{
Q_OBJECT
public:
MagWidget( QWidget *parent=0, const char *name=0 );
public slots:
void setZoom( int );
void setRefresh( int );
void save();
void multiSave();
protected:
void paintEvent( QPaintEvent * );
void mousePressEvent( QMouseEvent * );
void mouseReleaseEvent( QMouseEvent * );
void mouseMoveEvent( QMouseEvent * );
void focusOutEvent( QFocusEvent * );
void timerEvent( QTimerEvent * );
void resizeEvent( QResizeEvent * );
private:
void grab();
QComboBox *zoom;
QComboBox *refresh;
QPushButton *saveButton;
QPushButton *multiSaveButton;
QPushButton *quitButton;
QPixmap pm; // pixmap, magnified
QPixmap p; // pixmap
QImage image; // image of pixmap (for RGB)
QLabel *rgb;
int yoffset; // pixels in addition to the actual picture
int z; // magnification factor
int r; // autorefresh rate (index into refreshrates)
bool grabbing; // true if qmag is currently grabbing
int grabx, graby;
QString multifn; // filename for multisave
};
static const char *zoomfactors[] = {
"100%", "200%", "300%", "400%", "500%",
"600%", "700%", "800%", "1600%", 0 };
static const char *refreshrates[] = {
"No autorefresh", "4 per second", "3 per second", "2 per second",
"Every second", "Every two seconds", "Every three seconds",
"Every five seconds", "Every ten seconds", 0 };
static const int timer[] = {
0, 250, 333, 500, 1000, 2000, 3000, 5000, 10000 };
MagWidget::MagWidget( QWidget *parent, const char *name )
: QWidget( parent, name)
{
zoom = new QComboBox( FALSE, this );
CHECK_PTR(zoom);
zoom->insertStrList( zoomfactors, 9 );
connect( zoom, SIGNAL(activated(int)), SLOT(setZoom(int)) );
refresh = new QComboBox( FALSE, this );
CHECK_PTR(refresh);
refresh->insertStrList( refreshrates, 9 );
connect( refresh, SIGNAL(activated(int)), SLOT(setRefresh(int)) );
int w, x, n;
w = 0;
for( n=0; n<9; n++) {
int w2 = zoom->fontMetrics().width( zoomfactors[n] );
w = QMAX(w2, w);
}
zoom->setGeometry( 2, 2, w+30, 20 );
x = w+34;
w = 0;
for( n=0; n<9; n++) {
int w2 = refresh->fontMetrics().width( refreshrates[n] );
w = QMAX(w2, w);
}
refresh->setGeometry( x, 2, w+30, 20 );
saveButton = new QPushButton( this );
CHECK_PTR(saveButton);
connect( saveButton, SIGNAL(clicked()), this, SLOT(save()) );
saveButton->setText( "Save" );
saveButton->setGeometry( x+w+30+2, 2,
10+saveButton->fontMetrics().width("Save"), 20 );
multiSaveButton = new QPushButton( this );
multiSaveButton->setToggleButton(TRUE);
CHECK_PTR(multiSaveButton);
connect( multiSaveButton, SIGNAL(clicked()), this, SLOT(multiSave()) );
multiSaveButton->setText( "MultiSave" );
multiSaveButton->setGeometry( saveButton->geometry().right() + 2, 2,
10+multiSaveButton->fontMetrics().width("MultiSave"), 20 );
quitButton = new QPushButton( this );
CHECK_PTR(quitButton);
connect( quitButton, SIGNAL(clicked()), qApp, SLOT(quit()) );
quitButton->setText( "Quit" );
quitButton->setGeometry( multiSaveButton->geometry().right() + 2, 2,
10+quitButton->fontMetrics().width("Quit"), 20 );
rgb = new QLabel( this );
CHECK_PTR( rgb );
rgb->setText( "" );
rgb->setAlignment( AlignVCenter );
rgb->resize( width(), rgb->fontMetrics().height() + 4 );
yoffset = zoom->height() // top buttons
+ 4 // space around top buttons
+ rgb->height(); // color-value text height
z = 1; // default zoom (100%)
r = 0; // default refresh (none)
grabx = graby = -1;
grabbing = FALSE;
setMinimumSize( quitButton->pos().x(), yoffset+20 );
resize( quitButton->geometry().topRight().x() + 2, yoffset+60 );
setMouseTracking( TRUE ); // and do let me know what pixel I'm at, eh?
}
void MagWidget::setZoom( int index )
{
if (index == 8)
z = 16;
else
z = index+1;
grab();
}
void MagWidget::setRefresh( int index )
{
r = index;
killTimers();
if (index && !grabbing)
startTimer( timer[r] );
}
void MagWidget::save()
{
if ( !p.isNull() ) {
killTimers();
QString fn = QFileDialog::getSaveFileName();
if ( !fn.isEmpty() )
p.save( fn, "BMP" );
if ( r )
startTimer( timer[r] );
}
}
void MagWidget::multiSave()
{
if ( !p.isNull() ) {
multifn = ""; // stops saving
multifn = QFileDialog::getSaveFileName();
if ( multifn.isEmpty() )
multiSaveButton->setOn(FALSE);
if ( !r )
p.save( multifn, "BMP" );
} else {
multiSaveButton->setOn(FALSE);
}
}
void MagWidget::grab()
{
if ( !isVisible() )
return; // don't eat resources when iconified
if ( grabx < 0 || graby < 0 )
return; // don't grab until the user has said to
int x,y, w,h;
w = (width()+z-1)/z;
h = (height()+z-1-yoffset)/z;
if ( w<1 || h<1 )
return; // don't ask too much from the window system :)
x = grabx-w/2; // find a suitable position to grab from
y = graby-h/2;
if ( x + w > QApplication::desktop()->width() )
x = QApplication::desktop()->width()-w;
else if ( x < 0 )
x = 0;
if ( y + h > QApplication::desktop()->height() )
y = QApplication::desktop()->height()-h;
else if ( y < 0 )
y = 0;
p = QPixmap::grabWindow( QApplication::desktop()->winId(), x, y, w, h );
image = p.convertToImage();
QWMatrix m; // after getting it, scale it
m.scale( (double)z, (double)z );
pm = p.xForm( m );
if ( !multiSaveButton->isOn() )
repaint( FALSE ); // and finally repaint, flicker-free
}
void MagWidget::paintEvent( QPaintEvent * )
{
if ( !pm.isNull() ) {
QPainter paint( this );
paint.drawPixmap( 0, zoom->height()+4, pm,
0,0, width(), height()-yoffset );
}
}
void MagWidget::mousePressEvent( QMouseEvent *e )
{
if ( !grabbing ) { // prepare to grab...
grabbing = TRUE;
killTimers();
grabMouse( crossCursor );
grabx = -1;
graby = -1;
} else { // REALLY prepare to grab
grabx = mapToGlobal(e->pos()).x();
graby = mapToGlobal(e->pos()).y();
}
}
void MagWidget::mouseReleaseEvent( QMouseEvent * e )
{
if ( grabbing && grabx >= 0 && graby >= 0 ) {
grabbing = FALSE;
int rx, ry;
rx = mapToGlobal(e->pos()).x();
ry = mapToGlobal(e->pos()).y();
int w = QABS(rx-grabx);
int h = QABS(ry-graby);
if ( w > 10 && h > 10 ) {
int pz;
pz = 1;
while ( w*pz*h*pz < width()*(height()-yoffset) &&
w*pz < QApplication::desktop()->width() &&
h*pz < QApplication::desktop()->height() )
pz++;
if ( (w*pz*h*pz - width()*(height()-yoffset)) >
(width()*(height()-yoffset) - w*(pz-1)*h*(pz-1)) )
pz--;
if ( pz < 1 )
pz = 1;
if ( pz > 8 )
pz = 8;
zoom->setCurrentItem( pz-1 );
z = pz;
grabx = QMIN(rx, grabx) + w/2;
graby = QMIN(ry, graby) + h/2;
resize( w*z, h*z+yoffset );
}
releaseMouse();
grab();
if ( r )
startTimer( timer[r] );
}
}
void MagWidget::mouseMoveEvent( QMouseEvent *e )
{
if ( grabbing || pm.isNull() ||
e->pos().y() > height() - zoom->fontMetrics().height() - 4 ||
e->pos().y() < zoom->height()+4 ) {
rgb->setText( "" );
} else {
int x,y;
x = e->pos().x() / z;
y = (e->pos().y() - zoom->height() - 4) / z;
QString pixelinfo;
if ( image.valid(x,y) )
{
QRgb px = image.pixel(x,y);
pixelinfo.sprintf(" %3d,%3d,%3d #%02x%02x%02x",
qRed(px), qGreen(px), qBlue(px),
qRed(px), qGreen(px), qBlue(px));
}
QString label;
label.sprintf( "x=%d, y=%d %s",
x+grabx, y+graby, (const char*)pixelinfo );
rgb->setText( label );
}
}
void MagWidget::focusOutEvent( QFocusEvent * )
{
rgb->setText( "" );
}
void MagWidget::timerEvent( QTimerEvent * )
{
grab();
if ( multiSaveButton->isOn() && !multifn.isEmpty() ) {
QRegExp num("[0-9][0-9]*");
int start;
int len;
if ((start=num.match(multifn,0,&len))>=0)
multifn.replace(num,
QString().setNum(multifn.mid(start,len).toInt()+1)
);
p.save( multifn, "BMP" );
}
}
void MagWidget::resizeEvent( QResizeEvent * )
{
rgb->setGeometry( 0, height() - rgb->height(), width(), rgb->height() );
grab();
}
#include "qmag.moc"
int main( int argc, char **argv )
{
QApplication a( argc, argv );
MagWidget m;
a.setMainWidget( &m );
m.show();
return a.exec();
}
| 24.813699 | 78 | 0.581208 | sandsmark |
0c62eea35cd74d38e66ae17fb6b3666ce849f624 | 8,085 | cpp | C++ | component/oai-smf/src/api-server/impl/IndividualSMContextApiImpl.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-smf/src/api-server/impl/IndividualSMContextApiImpl.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-smf/src/api-server/impl/IndividualSMContextApiImpl.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | /**
* Nsmf_PDUSession
* SMF PDU Session Service. © 2019, 3GPP Organizational Partners (ARIB, ATIS,
* CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved.
*
* The version of the OpenAPI document: 1.1.0.alpha-1
*
*
* NOTE: This class is auto generated by OpenAPI Generator
* (https://openapi-generator.tech). https://openapi-generator.tech Do not edit
* the class manually.
*/
/*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698
*
* 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.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* contact@openairinterface.org
*/
#include "IndividualSMContextApiImpl.h"
#include <nghttp2/asio_http2_server.h>
#include "mime_parser.hpp"
#include "3gpp_conversions.hpp"
namespace oai {
namespace smf_server {
namespace api {
using namespace oai::smf_server::model;
IndividualSMContextApiImpl::IndividualSMContextApiImpl(
std::shared_ptr<Pistache::Rest::Router> rtr, smf::smf_app* smf_app_inst,
std::string address)
: IndividualSMContextApi(rtr),
m_smf_app(smf_app_inst),
m_address(address) {}
void IndividualSMContextApiImpl::release_sm_context(
const std::string& smContextRef,
const SmContextReleaseMessage& smContextReleaseMessage,
Pistache::Http::ResponseWriter& response) {
// Get the SmContextReleaseData from this message and process in smf_app
Logger::smf_api_server().info(
"Received a PDUSession_ReleaseSMContext Request from AMF.");
smf::pdu_session_release_sm_context_request sm_context_req_msg = {};
// convert from SmContextReleaseMessage to
// pdu_session_release_sm_context_request
xgpp_conv::sm_context_release_from_openapi(
smContextReleaseMessage, sm_context_req_msg);
boost::shared_ptr<
boost::promise<smf::pdu_session_release_sm_context_response> >
p = boost::make_shared<
boost::promise<smf::pdu_session_release_sm_context_response> >();
boost::shared_future<smf::pdu_session_release_sm_context_response> f;
f = p->get_future();
// Generate ID for this promise (to be used in SMF-APP)
uint32_t promise_id = generate_promise_id();
Logger::smf_api_server().debug("Promise ID generated %d", promise_id);
m_smf_app->add_promise(promise_id, p);
// Handle the itti_n11_release_sm_context_request message in smf_app
std::shared_ptr<itti_n11_release_sm_context_request> itti_msg =
std::make_shared<itti_n11_release_sm_context_request>(
TASK_SMF_SBI, TASK_SMF_APP, promise_id, smContextRef);
itti_msg->req = sm_context_req_msg;
itti_msg->http_version = 1;
m_smf_app->handle_pdu_session_release_sm_context_request(itti_msg);
// Wait for the result from APP and send reply to AMF
smf::pdu_session_release_sm_context_response sm_context_response = f.get();
Logger::smf_api_server().debug("Got result for promise ID %d", promise_id);
// TODO: Process the response
response.send(Pistache::Http::Code(sm_context_response.get_http_code()));
}
void IndividualSMContextApiImpl::retrieve_sm_context(
const std::string& smContextRef,
const SmContextRetrieveData& smContextRetrieveData,
Pistache::Http::ResponseWriter& response) {
Logger::smf_api_server().info("retrieve_sm_context...");
response.send(
Pistache::Http::Code::Not_Implemented,
"Retrieve_sm_context API has not been implemented yet!\n");
}
void IndividualSMContextApiImpl::update_sm_context(
const std::string& smContextRef,
const SmContextUpdateMessage& smContextUpdateMessage,
Pistache::Http::ResponseWriter& response) {
// Get the SmContextUpdateData from this message and process in smf_app
Logger::smf_api_server().info(
"Received a PDUSession_UpdateSMContext Request from AMF.");
smf::pdu_session_update_sm_context_request sm_context_req_msg = {};
// convert from SmContextUpdateMessage to
// pdu_session_update_sm_context_request
xgpp_conv::sm_context_update_from_openapi(
smContextUpdateMessage, sm_context_req_msg);
boost::shared_ptr<
boost::promise<smf::pdu_session_update_sm_context_response> >
p = boost::make_shared<
boost::promise<smf::pdu_session_update_sm_context_response> >();
boost::shared_future<smf::pdu_session_update_sm_context_response> f;
f = p->get_future();
// Generate ID for this promise (to be used in SMF-APP)
uint32_t promise_id = generate_promise_id();
Logger::smf_api_server().debug("Promise ID generated %d", promise_id);
m_smf_app->add_promise(promise_id, p);
// Handle the itti_n11_update_sm_context_request message in smf_app
std::shared_ptr<itti_n11_update_sm_context_request> itti_msg =
std::make_shared<itti_n11_update_sm_context_request>(
TASK_SMF_SBI, TASK_SMF_APP, promise_id, smContextRef);
itti_msg->req = sm_context_req_msg;
itti_msg->http_version = 1;
m_smf_app->handle_pdu_session_update_sm_context_request(itti_msg);
// Wait for the result from APP and send reply to AMF
smf::pdu_session_update_sm_context_response sm_context_response = f.get();
Logger::smf_api_server().debug("Got result for promise ID %d", promise_id);
nlohmann::json json_data = {};
std::string body = {};
std::string json_format;
sm_context_response.get_json_format(json_format);
sm_context_response.get_json_data(json_data);
Logger::smf_api_server().debug("Json data %s", json_data.dump().c_str());
if (sm_context_response.n1_sm_msg_is_set() and
sm_context_response.n2_sm_info_is_set()) {
mime_parser::create_multipart_related_content(
body, json_data.dump(), CURL_MIME_BOUNDARY,
sm_context_response.get_n1_sm_message(),
sm_context_response.get_n2_sm_information(), json_format);
response.headers().add<Pistache::Http::Header::ContentType>(
Pistache::Http::Mime::MediaType(
"multipart/related; boundary=" + std::string(CURL_MIME_BOUNDARY)));
} else if (sm_context_response.n1_sm_msg_is_set()) {
mime_parser::create_multipart_related_content(
body, json_data.dump(), CURL_MIME_BOUNDARY,
sm_context_response.get_n1_sm_message(),
multipart_related_content_part_e::NAS, json_format);
response.headers().add<Pistache::Http::Header::ContentType>(
Pistache::Http::Mime::MediaType(
"multipart/related; boundary=" + std::string(CURL_MIME_BOUNDARY)));
} else if (sm_context_response.n2_sm_info_is_set()) {
mime_parser::create_multipart_related_content(
body, json_data.dump(), CURL_MIME_BOUNDARY,
sm_context_response.get_n2_sm_information(),
multipart_related_content_part_e::NGAP, json_format);
response.headers().add<Pistache::Http::Header::ContentType>(
Pistache::Http::Mime::MediaType(
"multipart/related; boundary=" + std::string(CURL_MIME_BOUNDARY)));
} else if (json_data.size() > 0) {
response.headers().add<Pistache::Http::Header::ContentType>(
Pistache::Http::Mime::MediaType(json_format));
body = json_data.dump().c_str();
} else {
response.send(Pistache::Http::Code(sm_context_response.get_http_code()));
return;
}
response.send(
Pistache::Http::Code(sm_context_response.get_http_code()), body);
}
} // namespace api
} // namespace smf_server
} // namespace oai
| 41.891192 | 81 | 0.739518 | kukkalli |
0c643b724e962346eda2ddbfabbcf7c987c5aec9 | 3,713 | cpp | C++ | tools/viewer/SkottieSlide2.cpp | ndsol/subskia | 9a8f6e5ffc6676281a4389aa1503ba6c4352eaca | [
"BSD-3-Clause"
] | null | null | null | tools/viewer/SkottieSlide2.cpp | ndsol/subskia | 9a8f6e5ffc6676281a4389aa1503ba6c4352eaca | [
"BSD-3-Clause"
] | null | null | null | tools/viewer/SkottieSlide2.cpp | ndsol/subskia | 9a8f6e5ffc6676281a4389aa1503ba6c4352eaca | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkottieSlide.h"
#include "SkAnimTimer.h"
#include "SkCanvas.h"
#include "Skottie.h"
#include "SkOSFile.h"
#include "SkOSPath.h"
#include "SkStream.h"
const int CELL_WIDTH = 240;
const int CELL_HEIGHT = 160;
const int COL_COUNT = 4;
const int SPACER_X = 12;
const int SPACER_Y = 24;
const int MARGIN = 8;
SkottieSlide2::Rec::Rec(std::unique_ptr<skottie::Animation> anim) : fAnimation(std::move(anim))
{}
SkottieSlide2::Rec::Rec(Rec&& o)
: fAnimation(std::move(o.fAnimation))
, fTimeBase(o.fTimeBase)
, fName(o.fName)
, fShowAnimationInval(o.fShowAnimationInval)
{}
SkottieSlide2::SkottieSlide2(const SkString& path)
: fPath(path)
{
fName.set("skottie-dir");
}
void SkottieSlide2::load(SkScalar, SkScalar) {
SkString name;
SkOSFile::Iter iter(fPath.c_str(), "json");
while (iter.next(&name)) {
SkString path = SkOSPath::Join(fPath.c_str(), name.c_str());
if (auto anim = skottie::Animation::MakeFromFile(path.c_str())) {
fAnims.push_back(Rec(std::move(anim))).fName = name;
}
}
}
void SkottieSlide2::unload() {
fAnims.reset();
}
SkISize SkottieSlide2::getDimensions() const {
const int rows = (fAnims.count() + COL_COUNT - 1) / COL_COUNT;
return {
MARGIN + (COL_COUNT - 1) * SPACER_X + COL_COUNT * CELL_WIDTH + MARGIN,
MARGIN + (rows - 1) * SPACER_Y + rows * CELL_HEIGHT + MARGIN,
};
}
void SkottieSlide2::draw(SkCanvas* canvas) {
SkPaint paint;
paint.setTextSize(12);
paint.setAntiAlias(true);
paint.setTextAlign(SkPaint::kCenter_Align);
const SkRect dst = SkRect::MakeIWH(CELL_WIDTH, CELL_HEIGHT);
int x = 0, y = 0;
canvas->translate(MARGIN, MARGIN);
for (const auto& rec : fAnims) {
SkAutoCanvasRestore acr(canvas, true);
canvas->translate(x * (CELL_WIDTH + SPACER_X), y * (CELL_HEIGHT + SPACER_Y));
canvas->drawText(rec.fName.c_str(), rec.fName.size(),
dst.centerX(), dst.bottom() + paint.getTextSize(), paint);
rec.fAnimation->render(canvas, &dst);
if (++x == COL_COUNT) {
x = 0;
y += 1;
}
}
}
bool SkottieSlide2::animate(const SkAnimTimer& timer) {
for (auto& rec : fAnims) {
if (rec.fTimeBase == 0) {
// Reset the animation time.
rec.fTimeBase = timer.msec();
}
rec.fAnimation->animationTick(timer.msec() - rec.fTimeBase);
}
return true;
}
bool SkottieSlide2::onMouse(SkScalar x, SkScalar y, sk_app::Window::InputState state,
uint32_t modifiers) {
if (fTrackingCell < 0 && state == sk_app::Window::kDown_InputState) {
fTrackingCell = this->findCell(x, y);
}
if (fTrackingCell >= 0 && state == sk_app::Window::kUp_InputState) {
int index = this->findCell(x, y);
if (fTrackingCell == index) {
fAnims[index].fShowAnimationInval = !fAnims[index].fShowAnimationInval;
fAnims[index].fAnimation->setShowInval(fAnims[index].fShowAnimationInval);
}
fTrackingCell = -1;
}
return fTrackingCell >= 0;
}
int SkottieSlide2::findCell(float x, float y) const {
x -= MARGIN;
y -= MARGIN;
int index = -1;
if (x >= 0 && y >= 0) {
int ix = (int)x;
int iy = (int)y;
int col = ix / (CELL_WIDTH + SPACER_X);
int row = iy / (CELL_HEIGHT + SPACER_Y);
index = row * COL_COUNT + col;
if (index >= fAnims.count()) {
index = -1;
}
}
return index;
}
| 28.782946 | 95 | 0.603016 | ndsol |
0c6fb5886a7222b6db6ecbe337185e41a4950e77 | 1,888 | cxx | C++ | src/Cxx/Filtering/PerlinNoise.cxx | cvandijck/VTKExamples | b6bb89414522afc1467be8a1f0089a37d0c16883 | [
"Apache-2.0"
] | 309 | 2017-05-21T09:07:19.000Z | 2022-03-15T09:18:55.000Z | src/Cxx/Filtering/PerlinNoise.cxx | yijianmingliu/VTKExamples | dc8aac47c4384f9a2de9facbdd1ab3249f62ec99 | [
"Apache-2.0"
] | 379 | 2017-05-21T09:06:43.000Z | 2021-03-29T20:30:50.000Z | src/Cxx/Filtering/PerlinNoise.cxx | yijianmingliu/VTKExamples | dc8aac47c4384f9a2de9facbdd1ab3249f62ec99 | [
"Apache-2.0"
] | 170 | 2017-05-17T14:47:41.000Z | 2022-03-31T13:16:26.000Z | #include <vtkSmartPointer.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSampleFunction.h>
#include <vtkContourFilter.h>
#include <vtkProperty.h>
#include <vtkCamera.h>
#include <vtkPerlinNoise.h>
int main(int, char *[])
{
vtkSmartPointer<vtkPerlinNoise> perlinNoise =
vtkSmartPointer<vtkPerlinNoise>::New();
perlinNoise->SetFrequency(2, 1.25, 1.5);
perlinNoise->SetPhase(0, 0, 0);
vtkSmartPointer<vtkSampleFunction> sample =
vtkSmartPointer<vtkSampleFunction>::New();
sample->SetImplicitFunction(perlinNoise);
sample->SetSampleDimensions(65, 65, 20);
sample->ComputeNormalsOff();
vtkSmartPointer<vtkContourFilter> surface =
vtkSmartPointer<vtkContourFilter>::New();
surface->SetInputConnection(sample->GetOutputPort());
surface->SetValue(0, 0.0);
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(surface->GetOutputPort());
mapper->ScalarVisibilityOff();
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
actor->GetProperty()->SetColor(0.2, 0.4, 0.6);
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> interactor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
interactor->SetRenderWindow(renderWindow);
// Add the actors to the renderer, set the background and size
renderer->AddActor(actor);
renderer->SetBackground(1, 1, 1);
renderWindow->SetSize(300, 300);
renderer->ResetCamera();
renderWindow->Render();
interactor->Start();
return EXIT_SUCCESS;
}
| 29.968254 | 64 | 0.748411 | cvandijck |
0c72971cf74ae06ab55dafa05f85171b92cd722e | 8,924 | hpp | C++ | include/real_time_tools/threadsafe/threadsafe_object.hpp | KodlabPenn/real_time_tools | 26e07968ebc51933d8a2a6a8c69ae9dcc289238a | [
"BSD-3-Clause"
] | 4 | 2020-06-07T08:14:09.000Z | 2020-10-19T14:30:02.000Z | include/real_time_tools/threadsafe/threadsafe_object.hpp | KodlabPenn/real_time_tools | 26e07968ebc51933d8a2a6a8c69ae9dcc289238a | [
"BSD-3-Clause"
] | 21 | 2019-09-17T12:05:20.000Z | 2021-07-27T13:45:16.000Z | include/real_time_tools/threadsafe/threadsafe_object.hpp | KodlabPenn/real_time_tools | 26e07968ebc51933d8a2a6a8c69ae9dcc289238a | [
"BSD-3-Clause"
] | 5 | 2019-07-25T22:00:42.000Z | 2021-11-04T18:05:45.000Z | /**
* @file threadsafe_object.hpp
* @author Manuel Wuthrich (manuel.wuthrich@gmail.com)
* @author Maximilien Naveau (maximilien.naveau@gmail.com)
* @brief This file declares templated container for data buffering
* @version 0.1
* @date 2018-11-27
*
* @copyright Copyright (c) 2018
*
*/
#pragma once
#include <array>
#include <map>
#include <memory>
#include <tuple>
#include <vector>
#include "real_time_tools/timer.hpp"
#include <condition_variable>
#include <mutex>
namespace real_time_tools
{
/**
* @brief This is a template abstract interface class that define a data
* history. This re-writting of the vector style class is thread safe. So it
* allows the user to use the object without having to deal with mutexes nor
* condition variables. This class is not used so far.
*
* @tparam Type is the type of the data to store.
*/
template <typename Type>
class ThreadsafeHistoryInterface
{
/**
* @brief Get the element after the one with the given id. if there is no
* newer element, then wait until one arrives.
*
* @param id is the index of the element in the buffer.
* @return Type the next element.
*/
virtual Type get_next(size_t id) const
{
return get(get_next_id(id));
}
virtual size_t get_next_id(size_t id) const = 0;
/**
* @brief Get the newest value, this function waits if it is empty.
*
* @return Type the newest element.
*/
virtual Type get_newest() const
{
return get(get_newest_id());
}
/**
* @brief get_newest_id
*
* @return size_t
*/
virtual size_t get_newest_id() const = 0;
/**
* @brief Get the value whith a specific id.
*
* @param id
* @return Type
*/
virtual Type get(size_t id) const = 0;
/**
* @brief I guess this is to add a value but with no argument?
* \todo Manuel, could you delete this class or provide an implementation?
*/
virtual void add() = 0;
};
/**
* @brief The SingletypeThreadsafeObject is a thread safe object
*
* @tparam Type is the data type to store in the buffer.
* @tparam SIZE is the size of the buffer. It is better to know it at compile
* time to be 100% real time safe.
*/
template <typename Type, size_t SIZE>
class SingletypeThreadsafeObject
{
public:
/**
* @brief Construct a new SingletypeThreadsafeObject object
*/
SingletypeThreadsafeObject();
/**
* @brief Construct a new SingletypeThreadsafeObject object
*
* @param names
*/
SingletypeThreadsafeObject(const std::vector<std::string>& names);
/**
* @brief Wait until the data at the given index is modified.
*
* @param index
*/
void wait_for_update(const size_t& index) const;
/**
* @brief Wait until the data at the given name is modified.
*
* @param name
*/
void wait_for_update(const std::string& name) const
{
wait_for_update(name_to_index_.at(name));
}
/**
* @brief Wait unitl any data has been changed and return its index.
*
* @return size_t
*/
size_t wait_for_update() const;
/**
* Getters
*/
/**
* @brief get size.
*
* @return size_t
*/
size_t size()
{
return SIZE;
}
/**
* @brief Get the data by its index in the buffer.
*
* @param index
* @return Type
*/
Type get(const size_t& index = 0) const
{
std::unique_lock<std::mutex> lock((*data_mutexes_)[index]);
return (*data_)[index];
}
/**
* @brief Get the data by its name in the buffer.
*
* @param name
* @return Type
*/
Type get(const std::string& name) const
{
return get(name_to_index_.at(name));
}
/**
* @brief Get the data by its index in the buffer. Index is solved during
* compile time
*
* @tparam INDEX=0
* @return Type
*/
template <int INDEX = 0>
Type get() const
{
return get(INDEX);
}
/**
* Setters.
*/
/**
* @brief Set one element at a designated index.
*
* @param datum
* @param index
*/
void set(const Type& datum, const size_t& index = 0);
/**
* @brief Set one element at a designated index.
* Warning the index is resolved at compile time.
* This is used for backward comaptibility.
* \todo "This is used for backward comaptibility.", Manuel Which bakward?
*
* @tparam INDEX=0
* @param datum
*/
template <int INDEX = 0>
void set(Type datum)
{
set(datum, INDEX);
}
/**
* @brief Set one element using at a designated name. Internally this name
* is map to an index.
*
* @param datum
* @param name
*/
void set(const Type& datum, const std::string& name)
{
set(datum, name_to_index_.at(name));
}
private:
/**
* @brief This is the data buffer.
*/
std::shared_ptr<std::array<Type, SIZE>> data_;
/**
* @brief This is counting the data modification occurences for each
* individual buffers.
*/
std::shared_ptr<std::array<size_t, SIZE>> modification_counts_;
/**
* @brief This is counting the all data modification occurences for all
* buffer.
* /todo Can't we just some the modification_counts_ array whenever needed?
*/
std::shared_ptr<size_t> total_modification_count_;
/**
* @brief This is the map that allow to deal with data by their names.
*/
std::map<std::string, size_t> name_to_index_;
/**
* @brief This condition variable is used to wait untils any data has been
* changed.
*/
mutable std::shared_ptr<std::condition_variable> condition_;
/**
* @brief This is the mutex of the condition varaible.
*/
mutable std::shared_ptr<std::mutex> condition_mutex_;
/**
* @brief These are the individual mutexes of each data upon setting and
* getting.
*/
mutable std::shared_ptr<std::array<std::mutex, SIZE>> data_mutexes_;
};
/**
* @brief This object can have several types depending on what ones want to
* store.
*
* @tparam Types
*/
template <typename... Types>
class ThreadsafeObject
{
public:
/**
* @brief Define a specific "Type" which permit a more readable code.
*
* @tparam INDEX
*/
template <int INDEX>
using Type = typename std::tuple_element<INDEX, std::tuple<Types...>>::type;
/**
* @brief Define the size of the different types.
*/
static const std::size_t SIZE = sizeof...(Types);
/**
* @brief Construct a new ThreadsafeObject object
*/
ThreadsafeObject();
/**
* @brief Wait until the data with the deignated index is changed.
*
* @param index
*/
void wait_for_update(unsigned index) const;
/**
* @brief Wait until the data with the designated index is changed.
*
* @tparam INDEX=0
*/
template <unsigned INDEX = 0>
void wait_for_update() const
{
wait_for_update(INDEX);
}
/**
* @brief Wait until any data has been changed.
*
* @return size_t
*/
size_t wait_for_update() const;
/**
* Getters
*/
/**
* @brief Get the data with the designated index. The index is resolved at
* compile time.
*
* @tparam INDEX=0
* @return Type<INDEX>
*/
template <int INDEX = 0>
Type<INDEX> get() const;
/**
* Setters
*/
/**
* @brief Set the data with the designated index. The index is resolved at
* compile time.
*
* @tparam INDEX=0
* @param datum
*/
template <int INDEX = 0>
void set(Type<INDEX> datum);
private:
/**
* @brief the actual data buffers.
*/
std::shared_ptr<std::tuple<Types...>> data_;
/**
* @brief a condition variable that allow to wait until one data has been
* changed in the buffer.
*/
mutable std::shared_ptr<std::condition_variable> condition_;
/**
* @brief The mutex of the condition variable.
*/
mutable std::shared_ptr<std::mutex> condition_mutex_;
/**
* @brief This is counting the data modification occurences for each
* individual buffers.
*/
std::shared_ptr<std::array<size_t, SIZE>> modification_counts_;
/**
* @brief This is counting the all data modification occurences for all
* buffer.
* /todo Can't we just some the modification_counts_ array whenever needed?
*/
std::shared_ptr<size_t> total_modification_count_;
/**
* @brief These are the individual mutexes of each data upon setting and
* getting.
*/
std::shared_ptr<std::array<std::mutex, SIZE>> data_mutexes_;
};
} // namespace real_time_tools
#include "real_time_tools/threadsafe/threadsafe_object.hxx"
| 23.860963 | 80 | 0.609592 | KodlabPenn |
0c72c41efc704ecbb5da2011ba78e56b0d3e8276 | 472 | hpp | C++ | include/src/DataBase/SuffixSignature.hpp | zeta1999/METL-recursed | 495aaa610eb7a98fa720429ebccf9bb98abc3e55 | [
"Apache-2.0"
] | 10 | 2018-09-09T04:13:12.000Z | 2021-04-20T06:23:11.000Z | include/src/DataBase/SuffixSignature.hpp | zeta1999/METL-recursed | 495aaa610eb7a98fa720429ebccf9bb98abc3e55 | [
"Apache-2.0"
] | 3 | 2018-10-04T01:56:47.000Z | 2020-07-01T15:20:26.000Z | include/src/DataBase/SuffixSignature.hpp | zeta1999/METL-recursed | 495aaa610eb7a98fa720429ebccf9bb98abc3e55 | [
"Apache-2.0"
] | 3 | 2018-09-28T16:04:46.000Z | 2020-01-12T10:55:57.000Z |
#pragma once
#include <string>
#include <vector>
#include <cassert>
#include "src/TypeErasure/TypeEnum.hpp"
#include "src/DataBase/SuffixID.hpp"
#include "src/DataBase/OperationSignature.hpp"
namespace metl
{
namespace internal
{
using SuffixSignature = OperationSignature<SuffixLabel>;
inline SuffixSignature makeSignature(const SuffixID& id, const std::vector<TYPE>& arguments)
{
assert(arguments.size() == 1);
return {id.name, arguments};
}
}
}
| 17.481481 | 94 | 0.733051 | zeta1999 |
0c7a8f4f1325ceba8954140e4dcbd97ad570d2da | 28,994 | cpp | C++ | Source/main.cpp | rajatarora21/ComputerGraphics | 314288d3c7ed4cf1593327bd1ec03b2c5c6306da | [
"MIT"
] | null | null | null | Source/main.cpp | rajatarora21/ComputerGraphics | 314288d3c7ed4cf1593327bd1ec03b2c5c6306da | [
"MIT"
] | null | null | null | Source/main.cpp | rajatarora21/ComputerGraphics | 314288d3c7ed4cf1593327bd1ec03b2c5c6306da | [
"MIT"
] | null | null | null | //
// Yuvraj Singh Athwal(40075586), Rajat Arora(40078146), Zhen Long(27117507), Yiyang Zhou(40046467)
//PA 3
//Lab1, COMP371- https://moodle.concordia.ca/moodle/mod/resource/view.php?id=2306198
//importing required files.
#include "grids.h"
#include "shaderloader.h"
#include "cube.h"
#include "coord.h"
#include "sphere.h"
#include "rubikCube.h"
//initializing OpenGL libraries
#define GLEW_STATIC 1
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <iostream>
#include <vector>
#include <glm/gtc/type_ptr.hpp>
#include "glm/gtc/matrix_transform.hpp"
#include <glm/gtx/transform.hpp>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include "main.h"
#include "textRenderer.h"
using namespace std;
using namespace glm;
//viewMatrix
void setViewMatrix(int shader, mat4 viewMatrix)
{
GLuint viewMatrixLocation = glGetUniformLocation(shader, "viewMatrix");
glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, &viewMatrix[0][0]);
}
void setProjectionMatrix(int shader, mat4 projectionMatrix)
{
GLuint projectionMatrixLocation = glGetUniformLocation(shader, "projectionMatrix");
glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix[0][0]);
}
//main function
//letter and digit transform data
struct LetterDigitData
{
vector<mat4> letterMatrices; //letter's cube transforms
vector<mat4> digitMatrices; //digit's cube transforms
mat4 translation;
mat4 rotation;
mat4 scaling;
mat4 shearing;
bool continueShearXPos;
bool continueShearXNeg;
};
bool shadow = true;
LetterDigitData letterDigitDatas[5] = {
{
//draw sujects first name zhen and 3th alphabet E
{
glm::translate(mat4(1.0f), vec3(-0.06f,0.00f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.15f, 0.02f)), // left of E
glm::translate(mat4(1.0f), vec3(-0.02f,0.07f,0.00f))*glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.1f, 0.02f)), //top of E
glm::translate(mat4(1.0f), vec3(-0.02f,0.00f,0.00f))*glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.1f, 0.02f)),//mid of E
glm::translate(mat4(1.0f), vec3(-0.02f,-0.08f,0.00f))*glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.1f, 0.02f)),//botom of E
},
// student ID 27117507 and 4th digit is 1
{
glm::translate(mat4(1.0f), vec3(0.14f,-0.01f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.17f, 0.02f)),
},
glm::translate(mat4(1.0f), vec3(35.0f,5.0f,-35.0f)),//translation
mat4(1),//rotation
glm::scale(mat4(1),vec3(50)),//scaling
mat4(1),//shearing
false,
false,
},
{
//V and 7 for Yuvraj.
{
//V
glm::translate(mat4(1.0f), vec3(-0.11f,-0.03f,0.00f))*glm::rotate(glm::mat4(1.0f), glm::radians(15.0f), glm::vec3(0.0f, 0.0f, 1.0f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.18f, 0.02f)),
glm::translate(mat4(1.0f), vec3(-0.05f,-0.03f,0.00f))*glm::rotate(glm::mat4(1.0f), glm::radians(165.0f), glm::vec3(0.0f, 0.0f, 1.0f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.18f, 0.02f)),
},
{
// 7
glm::translate(mat4(1.0f), vec3(0.06f,0.03f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.08f, 0.02f)),
glm::translate(mat4(1.0f), vec3(0.05f,-0.05f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.08f, 0.02f)),
// top of 7
glm::translate(mat4(1.0f), vec3(0.03f,0.06f,0.00f))*glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.1f, 0.02f)),
},
glm::translate(mat4(1.0f), vec3(-35.0f,5.0f,35.0f)),//translation
mat4(1),//rotation
glm::scale(mat4(1),vec3(50)),//scaling
mat4(1),//shearing
false,
false,
},
/*
{
//V and 1 for Divyluv
{
//V
glm::translate(mat4(1.0f), vec3(-0.06f,-0.00f,0.00f))*glm::rotate(glm::mat4(1.0f), glm::radians(15.0f), glm::vec3(0.0f, 0.0f, 1.0f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.18f, 0.02f)),
glm::translate(mat4(1.0f), vec3(0.00f,-0.00f,0.00f))*glm::rotate(glm::mat4(1.0f), glm::radians(165.0f), glm::vec3(0.0f, 0.0f, 1.0f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.18f, 0.02f)),
},
{
//1
glm::translate(mat4(1.0f), vec3(0.06f,0.01f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.17f, 0.02f)),
},
glm::translate(mat4(1.0f), vec3(-35.0f,5.0f,-35.0f)),//translation
mat4(1),//rotation
glm::scale(mat4(1),vec3(50)),//scaling
mat4(1),//shearing
false,
false,
},
*/
{
//Y and 4 for Yiyang
{
glm::translate(mat4(1.0f), vec3(-0.14f,0.03f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.08f, 0.02f)),
glm::translate(mat4(1.0f), vec3(-0.11f,-0.05f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.08f, 0.02f)),
glm::translate(mat4(1.0f), vec3(-0.08f,0.03f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.08f, 0.02f)),
},
//4
{
glm::translate(mat4(1.0f), vec3(0.11f,0.03f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.08f, 0.02f)),
//mid of 4
glm::translate(mat4(1.0f), vec3(0.07f,-0.01f,0.00f))*glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.1f, 0.02f)),
// top right of 4
glm::translate(mat4(1.0f), vec3(0.01f,0.03f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.08f, 0.02f)),
//bottom right
glm::translate(mat4(1.0f), vec3(0.11f,-0.05f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.08f, 0.02f)),
},
glm::translate(mat4(1.0f), vec3(35.0f,5.0f,35.0f)),//translation
mat4(1),//rotation
glm::scale(mat4(1),vec3(50)),//scaling
mat4(1),//shearing
false,
false,
},
{
//J and 7 for Rajat
{
glm::translate(mat4(1.0f), vec3(-0.12f,-0.03f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.08f, 0.02f)),
// botom of J
glm::translate(mat4(1.0f), vec3(-0.07f,-0.06f,0.00f))*glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.1f, 0.02f)),
// top right of J
glm::translate(mat4(1.0f), vec3(-0.02f,0.05f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.08f, 0.02f)),
// bottom right of J
glm::translate(mat4(1.0f), vec3(-0.02f,-0.03f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.08f, 0.02f)),
},
{
// 7
glm::translate(mat4(1.0f), vec3(0.08f,0.05f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.08f, 0.02f)),
glm::translate(mat4(1.0f), vec3(0.07f,-0.03f,0.00f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.08f, 0.02f)),
// top of 7
glm::translate(mat4(1.0f), vec3(0.05f,0.08f,0.00f))*glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f))*glm::scale(mat4(1.0f), vec3(0.02f, 0.1f, 0.02f)),
},
glm::translate(mat4(1.0f), vec3(-35.0f,5.0f,-35.0f)),//translation
mat4(1),//rotation
glm::scale(mat4(1),vec3(50)),//scaling
mat4(1),//shearing
false,
false,
},
};
int editingModelId = -1;
int editModelIndex = -1;
RubikCube rubikCube;
float playTime = 0;
bool playing = false;
TextRenderer timeText;
void keyCallback(GLFWwindow *window, int keyCody, int scan,int action, int mods)
{
if (!mods&&action==GLFW_PRESS)
{
if (editingModelId >= 0 && editingModelId<5)
{
if (keyCody == 'G')
{
letterDigitDatas[editingModelId].continueShearXPos = !letterDigitDatas[editingModelId].continueShearXPos;
letterDigitDatas[editingModelId].continueShearXNeg = false;
for (size_t i = 0; i < 5; i++)
{
if (i != editingModelId)
{
letterDigitDatas[i].continueShearXNeg = false;
letterDigitDatas[i].continueShearXPos = false;
}
}
}
if (keyCody == 'H')
{
letterDigitDatas[editingModelId].continueShearXNeg = !letterDigitDatas[editingModelId].continueShearXNeg;
letterDigitDatas[editingModelId].continueShearXPos = false;
for (size_t i = 0; i < 5; i++)
{
if (i != editingModelId)
{
letterDigitDatas[i].continueShearXNeg = false;
letterDigitDatas[i].continueShearXPos = false;
}
}
}
}
if (keyCody>='1'&&keyCody<='5')
{
editingModelId = keyCody - '1';
}
}
if (action == GLFW_PRESS)
{
if (editModelIndex == -1)
{
if (keyCody == 'A') {
rubikCube.makeMove(RubikCube::L, glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) != GLFW_PRESS);
}
if (keyCody == 'D') {
rubikCube.makeMove(RubikCube::R, glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) != GLFW_PRESS);
}
if (keyCody == 'W') {
rubikCube.makeMove(RubikCube::U, glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) != GLFW_PRESS);
}
if (keyCody == 'S') {
rubikCube.makeMove(RubikCube::D, glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) != GLFW_PRESS);
}
if (keyCody == 'Q') {
rubikCube.makeMove(RubikCube::F, glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) != GLFW_PRESS);
}
if (keyCody == 'E') {
rubikCube.makeMove(RubikCube::B, glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) != GLFW_PRESS);
}
if (keyCody==' ')
{
playing = !playing;
}
}
}
}
GLuint loadTexture(const char *file)
{
GLuint tex=0;
int w, h;
unsigned char *pixels = stbi_load(file, &w, &h, 0, 4);
if (pixels)
{
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
free(pixels);
}
return tex;
}
int main(int argc, char*argv[])
{
// Initialize GLFW and OpenGL version
glfwInit();
#if defined(PLATFORM_OSX)
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#else
// On windows, we set OpenGL version to 2.1, to support more hardware
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
//glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE );
#endif
// Create Window, resolution is 1024x768
GLFWwindow* window = glfwCreateWindow(1024, 768, "PA3", NULL, NULL);
glfwSetKeyCallback(window, keyCallback);
if (window == NULL)
{
std::cerr << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Initialize GLEW
glewExperimental = true; // Needed for core profile
if (glewInit() != GLEW_OK) {
std::cerr << "Failed to create GLEW" << std::endl;
glfwTerminate();
return -1;
}
// Shaders
GLuint textureLitProgram;
GLuint unlitProgram;
GLuint depthProgram;
GLuint fontProgram;
GLuint currentProgram;
#if defined(PLATFORM_OSX)
std::string shaderPathPrefix = "Shaders/";
#else
std::string shaderPathPrefix = "../Assets/Shaders/";
#endif
unlitProgram = shaderloader::LoadShaders(shaderPathPrefix + "vertex_shader_color.glsl", shaderPathPrefix + "fragment_shader_color.glsl");
textureLitProgram = shaderloader::LoadShaders(shaderPathPrefix + "vertex_shader.glsl", shaderPathPrefix + "fragment_shader.glsl");
depthProgram = shaderloader::LoadShaders(shaderPathPrefix + "vertex_depth.glsl", shaderPathPrefix + "fragment_depth.glsl");
fontProgram= shaderloader::LoadShaders(shaderPathPrefix + "font_vert.glsl", shaderPathPrefix + "font_frag.glsl");
vec3 cameraPosition(0.0f, 50.0f, 80.0f);
vec3 cameraLookAt(0.0f, -5.0f, -8.0f);
vec3 cameraUp(0.0f, 1.0f, 0.0f);
float cameraSpeed = 1.0f;
grid* g = new grid();
int vao_grid = g->createGridArray();
cube* cube1 = new cube();
int vao_cube = cube1->createCubeArray();
coord* axies = new coord();
int vao_axis = axies->createAxisArray();
sphere* ball = new sphere();
int vao_ball = ball->createSphereArray();
rubikCube.initialize();
rubikCube.model = translate(mat4(1), vec3(0, 10, 0))*scale(mat4(1), vec3(5, 5, 5));
rubikCube.setCubeTexture(loadTexture("../Assets/Textures/cube.bmp"));
rubikCube.setFaceTexture({
loadTexture("../Assets/Textures/face1.png"),
loadTexture("../Assets/Textures/movie.jpg"),
loadTexture("../Assets/Textures/face6.png"),
loadTexture("../Assets/Textures/music.jpg"),
loadTexture("../Assets/Textures/face2.png"),
loadTexture("../Assets/Textures/game.jpg"),
});
GLuint grassTex = loadTexture("../Assets/Textures/grass.jpg");
GLuint boxTex = loadTexture("../Assets/Textures/crate.jpg");
GLuint metalTex = loadTexture("../Assets/Textures/metal.jpg");
GLuint ballTex = loadTexture("../Assets/Textures/bubble.png");
timeText.setFontTexture(loadTexture("../Assets/Textures/ascii.png"));
auto err = glGetError();
//depth render target
GLuint depthTex;
glGenTextures(1, &depthTex);
glBindTexture(GL_TEXTURE_2D, depthTex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 1024, 1024, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
//frame buffer
GLuint fbo;
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTex, 0);
glDrawBuffer(GL_NONE);
auto status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status !=GL_FRAMEBUFFER_COMPLETE)
{
printf("fbo error!");
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
float lastFrameTime = glfwGetTime();
int lastMouseLeftState = GLFW_RELEASE;
double lastMousePosX, lastMousePosY;
glfwGetCursorPos(window, &lastMousePosX, &lastMousePosY);
GLuint worldmatrixlocation;
GLuint mode = GL_TRIANGLES;
mat4 worldMatrix=mat4(1);
mat4 center = glm::rotate(mat4(1.0f), glm::radians(90.0f), vec3(0.0f, 1.0f, 0.0f)) * glm::translate(mat4(1.0), vec3(-0.34f, 0.0f, 0.52f));
float moving = 0.0f, raise = 0.0f;
float degree = 0.0f;
// Enable Backface culling
glEnable(GL_CULL_FACE);
// Enable z buffer
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
// Entering Main Loop
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClearDepth(1.0f);
while (!glfwWindowShouldClose(window))
{
float dt = glfwGetTime() - lastFrameTime;
lastFrameTime += dt;
rubikCube.update(dt);
if (playing)
{
playTime += dt;
}
double mouseX, mouseY;
glfwGetCursorPos(window, &mouseX, &mouseY);
double dx = mouseX - lastMousePosX;
double dy = mouseY - lastMousePosY;
lastMousePosX = mouseX;
lastMousePosY = mouseY;
//update model shearing
for (size_t i = 0; i < 5; i++)
{
if (letterDigitDatas[i].continueShearXPos)
{
mat4 shearing = mat4(
1, 0, 0, 0,
0.1*dt, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
letterDigitDatas[i].shearing = letterDigitDatas[i].shearing*shearing;
}
if (letterDigitDatas[i].continueShearXNeg)
{
mat4 shearing = mat4(
1, 0, 0, 0,
-0.1*dt, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
letterDigitDatas[i].shearing = letterDigitDatas[i].shearing*shearing;
}
}
mat4 lightVP;
//shadow pass
{
glClearDepth(1);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glViewport(0, 0, 1024, 1024);
glClear(GL_DEPTH_BUFFER_BIT);
currentProgram = depthProgram;
glUseProgram(depthProgram);
mat4 projection = perspective<float>(radians(160.0f), 1.0f, 0.1f, 50);
vec4 lightPos = vec4(0, 30, 0, 1);
vec4 lightDir = vec4(0, -1, 0, 0);
vec4 lightUp = vec4(1, 0, 0, 0);
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(2, 2);
mat4 view = lookAt(vec3(worldMatrix*lightPos), // eye
vec3(worldMatrix*lightPos)+ vec3(worldMatrix*lightDir), // center
vec3(worldMatrix*lightUp)); // up
setProjectionMatrix(currentProgram, projection);
setViewMatrix(currentProgram, view);
if (shadow)
lightVP = projection * view;
else
lightVP = worldMatrix;
for (auto &data : letterDigitDatas)
{
glBindTexture(GL_TEXTURE_2D, boxTex);
for (auto &m : data.letterMatrices)
{
glBindVertexArray(vao_cube);
mat4 modelMatrix = worldMatrix * data.translation * data.rotation *data.scaling*data.shearing*m;
worldmatrixlocation = glGetUniformLocation(currentProgram, "worldMatrix");
glUniformMatrix4fv(worldmatrixlocation, 1, GL_FALSE, &modelMatrix[0][0]);
glDrawArrays(mode, 0, 36); // 3 vertices, starting at vertex array index 0
glBindVertexArray(0);
}
glBindTexture(GL_TEXTURE_2D, metalTex);
for (auto &m : data.digitMatrices)
{
glBindVertexArray(vao_cube);
mat4 modelMatrix = worldMatrix * data.translation * data.rotation *data.scaling*data.shearing*m;
worldmatrixlocation = glGetUniformLocation(currentProgram, "worldMatrix");
glUniformMatrix4fv(worldmatrixlocation, 1, GL_FALSE, &modelMatrix[0][0]);
glDrawArrays(mode, 0, 36); // 3 vertices, starting at vertex array index 0
glBindVertexArray(0);
}
}
//draw rubik cube
rubikCube.render(currentProgram, worldMatrix);
//draw grids
glBindVertexArray(vao_grid);
mat4 gridWorldMatrix = worldMatrix * mat4(1);
worldmatrixlocation = glGetUniformLocation(currentProgram, "worldMatrix");
glUniformMatrix4fv(worldmatrixlocation, 1, GL_FALSE, &gridWorldMatrix[0][0]);
glDrawArrays(GL_TRIANGLES, 0, g->getSize()); // 3 vertices, starting at vertex array index 0
glBindVertexArray(0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDisable(GL_POLYGON_OFFSET_FILL);
}
int width;
int height;
glfwGetWindowSize(window, &width, &height);
glViewport(0, 0, width, height);
// Each frame, reset color of each pixel to glClearColor
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
currentProgram = textureLitProgram;
glUseProgram(currentProgram);
mat4 projection = perspective<float>(radians(60.0f), float(width) / height, 0.01f, 500);
mat4 view = lookAt(cameraPosition, // eye
cameraPosition + cameraLookAt, // center
cameraUp); // up
setProjectionMatrix(currentProgram, projection);
setViewMatrix(currentProgram, view);
GLuint viewMatrixLocation = glGetUniformLocation(currentProgram, "lightTransformMatrix");
glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, &worldMatrix[0][0]);
int lightVPLoc = glGetUniformLocation(currentProgram, "lightVP");
int texLoc = glGetUniformLocation(currentProgram, "tex");
int shadiwTexLoc = glGetUniformLocation(currentProgram, "shadowTex");
int roughnessLoc = glGetUniformLocation(currentProgram, "roughness");
glUniform1i(texLoc, 0);
glUniform1i(shadiwTexLoc, 1);
glUniformMatrix4fv(lightVPLoc,1,GL_FALSE,value_ptr(lightVP));
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, depthTex);
//draw letter and digit
for (auto &data : letterDigitDatas)
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, boxTex);
for (auto &m : data.letterMatrices)
{
glBindVertexArray(vao_cube);
mat4 modelMatrix = worldMatrix * data.translation * data.rotation *data.scaling*data.shearing*m;
worldmatrixlocation = glGetUniformLocation(currentProgram, "worldMatrix");
glUniformMatrix4fv(worldmatrixlocation, 1, GL_FALSE, &modelMatrix[0][0]);
glDrawArrays(mode, 0, 36); // 3 vertices, starting at vertex array index 0
glBindVertexArray(0);
}
glUniform1f(roughnessLoc, 0.0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, metalTex);
for (auto &m : data.digitMatrices)
{
glBindVertexArray(vao_cube);
mat4 modelMatrix = worldMatrix * data.translation * data.rotation *data.scaling*data.shearing*m;
worldmatrixlocation = glGetUniformLocation(currentProgram, "worldMatrix");
glUniformMatrix4fv(worldmatrixlocation, 1, GL_FALSE, &modelMatrix[0][0]);
glDrawArrays(mode, 0, 36); // 3 vertices, starting at vertex array index 0
glBindVertexArray(0);
}
glUniform1f(roughnessLoc, 1.0);
}
//draw rubik's cube
rubikCube.render(currentProgram, worldMatrix);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, grassTex);
//draw grids
glBindVertexArray(vao_grid);
mat4 gridWorldMatrix = worldMatrix * mat4(1);
worldmatrixlocation = glGetUniformLocation(currentProgram, "worldMatrix");
glUniformMatrix4fv(worldmatrixlocation, 1, GL_FALSE, &gridWorldMatrix[0][0]);
glDrawArrays(GL_TRIANGLES, 0, g->getSize()); // 3 vertices, starting at vertex array index 0
glBindVertexArray(0);
currentProgram = unlitProgram;
glUseProgram(currentProgram);
setProjectionMatrix(currentProgram, projection);
setViewMatrix(currentProgram, view);
//draw axes
mat4 axisWorldMatrix = worldMatrix * mat4(1);
glLineWidth(5);
worldmatrixlocation = glGetUniformLocation(currentProgram, "worldMatrix");
glUniformMatrix4fv(worldmatrixlocation, 1, GL_FALSE, &axisWorldMatrix[0][0]);
glBindVertexArray(vao_axis);
glDrawArrays(GL_LINES, 0, 6);
glBindVertexArray(0);
glLineWidth(1);
//draw bubble
currentProgram = textureLitProgram;
glUseProgram(currentProgram);
for (auto &data : letterDigitDatas)
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDepthMask(GL_FALSE);
//draw ball
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, ballTex);
glBindVertexArray(vao_ball);
mat4 modelMatrix = worldMatrix * data.translation * data.rotation *data.scaling*data.shearing*translate(mat4(1), vec3(0, 0.2, 0))*scale(mat4(1), vec3(0.2));
worldmatrixlocation = glGetUniformLocation(currentProgram, "worldMatrix");
glUniformMatrix4fv(worldmatrixlocation, 1, GL_FALSE, &modelMatrix[0][0]);
glDrawArrays(mode, 0, ball->getSize()); // 3 vertices, starting at vertex array index 0
glBindVertexArray(0);
glDisable(GL_BLEND);
glDepthMask(GL_TRUE);
}
//render text
currentProgram = fontProgram;
glUseProgram(currentProgram);
setProjectionMatrix(currentProgram, ortho<float>(0, width, 0, height, -100, 100));
timeText.setPosition({ 50,height - 50 });
char text[256] = "";
sprintf(text, "TIME:%.02fs", playTime);
timeText.setPosition({ 50,height - 50 });
timeText.setText(text);
timeText.render(currentProgram);
// End frame
glfwSwapBuffers(window); //render in the background buffer, and display the front buffer withn rendered image
// Detect inputs
glfwPollEvents();
editModelIndex = -1;
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS)
{
editModelIndex = 0;
}
else if (glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS)
{
editModelIndex = 1;
}
else if (glfwGetKey(window, GLFW_KEY_3) == GLFW_PRESS)
{
editModelIndex = 2;
}
else if (glfwGetKey(window, GLFW_KEY_4) == GLFW_PRESS)
{
editModelIndex = 3;
}
else if (glfwGetKey(window, GLFW_KEY_5) == GLFW_PRESS)
{
editModelIndex = 4;
}
if (editModelIndex>=0&& editModelIndex<5)
{
//scale up and down
if (glfwGetKey(window, GLFW_KEY_U) == GLFW_PRESS) {
letterDigitDatas[editModelIndex].scaling = glm::scale(letterDigitDatas[editModelIndex].scaling, vec3(1.01, 1.01, 1.01));
}
if (glfwGetKey(window, GLFW_KEY_J) == GLFW_PRESS) {
letterDigitDatas[editModelIndex].scaling = glm::scale(letterDigitDatas[editModelIndex].scaling, vec3(1/1.01, 1 / 1.01, 1 / 1.01));
}
//move the object
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
letterDigitDatas[editModelIndex].translation = glm::translate(letterDigitDatas[editModelIndex].translation, vec3(-0.05f, 0.0f, 0.0f));
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
letterDigitDatas[editModelIndex].translation = glm::translate(letterDigitDatas[editModelIndex].translation, vec3(0.05f, 0.0f, 0.0f));
}
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
letterDigitDatas[editModelIndex].translation = glm::translate(letterDigitDatas[editModelIndex].translation, vec3( 0.0f, 0.05f,0.0f));
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
letterDigitDatas[editModelIndex].translation = glm::translate(letterDigitDatas[editModelIndex].translation, vec3(0.0f, -0.05f, 0.0f));
}
// rotate 5 degree about Y axis
if (glfwGetKey(window, GLFW_KEY_Z) == GLFW_PRESS) {
letterDigitDatas[editModelIndex].rotation = glm::rotate(letterDigitDatas[editModelIndex].rotation, glm::radians(5.0f), glm::vec3(0.0f, 1.0f, 0.0f));
}
if (glfwGetKey(window, GLFW_KEY_X) == GLFW_PRESS) {
letterDigitDatas[editModelIndex].rotation = glm::rotate(letterDigitDatas[editModelIndex].rotation, glm::radians(-5.0f), glm::vec3(0.0f, 1.0f, 0.0f));
}
// rotate 5 degree about X axis
if (glfwGetKey(window, GLFW_KEY_C) == GLFW_PRESS) {
letterDigitDatas[editModelIndex].rotation = glm::rotate(letterDigitDatas[editModelIndex].rotation, glm::radians(5.0f), glm::vec3(1.0f, 0.0f, 0.0f));
}
if (glfwGetKey(window, GLFW_KEY_V) == GLFW_PRESS) {
letterDigitDatas[editModelIndex].rotation = glm::rotate(letterDigitDatas[editModelIndex].rotation, glm::radians(-5.0f), glm::vec3(1.0f, 0.0f, 0.0f));
}
// shearing
if (glfwGetKey(window, GLFW_KEY_B) == GLFW_PRESS) {
mat4 shearing = mat4(
1, 0, 0, 0,
0.05, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
letterDigitDatas[editModelIndex].shearing = letterDigitDatas[editModelIndex].shearing*shearing;
}
if (glfwGetKey(window, GLFW_KEY_N) == GLFW_PRESS) {
mat4 shearing = mat4(
1, 0, 0, 0,
-0.05, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
letterDigitDatas[editModelIndex].shearing = letterDigitDatas[editModelIndex].shearing*shearing;
}
}
// left button, zoom
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) {
cameraPosition += cameraLookAt*(float)dy*0.1f;
}
// right button, pan with respect to X
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS) {
glm::vec3 cameraSideVector = glm::cross(cameraLookAt, glm::vec3(0.0f, 1.0f, 0.0f));
glm::normalize(cameraSideVector);
cameraLookAt += 0.009f *(float)dx * cameraSideVector;
glm::mat4 viewMatrix = glm::lookAt(cameraPosition, // eye
cameraPosition + cameraLookAt, // center
glm::vec3(0.0f, 1.0f, 0.0f));// up
}
//middle button, tilt with respect to Y
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS) {
double mouseX, mouseY;
glfwGetCursorPos(window, &mouseX, &mouseY);
double dy = mouseY - lastMousePosY;
lastMousePosY = mouseY;
cameraLookAt += 0.009f *(float)dy * cameraUp;
}
// Rx and R-x and Ry and R-y world rotation
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS)
{
worldMatrix = rotate(mat4(1), 0.1f, vec3(0, 1, 0))*worldMatrix;
}
if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS)
{
worldMatrix = rotate(mat4(1), 0.1f, vec3(0, -1, 0))*worldMatrix;
}
if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS)
{
worldMatrix = rotate(mat4(1), 0.1f, vec3(1, 0, 0))*worldMatrix;
}
if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS)
{
worldMatrix = rotate(mat4(1), 0.1f, vec3(-1, 0, 0))*worldMatrix;
}
// home to reset
if (glfwGetKey(window, GLFW_KEY_HOME) == GLFW_PRESS) {
cameraPosition = vec3(0.0f, 50.0f, 80.0f);
cameraLookAt = vec3(0.0f, -5.0f, -8.0f);
worldMatrix = mat4(1);
}
// launch timer
if (glfwGetKey(window, GLFW_KEY_Y) == GLFW_PRESS) {
playing = true;
}
if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS) {
worldMatrix=mat4(1);
rubikCube.reset();
playTime = 0;
}
// switch render modes
if (glfwGetKey(window, GLFW_KEY_P) == GLFW_PRESS) {
mode = GL_POINTS;
}
if (glfwGetKey(window, GLFW_KEY_L) == GLFW_PRESS) {
mode = GL_LINES;
}
if (glfwGetKey(window, GLFW_KEY_T) == GLFW_PRESS) {
mode = GL_TRIANGLES;
}
if (glfwGetKey(window, GLFW_KEY_M) == GLFW_PRESS) {
if (shadow)
shadow = false;
else
shadow = true;
}
}
// Shutdown GLFW
glfwTerminate();
return 0;
}
| 34.110588 | 198 | 0.671518 | rajatarora21 |
0c7c8b823c53868261dc861515c7f334ab885366 | 206 | hpp | C++ | include/xnn/layers/pooling.hpp | ktnyt/xdfa | 962ef8f99150556272ff87c7b37494fd87f5fe79 | [
"MIT"
] | null | null | null | include/xnn/layers/pooling.hpp | ktnyt/xdfa | 962ef8f99150556272ff87c7b37494fd87f5fe79 | [
"MIT"
] | null | null | null | include/xnn/layers/pooling.hpp | ktnyt/xdfa | 962ef8f99150556272ff87c7b37494fd87f5fe79 | [
"MIT"
] | null | null | null | #ifndef __XNN_LAYERS_POOLING_HPP__
#define __XNN_LAYERS_POOLING_HPP__
#include "xnn/layers/pooling/average_pooling.hpp"
#include "xnn/layers/pooling/max_pooling.hpp"
#endif // __XNN_LAYERS_POOLING_HPP__
| 25.75 | 49 | 0.839806 | ktnyt |
0c7dba69a42bc938712778de215e1a6ad3cc6de6 | 821 | cpp | C++ | challenge Pattern/Assignment/Assignment4/prob2.1.cpp | sgpritam/DSAlgo | 3e0e6b19d4f8978b2fc3be48195705a285dbdce8 | [
"MIT"
] | 1 | 2020-03-06T21:05:14.000Z | 2020-03-06T21:05:14.000Z | challenge Pattern/Assignment/Assignment4/prob2.1.cpp | sgpritam/DSAlgo | 3e0e6b19d4f8978b2fc3be48195705a285dbdce8 | [
"MIT"
] | 2 | 2020-03-09T05:08:14.000Z | 2020-03-09T05:14:09.000Z | challenge Pattern/Assignment/Assignment4/prob2.1.cpp | sgpritam/DSAlgo | 3e0e6b19d4f8978b2fc3be48195705a285dbdce8 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
for(int i=1;i<=n/2+1;i++)
{
for(int space=1;space<=n/2-i+1;space++)
{
cout<<" ";
}
for(int j=1;j<=2*i-1;j++)
{
if(j==1 || j==2*i-1)
{
cout<<"*";
}
else
{
cout<<" ";
}
}
cout<<endl;
}
// Lower loop
for(int i=1;i<=n/2;i++){
for(int space=1;space<=i;space++)
{
cout<<" ";
}
for(int j=1;j<=n-2*i;j++)
{
if(j==1 || j==n-2*i)
{
cout<<"*";
}
else
{
cout<<" ";
}
}
cout<<endl;
}
}
| 17.104167 | 47 | 0.267966 | sgpritam |
0c80b87aeabd01d4c58e903d40cad75d47abcb17 | 1,190 | hpp | C++ | src/tools/Opcode.hpp | stfnwong/smips | f305d24e16632b0a4907607386fc9d98f3d389b5 | [
"MIT"
] | null | null | null | src/tools/Opcode.hpp | stfnwong/smips | f305d24e16632b0a4907607386fc9d98f3d389b5 | [
"MIT"
] | null | null | null | src/tools/Opcode.hpp | stfnwong/smips | f305d24e16632b0a4907607386fc9d98f3d389b5 | [
"MIT"
] | null | null | null | /*
* OPCODE
* Opcodes for SMIPS
*
* Stefan Wong 2019
*/
#ifndef __OPCODE_HPP
#define __OPCODE_HPP
#include <cstdint>
#include <string>
#include <vector>
/*
* Opcode
* Represents a single Opcode from the MIPS aseembly language.
* FOr use with Lexer object.
*/
struct Opcode
{
uint32_t instr;
std::string mnemonic;
public:
Opcode();
Opcode(const uint32_t c, const std::string& m);
void init(void);
std::string toString(void) const;
// operator overloads
bool operator==(const Opcode& that) const;
bool operator!=(const Opcode& that) const;
};
/*
* OpcodeTable
* Hold a collection of Opcodes
*/
class OpcodeTable
{
private:
std::vector<Opcode> op_list;
Opcode null_op;
public:
OpcodeTable();
~OpcodeTable();
void add(const Opcode& op);
Opcode& get(const std::string& mnemonic);
Opcode& get(const uint32_t opcode);
Opcode& getIdx(const int idx);
unsigned int size(void) const;
void init(void);
};
/*
* InstrCode
* Instruction code used by Assembler
*/
#endif /*__OPCODE_HPP*/
| 18.030303 | 62 | 0.597479 | stfnwong |
0c876c1c227c760ff856b96adf9a78cd92613320 | 132 | cpp | C++ | examples/ittapi/boo.cpp | varphone/hunter | 14a6b9a132d78ed0828497c7e8d9b42951209243 | [
"BSD-2-Clause"
] | 440 | 2019-08-25T13:07:04.000Z | 2022-03-30T21:57:15.000Z | examples/ittapi/boo.cpp | varphone/hunter | 14a6b9a132d78ed0828497c7e8d9b42951209243 | [
"BSD-2-Clause"
] | 401 | 2019-08-29T08:56:55.000Z | 2022-03-30T12:39:34.000Z | examples/ittapi/boo.cpp | varphone/hunter | 14a6b9a132d78ed0828497c7e8d9b42951209243 | [
"BSD-2-Clause"
] | 162 | 2019-09-02T13:31:36.000Z | 2022-03-30T09:16:54.000Z | #include <ittnotify.h>
int main() {
// pause data collection:
__itt_pause();
// Start data collection
__itt_resume();
}
| 13.2 | 27 | 0.643939 | varphone |
0c8ad14cd0bd5be4b5b0c002eef26b650bbb6e93 | 10,560 | cpp | C++ | eden/fs/win/mount/EdenDispatcher.cpp | jmswen/eden | 5e0b051703fa946cc77fc43004435ae6b20599a1 | [
"BSD-3-Clause"
] | null | null | null | eden/fs/win/mount/EdenDispatcher.cpp | jmswen/eden | 5e0b051703fa946cc77fc43004435ae6b20599a1 | [
"BSD-3-Clause"
] | null | null | null | eden/fs/win/mount/EdenDispatcher.cpp | jmswen/eden | 5e0b051703fa946cc77fc43004435ae6b20599a1 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "folly/portability/Windows.h"
#include <folly/Format.h>
#include <folly/logging/xlog.h>
#include "ProjectedFSLib.h"
#include "eden/fs/model/Blob.h"
#include "eden/fs/model/Tree.h"
#include "eden/fs/service/EdenError.h"
#include "eden/fs/win/mount/EdenDispatcher.h"
#include "eden/fs/win/mount/EdenMount.h"
#include "eden/fs/win/store/WinStore.h"
#include "eden/fs/win/utils/StringConv.h"
#include "eden/fs/win/utils/WinError.h"
using folly::sformat;
using std::make_unique;
using std::wstring;
namespace facebook {
namespace eden {
namespace {
struct PrjAlignedBufferDeleter {
void operator()(void* buffer) noexcept {
::PrjFreeAlignedBuffer(buffer);
}
};
} // namespace
constexpr uint32_t kMinChunkSize = 512 * 1024; // 512 KB
constexpr uint32_t kMaxChunkSize = 5 * 1024 * 1024; // 5 MB
#ifdef NDEBUG
// Some of the following functions will be called with a high frequency.
// Creating a way to totally take out the calls in the free builds.
#define TRACE(fmt, ...)
#else
#define TRACE(fmt, ...) XLOG(DBG6) << sformat(fmt, ##__VA_ARGS__)
#endif
EdenDispatcher::EdenDispatcher(const EdenMount* mount)
: mount_{mount}, winStore_{mount} {
XLOGF(
INFO,
"Creating Dispatcher mount (0x{:x}) root ({}) dispatcher (0x{:x})",
reinterpret_cast<uintptr_t>(mount_),
mount_->getPath(),
reinterpret_cast<uintptr_t>(this));
}
HRESULT EdenDispatcher::startEnumeration(
const PRJ_CALLBACK_DATA& callbackData,
const GUID& enumerationId) noexcept {
try {
std::vector<FileMetadata> list;
wstring path{callbackData.FilePathName};
TRACE(
"startEnumeration mount (0x{:x}) root ({}) path ({})",
reinterpret_cast<uintptr_t>(mount_),
mount_->getPath(),
wstringToString(path));
if (!winStore_.getAllEntries(path, list)) {
TRACE("File not found path ({})", wstringToString(path));
return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
}
auto [iterator, inserted] = enumSessions_.wlock()->emplace(
enumerationId,
make_unique<Enumerator>(
enumerationId, std::move(path), std::move(list)));
DCHECK(inserted);
return S_OK;
} catch (const std::exception& ex) {
return exceptionToHResult();
}
}
void EdenDispatcher::endEnumeration(const GUID& enumerationId) noexcept {
try {
auto erasedCount = enumSessions_.wlock()->erase(enumerationId);
DCHECK(erasedCount == 1);
} catch (const std::exception& ex) {
// Don't need to return result here - exceptionToHResult() will log the
// error.
(void)exceptionToHResult();
}
}
HRESULT EdenDispatcher::getEnumerationData(
const PRJ_CALLBACK_DATA& callbackData,
const GUID& enumerationId,
PCWSTR searchExpression,
PRJ_DIR_ENTRY_BUFFER_HANDLE bufferHandle) noexcept {
try {
//
// Error if we don't have the session.
//
auto lockedSessions = enumSessions_.rlock();
auto sessionIterator = lockedSessions->find(enumerationId);
if (sessionIterator == lockedSessions->end()) {
XLOG(DBG5) << "Enum instance not found: "
<< wstringToString(callbackData.FilePathName);
return HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER);
}
auto shouldRestart =
bool(callbackData.Flags & PRJ_CB_DATA_FLAG_ENUM_RESTART_SCAN);
auto& session = sessionIterator->second;
if (session->isSearchExpressionEmpty() || shouldRestart) {
if (searchExpression != nullptr) {
session->saveExpression(searchExpression);
} else {
session->saveExpression(L"*");
}
}
if (shouldRestart) {
session->restart();
}
//
// Traverse the list enumeration list and fill the remaining entry. Start
// from where the last call left off.
//
for (const FileMetadata* entry; (entry = session->current());
session->advance()) {
auto fileInfo = PRJ_FILE_BASIC_INFO();
fileInfo.IsDirectory = entry->isDirectory;
fileInfo.FileSize = entry->size;
TRACE(
"Enum {} {} size= {}",
wstringToString(entry->name),
fileInfo.IsDirectory ? "Dir" : "File",
fileInfo.FileSize);
if (S_OK !=
PrjFillDirEntryBuffer(entry->name.c_str(), &fileInfo, bufferHandle)) {
// We are out of buffer space. This entry didn't make it. Return without
// increment.
return S_OK;
}
}
return S_OK;
} catch (const std::exception& ex) {
return exceptionToHResult();
}
}
HRESULT
EdenDispatcher::getFileInfo(const PRJ_CALLBACK_DATA& callbackData) noexcept {
try {
PRJ_PLACEHOLDER_INFO placeholderInfo = {};
const wstring path{callbackData.FilePathName};
FileMetadata metadata = {};
if (!winStore_.getFileMetadata(path, metadata)) {
TRACE("{} : File not Found", wstringToString(path));
return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
}
TRACE(
"Found {} {} size= {}",
wstringToString(metadata.name),
metadata.isDirectory ? "Dir" : "File",
metadata.size);
placeholderInfo.FileBasicInfo.IsDirectory = metadata.isDirectory;
placeholderInfo.FileBasicInfo.FileSize = metadata.size;
//
// Don't use "metadata.name.c_str()" for the second argument in
// PrjWritePlaceholderInfo. That seems to throw internal error for FS create
// operation.
//
HRESULT result = PrjWritePlaceholderInfo(
callbackData.NamespaceVirtualizationContext,
callbackData.FilePathName,
&placeholderInfo,
sizeof(placeholderInfo));
if (FAILED(result)) {
XLOGF(
DBG2,
"Failed to send the file info. file {} error {} msg {}",
wstringToString(path),
result,
win32ErrorToString(result));
}
return result;
} catch (const std::exception& ex) {
return exceptionToHResult();
}
}
static uint64_t BlockAlignTruncate(uint64_t ptr, uint32_t alignment) {
return ((ptr) & (0 - (static_cast<uint64_t>(alignment))));
}
HRESULT
EdenDispatcher::getFileData(
const PRJ_CALLBACK_DATA& callbackData,
uint64_t byteOffset,
uint32_t length) noexcept {
try {
//
// We should return file data which is smaller than
// our kMaxChunkSize and meets the memory alignment requirements
// of the virtualization instance's storage device.
//
auto blob = winStore_.getBlob(callbackData.FilePathName);
if (!blob) {
return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
}
const folly::IOBuf& iobuf = blob->getContents();
//
// Assuming that it will not be a chain of IOBUFs.
// TODO: The following assert fails - need to dig more into IOBuf.
// assert(iobuf.next() == nullptr);
if (iobuf.length() <= kMinChunkSize) {
//
// If the file is small - copy the whole file in one shot.
//
return readSingleFileChunk(
callbackData.NamespaceVirtualizationContext,
callbackData.DataStreamId,
iobuf,
/*startOffset=*/0,
/*writeLength=*/iobuf.length());
} else if (length <= kMaxChunkSize) {
//
// If the request is with in our kMaxChunkSize - copy the entire request.
//
return readSingleFileChunk(
callbackData.NamespaceVirtualizationContext,
callbackData.DataStreamId,
iobuf,
/*startOffset=*/byteOffset,
/*writeLength=*/length);
} else {
//
// When the request is larger than kMaxChunkSize we split the
// request into multiple chunks.
//
PRJ_VIRTUALIZATION_INSTANCE_INFO instanceInfo;
HRESULT result = PrjGetVirtualizationInstanceInfo(
callbackData.NamespaceVirtualizationContext, &instanceInfo);
if (FAILED(result)) {
return result;
}
uint64_t startOffset = byteOffset;
uint64_t endOffset = BlockAlignTruncate(
startOffset + kMaxChunkSize, instanceInfo.WriteAlignment);
DCHECK(endOffset > 0);
DCHECK(endOffset > startOffset);
uint32_t chunkSize = endOffset - startOffset;
return readMultipleFileChunks(
callbackData.NamespaceVirtualizationContext,
callbackData.DataStreamId,
iobuf,
/*startOffset=*/startOffset,
/*length=*/length,
/*chunkSize=*/chunkSize);
}
} catch (const std::exception& ex) {
return exceptionToHResult();
}
}
HRESULT
EdenDispatcher::readSingleFileChunk(
PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT namespaceVirtualizationContext,
const GUID& dataStreamId,
const folly::IOBuf& iobuf,
uint64_t startOffset,
uint32_t length) {
return readMultipleFileChunks(
namespaceVirtualizationContext,
dataStreamId,
iobuf,
/*startOffset=*/startOffset,
/*length=*/length,
/*writeLength=*/length);
}
HRESULT
EdenDispatcher::readMultipleFileChunks(
PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT namespaceVirtualizationContext,
const GUID& dataStreamId,
const folly::IOBuf& iobuf,
uint64_t startOffset,
uint32_t length,
uint32_t chunkSize) {
HRESULT result;
std::unique_ptr<void, PrjAlignedBufferDeleter> writeBuffer{
PrjAllocateAlignedBuffer(namespaceVirtualizationContext, chunkSize)};
if (writeBuffer.get() == nullptr) {
return E_OUTOFMEMORY;
}
uint32_t remainingLength = length;
while (remainingLength > 0) {
uint32_t copySize = std::min(remainingLength, chunkSize);
//
// TODO(puneetk): Once backing store has the support for chunking the file
// contents, we can read the chunks of large files here and then write
// them to FS.
//
// TODO(puneetk): Build an interface to backing store so that we can pass
// the aligned buffer to avoid coping here.
//
RtlCopyMemory(writeBuffer.get(), iobuf.data() + startOffset, copySize);
// Write the data to the file in the local file system.
result = PrjWriteFileData(
namespaceVirtualizationContext,
&dataStreamId,
writeBuffer.get(),
startOffset,
copySize);
if (FAILED(result)) {
return result;
}
remainingLength -= copySize;
startOffset += copySize;
}
return S_OK;
}
} // namespace eden
} // namespace facebook
| 29.662921 | 80 | 0.665246 | jmswen |
0c8b5808bcb5b95335ee6beb8f70aa6f8caa3acb | 713 | cpp | C++ | src/ast/InterfaceMethodDeclaration.cpp | skylang/sky | 518add25e6a101ca2701b3c6bea977b0e76b340e | [
"MIT"
] | 3 | 2020-07-17T05:10:56.000Z | 2020-08-02T22:13:50.000Z | src/ast/InterfaceMethodDeclaration.cpp | skylang/sky | 518add25e6a101ca2701b3c6bea977b0e76b340e | [
"MIT"
] | null | null | null | src/ast/InterfaceMethodDeclaration.cpp | skylang/sky | 518add25e6a101ca2701b3c6bea977b0e76b340e | [
"MIT"
] | null | null | null | // Copyright (c) 2018 Stephan Unverwerth
// This code is licensed under MIT license (See LICENSE for details)
#include "InterfaceMethodDeclaration.h"
#include "Parameter.h"
#include "Expression.h"
#include <sstream>
namespace Sky {
std::string InterfaceMethodDeclaration::getDescription() {
std::stringstream sstr;
sstr << "function " << name << "(";
for (auto& param: parameters) {
if (param != parameters.front()) {
sstr << ", ";
}
sstr << param->name << ": " << param->declarationType->getFullName();
}
sstr << "): " << returnTypeExpression->typeValue->getFullName();
return sstr.str();
}
} | 29.708333 | 81 | 0.57784 | skylang |
0c8c08ffb1431cbb77df53ba81390bcefaa2d632 | 81,236 | cpp | C++ | third-party/casadi/casadi/interfaces/blocksqp/blocksqp.cpp | dbdxnuliba/mit-biomimetics_Cheetah | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | 8 | 2020-02-18T09:07:48.000Z | 2021-12-25T05:40:02.000Z | third-party/casadi/casadi/interfaces/blocksqp/blocksqp.cpp | geekfeiw/Cheetah-Software | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | null | null | null | third-party/casadi/casadi/interfaces/blocksqp/blocksqp.cpp | geekfeiw/Cheetah-Software | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | 13 | 2019-08-25T12:32:06.000Z | 2022-03-31T02:38:12.000Z | /*
* This file is part of CasADi.
*
* CasADi -- A symbolic framework for dynamic optimization.
* Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl,
* K.U. Leuven. All rights reserved.
* Copyright (C) 2011-2014 Greg Horn
*
* CasADi is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* CasADi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with CasADi; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "blocksqp.hpp"
#include "casadi/core/casadi_misc.hpp"
#include "casadi/core/conic.hpp"
using namespace std;
namespace casadi {
extern "C"
int CASADI_NLPSOL_BLOCKSQP_EXPORT
casadi_register_nlpsol_blocksqp(Nlpsol::Plugin* plugin) {
plugin->creator = Blocksqp::creator;
plugin->name = "blocksqp";
plugin->doc = Blocksqp::meta_doc.c_str();
plugin->version = CASADI_VERSION;
plugin->options = &Blocksqp::options_;
return 0;
}
extern "C"
void CASADI_NLPSOL_BLOCKSQP_EXPORT casadi_load_nlpsol_blocksqp() {
Nlpsol::registerPlugin(casadi_register_nlpsol_blocksqp);
}
Blocksqp::Blocksqp(const std::string& name, const Function& nlp)
: Nlpsol(name, nlp) {
}
Blocksqp::~Blocksqp() {
clear_mem();
}
Options Blocksqp::options_
= {{&Nlpsol::options_},
{{"qpsol",
{OT_STRING,
"The QP solver to be used by the SQP method"}},
{"qpsol_options",
{OT_DICT,
"Options to be passed to the QP solver"}},
{"linsol",
{OT_STRING,
"The linear solver to be used by the QP method"}},
{"print_header",
{OT_BOOL,
"Print solver header at startup"}},
{"print_iteration",
{OT_BOOL,
"Print SQP iterations"}},
{"eps",
{OT_DOUBLE,
"Values smaller than this are regarded as numerically zero"}},
{"opttol",
{OT_DOUBLE,
"Optimality tolerance"}},
{"nlinfeastol",
{OT_DOUBLE,
"Nonlinear feasibility tolerance"}},
{"schur",
{OT_BOOL,
"Use qpOASES Schur compliment approach"}},
{"globalization",
{OT_BOOL,
"Enable globalization"}},
{"restore_feas",
{OT_BOOL,
"Use feasibility restoration phase"}},
{"max_line_search",
{OT_INT,
"Maximum number of steps in line search"}},
{"max_consec_reduced_steps",
{OT_INT,
"Maximum number of consecutive reduced steps"}},
{"max_consec_skipped_updates",
{OT_INT,
"Maximum number of consecutive skipped updates"}},
{"max_iter",
{OT_INT,
"Maximum number of SQP iterations"}},
{"warmstart",
{OT_BOOL,
"Use warmstarting"}},
{"max_it_qp",
{OT_INT,
"Maximum number of QP iterations per SQP iteration"}},
{"block_hess",
{OT_INT,
"Blockwise Hessian approximation?"}},
{"hess_scaling",
{OT_INT,
"Scaling strategy for Hessian approximation"}},
{"fallback_scaling",
{OT_INT,
"If indefinite update is used, the type of fallback strategy"}},
{"max_time_qp",
{OT_DOUBLE,
"Maximum number of time in seconds per QP solve per SQP iteration"}},
{"ini_hess_diag",
{OT_DOUBLE,
"Initial Hessian guess: diagonal matrix diag(iniHessDiag)"}},
{"col_eps",
{OT_DOUBLE,
"Epsilon for COL scaling strategy"}},
{"col_tau1",
{OT_DOUBLE,
"tau1 for COL scaling strategy"}},
{"col_tau2",
{OT_DOUBLE,
"tau2 for COL scaling strategy"}},
{"hess_damp",
{OT_INT,
"Activate Powell damping for BFGS"}},
{"hess_damp_fac",
{OT_DOUBLE,
"Damping factor for BFGS Powell modification"}},
{"hess_update",
{OT_INT,
"Type of Hessian approximation"}},
{"fallback_update",
{OT_INT,
"If indefinite update is used, the type of fallback strategy"}},
{"hess_lim_mem",
{OT_INT,
"Full or limited memory"}},
{"hess_memsize",
{OT_INT,
"Memory size for L-BFGS updates"}},
{"which_second_derv",
{OT_INT,
"For which block should second derivatives be provided by the user"}},
{"skip_first_globalization",
{OT_BOOL,
"No globalization strategy in first iteration"}},
{"conv_strategy",
{OT_INT,
"Convexification strategy"}},
{"max_conv_qp",
{OT_INT,
"How many additional QPs may be solved for convexification per iteration?"}},
{"max_soc_iter",
{OT_INT,
"Maximum number of SOC line search iterations"}},
{"gamma_theta",
{OT_DOUBLE,
"Filter line search parameter, cf. IPOPT paper"}},
{"gamma_f",
{OT_DOUBLE,
"Filter line search parameter, cf. IPOPT paper"}},
{"kappa_soc",
{OT_DOUBLE,
"Filter line search parameter, cf. IPOPT paper"}},
{"kappa_f",
{OT_DOUBLE,
"Filter line search parameter, cf. IPOPT paper"}},
{"theta_max",
{OT_DOUBLE,
"Filter line search parameter, cf. IPOPT paper"}},
{"theta_min",
{OT_DOUBLE,
"Filter line search parameter, cf. IPOPT paper"}},
{"delta",
{OT_DOUBLE,
"Filter line search parameter, cf. IPOPT paper"}},
{"s_theta",
{OT_DOUBLE,
"Filter line search parameter, cf. IPOPT paper"}},
{"s_f",
{OT_DOUBLE,
"Filter line search parameter, cf. IPOPT paper"}},
{"kappa_minus",
{OT_DOUBLE,
"Filter line search parameter, cf. IPOPT paper"}},
{"kappa_plus",
{OT_DOUBLE,
"Filter line search parameter, cf. IPOPT paper"}},
{"kappa_plus_max",
{OT_DOUBLE,
"Filter line search parameter, cf. IPOPT paper"}},
{"delta_h0",
{OT_DOUBLE,
"Filter line search parameter, cf. IPOPT paper"}},
{"eta",
{OT_DOUBLE,
"Filter line search parameter, cf. IPOPT paper"}},
{"obj_lo",
{OT_DOUBLE,
"Lower bound on objective function [-inf]"}},
{"obj_up",
{OT_DOUBLE,
"Upper bound on objective function [inf]"}}
}
};
void Blocksqp::init(const Dict& opts) {
// Call the init method of the base class
Nlpsol::init(opts);
// Set default options
//string qpsol_plugin = "qpoases";
//Dict qpsol_options;
linsol_plugin_ = "ma27";
print_header_ = true;
print_iteration_ = true;
eps_ = 1.0e-16;
opttol_ = 1.0e-6;
nlinfeastol_ = 1.0e-6;
schur_ = true;
globalization_ = true;
restore_feas_ = true;
max_line_search_ = 20;
max_consec_reduced_steps_ = 100;
max_consec_skipped_updates_ = 100;
max_iter_ = 100;
warmstart_ = false;
max_it_qp_ = 5000;
block_hess_ = true;
hess_scaling_ = 2;
fallback_scaling_ = 4;
max_time_qp_ = 10000.0;
ini_hess_diag_ = 1.0;
col_eps_ = 0.1;
col_tau1_ = 0.5;
col_tau2_ = 1.0e4;
hess_damp_ = 1;
hess_damp_fac_ = 0.2;
hess_update_ = 1;
fallback_update_ = 2;
hess_lim_mem_ = 1;
hess_memsize_ = 20;
which_second_derv_ = 0;
skip_first_globalization_ = false;
conv_strategy_ = 0;
max_conv_qp_ = 1;
max_soc_iter_ = 3;
gamma_theta_ = 1.0e-5;
gamma_f_ = 1.0e-5;
kappa_soc_ = 0.99;
kappa_f_ = 0.999;
theta_max_ = 1.0e7;
theta_min_ = 1.0e-5;
delta_ = 1.0;
s_theta_ = 1.1;
s_f_ = 2.3;
kappa_minus_ = 0.333;
kappa_plus_ = 8.0;
kappa_plus_max_ = 100.0;
delta_h0_ = 1.0e-4;
eta_ = 1.0e-4;
obj_lo_ = -inf;
obj_up_ = inf;
// Read user options
for (auto&& op : opts) {
if (op.first=="qpsol") {
//qpsol_plugin = op.second.to_string();
casadi_warning("Option 'qpsol' currently not supported, ignored");
} else if (op.first=="qpsol_options") {
//qpsol_options = op.second;
casadi_warning("Option 'qpsol_options' currently not supported, ignored");
} else if (op.first=="linsol") {
linsol_plugin_ = string(op.second);
} else if (op.first=="print_header") {
print_header_ = op.second;
} else if (op.first=="print_iteration") {
print_iteration_ = op.second;
} else if (op.first=="eps") {
eps_ = op.second;
} else if (op.first=="opttol") {
opttol_ = op.second;
} else if (op.first=="nlinfeastol") {
nlinfeastol_ = op.second;
} else if (op.first=="schur") {
schur_ = op.second;
} else if (op.first=="globalization") {
globalization_ = op.second;
} else if (op.first=="restore_feas") {
restore_feas_ = op.second;
} else if (op.first=="max_line_search") {
max_line_search_ = op.second;
} else if (op.first=="max_consec_reduced_steps") {
max_consec_reduced_steps_ = op.second;
} else if (op.first=="max_consec_skipped_updates") {
max_consec_skipped_updates_ = op.second;
} else if (op.first=="max_iter") {
max_iter_ = op.second;
} else if (op.first=="warmstart") {
warmstart_ = op.second;
} else if (op.first=="max_it_qp") {
max_it_qp_ = op.second;
} else if (op.first=="block_hess") {
block_hess_ = op.second;
} else if (op.first=="hess_scaling") {
hess_scaling_ = op.second;
} else if (op.first=="fallback_scaling") {
fallback_scaling_ = op.second;
} else if (op.first=="max_time_qp") {
max_time_qp_ = op.second;
} else if (op.first=="ini_hess_diag") {
ini_hess_diag_ = op.second;
} else if (op.first=="col_eps") {
col_eps_ = op.second;
} else if (op.first=="col_tau1") {
col_tau1_ = op.second;
} else if (op.first=="col_tau2") {
col_tau2_ = op.second;
} else if (op.first=="hess_damp") {
hess_damp_ = op.second;
} else if (op.first=="hess_damp_fac") {
hess_damp_fac_ = op.second;
} else if (op.first=="hess_update") {
hess_update_ = op.second;
} else if (op.first=="fallback_update") {
fallback_update_ = op.second;
} else if (op.first=="hess_lim_mem") {
hess_lim_mem_ = op.second;
} else if (op.first=="hess_memsize") {
hess_memsize_ = op.second;
} else if (op.first=="which_second_derv") {
which_second_derv_ = op.second;
} else if (op.first=="skip_first_globalization") {
skip_first_globalization_ = op.second;
} else if (op.first=="conv_strategy") {
conv_strategy_ = op.second;
} else if (op.first=="max_conv_qp") {
max_conv_qp_ = op.second;
} else if (op.first=="max_soc_iter") {
max_soc_iter_ = op.second;
} else if (op.first=="gamma_theta") {
gamma_theta_ = op.second;
} else if (op.first=="gamma_f") {
gamma_f_ = op.second;
} else if (op.first=="kappa_soc") {
kappa_soc_ = op.second;
} else if (op.first=="kappa_f") {
kappa_f_ = op.second;
} else if (op.first=="theta_max") {
theta_max_ = op.second;
} else if (op.first=="theta_min") {
theta_min_ = op.second;
} else if (op.first=="delta") {
delta_ = op.second;
} else if (op.first=="s_theta") {
s_theta_ = op.second;
} else if (op.first=="s_f") {
s_f_ = op.second;
} else if (op.first=="kappa_minus") {
kappa_minus_ = op.second;
} else if (op.first=="kappa_plus") {
kappa_plus_ = op.second;
} else if (op.first=="kappa_plus_max") {
kappa_plus_max_ = op.second;
} else if (op.first=="delta_h0") {
delta_h0_ = op.second;
} else if (op.first=="eta") {
eta_ = op.second;
} else if (op.first=="obj_lo") {
obj_lo_ = op.second;
} else if (op.first=="obj_up") {
obj_up_ = op.second;
}
}
// If we compute second constraints derivatives switch to
// finite differences Hessian (convenience)
if (which_second_derv_ == 2) {
hess_update_ = 4;
block_hess_ = true;
}
// If we don't use limited memory BFGS we need to store only one vector.
if (!hess_lim_mem_) hess_memsize_ = 1;
if (!schur_ && hess_update_ == 1) {
print("***WARNING: SR1 update only works with qpOASES Schur complement version. "
"Using BFGS updates instead.\n");
hess_update_ = 2;
hess_scaling_ = fallback_scaling_;
}
// Setup NLP functions
create_function("nlp_fg", {"x", "p"}, {"f", "g"});
Function gf_jg = create_function("nlp_gf_jg", {"x", "p"},
{"f", "g", "grad:f:x", "jac:g:x"});
Asp_ = gf_jg.sparsity_out("jac_g_x");
if (!block_hess_) {
// No block-structured Hessian
blocks_ = {0, nx_};
which_second_derv_ = 0;
Hsp_ = Sparsity::dense(nx_, nx_);
} else {
// Detect block structure
// Get the sparsity pattern for the Hessian of the Lagrangian
Function grad_lag = oracle_.factory("grad_lag",
{"x", "p", "lam:f", "lam:g"}, {"grad:gamma:x"},
{{"gamma", {"f", "g"}}});
Hsp_ = grad_lag.sparsity_jac("x", "grad_gamma_x", false, true);
// Make sure diagonal exists
Hsp_ = Hsp_ + Sparsity::diag(nx_);
// Find the strongly connected components of the Hessian
// Unlike Sparsity::scc, assume ordered
const casadi_int* colind = Hsp_.colind();
const casadi_int* row = Hsp_.row();
blocks_.push_back(0);
casadi_int ind = 0;
while (ind < nx_) {
// Find the next cutoff
casadi_int next=ind+1;
while (ind<next && ind<nx_) {
for (casadi_int k=colind[ind]; k<colind[ind+1]; ++k) next = max(next, 1+row[k]);
ind++;
}
blocks_.push_back(next);
}
}
// Number of blocks
nblocks_ = blocks_.size()-1;
// Blocksizes
dim_.resize(nblocks_);
casadi_int max_size = 0;
nnz_H_ = 0;
for (casadi_int i=0; i<nblocks_; ++i) {
dim_[i] = blocks_[i+1]-blocks_[i];
max_size = max(max_size, dim_[i]);
nnz_H_ += dim_[i]*dim_[i];
}
if (verbose_) casadi_message(str(nblocks_) + " blocks of max size " + str(max_size) + ".");
// Allocate a QP solver
//casadi_assert(!qpsol_plugin.empty(), "'qpsol' option has not been set");
//qpsol_ = conic("qpsol", qpsol_plugin, {{"h", Hsp_}, {"a", Asp_}},
// qpsol_options);
//alloc(qpsol_);
// Allocate memory
alloc_w(Asp_.nnz(), true); // jac
alloc_w(nx_, true); // lam_xk
alloc_w(ng_, true); // lam_gk
alloc_w(ng_, true); // gk
alloc_w(nx_, true); // grad_fk
alloc_w(nx_, true); // grad_lagk
alloc_w(nx_+ng_, true); // lam_qp
alloc_w(nblocks_, true); // delta_norm
alloc_w(nblocks_, true); // delta_norm_old
alloc_w(nblocks_, true); // delta_gamma
alloc_w(nblocks_, true); // delta_gamma_old
alloc_w(nblocks_, true); // delta_h
alloc_w(nx_, true); // trial_xk
alloc_w(nx_, true); // lbx_qp
alloc_w(nx_, true); // ubx_qp
alloc_w(ng_, true); // lba_qp
alloc_w(ng_, true); // uba_qp
alloc_w(ng_, true); // jac_times_dxk
alloc_w(nx_*hess_memsize_, true); // deltaMat
alloc_w(nx_*hess_memsize_, true); // gammaMat
alloc_w(Asp_.nnz(), true); // jac_g
alloc_w(nnz_H_, true); // hess_lag
alloc_iw(nblocks_, true); // noUpdateCounter
// Allocate block diagonal Hessian(s)
casadi_int n_hess = hess_update_==1 || hess_update_==4 ? 2 : 1;
alloc_res(nblocks_*n_hess, true);
alloc_w(n_hess*nnz_H_, true);
alloc_iw(nnz_H_ + (nx_+1) + nx_, true); // hessIndRow
}
int Blocksqp::init_mem(void* mem) const {
if (Nlpsol::init_mem(mem)) return 1;
auto m = static_cast<BlocksqpMemory*>(mem);
// Create qpOASES memory
if (schur_) {
m->qpoases_mem = new QpoasesMemory();
m->qpoases_mem->linsol_plugin = linsol_plugin_;
}
m->colind.resize(Asp_.size2()+1);
m->row.resize(Asp_.nnz());
return 0;
}
void Blocksqp::set_work(void* mem, const double**& arg, double**& res,
casadi_int*& iw, double*& w) const {
auto m = static_cast<BlocksqpMemory*>(mem);
// Set work in base classes
Nlpsol::set_work(mem, arg, res, iw, w);
// Temporary memory
m->jac = w; w += Asp_.nnz();
m->lam_xk = w; w += nx_;
m->lam_gk = w; w += ng_;
m->gk = w; w += ng_;
m->grad_fk = w; w += nx_;
m->grad_lagk = w; w += nx_;
m->lam_qp = w; w += nx_+ng_;
m->delta_norm = w; w += nblocks_;
m->delta_norm_old = w; w += nblocks_;
m->delta_gamma = w; w += nblocks_;
m->delta_gamma_old = w; w += nblocks_;
m->delta_h = w; w += nblocks_;
m->trial_xk = w; w += nx_;
m->lbx_qp = w; w += nx_;
m->ubx_qp = w; w += nx_;
m->lba_qp = w; w += ng_;
m->uba_qp = w; w += ng_;
m->jac_times_dxk = w; w += ng_;
m->deltaMat = w; w += nx_*hess_memsize_;
m->gammaMat = w; w += nx_*hess_memsize_;
m->jac_g = w; w += Asp_.nnz();
m->hess_lag = w; w += nnz_H_;
m->hessIndRow = reinterpret_cast<int*>(iw); iw += nnz_H_ + (nx_+1) + nx_;
m->noUpdateCounter = iw; iw += nblocks_;
// First Hessian
m->hess1 = res; res += nblocks_;
for (casadi_int b=0; b<nblocks_; b++) {
m->hess1[b] = w; w += dim_[b]*dim_[b];
}
// Second Hessian, for SR1 or finite differences
if (hess_update_ == 1 || hess_update_ == 4) {
m->hess2 = res; res += nblocks_;
for (casadi_int b=0; b<nblocks_; b++) {
m->hess2[b] = w; w += dim_[b]*dim_[b];
}
} else {
m->hess2 = nullptr;
}
}
int Blocksqp::solve(void* mem) const {
auto m = static_cast<BlocksqpMemory*>(mem);
casadi_int ret = 0;
// Create problem evaluation object
vector<casadi_int> blocks = blocks_;
/*-------------------------------------------------*/
/* Create blockSQP method object and run algorithm */
/*-------------------------------------------------*/
m->itCount = 0;
m->qpItTotal = 0;
m->qpIterations = 0;
m->qpIterations2 = 0;
m->qpResolve = 0;
m->rejectedSR1 = 0;
m->hessSkipped = 0;
m->hessDamped = 0;
m->averageSizingFactor = 0.0;
m->nFunCalls = 0;
m->nDerCalls = 0;
m->nRestHeurCalls = 0;
m->nRestPhaseCalls = 0;
m->nTotalUpdates = 0;
m->nTotalSkippedUpdates = 0;
casadi_int maxblocksize = 1;
for (casadi_int k=0; k<nblocks_+1; k++) {
if (k > 0)
if (blocks_[k] - blocks_[k-1] > maxblocksize)
maxblocksize = blocks_[k] - blocks_[k-1];
}
if (hess_lim_mem_ && hess_memsize_ == 0)
const_cast<Blocksqp*>(this)->hess_memsize_ = maxblocksize;
// Reset the SQP metod
reset_sqp(m);
// Free existing memory, if any
if (m->qp) delete m->qp;
m->qp = nullptr;
if (schur_) {
m->qp = new qpOASES::SQProblemSchur(nx_, ng_, qpOASES::HST_UNKNOWN, 50,
m->qpoases_mem,
QpoasesInterface::qpoases_init,
QpoasesInterface::qpoases_sfact,
QpoasesInterface::qpoases_nfact,
QpoasesInterface::qpoases_solve);
} else {
m->qp = new qpOASES::SQProblem(nx_, ng_);
}
// Print header and information about the algorithmic parameters
if (print_header_) printInfo(m);
// Open output files
initStats(m);
initIterate(m);
// Initialize filter with pair (maxConstrViolation, objLowerBound)
initializeFilter(m);
// Primal-dual initial guess
casadi_copy(m->lam_x, nx_, m->lam_xk);
casadi_scal(nx_, -1., m->lam_xk);
casadi_copy(m->lam_g, ng_, m->lam_gk);
casadi_scal(ng_, -1., m->lam_gk);
casadi_copy(m->lam_xk, nx_, m->lam_qp);
casadi_copy(m->lam_gk, ng_, m->lam_qp+nx_);
ret = run(m, max_iter_, warmstart_);
m->success = ret==0;
if (ret==1) print("***WARNING: Maximum number of iterations reached\n");
// Get optimal cost
m->f = m->obj;
// Get constraints at solution
casadi_copy(m->gk, ng_, m->g);
// Get dual solution (simple bounds)
if (m->lam_x) {
casadi_copy(m->lam_xk, nx_, m->lam_x);
casadi_scal(nx_, -1., m->lam_x);
}
// Get dual solution (nonlinear bounds)
casadi_copy(m->lam_gk, ng_, m->lam_g);
casadi_scal(ng_, -1., m->lam_g);
return 0;
}
casadi_int Blocksqp::run(BlocksqpMemory* m, casadi_int maxIt, casadi_int warmStart) const {
casadi_int it, infoQP = 0;
bool skipLineSearch = false;
bool hasConverged = false;
if (warmStart == 0 || m->itCount == 0) {
// SQP iteration 0
/// Set initial Hessian approximation
calcInitialHessian(m);
/// Evaluate all functions and gradients for xk_0
(void)evaluate(m, &m->obj, m->gk, m->grad_fk, m->jac_g);
m->nDerCalls++;
/// Check if converged
hasConverged = calcOptTol(m);
if (print_iteration_) printProgress(m);
updateStats(m);
if (hasConverged) {
if (print_iteration_ && m->steptype < 2) {
print("\n***CONVERGENCE ACHIEVED!***\n");
}
return 0;
}
m->itCount++;
}
/*
* SQP Loop: during first iteration, m->itCount = 1
*/
for (it=0; it<maxIt; it++) {
/// Solve QP subproblem with qpOASES or QPOPT
updateStepBounds(m, 0);
infoQP = solveQP(m, m->dxk, m->lam_qp);
if (infoQP == 1) {
// 1.) Maximum number of iterations reached
print("***WARNING: Maximum number of QP iterations exceeded.***\n");
} else if (infoQP == 2 || infoQP > 3) {
// 2.) QP error (e.g., unbounded), solve again with pos.def. diagonal matrix (identity)
print("***WARNING: QP error. Solve again with identity matrix.***\n");
resetHessian(m);
infoQP = solveQP(m, m->dxk, m->lam_qp);
if (infoQP) {
// If there is still an error, terminate.
print("***WARNING: QP error. Stop.***\n");
return -1;
} else {
m->steptype = 1;
}
} else if (infoQP == 3) {
// 3.) QP infeasible, try to restore feasibility
bool qpError = true;
skipLineSearch = true; // don't do line search with restoration step
// Try to reduce constraint violation by heuristic
if (m->steptype < 2) {
print("***WARNING: QP infeasible. Trying to reduce constraint violation ...");
qpError = feasibilityRestorationHeuristic(m);
if (!qpError) {
m->steptype = 2;
print("Success.***\n");
} else {
print("Failure.***\n");
}
}
// Invoke feasibility restoration phase
//if (qpError && m->steptype < 3 && restore_feas_)
if (qpError && restore_feas_ && m->cNorm > 0.01 * nlinfeastol_) {
print("***Start feasibility restoration phase.***\n");
m->steptype = 3;
qpError = feasibilityRestorationPhase(m);
}
// If everything failed, abort.
if (qpError) {
print("***WARNING: QP error. Stop.\n");
return -1;
}
}
/// Determine steplength alpha
if (!globalization_ || (skip_first_globalization_ && m->itCount == 1)) {
// No globalization strategy, but reduce step if function cannot be evaluated
if (fullstep(m)) {
print("***WARNING: Constraint or objective could "
"not be evaluated at new point. Stop.***\n");
return -1;
}
m->steptype = 0;
} else if (globalization_ && !skipLineSearch) {
// Filter line search based on Waechter et al., 2006 (Ipopt paper)
if (filterLineSearch(m) || m->reducedStepCount > max_consec_reduced_steps_) {
// Filter line search did not produce a step. Now there are a few things we can try ...
bool lsError = true;
// Heuristic 1: Check if the full step reduces the KKT error by at
// least kappaF, if so, accept the step.
lsError = kktErrorReduction(m);
if (!lsError)
m->steptype = -1;
// Heuristic 2: Try to reduce constraint violation by closing
// continuity gaps to produce an admissable iterate
if (lsError && m->cNorm > 0.01 * nlinfeastol_ && m->steptype < 2) {
// Don't do this twice in a row!
print("***WARNING: Steplength too short. "
"Trying to reduce constraint violation...");
// Integration over whole time interval
lsError = feasibilityRestorationHeuristic(m);
if (!lsError) {
m->steptype = 2;
print("Success.***\n");
} else {
print("***WARNING: Failed.***\n");
}
}
// Heuristic 3: Recompute step with a diagonal Hessian
if (lsError && m->steptype != 1 && m->steptype != 2) {
// After closing continuity gaps, we already take a step with initial Hessian.
// If this step is not accepted then this will cause an infinite loop!
print("***WARNING: Steplength too short. "
"Trying to find a new step with identity Hessian.***\n");
m->steptype = 1;
resetHessian(m);
continue;
}
// If this does not yield a successful step, start restoration phase
if (lsError && m->cNorm > 0.01 * nlinfeastol_ && restore_feas_) {
print("***WARNING: Steplength too short. "
"Start feasibility restoration phase.***\n");
m->steptype = 3;
// Solve NLP with minimum norm objective
lsError = feasibilityRestorationPhase(m);
}
// If everything failed, abort.
if (lsError) {
print("***WARNING: Line search error. Stop.***\n");
return -1;
}
} else {
m->steptype = 0;
}
}
/// Calculate "old" Lagrange gradient: gamma = dL(xi_k, lambda_k+1)
calcLagrangeGradient(m, m->gamma, 0);
/// Evaluate functions and gradients at the new xk
(void)evaluate(m, &m->obj, m->gk, m->grad_fk, m->jac_g);
m->nDerCalls++;
/// Check if converged
hasConverged = calcOptTol(m);
/// Print one line of output for the current iteration
if (print_iteration_) printProgress(m);
updateStats(m);
if (hasConverged && m->steptype < 2) {
if (print_iteration_) print("\n***CONVERGENCE ACHIEVED!***\n");
m->itCount++;
return 0; //Convergence achieved!
}
/// Calculate difference of old and new Lagrange gradient:
// gamma = -gamma + dL(xi_k+1, lambda_k+1)
calcLagrangeGradient(m, m->gamma, 1);
/// Revise Hessian approximation
if (hess_update_ < 4 && !hess_lim_mem_) {
calcHessianUpdate(m, hess_update_, hess_scaling_);
} else if (hess_update_ < 4 && hess_lim_mem_) {
calcHessianUpdateLimitedMemory(m, hess_update_, hess_scaling_);
} else if (hess_update_ == 4) {
casadi_error("Not implemented");
}
// If limited memory updates are used, set pointers deltaXi and
// gamma to the next column in deltaMat and gammaMat
updateDeltaGamma(m);
m->itCount++;
skipLineSearch = false;
}
return 1;
}
/**
* Compute gradient of Lagrangian or difference of Lagrangian gradients (sparse version)
*
* flag == 0: output dL(xk, lambda)
* flag == 1: output dL(xi_k+1, lambda_k+1) - L(xi_k, lambda_k+1)
* flag == 2: output dL(xi_k+1, lambda_k+1) - df(xi)
*/
void Blocksqp::
calcLagrangeGradient(BlocksqpMemory* m,
const double* lam_x, const double* lam_g,
const double* grad_f, double *jacNz,
double* grad_lag, casadi_int flag) const {
// Objective gradient
if (flag == 0) {
casadi_copy(grad_f, nx_, grad_lag);
} else if (flag == 1) {
casadi_scal(nx_, -1., grad_lag);
casadi_axpy(nx_, 1., grad_f, grad_lag);
} else {
casadi_fill(grad_lag, nx_, 0.);
}
// - lambdaT * constrJac
const casadi_int* jacIndRow = Asp_.row();
const casadi_int* jacIndCol = Asp_.colind();
for (casadi_int iVar=0; iVar<nx_; iVar++) {
for (casadi_int iCon=jacIndCol[iVar]; iCon<jacIndCol[iVar+1]; iCon++) {
grad_lag[iVar] -= lam_g[jacIndRow[iCon]] * jacNz[iCon];
}
}
// - lambdaT * simpleBounds
casadi_axpy(nx_, -1., lam_x, grad_lag);
}
/**
* Wrapper if called with standard arguments
*/
void Blocksqp::
calcLagrangeGradient(BlocksqpMemory* m, double* grad_lag, casadi_int flag) const {
calcLagrangeGradient(m, m->lam_xk, m->lam_gk, m->grad_fk, m->jac_g,
grad_lag, flag);
}
/**
* Compute optimality conditions:
* ||grad_lag(xk,lambda)||_infty / (1 + ||lambda||_infty) <= TOL
* and
* ||constrViolation||_infty / (1 + ||xi||_infty) <= TOL
*/
bool Blocksqp::calcOptTol(BlocksqpMemory* m) const {
// scaled norm of Lagrangian gradient
calcLagrangeGradient(m, m->grad_lagk, 0);
m->gradNorm = casadi_norm_inf(nx_, m->grad_lagk);
m->tol = m->gradNorm/(1.0+fmax(casadi_norm_inf(nx_, m->lam_xk),
casadi_norm_inf(ng_, m->lam_gk)));
// norm of constraint violation
m->cNorm = lInfConstraintNorm(m, m->x, m->gk);
m->cNormS = m->cNorm /(1.0 + casadi_norm_inf(nx_, m->x));
if (m->tol <= opttol_ && m->cNormS <= nlinfeastol_)
return true;
else
return false;
}
void Blocksqp::printInfo(BlocksqpMemory* m) const {
char hessString1[100];
char hessString2[100];
char globString[100];
char qpString[100];
/* QP Solver */
if (schur_)
strcpy(qpString, "sparse, Schur complement approach");
else
strcpy(qpString, "sparse, reduced Hessian factorization");
/* Globalization */
if (globalization_) {
strcpy(globString, "filter line search");
} else {
strcpy(globString, "none (full step)");
}
/* Hessian approximation */
if (block_hess_ && (hess_update_ == 1 || hess_update_ == 2))
strcpy(hessString1, "block ");
else
strcpy(hessString1, "");
if (hess_lim_mem_ && (hess_update_ == 1 || hess_update_ == 2))
strcat(hessString1, "L-");
/* Fallback Hessian */
if (hess_update_ == 1 || hess_update_ == 4
|| (hess_update_ == 2 && !hess_damp_)) {
strcpy(hessString2, hessString1);
/* Fallback Hessian update type */
if (fallback_update_ == 0) {
strcat(hessString2, "Id");
} else if (fallback_update_ == 1) {
strcat(hessString2, "SR1");
} else if (fallback_update_ == 2) {
strcat(hessString2, "BFGS");
} else if (fallback_update_ == 4) {
strcat(hessString2, "Finite differences");
}
/* Fallback Hessian scaling */
if (fallback_scaling_ == 1) {
strcat(hessString2, ", SP");
} else if (fallback_scaling_ == 2) {
strcat(hessString2, ", OL");
} else if (fallback_scaling_ == 3) {
strcat(hessString2, ", mean");
} else if (fallback_scaling_ == 4) {
strcat(hessString2, ", selective sizing");
}
} else {
strcpy(hessString2, "-");
}
/* First Hessian update type */
if (hess_update_ == 0) {
strcat(hessString1, "Id");
} else if (hess_update_ == 1) {
strcat(hessString1, "SR1");
} else if (hess_update_ == 2) {
strcat(hessString1, "BFGS");
} else if (hess_update_ == 4) {
strcat(hessString1, "Finite differences");
}
/* First Hessian scaling */
if (hess_scaling_ == 1) {
strcat(hessString1, ", SP");
} else if (hess_scaling_ == 2) {
strcat(hessString1, ", OL");
} else if (hess_scaling_ == 3) {
strcat(hessString1, ", mean");
} else if (hess_scaling_ == 4) {
strcat(hessString1, ", selective sizing");
}
print("\n+---------------------------------------------------------------+\n");
print("| Starting blockSQP with the following algorithmic settings: |\n");
print("+---------------------------------------------------------------+\n");
print("| qpOASES flavor | %-34s|\n", qpString);
print("| Globalization | %-34s|\n", globString);
print("| 1st Hessian approximation | %-34s|\n", hessString1);
print("| 2nd Hessian approximation | %-34s|\n", hessString2);
print("+---------------------------------------------------------------+\n\n");
}
void Blocksqp::
acceptStep(BlocksqpMemory* m, double alpha) const {
acceptStep(m, m->dxk, m->lam_qp, alpha, 0);
}
void Blocksqp::
acceptStep(BlocksqpMemory* m, const double* deltaXi,
const double* lambdaQP, double alpha, casadi_int nSOCS) const {
double lStpNorm;
// Current alpha
m->alpha = alpha;
m->nSOCS = nSOCS;
// Set new x by accepting the current trial step
for (casadi_int k=0; k<nx_; k++) {
m->x[k] = m->trial_xk[k];
m->dxk[k] = alpha * deltaXi[k];
}
// Store the infinity norm of the multiplier step
m->lambdaStepNorm = 0.0;
for (casadi_int k=0; k<nx_; k++)
if ((lStpNorm = fabs(alpha*lambdaQP[k] - alpha*m->lam_xk[k])) > m->lambdaStepNorm)
m->lambdaStepNorm = lStpNorm;
for (casadi_int k=0; k<ng_; k++)
if ((lStpNorm = fabs(alpha*lambdaQP[nx_+k] - alpha*m->lam_gk[k])) > m->lambdaStepNorm)
m->lambdaStepNorm = lStpNorm;
// Set new multipliers
for (casadi_int k=0; k<nx_; k++)
m->lam_xk[k] = (1.0 - alpha)*m->lam_xk[k] + alpha*lambdaQP[k];
for (casadi_int k=0; k<ng_; k++)
m->lam_gk[k] = (1.0 - alpha)*m->lam_gk[k] + alpha*lambdaQP[nx_+k];
// Count consecutive reduced steps
if (m->alpha < 1.0)
m->reducedStepCount++;
else
m->reducedStepCount = 0;
}
void Blocksqp::
reduceStepsize(BlocksqpMemory* m, double *alpha) const {
*alpha = (*alpha) * 0.5;
}
void Blocksqp::
reduceSOCStepsize(BlocksqpMemory* m, double *alphaSOC) const {
// Update bounds on linearized constraints for the next SOC QP:
// That is different from the update for the first SOC QP!
for (casadi_int i=0; i<ng_; i++) {
double lbg = m->lbg ? m->lbg[i] : 0;
double ubg = m->ubg ? m->ubg[i] : 0;
if (lbg != inf) {
m->lba_qp[i] = *alphaSOC * m->lba_qp[i] - m->gk[i];
} else {
m->lba_qp[i] = inf;
}
if (ubg != inf) {
m->uba_qp[i] = *alphaSOC * m->uba_qp[i] - m->gk[i];
} else {
m->uba_qp[i] = inf;
}
}
*alphaSOC *= 0.5;
}
/**
* Take a full Quasi-Newton step, except when integrator fails:
* xk = xk + deltaXi
* lambda = lambdaQP
*/
casadi_int Blocksqp::fullstep(BlocksqpMemory* m) const {
double alpha;
double objTrial, cNormTrial;
// Backtracking line search
alpha = 1.0;
for (casadi_int k=0; k<10; k++) {
// Compute new trial point
for (casadi_int i=0; i<nx_; i++)
m->trial_xk[i] = m->x[i] + alpha * m->dxk[i];
// Compute problem functions at trial point
casadi_int info = evaluate(m, m->trial_xk, &objTrial, m->gk);
m->nFunCalls++;
cNormTrial = lInfConstraintNorm(m, m->trial_xk, m->gk);
// Reduce step if evaluation fails, if lower bound is violated
// or if objective or a constraint is NaN
if (info != 0 || objTrial < obj_lo_ || objTrial > obj_up_
|| !(objTrial == objTrial) || !(cNormTrial == cNormTrial)) {
print("info=%i, objTrial=%g\n", info, objTrial);
// evaluation error, reduce stepsize
reduceStepsize(m, &alpha);
continue;
} else {
acceptStep(m, alpha);
return 0;
}
}
return 1;
}
/**
*
* Backtracking line search based on a filter
* as described in Ipopt paper (Waechter 2006)
*
*/
casadi_int Blocksqp::filterLineSearch(BlocksqpMemory* m) const {
double alpha = 1.0;
double cNormTrial=0, objTrial, dfTdeltaXi=0;
// Compute ||constr(xi)|| at old point
double cNorm = lInfConstraintNorm(m, m->x, m->gk);
// Backtracking line search
casadi_int k;
for (k=0; k<max_line_search_; k++) {
// Compute new trial point
for (casadi_int i=0; i<nx_; i++)
m->trial_xk[i] = m->x[i] + alpha * m->dxk[i];
// Compute grad(f)^T * deltaXi
dfTdeltaXi = 0.0;
for (casadi_int i=0; i<nx_; i++)
dfTdeltaXi += m->grad_fk[i] * m->dxk[i];
// Compute objective and at ||constr(trial_xk)||_1 at trial point
casadi_int info = evaluate(m, m->trial_xk, &objTrial, m->gk);
m->nFunCalls++;
cNormTrial = lInfConstraintNorm(m, m->trial_xk, m->gk);
// Reduce step if evaluation fails, if lower bound is violated or if objective is NaN
if (info != 0 || objTrial < obj_lo_ || objTrial > obj_up_
|| !(objTrial == objTrial) || !(cNormTrial == cNormTrial)) {
// evaluation error, reduce stepsize
reduceStepsize(m, &alpha);
continue;
}
// Check acceptability to the filter
if (pairInFilter(m, cNormTrial, objTrial)) {
// Trial point is in the prohibited region defined by
// the filter, try second order correction
if (secondOrderCorrection(m, cNorm, cNormTrial, dfTdeltaXi, 0, k)) {
break; // SOC yielded suitable alpha, stop
} else {
reduceStepsize(m, &alpha);
continue;
}
}
// Check sufficient decrease, case I:
// If we are (almost) feasible and a "switching condition" is satisfied
// require sufficient progress in the objective instead of bi-objective condition
if (cNorm <= theta_min_) {
// Switching condition, part 1: grad(f)^T * deltaXi < 0 ?
if (dfTdeltaXi < 0)
// Switching condition, part 2: alpha * (- grad(f)^T * deltaXi)**sF
// > delta * cNorm**sTheta ?
if (alpha * pow((-dfTdeltaXi), s_f_)
> delta_ * pow(cNorm, s_theta_)) {
// Switching conditions hold: Require satisfaction of Armijo condition for objective
if (objTrial > m->obj + eta_*alpha*dfTdeltaXi) {
// Armijo condition violated, try second order correction
if (secondOrderCorrection(m, cNorm, cNormTrial, dfTdeltaXi, 1, k)) {
break; // SOC yielded suitable alpha, stop
} else {
reduceStepsize(m, &alpha);
continue;
}
} else {
// found suitable alpha, stop
acceptStep(m, alpha);
break;
}
}
}
// Check sufficient decrease, case II:
// Bi-objective (filter) condition
if (cNormTrial < (1.0 - gamma_theta_) * cNorm
|| objTrial < m->obj - gamma_f_ * cNorm) {
// found suitable alpha, stop
acceptStep(m, alpha);
break;
} else {
// Trial point is dominated by current point, try second order correction
if (secondOrderCorrection(m, cNorm, cNormTrial, dfTdeltaXi, 0, k)) {
break; // SOC yielded suitable alpha, stop
} else {
reduceStepsize(m, &alpha);
continue;
}
}
}
// No step could be found by the line search
if (k == max_line_search_) return 1;
// Augment the filter if switching condition or Armijo condition does not hold
if (dfTdeltaXi >= 0) {
augmentFilter(m, cNormTrial, objTrial);
} else if (alpha * pow((-dfTdeltaXi), s_f_) > delta_ * pow(cNorm, s_theta_)) {
// careful with neg. exponents!
augmentFilter(m, cNormTrial, objTrial);
} else if (objTrial <= m->obj + eta_*alpha*dfTdeltaXi) {
augmentFilter(m, cNormTrial, objTrial);
}
return 0;
}
/**
*
* Perform a second order correction step, i.e. solve the QP:
*
* min_d d^TBd + d^T grad_fk
* s.t. bl <= A^Td + constr(xi+alpha*deltaXi) - A^TdeltaXi <= bu
*
*/
bool Blocksqp::
secondOrderCorrection(BlocksqpMemory* m, double cNorm, double cNormTrial,
double dfTdeltaXi, bool swCond, casadi_int it) const {
// Perform SOC only on the first iteration of backtracking line search
if (it > 0) return false;
// If constraint violation of the trialstep is lower than the current one skip SOC
if (cNormTrial < cNorm) return false;
casadi_int nSOCS = 0;
double cNormTrialSOC, cNormOld, objTrialSOC;
// m->gk contains result at first trial point: c(xi+deltaXi)
// m->jac_times_dxk and m->grad_fk are unchanged so far.
// First SOC step
std::vector<double> deltaXiSOC(nx_, 0.);
std::vector<double> lambdaQPSOC(nx_+ng_, 0.);
// Second order correction loop
cNormOld = cNorm;
for (casadi_int k=0; k<max_soc_iter_; k++) {
nSOCS++;
// Update bounds for SOC QP
updateStepBounds(m, 1);
// Solve SOC QP to obtain new, corrected deltaXi
// (store in separate vector to avoid conflict with original deltaXi
// -> need it in linesearch!)
casadi_int info = solveQP(m, get_ptr(deltaXiSOC), get_ptr(lambdaQPSOC), false);
if (info != 0) return false; // Could not solve QP, abort SOC
// Set new SOC trial point
for (casadi_int i=0; i<nx_; i++) {
m->trial_xk[i] = m->x[i] + deltaXiSOC[i];
}
// Compute objective and ||constr(trialXiSOC)||_1 at SOC trial point
info = evaluate(m, m->trial_xk, &objTrialSOC, m->gk);
m->nFunCalls++;
cNormTrialSOC = lInfConstraintNorm(m, m->trial_xk, m->gk);
if (info != 0 || objTrialSOC < obj_lo_ || objTrialSOC > obj_up_
|| !(objTrialSOC == objTrialSOC) || !(cNormTrialSOC == cNormTrialSOC)) {
return false; // evaluation error, abort SOC
}
// Check acceptability to the filter (in SOC)
if (pairInFilter(m, cNormTrialSOC, objTrialSOC)) {
// Trial point is in the prohibited region defined by the filter, abort SOC
return false;
}
// Check sufficient decrease, case I (in SOC)
// (Almost feasible and switching condition holds for line search alpha)
if (cNorm <= theta_min_ && swCond) {
if (objTrialSOC > m->obj + eta_*dfTdeltaXi) {
// Armijo condition does not hold for SOC step, next SOC step
// If constraint violation gets worse by SOC, abort
if (cNormTrialSOC > kappa_soc_ * cNormOld) {
return false;
} else {
cNormOld = cNormTrialSOC;
}
continue;
} else {
// found suitable alpha during SOC, stop
acceptStep(m, get_ptr(deltaXiSOC), get_ptr(lambdaQPSOC), 1.0, nSOCS);
return true;
}
}
// Check sufficient decrease, case II (in SOC)
if (cNorm > theta_min_ || !swCond) {
if (cNormTrialSOC < (1.0 - gamma_theta_) * cNorm
|| objTrialSOC < m->obj - gamma_f_ * cNorm) {
// found suitable alpha during SOC, stop
acceptStep(m, get_ptr(deltaXiSOC), get_ptr(lambdaQPSOC), 1.0, nSOCS);
return true;
} else {
// Trial point is dominated by current point, next SOC step
// If constraint violation gets worse by SOC, abort
if (cNormTrialSOC > kappa_soc_ * cNormOld) {
return false;
} else {
cNormOld = cNormTrialSOC;
}
continue;
}
}
}
return false;
}
/**
* Minimize constraint violation by solving an NLP with minimum norm objective
*
* "The dreaded restoration phase" -- Nick Gould
*/
casadi_int Blocksqp::feasibilityRestorationPhase(BlocksqpMemory* m) const {
// No Feasibility restoration phase
if (!restore_feas_) return -1;
casadi_error("not implemented");
return 0;
}
/**
* Try to (partly) improve constraint violation by satisfying
* the (pseudo) continuity constraints, i.e. do a single shooting
* iteration with the current controls and measurement weights q and w
*/
casadi_int Blocksqp::feasibilityRestorationHeuristic(BlocksqpMemory* m) const {
m->nRestHeurCalls++;
// Call problem specific heuristic to reduce constraint violation.
// For shooting methods that means setting consistent values for
// shooting nodes by one forward integration.
for (casadi_int k=0; k<nx_; k++) // input: last successful step
m->trial_xk[k] = m->x[k];
// FIXME(@jaeandersson) Not implemented
return -1;
}
/**
* If the line search fails, check if the full step reduces the KKT error by a factor kappaF.
*/
casadi_int Blocksqp::kktErrorReduction(BlocksqpMemory* m) const {
casadi_int info = 0;
double objTrial, cNormTrial, trialGradNorm, trialTol;
// Compute new trial point
for (casadi_int i=0; i<nx_; i++)
m->trial_xk[i] = m->x[i] + m->dxk[i];
// Compute objective and ||constr(trial_xk)|| at trial point
std::vector<double> trialConstr(ng_, 0.);
info = evaluate(m, m->trial_xk, &objTrial, get_ptr(trialConstr));
m->nFunCalls++;
cNormTrial = lInfConstraintNorm(m, m->trial_xk, get_ptr(trialConstr));
if (info != 0 || objTrial < obj_lo_ || objTrial > obj_up_
|| !(objTrial == objTrial) || !(cNormTrial == cNormTrial)) {
// evaluation error
return 1;
}
// Compute KKT error of the new point
// scaled norm of Lagrangian gradient
std::vector<double> trialGradLagrange(nx_, 0.);
calcLagrangeGradient(m, m->lam_qp, m->lam_qp+nx_, m->grad_fk,
m->jac_g,
get_ptr(trialGradLagrange), 0);
trialGradNorm = casadi_norm_inf(nx_, get_ptr(trialGradLagrange));
trialTol = trialGradNorm/(1.0+casadi_norm_inf(nx_+ng_, m->lam_qp));
if (fmax(cNormTrial, trialTol) < kappa_f_ * fmax(m->cNorm, m->tol)) {
acceptStep(m, 1.0);
return 0;
} else {
return 1;
}
}
/**
* Check if current entry is accepted to the filter:
* (cNorm, obj) in F_k
*/
bool Blocksqp::
pairInFilter(BlocksqpMemory* m, double cNorm, double obj) const {
/*
* A pair is in the filter if:
* - it increases the objective and
* - it also increases the constraint violation
* The second expression in the if-clause states that we exclude
* entries that are within the feasibility tolerance, e.g.
* if an entry improves the constraint violation from 1e-16 to 1e-17,
* but increases the objective considerably we also think of this entry
* as dominated
*/
for (auto&& f : m->filter) {
if ((cNorm >= (1.0 - gamma_theta_) * f.first ||
(cNorm < 0.01 * nlinfeastol_ && f.first < 0.01 * nlinfeastol_)) &&
obj >= f.second - gamma_f_ * f.first) {
return 1;
}
}
return 0;
}
void Blocksqp::initializeFilter(BlocksqpMemory* m) const {
std::pair<double, double> initPair(theta_max_, obj_lo_);
// Remove all elements
auto iter=m->filter.begin();
while (iter != m->filter.end()) {
std::set< std::pair<double, double> >::iterator iterToRemove = iter;
iter++;
m->filter.erase(iterToRemove);
}
// Initialize with pair (maxConstrViolation, objLowerBound);
m->filter.insert(initPair);
}
/**
* Augment the filter:
* F_k+1 = F_k U { (c,f) | c > (1-gammaTheta)cNorm and f > obj-gammaF*c
*/
void Blocksqp::
augmentFilter(BlocksqpMemory* m, double cNorm, double obj) const {
std::pair<double, double> entry((1-gamma_theta_)*cNorm,
obj-gamma_f_*cNorm);
// Augment filter by current element
m->filter.insert(entry);
// Remove dominated elements
auto iter=m->filter.begin();
while (iter != m->filter.end()) {
if (iter->first > entry.first && iter->second > entry.second) {
auto iterToRemove = iter;
iter++;
m->filter.erase(iterToRemove);
} else {
iter++;
}
}
}
/**
* Initial Hessian: Identity matrix
*/
void Blocksqp::calcInitialHessian(BlocksqpMemory* m) const {
for (casadi_int b=0; b<nblocks_; b++)
//if objective derv is computed exactly, don't set the last block!
if (!(which_second_derv_ == 1 && block_hess_
&& b == nblocks_-1))
calcInitialHessian(m, b);
}
/**
* Initial Hessian for one block: Identity matrix
*/
void Blocksqp::calcInitialHessian(BlocksqpMemory* m, casadi_int b) const {
casadi_int dim = dim_[b];
casadi_fill(m->hess[b], dim*dim, 0.);
// Each block is a diagonal matrix
for (casadi_int i=0; i<dim; i++)
m->hess[b][i+i*dim] = ini_hess_diag_;
// If we maintain 2 Hessians, also reset the second one
if (m->hess2 != nullptr) {
casadi_fill(m->hess2[b], dim*dim, 0.);
for (casadi_int i=0; i<dim; i++)
m->hess2[b][i+i*dim] = ini_hess_diag_;
}
}
void Blocksqp::resetHessian(BlocksqpMemory* m) const {
for (casadi_int b=0; b<nblocks_; b++) {
if (!(which_second_derv_ == 1 && block_hess_ && b == nblocks_ - 1)) {
// if objective derv is computed exactly, don't set the last block!
resetHessian(m, b);
}
}
}
void Blocksqp::resetHessian(BlocksqpMemory* m, casadi_int b) const {
casadi_int dim = dim_[b];
// smallGamma and smallDelta are either subvectors of gamma and delta
// or submatrices of gammaMat, deltaMat, i.e. subvectors of gamma and delta
// from m prev. iterations (for L-BFGS)
double *smallGamma = m->gammaMat + blocks_[b];
double *smallDelta = m->deltaMat + blocks_[b];
for (casadi_int i=0; i<hess_memsize_; ++i) {
// Remove past information on Lagrangian gradient difference
casadi_fill(smallGamma, dim, 0.);
smallGamma += nx_;
// Remove past information on steps
smallDelta += nx_;
casadi_fill(smallDelta, dim, 0.);
}
// Remove information on old scalars (used for COL sizing)
m->delta_norm[b] = 1.0;
m->delta_gamma[b] = 0.0;
m->delta_norm_old[b] = 1.0;
m->delta_gamma_old[b] = 0.0;
m->noUpdateCounter[b] = -1;
calcInitialHessian(m, b);
}
void Blocksqp::
sizeInitialHessian(BlocksqpMemory* m, const double* gamma,
const double* delta, casadi_int b, casadi_int option) const {
casadi_int dim = dim_[b];
double scale;
double myEps = 1.0e3 * eps_;
if (option == 1) {
// Shanno-Phua
scale = casadi_dot(dim, gamma, gamma)
/ fmax(casadi_dot(dim, delta, gamma), myEps);
} else if (option == 2) {
// Oren-Luenberger
scale = casadi_dot(dim, delta, gamma)
/ fmax(casadi_dot(dim, delta, delta), myEps);
scale = fmin(scale, 1.0);
} else if (option == 3) {
// Geometric mean of 1 and 2
scale = sqrt(casadi_dot(dim, gamma, gamma)
/ fmax(casadi_dot(dim, delta, delta), myEps));
} else {
// Invalid option, ignore
return;
}
if (scale > 0.0) {
scale = fmax(scale, myEps);
for (casadi_int i=0; i<dim; i++)
for (casadi_int j=0; j<dim; j++)
m->hess[b][i+j*dim] *= scale;
} else {
scale = 1.0;
}
// statistics: average sizing factor
m->averageSizingFactor += scale;
}
void Blocksqp::
sizeHessianCOL(BlocksqpMemory* m, const double* gamma,
const double* delta, casadi_int b) const {
casadi_int dim = dim_[b];
double theta, scale, myEps = 1.0e3 * eps_;
double deltaNorm, deltaNormOld, deltaGamma, deltaGammaOld, deltaBdelta;
// Get sTs, sTs_, sTy, sTy_, sTBs
deltaNorm = m->delta_norm[b];
deltaGamma = m->delta_gamma[b];
deltaNormOld = m->delta_norm_old[b];
deltaGammaOld = m->delta_gamma_old[b];
deltaBdelta = 0.0;
for (casadi_int i=0; i<dim; i++)
for (casadi_int j=0; j<dim; j++)
deltaBdelta += delta[i] * m->hess[b][i+j*dim] * delta[j];
// Centered Oren-Luenberger factor
if (m->noUpdateCounter[b] == -1) {
// in the first iteration, this should equal the OL factor
theta = 1.0;
} else {
theta = fmin(col_tau1_, col_tau2_ * deltaNorm);
}
if (deltaNorm > myEps && deltaNormOld > myEps) {
scale = (1.0 - theta)*deltaGammaOld / deltaNormOld + theta*deltaBdelta / deltaNorm;
if (scale > eps_)
scale = ((1.0 - theta)*deltaGammaOld / deltaNormOld + theta*deltaGamma / deltaNorm) / scale;
} else {
scale = 1.0;
}
// Size only if factor is between zero and one
if (scale < 1.0 && scale > 0.0) {
scale = fmax(col_eps_, scale);
//print("Sizing value (COL) block %i = %g\n", b, scale);
for (casadi_int i=0; i<dim; i++)
for (casadi_int j=0; j<dim; j++)
m->hess[b][i+j*dim] *= scale;
// statistics: average sizing factor
m->averageSizingFactor += scale;
} else {
m->averageSizingFactor += 1.0;
}
}
/**
* Apply BFGS or SR1 update blockwise and size blocks
*/
void Blocksqp::
calcHessianUpdate(BlocksqpMemory* m, casadi_int updateType, casadi_int hessScaling) const {
casadi_int nBlocks;
bool firstIter;
//if objective derv is computed exactly, don't set the last block!
if (which_second_derv_ == 1 && block_hess_)
nBlocks = nblocks_ - 1;
else
nBlocks = nblocks_;
// Statistics: how often is damping active, what is the average COL sizing factor?
m->hessDamped = 0;
m->averageSizingFactor = 0.0;
for (casadi_int b=0; b<nBlocks; b++) {
casadi_int dim = dim_[b];
// smallGamma and smallDelta are subvectors of gamma and delta,
// corresponding to partially separability
double* smallGamma = m->gammaMat + blocks_[b];
double* smallDelta = m->deltaMat + blocks_[b];
// Is this the first iteration or the first after a Hessian reset?
firstIter = (m->noUpdateCounter[b] == -1);
// Update sTs, sTs_ and sTy, sTy_
m->delta_norm_old[b] = m->delta_norm[b];
m->delta_gamma_old[b] = m->delta_gamma[b];
m->delta_norm[b] = casadi_dot(dim, smallDelta, smallDelta);
m->delta_gamma[b] = casadi_dot(dim, smallDelta, smallGamma);
// Sizing before the update
if (hessScaling < 4 && firstIter)
sizeInitialHessian(m, smallGamma, smallDelta, b, hessScaling);
else if (hessScaling == 4)
sizeHessianCOL(m, smallGamma, smallDelta, b);
// Compute the new update
if (updateType == 1) {
calcSR1(m, smallGamma, smallDelta, b);
// Prepare to compute fallback update as well
m->hess = m->hess2;
// Sizing the fallback update
if (fallback_scaling_ < 4 && firstIter)
sizeInitialHessian(m, smallGamma, smallDelta, b, fallback_scaling_);
else if (fallback_scaling_ == 4)
sizeHessianCOL(m, smallGamma, smallDelta, b);
// Compute fallback update
if (fallback_update_ == 2)
calcBFGS(m, smallGamma, smallDelta, b);
// Reset pointer
m->hess = m->hess1;
} else if (updateType == 2) {
calcBFGS(m, smallGamma, smallDelta, b);
}
// If an update is skipped to often, reset Hessian block
if (m->noUpdateCounter[b] > max_consec_skipped_updates_) {
resetHessian(m, b);
}
}
// statistics: average sizing factor
m->averageSizingFactor /= nBlocks;
}
void Blocksqp::
calcHessianUpdateLimitedMemory(BlocksqpMemory* m,
casadi_int updateType, casadi_int hessScaling) const {
casadi_int nBlocks;
casadi_int m2, pos, posOldest, posNewest;
casadi_int hessDamped, hessSkipped;
double averageSizingFactor;
//if objective derv is computed exactly, don't set the last block!
if (which_second_derv_ == 1 && block_hess_) {
nBlocks = nblocks_ - 1;
} else {
nBlocks = nblocks_;
}
// Statistics: how often is damping active, what is the average COL sizing factor?
m->hessDamped = 0;
m->hessSkipped = 0;
m->averageSizingFactor = 0.0;
for (casadi_int b=0; b<nBlocks; b++) {
casadi_int dim = dim_[b];
// smallGamma and smallDelta are submatrices of gammaMat, deltaMat,
// i.e. subvectors of gamma and delta from m prev. iterations
double *smallGamma = m->gammaMat + blocks_[b];
double *smallDelta = m->deltaMat + blocks_[b];
// Memory structure
if (m->itCount > hess_memsize_) {
m2 = hess_memsize_;
posOldest = m->itCount % m2;
posNewest = (m->itCount-1) % m2;
} else {
m2 = m->itCount;
posOldest = 0;
posNewest = m2-1;
}
// Set B_0 (pretend it's the first step)
calcInitialHessian(m, b);
m->delta_norm[b] = 1.0;
m->delta_norm_old[b] = 1.0;
m->delta_gamma[b] = 0.0;
m->delta_gamma_old[b] = 0.0;
m->noUpdateCounter[b] = -1;
// Size the initial update, but with the most recent delta/gamma-pair
double *gammai = smallGamma + nx_*posNewest;
double *deltai = smallDelta + nx_*posNewest;
sizeInitialHessian(m, gammai, deltai, b, hessScaling);
for (casadi_int i=0; i<m2; i++) {
pos = (posOldest+i) % m2;
// Get new vector from list
gammai = smallGamma + nx_*pos;
deltai = smallDelta + nx_*pos;
// Update sTs, sTs_ and sTy, sTy_
m->delta_norm_old[b] = m->delta_norm[b];
m->delta_gamma_old[b] = m->delta_gamma[b];
m->delta_norm[b] = casadi_dot(dim, deltai, deltai);
m->delta_gamma[b] = casadi_dot(dim, gammai, deltai);
// Save statistics, we want to record them only for the most recent update
averageSizingFactor = m->averageSizingFactor;
hessDamped = m->hessDamped;
hessSkipped = m->hessSkipped;
// Selective sizing before the update
if (hessScaling == 4) sizeHessianCOL(m, gammai, deltai, b);
// Compute the new update
if (updateType == 1) {
calcSR1(m, gammai, deltai, b);
} else if (updateType == 2) {
calcBFGS(m, gammai, deltai, b);
}
m->nTotalUpdates++;
// Count damping statistics only for the most recent update
if (pos != posNewest) {
m->hessDamped = hessDamped;
m->hessSkipped = hessSkipped;
if (hessScaling == 4)
m->averageSizingFactor = averageSizingFactor;
}
}
// If an update is skipped to often, reset Hessian block
if (m->noUpdateCounter[b] > max_consec_skipped_updates_) {
resetHessian(m, b);
}
}
//blocks
m->averageSizingFactor /= nBlocks;
}
void Blocksqp::
calcBFGS(BlocksqpMemory* m, const double* gamma,
const double* delta, casadi_int b) const {
casadi_int dim = dim_[b];
double h1 = 0.0;
double h2 = 0.0;
double thetaPowell = 0.0;
casadi_int damped;
/* Work with a local copy of gamma because damping may need to change gamma.
* Note that m->gamma needs to remain unchanged!
* This may be important in a limited memory context:
* When information is "forgotten", B_i-1 is different and the
* original gamma might lead to an undamped update with the new B_i-1! */
std::vector<double> gamma2(gamma, gamma+dim);
double *B = m->hess[b];
// Bdelta = B*delta (if sizing is enabled, B is the sized B!)
// h1 = delta^T * B * delta
// h2 = delta^T * gamma
vector<double> Bdelta(dim, 0.0);
for (casadi_int i=0; i<dim; i++) {
for (casadi_int k=0; k<dim; k++)
Bdelta[i] += B[i+k*dim] * delta[k];
h1 += delta[i] * Bdelta[i];
//h2 += delta[i] * gamma[i];
}
h2 = m->delta_gamma[b];
/* Powell's damping strategy to maintain pos. def. (Nocedal/Wright p.537; SNOPT paper)
* Interpolates between current approximation and unmodified BFGS */
damped = 0;
if (hess_damp_)
if (h2 < hess_damp_fac_ * h1 / m->alpha && fabs(h1 - h2) > 1.0e-12) {
// At the first iteration h1 and h2 are equal due to COL scaling
thetaPowell = (1.0 - hess_damp_fac_)*h1 / (h1 - h2);
// Redefine gamma and h2 = delta^T * gamma
h2 = 0.0;
for (casadi_int i=0; i<dim; i++) {
gamma2[i] = thetaPowell*gamma2[i] + (1.0 - thetaPowell)*Bdelta[i];
h2 += delta[i] * gamma2[i];
}
// Also redefine deltaGamma for computation of sizing factor in the next iteration
m->delta_gamma[b] = h2;
damped = 1;
}
// For statistics: count number of damped blocks
m->hessDamped += damped;
// B_k+1 = B_k - Bdelta * (Bdelta)^T / h1 + gamma * gamma^T / h2
double myEps = 1.0e2 * eps_;
if (fabs(h1) < myEps || fabs(h2) < myEps) {
// don't perform update because of bad condition, might introduce negative eigenvalues
m->noUpdateCounter[b]++;
m->hessDamped -= damped;
m->hessSkipped++;
m->nTotalSkippedUpdates++;
} else {
for (casadi_int i=0; i<dim; i++)
for (casadi_int j=0; j<dim; j++)
B[i+j*dim] += - Bdelta[i]*Bdelta[j]/h1 + gamma2[i]*gamma2[j]/h2;
m->noUpdateCounter[b] = 0;
}
}
void Blocksqp::
calcSR1(BlocksqpMemory* m, const double* gamma,
const double* delta, casadi_int b) const {
casadi_int dim = dim_[b];
double *B = m->hess[b];
double myEps = 1.0e2 * eps_;
double r = 1.0e-8;
double h = 0.0;
// gmBdelta = gamma - B*delta
// h = (gamma - B*delta)^T * delta
vector<double> gmBdelta(dim);
for (casadi_int i=0; i<dim; i++) {
gmBdelta[i] = gamma[i];
for (casadi_int k=0; k<dim; k++)
gmBdelta[i] -= B[i+k*dim] * delta[k];
h += (gmBdelta[i] * delta[i]);
}
// B_k+1 = B_k + gmBdelta * gmBdelta^T / h
if (fabs(h) < r * casadi_norm_2(dim, delta)
*casadi_norm_2(dim, get_ptr(gmBdelta)) || fabs(h) < myEps) {
// Skip update if denominator is too small
m->noUpdateCounter[b]++;
m->hessSkipped++;
m->nTotalSkippedUpdates++;
} else {
for (casadi_int i=0; i<dim; i++)
for (casadi_int j=0; j<dim; j++)
B[i+j*dim] += gmBdelta[i]*gmBdelta[j]/h;
m->noUpdateCounter[b] = 0;
}
}
/**
* Set deltaXi and gamma as a column in the matrix containing
* the m most recent delta and gamma
*/
void Blocksqp::updateDeltaGamma(BlocksqpMemory* m) const {
if (hess_memsize_ == 1) return;
m->dxk = m->deltaMat + nx_*(m->itCount % hess_memsize_);
m->gamma = m->gammaMat + nx_*(m->itCount % hess_memsize_);
}
void Blocksqp::
computeNextHessian(BlocksqpMemory* m, casadi_int idx, casadi_int maxQP) const {
// Compute fallback update only once
if (idx == 1) {
// Switch storage
m->hess = m->hess2;
// If last block contains exact Hessian, we need to copy it
if (which_second_derv_ == 1) {
casadi_int dim = dim_[nblocks_-1];
casadi_copy(m->hess1[nblocks_-1], dim*dim, m->hess2[nblocks_-1]);
}
// Limited memory: compute fallback update only when needed
if (hess_lim_mem_) {
m->itCount--;
casadi_int hessDampSave = hess_damp_;
const_cast<Blocksqp*>(this)->hess_damp_ = 1;
calcHessianUpdateLimitedMemory(m, fallback_update_, fallback_scaling_);
const_cast<Blocksqp*>(this)->hess_damp_ = hessDampSave;
m->itCount++;
}
/* Full memory: both updates must be computed in every iteration
* so switching storage is enough */
}
// 'Nontrivial' convex combinations
if (maxQP > 2) {
/* Convexification parameter: mu_l = l / (maxQP-1).
* Compute it only in the first iteration, afterwards update
* by recursion: mu_l/mu_(l-1) */
double idxF = idx;
double mu = (idx==1) ? 1.0 / (maxQP-1) : idxF / (idxF - 1.0);
double mu1 = 1.0 - mu;
for (casadi_int b=0; b<nblocks_; b++) {
casadi_int dim = dim_[b];
for (casadi_int i=0; i<dim; i++) {
for (casadi_int j=0; j<dim; j++) {
m->hess2[b][i+j*dim] *= mu;
m->hess2[b][i+j*dim] += mu1 * m->hess1[b][i+j*dim];
}
}
}
}
}
/**
* Inner loop of SQP algorithm:
* Solve a sequence of QPs until pos. def. assumption (G3*) is satisfied.
*/
casadi_int Blocksqp::
solveQP(BlocksqpMemory* m, double* deltaXi, double* lambdaQP,
bool matricesChanged) const {
casadi_int maxQP, l;
if (globalization_ &&
hess_update_ == 1 &&
matricesChanged &&
m->itCount > 1) {
maxQP = max_conv_qp_ + 1;
} else {
maxQP = 1;
}
/*
* Prepare for qpOASES
*/
// Setup QProblem data
if (matricesChanged) {
if (m->A) delete m->A;
m->A = nullptr;
copy_vector(Asp_.colind(), m->colind);
copy_vector(Asp_.row(), m->row);
int* jacIndRow = get_ptr(m->row);
int* jacIndCol = get_ptr(m->colind);
m->A = new qpOASES::SparseMatrix(ng_, nx_,
jacIndRow, jacIndCol, m->jac_g);
}
double *g = m->grad_fk;
double *lb = m->lbx_qp;
double *lu = m->ubx_qp;
double *lbA = m->lba_qp;
double *luA = m->uba_qp;
// qpOASES options
qpOASES::Options opts;
if (matricesChanged && maxQP > 1)
opts.enableInertiaCorrection = qpOASES::BT_FALSE;
else
opts.enableInertiaCorrection = qpOASES::BT_TRUE;
opts.enableEqualities = qpOASES::BT_TRUE;
opts.initialStatusBounds = qpOASES::ST_INACTIVE;
opts.printLevel = qpOASES::PL_NONE;
opts.numRefinementSteps = 2;
opts.epsLITests = 2.2204e-08;
m->qp->setOptions(opts);
// Other variables for qpOASES
double cpuTime = matricesChanged ? max_time_qp_ : 0.1*max_time_qp_;
int maxIt = matricesChanged ? max_it_qp_ : 0.1*max_it_qp_;
qpOASES::SolutionAnalysis solAna;
qpOASES::returnValue ret = qpOASES::RET_INFO_UNDEFINED;
/*
* QP solving loop for convex combinations (sequential)
*/
for (l=0; l<maxQP; l++) {
/*
* Compute a new Hessian
*/
if (l > 0) {
// If the solution of the first QP was rejected, consider second Hessian
m->qpResolve++;
computeNextHessian(m, l, maxQP);
}
if (l == maxQP-1) {
// Enable inertia correction for supposedly convex QPs, just in case
opts.enableInertiaCorrection = qpOASES::BT_TRUE;
m->qp->setOptions(opts);
}
/*
* Prepare the current Hessian for qpOASES
*/
if (matricesChanged) {
// Convert block-Hessian to sparse format
convertHessian(m);
if (m->H) delete m->H;
m->H = nullptr;
m->H = new qpOASES::SymSparseMat(nx_, nx_,
m->hessIndRow, m->hessIndCol,
m->hess_lag);
m->H->createDiagInfo();
}
/*
* Call qpOASES
*/
if (matricesChanged) {
maxIt = max_it_qp_;
cpuTime = max_time_qp_;
if (m->qp->getStatus() == qpOASES::QPS_HOMOTOPYQPSOLVED ||
m->qp->getStatus() == qpOASES::QPS_SOLVED) {
ret = m->qp->hotstart(m->H, g, m->A, lb, lu, lbA, luA, maxIt, &cpuTime);
} else {
if (warmstart_) {
ret = m->qp->init(m->H, g, m->A, lb, lu, lbA, luA, maxIt, &cpuTime,
deltaXi, lambdaQP);
} else {
ret = m->qp->init(m->H, g, m->A, lb, lu, lbA, luA, maxIt, &cpuTime);
}
}
} else {
// Second order correction: H and A do not change
maxIt = 0.1*max_it_qp_;
cpuTime = 0.1*max_time_qp_;
ret = m->qp->hotstart(g, lb, lu, lbA, luA, maxIt, &cpuTime);
}
/*
* Check assumption (G3*) if nonconvex QP was solved
*/
if (l < maxQP-1 && matricesChanged) {
if (ret == qpOASES::SUCCESSFUL_RETURN) {
if (schur_) {
ret = solAna.checkCurvatureOnStronglyActiveConstraints(
dynamic_cast<qpOASES::SQProblemSchur*>(m->qp));
} else {
ret = solAna.checkCurvatureOnStronglyActiveConstraints(m->qp);
}
}
if (ret == qpOASES::SUCCESSFUL_RETURN) {
// QP was solved successfully and curvature is positive after removing bounds
m->qpIterations = maxIt + 1;
break; // Success!
} else {
// QP solution is rejected, save statistics
if (ret == qpOASES::RET_SETUP_AUXILIARYQP_FAILED)
m->qpIterations2++;
else
m->qpIterations2 += maxIt + 1;
m->rejectedSR1++;
}
} else {
// Convex QP was solved, no need to check assumption (G3*)
m->qpIterations += maxIt + 1;
}
} // End of QP solving loop
/*
* Post-processing
*/
// Get solution from qpOASES
m->qp->getPrimalSolution(deltaXi);
m->qp->getDualSolution(lambdaQP);
m->qpObj = m->qp->getObjVal();
// Compute constrJac*deltaXi, need this for second order correction step
casadi_fill(m->jac_times_dxk, ng_, 0.);
casadi_mv(m->jac_g, Asp_, deltaXi, m->jac_times_dxk, 0);
// Print qpOASES error code, if any
if (ret != qpOASES::SUCCESSFUL_RETURN && matricesChanged)
print("***WARNING: qpOASES error message: \"%s\"\n",
qpOASES::getGlobalMessageHandler()->getErrorCodeMessage(ret));
// Point Hessian again to the first Hessian
m->hess = m->hess1;
/* For full-memory Hessian: Restore fallback Hessian if convex combinations
* were used during the loop */
if (!hess_lim_mem_ && maxQP > 2 && matricesChanged) {
double mu = 1.0 / l;
double mu1 = 1.0 - mu;
casadi_int nBlocks = (which_second_derv_ == 1) ? nblocks_-1 : nblocks_;
for (casadi_int b=0; b<nBlocks; b++) {
casadi_int dim = dim_[b];
for (casadi_int i=0; i<dim; i++) {
for (casadi_int j=0; j<dim; j++) {
m->hess2[b][i+j*dim] *= mu;
m->hess2[b][i+j*dim] += mu1 * m->hess1[b][i+j*dim];
}
}
}
}
/* Return code depending on qpOASES returnvalue
* 0: Success
* 1: Maximum number of iterations reached
* 2: Unbounded
* 3: Infeasible
* 4: Other error */
switch (ret) {
case qpOASES::SUCCESSFUL_RETURN:
return 0;
case qpOASES::RET_MAX_NWSR_REACHED:
return 1;
case qpOASES::RET_HESSIAN_NOT_SPD:
case qpOASES::RET_HESSIAN_INDEFINITE:
case qpOASES::RET_INIT_FAILED_UNBOUNDEDNESS:
case qpOASES::RET_QP_UNBOUNDED:
case qpOASES::RET_HOTSTART_STOPPED_UNBOUNDEDNESS:
return 2;
case qpOASES::RET_INIT_FAILED_INFEASIBILITY:
case qpOASES::RET_QP_INFEASIBLE:
case qpOASES::RET_HOTSTART_STOPPED_INFEASIBILITY:
return 3;
default:
return 4;
}
}
/**
* Set bounds on the step (in the QP), either according
* to variable bounds in the NLP or according to
* trust region box radius
*/
void Blocksqp::updateStepBounds(BlocksqpMemory* m, bool soc) const {
// Bounds on step
for (casadi_int i=0; i<nx_; i++) {
double lbx = m->lbx ? m->lbx[i] : 0;
if (lbx != inf) {
m->lbx_qp[i] = lbx - m->x[i];
} else {
m->lbx_qp[i] = inf;
}
double ubx = m->ubx ? m->ubx[i] : 0;
if (ubx != inf) {
m->ubx_qp[i] = ubx - m->x[i];
} else {
m->ubx_qp[i] = inf;
}
}
// Bounds on linearized constraints
for (casadi_int i=0; i<ng_; i++) {
double lbg = m->lbg ? m->lbg[i] : 0;
if (lbg != inf) {
m->lba_qp[i] = lbg - m->gk[i];
if (soc) m->lba_qp[i] += m->jac_times_dxk[i];
} else {
m->lba_qp[i] = inf;
}
double ubg = m->ubg ? m->ubg[i] : 0;
if (ubg != inf) {
m->uba_qp[i] = ubg - m->gk[i];
if (soc) m->uba_qp[i] += m->jac_times_dxk[i];
} else {
m->uba_qp[i] = inf;
}
}
}
void Blocksqp::printProgress(BlocksqpMemory* m) const {
/*
* m->steptype:
*-1: full step was accepted because it reduces the KKT error although line search failed
* 0: standard line search step
* 1: Hessian has been reset to identity
* 2: feasibility restoration heuristic has been called
* 3: feasibility restoration phase has been called
*/
// Print headline every twenty iterations
if (m->itCount % 20 == 0) {
print("%-8s", " it");
print("%-21s", " qpIt");
print("%-9s", "obj");
print("%-11s", "feas");
print("%-7s", "opt");
print("%-11s", "|lgrd|");
print("%-9s", "|stp|");
print("%-10s", "|lstp|");
print("%-8s", "alpha");
print("%-6s", "nSOCS");
print("%-18s", "sk, da, sca");
print("%-6s", "QPr,mu");
print("\n");
}
if (m->itCount == 0) {
// Values for first iteration
print("%5i ", m->itCount);
print("%11i ", 0);
print("% 10e ", m->obj);
print("%-10.2e", m->cNormS);
print("%-10.2e", m->tol);
print("\n");
} else {
// All values
print("%5i ", m->itCount);
print("%5i+%5i ", m->qpIterations, m->qpIterations2);
print("% 10e ", m->obj);
print("%-10.2e", m->cNormS);
print("%-10.2e", m->tol);
print("%-10.2e", m->gradNorm);
print("%-10.2e", casadi_norm_inf(nx_, m->dxk));
print("%-10.2e", m->lambdaStepNorm);
print("%-9.1e", m->alpha);
print("%5i", m->nSOCS);
print("%3i, %3i, %-9.1e", m->hessSkipped, m->hessDamped, m->averageSizingFactor);
print("%i, %-9.1e", m->qpResolve, casadi_norm_1(nblocks_, m->delta_h)/nblocks_);
print("\n");
}
}
void Blocksqp::initStats(BlocksqpMemory* m) const {
m->itCount = 0;
m->qpItTotal = 0;
m->qpIterations = 0;
m->hessSkipped = 0;
m->hessDamped = 0;
m->averageSizingFactor = 0.0;
}
void Blocksqp::updateStats(BlocksqpMemory* m) const {
// Do not accidentally print hessSkipped in the next iteration
m->hessSkipped = 0;
m->hessDamped = 0;
// qpIterations = number of iterations for the QP that determines the step,
// can be a resolve (+SOC)
// qpIterations2 = number of iterations for a QP which solution was discarded
m->qpItTotal += m->qpIterations;
m->qpItTotal += m->qpIterations2;
m->qpIterations = 0;
m->qpIterations2 = 0;
m->qpResolve = 0;
}
/**
* Allocate memory for variables
* required by all optimization
* algorithms except for the Jacobian
*/
void Blocksqp::reset_sqp(BlocksqpMemory* m) const {
// dual variables (for general constraints and variable bounds)
casadi_fill(m->lam_xk, nx_, 0.);
casadi_fill(m->lam_gk, ng_, 0.);
// constraint vector with lower and upper bounds
// (Box constraints are not included in the constraint list)
casadi_fill(m->gk, ng_, 0.);
// gradient of objective
casadi_fill(m->grad_fk, nx_, 0.);
// gradient of Lagrangian
casadi_fill(m->grad_lagk, nx_, 0.);
// current step
casadi_fill(m->deltaMat, nx_*hess_memsize_, 0.);
m->dxk = m->deltaMat;
// trial step (temporary variable, for line search)
casadi_fill(m->trial_xk, nx_, 0.);
// bounds for step (QP subproblem)
casadi_fill(m->lbx_qp, nx_, 0.);
casadi_fill(m->ubx_qp, nx_, 0.);
casadi_fill(m->lba_qp, ng_, 0.);
casadi_fill(m->uba_qp, ng_, 0.);
// product of constraint Jacobian with step (deltaXi)
casadi_fill(m->jac_times_dxk, ng_, 0.);
// dual variables of QP (simple bounds and general constraints)
casadi_fill(m->lam_qp, nx_+ng_, 0.);
// line search parameters
casadi_fill(m->delta_h, nblocks_, 0.);
// filter as a set of pairs
m->filter.clear();
// difference of Lagrangian gradients
casadi_fill(m->gammaMat, nx_*hess_memsize_, 0.);
m->gamma = m->gammaMat;
// Scalars that are used in various Hessian update procedures
casadi_fill(m->noUpdateCounter, nblocks_, casadi_int(-1));
// For selective sizing: for each block save sTs, sTs_, sTy, sTy_
casadi_fill(m->delta_norm, nblocks_, 1.);
casadi_fill(m->delta_norm_old, nblocks_, 1.);
casadi_fill(m->delta_gamma, nblocks_, 0.);
casadi_fill(m->delta_gamma_old, nblocks_, 0.);
// Create one Matrix for one diagonal block in the Hessian
for (casadi_int b=0; b<nblocks_; b++) {
casadi_int dim = dim_[b];
casadi_fill(m->hess1[b], dim*dim, 0.);
}
// For SR1 or finite differences, maintain two Hessians
if (hess_update_ == 1 || hess_update_ == 4) {
for (casadi_int b=0; b<nblocks_; b++) {
casadi_int dim = dim_[b];
casadi_fill(m->hess2[b], dim*dim, 0.);
}
}
// Set Hessian pointer
m->hess = m->hess1;
}
/**
* Convert array *hess to a single symmetric sparse matrix in
* Harwell-Boeing format (as used by qpOASES)
*/
void Blocksqp::
convertHessian(BlocksqpMemory* m) const {
casadi_int count, colCountTotal, rowOffset;
casadi_int nnz;
// 1) count nonzero elements
nnz = 0;
for (casadi_int b=0; b<nblocks_; b++) {
casadi_int dim = dim_[b];
for (casadi_int i=0; i<dim; i++) {
for (casadi_int j=0; j<dim; j++) {
if (fabs(m->hess[b][i+j*dim]) > eps_) {
nnz++;
}
}
}
}
m->hessIndCol = m->hessIndRow + nnz;
m->hessIndLo = m->hessIndCol + (nx_+1);
// 2) store matrix entries columnwise in hessNz
count = 0; // runs over all nonzero elements
colCountTotal = 0; // keep track of position in large matrix
rowOffset = 0;
for (casadi_int b=0; b<nblocks_; b++) {
casadi_int dim = dim_[b];
for (casadi_int i=0; i<dim; i++) {
// column 'colCountTotal' starts at element 'count'
m->hessIndCol[colCountTotal] = count;
for (casadi_int j=0; j<dim; j++) {
if (fabs(m->hess[b][i+j*dim]) > eps_) {
m->hess_lag[count] = m->hess[b][i+j*dim];
m->hessIndRow[count] = j + rowOffset;
count++;
}
}
colCountTotal++;
}
rowOffset += dim;
}
m->hessIndCol[colCountTotal] = count;
// 3) Set reference to lower triangular matrix
for (casadi_int j=0; j<nx_; j++) {
casadi_int i;
for (i=m->hessIndCol[j]; i<m->hessIndCol[j+1] && m->hessIndRow[i]<j; i++) {}
m->hessIndLo[j] = i;
}
if (count != nnz)
print("***WARNING: Error in convertHessian: %i elements processed, "
"should be %i elements!\n", count, nnz);
}
void Blocksqp::initIterate(BlocksqpMemory* m) const {
m->alpha = 1.0;
m->nSOCS = 0;
m->reducedStepCount = 0;
m->steptype = 0;
m->obj = inf;
m->tol = inf;
m->cNorm = theta_max_;
m->gradNorm = inf;
m->lambdaStepNorm = 0.0;
}
casadi_int Blocksqp::
evaluate(BlocksqpMemory* m,
double *f, double *g,
double *grad_f, double *jac_g) const {
m->arg[0] = m->x; // x
m->arg[1] = m->p; // p
m->res[0] = f; // f
m->res[1] = g; // g
m->res[2] = grad_f; // grad:f:x
m->res[3] = jac_g; // jac:g:x
calc_function(m, "nlp_gf_jg");
return 0;
}
casadi_int Blocksqp::
evaluate(BlocksqpMemory* m, const double *xk, double *f,
double *g) const {
m->arg[0] = xk; // x
m->arg[1] = m->p; // p
m->res[0] = f; // f
m->res[1] = g; // g
calc_function(m, "nlp_fg");
return 0;
}
BlocksqpMemory::BlocksqpMemory() {
qpoases_mem = nullptr;
H = nullptr;
A = nullptr;
qp = nullptr;
}
BlocksqpMemory::~BlocksqpMemory() {
if (qpoases_mem) delete qpoases_mem;
if (H) delete H;
if (A) delete A;
if (qp) delete qp;
}
double Blocksqp::
lInfConstraintNorm(BlocksqpMemory* m, const double* xk, const double* g) const {
return fmax(casadi_max_viol(nx_, xk, m->lbx, m->ubx),
casadi_max_viol(ng_, g, m->lbg, m->ubg));
}
} // namespace casadi
| 32.40367 | 100 | 0.575324 | dbdxnuliba |
0c8c8eaf30b5af04651fec2711ebf9a438a9ecbf | 2,301 | cc | C++ | RAVL2/Math/Optimisation/OptimiseQuadraticCurve.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Math/Optimisation/OptimiseQuadraticCurve.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Math/Optimisation/OptimiseQuadraticCurve.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | // This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2002, University of Surrey
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
//! rcsid="$Id: OptimiseQuadraticCurve.cc 7441 2009-12-23 17:29:00Z ees1wc $"
//! lib=RavlOptimise
//! file="Ravl/Math/Optimisation/OptimiseQuadraticCurve.cc"
#include "Ravl/OptimiseQuadraticCurve.hh"
#include "Ravl/ObservationQuadraticPoint.hh"
#include "Ravl/Ransac.hh"
#include "Ravl/FitQuadraticPoints.hh"
#include "Ravl/EvaluateNumInliers.hh"
#include "Ravl/LevenbergMarquardt.hh"
namespace RavlN {
// Shrink-wrap quadratic curve fitting function
const StateVectorQuadraticC
OptimiseQuadraticCurve ( DListC<Point2dObsC> &matchList,
RealT varScale,
RealT chi2Thres,
UIntT noRansacIterations,
RealT ransacChi2Thres,
RealT compatChi2Thres,
UIntT noLevMarqIterations,
RealT lambdaStart,
RealT lambdaFactor )
{
// build list of observations
DListC<ObservationC> obsList;
for(DLIterC<Point2dObsC> it(matchList);it;it++)
obsList.InsLast(ObservationQuadraticPointC(it.Data().z()[0],
it.Data().z()[1],
it.Data().Ni()[1][1],
varScale, chi2Thres));
// Build RANSAC components
ObservationListManagerC obsManager(obsList);
FitQuadraticPointsC fitter;
EvaluateNumInliersC evaluator(ransacChi2Thres, compatChi2Thres);
// use RANSAC to fit affine projection
RansacC ransac(obsManager, fitter, evaluator);
// select and evaluate the given number of samples
for ( UIntT iteration=0; iteration < noRansacIterations; iteration++ )
ransac.ProcessSample(3);
// select observations compatible with solution
obsList = evaluator.CompatibleObservations(ransac.GetSolution(), obsList);
// initialise Levenberg-Marquardt algorithm with Ransac solution
StateVectorQuadraticC stateVecInit = ransac.GetSolution();
LevenbergMarquardtC lm = LevenbergMarquardtC(stateVecInit, obsList);
// apply Levenberg-Marquardt iterations
lm.NIterations ( obsList, noLevMarqIterations, lambdaStart, lambdaFactor );
return lm.GetSolution();
}
}
| 35.953125 | 79 | 0.735332 | isuhao |
0c8f110b2ec9cb0c87b74374ef7c4cc0a105e7e7 | 2,393 | cpp | C++ | cpp/Classes/models/User.cpp | cfoust/quat | da5b644400327c5c0ab7d1a28755e4c1cb5a57c6 | [
"MIT"
] | 1 | 2021-05-31T00:47:07.000Z | 2021-05-31T00:47:07.000Z | cpp/Classes/models/User.cpp | cfoust/quat | da5b644400327c5c0ab7d1a28755e4c1cb5a57c6 | [
"MIT"
] | null | null | null | cpp/Classes/models/User.cpp | cfoust/quat | da5b644400327c5c0ab7d1a28755e4c1cb5a57c6 | [
"MIT"
] | 1 | 2019-12-25T02:10:32.000Z | 2019-12-25T02:10:32.000Z | #include "User.h"
#include <cmath>
#include <algorithm>
namespace QUAT {
using namespace cocos2d;
User::User() {
// Initialize the basic variables
this->puzzlesPlayed = 0;
this->timePlayed = 0;
this->lastShownAd = 0;
this->showAd = false;
this->paid = true;
this->playingEndless = true;
// Load the dictionary
// We just have one of these because it occupies a fair
// bit of memory.
this->dictionary = new Dictionary();
this->dictionary->loadFromFile();
// Initialize the game states
this->endlessState = new GameState(this->dictionary);
this->timedState = new TimedState(this->dictionary);
}
bool User::isPaid() {
return this->paid;
}
int User::getPuzzlesPlayed() {
return this->puzzlesPlayed;
}
GameState * User::getGameState() {
return playingEndless ? endlessState : timedState;
}
GameState * User::getEndlessState() {
return endlessState;
}
TimedState * User::getTimedState() {
return timedState;
}
unsigned long User::getTimePlayed() {
return this->timePlayed;
}
bool User::isPlayingEndless() {
return playingEndless;
}
void User::setPlayingEndless(bool enabled) {
playingEndless = enabled;
}
bool User::shouldShowAd() {
if (this->showAd) {
this->showAd = false;
this->lastShownAd = this->timePlayed;
return true;
}
else {
return false;
}
}
bool User::registerPuzzle(Puzzle * puzzle) {
// Increment the puzzles played
this->puzzlesPlayed++;
// Return the result of adding the puzzle to the game state
return this->getGameState()->registerPuzzle(puzzle);
}
// The version of the User class's persistent data
#define USER_VERSION 1
void User::serialize(QuatStream & qs) {
int version;
// Check to see whether this is an old version
bool old = ((version = qs.version(USER_VERSION)) != 0);
// All of the primitives
qs.integer(&this->puzzlesPlayed);
qs.luinteger(&this->timePlayed);
qs.luinteger(&this->lastShownAd);
// Serialize the game states
this->endlessState->serialize(qs);
this->timedState->serialize(qs);
}
void User::update(float secs) {
this->timePlayed += floor(secs * 1000);
// Show an ad every 5 minutes
// We do this here because it only happens after a puzzle is done
if (((this->timePlayed - this->lastShownAd) > AD_MS) && !this->paid) {
this->showAd = true;
}
// Update the game states
this->endlessState->update(secs);
this->timedState->update(secs);
}
}
| 20.991228 | 71 | 0.696197 | cfoust |
0c95bbd929b0ba29c2527274d0de1f7f60b78716 | 3,634 | cpp | C++ | src/SonicWorlds.cpp | luksamuk/CWorlds | f1a7e7aa72ad91c4e00f12eba47e329fa22cd128 | [
"CC-BY-4.0"
] | 3 | 2016-09-02T16:13:43.000Z | 2017-08-14T21:35:14.000Z | src/SonicWorlds.cpp | luksamuk/CWorlds | f1a7e7aa72ad91c4e00f12eba47e329fa22cd128 | [
"CC-BY-4.0"
] | null | null | null | src/SonicWorlds.cpp | luksamuk/CWorlds | f1a7e7aa72ad91c4e00f12eba47e329fa22cd128 | [
"CC-BY-4.0"
] | null | null | null | // SonicWorlds.cpp
// Main code file
#include "SonicWorlds.hpp"
// class SW_Window
SDL_Window* SW_Window::m_window;
SDL_GLContext SW_Window::m_glcontext,
SW_Window::m_loadcontext;
void SW_Window::init(string name, bool vsync)
{
int winsize_x = 800,
winsize_y = 600;
// Create a window
m_window = SDL_CreateWindow(name.c_str(),
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
winsize_x, winsize_y, SDL_WINDOW_OPENGL);
if(!m_window) {
SW_Log("Error on window creation: %s\n", SDL_GetError());
return; /* todo: throw exception instead */
}
/*todo: icon setup*/
// OpenGL context creation
SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1);
m_loadcontext = SDL_GL_CreateContext(m_window);
m_glcontext = SDL_GL_CreateContext(m_window);
// Set VSync
if(vsync && SDL_GL_SetSwapInterval(1))
SW_Log("Warning: Could not enable VSync.\n");
// Setup OpenGL projection
// This will also invert the plane; Y axis grows top-bottom.
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float AspectRatio = float(winsize_x) / float(winsize_y);
glViewport(0, 0, winsize_x, -winsize_y);
if(AspectRatio >= 1.0f)
glOrtho(0, float(winsize_x) * AspectRatio, float(winsize_y),
0, -1, 1);
else
glOrtho(0, float(winsize_x), float(winsize_y) / AspectRatio,
0, -1 / AspectRatio, 1 / AspectRatio);
glMatrixMode(GL_MODELVIEW);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Setup OpenGL attributes
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
// Enable blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
}
//Test variables
float triangle_angle = 0.0f;
const float triangle_width = 200.0f,
triangle_height = 200.0f;
void SW_Window::update()
{
if(!m_window) return;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// test: draw a triangle rotating around its
// baricenter
glPushMatrix();
glTranslatef(400.0f, 300.0f, 0.0f);
glRotatef(triangle_angle, 0.0f, 0.0f, 1.0f);
glBegin(GL_TRIANGLES);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex2f(0.0f, -200.0f);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex2f(200.0f, 100.0f);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex2f(-200.0f, 100.0f);
glEnd();
glPopMatrix();
// rotation
triangle_angle += 5.0f;
if(triangle_angle >= 360.0f) triangle_angle -= 360.0f;
SDL_GL_SwapWindow(m_window);
}
void SW_Window::dispose()
{
SDL_GL_DeleteContext(m_loadcontext);
SDL_GL_DeleteContext(m_glcontext);
SDL_DestroyWindow(m_window);
}
// class SW_Core
bool SW_Core::m_run = true;
dword SW_Core::m_frametick,
SW_Core::m_frametick_old;
void SW_Core::init()
{
SW_Window::init("Sonic Worlds (C++/OpenGL backend) v" SONICWORLDS_VERSION,
true); // vsync
}
int SW_Core::dogameloop()
{
while(m_run) {
// FPS - Related
m_frametick_old = m_frametick;
m_frametick = SDL_GetTicks();
SW_Window::update();
// Testing!
SDL_Event event;
while(SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_QUIT:
m_run = false;
break;
default: break;
}
}
SW_Log("FPS: %0.04f\n", GetRefreshRate());
// -- Testing!
}
SW_Window::dispose();
return 0;
}
double SW_Core::GetDeltaTime() {
return (m_frametick - m_frametick_old) / 1000.0;
}
double SW_Core::GetRefreshRate() {
return 1.0 / GetDeltaTime();
}
| 23 | 75 | 0.704183 | luksamuk |
0c962a18f8cfd517e942eea403312fa83f246c86 | 6,162 | cpp | C++ | QSynthesis/Frontend/Tabs/Tuning/Editor/Modules/FindReplaceDialog.cpp | SineStriker/QSynthesis-Old | 7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d | [
"MIT"
] | 3 | 2021-12-08T05:30:52.000Z | 2021-12-18T10:46:49.000Z | QSynthesis/Frontend/Tabs/Tuning/Editor/Modules/FindReplaceDialog.cpp | QSynthesis/QSynthesis-Old | 7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d | [
"MIT"
] | null | null | null | QSynthesis/Frontend/Tabs/Tuning/Editor/Modules/FindReplaceDialog.cpp | QSynthesis/QSynthesis-Old | 7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d | [
"MIT"
] | null | null | null | #include "FindReplaceDialog.h"
FindReplaceDialog::FindReplaceDialog(QWidget *parent) : TransparentContainer(parent) {
m_current = 0;
m_total = 0;
mainLayout = new QGridLayout(this);
mainLayout->setVerticalSpacing(10);
findEdit = new FixedLineEdit();
replaceEdit = new FixedLineEdit();
findEdit->setPlaceholderText(tr("Find"));
replaceEdit->setPlaceholderText(tr("Replace"));
findEdit->setClearButtonEnabled(true);
replaceEdit->setClearButtonEnabled(true);
btnCase = new TextButton("Aa");
btnWord = new TextButton("W");
btnReserve = new TextButton("AB");
btnCase->setToolTip(tr("Case sensitive"));
btnWord->setToolTip(tr("Whole words only"));
btnReserve->setToolTip(tr("Preserve case"));
btnCase->setCheckable(true);
btnWord->setCheckable(true);
btnReserve->setCheckable(true);
QSize btnSize1(30, 30);
btnCase->setFixedSize(btnSize1);
btnWord->setFixedSize(btnSize1);
btnReserve->setFixedSize(btnSize1);
QFrame *separator = new QFrame();
separator->setProperty("type", "finder-separator");
separator->setFrameStyle(QFrame::VLine);
separator->setFrameShadow(QFrame::Plain);
separator->setFixedWidth(1);
lbResult = new QLabel();
lbResult->setMinimumWidth(100);
lbResult->setProperty("type", "finder-result");
lbResult->setAlignment(Qt::AlignCenter);
QSizeF padding(5, 5);
QSizeF padding2(8, 8);
QSize btnSize2(30, 30);
btnPrev = new IconButton(padding);
btnNext = new IconButton(padding);
btnReplace = new IconButton(padding);
btnReplaceAll = new IconButton(padding);
btnClose = new IconButton(padding2);
btnPrev->setIcon(":/images/arrow-left-line.svg");
btnNext->setIcon(":/images/arrow-right-line.svg");
btnReplace->setIcon(":/images/find-replace-line.svg");
btnReplaceAll->setIcon(":/images/file-search-line.svg");
btnClose->setIcon(":/images/close-line.svg");
btnPrev->setToolTip(tr("Previous occurrence"));
btnNext->setToolTip(tr("Next occurrence"));
btnReplace->setToolTip(tr("Replace"));
btnReplaceAll->setToolTip(tr("Replace all"));
btnNext->setFixedSize(btnSize2);
btnPrev->setFixedSize(btnSize2);
btnReplace->setFixedSize(btnSize2);
btnReplaceAll->setFixedSize(btnSize2);
btnClose->setFixedSize(btnSize2);
setFocusPolicy(Qt::ClickFocus);
findEdit->setFocusPolicy(Qt::ClickFocus);
replaceEdit->setFocusPolicy(Qt::ClickFocus);
installEventFilter(this);
findEdit->installEventFilter(this);
replaceEdit->installEventFilter(this);
connect(btnCase, &TextButton::toggled, this, &FindReplaceDialog::handleCaseBtnToggled);
connect(btnWord, &TextButton::toggled, this, &FindReplaceDialog::handleWordBtnToggled);
connect(btnPrev, &IconButton::clicked, this, &FindReplaceDialog::handlePrevBtnClicked);
connect(btnNext, &IconButton::clicked, this, &FindReplaceDialog::handleNextBtnClicked);
connect(btnReplace, &IconButton::clicked, this, &FindReplaceDialog::handleReplaceBtnClicked);
connect(btnReplaceAll, &IconButton::clicked, this,
&FindReplaceDialog::handleReplaceAllBtnClicked);
connect(findEdit, &FixedLineEdit::textChanged, this, &FindReplaceDialog::handleFindTextChanged);
connect(btnClose, &IconButton::clicked, this, &FindReplaceDialog::handleCloseBtnClicked);
mainLayout->addWidget(findEdit, 0, 0);
mainLayout->addWidget(replaceEdit, 1, 0, 1, 2);
mainLayout->addWidget(btnCase, 0, 1);
mainLayout->addWidget(btnWord, 0, 2);
mainLayout->addWidget(btnReserve, 1, 2);
mainLayout->addWidget(separator, 0, 3, 2, 1);
mainLayout->addWidget(lbResult, 0, 4);
mainLayout->addWidget(btnPrev, 0, 5);
mainLayout->addWidget(btnNext, 0, 6);
mainLayout->addWidget(btnClose, 0, 7);
mainLayout->addWidget(btnReplace, 1, 5);
mainLayout->addWidget(btnReplaceAll, 1, 6);
setLayout(mainLayout);
updateCaption();
setMinimumWidth(500);
}
FindReplaceDialog::~FindReplaceDialog() {
}
bool FindReplaceDialog::matchCase() const {
return btnCase->isChecked();
}
bool FindReplaceDialog::matchWord() const {
return btnWord->isChecked();
}
bool FindReplaceDialog::preserveCase() const {
return btnReserve->isChecked();
}
QString FindReplaceDialog::findText() const {
return findEdit->text();
}
QString FindReplaceDialog::replaceText() const {
return replaceEdit->text();
}
int FindReplaceDialog::current() const {
return m_current;
}
void FindReplaceDialog::setCurrent(int current) {
m_current = current;
updateCaption();
}
int FindReplaceDialog::total() const {
return m_total;
}
void FindReplaceDialog::setTotal(int total) {
m_total = total;
updateCaption();
}
void FindReplaceDialog::setFindTextFocus() {
findEdit->setFocus();
findEdit->selectAll();
}
void FindReplaceDialog::updateCaption() {
lbResult->setText(QString::number(m_current) + "/" + QString::number(m_total));
}
void FindReplaceDialog::handleCaseBtnToggled(bool checked) {
emit findStateChanged();
}
void FindReplaceDialog::handleWordBtnToggled(bool checked) {
emit findStateChanged();
}
void FindReplaceDialog::handleReserveBtnToggled(bool checked) {
}
void FindReplaceDialog::handlePrevBtnClicked() {
emit prevRequested();
}
void FindReplaceDialog::handleNextBtnClicked() {
emit nextRequested();
}
void FindReplaceDialog::handleReplaceBtnClicked() {
emit replaceRequested();
}
void FindReplaceDialog::handleReplaceAllBtnClicked() {
emit replaceAllRequested();
}
void FindReplaceDialog::handleFindTextChanged(const QString &text) {
emit findStateChanged();
}
void FindReplaceDialog::handleCloseBtnClicked() {
emit closeRequested();
}
bool FindReplaceDialog::eventFilter(QObject *obj, QEvent *event) {
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
int key = keyEvent->key();
if (key == Qt::Key_Enter || key == Qt::Key_Return) {
emit nextRequested();
return true;
}
}
return TransparentContainer::eventFilter(obj, event);
}
| 29.066038 | 100 | 0.708536 | SineStriker |
0c9be8bf8c8c8e849788107a267df066f7ee8212 | 228 | hpp | C++ | dynamic/wrappers/cell_based/FarhadifarForce2.cppwg.hpp | jmsgrogan/PyChaste | 48a9863d2c941c71e47ecb72e917b477ba5c1413 | [
"FTL"
] | 6 | 2017-02-04T16:10:53.000Z | 2021-07-01T08:03:16.000Z | dynamic/wrappers/cell_based/FarhadifarForce2.cppwg.hpp | jmsgrogan/PyChaste | 48a9863d2c941c71e47ecb72e917b477ba5c1413 | [
"FTL"
] | 6 | 2017-06-22T08:50:41.000Z | 2019-12-15T20:17:29.000Z | dynamic/wrappers/cell_based/FarhadifarForce2.cppwg.hpp | jmsgrogan/PyChaste | 48a9863d2c941c71e47ecb72e917b477ba5c1413 | [
"FTL"
] | 3 | 2017-05-15T21:33:58.000Z | 2019-10-27T21:43:07.000Z | #ifndef FarhadifarForce2_hpp__pyplusplus_wrapper
#define FarhadifarForce2_hpp__pyplusplus_wrapper
namespace py = pybind11;
void register_FarhadifarForce2_class(py::module &m);
#endif // FarhadifarForce2_hpp__pyplusplus_wrapper
| 32.571429 | 52 | 0.877193 | jmsgrogan |
0c9d816519d3dad3e6ab7306958464af0aa9d817 | 3,077 | cpp | C++ | Mysql/storage/ndb/nodejs/Adapter/impl/ndb/src/BlobHandler.cpp | clockzhong/WrapLAMP | fa7ad07da3f1759e74966a554befa47bbbbb8dd5 | [
"Apache-2.0"
] | 1 | 2015-12-24T16:44:50.000Z | 2015-12-24T16:44:50.000Z | Mysql/storage/ndb/nodejs/Adapter/impl/ndb/src/BlobHandler.cpp | clockzhong/WrapLAMP | fa7ad07da3f1759e74966a554befa47bbbbb8dd5 | [
"Apache-2.0"
] | 1 | 2015-12-24T18:23:56.000Z | 2015-12-24T18:24:26.000Z | Mysql/storage/ndb/nodejs/Adapter/impl/ndb/src/BlobHandler.cpp | clockzhong/WrapLAMP | fa7ad07da3f1759e74966a554befa47bbbbb8dd5 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2014, Oracle and/or its affiliates. All rights
reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2 of
the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
*/
#include <stdlib.h>
#include <assert.h>
#include <NdbApi.hpp>
#include <node_buffer.h>
#include "adapter_global.h"
#include "unified_debug.h"
#include "BlobHandler.h"
// BlobHandler constructor
BlobHandler::BlobHandler(int colId, int fieldNo) :
ndbBlob(0),
next(0),
content(0),
length(0),
columnId(colId),
fieldNumber(fieldNo)
{
}
// Helper functions for BlobReadHandler
int blobHandlerActiveHook(NdbBlob * ndbBlob, void * handler) {
BlobReadHandler * blobHandler = static_cast<BlobReadHandler *>(handler);
return blobHandler->runActiveHook(ndbBlob);
}
void freeBufferContentsFromJs(char *data, void *) {
free(data);
}
// BlobReadHandler methods
void BlobReadHandler::prepare(const NdbOperation * ndbop) {
ndbBlob = ndbop->getBlobHandle(columnId);
assert(ndbBlob);
ndbBlob->setActiveHook(blobHandlerActiveHook, this);
if(next) next->prepare(ndbop);
}
int BlobReadHandler::runActiveHook(NdbBlob *b) {
assert(b == ndbBlob);
int isNull;
ndbBlob->getNull(isNull);
if(! isNull) {
ndbBlob->getLength(length);
uint32_t nBytes = length;
content = (char *) malloc(length);
if(content) {
int rv = ndbBlob->readData(content, nBytes);
DEBUG_PRINT("BLOB read: column %d, length %d, read %d/%d",
columnId, length, rv, nBytes);
} else {
return -1;
}
}
return 0;
}
v8::Handle<v8::Value> BlobReadHandler::getResultBuffer() {
v8::HandleScope scope;
if(content) {
node::Buffer * buffer;
buffer = node::Buffer::New(content, length, freeBufferContentsFromJs, 0);
return scope.Close(buffer->handle_);
}
return v8::Null();
}
// BlobWriteHandler methods
BlobWriteHandler::BlobWriteHandler(int colId, int fieldNo,
v8::Handle<v8::Object> blobValue) :
BlobHandler(colId, fieldNo)
{
length = node::Buffer::Length(blobValue);
content = node::Buffer::Data(blobValue);
}
void BlobWriteHandler::prepare(const NdbOperation * ndbop) {
ndbBlob = ndbop->getBlobHandle(columnId);
if(! ndbBlob) {
DEBUG_PRINT("getBlobHandle %d: [%d] %s", columnId,
ndbop->getNdbError().code, ndbop->getNdbError().message);
assert(false);
}
DEBUG_PRINT("Prepare write for BLOB column %d, length %d", columnId, length);
ndbBlob->setValue(content, length);
if(next) next->prepare(ndbop);
}
| 26.299145 | 79 | 0.697433 | clockzhong |
0ca1581c71904194f6785936011967773f81bb97 | 1,737 | cpp | C++ | source/ggeometry/gcoordinate.cpp | birderyu/CSystem | c7c9034b7eb660c0dcd17d51002f4d83080b88b4 | [
"Apache-2.0"
] | 2 | 2016-07-30T04:55:39.000Z | 2016-08-02T08:18:46.000Z | source/ggeometry/gcoordinate.cpp | birderyu/gsystem | c7c9034b7eb660c0dcd17d51002f4d83080b88b4 | [
"Apache-2.0"
] | null | null | null | source/ggeometry/gcoordinate.cpp | birderyu/gsystem | c7c9034b7eb660c0dcd17d51002f4d83080b88b4 | [
"Apache-2.0"
] | null | null | null | #include "gcoordinate.h"
#include "GCore/gnew.h"
#ifdef G_GEOMETRY_HAS_Z
# define G_COORDINATE_X m_tCoord[0]
# define G_COORDINATE_Y m_tCoord[1]
# define G_COORDINATE_Z m_tCoord[2]
#else // !G_GEOMETRY_HAS_Z
greal _G_COORDINATE_z_ = 0;
# define G_COORDINATE_X m_tCoord[0]
# define G_COORDINATE_Y m_tCoord[1]
# define G_COORDINATE_Z GGeometryGlobal::_g_n_coordinate_z_
#endif // G_GEOMETRY_HAS_Z
GCoordinate::GCoordinate()
{
GMemSet(m_tCoord, 0, sizeof(greal)* G_COORDINATE_SIZE);
}
GCoordinate::GCoordinate(greal x, greal y)
{
G_COORDINATE_X = x;
G_COORDINATE_Y = y;
G_COORDINATE_Z = 0;
}
GCoordinate::GCoordinate(greal x, greal y, greal z)
{
G_COORDINATE_X = x;
G_COORDINATE_Y = y;
G_COORDINATE_Z = z;
}
GCoordinate::GCoordinate(const greal *p_c, gsize size)
{
gsize real_size = size < G_COORDINATE_SIZE ? size : G_COORDINATE_SIZE;
GMemCopy(m_tCoord, p_c, sizeof(greal)* real_size);
}
GCoordinate::GCoordinate(const GCoordinate &coord)
{
GMemCopy(m_tCoord, coord.m_tCoord, sizeof(greal)* G_COORDINATE_SIZE);
}
greal &GCoordinate::X()
{
return G_COORDINATE_X;
}
greal GCoordinate::X() const
{
return G_COORDINATE_X;
}
greal &GCoordinate::Y()
{
return G_COORDINATE_Y;
}
greal GCoordinate::Y() const
{
return G_COORDINATE_Y;
}
greal &GCoordinate::Z()
{
return G_COORDINATE_Z;
}
greal GCoordinate::Z() const
{
return G_COORDINATE_Z;
}
gvoid GCoordinate::SetX(greal x)
{
G_COORDINATE_X = x;
}
gvoid GCoordinate::SetY(greal y)
{
G_COORDINATE_Y = y;
}
gvoid GCoordinate::SetZ(greal z)
{
G_COORDINATE_Z = z;
}
guint GCoordinate::Dimension() const
{
return G_COORDINATE_SIZE;
}
const greal * GCoordinate::Cursor() const
{
return m_tCoord;
}
#undef G_COORDINATE_Z
#undef G_COORDINATE_Y
#undef G_COORDINATE_X | 17.029412 | 71 | 0.750144 | birderyu |
0ca33a5c22fda1855e6df955b3d2d0cb74e40ef6 | 391 | cpp | C++ | plugin/assimp/library_main.cpp | nomadsinteractive/ark | 52f84c6dbd5ca6bdd07d450b3911be1ffd995922 | [
"Apache-2.0"
] | 5 | 2018-03-28T09:14:55.000Z | 2018-04-02T11:54:33.000Z | plugin/assimp/library_main.cpp | nomadsinteractive/ark | 52f84c6dbd5ca6bdd07d450b3911be1ffd995922 | [
"Apache-2.0"
] | null | null | null | plugin/assimp/library_main.cpp | nomadsinteractive/ark | 52f84c6dbd5ca6bdd07d450b3911be1ffd995922 | [
"Apache-2.0"
] | null | null | null | #include "core/base/plugin.h"
#include "core/ark.h"
#include "core/base/api.h"
#include "core/base/plugin_manager.h"
#include "core/types/shared_ptr.h"
#include "generated/assimp_plugin.h"
using namespace ark;
using namespace ark::plugin::assimp;
extern "C" ARK_API Plugin* __ark_assimp_initialize__(Ark&);
Plugin* __ark_assimp_initialize__(Ark& ark)
{
return new AssimpPlugin();
}
| 20.578947 | 59 | 0.754476 | nomadsinteractive |
0ca4ec4451f28d72b617dcdc80bf599cc05d596f | 331 | cpp | C++ | ProgrammingInLua/chapters27_capi/demo3/main.cpp | MDGSF/LuaPractice | 69e788d7c28f6a07a381a53c6d294829348aa4ec | [
"MIT"
] | null | null | null | ProgrammingInLua/chapters27_capi/demo3/main.cpp | MDGSF/LuaPractice | 69e788d7c28f6a07a381a53c6d294829348aa4ec | [
"MIT"
] | null | null | null | ProgrammingInLua/chapters27_capi/demo3/main.cpp | MDGSF/LuaPractice | 69e788d7c28f6a07a381a53c6d294829348aa4ec | [
"MIT"
] | null | null | null | #include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lua.hpp"
int foo(lua_State *L) { return 0; }
int secure_foo(lua_State *L) {
lua_pushcfunction(L, foo);
return (lua_pcall(L, 0, 0, 0) == 0);
}
int main() {
lua_State *L = luaL_newstate(); // opens Lua
lua_close(L);
return 0;
}
| 15.761905 | 47 | 0.634441 | MDGSF |
0ca65de3b6d4fe81148de61559e9529bc329a18f | 10,630 | cpp | C++ | PosixTimespec_test/PosixTimespec_test.cpp | leighgarbs/toolbox | fd9ceada534916fa8987cfcb5220cece2188b304 | [
"MIT"
] | null | null | null | PosixTimespec_test/PosixTimespec_test.cpp | leighgarbs/toolbox | fd9ceada534916fa8987cfcb5220cece2188b304 | [
"MIT"
] | null | null | null | PosixTimespec_test/PosixTimespec_test.cpp | leighgarbs/toolbox | fd9ceada534916fa8987cfcb5220cece2188b304 | [
"MIT"
] | null | null | null | #include <iostream>
#include <time.h>
#include <vector>
#include "PosixTimespec_test.hpp"
#include "PosixTimespec.hpp"
#include "Test.hpp"
#include "TestCases.hpp"
#include "TestMacros.hpp"
TEST_PROGRAM_MAIN(PosixTimespec_test);
//==============================================================================
void PosixTimespec_test::addTestCases()
{
ADD_TEST_CASE(Operators);
}
//==============================================================================
void PosixTimespec_test::Operators::addTestCases()
{
ADD_TEST_CASE(Addition);
ADD_TEST_CASE(Subtraction);
ADD_TEST_CASE(GreaterThan);
ADD_TEST_CASE(GreaterThanOrEqualTo);
ADD_TEST_CASE(LessThan);
ADD_TEST_CASE(LessThanOrEqualTo);
}
//==============================================================================
void PosixTimespec_test::Operators::Addition::addTestCases()
{
ADD_TEST_CASE(Case1);
ADD_TEST_CASE(Case2);
ADD_TEST_CASE(Case3);
ADD_TEST_CASE(Case4);
}
//==============================================================================
void PosixTimespec_test::Operators::Subtraction::addTestCases()
{
ADD_TEST_CASE(Case1);
ADD_TEST_CASE(Case2);
ADD_TEST_CASE(Case3);
ADD_TEST_CASE(Case4);
}
//==============================================================================
void PosixTimespec_test::Operators::GreaterThan::addTestCases()
{
ADD_TEST_CASE(Case1);
ADD_TEST_CASE(Case2);
ADD_TEST_CASE(Case3);
}
//==============================================================================
void PosixTimespec_test::Operators::GreaterThanOrEqualTo::addTestCases()
{
ADD_TEST_CASE(Case1);
ADD_TEST_CASE(Case2);
ADD_TEST_CASE(Case3);
}
//==============================================================================
void PosixTimespec_test::Operators::LessThan::addTestCases()
{
ADD_TEST_CASE(Case1);
ADD_TEST_CASE(Case2);
ADD_TEST_CASE(Case3);
}
//==============================================================================
void PosixTimespec_test::Operators::LessThanOrEqualTo::addTestCases()
{
ADD_TEST_CASE(Case1);
ADD_TEST_CASE(Case2);
ADD_TEST_CASE(Case3);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::Addition::Case1::body()
{
return operatorTest(0, 0, 0, 1, 0, 1, ADDITION);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::Addition::Case2::body()
{
return operatorTest(
2346, 999999999, 1000, 40, 3347, 39, ADDITION);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::Addition::Case3::body()
{
return operatorTest(5, 0, 2, 500000000, 7, 500000000, ADDITION);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::Addition::Case4::body()
{
return operatorTest(1, 250000000, 0, 750000000, 2, 0, ADDITION);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::Subtraction::Case1::body()
{
return operatorTest(
0, 0, 0, 1, static_cast<time_t>(0) - 1, 999999999, SUBTRACTION);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::Subtraction::Case2::body()
{
return operatorTest(
2346, 999999999, 1000, 40, 1346, 999999959, SUBTRACTION);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::Subtraction::Case3::body()
{
return operatorTest(
5, 0, 2, 500000000, 2, 500000000, SUBTRACTION);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::Subtraction::Case4::body()
{
return operatorTest(
1, 250000000, 0, 750000000, 0, 500000000, SUBTRACTION);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::GreaterThan::Case1::body()
{
return operatorTest(1, 0, 0, 1, true, GREATER_THAN);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::GreaterThan::Case2::body()
{
return operatorTest(1, 0, 1, 0, false, GREATER_THAN);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::GreaterThan::Case3::body()
{
return operatorTest(0, 1, 1, 0, false, GREATER_THAN);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::GreaterThanOrEqualTo::Case1::body()
{
return operatorTest(1, 0, 0, 1, true, GREATER_THAN_OR_EQUAL_TO);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::GreaterThanOrEqualTo::Case2::body()
{
return operatorTest(1, 0, 1, 0, true, GREATER_THAN_OR_EQUAL_TO);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::GreaterThanOrEqualTo::Case3::body()
{
return operatorTest(0, 1, 1, 0, false, GREATER_THAN_OR_EQUAL_TO);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::LessThan::Case1::body()
{
return operatorTest(1, 0, 0, 1, false, LESS_THAN);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::LessThan::Case2::body()
{
return operatorTest(1, 0, 1, 0, false, LESS_THAN);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::LessThan::Case3::body()
{
return operatorTest(0, 1, 1, 0, true, LESS_THAN);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::LessThanOrEqualTo::Case1::body()
{
return operatorTest(1, 0, 0, 1, false, LESS_THAN_OR_EQUAL_TO);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::LessThanOrEqualTo::Case2::body()
{
return operatorTest(1, 0, 1, 0, true, LESS_THAN_OR_EQUAL_TO);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::LessThanOrEqualTo::Case3::body()
{
return operatorTest(0, 1, 1, 0, true, LESS_THAN_OR_EQUAL_TO);
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::operatorTest(
time_t lhs_tv_sec,
long lhs_tv_nsec,
time_t rhs_tv_sec,
long rhs_tv_nsec,
time_t result_tv_sec,
long result_tv_nsec,
ArithmeticOperation operation)
{
// Create representations in the basic POSIX timespec and PosixTimespec
PosixTimespec lhs;
lhs.tp.tv_sec = lhs_tv_sec;
lhs.tp.tv_nsec = lhs_tv_nsec;
timespec lhs_ts;
lhs_ts.tv_sec = lhs_tv_sec;
lhs_ts.tv_nsec = lhs_tv_nsec;
// Create representations in the basic POSIX timespec and PosixTimespec
PosixTimespec rhs;
rhs.tp.tv_sec = rhs_tv_sec;
rhs.tp.tv_nsec = rhs_tv_nsec;
timespec rhs_ts;
rhs_ts.tv_sec = rhs_tv_sec;
rhs_ts.tv_nsec = rhs_tv_nsec;
// Do three separate tests of each operator. One test uses a PosixTimespec
// on both sides and the other two use a PosixTimespec on only one side.
PosixTimespec result_bothsides;
PosixTimespec result_lhs;
PosixTimespec result_rhs;
if (operation == ADDITION)
{
result_bothsides = lhs + rhs;
result_lhs = lhs + rhs_ts;
result_rhs = lhs_ts + rhs;
}
else if (operation == SUBTRACTION)
{
result_bothsides = lhs - rhs;
result_lhs = lhs - rhs_ts;
result_rhs = lhs_ts - rhs;
}
MUST_BE_TRUE(result_bothsides.tp.tv_sec == result_tv_sec);
MUST_BE_TRUE(result_bothsides.tp.tv_nsec == result_tv_nsec);
MUST_BE_TRUE(result_lhs.tp.tv_sec == result_tv_sec);
MUST_BE_TRUE(result_lhs.tp.tv_nsec == result_tv_nsec);
MUST_BE_TRUE(result_rhs.tp.tv_sec == result_tv_sec);
MUST_BE_TRUE(result_rhs.tp.tv_nsec == result_tv_nsec);
return Test::PASSED;
}
//==============================================================================
Test::Result PosixTimespec_test::Operators::operatorTest(
time_t lhs_tv_sec,
long lhs_tv_nsec,
time_t rhs_tv_sec,
long rhs_tv_nsec,
bool result,
ComparisonOperation operation)
{
// Create representations in the basic POSIX timespec and PosixTimespec
PosixTimespec lhs;
lhs.tp.tv_sec = lhs_tv_sec;
lhs.tp.tv_nsec = lhs_tv_nsec;
timespec lhs_ts;
lhs_ts.tv_sec = lhs_tv_sec;
lhs_ts.tv_nsec = lhs_tv_nsec;
// Create representations in the basic POSIX timespec and PosixTimespec
PosixTimespec rhs;
rhs.tp.tv_sec = rhs_tv_sec;
rhs.tp.tv_nsec = rhs_tv_nsec;
timespec rhs_ts;
rhs_ts.tv_sec = rhs_tv_sec;
rhs_ts.tv_nsec = rhs_tv_nsec;
// Do three separate tests of each operator. One test uses a PosixTimespec
// on both sides and the other two use a PosixTimespec on only one side.
bool result_bothsides = false;
bool result_lhs = false;
bool result_rhs = false;
if (operation == GREATER_THAN)
{
result_bothsides = lhs > rhs;
result_lhs = lhs > rhs_ts;
result_rhs = lhs_ts > rhs;
}
else if (operation == GREATER_THAN_OR_EQUAL_TO)
{
result_bothsides = lhs >= rhs;
result_lhs = lhs >= rhs_ts;
result_rhs = lhs_ts >= rhs;
}
else if (operation == LESS_THAN)
{
result_bothsides = lhs < rhs;
result_lhs = lhs < rhs_ts;
result_rhs = lhs_ts < rhs;
}
else if (operation == LESS_THAN_OR_EQUAL_TO)
{
result_bothsides = lhs <= rhs;
result_lhs = lhs <= rhs_ts;
result_rhs = lhs_ts <= rhs;
}
MUST_BE_TRUE(result_bothsides == result);
MUST_BE_TRUE(result_lhs == result);
MUST_BE_TRUE(result_rhs == result);
return Test::PASSED;
}
| 32.31003 | 80 | 0.522201 | leighgarbs |
0ca8efe7daa5a13ef26181e08cd52b5a23f304fb | 10,393 | cpp | C++ | Source/IO/NCCheckpoint.cpp | etpalmer63/ERF | 88a3969ae93aae5b9d1416217df9051da476114e | [
"BSD-3-Clause-LBNL"
] | null | null | null | Source/IO/NCCheckpoint.cpp | etpalmer63/ERF | 88a3969ae93aae5b9d1416217df9051da476114e | [
"BSD-3-Clause-LBNL"
] | null | null | null | Source/IO/NCCheckpoint.cpp | etpalmer63/ERF | 88a3969ae93aae5b9d1416217df9051da476114e | [
"BSD-3-Clause-LBNL"
] | null | null | null | #include <ERF.H>
#include <NCInterface.H>
#include <AMReX_PlotFileUtil.H>
using namespace amrex;
void
ERF::WriteNCCheckpointFile () const
{
// checkpoint file name, e.g., chk00010
const std::string& checkpointname = amrex::Concatenate(check_file,istep[0],5);
amrex::Print() << "Writing NetCDF checkpoint " << checkpointname << "\n";
const int nlevels = finest_level+1;
// ---- ParallelDescriptor::IOProcessor() creates the directories
PreBuildDirectorHierarchy(checkpointname, "Level_", nlevels, true);
// write Header file
if (ParallelDescriptor::IOProcessor()) {
std::string HeaderFileName(checkpointname + "/Header.nc");
auto ncf = ncutils::NCFile::create(HeaderFileName, NC_CLOBBER | NC_NETCDF4);
const std::string ndim_name = "num_dimension";
const std::string nl_name = "finest_levels";
const std::string ng_name = "num_grids";
const std::string nvar_name = "num_vars";
const std::string ndt_name = "num_dt";
const std::string nstep_name = "num_istep";
const std::string ntime_name = "num_newtime";
const int ndt = dt.size();
const int nstep = istep.size();
const int ntime = t_new.size();
amrex::Vector<int> nbox(nlevels);
amrex::Vector<std::string> nbox_name(nlevels);
amrex::Vector<amrex::Vector<std::string> > lo_names(nlevels);
amrex::Vector<amrex::Vector<std::string> > hi_names(nlevels);
amrex::Vector<amrex::Vector<std::string> > typ_names(nlevels);
for (auto lev{0}; lev <= finest_level; ++lev) {
nbox[lev] = boxArray(lev).size();
nbox_name[lev] = "NBox_"+std::to_string(lev);
for (int nb(0); nb < boxArray(lev).size(); ++nb) {
lo_names[lev] .push_back("SmallEnd_"+std::to_string(lev)+"_"+std::to_string(nb));
hi_names[lev] .push_back("BigEnd_"+std::to_string(lev)+"_"+std::to_string(nb));
typ_names[lev].push_back("BoxType_"+std::to_string(lev)+"_"+std::to_string(nb));
}
}
ncf.enter_def_mode();
ncf.put_attr("title", "ERF NetCDF CheckPoint Header");
ncf.def_dim(ndim_name, AMREX_SPACEDIM);
ncf.def_dim(nl_name, nlevels);
ncf.def_dim(ndt_name, ndt);
ncf.def_dim(nstep_name, nstep);
ncf.def_dim(ntime_name, ntime);
for (auto lev{0}; lev <= finest_level; ++lev) {
ncf.def_dim(nbox_name[lev], nbox[lev]);
for (int nb(0); nb < boxArray(lev).size(); ++nb) {
ncf.def_var(lo_names[lev][nb], ncutils::NCDType::Int, {nbox_name[lev], ndim_name});
ncf.def_var(hi_names[lev][nb], ncutils::NCDType::Int, {nbox_name[lev], ndim_name});
ncf.def_var(typ_names[lev][nb], ncutils::NCDType::Int, {nbox_name[lev], ndim_name});
}
}
ncf.def_var("istep", ncutils::NCDType::Int, {nstep_name});
ncf.def_var("dt" , ncutils::NCDType::Real, {ndt_name} );
ncf.def_var("tnew" , ncutils::NCDType::Real, {ntime_name});
ncf.exit_def_mode();
// output headfile in NetCDF format
ncf.var("istep").put(istep.data(), {0}, {static_cast<long unsigned int>(nstep)});
ncf.var("dt") .put(dt.data(), {0}, {static_cast<long unsigned int>(ndt)});
ncf.var("tnew") .put(t_new.data(), {0}, {static_cast<long unsigned int>(ntime)});
// ncf.var("nbox") .put(nbox.begin(), {0}, {nstep});
for (auto lev{0}; lev <= finest_level; ++lev) {
auto box_array = boxArray(lev);
for (int nb(0); nb < box_array.size(); ++nb) {
long unsigned int nbb = static_cast<long unsigned int>(nb);
auto box = box_array[nb];
ncf.var(lo_names[lev][nb] ).put(box.smallEnd().begin(), {nbb, 0}, {1, AMREX_SPACEDIM});
ncf.var(hi_names[lev][nb] ).put(box.bigEnd().begin() , {nbb, 0}, {1, AMREX_SPACEDIM});
ncf.var(typ_names[lev][nb]).put(box.type().begin() , {nbb, 0}, {1, AMREX_SPACEDIM});
}
}
}
// write the MultiFab data to, e.g., chk00010/Level_0/
// Here we make copies of the MultiFab with no ghost cells
for (int lev = 0; lev <= finest_level; ++lev) {
MultiFab cons(grids[lev],dmap[lev],Cons::NumVars,0);
MultiFab::Copy(cons,vars_new[lev][Vars::cons],0,0,NVAR,0);
WriteNCMultiFab(cons, amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "Cell"));
MultiFab xvel(convert(grids[lev],IntVect(1,0,0)),dmap[lev],1,0);
MultiFab::Copy(xvel,vars_new[lev][Vars::xvel],0,0,1,0);
WriteNCMultiFab(xvel, amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "XFace"));
MultiFab yvel(convert(grids[lev],IntVect(0,1,0)),dmap[lev],1,0);
MultiFab::Copy(yvel,vars_new[lev][Vars::yvel],0,0,1,0);
WriteNCMultiFab(yvel, amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "YFace"));
MultiFab zvel(convert(grids[lev],IntVect(0,0,1)),dmap[lev],1,0);
MultiFab::Copy(zvel,vars_new[lev][Vars::zvel],0,0,1,0);
WriteNCMultiFab(zvel, amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "ZFace"));
}
}
//
// read NetCDF checkpoint to restart ERF
//
void
ERF::ReadNCCheckpointFile ()
{
amrex::Print() << "Restart from checkpoint " << restart_chkfile << "\n";
// Header
std::string HeaderFileName(restart_chkfile + "/Header.nc");
auto ncf = ncutils::NCFile::open(HeaderFileName, NC_CLOBBER | NC_NETCDF4);
const std::string nl_name = "finest_levels";
const std::string ng_name = "num_grids";
const std::string nvar_name = "num_vars";
const std::string ndt_name = "num_dt";
const std::string nstep_name = "num_istep";
const std::string ntime_name = "num_newtime";
const int nvar = static_cast<int>(ncf.dim(nvar_name).len());
AMREX_ALWAYS_ASSERT(nvar == Cons::NumVars);
const int ndt = static_cast<int>(ncf.dim(ndt_name).len());
const int nstep = static_cast<int>(ncf.dim(nstep_name).len());
const int ntime = static_cast<int>(ncf.dim(ntime_name).len());
// Assert we are reading in data with the same finest_level as we have
AMREX_ALWAYS_ASSERT(finest_level == static_cast<int>(ncf.dim(nl_name).len()));
// output headfile in NetCDF format
ncf.var("istep").get(istep.data(), {0}, {static_cast<long unsigned int>(nstep)});
ncf.var("dt") .get(dt.data(), {0}, {static_cast<long unsigned int>(ndt)});
ncf.var("t_new").get(t_new.data(), {0}, {static_cast<long unsigned int>(ntime)});
int ngrow_state = ComputeGhostCells(solverChoice.spatial_order)+1;
int ngrow_vels = ComputeGhostCells(solverChoice.spatial_order);
for (int lev = 0; lev <= finest_level; ++lev) {
int num_box = static_cast<int>(ncf.dim("Nbox_"+std::to_string(lev)).len());
// read in level 'lev' BoxArray from Header
BoxArray ba;
for (int nb(0); nb < num_box; ++nb) {
amrex::IntVect lo(AMREX_SPACEDIM);
amrex::IntVect hi(AMREX_SPACEDIM);
amrex::IntVect typ(AMREX_SPACEDIM);
auto lo_name = "SmallEnd_"+std::to_string(lev)+"_"+std::to_string(nb);
auto hi_name = "BigEnd_"+std::to_string(lev)+"_"+std::to_string(nb);
auto typ_name = "BoxType_"+std::to_string(lev)+"_"+std::to_string(nb);
ncf.var(lo_name) .get(lo.begin(), {0}, {AMREX_SPACEDIM});
ncf.var(hi_name) .get(hi.begin(), {0}, {AMREX_SPACEDIM});
ncf.var(typ_name).get(typ.begin(),{0}, {AMREX_SPACEDIM});
amrex::Box box = amrex::Box(lo, hi, typ);
ba.set(nb, box);
}
// ba.readFrom(is);
// GotoNextLine(is);
// create a distribution mapping
DistributionMapping dm { ba, ParallelDescriptor::NProcs() };
// set BoxArray grids and DistributionMapping dmap in AMReX_AmrMesh.H class
SetBoxArray(lev, ba);
SetDistributionMap(lev, dm);
// build MultiFab data
int ncomp = Cons::NumVars;
auto& lev_old = vars_old[lev];
auto& lev_new = vars_new[lev];
lev_new[Vars::cons].define(grids[lev], dmap[lev], ncomp, ngrow_state);
lev_old[Vars::cons].define(grids[lev], dmap[lev], ncomp, ngrow_state);
//!don: get the ghost cells right here
lev_new[Vars::xvel].define(convert(grids[lev], IntVect(1,0,0)), dmap[lev], 1, ngrow_vels);
lev_old[Vars::xvel].define(convert(grids[lev], IntVect(1,0,0)), dmap[lev], 1, ngrow_vels);
lev_new[Vars::yvel].define(convert(grids[lev], IntVect(0,1,0)), dmap[lev], 1, ngrow_vels);
lev_old[Vars::yvel].define(convert(grids[lev], IntVect(0,1,0)), dmap[lev], 1, ngrow_vels);
lev_new[Vars::zvel].define(convert(grids[lev], IntVect(0,0,1)), dmap[lev], 1, ngrow_vels);
lev_old[Vars::zvel].define(convert(grids[lev], IntVect(0,0,1)), dmap[lev], 1, ngrow_vels);
}
// read in the MultiFab data
for (int lev = 0; lev <= finest_level; ++lev)
{
MultiFab cons(grids[lev],dmap[lev],Cons::NumVars,0);
WriteNCMultiFab(cons, amrex::MultiFabFileFullPrefix(lev, restart_chkfile, "Level_", "Cell"));
MultiFab::Copy(vars_new[lev][Vars::cons],cons,0,0,Cons::NumVars,0);
MultiFab xvel(convert(grids[lev],IntVect(1,0,0)),dmap[lev],1,0);
WriteNCMultiFab(xvel, amrex::MultiFabFileFullPrefix(lev, restart_chkfile, "Level_", "Cell"));
MultiFab::Copy(vars_new[lev][Vars::xvel],xvel,0,0,1,0);
MultiFab yvel(convert(grids[lev],IntVect(0,1,0)),dmap[lev],1,0);
WriteNCMultiFab(yvel, amrex::MultiFabFileFullPrefix(lev, restart_chkfile, "Level_", "Cell"));
MultiFab::Copy(vars_new[lev][Vars::yvel],yvel,0,0,1,0);
MultiFab zvel(convert(grids[lev],IntVect(0,0,1)),dmap[lev],1,0);
WriteNCMultiFab(zvel, amrex::MultiFabFileFullPrefix(lev, restart_chkfile, "Level_", "Cell"));
MultiFab::Copy(vars_new[lev][Vars::zvel],zvel,0,0,1,0);
// Copy from new into old just in case
MultiFab::Copy(vars_old[lev][Vars::cons],vars_new[lev][Vars::cons],0,0,NVAR,0);
MultiFab::Copy(vars_old[lev][Vars::xvel],vars_new[lev][Vars::xvel],0,0,1,0);
MultiFab::Copy(vars_old[lev][Vars::yvel],vars_new[lev][Vars::yvel],0,0,1,0);
MultiFab::Copy(vars_old[lev][Vars::zvel],vars_new[lev][Vars::zvel],0,0,1,0);
}
}
| 43.852321 | 101 | 0.620995 | etpalmer63 |
0ca9e8d598056fbe8c5fe6853b7646c56cc9445d | 1,034 | cpp | C++ | Source/NdiMediaEditor/Private/Factories/NdiMediaFinderFactoryNew.cpp | Twentystudios/NdiMedia | 4cc842c11940fbd2062cb940cce1e49ff5bea453 | [
"BSD-3-Clause"
] | 101 | 2016-08-05T10:33:42.000Z | 2022-03-11T13:10:28.000Z | Source/NdiMediaEditor/Private/Factories/NdiMediaFinderFactoryNew.cpp | Twentystudios/NdiMedia | 4cc842c11940fbd2062cb940cce1e49ff5bea453 | [
"BSD-3-Clause"
] | 35 | 2016-10-03T14:35:25.000Z | 2021-03-25T05:18:34.000Z | Source/NdiMediaEditor/Private/Factories/NdiMediaFinderFactoryNew.cpp | Twentystudios/NdiMedia | 4cc842c11940fbd2062cb940cce1e49ff5bea453 | [
"BSD-3-Clause"
] | 34 | 2016-08-19T15:34:55.000Z | 2021-12-08T14:42:33.000Z | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "NdiMediaFinderFactoryNew.h"
#include "AssetTypeCategories.h"
#include "NdiMediaFinder.h"
/* UNdiMediaFinderFactoryNew structors
*****************************************************************************/
UNdiMediaFinderFactoryNew::UNdiMediaFinderFactoryNew(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
SupportedClass = UNdiMediaFinder::StaticClass();
bCreateNew = true;
bEditAfterNew = true;
}
/* UFactory overrides
*****************************************************************************/
UObject* UNdiMediaFinderFactoryNew::FactoryCreateNew(UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, UObject* Context, FFeedbackContext* Warn)
{
return NewObject<UNdiMediaFinder>(InParent, InClass, InName, Flags);
}
uint32 UNdiMediaFinderFactoryNew::GetMenuCategories() const
{
return EAssetTypeCategories::Media;
}
bool UNdiMediaFinderFactoryNew::ShouldShowInNewMenu() const
{
return true;
}
| 25.85 | 164 | 0.678917 | Twentystudios |
0cab53c9531ac6a58961228d5057b37aeb9ad755 | 3,499 | cpp | C++ | src/ThirdParty/Box2D/Lua/Collision/Shapes/PolygonShape.cpp | andoma/rainbow | ed1e70033217450457e52b90276e41a746d5086a | [
"MIT"
] | null | null | null | src/ThirdParty/Box2D/Lua/Collision/Shapes/PolygonShape.cpp | andoma/rainbow | ed1e70033217450457e52b90276e41a746d5086a | [
"MIT"
] | null | null | null | src/ThirdParty/Box2D/Lua/Collision/Shapes/PolygonShape.cpp | andoma/rainbow | ed1e70033217450457e52b90276e41a746d5086a | [
"MIT"
] | 1 | 2018-09-20T19:34:36.000Z | 2018-09-20T19:34:36.000Z | // Copyright (c) 2010-present Bifrost Entertainment AS and Tommy Nguyen
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
#include "ThirdParty/Box2D/Lua/Collision/Shapes/PolygonShape.h"
#include <memory>
#include <Box2D/Collision/Shapes/b2PolygonShape.h>
NS_B2_LUA_BEGIN
{
constexpr bool PolygonShape::is_constructible;
const char PolygonShape::class_name[] = "PolygonShape";
const luaL_Reg PolygonShape::functions[]{
{"GetType", &PolygonShape::GetType},
{"GetChildCount", &PolygonShape::GetChildCount},
{"Set", &PolygonShape::Set},
{"SetAsBox", &PolygonShape::SetAsBox},
{"TestPoint", &PolygonShape::TestPoint},
{"RayCast", &PolygonShape::RayCast},
{"ComputeAABB", &PolygonShape::ComputeAABB},
{"ComputeMass", &PolygonShape::ComputeMass},
{"Validate", &PolygonShape::Validate},
{nullptr, nullptr}};
PolygonShape::PolygonShape(lua_State* L) : is_owner_(false)
{
if (rainbow::lua::isuserdata(L, -1))
polygon_.reset(static_cast<b2PolygonShape*>(lua_touserdata(L, -1)));
else
{
polygon_ = std::make_unique<b2PolygonShape>();
is_owner_ = true;
}
}
PolygonShape::~PolygonShape()
{
if (!is_owner_)
polygon_.release();
}
int PolygonShape::GetType(lua_State* L)
{
lua_pushinteger(L, b2Shape::e_polygon);
return 1;
}
int PolygonShape::GetChildCount(lua_State* L)
{
lua_pushinteger(L, 1);
return 1;
}
int PolygonShape::Set(lua_State* L)
{
rainbow::lua::checkargs<PolygonShape, void*, lua_Number>(L);
PolygonShape* self = Bind::self(L);
if (self == nullptr)
return 0;
const int count = static_cast<int>(lua_tointeger(L, 3));
auto points = std::make_unique<b2Vec2[]>(count);
for (int i = 0; i < count; ++i)
{
lua_rawgeti(L, 2, i + 1);
points[i] = b2Vec2(luaR_getnumber(L, "x"), luaR_getnumber(L, "y"));
lua_pop(L, 1);
}
self->get()->Set(points.get(), count);
return 0;
}
int PolygonShape::SetAsBox(lua_State* L)
{
PolygonShape* self = Bind::self(L);
if (self == nullptr)
return 0;
const int n = lua_gettop(L);
LUA_ASSERT(L, n == 3 || n == 5, "3 or 5 parameters expected");
if (n == 3)
{
rainbow::lua::checkargs<PolygonShape, lua_Number, lua_Number>(L);
self->get()->SetAsBox(lua_tonumber(L, 2), lua_tonumber(L, 3));
}
else
{
rainbow::lua::checkargs<PolygonShape,
lua_Number,
lua_Number,
lua_Number,
lua_Number,
lua_Number>(L);
self->get()->SetAsBox(lua_tonumber(L, 2),
lua_tonumber(L, 3),
Vec2(L, 4, 5),
lua_tonumber(L, 6));
}
return 0;
}
int PolygonShape::Validate(lua_State* L)
{
return get1b(L, [](const b2PolygonShape* polygon) {
return polygon->Validate();
});
}
} NS_B2_LUA_END
| 30.163793 | 80 | 0.52415 | andoma |
0cacfb880c05969b886658d21854f8329e526d1f | 6,263 | hpp | C++ | stock_dbf_reader/stock_reader/mysql.hpp | smartdata-x/MarketSys | b4f999fb80b8f2357b75694c2ca94d46190a55f7 | [
"Apache-2.0"
] | null | null | null | stock_dbf_reader/stock_reader/mysql.hpp | smartdata-x/MarketSys | b4f999fb80b8f2357b75694c2ca94d46190a55f7 | [
"Apache-2.0"
] | null | null | null | stock_dbf_reader/stock_reader/mysql.hpp | smartdata-x/MarketSys | b4f999fb80b8f2357b75694c2ca94d46190a55f7 | [
"Apache-2.0"
] | 3 | 2016-10-25T01:56:17.000Z | 2019-06-24T04:45:06.000Z | #ifndef MYSQL_HPP_
#define MYSQL_HPP_
#include <cassert>
#include <cstdint>
#include <cstring>
#include <mysql.h>
#include <string>
#include <tuple>
#include <typeinfo>
#include <utility>
#include <vector>
#include "inpub_binder.hpp"
#include "mysql_exception.hpp"
#include "mysql_prepared_statement.hpp"
#include "output_binder.hpp"
#include "common.h"
#include "utils.hpp"
class mysql {
public:
mysql(base_logic::ConnAddr& configInfo);
~mysql();
mysql(const mysql& rhs) = delete;
mysql(mysql&& rhs) = delete;
mysql& operator=(const mysql& rhs) = delete;
mysql& operator=(mysql&& rhs) = delete;
public:
void OnDisconnec();
bool ConnectMySql();
bool Reconnect();
bool CheckConnected();
/**
* Normal query. Results are stored in the given vector.
* @param query The query to run.
* @param results A vector of tuples to store the results in.
* @param args Arguments to bind to the query.
*/
template <typename... InputArgs, typename... OutputArgs>
void runQuery(
std::vector<std::tuple<OutputArgs...>>* const results,
const char* const query,
// Args needs to be sent by reference, because the values need to be
// nontemporary (that is, lvalues) so that their memory locations
// can be bound to MySQL's prepared statement API
const InputArgs& ... args);
/**
* Command that doesn't return results, like "USE yelp" or
* "INSERT INTO user VALUES ('Brandon', 28)".
* @param query The query to run.
* @param args Arguments to bind to the query.
* @return The number of affected rows.
*/
/// @{
template <typename... Args>
my_ulonglong runCommand(
const char* const command,
// Args needs to be sent by reference, because the values need to be
// nontemporary (that is, lvalues) so that their memory locations
// can be bound to MySQL's prepared statement API
const Args& ... args) const;
my_ulonglong runCommand(const char* const command);
/// @}
/**
* Prepare a statement for multiple executions with different bound
* parameters. If you're running a one off query or statement, you
* should use runQuery or runCommand instead.
* @param query The query to prepare.
* @return A prepared statement object.
*/
MySqlPreparedStatement prepareStatement(const char* statement) const;
/**
* Run the command version of a prepared statement.
*/
/// @{
template <typename... Args>
my_ulonglong runCommand(
const MySqlPreparedStatement& statement,
const Args& ... args) const;
// my_ulonglong runCommand(const MySqlPreparedStatement& statement);
/// @}
/**
* Run the query version of a prepared statement.
*/
template <typename... InputArgs, typename... OutputArgs>
void runQuery(
std::vector<std::tuple<OutputArgs...>>* results,
const MySqlPreparedStatement& statement,
const InputArgs& ...) const;
private:
base_logic::ConnAddr& m_configInfo_;
int m_iReconnectCount_ = 0;
MYSQL* m_pConnection_;
};
template <typename... Args>
my_ulonglong mysql::runCommand(
const char* const command,
const Args& ... args
) const {
MySqlPreparedStatement statement(prepareStatement(command));
return runCommand(statement, args...);
}
template <typename... Args>
my_ulonglong mysql::runCommand(
const MySqlPreparedStatement& statement,
const Args& ... args
) const {
// Commands (e.g. INSERTs or DELETEs) should always have this set to 0
if (0 != statement.getFieldCount()) {
throw MySqlException("Tried to run query with runCommand");
}
if (sizeof...(args) != statement.getParameterCount()) {
std::string errorMessage;
errorMessage += "Incorrect number of parameters; command required ";
errorMessage += base_logic::Utils::convertString(statement.getParameterCount());
errorMessage += " but ";
errorMessage += base_logic::Utils::convertString(sizeof...(args));
errorMessage += " parameters were provided.";
throw MySqlException(errorMessage);
}
std::vector<MYSQL_BIND> bindParameters;
bindParameters.resize(statement.getParameterCount());
bindInputs<Args...>(&bindParameters, args...);
if (0 != mysql_stmt_bind_param(
statement.statementHandle_,
bindParameters.data())
) {
throw MySqlException(statement);
}
if (0 != mysql_stmt_execute(statement.statementHandle_)) {
throw MySqlException(statement);
}
// If the user ran a SELECT statement or something else, at least warn them
const auto affectedRows = mysql_stmt_affected_rows(
statement.statementHandle_);
if ((static_cast<decltype(affectedRows)>(-1)) == affectedRows) {
throw MySqlException("Tried to run query with runCommand");
}
return affectedRows;
}
template <typename... InputArgs, typename... OutputArgs>
void mysql::runQuery(
std::vector<std::tuple<OutputArgs...>>* const results,
const char* const query,
const InputArgs& ... args) {
assert(nullptr != results);
assert(nullptr != query);
MySqlPreparedStatement statement(prepareStatement(query));
runQuery(results, statement, args...);
}
template <typename... InputArgs, typename... OutputArgs>
void mysql::runQuery(
std::vector<std::tuple<OutputArgs...>>* const results,
const MySqlPreparedStatement& statement,
const InputArgs& ... args
) const {
assert(nullptr != results);
// SELECTs should always return something. Commands (e.g. INSERTs or
// DELETEs) should always have this set to 0.
if (0 == statement.getFieldCount()) {
throw MySqlException("Tried to run command with runQuery");
}
// Bind the input parameters
// Check that the parameter count is right
if (sizeof...(InputArgs) != statement.getParameterCount()) {
std::string errorMessage;
errorMessage += "Incorrect number of input parameters; query required ";
errorMessage += base_logic::Utils::convertString(statement.getParameterCount());
errorMessage += " but ";
errorMessage += base_logic::Utils::convertString(sizeof...(args));
errorMessage += " parameters were provided.";
throw MySqlException(errorMessage);
}
std::vector<MYSQL_BIND> inputBindParameters;
inputBindParameters.resize(statement.getParameterCount());
bindInputs<InputArgs...>(&inputBindParameters, args...);
if (0 != mysql_stmt_bind_param(
statement.statementHandle_,
inputBindParameters.data())
) {
throw MySqlException(statement);
}
setResults<OutputArgs...>(statement, results);
}
#endif // MYSQL_HPP_
| 29.82381 | 82 | 0.724254 | smartdata-x |
0caf3556f4e8aeb0bd63da5b06a2f2ffe22fd226 | 7,087 | cpp | C++ | groups/bsl/bslstl/bslstl_iosfwd.t.cpp | seanbaxter/bde-1 | 149176ebc2ae49c3b563895a7332fe638a760782 | [
"Apache-2.0"
] | 1 | 2022-01-23T11:31:12.000Z | 2022-01-23T11:31:12.000Z | groups/bsl/bslstl/bslstl_iosfwd.t.cpp | seanbaxter/bde-1 | 149176ebc2ae49c3b563895a7332fe638a760782 | [
"Apache-2.0"
] | 2 | 2020-11-05T15:20:55.000Z | 2021-01-05T19:38:43.000Z | groups/bsl/bslstl/bslstl_iosfwd.t.cpp | seanbaxter/bde-1 | 149176ebc2ae49c3b563895a7332fe638a760782 | [
"Apache-2.0"
] | 2 | 2020-01-16T17:58:12.000Z | 2020-08-11T20:59:30.000Z | // bslstl_iosfwd.t.cpp -*-C++-*-
#include <bslstl_iosfwd.h>
#include <bsls_bsltestutil.h>
#include <stdio.h>
#include <stdlib.h>
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
// Overview
// --------
// The component under test provides no functionality per se. Its sole purpose
// is to provide forward declarations, in its header file (for the convenience
// of 'bsl_iosfwd.h' in package 'bsl+bslhdrs'), of the standard types provided
// by the four 'bslstl' components that implement string-based streams.
// Therefore, it is sufficient to verify, via appropriate declarations, that
// the forward declarations are visible as expected.
//-----------------------------------------------------------------------------
// [ 1] BREATHING TEST
// ============================================================================
// STANDARD BSL ASSERT TEST FUNCTION
// ----------------------------------------------------------------------------
namespace {
int testStatus = 0;
void aSsErT(bool condition, const char *message, int line)
{
if (condition) {
printf("Error " __FILE__ "(%d): %s (failed)\n", line, message);
if (0 <= testStatus && testStatus <= 100) {
++testStatus;
}
}
}
} // close unnamed namespace
// ============================================================================
// STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT BSLS_BSLTESTUTIL_ASSERT
#define ASSERTV BSLS_BSLTESTUTIL_ASSERTV
#define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT
#define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally.
#define P BSLS_BSLTESTUTIL_P // Print identifier and value.
#define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLS_BSLTESTUTIL_L_ // current Line number
// ============================================================================
// NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)
#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)
#define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR)
#define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)
#define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)
#define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)
// ============================================================================
// GLOBAL TEST VALUES
// ----------------------------------------------------------------------------
//=============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------
//=============================================================================
// TEST FACILITIES
//-----------------------------------------------------------------------------
//=============================================================================
// USAGE EXAMPLE
//-----------------------------------------------------------------------------
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
bool verbose = argc > 2;
bool veryVerbose = argc > 3;
bool veryVeryVerbose = argc > 4;
bool veryVeryVeryVerbose = argc > 5;
(void)veryVerbose; // suppress warning
(void)veryVeryVerbose; // suppress warning
(void)veryVeryVeryVerbose; // suppress warning
printf("TEST " __FILE__ " CASE %d\n", test);
switch (test) { case 0: // Zero is always the leading case.
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST:
// Developers' Sandbox.
//
// Plan:
// Use, in name only, each of the standard types for which this
// component provides a forward declaration.
//
// Testing:
// This "test" *exercises* basic functionality, but *tests* nothing.
// --------------------------------------------------------------------
if (verbose) printf("\nBREATHING TEST"
"\n==============\n");
typedef void (*F1)(bsl::stringbuf&);
typedef void (*F2)(bsl::wstringbuf&);
typedef void (*F3)(bsl::istringstream&);
typedef void (*F4)(bsl::wistringstream&);
typedef void (*F5)(bsl::ostringstream&);
typedef void (*F6)(bsl::wostringstream&);
typedef void (*F7)(bsl::stringstream&);
typedef void (*F8)(bsl::wstringstream&);
// Meangless assertions to eliminate gcc "unused" warnings
ASSERT(sizeof(F1) == sizeof(F2));
ASSERT(sizeof(F3) == sizeof(F4));
ASSERT(sizeof(F5) == sizeof(F6));
ASSERT(sizeof(F7) == sizeof(F8));
} break;
default: {
fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
testStatus = -1;
}
}
if (testStatus > 0) {
fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
| 40.497143 | 79 | 0.466488 | seanbaxter |
0caf9398d1c7d6488eb8bcf273e9469f33ce18a1 | 2,082 | cc | C++ | src/ctl3d.cc | snmsts/xyzzy | 3291c7898d17f90b1a50c3de1aeb5f9a446d9061 | [
"RSA-MD"
] | 90 | 2015-01-13T13:36:13.000Z | 2022-03-25T12:22:19.000Z | src/ctl3d.cc | wanabe/xyzzy | a43581d9a2033d5c43d99cccfecc8e90aa3915e1 | [
"RSA-MD"
] | 6 | 2015-09-07T17:03:43.000Z | 2019-08-13T12:35:48.000Z | src/ctl3d.cc | wanabe/xyzzy | a43581d9a2033d5c43d99cccfecc8e90aa3915e1 | [
"RSA-MD"
] | 38 | 2015-02-21T13:42:59.000Z | 2022-03-25T12:25:15.000Z | #include "stdafx.h"
#include "sysdep.h"
#include "ctl3d.h"
#include "vfs.h"
static Ctl3d ctl3d;
Ctl3dState Ctl3d::state;
Ctl3d::~Ctl3d ()
{
if (state.registered && state.Unregister)
(*state.Unregister)(state.hinst);
if (state.hlib)
FreeLibrary (state.hlib);
}
void
Ctl3d::enable (HINSTANCE h)
{
if (sysdep.Win4p () || state.registered)
return;
if (!state.hlib)
{
state.hlib = WINFS::LoadLibrary ("ctl3d32.dll");
if (!state.hlib)
return;
state.Register = (BOOL (WINAPI *)(HINSTANCE))
GetProcAddress (state.hlib, "Ctl3dRegister");
state.Unregister = (BOOL (WINAPI *)(HINSTANCE))
GetProcAddress (state.hlib, "Ctl3dUnregister");
state.AutoSubclass = (BOOL (WINAPI *)(HINSTANCE))
GetProcAddress (state.hlib, "Ctl3dAutoSubclass");
state.UnAutoSubclass = (BOOL (WINAPI *)())
GetProcAddress (state.hlib, "Ctl3dUnAutoSubclass");
state.ColorChange = (BOOL (WINAPI *)())
GetProcAddress (state.hlib, "Ctl3dColorChange");
state.WinIniChange = (void (WINAPI *)())
GetProcAddress (state.hlib, "Ctl3dWinIniChange");
if (!state.Register || !state.Unregister
|| !state.AutoSubclass || !state.UnAutoSubclass
|| !state.ColorChange || !state.WinIniChange)
{
FreeLibrary (state.hlib);
state.hlib = 0;
return;
}
}
if (state.Register && state.AutoSubclass)
{
state.hinst = h;
(*state.Register)(state.hinst);
(*state.AutoSubclass)(state.hinst);
state.registered = 1;
}
}
void
Ctl3d::color_change ()
{
if (state.registered && state.ColorChange)
(*state.ColorChange)();
}
void
Ctl3d::ini_change ()
{
if (state.registered && state.WinIniChange)
(*state.WinIniChange)();
}
Ctl3dThread::Ctl3dThread ()
{
if (Ctl3d::state.registered && Ctl3d::state.AutoSubclass)
(*Ctl3d::state.AutoSubclass)(Ctl3d::state.hinst);
}
Ctl3dThread::~Ctl3dThread ()
{
if (Ctl3d::state.registered && Ctl3d::state.UnAutoSubclass)
(*Ctl3d::state.UnAutoSubclass)();
}
| 24.785714 | 61 | 0.627281 | snmsts |
0cb0513f28bd47fae2000ccd5f98171296258825 | 13,736 | cpp | C++ | src/elektronika/about.cpp | aestesis/elektronika | 870f72ca7f64942f8316b3cd8f733f43c7d2d117 | [
"Apache-2.0"
] | 14 | 2016-05-09T01:14:03.000Z | 2021-10-12T21:41:02.000Z | src/elektronika/about.cpp | aestesis/elektronika | 870f72ca7f64942f8316b3cd8f733f43c7d2d117 | [
"Apache-2.0"
] | null | null | null | src/elektronika/about.cpp | aestesis/elektronika | 870f72ca7f64942f8316b3cd8f733f43c7d2d117 | [
"Apache-2.0"
] | 6 | 2015-08-19T01:28:54.000Z | 2020-10-25T05:17:08.000Z | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// ABOUT.CPP (c) YoY'00 WEB: www.aestesis.org
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <math.h>
#include "about.h"
#include "main.h"
#include "resource.h"
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ACI Aabout::CI=ACI("Aabout", GUID(0x11111111,0x00000103), &Awindow::CI, 0, NULL);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class AaboutMenu : public Aobject
{
AOBJ
AaboutMenu (char *name, class Aobject *L, int x, int y, int w, int h);
virtual ~AaboutMenu ();
virtual void paint (Abitmap *b);
virtual bool mouse (int x, int y, int state, int event);
void calculText ();
int position;
Afont *font;
char str[8192][128];
int nbstr;
};
ACI AaboutMenu::CI=ACI("AaboutMenu", GUID(0x11111111,0x00000114), &Aobject::CI, 0, NULL);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AaboutMenu::AaboutMenu(char *name, Aobject *L, int x, int y, int w, int h) : Aobject(name, L, x, y, w, h)
{
state|=stateNOCONTEXT;
position=0;
font=alib.getFont(fontTERMINAL09);
calculText();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AaboutMenu::~AaboutMenu()
{
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool AaboutMenu::mouse(int x, int y, int state, int event)
{
switch(event)
{
case mouseWHEEL:
position=maxi(mini(position-(getWindow()->mouseW>>5), nbstr-5), 0);
return true;
}
return ((Aobject *)father)->mouse(x+pos.x, y+pos.y, state, event);
}
void AaboutMenu::calculText()
{
{
Aresobj *text=resource.getObj(MAKEINTRESOURCE(TXT_LICENSEDEMO), "TXT");
char *txt=(char *)text->lock();
int size=text->getSize();
int p=0;
nbstr=0;
while(p<size)
{
int d=p;
int w=4;
char t[2];
int l=size-p;
int pn=p;
char s=0;
int last;
t[1]=0;
while((p<size)&&(w<this->pos.w))
{
last=p;
s=t[0]=txt[p++];
switch(s)
{
case ' ':
l=p-d;
pn=p;
w+=font->w>>1;
break;
case '\n':
d=p;
break;
case '\r':
l=p-d;
pn=p;
w=this->pos.w;
break;
default:
w+=font->getWidth(t);
break;
}
}
if(!(p>=size))
p=pn;
else
l=p-d;
if(l>0)
{
strncpy(str[nbstr], txt+d, l);
str[nbstr++][l]=0;
}
else
str[nbstr++][0]=0;
}
text->unlock();
delete(text);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void AaboutMenu::paint(Abitmap *b)
{
b->boxfa(0, 0, pos.w-1, pos.h-1, 0xff000000, 0.9f);
{
int y=4;
int p=position;
int h=font->getHeight("A");
while(((y+h)<pos.h)&&(p<nbstr))
{
font->set(b, 4, y, str[p], 0xffffaa00);
p++;
y+=h;
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Aabout::Aabout(char *name, int x, int y, class MYwindow *myw) : Awindow(name, x, y, 400, 300)
{
this->myw=myw;
bac=false;
zorder(zorderTOP);
back=new Abitmap(pos.w, pos.h);
title=new Astatic("title", this, 0, 0, &resource.get(MAKEINTRESOURCE(PNG_ELEKTRONIKA), "PNG"));
title->show(TRUE);
buttonClose=new Abutton("close", this, 378, 6, 16, 16, &alibres.get(MAKEINTRESOURCE(117), "PNG"));
buttonClose->setTooltips("close button");
buttonClose->show(TRUE);
pal.ar=frand()*100.f;
pal.ag=frand()*100.f;
pal.ab=frand()*100.f;
pal.dr=(frand()+0.1f)*0.1f;
pal.dg=(frand()+0.1f)*0.1f;
pal.db=(frand()+0.1f)*0.1f;
pal.ar0=frand()*100.f;
pal.ag0=frand()*100.f;
pal.ab0=frand()*100.f;
pal.dr0=(frand()+0.1f)*0.09f;
pal.dg0=(frand()+0.1f)*0.09f;
pal.db0=(frand()+0.1f)*0.09f;
pal.ar1=frand()*100.f;
pal.ag1=frand()*100.f;
pal.ab1=frand()*100.f;
pal.dr1=(frand()+0.1f)*0.03f;
pal.dg1=(frand()+0.1f)*0.03f;
pal.db1=(frand()+0.1f)*0.03f;
pal.ar10=frand()*100.f;
pal.ag10=frand()*100.f;
pal.ab10=frand()*100.f;
pal.dr10=(frand()+0.1f)*0.01f;
pal.dg10=(frand()+0.1f)*0.01f;
pal.db10=(frand()+0.1f)*0.01f;
pal.n=1.f/(frand()*512.f+16.f);
zyg.zz1=5.f/(frand()*pos.w*10.f+(float)pos.w);
zyg.zz2=5.f/(frand()*pos.w*10.f+(float)pos.w);
zyg.zz3=5.f/(frand()*pos.w*10.f+(float)pos.w);
zyg.ax1=frand()*100.f;
zyg.ay1=frand()*100.f;
zyg.ax2=frand()*100.f;
zyg.ay2=frand()*100.f;
zyg.ax3=frand()*100.f;
zyg.ay3=frand()*100.f;
zyg.dx1=(frand()+0.1f)*0.03f;
zyg.dy1=(frand()+0.1f)*0.03f;
zyg.dx2=(frand()+0.1f)*0.03f;
zyg.dy2=(frand()+0.1f)*0.03f;
zyg.dx3=(frand()+0.1f)*0.03f;
zyg.dy3=(frand()+0.1f)*0.03f;
menu=new AaboutMenu("about menu", this, 10, pos.h-110, pos.w-20, 100);
menu->show(TRUE);
hlp=new Abutton("help", this, 306, 120, 80, 16, "HELP");
hlp->setTooltips("help file");
hlp->show(true);
web=new Abutton("web", this, 306, 140, 80, 16, "WEB");
web->setTooltips("aestesis web site");
web->show(true);
reg=new Abutton("reg", this, 306, 160, 80, 16, "DONATE");
reg->setTooltips("donate");
reg->show(true);
timer(100);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Aabout::~Aabout()
{
timer(0);
delete(hlp);
delete(web);
delete(reg);
delete(back);
delete(title);
delete(buttonClose);
delete(menu);
back=NULL;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Aabout::mouse(int x, int y, int state, int event)
{
switch(event)
{
case mouseLDOWN:
wx=pos.x;
wy=pos.y;
lx=pos.x+x;
ly=pos.y+y;
bac=TRUE;
mouseCapture(TRUE);
return TRUE;
case mouseNORMAL:
if((state&mouseL)&&bac)
move(wx+(x+pos.x)-lx, wy+(y+pos.y)-ly);
return TRUE;
case mouseLUP:
bac=FALSE;
mouseCapture(FALSE);
return TRUE;
case mouseRDOWN:
destroy();
return TRUE;
}
return FALSE;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Aabout::notify(Anode *o, int event, dword p)
{
switch(event)
{
case nyCLICK:
if(o==buttonClose)
{
destroy();
}
else if(o==hlp)
{
char help[1024];
GetModuleFileName(GetModuleHandle(null), help, sizeof(help));
if(help[0])
{
char *s=strrchr(help, '\\');
if(s)
*s=0;
}
strcat(help, "\\help\\elektronika.chm");
ShellExecute(getWindow()->hw, "open", help, NULL, NULL, SW_SHOWNORMAL);
}
else if(o==web)
{
ShellExecute(getWindow()->hw, "open", "http://www.aestesis.eu/", NULL, NULL, SW_SHOWNORMAL);
//httpto("http://www.aestesis.org/");
}
else if(o==reg)
{
ShellExecute(getWindow()->hw, "open", "http://aestesis.eu/", NULL, NULL, SW_SHOWNORMAL);
//httpto("http://www.aestesis.org/aestesis/register.php");
}
break;
}
return Aobject::notify(o, event , p);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Aabout::paint(Abitmap *b)
{
b->set(0, 0, back, bitmapDEFAULT, bitmapDEFAULT);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Aabout::pulse()
{
if(back)
{
int x,y,i;
dword palette[8192];
{
float ar=pal.ar;
float ag=pal.ag;
float ab=pal.ab;
float dr=pal.dr*0.1f;
float dg=pal.dg*0.1f;
float db=pal.db*0.1f;
float ar0=pal.ar0;
float ag0=pal.ag0;
float ab0=pal.ab0;
float dr0=pal.dr0*0.1f;
float dg0=pal.dg0*0.1f;
float db0=pal.db0*0.1f;
float ar1=pal.ar1;
float ag1=pal.ag1;
float ab1=pal.ab1;
float dr1=pal.dr1*0.1f;
float dg1=pal.dg1*0.1f;
float db1=pal.db1*0.1f;
float ar10=pal.ar10;
float ag10=pal.ag10;
float ab10=pal.ab10;
float dr10=pal.dr10*0.1f;
float dg10=pal.dg10*0.1f;
float db10=pal.db10*0.1f;
float n=pal.n*0.1f;
for(i=0; i<8192; i++)
{
float m=(float)sin(PI*(float)i*n)*0.4999f+0.5f;
float vb=(float)(sin(PI*(float)i*0.01f)*0.5f+0.5f);
byte r=(byte)(vb*((1.f-m)*((float)sin(ar1)*sin(ar10)*127.9f+128.f)+m*((float)sin(ar)*sin(ar0)*127.9f+128.f)))&255;
byte g=(byte)(vb*((1.f-m)*((float)sin(ag1)*sin(ag10)*127.9f+128.f)+m*((float)sin(ag)*sin(ag0)*127.9f+128.f)))&255;
byte b=0;//(byte)(vb*((1.f-m)*((float)sin(ab1)*sin(ab10)*127.9f+128.f)+m*((float)sin(ab)*sin(ab0)*127.9f+128.f)))&255;
palette[i]=color32(r, g, b, 255);
ar+=dr;
ag+=dg;
ab+=db;
ar0+=dr0;
ag0+=dg0;
ab0+=db0;
ar1+=dr1;
ag1+=dg1;
ab1+=db1;
ar10+=dr10;
ag10+=dg10;
ab10+=db10;
}
pal.ar+=pal.dr*10.f;
pal.ag+=pal.dg*10.f;
pal.ab+=pal.db*10.f;
pal.ar0+=pal.dr0*10.f;
pal.ag0+=pal.dg0*10.f;
pal.ab0+=pal.db0*10.f;
pal.ar1+=pal.dr1*10.f;
pal.ag1+=pal.dg1*10.f;
pal.ab1+=pal.db1*10.f;
pal.ar10+=pal.dr10*10.f;
pal.ag10+=pal.dg10*10.f;
pal.ab10+=pal.db10*10.f;
}
{
dword *d=back->body32;
float xx1=(float)sin(zyg.ax1)*pos.w;
float yy1=(float)sin(zyg.ay1)*pos.h;
float xx2=(float)sin(zyg.ax2)*pos.w;
float yy2=(float)sin(zyg.ay2)*pos.h;
float xx3=(float)sin(zyg.ax2)*pos.w;
float yy3=(float)sin(zyg.ay2)*pos.h;
zyg.ax1+=zyg.dx1;
zyg.ay1+=zyg.dy1;
zyg.ax2+=zyg.dx2;
zyg.ay2+=zyg.dy2;
zyg.ax3+=zyg.dx3;
zyg.ay3+=zyg.dy3;
for(y=0; y<pos.h; y++)
{
float dy1=(float)y-yy1;
float dy2=(float)y-yy2;
float dy3=(float)y-yy3;
dy1*=dy1;
dy2*=dy2;
dy3*=dy3;
for(x=0; x<pos.w; x++)
{
float dx1=(float)x-xx1;
float dx2=(float)x-xx2;
float dx3=(float)x-xx3;
*(d++)=palette[(int)(((float)sin(sqrt(dx1*dx1+dy1)*zyg.zz1) + (float)sin(sqrt(dx2*dx2+dy2)*zyg.zz2) + (float)sin(sqrt(dx2*dx2+dy2)*zyg.zz2) ) * (4095.f/3.f)+ 4096.f )];
}
}
}
back->boxfa(0,0,pos.w-1,pos.h-1,0xffffaa00,0.5f);
back->boxa(0,0,pos.w-1, pos.h-1,0xff000000,0.8f);
back->boxa(1,1,pos.w-2, pos.h-2,0xff000000,0.8f);
back->boxa(2,2,pos.w-3, pos.h-3,0xff000000,0.8f);
back->boxa(3,3,pos.w-4, pos.h-4,0xff000000,0.8f);
back->boxa(4,4,pos.w-5, pos.h-5,0xff000000,0.8f);
back->boxa(5,5,pos.w-6, pos.h-6,0xff000000,0.8f);
{
Afont *font=alib.getFont(fontCONFIDENTIAL14);
font->set(back, 10, 70, "live version " VERSION, 0xffffffff);
font->set(back, 10, pos.h-136, "aestesis 1991,2009", 0xffffffff);
font->set(back, 10, pos.h-176, "software developer YoY", 0xff000000);
font->set(back, 10, pos.h-156, "(CC) RENAN JEGOUZO", 0xff808080);
}
repaint();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 30.056893 | 174 | 0.39684 | aestesis |
0cb1fc67cfbbe61ad46e1197e2c8480758321140 | 11,631 | hpp | C++ | src/xsimd_fallback/xsimd_fallback_batch_impl.hpp | thexdesk/HiQsimulator | 0050444a7694de8c287d717d55870d12ff14c5e0 | [
"Apache-2.0"
] | 98 | 2019-07-08T01:41:51.000Z | 2022-03-11T14:51:01.000Z | src/xsimd_fallback/xsimd_fallback_batch_impl.hpp | thexdesk/HiQsimulator | 0050444a7694de8c287d717d55870d12ff14c5e0 | [
"Apache-2.0"
] | 36 | 2019-07-12T01:45:36.000Z | 2021-10-20T02:37:32.000Z | src/xsimd_fallback/xsimd_fallback_batch_impl.hpp | thexdesk/HiQsimulator | 0050444a7694de8c287d717d55870d12ff14c5e0 | [
"Apache-2.0"
] | 40 | 2019-07-10T20:20:29.000Z | 2022-03-11T14:51:20.000Z | // Copyright 2019 <Huawei Technologies Co., Ltd>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
//! Default constructor
template <typename T, std::size_t N>
xsimd::batch<T, N>::batch() : array_data_{}
{}
//! Constructor from an array of values
/*!
* Initializes a batch to the values pointed by \c data.
*/
template <typename T, std::size_t N>
xsimd::batch<T, N>::batch(T data[N])
: array_data_{details::array_from_pointer<T, N>(data)}
{}
//! Constructor from an array of values
/*!
* Initializes a batch to the values pointed by \c data.
*/
template <typename T, std::size_t N>
xsimd::batch<T, N>::batch(const std::array<T, N>& data) : array_data_{data}
{}
//! Constructor from scalar values
/*!
* Initializes all the values of the batch to \c val.
*/
template <typename T, std::size_t N>
xsimd::batch<T, N>::batch(T val)
: array_data_(details::array_from_scalar<T, N>(val))
{}
// -----------------------------------------------------------------------------
//! Access element (const)
/*!
* \param idx Index of an element in the batch
* \return The element at the specified position
*/
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::operator[](std::size_t idx) const
{
return array_data_[idx];
}
//! Access element
/*!
* \param idx Index of an element in the batch
* \return A reference to the element at the specified position
*/
template <typename T, std::size_t N>
auto& xsimd::batch<T, N>::operator[](std::size_t idx)
{
return array_data_[idx];
}
// =============================================================================
// Assignment operators
//! Assignment operator
/*!
* Assignment operator for batches of constant values.
*
* \param rhs Batch of constant values
* \return A reference to \c this.
*/
template <typename T, std::size_t N>
auto& xsimd::batch<T, N>::operator=(const batch<const T, N>& rhs)
{
PRAGMA_LOOP_IVDEP
for (std::size_t i(0); i < size; ++i) {
array_data_[i] = rhs[i];
}
return *this;
}
//! Move assignment operator
/*!
* Move assignment operator for batches of constant values.
*
* \param rhs R-value of batch of constant values
* \return A reference to \c this.
*/
template <typename T, std::size_t N>
auto& xsimd::batch<T, N>::operator=(batch<const T, N>&& rhs)
{
PRAGMA_LOOP_IVDEP
for (std::size_t i(0); i < size; ++i) {
array_data_[i] = rhs[i];
}
return *this;
}
//! Assignment operator for arbitrary expressions
/*!
* \param rhs RHS expression
* \return A reference to \c this.
*/
template <typename T, std::size_t N>
template <typename U, typename>
auto& xsimd::batch<T, N>::operator=(U&& rhs)
{
static_assert(size == details::expr_size<U>::size,
"Expression size must match batch size");
/*
* This can lead to near-optimal code if the compiler is
* allowed to vectorize and unroll the loop automatically
*/
PRAGMA_LOOP_IVDEP
for (std::size_t i(0); i < size; ++i) {
array_data_[i]
= details::make_expr(std::forward<U>(rhs))(eval_visitor(i));
}
return *this;
}
// =============================================================================
// Inplace operators
#define DEFINE_INPLACE_OP(OP) \
template <typename T, std::size_t N> \
template <typename U, typename> \
auto& xsimd::batch<T, N>::operator OP(U&& rhs) \
{ \
static_assert(std::is_arithmetic<details::remove_cvref_t<U>>::value \
|| size == details::expr_size<U>::size, \
"Expression size must match batch size"); \
\
PRAGMA_LOOP_IVDEP \
for (std::size_t i(0); i < size; ++i) { \
array_data_[i] OP details::make_expr(std::forward<U>(rhs))( \
eval_visitor(i)); \
} \
return *this; \
}
DEFINE_INPLACE_OP(+=)
DEFINE_INPLACE_OP(-=)
DEFINE_INPLACE_OP(*=)
DEFINE_INPLACE_OP(/=)
DEFINE_INPLACE_OP(&=)
DEFINE_INPLACE_OP(|=)
DEFINE_INPLACE_OP(^=)
#undef DEFINE_INPLACE_OP
//! Pre-increment operator.
/*!
* \return A reference to \c this.
*/
template <typename T, std::size_t N>
auto& xsimd::batch<T, N>::operator++()
{
PRAGMA_LOOP_IVDEP
for (auto& b: *this) {
++b;
}
return *this;
}
//! Post-increment operator.
/*!
* \return A reference to \c this.
*/
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::operator++(int)
{
auto tmp(*this);
++(*this);
return tmp;
}
//! Pre-decrement operator.
/*!
* \return A reference to \c this.
*/
template <typename T, std::size_t N>
auto& xsimd::batch<T, N>::operator--()
{
PRAGMA_LOOP_IVDEP
for (auto& b: *this) {
--b;
}
return *this;
}
//! Post-decrement operator.
/*!
* \return A reference to \c this.
*/
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::operator--(int)
{
auto tmp(*this);
--(*this);
return tmp;
}
// =============================================================================
// Function for iterator-like access
//! Returns iterator to beginning
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::begin() -> iterator
{
return array_data_.begin();
}
//! Returns iterator to end
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::end() -> iterator
{
return array_data_.end();
}
//! Returns const_iterator to beginning
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::begin() const -> const_iterator
{
return cbegin();
}
//! Returns const_iterator to end
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::end() const -> const_iterator
{
return cend();
}
//! Returns const_iterator to beginning
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::cbegin() const -> const_iterator
{
return array_data_.cbegin();
}
//! Returns const_iterator to end
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::cend() const -> const_iterator
{
return array_data_.cend();
}
// ------------------------------------------------------------------------------
//! Return reverse_iterator to reverse beginning
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::rbegin() -> reverse_iterator
{
return reverse_iterator(end());
}
//! Return reverse_iterator to reverse end
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::rend() -> reverse_iterator
{
return reverse_iterator(begin());
}
//! Return const_reverse_iterator to reverse beginning
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::rbegin() const -> const_reverse_iterator
{
return crbegin();
}
//! Return const_reverse_iterator to reverse end
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::rend() const -> const_reverse_iterator
{
return crend();
}
//! Return const_reverse_iterator to reverse beginning
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::crbegin() const -> const_reverse_iterator
{
return const_reverse_iterator(cend());
}
//! Return const_reverse_iterator to reverse end
template <typename T, std::size_t N>
auto xsimd::batch<T, N>::crend() const -> const_reverse_iterator
{
return const_reverse_iterator(cbegin());
}
// =============================================================================
// =============================================================================
// Constructor for const batches
template <typename T, std::size_t N>
constexpr xsimd::batch<const T, N>::batch() : data_(nullptr)
{}
template <typename T, std::size_t N>
constexpr xsimd::batch<const T, N>::batch(const T data[N]) : data_(data)
{}
template <typename T, std::size_t N>
constexpr xsimd::batch<const T, N>::batch(const std::array<T, N>& data)
: data_(&data[0])
{}
template <typename T, std::size_t N>
constexpr xsimd::batch<const T, N>::batch(const batch& rhs) : data_(rhs.data_)
{}
template <typename T, std::size_t N>
constexpr xsimd::batch<const T, N>::batch(batch&& rhs)
: data_(std::move(rhs.data_))
{}
// -----------------------------------------------------------------------------
template <typename T, std::size_t N>
constexpr auto& xsimd::batch<const T, N>::operator=(const batch& rhs)
{
data_ = rhs.data_;
return *this;
}
template <typename T, std::size_t N>
constexpr auto& xsimd::batch<const T, N>::operator=(batch&& rhs)
{
data_ = std::move(rhs.data_);
return *this;
}
// -----------------------------------------------------------------------------
//! Access element (const)
/*!
* \param idx Index of an element in the batch
* \return The element at the specified position
*/
template <typename T, std::size_t N>
constexpr auto xsimd::batch<const T, N>::operator[](std::size_t idx) const
{
return data_[idx];
}
// =============================================================================
// Function for iterator-like access
//! Returns const_iterator to beginning
template <typename T, std::size_t N>
constexpr auto xsimd::batch<const T, N>::begin() const -> const_iterator
{
return cbegin();
}
//! Returns const_iterator to end
template <typename T, std::size_t N>
constexpr auto xsimd::batch<const T, N>::end() const -> const_iterator
{
return cend();
}
//! Returns const_iterator to beginning
template <typename T, std::size_t N>
constexpr auto xsimd::batch<const T, N>::cbegin() const -> const_iterator
{
return data_;
}
//! Returns const_iterator to end
template <typename T, std::size_t N>
constexpr auto xsimd::batch<const T, N>::cend() const -> const_iterator
{
return data_ + size;
}
// -----------------------------------------------------------------------------
//! Return const_reverse_iterator to reverse beginning
template <typename T, std::size_t N>
constexpr auto xsimd::batch<const T, N>::rbegin() const
-> const_reverse_iterator
{
return crbegin();
}
//! Return const_reverse_iterator to reverse end
template <typename T, std::size_t N>
constexpr auto xsimd::batch<const T, N>::rend() const -> const_reverse_iterator
{
return crend();
}
//! Return const_reverse_iterator to reverse beginning
template <typename T, std::size_t N>
constexpr auto xsimd::batch<const T, N>::crbegin() const
-> const_reverse_iterator
{
return const_reverse_iterator(cend());
}
//! Return const_reverse_iterator to reverse end
template <typename T, std::size_t N>
constexpr auto xsimd::batch<const T, N>::crend() const -> const_reverse_iterator
{
return const_reverse_iterator(cbegin());
}
| 29.004988 | 81 | 0.580861 | thexdesk |
0cb2df04b700296df273dae8ab674ba28ea8bd3d | 8,791 | cpp | C++ | SystemInfo.cpp | knela96/Game-Engine | 06659d933c4447bd8d6c8536af292825ce4c2ab1 | [
"Unlicense"
] | 1 | 2019-11-16T22:01:56.000Z | 2019-11-16T22:01:56.000Z | SystemInfo.cpp | knela96/Game-Engine | 06659d933c4447bd8d6c8536af292825ce4c2ab1 | [
"Unlicense"
] | null | null | null | SystemInfo.cpp | knela96/Game-Engine | 06659d933c4447bd8d6c8536af292825ce4c2ab1 | [
"Unlicense"
] | null | null | null | #include"SystemInfo.h"
namespace Engine {
static sMStats MemoryStats_MMRG;
void RecalculateMemStatisticsFromMMGR() {
MemoryStats_MMRG = m_getMemoryStatistics();
}
SystemInfo::SystemInfo() {
mSoftware_Info.DetectSystemProperties();
mHardware_MemoryInfo.DetectSystemProperties();
mHardware_GPUInfo.DetectSystemProperties();
mHardware_CPUInfo.DetectSystemProperties();
}
void SoftwareInfo::DetectSystemProperties()
{
mSoftware_CppVersion = ExtractCppVersion(__cplusplus);
mSoftware_WindowsVersion = ExtractWindowsVersion();
mSoftware_SDLVersion = ExtractSDLVersion();
}
const std::string SoftwareInfo::ExtractCppVersion(long int cppValue)
{
std::string tmp_cppVersion = "NULL: return value does not match with any C++ version!";
switch (cppValue) {
case(199711L):
tmp_cppVersion = "C++ 98 or C++03";
break;
case(201103L):
tmp_cppVersion = "C++11";
break;
case(201402L):
tmp_cppVersion = "C++14";
break;
case(201703L):
tmp_cppVersion = "C++17";
break;
default:
tmp_cppVersion = "NULL: return value does not match with any C++ version!";
break;
}
return tmp_cppVersion;
}
const std::string SoftwareInfo::ExtractWindowsVersion()
{
OSVERSIONINFOEX OS;
ZeroMemory(&OS, sizeof(OSVERSIONINFOEX));
OS.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
GetVersionEx(&(OSVERSIONINFO&)OS);
std::string ret = "Windows ";
if (OS.dwMajorVersion == 10)
ret += "10";
else if (OS.dwMajorVersion == 6) {
if (OS.dwMinorVersion == 3)
ret += "8.1";
else if (OS.dwMinorVersion == 2)
ret += "8";
else if (OS.dwMinorVersion == 1)
ret += "7";
else
ret += "Vista";
}
else if (OS.dwMajorVersion == 5) {
if (OS.dwMinorVersion == 2)
ret += "XP SP2";
else if (OS.dwMinorVersion == 1)
ret += "XP";
else if (OS.dwMinorVersion == 0)
ret += "2000";
}
else if (OS.dwMajorVersion == 4 || OS.dwMajorVersion == 3)
ret += "WinNT";
else
ret = "WINDOWS VERSION NOT FOUND";
return ret;
}
const std::string SoftwareInfo::ExtractSDLVersion()
{
SDL_version linked;
SDL_version compiled;
SDL_VERSION(&compiled);
SDL_GetVersion(&linked);
std::string VersionString = "SDL Compiled Version " + std::to_string(compiled.major)
+ std::to_string(compiled.minor) + std::to_string(compiled.patch);
VersionString += ("\nSDL Linked Version " + std::to_string(linked.major)
+ std::to_string(linked.minor) + std::to_string(linked.patch));
return VersionString;
}
const std::string SoftwareInfo::GetCppCompilerVersion()
{
return (std::to_string(_MSVC_LANG) + " (" + ExtractCppVersion(_MSVC_LANG) + ")");
}
void MemoryHardware::DetectSystemProperties()
{
ExtractMemoryInfo();
RecalculateMemStatisticsFromMMGR();
}
void MemoryHardware::ExtractMemoryInfo() const
{
MEMORYSTATUSEX tmpMemoryInfo;
tmpMemoryInfo.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&tmpMemoryInfo);
m_MemoryInfo = tmpMemoryInfo;
m_MemoryInfo.dwLength = sizeof(MEMORYSTATUSEX);
GetProcessMemoryInfo(GetCurrentProcess(), &m_ProcessMemCounters, sizeof(m_ProcessMemCounters));
mProcess_vMemUsed = m_ProcessMemCounters.PagefileUsage;
mProcess_physMemUsed = m_ProcessMemCounters.WorkingSetSize;
}
void MemoryHardware::RecalculateRAMParameters()
{
DetectSystemProperties();
}
//Getting Stats of Memory from MMRG
const uint MemoryHardware::GetMemStatsFromMMGR_TotalReportedMemory() const { return MemoryStats_MMRG.totalReportedMemory; }
const uint MemoryHardware::GetMemStatsFromMMGR_TotalActualMemory() const { return MemoryStats_MMRG.totalActualMemory; }
const uint MemoryHardware::GetMemStatsFromMMGR_PeakReportedMemory() const { return MemoryStats_MMRG.peakReportedMemory; }
const uint MemoryHardware::GetMemStatsFromMMGR_PeakActualMemory() const { return MemoryStats_MMRG.peakActualMemory; }
const uint MemoryHardware::GetMemStatsFromMMGR_AccumulatedReportedMemory() const { return MemoryStats_MMRG.accumulatedReportedMemory; }
const uint MemoryHardware::GetMemStatsFromMMGR_AccumulatedActualMemory() const { return MemoryStats_MMRG.accumulatedActualMemory; }
const uint MemoryHardware::GetMemStatsFromMMGR_AccumulatedAllocUnitCount() const { return MemoryStats_MMRG.accumulatedAllocUnitCount; }
const uint MemoryHardware::GetMemStatsFromMMGR_TotalAllocUnitCount() const { return MemoryStats_MMRG.totalAllocUnitCount; }
const uint MemoryHardware::GetMemStatsFromMMGR_PeakAllocUnitCount() const { return MemoryStats_MMRG.peakAllocUnitCount; }
void GPUHardware::DetectSystemProperties()
{
GetGPUTotalVRAM();
GetGPUCurrentVRAM();
GPUDetect_ExtractGPUInfo();
}
const int GPUHardware::GetGPUTotalVRAM()
{
/*int tmp_GPUTotalVRAM = 0;
glGetIntegerv(0x9048, &tmp_GPUTotalVRAM);
m_GPUTotalVRAM = tmp_GPUTotalVRAM;*/
//return m_GPUTotalVRAM / KBTOMB;
return m_PI_GPUDet_GPUInfo.mPI_GPUDet_TotalVRAM_MB;
}
const int GPUHardware::GetGPUCurrentVRAM()
{
int tmp_GPUCurrentVRAM = 0;
glGetIntegerv(0x9049, &tmp_GPUCurrentVRAM);
m_GPUCurrentVRAM = tmp_GPUCurrentVRAM;
return tmp_GPUCurrentVRAM / KBTOMB;
}
void GPUHardware::GPUDetect_ExtractGPUInfo() const
{
GPUPrimaryInfo_IntelGPUDetect tmp;
std::wstring tmp_GPUBrand_WString;
if (getGraphicsDeviceInfo(&tmp.m_GPUVendor, &tmp.m_GPUID, &tmp_GPUBrand_WString, &tmp.mPI_GPUDet_TotalVRAM_Bytes, &tmp.mPI_GPUDet_VRAMUsage_Bytes, &tmp.mPI_GPUDet_CurrentVRAM_Bytes, &tmp.mPI_GPUDet_VRAMReserved_Bytes))
{
//Converting the WSTRING variable into a std::string
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
tmp.m_GPUBrand = converter.to_bytes(tmp_GPUBrand_WString);
//If you prefer that in a char[] variable type, use:
//sprintf_s(char[], char[] size, "%S", tmp_GPUBrand_WString.c_str());
tmp.mPI_GPUDet_TotalVRAM_MB = tmp.mPI_GPUDet_TotalVRAM_Bytes / BTOMB;
tmp.mPI_GPUDet_VRAMUsage_MB = tmp.mPI_GPUDet_VRAMUsage_Bytes / BTOMB;
tmp.mPI_GPUDet_CurrentVRAM_MB = tmp.mPI_GPUDet_CurrentVRAM_Bytes / BTOMB;
tmp.mPI_GPUDet_VRAMReserved_MB = tmp.mPI_GPUDet_VRAMReserved_Bytes / BTOMB;
m_PI_GPUDet_GPUInfo = tmp;
}
}
void ProcessorHardware::DetectSystemProperties()
{
GetCPUSystemInfo();
CheckForCPUInstructionsSet();
}
void ProcessorHardware::GetCPUSystemInfo()
{
GetSystemInfo(&m_CpuSysInfo);
m_CpuArchitecture = ExtractCPUArchitecture(m_CpuSysInfo);
getCPUInfo(&m_CPUBrand, &m_CPUVendor);
}
const std::string ProcessorHardware::ExtractCPUArchitecture(SYSTEM_INFO& SystemInfo)
{
std::string ret = "Unknown Architecture";
switch (SystemInfo.wProcessorArchitecture) {
case(PROCESSOR_ARCHITECTURE_AMD64):
ret = "x64 (AMD or Intel)";
break;
case(PROCESSOR_ARCHITECTURE_ARM):
ret = "ARM";
break;
case(PROCESSOR_ARCHITECTURE_ARM64):
ret = "ARM64";
break;
case(PROCESSOR_ARCHITECTURE_IA64):
ret = "Intel Itanium-based";
break;
case(PROCESSOR_ARCHITECTURE_INTEL):
ret = "x86";
break;
case(PROCESSOR_ARCHITECTURE_UNKNOWN):
ret = "Unknown architecture";
break;
default:
ret = "Unknown architecture";
break;
}
return ret;
}
void ProcessorHardware::CheckForCPUInstructionsSet()
{
if (SDL_Has3DNow() == true)
m_CPUInstructionSet.Available_3DNow = true;
if (SDL_HasRDTSC() == true)
m_CPUInstructionSet.RDTSC_Available = true;
if (SDL_HasAltiVec() == true)
m_CPUInstructionSet.AltiVec_Available = true;
if (SDL_HasAVX() == true)
m_CPUInstructionSet.AVX_Available = true;
if (SDL_HasAVX2() == true)
m_CPUInstructionSet.AVX2_Available = true;
if (SDL_HasMMX() == true)
m_CPUInstructionSet.MMX_Available = true;
if (SDL_HasSSE() == true)
m_CPUInstructionSet.SSE_Available = true;
if (SDL_HasSSE2() == true)
m_CPUInstructionSet.SSE2_Available = true;
if (SDL_HasSSE3() == true)
m_CPUInstructionSet.SSE3_Available = true;
if (SDL_HasSSE41() == true)
m_CPUInstructionSet.SSE41_Available = true;
if (SDL_HasSSE42() == true)
m_CPUInstructionSet.SSE42_Available = true;
}
const std::string ProcessorHardware::GetCPUInstructionSet() const
{
std::string ret = "";
InstructionsSet is = m_CPUInstructionSet;
if (is.Available_3DNow == true)
ret += "3DNOW, ";
if (is.RDTSC_Available == true)
ret += "RDTSC, ";
if (is.AltiVec_Available == true)
ret += "AltiVec, ";
if (is.AVX_Available == true)
ret += "AVX, ";
if (is.AVX2_Available == true)
ret += "AVX2, ";
if (is.MMX_Available == true)
ret += "MMX, ";
if (is.SSE_Available == true)
ret += "SSE, ";
if (is.SSE2_Available == true)
ret += "SSE2, ";
if (is.SSE3_Available == true)
ret += "SSE3, ";
if (is.SSE41_Available == true)
ret += "SSE41, ";
if (is.SSE42_Available == true)
ret += "SSE42, ";
ret += '\n';
return ret;
}
}
| 27.216718 | 220 | 0.730747 | knela96 |
0cb450c25568097ae662d51a102af867ce5a9270 | 902 | cpp | C++ | BkZOOLib/bkzoo/util/StringUtil.cpp | yoichibeer/BkZOO | 3ec97b6d34d0815063ca9d829e452771327101ff | [
"MIT"
] | null | null | null | BkZOOLib/bkzoo/util/StringUtil.cpp | yoichibeer/BkZOO | 3ec97b6d34d0815063ca9d829e452771327101ff | [
"MIT"
] | null | null | null | BkZOOLib/bkzoo/util/StringUtil.cpp | yoichibeer/BkZOO | 3ec97b6d34d0815063ca9d829e452771327101ff | [
"MIT"
] | null | null | null | /*
* BkZOO!
*
* Copyright 2011-2017 yoichibeer.
* Released under the MIT license.
*/
#include "StringUtil.h"
#include <sstream>
#include <ctime>
using namespace bkzoo;
namespace bkzoo
{
namespace util
{
std::string stringFromTime()
{
const time_t now = time(nullptr);
const struct tm *pnow = localtime(&now);
const int year = pnow->tm_year + 1900; /* 1900 - */
const int month = pnow->tm_mon + 1; /* 0-11 */
const int day = pnow->tm_mday + 1; /* 0-30 */
const int hour = pnow->tm_hour; /* 0-23 */
const int min = pnow->tm_min; /* 0-59 */
const int sec = pnow->tm_sec; /* 0-59 */
std::ostringstream oss;
oss << year << "." << month << "." << day << "." << hour << "." << min << "." << sec;
return oss.str();
}
}
}
| 22.55 | 97 | 0.486696 | yoichibeer |
0cb9b423042546198ac82f0c23a68e8773e7a9cb | 134 | cpp | C++ | WYMIANA - Zamiana miejsc/WYMIANA - Zamiana miejsc/main.cpp | wdsking/PolskiSpoj | aaa1128b0499f4e4e46405ff3ef2beec0127d0c0 | [
"MIT"
] | null | null | null | WYMIANA - Zamiana miejsc/WYMIANA - Zamiana miejsc/main.cpp | wdsking/PolskiSpoj | aaa1128b0499f4e4e46405ff3ef2beec0127d0c0 | [
"MIT"
] | null | null | null | WYMIANA - Zamiana miejsc/WYMIANA - Zamiana miejsc/main.cpp | wdsking/PolskiSpoj | aaa1128b0499f4e4e46405ff3ef2beec0127d0c0 | [
"MIT"
] | 2 | 2019-04-16T20:05:44.000Z | 2020-11-15T11:44:30.000Z | #include<stdio.h>
int main()
{
int x, y;
scanf("%d %d", &x, &y);
x += y;
y = x - y;
x -= y;
printf("%d %d", x, y);
return 0;
} | 11.166667 | 24 | 0.432836 | wdsking |
0cbbf656e6d6e3b7e62906f2259f976844885010 | 1,356 | cpp | C++ | include/MenuItemSDUpdater.cpp | beNative/M5Stack-Concepts | dfebc3d633bc4519021b15371e69c4a76e5cef65 | [
"Apache-2.0"
] | null | null | null | include/MenuItemSDUpdater.cpp | beNative/M5Stack-Concepts | dfebc3d633bc4519021b15371e69c4a76e5cef65 | [
"Apache-2.0"
] | null | null | null | include/MenuItemSDUpdater.cpp | beNative/M5Stack-Concepts | dfebc3d633bc4519021b15371e69c4a76e5cef65 | [
"Apache-2.0"
] | 1 | 2021-02-28T08:45:20.000Z | 2021-02-28T08:45:20.000Z | #include "MenuItemSDUpdater.h"
#include <M5StackUpdater.h> // https://github.com/tobozo/M5Stack-SD-Updater/
#include <SD.h>
#undef min
#include <algorithm>
static SDUpdater sdUpdater;
void MenuItemSDUpdater::onEnter() {
if (!name.length()) {
// SDのルートフォルダから *.bin ファイルを探す。
deleteItems();
SD.begin();
File root = SD.open("/");
File file = root.openNextFile();
MenuItemSDUpdater* mi;
while (file) {
if (!file.isDirectory()) {
String name = file.name();
int idx = name.lastIndexOf('.');
String ext = name.substring(idx + 1);
if (ext == "bin") {
name = name.substring(1, idx);
mi = new MenuItemSDUpdater(name, name);
addItem(mi);
}
}
file = root.openNextFile();
std::sort(Items.begin(), Items.end(), compareIgnoreCase);
}
root.close();
} else {
// 選択されたbinファイルでupdateを実行する。
String bin = "/" + name + ".bin";
sdUpdater.updateFromFS(SD, bin);
ESP.restart();
}
MenuItem::onEnter();
}
void MenuItemSDUpdater::onFocus() {
String filename = "/jpg/" + name + ".jpg";
if (SD.exists(filename.c_str())) {
M5.Lcd.drawJpgFile(SD, filename.c_str(), 200, 40);
}
}
void MenuItemSDUpdater::onDefocus() {
M5.Lcd.fillRect(200, 30, 120, 140, backgroundColor);
}
void MenuItemSDUpdater::onAfterDraw()
{
}
| 23.789474 | 78 | 0.601032 | beNative |
0cbcba69300f9ba57f4ccd06e03054f74079fc93 | 11,275 | hpp | C++ | libformula/Headers/formula/Scanner.hpp | purefunsolutions/ember-plus | d022732f2533ad697238c6b5210d7fc3eb231bfc | [
"BSL-1.0"
] | 78 | 2015-07-31T14:46:38.000Z | 2022-03-28T09:28:28.000Z | libformula/Headers/formula/Scanner.hpp | purefunsolutions/ember-plus | d022732f2533ad697238c6b5210d7fc3eb231bfc | [
"BSL-1.0"
] | 81 | 2015-08-03T07:58:19.000Z | 2022-02-28T16:21:19.000Z | libformula/Headers/formula/Scanner.hpp | purefunsolutions/ember-plus | d022732f2533ad697238c6b5210d7fc3eb231bfc | [
"BSL-1.0"
] | 49 | 2015-08-03T12:53:10.000Z | 2022-03-17T17:25:49.000Z | /*
Copyright (C) 2012-2016 Lawo GmbH (http://www.lawo.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 __LIBFORMULA_SCANNER_HPP
#define __LIBFORMULA_SCANNER_HPP
#include <string>
#include <cstring>
#include "ErrorStack.hpp"
#include "Symbol.hpp"
namespace libformula
{
/**
* The Scanner is iterating through the term string and identifies the single tokens which
* are used for parsing in the second pass.
*/
template<typename InputIterator>
class Scanner
{
typedef std::vector<Symbol<InputIterator> > SymbolContainerT;
public:
typedef typename SymbolContainerT::value_type value_type;
typedef typename SymbolContainerT::size_type size_type;
typedef typename SymbolContainerT::const_iterator const_iterator;
typedef typename SymbolContainerT::reference reference;
typedef typename SymbolContainerT::const_reference const_reference;
typedef InputIterator input_type;
/**
* Initializes a new scanner which immediately scans the provided term.
* @param first Pointer to the first character in the term buffer.
* @param last Points to the first item beyond the term to scan.
* @param error Pointer to the error stack, where all detected errors are logged.
* @note Note that the provided buffer must exist as long as the scanner instance
* is alive!
*/
Scanner(InputIterator first, InputIterator last, ErrorStack *error);
/**
* Returns the number of tokens identified and created by the scanner.
*/
size_type size() const;
/**
* Returns an iterator that points to the first symbol created by the scanner.
* @return An iterator that points to the first symbol created by the scanner.
*/
const_iterator begin() const;
/**
* Returns the iterator that points to the first location beyond the symbol buffer.
* @return The iterator that points to the first location beyond the symbol buffer.
*/
const_iterator end() const;
private:
/**
* Inserts a symbol to the internal symbol buffer.
* @param symbol The symbol to add.
*/
void push(const_reference symbol);
/**
* Scans a single character symbol and adds the identifies symbol into the buffer.
* @param first Current character.
* @param last End of the provided term string.
* @param error Error stack.
*/
InputIterator scanSingleCharSymbol(InputIterator first, InputIterator last, ErrorStack *error);
/**
* Tries to identify a symbol that consists of several characters, like a number or a function call.
* @param first Current character.
* @param last End of the provided term string.
* @param error Error stack.
*/
InputIterator scanMultiCharSymbol(InputIterator first, InputIterator last, ErrorStack *error);
/**
* Tries to match the current input to a function and inserts the symbol to the buffer.
* @param first Current character.
* @param last End of the provided term string.
* @param error Error stack.
*/
InputIterator scanFunction(InputIterator first, InputIterator last, ErrorStack *error);
/**
* Parses a number.
* @param first Current character.
* @param last End of the provided term string.
* @param error Error stack.
*/
InputIterator scanNumber(InputIterator first, InputIterator last, ErrorStack *error);
private:
SymbolContainerT m_symbols;
};
/**************************************************************************
* Inline implementation *
**************************************************************************/
template<typename InputIterator>
inline Scanner<InputIterator>::Scanner(InputIterator first, InputIterator last, ErrorStack *error)
{
while(first != last && isspace(*first))
++first;
for( ; first != last; )
{
switch(*first)
{
case SymbolType::It:
case SymbolType::Divide:
case SymbolType::LParen:
case SymbolType::Minus:
case SymbolType::Modulo:
case SymbolType::Multiply:
case SymbolType::Plus:
case SymbolType::Pow:
case SymbolType::RParen:
case SymbolType::Comma:
first = scanSingleCharSymbol(first, last, error);
break;
default:
first = scanMultiCharSymbol(first, last, error);
break;
}
while(first != last && isspace(*first))
++first;
}
push(value_type(SymbolType::EndOfFile, size(), last, last));
}
template<typename InputIterator>
inline typename Scanner<InputIterator>::size_type Scanner<InputIterator>::size() const
{
return m_symbols.size();
}
template<typename InputIterator>
inline typename Scanner<InputIterator>::const_iterator Scanner<InputIterator>::begin() const
{
return m_symbols.begin();
}
template<typename InputIterator>
inline typename Scanner<InputIterator>::const_iterator Scanner<InputIterator>::end() const
{
return m_symbols.end();
}
template<typename InputIterator>
inline InputIterator Scanner<InputIterator>::scanSingleCharSymbol(InputIterator first, InputIterator last, ErrorStack *error)
{
push(value_type(static_cast<SymbolType::_Domain>(*first), size(), first, first + 1));
return ++first;
}
template<typename InputIterator>
inline InputIterator Scanner<InputIterator>::scanMultiCharSymbol(InputIterator first, InputIterator last, ErrorStack *error)
{
if (::isalpha(*first))
{
return scanFunction(first, last, error);
}
else if (::isdigit(*first))
{
return scanNumber(first, last, error);
}
else
{
error->push(ErrorType::UnknownToken, "Unknown token");
return last;
}
}
template<typename InputIterator>
inline InputIterator Scanner<InputIterator>::scanFunction(InputIterator first, InputIterator last, ErrorStack *error)
{
typedef typename std::iterator_traits<InputIterator>::value_type type;
type buffer[32];
auto cursor = &buffer[0];
auto it = first;
while(it != last && ::isalpha(*it))
{
*cursor++ = ::tolower(*it++);
}
*cursor = 0;
if (strncmp(buffer, "sqrt", 4) == 0)
push(value_type(SymbolType::Sqrt, size(), first, it));
else if (strncmp(buffer, "log", 3) == 0)
push(value_type(SymbolType::Log, size(), first, it));
else if (strncmp(buffer, "ln", 2) == 0)
push(value_type(SymbolType::Ln, size(), first, it));
else if (strncmp(buffer, "round", 5) == 0)
push(value_type(SymbolType::Round, size(), first, it));
else if (strncmp(buffer, "ceil", 4) == 0)
push(value_type(SymbolType::Ceil, size(), first, it));
else if (strncmp(buffer, "int", 3) == 0)
push(value_type(SymbolType::Int, size(), first, it));
else if (strncmp(buffer, "float", 5) == 0)
push(value_type(SymbolType::Float, size(), first, it));
else if (strncmp(buffer, "exp", 3) == 0)
push(value_type(SymbolType::Exp, size(), first, it));
else if (strncmp(buffer, "sinh", 4) == 0)
push(value_type(SymbolType::Sinh, size(), first, it));
else if (strncmp(buffer, "sin", 3) == 0)
push(value_type(SymbolType::Sin, size(), first, it));
else if (strncmp(buffer, "cosh", 4) == 0)
push(value_type(SymbolType::Cosh, size(), first, it));
else if (strncmp(buffer, "cos", 3) == 0)
push(value_type(SymbolType::Cos, size(), first, it));
else if (strncmp(buffer, "tanh", 4) == 0)
push(value_type(SymbolType::Tanh, size(), first, it));
else if (strncmp(buffer, "tan", 3) == 0)
push(value_type(SymbolType::Tan, size(), first, it));
else if (strncmp(buffer, "atan", 4) == 0)
push(value_type(SymbolType::Atan, size(), first, it));
else if (strncmp(buffer, "acos", 4) == 0)
push(value_type(SymbolType::Acos, size(), first, it));
else if (strncmp(buffer, "asin", 4) == 0)
push(value_type(SymbolType::Asin, size(), first, it));
else if (strncmp(buffer, "pi", 2) == 0)
push(value_type(SymbolType::Pi, size(), first, it));
else if (strncmp(buffer, "e", 1) == 0)
push(value_type(SymbolType::E, size(), first, it));
else if (strncmp(buffer, "abs", 3) == 0)
push(value_type(SymbolType::Abs, size(), first, it));
else if (strncmp(buffer, "sgn", 3) == 0)
push(value_type(SymbolType::Sgn, size(), first, it));
else
{
error->push(ErrorType::UnknownFunction, buffer);
return last;
}
return it;
}
template<typename InputIterator>
inline InputIterator Scanner<InputIterator>::scanNumber(InputIterator first, InputIterator last, ErrorStack *error)
{
auto it = first;
auto exponents = 0;
auto operators = 0;
auto dots = 0;
while(it != last && exponents < 2 && operators < 2 && dots < 2)
{
if (*it == 'E' || *it == 'e')
++exponents;
else if (dots > 0 && (*it == '+' || *it == '-'))
++operators;
else if (*it == '.')
++dots;
else if (::isdigit(*it) == 0)
break;
++it;
}
auto const invalid = !(exponents < 2 && dots < 2 && operators < 2);
if (invalid == false)
{
if (dots == 0 && exponents == 0 && operators == 0)
{
push(value_type(SymbolType::IntegerValue, size(), first, it));
}
else
{
push(value_type(SymbolType::RealValue, size(), first, it));
}
return it;
}
else
{
error->push(ErrorType::TokenIsNotAValidNumber, std::string(first, it));
return last;
}
}
template<typename InputIterator>
inline void Scanner<InputIterator>::push(const_reference symbol)
{
m_symbols.push_back(symbol);
}
}
#endif // __LIBFORMULA_SCANNER_HPP
| 37.70903 | 129 | 0.555565 | purefunsolutions |
0cc02d13df35f66d9d939b792fd277139ee47d59 | 2,432 | hpp | C++ | liblogextract/include/logextract/log_data_source.hpp | Parrot-Developers/logger | 250b8e83f2c93434d6f613f1000a6ae9891aa567 | [
"BSD-3-Clause"
] | null | null | null | liblogextract/include/logextract/log_data_source.hpp | Parrot-Developers/logger | 250b8e83f2c93434d6f613f1000a6ae9891aa567 | [
"BSD-3-Clause"
] | null | null | null | liblogextract/include/logextract/log_data_source.hpp | Parrot-Developers/logger | 250b8e83f2c93434d6f613f1000a6ae9891aa567 | [
"BSD-3-Clause"
] | 1 | 2021-03-31T10:04:52.000Z | 2021-03-31T10:04:52.000Z | /**
* Copyright (c) 2019-2020 Parrot Drones SAS
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Parrot Drones SAS Company nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PARROT DRONES SAS COMPANY BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LOG_DATASOURCE_HPP
#define LOG_DATASOURCE_HPP
#include <vector>
#include "logextract/data_source.hpp"
namespace logextract {
class LogDataSource : public DataSource {
public:
inline LogDataSource(const std::string &name) : DataSource(name) {}
inline ~LogDataSource() {}
public:
inline void addEntry(const std::vector<char> &entry)
{ mLogEntries.push_back(entry); }
inline const std::vector<char> &getEntry(unsigned int idx) const
{ return mLogEntries[idx]; }
inline unsigned int getEntryCount() const
{ return mLogEntries.size(); }
inline virtual bool isEvent() override { return false; }
inline virtual bool isInternal() override { return false; }
inline virtual bool isTelemetry() override { return false; }
inline virtual bool isUlog() override { return true; }
private:
std::vector<std::vector<char>> mLogEntries;
};
}
#endif
| 38 | 80 | 0.757401 | Parrot-Developers |
0cc1da7e2deb9cfc343c619d6ff1ea29c40318e2 | 10,464 | tcc | C++ | include/dart/packet/object.tcc | Cfretz244/libdart | 987b01aa1f11455ac6aaf89f8e60825e92e6ec25 | [
"Apache-2.0"
] | 85 | 2019-05-09T19:12:25.000Z | 2021-02-07T16:31:55.000Z | include/dart/packet/object.tcc | Cfretz244/libdart | 987b01aa1f11455ac6aaf89f8e60825e92e6ec25 | [
"Apache-2.0"
] | 10 | 2019-05-09T22:37:27.000Z | 2020-03-29T03:25:16.000Z | include/dart/packet/object.tcc | Cfretz244/libdart | 987b01aa1f11455ac6aaf89f8e60825e92e6ec25 | [
"Apache-2.0"
] | 10 | 2019-05-11T08:05:10.000Z | 2020-06-11T11:05:17.000Z | #ifndef DART_PACKET_OBJECT_H
#define DART_PACKET_OBJECT_H
/*----- Project Includes -----*/
#include "../common.h"
/*----- Function Implementations -----*/
namespace dart {
template <template <class> class RefCount>
template <class... Args, class EnableIf>
basic_packet<RefCount> basic_packet<RefCount>::make_object(Args&&... pairs) {
return basic_heap<RefCount>::make_object(std::forward<Args>(pairs)...);
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
basic_packet<RefCount> basic_packet<RefCount>::make_object(gsl::span<basic_heap<RefCount> const> pairs) {
return basic_heap<RefCount>::make_object(pairs);
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
basic_packet<RefCount> basic_packet<RefCount>::make_object(gsl::span<basic_buffer<RefCount> const> pairs) {
return basic_heap<RefCount>::make_object(pairs);
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
basic_packet<RefCount> basic_packet<RefCount>::make_object(gsl::span<basic_packet const> pairs) {
return basic_heap<RefCount>::make_object(pairs);
}
template <template <class> class RefCount>
template <class KeyType, class ValueType, class EnableIf>
basic_packet<RefCount>& basic_packet<RefCount>::add_field(KeyType&& key, ValueType&& value) & {
get_heap().add_field(std::forward<KeyType>(key), std::forward<ValueType>(value));
return *this;
}
template <template <class> class RefCount>
template <class KeyType, class ValueType, class EnableIf>
basic_packet<RefCount>&& basic_packet<RefCount>::add_field(KeyType&& key, ValueType&& value) && {
add_field(std::forward<KeyType>(key), std::forward<ValueType>(value));
return std::move(*this);
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
basic_packet<RefCount>& basic_packet<RefCount>::remove_field(shim::string_view key) & {
erase(key);
return *this;
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
basic_packet<RefCount>&& basic_packet<RefCount>::remove_field(shim::string_view key) && {
remove_field(key);
return std::move(*this);
}
template <template <class> class RefCount>
template <class KeyType, class EnableIf>
basic_packet<RefCount>& basic_packet<RefCount>::remove_field(KeyType const& key) & {
erase(key.strv());
return *this;
}
template <template <class> class RefCount>
template <class KeyType, class EnableIf>
basic_packet<RefCount>&& basic_packet<RefCount>::remove_field(KeyType const& key) && {
remove_field(key);
return std::move(*this);
}
template <template <class> class RefCount>
template <class String, bool enabled, class EnableIf>
auto basic_packet<RefCount>::erase(basic_string<String> const& key) -> iterator {
return erase(key.strv());
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
auto basic_packet<RefCount>::erase(shim::string_view key) -> iterator {
return get_heap().erase(key);
}
template <template <class> class RefCount>
template <class... Args, class EnableIf>
basic_packet<RefCount> basic_packet<RefCount>::inject(Args&&... pairs) const {
return shim::visit([&] (auto& v) -> basic_packet { return v.inject(std::forward<Args>(pairs)...); }, impl);
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
basic_packet<RefCount> basic_packet<RefCount>::inject(gsl::span<basic_heap<RefCount> const> pairs) const {
return shim::visit([&] (auto& v) -> basic_packet { return v.inject(pairs); }, impl);
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
basic_packet<RefCount> basic_packet<RefCount>::inject(gsl::span<basic_buffer<RefCount> const> pairs) const {
return shim::visit([&] (auto& v) -> basic_packet { return v.inject(pairs); }, impl);
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
basic_packet<RefCount> basic_packet<RefCount>::inject(gsl::span<basic_packet const> pairs) const {
return shim::visit([&] (auto& v) -> basic_packet { return v.inject(pairs); }, impl);
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
basic_packet<RefCount> basic_packet<RefCount>::project(std::initializer_list<shim::string_view> keys) const {
return shim::visit([&] (auto& v) -> basic_packet { return v.project(keys); }, impl);
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
basic_packet<RefCount> basic_packet<RefCount>::project(gsl::span<std::string const> keys) const {
return shim::visit([&] (auto& v) -> basic_packet { return v.project(keys); }, impl);
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
basic_packet<RefCount> basic_packet<RefCount>::project(gsl::span<shim::string_view const> keys) const {
return shim::visit([&] (auto& v) -> basic_packet { return v.project(keys); }, impl);
}
template <template <class> class RefCount>
template <class String>
basic_packet<RefCount> basic_packet<RefCount>::operator [](basic_string<String> const& key) const& {
return (*this)[key.strv()];
}
template <template <class> class RefCount>
template <class String, bool enabled, class EnableIf>
basic_packet<RefCount>&& basic_packet<RefCount>::operator [](basic_string<String> const& key) && {
return std::move(*this)[key.strv()];
}
template <template <class> class RefCount>
basic_packet<RefCount> basic_packet<RefCount>::operator [](shim::string_view key) const& {
return get(key);
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
basic_packet<RefCount>&& basic_packet<RefCount>::operator [](shim::string_view key) && {
return std::move(*this).get(key);
}
template <template <class> class RefCount>
template <class String>
basic_packet<RefCount> basic_packet<RefCount>::get(basic_string<String> const& key) const& {
return get(key.strv());
}
template <template <class> class RefCount>
template <class String, bool enabled, class EnableIf>
basic_packet<RefCount>&& basic_packet<RefCount>::get(basic_string<String> const& key) && {
return std::move(*this).get(key.strv());
}
template <template <class> class RefCount>
basic_packet<RefCount> basic_packet<RefCount>::get(shim::string_view key) const& {
return shim::visit([&] (auto& v) -> basic_packet { return v.get(key); }, impl);
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
basic_packet<RefCount>&& basic_packet<RefCount>::get(shim::string_view key) && {
shim::visit([&] (auto& v) { v = std::move(v).get(key); }, impl);
return std::move(*this);
}
template <template <class> class RefCount>
template <class String, class T, class EnableIf>
basic_packet<RefCount> basic_packet<RefCount>::get_or(basic_string<String> const& key, T&& opt) const {
return get_or(key.strv(), std::forward<T>(opt));
}
template <template <class> class RefCount>
template <class T, class EnableIf>
basic_packet<RefCount> basic_packet<RefCount>::get_or(shim::string_view key, T&& opt) const {
if (is_object() && has_key(key)) return get(key);
else return convert::cast<basic_packet>(std::forward<T>(opt));
}
template <template <class> class RefCount>
basic_packet<RefCount> basic_packet<RefCount>::get_nested(shim::string_view path, char separator) const {
return shim::visit([&] (auto& v) -> basic_packet { return v.get_nested(path, separator); }, impl);
}
template <template <class> class RefCount>
template <class String>
basic_packet<RefCount> basic_packet<RefCount>::at(basic_string<String> const& key) const& {
return at(key.strv());
}
template <template <class> class RefCount>
template <class String, bool enabled, class EnableIf>
basic_packet<RefCount>&& basic_packet<RefCount>::at(basic_string<String> const& key) && {
return std::move(*this).at(key.strv());
}
template <template <class> class RefCount>
basic_packet<RefCount> basic_packet<RefCount>::at(shim::string_view key) const& {
return shim::visit([&] (auto& v) -> basic_packet { return v.at(key); }, impl);
}
template <template <class> class RefCount>
template <bool enabled, class EnableIf>
basic_packet<RefCount>&& basic_packet<RefCount>::at(shim::string_view key) && {
shim::visit([&] (auto& v) { v = std::move(v).at(key); }, impl);
return std::move(*this);
}
template <template <class> class RefCount>
template <class String>
auto basic_packet<RefCount>::find(basic_string<String> const& key) const -> iterator {
return find(key.strv());
}
template <template <class> class RefCount>
auto basic_packet<RefCount>::find(shim::string_view key) const -> iterator {
return shim::visit([&] (auto& v) -> iterator { return v.find(key); }, impl);
}
template <template <class> class RefCount>
template <class String>
auto basic_packet<RefCount>::find_key(basic_string<String> const& key) const -> iterator {
return find_key(key.strv());
}
template <template <class> class RefCount>
auto basic_packet<RefCount>::find_key(shim::string_view key) const -> iterator {
return shim::visit([&] (auto& v) -> iterator { return v.find_key(key); }, impl);
}
template <template <class> class RefCount>
std::vector<basic_packet<RefCount>> basic_packet<RefCount>::keys() const {
std::vector<basic_packet> packets;
packets.reserve(size());
shim::visit([&] (auto& v) {
for (auto& k : v.keys()) packets.push_back(std::move(k));
}, impl);
return packets;
}
template <template <class> class RefCount>
template <class String>
bool basic_packet<RefCount>::has_key(basic_string<String> const& key) const {
return has_key(key.strv());
}
template <template <class> class RefCount>
bool basic_packet<RefCount>::has_key(shim::string_view key) const {
return shim::visit([&] (auto& v) { return v.has_key(key); }, impl);
}
template <template <class> class RefCount>
template <class KeyType, class EnableIf>
bool basic_packet<RefCount>::has_key(KeyType const& key) const {
if (key.get_type() == type::string) return has_key(key.strv());
else return false;
}
}
#endif
| 38.189781 | 111 | 0.702886 | Cfretz244 |
0cc99871da16315c53c42ece580d46aeba1c5a43 | 19,647 | cpp | C++ | src/mongo/db/exec/sbe/stages/column_scan.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/exec/sbe/stages/column_scan.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/exec/sbe/stages/column_scan.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2022-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/exec/sbe/stages/column_scan.h"
#include "mongo/db/exec/sbe/expressions/expression.h"
#include "mongo/db/exec/sbe/size_estimator.h"
#include "mongo/db/exec/sbe/values/column_store_encoder.h"
#include "mongo/db/exec/sbe/values/columnar.h"
#include "mongo/db/index/columns_access_method.h"
namespace mongo {
namespace sbe {
namespace {
TranslatedCell translateCell(PathView path, const SplitCellView& splitCellView) {
value::ColumnStoreEncoder encoder;
SplitCellView::Cursor<value::ColumnStoreEncoder> cellCursor =
splitCellView.subcellValuesGenerator<value::ColumnStoreEncoder>(std::move(encoder));
return TranslatedCell{splitCellView.arrInfo, path, std::move(cellCursor)};
}
} // namespace
ColumnScanStage::ColumnScanStage(UUID collectionUuid,
StringData columnIndexName,
value::SlotVector fieldSlots,
std::vector<std::string> paths,
boost::optional<value::SlotId> recordSlot,
boost::optional<value::SlotId> recordIdSlot,
std::unique_ptr<EExpression> recordExpr,
std::vector<std::unique_ptr<EExpression>> pathExprs,
value::SlotId rowStoreSlot,
PlanYieldPolicy* yieldPolicy,
PlanNodeId nodeId)
: PlanStage("columnscan"_sd, yieldPolicy, nodeId),
_collUuid(collectionUuid),
_columnIndexName(columnIndexName),
_fieldSlots(std::move(fieldSlots)),
_paths(std::move(paths)),
_recordSlot(recordSlot),
_recordIdSlot(recordIdSlot),
_recordExpr(std::move(recordExpr)),
_pathExprs(std::move(pathExprs)),
_rowStoreSlot(rowStoreSlot) {
invariant(_fieldSlots.size() == _paths.size());
invariant(_fieldSlots.size() == _pathExprs.size());
}
std::unique_ptr<PlanStage> ColumnScanStage::clone() const {
std::vector<std::unique_ptr<EExpression>> pathExprs;
for (auto& expr : _pathExprs) {
pathExprs.emplace_back(expr->clone());
}
return std::make_unique<ColumnScanStage>(_collUuid,
_columnIndexName,
_fieldSlots,
_paths,
_recordSlot,
_recordIdSlot,
_recordExpr ? _recordExpr->clone() : nullptr,
std::move(pathExprs),
_rowStoreSlot,
_yieldPolicy,
_commonStats.nodeId);
}
void ColumnScanStage::prepare(CompileCtx& ctx) {
_outputFields.resize(_fieldSlots.size());
for (size_t idx = 0; idx < _outputFields.size(); ++idx) {
auto [it, inserted] = _outputFieldsMap.emplace(_fieldSlots[idx], &_outputFields[idx]);
uassert(6610212, str::stream() << "duplicate slot: " << _fieldSlots[idx], inserted);
}
if (_recordSlot) {
_recordAccessor = std::make_unique<value::OwnedValueAccessor>();
}
if (_recordIdSlot) {
_recordIdAccessor = std::make_unique<value::OwnedValueAccessor>();
}
_rowStoreAccessor = std::make_unique<value::OwnedValueAccessor>();
if (_recordExpr) {
ctx.root = this;
_recordExprCode = _recordExpr->compile(ctx);
}
for (auto& expr : _pathExprs) {
ctx.root = this;
_pathExprsCode.emplace_back(expr->compile(ctx));
}
tassert(6610200, "'_coll' should not be initialized prior to 'acquireCollection()'", !_coll);
std::tie(_coll, _collName, _catalogEpoch) = acquireCollection(_opCtx, _collUuid);
auto indexCatalog = _coll->getIndexCatalog();
auto indexDesc = indexCatalog->findIndexByName(_opCtx, _columnIndexName);
tassert(6610201,
str::stream() << "could not find index named '" << _columnIndexName
<< "' in collection '" << _collName << "'",
indexDesc);
_weakIndexCatalogEntry = indexCatalog->getEntryShared(indexDesc);
}
value::SlotAccessor* ColumnScanStage::getAccessor(CompileCtx& ctx, value::SlotId slot) {
if (_recordSlot && slot == *_recordSlot) {
return _recordAccessor.get();
}
if (_recordIdSlot && slot == *_recordIdSlot) {
return _recordIdAccessor.get();
}
if (auto it = _outputFieldsMap.find(slot); it != _outputFieldsMap.end()) {
return it->second;
}
if (_rowStoreSlot == slot) {
return _rowStoreAccessor.get();
}
return ctx.getAccessor(slot);
}
void ColumnScanStage::doSaveState(bool relinquishCursor) {
for (auto& cursor : _columnCursors) {
cursor.makeOwned();
}
if (_rowStoreCursor && relinquishCursor) {
_rowStoreCursor->save();
}
if (_rowStoreCursor) {
_rowStoreCursor->setSaveStorageCursorOnDetachFromOperationContext(!relinquishCursor);
}
for (auto& cursor : _columnCursors) {
cursor.cursor().save();
}
for (auto& [path, cursor] : _parentPathCursors) {
cursor->saveUnpositioned();
}
_coll.reset();
}
void ColumnScanStage::doRestoreState(bool relinquishCursor) {
invariant(_opCtx);
invariant(!_coll);
// If this stage has not been prepared, then yield recovery is a no-op.
if (!_collName) {
return;
}
tassert(6610202, "Catalog epoch should be initialized", _catalogEpoch);
_coll = restoreCollection(_opCtx, *_collName, _collUuid, *_catalogEpoch);
auto indexCatalogEntry = _weakIndexCatalogEntry.lock();
uassert(ErrorCodes::QueryPlanKilled,
str::stream() << "query plan killed :: index '" << _columnIndexName << "' dropped",
indexCatalogEntry && !indexCatalogEntry->isDropped());
if (_rowStoreCursor) {
if (relinquishCursor) {
const bool couldRestore = _rowStoreCursor->restore();
invariant(couldRestore);
}
}
for (auto& cursor : _columnCursors) {
cursor.cursor().restore();
}
for (auto& [path, cursor] : _parentPathCursors) {
cursor->restore();
}
}
void ColumnScanStage::doDetachFromOperationContext() {
if (_rowStoreCursor) {
_rowStoreCursor->detachFromOperationContext();
}
for (auto& cursor : _columnCursors) {
cursor.cursor().detachFromOperationContext();
}
for (auto& [path, cursor] : _parentPathCursors) {
cursor->detachFromOperationContext();
}
}
void ColumnScanStage::doAttachToOperationContext(OperationContext* opCtx) {
if (_rowStoreCursor) {
_rowStoreCursor->reattachToOperationContext(opCtx);
}
for (auto& cursor : _columnCursors) {
cursor.cursor().reattachToOperationContext(opCtx);
}
for (auto& [path, cursor] : _parentPathCursors) {
cursor->reattachToOperationContext(opCtx);
}
}
void ColumnScanStage::doDetachFromTrialRunTracker() {
_tracker = nullptr;
}
PlanStage::TrialRunTrackerAttachResultMask ColumnScanStage::doAttachToTrialRunTracker(
TrialRunTracker* tracker, TrialRunTrackerAttachResultMask childrenAttachResult) {
_tracker = tracker;
return childrenAttachResult | TrialRunTrackerAttachResultFlags::AttachedToStreamingStage;
}
void ColumnScanStage::open(bool reOpen) {
auto optTimer(getOptTimer(_opCtx));
_commonStats.opens++;
invariant(_opCtx);
if (_open) {
tassert(6610203, "reopened ColumnScanStage but reOpen=false", reOpen);
tassert(6610204, "ColumnScanStage is open but _coll is not null", _coll);
tassert(6610205, "ColumnScanStage is open but don't have _rowStoreCursor", _rowStoreCursor);
} else {
tassert(6610206, "first open to ColumnScanStage but reOpen=true", !reOpen);
if (!_coll) {
// We're being opened after 'close()'. We need to re-acquire '_coll' in this case and
// make some validity checks (the collection has not been dropped, renamed, etc.).
tassert(
6610207, "ColumnScanStage is not open but have _rowStoreCursor", !_rowStoreCursor);
tassert(6610208, "Collection name should be initialized", _collName);
tassert(6610209, "Catalog epoch should be initialized", _catalogEpoch);
_coll = restoreCollection(_opCtx, *_collName, _collUuid, *_catalogEpoch);
}
}
if (!_rowStoreCursor) {
_rowStoreCursor = _coll->getCursor(_opCtx, true);
}
if (_columnCursors.empty()) {
auto entry = _weakIndexCatalogEntry.lock();
tassert(6610210,
str::stream() << "expected IndexCatalogEntry for index named: " << _columnIndexName,
static_cast<bool>(entry));
auto iam = static_cast<ColumnStoreAccessMethod*>(entry->accessMethod());
// Eventually we can not include this column for the cases where a known dense column (_id)
// is being read anyway.
_columnCursors.push_back(ColumnCursor(iam->storage()->newCursor(_opCtx, "\xFF"_sd),
false /* add to document */));
for (auto&& path : _paths) {
_columnCursors.push_back(
ColumnCursor(iam->storage()->newCursor(_opCtx, path), true /* add to document */));
}
}
for (auto& columnCursor : _columnCursors) {
columnCursor.seekAtOrPast(RecordId());
}
_open = true;
}
void ColumnScanStage::readParentsIntoObj(StringData path,
value::Object* outObj,
StringDataSet* pathsReadSetOut,
bool first) {
auto parent = ColumnStore::getParentPath(path);
// If a top-level path doesn't exist, it just doesn't exist. It can't exist in some places
// within a document but not others. No further inspection is necessary.
if (!parent) {
return;
}
if (pathsReadSetOut->contains(*parent)) {
// We've already read the parent in, so skip it.
return;
}
// Create the parent path cursor if necessary.
// First we try to emplace a nullptr, so that we avoid creating the cursor when we don't have
// to.
auto [it, inserted] = _parentPathCursors.try_emplace(*parent, nullptr);
// If we inserted a new entry, replace the null with an actual cursor.
if (inserted) {
invariant(it->second == nullptr);
auto entry = _weakIndexCatalogEntry.lock();
tassert(6610211,
str::stream() << "expected IndexCatalogEntry for index named: " << _columnIndexName,
static_cast<bool>(entry));
auto iam = static_cast<ColumnStoreAccessMethod*>(entry->accessMethod());
it->second = iam->storage()->newCursor(_opCtx, *parent);
}
boost::optional<SplitCellView> splitCellView;
if (auto optCell = it->second->seekExact(_recordId)) {
splitCellView = SplitCellView::parse(optCell->value);
}
pathsReadSetOut->insert(*parent);
if (!splitCellView || splitCellView->isSparse) {
// We need this cell's parent too.
readParentsIntoObj(*parent, outObj, pathsReadSetOut, false);
}
if (splitCellView) {
auto translatedCell = translateCell(*parent, *splitCellView);
addCellToObject(translatedCell, *outObj);
}
}
PlanState ColumnScanStage::getNext() {
auto optTimer(getOptTimer(_opCtx));
// We are about to call next() on a storage cursor so do not bother saving our internal state in
// case it yields as the state will be completely overwritten after the next() call.
disableSlotAccess();
checkForInterrupt(_opCtx);
// Find minimum record ID of all column cursors.
_recordId = RecordId();
for (auto& cursor : _columnCursors) {
auto& result = cursor.lastCell();
if (result && (_recordId.isNull() || result->rid < _recordId)) {
_recordId = result->rid;
}
}
if (_recordId.isNull()) {
return trackPlanState(PlanState::IS_EOF);
}
auto [outTag, outVal] = value::makeNewObject();
auto& outObj = *value::bitcastTo<value::Object*>(outVal);
value::ValueGuard materializedObjGuard(outTag, outVal);
StringDataSet parentPathsRead;
bool useRowStore = false;
for (size_t i = 0; i < _columnCursors.size(); ++i) {
auto& lastCell = _columnCursors[i].lastCell();
const auto& path = _columnCursors[i].path();
boost::optional<SplitCellView> splitCellView;
if (lastCell && lastCell->rid == _recordId) {
splitCellView = SplitCellView::parse(lastCell->value);
}
if (splitCellView && (splitCellView->hasSubPaths || splitCellView->hasDuplicateFields)) {
useRowStore = true;
} else if (!useRowStore && _columnCursors[i].includeInOutput()) {
if (!splitCellView || splitCellView->isSparse) {
// Must read in the parent information first.
readParentsIntoObj(path, &outObj, &parentPathsRead);
}
if (splitCellView) {
auto translatedCell = translateCell(path, *splitCellView);
addCellToObject(translatedCell, outObj);
}
}
if (splitCellView) {
_columnCursors[i].next();
}
}
if (useRowStore) {
// TODO: In some cases we can avoid calling seek() on the row store cursor, and instead do
// a next() which should be much cheaper.
auto record = _rowStoreCursor->seekExact(_recordId);
// If there's no record, the index is out of sync with the row store.
invariant(record);
_rowStoreAccessor->reset(false,
value::TypeTags::bsonObject,
value::bitcastFrom<const char*>(record->data.data()));
if (_recordExpr) {
auto [owned, tag, val] = _bytecode.run(_recordExprCode.get());
_recordAccessor->reset(owned, tag, val);
}
} else {
_recordAccessor->reset(true, outTag, outVal);
materializedObjGuard.reset();
}
if (_recordIdAccessor) {
_recordIdAccessor->reset(
false, value::TypeTags::RecordId, value::bitcastFrom<RecordId*>(&_recordId));
}
for (size_t idx = 0; idx < _outputFields.size(); ++idx) {
auto [owned, tag, val] = _bytecode.run(_pathExprsCode[idx].get());
_outputFields[idx].reset(owned, tag, val);
}
++_specificStats.numReads;
if (_tracker && _tracker->trackProgress<TrialRunTracker::kNumReads>(1)) {
// If we're collecting execution stats during multi-planning and reached the end of the
// trial period because we've performed enough physical reads, bail out from the trial run
// by raising a special exception to signal a runtime planner that this candidate plan has
// completed its trial run early. Note that a trial period is executed only once per a
// PlanStage tree, and once completed never run again on the same tree.
_tracker = nullptr;
uasserted(ErrorCodes::QueryTrialRunCompleted, "Trial run early exit in scan");
}
return trackPlanState(PlanState::ADVANCED);
}
void ColumnScanStage::close() {
auto optTimer(getOptTimer(_opCtx));
trackClose();
_rowStoreCursor.reset();
_coll.reset();
_columnCursors.clear();
_parentPathCursors.clear();
_open = false;
}
std::unique_ptr<PlanStageStats> ColumnScanStage::getStats(bool includeDebugInfo) const {
auto ret = std::make_unique<PlanStageStats>(_commonStats);
ret->specific = std::make_unique<ScanStats>(_specificStats);
if (includeDebugInfo) {
BSONObjBuilder bob;
bob.append("columnIndexName", _columnIndexName);
bob.appendNumber("numReads", static_cast<long long>(_specificStats.numReads));
bob.append("paths", _paths);
bob.append("outputSlots", _fieldSlots.begin(), _fieldSlots.end());
ret->debugInfo = bob.obj();
}
return ret;
}
const SpecificStats* ColumnScanStage::getSpecificStats() const {
return &_specificStats;
}
std::vector<DebugPrinter::Block> ColumnScanStage::debugPrint() const {
auto ret = PlanStage::debugPrint();
// Print out output slots.
ret.emplace_back(DebugPrinter::Block("[`"));
for (size_t idx = 0; idx < _fieldSlots.size(); ++idx) {
if (idx) {
ret.emplace_back(DebugPrinter::Block("`,"));
}
DebugPrinter::addIdentifier(ret, _fieldSlots[idx]);
}
ret.emplace_back(DebugPrinter::Block("`]"));
if (_recordSlot) {
DebugPrinter::addIdentifier(ret, _recordSlot.get());
} else {
DebugPrinter::addIdentifier(ret, DebugPrinter::kNoneKeyword);
}
if (_recordIdSlot) {
DebugPrinter::addIdentifier(ret, _recordIdSlot.get());
} else {
DebugPrinter::addIdentifier(ret, DebugPrinter::kNoneKeyword);
}
// Print out paths.
ret.emplace_back(DebugPrinter::Block("[`"));
for (size_t idx = 0; idx < _paths.size(); ++idx) {
if (idx) {
ret.emplace_back(DebugPrinter::Block("`,"));
}
ret.emplace_back(str::stream() << "\"" << _paths[idx] << "\"");
}
ret.emplace_back(DebugPrinter::Block("`]"));
ret.emplace_back("@\"`");
DebugPrinter::addIdentifier(ret, _collUuid.toString());
ret.emplace_back("`\"");
ret.emplace_back("@\"`");
DebugPrinter::addIdentifier(ret, _columnIndexName);
ret.emplace_back("`\"");
return ret;
}
size_t ColumnScanStage::estimateCompileTimeSize() const {
size_t size = sizeof(*this);
size += size_estimator::estimate(_fieldSlots);
size += size_estimator::estimate(_paths);
size += size_estimator::estimate(_specificStats);
return size;
}
} // namespace sbe
} // namespace mongo
| 36.586592 | 100 | 0.629816 | benety |
0ccb2bb341daf353139cbb8ce66bf5eaec872959 | 4,648 | cc | C++ | tutorials/examples/simple_receiver_main.cc | isabella232/aistreams | 209f4385425405676a581a749bb915e257dbc1c1 | [
"Apache-2.0"
] | 6 | 2020-09-22T18:07:15.000Z | 2021-10-21T01:34:04.000Z | tutorials/examples/simple_receiver_main.cc | isabella232/aistreams | 209f4385425405676a581a749bb915e257dbc1c1 | [
"Apache-2.0"
] | 2 | 2020-11-10T13:17:39.000Z | 2022-03-30T11:22:14.000Z | tutorials/examples/simple_receiver_main.cc | isabella232/aistreams | 209f4385425405676a581a749bb915e257dbc1c1 | [
"Apache-2.0"
] | 3 | 2020-09-26T08:40:35.000Z | 2021-10-21T01:33:56.000Z | // Copyright 2020 Google LLC
//
// 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.
// This example shows how you can programmatically receive packets of an
// arbitrary type. We receive the Greeting message sent by simple_sender_main.
#include <memory>
#include <string>
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/strings/str_format.h"
#include "absl/time/time.h"
#include "aistreams/cc/aistreams.h"
#include "aistreams/port/logging.h"
#include "aistreams/port/status.h"
#include "aistreams/port/statusor.h"
#include "examples/hello.pb.h"
ABSL_FLAG(std::string, target_address, "",
"Address (ip:port) to the data ingress.");
ABSL_FLAG(std::string, ssl_root_cert_path, "",
"Path to the data ingress' ssl certificate.");
ABSL_FLAG(bool, authenticate_with_google, true,
"Set to true if you are sending to a stream on the Google managed "
"service; false otherwise.");
ABSL_FLAG(std::string, stream_name, "", "Name of the stream to receive from.");
ABSL_FLAG(int, timeout_in_sec, 5,
"Seconds to wait for the server to deliver a new packet");
namespace aistreams {
Status RunReceiver() {
// Options to configure the receiver.
//
// See aistreams/base/wrappers/receivers.h for more details.
ReceiverOptions receiver_options;
// Configure the connection to the data ingress.
//
// These have the usual conventions (see simple_ingester_main.cc for more
// details.)
ConnectionOptions connection_options;
connection_options.target_address = absl::GetFlag(FLAGS_target_address);
connection_options.ssl_options.ssl_root_cert_path =
absl::GetFlag(FLAGS_ssl_root_cert_path);
connection_options.authenticate_with_google =
absl::GetFlag(FLAGS_authenticate_with_google);
receiver_options.connection_options = connection_options;
// Specify the stream to receive from.
receiver_options.stream_name = absl::GetFlag(FLAGS_stream_name);
// Create a receiver queue that automatically gets packets from the server.
//
// This receiver will stop pulling packets from the server if it fills up. No
// packets will be dropped.
//
// See aistreams/base/wrappers/receivers.h for more info.
auto receiver_queue = std::make_unique<ReceiverQueue<Packet>>();
auto status = MakePacketReceiverQueue(receiver_options, receiver_queue.get());
if (!status.ok()) {
return UnknownError("Failed to create a packet receiver queue");
}
// Keep receiving packets until the sender says it is done.
Packet p;
std::string eos_reason;
int timeout_in_sec = absl::GetFlag(FLAGS_timeout_in_sec);
while (true) {
// Timeout if no packets have arrived. We simply keep retrying here, but you
// can quit/break.
if (!receiver_queue->TryPop(p, absl::Seconds(timeout_in_sec))) {
LOG(INFO) << "The receiver queue is currently empty";
continue;
}
// When you do get a Packet, you should check if it is an EOS.
//
// See aistreams/base/util/packet_utils.h for more info.
if (IsEos(p, &eos_reason)) {
LOG(INFO) << "Got EOS with reason: \"" << eos_reason << "\"";
break;
}
// Now you are sure it is a data packet, but you need to be sure that it is
// a Greeting. For this, you use PacketAs to adapt it to a Greeting.
//
// See aistreams/base/packet_as.h for more info on PacketAs.
// See examples/hello.proto for the Greeting message.
PacketAs<examples::Greeting> packet_as(std::move(p));
if (!packet_as.ok()) {
LOG(ERROR) << packet_as.status();
return UnknownError(
"The server gave a non-Greeting Packet. Call upstream ingester "
"and/or Google NOW!!");
}
examples::Greeting greeting = std::move(packet_as).ValueOrDie();
// Print the contents of the greeting.
LOG(INFO) << greeting.DebugString();
}
return OkStatus();
}
} // namespace aistreams
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
absl::ParseCommandLine(argc, argv);
auto status = aistreams::RunReceiver();
if (!status.ok()) {
LOG(ERROR) << status;
return EXIT_FAILURE;
}
return 0;
}
| 35.753846 | 80 | 0.70654 | isabella232 |
0cce115e7afb2e0f655c679e6a034ad18d19933f | 4,093 | cpp | C++ | Old/mp3streamer_Plugin/cmpegaudiostreamdecoder.cpp | Harteex/Tuniac | dac98a68c1b801b7fc82874aad16cc8adcabb606 | [
"BSD-3-Clause"
] | 3 | 2022-01-05T08:47:51.000Z | 2022-01-06T12:42:18.000Z | Old/mp3streamer_Plugin/cmpegaudiostreamdecoder.cpp | Harteex/Tuniac | dac98a68c1b801b7fc82874aad16cc8adcabb606 | [
"BSD-3-Clause"
] | null | null | null | Old/mp3streamer_Plugin/cmpegaudiostreamdecoder.cpp | Harteex/Tuniac | dac98a68c1b801b7fc82874aad16cc8adcabb606 | [
"BSD-3-Clause"
] | 1 | 2022-01-06T16:12:58.000Z | 2022-01-06T16:12:58.000Z | /*
* CMpegAudioDecoder.cpp
* audioenginetest
*
* Created by Tony Million on 24/11/2009.
* Copyright 2009 Tony Million. All rights reserved.
*
*/
#include "generaldefs.h"
#include "cmpegaudiostreamdecoder.h"
#include "stdlib.h"
#include "stdio.h"
#include "mpegdecoder.h"
#define FRAMES_FLAG 0x0001
#define BYTES_FLAG 0x0002
#define TOC_FLAG 0x0004
#define VBR_SCALE_FLAG 0x0008
void CMpegAudioDecoder::Destroy(void)
{
#ifdef DEBUG_DESTROY
printf("CMpegAudioDecoder::Destroy(this) == %p\n", this);
#endif
delete this;
}
bool CMpegAudioDecoder::SetState(unsigned long State)
{
return(true);
}
bool CMpegAudioDecoder::GetLength(unsigned long * MS)
{
*MS = ((float)m_TotalSamples / ((float)m_SampleRate / 1000.0f));
return true;
}
bool CMpegAudioDecoder::SetPosition(unsigned long * MS)
{
return false;
}
bool CMpegAudioDecoder::GetFormat(unsigned long * SampleRate, unsigned long * Channels)
{
*SampleRate = m_SampleRate;
*Channels = m_Channels;
return true;
}
bool CMpegAudioDecoder::GetBuffer(float ** ppBuffer, unsigned long * NumSamples)
{
int ret = 0;
while(true)
{
ret = decoder.syncNextFrame();
if(ret == decodeFrame_NeedMoreData)
{
uint32_t left = decoder.getBytesLeft();
uint32_t bytesthistime = MIN_MPEG_DATA_SIZE - left;
memcpy(m_databuffer, m_databuffer + bytesthistime, left);
unsigned __int64 bytesread;
m_pSource->Read(bytesthistime, m_databuffer + left, &bytesread);
if(bytesread < bytesthistime)
decoder.setEndOfStream();
decoder.setData(m_databuffer, left + bytesread);
}
else if(ret == decodeFrame_Success)
{
// found our first frame!
break;
}
else if((ret == decodeFrame_NotEnoughBRV) || (ret == decodeFrame_Xing) || ret == decodeFrame_NoFollowingHeader)
{
// also skip ID3 frames please
// need to go around again or we're gonna 'whoop'
continue;
}
else
{
// something else happened!
return false;
}
}
if((ret == decodeFrame_Success) || (ret == decodeFrame_Xing))
{
// we got a frame - now lets decode it innit
//memset(m_audiobuffer, 0, 4096 * 4);
decoder.synthFrame(m_audiobuffer);
*ppBuffer = m_audiobuffer;
*NumSamples = 2304;
return true;
}
return false;
}
bool CMpegAudioDecoder::Open(IAudioFileIO * pFileIO)
{
m_pSource = pFileIO;
if(!m_pSource)
return NULL;
//Lets find a frame so we can get sample rate and channels!
float * temp;
unsigned long blah;
if(GetBuffer(&temp, &blah))
{
m_SampleRate = decoder.header.SampleRate;
m_Channels = decoder.header.Channels;
decoder.Reset();
}
return true;
}
#include <math.h>
void deemphasis5015(void)
{
int num_channels = 2;
float frequency = 44100;
short * outbuf;
int numsamples[2];
double llastin[2], llastout[2];
int i, ch;
/* this implements an attenuation treble shelving filter
to undo the effect of pre-emphasis. The filter is of
a recursive first order */
short lastin;
double lastout;
short *pmm;
/* See deemphasis.gnuplot */
double V0 = 0.3365;
double OMEGAG = (1./19e-6);
double T = (1./frequency);
double H0 = (V0-1.);
double B = (V0*tan((OMEGAG * T)/2.0));
double a1 = ((B - 1.)/(B + 1.));
double b0 = (1.0 + (1.0 - a1) * H0/2.0);
double b1 = (a1 + (a1 - 1.0) * H0/2.0);
for (ch=0; ch< num_channels; ch++)
{
/* ---------------------------------------------------------------------
* For 48Khz: a1=-0.659065
* b0= 0.449605
* b1=-0.108670
* For 44.1Khz: a1=-0.62786881719628784282
* b0= 0.45995451989513153057
* b1=-0.08782333709141937339
* For 32kHZ ?
*/
lastin = llastin [ch];
lastout = llastout [ch];
for (pmm = (short *)outbuf [ch], i=0;
i < numsamples[0]; /* TODO: check for second channel */
i++)
{
lastout = *pmm * b0 + lastin * b1 - lastout * a1;
lastin = *pmm;
//*pmm++ = (lastout > 0.0) ? lastout + 0.5 : lastout - 0.5;
*pmm++ = lastout;
} // for (pmn = .. */
llastout [ch] = lastout;
llastin [ch] = lastin;
} // or (ch = .. */
}
| 21.542105 | 114 | 0.632299 | Harteex |
0cd1bb50d7747313c56f287327c917aa84ebcdfc | 4,660 | cpp | C++ | Programs/ResourceEditor1/Classes/Beast/Private/BeastModule.cpp | typicalMoves/dava.engine | 31625a6ae5f66c372089cbc436ed850102366154 | [
"BSD-3-Clause"
] | 4 | 2021-04-22T05:41:59.000Z | 2021-12-07T20:16:20.000Z | Programs/ResourceEditor1/Classes/Beast/Private/BeastModule.cpp | typicalMoves/dava.engine | 31625a6ae5f66c372089cbc436ed850102366154 | [
"BSD-3-Clause"
] | null | null | null | Programs/ResourceEditor1/Classes/Beast/Private/BeastModule.cpp | typicalMoves/dava.engine | 31625a6ae5f66c372089cbc436ed850102366154 | [
"BSD-3-Clause"
] | 1 | 2021-10-01T05:17:23.000Z | 2021-10-01T05:17:23.000Z | #include "Classes/Beast/BeastModule.h"
#if defined(__DAVAENGINE_BEAST__)
#include "Classes/Beast/Private/BeastDialog.h"
#include "Classes/Beast/Private/BeastRunner.h"
#include "Classes/Application/REGlobal.h"
#include "Classes/Application/RESettings.h"
#include "Classes/SceneManager/SceneData.h"
#include "Classes/Qt/Scene/SceneEditor2.h"
#include <TArc/Utils/ModuleCollection.h>
#include <TArc/WindowSubSystem/QtAction.h>
#include <TArc/WindowSubSystem/UI.h>
#include <TArc/WindowSubSystem/ActionUtils.h>
#include <TArc/Core/ContextAccessor.h>
#include <Engine/EngineContext.h>
#include <FileSystem/FileSystem.h>
#include <Reflection/ReflectionRegistrator.h>
#include <QMessageBox>
void BeastModule::PostInit()
{
using namespace DAVA;
using namespace DAVA::TArc;
QtAction* action = new QtAction(GetAccessor(), QString("Run Beast"));
{ // enabled/disabled state
action->SetStateUpdationFunction(QtAction::Enabled, Reflection::Create(ReflectedObject(this)), FastName("beastAvailable"), [](const Any& fieldValue) -> Any {
return fieldValue.Get<bool>(false);
});
}
connections.AddConnection(action, &QAction::triggered, MakeFunction(this, &BeastModule::OnBeastAndSave));
ActionPlacementInfo placementInfo;
placementInfo.AddPlacementPoint(CreateMenuPoint("Scene", { InsertionParams::eInsertionMethod::AfterItem, "actionInvalidateStaticOcclusion" }));
GetUI()->AddAction(DAVA::TArc::mainWindowKey, placementInfo, action);
}
void BeastModule::OnBeastAndSave()
{
using namespace DAVA;
SceneData* sceneData = GetAccessor()->GetActiveContext()->GetData<SceneData>();
DVASSERT(sceneData != nullptr);
RefPtr<SceneEditor2> scene = sceneData->GetScene();
DVASSERT(scene);
if (scene->GetEnabledTools())
{
if (QMessageBox::Yes == QMessageBox::question(GetUI()->GetWindow(DAVA::TArc::mainWindowKey), "Starting Beast", "Disable landscape editor and start beasting?", (QMessageBox::Yes | QMessageBox::No), QMessageBox::No))
{
scene->DisableToolsInstantly(SceneEditor2::LANDSCAPE_TOOLS_ALL);
bool success = !scene->IsToolsEnabled(SceneEditor2::LANDSCAPE_TOOLS_ALL);
if (!success)
{
Logger::Error(ResourceEditor::LANDSCAPE_EDITOR_SYSTEM_DISABLE_EDITORS.c_str());
return;
}
}
else
{
return;
}
}
InvokeOperation(REGlobal::SaveCurrentScene.ID);
if (!scene->IsLoaded() || scene->IsChanged())
{
return;
}
BeastDialog dlg(GetUI()->GetWindow(DAVA::TArc::mainWindowKey));
dlg.SetScene(scene.Get());
const bool run = dlg.Exec();
if (!run)
return;
RunBeast(dlg.GetPath(), dlg.GetMode());
scene->SetChanged();
InvokeOperation(REGlobal::SaveCurrentScene.ID);
scene->ClearAllCommands();
}
void BeastModule::RunBeast(const QString& outputPath, Beast::eBeastMode mode)
{
using namespace DAVA;
using namespace DAVA::TArc;
SceneData* sceneData = GetAccessor()->GetActiveContext()->GetData<SceneData>();
DVASSERT(sceneData != nullptr);
RefPtr<SceneEditor2> scene = sceneData->GetScene();
DVASSERT(scene);
const DAVA::FilePath path = outputPath.toStdString();
WaitDialogParams waitDlgParams;
waitDlgParams.message = "Starting Beast";
waitDlgParams.needProgressBar = true;
waitDlgParams.cancelable = true;
waitDlgParams.max = 100;
std::unique_ptr<WaitHandle> waitHandle = GetUI()->ShowWaitDialog(DAVA::TArc::mainWindowKey, waitDlgParams);
BeastRunner beast(scene.Get(), scene->GetScenePath(), path, mode, std::move(waitHandle));
beast.RunUIMode();
if (mode == Beast::eBeastMode::MODE_LIGHTMAPS)
{
// ReloadTextures should be delayed to give Qt some time for closing wait dialog before we will open new one for texture reloading.
delayedExecutor.DelayedExecute([this]() {
InvokeOperation(REGlobal::ReloadAllTextures.ID, REGlobal::GetGlobalContext()->GetData<CommonInternalSettings>()->textureViewGPU);
});
}
}
bool BeastModule::GetBeastAvailable() const
{
if (GetAccessor()->GetActiveContext() != nullptr)
{
DAVA::FileSystem* fs = DAVA::GetEngineContext()->fileSystem;
return fs->GetFilenamesTag().empty() == true;
}
return false;
}
DAVA_VIRTUAL_REFLECTION_IMPL(BeastModule)
{
DAVA::ReflectionRegistrator<BeastModule>::Begin()
.ConstructorByPointer()
.Field("beastAvailable", &BeastModule::GetBeastAvailable, nullptr)
.End();
}
DECL_GUI_MODULE(BeastModule);
#endif //#if defined (__DAVAENGINE_BEAST__)
| 32.137931 | 222 | 0.696137 | typicalMoves |
7b4c0900cccfce3a5c05032ae73783bab8cfe010 | 240 | hpp | C++ | CPP_US/src/Engine/Engine.hpp | Basher207/Unity-style-Cpp-engine | 812b0be2c61aea828cfd8c6d6f06f2cf6e889661 | [
"MIT"
] | null | null | null | CPP_US/src/Engine/Engine.hpp | Basher207/Unity-style-Cpp-engine | 812b0be2c61aea828cfd8c6d6f06f2cf6e889661 | [
"MIT"
] | null | null | null | CPP_US/src/Engine/Engine.hpp | Basher207/Unity-style-Cpp-engine | 812b0be2c61aea828cfd8c6d6f06f2cf6e889661 | [
"MIT"
] | null | null | null | #pragma once
//Adds all the relevant headers.
#include "GameObject.hpp"
#include "Camera.hpp"
#include "Input.hpp"
#include "Math.hpp"
#include "MeshRenderer.hpp"
#include "MonoBehaviour.hpp"
#include "Runner.hpp"
#include "Transform.hpp"
| 20 | 32 | 0.75 | Basher207 |
7b4fbc1d7cf44867c7ecb57322ef41a610e79ec8 | 18,027 | cpp | C++ | src/ED/LineSegment.cpp | yuki-inaho/stag | 89c5c648acae90375fb8ffc4bf9453f1b15cc835 | [
"MIT"
] | 125 | 2017-08-11T06:50:32.000Z | 2022-03-31T13:50:17.000Z | src/ED/LineSegment.cpp | yuki-inaho/stag | 89c5c648acae90375fb8ffc4bf9453f1b15cc835 | [
"MIT"
] | 22 | 2017-07-21T12:37:11.000Z | 2022-03-23T22:42:52.000Z | src/ED/LineSegment.cpp | yuki-inaho/stag | 89c5c648acae90375fb8ffc4bf9453f1b15cc835 | [
"MIT"
] | 26 | 2017-11-13T02:04:57.000Z | 2022-03-31T10:47:04.000Z | #include <stdio.h>
#include <math.h>
#include "LineSegment.h"
///------------------------------------------------------------------
/// Rounds a double number to its closest integer part.
/// E.g., 4.24-->4, 4.78-->5
///
int Round(double d){
return (int)(d+0.5);
} //end-Round
///-------------------------------------------------------------------------------
/// Simply returns the length of a line segment
///
double LineSegmentLength(LineSegment *ls){
double dx = ls->sx-ls->ex;
double dy = ls->sy-ls->ey;
return sqrt(dx*dx + dy*dy);
} //end-LineSegmentLength
///-------------------------------------------------------------------------------
/// Computes the angle between two line segments
/// Assumes that (ex, ey) of ls1 is closer to (sx, ey) of ls2
///
double ComputeAngleBetweenTwoLines(LineSegment *ls1, LineSegment *ls2, double *pMinDist){
double vx1 = ls1->ex - ls1->sx;
double vy1 = ls1->ey - ls1->sy;
double v1Len = sqrt(vx1*vx1 + vy1*vy1);
double vx2 = ls2->ex - ls2->sx;
double vy2 = ls2->ey - ls2->sy;
double v2Len = sqrt(vx2*vx2 + vy2*vy2);
double dotProduct = vx1*vx2 + vy1*vy2;
double result = dotProduct/(v1Len*v2Len);
if (result < -1.0) result = -1.0;
else if (result > 1.0) result = 1.0;
double angle = acos(result);
#define PI 3.14159
angle = (angle/PI)*180; // convert to degrees
if (pMinDist){
// Compute the distance between (ex, ey) of ls1 & (sx, sy) of ls2
double dx = ls1->ex - ls2->sx;
double dy = ls1->ey - ls2->sy;
*pMinDist = sqrt(dx*dx + dy*dy);
} //end-if
return angle;
} //end-ComputeAngleBetweenTwoLines
///-------------------------------------------------------------------------------
/// Computes the angle (in degrees) between two line segments
/// Also returns the minimum distance between the end points of the two lines
/// Which returns a value that designates which endpoints are closer
/// The meaning of this value is the following:
/// SS -- 00 - 0 (sx1, sy1) <--> (sx2, sy2)
/// SE -- 01 - 1 (sx1, sy1) <--> (ex2, ey2)
/// ES -- 10 - 2 (ex1, ey1) <--> (sx2, sy2)
/// EE -- 11 - 3 (ex1, ey1) <--> (ex2, ey2)
///
#define SS 0
#define SE 1
#define ES 2
#define EE 3
double ComputeAngleBetweenTwoLines2(LineSegment *ls1, LineSegment *ls2, double *pMinDist, int *pwhich){
double dx = ls1->sx - ls2->sx;
double dy = ls1->sy - ls2->sy;
double d = sqrt(dx*dx + dy*dy);
double min = d;
int which = SS;
dx = ls1->sx - ls2->ex;
dy = ls1->sy - ls2->ey;
d = sqrt(dx*dx + dy*dy);
if (d < min){min = d; which = SE;}
dx = ls1->ex - ls2->sx;
dy = ls1->ey - ls2->sy;
d = sqrt(dx*dx + dy*dy);
if (d < min){min = d; which = ES;}
dx = ls1->ex - ls2->ex;
dy = ls1->ey - ls2->ey;
d = sqrt(dx*dx + dy*dy);
if (d < min){min = d; which = EE;}
if (pMinDist) *pMinDist = min;
if (pwhich) *pwhich = which;
double vx1, vy1, vx2, vy2;
switch (which){
case SS:
vx1 = ls1->ex - ls1->sx;
vy1 = ls1->ey - ls1->sy;
vx2 = ls2->ex - ls2->sx;
vy2 = ls2->ey - ls2->sy;
break;
case SE:
vx1 = ls1->ex - ls1->sx;
vy1 = ls1->ey - ls1->sy;
vx2 = ls2->sx - ls2->ex;
vy2 = ls2->sy - ls2->ey;
break;
case ES:
vx1 = ls1->sx - ls1->ex;
vy1 = ls1->sy - ls1->ey;
vx2 = ls2->ex - ls2->sx;
vy2 = ls2->ey - ls2->sy;
break;
case EE:
vx1 = ls1->sx - ls1->ex;
vy1 = ls1->sy - ls1->ey;
vx2 = ls2->sx - ls2->ex;
vy2 = ls2->sy - ls2->ey;
break;
} //end-case
double v1Len = sqrt(vx1*vx1 + vy1*vy1);
double v2Len = sqrt(vx2*vx2 + vy2*vy2);
double dotProduct = vx1*vx2 + vy1*vy2;
double result = dotProduct/(v1Len*v2Len);
if (result < -1.0) result = -1.0;
else if (result > 1.0) result = 1.0;
double angle = acos(result);
#define PI 3.14159
angle = (angle/PI)*180; // convert to degrees
// Return the angle
return angle;
} //end-ComputeAngleBetweenTwoLines2
///-------------------------------------------------------------------------------
/// Computes the minimum distance between the end points of two lines
///
double ComputeMinDistanceBetweenTwoLines(LineSegment *ls1, LineSegment *ls2, int *pwhich){
double dx = ls1->sx - ls2->sx;
double dy = ls1->sy - ls2->sy;
double d = sqrt(dx*dx + dy*dy);
double min = d;
int which = SS;
dx = ls1->sx - ls2->ex;
dy = ls1->sy - ls2->ey;
d = sqrt(dx*dx + dy*dy);
if (d < min){min = d; which = SE;}
dx = ls1->ex - ls2->sx;
dy = ls1->ey - ls2->sy;
d = sqrt(dx*dx + dy*dy);
if (d < min){min = d; which = ES;}
dx = ls1->ex - ls2->ex;
dy = ls1->ey - ls2->ey;
d = sqrt(dx*dx + dy*dy);
if (d < min){min = d; which = EE;}
if (pwhich) *pwhich = which;
return min;
} //end-ComputeMinDistanceBetweenTwoLines
///-------------------------------------------------------------------------------
/// Computes the intersection point of the two lines ls1 & ls2
/// Assumes that the lines are NOT collinear
///
void FindIntersectionPoint(LineSegment *ls1, LineSegment *ls2, double *xInt, double *yInt){
double x = 0.0;
double y = 0.0;
if (ls1->invert == 0 && ls2->invert == 0){
// Both lines are of the form y = bx + a
x = (ls2->a - ls1->a)/(ls1->b - ls2->b);
y = ls1->b * x + ls1->a;
} else if (ls1->invert == 0 && ls2->invert == 1){
// LS1 is of the form y = bx + a, LS2 is of the form x = by + a
x = (ls2->b*ls1->a + ls2->a)/(1.0-ls2->b*ls1->b);
y = ls1->b * x + ls1->a;
} else if (ls1->invert == 1 && ls2->invert == 0){
// LS1 is of the form x = by + a and LS2 is of the form y = bx + a
y = (ls2->b*ls1->a + ls2->a)/(1.0-ls1->b*ls2->b);
x = ls1->b*y + ls1->a;
} else { // ls1->invert == 1 && ls2->invert == 1
// Both lines are of the form x = by + a
y = (ls1->a - ls2->a)/(ls2->b - ls1->b);
x = ls1->b*y + ls1->a;
} //end-else
*xInt = x;
*yInt = y;
} // end-FindIntersectionPoint
///-----------------------------------------------------------------
/// Checks if the given line segments are collinear & joins them if they are
/// In case of a join, ls1 is updated. ls2 is NOT changed
/// Returns true if join is successful, false otherwise
///
bool TryToJoinTwoLineSegments(LineSegment *ls1, LineSegment *ls2, double MAX_DISTANCE_BETWEEN_TWO_LINES, double MAX_ERROR){
// Must belong to the same segment
// if (ls1->segmentNo != ls2->segmentNo) return false;
int which;
double dist = ComputeMinDistanceBetweenTwoLines(ls1, ls2, &which);
if (dist > MAX_DISTANCE_BETWEEN_TWO_LINES) return false;
// Compute line lengths. Use the longer one as the ground truth
double dx = ls1->sx-ls1->ex;
double dy = ls1->sy-ls1->ey;
double prevLen = sqrt(dx*dx + dy*dy);
dx = ls2->sx-ls2->ex;
dy = ls2->sy-ls2->ey;
double nextLen = sqrt(dx*dx + dy*dy);
// Use the longer line as the ground truth
LineSegment *shorter = ls1;
LineSegment *longer = ls2;
if (prevLen > nextLen){shorter = ls2; longer = ls1;}
#if 0
// Use 5 points to check for collinearity
#define POINT_COUNT 5
double decr = 1.0/(POINT_COUNT-1);
double alpha = 1.0;
dist = 0.0;
while (alpha >= 0.0){
double px = alpha*shorter->sx + (1.0-alpha)*shorter->ex;
double py = alpha*shorter->sy + (1.0-alpha)*shorter->ey;
dist += ComputeMinDistance(px, py, longer->a, longer->b, longer->invert);
alpha -= decr;
} //end-while
dist /= POINT_COUNT;
#undef POINT_COUNT
#else
// Just use 3 points to check for collinearity
dist = ComputeMinDistance(shorter->sx, shorter->sy, longer->a, longer->b, longer->invert);
dist += ComputeMinDistance((shorter->sx+shorter->ex)/2.0, (shorter->sy+shorter->ey)/2.0, longer->a, longer->b, longer->invert);
dist += ComputeMinDistance(shorter->ex, shorter->ey, longer->a, longer->b, longer->invert);
dist /= 3.0;
#endif
if (dist > MAX_ERROR) return false;
#if 0
// Update the end points of ls1
if (which == 0) { // SS
ls1->sx = ls2->ex;
ls1->sy = ls2->ey;
} else if (which == 1){ // SE
ls1->sx = ls2->sx;
ls1->sy = ls2->sy;
} else if (which == 2){ // ES
ls1->ex = ls2->ex;
ls1->ey = ls2->ey;
} else { // EE
ls1->ex = ls2->sx;
ls1->ey = ls2->sy;
} //end-else
#else
/// 4 cases: 1:(s1, s2), 2:(s1, e2), 3:(e1, s2), 4:(e1, e2)
/// case 1: (s1, s2)
dx = fabs(ls1->sx-ls2->sx);
dy = fabs(ls1->sy-ls2->sy);
double d = dx+dy;
double max = d;
which = 1;
/// case 2: (s1, e2)
dx = fabs(ls1->sx-ls2->ex);
dy = fabs(ls1->sy-ls2->ey);
d = dx+dy;
if (d > max){
max = d;
which = 2;
} //end-if
/// case 3: (e1, s2)
dx = fabs(ls1->ex-ls2->sx);
dy = fabs(ls1->ey-ls2->sy);
d = dx+dy;
if (d > max){
max = d;
which = 3;
} //end-if
/// case 4: (e1, e2)
dx = fabs(ls1->ex-ls2->ex);
dy = fabs(ls1->ey-ls2->ey);
d = dx+dy;
if (d > max){
max = d;
which = 4;
} //end-if
if (which == 1){
// (s1, s2)
ls1->ex = ls2->sx;
ls1->ey = ls2->sy;
} else if (which == 2){
// (s1, e2)
ls1->ex = ls2->ex;
ls1->ey = ls2->ey;
} else if (which == 3){
// (e1, s2)
ls1->sx = ls2->sx;
ls1->sy = ls2->sy;
} else {
// (e1, e2)
ls1->sx = ls1->ex;
ls1->sy = ls1->ey;
ls1->ex = ls2->ex;
ls1->ey = ls2->ey;
} //end-else
#endif
// Update the first line's parameters
if (ls1->firstPixelIndex + ls1->len + 5 >= ls2->firstPixelIndex) ls1->len += ls2->len;
else if (ls2->len > ls1->len){
ls1->firstPixelIndex = ls2->firstPixelIndex;
ls1->len = ls2->len;
} //end-if
UpdateLineParameters(ls1);
return true;
} //end-TryToJoinTwoLineSegments
///-------------------------------------------------------------------
/// Traces the points on the line from (sx, sy) --> (ex, ey)
/// using only integer arithmetic using the famous Bresenham line tracking algorithm
/// The points on the line are filled into px and py arrays. No of points are also returned
///
void BresenhamLineTrace(int sx, int sy, int ex, int ey, int px[], int py[], int *noPoints){
int dx = ex-sx;
int dy = ey-sy;
int count = 0;
if (abs(dx) >= abs(dy)){
int xIncr = 1;
if (dx < 0) xIncr = -1;
int yIncr = 1;
if (dy < 0) yIncr = -1;
int incrE, incrNE, d, x, y;
d = abs(dy)*2-abs(dx);
incrE = abs(dy)*2;
incrNE = (abs(dy)-abs(dx))*2;
x = sx;
y = sy;
dx = abs(dx);
for (int xx=0; xx <= dx; xx++){
px[count] = x;
py[count] = y;
count++;
if (d <= 0){
d += incrE;
x += xIncr;
} else {
d += incrNE;
x += xIncr;
y += yIncr;
} //end-else
} //end-while
} else {
int xIncr = 1;
if (dx < 0) xIncr = -1;
int yIncr = 1;
if (dy < 0) yIncr = -1;
int incrE, incrNE, d, x, y;
d = abs(dx)*2-abs(dy);
incrE = abs(dx)*2;
incrNE = (abs(dx)-abs(dy))*2;
x = sx;
y = sy;
dy = abs(dy);
for (int yy=0; yy <= dy; yy++){
px[count] = x;
py[count] = y;
count++;
if (d <= 0){
d += incrE;
y += yIncr;
} else {
d += incrNE;
y += yIncr;
x += xIncr;
} //end-else
} //end-while
} //end-else
*noPoints = count;
} //end-BresenhamLineTrace
///---------------------------------------------------------------------------------
/// Given a point (x1, y1) and a line equation y=a+bx (invert=0) OR x=a+by (invert=1)
/// Computes the (x2, y2) on the line that is closest to (x1, y1)
///
void ComputeClosestPoint(double x1, double y1, double a, double b, int invert, double *xOut, double *yOut){
double x2, y2;
if (invert == 0){
if (b == 0){
x2 = x1;
y2 = a;
} else {
// Let the line passing through (x1, y1) that is perpendicular to a+bx be c+dx
double d = -1.0/(b);
double c = y1-d*x1;
x2 = (a-c)/(d-b);
y2 = a+b*x2;
} //end-else
} else {
/// invert = 1
if (b == 0){
x2 = a;
y2 = y1;
} else {
// Let the line passing through (x1, y1) that is perpendicular to a+by be c+dy
double d = -1.0/(b);
double c = x1-d*y1;
y2 = (a-c)/(d-b);
x2 = a+b*y2;
} //end-else
} //end-else
*xOut = x2;
*yOut = y2;
} //end-ComputeClosestPoint
///---------------------------------------------------------------------------------
/// Given a point (x1, y1) and a line equation y=a+bx (invert=0) OR x=a+by (invert=1)
/// Computes the minimum distance of (x1, y1) to the line
///
double ComputeMinDistance(double x1, double y1, double a, double b, int invert){
double x2, y2;
if (invert == 0){
if (b == 0){
x2 = x1;
y2 = a;
} else {
// Let the line passing through (x1, y1) that is perpendicular to a+bx be c+dx
double d = -1.0/(b);
double c = y1-d*x1;
x2 = (a-c)/(d-b);
y2 = a+b*x2;
} //end-else
} else {
/// invert = 1
if (b == 0){
x2 = a;
y2 = y1;
} else {
// Let the line passing through (x1, y1) that is perpendicular to a+by be c+dy
double d = -1.0/(b);
double c = x1-d*y1;
y2 = (a-c)/(d-b);
x2 = a+b*y2;
} //end-else
} //end-else
return sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
} //end-ComputeMinDistance
///-----------------------------------------------------------------------------------
/// Uses the two end points (sx, sy)----(ex, ey) of the line segment
/// and computes the line that passes through these points (a, b, invert)
///
void UpdateLineParameters(LineSegment *ls){
double dx = ls->ex-ls->sx;
double dy = ls->ey-ls->sy;
if (fabs(dx) >= fabs(dy)){
/// Line will be of the form y = a + bx
ls->invert = 0;
if (fabs(dy) < 1e-3){ls->b = 0; ls->a = (ls->sy+ls->ey)/2;}
else {
ls->b = dy/dx;
ls->a = ls->sy-(ls->b)*ls->sx;
} //end-else
} else {
/// Line will be of the form x = a + by
ls->invert = 1;
if (fabs(dx) < 1e-3){ls->b = 0; ls->a = (ls->sx+ls->ex)/2;}
else {
ls->b = dx/dy;
ls->a = ls->sx-(ls->b)*ls->sy;
} //end-else
} //end-else
} //end-UpdateLineParameters
///-----------------------------------------------------------------------------------
/// Given two points (sx, sy)----(ex, ey), computes the line that passes through these points
/// Assumes that the points are not very close
///
void ComputeLine(double sx, double sy, double ex, double ey, double *a, double *b, int *invert) {
double dx = ex-sx;
double dy = ey-sy;
if (fabs(dx) >= fabs(dy)){
/// Line will be of the form y = a + bx
*invert = 0;
if (fabs(dy) < 1e-3){*b = 0; *a = (sy+ey)/2;}
else {
*b = dy/dx;
*a = sy-(*b)*sx;
} //end-else
} else {
/// Line will be of the form x = a + by
*invert = 1;
if (fabs(dx) < 1e-3){*b = 0; *a = (sx+ex)/2;}
else {
*b = dx/dy;
*a = sx-(*b)*sy;
} //end-else
} //end-else
} //end-ComputeLine
///-----------------------------------------------------------------------------------
/// Fits a line of the form y=a+bx (invert == 0) OR x=a+by (invert == 1)
///
void LineFit(double *x, double *y, int count, double *a, double *b, double *e, int *invert) {
if (count<2) return;
double S=count, Sx=0.0, Sy=0.0, Sxx=0.0, Sxy=0.0;
for (int i=0; i<count; i++) {
Sx += x[i];
Sy += y[i];
} //end-for
double mx = Sx/count;
double my = Sy/count;
double dx = 0.0;
double dy = 0.0;
for (int i=0; i < count; i++) {
dx += (x[i] - mx)*(x[i] - mx);
dy += (y[i] - my)*(y[i] - my);
} //end-for
if (dx < dy) {
// Vertical line. Swap x & y, Sx & Sy
*invert = 1;
double *t = x;
x = y;
y = t;
double d = Sx;
Sx = Sy;
Sy = d;
} else {
*invert = 0;
} //end-else
// Now compute Sxx & Sxy
for (int i=0; i<count; i++) {
Sxx += x[i] * x[i];
Sxy += x[i] * y[i];
} //end-for
double D = S*Sxx - Sx*Sx;
*a = (Sxx*Sy - Sx*Sxy)/D;
*b = (S *Sxy - Sx* Sy)/D;
if (*b==0.0) {
// Vertical or horizontal line
double error = 0.0;
for (int i=0; i<count; i++) {
error += fabs((*a) - y[i]);
} //end-for
*e = error/count;
} else {
double error = 0.0;
for (int i=0; i<count; i++){
// Let the line passing through (x[i], y[i]) that is perpendicular to a+bx be c+dx
double d = -1.0/(*b);
double c = y[i]-d*x[i];
double x2 = ((*a)-c)/(d-(*b));
double y2 = (*a)+(*b)*x2;
double dist = (x[i]-x2)*(x[i]-x2) + (y[i]-y2)*(y[i]-y2);
error += dist;
} //end-for
*e = sqrt(error/count);
} //end-else
} // end LineFit
///-----------------------------------------------------------------------------------
/// Fits a line of the form y=a+bx (invert == 0) OR x=a+by (invert == 1)
/// Assumes that the direction of the line is known by a previous computation
///
void LineFit(double *x, double *y, int count, double *a, double *b, int invert){
if (count<2) return;
double S=count, Sx=0.0, Sy=0.0, Sxx=0.0, Sxy=0.0;
for (int i=0; i<count; i++) {
Sx += x[i];
Sy += y[i];
} //end-for
if (invert) {
// Vertical line. Swap x & y, Sx & Sy
double *t = x;
x = y;
y = t;
double d = Sx;
Sx = Sy;
Sy = d;
} //end-if
// Now compute Sxx & Sxy
for (int i=0; i<count; i++) {
Sxx += x[i] * x[i];
Sxy += x[i] * y[i];
} //end-for
double D = S*Sxx - Sx*Sx;
*a = (Sxx*Sy - Sx*Sxy)/D;
*b = (S *Sxy - Sx* Sy)/D;
} //end-LineFit
| 26.510294 | 130 | 0.485993 | yuki-inaho |
7b500580fc59dff7526e2bdc0f4b0f8fa7975e67 | 303 | cpp | C++ | libs/locale/build/has_iconv.cpp | cpp-pm/boost | 38c6c8c07f2fcc42d573b10807fef27ec14930f8 | [
"BSL-1.0"
] | 11,356 | 2017-12-08T19:42:32.000Z | 2022-03-31T16:55:25.000Z | libs/locale/build/has_iconv.cpp | cpp-pm/boost | 38c6c8c07f2fcc42d573b10807fef27ec14930f8 | [
"BSL-1.0"
] | 2,402 | 2017-12-08T22:31:01.000Z | 2022-03-28T19:25:52.000Z | libs/locale/build/has_iconv.cpp | cpp-pm/boost | 38c6c8c07f2fcc42d573b10807fef27ec14930f8 | [
"BSL-1.0"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | //
// Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#include <iconv.h>
int main()
{
iconv_t d = iconv_open(0,0);
(void)(d);
}
| 20.2 | 67 | 0.660066 | cpp-pm |
7b566c39ea793d84e61c4e64a5c1ecf09c071694 | 15,522 | cpp | C++ | bingo/bingo-core-c/src/ringo_core_c.cpp | f1nzer/Indigo | 59efbd0be0b42f449f706c3a3c8d094e483e5ef4 | [
"Apache-2.0"
] | null | null | null | bingo/bingo-core-c/src/ringo_core_c.cpp | f1nzer/Indigo | 59efbd0be0b42f449f706c3a3c8d094e483e5ef4 | [
"Apache-2.0"
] | null | null | null | bingo/bingo-core-c/src/ringo_core_c.cpp | f1nzer/Indigo | 59efbd0be0b42f449f706c3a3c8d094e483e5ef4 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
* Copyright (C) from 2009 to Present EPAM Systems.
*
* This file is part of Indigo toolkit.
*
* 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 "bingo_core_c_internal.h"
#include "base_cpp/profiling.h"
#include "molecule/cmf_saver.h"
#include "molecule/molfile_loader.h"
#include "molecule/smiles_saver.h"
#include "reaction/crf_saver.h"
#include "reaction/icr_saver.h"
#include "reaction/reaction_auto_loader.h"
#include "reaction/reaction_cml_saver.h"
#include "reaction/reaction_fingerprint.h"
#include "reaction/rsmiles_loader.h"
#include "reaction/rsmiles_saver.h"
#include "reaction/rxnfile_loader.h"
#include "reaction/rxnfile_saver.h"
using namespace indigo::bingo_core;
CEXPORT int ringoIndexProcessSingleRecord()
{
BINGO_BEGIN
{
BufferScanner scanner(self.index_record_data.ref());
NullOutput output;
TRY_READ_TARGET_RXN
{
try
{
if (self.single_ringo_index.get() == NULL)
{
self.single_ringo_index.create();
self.single_ringo_index->init(*self.bingo_context);
self.single_ringo_index->skip_calculate_fp = self.skip_calculate_fp;
}
self.ringo_index = self.single_ringo_index.get();
self.ringo_index->prepare(scanner, output, NULL);
}
catch (CmfSaver::Error& e)
{
if (self.bingo_context->reject_invalid_structures)
throw;
self.warning.readString(e.message(), true);
return 0;
}
catch (CrfSaver::Error& e)
{
if (self.bingo_context->reject_invalid_structures)
throw;
self.warning.readString(e.message(), true);
return 0;
}
}
CATCH_READ_TARGET_RXN({
if (self.bingo_context->reject_invalid_structures)
throw;
self.warning.readString(e.message(), true);
return 0;
});
}
BINGO_END(1, -1);
}
CEXPORT int ringoIndexReadPreparedReaction(int* id, const char** crf_buf, int* crf_buf_len, const char** fingerprint_buf, int* fingerprint_buf_len)
{
profTimerStart(t0, "index.prepare_reaction");
BINGO_BEGIN
{
if (id)
*id = self.index_record_data_id;
const Array<char>& crf = self.ringo_index->getCrf();
*crf_buf = crf.ptr();
*crf_buf_len = crf.size();
*fingerprint_buf = (const char*)self.ringo_index->getFingerprint();
*fingerprint_buf_len = self.bingo_context->fp_parameters.fingerprintSizeExtOrd() * 2;
return 1;
}
BINGO_END(-2, -2);
}
void _ringoCheckPseudoAndCBDM(BingoCore& self)
{
if (self.bingo_context == 0)
throw BingoError("context not set");
if (self.ringo_context == 0)
throw BingoError("context not set");
// TODO: pass this check inside RingoSubstructure
if (!self.bingo_context->treat_x_as_pseudoatom.hasValue())
throw BingoError("treat_x_as_pseudoatom option not set");
if (!self.bingo_context->ignore_closing_bond_direction_mismatch.hasValue())
throw BingoError("ignore_closing_bond_direction_mismatch option not set");
}
CEXPORT int ringoSetupMatch(const char* search_type, const char* query, const char* options)
{
profTimerStart(t0, "match.setup_match");
BINGO_BEGIN
{
_ringoCheckPseudoAndCBDM(self);
TRY_READ_TARGET_RXN
{
if (strcasecmp(search_type, "RSUB") == 0 || strcasecmp(search_type, "RSMARTS") == 0)
{
RingoSubstructure& substructure = self.ringo_context->substructure;
if (substructure.parse(options))
{
if (strcasecmp(search_type, "RSUB") == 0)
substructure.loadQuery(query);
else
substructure.loadSMARTS(query);
self.ringo_search_type = BingoCore::_SUBSTRUCTRE;
return 1;
}
}
else if (strcasecmp(search_type, "REXACT") == 0)
{
RingoExact& exact = self.ringo_context->exact;
exact.setParameters(options);
exact.loadQuery(query);
self.ringo_search_type = BingoCore::_EXACT;
return 1;
}
self.ringo_search_type = BingoCore::_UNDEF;
throw BingoError("Unknown search type '%s' or options string '%s'", search_type, options);
}
CATCH_READ_TARGET_RXN(self.error.readString(e.message(), 1); return -1;);
}
BINGO_END(-2, -2);
}
// Return value:
// 1 if the query is a substructure of the taret
// 0 if it is not
// -1 if something is bad with the target ("quiet" error)
// -2 if some other thing is bad ("sound" error)
CEXPORT int ringoMatchTarget(const char* target, int target_buf_len)
{
profTimerStart(t0, "match.match_target");
BINGO_BEGIN
{
if (self.ringo_search_type == BingoCore::_UNDEF)
throw BingoError("Undefined search type");
TRY_READ_TARGET_RXN
{
BufferScanner scanner(target, target_buf_len);
if (self.ringo_search_type == BingoCore::_SUBSTRUCTRE)
{
RingoSubstructure& substructure = self.ringo_context->substructure;
substructure.loadTarget(scanner);
return substructure.matchLoadedTarget() ? 1 : 0;
}
else if (self.ringo_search_type == BingoCore::_EXACT)
{
RingoExact& exact = self.ringo_context->exact;
exact.loadTarget(scanner);
return exact.matchLoadedTarget() ? 1 : 0;
}
else
throw BingoError("Invalid search type");
}
CATCH_READ_TARGET_RXN(self.warning.readString(e.message(), 1); return -1;);
}
BINGO_END(-2, -2);
}
// Return value:
// 1 if the query is a substructure of the taret
// 0 if it is not
// -1 if something is bad with the target ("quiet" error)
// -2 if some other thing is bad ("sound" error)
CEXPORT int ringoMatchTargetBinary(const char* target_bin, int target_bin_len)
{
profTimerStart(t0, "match.match_target_binary");
BINGO_BEGIN
{
if (self.ringo_search_type == BingoCore::_UNDEF)
throw BingoError("Undefined search type");
TRY_READ_TARGET_RXN
{
BufferScanner scanner(target_bin, target_bin_len);
if (self.ringo_search_type == BingoCore::_SUBSTRUCTRE)
{
RingoSubstructure& substructure = self.ringo_context->substructure;
return substructure.matchBinary(scanner) ? 1 : 0;
}
else if (self.ringo_search_type == BingoCore::_EXACT)
{
RingoExact& exact = self.ringo_context->exact;
return exact.matchBinary(scanner) ? 1 : 0;
}
else
throw BingoError("Invalid search type");
}
CATCH_READ_TARGET_RXN(self.warning.readString(e.message(), 1); return -1;);
}
BINGO_END(-2, -2);
}
CEXPORT const char* ringoRSMILES(const char* target_buf, int target_buf_len)
{
profTimerStart(t0, "rsmiles");
BINGO_BEGIN
{
_ringoCheckPseudoAndCBDM(self);
BufferScanner scanner(target_buf, target_buf_len);
QS_DEF(Reaction, target);
ReactionAutoLoader loader(scanner);
self.bingo_context->setLoaderSettings(loader);
loader.loadReaction(target);
ArrayOutput out(self.buffer);
RSmilesSaver saver(out);
saver.saveReaction(target);
out.writeByte(0);
return self.buffer.ptr();
}
BINGO_END(0, 0);
}
CEXPORT const char* ringoRxnfile(const char* reaction, int reaction_len)
{
BINGO_BEGIN
{
_ringoCheckPseudoAndCBDM(self);
BufferScanner scanner(reaction, reaction_len);
QS_DEF(Reaction, target);
ReactionAutoLoader loader(scanner);
self.bingo_context->setLoaderSettings(loader);
loader.loadReaction(target);
ArrayOutput out(self.buffer);
RxnfileSaver saver(out);
saver.saveReaction(target);
out.writeByte(0);
return self.buffer.ptr();
}
BINGO_END(0, 0);
}
CEXPORT const char* ringoRCML(const char* reaction, int reaction_len)
{
BINGO_BEGIN
{ // TODO: remove copy/paste in ringoRCML, ringoRxnfile and etc.
_ringoCheckPseudoAndCBDM(self);
BufferScanner scanner(reaction, reaction_len);
QS_DEF(Reaction, target);
ReactionAutoLoader loader(scanner);
self.bingo_context->setLoaderSettings(loader);
loader.loadReaction(target);
ArrayOutput out(self.buffer);
ReactionCmlSaver saver(out);
saver.saveReaction(target);
out.writeByte(0);
return self.buffer.ptr();
}
BINGO_END(0, 0);
}
CEXPORT const char* ringoAAM(const char* reaction, int reaction_len, const char* mode)
{
BINGO_BEGIN
{
_ringoCheckPseudoAndCBDM(self);
self.ringo_context->ringoAAM.parse(mode);
BufferScanner reaction_scanner(reaction, reaction_len);
self.ringo_context->ringoAAM.loadReaction(reaction_scanner);
self.ringo_context->ringoAAM.getResult(self.buffer);
self.buffer.push(0);
return self.buffer.ptr();
}
BINGO_END(0, 0);
}
CEXPORT const char* ringoCheckReaction(const char* reaction, int reaction_len)
{
BINGO_BEGIN
{
TRY_READ_TARGET_RXN
{
_ringoCheckPseudoAndCBDM(self);
QS_DEF(Reaction, rxn);
BufferScanner reaction_scanner(reaction, reaction_len);
ReactionAutoLoader loader(reaction_scanner);
self.bingo_context->setLoaderSettings(loader);
loader.loadReaction(rxn);
Reaction::checkForConsistency(rxn);
}
CATCH_READ_TARGET_RXN(self.buffer.readString(e.message(), true); return self.buffer.ptr())
catch (Exception& e)
{
e.appendMessage(" INTERNAL ERROR");
self.buffer.readString(e.message(), true);
return self.buffer.ptr();
}
catch (...)
{
return "INTERNAL UNKNOWN ERROR";
}
}
BINGO_END(0, 0);
}
CEXPORT int ringoGetQueryFingerprint(const char** query_fp, int* query_fp_len)
{
profTimerStart(t0, "match.query_fingerprint");
BINGO_BEGIN
{
if (self.ringo_search_type == BingoCore::_UNDEF)
throw BingoError("Undefined search type");
if (self.ringo_search_type == BingoCore::_SUBSTRUCTRE)
{
RingoSubstructure& substructure = self.ringo_context->substructure;
self.buffer.copy((const char*)substructure.getQueryFingerprint(), self.bingo_context->fp_parameters.fingerprintSizeExtOrd() * 2);
}
else
throw BingoError("Invalid search type");
*query_fp = self.buffer.ptr();
*query_fp_len = self.buffer.size();
}
BINGO_END(1, -2);
}
CEXPORT int ringoSetHightlightingMode(int enable)
{
BINGO_BEGIN
{
if (self.ringo_search_type == BingoCore::_SUBSTRUCTRE)
{
RingoSubstructure& substructure = self.ringo_context->substructure;
return substructure.preserve_bonds_on_highlighting = (enable != 0);
}
else
throw BingoError("Invalid search type");
}
BINGO_END(1, -2);
}
CEXPORT const char* ringoGetHightlightedReaction()
{
BINGO_BEGIN
{
if (self.ringo_search_type == BingoCore::_SUBSTRUCTRE)
{
RingoSubstructure& substructure = self.ringo_context->substructure;
substructure.getHighlightedTarget(self.buffer);
}
else
throw BingoError("Invalid search type");
self.buffer.push(0);
return self.buffer.ptr();
}
BINGO_END(0, 0);
}
CEXPORT const char* ringoICR(const char* reaction, int reaction_len, bool save_xyz, int* out_len)
{
BINGO_BEGIN
{
_ringoCheckPseudoAndCBDM(self);
BufferScanner scanner(reaction, reaction_len);
QS_DEF(Reaction, target);
ReactionAutoLoader loader(scanner);
self.bingo_context->setLoaderSettings(loader);
loader.loadReaction(target);
ArrayOutput out(self.buffer);
if ((save_xyz != 0) && !Reaction::haveCoord(target))
throw BingoError("reaction has no XYZ");
IcrSaver saver(out);
saver.save_xyz = (save_xyz != 0);
saver.saveReaction(target);
*out_len = self.buffer.size();
return self.buffer.ptr();
}
BINGO_END(0, 0);
}
CEXPORT int ringoGetHash(bool for_index, dword* hash)
{
BINGO_BEGIN
{
if (for_index)
{
*hash = self.ringo_index->getHash();
return 1;
}
else
{
if (self.ringo_search_type != BingoCore::_EXACT)
throw BingoError("Hash is valid only for exact search type");
RingoExact& exact = self.ringo_context->exact;
*hash = exact.getQueryHash();
return 1;
}
}
BINGO_END(-2, -2);
}
CEXPORT const char* ringoFingerprint(const char* reaction, int reaction_len, const char* options, int* out_len)
{
BINGO_BEGIN
{
_ringoCheckPseudoAndCBDM(self);
if (!self.bingo_context->fp_parameters_ready)
throw BingoError("Fingerprint settings not ready");
BufferScanner scanner(reaction, reaction_len);
QS_DEF(Reaction, target);
ReactionAutoLoader loader(scanner);
self.bingo_context->setLoaderSettings(loader);
loader.loadReaction(target);
ReactionFingerprintBuilder builder(target, self.bingo_context->fp_parameters);
builder.parseFingerprintType(options, false);
builder.process();
const char* buf = (const char*)builder.get();
int buf_len = self.bingo_context->fp_parameters.fingerprintSizeExtOrdSim() * 2;
self.buffer.copy(buf, buf_len);
*out_len = self.buffer.size();
return self.buffer.ptr();
}
BINGO_END(0, 0);
} | 31.044 | 148 | 0.591097 | f1nzer |
7b56a1a4f3b734e5ba6b1f56cf4886b0f9e95854 | 2,773 | cpp | C++ | Source/SnowClient.cpp | zcharli/snow-olsr | 3617044d3ad1a0541b346669bce76702f71f4d0c | [
"MIT"
] | 3 | 2018-08-08T22:31:52.000Z | 2019-12-17T14:02:59.000Z | Source/SnowClient.cpp | zcharli/snow-olsr | 3617044d3ad1a0541b346669bce76702f71f4d0c | [
"MIT"
] | null | null | null | Source/SnowClient.cpp | zcharli/snow-olsr | 3617044d3ad1a0541b346669bce76702f71f4d0c | [
"MIT"
] | null | null | null | #include "Headers/SnowClient.h"
#include "Headers/NetworkTrafficManager.h"
/* Testing headers */
#include "Headers/HelloMessage.h"
using namespace std;
SnowClient::SnowClient() {
//mSocketPtr = make_shared<WLAN>(INTERFACE_NAME);
}
SnowClient::~SnowClient() {}
int SnowClient::start() {
shared_ptr<NetworkTrafficManager> vNetworkManager = make_shared<NetworkTrafficManager>(INTERFACE_NAME);
vNetworkManager->init();
RoutingProtocol::getInstance().setPersonalAddress(vNetworkManager->getPersonalAddress());
while (1) {
shared_ptr<Packet> vPacket = vNetworkManager->getMessage();
if (vPacket != nullptr) {
//std::cout << "First packet " << vPacket->getSource() << std::endl;
if (vPacket->getSource()!= vNetworkManager->getPersonalAddress()) {
#if verbose
std::cout << "Malloc shared_ptr OLSR MESSAGE"<< std::endl;
#endif
shared_ptr<OLSRMessage> vMessage = make_shared<OLSRMessage>(vPacket);
#if verbose
std::cout << "OLSR Message is deserialized " << vPacket->getSource() << std::endl;
#endif
RoutingProtocol::getInstance().lockForUpdate();
if(RoutingProtocol::getInstance().updateState(vMessage).needsForwarding()) {
vNetworkManager->sendMsg(vMessage);
}
RoutingProtocol::getInstance().unLockAfterUpdate();
} else {
//std::cout << "Got a packet from my self lulz" << std::endl;
}
}
}
return 0;
}
// Code used to test deserialization and serialization
//
// std::shared_ptr<HelloMessage> msg = make_shared<HelloMessage>();
// HelloMessage::LinkMessage link;
// link.linkCode = 255;
// char a[] = {'1', '2', '3', '4', '5', '6'};
// MACAddress linkAddr(a);
// link.neighborIfAddr.push_back(linkAddr);
// msg->mLinkMessages.push_back(link);
// msg->type = 1;
// msg->htime = 255;
// msg->willingness = 255;
// msg->mMessageHeader.type = 1;
// msg->mMessageHeader.vtime = 255;
// msg->mMessageHeader.messageSize = 8080;
// memcpy(msg->mMessageHeader.originatorAddress, vNetworkManager->getPersonalAddress().data, WLAN_ADDR_LEN);
// // /msg.mMessageHeader.originatorAddress = vNetworkManager->getPersonalAddress().data;
// msg->mMessageHeader.timeToLive = 255;
// msg->mMessageHeader.hopCount = 255;
// msg->mMessageHeader.messageSequenceNumber = 8080;
// OLSRMessage omsg;
// omsg.messages.push_back(msg);
// char* serialized = omsg.serialize().getData();
// OLSRMessage dmsg(serialized);
| 37.986301 | 116 | 0.60476 | zcharli |
7b5a37d255cdd1fa127a2330b641b04937616e7e | 6,515 | cc | C++ | src/output/L2_Error_Calculator.cc | pgmaginot/DARK_ARTS | f04b0a30dcac911ef06fe0916921020826f5c42b | [
"MIT"
] | null | null | null | src/output/L2_Error_Calculator.cc | pgmaginot/DARK_ARTS | f04b0a30dcac911ef06fe0916921020826f5c42b | [
"MIT"
] | null | null | null | src/output/L2_Error_Calculator.cc | pgmaginot/DARK_ARTS | f04b0a30dcac911ef06fe0916921020826f5c42b | [
"MIT"
] | null | null | null | /** @file L2_Error_Calculator.cc
* @author pmaginot
* @brief A class that numerically approximates the L2 spatial errors of Temperature, Intensity, and Angle Integrated Intensity for MMS problems
*/
#include "L2_Error_Calculator.h"
// ##########################################################
// Public functions
// ##########################################################
L2_Error_Calculator::L2_Error_Calculator(const Angular_Quadrature& angular_quadrature,
const Fem_Quadrature& fem_quadrature,
const Cell_Data& cell_data,
const Input_Reader& input_reader)
:
m_n_dfem( fem_quadrature.get_number_of_interpolation_points() ) ,
m_n_cells( cell_data.get_total_number_of_cells() ),
/// m_n_quad_pts(fem_quadrature.get_number_of_integration_points() ),
m_n_quad_pts(fem_quadrature.get_number_of_source_points() ),
m_cell_data( cell_data ),
m_fem_quadrature( fem_quadrature ),
m_analytic_temperature(input_reader) ,
m_analytic_intensity(input_reader, angular_quadrature)
{
/// old way
// fem_quadrature.get_dfem_integration_points( m_integration_quadrature_pts );
// fem_quadrature.get_integration_weights( m_integration_quadrature_wts );
// fem_quadrature.get_dfem_at_integration_points( m_dfem_at_integration_pts );
/// more correct way
fem_quadrature.get_source_points(m_integration_quadrature_pts);
fem_quadrature.get_source_weights(m_integration_quadrature_wts);
fem_quadrature.get_dfem_at_source_points(m_dfem_at_integration_pts);
}
double L2_Error_Calculator::calculate_l2_error(const double time_eval, const Intensity_Moment_Data& phi) const
{
/// only going to calculate the error in the scalar flux
double err = 0.;
Eigen::VectorXd num_soln = Eigen::VectorXd::Zero(m_n_dfem);
for(int cell = 0 ; cell < m_n_cells ; cell++)
{
phi.get_cell_angle_integrated_intensity(cell,0,0 , num_soln);
err += calculate_local_l2_error(num_soln , m_cell_data.get_cell_left_edge(cell) , m_cell_data.get_cell_width(cell) , time_eval , PHI );
}
return sqrt(err);
}
double L2_Error_Calculator::calculate_l2_error(const double time_eval, const Temperature_Data& temperature) const
{
double err = 0.;
Eigen::VectorXd num_soln = Eigen::VectorXd::Zero(m_n_dfem);
for(int cell = 0 ; cell < m_n_cells ; cell++) {
temperature.get_cell_temperature(cell,num_soln);
err += calculate_local_l2_error(num_soln , m_cell_data.get_cell_left_edge(cell) , m_cell_data.get_cell_width(cell) , time_eval, TEMPERATURE );
}
return sqrt(err);
}
double L2_Error_Calculator::calculate_cell_avg_error(const double time_eval, const Intensity_Moment_Data& phi) const
{
/// only going to calculate the error in the scalar flux
double err = 0.;
Eigen::VectorXd num_soln = Eigen::VectorXd::Zero(m_n_dfem);
for(int cell = 0 ; cell < m_n_cells ; cell++)
{
phi.get_cell_angle_integrated_intensity(cell,0,0 , num_soln);
err += calculate_local_cell_avg_error(num_soln , m_cell_data.get_cell_left_edge(cell) , m_cell_data.get_cell_width(cell) , time_eval, PHI );
}
return sqrt(err);
}
double L2_Error_Calculator::calculate_cell_avg_error(const double time_eval, const Temperature_Data& temperature) const
{
double err = 0.;
Eigen::VectorXd num_soln = Eigen::VectorXd::Zero(m_n_dfem);
for(int cell = 0 ; cell < m_n_cells ; cell++) {
temperature.get_cell_temperature(cell,num_soln);
err += calculate_local_cell_avg_error(num_soln , m_cell_data.get_cell_left_edge(cell) , m_cell_data.get_cell_width(cell) , time_eval , TEMPERATURE );
}
return sqrt(err);
}
double L2_Error_Calculator::calculate_local_l2_error(
const Eigen::VectorXd& numeric_at_dfem, const double xL , const double dx , const double time , const Data_Type data ) const
{
double err = 0.;
/// add in dx/2 contribution
std::vector<double> numeric_soln;
m_fem_quadrature.evaluate_variable_at_quadrature_pts(numeric_at_dfem , m_dfem_at_integration_pts , numeric_soln);
double x_eval = 0.;
double analytic_soln = 0.;
for(int q = 0 ; q < m_n_quad_pts ; q++)
{
x_eval = xL + dx/2.*(1. + m_integration_quadrature_pts[q] );
switch(data)
{
case PHI:
{
analytic_soln = m_analytic_intensity.get_mms_phi(x_eval, time);
break;
}
case TEMPERATURE:
{
analytic_soln = m_analytic_temperature.get_mms_temperature(x_eval, time);
break;
}
default:
{
throw Dark_Arts_Exception(SUPPORT_OBJECT , "Trying to find the L2 error of a weird data type");
break;
}
}
// err += m_integration_quadrature_wts[q]*( analytic_soln*analytic_soln - 2.*numeric_soln[q]*analytic_soln + numeric_soln[q]*numeric_soln[q] );
err += m_integration_quadrature_wts[q]*( analytic_soln - numeric_soln[q])*( analytic_soln - numeric_soln[q]) ;
}
err *= dx/2.;
return err;
}
double L2_Error_Calculator::calculate_local_cell_avg_error(
const Eigen::VectorXd& numeric_at_dfem , const double xL , const double dx , const double time, const Data_Type data ) const
{
double err = 0.;
std::vector<double> numeric_soln;
m_fem_quadrature.evaluate_variable_at_quadrature_pts(numeric_at_dfem , m_dfem_at_integration_pts , numeric_soln);
double x_eval = 0.;
double analytic_soln = 0.;
double analytic_average = 0.;
double numeric_average = 0.;
for(int q = 0 ; q < m_n_quad_pts ; q++)
{
x_eval = xL + dx/2.*(1. + m_integration_quadrature_pts[q] );
switch(data)
{
case PHI:
{
analytic_soln = m_analytic_intensity.get_mms_phi(x_eval, time);
break;
}
case TEMPERATURE:
{
analytic_soln = m_analytic_temperature.get_mms_temperature(x_eval, time);
break;
}
default:
{
throw Dark_Arts_Exception(SUPPORT_OBJECT , "Trying to find the L2 error of a weird data type");
break;
}
}
analytic_average += m_integration_quadrature_wts[q]* analytic_soln ;
numeric_average += m_integration_quadrature_wts[q]*numeric_soln[q];
}
analytic_average /= 2.;
numeric_average /= 2.;
// err = dx*(analytic_average*analytic_average - 2.*analytic_average*numeric_average + numeric_average*numeric_average);
err = dx*(analytic_average-numeric_average)*(analytic_average-numeric_average) ;
return err;
}
| 36.396648 | 154 | 0.692556 | pgmaginot |
7b5cd1b1a1c5697011a60b990b9e544ec320d4db | 1,080 | cpp | C++ | src/benchmarks/ShowHash.cpp | perara-public/map_benchmark | 8efe2a5eab97449971733d71e2047c26537c6123 | [
"MIT"
] | 110 | 2019-02-19T05:20:55.000Z | 2022-03-21T10:14:18.000Z | src/benchmarks/ShowHash.cpp | perara-public/map_benchmark | 8efe2a5eab97449971733d71e2047c26537c6123 | [
"MIT"
] | 10 | 2019-02-27T09:41:39.000Z | 2021-04-15T06:35:56.000Z | src/benchmarks/ShowHash.cpp | perara-public/map_benchmark | 8efe2a5eab97449971733d71e2047c26537c6123 | [
"MIT"
] | 17 | 2019-02-26T12:12:43.000Z | 2022-01-27T07:03:59.000Z | #include "Hash.h"
#include "bench.h"
#include "hex.h"
#include <bitset>
template <typename T>
void showHash(T val) {
auto sh = std::hash<T>{}(val);
auto mh = Hash<T>{}(val);
std::cerr << hex(val) << " -> " << hex(sh) << " " << hex(mh) << " " << std::bitset<sizeof(size_t) * 8>(mh) << std::endl;
}
template <typename T>
void showHash(const char* title) {
std::cerr << std::endl << title << std::endl;
std::cerr << "input std::hash " << HashName << std::endl;
for (T i = 0; i < 100; ++i) {
showHash(i);
}
for (T i = 0; i < 10; ++i) {
T s = ((0x23d7 + i) << (sizeof(T) * 4)) + 12;
showHash(s);
}
// <= 0 so it works with int overflows
for (uint64_t i = 1; i <= (std::numeric_limits<T>::max)() && i != 0; i *= 2) {
showHash(static_cast<T>(i));
}
for (uint64_t i = 1; i <= (std::numeric_limits<T>::max)() && i != 0; i *= 2) {
showHash(static_cast<T>(i + 1));
}
}
BENCHMARK(ShowHash) {
showHash<uint64_t>("uint64_t");
showHash<int32_t>("int32_t");
}
| 26.341463 | 124 | 0.498148 | perara-public |
7b5dfd74467b7861e4667f8720b7e389065afea4 | 1,351 | cpp | C++ | src/IO/Device/ControlBoard/CM730.cpp | NaokiTakahashi12/OpenHumanoidController | ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d | [
"MIT"
] | 1 | 2019-09-23T06:21:47.000Z | 2019-09-23T06:21:47.000Z | src/IO/Device/ControlBoard/CM730.cpp | NaokiTakahashi12/hc-early | ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d | [
"MIT"
] | 12 | 2019-07-30T00:17:09.000Z | 2019-12-09T23:00:43.000Z | src/IO/Device/ControlBoard/CM730.cpp | NaokiTakahashi12/OpenHumanoidController | ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d | [
"MIT"
] | null | null | null |
/**
*
* @file CM730.cpp
* @author Naoki Takahashi
*
**/
#include "CM730.hpp"
#include "CM730ControlTable.hpp"
namespace IO {
namespace Device {
namespace ControlBoard {
CM730::CM730(RobotStatus::InformationPtr &robot_status_information_ptr) : SerialControlBoard(robot_status_information_ptr) {
id(default_id);
}
CM730::CM730(const ID &new_id, RobotStatus::InformationPtr &robot_status_information_ptr) : SerialControlBoard(new_id, robot_status_information_ptr) {
}
CM730::~CM730() {
}
std::string CM730::get_key() {
return "CM730";
}
void CM730::enable_power(const bool &flag) {
command_controller->set_packet(create_switch_power_packet(flag));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
void CM730::ping() {
command_controller->set_packet(Communicator::Protocols::DynamixelVersion1::create_ping_packet(id()));
}
Communicator::SerialFlowScheduler::SinglePacket CM730::create_switch_power_packet(const bool &flag) {
const auto value = flag ? Communicator::Protocols::DynamixelVersion1::enable : Communicator::Protocols::DynamixelVersion1::disable;
const auto packet = Communicator::Protocols::DynamixelVersion1::create_write_packet(
id(),
CM730ControlTable::dynamixel_power,
value
);
return packet;
}
}
}
}
| 25.018519 | 153 | 0.715766 | NaokiTakahashi12 |
7b5faea800d72e0705163223c5391249b42e51d7 | 1,030 | cpp | C++ | src/ipc/mq_receiver.cpp | kreopt/dcm | d9eae08b5ff716d5eb3d97684aeddd9492d342b0 | [
"MIT"
] | null | null | null | src/ipc/mq_receiver.cpp | kreopt/dcm | d9eae08b5ff716d5eb3d97684aeddd9492d342b0 | [
"MIT"
] | null | null | null | src/ipc/mq_receiver.cpp | kreopt/dcm | d9eae08b5ff716d5eb3d97684aeddd9492d342b0 | [
"MIT"
] | null | null | null | #include "mq_receiver.hpp"
#include <boost/interprocess/ipc/message_queue.hpp>
#include <thread>
#include "core/message.hpp"
namespace bip = boost::interprocess;
dcm::ipc::mq::receiver::receiver(const std::string &_mbox) : mbox_(_mbox) {
bip::message_queue::remove(_mbox.c_str());
mq_ = std::make_shared<bip::message_queue>(bip::create_only, mbox_.c_str(), MAX_MESSAGES, MAX_MESSAGE_SIZE);
}
dcm::ipc::mq::receiver::~receiver() {
bip::message_queue::remove(mbox_.c_str());
}
void dcm::ipc::mq::receiver::listen() {
size_t recvd_size;
uint priority;
while (!stop_) {
auto raw_msg = std::shared_ptr<char>(new char[MAX_MESSAGE_SIZE], [](char* _p){delete [] _p;});
mq_->receive(raw_msg.get(), MAX_MESSAGE_SIZE, recvd_size, priority);
if (on_message){
dcm::message msg;
interproc::buffer encoded(raw_msg.get(), recvd_size);
msg.decode_header(encoded);
on_message(std::move(msg));
}
std::this_thread::yield();
}
}
| 30.294118 | 112 | 0.645631 | kreopt |
7b6183048a03ea269bef1c4c6fb76adc6a32665a | 7,386 | cc | C++ | ns-allinone-2.35/ns-2.35/emulate/ping_responder.cc | nitishk017/ns2project | f037b796ff10300ffe0422580be5855c37d0b140 | [
"MIT"
] | 1 | 2020-05-29T13:04:42.000Z | 2020-05-29T13:04:42.000Z | ns-allinone-2.35/ns-2.35/emulate/ping_responder.cc | nitishk017/ns2project | f037b796ff10300ffe0422580be5855c37d0b140 | [
"MIT"
] | 1 | 2019-01-20T17:35:23.000Z | 2019-01-22T21:41:38.000Z | ns-allinone-2.35/ns-2.35/emulate/ping_responder.cc | nitishk017/ns2project | f037b796ff10300ffe0422580be5855c37d0b140 | [
"MIT"
] | 1 | 2021-09-29T16:06:57.000Z | 2021-09-29T16:06:57.000Z | /*
* Copyright (c) 1998 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the Network Research
* Group at Lawrence Berkeley National Laboratory.
* 4. Neither the name of the University nor of the Laboratory may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef lint
static const char rcsid[] =
"@(#) $Header: /cvsroot/nsnam/ns-2/emulate/ping_responder.cc,v 1.8 2000/09/01 03:04:10 haoboy Exp $";
#endif
#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include "agent.h"
#include "scheduler.h"
#include "emulate/internet.h"
//
// ping_responder.cc -- this agent may be inserted into nse as
// a real-world responder to ICMP ECHOREQUEST operations. It's
// used to test emulation mode, mostly (and in particular the rt scheduler)
//
class PingResponder : public Agent {
public:
PingResponder() : Agent(PT_LIVE) { }
void recv(Packet*, Handler*);
protected:
icmp* validate(int, ip*);
void reflect(ip*);
};
static class PingResponderClass : public TclClass {
public:
PingResponderClass() : TclClass("Agent/PingResponder") {}
TclObject* create(int , const char*const*) {
return (new PingResponder());
}
} class_pingresponder;
/*
* receive an ICMP echo request packet from the simulator.
* Actual IP packet is in the "data" portion of the packet, and
* is assumed to start with the IP header
*/
void
PingResponder::recv(Packet* pkt, Handler*)
{
hdr_cmn *ch = HDR_CMN(pkt);
int psize = ch->size();
u_char* payload = pkt->accessdata();
if (payload == NULL) {
fprintf(stderr, "%f: PingResponder(%s): recv NULL data area\n",
Scheduler::instance().clock(), name());
Packet::free(pkt);
return;
}
/*
* assume here that the data area contains an IP header!
*/
icmp* icmph;
if ((icmph = validate(psize, (ip*) payload)) == NULL) {
Internet::print_ip((ip*) payload);
Packet::free(pkt);
return;
}
/*
* tasks: change icmp type to echo-reply, recompute IP hdr cksum,
* recompute ICMP cksum
*/
icmph->icmp_type = ICMP_ECHOREPLY;
reflect((ip*) payload); // like kernel routine icmp_reflect()
/*
* set up simulator packet to go to the correct place
*/
Agent::initpkt(pkt);
ch->size() = psize; // will have been overwrittin by initpkt
target_->recv(pkt);
return;
}
/*
* check a bunch of stuff:
* ip vers ok, ip hlen is 5, proto is icmp, len big enough,
* not fragmented, cksum ok, saddr not mcast/bcast
*/
icmp*
PingResponder::validate(int sz, ip* iph)
{
if (sz < 20) {
fprintf(stderr, "%f: PingResponder(%s): sim pkt too small for base IP header(%d)\n",
Scheduler::instance().clock(), name(), sz);
return (NULL);
}
int ipver = (*((char*)iph) & 0xf0) >> 4;
if (ipver != 4) {
fprintf(stderr, "%f: PingResponder(%s): IP bad ver (%d)\n",
Scheduler::instance().clock(), name(), ipver);
return (NULL);
}
int iplen = ntohs(iph->ip_len);
int iphlen = (*((char*)iph) & 0x0f) << 2;
if (iplen < (iphlen + 8)) {
fprintf(stderr, "%f: PingResponder(%s): IP dgram not long enough (len: %d)\n",
Scheduler::instance().clock(), name(), iplen);
return (NULL);
}
if (sz < iplen) {
fprintf(stderr, "%f: PingResponder(%s): IP dgram not long enough (len: %d)\n",
Scheduler::instance().clock(), name(), iplen);
return (NULL);
}
if (iphlen != 20) {
fprintf(stderr, "%f: PingResponder(%s): IP bad hlen (%d)\n",
Scheduler::instance().clock(), name(), iphlen);
return (NULL);
}
if (Internet::in_cksum((u_short*) iph, iphlen)) {
fprintf(stderr, "%f: PingResponder(%s): IP bad cksum\n",
Scheduler::instance().clock(), name());
return (NULL);
}
if (iph->ip_p != IPPROTO_ICMP) {
fprintf(stderr, "%f: PingResponder(%s): not ICMP (proto: %d)\n",
Scheduler::instance().clock(), name(), iph->ip_p);
return (NULL);
}
if (iph->ip_off != 0) {
fprintf(stderr, "%f: PingResponder(%s): fragment! (off: 0x%x)\n",
Scheduler::instance().clock(), name(), ntohs(iph->ip_off));
return (NULL);
}
if (iph->ip_src.s_addr == 0xffffffff || iph->ip_src.s_addr == 0) {
fprintf(stderr, "%f: PingResponder(%s): bad src addr (%s)\n",
Scheduler::instance().clock(), name(),
inet_ntoa(iph->ip_src));
return (NULL);
}
if (IN_MULTICAST(ntohl(iph->ip_src.s_addr))) {
fprintf(stderr, "%f: PingResponder(%s): mcast src addr (%s)\n",
Scheduler::instance().clock(), name(),
inet_ntoa(iph->ip_src));
return (NULL);
}
icmp* icp = (icmp*) (iph + 1);
if (Internet::in_cksum((u_short*) icp, iplen - iphlen) != 0) {
fprintf(stderr,
"%f: PingResponder(%s): bad ICMP cksum\n",
Scheduler::instance().clock(), name());
return (NULL);
}
if (icp->icmp_type != ICMP_ECHO) {
fprintf(stderr, "%f: PingResponder(%s): not echo request (%d)\n",
Scheduler::instance().clock(), name(),
icp->icmp_type);
return (NULL);
}
if (icp->icmp_code != 0) {
fprintf(stderr, "%f: PingResponder(%s): bad code (%d)\n",
Scheduler::instance().clock(), name(),
icp->icmp_code);
return (NULL);
}
return (icp);
}
/*
* reflect: fix up the IP and ICMP info to reflect the packet
* back from where it came in real life
*
* this routine will just assume no IP options on the pkt
*/
void
PingResponder::reflect(ip* iph)
{
in_addr daddr = iph->ip_dst;
int iplen = ntohs(iph->ip_len);
int iphlen = (*((char*)iph) & 0x0f) << 2;
/* swap src and dest IP addresses on IP header */
iph->ip_dst = iph->ip_src;
iph->ip_src = daddr;
iph->ip_sum = 0;
iph->ip_sum = Internet::in_cksum((u_short*) iph, iphlen);
/* recompute the icmp cksum */
icmp* icp = (icmp*)(iph + 1); // just past standard IP header
icp->icmp_cksum = 0;
icp->icmp_cksum = Internet::in_cksum((u_short*)icp, iplen - iphlen);
}
| 29.782258 | 105 | 0.668291 | nitishk017 |
7b6439915c6da769852a49cef838cf5dfcea643c | 671 | cpp | C++ | source-code/UserDefinedTypes/TableStats/stats_main.cpp | gjbex/Scientific-C- | d7aeb88743ffa2a43b1df1569a9200b2447f401c | [
"CC-BY-4.0"
] | 115 | 2015-03-23T13:34:42.000Z | 2022-03-21T00:27:21.000Z | source-code/UserDefinedTypes/TableStats/stats_main.cpp | gjbex/Scientific-C- | d7aeb88743ffa2a43b1df1569a9200b2447f401c | [
"CC-BY-4.0"
] | 56 | 2015-02-25T15:04:26.000Z | 2022-01-03T07:42:48.000Z | source-code/UserDefinedTypes/TableStats/stats_main.cpp | gjbex/Scientific-C- | d7aeb88743ffa2a43b1df1569a9200b2447f401c | [
"CC-BY-4.0"
] | 59 | 2015-11-26T11:44:51.000Z | 2022-03-21T00:27:22.000Z | #include <iostream>
#include "stats.h"
int main() {
double value;
Stats stats;
while (std::cin >> value) {
stats.add(value);
}
try {
std::cout << "mean: " << stats.mean() << std::endl;
std::cout << "stddev: " << stats.stddev() << std::endl;
std::cout << "min: " << stats.min() << std::endl;
std::cout << "max: " << stats.max() << std::endl;
std::cout << "median: " << stats.median() << std::endl;
std::cout << "n: " << stats.nr_values() << std::endl;
} catch (std::out_of_range& e) {
std::cerr << "### error: " << e.what() << std::endl;
std::exit(1);
}
return 0;
}
| 27.958333 | 63 | 0.470939 | gjbex |
7b64e395000258c1f463ca0822ff1866a6897001 | 1,543 | hpp | C++ | src/GUI.hpp | kririae/Fluid-Visualization | fc3d6deceb2428479a4ec58d5dbe44dcfc1a204e | [
"MIT"
] | 2 | 2022-01-22T09:44:10.000Z | 2022-01-22T09:45:02.000Z | src/GUI.hpp | kririae/Fluid-Visualization | fc3d6deceb2428479a4ec58d5dbe44dcfc1a204e | [
"MIT"
] | null | null | null | src/GUI.hpp | kririae/Fluid-Visualization | fc3d6deceb2428479a4ec58d5dbe44dcfc1a204e | [
"MIT"
] | null | null | null | //
// Created by kr2 on 12/24/21.
//
#ifndef FLUIDVISUALIZATION_SRC_GUI_HPP
#define FLUIDVISUALIZATION_SRC_GUI_HPP
#include "Particle.hpp"
#include "Shader.hpp"
#include "PBuffer.hpp"
#include <functional>
#include <memory>
typedef unsigned int uint;
struct GLFWwindow;
class Solver;
class OrbitCamera;
class GUI {
public:
GUI(int WIDTH, int HEIGHT);
GUI(const GUI &) = delete;
GUI &operator=(const GUI &) = delete;
virtual ~GUI() = default;
virtual void mainLoop(const std::function<void()> &callback);
protected:
GLFWwindow *window{};
int width, height;
};
class RTGUI : public GUI {
// REAL-TIME GUI for Lagrange View stimulation(particles)
public:
RTGUI(int WIDTH, int HEIGHT);
~RTGUI() override = default;
void setParticles(const PBuffer& _buffer);
void setSolver(std::shared_ptr<Solver> _solver);
void mainLoop(const std::function<void()> &callback) override;
void del();
protected:
PBuffer buffer;
uint frame = 0;
unsigned int VAO{}, VBO{}, EBO{};
std::unique_ptr<Shader> p_shader{}, m_shader{};
std::shared_ptr<hvector<vec3> > mesh;
std::shared_ptr<hvector<uint> > indices;
std::shared_ptr<Solver> solver;
std::shared_ptr<OrbitCamera> camera;
bool snapshot{false};
bool pause{false};
uint lastPauseFrame{};
float lastX;
float lastY;
bool firstMouse{false};
private:
void renderParticles() const;
void refreshFps() const;
void processInput();
void saveParticles() const;
void mouseCallback(double x, double y);
};
#endif //FLUIDVISUALIZATION_SRC_GUI_HPP
| 20.851351 | 64 | 0.714193 | kririae |
7b66efcfc3e73148dc12bd31e7b6f173dcb25565 | 2,044 | cpp | C++ | lib/year2020/src/Day06Puzzle.cpp | MarkRDavison/AdventOfCode | 640ae6de76709367be8dfeb86b9f1f7d21908946 | [
"MIT"
] | null | null | null | lib/year2020/src/Day06Puzzle.cpp | MarkRDavison/AdventOfCode | 640ae6de76709367be8dfeb86b9f1f7d21908946 | [
"MIT"
] | null | null | null | lib/year2020/src/Day06Puzzle.cpp | MarkRDavison/AdventOfCode | 640ae6de76709367be8dfeb86b9f1f7d21908946 | [
"MIT"
] | null | null | null | #include <2020/Day06Puzzle.hpp>
#include <zeno-engine/Utility/StringExtensions.hpp>
#include <sstream>
#include <fstream>
#include <iostream>
namespace TwentyTwenty {
Day06Puzzle::Day06Puzzle() :
core::PuzzleBase("Custom Customs", 2020, 6) {
}
void Day06Puzzle::initialise(const core::InitialisationInfo& _initialisationInfo) {
setInputLines(ze::StringExtensions::splitStringByLines(ze::StringExtensions::loadFileToString(_initialisationInfo.parameters[0])));
}
void Day06Puzzle::setInputLines(const std::vector<std::string>& _inputLines) {
m_InputLines = std::vector<std::string>(_inputLines);
}
std::pair<std::string, std::string> Day06Puzzle::fastSolve() {
const auto& parsed = parseInput(m_InputLines);
auto part1 = doPart1(parsed);
auto part2 = doPart2(parsed);
return { part1, part2 };
}
std::vector<Day06Puzzle::Questions> Day06Puzzle::parseInput(const std::vector<std::string>& _input) {
std::vector<Day06Puzzle::Questions> parsed;
parsed.emplace_back();
for (const auto& i : _input) {
if (i.empty()) {
parsed.emplace_back();
continue;
}
auto& current = parsed.back();
current.emplace_back();
auto& qset = current.back();
for (const char c : i) {
qset.insert(c);
}
}
return parsed;
}
std::string Day06Puzzle::doPart1(const std::vector<Questions>& _parsedInput) {
int count = 0;
for (const auto& input : _parsedInput) {
std::set<char> uniqueAnswers;
for (const auto& q : input) {
for (const auto& answer : q) {
uniqueAnswers.insert(answer);
}
}
count += uniqueAnswers.size();
}
return std::to_string(count);;
}
std::string Day06Puzzle::doPart2(const std::vector<Questions>& _parsedInput) {
int count = 0;
for (const auto& t : _parsedInput) {
for (const auto& c : t[0]) {
bool valid = true;
for (unsigned i = 1; i < t.size(); ++i) {
if (t[i].count(c) <= 0) {
valid = false;
break;
}
}
if (valid) {
count++;
}
}
}
return std::to_string(count);;
}
}
| 21.291667 | 133 | 0.651174 | MarkRDavison |
7b682cb7d26f3b1663ee009f32fa184373b8c59b | 1,284 | cpp | C++ | 2-Data_Structures_and_Libraries/2.3-Non_Linear_Data_Structures_with_Built-in_Libraries/2-C++_STL_set_(Java_TreeSet)/vitorvgc/00978.cpp | IFCE-CP/CP3-solutions | 1abcabd9a06968184a55d3b0414637019014694c | [
"MIT"
] | 1 | 2017-11-16T10:56:17.000Z | 2017-11-16T10:56:17.000Z | 2-Data_Structures_and_Libraries/2.3-Non_Linear_Data_Structures_with_Built-in_Libraries/2-C++_STL_set_(Java_TreeSet)/vitorvgc/00978.cpp | IFCE-CP/CP3-solutions | 1abcabd9a06968184a55d3b0414637019014694c | [
"MIT"
] | null | null | null | 2-Data_Structures_and_Libraries/2.3-Non_Linear_Data_Structures_with_Built-in_Libraries/2-C++_STL_set_(Java_TreeSet)/vitorvgc/00978.cpp | IFCE-CP/CP3-solutions | 1abcabd9a06968184a55d3b0414637019014694c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
void print(priority_queue<int> pq) {
for(; !pq.empty(); pq.pop())
printf("%d\n", pq.top());
}
int main() {
int t;
for(scanf("%d", &t); t--; ) {
int b, sg, sb;
priority_queue<int> pqg, pqb;
scanf("%d %d %d", &b, &sg, &sb);
for(int i = 0, x; i < sg; ++i) {
scanf("%d", &x);
pqg.push(x);
}
for(int i = 0, x; i < sb; ++i) {
scanf("%d", &x);
pqb.push(x);
}
while(!pqg.empty() && !pqb.empty()) {
int n = min(b, (int)min(pqg.size(), pqb.size()));
vector<int> surv;
for(int i = 0; i < n; ++i) {
int g = pqg.top(); pqg.pop();
int b = pqb.top(); pqb.pop();
surv.push_back(g-b);
}
for(auto x : surv) {
if(x > 0) pqg.push(x);
else if(x < 0) pqb.push(-x);
}
}
if(pqg.empty() && pqb.empty())
printf("green and blue died\n");
else {
printf("%s wins\n", !pqg.empty() ? "green" : "blue");
print(!pqg.empty() ? pqg : pqb);
}
if(t) printf("\n");
}
return 0;
}
| 24.692308 | 65 | 0.374611 | IFCE-CP |
7b68f7a35a39189548e2159af99658ae33d1ae8a | 14,338 | hpp | C++ | include/gtest_mpi/gtest_mpi_internal.hpp | teonnik/gtest_mpi | 9664675870b36d1be6af682e3d99e63dfb6a3ad7 | [
"BSD-3-Clause"
] | 4 | 2019-05-31T09:35:09.000Z | 2021-08-08T03:59:49.000Z | include/gtest_mpi/gtest_mpi_internal.hpp | teonnik/gtest_mpi | 9664675870b36d1be6af682e3d99e63dfb6a3ad7 | [
"BSD-3-Clause"
] | 1 | 2019-06-20T12:31:27.000Z | 2019-06-20T12:31:27.000Z | include/gtest_mpi/gtest_mpi_internal.hpp | teonnik/gtest_mpi | 9664675870b36d1be6af682e3d99e63dfb6a3ad7 | [
"BSD-3-Clause"
] | 2 | 2019-05-31T09:35:14.000Z | 2019-06-14T14:16:43.000Z | // This project contains source code from the Googletest framework
// obtained from https://github.com/google/googletest with the following
// terms:
//
// Copyright 2005, Google 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 Google 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.
// ---------------------------------------------------------------------
//
// Modifications and additions are published under the following terms:
//
// Copyright 2019, Simon Frasch
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---------------------------------------------------------------------
#ifndef GUARD_GTEST_MPI_INTERNAL_HPP
#define GUARD_GTEST_MPI_INTERNAL_HPP
#include <gtest/gtest.h>
#include <mpi.h>
#include <unistd.h>
#include <cstdarg>
#include <string>
namespace gtest_mpi {
namespace { // no external linkage
// Taken / modified from Googletest
static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
static const char kUniversalFilter[] = "*";
static const char kDefaultOutputFormat[] = "xml";
static const char kDefaultOutputFile[] = "test_detail";
static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
static const char kTypeParamLabel[] = "TypeParam";
static const char kValueParamLabel[] = "GetParam()";
// Taken / modified from Googletest
enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW };
// Taken / modified from Googletest
static void PrintFullTestCommentIfPresent(const ::testing::TestInfo& test_info) {
const char* const type_param = test_info.type_param();
const char* const value_param = test_info.value_param();
if (type_param != NULL || value_param != NULL) {
printf(", where ");
if (type_param != NULL) {
printf("%s = %s", kTypeParamLabel, type_param);
if (value_param != NULL) printf(" and ");
}
if (value_param != NULL) {
printf("%s = %s", kValueParamLabel, value_param);
}
}
}
// Taken / modified from Googletest
bool ShouldUseColor(bool stdout_is_tty) {
using namespace ::testing;
using namespace ::testing::internal;
const char* const gtest_color = GTEST_FLAG(color).c_str();
if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
// On Windows the TERM variable is usually not set, but the
// console there does support colors.
return stdout_is_tty;
#else
// On non-Windows platforms, we rely on the TERM variable.
const char* const term = getenv("TERM");
const bool term_supports_color =
String::CStringEquals(term, "xterm") || String::CStringEquals(term, "xterm-color") ||
String::CStringEquals(term, "xterm-256color") || String::CStringEquals(term, "screen") ||
String::CStringEquals(term, "screen-256color") || String::CStringEquals(term, "tmux") ||
String::CStringEquals(term, "tmux-256color") ||
String::CStringEquals(term, "rxvt-unicode") ||
String::CStringEquals(term, "rxvt-unicode-256color") ||
String::CStringEquals(term, "linux") || String::CStringEquals(term, "cygwin");
return stdout_is_tty && term_supports_color;
#endif // GTEST_OS_WINDOWS
}
return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
String::CStringEquals(gtest_color, "1");
// We take "yes", "true", "t", and "1" as meaning "yes". If the
// value is neither one of these nor "auto", we treat it as "no" to
// be conservative.
}
// Taken / modified from Googletest
static const char* GetAnsiColorCode(GTestColor color) {
switch (color) {
case COLOR_RED:
return "1";
case COLOR_GREEN:
return "2";
case COLOR_YELLOW:
return "3";
default:
return NULL;
};
}
// Taken / modified from Googletest
static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
static const bool in_color_mode = ShouldUseColor(isatty(fileno(stdout)) != 0);
const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
if (!use_color) {
vprintf(fmt, args);
va_end(args);
return;
}
printf("\033[0;3%sm", GetAnsiColorCode(color));
vprintf(fmt, args);
printf("\033[m"); // Resets the terminal to default.
va_end(args);
}
// Taken / modified from Googletest
::testing::internal::Int32 Int32FromEnvOrDie(const char* var,
::testing::internal::Int32 default_val) {
using namespace ::testing;
using namespace ::testing::internal;
const char* str_val = getenv(var);
if (str_val == NULL) {
return default_val;
}
Int32 result;
if (!ParseInt32(Message() << "The value of environment variable " << var, str_val, &result)) {
exit(EXIT_FAILURE);
}
return result;
}
// Taken / modified from Googletest
static std::string FormatCountableNoun(int count, const char* singular_form,
const char* plural_form) {
using namespace ::testing;
return internal::StreamableToString(count) + " " + (count == 1 ? singular_form : plural_form);
}
// Taken / modified from Googletest
static std::string FormatTestCount(int test_count) {
return FormatCountableNoun(test_count, "test", "tests");
}
// Taken / modified from Googletest
static std::string FormatTestCaseCount(int test_case_count) {
return FormatCountableNoun(test_case_count, "test case", "test cases");
}
// Taken / modified from Googletest
static const char* TestPartResultTypeToString(::testing::TestPartResult::Type type) {
switch (type) {
case ::testing::TestPartResult::kSuccess:
return "Success";
case ::testing::TestPartResult::kNonFatalFailure:
case ::testing::TestPartResult::kFatalFailure:
#ifdef _MSC_VER
return "error: ";
#else
return "Failure\n";
#endif
default:
return "Unknown result type";
}
}
// Taken / modified from Googletest
bool ShouldShard(const char* total_shards_env, const char* shard_index_env,
bool in_subprocess_for_death_test) {
using namespace ::testing;
using namespace ::testing::internal;
if (in_subprocess_for_death_test) {
return false;
}
const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
if (total_shards == -1 && shard_index == -1) {
return false;
} else if (total_shards == -1 && shard_index != -1) {
const Message msg = Message() << "Invalid environment variables: you have " << kTestShardIndex
<< " = " << shard_index << ", but have left " << kTestTotalShards
<< " unset.\n";
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
} else if (total_shards != -1 && shard_index == -1) {
const Message msg = Message() << "Invalid environment variables: you have " << kTestTotalShards
<< " = " << total_shards << ", but have left " << kTestShardIndex
<< " unset.\n";
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
} else if (shard_index < 0 || shard_index >= total_shards) {
const Message msg =
Message() << "Invalid environment variables: we require 0 <= " << kTestShardIndex << " < "
<< kTestTotalShards << ", but you have " << kTestShardIndex << "=" << shard_index
<< ", " << kTestTotalShards << "=" << total_shards << ".\n";
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
}
return total_shards > 1;
}
// info from TestInfo, which does not have a copy constructor
struct TestInfoProperties {
std::string name;
std::string case_name;
std::string type_param;
std::string value_param;
bool should_run;
std::set<int> ranks;
};
// Holds null terminated strings in a single vector,
// which can be exchanged in a single MPI call
class StringCollection {
public:
void Add(const char* s) {
int size = 0;
for (; *s != '\0'; ++s, ++size) {
text.push_back(*s);
}
text.push_back('\0');
start_indices.push_back(prev_size);
prev_size = size + 1;
}
// Sends content to requested rank
void Send(MPI_Comm comm, int rank) const {
MPI_Send(text.data(), text.size(), MPI_CHAR, rank, 0, comm);
MPI_Send(start_indices.data(), start_indices.size(), MPI_INT, rank, 0, comm);
}
// Overrides content with data from requested rank
void Recv(MPI_Comm comm, int rank) {
MPI_Status status;
int count = 0;
// Recv text
MPI_Probe(rank, 0, comm, &status);
MPI_Get_count(&status, MPI_CHAR, &count);
text.resize(count);
MPI_Recv(text.data(), count, MPI_CHAR, rank, 0, comm, MPI_STATUS_IGNORE);
// Recv sizes
MPI_Probe(rank, 0, comm, &status);
MPI_Get_count(&status, MPI_INT, &count);
start_indices.resize(count);
MPI_Recv(start_indices.data(), count, MPI_INT, rank, 0, comm, MPI_STATUS_IGNORE);
}
void Reset() {
text.clear();
start_indices.clear();
prev_size = 0;
}
const char* get_str(const int id) const { return text.data() + start_indices[id]; }
const std::size_t Size() const { return start_indices.size(); }
private:
int prev_size = 0;
std::vector<char> text;
std::vector<int> start_indices;
};
// All info recuired to print a failed test result.
// Includes functionality for MPI exchange
struct TestPartResultCollection {
// Sends content to requested rank
void Send(MPI_Comm comm, int rank) {
MPI_Send(types.data(), types.size(), MPI_INT, rank, 0, comm);
MPI_Send(line_numbers.data(), line_numbers.size(), MPI_INT, rank, 0, comm);
summaries.Send(comm, rank);
messages.Send(comm, rank);
file_names.Send(comm, rank);
}
// Overrides content with data from requested rank
void Recv(MPI_Comm comm, int rank) {
MPI_Status status;
int count = 0;
// Recv text
MPI_Probe(rank, 0, comm, &status);
MPI_Get_count(&status, MPI_INT, &count);
types.resize(count);
MPI_Recv(types.data(), count, MPI_INT, rank, 0, comm, MPI_STATUS_IGNORE);
// Recv sizes
MPI_Probe(rank, 0, comm, &status);
MPI_Get_count(&status, MPI_INT, &count);
line_numbers.resize(count);
MPI_Recv(line_numbers.data(), count, MPI_INT, rank, 0, comm, MPI_STATUS_IGNORE);
summaries.Recv(comm, rank);
messages.Recv(comm, rank);
file_names.Recv(comm, rank);
}
void Add(const ::testing::TestPartResult& result) {
types.push_back(result.type());
line_numbers.push_back(result.line_number());
summaries.Add(result.summary());
messages.Add(result.message());
file_names.Add(result.file_name());
}
void Reset() {
types.clear();
line_numbers.clear();
summaries.Reset();
messages.Reset();
file_names.Reset();
}
std::size_t Size() const { return types.size(); }
std::vector<int> types;
std::vector<int> line_numbers;
StringCollection summaries;
StringCollection messages;
StringCollection file_names;
};
} // anonymous namespace
} // namespace gtest_mpi
#endif
| 35.934837 | 99 | 0.683917 | teonnik |
7b6932c63e3cfd74c36943631fae9d1aa5f72988 | 330 | cpp | C++ | pointer_example_4.cpp | pervincaliskan/SampleCExamples | c8cfd0076e4fdcfecdd4a1e97c482a506f6cca02 | [
"MIT"
] | 2 | 2019-12-22T18:52:34.000Z | 2021-10-18T18:35:22.000Z | pointer_example_4.cpp | pervincaliskan/SampleCExamples | c8cfd0076e4fdcfecdd4a1e97c482a506f6cca02 | [
"MIT"
] | 1 | 2022-01-18T17:21:26.000Z | 2022-01-18T17:21:26.000Z | pointer_example_4.cpp | pervincaliskan/SampleCExamples | c8cfd0076e4fdcfecdd4a1e97c482a506f6cca02 | [
"MIT"
] | null | null | null | #include<stdio.h>
int main(){
int x = 6;
int *xptr = &x;;
xptr = &x; // xptr gostergesine x adli bellek hucresinin adresi atandi
printf("x'in onceki degeri: %d\n", x);
x = *xptr + 1; // xptr gostergesinin gosterdigi bellek hucresindeki deger 1 artirildi
printf("x'in sonraki degeri: %d\n", x);
return 0;
}
| 17.368421 | 87 | 0.633333 | pervincaliskan |
7b6e7a36c9a59bb7e06980dbed33fca6e4402e9b | 5,391 | cpp | C++ | CodeXL/Components/GpuDebugging/AMDTProcessDebugger/src/pdRemoteProcessDebuggerEventsListenerThread.cpp | jeongjoonyoo/CodeXL | ea6d623d0530aa3a862ef0bf60ad2923a2f8f8a5 | [
"MIT"
] | 1,025 | 2016-04-19T21:36:08.000Z | 2020-04-26T05:12:53.000Z | CodeXL/Components/GpuDebugging/AMDTProcessDebugger/src/pdRemoteProcessDebuggerEventsListenerThread.cpp | jeongjoonyoo/CodeXL | ea6d623d0530aa3a862ef0bf60ad2923a2f8f8a5 | [
"MIT"
] | 244 | 2016-04-20T02:05:43.000Z | 2020-04-29T17:40:49.000Z | CodeXL/Components/GpuDebugging/AMDTProcessDebugger/src/pdRemoteProcessDebuggerEventsListenerThread.cpp | jeongjoonyoo/CodeXL | ea6d623d0530aa3a862ef0bf60ad2923a2f8f8a5 | [
"MIT"
] | 161 | 2016-04-20T03:23:53.000Z | 2020-04-14T01:46:55.000Z | //==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file pdRemoteProcessDebuggerEventsListenerThread.cpp
///
//==================================================================================
//------------------------------ pdRemoteProcessDebuggerEventsListenerThread.cpp ------------------------------
// Infra:
#include <AMDTBaseTools/Include/gtAssert.h>
#include <AMDTBaseTools/Include/gtAutoPtr.h>
#include <AMDTOSWrappers/Include/osChannel.h>
#include <AMDTOSWrappers/Include/osOSDefinitions.h>
#include <AMDTOSWrappers/Include/osTransferableObject.h>
#include <AMDTAPIClasses/Include/Events/apEventsHandler.h>
#include <AMDTAPIClasses/Include/Events/apEvent.h>
// Local:
#include <src/pdRemoteProcessDebuggerEventsListenerThread.h>
#include "osTimeInterval.h"
// Used for reading from the pipe:
static const gtSize_t s_sizeOfInt32 = sizeof(gtInt32);
// ---------------------------------------------------------------------------
// Name: pdRemoteProcessDebuggerEventsListenerThread::pdRemoteProcessDebuggerEventsListenerThread
// Description: Constructor
// Author: Uri Shomroni
// Date: 12/8/2009
// ---------------------------------------------------------------------------
pdRemoteProcessDebuggerEventsListenerThread::pdRemoteProcessDebuggerEventsListenerThread()
: osThread(L"pdRemoteProcessDebuggerEventsListenerThread"), _pEventChannel(NULL), _listeningPaused(true)
{
}
// ---------------------------------------------------------------------------
// Name: pdRemoteProcessDebuggerEventsListenerThread::~pdRemoteProcessDebuggerEventsListenerThread
// Description: Destructor
// Author: Uri Shomroni
// Date: 12/8/2009
// ---------------------------------------------------------------------------
pdRemoteProcessDebuggerEventsListenerThread::~pdRemoteProcessDebuggerEventsListenerThread()
{
beforeTermination();
}
#if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS
#pragma warning(push)
#pragma warning(disable: 4702)
#endif
// ---------------------------------------------------------------------------
// Name: pdRemoteProcessDebuggerEventsListenerThread::entryPoint
// Description: The thread's main loop - reads events from the process debugging
// server and transfers them to the application
// Author: Uri Shomroni
// Date: 12/8/2009
// ---------------------------------------------------------------------------
int pdRemoteProcessDebuggerEventsListenerThread::entryPoint()
{
int retVal = 0;
apEventsHandler& theEventsHandler = apEventsHandler::instance();
while (false == _terminated)
{
// Pause if needed:
osWaitForFlagToTurnOff(_listeningPaused, OS_CHANNEL_INFINITE_TIME_OUT);
if (_pEventChannel != NULL)
{
// Read the event type:
gtInt32 eventTypeAsInt32 = 0;
bool rcRead = _pEventChannel->read((gtByte*)&eventTypeAsInt32, s_sizeOfInt32);
// The above will fail when closing the pipe, so don't assert here:
if (rcRead && _terminated == false)
{
gtAutoPtr<osTransferableObject> aptrEventAsTransferableObject;
*_pEventChannel >> aptrEventAsTransferableObject;
// Make sure we got a transferableObject and it is an event:
GT_IF_WITH_ASSERT(aptrEventAsTransferableObject.pointedObject() != NULL)
{
GT_IF_WITH_ASSERT(aptrEventAsTransferableObject->isEventObject())
{
apEvent* pEve = (apEvent*)aptrEventAsTransferableObject.pointedObject();
// Register the event:
if (pEve != NULL)
{
GT_ASSERT((apEvent::EventType)eventTypeAsInt32 == pEve->eventType());
theEventsHandler.registerPendingDebugEvent(*pEve);
}
}
}
}
else
{
// We failed reading, so wait until we are told to start listening again:
_listeningPaused = true;
}
}
else // _pEventChannel == NULL
{
static bool isFirstTime = true;
if (isFirstTime)
{
// Only report this once, to avoid flooding the log:
isFirstTime = false;
GT_ASSERT(_pEventChannel != NULL);
}
}
}
return retVal;
}
#if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS
#pragma warning(pop)
#endif
// ---------------------------------------------------------------------------
// Name: pdRemoteProcessDebuggerEventsListenerThread::beforeTermination
// Description: Called before the thread is terminated
// Author: Uri Shomroni
// Date: 12/8/2009
// ---------------------------------------------------------------------------
void pdRemoteProcessDebuggerEventsListenerThread::beforeTermination()
{
_terminated = true;
if (_pEventChannel != nullptr)
{
_pEventChannel->setReadOperationTimeOut(0);
}
osTimeInterval timeout;
timeout.setAsMilliSeconds(100);
waitForThreadEnd(timeout);
}
| 36.924658 | 111 | 0.549063 | jeongjoonyoo |
7b6fd00fc4e231f30de15845796fba40b79f97b5 | 776 | hpp | C++ | src/home_screen.hpp | tomfleet/M5PaperUI | cad8ccbbdf2273865eb9cbec70f41f87eca3fadd | [
"Apache-2.0"
] | 24 | 2021-02-25T21:17:22.000Z | 2022-03-01T19:01:13.000Z | src/home_screen.hpp | sthagen/M5PaperUI | 05025433054d4e59ce8ec01eecbe44ac074b08ec | [
"Apache-2.0"
] | null | null | null | src/home_screen.hpp | sthagen/M5PaperUI | 05025433054d4e59ce8ec01eecbe44ac074b08ec | [
"Apache-2.0"
] | 10 | 2021-02-27T21:26:46.000Z | 2022-03-13T12:59:40.000Z | #pragma once
#include <memory>
#include "widgetlib.hpp"
class HomeScreen : public Frame {
public:
using ptr_t = std::shared_ptr<HomeScreen>;
HomeScreen(int16_t x, int16_t y, int16_t w, int16_t h);
static ptr_t Create(int16_t x, int16_t y, int16_t w, int16_t h) {
return std::make_shared<HomeScreen>(x, y, w, h);
}
/// Initializes all views that have been added to the frame.
void Init(WidgetContext *) override;
void Prepare(WidgetContext *) override;
ScreenUpdateMode Draw() override;
private:
void CreateAppButton(int16_t x, int16_t y, const std::string &name,
const uint8_t *icon, WButton::handler_fun_t fun);
WIconButton::ptr_t paint_button_;
WIconButton::ptr_t settings_button_;
bool hs_initialized_ = false;
}; | 25.866667 | 72 | 0.710052 | tomfleet |
7b700b53e635d656f15d42b7debe701c25e636ab | 4,975 | cpp | C++ | FS_Utils.cpp | Lynnvon/UnrealUtils | 2fe3b00ad8e0518a47a7f6415ebabe381923b74d | [
"MIT"
] | 1 | 2020-05-19T08:40:40.000Z | 2020-05-19T08:40:40.000Z | FS_Utils.cpp | Lynnvon/UnrealUtils | 2fe3b00ad8e0518a47a7f6415ebabe381923b74d | [
"MIT"
] | null | null | null | FS_Utils.cpp | Lynnvon/UnrealUtils | 2fe3b00ad8e0518a47a7f6415ebabe381923b74d | [
"MIT"
] | 1 | 2020-05-19T08:40:44.000Z | 2020-05-19T08:40:44.000Z | // Copyright Shinban.Inc
/*!
* file FS_Utils.cpp
*
* author Hailiang Feng
* date 2019/09/06 12:09
*
*
*/
#include "FS_Utils.h"
#include "Kismet/KismetMathLibrary.h"
#include "FlightSim.h"
#include "Engine/Texture2D.h"
//~~~ Image Wrapper ~~~
#include "ImageUtils.h"
#include "IImageWrapper.h"
#include "IImageWrapperModule.h"
//~~~ Image Wrapper ~~~
EVisualHelmetDirection UFS_Utils::GetAxisHelmetDirection(float Val)
{
static bool bDone = false;
EVisualHelmetDirection dir = EVisualHelmetDirection::None;
if (Val <= 1 && Val>0)
{
if (bDone) return dir;
bDone = true;
if (UKismetMathLibrary::InRange_FloatFloat(Val,0.0f,0.37f,false,false))
{
dir = EVisualHelmetDirection::Right;
}else if (UKismetMathLibrary::InRange_FloatFloat(Val,0.37f,0.74f,false,false))
{
dir = EVisualHelmetDirection::Down;
}else if(UKismetMathLibrary::InRange_FloatFloat(Val,0.74f,0.99f,false,false))
{
dir = EVisualHelmetDirection::Left;
}
else
{
dir = EVisualHelmetDirection::Up;
}
}
else
{
if (bDone)
{
dir = EVisualHelmetDirection::Origin;
}
bDone = false;
}
return dir;
}
FVector UFS_Utils::GetVectorBetweenTwoPointByAlpha(const FVector& Start,const FVector& End,const FVector& alpha)
{
float _dis = FVector::Distance(Start,End);
FVector _unitVector = GetUnitVector(Start,End);
FVector returnVal = FVector(_unitVector.X* _dis * alpha.X,_unitVector.Y * _dis * alpha.Y,_unitVector.Z * _dis * alpha.Z) + Start;
return returnVal;
}
FVector UFS_Utils::GetVectorBetweenTwoPointByAlpha(const FVector& Start, const FVector& End, float alpha)
{
float _dis = FVector::Distance(Start,End);
FVector _unitVector = GetUnitVector(Start,End);
FVector returnVal = FVector(_unitVector.X* _dis * alpha,_unitVector.Y * _dis * alpha,_unitVector.Z * _dis * alpha) + Start;
return returnVal;
}
FVector UFS_Utils::GetVectorWithCurve(const FVector& target, const FVector& curve)
{
return FVector(target.X*curve.X,target.Y*curve.Y,target.Z*curve.Z);
}
FRotator UFS_Utils::GetRotatorBetweenTwoAngleByAlpha(const FRotator& Start,const FRotator& End,const FVector& alpha)
{
FRotator returnVal = FMath::Lerp(Start,End,alpha.X);
return returnVal;
}
FRotator UFS_Utils::GetRotatorBetweenTwoAngleByAlpha(const FRotator& Start, const FRotator& End, float alpha)
{
FRotator returnVal = FMath::Lerp(Start,End,alpha);
return returnVal;
}
FVector UFS_Utils::GetUnitVector(const FVector& Start,const FVector& End)
{
return (End - Start ).GetSafeNormal();
}
FRotator UFS_Utils::FindLookAtRotation(const FVector& Start, const FVector& Target)
{
return MakeRotFromX(Target - Start);
}
FRotator UFS_Utils::MakeRotFromX(const FVector& X)
{
return FRotationMatrix::MakeFromX(X).Rotator();
}
float UFS_Utils::GetVectorLength(FVector _vector)
{
return _vector.Size();
}
FVector UFS_Utils::RotateVectorAroundAxis(FVector InVector, float Angle, FVector Axis)
{
return InVector.RotateAngleAxis(Angle,Axis);
}
void UFS_Utils::SetRelativeLocationSmooth(USceneComponent* target, FVector newLocation,float Delta, float Speed)
{
FVector TargetLocation = FMath::VInterpTo(target->RelativeLocation,newLocation,Delta,Speed);
target->SetRelativeLocation(TargetLocation);
}
UTexture2D* UFS_Utils::LoadTexture2D_FromFile(const FString& FullFilePath, EImageFormat ImageFormat, bool& IsValid, int32& Width, int32& Height)
{
IsValid = false;
UTexture2D* LoadedT2D = NULL;
IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule.CreateImageWrapper(ImageFormat);
//Load From File
TArray<uint8> RawFileData;
if (!FFileHelper::LoadFileToArray(RawFileData, *FullFilePath)) return NULL;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//Create T2D!
if (ImageWrapper.IsValid() && ImageWrapper->SetCompressed(RawFileData.GetData(), RawFileData.Num()))
{
const TArray<uint8>* UncompressedBGRA = NULL;
if (ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, UncompressedBGRA))
{
LoadedT2D = UTexture2D::CreateTransient(ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), PF_B8G8R8A8);
//Valid?
if(!LoadedT2D) return NULL;
//~~~~~~~~~~~~~~
//Out!
Width = ImageWrapper->GetWidth();
Height = ImageWrapper->GetHeight();
//Copy!
void* TextureData = LoadedT2D->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE);
FMemory::Memcpy(TextureData, UncompressedBGRA->GetData(), UncompressedBGRA->Num());
LoadedT2D->PlatformData->Mips[0].BulkData.Unlock();
//Update!
LoadedT2D->UpdateResource();
}
}
// Success!
IsValid = true;
return LoadedT2D;
}
FString UFS_Utils::GetTerrainConfigSection(FString section)
{
FString val;
if (!GConfig) return FString();
FString RegistrySection = "Terrain";
bool isSuccess = GConfig->GetString(
*RegistrySection,
(TEXT("%s"), *section),
val,
GGameIni
);
if (isSuccess)
{
return val;
}
return FString();
}
| 25.911458 | 144 | 0.728643 | Lynnvon |
7b700c00727d150f04e51eb299d09928f2e68b71 | 2,185 | cc | C++ | ecs/src/model/DescribeBandwidthLimitationResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | ecs/src/model/DescribeBandwidthLimitationResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | ecs/src/model/DescribeBandwidthLimitationResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/ecs/model/DescribeBandwidthLimitationResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ecs;
using namespace AlibabaCloud::Ecs::Model;
DescribeBandwidthLimitationResult::DescribeBandwidthLimitationResult() :
ServiceResult()
{}
DescribeBandwidthLimitationResult::DescribeBandwidthLimitationResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeBandwidthLimitationResult::~DescribeBandwidthLimitationResult()
{}
void DescribeBandwidthLimitationResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allBandwidthsNode = value["Bandwidths"]["Bandwidth"];
for (auto valueBandwidthsBandwidth : allBandwidthsNode)
{
Bandwidth bandwidthsObject;
if(!valueBandwidthsBandwidth["InternetChargeType"].isNull())
bandwidthsObject.internetChargeType = valueBandwidthsBandwidth["InternetChargeType"].asString();
if(!valueBandwidthsBandwidth["Max"].isNull())
bandwidthsObject.max = std::stoi(valueBandwidthsBandwidth["Max"].asString());
if(!valueBandwidthsBandwidth["Min"].isNull())
bandwidthsObject.min = std::stoi(valueBandwidthsBandwidth["Min"].asString());
if(!valueBandwidthsBandwidth["Unit"].isNull())
bandwidthsObject.unit = valueBandwidthsBandwidth["Unit"].asString();
bandwidths_.push_back(bandwidthsObject);
}
}
std::vector<DescribeBandwidthLimitationResult::Bandwidth> DescribeBandwidthLimitationResult::getBandwidths()const
{
return bandwidths_;
}
| 34.140625 | 113 | 0.778032 | aliyun |
7b72a3fcfc5eb6d9f1efd70ac1028c7117a6d729 | 1,994 | cpp | C++ | src/gmail/drafts/DraftsDraftResource.cpp | Vadimatorik/googleQt | 814ad6f695bb8e88d6a773e69fb8c188febaab00 | [
"MIT"
] | 24 | 2016-12-03T09:12:43.000Z | 2022-03-29T19:51:48.000Z | src/gmail/drafts/DraftsDraftResource.cpp | Vadimatorik/googleQt | 814ad6f695bb8e88d6a773e69fb8c188febaab00 | [
"MIT"
] | 4 | 2016-12-03T09:14:42.000Z | 2022-03-29T22:02:21.000Z | src/gmail/drafts/DraftsDraftResource.cpp | Vadimatorik/googleQt | 814ad6f695bb8e88d6a773e69fb8c188febaab00 | [
"MIT"
] | 7 | 2018-01-01T09:14:10.000Z | 2022-03-29T21:50:11.000Z | /**********************************************************
DO NOT EDIT
This file was generated from stone specification "drafts"
Part of "Ardi - the organizer" project.
osoft4ardi@gmail.com
www.prokarpaty.net
***********************************************************/
#include "gmail/drafts/DraftsDraftResource.h"
using namespace googleQt;
namespace googleQt{
namespace drafts{
///DraftResource
DraftResource::operator QJsonObject()const{
QJsonObject js;
this->toJson(js);
return js;
}
void DraftResource::toJson(QJsonObject& js)const{
if(!m_id.isEmpty())
js["id"] = QString(m_id);
js["message"] = (QJsonObject)m_message;
}
void DraftResource::fromJson(const QJsonObject& js){
m_id = js["id"].toString();
m_message.fromJson(js["message"].toObject());
}
QString DraftResource::toString(bool multiline)const
{
QJsonObject js;
toJson(js);
QJsonDocument doc(js);
QString s(doc.toJson(multiline ? QJsonDocument::Indented : QJsonDocument::Compact));
return s;
}
std::unique_ptr<DraftResource> DraftResource::factory::create(const QByteArray& data)
{
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonObject js = doc.object();
return create(js);
}
std::unique_ptr<DraftResource> DraftResource::factory::create(const QJsonObject& js)
{
std::unique_ptr<DraftResource> rv;
rv = std::unique_ptr<DraftResource>(new DraftResource);
rv->fromJson(js);
return rv;
}
#ifdef API_QT_AUTOTEST
std::unique_ptr<DraftResource> DraftResource::EXAMPLE(int context_index, int parent_context_index){
Q_UNUSED(context_index);
Q_UNUSED(parent_context_index);
static int example_idx = 0;
example_idx++;
std::unique_ptr<DraftResource> rv(new DraftResource);
rv->m_id = ApiAutotest::INSTANCE().getId("drafts::DraftResource", example_idx);
rv->m_message = *(messages::MessageResource::EXAMPLE(0, context_index).get());
return rv;
}
#endif //API_QT_AUTOTEST
}//drafts
}//googleQt
| 25.564103 | 99 | 0.674524 | Vadimatorik |
7b743bec1c240137fcf927b0b1bb703d3dd22fc7 | 3,320 | cpp | C++ | main.cpp | SirJonthe/VoxelRayTrace | 1c38a522e9734fcbac1ceb9c85c475a6c4709103 | [
"Zlib"
] | 26 | 2015-03-25T21:31:01.000Z | 2021-11-09T11:40:45.000Z | main.cpp | SirJonthe/VoxelRayTrace | 1c38a522e9734fcbac1ceb9c85c475a6c4709103 | [
"Zlib"
] | 1 | 2018-11-23T03:52:38.000Z | 2018-11-24T10:39:05.000Z | main.cpp | SirJonthe/VoxelRayTrace | 1c38a522e9734fcbac1ceb9c85c475a6c4709103 | [
"Zlib"
] | null | null | null | #include <iostream>
//#include <omp.h>
#include "PlatformSDL.h"
#include "Camera.h"
#include "Renderer.h"
#include "RobotModel.h"
#include "Math3d.h"
// Rudimentary OpenMP support is commented out
// see main(...) and Renderer::Render(...)
// see included header files in main.cpp and Renderer.cpp
int main(int argc, char **argv)
{
if (SDL_Init(SDL_INIT_VIDEO) == -1) {
std::cout << "Could not init SDL" << std::endl;
return 1;
}
//omp_set_num_threads(omp_get_num_procs);
int w = 800;
int h = 600;
bool fs = false;
if (argc > 1 && (argc-1)%2 == 0) {
for (int i = 1; i < argc; i+=2) {
if (strcmp(argv[i], "-w") == 0) {
w = atoi(argv[i+1]);
std::cout << "width set to " << w << " from argument " << argv[i+1] << std::endl;
} else if (strcmp(argv[i], "-h") == 0) {
h = atoi(argv[i+1]);
std::cout << "height set to " << h << " from argument " << argv[i+1] << std::endl;
} else if (strcmp(argv[i], "-fs") == 0) {
fs = bool( atoi(argv[i+1]) );
std::cout << "fullscreen set to " << fs << " from argument " << argv[i+1] << std::endl;
} else {
std::cout << "Unknown argument: " << argv[i] << std::endl;
}
}
}
Renderer renderer;
if (!renderer.Init(w, h, fs)) {
std::cout << "Could not init video mode" << std::endl;
SDL_Quit();
return 1;
}
SDL_WM_SetCaption("Voxel Ray Tracing", NULL);
SDL_WM_GrabInput(SDL_GRAB_ON);
SDL_ShowCursor(SDL_FALSE);
std::cout << "Total voxel volume: " << sizeof(Robot) << ", in bytes " << sizeof(Robot)*sizeof(Voxel) << std::endl;
SDL_Event event;
Camera camera(w, h);
camera.SetPosition(vec3_t(8.f, 8.f, 8.f));
bool quit = false;
float left = 0.f;
float right = 0.f;
float forward = 0.f;
float backward = 0.f;
float up = 0.f;
float down = 0.f;
while (!quit) {
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_w:
forward = 1.f;
break;
case SDLK_a:
left = 1.f;
break;
case SDLK_s:
backward = -1.f;
break;
case SDLK_d:
right = -1.f;
break;
case SDLK_q:
down = 1.f;
break;
case SDLK_e:
up = -1.f;
break;
case SDLK_ESCAPE:
quit = true;
break;
default: break;
}
break;
case SDL_QUIT:
quit = true;
break;
case SDL_KEYUP:
switch (event.key.keysym.sym) {
case SDLK_w:
forward = 0.f;
break;
case SDLK_a:
left = 0.f;
break;
case SDLK_s:
backward = 0.f;
break;
case SDLK_d:
right = 0.f;
break;
case SDLK_q:
down = 0.f;
break;
case SDLK_e:
up = 0.f;
break;
default: break;
}
break;
case SDL_MOUSEMOTION:
camera.Turn(-event.motion.xrel * 0.01f, 0.f);
break;
default: break;
}
}
const vec3_t prevCam = camera.GetPosition();
camera.Move(forward + backward, left + right, down + up);
for (int i = 0; i < 3; ++i) {
if (camera.GetPosition()[i] < 0 || camera.GetPosition()[i] >= 16) {
camera.SetPosition(prevCam);
break;
}
}
renderer.Render(camera, Robot, RobotDim);
renderer.Refresh();
}
renderer.CleanUp();
SDL_Quit();
return 0;
}
| 23.055556 | 116 | 0.544578 | SirJonthe |
7b79b4b70bf0f69e576097119703a7b5d8632ca7 | 2,274 | cpp | C++ | common/src/filters/out_buf.cpp | ane-community/botan-crypto-ane | 71056f5f0d5fd706e6d42e2f7ec0f7f55d86fb74 | [
"MIT"
] | 1 | 2018-03-09T20:21:47.000Z | 2018-03-09T20:21:47.000Z | common/src/filters/out_buf.cpp | ane-community/botan-crypto-ane | 71056f5f0d5fd706e6d42e2f7ec0f7f55d86fb74 | [
"MIT"
] | null | null | null | common/src/filters/out_buf.cpp | ane-community/botan-crypto-ane | 71056f5f0d5fd706e6d42e2f7ec0f7f55d86fb74 | [
"MIT"
] | 1 | 2020-03-05T23:42:00.000Z | 2020-03-05T23:42:00.000Z | /*
* Pipe Output Buffer
* (C) 1999-2007,2011 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/internal/out_buf.h>
#include <botan/secqueue.h>
#include <botan/internal/assert.h>
namespace Botan {
/*
* Read data from a message
*/
size_t Output_Buffers::read(byte output[], size_t length,
Pipe::message_id msg)
{
SecureQueue* q = get(msg);
if(q)
return q->read(output, length);
return 0;
}
/*
* Peek at data in a message
*/
size_t Output_Buffers::peek(byte output[], size_t length,
size_t stream_offset,
Pipe::message_id msg) const
{
SecureQueue* q = get(msg);
if(q)
return q->peek(output, length, stream_offset);
return 0;
}
/*
* Check available bytes in a message
*/
size_t Output_Buffers::remaining(Pipe::message_id msg) const
{
SecureQueue* q = get(msg);
if(q)
return q->size();
return 0;
}
/*
* Add a new output queue
*/
void Output_Buffers::add(SecureQueue* queue)
{
BOTAN_ASSERT(queue, "argument was NULL");
BOTAN_ASSERT(buffers.size() < buffers.max_size(),
"No more room in container");
buffers.push_back(queue);
}
/*
* Retire old output queues
*/
void Output_Buffers::retire()
{
for(size_t i = 0; i != buffers.size(); ++i)
if(buffers[i] && buffers[i]->size() == 0)
{
delete buffers[i];
buffers[i] = 0;
}
while(buffers.size() && !buffers[0])
{
buffers.pop_front();
offset = offset + Pipe::message_id(1);
}
}
/*
* Get a particular output queue
*/
SecureQueue* Output_Buffers::get(Pipe::message_id msg) const
{
if(msg < offset)
return 0;
BOTAN_ASSERT(msg < message_count(),
"Message number out of range");
return buffers[msg-offset];
}
/*
* Return the total number of messages
*/
Pipe::message_id Output_Buffers::message_count() const
{
return (offset + buffers.size());
}
/*
* Output_Buffers Constructor
*/
Output_Buffers::Output_Buffers()
{
offset = 0;
}
/*
* Output_Buffers Destructor
*/
Output_Buffers::~Output_Buffers()
{
for(size_t j = 0; j != buffers.size(); ++j)
delete buffers[j];
}
}
| 18.639344 | 60 | 0.596746 | ane-community |
7b7c1d1d50cd6094dd5bbff7146f6066a85d1f89 | 19,483 | cc | C++ | engine/gamma/index/gpu/gamma_index_ivfpq_gpu.cc | qbzenker/vearch | 34bcd53cf90d6bedc0582602b8282b65d21eaa9e | [
"Apache-2.0"
] | 1 | 2020-03-25T10:30:55.000Z | 2020-03-25T10:30:55.000Z | engine/gamma/index/gpu/gamma_index_ivfpq_gpu.cc | qbzenker/vearch | 34bcd53cf90d6bedc0582602b8282b65d21eaa9e | [
"Apache-2.0"
] | null | null | null | engine/gamma/index/gpu/gamma_index_ivfpq_gpu.cc | qbzenker/vearch | 34bcd53cf90d6bedc0582602b8282b65d21eaa9e | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2019 The Gamma Authors.
*
* This source code is licensed under the Apache License, Version 2.0 license
* found in the LICENSE file in the root directory of this source tree.
*/
#include "gamma_index_ivfpq_gpu.h"
#include <faiss/IndexFlat.h>
#include <faiss/gpu/GpuAutoTune.h>
#include <faiss/gpu/GpuCloner.h>
#include <faiss/gpu/GpuClonerOptions.h>
#include <faiss/gpu/StandardGpuResources.h>
#include <faiss/gpu/utils/DeviceUtils.h>
#include <faiss/utils/Heap.h>
#include <faiss/utils/utils.h>
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <fstream>
#include <mutex>
#include <set>
#include <vector>
#include "bitmap.h"
#include "gamma_index_ivfpq.h"
using std::string;
using std::vector;
namespace tig_gamma {
namespace gamma_gpu {
namespace {
const int kMaxBatch = 200; // max search batch num
const int kMaxRecallNum = 1024; // max recall num
const int kMaxReqNum = 200;
} // namespace
template <typename T>
class BlockingQueue {
public:
BlockingQueue() : mutex_(), condvar_(), queue_() {}
void Put(const T &task) {
{
std::lock_guard<std::mutex> lock(mutex_);
queue_.push_back(task);
}
condvar_.notify_all();
}
T Take() {
std::unique_lock<std::mutex> lock(mutex_);
condvar_.wait(lock, [this] { return !queue_.empty(); });
assert(!queue_.empty());
T front(queue_.front());
queue_.pop_front();
return front;
}
T TakeBatch(vector<T> &vec, int &n) {
std::unique_lock<std::mutex> lock(mutex_);
condvar_.wait(lock, [this] { return !queue_.empty(); });
assert(!queue_.empty());
int i = 0;
while (!queue_.empty() && i < kMaxBatch) {
T front(queue_.front());
queue_.pop_front();
vec[i++] = front;
}
n = i;
return nullptr;
}
size_t Size() const {
std::lock_guard<std::mutex> lock(mutex_);
return queue_.size();
}
private:
BlockingQueue(const BlockingQueue &);
BlockingQueue &operator=(const BlockingQueue &);
private:
mutable std::mutex mutex_;
std::condition_variable condvar_;
std::list<T> queue_;
};
class GPUItem {
public:
GPUItem(int n, const float *x, int k, float *dis, long *label) : x_(x) {
n_ = n;
k_ = k;
dis_ = dis;
label_ = label;
done_ = false;
}
void Notify() {
done_ = true;
cv_.notify_one();
}
int WaitForDone() {
std::unique_lock<std::mutex> lck(mtx_);
while (not done_) {
cv_.wait_for(lck, std::chrono::seconds(1),
[this]() -> bool { return done_; });
}
return 0;
}
int n_;
const float *x_;
float *dis_;
int k_;
long *label_;
int batch_size; // for perfomance test
private:
std::condition_variable cv_;
std::mutex mtx_;
bool done_;
};
GammaIVFPQGPUIndex::GammaIVFPQGPUIndex(size_t d, size_t nlist, size_t M,
size_t nbits_per_idx,
const char *docids_bitmap,
RawVector *raw_vec, int nprobe)
: GammaIndex(d, docids_bitmap, raw_vec) {
this->nlist_ = nlist;
this->M_ = M;
this->nbits_per_idx_ = nbits_per_idx;
this->nprobe_ = nprobe;
indexed_vec_count_ = 0;
search_idx_ = 0;
cur_qid_ = 0;
b_exited_ = false;
use_standard_resource_ = true;
is_indexed_ = false;
#ifdef PERFORMANCE_TESTING
search_count_ = 0;
#endif
}
GammaIVFPQGPUIndex::~GammaIVFPQGPUIndex() {
b_exited_ = true;
std::this_thread::sleep_for(std::chrono::seconds(2));
delete gpu_index_;
}
faiss::Index *GammaIVFPQGPUIndex::CreateGPUIndex(faiss::Index *cpu_index) {
int ngpus = faiss::gpu::getNumDevices();
vector<int> gpus;
for (int i = 0; i < ngpus; ++i) {
gpus.push_back(i);
}
if (use_standard_resource_) {
id_queues_.push_back(
new moodycamel::BlockingConcurrentQueue<GPUItem *>); // only use one
// queue
} else {
GammaMemManager manager;
tmp_mem_num_ = manager.Init(ngpus);
LOG(INFO) << "Resource num [" << tmp_mem_num_ << "]";
for (int i = 0; i < tmp_mem_num_; ++i) {
id_queues_.push_back(new moodycamel::BlockingConcurrentQueue<GPUItem *>);
}
}
vector<int> devs;
for (int i : gpus) {
if (use_standard_resource_) {
auto res = new faiss::gpu::StandardGpuResources;
res->initializeForDevice(i);
res->setTempMemory((size_t)1536 * 1024 * 1024); // 1.5 GiB
resources_.push_back(res);
} else {
auto res = new faiss::gpu::GammaGpuResources;
res->initializeForDevice(i);
resources_.push_back(res);
}
devs.push_back(i);
}
faiss::gpu::GpuMultipleClonerOptions *options =
new faiss::gpu::GpuMultipleClonerOptions();
options->indicesOptions = faiss::gpu::INDICES_32_BIT;
options->useFloat16CoarseQuantizer = false;
options->useFloat16 = true;
options->usePrecomputed = false;
options->reserveVecs = 0;
options->storeTransposed = true;
options->verbose = true;
// shard the index across GPUs
options->shard = true;
options->shard_type = 1;
faiss::Index *gpu_index = faiss::gpu::index_cpu_to_gpu_multiple(
resources_, devs, cpu_index, options);
return gpu_index;
}
int GammaIVFPQGPUIndex::CreateSearchThread() {
auto func_search =
std::bind(&GammaIVFPQGPUIndex::GPUThread, this, std::placeholders::_1);
if (use_standard_resource_) {
gpu_threads_.push_back(std::thread(func_search, id_queues_[0]));
gpu_threads_[0].detach();
} else {
for (int i = 0; i < tmp_mem_num_; ++i) {
gpu_threads_.push_back(std::thread(func_search, id_queues_[i]));
}
for (int i = 0; i < tmp_mem_num_; ++i) {
gpu_threads_[i].detach();
}
}
return 0;
}
int GammaIVFPQGPUIndex::Indexing() {
int vectors_count = raw_vec_->GetVectorNum();
if (vectors_count < 8192) {
LOG(ERROR) << "vector total count [" << vectors_count
<< "] less then 8192, failed!";
return -1;
}
if (is_indexed_) {
while (indexed_vec_count_ < vectors_count) {
AddRTVecsToIndex();
}
// dump index
{
faiss::Index *cpu_index = faiss::gpu::index_gpu_to_cpu(gpu_index_);
string file_name = "gpu.index";
faiss::write_index(cpu_index, file_name.c_str());
LOG(INFO) << "GPUIndex dump successed!";
}
return 0;
}
faiss::IndexFlatL2 *quantizer = new faiss::IndexFlatL2(d_);
faiss::IndexIVFPQ *cpu_index =
new faiss::IndexIVFPQ(quantizer, d_, nlist_, M_, nbits_per_idx_);
cpu_index->nprobe = nprobe_;
gpu_index_ = CreateGPUIndex(dynamic_cast<faiss::Index *>(cpu_index));
// gpu_index_->train(num, scope_vec.Get());
std::vector<std::thread> workers;
workers.push_back(std::thread([&]() {
int num = vectors_count > 100000 ? 100000 : vectors_count;
ScopeVector scope_vec;
raw_vec_->GetVectorHeader(0, num, scope_vec);
LOG(INFO) << num;
gpu_index_->train(num, scope_vec.Get());
}));
std::for_each(workers.begin(), workers.end(),
[](std::thread &t) { t.join(); });
LOG(INFO) << "Index GPU successed!";
while (indexed_vec_count_ < vectors_count) {
AddRTVecsToIndex();
}
// dump index
{
faiss::Index *cpu_index = faiss::gpu::index_gpu_to_cpu(gpu_index_);
string file_name = "gpu.index";
faiss::write_index(cpu_index, file_name.c_str());
LOG(INFO) << "GPUIndex dump successed!";
}
CreateSearchThread();
is_indexed_ = true;
return 0;
}
int GammaIVFPQGPUIndex::AddRTVecsToIndex() {
int ret = 0;
int total_stored_vecs = raw_vec_->GetVectorNum();
if (indexed_vec_count_ > total_stored_vecs) {
LOG(ERROR) << "internal error : indexed_vec_count should not greater than "
"total_stored_vecs!";
ret = -1;
} else if (indexed_vec_count_ == total_stored_vecs) {
;
#ifdef DEBUG_
LOG(INFO) << "no extra vectors existed for indexing";
#endif
} else {
int MAX_NUM_PER_INDEX = 20480;
int index_count =
(total_stored_vecs - indexed_vec_count_) / MAX_NUM_PER_INDEX + 1;
for (int i = 0; i < index_count; ++i) {
int start_docid = indexed_vec_count_;
int count_per_index =
(i == (index_count - 1) ? total_stored_vecs - start_docid
: MAX_NUM_PER_INDEX);
ScopeVector vector_head;
raw_vec_->GetVectorHeader(indexed_vec_count_,
indexed_vec_count_ + count_per_index,
vector_head);
if (!Add(count_per_index, vector_head.Get())) {
LOG(ERROR) << "add index from docid " << start_docid << " error!";
ret = -2;
}
}
}
return ret;
}
bool GammaIVFPQGPUIndex::Add(int n, const float *vec) {
// gpu_index_->add(n, vec);
std::vector<std::thread> workers;
workers.push_back(std::thread([&]() { gpu_index_->add(n, vec); }));
std::for_each(workers.begin(), workers.end(),
[](std::thread &t) { t.join(); });
indexed_vec_count_ += n;
LOG(INFO) << "Indexed vec count [" << indexed_vec_count_ << "]";
return true;
}
int GammaIVFPQGPUIndex::Search(const VectorQuery *query,
const GammaSearchCondition *condition,
VectorResult &result) {
if (gpu_threads_.size() == 0) {
LOG(ERROR) << "gpu index not indexed!";
return -1;
}
float *xq = reinterpret_cast<float *>(query->value->value);
int n = query->value->len / (d_ * sizeof(float));
if (n > kMaxReqNum) {
LOG(ERROR) << "req num [" << n << "] should not larger than [" << kMaxReqNum
<< "]";
return -1;
}
std::stringstream perf_ss;
#ifdef PERFORMANCE_TESTING
double start = utils::getmillisecs();
#endif
GPUSearch(n, xq, condition->topn, result.dists, result.docids, condition,
perf_ss);
#ifdef PERFORMANCE_TESTING
double gpu_search_end = utils::getmillisecs();
#endif
for (int i = 0; i < n; i++) {
int pos = 0;
std::map<int, int> docid2count;
for (int j = 0; j < condition->topn; j++) {
long *docid = result.docids + i * condition->topn + j;
if (docid[0] == -1) continue;
int vector_id = (int)docid[0];
int real_docid = this->raw_vec_->vid2docid_[vector_id];
if (docid2count.find(real_docid) == docid2count.end()) {
int real_pos = i * condition->topn + pos;
result.docids[real_pos] = real_docid;
int ret = this->raw_vec_->GetSource(vector_id, result.sources[real_pos],
result.source_lens[real_pos]);
if (ret != 0) {
result.sources[real_pos] = nullptr;
result.source_lens[real_pos] = 0;
}
result.dists[real_pos] = result.dists[i * condition->topn + j];
pos++;
docid2count[real_docid] = 1;
}
}
if (pos > 0) {
result.idx[i] = 0; // init start id of seeking
}
for (; pos < condition->topn; pos++) {
result.docids[i * condition->topn + pos] = -1;
result.dists[i * condition->topn + pos] = -1;
}
}
#ifdef PERFORMANCE_TESTING
double end = utils::getmillisecs();
perf_ss << "reorder cost [" << end - gpu_search_end << "]ms, "
<< "total cost [" << end - start << "]ms ";
LOG(INFO) << perf_ss.str();
#endif
return 0;
}
long GammaIVFPQGPUIndex::GetTotalMemBytes() { return 0; }
int GammaIVFPQGPUIndex::Dump(const string &dir, int max_vid) {
// faiss::Index *cpu_index = faiss::gpu::index_gpu_to_cpu(gpu_index_);
// string file_name = dir + "/gpu.index";
// faiss::write_index(cpu_index, file_name.c_str());
return 0;
}
int GammaIVFPQGPUIndex::Load(const vector<string> &index_dirs) {
// string file_name = index_dirs[index_dirs.size() - 1] + "/gpu.index";
string file_name = "gpu.index";
faiss::Index *cpu_index = faiss::read_index(file_name.c_str());
gpu_index_ = CreateGPUIndex(cpu_index);
indexed_vec_count_ = gpu_index_->ntotal;
is_indexed_ = true;
LOG(INFO) << "GPUIndex load successed, num [" << indexed_vec_count_ << "]";
CreateSearchThread();
return 0;
}
int GammaIVFPQGPUIndex::GPUThread(
moodycamel::BlockingConcurrentQueue<GPUItem *> *items_q) {
GammaMemManager manager;
std::thread::id tid = std::this_thread::get_id();
float *xx = new float[kMaxBatch * d_ * kMaxReqNum];
long *label = new long[kMaxBatch * kMaxRecallNum * kMaxReqNum];
float *dis = new float[kMaxBatch * kMaxRecallNum * kMaxReqNum];
while (not b_exited_) {
int size = 0;
GPUItem *items[kMaxBatch];
while (size == 0 && not b_exited_) {
size = items_q->wait_dequeue_bulk_timed(items, kMaxBatch, 1000);
}
if (size > 1) {
int max_recallnum = 0;
int cur = 0, total = 0;
for (int i = 0; i < size; ++i) {
max_recallnum = std::max(max_recallnum, items[i]->k_);
total += items[i]->n_;
memcpy(xx + cur, items[i]->x_, d_ * sizeof(float) * items[i]->n_);
cur += d_ * items[i]->n_;
}
gpu_index_->search(total, xx, max_recallnum, dis, label);
cur = 0;
for (int i = 0; i < size; ++i) {
memcpy(items[i]->dis_, dis + cur,
max_recallnum * sizeof(float) * items[i]->n_);
memcpy(items[i]->label_, label + cur,
max_recallnum * sizeof(long) * items[i]->n_);
items[i]->batch_size = size;
cur += max_recallnum * items[i]->n_;
items[i]->Notify();
}
} else if (size == 1) {
gpu_index_->search(items[0]->n_, items[0]->x_, items[0]->k_,
items[0]->dis_, items[0]->label_);
items[0]->batch_size = size;
items[0]->Notify();
}
if (not use_standard_resource_) {
manager.ReturnMem(tid);
}
}
delete xx;
delete label;
delete dis;
LOG(INFO) << "thread exit";
return 0;
}
int GammaIVFPQGPUIndex::GPUSearch(int n, const float *x, int k,
float *distances, long *labels,
const GammaSearchCondition *condition,
std::stringstream &perf_ss) {
auto recall_num = condition->recall_num;
if (recall_num > kMaxRecallNum) {
LOG(WARNING) << "recall_num should less than [" << kMaxRecallNum << "]";
recall_num = kMaxRecallNum;
}
vector<float> D(n * kMaxRecallNum);
vector<long> I(n * kMaxRecallNum);
double start = utils::getmillisecs();
GPUItem *item = new GPUItem(n, x, recall_num, D.data(), I.data());
if (use_standard_resource_) {
id_queues_[0]->enqueue(item);
} else {
int cur = ++cur_qid_;
if (cur >= tmp_mem_num_) {
cur = 0;
cur_qid_ = 0;
}
id_queues_[cur]->enqueue(item);
}
item->WaitForDone();
int batch_size = item->batch_size;
delete item;
double end1 = utils::getmillisecs();
// set filter
auto is_filterable = [this, condition](long docid) -> bool {
auto *num = condition->range_query_result;
return bitmap::test(docids_bitmap_, docid) || (num && not num->Has(docid));
};
using HeapForIP = faiss::CMin<float, idx_t>;
using HeapForL2 = faiss::CMax<float, idx_t>;
auto init_result = [&](int topk, float *simi, idx_t *idxi) {
if (condition->metric_type == DistanceMetricType::InnerProduct) {
faiss::heap_heapify<HeapForIP>(topk, simi, idxi);
} else {
faiss::heap_heapify<HeapForL2>(topk, simi, idxi);
}
};
auto reorder_result = [&](int topk, float *simi, idx_t *idxi) {
if (condition->metric_type == DistanceMetricType::InnerProduct) {
faiss::heap_reorder<HeapForIP>(topk, simi, idxi);
} else {
faiss::heap_reorder<HeapForL2>(topk, simi, idxi);
}
};
int raw_d = raw_vec_->GetDimension();
std::function<void(const float **)> compute_vec;
if (condition->has_rank) {
compute_vec = [&](const float **vecs) {
for (int i = 0; i < n; ++i) {
const float *xi = x + i * d_; // query
float *simi = distances + i * k;
long *idxi = labels + i * k;
init_result(k, simi, idxi);
for (int j = 0; j < recall_num; ++j) {
long vid = I[i * recall_num + j];
if (vid < 0) {
continue;
}
int docid = raw_vec_->vid2docid_[vid];
if (is_filterable(docid)) {
continue;
}
float dist = -1;
if (condition->metric_type == DistanceMetricType::InnerProduct) {
dist =
faiss::fvec_inner_product(xi, vecs[i * recall_num + j], raw_d);
} else {
dist = faiss::fvec_L2sqr(xi, vecs[i * recall_num + j], raw_d);
}
if (((condition->min_dist >= 0 && dist >= condition->min_dist) &&
(condition->max_dist >= 0 && dist <= condition->max_dist)) ||
(condition->min_dist == -1 && condition->max_dist == -1)) {
if (condition->metric_type == DistanceMetricType::InnerProduct) {
if (HeapForIP::cmp(simi[0], dist)) {
faiss::heap_pop<HeapForIP>(k, simi, idxi);
faiss::heap_push<HeapForIP>(k, simi, idxi, dist, vid);
}
} else {
if (HeapForL2::cmp(simi[0], dist)) {
faiss::heap_pop<HeapForL2>(k, simi, idxi);
faiss::heap_push<HeapForL2>(k, simi, idxi, dist, vid);
}
}
}
}
if (condition->sort_by_docid) {
vector<std::pair<long, float>> id_sim_pairs(k);
for (int z = 0; z < k; ++z) {
id_sim_pairs[z] = std::move(std::make_pair(idxi[z], simi[z]));
}
std::sort(id_sim_pairs.begin(), id_sim_pairs.end());
for (int z = 0; z < k; ++z) {
idxi[z] = id_sim_pairs[z].first;
simi[z] = id_sim_pairs[z].second;
}
} else {
reorder_result(k, simi, idxi);
}
} // parallel
};
} else {
compute_vec = [&](const float **vecs) {
for (int i = 0; i < n; ++i) {
float *simi = distances + i * k;
long *idxi = labels + i * k;
memset(simi, -1, sizeof(float) * recall_num);
memset(idxi, -1, sizeof(long) * recall_num);
for (int j = 0; j < recall_num; ++j) {
long vid = I[i * recall_num + j];
if (vid < 0) {
continue;
}
int docid = raw_vec_->vid2docid_[vid];
if (is_filterable(docid)) {
continue;
}
float dist = D[i * recall_num + j];
if (((condition->min_dist >= 0 && dist >= condition->min_dist) &&
(condition->max_dist >= 0 && dist <= condition->max_dist)) ||
(condition->min_dist == -1 && condition->max_dist == -1)) {
simi[j] = dist;
idxi[j] = vid;
}
}
}
};
}
std::function<void()> compute_dis;
if (condition->has_rank) {
// calculate inner product for selected possible vectors
compute_dis = [&]() {
ScopeVectors scope_vecs(recall_num * n);
raw_vec_->Gets(recall_num * n, I.data(), scope_vecs);
const float **vecs = scope_vecs.Get();
compute_vec(vecs);
};
} else {
compute_dis = [&]() { compute_vec(nullptr); };
}
compute_dis();
#ifdef PERFORMANCE_TESTING
double end_sort = utils::getmillisecs();
perf_ss << "GPU cost [" << end1 - start << "]ms, batch size [" << batch_size
<< "] inner cost [" << end_sort - end1 << "]ms ";
#endif
return 0;
}
} // namespace gamma_gpu
} // namespace tig_gamma
| 28.525622 | 80 | 0.591387 | qbzenker |
7b7de5ad6f9eff279a109584388401537b3f78ba | 2,701 | cpp | C++ | src/English/edt/en_PronounLinkerUtils.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | 1 | 2022-03-24T19:57:00.000Z | 2022-03-24T19:57:00.000Z | src/English/edt/en_PronounLinkerUtils.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | src/English/edt/en_PronounLinkerUtils.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.
#include "Generic/common/leak_detection.h"
#include "English/edt/en_PronounLinkerUtils.h"
#include "Generic/common/WordConstants.h"
#include "Generic/common/SymbolConstants.h"
#include "English/parse/en_STags.h"
#ifdef _WIN32
#define swprintf _snwprintf
#endif
Symbol EnglishPronounLinkerUtils::augmentIfPOS(Symbol type, const SynNode *node) {
if(node->getHeadPreterm()->getTag() == EnglishSTags::PRPS) {
Symbol pair[] = {type, Symbol(L"POS")};
return combineSymbols(pair, 2);
}
return type;
}
Symbol EnglishPronounLinkerUtils::combineSymbols(Symbol symArray[], int nSymArray, bool use_delimiter) {
wchar_t combined[256] = L"";
const wchar_t delim[] = L".";
for (int i=0; i<nSymArray; i++) {
wcscat(combined, symArray[i].to_string());
if (use_delimiter&& i!=nSymArray-1) wcscat(combined, delim);
}
return Symbol(combined);
}
Symbol EnglishPronounLinkerUtils::getNormDistSymbol(int distance) {
//first normalize the distance
if(distance > 20) distance = 12;
else if (distance > 10) distance = 11;
//now concatenate an "H" with the number
wchar_t number[10];
swprintf(number, 10, L"H%d", distance);
return Symbol(number);
}
// returns parent's headword. If said headword is a copula, we tack on the parent's head's first postmodifier
Symbol EnglishPronounLinkerUtils::getAugmentedParentHeadWord(const SynNode *node) {
if(node == NULL || node->getParent() == NULL)
return SymbolConstants::nullSymbol;
Symbol result = node->getParent()->getHeadWord();
if(WordConstants::isTensedCopulaTypeVerb(result)) {
//append first postmodifier if it exists
const SynNode *parentHead = node->getParent()->getHead();
int firstPostmodIndex = parentHead->getHeadIndex()+1;
if(firstPostmodIndex < parentHead->getNChildren()) {
Symbol pair[] = {result, parentHead->getChild(firstPostmodIndex)->getHeadWord()};
result = combineSymbols(pair, 2);
}
}
return result;
}
Symbol EnglishPronounLinkerUtils::getAugmentedParentHeadTag(const SynNode *node) {
if(node == NULL || node->getParent() == NULL)
return SymbolConstants::nullSymbol;
Symbol parword = node->getParent()->getHeadWord();
Symbol partag = node->getParent()->getHead()->getTag();
if(WordConstants::isTensedCopulaTypeVerb(parword)) {
//append first postmodifier if it exists
const SynNode *parent = node->getParent();
int headIndex = parent->getHeadIndex();
if(headIndex < parent->getNChildren()-1) {
Symbol pair[] = {partag, parent->getChild(headIndex+1)->getHead()->getTag()};
partag = combineSymbols(pair,2);
}
}
return partag;
}
| 33.345679 | 110 | 0.707886 | BBN-E |
7b7f57bcdba784ba0df008ae1a3e72f043fb74df | 7,210 | cpp | C++ | jack/example-clients/server_control.cpp | KimJeongYeon/jack2_android | 4a8787be4306558cb52e5379466c0ed4cc67e788 | [
"BSD-3-Clause-No-Nuclear-Warranty"
] | 47 | 2015-01-04T21:47:07.000Z | 2022-03-23T16:27:16.000Z | vendor/samsung/external/jack/example-clients/server_control.cpp | cesarmo759/android_kernel_samsung_msm8916 | f19717ef6c984b64a75ea600a735dc937b127c25 | [
"Apache-2.0"
] | 3 | 2015-02-04T21:40:11.000Z | 2019-09-16T19:53:51.000Z | jack/example-clients/server_control.cpp | KimJeongYeon/jack2_android | 4a8787be4306558cb52e5379466c0ed4cc67e788 | [
"BSD-3-Clause-No-Nuclear-Warranty"
] | 7 | 2015-05-17T08:22:52.000Z | 2021-08-07T22:36:17.000Z | /*
Copyright (C) 2008 Grame
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <jack/jack.h>
#include <jack/control.h>
static jackctl_driver_t * jackctl_server_get_driver(jackctl_server_t *server, const char *driver_name)
{
const JSList * node_ptr = jackctl_server_get_drivers_list(server);
while (node_ptr) {
if (strcmp(jackctl_driver_get_name((jackctl_driver_t *)node_ptr->data), driver_name) == 0) {
return (jackctl_driver_t *)node_ptr->data;
}
node_ptr = jack_slist_next(node_ptr);
}
return NULL;
}
static jackctl_internal_t * jackctl_server_get_internal(jackctl_server_t *server, const char *internal_name)
{
const JSList * node_ptr = jackctl_server_get_internals_list(server);
while (node_ptr) {
if (strcmp(jackctl_internal_get_name((jackctl_internal_t *)node_ptr->data), internal_name) == 0) {
return (jackctl_internal_t *)node_ptr->data;
}
node_ptr = jack_slist_next(node_ptr);
}
return NULL;
}
#if 0
static jackctl_parameter_t *
jackctl_get_parameter(
const JSList * parameters_list,
const char * parameter_name)
{
while (parameters_list)
{
if (strcmp(jackctl_parameter_get_name((jackctl_parameter_t *)parameters_list->data), parameter_name) == 0)
{
return (jackctl_parameter_t *)parameters_list->data;
}
parameters_list = jack_slist_next(parameters_list);
}
return NULL;
}
#endif
static void print_value(union jackctl_parameter_value value, jackctl_param_type_t type)
{
switch (type) {
case JackParamInt:
printf("parameter value = %d\n", value.i);
break;
case JackParamUInt:
printf("parameter value = %u\n", value.ui);
break;
case JackParamChar:
printf("parameter value = %c\n", value.c);
break;
case JackParamString:
printf("parameter value = %s\n", value.str);
break;
case JackParamBool:
printf("parameter value = %d\n", value.b);
break;
}
}
static void print_parameters(const JSList * node_ptr)
{
while (node_ptr != NULL) {
jackctl_parameter_t * parameter = (jackctl_parameter_t *)node_ptr->data;
printf("\nparameter name = %s\n", jackctl_parameter_get_name(parameter));
printf("parameter id = %c\n", jackctl_parameter_get_id(parameter));
printf("parameter short decs = %s\n", jackctl_parameter_get_short_description(parameter));
printf("parameter long decs = %s\n", jackctl_parameter_get_long_description(parameter));
print_value(jackctl_parameter_get_default_value(parameter), jackctl_parameter_get_type(parameter));
node_ptr = jack_slist_next(node_ptr);
}
}
static void print_driver(jackctl_driver_t * driver)
{
printf("\n--------------------------\n");
printf("driver = %s\n", jackctl_driver_get_name(driver));
printf("-------------------------- \n");
print_parameters(jackctl_driver_get_parameters(driver));
}
static void print_internal(jackctl_internal_t * internal)
{
printf("\n-------------------------- \n");
printf("internal = %s\n", jackctl_internal_get_name(internal));
printf("-------------------------- \n");
print_parameters(jackctl_internal_get_parameters(internal));
}
static void usage()
{
fprintf (stderr, "\n"
"usage: jack_server_control \n"
" [ --driver OR -d driver_name ]\n"
" [ --client OR -c client_name ]\n"
);
}
int main(int argc, char *argv[])
{
jackctl_server_t * server;
const JSList * parameters;
const JSList * drivers;
const JSList * internals;
const JSList * node_ptr;
jackctl_sigmask_t * sigmask;
int opt, option_index;
const char* driver_name = "dummy";
const char* client_name = "audioadapter";
const char *options = "d:c:";
struct option long_options[] = {
{"driver", 1, 0, 'd'},
{"client", 1, 0, 'c'},
{0, 0, 0, 0}
};
while ((opt = getopt_long (argc, argv, options, long_options, &option_index)) != -1) {
switch (opt) {
case 'd':
driver_name = optarg;
break;
case 'c':
client_name = optarg;
break;
default:
usage();
exit(0);
}
}
server = jackctl_server_create(NULL, NULL);
parameters = jackctl_server_get_parameters(server);
/*
jackctl_parameter_t* param;
union jackctl_parameter_value value;
param = jackctl_get_parameter(parameters, "verbose");
if (param != NULL) {
value.b = true;
jackctl_parameter_set_value(param, &value);
}
*/
printf("\n========================== \n");
printf("List of server parameters \n");
printf("========================== \n");
print_parameters(parameters);
printf("\n========================== \n");
printf("List of drivers \n");
printf("========================== \n");
drivers = jackctl_server_get_drivers_list(server);
node_ptr = drivers;
while (node_ptr != NULL) {
print_driver((jackctl_driver_t *)node_ptr->data);
node_ptr = jack_slist_next(node_ptr);
}
printf("\n========================== \n");
printf("List of internal clients \n");
printf("========================== \n");
internals = jackctl_server_get_internals_list(server);
node_ptr = internals;
while (node_ptr != NULL) {
print_internal((jackctl_internal_t *)node_ptr->data);
node_ptr = jack_slist_next(node_ptr);
}
// No error checking in this simple example...
jackctl_server_open(server, jackctl_server_get_driver(server, driver_name));
jackctl_server_start(server);
jackctl_server_load_internal(server, jackctl_server_get_internal(server, client_name));
/*
// Switch master test
jackctl_driver_t* master;
usleep(5000000);
printf("jackctl_server_load_master\n");
master = jackctl_server_get_driver(server, "coreaudio");
jackctl_server_switch_master(server, master);
usleep(5000000);
printf("jackctl_server_load_master\n");
master = jackctl_server_get_driver(server, "dummy");
jackctl_server_switch_master(server, master);
*/
sigmask = jackctl_setup_signals(0);
jackctl_wait_signals(sigmask);
jackctl_server_stop(server);
jackctl_server_close(server);
jackctl_server_destroy(server);
return 0;
}
| 29.428571 | 114 | 0.639528 | KimJeongYeon |
7b8c29d6976b119fe36a5f69a133ccaaf05316aa | 5,980 | cpp | C++ | MMOCoreORB/src/server/zone/managers/creature/SpawnAreaMap.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/src/server/zone/managers/creature/SpawnAreaMap.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/src/server/zone/managers/creature/SpawnAreaMap.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | /*
* SpawnAreaMap.cpp
*
* Created on: 12/08/2011
* Author: TheAnswer
*/
#include "SpawnAreaMap.h"
#include "server/zone/Zone.h"
#include "server/zone/managers/object/ObjectManager.h"
#include "server/zone/objects/area/areashapes/CircularAreaShape.h"
#include "server/zone/objects/area/areashapes/RectangularAreaShape.h"
#include "server/zone/objects/area/areashapes/RingAreaShape.h"
void SpawnAreaMap::loadMap(Zone* z) {
zone = z;
String planetName = zone->getZoneName();
setLoggingName("SpawnAreaMap " + planetName);
lua->init();
try {
loadRegions();
} catch (Exception& e) {
error(e.getMessage());
}
lua->deinit();
lua = nullptr;
}
void SpawnAreaMap::loadRegions() {
String planetName = zone->getZoneName();
lua->runFile("scripts/managers/spawn_manager/" + planetName + "_regions.lua");
LuaObject obj = lua->getGlobalObject(planetName + "_regions");
if (obj.isValidTable()) {
info("loading spawn areas...", true);
lua_State* s = obj.getLuaState();
for (int i = 1; i <= obj.getTableSize(); ++i) {
lua_rawgeti(s, -1, i);
LuaObject areaObj(s);
if (areaObj.isValidTable()) {
readAreaObject(areaObj);
}
areaObj.pop();
}
}
obj.pop();
for (int i = 0; i < size(); ++i) {
SpawnArea* area = get(i);
Locker locker(area);
for (int j = 0; j < noSpawnAreas.size(); ++j) {
SpawnArea* notHere = noSpawnAreas.get(j);
if (area->intersectsWith(notHere)) {
area->addNoSpawnArea(notHere);
}
}
}
}
void SpawnAreaMap::readAreaObject(LuaObject& areaObj) {
String name = areaObj.getStringAt(1);
float x = areaObj.getFloatAt(2);
float y = areaObj.getFloatAt(3);
int tier = areaObj.getIntAt(5);
if (tier == UNDEFINEDAREA)
return;
float radius = 0;
float x2 = 0;
float y2 = 0;
float innerRadius = 0;
float outerRadius = 0;
LuaObject areaShapeObject = areaObj.getObjectAt(4);
if (!areaShapeObject.isValidTable()) {
error("Invalid area shape table for spawn region " + name);
return;
}
int areaType = areaShapeObject.getIntAt(1);
if (areaType == CIRCLE) {
radius = areaShapeObject.getFloatAt(2);
if (radius <= 0 && !(tier & WORLDSPAWNAREA)) {
error("Invalid radius of " + String::valueOf(radius) + " must be > 0 for circular spawn region " + name);
return;
}
} else if (areaType == RECTANGLE) {
x2 = areaShapeObject.getFloatAt(2);
y2 = areaShapeObject.getFloatAt(3);
int rectWidth = x2 - x;
int rectHeight = y2 - y;
if (!(tier & WORLDSPAWNAREA) && (rectWidth <= 0 || rectHeight <= 0)) {
error("Invalid corner coordinates for rectangular spawn region " + name + ", total height: " + String::valueOf(rectHeight) + ", total width: " + String::valueOf(rectWidth));
return;
}
} else if (areaType == RING) {
innerRadius = areaShapeObject.getFloatAt(2);
outerRadius = areaShapeObject.getFloatAt(3);
if (!(tier & WORLDSPAWNAREA)) {
if (innerRadius <= 0) {
error("Invalid inner radius of " + String::valueOf(innerRadius) + " must be > 0 for ring spawn region " + name);
return;
} else if (outerRadius <= 0) {
error("Invalid outer radius of " + String::valueOf(outerRadius) + " must be > 0 for ring spawn region " + name);
return;
}
}
} else {
error("Invalid area type of " + String::valueOf(areaType) + " for spawn region " + name);
return;
}
areaShapeObject.pop();
if (radius == 0 && x2 == 0 && y2 == 0 && innerRadius == 0 && outerRadius == 0)
return;
static const uint32 crc = STRING_HASHCODE("object/spawn_area.iff");
ManagedReference<SpawnArea*> area = dynamic_cast<SpawnArea*>(ObjectManager::instance()->createObject(crc, 0, "spawnareas"));
if (area == nullptr)
return;
Locker objLocker(area);
StringId nameID(zone->getZoneName() + "_region_names", name);
area->setObjectName(nameID, false);
if (areaType == RECTANGLE) {
ManagedReference<RectangularAreaShape*> rectangularAreaShape = new RectangularAreaShape();
Locker shapeLocker(rectangularAreaShape);
rectangularAreaShape->setDimensions(x, y, x2, y2);
float centerX = x + ((x2 - x) / 2);
float centerY = y + ((y2 - y) / 2);
rectangularAreaShape->setAreaCenter(centerX, centerY);
area->setAreaShape(rectangularAreaShape);
} else if (areaType == CIRCLE) {
ManagedReference<CircularAreaShape*> circularAreaShape = new CircularAreaShape();
Locker shapeLocker(circularAreaShape);
circularAreaShape->setAreaCenter(x, y);
if (radius > 0)
circularAreaShape->setRadius(radius);
else
circularAreaShape->setRadius(zone->getBoundingRadius());
area->setAreaShape(circularAreaShape);
} else if (areaType == RING) {
ManagedReference<RingAreaShape*> ringAreaShape = new RingAreaShape();
Locker shapeLocker(ringAreaShape);
ringAreaShape->setAreaCenter(x, y);
ringAreaShape->setInnerRadius(innerRadius);
ringAreaShape->setOuterRadius(outerRadius);
area->setAreaShape(ringAreaShape);
}
area->setTier(tier);
area->initializePosition(x, 0, y);
if (tier & SPAWNAREA) {
area->setMaxSpawnLimit(areaObj.getIntAt(7));
LuaObject spawnGroups = areaObj.getObjectAt(6);
if (spawnGroups.isValidTable()) {
Vector<uint32> groups;
for (int i = 1; i <= spawnGroups.getTableSize(); i++) {
groups.add(spawnGroups.getStringAt(i).hashCode());
}
area->buildSpawnList(&groups);
}
spawnGroups.pop();
}
if ((radius != -1) && !(tier & WORLDSPAWNAREA)) {
zone->transferObject(area, -1, true);
} else {
if (tier & WORLDSPAWNAREA) {
worldSpawnAreas.add(area);
}
area->setZone(zone);
}
area->updateToDatabase();
put(nameID.getStringID().hashCode(), area);
if (tier & NOSPAWNAREA) {
area->setNoSpawnArea(true);
noSpawnAreas.add(area);
}
if (tier & NOBUILDZONEAREA) {
area->setNoBuildArea(true);
}
}
void SpawnAreaMap::unloadMap() {
noSpawnAreas.removeAll();
worldSpawnAreas.removeAll();
for (int i = 0; i < size(); i++) {
SpawnArea* area = get(i);
if (area != nullptr) {
Locker locker(area);
area->destroyObjectFromWorld(false);
}
}
removeAll();
}
| 25.232068 | 176 | 0.675585 | V-Fib |
7b8c880f4a418924a4dfd7ec11eed0f77cca3bef | 3,660 | cc | C++ | net/third_party/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder_test.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | net/third_party/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder_test.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | net/third_party/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder_test.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/third_party/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder.h"
#include <stddef.h>
#include <cstdint>
#include <type_traits>
#include "base/logging.h"
#include "net/third_party/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h"
#include "net/third_party/quic/http/decoder/quic_http_frame_decoder_listener.h"
#include "net/third_party/quic/http/quic_http_constants.h"
#include "net/third_party/quic/http/quic_http_structures.h"
#include "net/third_party/quic/http/test_tools/quic_http_frame_parts.h"
#include "net/third_party/quic/http/test_tools/quic_http_frame_parts_collector.h"
#include "net/third_party/quic/http/tools/quic_http_random_decoder_test.h"
#include "net/third_party/quic/platform/api/quic_string.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
namespace test {
// Provides friend access to an instance of the payload decoder, and also
// provides info to aid in testing.
class QuicHttpContinuationQuicHttpPayloadDecoderPeer {
public:
static constexpr QuicHttpFrameType FrameType() {
return QuicHttpFrameType::CONTINUATION;
}
// Returns the mask of flags that affect the decoding of the payload (i.e.
// flags that that indicate the presence of certain fields or padding).
static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }
static void Randomize(QuicHttpContinuationQuicHttpPayloadDecoder* p,
QuicTestRandomBase* rng) {
// QuicHttpContinuationQuicHttpPayloadDecoder has no fields,
// so there is nothing to randomize.
static_assert(
std::is_empty<QuicHttpContinuationQuicHttpPayloadDecoder>::value,
"Need to randomize fields of "
"QuicHttpContinuationQuicHttpPayloadDecoder");
}
};
namespace {
struct Listener : public QuicHttpFramePartsCollector {
void OnContinuationStart(const QuicHttpFrameHeader& header) override {
VLOG(1) << "OnContinuationStart: " << header;
StartFrame(header)->OnContinuationStart(header);
}
void OnHpackFragment(const char* data, size_t len) override {
VLOG(1) << "OnHpackFragment: len=" << len;
CurrentFrame()->OnHpackFragment(data, len);
}
void OnContinuationEnd() override {
VLOG(1) << "OnContinuationEnd";
EndFrame()->OnContinuationEnd();
}
};
class QuicHttpContinuationQuicHttpPayloadDecoderTest
: public AbstractQuicHttpPayloadDecoderTest<
QuicHttpContinuationQuicHttpPayloadDecoder,
QuicHttpContinuationQuicHttpPayloadDecoderPeer,
Listener>,
public ::testing::WithParamInterface<uint32_t> {
protected:
QuicHttpContinuationQuicHttpPayloadDecoderTest() : length_(GetParam()) {
VLOG(1) << "################ length_=" << length_ << " ################";
}
const uint32_t length_;
};
INSTANTIATE_TEST_CASE_P(VariousLengths,
QuicHttpContinuationQuicHttpPayloadDecoderTest,
::testing::Values(0, 1, 2, 3, 4, 5, 6));
TEST_P(QuicHttpContinuationQuicHttpPayloadDecoderTest, ValidLength) {
QuicString hpack_payload = Random().RandString(length_);
QuicHttpFrameHeader frame_header(length_, QuicHttpFrameType::CONTINUATION,
RandFlags(), RandStreamId());
set_frame_header(frame_header);
QuicHttpFrameParts expected(frame_header, hpack_payload);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(hpack_payload, expected));
}
} // namespace
} // namespace test
} // namespace net
| 37.346939 | 104 | 0.743716 | zipated |
7b9222e701e5eff56c25510359badcff6e8cdca4 | 14,100 | cpp | C++ | src/image_stone/example/002/dlg_effect_lib.cpp | suxinde2009/ImageStone | d9e6ce00379ba0c78278fa4bacc07c8f0f547feb | [
"MIT"
] | null | null | null | src/image_stone/example/002/dlg_effect_lib.cpp | suxinde2009/ImageStone | d9e6ce00379ba0c78278fa4bacc07c8f0f547feb | [
"MIT"
] | null | null | null | src/image_stone/example/002/dlg_effect_lib.cpp | suxinde2009/ImageStone | d9e6ce00379ba0c78278fa4bacc07c8f0f547feb | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "002.h"
#include "dlg_effect_lib.h"
//-------------------------------------------------------------------------------------
void DlgEffectLib::CEffectThumb::SetImage (HBITMAP hBmp)
{
BITMAP bm = {0} ;
if (GetObject (hBmp, sizeof(bm), &bm))
{
m_img.Attach (CreateCompatibleBitmap (CClientDC(NULL), bm.bmWidth, bm.bmHeight)) ;
FCImageDrawDC::DrawBitmap (FCImageDrawDC(m_img), CRect(0, 0, bm.bmWidth, bm.bmHeight), hBmp) ;
}
}
//-------------------------------------------------------------------------------------
void DlgEffectLib::CEffectThumb::DrawTitle (CDC& dc, CRect rcItemOnDC)
{
dc.FillSolidRect (rcItemOnDC, ::GetSysColor(COLOR_3DFACE)) ;
dc.FillSolidRect (CRect(rcItemOnDC.TopLeft(), CSize(rcItemOnDC.Width(),1)), RGB(160,160,160)) ;
dc.DrawText (m_text, rcItemOnDC, DT_SINGLELINE|DT_VCENTER|DT_CENTER) ;
}
//-------------------------------------------------------------------------------------
void DlgEffectLib::CEffectThumb::DrawThumb (CDC& dc, CRect rcItemOnDC)
{
if (IsMouseHovering())
{
dc.FillSolidRect (rcItemOnDC, RGB(220,241,253)) ;
FrameRect (dc, rcItemOnDC, CBrush(RGB(51,153,255))) ;
}
CRect rcTxt = rcItemOnDC ;
rcTxt.top = rcTxt.bottom - 20 ;
CRect rcImg = rcItemOnDC ;
rcImg.bottom = rcTxt.top ;
rcImg.DeflateRect(8,8,8,0) ;
if (m_img.GetSafeHandle())
{
FCImageDrawDC::DrawBitmap (dc, rcImg, m_img) ;
}
dc.DrawText (m_text, rcTxt, DT_SINGLELINE|DT_VCENTER|DT_CENTER) ;
}
//-------------------------------------------------------------------------------------
void DlgEffectLib::CEffectThumb::OnPaint_Item (CDC& dc)
{
CRect rcItemOnDC (CPoint(0,0), GetItemSize()) ;
if (m_command_id)
{
DrawThumb(dc, rcItemOnDC) ;
}
else
{
DrawTitle(dc, rcItemOnDC) ;
}
}
//-------------------------------------------------------------------------------------
void DlgEffectLib::CThumbLayout::Layout_ListItem (CWnd* pWnd, std::deque<FCListItem_Base*>& item_list)
{
CRect rcClient ;
pWnd->GetClientRect(rcClient) ;
CSize item_size ;
item_size.cx = rcClient.Width() / 2 ;
item_size.cy = 100 ;
int nCurrY = 0 ;
BOOL nLineIndex = 0 ;
CRect rcBound (0,0,0,0) ;
for (size_t i=0 ; i < item_list.size() ; i++)
{
CEffectThumb * pItem = (CEffectThumb*)item_list[i] ;
CRect rc ;
BOOL bNewLine = FALSE ;
if (pItem->m_command_id)
{
rc = CRect(CPoint(nLineIndex * item_size.cx,nCurrY), item_size) ;
nLineIndex++ ;
if (nLineIndex == 2)
bNewLine = TRUE ;
if (i < item_list.size()-1)
{
if (!((CEffectThumb*)item_list[i+1])->m_command_id)
bNewLine = TRUE ;
}
}
else
{
// title item
rc = CRect(CPoint(0,nCurrY), CSize(rcClient.Width(),26)) ;
bNewLine = TRUE ;
}
if (bNewLine)
{
nCurrY += rc.Height() ;
nLineIndex = 0 ;
}
pItem->SetRectOnCanvas (rc) ;
rcBound.UnionRect (rcBound, rc) ;
}
SetVScrollRange (pWnd, rcBound.Height()) ;
}
//-------------------------------------------------------------------------------------
DlgEffectLib::CEffectList::CEffectList()
{
m_thread = NULL ;
SetLayoutHandler(new CThumbLayout()) ;
AddThumb (ID_EFFECT_COLORTONE, NULL) ;
AddThumb (ID_EFFECT_GRAYSCALE, NULL) ;
AddThumb (ID_EFFECT_SOFTGLOW, NULL) ;
AddThumb (ID_EFFECT_SOFT_PORTRAIT, NULL) ;
AddThumb (ID_EFFECT_MOSAIC, NULL) ;
AddThumb (ID_EFFECT_INVERT, NULL) ;
AddThumb (ID_EFFECT_SMOOTHEDGE, NULL) ;
AddThumb (ID_EFFECT_BLURMOTION, NULL) ;
AddThumb (ID_EFFECT_BLURRADIAL, NULL) ;
AddThumb (ID_EFFECT_BLURZOOM, NULL) ;
AddThumb (0, GetPureMenuText(L"s_3_0")) ;
AddThumb (ID_EFFECT_NOISIFY, NULL) ;
AddThumb (ID_EFFECT_OILPAINT, NULL) ;
AddThumb (ID_EFFECT_EMBOSS, NULL) ;
AddThumb (ID_EFFECT_SPLASH, NULL) ;
AddThumb (ID_EFFECT_POSTERIZE, NULL) ;
AddThumb (ID_EFFECT_TEXTURE, NULL) ;
AddThumb (ID_EFFECT_3DGRID, NULL) ;
AddThumb (ID_EFFECT_PENCILSKETCH, NULL) ;
AddThumb (0, GetPureMenuText(L"s_3_1")) ;
AddThumb (ID_EFFECT_SHIFT, NULL) ;
AddThumb (ID_EFFECT_RIBBON, NULL) ;
AddThumb (ID_EFFECT_BULGE, NULL) ;
AddThumb (ID_EFFECT_TWIST, NULL) ;
AddThumb (ID_EFFECT_ILLUSION, NULL) ;
AddThumb (ID_EFFECT_WAVE, NULL) ;
AddThumb (ID_EFFECT_RIPPLE, NULL) ;
AddThumb (0, GetPureMenuText(L"s_3_2")) ;
AddThumb (ID_EFFECT_LENSFLARE, NULL) ;
AddThumb (ID_EFFECT_SUPERNOVA, NULL) ;
AddThumb (ID_EFFECT_GLASSTILE, NULL) ;
AddThumb (ID_EFFECT_BLINDS, NULL) ;
AddThumb (ID_EFFECT_RAISEFRAME, NULL) ;
AddThumb (0, GetPureMenuText(L"s_3_3")) ;
AddThumb (ID_EFFECT_HALFTONE, NULL) ;
AddThumb (ID_EFFECT_THRESHOLD, NULL) ;
AddThumb (ID_EFFECT_SOLARIZE, NULL) ;
AddThumb (ID_EFFECT_OLDPHOTO, NULL) ;
AddThumb (0, GetPureMenuText(L"s_3_4")) ;
AddThumb (ID_EFFECT_FILLGRID, NULL) ;
AddThumb (ID_EFFECT_VIDEO, NULL) ;
}
//-------------------------------------------------------------------------------------
DlgEffectLib::CEffectList::~CEffectList()
{
// first destroy window to cancel SendMessage, wait thread finish
DestroyWindow() ;
if (m_thread)
{
WaitForSingleObject (m_thread, INFINITE) ;
CloseHandle(m_thread) ;
}
}
//-------------------------------------------------------------------------------------
CString DlgEffectLib::CEffectList::GetPureMenuText (LPCWSTR sName)
{
CString s = theApp.GetText(L"MENU_TEXT", sName) ;
int n = s.Find(L"(&") ;
if (n != -1)
{
s = s.Left(n) ;
}
s.Replace (L"&", L"") ;
return s ;
}
//-------------------------------------------------------------------------------------
void DlgEffectLib::CEffectList::AddThumb (int nCommand, LPCWSTR sText)
{
CString s ;
if (nCommand)
{
s = theApp.GetMenuPureText(nCommand) ;
}
else
{
s = (sText ? sText : L"") ;
}
AddListItem (new CEffectThumb(nCommand, s)) ;
}
//-------------------------------------------------------------------------------------
LRESULT DlgEffectLib::CEffectList::WindowProc (UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == WM_PAINT)
{
// create sample when paint
if (!m_thread)
{
THREAD_PARAM * p = new THREAD_PARAM ;
p->m_wnd = m_hWnd ;
for (int i=0 ; i < GetListItemCount() ; i++)
{
p->m_cmd.push_back( ((CEffectThumb*)GetListItem(i))->m_command_id ) ;
}
m_thread = CreateThread (NULL, 0, MakeThumbThread, p, 0, NULL) ;
if (!m_thread)
{
ASSERT(FALSE) ;
delete p ;
}
}
}
if (msg == WM_OXO_EFFECT_THUMB_FINISH)
{
for (int i=0 ; i < GetListItemCount() ; i++)
{
CEffectThumb * pItem = (CEffectThumb*)GetListItem(i) ;
if (pItem->m_command_id == (int)wParam)
{
pItem->SetImage((HBITMAP)lParam) ;
break;
}
}
Invalidate() ;
return 0x11228899 ;
}
if (msg == WM_LBUTTONDOWN)
{
CEffectThumb * pItem = (CEffectThumb*)HitTestListItem(lParam) ;
if (pItem && pItem->m_command_id)
{
AfxGetMainWnd()->PostMessage(WM_COMMAND, MAKEWPARAM(pItem->m_command_id,0)) ;
}
}
return FCListWindow::WindowProc(msg, wParam, lParam) ;
}
//-------------------------------------------------------------------------------------
FCImageEffect* DlgEffectLib::CEffectList::CreateEffect (int nCommandID)
{
switch (nCommandID)
{
case ID_EFFECT_COLORTONE : return new FCEffectColorTone(FCColor(255,187,0),160) ;
case ID_EFFECT_GRAYSCALE : return new FCEffectGrayscale ;
case ID_EFFECT_SOFTGLOW : return new FCEffectSoftGlow(10,10,10) ;
case ID_EFFECT_SOFT_PORTRAIT : return new FCEffectSoftPortrait(5,0,20) ;
case ID_EFFECT_MOSAIC : return new FCEffectMosaic(6) ;
case ID_EFFECT_INVERT : return new FCEffectInvert ;
case ID_EFFECT_SMOOTHEDGE : return new FCEffectSmoothEdge(15) ;
case ID_EFFECT_BLURMOTION : return new FCEffectBlur_Motion(20,0) ;
case ID_EFFECT_BLURRADIAL : return new FCEffectBlur_Radial(10) ;
case ID_EFFECT_BLURZOOM : return new FCEffectBlur_Zoom(100) ;
case ID_EFFECT_NOISIFY : return new FCEffectNoisify(50,false) ;
case ID_EFFECT_OILPAINT : return new FCEffectOilPaint(3,30) ;
case ID_EFFECT_EMBOSS : return new FCEffectEmboss(0) ;
case ID_EFFECT_SPLASH : return new FCEffectSplash(10) ;
case ID_EFFECT_POSTERIZE : return new FCEffectPosterize(2) ;
case ID_EFFECT_TEXTURE :
{
FCObjImage * pImg = new FCObjImage ;
pImg->LoadResource (IDR_PNG_TEXTURE_CANVAS_2, L"PNG", IMG_PNG) ;
pImg->ConvertTo24Bit() ;
return new FCEffectFillPattern(pImg, 0xFF, true) ;
}
case ID_EFFECT_3DGRID : return new FCEffect3DGrid(16,128) ;
case ID_EFFECT_PENCILSKETCH : return new FCEffectPencilSketch(2,7) ;
case ID_EFFECT_SHIFT : return new FCEffectShift(10) ;
case ID_EFFECT_RIBBON : return new FCEffectRibbon(30,30) ;
case ID_EFFECT_BULGE : return new FCEffectBulge(100) ;
case ID_EFFECT_TWIST : return new FCEffectTwist(20,200) ;
case ID_EFFECT_ILLUSION : return new FCEffectIllusion(3) ;
case ID_EFFECT_WAVE : return new FCEffectWave(6,6) ;
case ID_EFFECT_RIPPLE : return new FCEffectRipple(38,15,true) ;
case ID_EFFECT_LENSFLARE : return new FCEffectLensFlare(CPoint(50,30)) ;
case ID_EFFECT_SUPERNOVA : return new FCEffectSupernova(CPoint(50,30),FCColor(255,255,60),10,100) ;
case ID_EFFECT_GLASSTILE : return new FCEffectTileReflection(20,10) ;
case ID_EFFECT_BLINDS : return new FCEffectBlinds(FCEffectBlinds::BLIND_X,10,100,FCColor(255,255,255)) ;
case ID_EFFECT_RAISEFRAME : return new FCEffectRaiseFrame(10) ;
case ID_EFFECT_HALFTONE : return new FCEffectHalftoneM3 ;
case ID_EFFECT_THRESHOLD : return new FCEffectThreshold(128) ;
case ID_EFFECT_SOLARIZE : return new FCEffectSolarize(128) ;
case ID_EFFECT_OLDPHOTO : return new FCEffectOldPhoto(2) ;
case ID_EFFECT_FILLGRID : return new FCEffectFillGrid(FCColor(0,128,255),FCColor(255,255,255),16,128) ;
case ID_EFFECT_VIDEO : return new FCEffectVideo(FCEffectVideo::VIDEO_TRIPED) ;
}
return NULL ;
}
//-------------------------------------------------------------------------------------
DWORD WINAPI DlgEffectLib::CEffectList::MakeThumbThread (LPVOID lpParameter)
{
FCObjImage demo_img ;
demo_img.LoadResource (IDR_PNG_EXAMPLE, L"PNG", IMG_PNG) ;
demo_img.ConvertTo32Bit() ;
std::auto_ptr<THREAD_PARAM> r ((THREAD_PARAM*)lpParameter) ;
for (size_t i=0 ; i < r->m_cmd.size() ; i++)
{
int nCommandID = r->m_cmd[i] ;
std::auto_ptr<FCImageEffect> eff (CreateEffect(nCommandID)) ;
if (!eff.get())
continue ;
FCObjImage img = demo_img ;
img.ApplyEffect (*eff) ;
img.ApplyEffect (FCEffectFillBackGround(FCColor(0xFF,0xFF,0xFF,0xFF))) ;
LRESULT l = ::SendMessage (r->m_wnd, WM_OXO_EFFECT_THUMB_FINISH, (WPARAM)nCommandID, (LPARAM)(HBITMAP)img) ;
if (l != 0x11228899)
break;
}
return 0 ;
}
//-------------------------------------------------------------------------------------
void DlgEffectLib::Create (CMDIFrameWnd* pMainFrame)
{
CDialogBar::Create (pMainFrame, IDD_EFFECT_LIB, CBRS_LEFT|CBRS_RIGHT|CBRS_SIZE_DYNAMIC, ID_EFFECT_LIB_VISIBLE) ;
m_sizeDefault.cx = 200 ;
m_sizeDefault.cy = GetSystemMetrics(SM_CYFULLSCREEN) - 200 ;
SetWindowText(L"Effect Lib") ;
pMainFrame->ShowControlBar (this, FALSE, FALSE) ; // hide at first
EnableDocking (CBRS_ALIGN_LEFT | CBRS_ALIGN_RIGHT) ;
pMainFrame->DockControlBar (this, AFX_IDW_DOCKBAR_RIGHT) ;
}
//-------------------------------------------------------------------------------------
CSize DlgEffectLib::CalcDynamicLayout(int nLength, DWORD dwMode)
{
if (dwMode & LM_VERTDOCK)
{
CSize sz = m_sizeDefault ;
sz.cy = GetSystemMetrics(SM_CYFULLSCREEN) ;
return sz ;
}
return CDialogBar::CalcDynamicLayout (nLength, dwMode) ;
}
//-------------------------------------------------------------------------------------
void DlgEffectLib::ShowList()
{
if (!m_list.get())
{
m_list.reset(new CEffectList) ;
CRect rc (CPoint(0,0), m_sizeDefault) ;
rc.DeflateRect(4,5,3,10) ;
m_list->Create(rc, this, 0, WS_VISIBLE) ;
}
}
//-------------------------------------------------------------------------------------
void DlgEffectLib::HideList()
{
m_list.reset() ;
}
//-------------------------------------------------------------------------------------
LRESULT DlgEffectLib::WindowProc (UINT msg, WPARAM wParam, LPARAM lParam)
{
if ((msg == WM_WINDOWPOSCHANGED) && lParam)
{
WINDOWPOS * p = (WINDOWPOS*)lParam ;
if (p->flags & SWP_SHOWWINDOW)
{
ShowList() ;
}
if (p->flags & SWP_HIDEWINDOW)
{
HideList() ;
}
}
return CDialogBar::WindowProc(msg, wParam, lParam) ;
}
| 36.061381 | 119 | 0.542837 | suxinde2009 |
7b92ac9a784990e32aedf5204d0c56ce6a168b4c | 2,961 | cc | C++ | FWCore/Utilities/test/test_catch2_EDGetToken.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | FWCore/Utilities/test/test_catch2_EDGetToken.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | FWCore/Utilities/test/test_catch2_EDGetToken.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include <functional>
#include "FWCore/Utilities/interface/EDGetToken.h"
#include "catch.hpp"
namespace edm {
class TestEDGetToken {
public:
template <typename... Args>
static edm::EDGetToken makeToken(Args&&... iArgs) {
return edm::EDGetToken(std::forward<Args>(iArgs)...);
}
template <typename T, typename... Args>
static edm::EDGetTokenT<T> makeTokenT(Args&&... iArgs) {
return edm::EDGetTokenT<T>(std::forward<Args>(iArgs)...);
}
template <typename T, typename... Args>
static const edm::EDGetTokenT<T> makeConstTokenT(Args&&... iArgs) {
return edm::EDGetTokenT<T>(std::forward<Args>(iArgs)...);
}
};
} // namespace edm
namespace {
class Adapter {
public:
template <typename T>
edm::EDGetTokenT<T> consumes() const {
return edm::TestEDGetToken::makeTokenT<T>(11U);
}
};
} // namespace
TEST_CASE("Test EDGetToken", "[EDGetToken]") {
SECTION("EDGetTokenT") {
SECTION("No argument ctr") {
edm::EDGetTokenT<int> token1 = edm::TestEDGetToken::makeTokenT<int>();
REQUIRE(token1.isUninitialized());
REQUIRE((token1.index() == 0xFFFFFFFF));
}
SECTION("1 arg ctr") {
edm::EDGetTokenT<int> token2 = edm::TestEDGetToken::makeTokenT<int>(11U);
REQUIRE(!token2.isUninitialized());
REQUIRE((token2.index() == 11));
}
SECTION("non const arg copy ctr") {
edm::EDGetTokenT<int> token2 = edm::TestEDGetToken::makeTokenT<int>(11U);
edm::EDGetTokenT<int> token3(token2);
REQUIRE(!token3.isUninitialized());
REQUIRE((token3.index() == 11));
}
SECTION("const arg copy ctr") {
const edm::EDGetTokenT<int> cToken2 = edm::TestEDGetToken::makeTokenT<int>(11U);
edm::EDGetTokenT<int> token4(cToken2);
REQUIRE(!token4.isUninitialized());
REQUIRE(token4.index() == 11);
}
SECTION("const arg copy ctr with move") {
auto const t = edm::TestEDGetToken::makeConstTokenT<int>(11U);
const edm::EDGetTokenT<int> cToken2{std::move(t)};
REQUIRE(!cToken2.isUninitialized());
REQUIRE(cToken2.index() == 11);
}
SECTION("Use Adapter") {
Adapter a;
const edm::EDGetTokenT<int> cToken2{a};
REQUIRE(!cToken2.isUninitialized());
REQUIRE(cToken2.index() == 11);
}
}
SECTION("EDGetToken") {
SECTION("No arg ctr") {
edm::EDGetToken token10 = edm::TestEDGetToken::makeToken();
REQUIRE(token10.isUninitialized());
REQUIRE(token10.index() == 0xFFFFFFFF);
}
SECTION("1 arg ctr") {
edm::EDGetToken token11 = edm::TestEDGetToken::makeToken(100);
REQUIRE(!token11.isUninitialized());
REQUIRE(token11.index() == 100);
}
SECTION("EDGetTokenT to EDGetToken ctr") {
edm::EDGetTokenT<int> token2 = edm::TestEDGetToken::makeTokenT<int>(11U);
edm::EDGetToken token12(token2);
REQUIRE(!token12.isUninitialized());
REQUIRE(token12.index() == 11);
}
}
}
| 30.525773 | 86 | 0.63053 | ckamtsikis |
7b92b68a537bf7fc0530c0f58ed4eead3c953bc6 | 3,896 | cpp | C++ | imove_peopleextractor/src/ImageProcessing/PeopleExtractor.cpp | fbredius/IMOVE | 912b4d0696e88acfc0ce7bc556eecf8fc423c4d3 | [
"MIT"
] | 3 | 2018-04-24T10:04:37.000Z | 2018-05-11T08:27:03.000Z | imove_peopleextractor/src/ImageProcessing/PeopleExtractor.cpp | fbredius/IMOVE | 912b4d0696e88acfc0ce7bc556eecf8fc423c4d3 | [
"MIT"
] | null | null | null | imove_peopleextractor/src/ImageProcessing/PeopleExtractor.cpp | fbredius/IMOVE | 912b4d0696e88acfc0ce7bc556eecf8fc423c4d3 | [
"MIT"
] | 3 | 2018-05-16T08:44:19.000Z | 2020-12-04T16:04:32.000Z | #include "PeopleExtractor.h"
// PeopleExtractor::PeopleExtractor(const cv::Size& frame_size, float pixels_per_meter, float resolution_resize_height, const Boundary& boundary) {
PeopleExtractor::PeopleExtractor(CameraConfiguration* camConfig) {
// Get values from camera configuration
frame_size = camConfig->getResolution();
float pixels_per_meter = camConfig->getMeter();
Boundary boundary = camConfig->getProjection().createReorientedTopLeftBoundary();
// Calculate resize ratio
resize_ratio = 1;
// Initialize empty frame
frame = cv::Mat::zeros(frame_size.height, frame_size.width, CV_8UC1);
// Initialize Detector
detector = PeopleDetector(pixels_per_meter, camConfig->getMinBlobArea(), camConfig->getMinBlobDistance());
// Initialize projector boundary
Boundary proj_bound = Boundary(Vector2(boundary.getUpperLeft().x, boundary.getUpperLeft().y),
Vector2(boundary.getUpperRight().x, boundary.getUpperRight().y),
Vector2(boundary.getLowerLeft().x, boundary.getLowerLeft().y),
Vector2(boundary.getLowerRight().x, boundary.getLowerRight().y));
// Initialize Identifier
identifier = PeopleIdentifier(proj_bound);
}
PeopleExtractor::~PeopleExtractor() {}
const scene_interface::People PeopleExtractor::extractPeople(cv::Mat& new_frame) {
// Convert frame to grayscale
//cvtColor(new_frame, new_frame, CV_RGB2GRAY);
// Downscale frame
resize(new_frame, new_frame, frame_size);
// Start working with new frame
frame = new_frame;
// Get a vector with every Person in the Scene, generated by the Identifier from the locations provided by the Detector
std::vector<Vector2> locations = detector.detect(frame);
std::vector<Person> people = identifier.match(locations);
debug_frame = detector.getDisplayFrame();
// Rescale location of every person based on downscaling
for (Person& p : people) {
Vector2 location = p.getLocation();
//cv::putText(debug_frame, std::to_string(p.getId()), cv::Point(location.x, location.y), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(0, 0, 255));
p.setLocation(Vector2(location.x*resize_ratio,location.y*resize_ratio));
}
// Convert people to Person class from scene interface
scene_interface::People converted_people = convert(people);
// Return all extracted people
return converted_people;
}
const scene_interface::People PeopleExtractor::convert(std::vector<Person>& people) {
scene_interface::People interface_people;
for (Person person : people) {
// Check person type
scene_interface::Person::PersonType interface_person_type;
switch (person.person_type) {
case Person::PersonType::Bystander:
interface_person_type = scene_interface::Person::PersonType::Bystander;
break;
case Person::PersonType::Participant:
interface_person_type = scene_interface::Person::PersonType::Participant;
break;
case Person::PersonType::None:
interface_person_type = scene_interface::Person::PersonType::None;
break;
}
// Check movement type
scene_interface::Person::MovementType interface_movement_type;
switch (person.movement_type) {
case Person::MovementType::StandingStill:
interface_movement_type = scene_interface::Person::MovementType::StandingStill;
break;
case Person::MovementType::Moving:
interface_movement_type = scene_interface::Person::MovementType::Moving;
break;
}
Vector2 location = person.getLocation();
// Add converted person to interface_people
interface_people.push_back(scene_interface::Person(
person.getId(),
scene_interface::Location(
location.x,
location.y
),
interface_person_type,
interface_movement_type
));
}
return interface_people;
}
const cv::Mat PeopleExtractor::getDebugFrame() const {
return debug_frame;
}
| 37.825243 | 147 | 0.728183 | fbredius |
7b95b03de13cffd104142153fac9c6592d5b6e33 | 3,426 | cpp | C++ | android/sample/jni/SonicGenerator.cpp | UzayAnil/sonic-2 | fb28489ce5fd499bf42d35d316d080225b202b01 | [
"MIT"
] | 124 | 2015-03-12T08:39:35.000Z | 2021-11-08T10:10:31.000Z | android/sample/jni/SonicGenerator.cpp | UzayAnil/sonic-2 | fb28489ce5fd499bf42d35d316d080225b202b01 | [
"MIT"
] | 7 | 2015-06-11T07:13:22.000Z | 2018-02-27T01:13:25.000Z | android/sample/jni/SonicGenerator.cpp | UzayAnil/sonic-2 | fb28489ce5fd499bf42d35d316d080225b202b01 | [
"MIT"
] | 57 | 2015-03-05T12:55:58.000Z | 2021-06-20T11:03:48.000Z | //
// SonicGenerator.cpp
//
//
// Created by linyehui on 2014-04-10.
// Copyright (c) 2014年 linyehui. All rights reserved.
//
#include <jni.h>
#include "com_duowan_sonic_SonicGenerator.h"
#include "freq_util/bb_header.h"
#include "queue/queue.h"
#include "generator_helper/generator_helper.h"
#include "pcm_render/pcm_render.h"
#ifdef __cplusplus //最好有这个,否则被编译器改了函数名字找不到不要怪我
extern "C" {
#endif
int getWaveLenByByte()
{
int len = SonicSDK::PCMRender::getChirpLengthByByte(RS_TOTAL_LEN) + SonicSDK::SONIC_HEADER_SIZE;
return len;
}
int genWaveData(const char* hash_array, char* buffer, int buffer_len)
{
if (0 == hash_array || 0 == buffer)
return -1;
int hash_len = strlen(hash_array);
if (hash_len != RS_DATA_LEN)
return -1;
if (buffer_len < getWaveLenByByte())
return -1;
char result_with_rs[RS_TOTAL_LEN + 1];
if (!SonicSDK::GeneratorHelper::genRSCode(hash_array, result_with_rs, RS_TOTAL_LEN + 1))
{
return 0;
}
long buffer_len_by_byte = SonicSDK::PCMRender::getChirpLengthByByte(RS_TOTAL_LEN);
short* wave_buffer = (short*)malloc(buffer_len_by_byte);
if (NULL == wave_buffer)
return 0;
unsigned char waveHeaderByteArray[SonicSDK::SONIC_HEADER_SIZE];
if (!SonicSDK::PCMRender::renderChirpData(
result_with_rs,
RS_TOTAL_LEN,
waveHeaderByteArray,
SonicSDK::SONIC_HEADER_SIZE,
wave_buffer,
buffer_len_by_byte))
{
free(wave_buffer);
return 0;
}
memcpy(buffer, waveHeaderByteArray, SonicSDK::SONIC_HEADER_SIZE);
memcpy(buffer + SonicSDK::SONIC_HEADER_SIZE, wave_buffer, buffer_len_by_byte);
//memcpy(pArray, wave_buffer, buffer_len_by_byte);
if (0 != wave_buffer)
{
free(wave_buffer);
}
jint output_len = SonicSDK::SONIC_HEADER_SIZE + buffer_len_by_byte;
return output_len;
}
/*
* Class: com_duowan_sonic_SonicGenerator
* Method: getWaveLenByByte
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_com_duowan_sonic_SonicGenerator_getWaveLenByByte
(JNIEnv *, jclass)
{
return getWaveLenByByte();
}
/*
* Class: com_duowan_sonic_SonicGenerator
* Method: genWaveData
* Signature: (Ljava/lang/String;[B)I
*/
JNIEXPORT jint JNICALL Java_com_duowan_sonic_SonicGenerator_genWaveData
(JNIEnv* env, jclass, jstring hash_string, jbyteArray buffer)
{
const char* pHashString = (const char*)env->GetStringUTFChars(hash_string, JNI_FALSE);
if (0 == pHashString)
return -1;
// env的调用好像不能嵌套,会crash,所以先把这个复制一份,然后先ReleaseStringUTFChars
// linyehui 2014-04-22
int len = strlen(pHashString);
char* hash_buffer = new char[len+1];
if (0 == hash_buffer)
{
env->ReleaseStringUTFChars(hash_string, pHashString);
return -1;
}
strcpy(hash_buffer, pHashString);
env->ReleaseStringUTFChars(hash_string, pHashString);
jboolean isCopy = false;
jbyteArray pArray = (jbyteArray) env->GetPrimitiveArrayCritical(buffer, &isCopy);
jsize size = env->GetArrayLength(buffer);
jint output_len = genWaveData(hash_buffer, (char*)pArray, size);
delete hash_buffer;
env->ReleasePrimitiveArrayCritical(buffer, pArray, JNI_COMMIT);
return output_len;
}
#ifdef __cplusplus
}
#endif
| 27.629032 | 97 | 0.670753 | UzayAnil |
7b98c1ad62eaa5bf9f48933390e25e1ed4819bae | 166 | cpp | C++ | doric-Qt/example/doric/engine/DoricNativeRequire.cpp | Xcoder1011/Doric | ad1a409ef5edb9de8f3e1544748a9fa8015760c8 | [
"Apache-2.0"
] | 116 | 2019-12-30T11:34:47.000Z | 2022-03-31T05:32:58.000Z | doric-Qt/example/doric/engine/DoricNativeRequire.cpp | Xcoder1011/Doric | ad1a409ef5edb9de8f3e1544748a9fa8015760c8 | [
"Apache-2.0"
] | 9 | 2020-04-26T02:04:27.000Z | 2022-01-26T07:31:01.000Z | doric-Qt/example/doric/engine/DoricNativeRequire.cpp | Xcoder1011/Doric | ad1a409ef5edb9de8f3e1544748a9fa8015760c8 | [
"Apache-2.0"
] | 18 | 2020-01-24T15:42:03.000Z | 2021-12-28T08:17:36.000Z | #include "DoricNativeRequire.h"
#include <QDebug>
Q_INVOKABLE void DoricNativeRequire::function(QString name) {
qDebug() << "nativeRequire: " << name.toUtf8();
}
| 20.75 | 61 | 0.722892 | Xcoder1011 |
7b9a3720b498e04ab54ebadc197a08c67a67d944 | 1,118 | cpp | C++ | src/reader.cpp | data-bridge/build | 1bd37f7061d9bd5caf0c1bd9c5cbbd85c7a45486 | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | src/reader.cpp | data-bridge/build | 1bd37f7061d9bd5caf0c1bd9c5cbbd85c7a45486 | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | src/reader.cpp | data-bridge/build | 1bd37f7061d9bd5caf0c1bd9c5cbbd85c7a45486 | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | /*
Part of BridgeData.
Copyright (C) 2016-17 by Soren Hein.
See LICENSE and README.
*/
#include <iostream>
#if defined(_WIN32) && defined(__MINGW32__)
#include "mingw.thread.h"
#else
#include <thread>
#endif
#include "args.h"
#include "Files.h"
#include "AllStats.h"
#include "dispatch.h"
using namespace std;
int main(int argc, char * argv[])
{
Options options;
readArgs(argc, argv, options);
setTables();
Files files;
files.set(options);
vector<thread> thr(options.numThreads);
vector<AllStats> allStatsList(options.numThreads);
Timer timer;
timer.start();
for (unsigned i = 0; i < options.numThreads; i++)
thr[i] = thread(dispatch, i, ref(files), options, ref(allStatsList[i]));
for (unsigned i = 0; i < options.numThreads; i++)
thr[i].join();
mergeResults(allStatsList, options);
printResults(allStatsList[0], options);
if (options.solveFlag)
files.writeDDInfo(BRIDGE_DD_INFO_SOLVE);
if (options.traceFlag)
files.writeDDInfo(BRIDGE_DD_INFO_TRACE);
timer.stop();
cout << "Time spent overall (elapsed): " << timer.str(2) << "\n";
}
| 18.327869 | 76 | 0.67263 | data-bridge |
7b9a86bd24183a25c29a0cf65f3bf35ffddebcaf | 5,403 | cc | C++ | cc/base/scoped_ptr_vector_unittest.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5 | 2015-04-30T00:13:21.000Z | 2019-07-10T02:17:24.000Z | cc/base/scoped_ptr_vector_unittest.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | cc/base/scoped_ptr_vector_unittest.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | // Copyright 2012 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 <set>
#include "cc/base/scoped_ptr_vector.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace cc {
namespace {
class Data {
public:
static scoped_ptr<Data> Create(int i) { return make_scoped_ptr(new Data(i)); }
int data() const { return data_; }
private:
explicit Data(int i) : data_(i) {}
int data_;
};
class IsOddPredicate {
public:
bool operator()(const Data* data) { return (data->data() % 2) == 1; }
};
TEST(ScopedPtrVectorTest, PushBack) {
ScopedPtrVector<Data> v;
// Insert 5 things into the vector.
v.push_back(Data::Create(1));
v.push_back(Data::Create(2));
v.push_back(Data::Create(3));
v.push_back(Data::Create(4));
v.push_back(Data::Create(5));
EXPECT_EQ(5u, v.size());
EXPECT_EQ(1, v[0]->data());
EXPECT_EQ(2, v[1]->data());
EXPECT_EQ(3, v[2]->data());
EXPECT_EQ(4, v[3]->data());
EXPECT_EQ(5, v[4]->data());
}
TEST(ScopedPtrVectorTest, InsertAndTake) {
// Insert 3 things into each vector.
ScopedPtrVector<Data> v;
v.push_back(Data::Create(1));
v.push_back(Data::Create(2));
v.push_back(Data::Create(6));
ScopedPtrVector<Data> v2;
v2.push_back(Data::Create(3));
v2.push_back(Data::Create(4));
v2.push_back(Data::Create(5));
ScopedPtrVector<Data>::iterator it = v.begin();
++it;
++it;
EXPECT_EQ(6, (*it)->data());
v.insert_and_take(it, &v2);
EXPECT_EQ(6u, v.size());
EXPECT_EQ(1, v[0]->data());
EXPECT_EQ(2, v[1]->data());
EXPECT_EQ(3, v[2]->data());
EXPECT_EQ(4, v[3]->data());
EXPECT_EQ(5, v[4]->data());
EXPECT_EQ(6, v[5]->data());
EXPECT_EQ(3u, v2.size());
EXPECT_EQ(nullptr, v2[0]);
EXPECT_EQ(nullptr, v2[1]);
EXPECT_EQ(nullptr, v2[2]);
}
TEST(ScopedPtrVectorTest, Partition) {
ScopedPtrVector<Data> v;
v.push_back(Data::Create(1));
v.push_back(Data::Create(2));
v.push_back(Data::Create(3));
v.push_back(Data::Create(4));
v.push_back(Data::Create(5));
ScopedPtrVector<Data>::iterator it = v.partition(IsOddPredicate());
std::set<int> odd_numbers;
for (ScopedPtrVector<Data>::iterator second_it = v.begin();
second_it != it;
++second_it) {
EXPECT_EQ(1, (*second_it)->data() % 2);
odd_numbers.insert((*second_it)->data());
}
EXPECT_EQ(3u, odd_numbers.size());
std::set<int> even_numbers;
for (; it != v.end(); ++it) {
EXPECT_EQ(0, (*it)->data() % 2);
even_numbers.insert((*it)->data());
}
EXPECT_EQ(2u, even_numbers.size());
}
class DataWithDestruction {
public:
static scoped_ptr<DataWithDestruction> Create(int i, int* destroy_count) {
return make_scoped_ptr(new DataWithDestruction(i, destroy_count));
}
int data() const { return data_; }
~DataWithDestruction() { ++(*destroy_count_); }
private:
explicit DataWithDestruction(int i, int* destroy_count)
: data_(i), destroy_count_(destroy_count) {}
int data_;
int* destroy_count_;
};
TEST(ScopedPtrVectorTest, RemoveIf) {
ScopedPtrVector<DataWithDestruction> v;
int destroyed[6] = {0};
v.push_back(DataWithDestruction::Create(1, &destroyed[0]));
v.push_back(DataWithDestruction::Create(2, &destroyed[1]));
v.push_back(DataWithDestruction::Create(3, &destroyed[2]));
v.push_back(DataWithDestruction::Create(3, &destroyed[3]));
v.push_back(DataWithDestruction::Create(4, &destroyed[4]));
v.push_back(DataWithDestruction::Create(5, &destroyed[5]));
int expect_destroyed[6] = {0};
// Removing more than one thing that matches.
auto is_three = [](DataWithDestruction* d) { return d->data() == 3; };
v.erase(v.remove_if(is_three), v.end());
EXPECT_EQ(4u, v.size());
expect_destroyed[2]++;
expect_destroyed[3]++;
for (size_t i = 0; i < arraysize(destroyed); ++i)
EXPECT_EQ(expect_destroyed[i], destroyed[i]) << i;
{
int expect_data[4] = {1, 2, 4, 5};
for (size_t i = 0; i < arraysize(expect_data); ++i)
EXPECT_EQ(expect_data[i], v[i]->data()) << i;
}
// Removing from the back of the vector.
auto is_five = [](DataWithDestruction* d) { return d->data() == 5; };
v.erase(v.remove_if(is_five), v.end());
EXPECT_EQ(3u, v.size());
expect_destroyed[5]++;
for (size_t i = 0; i < arraysize(destroyed); ++i)
EXPECT_EQ(expect_destroyed[i], destroyed[i]) << i;
{
int expect_data[3] = {1, 2, 4};
for (size_t i = 0; i < arraysize(expect_data); ++i)
EXPECT_EQ(expect_data[i], v[i]->data()) << i;
}
// Removing from the front of the vector.
auto is_one = [](DataWithDestruction* d) { return d->data() == 1; };
v.erase(v.remove_if(is_one), v.end());
EXPECT_EQ(2u, v.size());
expect_destroyed[0]++;
for (size_t i = 0; i < arraysize(destroyed); ++i)
EXPECT_EQ(expect_destroyed[i], destroyed[i]) << i;
{
int expect_data[2] = {2, 4};
for (size_t i = 0; i < arraysize(expect_data); ++i)
EXPECT_EQ(expect_data[i], v[i]->data()) << i;
}
// Removing things that aren't in the vector does nothing.
v.erase(v.remove_if(is_one), v.end());
EXPECT_EQ(2u, v.size());
for (size_t i = 0; i < arraysize(destroyed); ++i)
EXPECT_EQ(expect_destroyed[i], destroyed[i]) << i;
{
int expect_data[2] = {2, 4};
for (size_t i = 0; i < arraysize(expect_data); ++i)
EXPECT_EQ(expect_data[i], v[i]->data()) << i;
}
}
} // namespace
} // namespace cc
| 29.205405 | 80 | 0.643902 | kjthegod |
7b9e10ab1ad581b173f46315189e82526dcb0bdb | 10,190 | cpp | C++ | tests/src/json_stream_reader_tests.cpp | Cebtenzzre/jsoncons | 2301edbad93265a4f64c74609bc944cd279eb2a7 | [
"BSL-1.0"
] | null | null | null | tests/src/json_stream_reader_tests.cpp | Cebtenzzre/jsoncons | 2301edbad93265a4f64c74609bc944cd279eb2a7 | [
"BSL-1.0"
] | null | null | null | tests/src/json_stream_reader_tests.cpp | Cebtenzzre/jsoncons | 2301edbad93265a4f64c74609bc944cd279eb2a7 | [
"BSL-1.0"
] | null | null | null | // Copyright 2018 Daniel Parker
// Distributed under Boost license
#include <catch/catch.hpp>
#include <jsoncons/json.hpp>
#include <jsoncons/json_serializer.hpp>
#include <jsoncons/json_stream_reader.hpp>
#include <sstream>
#include <vector>
#include <utility>
#include <ctime>
using namespace jsoncons;
TEST_CASE("json_stream_reader string_value test")
{
std::string s = R"("Tom")";
std::istringstream is(s);
json_stream_reader reader(is);
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::string_value);
CHECK(reader.current().as<std::string>() == std::string("Tom"));
CHECK(reader.current().as<jsoncons::string_view>() == jsoncons::string_view("Tom"));
reader.next();
CHECK(reader.done());
}
TEST_CASE("json_stream_reader string_value as<int> test")
{
std::string s = R"("-100")";
std::istringstream is(s);
json_stream_reader reader(is);
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::string_value);
CHECK(reader.current().as<int>() == -100);
reader.next();
CHECK(reader.done());
}
TEST_CASE("json_stream_reader string_value as<unsigned> test")
{
std::string s = R"("100")";
std::istringstream is(s);
json_stream_reader reader(is);
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::string_value);
CHECK(reader.current().as<int>() == 100);
CHECK(reader.current().as<unsigned>() == 100);
reader.next();
CHECK(reader.done());
}
TEST_CASE("json_stream_reader null_value test")
{
std::string s = "null";
std::istringstream is(s);
json_stream_reader reader(is);
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::null_value);
reader.next();
CHECK(reader.done());
}
TEST_CASE("json_stream_reader bool_value test")
{
std::string s = "false";
std::istringstream is(s);
json_stream_reader reader(is);
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::bool_value);
reader.next();
CHECK(reader.done());
}
TEST_CASE("json_stream_reader int64_value test")
{
std::string s = "-100";
std::istringstream is(s);
json_stream_reader reader(is);
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::int64_value);
CHECK(reader.current().as<int>() == -100);
reader.next();
CHECK(reader.done());
}
TEST_CASE("json_stream_reader uint64_value test")
{
std::string s = "100";
std::istringstream is(s);
json_stream_reader reader(is);
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::uint64_value);
CHECK(reader.current().as<int>() == 100);
CHECK(reader.current().as<unsigned>() == 100);
reader.next();
CHECK(reader.done());
}
TEST_CASE("json_stream_reader bignum_value test")
{
std::string s = "-18446744073709551617";
std::istringstream is(s);
json_stream_reader reader(is);
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::bignum_value);
reader.next();
CHECK(reader.done());
}
TEST_CASE("json_stream_reader double_value test")
{
std::string s = "100.0";
std::istringstream is(s);
json_stream_reader reader(is);
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::double_value);
reader.next();
CHECK(reader.done());
}
TEST_CASE("json_stream_reader array_value test")
{
std::string s = R"(
[
{
"enrollmentNo" : 100,
"firstName" : "Tom",
"lastName" : "Cochrane",
"mark" : 55
},
{
"enrollmentNo" : 101,
"firstName" : "Catherine",
"lastName" : "Smith",
"mark" : 95},
{
"enrollmentNo" : 102,
"firstName" : "William",
"lastName" : "Skeleton",
"mark" : 60
}
]
)";
std::istringstream is(s);
json_stream_reader reader(is);
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::begin_array);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::begin_object);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::uint64_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::string_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::string_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::uint64_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::end_object);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::begin_object);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::uint64_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::string_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::string_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::uint64_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::end_object);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::begin_object);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::uint64_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::string_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::string_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::uint64_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::end_object);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::end_array);
reader.next();
CHECK(reader.done());
}
TEST_CASE("json_stream_reader object_value test")
{
std::string s = R"(
{
"enrollmentNo" : 100,
"firstName" : "Tom",
"lastName" : "Cochrane",
"mark" : 55
},
{
"enrollmentNo" : 101,
"firstName" : "Catherine",
"lastName" : "Smith",
"mark" : 95},
{
"enrollmentNo" : 102,
"firstName" : "William",
"lastName" : "Skeleton",
"mark" : 60
}
)";
std::istringstream is(s);
json_stream_reader reader(is);
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::begin_object);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::uint64_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::string_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::string_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::name);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::uint64_value);
reader.next();
REQUIRE_FALSE(reader.done());
CHECK(reader.current().event_type() == stream_event_type::end_object);
reader.next();
CHECK(reader.done());
}
| 30.972644 | 88 | 0.644259 | Cebtenzzre |
7ba26f7b9490f926b4f5ecd09ba3b14caf49ec07 | 2,457 | cpp | C++ | sumo/src/netimport/vissim/tempstructs/NIVissimVehicleType.cpp | iltempe/osmosi | c0f54ecdbb7c7b5602d587768617d0dc50f1d75d | [
"MIT"
] | null | null | null | sumo/src/netimport/vissim/tempstructs/NIVissimVehicleType.cpp | iltempe/osmosi | c0f54ecdbb7c7b5602d587768617d0dc50f1d75d | [
"MIT"
] | null | null | null | sumo/src/netimport/vissim/tempstructs/NIVissimVehicleType.cpp | iltempe/osmosi | c0f54ecdbb7c7b5602d587768617d0dc50f1d75d | [
"MIT"
] | 2 | 2017-12-14T16:41:59.000Z | 2020-10-16T17:51:27.000Z | /****************************************************************************/
/// @file NIVissimVehicleType.cpp
/// @author Daniel Krajzewicz
/// @date Sept 2002
/// @version $Id$
///
// -------------------
/****************************************************************************/
// SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
// Copyright (C) 2001-2017 DLR (http://www.dlr.de/) and contributors
/****************************************************************************/
//
// This file is part of SUMO.
// SUMO 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.
//
/****************************************************************************/
// ===========================================================================
// included modules
// ===========================================================================
#ifdef _MSC_VER
#include <windows_config.h>
#else
#include <config.h>
#endif
#include "NIVissimVehicleType.h"
NIVissimVehicleType::DictType NIVissimVehicleType::myDict;
NIVissimVehicleType::NIVissimVehicleType(const std::string& name,
const std::string& category, const RGBColor& color)
: myName(name), myCategory(category),
myColor(color) {}
NIVissimVehicleType::~NIVissimVehicleType() {}
bool
NIVissimVehicleType::dictionary(int id, const std::string& name, const std::string& category,
const RGBColor& color) {
NIVissimVehicleType* o = new NIVissimVehicleType(name, category, color);
if (!dictionary(id, o)) {
delete o;
return false;
}
return true;
}
bool
NIVissimVehicleType::dictionary(int id, NIVissimVehicleType* o) {
DictType::iterator i = myDict.find(id);
if (i == myDict.end()) {
myDict[id] = o;
return true;
}
return false;
}
NIVissimVehicleType*
NIVissimVehicleType::dictionary(int id) {
DictType::iterator i = myDict.find(id);
if (i == myDict.end()) {
return 0;
}
return (*i).second;
}
void
NIVissimVehicleType::clearDict() {
for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) {
delete(*i).second;
}
myDict.clear();
}
/****************************************************************************/
| 27.3 | 93 | 0.501425 | iltempe |
7ba2da4ac00956231e3ccac5506bdc31a1cce4f8 | 4,939 | cc | C++ | src/sdk/test/batch_muation_test.cc | cuisonghui/tera | 99a3f16de13dd454a64d64e938fcfeb030674d5f | [
"Apache-2.0",
"BSD-3-Clause"
] | 2,003 | 2015-07-13T08:36:45.000Z | 2022-03-26T02:10:07.000Z | src/sdk/test/batch_muation_test.cc | a1e2w3/tera | dbcd28af792d879d961bf9fc7eb60de81b437646 | [
"Apache-2.0",
"BSD-3-Clause"
] | 981 | 2015-07-14T00:03:24.000Z | 2021-05-10T09:50:01.000Z | src/sdk/test/batch_muation_test.cc | a1e2w3/tera | dbcd28af792d879d961bf9fc7eb60de81b437646 | [
"Apache-2.0",
"BSD-3-Clause"
] | 461 | 2015-07-14T02:53:35.000Z | 2022-03-10T10:31:49.000Z | // Copyright (c) 2015-2018, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: baorenyi@baidu.com
#include <atomic>
#include <iostream>
#include <string>
#include <thread>
#include <memory>
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "sdk/batch_mutation_impl.h"
#include "tera.h"
#include "sdk/sdk_task.h"
#include "sdk/sdk_zk.h"
#include "sdk/table_impl.h"
#include "sdk/test/mock_table.h"
#include "tera.h"
DECLARE_string(tera_coord_type);
namespace tera {
class BatchMutationTest : public ::testing::Test {
public:
BatchMutationTest() : batch_mu_(NULL) {
batch_mu_ = static_cast<BatchMutationImpl*>(OpenTable("batch_mu_test")->NewBatchMutation());
}
virtual ~BatchMutationTest() {}
std::shared_ptr<Table> OpenTable(const std::string& tablename) {
FLAGS_tera_coord_type = "fake_zk";
std::shared_ptr<MockTable> table_(new MockTable(tablename, &thread_pool_));
return table_;
}
BatchMutationImpl* batch_mu_;
common::ThreadPool thread_pool_;
};
TEST_F(BatchMutationTest, Put0) {
batch_mu_->Put("rowkey", "value", 12);
batch_mu_->Put("rowkey", "value1", 22);
EXPECT_EQ(batch_mu_->mu_map_.size(), 1);
EXPECT_EQ(batch_mu_->GetRows().size(), 1);
}
TEST_F(BatchMutationTest, Put1) {
batch_mu_->Put("rowkey", "value", 12);
batch_mu_->Put("rowkey1", "value1", 22);
EXPECT_EQ(batch_mu_->mu_map_.size(), 2);
EXPECT_EQ(batch_mu_->GetRows().size(), 2);
}
TEST_F(BatchMutationTest, Put2) {
batch_mu_->Put("rowkey", "cf", "qu", "value");
batch_mu_->Put("rowkey", "", "qu", "value");
batch_mu_->Put("rowkey2", "cf", "", "value");
batch_mu_->Put("rowkey3", "", "", "value");
batch_mu_->Put("rowkey4", "cf", "qu", "value", 0);
batch_mu_->Put("rowkey5", "cf", "qu", "value", 1);
batch_mu_->Put("rowkey6", "cf", "qu", "value", -1);
EXPECT_EQ(batch_mu_->mu_map_.size(), 6);
EXPECT_EQ(batch_mu_->GetRows().size(), 6);
EXPECT_EQ(batch_mu_->mu_map_["rowkey"].size(), 2);
EXPECT_EQ(batch_mu_->mu_map_["rowkey1"].size(), 0);
}
TEST_F(BatchMutationTest, OtherOps) {
batch_mu_->Add("rowkey", "cf", "qu", 12);
EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().type, RowMutation::kAdd);
batch_mu_->PutIfAbsent("rowkey", "cf", "qu", "value");
EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().type, RowMutation::kPutIfAbsent);
batch_mu_->Append("rowkey", "cf", "qu", "value");
EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().type, RowMutation::kAppend);
batch_mu_->DeleteRow("rowkey");
EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().type, RowMutation::kDeleteRow);
EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().timestamp, kLatestTimestamp);
batch_mu_->DeleteFamily("rowkey", "cf");
EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().type, RowMutation::kDeleteFamily);
EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().timestamp, kLatestTimestamp);
batch_mu_->DeleteColumns("rowkey", "cf", "qu");
EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().type, RowMutation::kDeleteColumns);
EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().timestamp, kLatestTimestamp);
batch_mu_->DeleteColumn("rowkey", "cf", "qu", -1);
EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().type, RowMutation::kDeleteColumn);
EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().timestamp, kLatestTimestamp);
const std::string& huge_str = std::string(1 + (32 << 20), 'h');
batch_mu_->Put(huge_str, "cf", "qu", "v");
EXPECT_EQ(batch_mu_->GetError().GetType(), ErrorCode::kBadParam);
batch_mu_->Put("r", "cf", huge_str, "v");
EXPECT_EQ(batch_mu_->GetError().GetType(), ErrorCode::kBadParam);
batch_mu_->Put("r", "cf", "qu", huge_str);
EXPECT_EQ(batch_mu_->GetError().GetType(), ErrorCode::kBadParam);
}
void MockOpStatCallback(Table* table, SdkTask* task) {
// Nothing to do
}
TEST_F(BatchMutationTest, RunCallback) {
EXPECT_FALSE(batch_mu_->IsAsync());
std::shared_ptr<Table> table = OpenTable("test");
batch_mu_->Prepare(MockOpStatCallback);
EXPECT_TRUE(batch_mu_->on_finish_callback_ != NULL);
EXPECT_TRUE(batch_mu_->start_ts_ > 0);
// set OpStatCallback
batch_mu_->RunCallback();
EXPECT_TRUE(batch_mu_->finish_);
EXPECT_TRUE(batch_mu_->IsFinished());
}
TEST_F(BatchMutationTest, Size) {
EXPECT_EQ(batch_mu_->Size(), 0);
int64_t ts = -1;
batch_mu_->Put("r", "cf", "qu", "v");
EXPECT_EQ(batch_mu_->Size(), 6 + sizeof(ts));
batch_mu_->Put("r", "cf", "qu", "v");
// only calc one rowkey
EXPECT_EQ(batch_mu_->Size(), (6 + sizeof(ts)) * 2 - 1);
batch_mu_->Put("R", "cf", "qu", "v");
EXPECT_EQ(batch_mu_->Size(), (6 + sizeof(ts)) * 3 - 1);
}
TEST_F(BatchMutationTest, GetMutation) {
batch_mu_->Put("r", "cf", "qu", "v");
batch_mu_->Put("r", "cf", "qu1", "v");
batch_mu_->Put("r2", "cf", "qu", "v");
batch_mu_->Put("r3", "cf", "qu", "v");
EXPECT_EQ((batch_mu_->GetMutation("r", 1)).qualifier, "qu1");
}
}
| 33.828767 | 96 | 0.678072 | cuisonghui |
7babe23056c9b996729ed10b7e0de941c3ebd3f5 | 3,523 | cpp | C++ | lib/ipv4addr.cpp | reroman/libreroarp | f269fda1260ff42f688258c95504ded318c5a3a8 | [
"BSD-3-Clause"
] | null | null | null | lib/ipv4addr.cpp | reroman/libreroarp | f269fda1260ff42f688258c95504ded318c5a3a8 | [
"BSD-3-Clause"
] | null | null | null | lib/ipv4addr.cpp | reroman/libreroarp | f269fda1260ff42f688258c95504ded318c5a3a8 | [
"BSD-3-Clause"
] | null | null | null | #include <reroman/ipv4addr.hpp>
#include <stdexcept>
#include <system_error>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
using namespace std;
using namespace reroman;
IPv4Addr::IPv4Addr( uint32_t addr ) noexcept
: data( {addr} ){}
IPv4Addr::IPv4Addr( string addr )
{
setAddr( addr );
}
IPv4Addr::IPv4Addr( struct in_addr addr ) noexcept
: data( addr ){}
IPv4Addr::IPv4Addr( const IPv4Addr &addr ) noexcept
: data( addr.data ){}
string IPv4Addr::toString( void ) const
{
char tmp[INET_ADDRSTRLEN];
inet_ntop( AF_INET, &data, tmp, INET_ADDRSTRLEN );
return string( tmp );
}
bool IPv4Addr::isValidNetmask( void ) const noexcept
{
uint32_t a = ntohl( data.s_addr );
if( !a || (a & 0xff) >= 254 )
return false;
a = ~a;
uint32_t b = a + 1;
return !( b & a );
}
void IPv4Addr::setAddr( string addr )
{
if( !inet_aton( addr.c_str(), &data ) )
throw invalid_argument( addr + " is not a valid IPv4 address" );
}
IPv4Addr IPv4Addr::operator+( int n ) const
{
int64_t tmp = ntohl( data.s_addr );
tmp += n;
if( tmp > 0xffffffff )
throw overflow_error( "IPv4 overflow" );
if( tmp < 0 )
throw underflow_error( "IPv4 underflow" );
return IPv4Addr( htonl( static_cast<uint32_t>(tmp) ) );
}
IPv4Addr IPv4Addr::operator-( int n ) const
{
int64_t tmp = ntohl( data.s_addr );
tmp -= n;
if( tmp > 0xffffffff )
throw overflow_error( "IPv4 overflow" );
if( tmp < 0 )
throw underflow_error( "IPv4 underflow" );
return IPv4Addr( htonl( static_cast<uint32_t>(tmp) ) );
}
IPv4Addr& IPv4Addr::operator++( void )
{
int64_t tmp = ntohl( data.s_addr );
tmp++;
if( tmp > 0xffffffff )
throw overflow_error( "IPv4 overflow" );
data.s_addr = htonl( tmp );
return *this;
}
IPv4Addr IPv4Addr::operator++( int )
{
IPv4Addr res( *this );
int64_t tmp = ntohl( data.s_addr );
tmp++;
if( tmp > 0xffffffff )
throw overflow_error( "IPv4 overflow" );
data.s_addr = htonl( tmp );
return res;
}
IPv4Addr& IPv4Addr::operator--( void )
{
int64_t tmp = ntohl( data.s_addr );
tmp--;
if( tmp < 0 )
throw underflow_error( "IPv4 underflow" );
data.s_addr = htonl( tmp );
return *this;
}
IPv4Addr IPv4Addr::operator--( int )
{
IPv4Addr res( *this );
int64_t tmp = ntohl( data.s_addr );
tmp--;
if( tmp < 0 )
throw underflow_error( "IPv4 underflow" );
data.s_addr = htonl( tmp );
return res;
}
IPv4Addr IPv4Addr::getFromInterface( string ifname )
{
int sockfd;
struct ifreq nic;
if( (sockfd = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 )
throw system_error( errno, generic_category(), "socket" );
if( ifname.size() >= IFNAMSIZ )
ifname.resize( IFNAMSIZ - 1 );
strcpy( nic.ifr_name, ifname.c_str() );
if( ioctl( sockfd, SIOCGIFADDR, &nic ) < 0 ){
close( sockfd );
throw system_error( errno, generic_category(), ifname );
}
IPv4Addr result( ((sockaddr_in*)&nic.ifr_addr)->sin_addr );
close( sockfd );
return result;
}
IPv4Addr IPv4Addr::getNmaskFromInterface( string ifname )
{
int sockfd;
struct ifreq nic;
if( (sockfd = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 )
throw system_error( errno, generic_category(), "socket" );
if( ifname.size() >= IFNAMSIZ )
ifname.resize( IFNAMSIZ - 1 );
strcpy( nic.ifr_name, ifname.c_str() );
if( ioctl( sockfd, SIOCGIFNETMASK, &nic ) < 0 ){
close( sockfd );
throw system_error( errno, generic_category(), ifname );
}
IPv4Addr result( ((sockaddr_in*)&nic.ifr_netmask)->sin_addr );
close( sockfd );
return result;
}
| 20.017045 | 66 | 0.665626 | reroman |
7bb426a4d497cca67c92563cdb64d1d6218a3c3a | 1,337 | cpp | C++ | SPH_transform/SPH_test.cpp | tostathaina/farsight | 7e9d6d15688735f34f7ca272e4e715acd11473ff | [
"Apache-2.0"
] | 8 | 2016-07-22T11:24:19.000Z | 2021-04-10T04:22:31.000Z | SPH_transform/SPH_test.cpp | YanXuHappygela/Farsight | 1711b2a1458c7e035edd21fe0019a1f7d23fcafa | [
"Apache-2.0"
] | null | null | null | SPH_transform/SPH_test.cpp | YanXuHappygela/Farsight | 1711b2a1458c7e035edd21fe0019a1f7d23fcafa | [
"Apache-2.0"
] | 7 | 2016-07-21T07:39:17.000Z | 2020-01-29T02:03:27.000Z | #include "Spherical_Harmonic_transform.h"
#include <fstream>
#include <stdio.h>
std::vector<std::vector<double> > ReadFile(const char *filename);
int main(int argc, char * argv [])
{
std::vector<std::vector<double> > data;
std::cout<<argv [1]<<std::endl;
const char* filename = "949.txt";
data = ReadFile("207.txt");
int L = 20;
SPH_Trasform* sph_trans = new SPH_Trasform();
sph_trans->Initialize(data, L);
sph_trans->Transform();
sph_trans->WriteFile();
return 0;
}
std::vector<std::vector<double> > ReadFile(const char *filename)
{
FILE *fp = fopen(filename,"r");
int num_samples = 0;
int num_features = 0;
if(fp == NULL)
{
fprintf(stderr,"can't open input file %s\n",filename);
exit(1);
}
int n=0;
while(1)
{
int c = fgetc(fp);
switch(c)
{
case '\n':
(num_samples)++;
n++;
if(num_features == 0)num_features = n;
break;
case '\t':
n++;
break;
case EOF:
goto out;
default:
;
}
}
out:
rewind(fp);
std::vector<std::vector<double> > tempdata;
for(int i=0; i<num_samples; i++)
{
std::vector<double > tempvector;
double temp;
for(int j=0; j<num_features; j++)
{
fscanf(fp, "%lf", &temp);
tempvector.push_back(temp);
}
tempdata.push_back(tempvector);
}
std::cout<<"Data file loaded !!!"<<std::endl;
return tempdata;
}
| 17.592105 | 65 | 0.614809 | tostathaina |
7bb4842f206386551cbb595198813881c22b5ce2 | 599 | hpp | C++ | Source/Ilum/Geometry/Mesh/Process/Parameterization.hpp | Chaf-Libraries/Ilum | 83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8 | [
"MIT"
] | 11 | 2022-01-09T05:32:56.000Z | 2022-03-28T06:35:16.000Z | Source/Ilum/Geometry/Mesh/Process/Parameterization.hpp | Chaf-Libraries/Ilum | 83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8 | [
"MIT"
] | null | null | null | Source/Ilum/Geometry/Mesh/Process/Parameterization.hpp | Chaf-Libraries/Ilum | 83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8 | [
"MIT"
] | 1 | 2021-11-20T15:39:03.000Z | 2021-11-20T15:39:03.000Z | #pragma once
#include "IMeshProcess.hpp"
namespace Ilum::geometry
{
class Parameterization : public IMeshProcess
{
public:
enum class TutteWeightType
{
Uniform,
Cotangent,
ShapePreserving
};
static std::pair<std::vector<Vertex>, std::vector<uint32_t>> MinimumSurface(const std::vector<Vertex> &in_vertices, const std::vector<uint32_t> &in_indices);
static std::pair<std::vector<Vertex>, std::vector<uint32_t>> TutteParameterization(const std::vector<Vertex> &in_vertices, const std::vector<uint32_t> &in_indices, TutteWeightType weight_type);
};
} // namespace Ilum::geometry | 28.52381 | 194 | 0.752922 | Chaf-Libraries |
7bb8ee6ab7343c12d49cce4f1ddd761d109e8fab | 687 | hpp | C++ | test/mock/core/runtime/core_factory_mock.hpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | test/mock/core/runtime/core_factory_mock.hpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | test/mock/core/runtime/core_factory_mock.hpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef KAGOME_CORE_FACTORY_MOCK_HPP
#define KAGOME_CORE_FACTORY_MOCK_HPP
#include "runtime/binaryen/core_factory.hpp"
#include <gmock/gmock.h>
namespace kagome::runtime::binaryen {
class CoreFactoryMock : public CoreFactory {
public:
~CoreFactoryMock() override = default;
MOCK_METHOD2(
createWithCode,
std::unique_ptr<Core>(
std::shared_ptr<RuntimeEnvironmentFactory> runtime_env_factory,
std::shared_ptr<WasmProvider> wasm_provider));
};
} // namespace kagome::runtime::binaryen
#endif // KAGOME_CORE_FACTORY_MOCK_HPP
| 23.689655 | 75 | 0.72198 | igor-egorov |