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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b3836fd9bba957a496ea400bae54631ac88acc6a | 1,017 | cpp | C++ | simpleMaxCounter/main.cpp | zlum/simple | b5eaf45ad814ec6a2236828ce2ae78b16193bfc1 | [
"MIT"
] | null | null | null | simpleMaxCounter/main.cpp | zlum/simple | b5eaf45ad814ec6a2236828ce2ae78b16193bfc1 | [
"MIT"
] | null | null | null | simpleMaxCounter/main.cpp | zlum/simple | b5eaf45ad814ec6a2236828ce2ae78b16193bfc1 | [
"MIT"
] | null | null | null | #include <cstdint>
#include <iostream>
#include <string>
using namespace std;
struct Res
{
explicit Res(int size): arr(new int[size]), n(size) {}
~Res() { delete[] arr; }
int* arr = nullptr;
int n = 0;
};
Res* findMax(int a[], int n)
{
if(n == 0) return nullptr;
int max = a[0];
int count = 1;
for(int i = 1; i < n - 1; ++i)
{
if(a[i] > max)
{
max = a[i];
count = 1;
}
else
if(a[i] == max)
{
++count;
}
}
Res* res = new Res(count);
for(int i = 0; i < count; ++i)
{
res->arr[i] = max;
}
return res;
}
int main()
{
int arr[] = {1,10,12,22,34,7,3,34,2};
Res* res = findMax(arr, sizeof(arr) / sizeof(int));
if(res != nullptr)
{
for(int i = 0; i < res->n; ++i)
{
cout << res->arr[i];
if(i < res->n - 1) cout << ", ";
}
cout << endl;
delete res;
}
return 0;
}
| 14.955882 | 58 | 0.410029 | zlum |
b385c5e95c2af92bd65606f96a4d039f08a891e9 | 118 | cpp | C++ | examples/qml-keypad/imports/tests/keypad/tst_keypad.cpp | bstubert/tdd-training-add-ons | c6ee54069ad056f6bb468c23c99b090d034b42a3 | [
"BSD-3-Clause"
] | 1 | 2021-11-25T20:27:19.000Z | 2021-11-25T20:27:19.000Z | examples/qml-keypad/imports/tests/keypad/tst_keypad.cpp | bstubert/tdd-training-add-ons | c6ee54069ad056f6bb468c23c99b090d034b42a3 | [
"BSD-3-Clause"
] | null | null | null | examples/qml-keypad/imports/tests/keypad/tst_keypad.cpp | bstubert/tdd-training-add-ons | c6ee54069ad056f6bb468c23c99b090d034b42a3 | [
"BSD-3-Clause"
] | null | null | null | // Copyright, Burkhard Stubert (burkhard.stubert@embeddeduse.com)
#include <QtQuickTest>
QUICK_TEST_MAIN(QmlKeypad)
| 19.666667 | 65 | 0.805085 | bstubert |
b3873f0356795ff40801a4737dad683a84e5637c | 10,439 | cpp | C++ | test/test_mock_mock.cpp | lingjf/h2unit | 5a55c718bc22ba52bd4500997b2df18939996efa | [
"Apache-2.0"
] | 5 | 2015-03-02T22:29:00.000Z | 2020-06-28T08:52:00.000Z | test/test_mock_mock.cpp | lingjf/h2unit | 5a55c718bc22ba52bd4500997b2df18939996efa | [
"Apache-2.0"
] | 5 | 2019-05-10T02:28:00.000Z | 2021-07-17T00:53:18.000Z | test/test_mock_mock.cpp | lingjf/h2unit | 5a55c718bc22ba52bd4500997b2df18939996efa | [
"Apache-2.0"
] | 5 | 2016-05-25T07:31:16.000Z | 2021-08-29T04:25:18.000Z | #include "../source/h2_unit.cpp"
#include "test_types.hpp"
SUITE(mock function)
{
Case(once)
{
MOCK(foobar2, int(int, const char*)).Once(1, "A").Return(11);
OK(11, foobar2(1, "A"));
}
Case(twice)
{
MOCK(foobar2, int(int, const char*)).Twice(Eq(1), _).Return(11);
OK(11, foobar2(1, "A"));
OK(11, foobar2(1, "BC"));
}
Case(3 times)
{
MOCK(foobar2, int(int, const char*)).Times(3).With(Ge(1), "A").Return(11);
OK(11, foobar2(1, "A"));
OK(11, foobar2(1, "A"));
OK(11, foobar2(1, "A"));
}
Case(any 0)
{
MOCK(foobar2, int(int, const char*)).Any(1, "A");
}
Case(any 1)
{
MOCK(foobar2, int(int, const char*)).Any().With(1, "A").Return(11);
OK(11, foobar2(1, "A"));
}
Case(any 2)
{
MOCK(foobar2, int(int, const char*)).Any().With(1, "A").Return(11);
OK(11, foobar2(1, "A"));
OK(11, foobar2(1, "A"));
}
Case(atleast 2)
{
MOCK(foobar2, int(int, const char*)).Atleast(2).With(1, "A").Return(11);
OK(11, foobar2(1, "A"));
OK(11, foobar2(1, "A"));
}
Case(atleast 3)
{
MOCK(foobar2, int(int, const char*)).Atleast(2).With(1, "A").Return(11);
OK(11, foobar2(1, "A"));
OK(11, foobar2(1, "A"));
OK(11, foobar2(1, "A"));
}
Case(atmost 1)
{
MOCK(foobar2, int(int, const char*)).Atmost(2).With(1, "A").Return(11);
OK(11, foobar2(1, "A"));
}
Case(atmost 2)
{
MOCK(foobar2, int(int, const char*)).Atmost(2).With(1, "A").Return(11);
OK(11, foobar2(1, "A"));
OK(11, foobar2(1, "A"));
}
Case(between)
{
MOCK(foobar2, int(int, const char*)).Between(2, 4).With(1, "A").Return(11);
OK(11, foobar2(1, "A"));
OK(11, foobar2(1, "A"));
}
Case(void return)
{
MOCK(foobar21, void(int& a, char*)).Once(1, (char*)"A");
char t[32] = "A";
int a1 = 1;
foobar21(a1, t);
}
Case(Th0)
{
MOCK(foobar21, void(int& a, char*)).Once().Th0(1);
char t[32] = "";
int a1 = 1;
foobar21(a1, t);
}
Case(Th1)
{
MOCK(foobar21, void(int& a, char*)).Once().Th1((char*)"A");
char t[32] = "A";
int a1 = 1;
foobar21(a1, t);
}
Case(zero parameter)
{
MOCK(foobar22, void()).Once();
foobar22();
}
Case(Is Null Matcher)
{
MOCK(foobar2, int(int, const char*)).Once(1, NULL).Return(11);
OK(11, foobar2(1, NULL));
}
Case(Substr Matcher)
{
MOCK(foobar2, int(int, const char*)).Once(1, Substr("BC")).Return(11);
OK(11, foobar2(1, "ABCD"));
}
Case(Not Matcher)
{
MOCK(foobar2, int(int, const char*)).Once(Not(2), _).Return(11);
OK(11, foobar2(1, "A"));
}
Case(AllOf Matcher)
{
MOCK(foobar2, int(int, const char*)).Once(AllOf(1, Ge(1)), _).Return(11);
OK(11, foobar2(1, "A"));
}
Case(AnyOf Matcher)
{
MOCK(foobar2, int(int, const char*)).Once(AnyOf(Le(1), Gt(2)), _).Return(11);
OK(11, foobar2(1, "A"));
}
Case(NoneOf Matcher)
{
MOCK(foobar2, int(int, const char*)).Once(NoneOf(1, Ge(1)), _).Return(11);
OK(11, foobar2(0, "A"));
}
Case(arguments up to 15)
{
MOCK(foobar16, int(int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int)).Once().Return(11);
OK(11, foobar16(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15));
}
}
SUITE(multi line)
{
Case(1 checkin)
{
MOCK(foobar2, int(int, const char*)).Once(1, "A").Return(11).Once().With(2, "B").Return(22).Twice(3, "C").Return(33);
OK(11, foobar2(1, "A"));
OK(22, foobar2(2, "B"));
OK(33, foobar2(3, "C"));
OK(33, foobar2(3, "C"));
}
Case(2 checkin)
{
MOCK(foobar2, int(int, const char*)).Once(1, "A").Return(11).Twice().With(2, "B").Return(22);
OK(11, foobar2(1, "A"));
OK(22, foobar2(2, "B"));
OK(22, foobar2(2, "B"));
}
}
SUITE(mock greed)
{
Case(greed default true)
{
MOCK(foobar2, int(int, const char*))
// .greed(true) // default is true
.Between(1, 3)
.With(1, "A")
.Return(11)
.Once(1, _)
.Return(22);
OK(11, foobar2(1, "A"));
OK(11, foobar2(1, "A"));
OK(11, foobar2(1, "A"));
OK(22, foobar2(1, "A"));
}
Case(greed false)
{
MOCK(foobar2, int(int, const char*)).greed(false).Between(1, 3).With(1, "A").Return(11).Once(1, _).Return(22);
OK(11, foobar2(1, "A"));
OK(22, foobar2(1, "A"));
}
}
SUITE(mock Return)
{
Case(delegate to origin without Return)
{
MOCK(foobar2, int(int, const char*)).Once(1, "A");
OK(2, foobar2(1, "A"));
}
}
SUITE(mock member function)
{
B_DerivedClass b;
Case(static member function)
{
MOCK(B_DerivedClass::static_f2, const char*(int a, int b)).Once(1, 2).Return("+B.static_f2");
OK("+B.static_f2", B_DerivedClass::static_f2(1, 2));
}
Case(normal member function)
{
MOCK(B_DerivedClass, normal_f2, const char*(int, int)).Once(1, 2).Return("+B.normal_f2");
OK("+B.normal_f2", b.normal_f2(1, 2));
}
Case(const member function)
{
MOCK(B_DerivedClass, const_f, const char*(int)).Once(1, 2).Return("+B.const_f");
OK("+B.const_f", b.const_f(1));
}
Case(noexcept member function)
{
MOCK(B_DerivedClass, noexcept_f, const char*(int)).Once(1, 2).Return("+B.noexcept_f");
OK("+B.noexcept_f", b.noexcept_f(1));
}
Case(const noexcept member function)
{
MOCK(B_DerivedClass, const_noexcept_f, const char*(int)).Once(1, 2).Return("+B.const_noexcept_f");
OK("+B.const_noexcept_f", b.const_noexcept_f(1));
}
Case(overload member function)
{
C_OverrideClass c;
// MOCK(C_OverrideClass, overload_f, const char*()).Once().Return("+C.overload_f0");
// OK("+C.overload_f0", c.overload_f());
MOCK(C_OverrideClass, overload_f, const char*(int, int)).Once(1, 2).Return("+C.overload_f2");
OK("+C.overload_f2", c.overload_f(1, 2));
MOCK(C_OverrideClass, overload_f, const char*(int, int, int)).Once(1, 2, 3).Return("+C.overload_f3");
OK("+C.overload_f3", c.overload_f(1, 2, 3));
}
Case(virtual member function)
{
MOCK(B_DerivedClass, virtual_f2, const char*(int, int)).Once(1, 2).Return("+B.virtual_f2");
OK("+B.virtual_f2", b.virtual_f2(1, 2));
}
#if !defined WIN32
Case(no default constructor)
{
MOCK(D_NoConstructorClass, virtual_f3, const char*(int, int, int)).Once().Return("+D.virtual_f3");
D_NoConstructorClass d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
OK("+D.virtual_f3", d.virtual_f3(1, 2, 3));
}
Case(abstract class)
{
MOCK(A_AbstractClass, virtual_f1, const char*(int)).Once().Return("+A.virtual_f1");
OK("+A.virtual_f1", b.virtual_f1(1));
}
#endif
Case(abstract virtual member function with object)
{
B_DerivedClass b;
OK("A.virtual_f1(1)a", b.virtual_f1(1));
A_AbstractClass* a = dynamic_cast<A_AbstractClass*>(&b);
MOCK(a, A_AbstractClass, virtual_f1, const char*(int)).Once().Return("+A.virtual_f1");
OK("+A.virtual_f1", b.virtual_f1(1));
}
Case(no default constructor with object)
{
D_NoConstructorClass d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
MOCK(d, D_NoConstructorClass, virtual_f3, const char*(int, int, int)).Once().Return("+D.virtual_f3");
OK("+D.virtual_f3", d.virtual_f3(1, 2, 3));
}
}
SUITE(mock template function)
{
Case(function 1 typename)
{
OK(4, foobar4<int>(0));
MOCK(foobar4<int>, int(int a)).Once().Return(-4);
OK(-4, foobar4<int>(0));
}
Case(function 2 typename)
{
OK(5, (foobar5<int, int>(1, 2)));
MOCK((foobar5<int, int>), int(int a, int b)).Once().Return(-5);
OK(-5, (foobar5<int, int>(1, 2)));
}
}
SUITE(mock template member function)
{
Case(member function 1 typename)
{
F_TemplateClass<int> f;
OK("F.static_f1(1)", f.static_f1(1));
OK("F.normal_f1(1)f", f.normal_f1(1));
OK("F.virtual_f1(1)f", f.virtual_f1(1));
MOCK(F_TemplateClass<int>::static_f1, const char*(int a)).Return("+F.static_f1");
OK("+F.static_f1", f.static_f1(0));
MOCK(F_TemplateClass<int>, normal_f1<int>, const char*(int a)).Return("+F.normal_f1");
OK("+F.normal_f1", f.normal_f1(0));
MOCK(F_TemplateClass<int>, virtual_f1, const char*(int a)).Return("+F.virtual_f1");
OK("+F.virtual_f1", f.virtual_f1(0));
}
Case(member function 2 typename)
{
G_TemplateClass<int, int> g;
OK("G.static_f2(1,2)", (g.static_f2<int, int>(1, 2)));
OK("G.normal_f2(1,2)g", (g.normal_f2<int, int>(1, 2)));
OK(Pair("G.virtual_f2", 12.7), (g.virtual_f2<int, int>(1, 2)));
MOCK((G_TemplateClass<int, int>::static_f2<int, int>), const char*(int a, int b)).Return("+G.static_f2");
OK("+G.static_f2", (g.static_f2<int, int>(0, 0)));
MOCK((G_TemplateClass<int, int>), (normal_f2<int, int>), const char*(int a, int b)).Return("+G.normal_f2");
OK("+G.normal_f2", (g.normal_f2<int, int>(0, 0)));
#if !defined WIN32 // Suck when member return Object
MOCK((G_TemplateClass<int, int>), (virtual_f2<int, int>), (std::pair<const char*, double>(int a, int b))).Return(std::make_pair("+G.virtual_f2", 0.0));
OK(Pair("+G.virtual_f2", 0.0), (g.virtual_f2<int, int>(0, 0)));
#endif
}
}
SUITE(mock omit checkin)
{
Case(only With)
{
MOCK(foobar2, int(int, const char*)).With(1, "A").Return(11);
OK(11, foobar2(1, "A"));
OK(11, foobar2(1, "A"));
}
Case(only Th0)
{
MOCK(foobar2, int(int, const char*)).Th0(1).Return(11);
OK(11, foobar2(1, "A"));
OK(11, foobar2(1, "A"));
}
Case(only Return)
{
MOCK(foobar2, int(int, const char*)).Return(22);
OK(22, foobar2(1, "A"));
OK(22, foobar2(1, "A"));
}
Case(only None)
{
MOCK(foobar2, int(int, const char*)).Return(11);
OK(11, foobar2(1, "A"));
OK(11, foobar2(1, "A"));
}
}
SUITE(mock by function name)
{
Todo(time) // nm undefined time()
{
MOCK("time", time_t(time_t*)).Once().Return(11);
OK(42, time(NULL));
}
Todo(time)
{
MOCK(time, time_t(time_t*)).Once().Return((time_t)0);
}
Case(foobar)
{
MOCK("foobar0", int()).Once().Return(1);
OK(1, foobar0());
}
}
| 25.775309 | 157 | 0.552831 | lingjf |
b3894a0c5b152946c1d4783e2ae2e059de07e951 | 615 | cpp | C++ | tests/ThreadTest1/source/main.cpp | markfinal/bam-boost | 655d1aa84f2aa2dad37385e8e8408574475bd962 | [
"BSD-3-Clause"
] | null | null | null | tests/ThreadTest1/source/main.cpp | markfinal/bam-boost | 655d1aa84f2aa2dad37385e8e8408574475bd962 | [
"BSD-3-Clause"
] | null | null | null | tests/ThreadTest1/source/main.cpp | markfinal/bam-boost | 655d1aa84f2aa2dad37385e8e8408574475bd962 | [
"BSD-3-Clause"
] | null | null | null | #include "boost/thread.hpp"
#include <iostream>
struct ThreadFunction
{
void operator()()
{
std::cout << "Worker thread id is " << boost::this_thread::get_id() << std::endl;
boost::this_thread::sleep_for(boost::chrono::seconds(10));
}
};
int main()
{
std::cout << "Main thread id is " << boost::this_thread::get_id() << std::endl;
ThreadFunction callable;
boost::thread thread1 = boost::thread(callable);
boost::thread thread2 = boost::thread(callable);
thread1.join();
thread2.join();
std::cout << "Threads have been joined" << std::endl;
return 0;
}
| 24.6 | 89 | 0.621138 | markfinal |
b38c5d40162417d29e9c1f4c40ed5f73abb180c9 | 4,544 | cpp | C++ | os/fs/iso9660/iso9660Stream.cpp | rvedam/es-operating-system | 32d3e4791c28a5623744800f108d029c40c745fc | [
"Apache-2.0"
] | 2 | 2020-11-30T18:38:20.000Z | 2021-06-07T07:44:03.000Z | os/fs/iso9660/iso9660Stream.cpp | LambdaLord/es-operating-system | 32d3e4791c28a5623744800f108d029c40c745fc | [
"Apache-2.0"
] | 1 | 2019-01-14T03:09:45.000Z | 2019-01-14T03:09:45.000Z | os/fs/iso9660/iso9660Stream.cpp | LambdaLord/es-operating-system | 32d3e4791c28a5623744800f108d029c40c745fc | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2008, 2009 Google Inc.
* Copyright 2006 Nintendo Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string.h>
#include <es.h>
#include <es/formatter.h>
#include "iso9660Stream.h"
Iso9660Stream::
Iso9660Stream(Iso9660FileSystem* fileSystem, Iso9660Stream* parent, u32 offset, u8* record) :
fileSystem(fileSystem), ref(1), cache(0),
parent(parent), offset(offset)
{
if (parent)
{
parent->addRef();
dirLocation = parent->location;
}
else
{
dirLocation = 0;
}
location = LittleEndian::dword(record + DR_Location) + LittleEndian::byte(record + DR_AttributeRecordLength);
location *= fileSystem->bytsPerSec;
size = LittleEndian::dword(record + DR_DataLength);
flags = LittleEndian::byte(record + DR_FileFlags);
dateTime = fileSystem->getTime(record + DR_RecordingDateAndTime);
// XXX interleave
cache = es::Cache::createInstance(this);
fileSystem->add(this);
}
Iso9660Stream::
~Iso9660Stream()
{
if (cache)
{
delete cache;
}
if (parent)
{
parent->release();
dirLocation = parent->location;
}
else
{
dirLocation = 0;
}
fileSystem->remove(this);
}
bool Iso9660Stream::
isRoot()
{
return parent ? false : true;
}
int Iso9660Stream::
hashCode() const
{
return Iso9660FileSystem::hashCode(dirLocation, offset);
}
long long Iso9660Stream::
getPosition()
{
return 0;
}
void Iso9660Stream::
setPosition(long long pos)
{
}
long long Iso9660Stream::
getSize()
{
return this->size;
}
void Iso9660Stream::
setSize(long long newSize)
{
}
int Iso9660Stream::
read(void* dst, int count)
{
return -1;
}
int Iso9660Stream::
read(void* dst, int count, long long offset)
{
if (size <= offset || count <= 0)
{
return 0;
}
if (size - offset < count)
{
count = size - offset;
}
int len;
int n;
for (len = 0; len < count; len += n, offset += n)
{
n = fileSystem->disk->read((u8*) dst + len,
((count - len) + fileSystem->bytsPerSec - 1) & ~(fileSystem->bytsPerSec - 1),
location + offset + len);
if (n <= 0)
{
break;
}
}
return len;
}
int Iso9660Stream::
write(const void* src, int count)
{
return -1;
}
int Iso9660Stream::
write(const void* src, int count, long long offset)
{
return -1;
}
void Iso9660Stream::
flush()
{
}
bool Iso9660Stream::
findNext(es::Stream* dir, u8* record)
{
ASSERT(isDirectory());
while (0 < dir->read(record, 1))
{
if (record[DR_Length] <= DR_FileIdentifier)
{
break;
}
if (dir->read(record + 1, record[DR_Length] - 1) < record[DR_Length] - 1)
{
break;
}
if (record[DR_FileIdentifierLength] == 0)
{
break;
}
if (record[DR_FileIdentifierLength] != 1 ||
record[DR_FileIdentifier] != 0 && record[DR_FileIdentifier] != 1)
{
return true;
}
}
return false;
}
Object* Iso9660Stream::
queryInterface(const char* riid)
{
Object* objectPtr;
if (isDirectory() && strcmp(riid, es::Context::iid()) == 0)
{
objectPtr = static_cast<es::Context*>(this);
}
else if (strcmp(riid, es::File::iid()) == 0)
{
objectPtr = static_cast<es::File*>(this);
}
else if (strcmp(riid, es::Binding::iid()) == 0)
{
objectPtr = static_cast<es::Binding*>(this);
}
else if (strcmp(riid, Object::iid()) == 0)
{
objectPtr = static_cast<es::Stream*>(this);
}
else
{
return NULL;
}
objectPtr->addRef();
return objectPtr;
}
unsigned int Iso9660Stream::
addRef()
{
return ref.addRef();
}
unsigned int Iso9660Stream::
release()
{
unsigned int count = ref.release();
if (count == 0)
{
delete this;
return 0;
}
return count;
}
| 20.106195 | 113 | 0.589349 | rvedam |
b38c6dfebbbd580df954935430776e4395b2235c | 4,106 | cpp | C++ | cplusplus/level2_simple_inference/n_performance/1_multi_process_thread/YOLOV3_coco_detection_4_thread/src/object_detect.cpp | Ascend/samples | 5e060ddf8c502cf0e248ecbe1c8986e95351cbbd | [
"Apache-2.0"
] | 25 | 2020-11-20T09:01:35.000Z | 2022-03-29T10:35:38.000Z | cplusplus/level2_simple_inference/n_performance/1_multi_process_thread/YOLOV3_coco_detection_4_thread/src/object_detect.cpp | Ascend/samples | 5e060ddf8c502cf0e248ecbe1c8986e95351cbbd | [
"Apache-2.0"
] | 5 | 2021-02-28T20:49:37.000Z | 2022-03-04T21:50:27.000Z | cplusplus/level2_simple_inference/n_performance/1_multi_process_thread/YOLOV3_coco_detection_4_thread/src/object_detect.cpp | Ascend/samples | 5e060ddf8c502cf0e248ecbe1c8986e95351cbbd | [
"Apache-2.0"
] | 16 | 2020-12-06T07:26:13.000Z | 2022-03-01T07:51:55.000Z | /**
* Copyright 2020 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.
* File sample_process.cpp
* Description: handle acl resource
*/
#include <iostream>
#include <pthread.h>
#include "acl/acl.h"
#include <time.h>
#include "acllite/AclLiteModel.h"
#include "object_detect.h"
#include "opencv2/opencv.hpp"
using namespace std;
ObjectDetect::ObjectDetect(const char* modelPath, uint32_t modelWidth,
uint32_t modelHeight)
: modelWidth_(modelWidth), modelHeight_(modelHeight), isInited_(false),
imageDataBuf_(nullptr), imageInfoBuf_(nullptr){
imageInfoSize_ = 0;
modelPath_ = modelPath;
}
ObjectDetect::~ObjectDetect() {
DestroyResource();
}
AclLiteError ObjectDetect::CreateInput() {
//Request image data memory for input model
aclError aclRet = aclrtMalloc(&imageDataBuf_, (size_t)(imageDataSize_), ACL_MEM_MALLOC_HUGE_FIRST);
if (aclRet != ACL_SUCCESS) {
ACLLITE_LOG_ERROR("malloc device data buffer failed, aclRet is %d", aclRet);
return ACLLITE_ERROR;
}
//The second input to Yolov3 is the input image width and height parameter
const float imageInfo[4] = {(float)modelWidth_, (float)modelHeight_,
(float)modelWidth_, (float)modelHeight_};
imageInfoSize_ = sizeof(imageInfo);
imageInfoBuf_ = CopyDataToDevice((void *)imageInfo, imageInfoSize_,
runMode_, MEMORY_DEVICE);
if (imageInfoBuf_ == nullptr) {
ACLLITE_LOG_ERROR("Copy image info to device failed");
return ACLLITE_ERROR;
}
AclLiteError ret = model_.CreateInput(imageDataBuf_, imageDataSize_,
imageInfoBuf_, imageInfoSize_);
if (ret != ACLLITE_OK) {
ACLLITE_LOG_ERROR("Create mode input dataset failed");
return ACLLITE_ERROR;
}
return ACLLITE_OK;
}
AclLiteError ObjectDetect::Init() {
//If it is already initialized, it is returned
if (isInited_) {
ACLLITE_LOG_INFO("Classify instance is initied already!");
return ACLLITE_OK;
}
//Gets whether the current application is running on host or Device
AclLiteError ret = aclrtGetRunMode(&runMode_);
if (ret != ACL_SUCCESS) {
ACLLITE_LOG_ERROR("acl get run mode failed");
return ACLLITE_ERROR;
}
//Initializes the model management instance
ret = model_.Init(modelPath_);
if (ret != ACLLITE_OK) {
ACLLITE_LOG_ERROR("Init model failed");
return ACLLITE_ERROR;
}
imageDataSize_ = model_.GetModelInputSize(0);
ret = CreateInput();
if (ret != ACLLITE_OK) {
ACLLITE_LOG_ERROR("Create model input failed");
return ACLLITE_ERROR;
}
isInited_ = true;
return ACLLITE_OK;
}
AclLiteError ObjectDetect::Inference(std::vector<InferenceOutput>& inferenceOutput, cv::Mat& reiszeMat) {
AclLiteError ret = CopyDataToDeviceEx(imageDataBuf_, imageDataSize_,
reiszeMat.ptr<uint8_t>(), imageDataSize_,
runMode_);
if (ret != ACLLITE_OK) {
ACLLITE_LOG_ERROR("Copy resized image data to device failed.");
return ACLLITE_ERROR;
}
//Perform reasoning
ret = model_.Execute(inferenceOutput);
if (ret != ACLLITE_OK) {
ACLLITE_LOG_ERROR("Execute model inference failed");
return ACLLITE_ERROR;
}
ACLLITE_LOG_INFO("Execute model inference success");
return ACLLITE_OK;
}
void ObjectDetect::DestroyResource()
{
model_.DestroyInput();
model_.DestroyResource();
aclrtFree(imageDataBuf_);
aclrtFree(imageInfoBuf_);
}
| 30.87218 | 105 | 0.686313 | Ascend |
b3921df1684fff63cf85db5625a04d78f66bb6e0 | 1,508 | cpp | C++ | CCC/Stage2/02/ccc02s2p1.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | 1 | 2017-10-01T00:51:39.000Z | 2017-10-01T00:51:39.000Z | CCC/Stage2/02/ccc02s2p1.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | null | null | null | CCC/Stage2/02/ccc02s2p1.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
using namespace std;
map<string,int> spam,nonspam,msg;
double check(map<string,int> f1,map<string,int> f2)
{
double top = 0;
double bot1 = 0;
double bot2 = 0;
for (map<string,int>::iterator it=f1.begin(); it!=f1.end(); ++it)
{
top+= it->second*f2[it->first];
bot1+= it->second*it->second;
}
for (map<string,int>::iterator it=f2.begin(); it!=f2.end(); ++it)
bot2+= it->second*it->second;
return top/sqrt(bot1)/sqrt(bot2);
}
int main()
{
int sn,nn,mn;
cin >> sn >> nn >> mn ;
string str;
for(int c=0;c!=sn;c++)
while(getline(cin,str) && str!="ENDMESSAGE")
if(str.size()>=3)
for(int i=0;i!=str.size()-2;i++)
spam[str.substr(i,3)]++;
for(int c=0;c!=nn;c++)
while(getline(cin,str) && str!="ENDMESSAGE")
if(str.size()>=3)
for(int i=0;i!=str.size()-2;i++)
nonspam[str.substr(i,3)]++;
for(int c=0;c!=mn;c++)
{
msg.clear();
while(getline(cin,str) && str!="ENDMESSAGE")
if(str.size()>=3)
for(int i=0;i!=str.size()-2;i++)
msg[str.substr(i,3)]++;
double f1 = check(msg,spam);
double f2 = check(msg,nonspam);
printf("%.5f %.5f\n",f1,f2);
printf("%s\n",f1>f2?"spam":"non-spam");
}
return 0;
} | 23.5625 | 70 | 0.572944 | zzh8829 |
b399de1cd6ee0e66d9a14f91f8c09d8387d0d36e | 587 | cpp | C++ | 牛客/小白月赛/11-C.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 7 | 2019-02-25T13:15:00.000Z | 2021-12-21T22:08:39.000Z | 牛客/小白月赛/11-C.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | null | null | null | 牛客/小白月赛/11-C.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 1 | 2019-04-03T06:12:46.000Z | 2019-04-03T06:12:46.000Z | #include<bits/stdc++.h>
using namespace std;
int n,m,T;
int a[100010];
int b[100010];
int k;
int main() {
scanf("%d%d%d",&n,&m,&T);
for(k=1; k<=T; k++) {
scanf("%d%d",a+k,b+k);
}
for(int i=1; i<=n; i++) {
for(int j=1; j<m; j++) {
//find
for(k=T; k>=1; k--) {
if(a[k]==1 && b[k]==i || a[k]==2 && b[k]==j) {
printf("%d ",k);
break;
}
}
if(k==0)
printf("0 ");
}
//j==m
for(k=T; k>=1; k--) {
if(a[k]==1 && b[k]==i || a[k]==2 && b[k]==m) {
printf("%d",k);
break;
}
}
if(k==0)
printf("0");
printf("\n");
}
return 0;
}
| 15.051282 | 50 | 0.398637 | LauZyHou |
b399fd285905f88ac99223bdc65fbf66a5fa3c2f | 869 | hpp | C++ | engine.hpp | ichristen/pGDS | c6959ea7db0cc01549eb170b7fdc273801735dbc | [
"MIT"
] | null | null | null | engine.hpp | ichristen/pGDS | c6959ea7db0cc01549eb170b7fdc273801735dbc | [
"MIT"
] | null | null | null | engine.hpp | ichristen/pGDS | c6959ea7db0cc01549eb170b7fdc273801735dbc | [
"MIT"
] | null | null | null | #ifndef ENGINE_HPP
#define ENGINE_HPP
#include <stdio.h>
#include <string>
#include <array>
#include <vector>
#include <map>
#ifdef __APPLE__
// #include <OpenGL/OpenGL.h>
// #include <Cocoa/Cocoa.h>
#endif
#ifdef __MINGW32__
#endif
#ifdef __linux__
#endif
#include "window.hpp"
#include "vector.hpp"
#include "device.hpp"
//#include <extern/include/engine.h> // MATLAB engine; it is slightly confusing that this has the same name...
//class WINDOW {
//#ifdef __APPLE__
// NSView* view;
//#endif
//};
class ENGINE {
WINDOW* window = nullptr; // The window that we render to.
// Engine* engine = nullptr; // Our encapsulated MATLAB context.
DEVICE* focus = nullptr; // The device we are looking at.
std::string path; // The current MATLAB path.
ENGINE();
void update();
};
#endif
| 18.891304 | 111 | 0.638665 | ichristen |
b39a35483919cfbd0466862cd87d1f943ef337a6 | 1,839 | cpp | C++ | test/test_simple_enc.cpp | cwxcode/HDR_EXR2MKV | 3b5403cb5789cc7e098c5393bcebf673b1cb123b | [
"BSD-3-Clause"
] | 46 | 2016-07-05T14:55:24.000Z | 2021-12-24T05:10:00.000Z | test/test_simple_enc.cpp | cwxcode/HDR_EXR2MKV | 3b5403cb5789cc7e098c5393bcebf673b1cb123b | [
"BSD-3-Clause"
] | 8 | 2018-05-25T07:36:41.000Z | 2021-04-08T14:27:54.000Z | test/test_simple_enc.cpp | cwxcode/HDR_EXR2MKV | 3b5403cb5789cc7e098c5393bcebf673b1cb123b | [
"BSD-3-Clause"
] | 16 | 2016-05-29T13:39:23.000Z | 2022-02-22T13:53:05.000Z | #include <luma_encoder.h>
#include "exr_interface.h"
#include <string.h>
int main(int argc, char* argv[])
{
if (argc > 1 && !(strcmp(argv[1], "-h") && strcmp(argv[1], "--help")) )
{
printf("Usage: ./test_simple_enc <hdr_frames> <start_frame> <end_frame> <output>\n");
return 1;
}
char *hdrFrames = NULL, *outputFile = NULL;
int startFrame = 1, endFrame = 5;
if (argc > 1)
hdrFrames = argv[1];
if (argc > 2)
startFrame = atoi(argv[2]);
if (argc > 3)
endFrame = atoi(argv[3]);
if (argc > 4)
outputFile = argv[4];
LumaEncoder encoder;
LumaEncoderParams params = encoder.getParams();
params.profile = 2;
params.bitrate = 1000;
params.keyframeInterval = 0;
params.bitDepth = 12;
params.ptfBitDepth = 11;
params.colorBitDepth = 8;
params.lossLess = 0; // --> // 0;
params.quantizerScale = 4;
params.ptf = LumaQuantizer::PTF_PQ;
params.colorSpace = LumaQuantizer::CS_LUV;
// LDR
//params.profile = 0;
//params.bitDepth = 8;
//params.ptfBitDepth = 8;
encoder.setParams(params);
char str[500];
for (int f = startFrame; f <= endFrame; f++)
{
printf("Encoding frame %d.\n", f );
LumaFrame frame;
if (hdrFrames != NULL)
{
sprintf(str, hdrFrames, f);
ExrInterface::readFrame(str, frame);
}
else
ExrInterface::testFrame(frame);
if (!encoder.initialized())
encoder.initialize(outputFile == NULL ? "output.mkv" : outputFile, frame.width, frame.height);
encoder.encode(&frame);
}
encoder.finish();
printf("Encoding finished. %d frames encoded.\n", endFrame-startFrame+1);
return 0;
}
| 24.851351 | 106 | 0.553562 | cwxcode |
b39fe748855d4d54a9ee69a535a5b35f9b54fe66 | 7,702 | hpp | C++ | sdk/packages/dynamixel/gems/registers.hpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 1 | 2020-04-14T13:55:16.000Z | 2020-04-14T13:55:16.000Z | sdk/packages/dynamixel/gems/registers.hpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 4 | 2020-09-25T22:34:29.000Z | 2022-02-09T23:45:12.000Z | sdk/packages/dynamixel/gems/registers.hpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 1 | 2020-07-02T11:51:17.000Z | 2020-07-02T11:51:17.000Z | /*
Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#pragma once
#include <cstdint>
#include <map>
#include "engine/core/byte.hpp"
#include "engine/core/math/utils.hpp"
namespace isaac {
namespace dynamixel {
namespace {
constexpr double kRpmRatio = 60.0;
} // namespace
// Serial port baudrate
// The integer values are mapped to the external dynamixel library
enum class Baudrate {
k4_5M = 7,
k4M = 6,
k3M = 5,
k2M = 4,
k1M = 3,
k115200 = 2,
k57600 = 1,
k9600 = 0,
kInvalid = -1
};
// Dynamixel model
// https://www.trossenrobotics.com/robot-servos
enum class Model {
AX12A = 0,
XM430 = 1,
MX12W = 2,
XC430 = 3,
INVALID = -1
};
// Servo register
struct ServoRegister {
uint16_t address;
uint8_t size;
int min;
int max;
};
// Register keys
enum RegisterKey {
MODEL_NUMBER, // 0
FIRMWARE_VERSION, // 1
DYNAMIXEL_ID, // 2
BAUDRATE, // 3
RETURN_DELAY_TIME, // 4
DRIVE_MODE, // 5
OPERATING_MODE, // 6
PROTOCOL_VERSION, // 7
CW_ANGLE_LIMIT, // 8
CCW_ANGLE_LIMIT, // 9
HOME_POSITION_OFFSET, // 10
TEMPERATURE_LIMIT, // 11
MIN_VOLTAGE_LIMIT, // 12
MAX_VOLTAGE_LIMIT, // 13
MAX_TORQUE, // 14
TORQUE_LIMIT, // 15
STATUS_RETURN_LEVEL, // 16
ALARM_LED, // 17
SHUTDOWN, // 18
TORQUE_ENABLE, // 19
GOAL_POSITION, // 20
MOVING_SPEED, // 21
CURRENT_POSITION, // 22
CURRENT_SPEED, // 23
CURRENT_LOAD, // 24
CURRENT_TEMPERATURE, // 25
CURRENT_VOLTAGE, // 26
ACCELERATION_VALUE_OF_PROFILE, // 27
VELOCITY_VALUE_OF_PROFILE, // 27
TIME_MS, // 28
LED, // 29
MOVING // 30
};
// Number of Dynamixel "position ticks" for a full rotation (from Dynamixel spec sheet)
constexpr int kAngleResolutionXM430 = 4096;
constexpr int kAngleResolutionXC430 = 4096;
constexpr int kAngleResolutionAX12A = 4096;
constexpr int kAngleResolutionMX12W = 4096;
// Rotations per minute per Dynamixel "speed tick" (from Dynamixel spec sheet)
constexpr double kRpmResolutionXM430 = 0.229;
constexpr double kRpmResolutionXC430 = 0.229;
constexpr double kRpmResolutionAX12A = 0.916;
constexpr double kRpmResolutionMX12W = 0.916;
// Hardware status codes (from Dynamixel spec sheet)
constexpr byte kStatusOk = 0x00;
constexpr byte kStatusInputVoltageError = 0x01;
constexpr byte kStatusAngleLimitError = 0x02;
constexpr byte kStatusOverheating = 0x04;
constexpr byte kStatusRangeError = 0x08;
constexpr byte kStatusChecksumError = 0x10;
constexpr byte kStatusOverloaded = 0x20;
constexpr byte kStatusInstructionError = 0x40;
// Max valid moving speed (from Dynamixel spec sheet)
constexpr int kMaxMovingSpeed = 0x3FF;
// Flag to control moving direction (from Dynamixel spec sheet)
constexpr int kMovingSpeedDirectionFlagAX12A = 0x400;
constexpr int kMovingSpeedDirectionFlagMX12W = 0x400;
// Inits registers depending on the Servo Model
// For instance for AX12
// http://emanual.robotis.com/docs/en/dxl/ax/ax-12a/#control-table
std::map<RegisterKey, ServoRegister> InitRegisters(Model model);
// Map enum values to integer values for the external dynamixel library
inline int GetBaudrateValue(Baudrate baudrate) {
switch (baudrate) {
case Baudrate::k4_5M:
return 4'500'000;
case Baudrate::k4M:
return 4'000'000;
case Baudrate::k3M:
return 3'000'000;
case Baudrate::k2M:
return 2'000'000;
case Baudrate::k1M:
return 1'000'000;
case Baudrate::k115200:
return 115'200;
case Baudrate::k57600:
return 57'600;
case Baudrate::k9600:
return 9'600;
case Baudrate::kInvalid:
break;
}
return 0;
}
// Gets protocol for instructions and status packet
inline float GetProtocol(Model model) {
switch (model) {
case Model::AX12A:
return 1.0;
case Model::MX12W:
return 1.0;
case Model::XM430:
return 2.0;
case Model::XC430:
return 2.0;
case Model::INVALID:
break;
}
return 0.0;
}
// Gets Angle value depending on motor model
inline int GetAngleResolution(Model model) {
switch (model) {
case Model::AX12A:
return kAngleResolutionAX12A;
case Model::MX12W:
return kAngleResolutionMX12W;
case Model::XM430:
return kAngleResolutionXM430;
case Model::XC430:
return kRpmResolutionXC430;
case Model::INVALID:
break;
}
return 0;
}
// Gets RPM value depending on motor model
inline double GetRpmResolution(Model model) {
switch (model) {
case Model::AX12A:
return kRpmResolutionAX12A;
case Model::MX12W:
return kRpmResolutionMX12W;
case Model::XM430:
return kRpmResolutionXM430;
case Model::XC430:
return kRpmResolutionXM430;
case Model::INVALID:
break;
}
return 0.0;
}
// Converts a dynamixel joint position to the corresponding angle in radians.
inline double TicksToAngle(Model model, int position_ticks) {
const int angle_resolution = GetAngleResolution(model);
const double factor = TwoPi<double> / static_cast<double>(angle_resolution);
return factor * static_cast<double>(position_ticks);
}
// Inverse of TicksToAngle
inline int AngleToTicks(Model model, double angle) {
const double factor = static_cast<double>(GetAngleResolution(model)) / TwoPi<double>;
return static_cast<int>(factor * WrapTwoPi(angle));
}
// Converts a dynamixel joint speed to the corresponding angular speed in radians per second.
inline double TicksToAngularSpeed(Model model, int speed_ticks) {
const double factor = (GetRpmResolution(model) * TwoPi<double>) / kRpmRatio;
switch (model) {
case Model::AX12A:
if (speed_ticks & kMovingSpeedDirectionFlagAX12A) {
speed_ticks = kMovingSpeedDirectionFlagAX12A - speed_ticks;
}
break;
case Model::MX12W:
if (speed_ticks & kMovingSpeedDirectionFlagMX12W) {
speed_ticks = kMovingSpeedDirectionFlagMX12W - speed_ticks;
}
break;
default:
break;
}
return factor * static_cast<double>(speed_ticks);
}
// Depending on the dynamixel model the negative value is stored differently. This option computes
// the correct negative value associated to `value` depending on the dynamixel model.
inline void ReverseValue(Model model, int& value) {
switch (model) {
case Model::AX12A:
value |= kMovingSpeedDirectionFlagAX12A;
return;
case Model::MX12W:
value |= kMovingSpeedDirectionFlagMX12W;
return;
default:
value = -value;
}
}
// Inverse of TicksToSpeed
inline int AngularSpeedToTicks(Model model, double angular_speed) {
const double factor = kRpmRatio / (GetRpmResolution(model) * TwoPi<double>);
int ticks = std::min(kMaxMovingSpeed, static_cast<int>(factor * std::abs(angular_speed)));
if (angular_speed < 0) { ReverseValue(model, ticks); }
return ticks;
}
} // namespace dynamixel
} // namespace isaac
| 29.737452 | 98 | 0.664762 | ddr95070 |
b3a42bde03db67b2845476db5e55ba0ba41e6ad2 | 230 | hpp | C++ | engine/include/engine/Serializable.hpp | kkitsune/GoblinEngine | f69a82b13b418391554f1aeb8957f445352184b6 | [
"MIT"
] | 9 | 2016-02-04T16:42:31.000Z | 2016-12-05T04:34:03.000Z | engine/include/engine/Serializable.hpp | kkitsune/GoblinEngine | f69a82b13b418391554f1aeb8957f445352184b6 | [
"MIT"
] | null | null | null | engine/include/engine/Serializable.hpp | kkitsune/GoblinEngine | f69a82b13b418391554f1aeb8957f445352184b6 | [
"MIT"
] | null | null | null | #pragma once
#include <json.hpp>
#include <ABI.h>
using Json = nlohmann::basic_json<>;
class E_ABI(engine) Serializable
{
public:
virtual ~Serializable()
{}
virtual Json save() = 0;
virtual void load(Json const&) = 0;
};
| 12.777778 | 36 | 0.678261 | kkitsune |
b3a7acbb2b12389223b884089ce1ec21b6a26c6b | 978 | cpp | C++ | naive_simulation_works/systemc_for_dummies/four_bit_adder/main.cpp | VSPhaneendraPaluri/pvsdrudgeworks | 5827f45567eecbcf0bb606de6adb1fb94fe2d8c6 | [
"MIT"
] | null | null | null | naive_simulation_works/systemc_for_dummies/four_bit_adder/main.cpp | VSPhaneendraPaluri/pvsdrudgeworks | 5827f45567eecbcf0bb606de6adb1fb94fe2d8c6 | [
"MIT"
] | null | null | null | naive_simulation_works/systemc_for_dummies/four_bit_adder/main.cpp | VSPhaneendraPaluri/pvsdrudgeworks | 5827f45567eecbcf0bb606de6adb1fb94fe2d8c6 | [
"MIT"
] | null | null | null | #include <systemc.h>
#include "Four_Bit_Adder.h"
#include "MyTestBenchDriver.h"
#include "MyTestBenchMonitor.h"
int sc_main(int sc_argc, char* sc_argv[])
{
sc_signal<sc_lv<1> > pb_a[4], pb_b[4], pb_z[5];
int i = 0;
Four_Bit_Adder MyAdder("MyAdder");
for(i=0; i < 4; i++)
{
MyAdder.a[i](pb_a[i]);
MyAdder.b[i](pb_b[i]);
MyAdder.z[i](pb_z[i]);
cout << "Instantiated MyAdder : " << i << endl;
}
MyAdder.z[4](pb_z[4]);
MyTestBenchDriver MyTBDriver("MyTBDriver");
for(i=0; i < 4; i++)
{
MyTBDriver.TBD_a[i](pb_a[i]);
MyTBDriver.TBD_b[i](pb_b[i]);
cout << "Instantiated MyTestBenchDriver : " << i << endl;
}
MyTestBenchMonitor MyTBMonitor("MyTBMonitor");
for(i=0; i < 4; i++)
{
MyTBMonitor.TBM_a[i](pb_a[i]);
MyTBMonitor.TBM_b[i](pb_b[i]);
MyTBMonitor.TBM_z[i](pb_z[i]);
cout << "Instantiated MyTestBenchMonitor : " << i << endl;
}
MyTBMonitor.TBM_z[4](pb_z[4]);
sc_set_time_resolution(1, SC_NS);
sc_start(60.0, SC_NS);
return 0;
}
| 21.26087 | 60 | 0.639059 | VSPhaneendraPaluri |
b3aecb9d7320b9ae30e0550e265e2bff6d69fe20 | 6,653 | cpp | C++ | connectors/dds4ccm/tests/LateBinding/ReadGet/Receiver/RG_LateBinding_Receiver_exec.cpp | qinwang13/CIAO | e69add1b5da8e9602bcc85d581ecbf1bd41c49a3 | [
"DOC"
] | 10 | 2016-07-20T00:55:50.000Z | 2020-10-04T19:07:10.000Z | connectors/dds4ccm/tests/LateBinding/ReadGet/Receiver/RG_LateBinding_Receiver_exec.cpp | qinwang13/CIAO | e69add1b5da8e9602bcc85d581ecbf1bd41c49a3 | [
"DOC"
] | 13 | 2016-09-27T14:08:27.000Z | 2020-11-11T10:45:56.000Z | connectors/dds4ccm/tests/LateBinding/ReadGet/Receiver/RG_LateBinding_Receiver_exec.cpp | qinwang13/CIAO | e69add1b5da8e9602bcc85d581ecbf1bd41c49a3 | [
"DOC"
] | 12 | 2016-04-20T09:57:02.000Z | 2021-12-24T17:23:45.000Z | // -*- C++ -*-
/**
* Code generated by the The ACE ORB (TAO) IDL Compiler v1.8.2
* TAO and the TAO IDL Compiler have been developed by:
* Center for Distributed Object Computing
* Washington University
* St. Louis, MO
* USA
* http://www.cs.wustl.edu/~schmidt/doc-center.html
* and
* Distributed Object Computing Laboratory
* University of California at Irvine
* Irvine, CA
* USA
* and
* Institute for Software Integrated Systems
* Vanderbilt University
* Nashville, TN
* USA
* http://www.isis.vanderbilt.edu/
*
* Information about TAO is available at:
* http://www.dre.vanderbilt.edu/~schmidt/TAO.html
**/
#include "RG_LateBinding_Receiver_exec.h"
#include "RG_LateBinding_Receiver_impl.h"
#include "tao/ORB_Core.h"
#include "ace/Reactor.h"
namespace CIAO_RG_LateBinding_Receiver_Impl
{
/**
* Facet Executor Implementation Class: info_get_status_exec_i
*/
info_get_status_exec_i::info_get_status_exec_i (
::RG_LateBinding::CCM_Receiver_Context_ptr ctx)
: ciao_context_ (
::RG_LateBinding::CCM_Receiver_Context::_duplicate (ctx))
{
}
info_get_status_exec_i::~info_get_status_exec_i (void)
{
}
// Operations from ::CCM_DDS::PortStatusListener
void
info_get_status_exec_i::on_requested_deadline_missed (::DDS::DataReader_ptr /* the_reader */,
const ::DDS::RequestedDeadlineMissedStatus & /* status */)
{
/* Your code here. */
}
void
info_get_status_exec_i::on_sample_lost (::DDS::DataReader_ptr /* the_reader */,
const ::DDS::SampleLostStatus & /* status */)
{
/* Your code here. */
}
/**
* Facet Executor Implementation Class: info_read_status_exec_i
*/
info_read_status_exec_i::info_read_status_exec_i (
::RG_LateBinding::CCM_Receiver_Context_ptr ctx)
: ciao_context_ (
::RG_LateBinding::CCM_Receiver_Context::_duplicate (ctx))
{
}
info_read_status_exec_i::~info_read_status_exec_i (void)
{
}
// Operations from ::CCM_DDS::PortStatusListener
void
info_read_status_exec_i::on_requested_deadline_missed (::DDS::DataReader_ptr /* the_reader */,
const ::DDS::RequestedDeadlineMissedStatus & /* status */)
{
/* Your code here. */
}
void
info_read_status_exec_i::on_sample_lost (::DDS::DataReader_ptr /* the_reader */,
const ::DDS::SampleLostStatus & /* status */)
{
/* Your code here. */
}
/**
* Facet Executor Implementation Class: reader_start_exec_i
*/
reader_start_exec_i::reader_start_exec_i (
::RG_LateBinding::CCM_Receiver_Context_ptr ctx,
Receiver_exec_i &callback)
: ciao_context_ (
::RG_LateBinding::CCM_Receiver_Context::_duplicate (ctx))
, callback_ (callback)
{
}
reader_start_exec_i::~reader_start_exec_i (void)
{
}
// Operations from ::ReaderStarter
void
reader_start_exec_i::start_read (void)
{
this->callback_.start_read ();
}
void
reader_start_exec_i::set_reader_properties (::CORBA::UShort nr_keys,
::CORBA::UShort nr_iterations)
{
this->callback_.keys (nr_keys);
this->callback_.iterations (nr_iterations);
}
/**
* Component Executor Implementation Class: Receiver_exec_i
*/
Receiver_exec_i::Receiver_exec_i (void)
: impl_ (0)
, keys_ (5)
, iterations_ (0)
{
}
Receiver_exec_i::~Receiver_exec_i (void)
{
delete this->impl_;
}
// Supported operations and attributes.
void
Receiver_exec_i::start_read (void)
{
ACE_NEW_THROW_EX (this->impl_,
RG_LateBinding_Receiver_impl (
this->ciao_context_.in (),
this->iterations_,
this->keys_),
::CORBA::INTERNAL ());
this->impl_->start ();
}
void
Receiver_exec_i::keys (::CORBA::UShort keys)
{
this->keys_ = keys;
}
void
Receiver_exec_i::iterations (::CORBA::UShort iterations)
{
this->iterations_ = iterations;
}
// Component attributes and port operations.
::CCM_DDS::CCM_PortStatusListener_ptr
Receiver_exec_i::get_info_get_status (void)
{
if ( ::CORBA::is_nil (this->ciao_info_get_status_.in ()))
{
info_get_status_exec_i *tmp = 0;
ACE_NEW_RETURN (
tmp,
info_get_status_exec_i (
this->ciao_context_.in ()),
::CCM_DDS::CCM_PortStatusListener::_nil ());
this->ciao_info_get_status_ = tmp;
}
return
::CCM_DDS::CCM_PortStatusListener::_duplicate (
this->ciao_info_get_status_.in ());
}
::CCM_DDS::CCM_PortStatusListener_ptr
Receiver_exec_i::get_info_read_status (void)
{
if ( ::CORBA::is_nil (this->ciao_info_read_status_.in ()))
{
info_read_status_exec_i *tmp = 0;
ACE_NEW_RETURN (
tmp,
info_read_status_exec_i (
this->ciao_context_.in ()),
::CCM_DDS::CCM_PortStatusListener::_nil ());
this->ciao_info_read_status_ = tmp;
}
return
::CCM_DDS::CCM_PortStatusListener::_duplicate (
this->ciao_info_read_status_.in ());
}
::CCM_ReaderStarter_ptr
Receiver_exec_i::get_start_reading (void)
{
if ( ::CORBA::is_nil (this->ciao_reader_start_.in ()))
{
reader_start_exec_i *tmp = 0;
ACE_NEW_RETURN (
tmp,
reader_start_exec_i (
this->ciao_context_.in (),
*this),
::CCM_ReaderStarter::_nil ());
this->ciao_reader_start_ = tmp;
}
return
::CCM_ReaderStarter::_duplicate (
this->ciao_reader_start_.in ());
}
// Operations from Components::SessionComponent.
void
Receiver_exec_i::set_session_context (
::Components::SessionContext_ptr ctx)
{
this->ciao_context_ =
::RG_LateBinding::CCM_Receiver_Context::_narrow (ctx);
if ( ::CORBA::is_nil (this->ciao_context_.in ()))
{
throw ::CORBA::INTERNAL ();
}
}
void
Receiver_exec_i::configuration_complete (void)
{
/* Your code here. */
}
void
Receiver_exec_i::ccm_activate (void)
{
/* Your code here. */
}
void
Receiver_exec_i::ccm_passivate (void)
{
/* Your code here. */
}
void
Receiver_exec_i::ccm_remove (void)
{
/* Your code here. */
}
extern "C" RECEIVER_EXEC_Export ::Components::EnterpriseComponent_ptr
create_RG_LateBinding_Receiver_Impl (void)
{
::Components::EnterpriseComponent_ptr retval =
::Components::EnterpriseComponent::_nil ();
ACE_NEW_NORETURN (
retval,
Receiver_exec_i);
return retval;
}
}
| 23.34386 | 96 | 0.63881 | qinwang13 |
a2a5e51de7fd35e2aebcddd5162c3c5f867bf381 | 1,348 | cpp | C++ | src_sycl/gen.cpp | frengels/cuda-to-sycl-nbody | 989f01cabb7fa0eceb70b18610e1b8b1e03eb8af | [
"MIT"
] | null | null | null | src_sycl/gen.cpp | frengels/cuda-to-sycl-nbody | 989f01cabb7fa0eceb70b18610e1b8b1e03eb8af | [
"MIT"
] | 3 | 2022-02-02T09:25:33.000Z | 2022-02-17T15:43:48.000Z | src_sycl/gen.cpp | frengels/cuda-to-sycl-nbody | 989f01cabb7fa0eceb70b18610e1b8b1e03eb8af | [
"MIT"
] | 1 | 2022-02-16T17:45:43.000Z | 2022-02-16T17:45:43.000Z | #include "gen.hpp"
#include <random>
const float PI = 3.14159265358979323846;
// Copyright (C) 2016 - 2018 Sarah Le Luron
// Copyright (C) 2022 Codeplay Software Limited
using namespace std;
mt19937 rng;
uniform_real_distribution<> dis(0, 1);
glm::vec4 randomParticlePos() {
// Random position on a 'thick disk'
glm::vec4 particle;
float t = dis(rng) * 2 * PI;
float s = dis(rng) * 100;
particle.x = cos(t) * s;
particle.y = sin(t) * s;
particle.z = dis(rng) * 4;
particle.w = 1.f;
return particle;
}
glm::vec4 randomParticleVel(glm::vec4 pos) {
// Initial velocity is 'orbital' velocity from position
glm::vec3 vel = glm::cross(glm::vec3(pos), glm::vec3(0, 0, 1));
float orbital_vel = sqrt(2.0 * glm::length(vel));
vel = glm::normalize(vel) * orbital_vel;
return glm::vec4(vel, 0.0);
}
std::vector<float> genFlareTex(int tex_size) {
std::vector<float> pixels(tex_size * tex_size);
float sigma2 = tex_size / 2.0;
float A = 1.0;
for (int i = 0; i < tex_size; ++i) {
float i1 = i - tex_size / 2;
for (int j = 0; j < tex_size; ++j) {
float j1 = j - tex_size / 2;
// gamma corrected gauss
pixels[i * tex_size + j] = pow(
A * exp(-((i1 * i1) / (2 * sigma2) + (j1 * j1) / (2 * sigma2))),
2.2);
}
}
return pixels;
} | 26.431373 | 77 | 0.588279 | frengels |
a2a8a9372654535bc6a4d7a017816f70de1f23f0 | 334 | cpp | C++ | Bit Manipulation/Clear_all_bits_from_LSB_to_i.cpp | pranav918/DSA-Implementations-Under-Construction | 4127d18b084652ae19959fc4f0da9cfad360df8d | [
"MIT"
] | 1 | 2021-06-18T13:59:38.000Z | 2021-06-18T13:59:38.000Z | Bit Manipulation/Clear_all_bits_from_LSB_to_i.cpp | pranav918/DSA-Implementations-Under-Construction | 4127d18b084652ae19959fc4f0da9cfad360df8d | [
"MIT"
] | null | null | null | Bit Manipulation/Clear_all_bits_from_LSB_to_i.cpp | pranav918/DSA-Implementations-Under-Construction | 4127d18b084652ae19959fc4f0da9cfad360df8d | [
"MIT"
] | null | null | null | /* Author : Pranav Deshmukh
PICT,Pune
Stay Focused!
*/
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, i;
cout << "Enter number followed by ith(from 0) bit place:" << endl;
cin >> n >> i;
int m = ~((1 << (i + 1)) - 1);
n = n & m;
cout << "Answer is " << n << endl;
return 0;
} | 19.647059 | 68 | 0.505988 | pranav918 |
a2a9174a976f58acebc1a7dcbeda149d508fe888 | 2,777 | hpp | C++ | Week2-Data-Structure-I/ZhengQianYi/src/ft/cuckoo_filter.hpp | zhengqianyi/training-plan | 456cce5d124de171fe73f8e108a7c61c08e7a326 | [
"MIT"
] | 1 | 2021-09-29T04:35:36.000Z | 2021-09-29T04:35:36.000Z | Week2-Data-Structure-I/ZhengQianYi/src/ft/cuckoo_filter.hpp | zqyi/training-plan | 456cce5d124de171fe73f8e108a7c61c08e7a326 | [
"MIT"
] | null | null | null | Week2-Data-Structure-I/ZhengQianYi/src/ft/cuckoo_filter.hpp | zqyi/training-plan | 456cce5d124de171fe73f8e108a7c61c08e7a326 | [
"MIT"
] | null | null | null | #ifndef FT_CUCKOO_FILTER_HPP
#define FT_CUCKOO_FILTER_HPP
#include "filter.hpp"
#include "cuckoo_vector.hpp"
#include "hasher.hpp"
#include "Rand_int.hpp"
#include <cmath>
namespace ft
{
class cuckoo_filter : public filter
{
private:
size_t cells_;
size_t fingerprint_size_;
size_t seed_;
cuckoo_vector v_;
HashType hash_name_;
public:
cuckoo_filter(HashType hash_name, size_t cells, size_t fingerprint_size);
using filter::add;
using filter::lookup;
/// Adds an element to the Bloom filter.
virtual void add(std::string const &o) override;
/// Retrieves the count of an element.
virtual bool lookup(std::string const &o) const override;
/// delete
void del(std::string const &o);
std::string get_v() const;
size_t get_cell()
{
return cells_;
}
};
cuckoo_filter ::cuckoo_filter(HashType hash_name, size_t cells, size_t fingerprint_size) : cells_(cells), fingerprint_size_(fingerprint_size), v_(cells, fingerprint_size), hash_name_(hash_name)
{
Rand_int rnd{1, 10000000};
seed_ = rnd();
}
void cuckoo_filter ::add(std::string const &o)
{
size_t fp = hashf(hash_name_, seed_, o) % (int)pow(2, (double)fingerprint_size_);
size_t idx = fp % cells_;
int flag = 0;
auto last_fp = v_.set(flag, idx, fp);
auto max_kick = cells_ * 2;
while (max_kick-- > 0)
{
if (last_fp == 0)
{
break;
}
else
{
//把上次拿出来的再插入
idx = (idx ^ hashf(hash_name_, seed_, last_fp)) % cells_;
flag = (flag + 1) % 2;
last_fp = v_.set(flag, idx, last_fp);
}
}
//空间已满
}
bool cuckoo_filter ::lookup(std::string const &o) const
{
size_t fp = hashf(hash_name_, seed_, o) % (int)pow(2, (double)fingerprint_size_);
size_t idx_0 = fp % cells_;
size_t idx_1 = (idx_0 ^ hashf(hash_name_, seed_, fp)) % cells_;
bool hit = v_.check(0, idx_0);
if (hit == false)
{
hit = v_.check(1, idx_1);
}
return hit;
}
void cuckoo_filter ::del(std::string const &o)
{
size_t fp = hashf(hash_name_, seed_, o) % (int)pow(2, (double)fingerprint_size_);
size_t idx_0 = fp % cells_;
size_t idx_1 = (idx_0 ^ hashf(hash_name_, seed_, fp)) % cells_;
if (v_.del(0, idx_0) == false)
{
v_.del(1, idx_1);
}
}
std::string cuckoo_filter::get_v() const
{
return v_.to_string();
}
} // namespace ft
#endif | 23.141667 | 197 | 0.548073 | zhengqianyi |
a2a927ab4042167ac93bb2ad9b59393818192880 | 131 | cpp | C++ | 200-300/235.cpp | Thomaw/Project-Euler | bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d | [
"MIT"
] | null | null | null | 200-300/235.cpp | Thomaw/Project-Euler | bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d | [
"MIT"
] | null | null | null | 200-300/235.cpp | Thomaw/Project-Euler | bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d | [
"MIT"
] | null | null | null | double s(double r, int n) {
double r2 = Pow(r, n);
double r1 = r - 1;
return 1/r1 * (900 * (r2-1) - 3*n*r2 + 3*(r2-1)/r1);
} | 26.2 | 54 | 0.503817 | Thomaw |
a2a9e9d5d07674bc99b1587d8fa18fa1ab596fc9 | 11,747 | cpp | C++ | cameraPreviewRecorder/jni/video_encoder/libvideo_encoder/soft_encoder/host_gpu_copier.cpp | belieflong/media-dev-android | 6103cdce4725bc9ab1a8d5d085abbdab26a164dc | [
"Apache-2.0"
] | 3 | 2020-11-11T04:08:19.000Z | 2021-04-27T01:07:42.000Z | shortvideolib/src/main/cpp/VideoEngine/video_encoder/soft_encoder/host_gpu_copier.cpp | daimaren/ShortVideo | 06b88ed6667b89b28853e0a791bab63eeea05e27 | [
"Apache-2.0"
] | 2 | 2020-09-22T20:42:16.000Z | 2020-11-11T04:08:57.000Z | shortvideolib/src/main/cpp/VideoEngine/video_encoder/soft_encoder/host_gpu_copier.cpp | daimaren/ShortVideo | 06b88ed6667b89b28853e0a791bab63eeea05e27 | [
"Apache-2.0"
] | 11 | 2020-07-04T03:03:18.000Z | 2022-03-17T10:19:19.000Z | #include "./host_gpu_copier.h"
#define LOG_TAG "HostGPUCopier"
HostGPUCopier::HostGPUCopier() {
mGLProgId = 0;
downloadTex = 0;
this->isRecording = false;
}
HostGPUCopier::~HostGPUCopier() {
}
void HostGPUCopier::copyYUY2Image(GLuint ipTex, byte* yuy2ImageBuffer, int width, int height) {
//将纹理渲染到YUY2格式的数据
// LOGI("width is %d height is %d", width, height);
this->convertYUY2(ipTex, width, height);
//Download image
const unsigned int yuy2Pairs = (width + 1) / 2;
int imageBufferSize = getBufferSizeInBytes(width, height);
this->downloadImageFromTexture(downloadTex, yuy2ImageBuffer, yuy2Pairs, height);
}
void HostGPUCopier::ensureTextureStorage(GLint internalFormat, const unsigned int yuy2Pairs, int height) {
if (!downloadTex) {
glGenTextures(1, &downloadTex);
checkGlError("glGenTextures downloadTex");
glBindTexture(GL_TEXTURE_2D, downloadTex);
checkGlError("glBindTexture downloadTex");
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_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);
} else {
glBindTexture(GL_TEXTURE_2D, downloadTex);
checkGlError("glBindTexture downloadTex");
}
// Specify texture
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, yuy2Pairs, (GLsizei) height, 0, internalFormat, GL_UNSIGNED_BYTE, 0);
}
void HostGPUCopier::convertYUY2(GLuint ipTex, int width, int height) {
prepareConvertToYUY2Program();
const unsigned int yuy2Pairs = (width + 1) / 2;
//GL_OES_required_internalFormat 0x8058 // GL_RGBA8/GL_RGBA8_OES
GLint internalFormat = GL_RGBA;
ensureTextureStorage(internalFormat, yuy2Pairs, height);
glActiveTexture(GL_TEXTURE0);
checkGlError("glActiveTexture GL_TEXTURE0");
glBindTexture(GL_TEXTURE_2D, ipTex);
checkGlError("glBindTexture ipTex");
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Attach YUY2 texture to frame buffer
glBindFramebuffer(GL_FRAMEBUFFER, FBO);
checkGlError("glBindFramebuffer");
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, downloadTex, 0);
checkGlError("glFramebufferTexture2D");
int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
LOGE("GL_FRAMEBUFFER_COMPLETE false\n");
}
/**
* 首先glReadPixels读出来的格式是GL_RGBA,每一个像素是用四个字节表示
* 而我们期望的读出来的是YUY2
* width:4 height:4
* RGBA size : 4 * 4 * 4 = 64
* YUY2 suze : 4 * 4 * 2 = 32
* glReadPixels()
*/
glViewport(0, 0, yuy2Pairs, height);
checkGlError("glViewport...");
// LOGI("glUseProgram mGLProgId is %d", mGLProgId);
glUseProgram(mGLProgId);
checkGlError("glUseProgram mGLProgId...");
// Upload some uniforms if needed
float sPerHalfTexel = (float) (0.5f / (float) width);
// LOGI("sPerHalfTexel is %.8f...", sPerHalfTexel);
glUniform1f(uniformLoc_sPerHalfTexel, sPerHalfTexel);
checkGlError("glUniform1f uniformLoc_sPerHalfTexel...");
if (IS_LUMA_UNKNOW_FLAG) {
GLfloat coefYVec[4] = { (GLfloat) NV_YUY2_R_Y_UNKNOW, (GLfloat) NV_YUY2_G_Y_UNKNOW, (GLfloat) NV_YUY2_B_Y_UNKNOW, (GLfloat) 16 / 255 };
GLfloat coefUVec[4] = { -(GLfloat) NV_YUY2_R_U_UNKNOW, -(GLfloat) NV_YUY2_G_U_UNKNOW, (GLfloat) NV_YUY2_B_U_UNKNOW, (GLfloat) 128 / 255 };
GLfloat coefVVec[4] = { (GLfloat) NV_YUY2_R_V_UNKNOW, -(GLfloat) NV_YUY2_G_V_UNKNOW, -(GLfloat) NV_YUY2_B_V_UNKNOW, (GLfloat) 128 / 255 };
glUniform4fv(uniformLoc_coefY, 1, coefYVec);
checkGlError("glUniform4fv uniformLoc_coefY");
glUniform4fv(uniformLoc_coefU, 1, coefUVec);
checkGlError("glUniform4fv uniformLoc_coefU");
glUniform4fv(uniformLoc_coefV, 1, coefVVec);
checkGlError("glUniform4fv uniformLoc_coefV");
} else if (IS_LUMA_601_FLAG) {
GLfloat coefYVec[4] = { (GLfloat) NV_YUY2_R_Y_601, (GLfloat) NV_YUY2_G_Y_601, (GLfloat) NV_YUY2_B_Y_601, (GLfloat) 16 / 255 };
GLfloat coefUVec[4] = { -(GLfloat) NV_YUY2_R_U_601, -(GLfloat) NV_YUY2_G_U_601, (GLfloat) NV_YUY2_B_U_601, (GLfloat) 128 / 255 };
GLfloat coefVVec[4] = { (GLfloat) NV_YUY2_R_V_601, -(GLfloat) NV_YUY2_G_V_601, -(GLfloat) NV_YUY2_B_V_601, (GLfloat) 128 / 255 };
glUniform4fv(uniformLoc_coefY, 1, coefYVec);
checkGlError("glUniform4fv uniformLoc_coefY");
glUniform4fv(uniformLoc_coefU, 1, coefUVec);
checkGlError("glUniform4fv uniformLoc_coefU");
glUniform4fv(uniformLoc_coefV, 1, coefVVec);
checkGlError("glUniform4fv uniformLoc_coefV");
} else {
GLfloat coefYVec[4] = { (GLfloat) NV_YUY2_R_Y_709, (GLfloat) NV_YUY2_G_Y_709, (GLfloat) NV_YUY2_B_Y_709, (GLfloat) 16 / 255 };
GLfloat coefUVec[4] = { -(GLfloat) NV_YUY2_R_U_709, -(GLfloat) NV_YUY2_G_U_709, (GLfloat) NV_YUY2_B_U_709, (GLfloat) 128 / 255 };
GLfloat coefVVec[4] = { (GLfloat) NV_YUY2_R_V_709, -(GLfloat) NV_YUY2_G_V_709, -(GLfloat) NV_YUY2_B_V_709, (GLfloat) 128 / 255 };
glUniform4fv(uniformLoc_coefY, 1, coefYVec);
checkGlError("glUniform4fv uniformLoc_coefY");
glUniform4fv(uniformLoc_coefU, 1, coefUVec);
checkGlError("glUniform4fv uniformLoc_coefU");
glUniform4fv(uniformLoc_coefV, 1, coefVVec);
checkGlError("glUniform4fv uniformLoc_coefV");
}
bool flipVertically = true;
VertexCoordVec vertices[4];
if (isRecording) {
//正常录制的参数
vertices[0].x = -1;
vertices[0].y = -1;
vertices[0].s = 1;
vertices[0].t = flipVertically ? 1 : 0;
vertices[1].x = 1;
vertices[1].y = -1;
vertices[1].s = 1;
vertices[1].t = flipVertically ? 0 : 1;
vertices[2].x = -1;
vertices[2].y = 1;
vertices[2].s = 0.25;
vertices[2].t = flipVertically ? 1 : 0;
vertices[3].x = 1;
vertices[3].y = 1;
vertices[3].s = 0.25;
vertices[3].t = flipVertically ? 0 : 1;
} else {
//视频合唱的参数
vertices[0].x = -1;
vertices[0].y = 1;
vertices[0].s = 0;
vertices[0].t = flipVertically ? 0 : 1;
vertices[1].x = -1;
vertices[1].y = -1;
vertices[1].s = 0;
vertices[1].t = flipVertically ? 1 : 0;
vertices[2].x = 1;
vertices[2].y = 1;
vertices[2].s = 1.0;
vertices[2].t = flipVertically ? 0 : 1;
vertices[3].x = 1;
vertices[3].y = -1;
vertices[3].s = 1.0;
vertices[3].t = flipVertically ? 1 : 0;
}
//
// Draw array
//
glDisable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glVertexAttribPointer(attrLoc_pos, 2, GL_FLOAT, GL_FALSE, (GLsizei) sizeof(VertexCoordVec), (const GLvoid *) &vertices[0].x);
glEnableVertexAttribArray(attrLoc_pos);
checkGlError("glEnableVertexAttribArray attrLoc_pos...");
glVertexAttribPointer(attrLoc_texCoord, 2, GL_FLOAT, GL_FALSE, (GLsizei) sizeof(VertexCoordVec), (const GLvoid *) &vertices[0].s);
glEnableVertexAttribArray(attrLoc_texCoord);
checkGlError("glEnableVertexAttribArray attrLoc_texCoord...");
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
checkGlError("glDrawArrays...");
glDisableVertexAttribArray(attrLoc_pos);
glDisableVertexAttribArray(attrLoc_texCoord);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glUseProgram(0);
}
void HostGPUCopier::downloadImageFromTexture(GLuint texId, void *imageBuf, unsigned int imageWidth, unsigned int imageHeight) {
// Set texture's min/mag filter to ensure frame buffer completeness
glBindTexture(GL_TEXTURE_2D, texId);
checkGlError("glBindTexture texId");
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindFramebuffer(GL_FRAMEBUFFER, FBO);
checkGlError("glBindFramebuffer");
// Attach texture to frame buffer
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texId, 0);
checkGlError("glFramebufferTexture2D...");
// Download image
glReadPixels(0, 0, (GLsizei) imageWidth, (GLsizei) imageHeight, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid *) imageBuf);
checkGlError("glReadPixels() failed!");
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
int HostGPUCopier::getBufferSizeInBytes(int width, int height) {
return width * height * 2;
}
void HostGPUCopier::destroy() {
if (vertexShader)
glDeleteShader(vertexShader);
if (pixelShader)
glDeleteShader(pixelShader);
if(downloadTex){
glDeleteTextures(1, &downloadTex);
}
if (mGLProgId) {
glDeleteProgram(mGLProgId);
mGLProgId = 0;
}
}
bool HostGPUCopier::prepareConvertToYUY2Program() {
bool ret = true;
if (mGLProgId) {
return ret;
}
mGLProgId = loadProgram(vertexShaderStr, convertToYUY2FragmentShaderStr);
if (!mGLProgId) {
return false;
}
/**
* Query attribute locations and uniform locations
*/
attrLoc_pos = glGetAttribLocation(mGLProgId, "posAttr");
checkGlError("glGetAttribLocation posAttr");
attrLoc_texCoord = glGetAttribLocation(mGLProgId, "texCoordAttr");
checkGlError("glGetAttribLocation texCoordAttr");
mGLUniformTexture = glGetUniformLocation(mGLProgId, "sampler");
checkGlError("glGetAttribLocation sampler");
uniformLoc_coefY = glGetUniformLocation(mGLProgId, "coefY");
uniformLoc_coefU = glGetUniformLocation(mGLProgId, "coefU");
uniformLoc_coefV = glGetUniformLocation(mGLProgId, "coefV");
uniformLoc_sPerHalfTexel = glGetUniformLocation(mGLProgId, "sPerHalfTexel");
glUseProgram(mGLProgId);
/**
* Upload some uniforms
*/
if (IS_LUMA_UNKNOW_FLAG) {
GLfloat coefYVec[4] = { (GLfloat) NV_YUY2_R_Y_UNKNOW, (GLfloat) NV_YUY2_G_Y_UNKNOW, (GLfloat) NV_YUY2_B_Y_UNKNOW, (GLfloat) 16 / 255 };
GLfloat coefUVec[4] = { -(GLfloat) NV_YUY2_R_U_UNKNOW, -(GLfloat) NV_YUY2_G_U_UNKNOW, (GLfloat) NV_YUY2_B_U_UNKNOW, (GLfloat) 128 / 255 };
GLfloat coefVVec[4] = { (GLfloat) NV_YUY2_R_V_UNKNOW, -(GLfloat) NV_YUY2_G_V_UNKNOW, -(GLfloat) NV_YUY2_B_V_UNKNOW, (GLfloat) 128 / 255 };
glUniform4fv(uniformLoc_coefY, 1, coefYVec);
checkGlError("glUniform4fv uniformLoc_coefY");
glUniform4fv(uniformLoc_coefU, 1, coefUVec);
checkGlError("glUniform4fv uniformLoc_coefU");
glUniform4fv(uniformLoc_coefV, 1, coefVVec);
checkGlError("glUniform4fv uniformLoc_coefV");
} else if (IS_LUMA_601_FLAG) {
GLfloat coefYVec[4] = { (GLfloat) NV_YUY2_R_Y_601, (GLfloat) NV_YUY2_G_Y_601, (GLfloat) NV_YUY2_B_Y_601, (GLfloat) 16 / 255 };
GLfloat coefUVec[4] = { -(GLfloat) NV_YUY2_R_U_601, -(GLfloat) NV_YUY2_G_U_601, (GLfloat) NV_YUY2_B_U_601, (GLfloat) 128 / 255 };
GLfloat coefVVec[4] = { (GLfloat) NV_YUY2_R_V_601, -(GLfloat) NV_YUY2_G_V_601, -(GLfloat) NV_YUY2_B_V_601, (GLfloat) 128 / 255 };
glUniform4fv(uniformLoc_coefY, 1, coefYVec);
checkGlError("glUniform4fv uniformLoc_coefY");
glUniform4fv(uniformLoc_coefU, 1, coefUVec);
checkGlError("glUniform4fv uniformLoc_coefU");
glUniform4fv(uniformLoc_coefV, 1, coefVVec);
checkGlError("glUniform4fv uniformLoc_coefV");
} else {
GLfloat coefYVec[4] = { (GLfloat) NV_YUY2_R_Y_709, (GLfloat) NV_YUY2_G_Y_709, (GLfloat) NV_YUY2_B_Y_709, (GLfloat) 16 / 255 };
GLfloat coefUVec[4] = { -(GLfloat) NV_YUY2_R_U_709, -(GLfloat) NV_YUY2_G_U_709, (GLfloat) NV_YUY2_B_U_709, (GLfloat) 128 / 255 };
GLfloat coefVVec[4] = { (GLfloat) NV_YUY2_R_V_709, -(GLfloat) NV_YUY2_G_V_709, -(GLfloat) NV_YUY2_B_V_709, (GLfloat) 128 / 255 };
glUniform4fv(uniformLoc_coefY, 1, coefYVec);
checkGlError("glUniform4fv uniformLoc_coefY");
glUniform4fv(uniformLoc_coefU, 1, coefUVec);
checkGlError("glUniform4fv uniformLoc_coefU");
glUniform4fv(uniformLoc_coefV, 1, coefVVec);
checkGlError("glUniform4fv uniformLoc_coefV");
}
glUseProgram(0);
glGenFramebuffers(1, &FBO);
checkGlError("glGenFramebuffers");
return ret;
}
| 38.514754 | 140 | 0.752362 | belieflong |
a2ac58994f69c2901dd523177a165ed8737edc8d | 667 | cc | C++ | iridium/files/patch-chrome_browser_profiles_chrome__browser__main__extra__parts__profiles.cc | behemoth3663/ports_local | ad57042ae62c907f9340ee696f468fdfeb562a8b | [
"BSD-3-Clause"
] | 1 | 2022-02-08T02:24:08.000Z | 2022-02-08T02:24:08.000Z | iridium/files/patch-chrome_browser_profiles_chrome__browser__main__extra__parts__profiles.cc | behemoth3663/ports_local | ad57042ae62c907f9340ee696f468fdfeb562a8b | [
"BSD-3-Clause"
] | null | null | null | iridium/files/patch-chrome_browser_profiles_chrome__browser__main__extra__parts__profiles.cc | behemoth3663/ports_local | ad57042ae62c907f9340ee696f468fdfeb562a8b | [
"BSD-3-Clause"
] | null | null | null | --- chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc.orig 2020-03-16 18:40:29 UTC
+++ chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc
@@ -295,7 +295,7 @@ void ChromeBrowserMainExtraPartsProfiles::
if (base::FeatureList::IsEnabled(media::kUseMediaHistoryStore))
media_history::MediaHistoryKeyedServiceFactory::GetInstance();
#if defined(OS_WIN) || defined(OS_MACOSX) || \
- (defined(OS_LINUX) && !defined(OS_CHROMEOS))
+ (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || defined(OS_BSD)
metrics::DesktopProfileSessionDurationsServiceFactory::GetInstance();
#endif
ModelTypeStoreServiceFactory::GetInstance();
| 55.583333 | 100 | 0.775112 | behemoth3663 |
a2ad0de602bed30a14fbe3b1da51a6820b913644 | 1,788 | cpp | C++ | Source/FishEngine/ECS.cpp | yushroom/FishEngine-ECS | 99e96f96d30a1cc624a7ffb410a34e418449dd81 | [
"MIT"
] | 10 | 2018-08-28T17:07:06.000Z | 2021-06-19T09:51:27.000Z | Source/FishEngine/ECS.cpp | yushroom/FishEngine-ECS | 99e96f96d30a1cc624a7ffb410a34e418449dd81 | [
"MIT"
] | 1 | 2018-10-25T19:42:10.000Z | 2018-10-30T09:34:05.000Z | Source/FishEngine/ECS.cpp | yushroom/FishEngine-ECS | 99e96f96d30a1cc624a7ffb410a34e418449dd81 | [
"MIT"
] | 5 | 2018-10-25T19:39:26.000Z | 2020-08-09T05:47:57.000Z | #include <FishEngine/ECS/Component.hpp>
#include <FishEngine/ECS/GameObject.hpp>
#include <FishEngine/ECS/Scene.hpp>
#include <FishEngine/ECS/System.hpp>
#include <FishEngine/Components/Transform.hpp>
#include <FishEngine/Serialization/Archive.hpp>
using namespace FishEngine;
GameObject::GameObject(EntityID entityID, Scene* scene) : ID(entityID)
{
}
void Component::Deserialize(InputArchive& archive)
{
archive.AddNVP("m_EntityID", this->entityID);
archive.AddNVP("m_Enabled", this->m_Enabled);
}
void Component::Serialize(OutputArchive& archive) const
{
archive.AddNVP("m_EntityID", this->entityID);
archive.AddNVP("m_Enabled", this->m_Enabled);
}
void Scene::Start()
{
std::sort(m_Systems.begin(), m_Systems.end(), [](System* a, System* b) {
return a->m_Priority < b->m_Priority;
});
for (System* s : m_Systems)
{
s->Start();
}
}
void Scene::Update()
{
for (System* s : m_Systems)
{
if (s->m_Enabled)
s->Update();
}
}
void Scene::PostUpdate()
{
for (System* s : m_Systems)
{
s->PostUpdate();
}
}
GameObject* Scene::CreateGameObject()
{
m_LastEntityID++;
EntityID id = m_LastEntityID;
GameObject* go = new GameObject(id, this);
m_GameObjects[id] = go;
go->m_Transform = GameObjectAddComponent<Transform>(go);
go->m_Scene = this;
m_RootTransforms.push_back(go->GetTransform());
return go;
}
void Scene::AddRootTransform(Transform* t)
{
if (m_Cleaning)
return;
m_RootTransforms.push_back(t);
// t->m_RootOrder = m_RootTransforms.size() - 1;
}
void Scene::RemoveRootTransform(Transform* t)
{
auto pos = std::find(m_RootTransforms.begin(), m_RootTransforms.end(), t);
//assert(pos != m_RootTransforms.end());
if (pos == m_RootTransforms.end()) {
//LogWarning("transform not found");
return;
}
m_RootTransforms.erase(pos);
}
| 20.089888 | 75 | 0.706935 | yushroom |
a2adb990212cd924d9398e7fbe452c0d0d30865c | 6,878 | hxx | C++ | include/knapsack_object.hxx | LPMP/equality-knapsack | 2a44a156aa8cd2bee1757a8b23facdc2be3246e0 | [
"BSD-2-Clause"
] | null | null | null | include/knapsack_object.hxx | LPMP/equality-knapsack | 2a44a156aa8cd2bee1757a8b23facdc2be3246e0 | [
"BSD-2-Clause"
] | null | null | null | include/knapsack_object.hxx | LPMP/equality-knapsack | 2a44a156aa8cd2bee1757a8b23facdc2be3246e0 | [
"BSD-2-Clause"
] | null | null | null | #ifndef EKP_KNAPSACK_OBJECT_HXX
#define EKP_KNAPSACK_OBJECT_HXX
#include <config.hxx>
#include <algorithm>
#include <vector>
#include <numeric>
#include <memory>
#include <stack>
#include <tuple>
namespace ekp {
class ekp_instance {
public:
using node = std::tuple<REAL,REAL,REAL,REAL>;
struct knapsack_item {
REAL cost;
INDEX weight;
INDEX var;
REAL val = 0.0;
bool removed = false;
knapsack_item* next = NULL;
knapsack_item* prev = NULL;
};
template<typename M>
ekp_instance(M& m)
: ekp_instance(m.costs,m.weights,m.b) { }
ekp_instance(std::vector<REAL> c,std::vector<INDEX> w,INDEX b)
: nVars_(c.size()),rhs_(b)
{
items_.reserve(nVars_);
items_ptr_.reserve(nVars_);
removed_.reserve(nVars_);
for(INDEX i=0;i<nVars_;i++){
std::shared_ptr<knapsack_item> item(new knapsack_item);
item->cost = c[i];
item->weight = (REAL) w[i];
item->var = i;
items_.push_back(item.get());
items_ptr_.push_back(item);
}
this->sort();
}
REAL cost(INDEX i){ assert(i<nVars_); return items_[i]->cost; }
INDEX weight(INDEX i){ assert(i<nVars_); return items_[i]->weight; }
INDEX index(INDEX i){ assert(i<nVars_); return items_[i]->var; }
INDEX rhs() const { return rhs_; }
INDEX numberOfVars() const { return nVars_; };
knapsack_item* item(INDEX i){ assert(i<nVars_); return items_ptr_[i].get(); }
knapsack_item* Begin() const { return begin_; }
knapsack_item* End() const { return end_; }
void sort(){
auto f = [&](knapsack_item* i,knapsack_item* j){
REAL iv = i->cost/((REAL) i->weight);
REAL jv = j->cost/((REAL) j->weight);
return iv < jv;
};
std::sort(items_.begin(),items_.end(),f);
this->UpdateList();
}
bool remove(knapsack_item* p){
if( rhs_ < p->val*p->weight ){ return false; }
assert( p->removed == false );
p->removed = true;
removed_.push_back(p);
auto prev = p->prev;
auto next = p->next;
assert( p->val == 0 || p->val == 1 );
rhs_ = rhs_ - p->val*p->weight;
if( prev != NULL ){ prev->next = next; } else { begin_ = next; }
if( next != NULL ){ next->prev = prev; }
return true;
}
bool restore(){
if( removed_.empty() ){
return false;
} else {
auto p = removed_.back();
p->removed = false;
auto prev = p->prev;
auto next = p->next;
assert( p->val == 0 || p->val == 1 );
rhs_ = rhs_ + p->val*p->weight;
if( prev != NULL ){ prev->next = p; } else { begin_ = p; }
if( next != NULL ){ next->prev = p; }
removed_.pop_back();
return true;
}
}
/**
* Create solution vector and calculate cost
**/
void solution(std::vector<REAL>& x){
x.resize(nVars_ + fixed_.size() ,0.0);
cost_ = 0.0;
weight_ = 0.0;
REAL weight_removed = 0.0;
for( auto v : items_ ){
assert( 0.0 <= v->val && v->val <= 1.0 );
x[v->var] = v->val;
cost_ += v->val*v->cost;
weight_ += v->val*((REAL) v->weight);
if( v->removed ){
weight_removed += v->val*((REAL) v->weight);
}
}
assert( weight_ == rhs_ + weight_removed );
assert( rhs_ == 0 || weight_ > 0.0 );
for( auto v : fixed_ ){
assert( 0 <= std::get<0>(v) && std::get<0>(v) < x.size() );
assert( std::get<1>(v) == 0.0 || std::get<1>(v) == 1.0 );
x[std::get<0>(v)] = std::get<1>(v);
cost_ += std::get<1>(v)*std::get<2>(v);
weight_ += std::get<1>(v)*std::get<3>(v);
}
}
bool feasible(REAL bestIntSol = EKPINF){
if( begin_ == end_ ){
assert( begin_ == NULL && end_ == NULL );
INDEX w = 0;
for( auto p : removed_ ){ w += p->weight; }
for( auto p : fixed_ ){ w += std::get<3>(p); }
return w == rhs_;
} else {
INDEX w = 0; INDEX wk = begin_->weight; INDEX wwk = begin_->weight;
INDEX bk = 0; REAL ck = EKPINF; REAL zk = 0;
for( auto item = begin_;item!=end_;item=item->next ){
w += item->weight;
if( item->weight < wk ){ wwk = wk; wk = item->weight; }
if( wk < item->weight && item->weight < wwk ){ wwk = item->weight; }
if( item->cost < ck ){ ck = item->cost; }
}
for( auto p : removed_ ){ zk += p->val*p->cost; }
for( auto p : fixed_ ){ zk += std::get<1>(p)*std::get<2>(p); }
bool temp = true;
if( rhs_ > 0 ){
temp = temp && !(wk < rhs_ && rhs_ < wwk);
temp = temp && !(rhs_ < wk);
temp = temp && ck + zk < bestIntSol;
}
return temp;
}
}
REAL cost(){ assert(cost_ < EKPINF); return cost_; }
REAL weight(){ assert( weight_ > 0.0 ); return weight_; }
private:
void UpdateList(){
auto p0 = items_.begin();
auto p1 = items_.begin(); p1++;
begin_ = *p0;
while ( p1 != items_.end() )
{
(*p0)->next = *p1;
(*p1)->prev = *p0;
p0++;p1++;
}
}
INDEX nVars_;
INDEX rhs_;
REAL cost_ = EKPINF;
REAL weight_ = 0.0;
std::vector<knapsack_item*> items_;
std::vector<std::shared_ptr<knapsack_item>> items_ptr_;
knapsack_item* begin_;
knapsack_item* end_ = NULL;
std::vector<knapsack_item*> removed_;
std::vector<node> fixed_;
};
template<>
ekp_instance::ekp_instance(ekp_instance& ekp)
: rhs_(ekp.rhs()){
items_.reserve(ekp.numberOfVars());
items_ptr_.reserve(ekp.numberOfVars());
knapsack_item* it = ekp.Begin();
knapsack_item* end = ekp.End();
while( it != end ){
std::shared_ptr<knapsack_item> item(new knapsack_item);
item->cost = it->cost;
item->weight = it->weight;
item->var = it->var;
items_.push_back(item.get());
items_ptr_.push_back(item);
it = it->next;
}
fixed_.reserve( ekp.removed_.size() + ekp.fixed_.size() );
for( auto p : ekp.fixed_ ){
fixed_.push_back(p);
}
for( auto p : ekp.removed_ ){
assert( p->val == 0.0 || p->val == 1.0 );
fixed_.push_back(std::make_tuple(p->var,p->val,p->cost,p->weight));
}
nVars_ = items_.size();
if( nVars_ > 0){
removed_.reserve(nVars_);
this->UpdateList();
} else {
begin_ = NULL;
end_ = NULL;
}
assert( fixed_.size() + nVars_ == ekp.numberOfVars() + ekp.fixed_.size() );
}
}
#endif // EKP_KNAPSACK_OBJECT_HXX
| 26.867188 | 82 | 0.508287 | LPMP |
a2b079c7c95647c2bc8228fbb9a17fbaec414162 | 33,132 | hpp | C++ | src/frame_graph/frame_graph.hpp | LaisoEmilio/WispRenderer | 8186856a7b3e1f0a19f6f6c8a9b99d8ccff38572 | [
"Apache-2.0"
] | 203 | 2019-04-26T10:52:22.000Z | 2022-03-15T17:42:44.000Z | src/frame_graph/frame_graph.hpp | LaisoEmilio/WispRenderer | 8186856a7b3e1f0a19f6f6c8a9b99d8ccff38572 | [
"Apache-2.0"
] | 90 | 2018-11-23T09:07:05.000Z | 2019-04-13T10:44:03.000Z | src/frame_graph/frame_graph.hpp | LaisoEmilio/WispRenderer | 8186856a7b3e1f0a19f6f6c8a9b99d8ccff38572 | [
"Apache-2.0"
] | 14 | 2019-06-19T00:52:00.000Z | 2021-02-19T13:44:01.000Z | /*!
* Copyright 2019 Breda University of Applied Sciences and Team Wisp (Viktor Zoutman, Emilio Laiso, Jens Hagen, Meine Zeinstra, Tahar Meijs, Koen Buitenhuis, Niels Brunekreef, Darius Bouma, Florian Schut)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <vector>
#include <string>
#include <type_traits>
#include <stack>
#include <deque>
#include <future>
#include <any>
#include "../util/thread_pool.hpp"
#include "../util/delegate.hpp"
#include "../renderer.hpp"
#include "../platform_independend_structs.hpp"
#include "../settings.hpp"
#include "../d3d12/d3d12_settings.hpp"
#include "../structs.hpp"
#include "../wisprenderer_export.hpp"
#ifndef _DEBUG
#define FG_MAX_PERFORMANCE
#endif
template<typename ...Ts>
std::vector<std::reference_wrapper<const std::type_info>> FG_DEPS() {
return { (typeid(Ts))... };
}
namespace wr
{
enum class RenderTaskType
{
DIRECT,
COMPUTE,
COPY
};
enum class CPUTextureType
{
PIXEL_DATA,
DEPTH_DATA
};
struct CPUTextures
{
std::optional<CPUTexture> pixel_data = std::nullopt;
std::optional<CPUTexture> depth_data = std::nullopt;
};
//! Typedef for the render task handle.
using RenderTaskHandle = std::uint32_t;
// Forward declarations.
class FrameGraph;
/*! Structure that describes a render task */
/*!
All non default initialized member variables should be fully initialized to prevent undifined behaviour.
*/
struct RenderTaskDesc
{
// Typedef the function pointer types to keep the code readable.
using setup_func_t = util::Delegate<void(RenderSystem&, FrameGraph&, RenderTaskHandle, bool)>;
using execute_func_t = util::Delegate<void(RenderSystem&, FrameGraph&, SceneGraph&, RenderTaskHandle)>;
using destroy_func_t = util::Delegate<void(FrameGraph&, RenderTaskHandle, bool)>;
/*! The type of the render task.*/
RenderTaskType m_type = RenderTaskType::DIRECT;
/*! The function pointers for the task.*/
setup_func_t m_setup_func;
execute_func_t m_execute_func;
destroy_func_t m_destroy_func;
/*! The properties for the render target this task renders to. If this is `std::nullopt` no render target will be created. */
std::optional<RenderTargetProperties> m_properties;
bool m_allow_multithreading = true;
};
//! Frame Graph
/*!
The Frame Graph is responsible for managing all tasks the renderer should perform.
The idea is you can add tasks to the scene graph and when you call `RenderSystem::Render` it will run the tasks added.
It will not just run tasks but will also assign command lists and render targets to the tasks.
The Frame Graph is also capable of mulithreaded execution.
It will split the command lists that are allowed to be multithreaded on X amount of threads specified in `settings.hpp`
*/
class FrameGraph
{
// Obtain the type definitions from `RenderTaskDesc` to keep the code readable.
using setup_func_t = RenderTaskDesc::setup_func_t;
using execute_func_t = RenderTaskDesc::execute_func_t;
using destroy_func_t = RenderTaskDesc::destroy_func_t;
public:
//! Constructor.
/*!
This constructor is able to reserve space for render tasks.
This works by calling `std::vector::reserve`.
\param num_reserved_tasks Amount of tasks we should reserve space for.
*/
FrameGraph(std::size_t num_reserved_tasks = 1) :
m_render_system(nullptr),
m_num_tasks(0),
m_thread_pool(new util::ThreadPool(settings::num_frame_graph_threads)),
m_uid(GetFreeUID())
{
// lambda to simplify reserving space.
auto reserve = [num_reserved_tasks](auto v) { v.reserve(num_reserved_tasks); };
// Reserve space for all vectors.
reserve(m_setup_funcs);
reserve(m_execute_funcs);
reserve(m_destroy_funcs);
reserve(m_cmd_lists);
reserve(m_render_targets);
reserve(m_data);
reserve(m_data_type_info);
#ifndef FG_MAX_PERFORMANCE
reserve(m_dependencies);
reserve(m_names);
#endif
reserve(m_types);
reserve(m_rt_properties);
m_settings = decltype(m_settings)(num_reserved_tasks, std::nullopt); // Resizing so I can initialize it with null since this is an optional value.
m_futures.resize(num_reserved_tasks); // std::thread doesn't allow me to reserve memory for the vector. Hence I'm resizing.
}
//! Destructor
/*!
This destructor destroys all the task data and the thread pool.
If you want to reuse the frame graph I recommend calling `FrameGraph::Destroy`
*/
~FrameGraph()
{
delete m_thread_pool;
Destroy();
}
FrameGraph(const FrameGraph&) = delete;
FrameGraph(FrameGraph&&) = delete;
FrameGraph& operator=(const FrameGraph&) = delete;
FrameGraph& operator=(FrameGraph&&) = delete;
//! Setup the render tasks
/*!
Calls all setup function pointers and obtains the required render targets and command lists.
It is recommended to try to avoid calling this during runtime because it can cause stalls if the setup functions are expensive.
\param render_system The render system we want to use for rendering.
*/
inline void Setup(RenderSystem& render_system)
{
bool is_valid = Validate();
if (!is_valid)
{
LOGE("Framegraph validation failed. Aborting setup.");
return;
}
// Resize these vectors since we know the end size already.
m_cmd_lists.resize(m_num_tasks);
m_should_execute.resize(m_num_tasks, true); // All tasks should execute by default.
m_render_targets.resize(m_num_tasks);
m_futures.resize(m_num_tasks);
m_render_system = &render_system;
auto get_command_list_from_render_system = [this](auto type)
{
switch (type)
{
case RenderTaskType::DIRECT:
return m_render_system->GetDirectCommandList(d3d12::settings::num_back_buffers);
case RenderTaskType::COMPUTE:
return m_render_system->GetComputeCommandList(d3d12::settings::num_back_buffers);
case RenderTaskType::COPY:
return m_render_system->GetCopyCommandList(d3d12::settings::num_back_buffers);
default:
LOGC("Tried creating a command list of a type that is not supported.");
return static_cast<wr::CommandList*>(nullptr);
}
};
if constexpr (settings::use_multithreading)
{
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i)
{
// Get the proper command list from the render system.
m_cmd_lists[i] = get_command_list_from_render_system(m_types[i]);
#ifndef FG_MAX_PERFORMANCE
render_system.SetCommandListName(m_cmd_lists[i], m_names[i]);
#endif
// Get a render target from the render system.
if (m_rt_properties[i].has_value())
{
m_render_targets[i] = render_system.GetRenderTarget(m_rt_properties[i].value());
#ifndef FG_MAX_PERFORMANCE
render_system.SetRenderTargetName(m_render_targets[i], m_names[i]);
#endif
}
}
Setup_MT_Impl();
}
else
{
// Itterate over all the tasks.
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i)
{
// Get the proper command list from the render system.
m_cmd_lists[i] = get_command_list_from_render_system(m_types[i]);
#ifndef FG_MAX_PERFORMANCE
render_system.SetCommandListName(m_cmd_lists[i], m_names[i]);
#endif
// Get a render target from the render system.
if (m_rt_properties[i].has_value())
{
m_render_targets[i] = render_system.GetRenderTarget(m_rt_properties[i].value());
#ifndef FG_MAX_PERFORMANCE
render_system.SetRenderTargetName(m_render_targets[i], m_names[i]);
#endif
}
// Call the setup function pointer.
m_setup_funcs[i](render_system, *this, i, false);
}
}
// Finish the setup before continuing for savety.
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i)
{
WaitForCompletion(i);
}
}
/*! Execute all render tasks */
/*!
For every render task call the setup function pointers and tell the render system we started a render task of a certain type.
\param render_system The render system we want to use for rendering.
\param scene_graph The scene graph we want to render.
*/
inline void Execute(SceneGraph& scene_graph)
{
ResetOutputTexture();
// Check if we need to disable some tasks
while (!m_should_execute_change_request.empty())
{
auto front = m_should_execute_change_request.front();
m_should_execute[front.first] = front.second;
m_should_execute_change_request.pop();
}
if constexpr (settings::use_multithreading)
{
Execute_MT_Impl(scene_graph);
}
else
{
Execute_ST_Impl(scene_graph);
}
}
/*! Resize all render tasks */
/*!
This function calls resize all render tasks to a specific width and height.
The width and height parameters should be the output size.
Please note this function calls Destroy than setup with the resize boolean set to true.
*/
inline void Resize(std::uint32_t width, std::uint32_t height)
{
// Make sure the tasks are finished executing
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i)
{
WaitForCompletion(i);
}
// Make sure the GPU has finished with the tasks
m_render_system->WaitForAllPreviousWork();
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i)
{
m_destroy_funcs[i](*this, i, true);
if (m_rt_properties[i].has_value() && !m_rt_properties[i].value().m_is_render_window)
{
m_render_system->ResizeRenderTarget(&m_render_targets[i],
static_cast<std::uint32_t>(std::ceil(width * m_rt_properties[i].value().m_resolution_scale.Get())),
static_cast<std::uint32_t>(std::ceil(height * m_rt_properties[i].value().m_resolution_scale.Get())));
}
m_setup_funcs[i](*m_render_system, *this, i, true);
}
}
/*! Get Resolution scale of specified Render Task */
/*!
Checks if specified RenderTask has valid properties and returns it's resolution scalar.
*/
[[nodiscard]] inline const float GetRenderTargetResolutionScale(RenderTaskHandle handle) const
{
if (m_rt_properties[handle].has_value())
{
return m_rt_properties[handle].value().m_resolution_scale.Get();
}
else
{
LOGW("Error: GetResolutionScale tried accessing invalid data!")
}
return 1.0f;
}
/*! Destroy all tasks */
/*!
Calls all destroy functions and release any allocated data.
*/
void Destroy()
{
// Make sure all tasks finished executing
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i)
{
WaitForCompletion(i);
}
m_render_system->WaitForAllPreviousWork();
// Send the destroy events to the render tasks.
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i)
{
m_destroy_funcs[i](*this, i, false);
}
// Make sure we free the data objects we allocated.
for (auto& data : m_data)
{
data.reset();
}
for (auto& cmd_list : m_cmd_lists)
{
m_render_system->DestroyCommandList(cmd_list);
}
for(decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i)
{
if(m_rt_properties[i].has_value() && !m_rt_properties[i]->m_is_render_window)
{
m_render_system->DestroyRenderTarget(&m_render_targets[i]);
}
}
// Reset all members in the case of the user wanting to reuse this frame graph after `FrameGraph::Destroy`.
m_setup_funcs.clear();
m_execute_funcs.clear();
m_destroy_funcs.clear();
m_cmd_lists.clear();
m_render_targets.clear();
m_data.clear();
m_data_type_info.clear();
m_settings.clear();
#ifndef FG_MAX_PERFORMANCE
m_dependencies.clear();
m_names.clear();
#endif
m_types.clear();
m_rt_properties.clear();
m_futures.clear();
m_num_tasks = 0;
}
/* Stall the current thread until the render task has finished. */
inline void WaitForCompletion(RenderTaskHandle handle)
{
// If we are not allowed to use multithreading let the compiler optimize this away completely.
if constexpr (settings::use_multithreading)
{
if (auto& future = m_futures[handle]; future.valid())
{
future.wait();
}
}
}
/*! Wait for a previous task. */
/*!
This function loops over all tasks and checks whether it has the same type information as the template variable.
If a task was found it waits for it.
If no task is found with the type specified a nullptr will be returned and a error message send to the logging system.
The template parameter should be a Data struct of a the task you want to wait for.
*/
template<typename T>
inline void WaitForPredecessorTask()
{
static_assert(std::is_class<T>::value ||
std::is_floating_point<T>::value ||
std::is_integral<T>::value,
"The template variable should be a class, struct, floating point value or a integral value.");
static_assert(!std::is_pointer<T>::value,
"The template variable type should not be a pointer. Its implicitly converted to a pointer.");
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; i++)
{
if (typeid(T) == m_data_type_info[i])
{
WaitForCompletion(i);
return;
}
}
LOGC("Failed to find predecessor data! Please check your task order.");
return;
}
/*! Get the data of a task. (Modifyable) */
/*!
The template variable is used to specify the type of the data structure.
\param handle The handle to the render task. (Given by the `Setup`, `Execute` and `Destroy` functions)
*/
template<typename T = void*>
[[nodiscard]] inline auto & GetData(RenderTaskHandle handle) const
{
static_assert(std::is_class<T>::value ||
std::is_floating_point<T>::value ||
std::is_integral<T>::value,
"The template variable should be a class, struct, floating point value or a integral value.");
static_assert(!std::is_pointer<T>::value,
"The template variable type should not be a pointer. Its implicitly converted to a pointer.");
return *static_cast<T*>(m_data[handle].get());
}
/*! Get the data of a previously ran task. (Constant) */
/*!
This function loops over all tasks and checks whether it has the same type information as the template variable.
If no task is found with the type specified a nullptr will be returned and a error message send to the logging system.
\param handle The handle to the render task. (Given by the `Setup`, `Execute` and `Destroy` functions)
*/
template<typename T>
[[nodiscard]] inline auto const & GetPredecessorData()
{
static_assert(std::is_class<T>::value ||
std::is_floating_point<T>::value ||
std::is_integral<T>::value,
"The template variable should be a class, struct, floating point value or a integral value.");
static_assert(!std::is_pointer<T>::value,
"The template variable type should not be a pointer. Its implicitly converted to a pointer.");
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; i++)
{
if (typeid(T) == m_data_type_info[i])
{
WaitForCompletion(i);
return *static_cast<T*>(m_data[i].get());
}
}
LOGC("Failed to find predecessor data! Please check your task order.")
return *static_cast<T*>(nullptr);
}
/*! Get the render target of a previously ran task. (Constant) */
/*!
This function loops over all tasks and checks whether it has the same type information as the template variable.
If no task is found with the type specified a nullptr will be returned and a error message send to the logging system.
*/
template<typename T>
[[nodiscard]] inline RenderTarget* GetPredecessorRenderTarget()
{
static_assert(std::is_class<T>::value,
"The template variable should be a class or struct.");
static_assert(!std::is_pointer<T>::value,
"The template variable type should not be a pointer. Its implicitly converted to a pointer.");
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; i++)
{
if (typeid(T) == m_data_type_info[i])
{
WaitForCompletion(i);
return m_render_targets[i];
}
}
LOGC("Failed to find predecessor render target! Please check your task order.");
return nullptr;
}
/*! Get the command list of a task. */
/*!
The template variable allows you to cast the command list to a "non platform independent" different type. For example a `D3D12CommandList`.
\param handle The handle to the render task. (Given by the `Setup`, `Execute` and `Destroy` functions)
*/
template<typename T = CommandList>
[[nodiscard]] inline auto GetCommandList(RenderTaskHandle handle) const
{
static_assert(std::is_class<T>::value || std::is_void<T>::value,
"The template variable should be a void, class or struct.");
static_assert(!std::is_pointer<T>::value,
"The template variable type should not be a pointer. Its implicitly converted to a pointer.");
return static_cast<T*>(m_cmd_lists[handle]);
}
/*! Get the command list of a previously ran task. */
/*!
The function allows the user to get a command list from another render task. These command lists are not meant
to be used as they could be closed or in flight. This function was created only so that ray tracing tasks could get
the heap from the acceleration structure command list.
*/
template<typename T>
[[nodiscard]] inline wr::CommandList* GetPredecessorCommandList()
{
static_assert(std::is_class<T>::value,
"The template variable should be a void, class or struct.");
static_assert(!std::is_pointer<T>::value,
"The template variable type should not be a pointer. Its implicitly converted to a pointer.");
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; i++)
{
if (typeid(T) == m_data_type_info[i])
{
WaitForCompletion(i);
return m_cmd_lists[i];
}
}
LOGC("Failed to find predecessor command list! Please check your task order.");
return nullptr;
}
template<typename T>
[[nodiscard]] std::vector<T*> GetAllCommandLists()
{
std::vector<T*> retval;
retval.reserve(m_num_tasks);
// TODO: Just return the fucking vector as const ref.
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; i++)
{
// Don't return command lists from tasks that don't require to be executed.
if (!m_should_execute[i])
{
continue;
}
WaitForCompletion(i);
retval.push_back(static_cast<T*>(m_cmd_lists[i]));
}
return retval;
}
/*! Get the render target of a task. */
/*!
The template variable allows you to cast the render target to a "non platform independent" different type. For example a `D3D12RenderTarget`.
\param handle The handle to the render task. (Given by the `Setup`, `Execute` and `Destroy` functions)
*/
template<typename T = RenderTarget>
[[nodiscard]] inline auto GetRenderTarget(RenderTaskHandle handle) const
{
static_assert(std::is_class<T>::value || std::is_void<T>::value,
"The template variable should be a void, class or struct.");
static_assert(!std::is_pointer<T>::value,
"The template variable type should not be a pointer. Its implicitly converted to a pointer.");
return static_cast<T*>(m_render_targets[handle]);
}
/*! Check if this frame graph has a task. */
/*!
This checks if the frame graph has the task that has been given as the template variable.
*/
template<typename T>
inline bool HasTask() const
{
return GetHandleFromType<T>().has_value();
}
/*! Validates the frame graph for correctness */
/*!
This function uses the dependencies to check whether the frame graph is constructed properly by the user.
Note: This function only works when `FG_MAX_PERFORMANCE` is defined.
*/
bool Validate()
{
bool result = true;
#ifndef FG_MAX_PERFORMANCE
// Loop over all the tasks.
for (decltype(m_num_tasks) handle = 0; handle < m_num_tasks; ++handle)
{
// Loop over the task's dependencies.
for (auto dependency : m_dependencies[handle])
{
bool found_dependency = false;
// Loop over the predecessor tasks.
for (decltype(m_num_tasks) prev_handle = 0; prev_handle < handle; ++prev_handle)
{
const auto& task_type_info = m_data_type_info[prev_handle].get();
if (task_type_info == dependency.get())
{
found_dependency = true;
}
}
if (!found_dependency)
{
LOGW("Framegraph validation: Failed to find dependency {}", dependency.get().name());
result = false;
}
}
}
#endif
return result;
}
/*! Add a task to the Frame Graph. */
/*!
This creates a new render task based on a description.
The dependencies parameters can contain a list of typeid's of render tasks this task depends on.
You can use the FG_DEPS macro as followed: `AddTask<desc, FG_DEPS(OtherTaskData)>`
\param desc A description of the render task.
*/
template<typename T>
inline void AddTask(RenderTaskDesc& desc, std::wstring const & name, std::vector<std::reference_wrapper<const std::type_info>> dependencies = {})
{
static_assert(std::is_class<T>::value ||
std::is_floating_point<T>::value ||
std::is_integral<T>::value,
"The template variable should be a class, struct, floating point value or a integral value.");
static_assert(std::is_default_constructible<T>::value,
"The template variable is not default constructible or nothrow consructible!");
static_assert(!std::is_pointer<T>::value,
"The template variable type should not be a pointer. Its implicitly converted to a pointer.");
m_setup_funcs.emplace_back(desc.m_setup_func);
m_execute_funcs.emplace_back(desc.m_execute_func);
m_destroy_funcs.emplace_back(desc.m_destroy_func);
#ifndef FG_MAX_PERFORMANCE
m_dependencies.emplace_back(dependencies);
m_names.emplace_back(name);
#endif
m_settings.resize(m_num_tasks + 1ull);
m_types.emplace_back(desc.m_type);
m_rt_properties.emplace_back(desc.m_properties);
m_data.emplace_back(std::make_shared<T>());
m_data_type_info.emplace_back(typeid(T));
// If we are allowed to do multithreading place the task in the appropriate vector
if constexpr (settings::use_multithreading)
{
if (desc.m_allow_multithreading)
{
m_multi_threaded_tasks.emplace_back(m_num_tasks);
}
else
{
m_single_threaded_tasks.emplace_back(m_num_tasks);
}
}
m_num_tasks++;
}
/*! Return the frame graph's unique id.*/
[[nodiscard]] const std::uint64_t GetUID() const noexcept
{
return m_uid;
};
/*! Return the cpu texture. */
[[nodiscard]] CPUTextures const & GetOutputTexture() const noexcept
{
return m_output_cpu_textures;
}
/*! Save a render target to disc */
/*
Tells the render system to save a render target to disc as a image.
\param index The index of the render target from the task you want to save.
*/
template<typename T>
void SaveTaskToDisc(std::string const & path, int index = 0)
{
auto handle = GetHandleFromType<T>();
if (handle.has_value())
{
m_render_system->RequestRenderTargetSaveToDisc(path, m_render_targets[handle.value()], index);
}
else
{
LOGW("Failed to save render task to disc, Task was not found.");
}
}
/*! Set the cpu texture's data. */
void SetOutputTexture(const CPUTexture& output_texture, CPUTextureType type)
{
switch (type)
{
case wr::CPUTextureType::PIXEL_DATA:
if (m_output_cpu_textures.pixel_data != std::nullopt)
{
LOGW("Warning: CPU texture pixel data is written to more than once a frame!");
}
// Save the pixel data
m_output_cpu_textures.pixel_data = output_texture;
break;
case wr::CPUTextureType::DEPTH_DATA:
if (m_output_cpu_textures.depth_data != std::nullopt)
{
LOGW("Warning: CPU texture depth data is written to more than once a frame!");
}
// Save the depth data
m_output_cpu_textures.depth_data = output_texture;
break;
default:
// Should never happen
LOGC("Invalid CPU texture type supplied!")
break;
}
}
/*! Enable or disable execution of a task. */
inline void SetShouldExecute(RenderTaskHandle handle, bool value)
{
m_should_execute_change_request.emplace(std::make_pair(handle, value));
}
/*! Enable or disable execution of a task. Templated version */
template<typename T>
inline void SetShouldExecute(bool value)
{
auto handle = GetHandleFromType<T>();
if (handle.has_value())
{
SetShouldExecute(handle.value(), value);
}
else
{
LOGW("Failed to mark the task for execution, Task was not found.");
}
}
/*! Update the settings of a task. */
/*!
This is used to update settings of a render task.
This must ge called BEFORE `FrameGraph::Setup` or `RenderSystem::Render`.
*/
template<typename T>
inline void UpdateSettings(std::any settings)
{
auto handle = GetHandleFromType<T>();
if (handle.has_value())
{
m_settings[handle.value()] = settings;
}
else
{
LOGW("Failed to update settings, Could not find render task");
}
}
/*! Gives you the settings of a task by handle. */
/*!
This gives you the settings for a render task casted to `R`.
Meant to be used for INSIDE the tasks.
The return value can be a nullptr.
\tparam T The render task data type used for identification.
\tparam R The type of the settings object.
*/
template<typename T, typename R>
[[nodiscard]] inline R GetSettings() const try
{
static_assert(std::is_class<T>::value ||
std::is_floating_point<T>::value ||
std::is_integral<T>::value,
"The first template variable should be a class, struct, floating point value or a integral value.");
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; i++)
{
if (typeid(T) == m_data_type_info[i])
{
return std::any_cast<R>(m_settings[i].value());
}
}
LOGC("Failed to find task settings! Does your frame graph contain this task?");
return R();
}
catch (const std::bad_any_cast & e) {
LOGC("A task settings requested failed to cast to T. ({})", e.what());
return R();
}
/*! Gives you the settings of a task by handle. */
/*!
This gives you the settings for a render task casted to `T`.
Meant to be used for INSIDE the tasks.
The return value can be a nullptr.
*/
template<typename T>
[[nodiscard]] inline T GetSettings(RenderTaskHandle handle) const try
{
static_assert(std::is_class<T>::value ||
std::is_floating_point<T>::value ||
std::is_integral<T>::value,
"The template variable should be a class, struct, floating point value or a integral value.");
return std::any_cast<T>(m_settings[handle].value());
}
catch (const std::bad_any_cast& e) {
LOGW("A task settings requested failed to cast to T. ({})", e.what());
return T();
}
/*! Resets the CPU texture data for this frame. */
inline void ResetOutputTexture()
{
// Frame has been rendered, allow a task to write to the CPU texture in the next frame
m_output_cpu_textures.pixel_data = std::nullopt;
m_output_cpu_textures.depth_data = std::nullopt;
}
private:
/*! Get the handle from a task by data type */
/* This function is zero overhead with GCC-8.2, -03 */
template<typename T>
inline std::optional<RenderTaskHandle> GetHandleFromType() const
{
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i)
{
if (m_data_type_info[i].get() == typeid(T))
{
return i;
}
}
return std::nullopt;
}
/*! Setup tasks multi threaded */
inline void Setup_MT_Impl()
{
// Multithreading behaviour
for (const auto handle : m_multi_threaded_tasks)
{
m_futures[handle] = m_thread_pool->Enqueue([this, handle]
{
m_setup_funcs[handle](*m_render_system, *this, handle, false);
});
}
// Singlethreading behaviour
for (const auto handle : m_single_threaded_tasks)
{
m_setup_funcs[handle](*m_render_system, *this, handle, false);
}
}
/*! Execute tasks multi threaded */
inline void Execute_MT_Impl(SceneGraph& scene_graph)
{
// Multithreading behaviour
for (const auto handle : m_multi_threaded_tasks)
{
// Skip this task if it doesn't need to be executed
if (!m_should_execute[handle])
{
continue;
}
m_futures[handle] = m_thread_pool->Enqueue([this, handle, &scene_graph]
{
ExecuteSingleTask(scene_graph, handle);
});
}
// Singlethreading behaviour
for (const auto handle : m_single_threaded_tasks)
{
// Skip this task if it doesn't need to be executed
if (!m_should_execute[handle])
{
continue;
}
ExecuteSingleTask(scene_graph, handle);
}
}
/*! Execute tasks single threaded */
inline void Execute_ST_Impl(SceneGraph& scene_graph)
{
for (decltype(m_num_tasks) i = 0; i < m_num_tasks; ++i)
{
// Skip this task if it doesn't need to be executed
if (!m_should_execute[i])
{
continue;
}
ExecuteSingleTask(scene_graph, i);
}
}
/*! Execute a single task */
inline void ExecuteSingleTask(SceneGraph& sg, RenderTaskHandle handle)
{
auto cmd_list = m_cmd_lists[handle];
auto render_target = m_render_targets[handle];
auto rt_properties = m_rt_properties[handle];
m_render_system->ResetCommandList(cmd_list);
switch (m_types[handle])
{
case RenderTaskType::DIRECT:
if (rt_properties.has_value())
{
m_render_system->StartRenderTask(cmd_list, { render_target, rt_properties.value() });
}
m_execute_funcs[handle](*m_render_system, *this, sg, handle);
if (rt_properties.has_value())
{
m_render_system->StopRenderTask(cmd_list, { render_target, rt_properties.value() });
}
break;
case RenderTaskType::COMPUTE:
if (rt_properties.has_value())
{
m_render_system->StartComputeTask(cmd_list, { render_target, rt_properties.value() });
}
m_execute_funcs[handle](*m_render_system, *this, sg, handle);
if (rt_properties.has_value())
{
m_render_system->StopComputeTask(cmd_list, { render_target, rt_properties.value() });
}
break;
case RenderTaskType::COPY:
if (rt_properties.has_value())
{
m_render_system->StartCopyTask(cmd_list, { render_target, rt_properties.value() });
}
m_execute_funcs[handle](*m_render_system, *this, sg, handle);
if (rt_properties.has_value())
{
m_render_system->StopCopyTask(cmd_list, { render_target, rt_properties.value() });
}
break;
}
m_render_system->CloseCommandList(cmd_list);
}
/*! Get a free unique ID. */
static std::uint64_t GetFreeUID()
{
if (!m_free_uids.empty())
{
std::uint64_t uid = m_free_uids.top();
m_free_uids.pop();
return uid;
}
std::uint64_t uid = m_largest_uid;
m_largest_uid++;
return uid;
}
/*! Get a release a unique ID for reuse. */
WISPRENDERER_EXPORT static void ReleaseUID(std::uint64_t uid)
{
m_free_uids.push(uid);
}
RenderSystem* m_render_system;
/*! The number of tasks we have added. */
std::uint32_t m_num_tasks;
/*! The thread pool used for multithreading */
util::ThreadPool* m_thread_pool;
/*! Vectors which allow us to itterate over only single threader or only multithreaded tasks. */
std::vector<RenderTaskHandle> m_multi_threaded_tasks;
std::vector<RenderTaskHandle> m_single_threaded_tasks;
/*! Holds the textures that can be written to memory. */
CPUTextures m_output_cpu_textures;
/*! Task function pointers. */
std::vector<setup_func_t> m_setup_funcs;
std::vector<execute_func_t> m_execute_funcs;
std::vector<destroy_func_t> m_destroy_funcs;
/*! Task target and command list. */
std::vector<CommandList*> m_cmd_lists;
std::vector<RenderTarget*> m_render_targets;
/*! Task data and the type information of the original data structure. */
std::vector<std::shared_ptr<void>> m_data;
std::vector<std::reference_wrapper<const std::type_info>> m_data_type_info;
/*! Task settings that can be passed to the frame graph from outside the task. */
std::vector<std::optional<std::any>> m_settings;
/*! Defines whether a task should execute or not. */
std::vector<bool> m_should_execute;
/*! Used to queue a request to change the should execute value */
std::queue<std::pair<RenderTaskHandle, bool>> m_should_execute_change_request;
/*! Descriptions of the tasks. */
#ifndef FG_MAX_PERFORMANCE
/*! Stored the dependencies of a task. */
std::vector<std::vector<std::reference_wrapper<const std::type_info>>> m_dependencies;
/*! The names of the render targets meant for debugging */
std::vector<std::wstring> m_names;
#endif
std::vector<RenderTaskType> m_types;
std::vector<std::optional<RenderTargetProperties>> m_rt_properties;
std::vector<std::future<void>> m_futures;
const std::uint64_t m_uid;
static inline std::uint64_t m_largest_uid = 0;
static inline std::stack<std::uint64_t> m_free_uids = {};
};
} /* wr */
| 31.464387 | 204 | 0.696125 | LaisoEmilio |
a2b0ec13c962e69c833e00d65520b8fd008cab14 | 1,204 | cpp | C++ | semaphore/semA.cpp | chengwenwu/IPC | 2e01f397d15b2d2911f3494fc98c9ca5e8d274a9 | [
"MIT"
] | null | null | null | semaphore/semA.cpp | chengwenwu/IPC | 2e01f397d15b2d2911f3494fc98c9ca5e8d274a9 | [
"MIT"
] | null | null | null | semaphore/semA.cpp | chengwenwu/IPC | 2e01f397d15b2d2911f3494fc98c9ca5e8d274a9 | [
"MIT"
] | null | null | null | #include <iostream>
#include "sem.hpp"
using namespace std;
int main()
{
// 获取共享内存
int shmId = shmget(ftok(SHM_FILE, PROJ_ID), SHM_SIZE, IPC_CREAT | IPC_EXCL | 0666);
if (shmId == -1) {
perror("shmget:");
return 0;
}
// 绑定共享内存地址
char *shmMemory = (char *)shmat(shmId, NULL, 0);
// 获取信号量,并设置默认值
int semIdR = CreateSem(A_READ_FILE, 0);
int semIdW = CreateSem(A_WRITE_FILE, 0);
if (semIdR == -1 || semIdW == -1) {
perror("CreateSem:");
return -1;
}
sleep(3);
// 向共享内存写数据
sprintf(shmMemory, "A");
if (SemV(semIdW) == -1) {
perror("SemV w error:");
return 0;
}
cout << "A write success\n";
// 等待进程B,写B进来
if (SemP(semIdR) == -1) {
perror("SemV R error:");
return 0;
}
if (memcmp(shmMemory, "B", strlen("B")) == 0) {
cout << "read from mem: " << shmMemory << endl;
}
if (SemTimerP(semIdR, 5) == -1) {
perror("timer P:");
}
cout << "A End\n";
// 解绑内存
shmdt(shmMemory);
// 释放信号量
semctl(semIdR, 0, IPC_RMID);
semctl(semIdW, 0, IPC_RMID);
// 释放共享内存
shmctl(shmId, IPC_RMID, NULL);
return 0;
} | 19.737705 | 87 | 0.516611 | chengwenwu |
a2b4e7193801736e204ef14cc464d9dae226c518 | 21,840 | cpp | C++ | src/TextWriter.cpp | arielscarpinelli/pianogame | abca8a622afa4bb1b63aa1c457a0d36488033b4f | [
"MIT"
] | null | null | null | src/TextWriter.cpp | arielscarpinelli/pianogame | abca8a622afa4bb1b63aa1c457a0d36488033b4f | [
"MIT"
] | null | null | null | src/TextWriter.cpp | arielscarpinelli/pianogame | abca8a622afa4bb1b63aa1c457a0d36488033b4f | [
"MIT"
] | null | null | null |
// Copyright (c)2007 Nicholas Piegdon
// See license.txt for license information
#include <map>
#include "TextWriter.h"
#include "Renderer.h"
#include "PianoGameError.h"
#include "os_graphics.h"
#ifdef WIN32
// TODO: This should be deleted at shutdown
static std::map<int, HFONT> font_handle_lookup;
static int next_call_list_start = 1;
#else
// TODO: This should be deleted at shutdown
GLuint Texture2DCreateFromString(const GLchar * const pString,
const GLchar * const pFontName,
const CGFloat& rFontSize,
const CTTextAlignment& rAlignment,
const CGFloat * const pColor,
CGSize& rSize);
#endif
// TODO: This should be deleted at shutdown
static std::map<int, int> font_size_lookup;
TextWriter::TextWriter(int in_x, int in_y, Renderer &in_renderer, bool in_centered, int in_size, std::wstring fontname) :
x(in_x), y(in_y), size(in_size), original_x(0), last_line_height(0), centered(in_centered), renderer(in_renderer)
{
x += renderer.m_xoffset;
original_x = x;
y += renderer.m_yoffset;
#ifdef WIN32
Context c = renderer.m_context;
point_size = MulDiv(size, GetDeviceCaps(c, LOGPIXELSY), 72);
HFONT font = 0;
if (font_size_lookup[in_size] == 0)
{
// Set up the LOGFONT structure
LOGFONT logical_font;
logical_font.lfHeight = get_point_size();
logical_font.lfWidth = 0;
logical_font.lfEscapement = 0;
logical_font.lfOrientation = 0;
logical_font.lfWeight = FW_NORMAL;
logical_font.lfItalic = false;
logical_font.lfUnderline = false;
logical_font.lfStrikeOut = false;
logical_font.lfCharSet = ANSI_CHARSET;
logical_font.lfOutPrecision = OUT_DEFAULT_PRECIS;
logical_font.lfClipPrecision = CLIP_DEFAULT_PRECIS;
logical_font.lfQuality = PROOF_QUALITY;
logical_font.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
lstrcpy(logical_font.lfFaceName, fontname.c_str());
font = CreateFontIndirect(&logical_font);
HFONT previous_font = (HFONT)SelectObject(c, font);
wglUseFontBitmaps(c, 0, 128, next_call_list_start);
font_size_lookup[in_size] = next_call_list_start;
font_handle_lookup[in_size] = font;
next_call_list_start += 130;
SelectObject(c, previous_font);
}
#else
// TODO: is this sufficient?
point_size = size;
#endif
}
TextWriter::~TextWriter()
{
}
int TextWriter::get_point_size()
{
return point_size;
}
TextWriter& TextWriter::next_line()
{
y += std::max(last_line_height, get_point_size());
x = original_x;
last_line_height = 0;
return *this;
}
TextWriter& Text::operator<<(TextWriter& tw) const
{
int draw_x;
int draw_y;
// TODO: This isn't Unicode!
std::string narrow(m_text.begin(), m_text.end());
#ifndef WIN32
CGFloat color[4] = {m_color.r / 255.0f, m_color.g / 255.0f, m_color.b / 255.0f, m_color.a / 255.0f};
CGSize size;
GLuint texture = Texture2DCreateFromString(narrow.c_str(), nullptr, tw.size, tw.centered ? kCTTextAlignmentCenter : kCTTextAlignmentLeft, color, size);
draw_x = size.width;
draw_y = size.height;
#endif
calculate_position_and_advance_cursor(tw, &draw_x, &draw_y);
glPushMatrix();
#ifdef WIN32
glBindTexture(GL_TEXTURE_2D, 0);
tw.renderer.SetColor(m_color);
glListBase(font_size_lookup[tw.size]);
glRasterPos2i(draw_x, draw_y + tw.size);
glCallLists(static_cast<int>(narrow.length()), GL_UNSIGNED_BYTE, narrow.c_str());
#else
tw.renderer.DrawTextTextureQuad(texture, draw_x, draw_y, size.width, size.height);
//glDeleteTextures(1, &texture);
#endif
glPopMatrix();
// TODO: Should probably delete these on shutdown.
//glDeleteLists(1000, 128);
return tw;
}
void Text::calculate_position_and_advance_cursor(TextWriter &tw, int *out_x, int *out_y) const
{
#ifdef WIN32
const long options = DT_LEFT | DT_NOPREFIX;
Context c = tw.renderer.m_context;
int previous_map_mode = SetMapMode(c, MM_TEXT);
HFONT font = font_handle_lookup[tw.size];
// Create the font we want to use, and swap it out with
// whatever is currently in there, along with our color
HFONT previous_font = (HFONT)SelectObject(c, font);
// Call DrawText to find out how large our text is
RECT drawing_rect = { tw.x, tw.y, 0, 0 };
tw.last_line_height = DrawText(c, m_text.c_str(), int(m_text.length()), &drawing_rect, options | DT_CALCRECT);
// Return the hdc settings to their previous setting
SelectObject(c, previous_font);
SetMapMode(c, previous_map_mode);
#else
Rect drawing_rect = { tw.y, tw.x, tw.y + *out_y, tw.x + *out_x};
#endif
// Update the text-writer with post-draw coordinates
if (tw.centered) drawing_rect.left -= (drawing_rect.right - drawing_rect.left) / 2;
if (!tw.centered) tw.x += drawing_rect.right - drawing_rect.left;
// Tell the draw function where to put the text
*out_x = drawing_rect.left;
*out_y = drawing_rect.top;
}
TextWriter& operator<<(TextWriter& tw, const Text& t)
{
return t.operator <<(tw);
}
TextWriter& newline(TextWriter& tw)
{
return tw.next_line();
}
TextWriter& operator<<(TextWriter& tw, const std::wstring& s) { return tw << Text(s, White); }
TextWriter& operator<<(TextWriter& tw, const int& i) { return tw << Text(i, White); }
TextWriter& operator<<(TextWriter& tw, const unsigned int& i) { return tw << Text(i, White); }
TextWriter& operator<<(TextWriter& tw, const long& l) { return tw << Text(l, White); }
TextWriter& operator<<(TextWriter& tw, const unsigned long& l) { return tw << Text(l, White); }
// Create a bitmap context from a string, font, justification, and font size
static CGContextRef CGContextCreateFromAttributedString(CFAttributedStringRef pAttrString,
const CFRange& rRange,
CGColorSpaceRef pColorspace,
CGSize& rSize)
{
CGContextRef pContext = nullptr;
if(pAttrString != nullptr)
{
// Acquire a frame setter
CTFramesetterRef pFrameSetter = CTFramesetterCreateWithAttributedString(pAttrString);
if(pFrameSetter != nullptr)
{
// Create a path for layout
CGMutablePathRef pPath = CGPathCreateMutable();
if(pPath != nullptr)
{
CFRange range;
CGSize constraint = CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX);
// Get the CoreText suggested size from our framesetter
rSize = CTFramesetterSuggestFrameSizeWithConstraints(pFrameSetter,
rRange,
nullptr,
constraint,
&range);
// Set path bounds
CGRect bounds = CGRectMake(0.0f,
0.0f,
rSize.width,
rSize.height);
// Bound the path
CGPathAddRect(pPath, nullptr, bounds);
// Layout the attributed string in a frame
CTFrameRef pFrame = CTFramesetterCreateFrame(pFrameSetter, range, pPath, nullptr);
if(pFrame != nullptr)
{
// Compute bounds for the bitmap context
size_t width = size_t(rSize.width);
size_t height = size_t(rSize.height);
size_t stride = sizeof(GLuint) * width;
// No explicit backing-store allocation here. We'll let the
// context allocate the storage for us.
pContext = CGBitmapContextCreate(nullptr,
width,
height,
8,
stride,
pColorspace,
kCGImageAlphaPremultipliedLast);
if(pContext != nullptr)
{
// Use this for vertical reflection
CGContextTranslateCTM(pContext, 0.0, height);
CGContextScaleCTM(pContext, 1.0, -1.0);
// Draw the frame into a bitmap context
CTFrameDraw(pFrame, pContext);
// Flush the context
CGContextFlush(pContext);
} // if
// Release the frame
CFRelease(pFrame);
} // if
CFRelease(pPath);
} // if
CFRelease(pFrameSetter);
} // if
} // if
return pContext;
} // CGContextCreateFromString
// Create an attributed string from a CF string, font, justification, and font size
static CFMutableAttributedStringRef CFMutableAttributedStringCreate(CFStringRef pString,
CFStringRef pFontNameSrc,
CGColorRef pComponents,
const CGFloat& rFontSize,
const CTTextAlignment nAlignment,
CFRange *pRange)
{
CFMutableAttributedStringRef pAttrString = nullptr;
if(pString != nullptr)
{
// Paragraph style setting structure
const GLuint nCntStyle = 2;
// For single spacing between the lines
const CGFloat nLineHeightMultiple = 1.0f;
// Paragraph settings with alignment and style
CTParagraphStyleSetting settings[nCntStyle] =
{
{
kCTParagraphStyleSpecifierAlignment,
sizeof(CTTextAlignment),
&nAlignment
},
{
kCTParagraphStyleSpecifierLineHeightMultiple,
sizeof(CGFloat),
&nLineHeightMultiple
}
};
// Create a paragraph style
CTParagraphStyleRef pStyle = CTParagraphStyleCreate(settings, nCntStyle);
if(pStyle != nullptr)
{
// If the font name is nullptr default to Helvetica
CFStringRef pFontNameDst = (pFontNameSrc) ? pFontNameSrc : CFSTR("Helvetica");
// Prepare font
CTFontRef pFont = CTFontCreateWithName(pFontNameDst, rFontSize, nullptr);
if(pFont != nullptr)
{
// Set attributed string properties
const GLuint nCntDict = 3;
CFStringRef keys[nCntDict] =
{
kCTParagraphStyleAttributeName,
kCTFontAttributeName,
kCTForegroundColorAttributeName
};
CFTypeRef values[nCntDict] =
{
pStyle,
pFont,
pComponents
};
// Create a dictionary of attributes for our string
CFDictionaryRef pAttributes = CFDictionaryCreate(nullptr,
(const void **)&keys,
(const void **)&values,
nCntDict,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
if(pAttributes != nullptr)
{
// Creating a mutable attributed string
pAttrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
if(pAttrString != nullptr)
{
// Set a mutable attributed string with the input string
CFAttributedStringReplaceString(pAttrString, CFRangeMake(0, 0), pString);
// Compute the mutable attributed string range
*pRange = CFRangeMake(0, CFAttributedStringGetLength(pAttrString));
// Set the attributes
CFAttributedStringSetAttributes(pAttrString, *pRange, pAttributes, 0);
} // if
CFRelease(pAttributes);
} // if
CFRelease(pFont);
} // if
CFRelease(pStyle);
} // if
} // if
return pAttrString;
} // CFMutableAttributedStringCreate
// Create a 2D texture
static GLuint GLUTexture2DCreate(const GLuint& rWidth,
const GLuint& rHeight,
const GLvoid * const pPixels)
{
GLuint nTID = 0;
// Greate a texture
glGenTextures(1, &nTID);
if(nTID)
{
// Bind a texture with ID
glBindTexture(GL_TEXTURE_2D, nTID);
// Set texture properties (including linear mipmap)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_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);
// Initialize the texture
glTexImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
rWidth,
rHeight,
0,
GL_RGBA,
GL_UNSIGNED_INT_8_8_8_8_REV,
pPixels);
// Generate mipmaps
glGenerateMipmap(GL_TEXTURE_2D);
// Discard
glBindTexture(GL_TEXTURE_2D, 0);
} // if
return nTID;
} // GLUTexture2DCreate
// Create a texture from a bitmap context
static GLuint GLUTexture2DCreateFromContext(CGContextRef pContext)
{
GLuint nTID = 0;
if(pContext != nullptr)
{
GLuint nWidth = GLuint(CGBitmapContextGetWidth(pContext));
GLuint nHeight = GLuint(CGBitmapContextGetHeight(pContext));
const GLvoid *pPixels = CGBitmapContextGetData(pContext);
nTID = GLUTexture2DCreate(nWidth, nHeight, pPixels);
// Was there a GL error?
GLenum nErr = glGetError();
if(nErr != GL_NO_ERROR)
{
glDeleteTextures(1, &nTID);
throw PianoGameError(L"OpenGL error trying to create texture");
} // if
} // if
return nTID;
} // GLUTexture2DCreateFromContext
// Create a bitmap context from a core foundation string, font,
// justification, and font size
static CGContextRef CGContextCreateFromString(CFStringRef pString,
CFStringRef pFontName,
const CGFloat& rFontSize,
const CTTextAlignment& rAlignment,
const CGFloat * const pComponents,
CGSize &rSize)
{
CGContextRef pContext = nullptr;
if(pString != nullptr)
{
// Get a generic linear RGB color space
CGColorSpaceRef pColorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGBLinear);
if(pColorspace != nullptr)
{
// Create a white color reference
CGColorRef pColor = CGColorCreate(pColorspace, pComponents);
if(pColor != nullptr)
{
// Creating a mutable attributed string
CFRange range;
CFMutableAttributedStringRef pAttrString = CFMutableAttributedStringCreate(pString,
pFontName,
pColor,
rFontSize,
rAlignment,
&range);
if(pAttrString != nullptr)
{
// Create a context from our attributed string
pContext = CGContextCreateFromAttributedString(pAttrString,
range,
pColorspace,
rSize);
CFRelease(pAttrString);
} // if
CFRelease(pColor);
} // if
CFRelease(pColorspace);
} // if
} // if
return pContext;
} // CGContextCreateFromString
// Create a bitmap context from a c-string, font, justification, and font size
static CGContextRef CGContextCreateFromString(const GLchar * const pString,
const GLchar * const pFontName,
const CGFloat& rFontSize,
const CTTextAlignment& rAlignment,
const CGFloat * const pComponents,
CGSize& rSize)
{
CGContextRef pContext = nullptr;
if(pString != nullptr)
{
CFStringRef pCFString = CFStringCreateWithCString(kCFAllocatorDefault,
pString,
kCFStringEncodingASCII);
if(pCFString != nullptr)
{
const GLchar *pFontString = (pFontName) ? pFontName : "Helvetica";
CFStringRef pFontCFString = CFStringCreateWithCString(kCFAllocatorDefault,
pFontString,
kCFStringEncodingASCII);
if(pFontCFString != nullptr)
{
pContext = CGContextCreateFromString(pCFString,
pFontCFString,
rFontSize,
rAlignment,
pComponents,
rSize);
CFRelease(pFontCFString);
} // if
CFRelease(pCFString);
} // if
} // if
return pContext;
} // CGContextCreateFromString
// Generate a texture from a cstring, using a font, at a size,
// with alignment and color
GLuint Texture2DCreateFromString(const GLchar * const pString,
const GLchar * const pFontName,
const CGFloat& rFontSize,
const CTTextAlignment& rAlignment,
const CGFloat * const pColor,
CGSize& rSize)
{
GLuint nTID = 0;
CGContextRef pCtx = CGContextCreateFromString(pString,
pFontName,
rFontSize,
rAlignment,
pColor,
rSize);
if(pCtx != nullptr)
{
nTID = GLUTexture2DCreateFromContext(pCtx);
CGContextRelease(pCtx);
} // if
return nTID;
} // GLUTexture2DCreateFromString
| 37.142857 | 155 | 0.479533 | arielscarpinelli |
a2b5a6f648c038c0d60e10b5ab74baeed2bd153d | 1,844 | cpp | C++ | CPSC 2 Lectures/Copy Constructors/overload2_2.cpp | pwoodru/Academics | d2d10d26a4802e2ba8eb5a03057ff91e1644e93c | [
"MIT"
] | null | null | null | CPSC 2 Lectures/Copy Constructors/overload2_2.cpp | pwoodru/Academics | d2d10d26a4802e2ba8eb5a03057ff91e1644e93c | [
"MIT"
] | null | null | null | CPSC 2 Lectures/Copy Constructors/overload2_2.cpp | pwoodru/Academics | d2d10d26a4802e2ba8eb5a03057ff91e1644e93c | [
"MIT"
] | null | null | null | #include "overload2_2.h"
//***************************************************
//The overloaded operator function for assignment *
//***************************************************
NumberArray& NumberArray::operator=(const NumberArray &right)
{ //cout<< "In operator =" << endl;
if (arraySize > 0) delete [] aPtr;
arraySize = right.arraySize;
aPtr = new double[arraySize];
for (int index = 0; index < arraySize; index++)
aPtr[index] = right.aPtr[index];
return *this;
}
//*******************************************
//Copy Constructor *
//*******************************************
NumberArray::NumberArray(const NumberArray &obj)
{ //cout << "In copy constructor" << endl;
arraySize = obj.arraySize;
aPtr = new double[arraySize];
for(int index = 0; index < arraySize; index++)
aPtr[index] = obj.aPtr[index];
}
//*********************************************
//Constructor *
//*********************************************
NumberArray::NumberArray(int size, double value)
{ //cout << "in regular constructor" << endl;
arraySize = size;
aPtr = new double[arraySize];
//setValue(value);
for(int index = 0; index < arraySize; index++)
aPtr[index] = value;
}
//***************************************************
//Sets the value stored in all entries of the array *
//***************************************************
void NumberArray::setValue(double value)
{
for(int index = 0; index < arraySize; index++)
aPtr[index] = value;
}
//***************************************
//Print out all entries in the array *
//***************************************
void NumberArray::print()
{
for(int index = 0; index < arraySize; index++)
cout << aPtr[index] << " ";
}
| 31.254237 | 62 | 0.444685 | pwoodru |
a2ba91162019f55ab5b9a0e888c613abf75fdb30 | 509 | cpp | C++ | Vector-Erase.cpp | arnav-tandon/HackerRankChallenges | 4dddbe42044ba1673ceaed6ccfd026df89cdb8dc | [
"MIT"
] | null | null | null | Vector-Erase.cpp | arnav-tandon/HackerRankChallenges | 4dddbe42044ba1673ceaed6ccfd026df89cdb8dc | [
"MIT"
] | null | null | null | Vector-Erase.cpp | arnav-tandon/HackerRankChallenges | 4dddbe42044ba1673ceaed6ccfd026df89cdb8dc | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, x, p, q, r;
cin >> n;
vector<int> a;
for(int i = 0; i < n; ++i){
cin >> x;
a.push_back(x);
}
cin >> p;
a.erase(a.begin() + (p - 1));
cin >> q >> r;
a.erase(a.begin() + (q - 1),a.begin() + (r - 1));
cout << a.size() << "\n";
for(int k = 0; k < a.size(); ++k){
cout << a[k] << ' ';
}
return 0;
}
| 18.851852 | 53 | 0.440079 | arnav-tandon |
a2baf8fd519740ff9d83bda7facdefaad64f1177 | 2,629 | cpp | C++ | src/setshowinfo.cpp | mahuifa/DesktopTime | 067bd36a42d7349d8905c2bf81a74b6a1f895f05 | [
"Apache-2.0"
] | 1 | 2022-03-20T15:29:15.000Z | 2022-03-20T15:29:15.000Z | src/setshowinfo.cpp | mahuifa/DesktopTime | 067bd36a42d7349d8905c2bf81a74b6a1f895f05 | [
"Apache-2.0"
] | null | null | null | src/setshowinfo.cpp | mahuifa/DesktopTime | 067bd36a42d7349d8905c2bf81a74b6a1f895f05 | [
"Apache-2.0"
] | null | null | null | #include "setshowinfo.h"
#include "ui_setshowinfo.h"
#include <QFileDialog>
#include <qdebug.h>
#include "head.h"
SetShowInfo::SetShowInfo(QWidget *parent) :
QWidget(parent),
ui(new Ui::SetShowInfo)
{
ui->setupUi(this);
this->setWindowTitle("显示设置");
for(int i = 1; i < 100; i++)
{
ui->comboBox_size->addItem(QString("%1").arg(i), i);
}
}
SetShowInfo::~SetShowInfo()
{
delete ui;
}
/**
* @brief 传入需要设置的字体
* @param time 时间字体
* @param date 日期字体
*/
void SetShowInfo::setFont(const QFont &time, const QFont &date)
{
m_fontDate = date;
m_fontTime = time;
ui->comboBox_size->setCurrentText(QString("%1").arg(time.pointSize()));
ui->fontComboBox->setCurrentFont(time);
}
void SetShowInfo::on_fontComboBox_currentFontChanged(const QFont &f)
{
m_fontTime = f;
m_fontTime.setPointSize(ui->comboBox_size->currentData().toInt());
if(ui->check_time->isChecked())
{
emit newFont(m_fontTime, SetType::Time);
}
if(ui->check_date->isChecked())
{
emit newFont(m_fontTime, SetType::Date);
}
}
void SetShowInfo::on_comboBox_size_activated(int index)
{
on_fontComboBox_currentFontChanged(ui->fontComboBox->font());
}
void SetShowInfo::on_horizontalSlider_space_valueChanged(int value)
{
emit newSpace(value);
}
void SetShowInfo::on_comboBox_activated(const QString &arg1)
{
if(arg1 == "无")
{
emit newBgImage("none");
QColor color(255, 255, 255);
emit newColor(color, SetType::Background);
}
else
{
emit newBgImage(arg1);
}
}
void SetShowInfo::on_but_open_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,
"选择图片!",
"./",
"图片文件(*png *jpg)");
ui->lineEdit_path->setText(fileName);
emit newBgImage(fileName);
}
void SetShowInfo::on_com_time_activated(const QString &arg1)
{
emit newStyle(arg1, SetType::Time);
}
void SetShowInfo::on_com_date_activated(const QString &arg1)
{
emit newStyle(arg1, SetType::Date);
}
void SetShowInfo::on_but_fontColor_clicked()
{
QColor color = QColorDialog::getColor(Qt::white);
if(ui->check_time->isChecked())
{
emit newColor(color, SetType::Time);
}
if(ui->check_date->isChecked())
{
emit newColor(color, SetType::Date);
}
}
void SetShowInfo::on_but_bgColor_clicked()
{
QColor color = QColorDialog::getColor(Qt::white);
emit newColor(color, SetType::Background);
}
| 20.700787 | 75 | 0.617725 | mahuifa |
a2bd2cc7f04e5d37e3d0958fb038281b963f26a1 | 7,738 | cpp | C++ | IOSServer/Decomp.cpp | satadriver/GoogleServiceServer | 7d6e55d2f9a189301dd68821c920d0a0e300322a | [
"Apache-2.0"
] | null | null | null | IOSServer/Decomp.cpp | satadriver/GoogleServiceServer | 7d6e55d2f9a189301dd68821c920d0a0e300322a | [
"Apache-2.0"
] | null | null | null | IOSServer/Decomp.cpp | satadriver/GoogleServiceServer | 7d6e55d2f9a189301dd68821c920d0a0e300322a | [
"Apache-2.0"
] | null | null | null |
#include <windows.h>
#include "iosServer.h"
#include "PublicFunction.h"
#include "CryptoUtils.h"
#include "Coder.h"
#include "FileOperator.h"
int DisposePrefixZip(char * filename,char * dstfilename) {
lstrcpyA(dstfilename, filename);
int fnlen = lstrlenA(dstfilename);
for (int i = 0; i < fnlen - 4 + 1; i ++)
{
if (memcmp(dstfilename + i,".zip",4) == 0)
{
*(dstfilename + i) = 0;
return TRUE;
}
}
return FALSE;
}
int DecompressFromFileBlock(char * filename) {
char szdstfilename[MAX_PATH];
DisposePrefixZip(filename, szdstfilename);
HANDLE hf = CreateFileA(filename, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
return FALSE;
}
HANDLE hfdst = CreateFileA(szdstfilename, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (hfdst == INVALID_HANDLE_VALUE)
{
CloseHandle(hf);
return FALSE;
}
int ret = 0;
DWORD dwcnt = 0;
int filesize = GetFileSize(hf, 0);
int cnt = 0;
do
{
char bdecompsize[4];
char bcompsize[4];
ret = ReadFile(hf, bdecompsize, 4, &dwcnt, 0);
ret = ReadFile(hf, bcompsize, 4, &dwcnt, 0);
int decompsize = *(int*)bdecompsize;
int compsize = *(int*)bcompsize;
char * lpsrcbuf = new char[compsize];
char * lpdstbuf = new char[decompsize + 0x1000];
ret = ReadFile(hf, lpsrcbuf, compsize, &dwcnt, 0);
unsigned long outlen = decompsize;
ret = uncompress((unsigned char*)lpdstbuf, &outlen, (unsigned char*)lpsrcbuf, compsize);
if (ret == 0)
{
ret = WriteFile(hfdst, lpdstbuf, outlen, &dwcnt, 0);
}
delete[] lpsrcbuf;
delete[] lpdstbuf;
cnt += (8 + compsize);
} while (cnt < filesize);
CloseHandle(hf);
DeleteFileA(filename);
CloseHandle(hfdst);
char szcmd[MAX_PATH];
wsprintfA(szcmd, "cmd /c renanme %s %s", filename, szdstfilename);
WinExec(szcmd,SW_HIDE);
return TRUE;
}
int DecryptAndDecompFile(LPDATAPROCESS_PARAM lpparam, char * filename, char * lpdstfn, char * imei, char * username, int withparam, int append,DWORD type) {
DATAPROCESS_PARAM stparam = *lpparam;
char szlog[1024];
char errorbuf[1024];
HANDLE hf = CreateFileA(filename, GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
return FALSE;
}
int filesize = GetFileSize(hf, 0);
char * lpdata = new char[filesize];
DWORD dwcnt = 0;
int ret = ReadFile(hf, lpdata, filesize, &dwcnt, 0);
CloseHandle(hf);
DeleteFileA(filename);
if ( ((type & PACKET_CRYPT_FLAG) && (type & PACKET_COMPRESS_FLAG)) ||
((type & 1) && (*(unsigned short*)(lpdata + sizeof(int)) != 0x9c78)) )
{
int len = CryptoUtils:: xorCryptData(lpdata, filesize, imei, CRYPT_KEY_SIZE, lpdata, filesize);
if (type & PACKET_COMPRESS_FLAG)
{
;
}
int compresssize = *(int*)(lpdata);
if (compresssize <= 0)
{
delete[] lpdata;
wsprintfA(szlog, "DecryptAndDecompFile uncompress file:%s size 0", filename);
ErrorFormat(&stparam, errorbuf, szlog);
WriteLogFile(errorbuf);
return FALSE;
}
unsigned long unzipbufLen = compresssize + 0x1000;
unsigned char * unzipbuf = (unsigned char*)new char[unzipbufLen];
if (unzipbuf == FALSE)
{
delete[] lpdata;
return FALSE;
}
ret = uncompress((Bytef*)unzipbuf, (uLongf*)&unzipbufLen, (Bytef*)(lpdata + sizeof(DWORD)), (uLongf)(filesize - sizeof(DWORD)));
if (ret != Z_OK) {
delete[]unzipbuf;
delete[] lpdata;
wsprintfA(szlog, "DecryptAndDecompFile uncompress error:%s", filename);
ErrorFormat(&stparam, errorbuf, szlog);
WriteLogFile(errorbuf);
WriteErrorPacket("uncompress error", lpdata, ERRORPACKETSIZE);
return FALSE;
}
*(DWORD*)(unzipbuf + unzipbufLen) = 0;
delete[] lpdata;
if (withparam)
{
FileOperator::GetPathFromFullName(filename, lpdstfn);
char * lpbuf = (char*)unzipbuf;
DWORD dwfilenamesize = *(DWORD*)lpbuf;
char szfilename[MAX_PATH] = { 0 };
lpbuf += sizeof(DWORD);
memmove(szfilename, lpbuf, dwfilenamesize);
lpbuf += dwfilenamesize;
DWORD dwfilesize = *(DWORD*)lpbuf;
lpbuf += sizeof(DWORD);
char szgbkfn[MAX_PATH] = { 0 };
ret = Coder::UTF8FNToGBKFN(szfilename, dwfilenamesize, szgbkfn, MAX_PATH);
lstrcatA(lpdstfn, szgbkfn);
hf = CreateFileA(lpdstfn, GENERIC_WRITE, 0, 0, append, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
delete[]unzipbuf;
return FALSE;
}
ret = SetFilePointer(hf, 0, 0, FILE_END);
ret = WriteFile(hf, lpbuf, dwfilesize, &dwcnt, 0);
CloseHandle(hf);
}
else {
ret = FileOperator::TripSufixName(filename, lpdstfn, ".tmp");
hf = CreateFileA(lpdstfn, GENERIC_WRITE, 0, 0, append, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
delete[]unzipbuf;
return FALSE;
}
ret = SetFilePointer(hf, 0, 0, FILE_END);
ret = WriteFile(hf, unzipbuf, unzipbufLen, &dwcnt, 0);
CloseHandle(hf);
}
delete[]unzipbuf;
return TRUE;
}
else {
if (withparam)
{
FileOperator::GetPathFromFullName(filename, lpdstfn);
char * lpbuf = (char*)lpdata;
DWORD dwfilenamesize = *(DWORD*)lpbuf;
char szfilename[MAX_PATH] = { 0 };
lpbuf += sizeof(DWORD);
memmove(szfilename, lpbuf, dwfilenamesize);
lpbuf += dwfilenamesize;
DWORD dwfilesize = *(DWORD*)lpbuf;
lpbuf += sizeof(DWORD);
char szgbkfn[MAX_PATH] = { 0 };
ret = Coder::UTF8FNToGBKFN(szfilename, dwfilenamesize, szgbkfn, MAX_PATH);
lstrcatA(lpdstfn, szgbkfn);
hf = CreateFileA(lpdstfn, GENERIC_WRITE, 0, 0, append, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
delete[] lpdata;
return FALSE;
}
ret = SetFilePointer(hf, 0, 0, FILE_END);
ret = WriteFile(hf, lpbuf, dwfilesize , &dwcnt, 0);
CloseHandle(hf);
}
else {
ret = FileOperator::TripSufixName(filename, lpdstfn, ".tmp");
hf = CreateFileA(lpdstfn, GENERIC_WRITE, 0, 0, append, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
delete[] lpdata;
return FALSE;
}
ret = SetFilePointer(hf, 0, 0, FILE_END);
ret = WriteFile(hf, lpdata, filesize, &dwcnt, 0);
CloseHandle(hf);
}
delete[] lpdata;
return TRUE;
}
return TRUE;
}
int NoneDecryptDataWiHeader(LPDATAPROCESS_PARAM lpparam, char * filename,char * lpdstfn,char * imei,char * username,int withparam,int append) {
DATAPROCESS_PARAM stparam = *lpparam;
//char szlog[1024];
//char errorbuf[1024];
HANDLE hf = CreateFileA(filename, GENERIC_WRITE|GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
return FALSE;
}
int filesize = GetFileSize(hf, 0);
char * lpdata = new char[filesize];
DWORD dwcnt = 0;
int ret = ReadFile(hf, lpdata, filesize, &dwcnt, 0);
CloseHandle(hf);
if (withparam)
{
FileOperator::GetPathFromFullName(filename, lpdstfn);
char * lpbuf = (char*)lpdata;
DWORD dwfilenamesize = *(DWORD*)lpbuf;
char szfilename[MAX_PATH] = { 0 };
lpbuf += sizeof(DWORD);
memmove(szfilename, lpbuf, dwfilenamesize);
lpbuf += dwfilenamesize;
DWORD dwfilesize = *(DWORD*)lpbuf;
lpbuf += sizeof(DWORD);
char szgbkfn[MAX_PATH] = { 0 };
ret = Coder::UTF8FNToGBKFN(szfilename, dwfilenamesize, szgbkfn, MAX_PATH);
lstrcatA(lpdstfn, szgbkfn);
hf = CreateFileA(lpdstfn, GENERIC_WRITE, 0, 0, append, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
return FALSE;
}
ret = WriteFile(hf, lpbuf, filesize - (lpbuf - lpdata), &dwcnt, 0);
CloseHandle(hf);
DeleteFileA(filename);
}
else {
return TRUE;
hf = CreateFileA(filename, GENERIC_WRITE, 0, 0, append, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
return FALSE;
}
ret = WriteFile(hf, lpdata, filesize, &dwcnt, 0);
CloseHandle(hf);
lstrcpyA(lpdstfn, filename);
}
return TRUE;
} | 25.123377 | 156 | 0.676402 | satadriver |
a2bdb1e951c5b6a99024734de3fa57d343ca12e4 | 1,780 | hpp | C++ | include/view/view.hpp | modern-cpp-examples/match3 | bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e | [
"BSL-1.0"
] | 166 | 2016-04-27T19:01:00.000Z | 2022-03-27T02:16:55.000Z | include/view/view.hpp | Fuyutsubaki/match3 | bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e | [
"BSL-1.0"
] | 4 | 2016-05-19T07:47:38.000Z | 2018-03-22T04:33:00.000Z | include/view/view.hpp | Fuyutsubaki/match3 | bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e | [
"BSL-1.0"
] | 17 | 2016-05-18T21:17:39.000Z | 2022-03-20T22:37:14.000Z | //
// Copyright (c) 2016 Krzysztof Jusiak (krzysztof at jusiak dot net)
//
// 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)
//
#pragma once
#include "config.hpp"
#include "view/icanvas.hpp"
namespace match3 {
class view {
static constexpr auto grid_size = 38;
static constexpr auto grid_offset = grid_size + 5;
static constexpr auto grids_offset_x = 15;
static constexpr auto grids_offset_y = 50;
public:
view(icanvas& canvas, config conf) : canvas_(canvas), config_(conf) {
grids.reserve(config_.board_colors);
for (auto i = 0; i <= config_.board_colors; ++i) {
grids.emplace_back(
canvas_.load_image("data/images/" + std::to_string(i) + ".png"));
};
match_ = canvas_.load_image("data/images/match.png");
}
void set_grid(int x, int y, int c) {
canvas_.draw(grids[c], grids_offset_x + (x * grid_offset),
grids_offset_y + (y * grid_offset));
}
void update_grid(int x, int y) {
canvas_.draw(match_, grids_offset_x + (x * grid_offset),
grids_offset_y + (y * grid_offset), false /*cleanup*/);
}
auto get_position(int x, int y) const noexcept {
return (((y - grids_offset_y) / grid_offset) * config_.board_width) +
((x - grids_offset_x) / grid_offset);
}
void set_text(const std::string& text, int x, int y, int font_size = 14) {
canvas_.draw(canvas_.create_text(text, "data/fonts/font.ttf", font_size), x,
y);
}
void update() { canvas_.render(); }
void clear() { canvas_.clear(); }
private:
std::vector<std::shared_ptr<void>> grids;
std::shared_ptr<void> match_;
icanvas& canvas_;
config config_;
};
} // match3
| 28.253968 | 80 | 0.651685 | modern-cpp-examples |
a2c32fc6625ba36bb03e06e3593f37ddfa7bb63e | 6,190 | hpp | C++ | redemption/src/utils/sugar/bounded_bytes_view.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | redemption/src/utils/sugar/bounded_bytes_view.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | redemption/src/utils/sugar/bounded_bytes_view.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | /*
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.
Product name: redemption, a FLOSS RDP proxy
Copyright (C) Wallix 2021
Author(s): Proxies Team
*/
#pragma once
#include "utils/sugar/byte_ptr.hpp"
#include "utils/sugar/bounded_array_view.hpp"
/**
* \c bounded_array_view on \c uint8_t* and \c char*
*/
template<std::size_t AtLeast, std::size_t AtMost>
struct writable_bounded_bytes_view : writable_bounded_array_view<uint8_t, AtLeast, AtMost>
{
using writable_bounded_u8_array_view = writable_bounded_array_view<uint8_t, AtLeast, AtMost>;
using writable_bounded_chars_view = writable_bounded_array_view<char, AtLeast, AtMost>;
writable_bounded_bytes_view() = delete;
writable_bounded_bytes_view(writable_bounded_bytes_view &&) = default;
writable_bounded_bytes_view(writable_bounded_bytes_view const &) = default;
writable_bounded_bytes_view & operator=(writable_bounded_bytes_view &&) = default;
writable_bounded_bytes_view & operator=(writable_bounded_bytes_view const &) = default;
template<class T, std::size_t n>
writable_bounded_bytes_view(T(&)[n]) = delete;
template<class T, std::size_t n>
writable_bounded_bytes_view & operator=(T(&)[n]) = delete;
writable_bounded_bytes_view(writable_bounded_chars_view av) noexcept /*NOLINT*/
: writable_bounded_u8_array_view(
writable_bounded_u8_array_view::assumed(byte_ptr_cast(av.data())))
{}
writable_bounded_bytes_view(writable_bounded_u8_array_view av) noexcept /*NOLINT*/
: writable_bounded_u8_array_view(av)
{}
template<class U, typename std::enable_if<
std::is_constructible<writable_bounded_u8_array_view, U&&>::value, bool
>::type = 1>
explicit constexpr writable_bounded_bytes_view(U && a) noexcept /*NOLINT*/
: writable_bounded_u8_array_view(a)
{}
template<class U, typename std::enable_if<
std::is_constructible<writable_bounded_chars_view, U&&>::value, bool
>::type = 1>
explicit constexpr writable_bounded_bytes_view(U && a) noexcept /*NOLINT*/
: writable_bounded_bytes_view(writable_bounded_chars_view(a))
{}
[[nodiscard]] char * as_charp() noexcept { return char_ptr_cast(this->data()); }
[[nodiscard]] char const * as_charp() const noexcept { return char_ptr_cast(this->data()); }
[[nodiscard]] constexpr uint8_t * as_u8p() noexcept { return this->data(); }
[[nodiscard]] constexpr uint8_t const * as_u8p() const noexcept { return this->data(); }
[[nodiscard]] writable_bounded_chars_view as_chars() noexcept
{
return writable_bounded_chars_view::assumed(this->as_charp());
}
[[nodiscard]] bounded_array_view<char, AtLeast, AtMost> as_chars() const noexcept
{
return bounded_array_view<char, AtLeast, AtMost>::assumed(this->as_charp());
}
};
template<class T, class Bounds = sequence_to_size_bounds_t<T>>
writable_bounded_bytes_view(T&&) -> writable_bounded_bytes_view<
Bounds::at_least, Bounds::at_most
>;
/**
* \c bounded_array_view on constant \c uint8_t* and \c char*
*/
template<std::size_t AtLeast, std::size_t AtMost>
struct bounded_bytes_view : bounded_array_view<uint8_t, AtLeast, AtMost>
{
using bounded_u8_array_view = bounded_array_view<uint8_t, AtLeast, AtMost>;
using bounded_chars_view = bounded_array_view<char, AtLeast, AtMost>;
bounded_bytes_view() = delete;
bounded_bytes_view(bounded_bytes_view &&) = default;
bounded_bytes_view(bounded_bytes_view const &) = default;
bounded_bytes_view & operator=(bounded_bytes_view &&) = default;
bounded_bytes_view & operator=(bounded_bytes_view const &) = default;
template<class T, std::size_t n>
bounded_bytes_view(T(&)[n]) = delete;
template<class T, std::size_t n>
bounded_bytes_view & operator=(T(&)[n]) = delete;
bounded_bytes_view(bounded_chars_view av) noexcept /*NOLINT*/
: bounded_u8_array_view(byte_ptr_cast(av.data()), av.size())
{}
template<class U, typename std::enable_if<
std::is_constructible<bounded_u8_array_view, U&&>::value, bool
>::type = 1>
constexpr bounded_bytes_view(U && a) noexcept(noexcept(bounded_u8_array_view(a))) /*NOLINT*/
: bounded_u8_array_view(a)
{}
template<class U, typename std::enable_if<
std::is_constructible<bounded_chars_view, U&&>::value, bool
>::type = 1>
constexpr bounded_bytes_view(U && a) noexcept(noexcept(bounded_chars_view(a))) /*NOLINT*/
: bounded_bytes_view(bounded_chars_view(a))
{}
[[nodiscard]] char const * as_charp() const noexcept { return char_ptr_cast(this->data()); }
[[nodiscard]] constexpr uint8_t const * as_u8p() const noexcept { return this->data(); }
[[nodiscard]] bounded_chars_view as_chars() const noexcept
{
return bounded_chars_view::assumed(this->as_charp());
}
};
template<class T, class Bounds = sequence_to_size_bounds_t<T>>
bounded_bytes_view(T&&) -> bounded_bytes_view<
Bounds::at_least, Bounds::at_most
>;
template<std::size_t N>
using sized_bytes_view = bounded_bytes_view<N, N>;
template<std::size_t N>
using writable_sized_bytes_view = writable_bounded_bytes_view<N, N>;
namespace detail
{
template<std::size_t AtLeast, std::size_t AtMost>
struct sequence_to_size_bounds_impl<writable_bounded_bytes_view<AtLeast, AtMost>>
{
using type = size_bounds<AtLeast, AtMost>;
};
template<std::size_t AtLeast, std::size_t AtMost>
struct sequence_to_size_bounds_impl<bounded_bytes_view<AtLeast, AtMost>>
{
using type = size_bounds<AtLeast, AtMost>;
};
}
| 36.19883 | 97 | 0.73021 | DianaAssistant |
a2c5c26adb1d42ddc624f3d00c7333a20e7b2e03 | 673 | cpp | C++ | 1128/main.cpp | Heliovic/PAT_Solutions | 7c5dd554654045308f2341713c3e52cc790beb59 | [
"MIT"
] | 2 | 2019-03-18T12:55:38.000Z | 2019-09-07T10:11:26.000Z | 1128/main.cpp | Heliovic/My_PAT_Answer | 7c5dd554654045308f2341713c3e52cc790beb59 | [
"MIT"
] | null | null | null | 1128/main.cpp | Heliovic/My_PAT_Answer | 7c5dd554654045308f2341713c3e52cc790beb59 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <algorithm>
#define MAX_N 1024
using namespace std;
int pos[MAX_N];
int K, N;
int main()
{
scanf("%d", &K);
L1:
while (K--)
{
scanf("%d", &N);
for (int i = 0; i < N; i++)
scanf("%d", &pos[i]);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (i == j)
continue;
if (pos[i] == pos[j] || abs(i - j) == abs(pos[i] - pos[j]))
{
printf("NO\n");
goto L1;
}
}
}
printf("YES\n");
}
return 0;
}
| 16.825 | 75 | 0.325409 | Heliovic |
a2c8029c8c782c30b83c0d09ab05553b9cc210a8 | 213 | cpp | C++ | Recursion/NestedRecursion/main.cpp | rsghotra/AbdulBari | 2d2845608840ddda6e5153ec91966110ca7e25f5 | [
"Apache-2.0"
] | 1 | 2020-12-02T09:21:52.000Z | 2020-12-02T09:21:52.000Z | Recursion/NestedRecursion/main.cpp | rsghotra/AbdulBari | 2d2845608840ddda6e5153ec91966110ca7e25f5 | [
"Apache-2.0"
] | null | null | null | Recursion/NestedRecursion/main.cpp | rsghotra/AbdulBari | 2d2845608840ddda6e5153ec91966110ca7e25f5 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int fun(int n) {
if(n>100) {
return n - 10;
}
return fun(fun(n+11));
}
int main() {
int r;
r = fun(1);
cout << r << endl;
return 0;
} | 12.529412 | 26 | 0.488263 | rsghotra |
a2c8da167c6bc0830793b05dd9599c82aab490a8 | 4,847 | hpp | C++ | pooling.hpp | CP-Panizza/Num | f1e21c1ebba7519e3b70e9259a8ee2bd99d4942f | [
"MIT"
] | 3 | 2020-06-22T14:46:42.000Z | 2020-07-04T07:58:53.000Z | pooling.hpp | CP-Panizza/CNN | f1e21c1ebba7519e3b70e9259a8ee2bd99d4942f | [
"MIT"
] | null | null | null | pooling.hpp | CP-Panizza/CNN | f1e21c1ebba7519e3b70e9259a8ee2bd99d4942f | [
"MIT"
] | null | null | null | #ifndef _POOLING_HPP_
#define _POOLING_HPP_
#include "matrix.hpp"
#include "utils.h"
#include <vector>
class Pooling {
public:
int pool_size;
int stride;
std::vector<std::vector<Matrix<double> *>> *mask = nullptr;
std::vector<int> out_shape; //输出的维度信息 N,C,H,W
std::vector<int> input_shape;
Pooling(int pool_size, int stride, std::vector<int> &input_shape) : pool_size(pool_size), stride(stride) {
this->input_shape = input_shape;
int N = input_shape[0], C = input_shape[1], H = input_shape[2], W = input_shape[3];
int out_h = 1 + (H - this->pool_size) / this->stride;
int out_w = 1 + (W - this->pool_size) / this->stride;
out_shape.push_back(N);
out_shape.push_back(C);
out_shape.push_back(out_h);
out_shape.push_back(out_w);
}
std::vector<std::vector<Matrix<double> *> > *forward(std::vector<std::vector<Matrix<double> *> > *x) {
int N = static_cast<int>(x->size()), C = static_cast<int>(((*x)[0]).size()), H = ((*x)[0])[0]->height, W = ((*x)[0])[0]->width;
int out_h = 1 + (H - this->pool_size) / this->stride;
int out_w = 1 + (W - this->pool_size) / this->stride;
//回收上次循环的内存
if (this->mask != nullptr) {
free_data(this->mask);
this->mask = nullptr;
}
//初始化输出和mask标记
this->mask = new std::vector<std::vector<Matrix<double> *>>;
auto out = new std::vector<std::vector<Matrix<double> *>>;
for (int i = 0; i < N; ++i) {
this->mask->push_back(std::vector<Matrix<double> *>(C));
out->push_back(std::vector<Matrix<double> *>(C));
}
Matrix<double> *mat = nullptr;
Matrix<double> *each_mask = nullptr;
Matrix<double> *sub_mat = nullptr;
double *line = nullptr;
double max_val = 0;
int max_idx = 0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < C; ++j) {
mat = new Matrix<double>(out_h, out_w);
each_mask = new Matrix<double>(out_h, out_w);
for (int h = 0, m = 0; h <= H - this->pool_size; h += this->stride, ++m) {
for (int w = 0, n = 0; w <= W - this->pool_size; w += this->stride, ++n) {
sub_mat = (*x)[i][j]->SubMat(h, w, this->pool_size, this->pool_size);
line = sub_mat->to_line();
max_val = max(line, this->pool_size * this->pool_size);
max_idx = max_index(line, this->pool_size * this->pool_size);
mat->Set(m, n, max_val);
each_mask->Set(m, n, max_idx);
delete (sub_mat);
delete[](line);
}
}
(*mask)[i][j] = each_mask;
(*out)[i][j] = mat;
}
}
return out;
}
std::vector<std::vector<Matrix<double> *> > *backword(std::vector<std::vector<Matrix<double> *> > *dout) {
//初始化out
int N = this->input_shape[0], C = this->input_shape[1], H = this->input_shape[2], W = this->input_shape[3];
auto out = new std::vector<std::vector<Matrix<double> *>>;
for (int i = 0; i < N; ++i) {
out->push_back(std::vector<Matrix<double> *>(C));
}
for (int i = 0; i < N; ++i) {
for (int j = 0; j < C; ++j) {
(*out)[i][j] = new Matrix<double>(H, W);
}
}
//计算pooling反向传播
Matrix<double> *_mask = nullptr;
int idx;
double val;
int no;
for (int i = 0; i < this->mask->size(); ++i) {
for (int j = 0; j < (*this->mask)[i].size(); ++j) {
_mask = (*this->mask)[i][j];
for (int m = 0; m < _mask->height; m+=this->pool_size) {
for (int n = 0; n < _mask->width; n+=this->pool_size) {
idx = static_cast<int>(_mask->Get(m, n));
val = (*dout)[i][j]->Get(m, n);
no = 0;
for (int k = m * this->stride; k < (m * this->stride) + this->pool_size; ++k) {
for (int p = n * this->stride; p < (n * this->stride) + this->pool_size; ++p) {
if (no++ == idx) {
(*out)[i][j]->Set(k, p, val);
goto done;
}
}
}
done:;
}
}
}
}
return out;
}
};
#endif //_POOLING_HPP_ | 38.165354 | 136 | 0.438828 | CP-Panizza |
a2ca4c13f1112c460ba577ab92c6e14ce5fc2bc8 | 3,982 | cpp | C++ | src/system/libroot/add-ons/icu/ICUCategoryData.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 4 | 2016-03-29T21:45:21.000Z | 2016-12-20T00:50:38.000Z | src/system/libroot/add-ons/icu/ICUCategoryData.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | null | null | null | src/system/libroot/add-ons/icu/ICUCategoryData.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 3 | 2018-12-17T13:07:38.000Z | 2021-09-08T13:07:31.000Z | /*
* Copyright 2010-2011, Oliver Tappe, zooey@hirschkaefer.de.
* Distributed under the terms of the MIT License.
*/
#include "ICUCategoryData.h"
#include <string.h>
#include <unicode/uchar.h>
namespace BPrivate {
namespace Libroot {
ICUCategoryData::ICUCategoryData(pthread_key_t tlsKey)
:
fThreadLocalStorageKey(tlsKey)
{
*fPosixLocaleName = '\0';
*fGivenCharset = '\0';
}
ICUCategoryData::~ICUCategoryData()
{
}
status_t
ICUCategoryData::SetTo(const Locale& locale, const char* posixLocaleName)
{
if (!posixLocaleName)
return B_BAD_VALUE;
fLocale = locale;
strlcpy(fPosixLocaleName, posixLocaleName, skMaxPosixLocaleNameLen);
*fGivenCharset = '\0';
// POSIX locales often contain an embedded charset, but ICU does not
// handle these within locales (that part of the name is simply
// ignored).
// We need to fetch the charset specification and lookup an appropriate
// ICU charset converter. This converter will later be used to get info
// about ctype properties.
const char* charsetStart = strchr(fPosixLocaleName, '.');
if (charsetStart) {
++charsetStart;
int l = 0;
while (charsetStart[l] != '\0' && charsetStart[l] != '@')
++l;
snprintf(fGivenCharset, UCNV_MAX_CONVERTER_NAME_LENGTH, "%.*s", l,
charsetStart);
}
if (!strlen(fGivenCharset))
strcpy(fGivenCharset, "utf-8");
return _SetupConverter();
}
status_t
ICUCategoryData::SetToPosix()
{
fLocale = Locale::createFromName("en_US_POSIX");
strcpy(fPosixLocaleName, "POSIX");
strcpy(fGivenCharset, "US-ASCII");
return _SetupConverter();
}
status_t
ICUCategoryData::_ConvertUnicodeStringToLocaleconvEntry(
const UnicodeString& string, char* destination, int destinationSize,
const char* defaultValue)
{
UConverter* converter;
status_t result = _GetConverter(converter);
if (result != B_OK)
return result;
UErrorCode icuStatus = U_ZERO_ERROR;
ucnv_fromUChars(converter, destination, destinationSize, string.getBuffer(),
string.length(), &icuStatus);
if (!U_SUCCESS(icuStatus)) {
switch (icuStatus) {
case U_BUFFER_OVERFLOW_ERROR:
result = B_NAME_TOO_LONG;
break;
case U_INVALID_CHAR_FOUND:
case U_TRUNCATED_CHAR_FOUND:
case U_ILLEGAL_CHAR_FOUND:
result = B_BAD_DATA;
break;
default:
result = B_ERROR;
break;
}
strlcpy(destination, defaultValue, destinationSize);
}
return result;
}
status_t
ICUCategoryData::_GetConverter(UConverter*& converterOut)
{
// we use different converters per thread to avoid concurrent accesses
ICUThreadLocalStorageValue* tlsValue = NULL;
status_t result = ICUThreadLocalStorageValue::GetInstanceForKey(
fThreadLocalStorageKey, tlsValue);
if (result != B_OK)
return result;
if (tlsValue->converter != NULL) {
if (strcmp(tlsValue->charset, fGivenCharset) == 0) {
converterOut = tlsValue->converter;
return B_OK;
}
// charset no longer matches the converter, we need to dump it and
// create a new one
ucnv_close(tlsValue->converter);
tlsValue->converter = NULL;
}
// create a new converter for the current charset
UErrorCode icuStatus = U_ZERO_ERROR;
UConverter* icuConverter = ucnv_open(fGivenCharset, &icuStatus);
if (icuConverter == NULL)
return B_NAME_NOT_FOUND;
// setup the new converter to stop upon any errors
icuStatus = U_ZERO_ERROR;
ucnv_setToUCallBack(icuConverter, UCNV_TO_U_CALLBACK_STOP, NULL, NULL, NULL,
&icuStatus);
if (!U_SUCCESS(icuStatus)) {
ucnv_close(icuConverter);
return B_ERROR;
}
icuStatus = U_ZERO_ERROR;
ucnv_setFromUCallBack(icuConverter, UCNV_FROM_U_CALLBACK_STOP, NULL, NULL,
NULL, &icuStatus);
if (!U_SUCCESS(icuStatus)) {
ucnv_close(icuConverter);
return B_ERROR;
}
tlsValue->converter = icuConverter;
strlcpy(tlsValue->charset, fGivenCharset, sizeof(tlsValue->charset));
converterOut = icuConverter;
return B_OK;
}
status_t
ICUCategoryData::_SetupConverter()
{
UConverter* converter;
return _GetConverter(converter);
}
} // namespace Libroot
} // namespace BPrivate
| 23.151163 | 77 | 0.741336 | axeld |
a2cf8e32027366a348ac340ac7a8fb437954ad21 | 709 | cpp | C++ | src/tests/test_uuids.cpp | ondra-novak/couchit | 10af4464327dcc2aeb470fe2db7fbd1594ff1b0d | [
"MIT"
] | 4 | 2017-03-20T22:14:10.000Z | 2018-03-21T09:24:32.000Z | src/tests/test_uuids.cpp | ondra-novak/couchit | 10af4464327dcc2aeb470fe2db7fbd1594ff1b0d | [
"MIT"
] | null | null | null | src/tests/test_uuids.cpp | ondra-novak/couchit | 10af4464327dcc2aeb470fe2db7fbd1594ff1b0d | [
"MIT"
] | null | null | null | /*
* test_uuids.cpp
*
* Created on: 10. 3. 2016
* Author: ondra
*/
#include <iostream>
#include <set>
#include <chrono>
#include <thread>
#include "../couchit/couchDB.h"
#include "test_common.h"
#include "testClass.h"
namespace couchit {
using namespace json;
static void genFastUUIDS(std::ostream &print) {
std::set<String> uuidmap;
CouchDB db(getTestCouch());
for (std::size_t i = 0; i < 50; i++) {
String uuid ( db.genUID("test-"));
std::cout << uuid << std::endl;
uuidmap.insert(uuid);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
print << uuidmap.size();
}
void testUUIDs(TestSimple &tst) {
tst.test("couchdb.genfastuid","50") >> &genFastUUIDS;
}
}
| 16.488372 | 62 | 0.651622 | ondra-novak |
a2cfb318bdb4cf5e13a620e544f649b8661f2adc | 966 | cpp | C++ | source/vmalloc.cpp | EthanArmbrust/snes9xgx | 4e11dc00b3672fe4f0979317cca35ce97d1c2d09 | [
"Xnet",
"X11"
] | 294 | 2016-07-09T01:13:19.000Z | 2022-03-28T02:59:29.000Z | source/vmalloc.cpp | EthanArmbrust/snes9xgx | 4e11dc00b3672fe4f0979317cca35ce97d1c2d09 | [
"Xnet",
"X11"
] | 173 | 2016-07-30T16:20:25.000Z | 2022-02-20T10:46:45.000Z | source/vmalloc.cpp | EthanArmbrust/snes9xgx | 4e11dc00b3672fe4f0979317cca35ce97d1c2d09 | [
"Xnet",
"X11"
] | 167 | 2016-07-19T20:33:43.000Z | 2022-03-15T18:09:15.000Z | /****************************************************************************
* Snes9x Nintendo Wii/Gamecube Port
*
* emu_kidid 2015-2018
*
* vmalloc.cpp
*
* GC VM memory allocator
***************************************************************************/
#ifdef USE_VM
#include <ogc/machine/asm.h>
#include <ogc/lwp_heap.h>
#include <ogc/system.h>
#include <ogc/machine/processor.h>
#include "utils/vm/vm.h"
static heap_cntrl vm_heap;
static int vm_initialised = 0;
void InitVmManager ()
{
__lwp_heap_init(&vm_heap, (void *)ARAM_VM_BASE, ARAM_SIZE, 32);
vm_initialised = 1;
}
void* vm_malloc(u32 size)
{
if(!vm_initialised) InitVmManager();
return __lwp_heap_allocate(&vm_heap, size);
}
bool vm_free(void *ptr)
{
if(!vm_initialised) InitVmManager();
return __lwp_heap_free(&vm_heap, ptr);
}
int vm_size_free()
{
if(!vm_initialised) InitVmManager();
heap_iblock info;
__lwp_heap_getinfo(&vm_heap,&info);
return info.free_size;
}
#endif
| 19.32 | 77 | 0.610766 | EthanArmbrust |
a2d3043363fd73b00732cc491b0aed535701fbdd | 5,792 | cc | C++ | chrome/browser/ui/views/extensions/bookmark_app_confirmation_view.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | chrome/browser/ui/views/extensions/bookmark_app_confirmation_view.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | chrome/browser/ui/views/extensions/bookmark_app_confirmation_view.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.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 "chrome/browser/ui/views/extensions/bookmark_app_confirmation_view.h"
#include "base/callback_helpers.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "chrome/grit/generated_resources.h"
#include "components/constrained_window/constrained_window_views.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_contents.h"
#include "extensions/common/constants.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_source.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_client_view.h"
namespace {
// Minimum width of the the bubble.
const int kMinBubbleWidth = 300;
// Size of the icon.
const int kIconSize = extension_misc::EXTENSION_ICON_MEDIUM;
class WebAppInfoImageSource : public gfx::ImageSkiaSource {
public:
WebAppInfoImageSource(int dip_size, const WebApplicationInfo& info)
: dip_size_(dip_size), info_(info) {}
~WebAppInfoImageSource() override {}
private:
gfx::ImageSkiaRep GetImageForScale(float scale) override {
int size = base::saturated_cast<int>(dip_size_ * scale);
for (const auto& icon_info : info_.icons) {
if (icon_info.width == size)
return gfx::ImageSkiaRep(icon_info.data, scale);
}
return gfx::ImageSkiaRep();
}
int dip_size_;
WebApplicationInfo info_;
};
} // namespace
BookmarkAppConfirmationView::~BookmarkAppConfirmationView() {}
// static
void BookmarkAppConfirmationView::CreateAndShow(
gfx::NativeWindow parent,
const WebApplicationInfo& web_app_info,
const BrowserWindow::ShowBookmarkAppBubbleCallback& callback) {
constrained_window::CreateBrowserModalDialogViews(
new BookmarkAppConfirmationView(web_app_info, callback), parent)
->Show();
}
BookmarkAppConfirmationView::BookmarkAppConfirmationView(
const WebApplicationInfo& web_app_info,
const BrowserWindow::ShowBookmarkAppBubbleCallback& callback)
: web_app_info_(web_app_info),
callback_(callback),
open_as_window_checkbox_(nullptr),
title_tf_(nullptr) {
views::BoxLayout* layout = new views::BoxLayout(
views::BoxLayout::kHorizontal, views::kButtonHEdgeMarginNew,
views::kButtonHEdgeMarginNew, views::kButtonHEdgeMarginNew);
layout->set_cross_axis_alignment(
views::BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER);
SetLayoutManager(layout);
views::ImageView* icon_image_view = new views::ImageView();
gfx::Size image_size(kIconSize, kIconSize);
gfx::ImageSkia image(new WebAppInfoImageSource(kIconSize, web_app_info_),
image_size);
icon_image_view->SetImageSize(image_size);
icon_image_view->SetImage(image);
AddChildView(icon_image_view);
title_tf_ = new views::Textfield();
title_tf_->SetText(web_app_info_.title);
title_tf_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_BOOKMARK_APP_AX_BUBBLE_NAME_LABEL));
title_tf_->set_controller(this);
AddChildView(title_tf_);
layout->SetFlexForView(title_tf_, 1);
title_tf_->SelectAll(true);
}
views::View* BookmarkAppConfirmationView::GetInitiallyFocusedView() {
return title_tf_;
}
ui::ModalType BookmarkAppConfirmationView::GetModalType() const {
return ui::MODAL_TYPE_WINDOW;
}
base::string16 BookmarkAppConfirmationView::GetWindowTitle() const {
#if defined(USE_ASH)
int ids = IDS_ADD_TO_SHELF_BUBBLE_TITLE;
#else
int ids = IDS_ADD_TO_DESKTOP_BUBBLE_TITLE;
#endif
return l10n_util::GetStringUTF16(ids);
}
bool BookmarkAppConfirmationView::ShouldShowCloseButton() const {
return false;
}
void BookmarkAppConfirmationView::WindowClosing() {
if (!callback_.is_null())
callback_.Run(false, web_app_info_);
}
views::View* BookmarkAppConfirmationView::CreateExtraView() {
open_as_window_checkbox_ = new views::Checkbox(
l10n_util::GetStringUTF16(IDS_BOOKMARK_APP_BUBBLE_OPEN_AS_WINDOW));
open_as_window_checkbox_->SetChecked(web_app_info_.open_as_window);
return open_as_window_checkbox_;
}
bool BookmarkAppConfirmationView::Accept() {
web_app_info_.title = GetTrimmedTitle();
web_app_info_.open_as_window = open_as_window_checkbox_->checked();
base::ResetAndReturn(&callback_).Run(true, web_app_info_);
return true;
}
base::string16 BookmarkAppConfirmationView::GetDialogButtonLabel(
ui::DialogButton button) const {
return l10n_util::GetStringUTF16(button == ui::DIALOG_BUTTON_OK ? IDS_ADD
: IDS_CANCEL);
}
bool BookmarkAppConfirmationView::IsDialogButtonEnabled(
ui::DialogButton button) const {
return button == ui::DIALOG_BUTTON_OK ? !GetTrimmedTitle().empty() : true;
}
gfx::Size BookmarkAppConfirmationView::GetMinimumSize() const {
gfx::Size size(views::DialogDelegateView::GetPreferredSize());
size.SetToMax(gfx::Size(kMinBubbleWidth, 0));
return size;
}
void BookmarkAppConfirmationView::ContentsChanged(
views::Textfield* sender,
const base::string16& new_contents) {
DCHECK_EQ(title_tf_, sender);
GetDialogClientView()->UpdateDialogButtons();
}
base::string16 BookmarkAppConfirmationView::GetTrimmedTitle() const {
base::string16 title(title_tf_->text());
base::TrimWhitespace(title, base::TRIM_ALL, &title);
return title;
}
| 33.479769 | 80 | 0.762258 | google-ar |
a2d36653fd6175ddc06d4d8b07e6f0e828a579e7 | 1,018 | hpp | C++ | src/sort_test.hpp | loryruta/gpu-radix-sort | 39a973e46834dd7f06a8855e95aa3b3cc7e1709e | [
"MIT"
] | 6 | 2021-11-11T09:12:10.000Z | 2022-03-05T15:56:16.000Z | src/sort_test.hpp | rutay/parallel-radix-sort | 39a973e46834dd7f06a8855e95aa3b3cc7e1709e | [
"MIT"
] | null | null | null | src/sort_test.hpp | rutay/parallel-radix-sort | 39a973e46834dd7f06a8855e95aa3b3cc7e1709e | [
"MIT"
] | 1 | 2021-11-09T06:51:18.000Z | 2021-11-09T06:51:18.000Z | #pragma once
#include "generated/radix_sort.hpp"
namespace rgc::radix_sort
{
class array_compare
{
private:
program m_program;
GLuint m_errors_counter;
GLuint m_error_marks_buf;
public:
array_compare(size_t max_arr_len);
~array_compare();
GLuint compare(GLuint arr_1, GLuint arr_2, size_t arr_len);
};
class check_permuted
{
private:
GLuint m_max_val;
array_compare m_array_compare;
program m_count_elements_program;
GLuint m_original_counts_buf;
GLuint m_permuted_counts_buf;
void count_elements(GLuint arr, size_t arr_len, GLuint counts_buf);
public:
check_permuted(GLuint max_val); // min_val = 0
~check_permuted();
void memorize_original_array(GLuint arr, size_t arr_len);
void memorize_permuted_array(GLuint arr, size_t arr_len);
bool is_permuted();
};
class check_sorted
{
private:
program m_program;
GLuint m_errors_counter;
public:
check_sorted();
~check_sorted();
bool is_sorted(GLuint arr, size_t arr_len, GLuint* errors_count);
};
}
| 17.551724 | 69 | 0.753438 | loryruta |
a2d42874d1c5b9c1d5f9474430caee9552b111fc | 3,683 | cpp | C++ | Algorithm/src/algorithm/leetcode/two_sum.cpp | elloop/algorithm | 5485be0aedbc18968f775cff9533a2d444dbdcb5 | [
"MIT"
] | 15 | 2015-11-04T12:53:23.000Z | 2021-08-10T09:53:12.000Z | Algorithm/src/algorithm/leetcode/two_sum.cpp | elloop/algorithm | 5485be0aedbc18968f775cff9533a2d444dbdcb5 | [
"MIT"
] | null | null | null | Algorithm/src/algorithm/leetcode/two_sum.cpp | elloop/algorithm | 5485be0aedbc18968f775cff9533a2d444dbdcb5 | [
"MIT"
] | 6 | 2015-11-13T10:17:01.000Z | 2020-05-14T07:25:48.000Z | #include <map>
#include <string>
#include <cstring>
#include <iostream>
#include <vector>
#include "inc.h"
#include "valid_parentheses.h"
#include "rotate_array.h"
#include "title_to_number.h"
#include "trailing_zeroes.h"
#include "column_to_title.h"
#include "compare_version.h"
#include "intersection_of_linklist.h"
#include "zig_zag.h"
#include "min_stack.h"
#include "gtest/gtest.h"
NS_BEGIN(elloop);
using std::vector;
using std::map;
class S {
public:
static vector<int> solve(vector<int>& numbers, int target) {
vector<int> result;
vector<int>::size_type i(0);
map<int, int> half;
for (; i<numbers.size(); ++i) {
if (half.find(numbers[i]) != half.end()) {
result.push_back(half.find(numbers[i])->second);
result.push_back(i+1);
return result;
}
else {
half.insert(std::make_pair(target-numbers[i], i+1));
}
}
return result;
}
};
BEGIN_TEST(TwoSum, Test1, @@);
/*
int a[] = {1, 2, 3, 4, 5, 6, 7, 8};
vector<int> src;
src.assign(a, a+sizeof a / sizeof a[0]);
int target = a[2] + a[3];
vector<int> result = S::solve(src, target);
for (auto i : result) {
pln(i);
}
*/
// TODO: more solutions.
// valid_parentheses::Solution s;
// string str("()[]}");
// psln(s.isValid(str));
rotate_array::Solution s;
int nums[] = {1, 2, 3, 4, 5};
int k = 6;
s.rotate(nums, sizeof nums/ sizeof nums[0], k);
// TODO: make a summary about memcpy and memmove.
// test memcpy and memmove.
// int a[] = {1, 2, 3, 4};
// int b[] = {0, 0, 0,0,0};
// int n(4);
// // ::memcpy(b+1, (int*)a, sizeof (int) * (n));
// ::memmove(a+1, a, sizeof (int) *(n-1));
// ::memcpy(a+1, a, sizeof (int) *(n-1));
// print_array(a);
// title_to_number::Solution s;
// psln(s.titleToNumber("ZA"));
// trailing_zeroes::Solution s;
// psln(s.trailingZeroes(4));
// psln(s.trailingZeroes(2147483647));
// for (int i=4; i<250; ) {
// p(i); p(": ");
// pln(s.trailingZeroes(i));
// i += 5;
// }
// compare_version::Solution s;
// psln(s.compareVersion("1", "2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.10000.1.1.1.1.1.2.3.4.5.6.7"));
// psln(s.compareVersion("1.1.0", "1.1"));
// string s1("01");
// string s2("1");
// vector<int> x = s.getNumbers(s1);
// vector<int> x2 = s.getNumbers(s2);
// int i = x.size();
// int j = x2.size();
// psln(i);
// psln(j);
// psln(s.compareVersion(s1, s2));
// string v1, v2;
// while (cin >> v1 >> v2) {
// psln(s.compareVersion(v1, v2));
// }
// column_to_title::Solution s;
// s.convertToTitle(52);
// using namespace intersection_of_linklist;
// intersection_of_linklist::Solution s;
// Solution::ListNode * p = new Solution::ListNode[13];
// Solution::ListNode * q = new Solution::ListNode[13];
// psln(s.getIntersectionNode(p, q));
// delete p;
// delete q;
// zig_zag::Solution s;
// psln(s.convert("PAYPALISHIRING", 3));
// char str[] = "hello";
// string s(str, str + 5);
// psln(s);
/* using min_stack::MinStack; */
// MinStack s;
// s.push(10);
// s.push(11);
// s.push(1);
// psln(s.top());
// s.pop();
// psln(s.top());
/* psln(s.getMin()); */
// using min_stack::MinStack2;
// MinStack2 s;
// s.push(2147483646);
// s.push(2147483646);
// s.push(2147483647);
// psln(s.top());
// s.pop();
// psln(s.getMin());
// s.pop();
// psln(s.getMin());
// s.pop();
// s.push(2147483647);
// psln(s.top());
// psln(s.getMin());
// s.push(-2147483648);
// psln(s.top());
// psln(s.getMin());
// s.pop();
// psln(s.getMin());
END_TEST;
NS_END(elloop);
| 22.053892 | 96 | 0.555797 | elloop |
a2d544b2a2cdefa656d835063c5de87b0fc3b3af | 520 | hpp | C++ | Engine/Include/FishEngine/BoxCollider.hpp | ValtoGameEngines/Fish-Engine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 240 | 2017-02-17T10:08:19.000Z | 2022-03-25T14:45:29.000Z | Engine/Include/FishEngine/BoxCollider.hpp | ValtoGameEngines/Fish-Engine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 2 | 2016-10-12T07:08:38.000Z | 2017-04-05T01:56:30.000Z | Engine/Include/FishEngine/BoxCollider.hpp | yushroom/FishEngine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 39 | 2017-03-02T09:40:07.000Z | 2021-12-04T07:28:53.000Z | #ifndef BoxCollider_hpp
#define BoxCollider_hpp
#include "Collider.hpp"
namespace FishEngine
{
class FE_EXPORT BoxCollider : public Collider
{
public:
DefineComponent(BoxCollider);
BoxCollider() = default;
BoxCollider(const Vector3& center,
const Vector3& size);
virtual void OnDrawGizmosSelected() override;
private:
friend class FishEditor::Inspector;
Vector3 m_center{0, 0, 0};
Vector3 m_size{1, 1, 1};
virtual void CreatePhysicsShape() override;
};
}
#endif // BoxCollider_hpp
| 17.931034 | 47 | 0.730769 | ValtoGameEngines |
a2d8479782400383e3d78a74f87c83433c137a8a | 5,500 | cpp | C++ | src/bls12_381/curve.cpp | gtfierro/jedi-pairing | 07791509e7702094118eba34337868a646363dc2 | [
"BSD-3-Clause"
] | 4 | 2020-10-27T09:38:17.000Z | 2021-11-01T07:05:34.000Z | src/bls12_381/curve.cpp | gtfierro/jedi-pairing | 07791509e7702094118eba34337868a646363dc2 | [
"BSD-3-Clause"
] | null | null | null | src/bls12_381/curve.cpp | gtfierro/jedi-pairing | 07791509e7702094118eba34337868a646363dc2 | [
"BSD-3-Clause"
] | 2 | 2021-08-09T06:27:46.000Z | 2021-08-09T19:55:07.000Z | /*
* Copyright (c) 2018, Sam Kumar <samkumar@cs.berkeley.edu>
* Copyright (c) 2018, University of California, Berkeley
* 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. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdint.h>
#include "bls12_381/fq.hpp"
#include "bls12_381/fq2.hpp"
#include "bls12_381/curve.hpp"
namespace embedded_pairing::bls12_381 {
extern constexpr Fq g1_b_coeff_var = g1_b_coeff;
extern constexpr Fq2 g2_b_coeff_var = g2_b_coeff;
template <typename Projective, typename Affine, typename BaseField>
void sample_random_generator(Projective& result, void (*get_random_bytes)(void*, size_t)) {
do {
Affine random;
BaseField x;
unsigned char b;
do {
x.random(get_random_bytes);
get_random_bytes(&b, sizeof(b));
} while (!random.get_point_from_x(x, (b & 0x1) == 0x1, true));
result.multiply(random, Affine::cofactor);
} while (result.is_zero());
}
void G1::random_generator(void (*get_random_bytes)(void*, size_t)) {
sample_random_generator<G1, G1Affine, Fq>(*this, get_random_bytes);
}
void G2::random_generator(void (*get_random_bytes)(void*, size_t)) {
sample_random_generator<G2, G2Affine, Fq2>(*this, get_random_bytes);
}
/* Procedures for encoding/decoding. */
template <typename Affine, bool compressed>
void Encoding<Affine, compressed>::encode(const Affine& g) {
if (g.is_zero()) {
memset(this->data, 0x0, sizeof(this->data));
this->data[0] = encoding_flags_infinity;
} else {
g.x.write_big_endian(&this->data[0]);
if constexpr(compressed) {
typename Affine::BaseFieldType negy;
negy.negate(g.y);
if (Affine::BaseFieldType::compare(g.y, negy) == 1) {
this->data[0] |= encoding_flags_greater;
}
} else {
g.y.write_big_endian(&this->data[sizeof(typename Affine::BaseFieldType)]);
}
}
if constexpr(compressed) {
this->data[0] |= encoding_flags_compressed;
}
}
template <typename Affine, bool compressed>
bool Encoding<Affine, compressed>::decode(Affine& g, bool checked) const {
if (checked && is_encoding_compressed(this->data[0]) != compressed) {
return false;
}
if ((this->data[0] & encoding_flags_infinity) != 0) {
if (checked) {
if ((this->data[0] & ~(encoding_flags_compressed | encoding_flags_infinity)) != 0) {
return false;
}
for (int i = 1; i != sizeof(this->data); i++) {
if (this->data[i] != 0) {
return false;
}
}
}
g.copy(Affine::zero);
return true;
}
/* The "read_big_endian" method masks off the three control bits. */
g.x.read_big_endian(&this->data[0]);
bool greater = ((this->data[0] & encoding_flags_greater) != 0);
if constexpr(compressed) {
if (!g.get_point_from_x(g.x, greater, checked)) {
return false;
}
} else {
if (checked && greater) {
return false;
}
g.y.read_big_endian(&this->data[sizeof(typename Affine::BaseFieldType)]);
g.infinity = false;
}
if (checked) {
if constexpr(!compressed) {
if (!g.is_on_curve()) {
return false;
}
}
return g.is_in_correct_subgroup_assuming_on_curve();
}
return true;
}
/* Explicitly instantiate Encoding templates. */
template struct Encoding<G1Affine, false>;
template struct Encoding<G1Affine, true>;
template struct Encoding<G2Affine, false>;
template struct Encoding<G2Affine, true>;
}
| 37.671233 | 100 | 0.613818 | gtfierro |
a2d84d1679838c077a221790b77f4531e41ae4a5 | 5,695 | cpp | C++ | modules/task_3/kudriavtsev_a_radix_sort/main.cpp | Vodeneev/pp_2020_autumn_math | 9b7e5ec56e09474c9880810a6124e3e416bb7e16 | [
"BSD-3-Clause"
] | null | null | null | modules/task_3/kudriavtsev_a_radix_sort/main.cpp | Vodeneev/pp_2020_autumn_math | 9b7e5ec56e09474c9880810a6124e3e416bb7e16 | [
"BSD-3-Clause"
] | null | null | null | modules/task_3/kudriavtsev_a_radix_sort/main.cpp | Vodeneev/pp_2020_autumn_math | 9b7e5ec56e09474c9880810a6124e3e416bb7e16 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 Kudriavtsev Alexander
#include <gtest-mpi-listener.hpp>
#include <gtest/gtest.h>
#include <vector>
#include <algorithm>
#include "./ops_mpi.h"
TEST(Parallel_Operations_MPI, Test_Seq_20) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1;
const int n = 20;
if (rank == 0) {
std::vector<int> vec2 = vec1 = getRandomVector(n);
double t_b = MPI_Wtime();
radixSort(vec1.data(), n);
double t_e = MPI_Wtime();
std::cout << "Sequential time: " << t_e - t_b << std::endl;
std::sort(vec2.begin(), vec2.end());
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Seq_2000) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1;
const int n = 20;
if (rank == 0) {
std::vector<int> vec2 = vec1 = getRandomVector(n);
double t_b = MPI_Wtime();
radixSort(vec1.data(), n);
double t_e = MPI_Wtime();
std::cout << "Sequential time: " << t_e - t_b << std::endl;
std::sort(vec2.begin(), vec2.end());
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Seq_20000) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1;
const int n = 20;
if (rank == 0) {
std::vector<int> vec2 = vec1 = getRandomVector(n);
double t_b = MPI_Wtime();
radixSort(vec1.data(), n);
double t_e = MPI_Wtime();
std::cout << "Sequential time: " << t_e - t_b << std::endl;
std::sort(vec2.begin(), vec2.end());
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Par_20) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1, vec2;
const int n = 20;
if (rank == 0) {
vec2 = vec1 = getRandomVector(n);
}
parallelRadixSort(vec1.data(), n);
if (rank == 0) {
std::sort(vec2.begin(), vec2.end());
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Par_2000) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1, vec2;
const int n = 2000;
if (rank == 0) {
vec2 = vec1 = getRandomVector(n);
}
parallelRadixSort(vec1.data(), n);
if (rank == 0) {
std::sort(vec2.begin(), vec2.end());
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Par_3041) { // Simple Number
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1, vec2;
const int n = 3041;
if (rank == 0) {
vec2 = vec1 = getRandomVector(n);
}
parallelRadixSort(vec1.data(), n);
if (rank == 0) {
std::sort(vec2.begin(), vec2.end());
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Par_43201) { // Big Simple Number
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1, vec2;
const int n = 43201;
if (rank == 0) {
vec2 = vec1 = getRandomVector(n);
}
parallelRadixSort(vec1.data(), n);
if (rank == 0) {
std::sort(vec2.begin(), vec2.end());
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Par_1000000) { // Big Number 1
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1, vec2;
const int n = 1000000;
if (rank == 0) {
vec2 = vec1 = getRandomVector(n);
}
parallelRadixSort(vec1.data(), n);
if (rank == 0) {
double t_b = MPI_Wtime();
radixSort(vec2.data(), n);
double t_e = MPI_Wtime();
std::cout << "Sequential time: " << t_e - t_b << std::endl;
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Par_5000000) { // Big Number 2
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1, vec2;
const int n = 5000000;
if (rank == 0) {
vec2 = vec1 = getRandomVector(n);
}
parallelRadixSort(vec1.data(), n);
if (rank == 0) {
double t_b = MPI_Wtime();
radixSort(vec2.data(), n);
double t_e = MPI_Wtime();
std::cout << "Sequential time: " << t_e - t_b << std::endl;
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Par_10000000) { // Big Number 3
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1, vec2;
const int n = 10000000;
if (rank == 0) {
vec2 = vec1 = getRandomVector(n);
}
parallelRadixSort(vec1.data(), n);
if (rank == 0) {
double t_b = MPI_Wtime();
radixSort(vec2.data(), n);
double t_e = MPI_Wtime();
std::cout << "Sequential time: " << t_e - t_b << std::endl;
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 29.35567 | 78 | 0.565233 | Vodeneev |
a2d8901d8495d3a8e2b7fb8f3d03765370e198f1 | 647 | cpp | C++ | heavenLi_pyopengl/hliGLutils/metaUtils/doesDrawCallExist.cpp | iyr/heavenli | 90f2786b0a8934302910f2214e71ee851e678baa | [
"BSD-3-Clause"
] | null | null | null | heavenLi_pyopengl/hliGLutils/metaUtils/doesDrawCallExist.cpp | iyr/heavenli | 90f2786b0a8934302910f2214e71ee851e678baa | [
"BSD-3-Clause"
] | null | null | null | heavenLi_pyopengl/hliGLutils/metaUtils/doesDrawCallExist.cpp | iyr/heavenli | 90f2786b0a8934302910f2214e71ee851e678baa | [
"BSD-3-Clause"
] | null | null | null | using namespace std;
extern map<string, drawCall> drawCalls;
PyObject* doesDrawCallExist_hliGLutils(PyObject* self, PyObject* args) {
PyObject* drawcallPyString;
// Parse Inputs
if ( !PyArg_ParseTuple(args,
"O",
&drawcallPyString
) )
{
Py_RETURN_NONE;
}
// Parse image name
const char* NameChars = PyUnicode_AsUTF8(drawcallPyString);
string NameString = NameChars;
if (doesDrawCallExist(NameString))
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
bool doesDrawCallExist(string drawcall){
if (drawCalls.count(drawcall) > 0) return true;
else return false;
}
| 20.21875 | 72 | 0.669243 | iyr |
a2d900c3523fdbbf7d57d2733c2c8c653159e676 | 33,925 | cpp | C++ | SimpleSvmHook/Logging.cpp | zanzo420/SimpleSvmHook | 7cef39ffad9c15a31615a9b032b910011b3bdb1b | [
"MIT"
] | 194 | 2018-07-02T11:43:47.000Z | 2022-03-24T01:50:07.000Z | SimpleSvmHook/Logging.cpp | zanzo420/SimpleSvmHook | 7cef39ffad9c15a31615a9b032b910011b3bdb1b | [
"MIT"
] | 7 | 2018-09-18T17:33:25.000Z | 2022-03-19T04:13:22.000Z | SimpleSvmHook/Logging.cpp | zanzo420/SimpleSvmHook | 7cef39ffad9c15a31615a9b032b910011b3bdb1b | [
"MIT"
] | 55 | 2018-07-29T19:12:47.000Z | 2022-01-20T13:09:20.000Z | /*!
@file Logging.cpp
@brief Implements interfaces to logging functions.
@details This file is migrated from an old codebase and does not always
align with a coding style used in the rest of files.
@author Satoshi Tanda
@copyright Copyright (c) 2018-2019, Satoshi Tanda. All rights reserved.
*/
#include "Logging.hpp"
#define NTSTRSAFE_NO_CB_FUNCTIONS
#include <ntstrsafe.h>
#pragma prefast(disable : 30030)
#pragma prefast(disable : __WARNING_ERROR, "This is completely bogus.")
EXTERN_C_START
//
// A size for log buffer in NonPagedPool. Two buffers are allocated with this
// size. Exceeded logs are ignored silently. Make it bigger if a buffered log
// size often reach this size.
//
static const ULONG k_LogpBufferSizeInPages = 16;
//
// An actual log buffer size in bytes.
//
static const ULONG k_LogpBufferSize = PAGE_SIZE * k_LogpBufferSizeInPages;
//
// A size that is usable for logging. Minus one because the last byte is kept
// for \0.
//
static const ULONG k_LogpBufferUsableSize = k_LogpBufferSize - 1;
//
// An interval to flush buffered log entries into a log file.
//
static const ULONG k_LogpLogFlushIntervalMsec = 50;
//
// The pool tag.
//
static const ULONG k_LogpPoolTag = 'rgoL';
//
// The mask value to indicate the message was already printed out to debug buffer.
//
static const UCHAR k_MessagePrinted = 0x80;
typedef struct _LOG_BUFFER_INFO
{
//
// A pointer to buffer currently used. It is either LogBuffer1 or LogBuffer2.
//
volatile PSTR LogBufferHead;
//
// A pointer to where the next log should be written.
//
volatile PSTR LogBufferTail;
PSTR LogBuffer1;
PSTR LogBuffer2;
//
// Holds the biggest buffer usage to determine a necessary buffer size.
//
SIZE_T LogMaxUsage;
HANDLE LogFileHandle;
KSPIN_LOCK SpinLock;
ERESOURCE Resource;
BOOLEAN ResourceInitialized;
volatile BOOLEAN BufferFlushThreadShouldBeAlive;
volatile BOOLEAN BufferFlushThreadStarted;
HANDLE BufferFlushThreadHandle;
WCHAR LogFilePath[200];
} LOG_BUFFER_INFO, *PLOG_BUFFER_INFO;
NTKERNELAPI
PCHAR
NTAPI
PsGetProcessImageFileName (
_In_ PEPROCESS Process
);
static DRIVER_REINITIALIZE LogpReinitializationRoutine;
static KSTART_ROUTINE LogpBufferFlushThreadRoutine;
//
// The enabled log level.
//
static ULONG g_LogpDebugFlag;
//
// The log buffer.
//
static LOG_BUFFER_INFO g_LogpLogBufferInfo;
//
// Whether the driver is verified by Driver Verifier.
//
static BOOLEAN g_LogpDriverVerified;
/*!
@brief Tests if the printed bit is on.
@param[in] Message - The log message to test.
@return TRUE if the message has the printed bit; or FALSE.
*/
static
_Check_return_
BOOLEAN
LogpIsPrinted (
_In_ PCSTR Message
)
{
return BooleanFlagOn(Message[0], k_MessagePrinted);
}
/*!
@brief Marks the Message as it is already printed out, or clears the printed
bit and restores it to the original.
@param[in] Message - The log message to set the bit.
@param[in] SetBit - TRUE to set the bit; FALSE t clear the bit.
*/
static
VOID
LogpSetPrintedBit (
_In_ PSTR Message,
_In_ BOOLEAN SetBit
)
{
if (SetBit != FALSE)
{
SetFlag(Message[0], k_MessagePrinted);
}
else
{
ClearFlag(Message[0], k_MessagePrinted);
}
}
/*!
@brief Calls DbgPrintEx() while converting \r\n to \n\0.
@param[in] Message - The log message to print out.
*/
static
VOID
LogpDoDbgPrint (
_In_ PSTR Message
)
{
size_t locationOfCr;
if (BooleanFlagOn(g_LogpDebugFlag, k_LogOptDisableDbgPrint))
{
goto Exit;
}
locationOfCr = strlen(Message) - 2;
Message[locationOfCr] = '\n';
Message[locationOfCr + 1] = ANSI_NULL;
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "%s", Message);
Exit:
return;
}
/*!
@brief Sleep the current thread's execution for milliseconds.
@param[in] Millisecond - The duration to sleep in milliseconds.
*/
LOGGING_PAGED
static
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
LogpSleep (
_In_ LONG Millisecond
)
{
LARGE_INTEGER interval;
PAGED_CODE();
interval.QuadPart = -(10000ll * Millisecond);
(VOID)KeDelayExecutionThread(KernelMode, FALSE, &interval);
}
/*!
@brief Logs the current log entry to and flush the log file.
@param[in] Message - The log message to buffer.
@param[in] Info - Log buffer information.
@return STATUS_SUCCESS on success; otherwise, an appropriate error code.
*/
static
_IRQL_requires_max_(PASSIVE_LEVEL)
_Check_return_
NTSTATUS
LogpWriteMessageToFile (
_In_ PCSTR Message,
_In_ const LOG_BUFFER_INFO* Info
)
{
NTSTATUS status;
IO_STATUS_BLOCK ioStatus;
NT_ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL);
status = ZwWriteFile(Info->LogFileHandle,
nullptr,
nullptr,
nullptr,
&ioStatus,
const_cast<PSTR>(Message),
static_cast<ULONG>(strlen(Message)),
nullptr,
nullptr);
if (!NT_SUCCESS(status))
{
//
// It could happen when you did not register IRP_SHUTDOWN and call
// LogIrpShutdownHandler() and the system tried to log to a file after
// a file system was unmounted.
//
goto Exit;
}
status = ZwFlushBuffersFile(Info->LogFileHandle, &ioStatus);
if (!NT_SUCCESS(status))
{
goto Exit;
}
Exit:
return status;
}
/*!
@brief Buffers the log entry to the log buffer.
@param[in] Message - The log message to buffer.
@param[in,out] Info - Log buffer information.
@return STATUS_SUCCESS on success; otherwise, an appropriate error code.
*/
static
_Check_return_
NTSTATUS
LogpBufferMessage (
_In_ PCSTR Message,
_Inout_ PLOG_BUFFER_INFO Info
)
{
NTSTATUS status;
KLOCK_QUEUE_HANDLE lockHandle;
KIRQL oldIrql;
SIZE_T usedBufferSize;
//
// Acquire a spin lock to add the log safely.
//
oldIrql = KeGetCurrentIrql();
if (oldIrql < DISPATCH_LEVEL)
{
KeAcquireInStackQueuedSpinLock(&Info->SpinLock, &lockHandle);
}
else
{
KeAcquireInStackQueuedSpinLockAtDpcLevel(&Info->SpinLock, &lockHandle);
}
NT_ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL);
//
// Copy the current log to the buffer.
//
usedBufferSize = Info->LogBufferTail - Info->LogBufferHead;
status = RtlStringCchCopyA(const_cast<PSTR>(Info->LogBufferTail),
k_LogpBufferUsableSize - usedBufferSize,
Message);
//
// Update Info.LogMaxUsage if necessary.
//
if (NT_SUCCESS(status))
{
size_t messageLength;
messageLength = strlen(Message) + 1;
Info->LogBufferTail += messageLength;
usedBufferSize += messageLength;
if (usedBufferSize > Info->LogMaxUsage)
{
Info->LogMaxUsage = usedBufferSize;
}
}
else
{
Info->LogMaxUsage = k_LogpBufferSize;
}
*Info->LogBufferTail = ANSI_NULL;
if (oldIrql < DISPATCH_LEVEL)
{
KeReleaseInStackQueuedSpinLock(&lockHandle);
}
else
{
KeReleaseInStackQueuedSpinLockFromDpcLevel(&lockHandle);
}
return status;
}
/*!
@brief Processes all buffered log messages.
@param[in,out] Info - Log buffer information.
@details This function switches the current log buffer, saves the contents
of old buffer to the log file, and prints them out as necessary. This
function does not flush the log file, so code should call
LogpWriteMessageToFile() or ZwFlushBuffersFile() later.
*/
static
_Check_return_
NTSTATUS
LogpFlushLogBuffer (
_Inout_ PLOG_BUFFER_INFO Info
)
{
NTSTATUS status;
KLOCK_QUEUE_HANDLE lockHandle;
PSTR oldLogBuffer;
IO_STATUS_BLOCK ioStatus;
NT_ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL);
status = STATUS_SUCCESS;
//
// Enter a critical section and acquire a reader lock for Info in order to
// write a log file safely.
//
ExEnterCriticalRegionAndAcquireResourceExclusive(&Info->Resource);
//
// Acquire a spin lock for Info.LogBuffer(s) in order to switch its head
// safely.
//
KeAcquireInStackQueuedSpinLock(&Info->SpinLock, &lockHandle);
oldLogBuffer = Info->LogBufferHead;
Info->LogBufferHead = (oldLogBuffer == Info->LogBuffer1) ? Info->LogBuffer2
: Info->LogBuffer1;
Info->LogBufferHead[0] = ANSI_NULL;
Info->LogBufferTail = Info->LogBufferHead;
KeReleaseInStackQueuedSpinLock(&lockHandle);
//
// Write all log entries in old log buffer.
//
for (PSTR currentLogEntry = oldLogBuffer; currentLogEntry[0] != ANSI_NULL; /**/)
{
BOOLEAN printedOut;
size_t entryLength;
//
// Check the printed bit and clear it.
//
printedOut = LogpIsPrinted(currentLogEntry);
LogpSetPrintedBit(currentLogEntry, FALSE);
entryLength = strlen(currentLogEntry);
status = ZwWriteFile(Info->LogFileHandle,
nullptr,
nullptr,
nullptr,
&ioStatus,
currentLogEntry,
static_cast<ULONG>(entryLength),
nullptr,
nullptr);
if (!NT_SUCCESS(status))
{
//
// It could happen when you did not register IRP_SHUTDOWN and call
// LogIrpShutdownHandler() and the system tried to log to a file after
// a file system was unmounted.
//
NOTHING;
}
//
// Print it out if requested and the Message is not already printed out
//
if (printedOut == FALSE)
{
LogpDoDbgPrint(currentLogEntry);
}
currentLogEntry += entryLength + 1;
}
oldLogBuffer[0] = ANSI_NULL;
ExReleaseResourceAndLeaveCriticalRegion(&Info->Resource);
return status;
}
/*!
@brief Returns TRUE when a log file is opened.
@param[in] Info - Log buffer information.
@return TRUE when a log file is opened.
*/
static
_Check_return_
BOOLEAN
LogpIsLogFileActivated (
_In_ const LOG_BUFFER_INFO* Info
)
{
BOOLEAN activated;
if (Info->BufferFlushThreadShouldBeAlive != FALSE)
{
NT_ASSERT(Info->BufferFlushThreadHandle != nullptr);
NT_ASSERT(Info->LogFileHandle != nullptr);
activated = TRUE;
}
else
{
NT_ASSERT(Info->BufferFlushThreadHandle == nullptr);
NT_ASSERT(Info->LogFileHandle == nullptr);
activated = FALSE;
}
return activated;
}
/*!
@brief Returns TRUE when a log file is enabled.
@param[in] Info - Log buffer information.
@return TRUE when a log file is enabled.
*/
static
_Check_return_
BOOLEAN
LogpIsLogFileEnabled (
_In_ const LOG_BUFFER_INFO* Info
)
{
BOOLEAN enabled;
if (Info->LogBuffer1 != nullptr)
{
NT_ASSERT(Info->LogBuffer2 != nullptr);
NT_ASSERT(Info->LogBufferHead != nullptr);
NT_ASSERT(Info->LogBufferTail != nullptr);
enabled = TRUE;
}
else
{
NT_ASSERT(Info->LogBuffer2 == nullptr);
NT_ASSERT(Info->LogBufferHead == nullptr);
NT_ASSERT(Info->LogBufferTail == nullptr);
enabled = FALSE;
}
return enabled;
}
/*!
@brief Returns the function's base name.
@param[in] FunctionName - The function name given by the __FUNCTION__ macro.
@return The function's base name, for example, "MethodName" for
"NamespaceName::ClassName::MethodName".
*/
static
_Check_return_
PCSTR
LogpFindBaseFunctionName (
_In_ PCSTR FunctionName
)
{
PCSTR ptr;
PCSTR name;
name = ptr = FunctionName;
while (*(ptr++) != ANSI_NULL)
{
if (*ptr == ':')
{
name = ptr + 1;
}
}
return name;
}
/*!
@brief Logs the entry according to Attribute and the thread condition.
@param[in] Message - The log message to print or buffer.
@param[in] Attribute - The bit mask indicating how this message should be
printed out.
@return STATUS_SUCCESS on success; otherwise, an appropriate error code.
*/
static
_Check_return_
NTSTATUS
LogpPut (
_In_ PSTR Message,
_In_ ULONG Attribute
)
{
NTSTATUS status;
BOOLEAN callDbgPrint;
PLOG_BUFFER_INFO info;
status = STATUS_SUCCESS;
callDbgPrint = ((!BooleanFlagOn(Attribute, k_LogpLevelOptSafe)) &&
(KeGetCurrentIrql() < CLOCK_LEVEL));
//
// Log the entry to a file or buffer.
//
info = &g_LogpLogBufferInfo;
if (LogpIsLogFileEnabled(info) != FALSE)
{
//
// Can we log it to a file now?
//
if (!BooleanFlagOn(Attribute, k_LogpLevelOptSafe) &&
(KeGetCurrentIrql() == PASSIVE_LEVEL) &&
(LogpIsLogFileActivated(info) != FALSE))
{
#pragma warning(push)
#pragma warning(disable : __WARNING_INFERRED_IRQ_TOO_HIGH)
if (KeAreAllApcsDisabled() == FALSE)
{
//
// Yes, we can. Do it.
//
(VOID)LogpFlushLogBuffer(info);
status = LogpWriteMessageToFile(Message, info);
}
#pragma warning(pop)
}
else
{
//
// No, we cannot. Set the printed bit if needed, and then buffer it.
//
if (callDbgPrint != FALSE)
{
LogpSetPrintedBit(Message, TRUE);
}
status = LogpBufferMessage(Message, info);
LogpSetPrintedBit(Message, FALSE);
}
}
//
// Can it safely be printed?
//
if (callDbgPrint != FALSE)
{
LogpDoDbgPrint(Message);
}
return status;
}
/*!
@brief Concatenates meta information such as the current time and a process
ID to the user supplied log message.
@param[in] Level - The level of this log message.
@param[in] FunctionName - The name of the function originating this log message.
@param[in] LogMessage - The user supplied log message.
@param[out] LogBuffer - Buffer to store the concatenated message.
@param[in] LogBufferLength - The size of buffer in characters.
@return STATUS_SUCCESS on success; otherwise, an appropriate error code.
*/
static
_Check_return_
NTSTATUS
LogpMakePrefix (
_In_ ULONG Level,
_In_ PCSTR FunctionName,
_In_ PCSTR LogMessage,
_Out_writes_z_(LogBufferLength) PSTR LogBuffer,
_In_ SIZE_T LogBufferLength
)
{
NTSTATUS status;
PCSTR levelString;
CHAR time[20];
CHAR functionName[50];
CHAR processorNumber[10];
switch (Level)
{
case k_LogpLevelDebug:
levelString = "DBG\t";
break;
case k_LogpLevelInfo:
levelString = "INF\t";
break;
case k_LogpLevelWarn:
levelString = "WRN\t";
break;
case k_LogpLevelError:
levelString = "ERR\t";
break;
default:
status = STATUS_INVALID_PARAMETER;
goto Exit;
}
//
// Want the current time?
//
if (!BooleanFlagOn(g_LogpDebugFlag, k_LogOptDisableTime))
{
TIME_FIELDS timeFields;
LARGE_INTEGER systemTime, localTime;
KeQuerySystemTime(&systemTime);
ExSystemTimeToLocalTime(&systemTime, &localTime);
RtlTimeToTimeFields(&localTime, &timeFields);
status = RtlStringCchPrintfA(time,
RTL_NUMBER_OF(time),
"%02hd:%02hd:%02hd.%03hd\t",
timeFields.Hour,
timeFields.Minute,
timeFields.Second,
timeFields.Milliseconds);
if (!NT_SUCCESS(status))
{
goto Exit;
}
}
else
{
time[0] = ANSI_NULL;
}
//
// Want the function name?
//
if (!BooleanFlagOn(g_LogpDebugFlag, k_LogOptDisableFunctionName))
{
PCSTR baseFunctionName;
baseFunctionName = LogpFindBaseFunctionName(FunctionName);
status = RtlStringCchPrintfA(functionName,
RTL_NUMBER_OF(functionName),
"%-40s\t",
baseFunctionName);
if (!NT_SUCCESS(status))
{
goto Exit;
}
}
else
{
functionName[0] = ANSI_NULL;
}
//
// Want the processor number?
//
if (!BooleanFlagOn(g_LogpDebugFlag, k_LogOptDisableProcessorNumber))
{
status = RtlStringCchPrintfA(processorNumber,
RTL_NUMBER_OF(processorNumber),
"#%lu\t",
KeGetCurrentProcessorNumberEx(nullptr));
if (!NT_SUCCESS(status))
{
goto Exit;
}
}
else
{
processorNumber[0] = ANSI_NULL;
}
//
// It uses PsGetProcessId(PsGetCurrentProcess()) instead of
// PsGetCurrentThreadProcessId() because the later sometimes returns
// unwanted value, for example, PID == 4 while its image name is not
// ntoskrnl.exe. The author is guessing that it is related to attaching
// processes but not quite sure. The former way works as expected.
//
status = RtlStringCchPrintfA(LogBuffer,
LogBufferLength,
"%s%s%s%5Iu\t%5Iu\t%-15s\t%s%s\r\n",
time,
levelString,
processorNumber,
reinterpret_cast<ULONG_PTR>(PsGetProcessId(PsGetCurrentProcess())),
reinterpret_cast<ULONG_PTR>(PsGetCurrentThreadId()),
PsGetProcessImageFileName(PsGetCurrentProcess()),
functionName,
LogMessage);
if (!NT_SUCCESS(status))
{
goto Exit;
}
Exit:
return status;
}
/*!
@brief Terminates a log file related code.
@param[in] Info - Log buffer information.
*/
LOGGING_PAGED
static
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
LogpCleanupBufferInfo (
_In_ PLOG_BUFFER_INFO Info
)
{
NTSTATUS status;
PAGED_CODE();
//
// Closing the log buffer flush thread.
//
if (Info->BufferFlushThreadHandle != nullptr)
{
Info->BufferFlushThreadShouldBeAlive = FALSE;
status = ZwWaitForSingleObject(Info->BufferFlushThreadHandle, FALSE, nullptr);
NT_ASSERT(NT_SUCCESS(status));
ZwClose(Info->BufferFlushThreadHandle);
Info->BufferFlushThreadHandle = nullptr;
}
//
// Cleaning up other things.
//
if (Info->LogFileHandle != nullptr)
{
ZwClose(Info->LogFileHandle);
Info->LogFileHandle = nullptr;
}
if (Info->LogBuffer2 != nullptr)
{
ExFreePoolWithTag(Info->LogBuffer2, k_LogpPoolTag);
Info->LogBuffer2 = nullptr;
}
if (Info->LogBuffer1 != nullptr)
{
ExFreePoolWithTag(Info->LogBuffer1, k_LogpPoolTag);
Info->LogBuffer1 = nullptr;
}
if (Info->ResourceInitialized != FALSE)
{
ExDeleteResourceLite(&Info->Resource);
Info->ResourceInitialized = FALSE;
}
}
/*!
@brief Initializes a log file and starts a log buffer thread.
@param[in,out] Info - Log buffer information.
@param[out] ReinitRequired - A pointer to receive whether re-initialization
is required.
@return STATUS_SUCCESS on success; otherwise, an appropriate error code.
*/
LOGGING_PAGED
static
_IRQL_requires_max_(PASSIVE_LEVEL)
_Check_return_
NTSTATUS
LogpInitializeLogFile (
_Inout_ PLOG_BUFFER_INFO Info,
_Out_ PBOOLEAN ReinitRequired
)
{
NTSTATUS status;
UNICODE_STRING logFilePathU;
OBJECT_ATTRIBUTES objectAttributes;
IO_STATUS_BLOCK ioStatus;
PAGED_CODE();
*ReinitRequired = FALSE;
if (Info->LogFileHandle != nullptr)
{
status = STATUS_SUCCESS;
goto Exit;
}
//
// Initialize a log file.
//
RtlInitUnicodeString(&logFilePathU, Info->LogFilePath);
InitializeObjectAttributes(&objectAttributes,
&logFilePathU,
OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE,
nullptr,
nullptr);
status = ZwCreateFile(&Info->LogFileHandle,
FILE_APPEND_DATA | SYNCHRONIZE,
&objectAttributes,
&ioStatus,
nullptr,
FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_READ,
FILE_OPEN_IF,
FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE,
nullptr,
0);
if (!NT_SUCCESS(status))
{
goto Exit;
}
//
// Initialize a log buffer flush thread.
//
Info->BufferFlushThreadShouldBeAlive = TRUE;
status = PsCreateSystemThread(&Info->BufferFlushThreadHandle,
THREAD_ALL_ACCESS,
nullptr,
nullptr,
nullptr,
LogpBufferFlushThreadRoutine,
Info);
if (!NT_SUCCESS(status))
{
ZwClose(Info->LogFileHandle);
Info->LogFileHandle = nullptr;
Info->BufferFlushThreadShouldBeAlive = FALSE;
goto Exit;
}
//
// Wait until the thread starts.
//
while (Info->BufferFlushThreadStarted == FALSE)
{
LogpSleep(100);
}
Exit:
if (status == STATUS_OBJECTID_NOT_FOUND)
{
*ReinitRequired = TRUE;
status = STATUS_SUCCESS;
}
return status;
}
/*!
@brief Initializes a log file related code such as a flushing thread.
@param[in] LogFilePath - A log file path.
@param[in,out] Info - Log buffer information.
@param[out] ReinitRequired - A pointer to receive whether re-initialization
is required.
@return STATUS_SUCCESS on success; otherwise, an appropriate error code.
*/
LOGGING_INIT
static
_IRQL_requires_max_(PASSIVE_LEVEL)
_Check_return_
NTSTATUS
LogpInitializeBufferInfo (
_In_ PCWSTR LogFilePath,
_Inout_ PLOG_BUFFER_INFO Info,
_Out_ PBOOLEAN ReinitRequired
)
{
NTSTATUS status;
PAGED_CODE();
*ReinitRequired = FALSE;
KeInitializeSpinLock(&Info->SpinLock);
status = RtlStringCchCopyW(Info->LogFilePath,
RTL_NUMBER_OF_FIELD(LOG_BUFFER_INFO, LogFilePath),
LogFilePath);
if (!NT_SUCCESS(status))
{
goto Exit;
}
status = ExInitializeResourceLite(&Info->Resource);
if (!NT_SUCCESS(status))
{
goto Exit;
}
Info->ResourceInitialized = TRUE;
//
// Allocate two log buffers on NonPagedPool.
//
Info->LogBuffer1 = static_cast<PSTR>(ExAllocatePoolWithTag(NonPagedPool,
k_LogpBufferSize,
k_LogpPoolTag));
if (Info->LogBuffer1 == nullptr)
{
LogpCleanupBufferInfo(Info);
status = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
Info->LogBuffer2 = static_cast<PSTR>(ExAllocatePoolWithTag(NonPagedPool,
k_LogpBufferSize,
k_LogpPoolTag));
if (Info->LogBuffer2 == nullptr)
{
LogpCleanupBufferInfo(Info);
status = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
//
// Initialize these buffers. For diagnostic, fill them with some
// distinguishable bytes and then, ensure it is null-terminated.
//
RtlFillMemory(Info->LogBuffer1, k_LogpBufferSize, 0xff);
Info->LogBuffer1[0] = ANSI_NULL;
Info->LogBuffer1[k_LogpBufferSize - 1] = ANSI_NULL;
RtlFillMemory(Info->LogBuffer2, k_LogpBufferSize, 0xff);
Info->LogBuffer2[0] = ANSI_NULL;
Info->LogBuffer2[k_LogpBufferSize - 1] = ANSI_NULL;
//
// Buffer should be used is LogBuffer1, and location should be written logs
// is the head of the buffer.
//
Info->LogBufferHead = Info->LogBuffer1;
Info->LogBufferTail = Info->LogBuffer1;
status = LogpInitializeLogFile(Info, ReinitRequired);
if (!NT_SUCCESS(status))
{
goto Exit;
}
if (*ReinitRequired != FALSE)
{
LOGGING_LOG_INFO("The log file needs to be activated later.");
}
Exit:
if (!NT_SUCCESS(status))
{
LogpCleanupBufferInfo(Info);
}
return status;
}
/*!
@brief Initializes the log system.
@param[in] Flag - A OR-ed Flag to control a log level and options. It is an
OR-ed value of kLogPutLevel* and kLogOpt*. For example,
k_LogPutLevelDebug | k_LogOptDisableFunctionName.
@param[in] LogFilePath - A log file path.
@param[out] ReinitRequired - A pointer to receive whether re-initialization
is required. When this parameter returns TRUE, the caller must call
LogRegisterReinitialization() to register re-initialization.
@return STATUS_SUCCESS on success or else on failure.
@details Allocates internal log buffers, initializes related resources,
starts a log flush thread and creates a log file if requested. This
function returns TRUE to ReinitRequired if a file-system is not
initialized yet.
*/
LOGGING_INIT
_Use_decl_annotations_
NTSTATUS
InitializeLogging (
ULONG Flag,
PCWSTR LogFilePath,
PBOOLEAN ReinitRequired
)
{
NTSTATUS status;
PAGED_CODE();
*ReinitRequired = FALSE;
g_LogpDriverVerified = (MmIsDriverVerifyingByAddress(&InitializeLogging) != FALSE);
g_LogpDebugFlag = Flag;
//
// Initialize a log file if a log file path is specified.
//
if (ARGUMENT_PRESENT(LogFilePath))
{
status = LogpInitializeBufferInfo(LogFilePath,
&g_LogpLogBufferInfo,
ReinitRequired);
if (!NT_SUCCESS(status))
{
goto Exit;
}
}
//
// Test the log.
//
status = LOGGING_LOG_INFO("Logger was %sinitialized",
(*ReinitRequired != FALSE) ? "partially " : "");
if (!NT_SUCCESS(status))
{
goto Exit;
}
if (g_LogpDriverVerified != FALSE)
{
LOGGING_LOG_WARN("Driver being verified. All *_SAFE logs will be dropped.");
}
Exit:
if (!NT_SUCCESS(status))
{
if (LogFilePath != nullptr)
{
LogpCleanupBufferInfo(&g_LogpLogBufferInfo);
}
}
return status;
}
/*!
@brief Registers re-initialization.
@param[in] DriverObject - A driver object being loaded
@details A driver must call this function, or call CleanupLogging() and
return non STATUS_SUCCESS from DriverEntry() if InitializeLogging()
returned TRUE to ReinitRequired.If this function is called,
DriverEntry() must return STATUS_SUCCESS.
*/
LOGGING_INIT
_Use_decl_annotations_
VOID
LogRegisterReinitialization (
PDRIVER_OBJECT DriverObject
)
{
PAGED_CODE();
IoRegisterBootDriverReinitialization(DriverObject,
LogpReinitializationRoutine,
&g_LogpLogBufferInfo);
LOGGING_LOG_INFO("The log file will be activated later.");
}
/*!
@brief Initializes a log file at the re-initialization phase.
@param[in] DriverObject - The driver object to initialize.
@param[in] Context - The context pointer passed to the registration function.
@param[in] Count - The number indicating how many time this reinitialization
callback is invoked, starting at 1.
*/
LOGGING_PAGED
static
_Use_decl_annotations_
VOID
LogpReinitializationRoutine (
PDRIVER_OBJECT DriverObject,
PVOID Context,
ULONG Count
)
{
NTSTATUS status;
PLOG_BUFFER_INFO info;
BOOLEAN reinitRequired;
PAGED_CODE();
UNREFERENCED_PARAMETER(DriverObject);
UNREFERENCED_PARAMETER(Count);
NT_ASSERT(ARGUMENT_PRESENT(Context));
_Analysis_assume_(ARGUMENT_PRESENT(Context));
info = static_cast<PLOG_BUFFER_INFO>(Context);
status = LogpInitializeLogFile(info, &reinitRequired);
if (!NT_SUCCESS(status))
{
NT_ASSERT(FALSE);
goto Exit;
}
NT_ASSERT(reinitRequired != FALSE);
LOGGING_LOG_INFO("The log file has been activated.");
Exit:
return;
}
/*!
@brief Terminates the log system. Should be called from an IRP_MJ_SHUTDOWN handler.
*/
LOGGING_PAGED
_Use_decl_annotations_
VOID
LogIrpShutdownHandler (
VOID
)
{
PLOG_BUFFER_INFO info;
PAGED_CODE();
LOGGING_LOG_DEBUG("Flushing... (Max log buffer usage = %Iu/%lu bytes)",
g_LogpLogBufferInfo.LogMaxUsage,
k_LogpBufferSize);
LOGGING_LOG_INFO("Bye!");
g_LogpDebugFlag = k_LogPutLevelDisable;
//
// Wait until the log buffer is emptied.
//
info = &g_LogpLogBufferInfo;
while (info->LogBufferHead[0] != ANSI_NULL)
{
LogpSleep(k_LogpLogFlushIntervalMsec);
}
}
/*!
@brief Terminates the log system. Should be called from a DriverUnload routine.
*/
LOGGING_PAGED
_Use_decl_annotations_
VOID
CleanupLogging (
VOID
)
{
PAGED_CODE();
LOGGING_LOG_DEBUG("Finalizing... (Max log buffer usage = %Iu/%lu bytes)",
g_LogpLogBufferInfo.LogMaxUsage,
k_LogpBufferSize);
LOGGING_LOG_INFO("Bye!");
g_LogpDebugFlag = k_LogPutLevelDisable;
LogpCleanupBufferInfo(&g_LogpLogBufferInfo);
}
/*!
@brief Logs a message; use HYPERPLATFORM_LOG_*() macros instead.
@param[in] Level - Severity of a message.
@param[in] FunctionName - A name of a function called this function.
@param[in] Format - A format string.
@return STATUS_SUCCESS on success.
@see LOGGING_LOG_DEBUG.
@see LOGGING_LOG_DEBUG_SAFE.
*/
_Use_decl_annotations_
NTSTATUS
LogpPrint (
ULONG Level,
PCSTR FunctionName,
PCSTR Format,
...
)
{
NTSTATUS status;
va_list args;
CHAR logMessage[412];
ULONG pureLevel;
ULONG attributes;
CHAR message[512];
if (!BooleanFlagOn(g_LogpDebugFlag, Level))
{
status = STATUS_SUCCESS;
goto Exit;
}
if ((g_LogpDriverVerified != FALSE) && BooleanFlagOn(Level, k_LogpLevelOptSafe))
{
status = STATUS_SUCCESS;
goto Exit;
}
va_start(args, Format);
status = RtlStringCchVPrintfA(logMessage,
RTL_NUMBER_OF(logMessage),
Format,
args);
va_end(args);
if (!NT_SUCCESS(status))
{
goto Exit;
}
if (logMessage[0] == ANSI_NULL)
{
status = STATUS_INVALID_PARAMETER;
goto Exit;
}
pureLevel = Level & 0xf0;
attributes = Level & 0x0f;
//
// A single entry of log should not exceed 512 bytes. See
// Reading and Filtering Debugging Messages in MSDN for details.
//
static_assert(RTL_NUMBER_OF(message) <= 512,
"One log message should not exceed 512 bytes.");
status = LogpMakePrefix(pureLevel,
FunctionName,
logMessage,
message,
RTL_NUMBER_OF(message));
if (!NT_SUCCESS(status))
{
goto Exit;
}
status = LogpPut(message, attributes);
if (!NT_SUCCESS(status))
{
NT_ASSERT(FALSE);
goto Exit;
}
Exit:
return status;
}
/*!
@brief The entry point of the buffer flush thread.
@param[in] StartContext - The thread context pointer.
@return STATUS_SUCCESS on success; otherwise, an appropriate error code.
@details A thread runs as long as Info.BufferFlushThreadShouldBeAlive is TRUE
and flushes a log buffer to a log file every k_LogpLogFlushIntervalMsec msec.
*/
LOGGING_PAGED
static
_Use_decl_annotations_
VOID
LogpBufferFlushThreadRoutine (
PVOID StartContext
)
{
NTSTATUS status;
PLOG_BUFFER_INFO info;
PAGED_CODE();
status = STATUS_SUCCESS;
info = static_cast<PLOG_BUFFER_INFO>(StartContext);
info->BufferFlushThreadStarted = TRUE;
LOGGING_LOG_DEBUG("Logger thread started");
while (info->BufferFlushThreadShouldBeAlive != FALSE)
{
NT_ASSERT(LogpIsLogFileActivated(info) != FALSE);
if (info->LogBufferHead[0] != ANSI_NULL)
{
NT_ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL);
NT_ASSERT(KeAreAllApcsDisabled() == FALSE);
status = LogpFlushLogBuffer(info);
//
// Do not flush the file for overall performance. Even a case of
// bug check, we should be able to recover logs by looking at both
// log buffers.
//
}
LogpSleep(k_LogpLogFlushIntervalMsec);
}
PsTerminateSystemThread(status);
}
EXTERN_C_END
| 25.373972 | 100 | 0.608018 | zanzo420 |
a2d9fb0c35da66d6d5f3f1caf14a1e5def905d43 | 3,820 | cpp | C++ | core/src/UI/UIFrameConstraint.cpp | hhsaez/crimild | e3efee09489939338df55e8af9a1f9ddc01301f7 | [
"BSD-3-Clause"
] | 36 | 2015-03-12T10:42:36.000Z | 2022-01-12T04:20:40.000Z | core/src/UI/UIFrameConstraint.cpp | hhsaez/crimild | e3efee09489939338df55e8af9a1f9ddc01301f7 | [
"BSD-3-Clause"
] | 1 | 2015-12-17T00:25:43.000Z | 2016-02-20T12:00:57.000Z | core/src/UI/UIFrameConstraint.cpp | hhsaez/crimild | e3efee09489939338df55e8af9a1f9ddc01301f7 | [
"BSD-3-Clause"
] | 6 | 2017-06-17T07:57:53.000Z | 2019-04-09T21:11:24.000Z | /*
* Copyright (c) 2002-present, H. Hernán Saez
* 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 <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "UIFrameConstraint.hpp"
#include "UIFrame.hpp"
#include "SceneGraph/Node.hpp"
using namespace crimild;
using namespace ui;
UIFrameConstraint::UIFrameConstraint( Type type, crimild::Real32 value )
: _type( type ),
_value( value )
{
}
UIFrameConstraint::UIFrameConstraint( Type type, UIFrame *referenceFrame )
: _type( type ),
_referenceFrame( referenceFrame )
{
}
UIFrameConstraint::~UIFrameConstraint( void )
{
}
void UIFrameConstraint::apply( UIFrame *frame, UIFrame *parentFrame ) const
{
auto rect = frame->getExtensions();
auto ref = _referenceFrame != nullptr ? _referenceFrame->getExtensions() : parentFrame->getExtensions();
crimild::Real32 x = rect.getX();
crimild::Real32 y = rect.getY();
crimild::Real32 w = rect.getWidth();
crimild::Real32 h = rect.getHeight();
switch ( _type ) {
case Type::TOP:
y = ref.getY() + _value;
break;
case Type::LEFT:
x = ref.getX() + _value;
break;
case Type::RIGHT:
if ( _referenceFrame == nullptr ) {
x = ref.getX() + ref.getWidth() - w - _value;
}
else {
w = ref.getX() + ref.getWidth() - x;
}
break;
case Type::BOTTOM:
if ( _referenceFrame == nullptr ) {
y = ref.getY() + ref.getHeight() - h - _value;
}
else {
h = ref.getY() + ref.getHeight() - y;
}
break;
case Type::WIDTH:
w = _value;
break;
case Type::HEIGHT:
h = _value;
break;
case Type::EDGES:
x = 0;
y = 0;
w = ref.getWidth();
h = ref.getHeight();
break;
case Type::CENTER:
break;
case Type::CENTER_X:
x = ref.getX() + 0.5f * ( ref.getWidth() - w );
break;
case Type::CENTER_Y:
y = ref.getY() + 0.5f * ( ref.getHeight() - h );
break;
case Type::AFTER:
x = ref.getX() + ref.getWidth();
break;
case Type::BELOW:
y = ref.getY() + ref.getHeight();
break;
case Type::MARGIN:
x += _value;
y += _value;
w -= 2 * _value;
h -= 2 * _value;
break;
case Type::MARGIN_TOP:
y += _value;
break;
case Type::MARGIN_RIGHT:
w -= _value;
break;
case Type::MARGIN_BOTTOM:
h -= _value;
break;
case Type::MARGIN_LEFT:
x += _value;
break;
default:
break;
}
frame->setExtensions( Rectf( x, y, w, h ) );
}
| 24.33121 | 105 | 0.66466 | hhsaez |
a2da62d6cf8d8a0430ec9314853678048dca5350 | 8,973 | cpp | C++ | src/ofApp.cpp | clovistessier/kinect-hand-tracker-osc | 4dfcfe3e0ed0c625644bb158d83033d5b8dab724 | [
"MIT"
] | null | null | null | src/ofApp.cpp | clovistessier/kinect-hand-tracker-osc | 4dfcfe3e0ed0c625644bb158d83033d5b8dab724 | [
"MIT"
] | null | null | null | src/ofApp.cpp | clovistessier/kinect-hand-tracker-osc | 4dfcfe3e0ed0c625644bb158d83033d5b8dab724 | [
"MIT"
] | null | null | null | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup()
{
ofSetLogLevel(OF_LOG_VERBOSE);
// enable depth->video image calibration
kinect.setRegistration(true);
kinect.init();
//kinect.init(true); // shows infrared instead of RGB video image
//kinect.init(false, false); // disable video image (faster fps)
kinect.open(); // opens first available kinect
//kinect.open(1); // open a kinect by id, starting with 0 (sorted by serial # lexicographically))
//kinect.open("A00366902078051A"); // open a kinect using it's unique serial #
// print the intrinsic IR sensor values
if (kinect.isConnected())
{
ofLogNotice() << "sensor-emitter dist: " << kinect.getSensorEmitterDistance() << "cm";
ofLogNotice() << "sensor-camera dist: " << kinect.getSensorCameraDistance() << "cm";
ofLogNotice() << "zero plane pixel size: " << kinect.getZeroPlanePixelSize() << "mm";
ofLogNotice() << "zero plane dist: " << kinect.getZeroPlaneDistance() << "mm";
}
grayImage.allocate(kinect.width, kinect.height);
grayThreshNear.allocate(kinect.width, kinect.height);
grayThreshFar.allocate(kinect.width, kinect.height);
grayThreshRes.allocate(kinect.width, kinect.height);
ofSetFrameRate(60);
cameraAngle.addListener(this, &ofApp::cameraAngleChanged);
// give ourselves some sliders to adjust the CV params
gui.setup();
gui.add(cameraAngle.set("camera angle", 0, -30, 30));
gui.add(nearThreshold.set("near threshold", 255, 0, 255));
gui.add(farThreshold.set("far threshold", 200, 0, 255));
gui.add(minBlobArea.set("min blob area", 1000, 1, (kinect.width * kinect.height / 2)));
gui.add(maxBlobArea.set("max blob area", 10000, 1, (kinect.width * kinect.height)));
gui.add(nBlobsConsidered.set("blobs to look for", 2, 1, 10));
sender.setup("localhost", SEND_PORT);
// start off by drawing the gui
bDrawGui = true;
left.setup(0.25, 0.5, 0.5, ofColor::red);
right.setup(0.75, 0.5, 0.5, ofColor::blue);
}
//--------------------------------------------------------------
void ofApp::update()
{
kinect.update();
// there is a new frame and we are connected
if (kinect.isFrameNew())
{
// load grayscale image from the kinect source
ofPixels depthPixels = kinect.getDepthPixels();
depthPixels.mirror(false, true);
grayImage.setFromPixels(depthPixels);
// we do two thresholds - for the far plane and one for the near plane
// we then do a cvAnd to get the pixels which are a union of the two thresholds
grayThreshNear = grayImage;
grayThreshFar = grayImage;
grayThreshNear.threshold(nearThreshold.get(), true);
grayThreshFar.threshold(farThreshold.get());
cvAnd(grayThreshNear.getCvImage(), grayThreshFar.getCvImage(), grayThreshRes.getCvImage(), NULL);
// update the cv images
grayImage.flagImageChanged();
grayThreshRes.flagImageChanged();
// find the countours which are between the size of 20 pixels and 1/3 the w*h pixels.
// don't find holes because hands shouldn't have interior contours
contourFinder.findContours(grayThreshRes, minBlobArea.get(), maxBlobArea.get(), nBlobsConsidered.get(), false);
//store all the hand positions we found, normalized 0-1
hands.clear();
for (auto bit = contourFinder.blobs.begin(); bit != contourFinder.blobs.end(); bit++)
{
ofDefaultVec3 hand;
float x = bit->centroid.x;
float y = bit->centroid.y;
float depth = depthPixels.getColor(x, y).getBrightness();
hand.x = ofMap(x, 0, contourFinder.getWidth(), 0.0f, 1.0f, true);
hand.y = ofMap(y, 0, contourFinder.getHeight(), 0.0f, 1.0f, true);
hand.z = ofMap(depth, farThreshold.get(), nearThreshold.get(), 0.0f, 1.0f, true);
hands.push_back(hand);
}
int nPrevMatched = static_cast<int>(left.matched) + static_cast<int>(right.matched);
if (nPrevMatched == 0)
{
// match them to left and right
for (vector<ofDefaultVec3>::iterator itr = hands.begin(); itr != hands.end(); itr++)
{
if (itr->x > 0.5)
{
right.update(*itr);
}
else if (itr->x < 0.5)
{
left.update(*itr);
}
}
}
else if (nPrevMatched == 1)
{
Hand *prev;
Hand *other;
if (left.matched)
{
prev = &left;
other = &right
}
else
{
prev = &right;
other = &left;
}
vector<ofDefaultVec3>::iterator next;
float recordDistance = 10.0;
for (vector<ofDefaultVec3>::iterator itr = hands.begin(); itr != hands.end(); itr++)
{
float distSq = ofDistSquared(prev->pos.x, prev->pos.y, prev->pos.z, itr->x, itr->y, itr->z);
if (distSq < recordDistance)
{
next = itr;
recordDistance = distSq;
}
}
prev->update(*next);
hands.erase(next);
other->update(*(hands.begin()));
prev = nullptr;
other = nullptr;
next = nullptr;
}
}
ofxOscMessage m;
if (right.changed && right.valid)
{
m.setAddress("/kinect/right");
m.addFloatArg(right.pos.x);
m.addFloatArg(right.pos.y);
m.addFloatArg(right.pos.z);
sender.sendMessage(m, false);
right.changed = false;
}
if (left.changed && left.valid)
{
m.clear();
m.setAddress("/kinect/left");
m.addFloatArg(left.pos.x);
m.addFloatArg(left.pos.y);
m.addFloatArg(left.pos.z);
sender.sendMessage(m, false);
left.changed = false;
}
}
//--------------------------------------------------------------
void ofApp::draw()
{
// draw from the live kinect
// kinect.drawDepth(10, 10, 400, 300);
// kinect.draw(420, 10, 400, 300);
// grayImage.draw(10, 320, 400, 300);
// contourFinder.draw(10, 320, 400, 300);
ofSetColor(255, 255, 255);
kinectRGB = kinect.getPixels();
kinectRGB.mirror(false, true);
kinectRGB.draw(0, 0, 640, 480);
grayImage.draw(0, 480, 640, 480);
grayThreshRes.draw(0, 960, 640, 480);
ofSetColor(255, 0, 0);
ofNoFill();
contourFinder.draw(0, 960, 640, 480);
// ofSetColor(255, 0, 0);
// float rRad = ofMap(rh.z, farThreshold.get(), nearThreshold.get(), 5.0, 20.0, true);
// ofDrawCircle(rh.x, rh.y, rRad);
// ofSetColor(0, 0, 255);
// float lRad = ofMap(lh.z, farThreshold.get(), nearThreshold.get(), 5.0, 20.0, true);
// ofDrawCircle(lh.x, lh.y, lRad);
left.draw(0, 0, 640, 480);
right.draw(0, 0, 640, 480);
left.draw(0, 960, 640, 480);
right.draw(0, 960, 640, 480);
if (bDrawGui)
{
gui.draw();
}
}
//--------------------------------------------------------------
void ofApp::exit()
{
cameraAngle = 0;
kinect.setCameraTiltAngle(0);
kinect.close();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key)
{
switch (key)
{
case 'g':
bDrawGui = !bDrawGui;
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key)
{
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y)
{
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button)
{
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button)
{
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button)
{
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y)
{
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y)
{
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h)
{
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg)
{
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo)
{
}
void ofApp::cameraAngleChanged(int &cameraAngle)
{
// clamp the angle between -30 and 30 degrees
int new_angle = min(30, max(cameraAngle, -30));
kinect.setCameraTiltAngle(new_angle);
}
| 30.416949 | 119 | 0.513875 | clovistessier |
a2db57facee46af451f72ab1794bef186594978b | 2,509 | cpp | C++ | net/tcpip/services/telnet/server/tlntsess/main.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | net/tcpip/services/telnet/server/tlntsess/main.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | net/tcpip/services/telnet/server/tlntsess/main.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // scraper.cpp : This file contains the
// Created: Dec '97
// History:
// Copyright (C) 1997 Microsoft Corporation
// All rights reserved.
// Microsoft Confidential
#include <CmnHdr.h>
#include <TChar.h>
#include <New.h>
#include <Debug.h>
#include <MsgFile.h>
#include <TelnetD.h>
#include <TlntUtils.h>
#include <Session.h>
#include <Resource.h>
#include <LocResMan.h>
#pragma warning( disable : 4100 )
using namespace _Utils;
using CDebugLevel::TRACE_DEBUGGING;
using CDebugLevel::TRACE_HANDLE;
using CDebugLevel::TRACE_SOCKET;
HINSTANCE g_hInstRes = NULL;
TCHAR g_szHeaderFormat[ MAX_STRING_LENGTH ];
CSession *pClientSession = NULL;
int __cdecl NoMoreMemory( size_t size )
{
int NO_MORE_MEMORY = 1;
LogEvent( EVENTLOG_ERROR_TYPE, MSG_NOMOREMEMORY, _T(" ") );
ExitProcess( 1 );
_chASSERT(NO_MORE_MEMORY != 1);
return 0;
}
void Init( )
{
#if _DEBUG || DBG
CHAR szLogFileName[MAX_PATH];
_snprintf( szLogFileName, (MAX_PATH-1), "c:\\temp\\scraper%d.log", GetCurrentThreadId() );
CDebugLogger::Init( TRACE_DEBUGGING, szLogFileName );
#endif
HrLoadLocalizedLibrarySFU(NULL, L"TLNTSVRR.DLL", &g_hInstRes, NULL);
LoadString(g_hInstRes, IDS_MESSAGE_HEADER, g_szHeaderFormat, MAX_STRING_LENGTH );
}
void Shutdown()
{
#if _DEBUG || DBG
CDebugLogger::ShutDown();
#endif
}
void
LogEvent( WORD wType, DWORD dwEventID, LPCTSTR pFormat, ... )
{
LPCTSTR lpszStrings[1];
lpszStrings[0] = pFormat;
LogToTlntsvrLog( pClientSession->m_hLogHandle, wType, dwEventID,
(LPCTSTR*) &lpszStrings[0] );
return;
}
int __cdecl main()
{
// DebugBreak();
SetErrorMode(SEM_FAILCRITICALERRORS |
SEM_NOGPFAULTERRORBOX |
SEM_NOALIGNMENTFAULTEXCEPT |
SEM_NOOPENFILEERRORBOX
);
_set_new_handler( NoMoreMemory );
Init( );
pClientSession = new CSession;
if( pClientSession )
{
__try
{
if( pClientSession->Init() )
{
_TRACE( TRACE_DEBUGGING, "new session ..." );
pClientSession->WaitForIo();
}
}
__finally
{
_TRACE( TRACE_DEBUGGING, "finally block ..." );
pClientSession->Shutdown();
delete pClientSession;
}
}
Shutdown();
return( 0 );
}
| 22.008772 | 95 | 0.597449 | npocmaka |
a2db62dba8023f3b19b00e83d89ff9b7b944cd74 | 11,392 | cpp | C++ | willow/src/op/concat.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 61 | 2020-07-06T17:11:46.000Z | 2022-03-12T14:42:51.000Z | willow/src/op/concat.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 1 | 2021-02-25T01:30:29.000Z | 2021-11-09T11:13:14.000Z | willow/src/op/concat.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 6 | 2020-07-15T12:33:13.000Z | 2021-11-07T06:55:00.000Z | // Copyright (c) 2019 Graphcore Ltd. All rights reserved.
#include <algorithm>
#include <memory>
#include <popart/alias/aliasmodel.hpp>
#include <popart/graph.hpp>
#include <popart/op/concat.hpp>
#include <popart/opmanager.hpp>
#include <popart/opserialiser.hpp>
#include <popart/region.hpp>
#include <popart/tensor.hpp>
#include <popart/tensorindex.hpp>
namespace popart {
ConcatInplaceOp::ConcatInplaceOp(int64_t axis_, const Op::Settings &settings_)
: ConcatOp(Onnx::CustomOperators::ConcatInplace, axis_, settings_) {}
ConcatOp::ConcatOp(const OperatorIdentifier &_opid,
int64_t axis_,
const Op::Settings &settings_)
: Op(_opid, settings_), axis(axis_) {}
ConcatInplaceOp::ConcatInplaceOp(const ConcatOp &op, int64_t axis_)
: ConcatOp(Onnx::CustomOperators::ConcatInplace, axis_, op.getSettings()) {}
std::unique_ptr<Op> ConcatOp::clone() const {
return std::make_unique<ConcatOp>(*this);
}
void ConcatOp::growAliasModel(AliasModel &m) const {
std::vector<poprithms::memory::inplace::TensorId> inIds;
inIds.reserve(input->n());
for (const auto &x : input->tensorMap()) {
inIds.push_back(m.getPoprithmsTensorId(x.second->id));
}
const auto cat = m.g.concat(inIds, getAxis());
m.insertViewChange(cat, *outTensor(0), isOutplace());
}
poprithms::memory::inplace::Proposal
ConcatOp::mapInplaceProposal(const AliasModel &aliasModel,
OperatorIdentifier id) const {
return mapInplaceProposalGate0(aliasModel, id);
}
void ConcatOp::regMapPreChecks(InIndex inIndex) const {
if (inIndex >= input->tensorMap().size() || inIndex < 0) {
throw error("invalid index in ConcatOp::fwdRegMap");
}
}
view::RegMap ConcatOp::fwdRegMap(InIndex inIndex, OutIndex) const {
regMapPreChecks(inIndex);
int64_t offset = getOutOffset(inIndex);
int64_t axisIn = getAxis();
return [axisIn, offset](const view::Region &r_in) {
view::LowBounds lower = r_in.getLower();
view::UppBounds upper = r_in.getUpper();
lower[axisIn] += offset;
upper[axisIn] += offset;
return view::Regions(1, view::Region(lower, upper, r_in.getAccessType()));
};
}
view::RegMap ConcatOp::bwdRegMap(InIndex inIndex, OutIndex) const {
regMapPreChecks(inIndex);
int64_t offset = getOutOffset(inIndex);
int64_t axisIn = getAxis();
auto inShape = inTensor(inIndex)->info.shape();
return [axisIn, offset, inShape](const view::Region &r_out) {
view::LowBounds lower = r_out.getLower();
view::UppBounds upper = r_out.getUpper();
lower[axisIn] -= offset;
upper[axisIn] -= offset;
return view::Regions(
1,
view::Region(lower, upper, r_out.getAccessType())
.intersect(view::Region::getFull(inShape, r_out.getAccessType())));
};
}
std::unique_ptr<Op>
ConcatOp::getInplaceVariant(const OperatorIdentifier &operator_id) const {
if (operator_id == Onnx::CustomOperators::ConcatInplace) {
return std::make_unique<ConcatInplaceOp>(*this, axis);
}
// catch remaining cases and throw an error
return Op::getInplaceVariant(operator_id);
}
std::unique_ptr<Op> ConcatInplaceOp::clone() const {
return std::make_unique<ConcatInplaceOp>(*this);
}
int64_t ConcatOp::getAxis() const {
// Onnx 11 supports negative axis indexing for argmin and argmax.
if (axis >= 0) {
return axis;
} else {
return inInfo(getInIndex(0)).rank() + axis;
}
}
std::vector<std::tuple<OperatorIdentifier, float>>
ConcatOp::inplacePriorityDefault() const {
// see T6768: choosing default priorities
return {{Onnx::CustomOperators::ConcatInplace, 10.0f}};
}
Shape ConcatOp::getOutputShape(int64_t axis,
const std::vector<const Shape *> inputs) {
Shape outShape(*inputs[0]);
outShape[axis] = 0;
for (int i = 0; i < inputs.size(); i++) {
const auto &shape = *inputs[i];
if (outShape.size() != shape.size()) {
throw error(
"Input {} of {} to concat does not have matching output rank. "
"Input {} has rank {} ({}) while the output has rank {} ({})."
"Concat axis {}.",
i,
inputs.size(),
i,
shape.size(),
shape,
outShape.size(),
outShape,
axis);
}
auto outShapePrefixBegin = std::begin(outShape);
auto outShapePrefixEnd = std::begin(outShape) + axis;
auto outShapeSuffixBegin = std::begin(outShape) + axis + 1;
auto outShapeSuffixEnd = std::end(outShape);
auto shapePrefixBegin = std::begin(shape);
auto shapeSuffixBegin = std::begin(shape) + axis + 1;
if (!std::equal(outShapePrefixBegin, outShapePrefixEnd, shapePrefixBegin) ||
!std::equal(outShapeSuffixBegin, outShapeSuffixEnd, shapeSuffixBegin)) {
std::stringstream ss;
ss << "In ConcatOp::getOutputShape, axis = " << axis << " and shapes : ";
for (auto sp : inputs) {
ss << '\n';
appendSequence(ss, *sp);
}
throw error(
"Input {} to concat does not have matching shape. {}", i, ss.str());
}
outShape[axis] += shape[axis];
}
return outShape;
}
void ConcatOp::validateAxis() const {
auto r = static_cast<int64_t>(inShape(InIndex(0)).size());
if (axis < -r || axis > r - 1) {
throw error("Attribute 'axis' of ConcatOp, {}, is outside of acceptable "
"range [{}, {}]",
-r,
r - 1);
}
}
void ConcatOp::setup() {
validateAxis();
const auto input_count = input->n();
if (input_count == 0) {
throw error("Cannot concat zero tensors");
}
const DataType outType = inInfo(getInIndex(0)).dataType();
std::vector<const Shape *> inputs;
inputs.reserve(input_count);
for (int i = 0; i < input_count; i++) {
inputs.push_back(&inShape(getInIndex(i)));
}
Shape outShape;
try {
outShape = getOutputShape(getAxis(), inputs);
} catch (const error &) {
logging::op::err(
"Error trying to calculate output shape for concat {}({}, {})",
id,
opid,
name());
throw;
}
outInfo(getOutIndex()) = TensorInfo(outType, outShape);
}
int64_t ConcatOp::getOutOffset(int64_t dim) const {
int64_t offset = 0;
for (int i = 0; i < dim; i++) {
const auto shape = inShape(getInIndex(i));
offset += shape.at(getAxis());
}
return offset;
}
std::vector<std::unique_ptr<Op>> ConcatOp::getGradOps() {
std::vector<std::unique_ptr<Op>> result;
result.reserve(input->n());
for (int i = 0; i < input->n(); ++i) {
result.push_back(std::make_unique<ConcatGradOp>(*this, i));
}
return result;
}
// Concat can be replace by identity if there is 1 input
bool ConcatOp::canBeReplacedByIdentity() const { return input->n() == 1; }
ConcatGradOp::ConcatGradOp(const ConcatOp &fwd, InIndex inputIndex)
: Op(Onnx::GradOperators::ConcatGrad, fwd.getSettings()),
axis(fwd.getAxis()), start(0), end(0), fwdInput(inputIndex) {
for (int i = 0; i < inputIndex; ++i) {
auto shape = fwd.inShape(ConcatOp::getInIndex(i));
start += shape[getAxis()];
}
for (int i = 0; i <= inputIndex; ++i) {
auto shape = fwd.inShape(ConcatOp::getInIndex(i));
end += shape[getAxis()];
}
const DataType outType =
fwd.inInfo(ConcatOp::getInIndex(fwdInput)).dataType();
Shape outShape = fwd.inShape(ConcatOp::getInIndex(fwdInput));
outShape[getAxis()] = end - start;
gradInfo = TensorInfo(outType, outShape);
gradOutToNonGradInInfo = {{getOutIndex(), ConcatOp::getInIndex(fwdInput)}};
}
void ConcatOp::appendOutlineAttributes(OpSerialiserBase &os) const {
Op::appendOutlineAttributes(os);
os.appendAttribute("axis", axis);
}
ConcatGradOp::ConcatGradOp(const OperatorIdentifier &_opid,
const ConcatGradOp &concat_grad_op)
: Op(_opid, concat_grad_op.getSettings()), axis(concat_grad_op.axis),
start(concat_grad_op.start), end(concat_grad_op.end),
fwdInput(concat_grad_op.fwdInput), gradInfo(concat_grad_op.gradInfo),
gradOutToNonGradInInfo(concat_grad_op.gradOutToNonGradInInfo) {}
std::unique_ptr<Op> ConcatGradOp::clone() const {
return std::make_unique<ConcatGradOp>(*this);
}
const std::vector<GradInOutMapper> &ConcatGradOp::gradInputInfo() const {
static const std::vector<GradInOutMapper> inInfo = {
{getInIndex(), ConcatOp::getOutIndex(), GradOpInType::GradOut}};
return inInfo;
}
const std::map<int, int> &ConcatGradOp::gradOutToNonGradIn() const {
return gradOutToNonGradInInfo;
}
void ConcatGradOp::setup() { outInfo(getOutIndex()) = gradInfo; }
void ConcatGradOp::appendOutlineAttributes(OpSerialiserBase &os) const {
Op::appendOutlineAttributes(os);
os.appendAttribute("axis", axis);
os.appendAttribute("start", start);
os.appendAttribute("end", end);
}
int64_t ConcatGradOp::getAxis() const { return axis; }
int64_t ConcatGradOp::getStart() const { return start; }
int64_t ConcatGradOp::getEnd() const { return end; }
void ConcatGradOp::configureShardedOp(Op *const shardedOp,
const Settings *const settings_) const {
Op::configureShardedOp(shardedOp, settings_);
auto oldInShape = inInfo(ConcatGradOp::getInIndex()).shape();
Tensor *inTensor = shardedOp->input->tensor(ConcatGradOp::getInIndex());
Tensor *outTensor = shardedOp->output->tensor(ConcatGradOp::getOutIndex());
auto newInShape = inTensor->info.shape();
int64_t reduction = 1;
for (size_t i = 0; i < oldInShape.size(); ++i) {
reduction = oldInShape.at(i) / newInShape.at(i);
if (reduction > 1) {
Op *prod = outTensor->getProducer();
ConcatGradOp *concatGradProd = dynamic_cast<ConcatGradOp *>(prod);
auto type = concatGradProd->gradInfo.dataType();
auto shape = concatGradProd->gradInfo.shape();
shape[i] /= reduction;
concatGradProd->gradInfo.set(type, shape);
concatGradProd->setup();
break;
}
}
}
namespace {
// Do we support other types??
static OpDefinition::DataTypes T = {DataType::UINT8,
DataType::UINT16,
DataType::UINT32,
DataType::UINT64,
DataType::INT8,
DataType::INT16,
DataType::INT32,
DataType::INT64,
DataType::FLOAT16,
DataType::FLOAT,
DataType::BOOL};
static OpDefinition concatOpDef({OpDefinition::Inputs({{"inputs", T}}),
OpDefinition::Outputs({{"concat_result", T}}),
OpDefinition::Attributes({
{"axis", {"*"}},
})});
static OpCreator<ConcatOp> concatOpCreator(
OpDefinitions({{Onnx::Operators::Concat_1, concatOpDef},
{Onnx::Operators::Concat_4, concatOpDef},
{Onnx::Operators::Concat_11, concatOpDef}}),
[](const OpCreatorInfo &info) {
int64_t axis = info.attributes.getAttribute<Attributes::Int>("axis");
return std::unique_ptr<Op>(new ConcatOp(info.opid, axis, info.settings));
},
true);
} // namespace
} // namespace popart
| 32.641834 | 80 | 0.629828 | gglin001 |
a2dd9ceaf0f037a2a325fdce8675ad0d1eff1c25 | 5,023 | cpp | C++ | cat/src/v20180409/model/UpdateProbeTaskConfigurationListRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | cat/src/v20180409/model/UpdateProbeTaskConfigurationListRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | cat/src/v20180409/model/UpdateProbeTaskConfigurationListRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cat/v20180409/model/UpdateProbeTaskConfigurationListRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Cat::V20180409::Model;
using namespace std;
UpdateProbeTaskConfigurationListRequest::UpdateProbeTaskConfigurationListRequest() :
m_taskIdsHasBeenSet(false),
m_nodesHasBeenSet(false),
m_intervalHasBeenSet(false),
m_parametersHasBeenSet(false),
m_cronHasBeenSet(false)
{
}
string UpdateProbeTaskConfigurationListRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_taskIdsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TaskIds";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_taskIds.begin(); itr != m_taskIds.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_nodesHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Nodes";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_nodes.begin(); itr != m_nodes.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_intervalHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Interval";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_interval, allocator);
}
if (m_parametersHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Parameters";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_parameters.c_str(), allocator).Move(), allocator);
}
if (m_cronHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Cron";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_cron.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
vector<string> UpdateProbeTaskConfigurationListRequest::GetTaskIds() const
{
return m_taskIds;
}
void UpdateProbeTaskConfigurationListRequest::SetTaskIds(const vector<string>& _taskIds)
{
m_taskIds = _taskIds;
m_taskIdsHasBeenSet = true;
}
bool UpdateProbeTaskConfigurationListRequest::TaskIdsHasBeenSet() const
{
return m_taskIdsHasBeenSet;
}
vector<string> UpdateProbeTaskConfigurationListRequest::GetNodes() const
{
return m_nodes;
}
void UpdateProbeTaskConfigurationListRequest::SetNodes(const vector<string>& _nodes)
{
m_nodes = _nodes;
m_nodesHasBeenSet = true;
}
bool UpdateProbeTaskConfigurationListRequest::NodesHasBeenSet() const
{
return m_nodesHasBeenSet;
}
int64_t UpdateProbeTaskConfigurationListRequest::GetInterval() const
{
return m_interval;
}
void UpdateProbeTaskConfigurationListRequest::SetInterval(const int64_t& _interval)
{
m_interval = _interval;
m_intervalHasBeenSet = true;
}
bool UpdateProbeTaskConfigurationListRequest::IntervalHasBeenSet() const
{
return m_intervalHasBeenSet;
}
string UpdateProbeTaskConfigurationListRequest::GetParameters() const
{
return m_parameters;
}
void UpdateProbeTaskConfigurationListRequest::SetParameters(const string& _parameters)
{
m_parameters = _parameters;
m_parametersHasBeenSet = true;
}
bool UpdateProbeTaskConfigurationListRequest::ParametersHasBeenSet() const
{
return m_parametersHasBeenSet;
}
string UpdateProbeTaskConfigurationListRequest::GetCron() const
{
return m_cron;
}
void UpdateProbeTaskConfigurationListRequest::SetCron(const string& _cron)
{
m_cron = _cron;
m_cronHasBeenSet = true;
}
bool UpdateProbeTaskConfigurationListRequest::CronHasBeenSet() const
{
return m_cronHasBeenSet;
}
| 27.905556 | 104 | 0.720884 | suluner |
a2de25e49dd08d862a35f24b08b0afdbafd6589b | 377 | cpp | C++ | NaPomocMatiemu/NaPomocMatiemu/KlientC.cpp | MiszelHub/PobiMatiego | 96def41a0927e54f3c2310d98cb88f586e0e4d46 | [
"MIT"
] | null | null | null | NaPomocMatiemu/NaPomocMatiemu/KlientC.cpp | MiszelHub/PobiMatiego | 96def41a0927e54f3c2310d98cb88f586e0e4d46 | [
"MIT"
] | null | null | null | NaPomocMatiemu/NaPomocMatiemu/KlientC.cpp | MiszelHub/PobiMatiego | 96def41a0927e54f3c2310d98cb88f586e0e4d46 | [
"MIT"
] | null | null | null | #include "KlientC.h"
KlientC::KlientC(std::string nazwaTypu) :Typ(nazwaTypu)
{
//ctor
}
KlientC::~KlientC()
{
//dtor
}
double KlientC::obliczRabat(double bilans)
{
double rabat = 0;
if (bilans <= 50)
{
rabat = bilans*0.05;
}
else if ((bilans > 50) && (bilans <= 100))
{
rabat = bilans*0.07;
}
else if (bilans > 100)
{
rabat = bilans*0.1;
}
return rabat;
} | 13 | 55 | 0.607427 | MiszelHub |
a2dfc3848ad3959227f3f7816adb85e133e79bf5 | 31,103 | cpp | C++ | aten/src/TH/generic/THTensorEvenMoreMath.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | 1 | 2019-07-21T02:13:22.000Z | 2019-07-21T02:13:22.000Z | aten/src/TH/generic/THTensorEvenMoreMath.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | null | null | null | aten/src/TH/generic/THTensorEvenMoreMath.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | null | null | null | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/THTensorEvenMoreMath.cpp"
#else
#include <TH/generic/THTensorApply.hpp>
void THTensor_(fill)(THTensor *r_, real value)
{
if (THTensor_(isContiguous)(r_) || THTensor_(isTransposed)(r_)) {
TH_TENSOR_APPLY_CONTIG(real, r_, THVector_(fill)(r__data, value, r__len););
} else {
TH_TENSOR_APPLY(real, r_,
if (r__stride == 1) {
THVector_(fill)(r__data, value, r__size);
r__i = r__size;
r__data += r__stride * r__size;
break;
} else {
*r__data = value;
}
);
}
}
void THTensor_(zero)(THTensor *r_)
{
THTensor_(fill)(r_, 0);
}
void THTensor_(maskedFill)(THTensor *tensor, THByteTensor *mask, real value)
{
TH_TENSOR_APPLY2(real, tensor, unsigned char, mask,
if (*mask_data > 1)
{
THFree(mask_counter);
THFree(tensor_counter);
THError("Mask tensor can take 0 and 1 values only");
}
else if (*mask_data == 1)
{
*tensor_data = value;
});
}
void THTensor_(maskedCopy)(THTensor *tensor, THByteTensor *mask, THTensor* src )
{
THTensor *srct = THTensor_(newContiguous)(src);
real *src_data = THTensor_(data)(srct);
ptrdiff_t cntr = 0;
ptrdiff_t nelem = THTensor_(nElement)(srct);
if (THTensor_(nElement)(tensor) != THByteTensor_nElement(mask))
{
THTensor_(free)(srct);
THError("Number of elements of destination tensor != Number of elements in mask");
}
TH_TENSOR_APPLY2(real, tensor, unsigned char, mask,
if (*mask_data > 1)
{
THTensor_(free)(srct);
THFree(mask_counter);
THFree(tensor_counter);
THError("Mask tensor can take 0 and 1 values only");
}
else if (*mask_data == 1)
{
if (cntr == nelem)
{
THTensor_(free)(srct);
THFree(mask_counter);
THFree(tensor_counter);
THError("Number of elements of src < number of ones in mask");
}
*tensor_data = *src_data;
src_data++;
cntr++;
});
THTensor_(free)(srct);
}
void THTensor_(maskedSelect)(THTensor *tensor, THTensor *src, THByteTensor *mask)
{
ptrdiff_t numel = THByteTensor_sumall(mask);
real *tensor_data;
#ifdef DEBUG
THAssert(numel <= LONG_MAX);
#endif
THTensor_(resize1d)(tensor,numel);
tensor_data = THTensor_(data)(tensor);
TH_TENSOR_APPLY2(real, src, unsigned char, mask,
if (*mask_data > 1)
{
THFree(mask_counter);
THFree(src_counter);
THError("Mask tensor can take 0 and 1 values only");
}
else if (*mask_data == 1)
{
*tensor_data = *src_data;
tensor_data++;
});
}
// Finds non-zero elements of a tensor and returns their subscripts
void THTensor_(nonzero)(THLongTensor *subscript, THTensor *tensor)
{
ptrdiff_t numel = 0;
int64_t *subscript_data;
int64_t i = 0;
int64_t dim;
int64_t div = 1;
#ifdef TH_REAL_IS_HALF
#define IS_NONZERO(val) ((val.x & 0x7fff) != 0)
#else
#define IS_NONZERO(val) ((val)!=0)
#endif
/* First Pass to determine size of subscripts */
TH_TENSOR_APPLY(real, tensor,
if IS_NONZERO(*tensor_data) {
++numel;
});
#ifdef DEBUG
THAssert(numel <= LONG_MAX);
#endif
THLongTensor_resize2d(subscript, numel, tensor->dim());
/* Second pass populates subscripts */
subscript_data = THLongTensor_data(subscript);
TH_TENSOR_APPLY(real, tensor,
if IS_NONZERO(*tensor_data) {
div = 1;
for (dim = tensor->dim() - 1; dim >= 0; dim--) {
*(subscript_data + dim) = (i/div) % THTensor_sizeLegacyNoScalars(tensor, dim);
div *= THTensor_sizeLegacyNoScalars(tensor, dim);
}
subscript_data += tensor->dim();
}
++i;);
}
void THTensor_(indexSelect)(THTensor *tensor, THTensor *src, int dim, THLongTensor *index)
{
ptrdiff_t i, numel;
THLongStorage *newSize;
THTensor *tSlice, *sSlice;
int64_t *index_data;
real *tensor_data, *src_data;
THArgCheck(THTensor_nDimensionLegacyNoScalars(index) == 1, 3, "Index is supposed to be 1-dimensional");
THArgCheck(dim < THTensor_nDimensionLegacyNoScalars(src), 4, "Indexing dim %d is out of bounds of tensor", dim + TH_INDEX_BASE);
numel = THLongTensor_nElement(index);
newSize = THLongStorage_newWithSize(src->dim());
THLongStorage_rawCopy(newSize, THTensor_getSizePtr(src));
#ifdef DEBUG
THAssert(numel <= LONG_MAX);
#endif
THLongStorage_data(newSize)[dim] = numel;
THTensor_(resize)(tensor,newSize,NULL);
THLongStorage_free(newSize);
index = THLongTensor_newContiguous(index);
index_data = THLongTensor_data(index);
if (dim == 0 && THTensor_(isContiguous)(src) && THTensor_(isContiguous)(tensor))
{
tensor_data = THTensor_(data)(tensor);
src_data = THTensor_(data)(src);
auto src_size0 = THTensor_sizeLegacyNoScalars(src, 0);
ptrdiff_t rowsize = src_size0 == 0 ? 1: THTensor_(nElement)(src) / src_size0;
// check that the indices are within range
int64_t max = src_size0 - 1 + TH_INDEX_BASE;
for (i=0; i<numel; i++) {
if (index_data[i] < TH_INDEX_BASE || index_data[i] > max) {
THLongTensor_free(index);
THError("index out of range");
}
}
if (src->dim() <= 1) {
#pragma omp parallel for if(numel > TH_OMP_OVERHEAD_THRESHOLD) private(i)
for (i=0; i<numel; i++)
tensor_data[i] = src_data[index_data[i] - TH_INDEX_BASE];
} else {
#pragma omp parallel for if(numel*rowsize > TH_OMP_OVERHEAD_THRESHOLD) private(i)
for (i=0; i<numel; i++)
memcpy(tensor_data + i*rowsize, src_data + (index_data[i] - TH_INDEX_BASE)*rowsize, rowsize*sizeof(real));
}
}
else if (src->dim() <= 1)
{
for (i=0; i<numel; i++)
THTensor_(set1d)(tensor,i,THTensor_(get1d)(src,index_data[i] - TH_INDEX_BASE));
}
else
{
for (i=0; i<numel; i++)
{
tSlice = THTensor_(new)();
sSlice = THTensor_(new)();
THTensor_(select)(tSlice, tensor, dim, i);
THTensor_(select)(sSlice, src, dim, index_data[i] - TH_INDEX_BASE);
THTensor_(copy)(tSlice, sSlice);
THTensor_(free)(tSlice);
THTensor_(free)(sSlice);
}
}
THLongTensor_free(index);
}
void THTensor_(indexCopy)(THTensor *tensor, int dim, THLongTensor *index, THTensor *src)
{
ptrdiff_t i, numel;
THTensor *tSlice, *sSlice;
int64_t *index_data;
// Error checking for this function has moved to ATen!!
numel = THLongTensor_nElement(index);
index = THLongTensor_newContiguous(index);
index_data = THLongTensor_data(index);
if (tensor->dim() > 1 )
{
tSlice = THTensor_(new)();
sSlice = THTensor_(new)();
for (i=0; i<numel; i++)
{
THTensor_(select)(tSlice, tensor, dim, index_data[i] - TH_INDEX_BASE);
THTensor_(select)(sSlice, src, dim, i);
THTensor_(copy)(tSlice, sSlice);
}
THTensor_(free)(tSlice);
THTensor_(free)(sSlice);
}
else
{
for (i=0; i<numel; i++)
{
THTensor_(set1d)(tensor, index_data[i] - TH_INDEX_BASE, THTensor_(get1d)(src,i));
}
}
THLongTensor_free(index);
}
static ptrdiff_t THTensor_(dataOffset)(THTensor* tensor, ptrdiff_t linearIndex) {
auto size = tensor->sizes();
auto stride = tensor->strides();
int nDim = THTensor_nDimensionLegacyAll(tensor);
ptrdiff_t dataOffset = 0;
for (int i = nDim - 1; i >= 0; i--) {
dataOffset += (linearIndex % size[i]) * stride[i];
linearIndex /= size[i];
}
return dataOffset;
}
static inline void THTensor_(checkLinearIndex)(int64_t linearIndex, int64_t numel) {
THArgCheck(linearIndex < numel && linearIndex >= -numel, 2, "out of range: %d out of %d", (int)linearIndex, (int)numel);
}
static inline int64_t THTensor_(wrapLinearIndex)(int64_t linearIndex, int64_t numel) {
return linearIndex < 0 ? linearIndex + numel : linearIndex;
}
void THTensor_(take)(THTensor *r_, THTensor *src, THLongTensor *index)
{
THTensor_(resizeNd)(r_, index->dim(), THTensor_getSizePtr(index), NULL);
THTensor* dst = THTensor_(newContiguous)(r_);
index = THLongTensor_newContiguous(index);
int64_t* index_data = THLongTensor_data(index);
ptrdiff_t srcElements = THTensor_(nElement)(src);
real* src_data = THTensor_(data)(src);
real* dst_data = THTensor_(data)(dst);
ptrdiff_t nIndices = THLongTensor_nElement(index);
int isContiguous = THTensor_(isContiguous)(src);
// Exceptions must not be thrown across OpenMP parallel sections, so we
// record the position of the invalid index and throw the exception after the
// loop.
std::atomic<int64_t> invalidIdxPos(-1);
ptrdiff_t i;
#pragma omp parallel for if(nIndices > TH_OMP_OVERHEAD_THRESHOLD) private(i)
for (i = 0; i < nIndices; i++) {
int64_t idx = index_data[i];
if (idx < srcElements && idx >= -srcElements) {
idx = THTensor_(wrapLinearIndex)(idx, srcElements);
if (isContiguous) {
dst_data[i] = src_data[idx];
} else {
dst_data[i] = src_data[THTensor_(dataOffset)(src, idx)];
}
} else {
int64_t tmp = -1;
invalidIdxPos.compare_exchange_strong(tmp, i);
}
}
if (invalidIdxPos >= 0) {
THTensor_(checkLinearIndex)(index_data[invalidIdxPos], srcElements);
}
THLongTensor_free(index);
THTensor_(freeCopyTo)(dst, r_);
}
void THTensor_(put)(THTensor *tensor, THLongTensor *index, THTensor *src, int accumulate)
{
THArgCheck(THLongTensor_nElement(index) == THTensor_(nElement)(src), 3,
"src should have the same number of elements as index");
index = THLongTensor_newContiguous(index);
src = THTensor_(newContiguous)(src);
real* data = THTensor_(data)(tensor);
ptrdiff_t numel = THTensor_(nElement)(tensor);
int is_contiguous = THTensor_(isContiguous)(tensor);
TH_TENSOR_APPLY2(int64_t, index, real, src,
THTensor_(checkLinearIndex)(*index_data, numel);
int64_t linearIndex = THTensor_(wrapLinearIndex)(*index_data, numel);
int64_t dataOffset = is_contiguous ? linearIndex : THTensor_(dataOffset)(tensor, linearIndex);
if (accumulate) {
data[dataOffset] += *src_data;
} else {
data[dataOffset] = *src_data;
}
);
THTensor_(free)(src);
THLongTensor_free(index);
}
void THTensor_(indexAdd)(THTensor *tensor, int dim, THLongTensor *index, THTensor *src)
{
ptrdiff_t i, numel;
THTensor *tSlice, *sSlice;
int64_t *index_data;
numel = THLongTensor_nElement(index);
THArgCheck(THTensor_nDimensionLegacyNoScalars(index) == 1, 3, "Index is supposed to be a vector");
THArgCheck(dim < THTensor_nDimensionLegacyNoScalars(src), 4,"Indexing dim %d is out of bounds of tensor", dim + TH_INDEX_BASE);
THArgCheck(numel == THTensor_sizeLegacyNoScalars(src, dim),4,"Number of indices should be equal to source:size(dim)");
index = THLongTensor_newContiguous(index);
index_data = THLongTensor_data(index);
if (tensor->dim() > 1)
{
tSlice = THTensor_(new)();
sSlice = THTensor_(new)();
for (i=0; i<numel; i++)
{
THTensor_(select)(tSlice, tensor, dim, index_data[i] - TH_INDEX_BASE);
THTensor_(select)(sSlice, src, dim, i);
THTensor_(cadd)(tSlice, tSlice, 1.0, sSlice);
}
THTensor_(free)(tSlice);
THTensor_(free)(sSlice);
}
else
{
for (i=0; i<numel; i++)
{
THTensor_(set1d)(tensor,
index_data[i] - TH_INDEX_BASE,
THTensor_(get1d)(src,i) + THTensor_(get1d)(tensor,index_data[i] - TH_INDEX_BASE));
}
}
THLongTensor_free(index);
}
void THTensor_(indexFill)(THTensor *tensor, int dim, THLongTensor *index, real val)
{
ptrdiff_t i, numel;
THTensor *tSlice;
int64_t *index_data;
numel = THLongTensor_nElement(index);
THArgCheck(THTensor_nDimensionLegacyNoScalars(index) == 1, 3, "Index is supposed to be a vector");
THArgCheck(dim < THTensor_nDimensionLegacyNoScalars(tensor), 4,"Indexing dim %d is out of bounds of tensor", dim + TH_INDEX_BASE);
index = THLongTensor_newContiguous(index);
index_data = THLongTensor_data(index);
for (i=0; i<numel; i++)
{
if (tensor->dim() > 1)
{
tSlice = THTensor_(new)();
THTensor_(select)(tSlice, tensor,dim,index_data[i] - TH_INDEX_BASE);
THTensor_(fill)(tSlice, val);
THTensor_(free)(tSlice);
}
else
{
THTensor_(set1d)(tensor, index_data[i] - TH_INDEX_BASE, val);
}
}
THLongTensor_free(index);
}
void THTensor_(gather)(THTensor *tensor, THTensor *src, int dim, THLongTensor *index)
{
int64_t elems_per_row, i, idx;
THArgCheck(THLongTensor_nDimensionLegacyNoScalars(index) == THTensor_(nDimensionLegacyNoScalars)(src), 4,
"Index tensor must have same dimensions as input tensor");
THArgCheck(dim >= 0 && dim < THTensor_(nDimensionLegacyNoScalars)(tensor), 3,
"Index dimension is out of bounds");
THArgCheck(THTensor_(nDimensionLegacyNoScalars)(src) == THTensor_(nDimensionLegacyNoScalars)(tensor), 2,
"Input tensor must have same dimensions as output tensor");
elems_per_row = THTensor_sizeLegacyNoScalars(index, dim);
TH_TENSOR_DIM_APPLY3(real, tensor, real, src, int64_t, index, dim,
TH_TENSOR_DIM_APPLY3_SIZE_EQ_EXCEPT_DIM,
for (i = 0; i < elems_per_row; ++i)
{
idx = *(index_data + i*index_stride);
if (idx < TH_INDEX_BASE || idx >= src_size + TH_INDEX_BASE)
{
THFree(TH_TENSOR_DIM_APPLY_counter);
THError("Invalid index in gather");
}
*(tensor_data + i*tensor_stride) = src_data[(idx - TH_INDEX_BASE) * src_stride];
})
}
void THTensor_(scatter)(THTensor *tensor, int dim, THLongTensor *index, THTensor *src)
{
int64_t elems_per_row, i, idx;
THArgCheck(dim < THTensor_(nDimensionLegacyNoScalars)(tensor), 2, "Index dimension is out of bounds");
THArgCheck(THLongTensor_nDimensionLegacyNoScalars(index) == THTensor_(nDimensionLegacyNoScalars)(tensor), 3,
"Index tensor must have same dimensions as output tensor");
THArgCheck(THTensor_(nDimensionLegacyNoScalars)(src) == THTensor_(nDimensionLegacyNoScalars)(tensor), 4,
"Input tensor must have same dimensions as output tensor");
elems_per_row = THTensor_sizeLegacyNoScalars(index, dim);
TH_TENSOR_DIM_APPLY3(real, tensor, real, src, int64_t, index, dim,
TH_TENSOR_DIM_APPLY3_SIZE_SCATTER,
for (i = 0; i < elems_per_row; ++i)
{
idx = *(index_data + i*index_stride);
if (idx < TH_INDEX_BASE || idx >= tensor_size + TH_INDEX_BASE)
{
THFree(TH_TENSOR_DIM_APPLY_counter);
THError("Invalid index in scatter");
}
tensor_data[(idx - TH_INDEX_BASE) * tensor_stride] = *(src_data + i*src_stride);
})
}
void THTensor_(scatterAdd)(THTensor *tensor, int dim, THLongTensor *index, THTensor *src)
{
int64_t elems_per_row, i, idx;
THArgCheck(dim < THTensor_(nDimensionLegacyNoScalars)(tensor), 2, "Index dimension is out of bounds");
THArgCheck(THLongTensor_nDimensionLegacyNoScalars(index) == THTensor_(nDimensionLegacyNoScalars)(tensor), 3,
"Index tensor must have same dimensions as output tensor");
THArgCheck(THTensor_(nDimensionLegacyNoScalars)(src) == THTensor_(nDimensionLegacyNoScalars)(tensor), 4,
"Input tensor must have same dimensions as output tensor");
elems_per_row = THTensor_sizeLegacyNoScalars(index, dim);
TH_TENSOR_DIM_APPLY3(real, tensor, real, src, int64_t, index, dim,
TH_TENSOR_DIM_APPLY3_SIZE_SCATTER,
for (i = 0; i < elems_per_row; ++i)
{
idx = *(index_data + i*index_stride);
if (idx < TH_INDEX_BASE || idx >= tensor_size + TH_INDEX_BASE)
{
THFree(TH_TENSOR_DIM_APPLY_counter);
THError("Invalid index in scatterAdd");
}
tensor_data[(idx - TH_INDEX_BASE) * tensor_stride] += *(src_data + i*src_stride);
})
}
void THTensor_(scatterFill)(THTensor *tensor, int dim, THLongTensor *index, real val)
{
int64_t elems_per_row, i, idx;
THArgCheck(dim < THTensor_(nDimensionLegacyAll)(tensor), 2, "Index dimension is out of bounds");
THArgCheck(THLongTensor_nDimensionLegacyAll(index) == THTensor_(nDimensionLegacyAll)(tensor), 3,
"Index tensor must have same dimensions as output tensor");
elems_per_row = THTensor_sizeLegacyNoScalars(index, dim);
TH_TENSOR_DIM_APPLY2(real, tensor, int64_t, index, dim,
for (i = 0; i < elems_per_row; ++i)
{
idx = *(index_data + i*index_stride);
if (idx < TH_INDEX_BASE || idx >= tensor_size + TH_INDEX_BASE)
{
THFree(TH_TENSOR_DIM_APPLY_counter);
THError("Invalid index in scatter");
}
tensor_data[(idx - TH_INDEX_BASE) * tensor_stride] = val;
})
}
accreal THTensor_(dot)(THTensor *tensor, THTensor *src)
{
accreal sum = 0;
/* we use a trick here. careful with that. */
TH_TENSOR_APPLY2(real, tensor, real, src,
int64_t sz = (tensor_size-tensor_i < src_size-src_i ? tensor_size-tensor_i : src_size-src_i);
sum += THBlas_(dot)(sz, src_data, src_stride, tensor_data, tensor_stride);
tensor_i += sz;
src_i += sz;
tensor_data += sz*tensor_stride;
src_data += sz*src_stride;
break;);
return sum;
}
real THTensor_(minall)(THTensor *tensor)
{
real theMin;
real value;
THArgCheck(THTensor_nDimensionLegacyAll(tensor) > 0, 1, "tensor must have one dimension");
theMin = THTensor_(data)(tensor)[0];
TH_TENSOR_APPLY(real, tensor,
value = *tensor_data;
/* This is not the same as value<theMin in the case of NaNs */
if(!(value >= theMin))
{
theMin = value;
th_isnan_break(value)
});
return theMin;
}
real THTensor_(maxall)(THTensor *tensor)
{
real theMax;
real value;
THArgCheck(THTensor_nDimensionLegacyAll(tensor) > 0, 1, "tensor must have one dimension");
theMax = THTensor_(data)(tensor)[0];
TH_TENSOR_APPLY(real, tensor,
value = *tensor_data;
/* This is not the same as value>theMax in the case of NaNs */
if(!(value <= theMax))
{
theMax = value;
th_isnan_break(value)
});
return theMax;
}
accreal THTensor_(sumall)(THTensor *tensor)
{
accreal sum = 0;
int serial_path = 0;
#ifdef _OPENMP
int inOMP = omp_in_parallel();
if(inOMP) {
serial_path = 1;
} else {
TH_TENSOR_APPLY_REDUCTION_OMP(real, tensor, +:sum, sum += *tensor_data;, UNCERTAIN_TH_OMP_OVERHEAD_THRESHOLD);
}
#else
serial_path = 1;
#endif
if (serial_path) {
TH_TENSOR_APPLY(real, tensor, sum += *tensor_data;);
}
return sum;
}
accreal THTensor_(prodall)(THTensor *tensor)
{
accreal prod = 1;
int serial_path = 0;
#ifdef _OPENMP
int inOMP = omp_in_parallel();
if(inOMP) {
serial_path = 1;
} else {
TH_TENSOR_APPLY_REDUCTION_OMP(real, tensor, *:prod, prod *= *tensor_data;, UNCERTAIN_TH_OMP_OVERHEAD_THRESHOLD);
}
#else
serial_path = 1;
#endif
if (serial_path) {
TH_TENSOR_APPLY(real, tensor, prod *= *tensor_data;);
}
return prod;
}
void THTensor_(add)(THTensor *r_, THTensor *t, real value)
{
THTensor_(resizeAs)(r_, t);
int64_t r_Size = THTensor_(nElement)(r_);
int r_Contig = THTensor_(isContiguous)(r_);
int tContig = THTensor_(isContiguous)(t);
int serial_path = 0;
if (r_Contig && tContig) {
TH_TENSOR_APPLY2_CONTIG(real, r_, real, t, THVector_(adds)(r__data, t_data, value, r__len););
} else {
#ifdef _OPENMP
int inOMP = omp_in_parallel();
if (inOMP) {
serial_path = 1;
} else {
TH_TENSOR_APPLY2_OMP(r_Size, r_Contig, tContig, real, r_, real, t, *r__data = *t_data + value;, ORDIN_TH_OMP_OVERHEAD_THRESHOLD)
}
#else
(void)r_Size;
serial_path = 1;
#endif
}
if (serial_path) {
TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data + value;);
}
}
void THTensor_(sub)(THTensor *r_, THTensor *t, real value)
{
THTensor_(add)(r_, t, -value);
}
void THTensor_(add_scaled)(THTensor *r_, THTensor *t, real value, real alpha)
{
THTensor_(add)(r_, t, value * alpha);
}
void THTensor_(sub_scaled)(THTensor *r_, THTensor *t, real value, real alpha)
{
THTensor_(add)(r_, t, -value * alpha);
}
void THTensor_(mul)(THTensor *r_, THTensor *t, real value)
{
THTensor_(resizeAs)(r_, t);
int64_t r_Size = THTensor_(nElement)(r_);
int r_Contig = THTensor_(isContiguous)(r_);
int tContig = THTensor_(isContiguous)(t);
int serial_path = 0;
if (r_Contig && tContig) {
TH_TENSOR_APPLY2_CONTIG(real, r_, real, t, THVector_(muls)(r__data, t_data, value, r__len););
} else {
#ifdef _OPENMP
int inOMP = omp_in_parallel();
if (inOMP) {
serial_path = 1;
} else {
TH_TENSOR_APPLY2_OMP(r_Size, r_Contig, tContig, real, r_, real, t, *r__data = *t_data * value;, ORDIN_TH_OMP_OVERHEAD_THRESHOLD)
}
#else
(void)r_Size;
serial_path = 1;
#endif
}
if (serial_path) {
TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data * value;);
}
}
void THTensor_(div)(THTensor *r_, THTensor *t, real value)
{
THTensor_(resizeAs)(r_, t);
int64_t r_Size = THTensor_(nElement)(r_);
int r_Contig = THTensor_(isContiguous)(r_);
int tContig = THTensor_(isContiguous)(t);
int serial_path = 0;
if (r_Contig && tContig) {
TH_TENSOR_APPLY2_CONTIG(real, r_, real, t, THVector_(divs)(r__data, t_data, value, r__len););
} else {
#ifdef _OPENMP
int inOMP = omp_in_parallel();
if (inOMP) {
serial_path = 1;
} else {
TH_TENSOR_APPLY2_OMP(r_Size, r_Contig, tContig, real, r_, real, t, *r__data = *t_data / value;, ORDIN_TH_OMP_OVERHEAD_THRESHOLD)
}
#else
(void)r_Size;
serial_path = 1;
#endif
}
if (serial_path) {
TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data / value;);
}
}
void THTensor_(lshift)(THTensor *r_, THTensor *t, real value)
{
#if defined(TH_REAL_IS_FLOAT)
return THTensor_(mul)(r_, t, powf(2, value));
#elif defined(TH_REAL_IS_DOUBLE)
return THTensor_(mul)(r_, t, pow(2, value));
#elif defined(TH_REAL_IS_HALF)
return THError("lshift is not supported for torch.HalfTensor");
#else
THTensor_(resizeAs)(r_, t);
int64_t r_Size = THTensor_(nElement)(r_);
int r_Contig = THTensor_(isContiguous)(r_);
int tContig = THTensor_(isContiguous)(t);
int serial_path = 0;
if (r_Contig && tContig) {
real *tp = THTensor_(data)(t);
real *rp = THTensor_(data)(r_);
int64_t i;
#pragma omp parallel for if(r_Size > TH_OMP_OVERHEAD_THRESHOLD * 100) private(i)
for (i=0; i<r_Size; i++) {
#if defined(TH_REAL_IS_BYTE)
rp[i] = ((real) tp[i]) << value;
#else
rp[i] = ((ureal) tp[i]) << value;
#endif
}
} else {
#ifdef _OPENMP
int inOMP = omp_in_parallel();
if (inOMP) {
serial_path = 1;
} else {
#if defined(TH_REAL_IS_BYTE)
TH_TENSOR_APPLY2_OMP(r_Size, r_Contig, tContig, real, r_, real, t, *r__data = (((real) *t_data) << value);, UNCERTAIN_TH_OMP_OVERHEAD_THRESHOLD);
#else
TH_TENSOR_APPLY2_OMP(r_Size, r_Contig, tContig, real, r_, real, t, *r__data = (((ureal) *t_data) << value);, UNCERTAIN_TH_OMP_OVERHEAD_THRESHOLD);
#endif
}
#else
serial_path = 1;
#endif
}
if (serial_path) {
#if defined(TH_REAL_IS_BYTE)
TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (((real) *t_data) << value););
#else
TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (((ureal) *t_data) << value););
#endif
}
#endif
}
void THTensor_(rshift)(THTensor *r_, THTensor *t, real value)
{
#if defined(TH_REAL_IS_FLOAT)
return THTensor_(div)(r_, t, powf(2, value));
#elif defined(TH_REAL_IS_DOUBLE)
return THTensor_(div)(r_, t, pow(2, value));
#elif defined(TH_REAL_IS_HALF)
return THError("rshift is not supported for torch.HalfTensor");
#else
THTensor_(resizeAs)(r_, t);
int64_t r_Size = THTensor_(nElement)(r_);
int r_Contig = THTensor_(isContiguous)(r_);
int tContig = THTensor_(isContiguous)(t);
int serial_path = 0;
if (r_Contig && tContig) {
real *tp = THTensor_(data)(t);
real *rp = THTensor_(data)(r_);
int64_t i;
#pragma omp parallel for if(r_Size > TH_OMP_OVERHEAD_THRESHOLD * 100) private(i)
for (i=0; i<r_Size; i++) {
#if defined(TH_REAL_IS_BYTE)
rp[i] = ((real) tp[i]) >> value;
#else
rp[i] = ((ureal) tp[i]) >> value;
#endif
}
} else {
#ifdef _OPENMP
int inOMP = omp_in_parallel();
if (inOMP) {
serial_path = 1;
} else {
#if defined(TH_REAL_IS_BYTE)
TH_TENSOR_APPLY2_OMP(r_Size, r_Contig, tContig, real, r_, real, t, *r__data = (((real) *t_data) >> value);, UNCERTAIN_TH_OMP_OVERHEAD_THRESHOLD);
#else
TH_TENSOR_APPLY2_OMP(r_Size, r_Contig, tContig, real, r_, real, t, *r__data = (((ureal) *t_data) >> value);, UNCERTAIN_TH_OMP_OVERHEAD_THRESHOLD);
#endif
}
#else
serial_path = 1;
#endif
}
if (serial_path) {
#if defined(TH_REAL_IS_BYTE)
TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (((real) *t_data) >> value););
#else
TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (((ureal) *t_data) >> value););
#endif
}
#endif
}
void THTensor_(fmod)(THTensor *r_, THTensor *t, real value)
{
THTensor_(resizeAs)(r_, t);
int64_t r_Size = THTensor_(nElement)(r_);
int r_Contig = THTensor_(isContiguous)(r_);
int tContig = THTensor_(isContiguous)(t);
int serial_path = 0;
if (r_Contig && tContig) {
real *tp = THTensor_(data)(t);
real *rp = THTensor_(data)(r_);
int64_t i;
#pragma omp parallel for if(r_Size > TH_OMP_OVERHEAD_THRESHOLD) private(i)
for (i=0; i<r_Size; i++) {
#if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE)
rp[i] = fmod(tp[i], value);
#else
rp[i] = tp[i] % value;
#endif
}
} else {
#ifdef _OPENMP
int inOMP = omp_in_parallel();
if (inOMP) {
serial_path = 1;
} else {
#if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE)
TH_TENSOR_APPLY2_OMP(r_Size, r_Contig, tContig, real, r_, real, t, *r__data = fmod(*t_data, value);, UNCERTAIN_TH_OMP_OVERHEAD_THRESHOLD);
#else
TH_TENSOR_APPLY2_OMP(r_Size, r_Contig, tContig, real, r_, real, t, *r__data = (*t_data % value);, UNCERTAIN_TH_OMP_OVERHEAD_THRESHOLD);
#endif
}
#else
serial_path = 1;
#endif
}
if (serial_path) {
#if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE)
TH_TENSOR_APPLY2(real, r_, real, t, *r__data = fmod(*t_data, value););
#else
TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (*t_data % value););
#endif
}
}
// Should wrap if the value (a) has a different sign than the divisor (b), but is not 0.
static inline bool modulo_wrap(real a, real b) {
return (a != 0) && (a < 0) != (b < 0);
}
void THTensor_(remainder)(THTensor *r_, THTensor *t, real value)
{
THTensor_(resizeAs)(r_, t);
int64_t r_Size = THTensor_(nElement)(r_);
int r_Contig = THTensor_(isContiguous)(r_);
int tContig = THTensor_(isContiguous)(t);
int serial_path = 0;
if (r_Contig && tContig) {
real *tp = THTensor_(data)(t);
real *rp = THTensor_(data)(r_);
int64_t i;
#pragma omp parallel for if(r_Size > TH_OMP_OVERHEAD_THRESHOLD) private(i)
for (i=0; i<r_Size; i++) {
#if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE)
rp[i] = (value == 0)? NAN : tp[i] - value * floor(tp[i] / value);
#else
// There is no NAN for integers
rp[i] = tp[i] % value;
if (modulo_wrap(rp[i], value))
rp[i] += value;
#endif
}
} else {
#ifdef _OPENMP
int inOMP = omp_in_parallel();
if (inOMP) {
serial_path = 1;
} else {
#if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE)
TH_TENSOR_APPLY2_OMP(r_Size, r_Contig, tContig, real, r_, real, t, *r__data = (value == 0)? NAN : *t_data - value * floor(*t_data / value);, UNCERTAIN_TH_OMP_OVERHEAD_THRESHOLD);
#else
// There is no NAN for integers
TH_TENSOR_APPLY2_OMP(r_Size, r_Contig, tContig, real, r_, real, t, *r__data = *t_data % value;
if (modulo_wrap(*r__data, value)) *r__data += value;, UNCERTAIN_TH_OMP_OVERHEAD_THRESHOLD);
#endif
}
#else
serial_path = 1;
#endif
}
if (serial_path) {
#if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE)
TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (value == 0)? NAN : *t_data - value * floor(*t_data / value););
#else
// There is no NAN for integers
TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data % value;
if (modulo_wrap(*r__data, value)) *r__data += value;);
#endif
}
}
void THTensor_(bitand)(THTensor *r_, THTensor *t, real value)
{
#if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) || defined(TH_REAL_IS_HALF)
(void)r_;
(void)t;
(void)value;
return THError("bitand is only supported for integer type tensors");
#else
THTensor_(resizeAs)(r_, t);
int64_t r_Size = THTensor_(nElement)(r_);
int r_Contig = THTensor_(isContiguous)(r_);
int serial_path = 0;
int tContig = THTensor_(isContiguous)(t);
if (r_Contig && tContig) {
real *tp = THTensor_(data)(t);
real *rp = THTensor_(data)(r_);
int64_t i;
#pragma omp parallel for if(r_Size > TH_OMP_OVERHEAD_THRESHOLD * 100) private(i)
for (i=0; i<r_Size; i++) {
rp[i] = tp[i] & value;
}
} else {
#ifdef _OPENMP
int inOMP = omp_in_parallel();
if (inOMP) {
serial_path = 1;
} else {
TH_TENSOR_APPLY2_OMP(r_Size, r_Contig, tContig, real, r_, real, t, *r__data = *t_data & value;, UNCERTAIN_TH_OMP_OVERHEAD_THRESHOLD);
}
#else
serial_path = 1;
#endif
}
if (serial_path) {
TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data & value;);
}
#endif
}
#endif /* TH_GENERIC_FILE */
| 32.809072 | 184 | 0.626756 | DavidKo3 |
a2e35f06d334d1d7fe91d45a1dfdcf3251d4e969 | 1,840 | cpp | C++ | lib/Backends/CevaSPF2/libjit_spf2/libjit_spf2.cpp | YaronBenAtar/glow | a13706a4239fa7eaf059c670dc573e3eb0768f86 | [
"Apache-2.0"
] | null | null | null | lib/Backends/CevaSPF2/libjit_spf2/libjit_spf2.cpp | YaronBenAtar/glow | a13706a4239fa7eaf059c670dc573e3eb0768f86 | [
"Apache-2.0"
] | null | null | null | lib/Backends/CevaSPF2/libjit_spf2/libjit_spf2.cpp | YaronBenAtar/glow | a13706a4239fa7eaf059c670dc573e3eb0768f86 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (c) Glow Contributors. See CONTRIBUTORS file.
*
* 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 <algorithm>
#include <assert.h>
#include <chrono>
#include <cmath>
#include <math.h>
#include <numeric>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include "../../../LLVMIRCodeGen/libjit/libjit_defs.h"
extern "C" {
/// Macro to define a mini-kernel for data-parallel operations with immediate
/// operands.
/// \p name the name of the kernel
/// \p type the type of the tensor elements and of the return value
/// \p body the operation to be performed
#define DEFINE_DATA_PARALLEL_KERNEL_WITH_IMM_OPERAND(name, type, body) \
type name(dim_t idx, type val, const type *LHS, const type *RHS) { \
return body; \
}
DEFINE_DATA_PARALLEL_KERNEL_WITH_IMM_OPERAND(libjit_element_maxsplat_kernel_f,
float, MAX(LHS[idx], val))
DEFINE_DATA_PARALLEL_KERNEL_WITH_IMM_OPERAND(libjit_element_maxsplat_kernel_i8,
int8_t, MAX(LHS[idx], val))
#undef DEFINE_DATA_PARALLEL_KERNEL_WITH_IMM_OPERAND
} // extern "C"
| 36.078431 | 81 | 0.656522 | YaronBenAtar |
a2e3dfa6d740f7f8e49746e83d1d67d011e6d7a9 | 2,977 | cpp | C++ | src/ecckd/read_spectrum.cpp | ecmwf-ifs/ecckd | 6115f9b8e29a55cb0f48916857bdc77fec41badd | [
"Apache-2.0"
] | null | null | null | src/ecckd/read_spectrum.cpp | ecmwf-ifs/ecckd | 6115f9b8e29a55cb0f48916857bdc77fec41badd | [
"Apache-2.0"
] | null | null | null | src/ecckd/read_spectrum.cpp | ecmwf-ifs/ecckd | 6115f9b8e29a55cb0f48916857bdc77fec41badd | [
"Apache-2.0"
] | null | null | null | // read_spectrum.cpp - Read a profile of spectral optical depth
//
// Copyright (C) 2019- ECMWF.
//
// This software is licensed under the terms of the Apache Licence Version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
//
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Author: Robin Hogan
// Email: r.j.hogan@ecmwf.int
#include "Error.h"
#include "read_spectrum.h"
/// Read a profile of spectral optical depth from a NetCDF file
void
read_spectrum(std::string& file_name, ///< File name containing spectra
int iprof, ///< Index of profile (0 based)
adept::Vector& pressure_hl, ///< Half-level pressure (Pa)
adept::Vector& temperature_hl, ///< Half-level temperature (K)
adept::Vector& wavenumber_cm_1, ///< Wavenumber (cm-1)
adept::Vector& d_wavenumber_cm_1,///< Wavenumber interval (cm-1)
adept::Matrix& optical_depth, ///< Spectral optical depth
std::string& molecule, ///< Chemical formula of molecule
Real& reference_surface_vmr, ///< Reference volume mixing ratio (or -1.0)
adept::Vector& vmr_fl, ///< Volume mixing ratio on full levels
int* ncol ///< Number of columns in file
) {
DataFile file(file_name);
pressure_hl.clear();
wavenumber_cm_1.clear();
d_wavenumber_cm_1.clear();
optical_depth.clear();
if (ncol) {
intVector dims = file.size("pressure_hl");
*ncol = dims(0);
}
file.read(pressure_hl, "pressure_hl", iprof);
if (file.exist("temperature_hl")) {
file.read(temperature_hl, "temperature_hl", iprof);
}
else {
WARNING << "\"temperature_hl\" not present";
ENDWARNING;
}
file.read(wavenumber_cm_1, "wavenumber");
if (file.exist("d_wavenumber")) {
file.read(d_wavenumber_cm_1, "d_wavenumber");
}
else {
d_wavenumber_cm_1.resize(wavenumber_cm_1.size());
d_wavenumber_cm_1(range(1,end-1))
= 0.5 * (wavenumber_cm_1(range(2,end))
-wavenumber_cm_1(range(0,end-2)));
d_wavenumber_cm_1(0) = 0.5*d_wavenumber_cm_1(1);
d_wavenumber_cm_1(end) = 0.5*d_wavenumber_cm_1(end-1);
}
file.read(molecule, DATA_FILE_GLOBAL_SCOPE, "constituent_id");
if (file.exist("reference_surface_mole_fraction")) {
file.read(reference_surface_vmr, "reference_surface_mole_fraction");
}
else {
reference_surface_vmr = -1.0;
}
// Read volume mixing ratio on full levels, or negative value if not
// present (e.g. for hybrid spectra)
if (file.exist("mole_fraction_fl") && file.size("mole_fraction_fl").size() == 2) {
file.read(vmr_fl, "mole_fraction_fl", iprof);
}
else {
vmr_fl.resize(pressure_hl.size()-1);
vmr_fl = -1.0;
}
file.read(optical_depth, "optical_depth", iprof);
file.close();
}
| 33.829545 | 84 | 0.660396 | ecmwf-ifs |
a2e5c3e9fe23c448048b9172336d81df9c1b2f02 | 6,313 | cc | C++ | src/operators/test/operator_advdiff_surface.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 37 | 2017-04-26T16:27:07.000Z | 2022-03-01T07:38:57.000Z | src/operators/test/operator_advdiff_surface.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 494 | 2016-09-14T02:31:13.000Z | 2022-03-13T18:57:05.000Z | src/operators/test/operator_advdiff_surface.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 43 | 2016-09-26T17:58:40.000Z | 2022-03-25T02:29:59.000Z | /*
Operators
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Author: Konstantin Lipnikov (lipnikov@lanl.gov)
*/
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
// TPLs
#include "Teuchos_RCP.hpp"
#include "Teuchos_ParameterList.hpp"
#include "Teuchos_ParameterXMLFileReader.hpp"
#include "UnitTest++.h"
// Amanzi
#include "GMVMesh.hh"
#include "MeshFactory.hh"
#include "Mesh_MSTK.hh"
#include "Tensor.hh"
#include "WhetStoneDefs.hh"
// Amanzi::Operators
#include "OperatorDefs.hh"
#include "PDE_Accumulation.hh"
#include "PDE_DiffusionMFD.hh"
#include "PDE_AdvectionUpwind.hh"
#include "Verification.hh"
/* *****************************************************************
* This test replaces tensor and boundary conditions by continuous
* functions. This is a prototype for future solvers.
* **************************************************************** */
TEST(ADVECTION_DIFFUSION_SURFACE) {
using namespace Teuchos;
using namespace Amanzi;
using namespace Amanzi::AmanziMesh;
using namespace Amanzi::AmanziGeometry;
using namespace Amanzi::Operators;
auto comm = Amanzi::getDefaultComm();
int MyPID = comm->MyPID();
if (MyPID == 0) std::cout << "\nTest: Advection-duffusion on a surface" << std::endl;
// read parameter list
std::string xmlFileName = "test/operator_advdiff_surface.xml";
ParameterXMLFileReader xmlreader(xmlFileName);
ParameterList plist = xmlreader.getParameters();
// create an MSTK mesh framework
ParameterList region_list = plist.sublist("regions");
Teuchos::RCP<GeometricModel> gm = Teuchos::rcp(new GeometricModel(3, region_list, *comm));
MeshFactory meshfactory(comm,gm);
meshfactory.set_preference(Preference({Framework::MSTK}));
RCP<const Mesh> mesh = meshfactory.create(0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 40, 40, 5);
RCP<const Mesh_MSTK> mesh_mstk = rcp_static_cast<const Mesh_MSTK>(mesh);
// extract surface mesh
std::vector<std::string> setnames;
setnames.push_back(std::string("Top surface"));
RCP<Mesh> surfmesh = meshfactory.create(mesh_mstk, setnames, AmanziMesh::FACE);
/* modify diffusion coefficient */
Teuchos::RCP<std::vector<WhetStone::Tensor> > K = Teuchos::rcp(new std::vector<WhetStone::Tensor>());
int ncells_owned = surfmesh->num_entities(AmanziMesh::CELL, AmanziMesh::Parallel_type::OWNED);
int nfaces_wghost = surfmesh->num_entities(AmanziMesh::FACE, AmanziMesh::Parallel_type::ALL);
for (int c = 0; c < ncells_owned; c++) {
WhetStone::Tensor Kc(2, 1);
Kc(0, 0) = 1.0;
K->push_back(Kc);
}
// create boundary data
Teuchos::RCP<BCs> bc = Teuchos::rcp(new BCs(surfmesh, AmanziMesh::FACE, WhetStone::DOF_Type::SCALAR));
std::vector<int>& bc_model = bc->bc_model();
std::vector<double>& bc_value = bc->bc_value();
for (int f = 0; f < nfaces_wghost; f++) {
const Point& xf = surfmesh->face_centroid(f);
if (fabs(xf[0]) < 1e-6 || fabs(xf[0] - 1.0) < 1e-6 ||
fabs(xf[1]) < 1e-6 || fabs(xf[1] - 1.0) < 1e-6) {
bc_model[f] = OPERATOR_BC_DIRICHLET;
bc_value[f] = xf[1] * xf[1];
}
}
// create diffusion operator
Teuchos::ParameterList olist = plist.sublist("PK operator").sublist("diffusion operator");
auto op_diff = Teuchos::rcp(new PDE_DiffusionMFD(olist, (Teuchos::RCP<const AmanziMesh::Mesh>) surfmesh));
op_diff->Init(olist);
op_diff->SetBCs(bc, bc);
const CompositeVectorSpace& cvs = op_diff->global_operator()->DomainMap();
// set up the diffusion operator
op_diff->Setup(K, Teuchos::null, Teuchos::null);
op_diff->UpdateMatrices(Teuchos::null, Teuchos::null);
// get the global operator
Teuchos::RCP<Operator> global_op = op_diff->global_operator();
// create an advection operator
Teuchos::ParameterList alist;
Teuchos::RCP<PDE_AdvectionUpwind> op_adv = Teuchos::rcp(new PDE_AdvectionUpwind(alist, global_op));
op_adv->SetBCs(bc, bc);
// get a flux field
Teuchos::RCP<CompositeVector> u = Teuchos::rcp(new CompositeVector(cvs));
Epetra_MultiVector& uf = *u->ViewComponent("face");
int nfaces = surfmesh->num_entities(AmanziMesh::FACE, AmanziMesh::Parallel_type::OWNED);
Point vel(4.0, 4.0, 0.0);
for (int f = 0; f < nfaces; f++) {
uf[0][f] = vel * surfmesh->face_normal(f);
}
op_adv->Setup(*u);
op_adv->UpdateMatrices(u.ptr());
// Add an accumulation term.
CompositeVector solution(cvs);
solution.PutScalar(0.0); // solution at time T=0
CompositeVector phi(cvs);
phi.PutScalar(0.2);
double dT = 0.02;
Teuchos::RCP<PDE_Accumulation> op_acc = Teuchos::rcp(new PDE_Accumulation(AmanziMesh::CELL, global_op));
op_acc->AddAccumulationDelta(solution, phi, phi, dT, "cell");
// BCs and assemble
op_diff->ApplyBCs(true, true, true);
op_adv->ApplyBCs(true, true, true);
// Create a preconditioner
ParameterList slist = plist.sublist("preconditioners").sublist("Hypre AMG");
global_op->set_inverse_parameters("Hypre AMG", plist.sublist("preconditioners"));
global_op->InitializeInverse();
global_op->ComputeInverse();
// Test SPD properties of the matrix and preconditioner.
VerificationCV ver(global_op);
ver.CheckMatrixSPD(false, true);
ver.CheckPreconditionerSPD(1e-12, false, true);
// Create a solver and solve the problem
CompositeVector& rhs = *global_op->rhs();
global_op->set_inverse_parameters("Hypre AMG", plist.sublist("preconditioners"), "AztecOO CG", plist.sublist("solvers"));
global_op->InitializeInverse();
global_op->ComputeInverse();
global_op->ApplyInverse(rhs, solution);
int num_itrs = global_op->num_itrs();
CHECK(num_itrs > 5 && num_itrs < 15);
ver.CheckResidual(solution, 1.0e-12);
if (MyPID == 0) {
std::cout << "pressure solver (gmres): ||r||=" << global_op->residual()
<< " itr=" << global_op->num_itrs()
<< " code=" << global_op->returned_code() << std::endl;
// visualization
const Epetra_MultiVector& p = *solution.ViewComponent("cell");
GMV::open_data_file(*surfmesh, (std::string)"operators.gmv");
GMV::start_data();
GMV::write_cell_data(p, 0, "solution");
GMV::close_data_file();
}
}
| 34.124324 | 123 | 0.685728 | fmyuan |
a2e7a249e78fa4d3b3edc478f44e4b482371cc90 | 399 | cpp | C++ | hw4-jasonsie88-master/src/lib/AST/return.cpp | jasonsie88/Intro._to_Compiler_Design | 228205241fcba7eb3407ec72936a52b0266671bb | [
"MIT"
] | null | null | null | hw4-jasonsie88-master/src/lib/AST/return.cpp | jasonsie88/Intro._to_Compiler_Design | 228205241fcba7eb3407ec72936a52b0266671bb | [
"MIT"
] | null | null | null | hw4-jasonsie88-master/src/lib/AST/return.cpp | jasonsie88/Intro._to_Compiler_Design | 228205241fcba7eb3407ec72936a52b0266671bb | [
"MIT"
] | null | null | null | #include "AST/return.hpp"
#include "visitor/AstNodeVisitor.hpp"
ReturnNode::ReturnNode(const uint32_t line, const uint32_t col,ExpressionNode *new_p_ret_val)
:AstNode{line, col}, m_ret_val(new_p_ret_val){}
void ReturnNode::accept(AstNodeVisitor &p_visitor){
p_visitor.visit(*this);
}
void ReturnNode::visitChildNodes(AstNodeVisitor &p_visitor) {
m_ret_val->accept(p_visitor);
}
| 28.5 | 93 | 0.759398 | jasonsie88 |
a2e88e8615feecfdb9e6d8eb80bb94ad08dafea7 | 585 | cpp | C++ | structural/proxy/SecureProxy.cpp | masiboo/design-patterns-in-cpp | c690b1deecd0e70a132ad8768c519f1559b10246 | [
"Apache-2.0"
] | null | null | null | structural/proxy/SecureProxy.cpp | masiboo/design-patterns-in-cpp | c690b1deecd0e70a132ad8768c519f1559b10246 | [
"Apache-2.0"
] | null | null | null | structural/proxy/SecureProxy.cpp | masiboo/design-patterns-in-cpp | c690b1deecd0e70a132ad8768c519f1559b10246 | [
"Apache-2.0"
] | null | null | null | #include "SecureProxy.h"
#include "RealClient.h"
#include <iostream>
using std::cin;
using std::cout;
using proxy::SecureProxy;
SecureProxy::SecureProxy(const char* pPasswd)
{
m_Passwd = new string( pPasswd );
m_Client = new RealClient();
}
SecureProxy::~SecureProxy()
{
delete m_Passwd;
m_Passwd = NULL;
delete m_Client;
m_Client = NULL;
}
const string& SecureProxy::GetAccountNumber()
{
string tmpPass;
cout<<"Enter passward: ";
cin>>tmpPass;
if( !tmpPass.compare( m_Passwd->c_str() ) )
{
return m_Client->GetAccountNumber();
}
throw "Illegal password...\n";
}
| 15.810811 | 45 | 0.702564 | masiboo |
a2ea29ecfc093b2473ab2ac741db4a544160338f | 4,931 | cpp | C++ | src/rl/hal/HilscherCifx.cpp | Roboy/rl | 7686cbd5f9c3630daa6d972f2244ed31f4dc5142 | [
"BSD-2-Clause"
] | 568 | 2015-01-23T03:38:45.000Z | 2022-03-30T16:12:56.000Z | src/rl/hal/HilscherCifx.cpp | jencureboy/rl | 658cdd8387397261ebf0f52d3bde74aae0379e24 | [
"BSD-2-Clause"
] | 53 | 2016-03-23T13:16:47.000Z | 2022-03-17T05:58:06.000Z | src/rl/hal/HilscherCifx.cpp | jencureboy/rl | 658cdd8387397261ebf0f52d3bde74aae0379e24 | [
"BSD-2-Clause"
] | 169 | 2015-01-26T12:59:41.000Z | 2022-03-29T13:44:54.000Z | //
// Copyright (c) 2009, Markus Rickert
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include <cstring>
#ifndef WIN32
#include <cifxlinux.h>
#endif // WIN32
#include "HilscherCifx.h"
namespace rl
{
namespace hal
{
HilscherCifx::HilscherCifx(const ::std::string& board, const ::std::size_t& number) :
Fieldbus(),
board(board),
channel(),
driver(),
number()
{
}
HilscherCifx::~HilscherCifx()
{
}
void
HilscherCifx::close()
{
::std::int32_t error = ::xChannelBusState(this->channel, CIFX_BUS_STATE_OFF, nullptr, 1000);
if (CIFX_NO_ERROR != error)
{
throw Exception(error);
}
error = ::xChannelConfigLock(this->channel, CIFX_CONFIGURATION_UNLOCK, nullptr, 1000);
if (CIFX_NO_ERROR != error)
{
throw Exception(error);
}
error = ::xChannelHostState(this->channel, CIFX_HOST_STATE_NOT_READY, nullptr, 1000);
if (CIFX_NO_ERROR != error)
{
throw Exception(error);
}
error = ::xChannelClose(&this->channel);
if (CIFX_NO_ERROR != error)
{
throw Exception(error);
}
error = ::xDriverClose(&this->driver);
if (CIFX_NO_ERROR != error)
{
throw Exception(error);
}
#ifndef WIN32
::cifXDriverDeinit();
#endif // WIN32
this->setConnected(false);
}
void
HilscherCifx::open()
{
::std::int32_t error;
#ifndef WIN32
::CIFX_LINUX_INIT init;
init.base_dir = nullptr;
init.iCardNumber = 0;
init.fEnableCardLocking = 0;
init.init_options = CIFX_DRIVER_INIT_AUTOSCAN;
init.poll_interval = 0;
init.poll_StackSize = 0;
init.trace_level = 255;
init.user_card_cnt = 0;
init.user_cards = nullptr;
error = ::cifXDriverInit(&init);
if (CIFX_NO_ERROR != error)
{
throw Exception(error);
}
#endif // WIN32
error = ::xDriverOpen(&this->driver);
if (CIFX_NO_ERROR != error)
{
throw Exception(error);
}
error = ::xChannelOpen(nullptr, const_cast<char*>(this->board.c_str()), this->number, &this->channel);
if (CIFX_NO_ERROR != error)
{
throw Exception(error);
}
error = ::xChannelHostState(this->channel, CIFX_HOST_STATE_READY, nullptr, 1000);
if (CIFX_NO_ERROR != error)
{
throw Exception(error);
}
error = ::xChannelConfigLock(this->channel, CIFX_CONFIGURATION_LOCK, nullptr, 1000);
if (CIFX_NO_ERROR != error)
{
throw Exception(error);
}
error = ::xChannelBusState(this->channel, CIFX_BUS_STATE_ON, nullptr, 1000);
if (CIFX_NO_ERROR != error)
{
throw Exception(error);
}
this->setConnected(true);
}
void
HilscherCifx::read(void* data, const ::std::size_t& offset, const ::std::size_t& length)
{
::std::int32_t error = ::xChannelIORead(this->channel, 0, offset, length, data, 10);
if (CIFX_NO_ERROR != error)
{
throw Exception(error);
}
}
void
HilscherCifx::write(void* data, const ::std::size_t& offset, const ::std::size_t& length)
{
::std::int32_t error = ::xChannelIOWrite(this->channel, 0, offset, length, data, 10);
if (CIFX_NO_ERROR != error)
{
throw Exception(error);
}
}
HilscherCifx::Exception::Exception(const ::std::int32_t& error) :
ComException(""),
buffer(),
error(error)
{
::xDriverGetErrorDescription(this->error, this->buffer, sizeof(this->buffer));
}
HilscherCifx::Exception::~Exception() throw()
{
}
::std::int32_t
HilscherCifx::Exception::getError() const
{
return this->error;
}
const char*
HilscherCifx::Exception::what() const throw()
{
return this->buffer;
}
}
}
| 23.821256 | 105 | 0.664571 | Roboy |
a2eb54cbc0b6596420a502a2c5229c5752bce2d5 | 5,355 | cxx | C++ | admin/netui/common/src/misc/fsenum/fsenmos2.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/netui/common/src/misc/fsenum/fsenmos2.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/netui/common/src/misc/fsenum/fsenmos2.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /**********************************************************************/
/** Microsoft Windows/NT **/
/** Copyright(c) Microsoft Corp., 1991 **/
/**********************************************************************/
/*
FSEnmOS2.cxx
This file contains the implementation of OS2_FS_ENUM
These are used for traversing files and directories
on a volume under OS/2.
FILE HISTORY:
Johnl 04-Oct-1991 Created
*/
#define INCL_DOSERRORS
#define INCL_NETERRORS
#define INCL_OS2
#include "lmui.hxx"
#include "fsenum.hxx"
/*************************************************************************
NAME: OS2_DIR_BLOCK
SYNOPSIS: Dir block that contains the OS2 File Find buffer
INTERFACE: See parent
PARENT: DIR_BLOCK
USES: FILEFINDBUF2, HDIR
CAVEATS:
NOTES:
HISTORY:
Johnl 16-Oct-1991 Created
**************************************************************************/
class OS2_DIR_BLOCK : public DIR_BLOCK
{
friend class OS2_FS_ENUM ;
private:
struct FILEFINDBUF2 _ffbuff2 ;
HDIR _hdir ;
public:
OS2_DIR_BLOCK() : _hdir( HDIR_CREATE )
{ /* Nothing else to do */ }
virtual ~OS2_DIR_BLOCK() ;
virtual UINT QueryAttr( void ) ;
virtual const TCHAR * QueryFileName( void ) ;
} ;
OS2_DIR_BLOCK::~OS2_DIR_BLOCK()
{
DosFindClose( _hdir ) ;
}
/*******************************************************************
NAME: OS2_DIR_BLOCK::QueryAttr
SYNOPSIS: Returns the file attributes for the current file
RETURNS: Bit mask of the current file attributes
NOTES:
HISTORY:
Johnl 16-Oct-1991 Created
********************************************************************/
UINT OS2_DIR_BLOCK::QueryAttr( void )
{
return (UINT) _ffbuff2.attrFile ;
}
/*******************************************************************
NAME: OS2_DIR_BLOCK::QueryFileName
SYNOPSIS: Returns the file name of the current file in this dir block
RETURNS: Pointer to the files name
NOTES: The client should be sure that FindFirst has successfully
been called on this dir block before invoking this method.
HISTORY:
Johnl 16-Oct-1991 Created
********************************************************************/
const TCHAR * OS2_DIR_BLOCK::QueryFileName( void )
{
return _ffbuff2.achName ;
}
/*******************************************************************
NAME: OS2_FS_ENUM::OS2_FS_ENUM
SYNOPSIS: Constructor for an OS/2 File/directory enumerator
ENTRY: pszPath - Base path to start the enumeration
pszMask - Mask to filter the files/dirs with
filtypInclude - include files/dirs or both
EXIT:
RETURNS:
NOTES:
HISTORY:
Johnl 16-Oct-1991 Created
********************************************************************/
OS2_FS_ENUM::OS2_FS_ENUM ( const TCHAR * pszPath,
const TCHAR * pszMask,
enum FILE_TYPE filtypeInclude )
: FS_ENUM( pszPath, pszMask, filtypeInclude )
{
if ( QueryError() )
return ;
}
OS2_FS_ENUM::~OS2_FS_ENUM ()
{ /* Nothing to do */ }
/*******************************************************************
NAME: OS2_FS_ENUM::FindFirst
SYNOPSIS: Regular FindFirst redefinition, calls DosFindFirst2
ENTRY: See parent
EXIT:
RETURNS: NERR_Success if successful, error code otherwise
NOTES:
HISTORY:
Johnl 16-Oct-1991 Created
********************************************************************/
APIERR OS2_FS_ENUM::FindFirst( DIR_BLOCK * pDirBlock,
const NLS_STR & nlsSearchPath,
UINT uiSearchAttr )
{
USHORT usSearchCount = 1 ;
OS2_DIR_BLOCK * pOS2DirBlock = (OS2_DIR_BLOCK *) pDirBlock ;
return DosFindFirst2( (PSZ) nlsSearchPath.QueryPch(),
&(pOS2DirBlock->_hdir),
(USHORT) uiSearchAttr,
(PVOID) &(pOS2DirBlock->_ffbuff2),
sizeof( pOS2DirBlock->_ffbuff2 ),
&usSearchCount,
FIL_QUERYEASIZE,
0L ) ;
}
/*******************************************************************
NAME: OS2_FS_ENUM::FindNext
SYNOPSIS: Typical FindNext redefinition, calls DosFindNext
ENTRY: See parent
EXIT:
RETURNS: NERR_Success if successful, error code otherwise
NOTES:
HISTORY:
Johnl 16-Oct-1991 Created
********************************************************************/
APIERR OS2_FS_ENUM::FindNext( DIR_BLOCK * pDirBlock, UINT uiSearchAttr )
{
USHORT usSearchCount = 1 ;
OS2_DIR_BLOCK * pOS2DirBlock = (OS2_DIR_BLOCK *) pDirBlock ;
return DosFindNext( pOS2DirBlock->_hdir,
(PFILEFINDBUF) &(pOS2DirBlock->_ffbuff2),
sizeof( pOS2DirBlock->_ffbuff2 ),
&usSearchCount ) ;
}
/*******************************************************************
NAME: OS2_FS_ENUM::CreateDirBlock
SYNOPSIS: Typical redefinition of CreateDirBlock
ENTRY:
EXIT:
RETURNS: A pointer to a newly created OS2_DIR_BLOCK
NOTES:
HISTORY:
Johnl 16-Oct-1991 Created
********************************************************************/
DIR_BLOCK * OS2_FS_ENUM::CreateDirBlock( void )
{
return new OS2_DIR_BLOCK() ;
}
| 22.690678 | 76 | 0.50887 | npocmaka |
a2ecd9f3ff23a5e466fc34cb47c96b795bb37149 | 28,270 | cpp | C++ | printscan/ui/wiadefui/ppscan.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | printscan/ui/wiadefui/ppscan.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | printscan/ui/wiadefui/ppscan.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*******************************************************************************
*
* (C) COPYRIGHT MICROSOFT CORPORATION, 1998
*
* TITLE: PPSCAN.CPP
*
* VERSION: 1.0
*
* AUTHOR: ShaunIv
*
* DATE: 5/17/1999
*
* DESCRIPTION:
*
*******************************************************************************/
#include "precomp.h"
#pragma hdrstop
#include "ppscan.h"
#include "resource.h"
#include "wiacsh.h"
//
// Context Help IDs
//
static const DWORD g_HelpIDs[] =
{
IDC_SCANPROP_BRIGHTNESS_PROMPT, IDH_WIA_BRIGHTNESS,
IDC_SCANPROP_BRIGHTNESS_SLIDER, IDH_WIA_BRIGHTNESS,
IDC_SCANPROP_BRIGHTNESS_EDIT, IDH_WIA_BRIGHTNESS,
IDC_SCANPROP_CONTRAST_PROMPT, IDH_WIA_CONTRAST,
IDC_SCANPROP_CONTRAST_SLIDER, IDH_WIA_CONTRAST,
IDC_SCANPROP_CONTRAST_EDIT, IDH_WIA_CONTRAST,
IDC_SCANPROP_RESOLUTION_PROMPT, IDH_WIA_PIC_RESOLUTION,
IDC_SCANPROP_RESOLUTION_EDIT, IDH_WIA_PIC_RESOLUTION,
IDC_SCANPROP_RESOLUTION_UPDOWN, IDH_WIA_PIC_RESOLUTION,
IDC_SCANPROP_PREVIEW, IDH_WIA_CUSTOM_PREVIEW,
IDC_SCANPROP_DATATYPE_PROMPT, IDH_WIA_IMAGE_TYPE,
IDC_SCANPROP_DATATYPE_LIST, IDH_WIA_IMAGE_TYPE,
IDC_SCANPROP_RESTOREDEFAULT, IDH_WIA_RESTORE_DEFAULT,
IDOK, IDH_OK,
IDCANCEL, IDH_CANCEL,
0, 0
};
extern HINSTANCE g_hInstance;
//
// These are the data types we support
//
static struct
{
int nStringId;
LONG nDataType;
UINT nPreviewWindowIntent;
} g_AvailableColorDepths[] =
{
{ IDS_SCANPROP_COLOR, WIA_DATA_COLOR, BCPWM_COLOR },
{ IDS_SCANPROP_GRAYSCALE, WIA_DATA_GRAYSCALE, BCPWM_GRAYSCALE },
{ IDS_SCANPROP_BLACKANDWHITE, WIA_DATA_THRESHOLD, BCPWM_BW }
};
#define AVAILABLE_COLOR_DEPTH_COUNT (sizeof(g_AvailableColorDepths)/sizeof(g_AvailableColorDepths[0]))
//
// If we don't have a good range of values for the brightness and contrast settings,
// we want to disable the preview control. This is the minumum number of values
// we consider useful for this purpose
//
const int CScannerCommonPropertyPage::c_nMinBrightnessAndContrastSettingCount = 10;
//
// The only constructor
//
CScannerCommonPropertyPage::CScannerCommonPropertyPage( HWND hWnd )
: m_hWnd(hWnd),
m_nProgrammaticSetting(0),
m_nControlsInUse(0)
{
}
CScannerCommonPropertyPage::~CScannerCommonPropertyPage(void)
{
m_hWnd = NULL;
}
LRESULT CScannerCommonPropertyPage::OnKillActive( WPARAM , LPARAM )
{
CWaitCursor wc;
if (!ValidateEditControls())
{
return TRUE;
}
ApplySettings();
return FALSE;
}
LRESULT CScannerCommonPropertyPage::OnSetActive( WPARAM , LPARAM )
{
CWaitCursor wc;
Initialize();
return 0;
}
LRESULT CScannerCommonPropertyPage::OnApply( WPARAM , LPARAM )
{
if (ApplySettings())
{
return PSNRET_NOERROR;
}
else
{
//
// Tell the user there was an error
//
MessageBox( m_hWnd,
CSimpleString( IDS_SCANPROP_UNABLETOWRITE, g_hInstance ),
CSimpleString( IDS_SCANPROP_ERROR_TITLE, g_hInstance ),
MB_ICONINFORMATION );
return PSNRET_INVALID_NOCHANGEPAGE;
}
}
void CScannerCommonPropertyPage::SetText( HWND hWnd, LPCTSTR pszText )
{
m_nProgrammaticSetting++;
SetWindowText( hWnd, pszText );
m_nProgrammaticSetting--;
}
void CScannerCommonPropertyPage::SetText( HWND hWnd, LONG nNumber )
{
SetText( hWnd, CSimpleStringConvert::NumberToString( nNumber ) );
}
bool CScannerCommonPropertyPage::PopulateDataTypes(void)
{
//
// We will be successful if we can add at least one data type
//
bool bSuccess = false;
//
// Clear the list
//
SendDlgItemMessage( m_hWnd, IDC_SCANPROP_DATATYPE_LIST, CB_RESETCONTENT, 0, 0 );
//
// Try to load the data types for this device
//
CSimpleDynamicArray<LONG> SupportedDataTypes;
LONG nCurrentDataType;
if (PropStorageHelpers::GetProperty( m_pIWiaItem, WIA_IPA_DATATYPE, nCurrentDataType ) &&
PropStorageHelpers::GetPropertyList( m_pIWiaItem, WIA_IPA_DATATYPE, SupportedDataTypes ))
{
//
// Loop through each of the data types we handle, and see if it is supported by the device
//
m_nInitialDataTypeSelection = 0;
for (int i=0;i<AVAILABLE_COLOR_DEPTH_COUNT;i++)
{
//
// Is this one of the data types we support?
//
if (SupportedDataTypes.Find(g_AvailableColorDepths[i].nDataType) != -1)
{
//
// Load the data type string and make sure it is valid
//
CSimpleString strDataTypeName( g_AvailableColorDepths[i].nStringId, g_hInstance );
if (strDataTypeName.Length())
{
//
// Add the string to the combo box
//
LRESULT nIndex = SendDlgItemMessage( m_hWnd, IDC_SCANPROP_DATATYPE_LIST, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(strDataTypeName.String()));
if (nIndex != CB_ERR)
{
//
// Save the index of the global data type struct we are using for this entry
//
SendDlgItemMessage( m_hWnd, IDC_SCANPROP_DATATYPE_LIST, CB_SETITEMDATA, nIndex, i );
//
// Whew, we made it at least once, so we are using this control
//
bSuccess = true;
//
// Save the current selection and update the preview control
//
if (nCurrentDataType == g_AvailableColorDepths[i].nDataType)
{
m_nInitialDataTypeSelection = static_cast<int>(nIndex);
SendDlgItemMessage( m_hWnd, IDC_SCANPROP_PREVIEW, BCPWM_SETINTENT, 0, g_AvailableColorDepths[i].nPreviewWindowIntent );
}
}
}
}
}
//
// Set the current selection
//
SendDlgItemMessage( m_hWnd, IDC_SCANPROP_DATATYPE_LIST, CB_SETCURSEL, m_nInitialDataTypeSelection, 0 );
}
return bSuccess;
}
bool CScannerCommonPropertyPage::IsUselessPreviewRange( const CValidWiaSettings &Settings )
{
return (Settings.GetItemCount() < c_nMinBrightnessAndContrastSettingCount);
}
void CScannerCommonPropertyPage::Initialize()
{
//
// Make sure we don't get into an infinite loop
//
m_nProgrammaticSetting++;
//
// Assume we aren't using any controls at all
//
m_nControlsInUse = 0;
//
// Get the valid settings for brightness and set up the associated controls
//
if (!m_ValidBrightnessSettings.Read( m_pIWiaItem, WIA_IPS_BRIGHTNESS ))
{
//
// Disable brightness controls
//
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_BRIGHTNESS_PROMPT ), FALSE );
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_BRIGHTNESS_EDIT ), FALSE );
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_BRIGHTNESS_SLIDER ), FALSE );
}
else
{
//
// Enable brightness controls
//
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_BRIGHTNESS_PROMPT ), TRUE );
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_BRIGHTNESS_EDIT ), TRUE );
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_BRIGHTNESS_SLIDER ), TRUE );
m_BrightnessSliderAndEdit.Initialize(
GetDlgItem(m_hWnd,IDC_SCANPROP_BRIGHTNESS_SLIDER),
GetDlgItem(m_hWnd,IDC_SCANPROP_BRIGHTNESS_EDIT),
GetDlgItem(m_hWnd,IDC_SCANPROP_PREVIEW),
BCPWM_SETBRIGHTNESS, &m_ValidBrightnessSettings );
//
// Remember that we are using this control
//
m_nControlsInUse |= UsingBrightness;
}
//
// Get the valid settings for contrast and set up the associated controls
//
if (!m_ValidContrastSettings.Read( m_pIWiaItem, WIA_IPS_CONTRAST ))
{
//
// Disable contrast controls
//
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_CONTRAST_PROMPT ), FALSE );
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_CONTRAST_EDIT ), FALSE );
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_CONTRAST_SLIDER ), FALSE );
}
else
{
//
// Enable contrast controls
//
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_CONTRAST_PROMPT ), TRUE );
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_CONTRAST_EDIT ), TRUE );
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_CONTRAST_SLIDER ), TRUE );
m_ContrastSliderAndEdit.Initialize(
GetDlgItem(m_hWnd,IDC_SCANPROP_CONTRAST_SLIDER),
GetDlgItem(m_hWnd,IDC_SCANPROP_CONTRAST_EDIT),
GetDlgItem(m_hWnd,IDC_SCANPROP_PREVIEW),
BCPWM_SETCONTRAST, &m_ValidContrastSettings );
//
// Remember that we are using this control
//
m_nControlsInUse |= UsingContrast;
}
//
// Should we disable resolution? Assume yes.
//
bool bDisableResolution = true;
//
// Figure out what the *common* list of valid settings for horizontal
// and vertical resolution
//
CValidWiaSettings HorizontalResolution;
if (HorizontalResolution.Read( m_pIWiaItem, WIA_IPS_XRES ))
{
//
// Y Resolution can be read-only, and be linked to X resolution
//
if (PropStorageHelpers::IsReadOnlyProperty(m_pIWiaItem, WIA_IPS_YRES))
{
m_ValidResolutionSettings = HorizontalResolution;
//
// If we made it this far, we have good resolution settings
//
bDisableResolution = false;
}
else
{
CValidWiaSettings VerticalResolution;
if (VerticalResolution.Read( m_pIWiaItem, WIA_IPS_YRES ))
{
if (m_ValidResolutionSettings.FindIntersection(HorizontalResolution,VerticalResolution))
{
//
// If we made it this far, we have good resolution settings
//
bDisableResolution = false;
}
}
}
}
//
// If we can't display resolution, disable it
//
if (bDisableResolution)
{
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_RESOLUTION_PROMPT ), FALSE );
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_RESOLUTION_EDIT ), FALSE );
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_RESOLUTION_UPDOWN ), FALSE );
}
else
{
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_RESOLUTION_PROMPT ), TRUE );
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_RESOLUTION_EDIT ), TRUE );
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_RESOLUTION_UPDOWN ), TRUE );
m_ResolutionUpDownAndEdit.Initialize(
GetDlgItem( m_hWnd, IDC_SCANPROP_RESOLUTION_UPDOWN ),
GetDlgItem( m_hWnd, IDC_SCANPROP_RESOLUTION_EDIT ),
&m_ValidResolutionSettings );
//
// Remember that we are using this control
//
m_nControlsInUse |= UsingResolution;
}
//
// If we can't populate datatype, disable it
//
if (!PopulateDataTypes())
{
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_DATATYPE_PROMPT ), FALSE );
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_DATATYPE_LIST ), FALSE );
}
else
{
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_DATATYPE_PROMPT ), TRUE );
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_DATATYPE_LIST ), TRUE );
m_nControlsInUse |= UsingDataType;
}
//
// This means all controls were disabled
//
if (!m_nControlsInUse)
{
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_RESTOREDEFAULT ), FALSE );
}
else
{
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_RESTOREDEFAULT ), TRUE );
}
//
// If we are not using brightness or contrast OR if the brightness and contrast values are not useful
// for presenting meaningful feedback, disable the preview control so it doesn't mislead the user.
//
if (!(m_nControlsInUse & (UsingContrast|UsingBrightness)) || IsUselessPreviewRange(m_ValidBrightnessSettings) || IsUselessPreviewRange(m_ValidContrastSettings))
{
EnableWindow( GetDlgItem( m_hWnd, IDC_SCANPROP_PREVIEW ), FALSE );
}
//
// Start responding to EN_CHANGE messages again
//
m_nProgrammaticSetting--;
//
// Make sure the correct image is in the thumbnail
//
OnDataTypeSelChange(0,0);
}
LRESULT CScannerCommonPropertyPage::OnInitDialog( WPARAM, LPARAM lParam )
{
//
// Get the WIA item
//
PROPSHEETPAGE *pPropSheetPage = reinterpret_cast<PROPSHEETPAGE*>(lParam);
if (pPropSheetPage)
{
m_pIWiaItem = reinterpret_cast<IWiaItem*>(pPropSheetPage->lParam);
}
if (!m_pIWiaItem)
{
return -1;
}
//
// Load the preview control bitmaps
//
HBITMAP hBmpColor = reinterpret_cast<HBITMAP>(LoadImage(g_hInstance, MAKEINTRESOURCE(IDB_SCANPROP_BITMAPPHOTO), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION ));
HBITMAP hBmpGrayscale = reinterpret_cast<HBITMAP>(LoadImage(g_hInstance, MAKEINTRESOURCE(IDB_SCANPROP_BITMAPGRAYSCALE), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION ));
HBITMAP hBmpBlackAndWhite = reinterpret_cast<HBITMAP>(LoadImage(g_hInstance, MAKEINTRESOURCE(IDB_SCANPROP_BITMAPTEXT), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION ));
//
// If they all loaded OK, set them
//
if (hBmpColor && hBmpGrayscale && hBmpBlackAndWhite)
{
SendDlgItemMessage( m_hWnd, IDC_SCANPROP_PREVIEW, BCPWM_LOADIMAGE, BCPWM_COLOR, reinterpret_cast<LPARAM>(hBmpColor));
SendDlgItemMessage( m_hWnd, IDC_SCANPROP_PREVIEW, BCPWM_LOADIMAGE, BCPWM_GRAYSCALE, reinterpret_cast<LPARAM>(hBmpGrayscale));
SendDlgItemMessage( m_hWnd, IDC_SCANPROP_PREVIEW, BCPWM_LOADIMAGE, BCPWM_BW, reinterpret_cast<LPARAM>(hBmpBlackAndWhite));
}
else
{
//
// Otherwise delete all of the bitmaps
//
if (hBmpColor)
{
DeleteObject(hBmpColor);
}
if (hBmpGrayscale)
{
DeleteObject(hBmpGrayscale);
}
if (hBmpBlackAndWhite)
{
DeleteObject(hBmpBlackAndWhite);
}
}
return TRUE;
}
LRESULT CScannerCommonPropertyPage::OnHScroll( WPARAM wParam, LPARAM lParam )
{
WIA_PUSH_FUNCTION((TEXT("CScannerCommonPropertyPage::OnHScroll( %08X, %08X )"), wParam, lParam ));
if (m_nProgrammaticSetting)
{
return 0;
}
//
// Contrast
//
if (reinterpret_cast<HWND>(lParam) == GetDlgItem( m_hWnd, IDC_SCANPROP_CONTRAST_SLIDER ) )
{
m_nProgrammaticSetting++;
m_ContrastSliderAndEdit.HandleSliderUpdate();
m_nProgrammaticSetting--;
}
//
// Brightness
//
else if (reinterpret_cast<HWND>(lParam) == GetDlgItem( m_hWnd, IDC_SCANPROP_BRIGHTNESS_SLIDER ) )
{
m_nProgrammaticSetting++;
m_BrightnessSliderAndEdit.HandleSliderUpdate();
m_nProgrammaticSetting--;
}
return 0;
}
LRESULT CScannerCommonPropertyPage::OnVScroll( WPARAM wParam, LPARAM lParam )
{
WIA_PUSH_FUNCTION((TEXT("CScannerCommonPropertyPage::OnVScroll( %08X, %08X )"), wParam, lParam ));
if (m_nProgrammaticSetting)
{
return 0;
}
//
// Resolution
//
if (reinterpret_cast<HWND>(lParam) == GetDlgItem( m_hWnd, IDC_SCANPROP_RESOLUTION_UPDOWN ) )
{
m_nProgrammaticSetting++;
m_ResolutionUpDownAndEdit.HandleUpDownUpdate();
m_nProgrammaticSetting--;
}
return 0;
}
void CScannerCommonPropertyPage::OnBrightnessEditChange( WPARAM, LPARAM )
{
if (m_nProgrammaticSetting)
{
return;
}
m_nProgrammaticSetting++;
m_BrightnessSliderAndEdit.HandleEditUpdate();
m_nProgrammaticSetting--;
}
void CScannerCommonPropertyPage::OnContrastEditChange( WPARAM, LPARAM )
{
if (m_nProgrammaticSetting)
{
return;
}
m_nProgrammaticSetting++;
m_ContrastSliderAndEdit.HandleEditUpdate();
m_nProgrammaticSetting--;
}
void CScannerCommonPropertyPage::OnResolutionEditChange( WPARAM, LPARAM )
{
if (m_nProgrammaticSetting)
{
return;
}
m_nProgrammaticSetting++;
m_ResolutionUpDownAndEdit.HandleEditUpdate();
m_nProgrammaticSetting--;
}
void CScannerCommonPropertyPage::OnDataTypeSelChange( WPARAM, LPARAM )
{
if (m_nProgrammaticSetting)
{
return;
}
m_nProgrammaticSetting++;
int nCurSel = static_cast<int>(SendDlgItemMessage( m_hWnd, IDC_SCANPROP_DATATYPE_LIST, CB_GETCURSEL, 0, 0 ));
if (nCurSel != CB_ERR)
{
int nDataTypeIndex = static_cast<int>(SendDlgItemMessage( m_hWnd, IDC_SCANPROP_DATATYPE_LIST, CB_GETITEMDATA, nCurSel, 0 ));
if (nDataTypeIndex >= 0 && nDataTypeIndex < AVAILABLE_COLOR_DEPTH_COUNT)
{
SendDlgItemMessage( m_hWnd, IDC_SCANPROP_PREVIEW, BCPWM_SETINTENT, 0, g_AvailableColorDepths[nDataTypeIndex].nPreviewWindowIntent );
if (m_nControlsInUse & UsingContrast)
{
if (BCPWM_BW == g_AvailableColorDepths[nDataTypeIndex].nPreviewWindowIntent)
{
EnableWindow( GetDlgItem(m_hWnd,IDC_SCANPROP_CONTRAST_PROMPT), FALSE );
ShowWindow( GetDlgItem(m_hWnd,IDC_SCANPROP_CONTRAST_PROMPT), SW_HIDE );
EnableWindow( GetDlgItem(m_hWnd,IDC_SCANPROP_CONTRAST_SLIDER), FALSE );
ShowWindow( GetDlgItem(m_hWnd,IDC_SCANPROP_CONTRAST_SLIDER), SW_HIDE );
EnableWindow( GetDlgItem(m_hWnd,IDC_SCANPROP_CONTRAST_EDIT), FALSE );
ShowWindow( GetDlgItem(m_hWnd,IDC_SCANPROP_CONTRAST_EDIT), SW_HIDE );
}
else
{
EnableWindow( GetDlgItem(m_hWnd,IDC_SCANPROP_CONTRAST_PROMPT), TRUE );
ShowWindow( GetDlgItem(m_hWnd,IDC_SCANPROP_CONTRAST_PROMPT), SW_SHOW );
EnableWindow( GetDlgItem(m_hWnd,IDC_SCANPROP_CONTRAST_SLIDER), TRUE );
ShowWindow( GetDlgItem(m_hWnd,IDC_SCANPROP_CONTRAST_SLIDER), SW_SHOW );
EnableWindow( GetDlgItem(m_hWnd,IDC_SCANPROP_CONTRAST_EDIT), TRUE );
ShowWindow( GetDlgItem(m_hWnd,IDC_SCANPROP_CONTRAST_EDIT), SW_SHOW );
}
}
}
}
m_nProgrammaticSetting--;
}
bool CScannerCommonPropertyPage::ValidateEditControls(void)
{
m_nProgrammaticSetting++;
bool bSuccess = true;
//
// Get and set the brightness setting
//
if (m_nControlsInUse & UsingBrightness)
{
if (m_ValidBrightnessSettings.IsValid() && !m_BrightnessSliderAndEdit.ValidateEditControl())
{
m_BrightnessSliderAndEdit.HandleEditUpdate();
m_BrightnessSliderAndEdit.HandleSliderUpdate();
SetFocus( GetDlgItem( m_hWnd, IDC_SCANPROP_BRIGHTNESS_EDIT ) );
CSimpleString strMessage;
strMessage.Format( IDS_SCANPROP_INVALIDEDITVALUE, g_hInstance,
CSimpleString( IDS_SCANPROP_BRIGHTNESS, g_hInstance ).String() );
if (strMessage.Length())
{
MessageBox( m_hWnd,
strMessage,
CSimpleString( IDS_SCANPROP_ERROR_TITLE, g_hInstance ),
MB_ICONINFORMATION );
}
bSuccess = false;
}
}
//
// Get and set the contrast setting
//
if (m_nControlsInUse & UsingContrast)
{
if (m_ValidContrastSettings.IsValid() && !m_ContrastSliderAndEdit.ValidateEditControl())
{
m_ContrastSliderAndEdit.HandleEditUpdate();
m_ContrastSliderAndEdit.HandleSliderUpdate();
SetFocus( GetDlgItem( m_hWnd, IDC_SCANPROP_CONTRAST_EDIT ) );
CSimpleString strMessage;
strMessage.Format( IDS_SCANPROP_INVALIDEDITVALUE, g_hInstance,
CSimpleString( IDS_SCANPROP_CONTRAST, g_hInstance ).String());
if (strMessage.Length())
{
MessageBox( m_hWnd,
strMessage,
CSimpleString( IDS_SCANPROP_ERROR_TITLE, g_hInstance ),
MB_ICONINFORMATION );
}
bSuccess = false;
}
}
//
// Get and set the resolution setting
//
if (m_nControlsInUse & UsingResolution)
{
if (m_ValidResolutionSettings.IsValid() && !m_ResolutionUpDownAndEdit.ValidateEditControl())
{
m_ResolutionUpDownAndEdit.HandleEditUpdate();
m_ResolutionUpDownAndEdit.HandleUpDownUpdate();
SetFocus( GetDlgItem( m_hWnd, IDC_SCANPROP_RESOLUTION_EDIT ) );
CSimpleString strMessage;
strMessage.Format( IDS_SCANPROP_INVALIDEDITVALUE, g_hInstance,
CSimpleString( IDS_SCANPROP_RESOLUTION, g_hInstance ).String());
if (strMessage.Length())
{
MessageBox( m_hWnd,
strMessage,
CSimpleString( IDS_SCANPROP_ERROR_TITLE, g_hInstance ),
MB_ICONINFORMATION );
}
bSuccess = false;
}
}
//
// If we made it this far, we're OK
//
m_nProgrammaticSetting--;
return bSuccess;
}
bool CScannerCommonPropertyPage::ApplySettings(void)
{
//
// Get and set the brightness setting
//
if (m_nControlsInUse & UsingBrightness)
{
LONG nBrightness = m_BrightnessSliderAndEdit.GetValueFromCurrentPos();
if (!PropStorageHelpers::SetProperty( m_pIWiaItem, WIA_IPS_BRIGHTNESS, nBrightness ))
{
return false;
}
}
//
// Get and set the contrast setting
//
if (m_nControlsInUse & UsingBrightness)
{
LONG nContrast = m_ContrastSliderAndEdit.GetValueFromCurrentPos();
if (!PropStorageHelpers::SetProperty( m_pIWiaItem, WIA_IPS_CONTRAST, nContrast ))
{
return false;
}
}
//
// Get and set the resolution setting
//
if (m_nControlsInUse & UsingResolution)
{
LONG nResolution = m_ResolutionUpDownAndEdit.GetValueFromCurrentPos();
if (!PropStorageHelpers::SetProperty( m_pIWiaItem, WIA_IPS_XRES, nResolution ) ||
(!PropStorageHelpers::IsReadOnlyProperty( m_pIWiaItem, WIA_IPS_YRES ) && !PropStorageHelpers::SetProperty( m_pIWiaItem, WIA_IPS_YRES, nResolution )))
{
return false;
}
}
//
// Get, validate and set the data type setting
//
if (m_nControlsInUse & UsingDataType)
{
int nCurSel = static_cast<int>(SendDlgItemMessage( m_hWnd, IDC_SCANPROP_DATATYPE_LIST, CB_GETCURSEL, 0, 0 ));
if (nCurSel != CB_ERR)
{
int nDataTypeIndex = static_cast<int>(SendDlgItemMessage( m_hWnd, IDC_SCANPROP_DATATYPE_LIST, CB_GETITEMDATA, nCurSel, 0 ));
if (nDataTypeIndex >= 0 && nDataTypeIndex < AVAILABLE_COLOR_DEPTH_COUNT)
{
LONG nDataType = g_AvailableColorDepths[nDataTypeIndex].nDataType;
if (!PropStorageHelpers::SetProperty( m_pIWiaItem, WIA_IPA_DATATYPE, nDataType ))
{
return false;
}
}
}
}
//
// If we made it this far, we're OK
//
return true;
}
void CScannerCommonPropertyPage::OnRestoreDefault( WPARAM, LPARAM )
{
//
// Ignore EN_CHANGE messages
//
m_nProgrammaticSetting++;
//
// Restore the brightness setting
//
if (m_nControlsInUse & UsingBrightness)
{
m_BrightnessSliderAndEdit.Restore();
}
//
// Restore the contrast setting
//
if (m_nControlsInUse & UsingContrast)
{
m_ContrastSliderAndEdit.Restore();
}
//
// Restore the resolution setting
//
if (m_nControlsInUse & UsingResolution)
{
m_ResolutionUpDownAndEdit.Restore();
}
//
// Restore the data type setting
//
if (m_nControlsInUse & UsingDataType)
{
SendDlgItemMessage( m_hWnd, IDC_SCANPROP_DATATYPE_LIST, CB_SETCURSEL, m_nInitialDataTypeSelection, 0 );
SendDlgItemMessage( m_hWnd, IDC_SCANPROP_PREVIEW, BCPWM_SETINTENT, 0, g_AvailableColorDepths[m_nInitialDataTypeSelection].nPreviewWindowIntent );
}
//
// OK, start handling user input
//
m_nProgrammaticSetting--;
//
// Force an update of the data type controls
//
OnDataTypeSelChange(0,0);
}
LRESULT CScannerCommonPropertyPage::OnHelp( WPARAM wParam, LPARAM lParam )
{
return WiaHelp::HandleWmHelp( wParam, lParam, g_HelpIDs );
}
LRESULT CScannerCommonPropertyPage::OnContextMenu( WPARAM wParam, LPARAM lParam )
{
return WiaHelp::HandleWmContextMenu( wParam, lParam, g_HelpIDs );
}
LRESULT CScannerCommonPropertyPage::OnSysColorChange( WPARAM wParam, LPARAM lParam )
{
SendDlgItemMessage( m_hWnd, IDC_SCANPROP_BRIGHTNESS_SLIDER, WM_SYSCOLORCHANGE, wParam, lParam );
SendDlgItemMessage( m_hWnd, IDC_SCANPROP_CONTRAST_SLIDER, WM_SYSCOLORCHANGE, wParam, lParam );
return 0;
}
LRESULT CScannerCommonPropertyPage::OnNotify( WPARAM wParam, LPARAM lParam )
{
SC_BEGIN_NOTIFY_MESSAGE_HANDLERS()
{
SC_HANDLE_NOTIFY_MESSAGE_CODE(PSN_APPLY, OnApply);
SC_HANDLE_NOTIFY_MESSAGE_CODE(PSN_KILLACTIVE,OnKillActive);
SC_HANDLE_NOTIFY_MESSAGE_CODE(PSN_SETACTIVE,OnSetActive);
}
SC_END_NOTIFY_MESSAGE_HANDLERS();
}
LRESULT CScannerCommonPropertyPage::OnCommand( WPARAM wParam, LPARAM lParam )
{
SC_BEGIN_COMMAND_HANDLERS()
{
SC_HANDLE_COMMAND_NOTIFY(EN_CHANGE,IDC_SCANPROP_BRIGHTNESS_EDIT,OnBrightnessEditChange);
SC_HANDLE_COMMAND_NOTIFY(EN_CHANGE,IDC_SCANPROP_CONTRAST_EDIT,OnContrastEditChange);
SC_HANDLE_COMMAND_NOTIFY(EN_CHANGE,IDC_SCANPROP_RESOLUTION_EDIT,OnResolutionEditChange);
SC_HANDLE_COMMAND_NOTIFY(CBN_SELCHANGE,IDC_SCANPROP_DATATYPE_LIST,OnDataTypeSelChange);
SC_HANDLE_COMMAND( IDC_SCANPROP_RESTOREDEFAULT, OnRestoreDefault );
}
SC_END_COMMAND_HANDLERS();
}
INT_PTR CALLBACK CScannerCommonPropertyPage::DialogProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
SC_BEGIN_DIALOG_MESSAGE_HANDLERS(CScannerCommonPropertyPage)
{
SC_HANDLE_DIALOG_MESSAGE( WM_INITDIALOG, OnInitDialog );
SC_HANDLE_DIALOG_MESSAGE( WM_NOTIFY, OnNotify );
SC_HANDLE_DIALOG_MESSAGE( WM_COMMAND, OnCommand );
SC_HANDLE_DIALOG_MESSAGE( WM_HSCROLL, OnHScroll );
SC_HANDLE_DIALOG_MESSAGE( WM_VSCROLL, OnVScroll );
SC_HANDLE_DIALOG_MESSAGE( WM_HELP, OnHelp );
SC_HANDLE_DIALOG_MESSAGE( WM_CONTEXTMENU, OnContextMenu );
SC_HANDLE_DIALOG_MESSAGE( WM_SYSCOLORCHANGE, OnSysColorChange );
}
SC_END_DIALOG_MESSAGE_HANDLERS();
}
| 32.948718 | 172 | 0.621224 | npocmaka |
a2ee18462b6b3ca688687e7953cb349c73c33be8 | 1,658 | cpp | C++ | src/services/cpuinfo/CpuInfo.cpp | slabasan/Caliper | 85601f48e7f883fb87dec85e92c849eec2bb61f7 | [
"BSD-3-Clause"
] | 220 | 2016-01-19T19:00:10.000Z | 2022-03-29T02:09:39.000Z | src/services/cpuinfo/CpuInfo.cpp | slabasan/Caliper | 85601f48e7f883fb87dec85e92c849eec2bb61f7 | [
"BSD-3-Clause"
] | 328 | 2016-05-12T15:47:30.000Z | 2022-03-30T19:42:02.000Z | src/services/cpuinfo/CpuInfo.cpp | slabasan/Caliper | 85601f48e7f883fb87dec85e92c849eec2bb61f7 | [
"BSD-3-Clause"
] | 48 | 2016-03-04T22:04:39.000Z | 2021-12-18T12:11:43.000Z | // Copyright (c) 2019, Lawrence Livermore National Security, LLC.
// See top-level LICENSE file for details.
#include "caliper/CaliperService.h"
#include "caliper/Caliper.h"
#include "caliper/SnapshotRecord.h"
#include "caliper/common/Attribute.h"
#include "caliper/common/Log.h"
#include <unistd.h>
#include <sys/syscall.h>
using namespace cali;
namespace
{
Attribute cpu_attr;
Attribute node_attr;
void snapshot_cb(Caliper*, Channel*, int scopes, const SnapshotRecord*, SnapshotRecord* rec)
{
#ifdef SYS_getcpu
if (scopes & CALI_SCOPE_THREAD) {
unsigned cpu = 0, node = 0;
if (syscall(SYS_getcpu, &cpu, &node, NULL) == 0) {
rec->append(cpu_attr.id(),
cali_make_variant_from_uint(cpu));
rec->append(node_attr.id(),
cali_make_variant_from_uint(node));
}
}
#endif
}
void cpuinfo_register(Caliper* c, Channel* chn)
{
cpu_attr =
c->create_attribute("cpuinfo.cpu", CALI_TYPE_UINT,
CALI_ATTR_ASVALUE |
CALI_ATTR_SKIP_EVENTS |
CALI_ATTR_SCOPE_THREAD);
node_attr =
c->create_attribute("cpuinfo.numa_node", CALI_TYPE_UINT,
CALI_ATTR_ASVALUE |
CALI_ATTR_SKIP_EVENTS |
CALI_ATTR_SCOPE_THREAD);
chn->events().snapshot.connect(snapshot_cb);
Log(1).stream() << chn->name() << ": Registered cpuinfo service" << std::endl;
}
} // namespace [anonymous]
namespace cali
{
CaliperService cpuinfo_service = { "cpuinfo", ::cpuinfo_register };
}
| 25.121212 | 92 | 0.606755 | slabasan |
a2ee3f17801ab1032dc63d99d54c03bcd005f0d0 | 11,991 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/dreams/DreamController.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/dreams/DreamController.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/dreams/DreamController.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// 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 "elastos/droid/server/dreams/DreamController.h"
#include <elastos/droid/os/UserHandle.h>
#include <elastos/core/StringBuilder.h>
#include <elastos/utility/logging/Slogger.h>
#include <Elastos.Droid.Os.h>
#include <Elastos.Droid.View.h>
#include <Elastos.Droid.Service.h>
#include <Elastos.CoreLibrary.IO.h>
using Elastos::Droid::Os::UserHandle;
using Elastos::Droid::Os::IUserHandle;
using Elastos::Droid::Os::CUserHandle;
using Elastos::Droid::View::IWindowManagerGlobal;
using Elastos::Droid::View::CWindowManagerGlobal;
using Elastos::Droid::View::IWindowManagerGlobalHelper;
using Elastos::Droid::View::CWindowManagerGlobalHelper;
using Elastos::Droid::View::IWindowManagerLayoutParams;
using Elastos::Droid::Content::CIntent;
using Elastos::Droid::Content::IIntent;
using Elastos::Droid::Service::Dreams::IDreamService;
using Elastos::Droid::Content::EIID_IServiceConnection;
using Elastos::Core::StringBuilder;
using Elastos::Core::EIID_IRunnable;
using Elastos::Utility::Logging::Slogger;
namespace Elastos {
namespace Droid {
namespace Server {
namespace Dreams {
const String DreamController::TAG("DreamController");
const Int32 DreamController::DREAM_CONNECTION_TIMEOUT;
const Int32 DreamController::DREAM_FINISH_TIMEOUT;
ECode DreamController::ProxyDiedRunnable::Run()
{
mDRHost->mService = NULL;
if (mDRHost->mHost->mCurrentDream.Get() == mDRHost) {
mDRHost->mHost->StopDream(TRUE /*immediate*/);
}
return NOERROR;
}
ECode DreamController::ConnectedRunnable::Run()
{
mDRHost->mConnected = TRUE;
if (mDRHost->mHost->mCurrentDream.Get() == mDRHost && mDRHost->mService == NULL) {
mDRHost->mHost->Attach(IIDreamService::Probe(mService));
}
return NOERROR;
}
ECode DreamController::DisconnectedRunnable::Run()
{
mDRHost->mService = NULL;
if (mDRHost->mHost->mCurrentDream.Get() == mDRHost) {
mDRHost->mHost->StopDream(TRUE /*immediate*/);
}
return NOERROR;
}
ECode DreamController::StopDreamRunnable::Run()
{
mDCHost->mListener->OnDreamStopped(mOldDream->mToken);
return NOERROR;
}
ECode DreamController::StopUnconnectedDreamRunnable::Run()
{
if (mDCHost->mCurrentDream != NULL && mDCHost->mCurrentDream->mBound && !mDCHost->mCurrentDream->mConnected) {
Slogger::W(TAG, "Bound dream did not connect in the time allotted");
mDCHost->StopDream(TRUE /*immediate*/);
}
return NOERROR;
}
ECode DreamController::StopStubbornDreamRunnable::Run()
{
Slogger::W(TAG, "Stubborn dream did not finish itself in the time allotted");
mDCHost->StopDream(TRUE /*immediate*/);
return NOERROR;
}
CAR_INTERFACE_IMPL(DreamController::DreamRecord, Object, IServiceConnection)
DreamController::DreamRecord::DreamRecord(
/* [in] */ IBinder* token,
/* [in] */ IComponentName* name,
/* [in] */ Boolean isTest,
/* [in] */ Boolean canDoze,
/* [in] */ Int32 userId,
/* [in] */ DreamController* host)
: mToken(token)
, mName(name)
, mIsTest(isTest)
, mCanDoze(canDoze)
, mUserId(userId)
, mWakingGently(FALSE)
, mHost(host)
{}
ECode DreamController::DreamRecord::ProxyDied()
{
AutoPtr<ProxyDiedRunnable> runnable = new ProxyDiedRunnable(this);
Boolean result;
mHost->mHandler->Post(runnable, &result);
return NOERROR;
}
ECode DreamController::DreamRecord::OnServiceConnected(
/* [in] */ IComponentName* name,
/* [in] */ IBinder* service)
{
AutoPtr<ConnectedRunnable> runnable = new ConnectedRunnable(this, service);
Boolean result;
mHost->mHandler->Post(runnable, &result);
return NOERROR;
}
ECode DreamController::DreamRecord::OnServiceDisconnected(
/* [in] */ IComponentName* name)
{
AutoPtr<DisconnectedRunnable> runnable = new DisconnectedRunnable(this);
Boolean result;
mHost->mHandler->Post(runnable, &result);
return NOERROR;
}
DreamController::DreamController(
/* [in] */ IContext* context,
/* [in] */ IHandler* handler,
/* [in] */ Listener* listener)
: mContext(context)
, mHandler(handler)
, mListener(listener)
{
AutoPtr<IWindowManagerGlobalHelper> windowMangerGlobal;
CWindowManagerGlobalHelper::AcquireSingleton((IWindowManagerGlobalHelper**)&windowMangerGlobal);
windowMangerGlobal->GetWindowManagerService((IIWindowManager**)&mIWindowManager);
CIntent::New(IIntent::ACTION_DREAMING_STARTED, (IIntent**)&mDreamingStartedIntent);
mDreamingStartedIntent->AddFlags(IIntent::FLAG_RECEIVER_REGISTERED_ONLY);
CIntent::New(IIntent::ACTION_DREAMING_STOPPED, (IIntent**)&mDreamingStoppedIntent);
mDreamingStoppedIntent->AddFlags(IIntent::FLAG_RECEIVER_REGISTERED_ONLY);
CIntent::New(IIntent::ACTION_CLOSE_SYSTEM_DIALOGS, (IIntent**)&mCloseNotificationShadeIntent);
mStopUnconnectedDreamRunnable = new StopUnconnectedDreamRunnable(this);
mStopStubbornDreamRunnable = new StopStubbornDreamRunnable(this);
}
ECode DreamController::Dump(
/* [in] */ IPrintWriter* pw)
{
pw->Println(String("Dreamland:"));
if (mCurrentDream != NULL) {
pw->Println(String(" mCurrentDream:"));
String tokens;
mCurrentDream->mToken->ToString(&tokens);
pw->Println(String(" mToken=") + tokens);
String names;
mCurrentDream->mName->ToString(&names);
pw->Println(String(" mName=") + names);
StringBuilder sb1(" mIsTest=");
sb1 += mCurrentDream->mIsTest;
pw->Println(sb1.ToString());
StringBuilder sb6(" mCanDoze=");
sb6 += mCurrentDream->mCanDoze;
pw->Println(sb6.ToString());
StringBuilder sb2(" mUserId=");
sb2 += mCurrentDream->mUserId;
pw->Println(sb2.ToString());
StringBuilder sb3(" mBound=");
sb3 += mCurrentDream->mBound;
pw->Println(sb3.ToString());
StringBuilder sb4(" mService=");
sb4 += mCurrentDream->mService;
pw->Println(sb4.ToString());
StringBuilder sb5(" mSentStartBroadcast=");
sb5 += mCurrentDream->mSentStartBroadcast;
pw->Println(sb5.ToString());
StringBuilder sb7(" mWakingGently=");
sb7 += mCurrentDream->mWakingGently;
pw->Println(sb7.ToString());
}
else {
pw->Println(String(" mCurrentDream: NULL"));
}
return NOERROR;
}
ECode DreamController::StartDream(
/* [in] */ IBinder* token,
/* [in] */ IComponentName* name,
/* [in] */ Boolean isTest,
/* [in] */ Boolean canDoze,
/* [in] */ Int32 userId)
{
StopDream(TRUE /*immediate*/);
// Close the notification shade. Don't need to send to all, but better to be explicit.
mContext->SendBroadcastAsUser(mCloseNotificationShadeIntent, UserHandle::ALL);
Slogger::I(TAG, "Starting dream: name=%p, isTest=%d, canDoze=%d, userId=%d",
name, isTest, canDoze, userId);
mCurrentDream = new DreamRecord(token, name, isTest, canDoze, userId, this);
// try {
if (FAILED(mIWindowManager->AddWindowToken(token, IWindowManagerLayoutParams::TYPE_DREAM))) {
// } catch (RemoteException ex) {
// Slog.e(TAG, "Unable to add window token for dream.", ex);
Slogger::E(TAG, "Unable to add window token for dream.");
StopDream(TRUE /*immediate*/);
return NOERROR;
}
AutoPtr<IIntent> intent;
CIntent::New(IDreamService::SERVICE_INTERFACE,(IIntent**)&intent);
intent->SetComponent(name);
intent->AddFlags(IIntent::FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// try {
AutoPtr<IUserHandle> uh;
CUserHandle::New(userId, (IUserHandle**)&uh);
Boolean result;
ECode ec = mContext->BindServiceAsUser(intent, mCurrentDream,
IContext::BIND_AUTO_CREATE, uh, &result);
if (!result || (ec == (ECode)E_SECURITY_EXCEPTION)) {
Slogger::E(TAG, "Unable to bind dream service: %s", TO_CSTR(intent));
StopDream(TRUE /*immediate*/);
return NOERROR;
}
mCurrentDream->mBound = TRUE;
mHandler->PostDelayed(mStopUnconnectedDreamRunnable, DREAM_CONNECTION_TIMEOUT, &result);
return NOERROR;
}
ECode DreamController::StopDream(
/* [in] */ Boolean immediate)
{
if (mCurrentDream == NULL) {
return NOERROR;
}
Boolean bval;
if (!immediate) {
if (mCurrentDream->mWakingGently) {
return NOERROR; // already waking gently
}
if (mCurrentDream->mService != NULL) {
// Give the dream a moment to wake up and finish itself gently.
mCurrentDream->mWakingGently = TRUE;
// try {
mCurrentDream->mService->WakeUp();
mHandler->PostDelayed(mStopStubbornDreamRunnable, DREAM_FINISH_TIMEOUT, &bval);
return NOERROR;
// } catch (RemoteException ex) {
// // oh well, we tried, finish immediately instead
// }
}
}
AutoPtr<DreamRecord> oldDream = mCurrentDream;
mCurrentDream = NULL;
Slogger::I(TAG, "Stopping dream: name=%p, isTest=%d, canDoze=%d, userId=%d",
oldDream->mName.Get(), oldDream->mIsTest, oldDream->mCanDoze, oldDream->mUserId);
mHandler->RemoveCallbacks(mStopUnconnectedDreamRunnable);
mHandler->RemoveCallbacks(mStopStubbornDreamRunnable);
if (oldDream->mSentStartBroadcast) {
mContext->SendBroadcastAsUser(mDreamingStoppedIntent, UserHandle::ALL);
}
if (oldDream->mService != NULL) {
// Tell the dream that it's being stopped so that
// it can shut down nicely before we yank its window token out from
// under it.
// try {
oldDream->mService->Detach();
// } catch (RemoteException ex) {
// we don't care; this thing is on the way out
// }
// try {
AutoPtr<IProxy> proxy = (IProxy*)oldDream->mService->Probe(EIID_IProxy);
Boolean result;
proxy->UnlinkToDeath(oldDream, 0, &result);
// } catch (NoSuchElementException ex) {
// don't care
// }
oldDream->mService = NULL;
}
if (oldDream->mBound) {
mContext->UnbindService(oldDream);
}
// try {
ECode ec = mIWindowManager->RemoveWindowToken(oldDream->mToken);
if (ec == (ECode)E_REMOTE_EXCEPTION) {
Slogger::W(TAG, "Error removing window token for dream.");
}
AutoPtr<StopDreamRunnable> runnable = new StopDreamRunnable(this, oldDream);
mHandler->Post(runnable, &bval);
return NOERROR;
}
void DreamController::Attach(
/* [in] */ IIDreamService* service)
{
// try {
AutoPtr<IProxy> proxy = (IProxy*)service->Probe(EIID_IProxy);
proxy->LinkToDeath(mCurrentDream, 0);
ECode ec = service->Attach(mCurrentDream->mToken, mCurrentDream->mCanDoze);
if (ec == (ECode)E_REMOTE_EXCEPTION) {
// } catch (RemoteException ex) {
// Slog.e(TAG, "The dream service died unexpectedly.", ex);
StopDream(TRUE /*immediate*/);
return;
}
mCurrentDream->mService = service;
if (!mCurrentDream->mIsTest) {
mContext->SendBroadcastAsUser(mDreamingStartedIntent, UserHandle::ALL);
mCurrentDream->mSentStartBroadcast = TRUE;
}
}
} // namespace Dreams
} // namespace Server
} // namespace Droid
} // namespace Elastos
| 33.777465 | 114 | 0.66208 | jingcao80 |
a2f8fca6aefc8ba5862a9455ca40796998630a7a | 7,183 | cpp | C++ | tools/Vitis-AI-Runtime/VART/target_factory/src/target_factory.cpp | Carles-Figuerola/Vitis-AI | fc043ea4aca1f9fe4e18962e6a6ae397812bb34b | [
"Apache-2.0"
] | 1 | 2020-12-18T14:49:19.000Z | 2020-12-18T14:49:19.000Z | tools/Vitis-AI-Runtime/VART/target_factory/src/target_factory.cpp | cy333/Vitis-AI | 611b82cfc32ea2fe04491432bf8feed1f378c9de | [
"Apache-2.0"
] | null | null | null | tools/Vitis-AI-Runtime/VART/target_factory/src/target_factory.cpp | cy333/Vitis-AI | 611b82cfc32ea2fe04491432bf8feed1f378c9de | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2019 Xilinx Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "vitis/ai/target_factory.hpp"
#include <fcntl.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include <UniLog/UniLog.hpp>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include "config.hpp"
#include "target_list.hpp"
namespace vitis {
namespace ai {
static uint64_t type2int(const std::string& type) {
uint32_t ret = 0U;
if (type == "DPUCZDX8G")
ret = 1U;
else if (type == "DPUCAHX8H")
ret = 2U;
else if (type == "DPUCAHX8L")
ret = 3U;
else if (type == "DPUCZDI4G")
ret = 4U;
else if (type == "DPUCVDX8H")
ret = 5U;
else if (type == "DPUCVDX8G")
ret = 6U;
else
UNI_LOG_FATAL(TARGET_FACTORY_INVALID_TYPE) << type;
return ret;
}
static std::string int2type(uint64_t type) {
std::string ret = "";
if (type == 1U)
ret = "DPUCZDX8G";
else if (type == 2U)
ret = "DPUCAHX8H";
else if (type == 3U)
ret = "DPUCAHX8L";
else if (type == 4U)
ret = "DPUCZDI4G";
else if (type == 5U)
ret = "DPUCVDX8H";
else if (type == 6U)
ret = "DPUCVDX8G";
else
UNI_LOG_FATAL(TARGET_FACTORY_INVALID_TYPE) << type;
return ret;
}
std::string to_string(const std::map<std::string, std::uint64_t>& value) {
std::ostringstream str;
int c = 0;
str << "{";
for (auto& x : value) {
if (c++ != 0) {
str << ",";
}
str << x.first << "=>" << std::hex << "0x" << x.second << std::dec;
}
str << "}";
return str.str();
};
const Target create_target_v2(const std::uint64_t fingerprint);
class TargetFactoryImp : public TargetFactory {
public:
const Target create(const std::string& name) const override {
return this->create(this->get_fingerprint(name));
}
const Target create(const std::string& type, std::uint64_t isa_version,
std::uint64_t feature_code) const override {
return this->create(this->get_fingerprint(type, isa_version, feature_code));
}
const Target create(const std::uint64_t fingerprint) const override {
if (map_fingerprint_target_.count(fingerprint) != 0) {
return map_fingerprint_target_.at(fingerprint);
} else {
auto type = int2type(fingerprint >> 56);
if (type == "DPUCZDX8G") {
return create_target_v2(fingerprint);
} else {
UNI_LOG_FATAL(TARGET_FACTORY_UNREGISTERED_TARGET)
<< "Cannot find or create target with fingerprint=0x" << std::hex
<< std::setfill('0') << std::setw(16) << fingerprint;
}
}
}
const std::uint64_t get_fingerprint(const std::string& name) const override {
UNI_LOG_CHECK(map_name_fingerprint_.count(name) != 0,
TARGET_FACTORY_UNREGISTERED_TARGET)
<< "Cannot find target with name " << name
<< ", valid names are: " << to_string(map_name_fingerprint_);
return map_name_fingerprint_.at(name);
}
const std::uint64_t get_fingerprint(
const std::string& type, std::uint64_t isa_version,
std::uint64_t feature_code) const override {
uint64_t fingureprint = 0U;
UNI_LOG_CHECK((feature_code & 0xffff000000000000) == 0,
TARGET_FACTORY_INVALID_ISA_VERSION)
<< "0x" << std::hex << setfill('0') << setw(16) << feature_code;
UNI_LOG_CHECK((isa_version & 0xffffffffffffff00) == 0,
TARGET_FACTORY_INVALID_FEATURE_CODE)
<< "0x" << std::hex << setfill('0') << setw(16) << isa_version;
fingureprint |= feature_code;
fingureprint |= isa_version << 48;
fingureprint |= type2int(type) << 56;
return fingureprint;
}
void dump(const Target& target, const std::string& file) const override {
auto fd = open(file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 00644);
google::protobuf::io::FileOutputStream fstream(fd);
google::protobuf::TextFormat::Print(target, &fstream);
}
public:
void register_h(const Target& target) {
auto name = target.name();
auto fingerprint = this->get_fingerprint(
target.type(), target.isa_version(), target.feature_code());
UNI_LOG_CHECK(map_fingerprint_target_.count(fingerprint) == 0,
TARGET_FACTORY_MULTI_REGISTERED_TARGET)
<< "fingerprint=0x" << std::hex << std::setw(16) << std::setfill('0')
<< fingerprint;
UNI_LOG_CHECK(map_name_fingerprint_.count(name) == 0,
TARGET_FACTORY_MULTI_REGISTERED_TARGET)
<< "name=" << name;
map_fingerprint_target_.emplace(fingerprint, target);
map_name_fingerprint_.emplace(name, fingerprint);
}
public:
TargetFactoryImp() = default;
TargetFactoryImp(const TargetFactoryImp&) = delete;
TargetFactoryImp& operator=(const TargetFactoryImp&) = delete;
private:
std::map<std::uint64_t, const Target> map_fingerprint_target_;
std::map<std::string, std::uint64_t> map_name_fingerprint_;
};
static std::unique_ptr<std::vector<std::string>> get_target_prototxt_list() {
auto ret = std::make_unique<std::vector<std::string>>();
auto target_prototxts = std::string{TARGET_PROTOTXTS};
std::string::size_type pos_begin = 0, pos_end = 0;
while ((pos_begin = target_prototxts.find("#begin", pos_begin)) !=
std::string::npos &&
(pos_end = target_prototxts.find("#end", pos_begin)) !=
std::string::npos) {
ret->emplace_back(
target_prototxts.substr(pos_begin + 6, pos_end - pos_begin - 6));
++pos_begin;
}
return ret;
}
static void register_targets(TargetFactoryImp* factory) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
auto target_prototxt_list = get_target_prototxt_list();
for (auto& target_prototxt : *target_prototxt_list) {
Target target;
UNI_LOG_CHECK(
google::protobuf::TextFormat::ParseFromString(target_prototxt, &target),
TARGET_FACTORY_PARSE_TARGET_FAIL)
<< "Cannot parse prototxt: \n"
<< target_prototxt;
UNI_LOG_CHECK(target.name() != "" && target.type() != "",
TARGET_FACTORY_PARSE_TARGET_FAIL)
<< "Uninitialized name or type";
factory->register_h(target);
}
}
const TargetFactory* target_factory() {
static std::once_flag register_once_flag;
static TargetFactoryImp self;
std::call_once(register_once_flag, register_targets, &self);
return &self;
}
const std::string TargetFactory::get_lib_name() {
const auto ret =
std::string{PROJECT_NAME} + "." + std::string{PROJECT_VERSION};
return ret;
}
const std::string TargetFactory::get_lib_id() {
const auto ret = std::string{PROJECT_GIT_COMMIT_ID};
return ret;
}
} // namespace ai
} // namespace vitis
| 31.783186 | 80 | 0.668941 | Carles-Figuerola |
0c029c40830e8334546c12956a738db707fc4389 | 604 | cpp | C++ | testsuite/foreach.cpp | mr-j0nes/RaftLib | 19b2b5401365ba13788044bfbcca0820f48b650a | [
"Apache-2.0"
] | 759 | 2016-05-23T22:40:00.000Z | 2022-03-25T09:05:41.000Z | testsuite/foreach.cpp | Myicefrog/RaftLib | 5ff105293bc851ed73bdfd8966b15d0cadb45eb0 | [
"Apache-2.0"
] | 111 | 2016-05-24T02:30:14.000Z | 2021-08-16T15:11:53.000Z | testsuite/foreach.cpp | Myicefrog/RaftLib | 5ff105293bc851ed73bdfd8966b15d0cadb45eb0 | [
"Apache-2.0"
] | 116 | 2016-05-31T08:03:05.000Z | 2022-03-01T00:54:31.000Z | #include <cassert>
#include <iostream>
#include <cstdint>
#include <cstdlib>
#include <vector>
#include <iterator>
#include <raft>
#include <raftio>
int
main()
{
const auto arr_size( 1000 );
using type_t = std::int32_t;
type_t *arr = (type_t*) malloc( sizeof( type_t ) * arr_size );
for( type_t i( 0 ); i < arr_size; i++ )
{
arr[ i ] = i;
}
using print = raft::print< type_t, '\n' >;
using foreach = raft::for_each< type_t >;
print p;
foreach fe( arr, arr_size, 1 );
raft::map m;
m += fe >> p;
m.exe();
free( arr );
return( EXIT_SUCCESS );
}
| 19.483871 | 65 | 0.577815 | mr-j0nes |
0c0be1417faa6d5fce8942a0e43d9fa420df59f7 | 198 | cpp | C++ | chap01_flow_control/practice03/02.cpp | kdzlvaids/problem_solving-pknu-2016 | 6a9e64f31f0d17c949e2b640fbd0a7628d1e5ece | [
"MIT"
] | null | null | null | chap01_flow_control/practice03/02.cpp | kdzlvaids/problem_solving-pknu-2016 | 6a9e64f31f0d17c949e2b640fbd0a7628d1e5ece | [
"MIT"
] | null | null | null | chap01_flow_control/practice03/02.cpp | kdzlvaids/problem_solving-pknu-2016 | 6a9e64f31f0d17c949e2b640fbd0a7628d1e5ece | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <math.h>
int main(void)
{
int num;
printf("Enter num= ");
scanf("%d", &num);
printf("Result: %d\n", (int)sqrt(num) * (int)sqrt(num));
return 0;
}
| 13.2 | 60 | 0.535354 | kdzlvaids |
0c0e468c4416d7fc046da64ef1c17fdf5c687d58 | 349 | cpp | C++ | src/CCommandDest.cpp | colinw7/CCommand | 36745e2eea76e6569f8f810046c5c8e2f5030947 | [
"MIT"
] | 1 | 2021-12-23T02:21:06.000Z | 2021-12-23T02:21:06.000Z | src/CCommandDest.cpp | colinw7/CCommand | 36745e2eea76e6569f8f810046c5c8e2f5030947 | [
"MIT"
] | null | null | null | src/CCommandDest.cpp | colinw7/CCommand | 36745e2eea76e6569f8f810046c5c8e2f5030947 | [
"MIT"
] | null | null | null | #include <CCommandDest.h>
#include <CCommand.h>
CCommandDest::
CCommandDest(CCommand *command) :
command_(command)
{
}
CCommandDest::
CCommandDest(CCommand *command, FILE *fp) :
command_(command)
{
fd_ = fileno(fp);
}
CCommandDest::
~CCommandDest()
{
}
void
CCommandDest::
throwError(const std::string &msg)
{
command_->throwError(msg);
}
| 12.464286 | 43 | 0.713467 | colinw7 |
0c0f57ed3a90897a3ab1010f4959333b6233ef25 | 9,766 | cpp | C++ | source/housys/test/hou/sys/test_file.cpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | 2 | 2018-04-12T20:59:20.000Z | 2018-07-26T16:04:07.000Z | source/housys/test/hou/sys/test_file.cpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | source/housys/test/hou/sys/test_file.cpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | // Houzi Game Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
#include "hou/test.hpp"
#include "hou/sys/test_data.hpp"
#include "hou/sys/file.hpp"
#include "hou/sys/sys_exceptions.hpp"
using namespace hou;
using namespace testing;
namespace
{
class test_file : public Test
{
public:
static const std::string filename;
static const std::string file_content;
public:
test_file();
virtual ~test_file();
};
using test_file_death_test = test_file;
template <typename Container>
bool testFileContents(
const std::string& filename, const Container& expected, file_type type);
const std::string test_file::filename
= get_output_dir() + u8"test_file-\U00004f60\U0000597d-BinaryFile.txt";
const std::string test_file::file_content = u8"This is\na test file";
test_file::test_file()
{
file f(filename, file_open_mode::write, file_type::binary);
f.write(file_content);
}
test_file::~test_file()
{
remove_dir(filename);
}
template <typename Container>
bool testFileContents(
const std::string& filename, const Container& expected, file_type type)
{
file f(filename, file_open_mode::read, type);
Container buffer(f.get_byte_count(), 0);
f.read(buffer);
return expected == buffer;
}
} // namespace
TEST_F(test_file, creation)
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_FALSE(f.eof());
EXPECT_FALSE(f.error());
EXPECT_TRUE(f.is_open());
EXPECT_EQ(file_content.size(), f.get_byte_count());
EXPECT_EQ(0, f.tell());
std::string content(f.get_byte_count(), 0);
f.read(content);
EXPECT_EQ(file_content, content);
}
TEST_F(test_file_death_test, creation_error)
{
std::string fake_name = "NotAValidName.txt";
EXPECT_ERROR_N(file f(fake_name, file_open_mode::read, file_type::binary),
file_open_error, fake_name);
}
TEST_F(test_file, move_constructor)
{
file f_dummy(filename, file_open_mode::read, file_type::binary);
file f(std::move(f_dummy));
EXPECT_FALSE(f.eof());
EXPECT_FALSE(f.error());
EXPECT_TRUE(f.is_open());
EXPECT_FALSE(f_dummy.is_open());
EXPECT_EQ(file_content.size(), f.get_byte_count());
EXPECT_EQ(0, f.tell());
std::string content(f.get_byte_count(), 0);
f.read(content);
EXPECT_EQ(file_content, content);
}
TEST_F(test_file, close)
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_TRUE(f.is_open());
f.close();
EXPECT_FALSE(f.is_open());
}
TEST_F(test_file, cursor_positioning)
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_EQ(0, f.tell());
f.seek_set(5);
EXPECT_EQ(5, f.tell());
f.seek_offset(2);
EXPECT_EQ(7, f.tell());
f.seek_offset(-3);
EXPECT_EQ(4, f.tell());
}
TEST_F(test_file_death_test, cursor_positioning_error)
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_ERROR_0(f.seek_set(-1), cursor_error);
EXPECT_ERROR_0(f.seek_offset(-2), cursor_error);
// error flag is not set, only for read / write errors!
EXPECT_FALSE(f.error());
}
TEST_F(test_file, file_size)
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_EQ(19u, f.get_byte_count());
}
TEST_F(test_file, file_size_cursor_position)
{
// Test if the size is correct if the cursor is not at the beginning, and if
// requesting the file size does not change the cursor position.
file f(filename, file_open_mode::read, file_type::binary);
char c;
f.getc(c);
f.getc(c);
long cur_pos = f.tell();
size_t file_size = f.get_byte_count();
EXPECT_EQ(cur_pos, f.tell());
EXPECT_EQ(19u, file_size);
}
TEST_F(test_file, getc_binary)
{
file f(filename, file_open_mode::read, file_type::binary);
char c = 0;
size_t i = 0;
while(f.getc(c))
{
EXPECT_EQ(file_content[i], c);
++i;
}
EXPECT_TRUE(f.eof());
}
TEST_F(test_file, putc_binary)
{
std::string to_write = u8"I have\nwritten this";
{
file f(filename, file_open_mode::write, file_type::binary);
for(size_t i = 0; i < to_write.size(); ++i)
{
f.putc(to_write[i]);
}
}
EXPECT_TRUE(testFileContents(filename, to_write, file_type::binary));
}
TEST_F(test_file, gets_binary)
{
file f(filename, file_open_mode::read, file_type::binary);
// Since a \0 is added, an extra character is needed
std::string s(4u, 'a');
// Gets stop reading at new lines, so we must be careful with that when
// performing the comparisons inside the test.
size_t cursor = 0;
while(size_t count = f.gets(s))
{
EXPECT_EQ(file_content.substr(cursor, count), s.substr(0u, count));
cursor += count;
}
EXPECT_TRUE(f.eof());
}
TEST_F(test_file, puts_binary)
{
std::string to_write = u8"I have\nwritten this";
{
file f(filename, file_open_mode::write, file_type::binary);
f.puts(to_write);
}
EXPECT_TRUE(testFileContents(filename, to_write, file_type::binary));
}
TEST_F(test_file, read_buffer_binary)
{
file f(filename, file_open_mode::read, file_type::binary);
std::vector<char> buf(3u, 0);
size_t i = 0;
while(f.read(buf.data(), buf.size()) == buf.size())
{
EXPECT_ARRAY_EQ(file_content.substr(i * buf.size(), buf.size()).data(),
buf.data(), buf.size());
++i;
}
EXPECT_TRUE(f.eof());
}
TEST_F(test_file, write_buffer_binary)
{
std::vector<char> to_write{23, 12, 15, 0, 14, 1};
{
file f(filename, file_open_mode::write, file_type::binary);
f.write(to_write.data(), to_write.size());
}
EXPECT_TRUE(testFileContents(filename, to_write, file_type::binary));
}
TEST_F(test_file, read_string_binary)
{
file f(filename, file_open_mode::read, file_type::binary);
std::string buf(3u, 0);
size_t i = 0;
while(f.read(buf) == buf.size())
{
EXPECT_ARRAY_EQ(file_content.substr(i * buf.size(), buf.size()).data(),
buf.data(), buf.size());
++i;
}
EXPECT_TRUE(f.eof());
}
TEST_F(test_file, write_string_binary)
{
std::string to_write = u8"I have\nwritten this";
{
file f(filename, file_open_mode::write, file_type::binary);
f.write(to_write);
}
EXPECT_TRUE(testFileContents(filename, to_write, file_type::binary));
}
TEST_F(test_file, read_container_binary)
{
file f(filename, file_open_mode::read, file_type::binary);
std::vector<char> buf(3u, 0);
size_t i = 0;
while(f.read(buf) == buf.size())
{
EXPECT_ARRAY_EQ(file_content.substr(i * buf.size(), buf.size()).data(),
buf.data(), buf.size());
++i;
}
EXPECT_TRUE(f.eof());
}
TEST_F(test_file, write_container_binary)
{
std::vector<char> to_write{23, 12, 15, 0, 14, 1};
{
file f(filename, file_open_mode::write, file_type::binary);
f.write(to_write);
}
EXPECT_TRUE(testFileContents(filename, to_write, file_type::binary));
}
TEST_F(test_file, append_binary)
{
std::string to_write = u8"I have\nwritten this";
{
file f(filename, file_open_mode::append, file_type::binary);
f.write(to_write);
}
EXPECT_TRUE(
testFileContents(filename, file_content + to_write, file_type::binary));
}
TEST_F(test_file_death_test, read_from_write_only_file)
{
file f(filename, file_open_mode::write, file_type::binary);
char c;
EXPECT_ERROR_0(f.getc(c), read_error);
std::string buffer(3u, 0);
EXPECT_ERROR_0(f.read(buffer), read_error);
#if defined(HOU_USE_EXCEPTIONS)
// With no exceptions handling, the DEPRECATED_HOU_EXPECT_ERROR macro does
// some magic, so that in the end the error flag is not set for f.
EXPECT_TRUE(f.error());
#endif
}
TEST_F(test_file_death_test, write_to_read_only_file)
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_ERROR_0(f.putc('a'), write_error);
std::string to_write = u8"I have\nwritten this";
EXPECT_ERROR_0(f.write(to_write), write_error);
#ifndef HOU_DISABLE_EXCEPTIONS
// With no exceptions handling, the DEPRECATED_HOU_EXPECT_ERROR macro does
// some magic, so that in the end the error flag is not set for f.
EXPECT_TRUE(f.error());
#endif
}
TEST_F(test_file, eof)
{
file f(filename, file_open_mode::read, file_type::binary);
char c = 0;
while(f.getc(c))
{
}
EXPECT_TRUE(f.eof());
}
TEST_F(test_file, get_size_after_putc)
{
// Note: on some filesystems the size is not immediately updated.
// For this reason it is necessary to open the file again to check the size.
{
file f(filename, file_open_mode::append, file_type::binary);
EXPECT_EQ(file_content.size(), f.get_byte_count());
f.putc('a');
}
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_EQ(file_content.size() + 1u, f.get_byte_count());
}
}
TEST_F(test_file, get_size_after_puts)
{
// Note: on some filesystems the size is not immediately updated.
// For this reason it is necessary to open the file again to check the size.
std::string to_write = u8"New stuff!";
{
file f(filename, file_open_mode::append, file_type::binary);
EXPECT_EQ(file_content.size(), f.get_byte_count());
f.puts(to_write);
}
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_EQ(file_content.size() + to_write.size(), f.get_byte_count());
}
}
TEST_F(test_file, get_size_after_write)
{
// Note: on some filesystems the size is not immediately updated.
// For this reason it is necessary to open the file again to check the size.
std::vector<uint16_t> to_write{23, 12, 15, 0, 14, 1};
{
file f(filename, file_open_mode::append, file_type::binary);
EXPECT_EQ(file_content.size(), f.get_byte_count());
f.write(to_write);
}
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_EQ(file_content.size() + to_write.size() * sizeof(uint16_t),
f.get_byte_count());
}
}
// Test flush.
// Test flush error.
// Test close error.
// Test tell error.
// Tests for text files.
| 21.654102 | 78 | 0.693017 | DavideCorradiDev |
0c137e475906bda531b9c20539a798caea1e9b61 | 8,503 | cpp | C++ | src/cui-1.0.4/FORIS/FORIS.cpp | MaiReo/crass | 11579527090faecab27f98b1e221172822928f57 | [
"BSD-3-Clause"
] | 1 | 2021-07-21T00:58:45.000Z | 2021-07-21T00:58:45.000Z | src/cui-1.0.4/FORIS/FORIS.cpp | MaiReo/crass | 11579527090faecab27f98b1e221172822928f57 | [
"BSD-3-Clause"
] | null | null | null | src/cui-1.0.4/FORIS/FORIS.cpp | MaiReo/crass | 11579527090faecab27f98b1e221172822928f57 | [
"BSD-3-Clause"
] | null | null | null | #include <windows.h>
#include <tchar.h>
#include <crass_types.h>
#include <acui.h>
#include <cui.h>
#include <package.h>
#include <resource.h>
#include <cui_error.h>
#include <stdio.h>
#include <zlib.h>
#include <utility.h>
/* 接口数据结构: 表示cui插件的一般信息 */
struct acui_information FORIS_cui_information = {
_T("STACK"), /* copyright */
_T(""), /* system */
_T(".GPK .GPK.*"), /* package */
_T("1.0.2"), /* revision */
_T("痴漢公賊"), /* author */
_T("2009-7-21 10:16"), /* date */
NULL, /* notion */
ACUI_ATTRIBUTE_LEVEL_STABLE
};
/* 所有的封包特定的数据结构都要放在这个#pragma段里 */
#pragma pack (1)
typedef struct {
s8 sig0[12];
u32 pidx_length;
s8 sig1[16];
} GPK_sig_t;
// gpk pidx format:
typedef struct {
unsigned short unilen; // unicode string length
unsigned short *unistring; // unicode string exclude NULL
unsigned short sub_version; // same as script.gpk.* suffix
unsigned short version; // major version(always 1)
unsigned short zero; // always 0
unsigned int offset; // pidx data file offset
unsigned int comprlen; // compressed pidx data length
unsigned char dflt[4]; // magic "DFLT" or " "
unsigned int uncomprlen; // raw pidx data length(if magic isn't DFLT, then this filed always zero)
unsigned char comprheadlen; // pidx data header length
unsigned char *comprheaddata; // pidx data
} GPK_pidx_t;
#pragma pack ()
/* .dat封包的索引项结构 */
typedef struct {
s8 name[256];
u32 name_length;
u32 offset;
u32 length;
} dat_entry_t;
static int no_exe_parameter = 1;
static u8 ciphercode[16];
static void GPK_decode(BYTE *buffer, DWORD buffer_len)
{
unsigned int i = 0, k = 0;
while (i < buffer_len) {
buffer[i++] ^= ciphercode[k++];
if (k >= 16)
k = 0;
}
}
/********************* GPK *********************/
/* 封包匹配回调函数 */
static int FORIS_GPK_match(struct package *pkg)
{
if (no_exe_parameter)
return -CUI_EMATCH;
if (pkg->pio->open(pkg, IO_READONLY))
return -CUI_EOPEN;
u32 offset;
pkg->pio->length_of(pkg, &offset);
offset -= sizeof(GPK_sig_t);
if (pkg->pio->seek(pkg, offset, IO_SEEK_SET)) {
pkg->pio->close(pkg);
return -CUI_ESEEK;
}
GPK_sig_t GPK_sig;
if (pkg->pio->read(pkg, &GPK_sig, sizeof(GPK_sig))) {
pkg->pio->close(pkg);
return -CUI_EREAD;
}
#define GPK_TAILER_IDENT0 "STKFile0PIDX"
#define GPK_TAILER_IDENT1 "STKFile0PACKFILE"
if (strncmp(GPK_TAILER_IDENT0, GPK_sig.sig0, strlen(GPK_TAILER_IDENT0))
|| strncmp(GPK_TAILER_IDENT1, GPK_sig.sig1, strlen(GPK_TAILER_IDENT1))) {
pkg->pio->close(pkg);
return -CUI_EMATCH;
}
return 0;
}
/* 封包索引目录提取函数 */
static int FORIS_GPK_extract_directory(struct package *pkg,
struct package_directory *pkg_dir)
{
u32 offset;
pkg->pio->length_of(pkg, &offset);
offset -= sizeof(GPK_sig_t);
GPK_sig_t GPK_sig;
if (pkg->pio->readvec(pkg, &GPK_sig, sizeof(GPK_sig), offset, IO_SEEK_SET))
return -CUI_EREADVEC;
u32 comprlen = GPK_sig.pidx_length;
offset -= comprlen; /* point to pidx segment */
if (pkg->pio->seek(pkg, offset, IO_SEEK_SET))
return -CUI_ESEEK;
BYTE *compr = new BYTE[comprlen];
if (!compr)
return -CUI_EMEM;
if (pkg->pio->read(pkg, compr, comprlen)) {
delete [] compr;
return -CUI_EREAD;
}
GPK_decode(compr, comprlen);
u32 uncomprlen = *(u32 *)compr;
comprlen -= 4;
BYTE *uncompr = new BYTE[uncomprlen];
if (!uncompr) {
delete [] compr;
return -CUI_EMEM;
}
DWORD act_uncomprlen = uncomprlen;
if (uncompress(uncompr, &act_uncomprlen, compr + 4, comprlen) != Z_OK) {
delete [] uncompr;
delete [] compr;
return -CUI_EUNCOMPR;
}
delete [] compr;
BYTE *p = uncompr;
pkg_dir->index_entries = 0;
while (1) {
u16 nlen = *(u16 *)p;
if (!nlen)
break;
p += 2 + nlen * 2 + 22;
p += *p + 1;
pkg_dir->index_entries++;
}
pkg_dir->directory = uncompr;
pkg_dir->directory_length = act_uncomprlen;
pkg_dir->flags = PKG_DIR_FLAG_VARLEN;
return 0;
}
/* 封包索引项解析函数 */
static int FORIS_GPK_parse_resource_info(struct package *pkg,
struct package_resource *pkg_res)
{
BYTE *entry = (BYTE *)pkg_res->actual_index_entry;
pkg_res->name_length = *(u16 *)entry;
entry += 2;
wcsncpy((WCHAR *)pkg_res->name, (WCHAR *)entry, pkg_res->name_length);
entry += pkg_res->name_length * 2 + 6;
pkg_res->offset = *(u32 *)entry;
entry += 4;
pkg_res->raw_data_length = *(u32 *)entry;
entry += 4;
/* magic "DFLT" or " ",
* if magic isn't DFLT, this filed always zero
*/
entry += 4;
pkg_res->actual_data_length = *(u32 *)entry;
entry += 4;
BYTE compr_head_len = *entry;
pkg_res->actual_index_entry_length = 2 + pkg_res->name_length * 2
+ 22 + compr_head_len + 1;
pkg_res->flags = PKG_RES_FLAG_UNICODE;
return 0;
}
/* 封包资源提取函数 */
static int FORIS_GPK_extract_resource(struct package *pkg,
struct package_resource *pkg_res)
{
BYTE *entry = (BYTE *)pkg_res->actual_index_entry
+ 2 + pkg_res->name_length * 2 + 22;
BYTE compr_head_len = *entry++;
DWORD comprlen = compr_head_len + pkg_res->raw_data_length;
BYTE *compr = new BYTE[comprlen];
if (!compr)
return -CUI_EMEM;
memcpy(compr, entry, compr_head_len);
if (pkg->pio->readvec(pkg, compr + compr_head_len, pkg_res->raw_data_length,
pkg_res->offset, IO_SEEK_SET)) {
delete [] compr;
return -CUI_EREADVEC;
}
BYTE *uncompr;
if (pkg_res->actual_data_length) {
DWORD uncomprlen = pkg_res->actual_data_length;
uncompr = new BYTE[uncomprlen];
if (!uncompr) {
delete [] compr;
return -CUI_EMEM;
}
if (uncompress(uncompr, &uncomprlen, compr, comprlen) != Z_OK) {
delete [] uncompr;
delete [] compr;
return -CUI_EUNCOMPR;
}
} else
uncompr = NULL;
pkg_res->raw_data = compr;
pkg_res->actual_data = uncompr;
return 0;
}
/* 资源保存函数 */
static int FORIS_GPK_save_resource(struct resource *res,
struct package_resource *pkg_res)
{
if (res->rio->create(res))
return -CUI_ECREATE;
if (pkg_res->actual_data && pkg_res->actual_data_length) {
if (res->rio->write(res, pkg_res->actual_data, pkg_res->actual_data_length)) {
res->rio->close(res);
return -CUI_EWRITE;
}
} else if (pkg_res->raw_data && pkg_res->raw_data_length) {
if (res->rio->write(res, pkg_res->raw_data, pkg_res->raw_data_length)) {
res->rio->close(res);
return -CUI_EWRITE;
}
}
res->rio->close(res);
return 0;
}
/* 封包资源释放函数 */
static void FORIS_GPK_release_resource(struct package *pkg,
struct package_resource *pkg_res)
{
if (pkg_res->actual_data) {
delete [] pkg_res->actual_data;
pkg_res->actual_data = NULL;
}
if (pkg_res->raw_data) {
delete [] pkg_res->raw_data;
pkg_res->raw_data = NULL;
}
}
/* 封包卸载函数 */
static void FORIS_GPK_release(struct package *pkg,
struct package_directory *pkg_dir)
{
if (pkg_dir->directory) {
delete [] pkg_dir->directory;
pkg_dir->directory = NULL;
}
pkg->pio->close(pkg);
}
/* 封包处理回调函数集合 */
static cui_ext_operation FORIS_GPK_operation = {
FORIS_GPK_match, /* match */
FORIS_GPK_extract_directory, /* extract_directory */
FORIS_GPK_parse_resource_info, /* parse_resource_info */
FORIS_GPK_extract_resource, /* extract_resource */
FORIS_GPK_save_resource, /* save_resource */
FORIS_GPK_release_resource, /* release_resource */
FORIS_GPK_release /* release */
};
/* 接口函数: 向cui_core注册支持的封包类型 */
int CALLBACK FORIS_register_cui(struct cui_register_callback *callback)
{
if (callback->add_extension(callback->cui, _T(".GPK"), NULL,
NULL, &FORIS_GPK_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR))
return -1;
if (callback->add_extension(callback->cui, _T(".GPK.*"), NULL,
NULL, &FORIS_GPK_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR))
return -1;
const char *exe_file = get_options("exe");
no_exe_parameter = 1;
if (exe_file) {
HMODULE exe = LoadLibraryA(exe_file);
if ((DWORD)exe > 31) {
HRSRC code = FindResourceA(exe, "CIPHERCODE", "CODE");
if (code) {
DWORD sz = SizeofResource(exe, code);
if (sz == 16) {
HGLOBAL hsrc = LoadResource(exe, code);
if (hsrc) {
LPVOID cipher = LockResource(hsrc);
if (cipher) {
memcpy(ciphercode, cipher, 16);
no_exe_parameter = 0;
}
FreeResource(hsrc);
}
} else if (sz == 20) { // SchoolDays
HGLOBAL hsrc = LoadResource(exe, code);
if (hsrc) {
LPVOID cipher = LockResource(hsrc);
if (cipher && *(u32 *)cipher == 16) {
memcpy(ciphercode, (BYTE *)cipher + 4, 16);
no_exe_parameter = 0;
}
FreeResource(hsrc);
}
}
}
FreeLibrary(exe);
}
}
return 0;
}
}
| 24.363897 | 100 | 0.66553 | MaiReo |
0c15f885683439fab16e2e7e6b720d6384581cee | 680 | cpp | C++ | W1D3/I.cpp | MartrixG/2019-summer-OI | 4765533f4a373f6f277c1309c534050e52d631d8 | [
"MIT"
] | null | null | null | W1D3/I.cpp | MartrixG/2019-summer-OI | 4765533f4a373f6f277c1309c534050e52d631d8 | [
"MIT"
] | null | null | null | W1D3/I.cpp | MartrixG/2019-summer-OI | 4765533f4a373f6f277c1309c534050e52d631d8 | [
"MIT"
] | null | null | null | #include"pch.h"
#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
int a[500010];
int loc[500010];
int num[500010];
vector<int>to[500010];
int tot;
int main()
{
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
loc[a[i]] = i;
}
for (int i = 1; i <= m; i++)
{
int x, y;
scanf("%d%d", &x, &y);
to[y].push_back(x);
}
int ans = 0;
num[loc[a[n]]] = -1;
for (int i = n; i >= 1; i--)
{
if (n - ans - loc[a[i]] == num[loc[a[i]]]) ans++;
else
{
for (int j = 0; j < to[a[i]].size(); j++)
{
num[loc[to[a[i]][j]]]++;
}
}
}
printf("%d\n", ans);
return 0;
} | 15.813953 | 51 | 0.498529 | MartrixG |
0c181b0d37f7d825612d06ef59f38431e0889fac | 77 | cxx | C++ | Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+double.9-.cxx | eile/ITK | 2f09e6e2f9e0a4a7269ac83c597f97b04f915dc1 | [
"Apache-2.0"
] | 4 | 2015-05-22T03:47:43.000Z | 2016-06-16T20:57:21.000Z | Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+double.9-.cxx | GEHC-Surgery/ITK | f5df62749e56c9036e5888cfed904032ba5fdfb7 | [
"Apache-2.0"
] | null | null | null | Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+double.9-.cxx | GEHC-Surgery/ITK | f5df62749e56c9036e5888cfed904032ba5fdfb7 | [
"Apache-2.0"
] | 9 | 2016-06-23T16:03:12.000Z | 2022-03-31T09:25:08.000Z | #include <vnl/vnl_vector_fixed.txx>
VNL_VECTOR_FIXED_INSTANTIATE(double,9);
| 19.25 | 39 | 0.831169 | eile |
0c1a12519fa813eaadd222f93c3a8b005d870d26 | 821 | cc | C++ | gui/components/gui_colorbox.cc | BradenButler/simutrans | 86f29844625119182896e0e08d7b775bc847758d | [
"Artistic-1.0"
] | 292 | 2015-01-04T20:33:57.000Z | 2022-03-21T21:36:25.000Z | gui/components/gui_colorbox.cc | BradenButler/simutrans | 86f29844625119182896e0e08d7b775bc847758d | [
"Artistic-1.0"
] | 32 | 2018-01-31T11:11:16.000Z | 2022-03-03T14:37:58.000Z | gui/components/gui_colorbox.cc | BradenButler/simutrans | 86f29844625119182896e0e08d7b775bc847758d | [
"Artistic-1.0"
] | 126 | 2015-01-05T10:27:14.000Z | 2022-03-05T14:08:50.000Z | /*
* This file is part of the Simutrans project under the Artistic License.
* (see LICENSE.txt)
*/
#include "gui_colorbox.h"
#include "../gui_theme.h"
#include "../../display/simgraph.h"
gui_colorbox_t::gui_colorbox_t(PIXVAL c)
{
color = c;
max_size = scr_size(scr_size::inf.w, D_INDICATOR_HEIGHT);
}
scr_size gui_colorbox_t::get_min_size() const
{
return scr_size(D_INDICATOR_WIDTH, D_INDICATOR_HEIGHT);
}
scr_size gui_colorbox_t::get_max_size() const
{
return scr_size(max_size.w, D_INDICATOR_HEIGHT);
}
void gui_colorbox_t::draw(scr_coord offset)
{
offset += pos;
display_ddd_box_clip_rgb(offset.x, offset.y, size.w, D_INDICATOR_HEIGHT, color_idx_to_rgb(MN_GREY0), color_idx_to_rgb(MN_GREY4));
display_fillbox_wh_clip_rgb(offset.x + 1, offset.y + 1, size.w - 2, D_INDICATOR_HEIGHT-2, color, true);
}
| 23.457143 | 130 | 0.752741 | BradenButler |
0c30ba7788d872e1aa541f6a0b167b4fb51ea633 | 7,272 | cpp | C++ | Overlay/src/Loader.cpp | narindertamber66/https-github.com-acidicoala-ScreamAPI | 4f7e0dfae3be99526dc21b3eed91ae2231f1a209 | [
"0BSD"
] | null | null | null | Overlay/src/Loader.cpp | narindertamber66/https-github.com-acidicoala-ScreamAPI | 4f7e0dfae3be99526dc21b3eed91ae2231f1a209 | [
"0BSD"
] | null | null | null | Overlay/src/Loader.cpp | narindertamber66/https-github.com-acidicoala-ScreamAPI | 4f7e0dfae3be99526dc21b3eed91ae2231f1a209 | [
"0BSD"
] | null | null | null | #include "pch.h"
#include "Loader.h"
#include "Overlay.h"
#include <fstream>
#include <future>
#include <Config.h>
// Instructions on how to build libcurl on Windows can be found here:
// https://www.youtube.com/watch?reload=9&v=q_mXVZ6VJs4
#pragma comment(lib,"Ws2_32.lib")
#pragma comment(lib,"Wldap32.lib")
#pragma comment(lib,"Crypt32.lib")
#pragma comment(lib,"Normaliz.lib")
#define CURL_STATICLIB
#include "curl/curl.h"
#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_PNG
#define STBI_ONLY_JPEG
#include "stb_image.h"
namespace Loader{
#define CACHE_DIR ".ScreamApi_Cache"
/**
* Initialize the loader and its dependencies.
* @return true if initialization was successfull
* false if there was an error in initialization
*/
bool init(){
// Init curl first
#pragma warning(suppress: 26812) // Unscoped enum...
CURLcode errorCode = curl_global_init(CURL_GLOBAL_ALL);
if(errorCode != CURLE_OK){
// Something went wrong
Logger::error("Loader: Failed to initialize curl. Error code: %d", errorCode);
return false;
}
// Create directory if it doesn't already exist
auto success = CreateDirectoryA(CACHE_DIR, NULL); // FIXME: Non-unicode function
if(success || GetLastError() == ERROR_ALREADY_EXISTS){
Logger::ovrly("Loader: Successfully initialized");
return true;
} else{
Logger::error("Loader: Failed to create '%s' directory. Error code: %d", CACHE_DIR, GetLastError());
return false;
}
}
void shutdown(){
curl_global_cleanup();
if(!Config::CacheIcons()){
if(!RemoveDirectoryA(CACHE_DIR))
Logger::error("Failed to remove %s directory. Error code: %d", CACHE_DIR, GetLastError());
}
Logger::ovrly("Loader: Shutdown");
}
// Helper utility to generate icon path based on the AchievementID
std::string getIconPath(Overlay_Achievement& achievement){
return CACHE_DIR"\\" + std::string(achievement.AchievementId) + ".png";
}
// Simple helper function to load an image into a DX11 texture with common settings
void loadIconTexture(Overlay_Achievement& achievement){
static std::mutex loadIconMutex;
{ // Code block for lock_guard destructor to release lock
std::lock_guard<std::mutex> guard(loadIconMutex);
Logger::ovrly("Loading icon texure for achievement: %s", achievement.AchievementId);
auto iconPath = getIconPath(achievement);
// Load from disk into a raw RGBA buffer
int image_width = 0;
int image_height = 0;
auto* image_data = stbi_load(iconPath.c_str(), &image_width, &image_height, NULL, 4);
if(image_data == NULL){
Logger::error("Failed to load icon: %s. Failure reason: %s", iconPath.c_str(), stbi_failure_reason());
return;
}
// Create texture
D3D11_TEXTURE2D_DESC desc;
desc.Width = image_width;
desc.Height = image_height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
ID3D11Texture2D* pTexture = nullptr;
D3D11_SUBRESOURCE_DATA subResource;
subResource.pSysMem = image_data;
subResource.SysMemPitch = static_cast<UINT>(desc.Width * 4);
subResource.SysMemSlicePitch = 0;
// FIXME: This function call somtimes messes up the Railway Empire. No idea why.
auto result = Overlay::gD3D11Device->CreateTexture2D(&desc, &subResource, &pTexture);
if(SUCCEEDED(result)){
// Create texture view
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
memset(&srvDesc, 0, sizeof(srvDesc));
srvDesc.Format = desc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = desc.MipLevels;
result = Overlay::gD3D11Device->CreateShaderResourceView(pTexture, &srvDesc, &achievement.IconTexture);
pTexture->Release();
if(FAILED(result))
Logger::error("Failed to create shader resource view. Error code: %x", result);
} else {
Logger::error("Failed to load the texture. Error code: %x", result);
}
stbi_image_free(image_data);
}
}
// Downloads the online icon into local cache folder
void downloadFile(const char* url, const char* filename){
FILE* file_handle;
CURL* curl_handle = curl_easy_init();
Logger::ovrly("Downloading icon to: %s", filename);
errno_t err = fopen_s(&file_handle, filename, "wb");
if(!err && file_handle != NULL){
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, file_handle);
curl_easy_setopt(curl_handle, CURLOPT_URL, url);
curl_easy_perform(curl_handle);
fclose(file_handle);
} else{
Logger::error("Failed to open file for writing: %s", filename);
}
curl_easy_cleanup(curl_handle);
}
int getLocalFileSize(WIN32_FILE_ATTRIBUTE_DATA& fileInfo){
LARGE_INTEGER size;
size.HighPart = fileInfo.nFileSizeHigh;
size.LowPart = fileInfo.nFileSizeLow;
return (int) size.QuadPart;
}
// Downloads only the file headers and retuns the size of the file
int getOnlineFileSize(const char* url){
CURL* curl_handle = curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_URL, url);
curl_easy_setopt(curl_handle, CURLOPT_HEADER, 1);
curl_easy_setopt(curl_handle, CURLOPT_NOBODY, 1);
curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST, "GET");
curl_easy_perform(curl_handle);
curl_off_t contentLength;
curl_easy_getinfo(curl_handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &contentLength);
curl_easy_cleanup(curl_handle);
return (int) contentLength;
}
void downloadIconIfNecessary(Overlay_Achievement& achievement){
auto iconPath = getIconPath(achievement);
WIN32_FILE_ATTRIBUTE_DATA fileInfo;
auto fileAttributes = GetFileAttributesExA(iconPath.c_str(), GetFileExInfoStandard, &fileInfo);
if(fileAttributes){
if(Config::ValidateIcons()){
// File exists
if(getLocalFileSize(fileInfo) == getOnlineFileSize(achievement.UnlockedIconURL)) {
Logger::ovrly("Using cached icon: %s", iconPath.c_str());
} else{
// Download the file again if the local version is different from online one
downloadFile(achievement.UnlockedIconURL, iconPath.c_str());
}
} else {
Logger::ovrly("Using cached icon: %s", iconPath.c_str());
}
} else if(GetLastError() == ERROR_FILE_NOT_FOUND){
// File doesn't exist
downloadFile(achievement.UnlockedIconURL, iconPath.c_str());
} else{
// File exists, but we could not read it's attributes.
Logger::error("Failed to read file attributes. Error code: %d", GetLastError());
// TODO: Use FormatMessage to print user-friendly error message?
return;
}
loadIconTexture(achievement);
if(!Config::CacheIcons()){
if(!DeleteFileA(iconPath.c_str()))
Logger::error("Failed to remove %s file. Error code: %d", iconPath.c_str(), GetLastError());
}
}
// Asynchronously downloads the icons and loads them into textures in order to keep UI responsive
void AsyncLoadIcons(){
if(Config::LoadIcons() && init()){
static std::vector<std::future<void>>asyncJobs;
for(auto& achievement : *Overlay::achievements){
asyncJobs.emplace_back(std::async(std::launch::async, downloadIconIfNecessary, std::ref(achievement)));
}
static auto awaitFuture = std::async(std::launch::async, [&](){
for(auto& job : asyncJobs){
// Asynchronously wait for all other async jobs to be completed
job.wait();
}
asyncJobs.clear();
shutdown();
});
}
}
} | 32.609865 | 106 | 0.738036 | narindertamber66 |
0c35d1e8e44f5d8b9e7bd8c00e97fe10fc7c2e6a | 1,325 | cpp | C++ | test/result.cpp | elpescado/core-jsonrpc | 12f85727168086a0a964aa9b934cd62f360c4cc3 | [
"MIT"
] | null | null | null | test/result.cpp | elpescado/core-jsonrpc | 12f85727168086a0a964aa9b934cd62f360c4cc3 | [
"MIT"
] | null | null | null | test/result.cpp | elpescado/core-jsonrpc | 12f85727168086a0a964aa9b934cd62f360c4cc3 | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include "result.h"
#include <json/value.h>
using namespace core::jsonrpc;
TEST(ResultTest, TestConstructor)
{
Json::Value id(5);
Result res(id);
ASSERT_EQ(id, res.id());
ASSERT_EQ(ResultState::None, res.state());
ASSERT_THROW(res.result(), std::invalid_argument);
}
TEST(ResultTest, TestSetResult)
{
Json::Value id(6);
Json::Value result("A Test Result");
Result res(id);
res.set_result(result);
ASSERT_EQ(ResultState::Result, res.state());
ASSERT_EQ(result, res.result());
}
TEST(ResultTest, TestSetResultTwice)
{
Json::Value id(6);
Json::Value result("A Test Result");
Result res(id);
res.set_result(result);
ASSERT_THROW(res.set_result(result), std::invalid_argument);
}
TEST(ResultTest, TestSignalStateChanged)
{
bool fired = false;
Json::Value id(7);
Json::Value result("A Test Result");
Result res(id);
res.signal_state_changed.connect([&fired](){
fired = true;
});
res.set_result(result);
ASSERT_EQ(true, fired);
}
TEST(ResultTest, TestSetError)
{
bool fired = false;
Json::Value id("8");
Result res(id);
res.signal_state_changed.connect([&fired](){
fired = true;
});
res.set_error(Error(42, "Malfunction"));
ASSERT_EQ(true, fired);
Error e = res.error();
ASSERT_EQ(42, e.code());
ASSERT_EQ(std::string("Malfunction"), e.message());
}
| 18.150685 | 61 | 0.693585 | elpescado |
0c38056fb841e231d209450010e13fbe78092b17 | 764 | cpp | C++ | Projects/CoX/Servers/MapServer/MapTemplate.cpp | teronis84/Segs | 71ac841a079fd769c3a45836ac60f34e4fff32b9 | [
"BSD-3-Clause"
] | null | null | null | Projects/CoX/Servers/MapServer/MapTemplate.cpp | teronis84/Segs | 71ac841a079fd769c3a45836ac60f34e4fff32b9 | [
"BSD-3-Clause"
] | null | null | null | Projects/CoX/Servers/MapServer/MapTemplate.cpp | teronis84/Segs | 71ac841a079fd769c3a45836ac60f34e4fff32b9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Super Entity Game Server Project
* http://segs.sf.net/
* Copyright (c) 2006 - 2016 Super Entity Game Server Team (see Authors.txt)
* This software is licensed! (See License.txt for details)
*
*/
#include "MapTemplate.h"
#include "MapInstance.h"
MapTemplate::MapTemplate(const std::string &/*template_filename*/)
{
}
MapInstance * MapTemplate::get_instance()
{
if(m_instances.size()==0)
{
m_instances.push_back(new MapInstance("City_00_01")); // should be replaced with proper cloning of map structure
m_instances.back()->activate(THR_NEW_LWP|THR_JOINABLE|THR_INHERIT_SCHED,1);
m_instances.back()->start();
}
return m_instances.front();
}
size_t MapTemplate::num_instances()
{
return m_instances.size();
}
| 25.466667 | 120 | 0.697644 | teronis84 |
0c3b4d5e2326499867cf563347d0eeb19a0658e8 | 558 | cpp | C++ | src/cricketer.cpp | tomdodd4598/UCL-PHAS0100-CandamirTilesExample1 | 8a324462d93db49a6a2c88fb382bca110c7ec611 | [
"MIT"
] | null | null | null | src/cricketer.cpp | tomdodd4598/UCL-PHAS0100-CandamirTilesExample1 | 8a324462d93db49a6a2c88fb382bca110c7ec611 | [
"MIT"
] | null | null | null | src/cricketer.cpp | tomdodd4598/UCL-PHAS0100-CandamirTilesExample1 | 8a324462d93db49a6a2c88fb382bca110c7ec611 | [
"MIT"
] | null | null | null | #include "cricketer.hpp"
#include "equipment.hpp"
#include <string>
namespace cricket {
std::string Cricketer::equipment_string() const {
std::string str = "[";
bool begin = true;
for (auto& e : equipment_list) {
if (begin) {
begin = false;
}
else {
str += ", ";
}
str += e->type_string();
str += ": {";
str += e->to_string();
str += '}';
}
str += ']';
return str;
}
}
| 19.241379 | 53 | 0.399642 | tomdodd4598 |
0c3f6c3f42c0b0eabfcef4f8b2fd02369c26b922 | 135 | cpp | C++ | Schweizer-Messer/sm_logging/src/LoggingEvent.cpp | PushyamiKaveti/kalibr | d8bdfc59ee666ef854012becc93571f96fe5d80c | [
"BSD-4-Clause"
] | 2,690 | 2015-01-07T03:50:23.000Z | 2022-03-31T20:27:01.000Z | Schweizer-Messer/sm_logging/src/LoggingEvent.cpp | PushyamiKaveti/kalibr | d8bdfc59ee666ef854012becc93571f96fe5d80c | [
"BSD-4-Clause"
] | 481 | 2015-01-27T10:21:00.000Z | 2022-03-31T14:02:41.000Z | Schweizer-Messer/sm_logging/src/LoggingEvent.cpp | PushyamiKaveti/kalibr | d8bdfc59ee666ef854012becc93571f96fe5d80c | [
"BSD-4-Clause"
] | 1,091 | 2015-01-26T21:21:13.000Z | 2022-03-30T01:55:33.000Z | #include <sm/logging/LoggingEvent.hpp>
namespace sm {
namespace logging {
} // namespace logging
} // namespace sm
| 13.5 | 38 | 0.62963 | PushyamiKaveti |
0c41a2e57c2817dfdfec15bff79f24721e569092 | 171,616 | cpp | C++ | AIPDebug/Display-Interface/w_conf.cpp | Bluce-Song/Master-AIP | 1757ab392504d839de89460da17630d268ff3eed | [
"Apache-2.0"
] | null | null | null | AIPDebug/Display-Interface/w_conf.cpp | Bluce-Song/Master-AIP | 1757ab392504d839de89460da17630d268ff3eed | [
"Apache-2.0"
] | null | null | null | AIPDebug/Display-Interface/w_conf.cpp | Bluce-Song/Master-AIP | 1757ab392504d839de89460da17630d268ff3eed | [
"Apache-2.0"
] | null | null | null | #include "w_conf.h"
#include "ui_w_conf.h"
static bool Clicked = true;
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 设置界面初始化
******************************************************************************/
w_Conf::w_Conf(QWidget *parent) :
QWidget(parent),
ui(new Ui::w_Conf)
{
this->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint); // 去掉标题栏
ui->setupUi(this);
WDLR = NULL; // -电阻界面为空
WMAG = NULL; // -反嵌界面为空
WIR = NULL; // -绝缘界面为空
WACW = NULL; // -交耐界面为空
WDCW = NULL; // -直耐界面为空
WIMP = NULL; // -匝间界面为空
WPWR = NULL; // -功率界面为空
WINDL = NULL; // -电感界面为空
WBLOCK = NULL; // -堵转界面为空
WLVS = NULL; // -低启界面为空
WPG = NULL; // -霍尔界面为空
WLOAD = NULL; // -负载界面为空
WNoLoad = NULL; // -空载界面为空
WBEMF = NULL; // -BEMF界面为空
btnGroup_function = new QButtonGroup; // -配置按钮
btnGroup_function->addButton(ui->Key_A, Qt::Key_A);
btnGroup_function->addButton(ui->Key_B, Qt::Key_B);
btnGroup_function->addButton(ui->Key_C, Qt::Key_C);
btnGroup_function->addButton(ui->Key_D, Qt::Key_D); ui->Key_D->hide();
btnGroup_function->addButton(ui->Key_E, Qt::Key_E); ui->Key_E->hide();
connect(btnGroup_function, SIGNAL(buttonClicked(int)), \
this, SLOT(SlOT_Button_Function_Judge(int)));
btnGroup_Color = new QButtonGroup; // -颜色按键
connect(btnGroup_Color, SIGNAL(buttonClicked(int)), this, SLOT(SlOT_Button_Color_Judge(int)));
btnGroup_Conf = new QButtonGroup; // -测试项目
btnGroup_Conf->addButton(ui->Button_ALL, Qt::Key_0);
btnGroup_Conf->addButton(ui->Button_DLR, Qt::Key_1); ui->Button_DLR->hide();
btnGroup_Conf->addButton(ui->Button_MAG, Qt::Key_2); ui->Button_MAG->hide();
btnGroup_Conf->addButton(ui->Button_IR, Qt::Key_3); ui->Button_IR->hide();
btnGroup_Conf->addButton(ui->Button_ACW, Qt::Key_4); ui->Button_ACW->hide();
btnGroup_Conf->addButton(ui->Button_DCW, Qt::Key_5); ui->Button_DCW->hide();
btnGroup_Conf->addButton(ui->Button_IMP, Qt::Key_6); ui->Button_IMP->hide();
btnGroup_Conf->addButton(ui->Button_PWR, Qt::Key_7); ui->Button_PWR->hide();
btnGroup_Conf->addButton(ui->Button_INDL, Qt::Key_8); ui->Button_INDL->hide();
btnGroup_Conf->addButton(ui->Button_BLOCK, Qt::Key_9); ui->Button_BLOCK->hide();
btnGroup_Conf->addButton(ui->Button_LVS, 58); ui->Button_LVS->hide();
btnGroup_Conf->addButton(ui->Button_Hall, 59); ui->Button_Hall->hide();
btnGroup_Conf->addButton(ui->Button_Load, 60); ui->Button_Load->hide();
btnGroup_Conf->addButton(ui->Button_NoLoad, 61); ui->Button_NoLoad->hide();
btnGroup_Conf->addButton(ui->Button_BEMF, 61); ui->Button_BEMF->hide();
connect(btnGroup_Conf, SIGNAL(buttonClicked(int)), this, SLOT(SlOT_Button_Conf_Judge(int)));
int i = 0;
Item_Widget = new QWidget(this); // -建立弹出项目
Item_Widget->setGeometry(450, 10, 250, 571);
Item_Widget->setWindowFlags(Qt::WindowStaysOnTopHint);
QStringList Item_Text, Item_Id;
Item_Text.clear();
Count_Item = 14;
Item_Text << tr("取消") << tr("设置") << tr("电阻") << tr("电感") << tr("反嵌") << tr("绝缘")\
<< tr("交耐") << tr("直耐") << tr("匝间") << tr("电参")\
<< tr("堵转") << tr("低启")\
<< tr("HALL") << tr("负载") << tr("空载") << tr("BEMF");
Item_Id << tr("0") << tr("20") << tr("1") << tr("8") << tr("2") << tr("3")\
<< tr("4") << tr("5") << tr("6") << tr("7")\
<< tr("9") << tr("10")\
<< tr("11") << tr("12") << tr("13") << tr("14");
int position[] = {00, 10, 30, 40, 50, 60, \
70, 80, 90, 31, \
41, 51, \
61, 71, 81, 91};
QGridLayout *Item_all = new QGridLayout;
btnGroup_Item = new QButtonGroup; // -进行设置按键的增加
for (i = 0; i < Item_Text.size(); i++) {
Item_Putton.append(new QPushButton(this));
btnGroup_Item->addButton(Item_Putton[i], Item_Id.at(i).toInt());
Item_Putton[i]->setText(Item_Text.at(i));
Item_Putton[i]->setMinimumHeight(40);
Item_Putton[i]->setMinimumWidth(90);
Item_all->addWidget(Item_Putton[i], position[i]/10, position[i]%10);
}
for (i = 2; i < Item_Text.size(); i++) {
Item_Putton[i]->hide(); // 功能隐藏
}
connect(btnGroup_Item, SIGNAL(buttonClicked(int)), this, SLOT(SlOT_ButtonProj(int)));
Item_Putton[0]->setStyleSheet("background-color: gray;");
Item_Putton[1]->setStyleSheet("background-color: green;");
QLabel *Item_Lable_padding = new QLabel;
Item_Lable_padding->setStyleSheet("background-color: #191919;");
Item_Lable_padding->setMinimumHeight(50);
Item_all->addWidget(Item_Lable_padding, 2, 0);
Item_all->setAlignment(Qt::AlignTop);
Item_Chose_Box = new QCheckBox(this);
Item_Chose_Box->setStyleSheet
("QCheckBox::indicator {image: url(:/image/053.png);"\
"width: 50px;height: 55px;}"\
"QCheckBox::indicator:checked {image: url(:/image/051.png);}");
Item_Chose_Box->setChecked(false);
connect(Item_Chose_Box, SIGNAL(stateChanged(int)), \
this, SLOT(Item_Chose_Box_stateChanged(int)));
Item_all->addWidget(Item_Chose_Box, 0, 1);
Item_Widget->setStyleSheet(".QWidget{background-color: #191919;border: 2px solid #447684;}");
Item_Widget->setLayout(Item_all);
Item_Widget->hide();
btnGroup_IMP_Sample = new QButtonGroup;
btnGroup_IMP_Sample->addButton(ui->imp_button_add, 0); ui->imp_button_add->hide();
btnGroup_IMP_Sample->addButton(ui->imp_button_cancel, 1); ui->imp_button_cancel->hide();
btnGroup_IMP_Sample->addButton(ui->imp_button_finsh, 2); ui->imp_button_finsh->hide();
connect(btnGroup_IMP_Sample, SIGNAL(buttonClicked(int)), \
this, SLOT(SlOT_Button_IMP_Sample(int)));
Test_Item.clear();
Test_Item.append(tr("清除")); // 0
Test_Item.append(tr("电阻")); // 1
Test_Item.append(tr("反嵌")); // 2
Test_Item.append(tr("绝缘")); // 3
Test_Item.append(tr("交耐")); // 4
Test_Item.append(tr("直耐")); // 5
Test_Item.append(tr("匝间")); // 6
Test_Item.append(tr("电参")); // 7
Test_Item.append(tr("电感")); // 8
Test_Item.append(tr("堵转")); // 9
Test_Item.append(tr("低启")); // 10
Test_Item.append(tr("HALL")); // 11
Test_Item.append(tr("负载")); // 12
Test_Item.append(tr("空载")); // 13
Test_Item.append(tr("BEMF")); // 14
Test_Item.append(tr("PG")); // 11
ui->fileTab->horizontalHeader()->setStyleSheet
("QHeaderView::section{background-color:#191919;"\
"color: white;padding-left: 4px;border: 1px solid #447684;}");
ui->fileTab->horizontalHeader()->setResizeMode(QHeaderView::Fixed);
ui->test->horizontalHeader()->setStyleSheet
("QHeaderView::section{background-color:#191919;"\
"color: white;padding-left: 4px;border: 1px solid #447684;}");
Mouse.Time = new QTimer(this);
connect(Mouse.Time, SIGNAL(timeout()), this, SLOT(test_mouse_check()));
Mouse.Ms = 0; Mouse.Us = 0;
Mouse.Flag = false;
Conf_User = User_Operator; // -默认设置为操作员
TabWidget_Changed = true; // -默认设置为页面改变
remove_row = 0; // -移除的项目
Quick_Set = false; // -默认非快速设置
index_c = 0; // -当前页面的序列号, 默认为0
parameter.clear();
parameter.append(QString(tr("Conf")));
parameter.append(QString(tr("DLR")));
parameter.append(QString(tr("MAG")));
parameter.append(QString(tr("IR")));
parameter.append(QString(tr("ACW")));
parameter.append(QString(tr("DCW")));
parameter.append(QString(tr("IMP")));
parameter.append(QString(tr("PWR")));
parameter.append(QString(tr("INDL")));
parameter.append(QString(tr("BLOCK")));
parameter.append(QString(tr("LVS")));
parameter.append(QString(tr("HALL")));
parameter.append(QString(tr("LOAD")));
parameter.append(QString(tr("NOLOAD")));
parameter.append(QString(tr("BEMF")));
Conf_label_Hide = new QLabel(ui->W_All);
Conf_label_Hide->setGeometry(0, 0, 700, 600);
Conf_label_Hide->hide();
conf_Waring = false;
label_Waring = new QLabel(this);
label_Waring->setGeometry(0, 0, 800, 600);
label_Waring->hide();
Beep.Time = new QTimer(this);
connect(Beep.Time, SIGNAL(timeout()), this, SLOT(beep_stop()));
Beep.Flag = false;
QString path = ("/mnt/nandflash/AIP/Model/"); // -读取全部型号, 建立文件类型列表--model_Type
QDir *dir = new QDir(path);
QStringList filter; filter << "*.jpg";
QString FileName;
QString FileNameInter;
dir->setNameFilters(filter);
QList<QFileInfo> *fileInfo = new QList<QFileInfo>(dir->entryInfoList(filter));
ui->MotorType->clear();
for (i = 0; i < fileInfo->count(); i++) {
FileName = fileInfo->at(i).fileName();
FileNameInter = FileName.mid(0, FileName.indexOf("."));
ui->MotorType->addItem(FileNameInter, i);
model_Type.append(FileNameInter);
}
// FILE *SD_Exist;
// SD_Exist = fopen("/dev/mmcblk0", "r"); // 查看SD卡是否进行挂载
// if (SD_Exist != NULL) {
// sdcard_exist = true;
// sql.openSql("/mnt/sdcard/aip.db"); // 打开 sdcard 数据库
// } else {
// sdcard_exist = false;
// sql.openSql("/mnt/nandflash/aip.db"); // 打开 nandflash 数据库
// }
same_ip_address = false;
NetSQL_OpenOk = false;
// if (Get_Ip_Address()) // 判断IP是否处在同一个网段
{
same_ip_address = true;
}
isopend = false;
label_Set = new QLabel(this);
label_Set->setGeometry(720, 10, 66, 571);
label_Set->setText(tr("设\n置\n中\n,\n请\n稍\n候"));
label_Set->setStyleSheet("color: white;font: Bold 30pt Ubuntu;");
label_Set->setAlignment(Qt::AlignCenter);
label_Set->hide();
lable_Zero = new QLabel(this);
lable_Zero->setGeometry(0, 0, 800, 600);
lable_Zero->setStyleSheet("color: white;font: Bold 30pt Ubuntu;");
lable_Zero->setText(tr("正在清零,请稍后"));
lable_Zero->setAlignment(Qt::AlignCenter);
lable_Zero->hide();
Ini_Power_Chose = 0; // -功率板的电源初始化为0
Ini_Mag_Hide = 0;
Ini_Udp_Enable = false;
Ini_ACW_And_IR = false;
Ini_System.clear();
Ini_Number = 0;
Ini_Proj_Real.clear();
Ini_Proj.clear();
SQL_Init = true;
SQL_Widget = new QWidget(this);
SQL_Widget->setGeometry(150, 100, 500, 400);
SQL_Widget->setWindowFlags(Qt::WindowStaysOnTopHint);
SQL_Widget->setStyleSheet
("border-radius: 10px;padding:2px 4px;background-color: gray;"\
"color: black;border-color: black;");
QGridLayout *SQL_upside = new QGridLayout;
QString SQL_table[5]={tr("生产线:"), tr("生产任务号:"), \
tr("计划数量:"), tr("生产部门:"), tr("产品型号:")};
for (i = 0; i < 5; i++) {
SQL_lable.append(new QLabel(this));
SQL_lable[i]->setText(SQL_table[i]);
SQL_lable[i]->setMaximumHeight(35); SQL_lable[i]->setMaximumWidth(135);
SQL_lable[i]->setAlignment(Qt::AlignCenter);
SQL_upside->addWidget(SQL_lable[i], i, 0);
if (i > 1) {
SQL_Line_Text.append(new QLineEdit(this));
SQL_Line_Text[i-2]->setMaximumHeight(35); SQL_Line_Text[i-2]->setMaximumWidth(255);
SQL_upside->addWidget(SQL_Line_Text[i-2], i, 1);
}
}
SQL_Produce_Plan = new QComboBox(this);
SQL_Produce_Plan->setMaximumHeight(35); SQL_Produce_Plan->setMaximumWidth(255);
SQL_upside->addWidget(SQL_Produce_Plan, 0, 1);
connect(SQL_Produce_Plan, SIGNAL(currentIndexChanged(const QString &)), \
this, SLOT(SQL_Produce_Plan_textChanged(const QString &)));
SQL_Produce_Number = new QComboBox(this);
SQL_Produce_Number->setMaximumHeight(35); SQL_Produce_Number->setMaximumWidth(255);
SQL_upside->addWidget(SQL_Produce_Number, 1, 1);
connect(SQL_Produce_Number, SIGNAL(currentIndexChanged(const QString &)), \
this, SLOT(SQL_Produce_Number_textChanged(const QString &)));
QPushButton *button_quit_SQL = new QPushButton;
button_quit_SQL->setText(tr("退出"));
button_quit_SQL->setMinimumHeight(50);
button_quit_SQL->setMinimumWidth(90);
button_quit_SQL->setStyleSheet("background: qlineargradient"\
"(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #5B5F5F, "\
"stop: 0.5 #0C2436,stop: 1 #27405A);");
SQL_upside->addWidget(button_quit_SQL, 0, 5);
connect(button_quit_SQL, SIGNAL(clicked()), this, SLOT(SQL_Widget_autoquit()));
QVBoxLayout *Histogram_Widget_layout_SQL = new QVBoxLayout;
Histogram_Widget_layout_SQL->addLayout(SQL_upside);
SQL_Widget->setLayout(Histogram_Widget_layout_SQL);
SQL_Widget->hide();
SQL_Init = false;
PWR_Test_Usart = false;
SQL_Error = false;
strTest.clear(); // -测试项目清除
strParam.clear(); // -测试参数清除
Result_indl.dat[0] = 0;
Result_indl.dat[1] = 0;
Result_indl.dat[2] = 0;
Result_indl.dat[3] = 0;
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 析构
******************************************************************************/
w_Conf::~w_Conf()
{
delete btnGroup_function;
delete ui;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.1.15
* brief: 获取ip地址,并且与数据库ip做对比
******************************************************************************/
int w_Conf::Get_Ip_Address()
{
int sock_get_ip = 0;
int i = 0;
bool ip_same = 0;
char ipaddr[50];
struct sockaddr_in *sin;
struct ifreq ifr_ip;
if ((sock_get_ip=socket(AF_INET, SOCK_STREAM, 0)) == -1) {
//
} else {
//
}
memset(&ifr_ip, 0, sizeof(ifr_ip));
strncpy(ifr_ip.ifr_name, "eth0", sizeof(ifr_ip.ifr_name) - 1);
if (ioctl(sock_get_ip, SIOCGIFADDR, &ifr_ip) < 0) {
//
}
sin = (struct sockaddr_in *)&ifr_ip.ifr_addr;
strcpy(ipaddr, inet_ntoa(sin->sin_addr));
QStringList ip_split = QString(ipaddr).split(".");
QSettings set_odbc("/usr/local/arm/unixODBC/etc/odbc.ini", QSettings::IniFormat); // 数据库 ip
QString sql_net_ip = set_odbc.value("testodbc/Server", "1,1,1,1").toString();
QStringList sql_net_ip_split = QString(sql_net_ip).split(".");
for (i = 0; i < sql_net_ip_split.size() - 1; i++) {
if (ip_split.at(i) == sql_net_ip_split.at(i)) {
ip_same = 1;
} else {
ip_same = 0;
break;
}
}
return ip_same;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.1
* brief: 处理鼠标被按下事件
******************************************************************************/
void w_Conf::mousePressEvent(QMouseEvent *event)
{
handleMousePressEvent(event);
Item_Widget->hide();
Conf_label_Hide->hide();
Mouse.Ms = 0; Mouse.Us = 0;
Mouse.Time->start(1);
Mouse.Flag = false;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.1
* brief: 处理鼠标离开事件
******************************************************************************/
void w_Conf::mouseReleaseEvent(QMouseEvent *event)
{
Mouse.Time->stop();
if ((Mouse.Ms >= 2) && (!conf_Waring)) {
Singal_Conf_to_Main(QStringList(""), QString(""), wHelp_Surface, 2);
}
Mouse.Ms = 0; Mouse.Us = 0;
Mouse.Flag = false;
event->x();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.1
* brief: 长按计时功能
******************************************************************************/
void w_Conf::test_mouse_check()
{
Mouse.Us++;
if (Mouse.Us >= 1000) {
Mouse.Us = 0;
Mouse.Ms++;
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.7.19
* brief: 点击页面操作
******************************************************************************/
bool w_Conf::handleMousePressEvent(QMouseEvent *event)
{
QPoint topLeftUser(0, 30); // left top
QPoint rightBottomUser(711, 600);
QRect rectUser(topLeftUser, rightBottomUser);
if (rectUser.contains(event->pos())) {
if ((Conf_User == User_Operator) && (!conf_Waring)) {
Pri_Conf_WMessage(tr(" 当前用户模式为操作员 \n"\
"无权限进行保存和修改 "));
}
}
return true;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.1
* brief: 蜂鸣器停止
******************************************************************************/
void w_Conf::beep_stop()
{
Beep_PWM_Stop();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.31
* brief: 蜂鸣器的报警状态
******************************************************************************/
void w_Conf::Beep_State()
{
if (Beep.Flag) {
return;
}
Beep.Flag = true;
Beep.Time->setSingleShot(TRUE); Beep.Time->start(80); Beep_PWM_Start(99);
Beep.Flag = false;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.31
* brief: 匝间进行采样
******************************************************************************/
void w_Conf::SlOT_Button_IMP_Sample(int id)
{
if (Conf_User == User_Operator) {
Pri_Conf_WMessage(tr(" 当前用户模式为操作员 \n"\
"无权限进行保存和修改 "));
} else {
WIMP->Pub_Conf_GetSample(id);
if (id == 2) {
SlOT_Button_Function_Judge(Qt::Key_B);
} else {
//
}
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.10
* brief: 可选项目 按键功能 // 已屏蔽
******************************************************************************/
void w_Conf::SlOT_ButtonProj(int id)
{
int i = 0;
qDebug() << "SlOT_ButtonProj";
Item_Widget->hide();
Conf_label_Hide->hide();
if (remove_row < (test_Inifile.size())) {
switch (id) {
case 0: // -清除
test_Inifile.removeAt(remove_row);
break;
case 20: // -设置
SlOT_Button_Conf_Judge(test_Inifile.at(remove_row).toInt()+48);
break;
default: // -取代 (电阻 反嵌 绝缘 交耐 直耐 匝间 电参 电感 堵转 低启)
test_Inifile.replace(remove_row, (QString::number(id)));
break;
}
} else {
if ((id != 0) && (id != 20)) { // -去除(清除和取消)
test_Inifile.append(QString::number(id));
}
}
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
QString name_list;
name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setValue(name_list, test_Inifile);
ui->test->setRowCount(0);
ui->test->setGeometry(305, 20, 131, 39*14 + (ui->test->horizontalHeader()->height()));
ui->test->setRowCount(13);
for (i = 0; i < 13; i++) {
ui->test->setRowHeight(i, 39);
}
Init_test_TableWidget(); // -初始化测试项目
for (i = 1; i <= Count_Item; i++) { // -设置显示, 锁定端子号
btnGroup_Item->button(i)->hide();
}
btnGroup_Item->button(0)->show();
btnGroup_Item->button(20)->show();
for (i = 1; i < Ini_Proj.size(); i++) {
btnGroup_Item->button(Ini_Proj.at(i).toInt())->show();
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.7.19
* brief: 在操作页面获取焦点
******************************************************************************/
void w_Conf::Usart_GetFcous()
{
switch (index_c) {
case 0:
//
break;
case 1:
WDLR->Pub_Conf_Set_DLR("", 8);
break;
case 2:
WMAG->Pub_Conf_Set_MAG("", 8);
break;
case 3:
//
break;
case 4:
//
break;
case 5:
//
break;
case 6:
WIMP->Pub_Conf_Set_IMP("", 9);
break;
case 7:
//
break;
case 8:
//
break;
case 9:
//
break;
case 10:
//
break;
case 11: // 霍尔
//
break;
case 12: // 负载
//
break;
case 13: // 空载
//
break;
case 14: // 反电动势
//
break;
default:
//
break;
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.10
* brief: 进入测试项目的设置界面
******************************************************************************/
void w_Conf::SlOT_Button_Conf_Judge(int id)
{
qDebug() << id - 48 << index_c;
if (((id - 48) != index_c) && (!Quick_Set)) {
Save_Hint();
}
ui->Key_A->show(); ui->Key_B->setText(tr("测试主页"));
ui->Key_B->show(); ui->Key_B->setText(tr("保存设置"));
ui->Button_ALL->show(); ui->Button_ALL->setText(tr("设置首页"));
ui->Key_C->hide();
ui->Key_D->hide();
ui->Key_E->hide(); ui->Key_E->setText("补偿");
ui->Key_D->setStyleSheet("background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"\
"stop: 0 #5B5F5F, stop: 0.5 #0C2436,"\
"stop: 1 #27405A); color:rgb(255, 255, 255);");
ui->Key_E->setStyleSheet("background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"\
"stop: 0 #5B5F5F, stop: 0.5 #0C2436,"\
"stop: 1 #27405A); color:rgb(255, 255, 255);");
switch (id) {
case Qt::Key_0:
ui->label_User->setGeometry(299, 0, 401, 600);
ui->stackedWidget->setCurrentIndex(0);
ui->imp_button_add->hide();
ui->imp_button_cancel->hide();
ui->imp_button_finsh->hide();
ui->Button_ALL->hide();
ui->Key_C->show(); ui->Key_C->setText(tr("快速设置"));
break;
case Qt::Key_1: // -电阻
WDLR->Pub_Conf_Set_DLR(QString::number(Out_Channel_6), 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WDLR));
ui->Key_D->show(); ui->Key_D->setText(tr("左清零"));
ui->Key_E->show(); ui->Key_E->setText(tr("右清零"));
if (WDLR->DLR_Compensate_Left) {
ui->Key_D->setStyleSheet("background:#00FF00;color:rgb(0, 0, 0);");
ui->Key_D->setText(tr("左OK")); // -已清零
} else {
ui->Key_D->setText(tr("左清零")); // -未清零
}
if (WDLR->DLR_Compensate_Right) {
ui->Key_E->setStyleSheet("background:#00FF00;color:rgb(0, 0, 0);");
ui->Key_E->setText(tr("右OK")); // -已清零
} else {
ui->Key_E->setText(tr("右清零")); // -未清零
}
break;
case Qt::Key_2: // -反嵌
if (WMAG != NULL) {
WMAG->Pub_Conf_Set_MAG(QString::number(Out_Channel_6), 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WMAG));
Board_DLR = 1;
ui->Key_D->show(); ui->Key_D->setText(tr("采集"));
WMAG->Pub_Conf_Set_MAG("", 9);
break;
} else if (WPWR != NULL) {
id = 0x37;
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WPWR));
WPWR->setFocus();
break;
} else {
//
}
break;
case Qt::Key_3: // -绝缘
WIR->Pub_Conf_Set_IR(QString::number(Out_Channel_6), 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WIR));
if (Ini_ACW_And_IR) {
ui->Key_E->hide();
} else {
ui->Key_E->show();
}
if (WIR->IR_Back_Key_E()) {
ui->Key_E->setStyleSheet("background:#00FF00;color:rgb(0, 0, 0);");
ui->Key_E->setText(tr("已补偿"));
} else {
ui->Key_E->setText(tr("未补偿"));
}
break;
case Qt::Key_4: // -交耐
WACW->Pub_Conf_Set_ACW(QString::number(Out_Channel_6), 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WACW));
if (Ini_ACW_And_IR) {
ui->Key_E->hide();
} else {
ui->Key_E->show();
}
if (WACW->ACW_Back_Key_E()) {
ui->Key_E->setStyleSheet("background:#00FF00;color:rgb(0, 0, 0);");
ui->Key_E->setText(tr("已补偿"));
} else {
ui->Key_E->setText(tr("未补偿"));
}
break;
case Qt::Key_5: // -直耐
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WDCW));
break;
case Qt::Key_6: // -匝间
WIMP->Pub_Conf_Set_IMP(QString::number(Out_Channel_6), 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WIMP));
WIMP->Pub_Conf_Set_IMP("", 3);
ui->Key_D->show(); ui->Key_D->setText(tr("采集"));
ui->imp_button_add->show();
ui->imp_button_cancel->show();
ui->imp_button_finsh->show();
break;
case Qt::Key_7:
WPWR->Pub_Conf_Set_PWR(QString::number(Out_Channel_6), 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WPWR));
WPWR->setFocus();
break;
case Qt::Key_8:
WINDL->Pub_Conf_Set_INDL(QString::number(Out_Channel_6), 100, 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WINDL));
WINDL->setFocus();
break;
case Qt::Key_9:
WBLOCK->Pub_Conf_Set_BLOCK(QString::number(Out_Channel_6), 100, 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WBLOCK));
WBLOCK->setFocus();
WBLOCK->Pub_Conf_Set_BLOCK("", 1, 6);
break;
case 58:
WLVS->Pub_Conf_Set_LVS(QString::number(Out_Channel_6), 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WLVS));
WLVS->setFocus();
break;
case 59: // 霍尔
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WPG));
WPG->setFocus();
break;
case 60: // 负载
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WLOAD));
WLOAD->setFocus();
break;
case 61: // 空载
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WNoLoad));
WNoLoad->setFocus();
break;
case 62: // 反电动势
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WBEMF));
WBEMF->setFocus();
break;
default:
ui->Key_C->show();
ui->stackedWidget->setCurrentIndex(0);
break;
}
if (Quick_Set) {
ui->Key_A->hide();
ui->Key_B->hide();
ui->Key_C->hide();
ui->Key_D->hide();
ui->Key_E->hide();
ui->imp_button_add->hide();
ui->imp_button_cancel->hide();
ui->imp_button_finsh->hide();
ui->Button_ALL->hide();
}
qApp->processEvents();
index_c = (id - 48)%16; // -获取保存序列号-16
TabWidget_Changed = true;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.7.19
* brief: 配置页面的键盘操作
******************************************************************************/
void w_Conf::Usart_Button(int Usart_number)
{
if (Usart_number == 26) {
SlOT_Button_Function_Judge(Qt::Key_A);
} else if (Usart_number == 27) {
SlOT_Button_Function_Judge(Qt::Key_B);
} else if (Usart_number == 24) {
switch (index_c) {
case 0:
SlOT_Button_Function_Judge(Qt::Key_C);
break;
case 1:
SlOT_Button_Function_Judge(Qt::Key_E);
break;
case 2:
SlOT_Button_Function_Judge(Qt::Key_D);
break;
case 3:
SlOT_Button_Function_Judge(Qt::Key_E);
break;
case 4:
SlOT_Button_Function_Judge(Qt::Key_E);
break;
case 5:
//
break;
case 6:
SlOT_Button_Function_Judge(Qt::Key_D);
break;
case 7:
//
break;
case 8:
//
break;
case 9:
//
break;
case 10:
//
break;
case 11: // 霍尔
//
break;
case 12: // 负载
//
break;
case 13: // 空载
//
break;
case 14: // 反电动势
//
break;
default:
//
break;
}
} else if (Usart_number == 25) {
SlOT_Button_Conf_Judge(Qt::Key_0);
} else {
//
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2015.12.30
* brief: 颜色设置
******************************************************************************/
void w_Conf::SlOT_Button_Color_Judge(int id)
{
if (id >= 12) {
return;
}
iColorBtn = id;
Singal_Conf_to_Main(QStringList(""), QString(""), wColr_Surface, 2);
}
void w_Conf::PC_Test_Param_connect() {
QStringList netdata;
QStringList strParam_c;
strParam_c.clear();
netdata.clear();
netdata.append(strTest);
strParam_c = strParam;
for (int i = 0; i < strParam.size(); i++) {
strParam_c.replace(i, QString(strParam_c.at(i)).replace(QRegExp("\\,"), " "));
}
netdata.append(strParam_c);
PC_Test_Param_Data(netdata);
}
void w_Conf::FG_bound_Item() {
int i = 0;
qDebug() << "FG_bound_Item();";
qDebug() << test_Inifile;
if (test_Inifile.contains(tr("11"))) {
qDebug() << "2018-3-22 Hall---->" << WPG->Copy_BLDCPG_List.at(3);
// (0 空载) (1 负载) (2 BEMF)
// (13 空载) (12 负载) (14 BEMF)
switch (WPG->Copy_BLDCPG_List.at(3).toInt()) {
case 0:
if (Ini_Proj.contains(tr("13"))) {
test_Inifile.removeAt(test_Inifile.indexOf(tr("13")));
test_Inifile.insert(test_Inifile.indexOf(tr("11")),QString(tr("13")));
}
else {
test_Inifile.removeAt(test_Inifile.indexOf(tr("11")));// 删除FG
}
break;
case 1:
if (Ini_Proj.contains(tr("12"))) {
test_Inifile.removeAt(test_Inifile.indexOf(tr("12")));
test_Inifile.insert(test_Inifile.indexOf(tr("11")),QString(tr("12")));
}
else {
test_Inifile.removeAt(test_Inifile.indexOf(tr("11")));// 删除FG
}
break;
case 2:
if (Ini_Proj.contains(tr("14"))) {
test_Inifile.removeAt(test_Inifile.indexOf(tr("14")));
test_Inifile.insert(test_Inifile.indexOf(tr("11")),QString(tr("14")));
}
else {
test_Inifile.removeAt(test_Inifile.indexOf(tr("11")));// 删除FG
}
break;
default:
break;
}
qDebug() << test_Inifile;
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
QString name_list;
name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setValue(name_list, test_Inifile);
ui->test->setRowCount(0);
ui->test->setGeometry(305, 20, 131, 39*14 + (ui->test->horizontalHeader()->height()));
ui->test->setRowCount(13);
for (i = 0; i < 13; i++) {
ui->test->setRowHeight(i, 39);
}
Init_test_TableWidget();
qApp->processEvents(); // 立即显示生效
ui->test->item((test_Inifile.indexOf(tr("1"))),0)->setTextColor(QColor("green"));
} else {
//
}
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 按钮功能-功能选择 (测试主页 保存设置 快速设置 采集波形 补偿)
******************************************************************************/
void w_Conf::SlOT_Button_Function_Judge(int id)
{
int i = 0;
bool Exist_Pwr;
Exist_Pwr = false;
switch (id) {
case Qt::Key_A: {
if (Conf_User == User_Administrators) { // -管理员(进行保存提示)
Save_Hint();
}
TabWidget_Changed = true;
/*判断是否存在功率的测试项目,若存在在功率前添加电阻*/
if ((test_Inifile.contains(tr("7"))) || \
(test_Inifile.contains(tr("9"))) || \
(test_Inifile.contains(tr("10")))|| \
(test_Inifile.contains(tr("13")))) {
Exist_Pwr = true;
WDLR->Pub_Conf_Set_DLR("0", 4); // -WDLR->DLR_TestNumber的总数
if ((test_Inifile.indexOf(tr("1"))) == 0) {
//
} else {
test_Inifile.removeAt(test_Inifile.indexOf(tr("1")));
test_Inifile.insert(0, "1");
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
QString name_list;
name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setValue(name_list, test_Inifile);
ui->test->setRowCount(0);
ui->test->setGeometry(305, 20, 131, 39*14+(ui->test->horizontalHeader()->height()));
ui->test->setRowCount(13);
for (i = 0; i < 13; i++) {
ui->test->setRowHeight(i, 39);
}
Init_test_TableWidget();
qApp->processEvents(); // 立即显示生效
}
if ((test_Inifile.contains(tr("1")))) {
if (WDLR->DLR_TestNumber == 0) {
WDLR->Pub_Conf_Set_DLR("", 12);
WDLR->Pub_Conf_Set_DLR("", 3);
RES = WDLR->Copy_DLR_List;
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
QString name_list;
name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setValue(name_list, test_Inifile);
ui->test->setRowCount(0);
ui->test->setGeometry(305, 20, 131, 39*14 + \
(ui->test->horizontalHeader()->height()));
ui->test->setRowCount(13);
for (i = 0; i < 13; i++) {
ui->test->setRowHeight(i, 39);
}
Init_test_TableWidget();
qApp->processEvents(); // 立即显示生效
}
} else if (WDLR != NULL) {
test_Inifile.insert(0, "1");
WDLR->Pub_Conf_Set_DLR("", 12);
WDLR->Pub_Conf_Set_DLR("", 3);
RES = WDLR->Copy_DLR_List;
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
QString name_list;
name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setValue(name_list, test_Inifile);
ui->test->setRowCount(0);
ui->test->setGeometry(305, 20, 131, 39*14+(ui->test->horizontalHeader()->height()));
ui->test->setRowCount(13);
for (i = 0; i < 13; i++) {
ui->test->setRowHeight(i, 39);
}
Init_test_TableWidget();
qApp->processEvents();
} else {
//
}
ui->test->item((test_Inifile.indexOf(tr("1"))),0)->setTextColor(QColor("green"));
}
FG_bound_Item();
for (i = 0; i < test_Inifile.size(); i++) {
switch (test_Inifile[i].toInt()) {
case 1:
qDebug() << "Test RES ";
WDLR->Pub_Conf_Set_DLR("0", 4);
break;
case 2:
qDebug() << "Test OPP ";
WMAG->Pub_Conf_Set_MAG(" ", 7);
break;
case 3:
qDebug() << "Test INS ";
WIR->Pub_Conf_Set_IR(QString::number(Ini_IRHostJudge), 5);
break;
case 4:
qDebug() << "Test ACV ";
WACW->Pub_Conf_Set_ACW(" ", 5);
break;
case 5:
qDebug() << "Test DCV ";
break;
case 6:
qDebug() << "Test_IMP ";
break;
case 7: qDebug() << "Test_PWR ";
WPWR->Pub_Conf_Set_PWR("0", 3);
break;
case 8:
qDebug() << "Test_INDL";
WINDL->Pub_Conf_Set_INDL("0", 1, 3);
break;
case 9: qDebug() << "Test_BLOCK";
break;
case 10:
qDebug() << "Test_LVS";
WLVS->Pub_Conf_Set_LVS("0", 3);
break;
case 11:
qDebug() << "Test_PG";
break;
case 12:
qDebug() << "Test_LOAD";
break;
case 13:
qDebug() << "Test_NOLOAD";
break;
case 14:
qDebug() << "Test_BEMF";
break;
default:
//
break;
}
}
Sync_Test_Widget();
QStringList Main_Data; Main_Data.clear();
Main_Data.append(Ini_ActiveFile);
Main_Data.append(QString::number(Test_Occur_Debug));
Main_Data.append(serial_number);
Main_Data.append(SQL_Line_Text.at(0)->text());
Main_Data.append(QString::number(Exist_Pwr));
Main_Data.append(QString::number(strTest.size()));
Main_Data.append(QString::number(strParam.size()));
Main_Data.append(strTest);
Main_Data.append(strParam);
PC_Test_Param_connect();
Singal_Conf_to_Main(Main_Data, QString(""), wTest_Surface, 1);
break;
}
case Qt::Key_B:
Beep_State(); // -蜂鸣器提醒
if (Conf_User == User_Operator) {
Pri_Conf_WMessage(tr(" 当前用户模式为操作员 \n"\
"无权限进行保存和修改 "));
break;
}
qDebug() << "Qt::Key_B";
TabWidget_Changed = false;
switch (Ini_Proj.at(ui->stackedWidget->currentIndex()).toInt()) {
case 0:
qDebug() << "CONF";
Save_ConfData();
conf_c = CONF;
break;
case 1:
qDebug() << "RES";
WDLR->Pub_Conf_Set_DLR("", 3);
RES = WDLR->Copy_DLR_List;
break;
case 2:
qDebug() << "OPP";
WMAG->Pub_Conf_Set_MAG("", 2);
OPP = WMAG->Copy_MAG_List;
break;
case 3:
qDebug() << "INS";
WIR->Pub_Conf_Set_IR("", 2);
INS = WIR->Copy_IR_List;
break;
case 4:
qDebug() << "ACV";
WACW->Pub_Conf_Set_ACW("", 2);
ACV = WACW->Copy_ACW_List;
break;
case 5:
qDebug() << "DCV";
WDCW->Save_DCW_Data();
DCV = WDCW->Copy_DCW_List;
break;
case 6:
qDebug() << "ITT";
WIMP->Pub_Conf_Set_IMP("", 4);
ITT = WIMP->Copy_IMP_List;
break;
case 7:
WPWR->Pub_Conf_Set_PWR("", 2);
PWR = WPWR->Copy_PWR_List;
qDebug() << "PWR";
break;
case 8:
WINDL->Pub_Conf_Set_INDL("", 1, 2);
INDL = WINDL->Copy_INDL_List;
qDebug() << "INDL";
break;
case 9:
WBLOCK->Pub_Conf_Set_BLOCK("", 1, 2);
BLOCK = WBLOCK->Copy_BLOCK_List;
qDebug() << "BLOCK";
break;
case 10:
WLVS->Pub_Conf_Set_LVS("", 2);
LVS = WLVS->Copy_LVS_List;
qDebug() << "LVS";
break;
case 11:
WPG->Pub_Conf_Set_PG(QStringList(""), 2);
BLDCPG = WPG->Copy_BLDCPG_List;
qDebug() << "BLDCPG-save";
break;
case 12:
WLOAD->Pub_Conf_Set_LOAD("", 2);
qDebug() << "LOAD 1";
LOAD = WLOAD->Copy_LOAD_List;
qDebug() << "LOAD 2";
qDebug() << "LOAD";
break;
case 13:
WNoLoad->Pub_Conf_Set_NOLOAD(QStringList(""), 2);
NOLOAD = WNoLoad->Copy_NOLOAD_List;
qDebug() << "NOLOAD";
break;
case 14:
WBEMF->Pub_Conf_Set_BEMF(QString(""), 2);
BEMF = WBEMF->Copy_BEMF_List;
qDebug() << "BEMF";
break;
default: break;
}
Save_SqlData();
TabWidget_Changed = true;
qDebug() << "Start All OK";
break;
case Qt::Key_C:
if (Conf_User == User_Operator) {
Pri_Conf_WMessage(tr(" 当前用户模式为操作员 \n"\
"无权限进行保存和修改 "));
break;
}
Item_Widget->hide();
if ((Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 0) && \
(ui->MotorType->currentText() != "None")) { // 在 None型号时,不能进行快速设置
QMessageBox Quick_Set_Ask;
Quick_Set_Ask.setWindowFlags(Qt::FramelessWindowHint);
Quick_Set_Ask.setStyleSheet("QMessageBox{border:3px groove gray;}"\
"background-color: rgb(209, 209, 157);");
Quick_Set_Ask.setText(tr(" 确定进行快速设置 \n "));
Quick_Set_Ask.addButton(QMessageBox::Ok)->setStyleSheet
("border:none;height:30px;width:65px;border:5px groove gray;"\
"border-radius:10px;padding:2px 4px;");
Quick_Set_Ask.addButton(QMessageBox::Cancel)->setStyleSheet
("border:none;height:30px;width:65px;border:5px groove gray;"\
"border-radius:10px;padding:2px 4px;");
Quick_Set_Ask.setButtonText(QMessageBox::Ok, QString(tr("确 定")));
Quick_Set_Ask.setButtonText(QMessageBox::Cancel, QString(tr("取 消")));
Quick_Set_Ask.setIcon(QMessageBox::Warning);
int ret = Quick_Set_Ask.exec();
if (ret == QMessageBox::Ok) {
Quick_Set_Function();
}
if (ret == QMessageBox::Cancel) {
//
}
}
break;
case Qt::Key_D:
qDebug() << "Qt::Key_D";
if (Conf_User == User_Operator) {
Pri_Conf_WMessage(tr(" 当前用户模式为操作员 \n"\
"无权限进行保存和修改 "));
break;
}
if (Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 1) { // 电阻
if (WDLR->Pub_Conf_Station(QString(tr("Left")))) {
ui->Key_D->setStyleSheet
("background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"\
"stop: 0 #5B5F5F, stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_D->setText(tr("左清零"));
}
} else if ((Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 2) && (Board_DLR)) {
Board_DLR = 0;
label_Waring_MAG = new QLabel(this);
label_Waring_MAG->setGeometry(700, 0, 800, 600);
label_Waring_MAG->show();
WMAG->Pub_Conf_Set_MAG("3", 3);
WMAG->Pub_Conf_Set_MAG(" ", 6);
label_Waring_MAG->hide();
} else if ((Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 6)) {
label_Waring_MAG = new QLabel(this);
label_Waring_MAG->setGeometry(700, 0, 800, 600);
label_Waring_MAG->show();
WIMP->Pub_Conf_Set_IMP("", 7);
label_Waring_MAG->hide();
} else {
//
}
break;
case Qt::Key_E:
qDebug() << "Qt::Key_E";
if (Conf_User == User_Operator) {
Pri_Conf_WMessage(tr(" 当前用户模式为操作员 \n"\
"无权限进行保存和修改 "));
break;
}
SlOT_Button_Function_Judge(Qt::Key_B); // -进行保存
TabWidget_Changed = true; // -触发没有保存
if (Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 1) { // -电阻
if (WDLR->Pub_Conf_Station(QString(tr("Right")))) {
ui->Key_E->setStyleSheet
("background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"\
"stop: 0 #5B5F5F, stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_E->setText(tr("右清零"));
}
} else if (Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 3) { // -绝缘
IRACW_Compensate = TestIW_IR;
if (WIR->IR_If_Compensate(QString::number(Ini_ACW_And_IR))) {
ui->Key_E->setStyleSheet
("background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"\
"stop: 0 #5B5F5F, stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_E->setText(tr("未补偿"));
}
} else if (Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 4) { // -交耐
qDebug() << "交耐";
IRACW_Compensate = TestIW_ACW;
WACW->Pub_Conf_Set_ACW(QString::number(Ini_IR5000), 101);
if (WACW->ACW_If_Compensate(QString::number(Ini_ACW_And_IR))) {
ui->Key_E->setStyleSheet
("background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"\
"stop: 0 #5B5F5F, stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_E->setText(tr("未补偿"));
}
} else {
//
}
break;
default:
//
break;
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.7.19
* brief: 快速设置
******************************************************************************/
void w_Conf::Quick_Set_Function()
{
int i = 0, j = 0, x = 0;
Quick_Set = true; label_Waring->show();
label_Set->show();
ui->Key_A->hide();
ui->Key_B->hide();
ui->Key_C->hide();
ui->Key_D->hide();
ui->Key_E->hide();
ui->imp_button_add->hide();
ui->imp_button_cancel->hide();
ui->imp_button_finsh->hide();
ui->Button_ALL->hide();
for (i = 0; i < test_List.size(); i++) { // -快速设置选择项目
if (i != test_List.indexOf(test_List.at(i))) { // -去除重复选项
continue;
}
SlOT_Button_Conf_Judge(48+Test_Item.indexOf(test_List.at(i))); // -页面切换
if (Test_Item.indexOf(test_List.at(i)) == 1) { // -电阻
qDebug() << "DLR Quick_Set";
WDLR->Pub_Conf_Set_DLR(Ini.DLR, 6);
// if (WDLR->DLR_Compensate_Left) {
// WDLR->DLR_Compensate_Left = false;
ui->Key_D->setStyleSheet("background: qlineargradient"\
"(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #5B5F5F, "\
"stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_D->setText(tr("左清零"));
// }
// if (WDLR->DLR_Compensate_Right) {
// WDLR->DLR_Compensate_Right = false;
ui->Key_E->setStyleSheet("background: qlineargradient"\
"(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #5B5F5F, "\
"stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_E->setText(tr("右清零"));
// }
for (j = 7; j > 0; j--) { // 档位选择
usleep(50000);
usleep(50000);
usleep(50000);
usleep(50000);
usleep(50000);
WDLR->Pub_Conf_Set_DLR(QString::number(j), 4);
WDLR->Pub_Conf_Set_DLR("", 5);
Board_DLR = 0;
QEventLoop DLRloop; // 进行延时等待结果
for (x = 0; x < 10; x++) {
QTimer::singleShot(300, &DLRloop, SLOT(quit()));
DLRloop.exec();
if (Board_DLR == 1) { // 设置电阻
x = 21;
}
}
usleep(50000);
usleep(50000);
usleep(50000);
usleep(50000);
usleep(50000);
}
QEventLoop DLRloop;
QTimer::singleShot(300, &DLRloop, SLOT(quit()));
DLRloop.exec();
for (j = 0; j < 8; j++) {
if (!(AutoSet[j].isEmpty())) {
WDLR->on_AutoSet(AutoSet[j]);
AutoSet[j].clear();
}
}
WDLR->Pub_Conf_Set_DLR("", 9);
} else if (Test_Item.indexOf(test_List.at(i)) == 2) { // -反嵌
qDebug() << "MAG Quick_Set";
int cutt; cutt = 0;
WMAG->Pub_Conf_Set_MAG("19", 10);
WMAG->Pub_Conf_Set_MAG(Ini.MAG, 5);
SlOT_Button_Function_Judge(Qt::Key_D);
QEventLoop eventloop;
for (j = 0; j < 100; j++) {
QTimer::singleShot(100, &eventloop, SLOT(quit()));
eventloop.exec();
if (Board_DLR == 1) {
cutt++;
if (cutt == (Ini.MAG.size()/2)) {
j = 101;
}
}
}
} else if (Test_Item.indexOf(test_List.at(i)) == 3) { // -绝缘
qDebug() << "IR Quick_Set";
WIR->Pub_Conf_Set_IR("", 3);
ui->Key_E->setText(tr("未补偿"));
} else if (Test_Item.indexOf(test_List.at(i)) == 4) { // -交耐
qDebug() << "ACW Quick_Set";
WACW->Pub_Conf_Set_ACW("", 3);
ui->Key_E->setText(tr("未补偿"));
} else if (Test_Item.indexOf(test_List.at(i)) == 5) { // -直耐
qDebug() << "DCW Quick_Set";
} else if (Test_Item.indexOf(test_List.at(i)) == 6) { // -匝间
qDebug() << "IMP Quick_Set";
WIMP->Pub_Conf_Set_IMP("19", 13);
WIMP->Pub_Conf_Set_IMP(Ini.IMP, 6); // 匝间-设置电压数值
SlOT_Button_Function_Judge(Qt::Key_D); // 匝间-采集波形
QEventLoop eventloop;
for (j = 0; j < 300; j++) {
QTimer::singleShot(100, &eventloop, SLOT(quit()));
eventloop.exec();
if (WIMP->Pub_Conf_GetSample(3)) {
j = 301;
}
}
} else if (Test_Item.indexOf(test_List.at(i)) == 7) { // -电参
qDebug() << "PWR Quick_Set";
} else if (Test_Item.indexOf(test_List.at(i)) == 8) { // -电感
qDebug() << "INDL Quick_Set";
WINDL->Pub_Conf_Set_INDL(Ini.IINDL, 1, 6); // 电感设置数值
WINDL->Pub_Conf_Set_INDL("", 1, 8);
WINDL->Pub_Conf_Set_INDL("", 1, 4);
Board_INDL = 0;
QEventLoop eventloop;
for (j = 0; j < 100; j++) {
QTimer::singleShot(100, &eventloop, SLOT(quit()));
eventloop.exec();
if (Board_INDL == 1) {
Board_INDL = 0;
j = 98;
}
}
Board_INDL = 0;
WINDL->Pub_Conf_Set_INDL("", 1, 3);
WINDL->Pub_Conf_Set_INDL("", 1, 4);
for (j = 0; j < 100; j++) {
QTimer::singleShot(100, &eventloop, SLOT(quit()));
eventloop.exec();
if (Board_INDL == 1) {
Board_INDL = 0;
j = 101;
}
}
} else if (Test_Item.indexOf(test_List.at(i)) == 9) { // -堵转
qDebug() << "BLOCK Quick_Set";
} else if (Test_Item.indexOf(test_List.at(i)) == 10) { // -低启
qDebug() << "LVS Quick_Set";
}
QEventLoop eventloop;
QTimer::singleShot(600, &eventloop, SLOT(quit())); // -延时等待,暂留视觉
eventloop.exec();
qApp->processEvents();
SlOT_Button_Function_Judge(Qt::Key_B); // -快速设置保存
}
Quick_Set = false;
label_Waring->hide();
label_Set->hide();
SlOT_Button_Conf_Judge(Qt::Key_0); // 设置完成后返回设置首页
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 同步数据库与设置界面
******************************************************************************/
void w_Conf::Sync_Conf()
{
int i = 0, j = 0;
QStringList BLDC_Noload_Data;
QStringList BLDC_PG_Data;
Get_SqlData(); // -读取数据库文件
Init_Conf_Interface(); // -初始化设置界面
for (i = 0; i < Ini_Proj.size(); i++) {
Conf_ProjKey(Ini_Proj.at(i).toInt(), true);
}
Save_Ini_DateFile();
Init_Conf_file(currentFile.size(), currentFile); // -初始化文件名称
qApp->processEvents();
if (ui->stackedWidget->count() > 1) {
for (i = ui->stackedWidget->count(); i >= 1; i--) {
switch (Ini_Proj.at(i-1).toInt()) {
case 1:
qDebug() << "removeWidget(WDLR)";
ui->stackedWidget->removeWidget(WDLR);
break;
case 2:
qDebug() << "removeWidget(WMAG)";
ui->stackedWidget->removeWidget(WMAG);
break;
case 3:
qDebug() << "removeWidget(WIR)";
ui->stackedWidget->removeWidget(WIR);
break;
case 4:
qDebug() << "removeWidget(WACW)";
ui->stackedWidget->removeWidget(WACW);
break;
case 5:
qDebug() << "removeWidget(WDCW)";
ui->stackedWidget->removeWidget(WDCW);
break;
case 6:
qDebug() << "removeWidget(WIMP)";
ui->stackedWidget->removeWidget(WIMP);
break;
case 7:
qDebug() << "removeWidget(WPWR)";
ui->stackedWidget->removeWidget(WPWR);
break;
case 8:
qDebug() << "removeWidget(WINDL)";
ui->stackedWidget->removeWidget(WINDL);
break;
case 9:
qDebug() << "removeWidget(WBLOCK)";
ui->stackedWidget->removeWidget(WBLOCK);
break;
case 10:
qDebug() << "removeWidget(LVS)";
ui->stackedWidget->removeWidget(WLVS);
case 11:
qDebug() << "removeWidget(WPG)";
ui->stackedWidget->removeWidget(WPG);
case 12:
qDebug() << "removeWidget(WLOAD)";
ui->stackedWidget->removeWidget(WLOAD);
case 13:
qDebug() << "removeWidget(WNoLoad)";
ui->stackedWidget->removeWidget(WNoLoad);
case 14:
qDebug() << "removeWidget(WBEMF)";
ui->stackedWidget->removeWidget(WBEMF);
break;
default:
qDebug() << "removeWidget(----NULL)";
break;
}
}
}
// struct timeval start, stop, dif f;
for (i = 1; i < Ini_Proj.size(); i++) {
// gettimeofday(&start, 0);
switch (Ini_Proj.at(i).toInt()) {
case 1:
qDebug() << "Init_DLR";
WDLR = new Widget_DLR(this);
ui->stackedWidget->addWidget(WDLR);
if (RES.size() < 153) {
qDebug() << "RES Error" << RES.size();
for (j = RES.size(); j < 153; j++) {
RES.append("0");
}
} else {
qDebug() << "RES Ok";
}
WDLR->Copy_DLR_List = RES; // DLR数据 复制
WDLR->Pub_Conf_Set_DLR(QString::number(Ini_DCR15), 1);
WDLR->Pub_Conf_Set_DLR(QString::number(Ini_DCR_Balance), 13);
connect(WDLR, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 2:
qDebug() << "Init_MAG";
WMAG = new Widget_MAG(this);
ui->stackedWidget->addWidget(WMAG);
if (OPP.size() < 6560) {
qDebug() << "OPP Error" << OPP.size();
for (j = OPP.size(); j < 6560; j++) {
OPP.append("0");
}
} else {
qDebug() << "OPP Ok";
}
WMAG->Copy_MAG_List = OPP; // MAG数据 复制
WMAG->Pub_Conf_Set_MAG(QString::number(Ini_Mag_Hide), 1);
connect(WMAG, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 3:
qDebug() << "Init_IR";
WIR = new Widget_IR(this);
ui->stackedWidget->addWidget(WIR);
if (INS.size() < 100) { // 增加相间绝缘
QStringList list;
for (j = 0; j < 200; j++) {
list.append("0");
}
INS.append(list);
}
if (INS.size() < 229) {
qDebug() << "INS Error" << INS.size();
for (j = INS.size(); j < 229; j++) {
INS.append("0");
}
} else {
qDebug() << "INS Ok";
}
WIR->Copy_IR_List = INS; // IR数据 复制
WIR->Pub_Conf_Set_IR(QString::number(Ini_ACW_And_IR), 1);
connect(WIR, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 4:
qDebug() << "Init_ACW";
WACW = new Widget_ACW(this);
ui->stackedWidget->addWidget(WACW);
if (ACV.size() < 100) { // 增加相间耐压
QStringList list;
for (j = 0; j < 200; j++) {
list.append("0");
}
ACV.append(list);
}
if (ACV.size() < 226) {
qDebug() << "ACV Error" << ACV.size();
for (j = ACV.size(); j < 226; j++) {
ACV.append("0");
}
} else {
qDebug() << "ACV Ok";
}
WACW->Copy_ACW_List = ACV; // ACW数据 复制
WACW->Pub_Conf_Set_ACW(QString::number(Ini_IR5000), 101);
WACW->Pub_Conf_Set_ACW(QString::number(Ini_ACW_And_IR), 1);
connect(WACW, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 5:
qDebug() << "Init_DCW";
WDCW = new Widget_DCW(this);
ui->stackedWidget->addWidget(WDCW);
WDCW->Copy_DCW_List = DCV; // DCW数据 复制
WDCW->Init_DCW();
connect(WDCW, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 6:
qDebug() << "Init_IMP";
WIMP = new Widget_IMP(this);
ui->stackedWidget->addWidget(WIMP);
if (ITT.size() < 6561) {
qDebug() << "ITT Error" << ITT.size();
ITT.clear();
for (j = ITT.size(); j < 6561; j++) {
ITT.append("0");
}
} else {
qDebug() << "ITT Ok";
}
WIMP->Copy_IMP_List = ITT; // IMP数据 复制
WIMP->Pub_Conf_Set_IMP(QString::number(Ini_IMP5000), 101);
WIMP->Pub_Conf_Set_IMP(Ini_ActiveFile, 1);
if (Ini_Set_ImpVolt == QString(tr("noback"))) { // 匝间初始化-反馈-不反馈-
WIMP->Pub_Conf_Set_IMP("", 12);
}
connect(WIMP, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 7:
qDebug() << "Init_WPWR";
WPWR = new Widget_PWR(this);
ui->stackedWidget->addWidget(WPWR);
if (PWR.size() < 495) {
qDebug() << "PWR Error" << PWR.size();
for (j = PWR.size(); j < 495; j++) {
PWR.append("0");
}
} else {
qDebug() << "PWR Ok";
}
WPWR->Copy_PWR_List = PWR;
WPWR->Pub_Conf_Set_PWR(Ini_Motor, 1);
connect(WPWR, SIGNAL(canSend(can_frame, int)), this, SLOT(SlOT_CanSendFrame_PWR(can_frame, int)));
WPWR->Pub_Conf_Set_PWR(QString::number(Ini_Power_Chose), 4);
WPWR->Pub_Conf_Set_PWR(QString::number(Ini_Pwr_Turn), 6);
break;
case 8:
qDebug() << "Init_WINDL";
WINDL = new Widget_INDL(this);
ui->stackedWidget->addWidget(WINDL);
if (INDL.size() < 495) {
qDebug() << "INDL Error" << INDL.size();
for (j = INDL.size(); j < 495; j++) {
INDL.append("0");
}
} else {
qDebug() << "INDL Ok";
}
WINDL->Copy_INDL_List = INDL;
WINDL->Pub_Conf_Set_INDL("", 1, 1);
connect(WINDL, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
connect(WINDL, SIGNAL(Lable_Display()), this, SLOT(SlOT_Lable_Display()));
break;
case 9:
qDebug() << "Init_WBLOCK";
WBLOCK = new Widget_BLOCK(this);
ui->stackedWidget->addWidget(WBLOCK);
if (BLOCK.size() < 495) {
qDebug() << "BLOCK Error" << BLOCK.size();
for (j = BLOCK.size(); j < 495; j++) {
BLOCK.append("0");
}
} else {
qDebug() << "BLOCK Ok";
}
WBLOCK->Copy_BLOCK_List = BLOCK;
WBLOCK->Pub_Conf_Set_BLOCK("", 1, 1);
connect(WBLOCK, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
WBLOCK->Pub_Conf_Set_BLOCK(QString::number(Ini_Power_Chose), 1, 4);
break;
case 10:
qDebug() << "Init_WLVS";
WLVS = new Widget_LVS(this);
ui->stackedWidget->addWidget(WLVS);
if (LVS.size() < 495) {
qDebug() << "LVS Error" << LVS.size();
for (j = LVS.size(); j < 495; j++) {
LVS.append("0");
}
} else {
qDebug() << "LVS Ok";
}
WLVS->Copy_LVS_List = LVS;
WLVS->Pub_Conf_Set_LVS(QString(""), 1);
connect(WLVS, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
WLVS->Pub_Conf_Set_LVS(QString::number(Ini_Power_Chose), 4);
break;
case 11:
qDebug() << "Init_WHALL";
WPG = new Widget_BLDC_PG(this);
ui->stackedWidget->addWidget(WPG);
if (BLDCPG.size() < 300) {
qDebug() << "BLDCPG Error" << BLDCPG.size();
for (j = BLDCPG.size(); j < 300; j++) {
BLDCPG.append("0");
}
} else {
qDebug() << "BLDCPG Ok";
}
BLDC_PG_Data.clear();
BLDC_PG_Data.append(QString::number(Ini_BLDC_PG_Chose));
WPG->Copy_BLDCPG_List = BLDCPG;
WPG->Pub_Conf_Set_PG(BLDC_PG_Data, 1);
connect(WPG, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 12:
qDebug() << "Init_WLOAD";
WLOAD = new Widget_Load(this);
ui->stackedWidget->addWidget(WLOAD);
if (LOAD.size() < 200) {
qDebug() << "LOAD Error" << LOAD.size();
for (j = LOAD.size(); j < 200; j++) {
LOAD.append("0");
}
} else {
qDebug() << "LOAD Ok";
}
WLOAD->Copy_LOAD_List = LOAD;
WLOAD->Pub_Conf_Set_LOAD(QString(""), 1);
connect(WLOAD, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 13:
qDebug() << "Init_WNoLoad";
WNoLoad = new Widget_Noload(this);
ui->stackedWidget->addWidget(WNoLoad);
if (NOLOAD.size() < 200) {
qDebug() << "NOLOAD Error" << NOLOAD.size();
for (j = NOLOAD.size(); j < 200; j++) {
NOLOAD.append("0");
}
} else {
qDebug() << "NOLOAD Ok";
}
BLDC_Noload_Data.clear();
BLDC_Noload_Data.append(QString::number(Ini_BLDC_Start_Mode));
BLDC_Noload_Data.append(QString::number(Ini_BLDC_Start_Item));
WNoLoad->Copy_NOLOAD_List = NOLOAD;
WNoLoad->Pub_Conf_Set_NOLOAD(BLDC_Noload_Data, 1);
connect(WNoLoad, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 14:
qDebug() << "Init_WBEMF";
WBEMF = new Widget_BEMF(this);
ui->stackedWidget->addWidget(WBEMF);
if (BEMF.size() < 200) {
qDebug() << "BEMF Error" << BEMF.size();
for (j = BEMF.size(); j < 200; j++) {
BEMF.append("0");
}
} else {
qDebug() << "BEMF Ok";
}
WBEMF->Copy_BEMF_List = BEMF;
WBEMF->Pub_Conf_Set_BEMF(QString(""), 1);
connect(WBEMF, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
default:
//
break;
}
// gettimeofday(&stop, 0);
// timeval_subtract(&dif f, &start, &stop);
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.7.19
* brief: 计时操作
******************************************************************************/
int w_Conf::timeval_subtract(struct timeval* result, struct timeval* x, struct timeval* y)
{
if (x->tv_sec > y->tv_sec )
return -1;
if ((x->tv_sec == y->tv_sec) && (x->tv_usec > y->tv_usec) )
return -1;
result->tv_sec = (y->tv_sec-x->tv_sec);
result->tv_usec = (y->tv_usec-x->tv_usec);
if (result->tv_usec < 0) {
result->tv_sec--;
result->tv_usec += 1000000;
}
return 0;
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 同步测试界面参数
******************************************************************************/
void w_Conf::Sync_Test_Widget()
{
signed int i = 0;
int j = 0;
QString name_list;
QStringList Back_Data;
strTest.clear(); // -测试项目
strParam.clear(); // -测试参数
sql_Test.clear(); // -测试数据库保存项目
for (i = 0; i < test_Inifile.size(); i++) {
for (j = 1; j < Ini_Proj.size(); j++) {
if (test_Inifile.at(i).toInt() == Ini_Proj[j].toInt()) {
break;
qDebug() << "break";
}
if (j == (Ini_Proj.size()-1)) {
test_Inifile.removeAt(i);
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setValue(name_list, test_Inifile);
i--;
}
}
}
Test_Occur_Debug = CONF.at(12).toInt();
serial_number = CONF.at(14);
Conf_Test = test_Inifile;
int remove_number = 0;
int size = Conf_Test.size();
for (i = 0; i < size; i++) {
remove_number++;
qDebug() << "1111111" << ui->test->item(i, 0)->textColor().name();
if (ui->test->item(i, 0)->textColor().name() != "#008000") {
// 绿色字体的下发
Conf_Test.removeAt(remove_number-1);
remove_number--;
}
}
for (i = 0; i < Conf_Test.size(); i++) {
switch (Conf_Test.at(i).toInt()) {
case 1: // 电阻
strRES = RES;
Back_Data = WDLR->DCR_Test_Param();
strTest.append(Back_Data.mid(4, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(4 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
strDLR_UpDown = Back_Data.mid(4 + Back_Data.at(0).toInt() + \
Back_Data.at(1).toInt(), Back_Data.at(2).toInt());
sql_Test.append(Back_Data.mid(4 + Back_Data.at(0).toInt() + \
Back_Data.at(1).toInt() + Back_Data.at(2).toInt()));
break;
case 2: // 反嵌
strOPP = OPP;
Back_Data = WMAG->MAG_Test_Param(Ini_Mag_Hide);
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 3: // 绝缘
strIR = INS;
Back_Data = WIR->IR_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 4: // 交耐
strACW = ACV;
Back_Data = WACW->ACW_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 5: // 直耐
//
break;
case 6: // 匝间
strITT = ITT;
Back_Data = WIMP->IMP_Test_Param(Ini_imp_min);
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
strIMP_Param = Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt());
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 7: // 电参
strPWR = PWR;
Back_Data = WPWR->PWR_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 8: // 电感
strINDL = INDL;
Back_Data = WINDL->INDL_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 9: // -堵转
strBLOCK = BLOCK;
Back_Data = WBLOCK->BLOCK_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 10: // -低启
strLVS = LVS;
Back_Data = WLVS->LVS_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 11: // -霍尔
strPG = BLDCPG;
Back_Data = WPG->PG_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 12: // -负载
strLOAD = LOAD;
Back_Data = WLOAD->LOAD_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 13: // -空载
strNOLOAD = NOLOAD;
Back_Data = WNoLoad->NOLOAD_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 14: // -反电动势
strBEMF = BEMF;
Back_Data = WBEMF->BEMF_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
default:
//
break;
}
}
QString Check_strTest; // -建立字符串, 字符串列表转化为字符串
for (i = 0; i < strTest.size(); i++) {
Check_strTest += strTest.at(i);
}
signed int si;
qDebug() << "2018-7-11 Conf_Test" << Check_strTest <<Conf_Test;
for (si = 0; si < Conf_Test.size(); si++) {
switch (Conf_Test.at(si).toInt()) {
case 1:
if (Check_strTest.indexOf(QString(tr("电阻"))) < 0) {
Conf_Test.removeAt(si);
si--;
}
break;
case 2:
if ((Check_strTest.indexOf(QString(tr("反嵌"))) < 0) && \
(Check_strTest.indexOf(QString(tr("磁旋"))) < 0)) {
Conf_Test.removeAt(si);
si--;
}
break;
case 3:
if (Check_strTest.indexOf(QString(tr("绝缘"))) < 0) {
Conf_Test.removeAt(si);
si--;
}
break;
case 4:
if (Check_strTest.indexOf(QString(tr("交耐"))) < 0) {
Conf_Test.removeAt(si);
si--;
}
break;
case 5:
//
break;
case 6:
if (Check_strTest.indexOf(QString(tr("匝间")), 0, Qt::CaseInsensitive) < 0) {
Conf_Test.removeAt(si);
si--;
}
break;
case 7:
//
break;
case 8:
if (Check_strTest.indexOf(QString(tr("电感"))) < 0) {
Conf_Test.removeAt(si);
si--;
}
break;
case 9:
//
break;
case 10:
//
break;
case 11:
//
break;
case 12:
//
break;
case 13:
//
break;
case 14:
//
break;
default:
break;
}
}
qDebug() << "2018-7-11 Conf_Test" << Conf_Test;
qDebug() << "sql_Test--------" << sql_Test;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.7.19
* brief: 保存配置Ini文件
******************************************************************************/
void w_Conf::Save_Ini_DateFile()
{
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
set_Test_File.setValue("DateFile/datefile", DateFile);
set_Test_File.setValue("DateFile/currentfile", currentFile);
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 从配置文件中,读取设置数据
******************************************************************************/
void w_Conf::Get_SqlData()
{
int i = 0;
QStringList Allocation_list; // -默认 Allocation/Item
Allocation_list.clear();
Allocation_list.append("13");
Allocation_list.append("14");
Allocation_list.append("0");
Allocation_list.append("0");
Allocation_list.append("0");
Allocation_list.append("0");
Allocation_list.append("1");
QStringList Password_list; // -默认 Password/Text
Password_list.clear();
Password_list.append("6");
Password_list.append("456");
Password_list.append("789");
QStringList System_list; // 默认 System/Text
System_list.clear();
System_list.append("9"); // -蜂鸣器的档位
System_list.append("0.1"); // -合格时间
System_list.append("0.3"); // -不合格时间
System_list.append("9"); // -Led档位
System_list.append("0"); // -启动模式
System_list.append("1"); // -管理员
QString parameter_set;
QSettings *set_Sys = new QSettings(Sys_path, QSettings::IniFormat);
set_Sys->setIniCodec("GB18030");
Ini_Number = set_Sys->value("Allocation/All", "7").toString().toInt();
Ini_Proj_Real = set_Sys->value("Allocation/Item", Allocation_list).toStringList();
// Ini_Proj_Real.append(tr("14"));
Ini_Proj = set_Sys->value("Allocation/Item",
Allocation_list).toStringList().mid(5, Ini_Number);
// Ini_Proj.append(tr("14"));
Ini_Password = set_Sys->value("Password/Text", Password_list).toStringList();
Ini_SQL_Enable = set_Sys->value("Sql/Text", "disable").toString();
Ini_Factory = set_Sys->value("Factory/text", "V-0.0.0").toString();
Ini_Set_ImpVolt = set_Sys->value("impvolt/text", "noback").toString();
Ini_IRHostJudge = set_Sys->value("IRHostJudge/text", "0").toInt();
Ini_Motor = set_Sys->value("System/PG", "Common").toString();
Ini_DCR_Balance = set_Sys->value("System/Unbalance", "1").toInt();
Ini_Task_Table = set_Sys->value("Sql/Task_Table", "1").toString();
Ini_Pwr_Turn = set_Sys->value("System/Shan_Turn", "0").toInt();
Ini_Power_Chose = set_Sys->value("power/Text", "0").toInt();
// -电源选择方式-默认为0
Ini_Mag_Hide = set_Sys->value("magshapehide/text", "0").toInt();
// -反嵌的波形是否隐藏-默认为0
Ini_Udp_Enable = set_Sys->value("UDP/text", "0").toInt();
// -UDP上传-默认为0
Ini_ACW_And_IR = set_Sys->value("commonACW/text", "0").toInt();
// -设置相间耐压和普通耐压的转换-默认为0
Ini_System = set_Sys->value("System/Text", System_list).toStringList();
Ini_ActiveFile = set_Sys->value("ActiveFile/file", "Base_File").toString();
// 获取当前文件
Ini_imp_min = set_Sys->value("imp_min/area_diff", "0").toInt();
// -设置匝间下限
Ini_BLDC_Start_Mode = set_Sys->value("BLDC/Start_Mode", "0").toInt();
Ini_BLDC_Start_Item = set_Sys->value("BLDC/Start_Item", "0").toInt();
Ini_BLDC_PG_Chose = set_Sys->value("BLDC/PG_Chose", "0").toInt();
Out_Channel_6 = set_Sys->value("System/out6", "0").toInt();
Ini_IMP5000 = set_Sys->value("System/IMP5000", "0").toInt();
Ini_IR5000 = set_Sys->value("System/IR5000", "0").toInt();
Ini_DCR15 = set_Sys->value("System/dcr_Disable", "0").toInt();
system("sync");
delete set_Sys;
qDebug() << "Ini_Proj---------------------------->" << Ini_Proj;
Conf_User = Ini_System.at(5).toInt(); // 2017.6.7 添加使用用户
Ini_Factory = "A"+Ini_Factory;
ui->label_Text->setText(QString(tr("当前文件:")) + Ini_ActiveFile);
if ((Ini_SQL_Enable == "enable") && (same_ip_address) && (!isopend)) {
isopend = true;
if (sql_net.open_net_Sql("testodbc")) {
Singal_Conf_to_Main(QStringList(""), QString(""), 1, 3);
NetSQL_OpenOk = true;
SQL_Init = true;
SQL_Task.clear();
QSqlQuery query_net(sql_net.dbtwo); qDebug() << "Sql Init";
if (sql_net.dbtwo.tables().contains(Ini_Factory)) {
// -查询是否存在表,若不存在进行创建数据库
//
} else {
QString create = (QString(tr("create table %1 (id integer primary key, "\
"项目 nvarchar(50), 参数 nvarchar(50), 结果 nvarchar(50), "\
"判定 nvarchar(50), 配置 nvarchar(50), 项目1 nvarchar(50), "\
"项目2 nvarchar(50))")).arg(Ini_Factory));
query_net.exec(create);
} qDebug() << "Sql Init Finsh";
QString net_str = QString(tr("Select 生产线, 生产任务编号 from %1 "))\
.arg(Ini_Task_Table); //
query_net.exec(net_str);
while (query_net.next()) {
SQL_Task.append(query_net.value(0).toString().trimmed());
SQL_Task.append(query_net.value(1).toString().trimmed());
}
for (i = 0; i < SQL_Task.size()/2; i++) {
SQL_Produce_Plan->addItem(QWidget::tr("%1").arg(SQL_Task.at(i*2+0)));
SQL_Produce_Number->addItem(QWidget::tr("%1").arg(SQL_Task.at(i*2+1)));
}
SQL_Init = false;
SQL_Produce_Plan_textChanged(SQL_Produce_Plan->currentText());
} else {
NetSQL_OpenOk = false;
}
} else {
qDebug() << "SQL Disable";
}
QString Filename;
Filename = QString("/mnt/nandflash/AIP/ConfFile/%1.ini").arg(Ini_ActiveFile);
QSettings set_File(Filename, QSettings::IniFormat);
for (i = 0; i < parameter.size(); i++) {
parameter_set = QString("%1/value").arg(parameter[i]);
strList[i] = set_File.value(parameter_set).toStringList();
}
QSettings Add_File("/mnt/nandflash/AIP/AddFile.ini", QSettings::IniFormat);
Add_File.setIniCodec("UTF-8");
if (PWR == QStringList()) {
qDebug() << "PWR == NULL";
strList[7] = Add_File.value("PWR/value").toStringList();
}
if (INDL == QStringList()) {
qDebug() << "INDL == NULL";
strList[8] = Add_File.value("INDL/value").toStringList();
}
if (BLOCK == QStringList()) {
qDebug() << "BLOCK == NULL";
strList[9] = Add_File.value("BLOCK/value").toStringList();
}
if (LVS == QStringList()) {
qDebug() << "LVS == NULL";
strList[10] = Add_File.value("LVS/value").toStringList();
}
if (CONF.size() < 100) {
qDebug() << "CONF Error" << CONF.size();
for (i = CONF.size(); i < 150; i++) {
CONF.append("0");
}
} else {
qDebug() << "CONF Ok";
}
conf_c = CONF;
// 获取Test_File.ini文件(若不存在,建立ini文件)
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
QString name_list; name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setIniCodec("UTF-8");
test_Inifile = set_Test_File.value(name_list).toStringList();
qDebug() << "test_Inifile" << test_Inifile;
// -2016-12-9 在修改配置后,以前的测试文件必须删除,比如之前的-<测试项目>-有电参,
// 现在配置里面取消电参配置,在测试文件-<测试项目>-取消电参
for (i = 0; i < test_Inifile.size(); i++) {
if (Ini_Proj.indexOf(test_Inifile.at(i)) >= 0) {
//
} else {
test_Inifile.removeAt(i);
i--;
}
}
DateFile = set_Test_File.value("DateFile/datefile").toStringList();
currentFile = set_Test_File.value("DateFile/currentfile").toStringList();
/* QSqlQuery query(sql.db);
sql.db.transaction();
if (sql.isTabExst("TestDa", sql.db)) { // 若TestDa存在,必要时进行删除操作
} else {
QString create=tr("create table TestDa (id integer primary key,"\
"项目 Text,参数 Text,结果 Text,判定 Text,配置 Text,"\
"项目1 Text,项目2 Text)");
query.exec(create);
if (sdcard_exist) {
system("chmod +x /mnt/sdcard/aip.db");
} else {
system("chmod +x /mnt/nandflash/aip.db");
}
} */
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 初始化文件名称
******************************************************************************/
void w_Conf::Init_Conf_file(int row, QStringList file)
{
int i = 0;
ui->fileTab->setRowCount(0);
ui->fileTab->setColumnWidth(0, 135); // -初始化文件名称
if (row > 9) { // -设置文件和型号行数
ui->fileTab->setRowCount(row);
for (i = 0; i < row; i++) {
ui->fileTab->setRowHeight(i, 39);
}
} else {
ui->fileTab->setRowCount(9);
for (i = 0; i < 9; i++) {
ui->fileTab->setRowHeight(i, 39);
}
}
for (i = 0; i < row; i++) {
QTableWidgetItem *pItem = new QTableWidgetItem(file.at(i));
pItem->setTextAlignment(Qt::AlignCenter);
ui->fileTab->setItem(i, 0, pItem);
}
ui->fileTab->verticalScrollBar()->setValue(0);
checked_File = file;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2015.6.6
* brief: 可选项目 按键使能
******************************************************************************/
void w_Conf::Conf_ProjKey(int i, bool judge)
{
if (judge == false) {
btnGroup_Item->button(i)->hide();
} else {
btnGroup_Item->button(i)->show();
}
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 初始化设置界面
******************************************************************************/
void w_Conf::Init_Conf_Interface()
{
int i = 0;
ui->combConf1->setCurrentIndex(CONF[12].toInt()); // 遇不合格测试项目是否继续
ui->file_number->setText(CONF[14]);
if (model_Type.indexOf(CONF[13]) >= 0) {
if (CONF[13] == ui->MotorType->currentText()) {
on_MotorType_currentIndexChanged(model_Type.indexOf(CONF[13]));
} else {
ui->MotorType->setCurrentIndex(model_Type.indexOf(CONF[13]));
}
} else {
on_MotorType_currentIndexChanged(0);
}
ui->test->setRowCount(0);
ui->test->setGeometry(305, 20, 131, 39*14+(ui->test->horizontalHeader()->height()));
if ((test_Inifile.size()) >= 13) {
if (test_Inifile.size() <= 15) {
ui->test->setRowCount(test_Inifile.size()+1);
for (i = 0; i < (test_Inifile.size() + 1); i++) {
ui->test->setRowHeight(i, 39);
}
} else {
ui->test->setRowCount(16);
for (i = 0; i < (test_Inifile.size() + 1); i++) {
ui->test->setRowHeight(i, 39);
}
}
} else {
ui->test->setRowCount(13);
for (i = 0; i < 13; i++) {
ui->test->setRowHeight(i, 39);
}
}
Init_test_TableWidget();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2015.12.30
* brief: 初始化测试项目
******************************************************************************/
void w_Conf::Init_test_TableWidget()
{
int i = 0;
test_List.clear();
for (i = 0; i < test_Inifile.size(); i++) {
int item = test_Inifile[i].toInt();
test_List.append(Test_Item[item]);
QTableWidgetItem *pItem = new QTableWidgetItem;
pItem->setTextAlignment(Qt::AlignCenter);
pItem->setText(Test_Item[item]);
pItem->setTextColor(QColor("green"));
ui->test->setItem(i, 0, pItem);
}
qApp->processEvents();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2015.12.30
* brief: 将数据存入数据库
******************************************************************************/
void w_Conf::Save_SqlData()
{
qDebug() << "ui->stackedWidget->currentIndex()" << ui->stackedWidget->currentIndex();
qDebug() << Ini_Proj;
int num = Ini_Proj[ui->stackedWidget->currentIndex()].toInt();
QString Filename;
Filename = QString("/mnt/nandflash/AIP/ConfFile/%1.ini").arg(Ini_ActiveFile);
QSettings set_File(Filename, QSettings::IniFormat);
set_File.setValue(QString("%1/value").arg(parameter[num]), strList[num]);
}
/******************************************************************************
* version: 1.0
* author: SL
* date: 2016.4.15
* brief: 将配置数据存入数据库
******************************************************************************/
void w_Conf::Save_SystemConf_Data(int choose)
{
QSettings *configIniWrite = new QSettings(Sys_path, QSettings::IniFormat);
configIniWrite->setIniCodec("GB18030");
switch (choose) {
case 1:
configIniWrite->beginGroup("Allocation"); // -配置数据
configIniWrite->setValue("All", QString::number(Ini_Number));
configIniWrite->setValue("Item", QStringList(Ini_Proj_Real));
break;
case 2:
configIniWrite->beginGroup("System"); //系统数据
configIniWrite->setValue("Text", QStringList(Ini_System.mid(0, 6)));
break;
case 3:
configIniWrite->beginGroup("Password"); // -密码数据
configIniWrite->setValue("Text", QStringList(Ini_Password));
break;
default:
//
break;
}
system("sync");
configIniWrite->endGroup();
delete configIniWrite;
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 保存配置数据
******************************************************************************/
void w_Conf::Save_ConfData()
{
int i = 0; // -更新设置数据
Item_Widget->hide();
Conf_label_Hide->hide();
for (i = 0; i < 8; i++) {
CONF.replace(i, colorIdList[i]);
}
CONF.replace(12, QString::number(ui->combConf1->currentIndex()));
CONF.replace(13, ui->MotorType->currentText());
CONF.replace(14, ui->file_number->text());
}
void w_Conf::Set_Color(QString colr)
{
QString str;
colorIdList.replace(iColorBtn, colr);
colorIdList_C.replace(iColorBtn, colr);
if (colr == "#000000") {
str = QString("height:120px;width:95px;background-color:%1;color:white;").arg((colr));
} else {
str = QString("height:120px;width:95px;background-color:%1").arg((colr));
}
qColor_BtnList[iColorBtn]->setStyleSheet(str);
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2015.5.11
* brief: 设置提示保存
******************************************************************************/
void w_Conf::Save_Hint()
{
int i = 0, SetAddress = 0; // -初始状态 0
if (!TabWidget_Changed) {
return;
}
for (i = 0; i < (Ini_Number-5); i++) {
if ((Ini_Proj.at(i).toInt()) == index_c) {
SetAddress = i;
break;
}
}
if (SetAddress > Ini_Proj.size()) {
SetAddress = 0;
}
switch (Ini_Proj.at(SetAddress).toInt()) {
case 0:
qDebug() << "配置首页";
Save_ConfData();
if (CONF != conf_c) {
conf_c = CONF;
if (model_Type.indexOf(CONF[13]) >= 0) {
ui->MotorType->setCurrentIndex(model_Type.indexOf(CONF[13]));
} else {
ui->MotorType->setCurrentIndex(0); // -设定文件
}
Init_Conf_Interface();
}
break;
case 1:
qDebug() << "电阻";
WDLR->Pub_Conf_Set_DLR("", 3);
if (RES != WDLR->Copy_DLR_List) {
TabWidget_Changed = false;
}
break;
case 2:
qDebug() << "反嵌";
WMAG->Pub_Conf_Set_MAG("", 2);
if (OPP != WMAG->Copy_MAG_List) {
TabWidget_Changed = false;
}
break;
case 3:
qDebug() << "绝缘";
WIR->Pub_Conf_Set_IR("", 2);
if (INS != WIR->Copy_IR_List) {
TabWidget_Changed = false;
}
break;
case 4:
qDebug() << "交耐";
WACW->Pub_Conf_Set_ACW("", 2);
if (ACV != WACW->Copy_ACW_List) {
TabWidget_Changed = false;
}
break;
case 5:
qDebug() << "直耐";
WDCW->Save_DCW_Data();
if (DCV != WDCW->Copy_DCW_List) {
TabWidget_Changed = false;
}
break;
case 6:
qDebug() << "匝间";
WIMP->Pub_Conf_Set_IMP("", 4);
if (ITT != WIMP->Copy_IMP_List) {
TabWidget_Changed = false;
}
break;
case 7:
qDebug() << "电参";
WPWR->Pub_Conf_Set_PWR("", 2);
if (PWR != WPWR->Copy_PWR_List) {
TabWidget_Changed = false;
}
break;
case 8:
qDebug() << "电感";
WINDL->Pub_Conf_Set_INDL("", 1, 2);
if (INDL != WINDL->Copy_INDL_List) {
TabWidget_Changed = false;
}
qDebug() << "电感";
break;
case 9:
qDebug() << "堵转";
WBLOCK->Pub_Conf_Set_BLOCK("", 1, 2);
if (BLOCK != WBLOCK->Copy_BLOCK_List) {
TabWidget_Changed = false;
}
break;
case 10:
qDebug() << "低启";
WLVS->Pub_Conf_Set_LVS("", 2);
if (LVS != WLVS->Copy_LVS_List) {
TabWidget_Changed = false;
}
break;
case 11:
qDebug() << "霍尔";
WPG->Pub_Conf_Set_PG(QStringList(""), 2);
if (BLDCPG != WPG->Copy_BLDCPG_List) {
qDebug() << BLDCPG;
qDebug() << WPG->Copy_BLDCPG_List;
TabWidget_Changed = false;
}
break;
case 12:
qDebug() << "负载";
WLOAD->Pub_Conf_Set_LOAD("", 2);
if (LOAD != WLOAD->Copy_LOAD_List) {
TabWidget_Changed = false;
}
break;
case 13:
qDebug() << "空载";
WNoLoad->Pub_Conf_Set_NOLOAD(QStringList(""), 2);
if (NOLOAD != WNoLoad->Copy_NOLOAD_List) {
TabWidget_Changed = false;
}
break;
case 14:
WBEMF->Pub_Conf_Set_BEMF(QString(""), 2);
if (BEMF != WBEMF->Copy_BEMF_List) {
TabWidget_Changed = false;
}
qDebug() << "反电动势";
break;
default:
//
break;
}
if (TabWidget_Changed) { // -数据有改动
return;
}
ui->stackedWidget->setCurrentIndex(SetAddress); // 11.11 更改设置
QMessageBox message; //= new QMessageBox(this);
message.setWindowFlags(Qt::FramelessWindowHint);
message.setStyleSheet("QMessageBox{border:3px groove gray;}"\
"background-color: rgb(209, 209, 157);");
message.setText(tr(" 是否进行保存 \n "));
message.addButton(QMessageBox::Ok)->setStyleSheet
("border:none;height:30px;width:65px;"\
"border:5px groove gray;border-radius:10px;padding:2px 4px;");
message.addButton(QMessageBox::Cancel)->setStyleSheet
("border:none;height:30px;width:65px;border:5px groove gray;"\
"border-radius:10px;padding:2px 4px;");
message.setButtonText(QMessageBox::Ok, QString(tr("确 定")));
message.setButtonText(QMessageBox::Cancel, QString(tr("取 消")));
message.setIcon(QMessageBox::Warning);
int ret = message.exec();
if (ret == QMessageBox::Ok) {
SlOT_Button_Function_Judge(Qt::Key_B); // -触发保存
}
if (ret == QMessageBox::Cancel) {
switch (Ini_Proj.at(SetAddress).toInt()) {
case 0:
CONF = conf_c;
if (model_Type.indexOf(CONF[13]) >= 0) {
ui->MotorType->setCurrentIndex(model_Type.indexOf(CONF[13]));
} else {
ui->MotorType->setCurrentIndex(0); // -设定文件
}
Init_Conf_Interface();
break;
case 1:
WDLR->Copy_DLR_List = RES;
WDLR->Pub_Conf_Set_DLR(QString::number(Ini_DCR15), 1);
WDLR->Pub_Conf_Set_DLR(QString::number(Ini_DCR_Balance), 13);
break;
case 2:
WMAG->Copy_MAG_List = OPP;
WMAG->Pub_Conf_Set_MAG(QString::number(Ini_Mag_Hide), 1);
break;
case 3:
WIR->Copy_IR_List = INS;
WIR->Pub_Conf_Set_IR(QString::number(Ini_ACW_And_IR), 1);
break;
case 4:
WACW->Copy_ACW_List = ACV;
WACW->Pub_Conf_Set_ACW(QString::number(Ini_IR5000), 101);
WACW->Pub_Conf_Set_ACW(QString::number(Ini_ACW_And_IR), 1);
break;
case 5:
WDCW->Copy_DCW_List = DCV;
WDCW->Init_DCW();
break;
case 6:
WIMP->Copy_IMP_List = ITT;
WIMP->Pub_Conf_Set_IMP(QString::number(Ini_IMP5000), 101);
WIMP->Pub_Conf_Set_IMP(Ini_ActiveFile, 1);
break;
case 7:
qDebug() << "电参 保存";
WPWR->Copy_PWR_List = PWR;
WPWR->Pub_Conf_Set_PWR(Ini_Motor, 1);
WPWR->Pub_Conf_Set_PWR(QString::number(Ini_Pwr_Turn), 6);
break;
case 8:
WINDL->Copy_INDL_List = INDL;
WINDL->Pub_Conf_Set_INDL("", 1, 1);
qDebug() << "电感 保存";
break;
case 9:
qDebug() << "堵转 保存";
WBLOCK->Copy_BLOCK_List = BLOCK;
WBLOCK->Pub_Conf_Set_BLOCK("", 1, 1);
break;
case 10:
qDebug() << "低启 保存";
WLVS->Copy_LVS_List = LVS;
WLVS->Pub_Conf_Set_LVS(QString(""), 1);
break;
case 11:
qDebug() << "霍尔 保存";
break;
case 12:
qDebug() << "负载 保存";
break;
case 13:
qDebug() << "空载 保存";
break;
case 14:
qDebug() << "反电动势 保存";
break;
default:
//
break;
}
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.6.6
* brief: 选定 测试项目
******************************************************************************/
void w_Conf::on_test_clicked(const QModelIndex &index)
{
int i = 0;
btnGroup_Item->button(0)->hide();
btnGroup_Item->button(20)->hide();
Item_Chose_Box->hide();
Item_Chose_Box->setChecked(true);
if ((index.row() + 1) <= (test_Inifile.size())) {
btnGroup_Item->button(0)->show();
btnGroup_Item->button(20)->show();
Item_Chose_Box->show();
if (ui->test->item(index.row(), 0)->textColor().name() != "#008000") {
Item_Chose_Box->setChecked(false);
}
}
for (i = 1; i <= 10; i++) { // -设置组不能超过--两组
if (test_Inifile.indexOf(QString::number(i)) < 0) {
continue;
}
if (test_Inifile.indexOf(QString::number(i), \
(1+test_Inifile.indexOf(QString::number(i)))) >= 0) {
btnGroup_Item->button(i)->hide();
}
}
remove_row = index.row();
Conf_label_Hide->show();
Item_Widget->show(); Item_Widget->raise();
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 添加文件
******************************************************************************/
void w_Conf::on_fileBtnAdd_clicked()
{
int i = 0;
char copystr[256];
QString currentDateTime = QDateTime::currentDateTime().toString\
("yyyy-MM-dd hh:mm:ss"); // -设置显示格式
if (ui->fileEdit1->text() != NULL) {
for (i = 0; i < currentFile.size(); i++) {
if (ui->fileEdit1->text() == currentFile.at(i)) {
ui->label_Text->setText(tr("型号名称重復"));
break;
}
}
if (i == currentFile.size()) {
currentFile.append(ui->fileEdit1->text());
DateFile.append(currentDateTime);
Save_Ini_DateFile();
Init_Conf_file(currentFile.size(), currentFile);
ui->fileTab->verticalScrollBar()->setValue(ui->fileTab->rowCount());
//更新数据
sprintf(copystr, "touch /mnt/nandflash/AIP/ConfFile/%s.ini", \
QString(ui->fileEdit1->text()).toUtf8().data());
system(copystr);
sprintf(copystr, "chmod +x /mnt/nandflash/AIP/ConfFile/%s.ini", \
QString(ui->fileEdit1->text()).toUtf8().data());
system(copystr);
QString Filename; Filename = QString("/mnt/nandflash/AIP/ConfFile/%1.ini").\
arg(ui->fileEdit1->text());
QSettings set_File(Filename, QSettings::IniFormat);
qDebug() << "11";
for (i = 0; i < parameter.size(); i++) {
set_File.setValue(QString("%1/value").arg(parameter[i]), strList[i]);
}
qDebug() << "22";
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
set_Test_File.setValue(QString("Test_File/%1").arg \
(ui->fileEdit1->text()), test_Inifile);
ui->label_Text->setText(QString(tr("当前文件:")) + Ini_ActiveFile);
qDebug() << "33";
on_fileTab_cellClicked(currentFile.size()-1, 0);
}
ui->fileEdit1->clear();
} else {
Pri_Conf_WMessage(QString(tr("请输入型号名称")));
}
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 删除文件
******************************************************************************/
void w_Conf::on_fileBtnDel_clicked()
{
char copystr[256];
ui->fileTab->currentRow();
if (currentFile.at(0) != "Base_File") {
currentFile.removeAt(0); DateFile.removeAt(0);
Save_Ini_DateFile();
sprintf(copystr, "rm /mnt/nandflash/AIP/ConfFile/%s.ini", \
QString(Ini_ActiveFile).toUtf8().data());
system(copystr);
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
set_Test_File.remove(QString("Test_File/%1").arg(Ini_ActiveFile));
Init_Conf_file(currentFile.size(), currentFile);
on_fileTab_cellClicked(0, 0);
} else if (currentFile.at(0) == "Base_File") {
Pri_Conf_WMessage(QString(tr("Base_File不能删除 ")));
} else {
//
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.1
* brief: Can发送数据 触发
******************************************************************************/
void w_Conf::SlOT_CanSendFrame(can_frame frame)
{
emit canSend(frame, 88); // -总触发
}
void w_Conf::SlOT_CanSendFrame_PWR(can_frame frame,int Usart) {
if (Usart==1) {
PWR_Test_Usart = true;
}
else {
}
emit canSend(frame,88); // 总触发
qDebug()<<"下发";
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.19
* brief: 电感清0
******************************************************************************/
void w_Conf::SlOT_Lable_Display()
{
lable_Zero->show();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.8
* brief: 温度进行补偿
******************************************************************************/
void w_Conf::DLR_Compensate_Back(QStringList list)
{
int DLR_Compensate = 0;
DLR_Compensate = WDLR->Pub_Conf_DLR_Compensate(list);
if (DLR_Compensate == 1) {
ui->Key_D->setStyleSheet("background:#00FF00; color:rgb(0, 0, 0);");
ui->Key_D->setText(tr("左OK")); // -已补偿
} else if (DLR_Compensate == 2) {
ui->Key_D->setStyleSheet("background: qlineargradient"\
"(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #5B5F5F, "\
"stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_D->setText(tr("左清零")); // -未补偿
Pri_Conf_WMessage(tr(" 左工位补偿错误 "));
} else if (DLR_Compensate == 3) {
ui->Key_E->setStyleSheet("background:#00FF00; color:rgb(0, 0, 0);");
ui->Key_E->setText(tr("右OK")); // -已补偿
} else if (DLR_Compensate == 4) {
ui->Key_E->setStyleSheet("background: qlineargradient"\
"(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #5B5F5F, "\
"stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_E->setText(tr("右清零")); // -未补偿
Pri_Conf_WMessage(tr(" 右工位补偿错误 "));
} else {
//
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.10
* brief: 设置操作员和管理者
******************************************************************************/
void w_Conf::Conf_Set_User(int value)
{
int id = value/1000;
int changer_number = value%1000;
if (Conf_User == User_Administrators) {
ui->label_User->hide(); // -可以设置
ui->fileEdit1->setEnabled(true);
ui->fileBtnAdd->setEnabled(true);
ui->fileBtnCheck->setEnabled(true);
ui->fileBtnDel->setEnabled(true);
} else {
//
}
if ((Conf_User == User_Operator) && (!conf_Waring)) {
ui->label_User->show(); // -不可以设置
ui->label_User->raise();
ui->fileEdit1->setDisabled(true);
ui->fileBtnAdd->setDisabled(true);
ui->fileBtnCheck->setDisabled(true);
ui->fileBtnDel->setDisabled(true);
} else {
//
}
if (changer_number != 0) {
on_fileTab_cellClicked(changer_number, 0);
} else {
//
}
ui->imp_button_add->hide();
ui->imp_button_cancel->hide();
ui->imp_button_finsh->hide();
if (id < 100) {
if((Conf_User==User_Operator)&&(!conf_Waring)) {
qDebug()<<"进行移动";
ui->label_User->setGeometry(0,0,721,600);
ui->label_User->move(0,0);
}
SlOT_Button_Conf_Judge(48+id); // -进入到设置首页
} else {
ui->label_User->setGeometry(299,0,401,600);
SlOT_Button_Conf_Judge(48); // -进入到设置首页
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.19
* brief: 配置查询文件和型号
******************************************************************************/
void w_Conf::on_fileBtnCheck_clicked()
{
int i = 0;
int Error_Flag = 0;
QStringList Check_File;
if (ui->fileEdit1->text() == "") {
Error_Flag = 1;
} else if (ui->fileEdit1->text() != "") {
Check_File.clear();
for (i = 0; i < currentFile.size(); i++) {
if (!(ui->fileTab->item(i, 0) == NULL)) {
if (ui->fileTab->item(i, 0)->text().contains\
(ui->fileEdit1->text(), Qt::CaseInsensitive)) {
Check_File.append(ui->fileTab->item(i, 0)->text());
Error_Flag = 2;
}
}
}
if (Error_Flag == 2) {
Init_Conf_file(Check_File.size(), Check_File);
}
} else {
//
}
if (Error_Flag == 0) {
Pri_Conf_WMessage(tr(" 当前查询不存在 "));
}
if (Error_Flag == 1) {
Save_Ini_DateFile();
Init_Conf_file(currentFile.size(), currentFile);
}
ui->fileEdit1->clear(); // -文件和型号清空
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.19
* brief: 设置警告弹出框
******************************************************************************/
void w_Conf::Pri_Conf_WMessage(QString Waring_Text)
{
conf_Waring = true; label_Waring->show();
QMessageBox *message = new QMessageBox(this);
message->setWindowFlags(Qt::FramelessWindowHint);
message->setStyleSheet("QMessageBox{border: gray;border-radius: 10px;"\
"padding:2px 4px;background-color: gray;height:390px;width:375px;}");
message->setText("\n"+Waring_Text+"\n");
message->addButton(QMessageBox::Ok)->setStyleSheet("height:39px;width:75px;"\
"border:5px groove;border:none;border-radius:10px;padding:2px 4px;");
message->setButtonText(QMessageBox::Ok, QString(tr("确 定")));
message->setIcon(QMessageBox::Warning);
message->exec();
conf_Waring = false; label_Waring->hide();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.19
* brief: 单击文件列表 更换数据管理型号
******************************************************************************/
void w_Conf::on_fileTab_cellClicked(int row, int column)
{
int i = 0, Count = 0;
if (!Clicked) {
return;
}
column = 0;
label_Waring->show();
Clicked = false;
if (Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 0) {
if (row < 0) {
label_Waring->hide();
Clicked = true;
return;
}
if (row >= (checked_File.size())) {
label_Waring->hide();
Clicked = true;
return;
}
if (checked_File.at(row) == Ini_ActiveFile) {
label_Waring->hide();
Clicked = true;
return;
}
for (i = 0; i < currentFile.size(); i++) {
if (ui->fileTab->item(row, 0)->text() == currentFile.at(i)) { // -设置背景
Count = i;
break;
}
}
QSettings *set_Sys = new QSettings(Sys_path, QSettings::IniFormat);
set_Sys->setIniCodec("GB18030");
set_Sys->setValue("ActiveFile/file", ui->fileTab->item(row, 0)->text());
system("sync");
delete set_Sys;
currentFile.removeAt(i);
currentFile.insert(0, ui->fileTab->item(row, 0)->text());
DateFile.removeAt(i);
DateFile.insert(0, QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
Save_Ini_DateFile();
Sync_Conf();
}
label_Waring->hide();
Clicked = true;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.19
* brief: 测试界面和配置界面传递信息
******************************************************************************/
void w_Conf::Slot_test_to_conf(QStringList list, QString str, int value)
{
str.clear();
switch (value) {
case 1:
Save_Test_Data(list);
break;
case 2:
WIR->Pub_Conf_Set_IR(QString::number(Ini_IRHostJudge), 5); // -测试绝缘启动
break;
case 3:
WACW->Pub_Conf_Set_ACW(" ", 5); // -测试交耐启动
break;
default:
break;
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.28
* brief: 测试数据的保存
******************************************************************************/
void w_Conf::Save_Test_Data(QStringList all_data)
{
int i = 0;
QStringList Result, Judge, Get_Set;
Result = all_data.mid(3, all_data.at(0).toInt()); // -结果
Judge = all_data.mid(3+all_data.at(0).toInt(), all_data.at(1).toInt()); // -判定
Get_Set = all_data.mid(3+all_data.at(0).toInt()+all_data.at(1).toInt(), \
all_data.at(2).toInt()); // -数据
/* QStringList_No_OK = all_data.mid(4+all_data.at(0).toInt()+ \
all_data.at(1).toInt()+all_data.at(2).toInt(),all_data.at(3).toInt()); // -不合格项目
QSqlQuery query(sql.db);
sql.db.transaction(); */
if (strTest.size() != Judge.size()) { // -补齐判定数据
for (i = Judge.size(); i < strTest.size(); i++) {
Judge.append("");
}
}
if (strTest.size() != Result.size()) { // -补齐结果数据
for (i = Result.size(); i < strTest.size(); i++) {
Result.append("");
}
}
for (i = 0; i < strTest.size(); i++) { // -判断测试结果中是否包含"," ","替换为 ","
if ((strTest.at(i).contains(tr("绝缘"))) || \
(strTest.at(i).contains(tr("交耐"))) || \
(strTest.at(i).contains(tr("匝间"))) || \
(strTest.at(i).contains(tr("电感"))) || \
(strTest.at(i).contains(tr("堵转"))) || \
(strTest.at(i).contains(tr("电参"))) || \
(strTest.at(i).contains(tr("低启"))) || \
(strTest.at(i).contains(tr("PG"))) || \
(strTest.at(i).contains(tr("空载"))) || \
(strTest.at(i).contains(tr("HALL")))) { // 绝缘 交耐 匝间
strParam.replace(i, QString(strParam.at(i)).replace(QRegExp("\\,"), " "));
// 2017 3 10 印度问题改变","--" "
}
if ((strTest.at(i).contains(tr("电阻"))) || \
(strTest.at(i).contains(tr("绝缘")))) {
strParam.replace(i, QString(strParam.at(i)).replace(QRegExp("\\Ω"), " "));
}
}
for (i = 0; i < Judge.size(); i++) {
if (strTest.at(i).contains(tr("电阻"))) { // -电阻参数
Result.replace(i, QString(Result.at(i)).replace(QRegExp("\\Ω"), ""));
} else if (strTest.at(i).contains(tr("绝缘"))) { // -绝缘
Result.replace(i, QString(Result.at(i)).mid \
(QString(Result.at(i)).indexOf(",")+1, QString(Result.at(i)).length()));
Result.replace(i, QString(Result.at(i)).replace(QRegExp("\\MΩ"), ""));
} else if (strTest.at(i).contains(tr("交耐"))) { // -交耐
Result.replace(i, QString(Result.at(i)).mid \
(QString(Result.at(i)).indexOf(",")+1, QString(Result.at(i)).length()));
Result.replace(i, QString(Result.at(i)).replace(QRegExp("\\mA"), ""));
} else if (strTest.at(i).contains(tr("匝间"))) { // -匝间 若没有(电晕,相位)时进行补齐
if ((QStringList(QString(Result.at(i)).split(",")).size()-1) == 1) {
Result.replace(i, QString(Result.at(i)).append(", , "));
} else if ((QStringList(QString(Result.at(i)).split(",")).size()-1) == 3) {
//
} else {
Result.replace(i, " , , , ");
}
} else if (strTest.at(i).contains(tr("电感"))) { // -电感 若没有(Q值)时进行补齐
if ((QStringList(QString(Result.at(i)).split(",")).size()-1) == 0) {
Result.replace(i, QString(Result.at(i)).append(", "));
} else {
//
}
} else if (strTest.at(i).contains(tr("电参"))) { // -电参
if ((QStringList(QString(Result.at(i)).split(",")).size()-1) == 2) {
Result.replace(i, QString(Result.at(i)).replace(QRegExp("[A-Z]"), " "));
qDebug() << Result.at(i);
} else {
Result.replace(i, " , , ");
}
} else if (strTest.at(i).contains(tr("堵转"))) { // -堵转
if ((QStringList(QString(Result.at(i)).split(",")).size()-1) == 1) {
Result.replace(i, QString(Result.at(i)).replace(QRegExp("[A-Z]"), " "));
} else {
Result.replace(i, " , ");
}
} else if (strTest.at(i).contains(tr("低启"))) { // -低启
if ((QStringList(QString(Result.at(i)).split(",")).size()-1) == 1) {
Result.replace(i, QString(Result.at(i)).replace(QRegExp("[A-Z]"), " "));
} else {
Result.replace(i, " , ");
}
} else if (strTest.at(i).contains(tr("PG"))) { // -PG
Result.replace(i, QString(Result.at(i)).replace(QRegExp("\\,"), " "));
} else if (strTest.at(i).contains(tr("空载"))) { // -空载
Result.replace(i, QString(Result.at(i)).replace(QRegExp("\\,"), " "));
} else if (strTest.at(i).contains(tr("HALL"))) { // -HALL
Result.replace(i, QString(Result.at(i)).replace(QRegExp("\\,"), " "));
} else {
//
}
}
QStringList SQL_Item, SQL_Param, SQL_Result, SQL_Judge;
SQL_Item.append("ITEM-1"); // -ITEM-1
SQL_Item.append("ITEM-2"); // -ITEM-2
SQL_Item.append("ITEM-3"); // -ITEM-3
SQL_Param.append(Get_Set.at(3)); // -date
SQL_Param.append(Get_Set.at(2)); // -时间
SQL_Param.append(Get_Set.at(5)); // -编号
SQL_Result.append(Ini_ActiveFile); // -当前型号
SQL_Result.append(Get_Set.at(4)); // -温度
SQL_Result.append(Get_Set.at(6)); // -用户
SQL_Judge.append(Get_Set.at(1)); // -总结果
SQL_Judge.append(Get_Set.at(0)); // -工位
SQL_Judge.append(QString::number(Judge.size())); // -总测试项目
SQL_Item.append(strTest);
SQL_Param.append(strParam);
SQL_Result.append(Result);
SQL_Judge.append(Judge);
QString QStringList_OK, QStringList_No_OK;
QStringList_OK.clear();
QStringList_No_OK.clear();
QString s;
for (i = 0; i < 19; i++) { // 柱状图的测试数据进行清空
Error_Item[i] = 0;
Error_Item_Count[i] = 0;
}
for (i = 0; i < strTest.size(); i++) {
if (strTest.at(i) == (tr("磁旋"))) {
if (Judge[i] == "OK") {
QStringList_OK += tr("磁旋 ");
} else {
QStringList_No_OK += tr("磁旋 ");
}
continue;
} else if (strTest.at(i) == (tr("转向"))) {
if (Judge[i] == "OK") {
QStringList_OK += (tr("转向 "));
} else {
QStringList_No_OK += (tr("转向 "));
}
continue;
} else if (strTest.at(i).contains(tr("PG"))) {
if (Judge[i] == "OK") {
QStringList_OK += tr("PG ");
} else {
QStringList_No_OK += tr("PG ");
}
continue;
} else {
//
}
if (Judge[i] == "OK") {
continue;
}
int k = 0;
for (int t = 0; t < Test_Item.size(); t++) {
if (strTest.at(i).contains(Test_Item.at(t))) {
k = t;
break;
}
}
if (k <= 16) {
Error_Item_Count[k]++;
if (Error_Item_Count[k] == 1) {
QStringList_No_OK += ((Test_Item.at(k))+" ");
Error_Item[k]++;
} else {
//
}
} else {
//
}
}
qDebug() << "Test_Item" << Test_Item;
qDebug() << "QStringList_OK" << QStringList_OK;
qDebug() << "QStringList_No_OK" << QStringList_No_OK;
qDebug() << "Conf_Test" << Conf_Test;
for (i = 0; i < Conf_Test.size(); i++) {
if (QStringList_No_OK.contains(Test_Item.at(Conf_Test.at(i).toInt()))) {
//
} else {
QStringList_OK += (Test_Item.at(Conf_Test.at(i).toInt())+" ");
}
}
/* int id = sql.selectMax("TestDa");
query.prepare(QString(tr("insert into TestDa (id,项目,参数,结果,判定,配置)"\
"values(:id,:项目,:参数,:结果,:判定,:配置)")));
for (i = 0; i < SQL_Item.size(); i++) {
// qDebug() << "SQL_Item.at(i)" << SQL_Item.at(i);
// qDebug() << "SQL_Param.at(i)" << SQL_Param.at(i);
// qDebug() << "SQL_Result.at(i)" << SQL_Result.at(i);
// qDebug() << "SQL_Judge.at(i)" << SQL_Judge.at(i);
// qDebug() << QStringList_OK + "------" + QStringList_No_OK;
id = id + 1;
query.bindValue(tr(":id" ), id);
query.bindValue(tr(":项目"), SQL_Item.at(i));
query.bindValue(tr(":参数"), SQL_Param.at(i));
query.bindValue(tr(":结果"), SQL_Result.at(i));
query.bindValue(tr(":判定"), SQL_Judge.at(i));
if (i > 0) {
query.bindValue(tr(":配置"), tr(""));
} else {
query.bindValue(tr(":配置"), QStringList_OK + QStringList_No_OK + "------" + QStringList_No_OK);
}
query.exec();
}
sql.db.commit(); */
QStringList tmpList;
for (int i=0; i < strTest.size(); i++) {
QString tmpStr;
tmpStr.append(strTest.at(i));
tmpStr.append("@");
tmpStr.append(strParam.at(i));
tmpStr.append("@");
if (i < Result.size())
tmpStr.append(Result.at(i));
else
tmpStr.append("");
tmpStr.append("@");
if (i < Judge.size())
tmpStr.append(Judge.at(i));
else
tmpStr.append("");
tmpList.append(tmpStr);
}
QVariantMap tmpMap;
tmpMap.insert("enum", QMessageBox::Save);
tmpMap.insert("post", Get_Set.at(0)); // 工位
tmpMap.insert("pass", Get_Set.at(1)); // 总判定
tmpMap.insert("time", Get_Set.at(2)); // 时间
tmpMap.insert("date", Get_Set.at(3)); // 日期
tmpMap.insert("temp", Get_Set.at(4)); // 温度
tmpMap.insert("numb", Get_Set.at(5)); // 编码
tmpMap.insert("user", Get_Set.at(6)); // 用户
tmpMap.insert("type", Ini_ActiveFile); // 型号
tmpMap.insert("data", tmpList.join("\n"));
emit sendAppMap(tmpMap);
qDebug() << tmpMap;
tmpMap.clear();
/* for (i = 0; i < QStringList_OK.size(); i++) {
s.clear();
s = QString(tr("%1@%2@OK")).arg(QStringList_OK.at(i)).arg(SQL_Result.at(0));
WConf_WriteSql(s.toUtf8());
}
for (i = 0; i < QStringList_No_OK.size(); i++) {
s.clear();
s = QString(tr("%1@%2@NG")).arg(QStringList_No_OK.at(i)).arg(SQL_Result.at(0));
WConf_WriteSql(s.toUtf8());
}
for (i = 3; i < SQL_Item.size(); i++) {
s.clear();
s.append(sql_Test.at(i-3) + "@" + SQL_Item.at(i) + " " + SQL_Param.at(i) + \
"@" + SQL_Result.at(i) + "@" + SQL_Judge.at(i));
qDebug() << "s" << s;
WConf_WriteSql(s.toUtf8());
}
s = QString(tr("总数@%1@%2")).arg(SQL_Result.at(0)).arg(SQL_Judge.at(0));
WConf_WriteSql(s.toUtf8()); */
if ((Ini_Udp_Enable) || (NetSQL_OpenOk)) { // -
if (SQL_Item.at(1) == "ITEM-2") {
SQL_Result.replace(1, QString(SQL_Result.at(1)).replace(QRegExp("\\°C"), "C"));
if (SQL_Judge.at(1) == QString(tr("左工位"))) {
SQL_Judge.replace(1, "Left");
} else {
SQL_Judge.replace(1, "Right");
}
}
if (SQL_Item.at(2) == "ITEM-3") {
if (SQL_Result.at(2) == QString(tr("管理员"))) {
SQL_Result.replace(2, "Admin");
} else {
SQL_Result.replace(2, "Guest");
}
}
for (i = 0; i < SQL_Item.size(); i++) {
if (SQL_Item.at(i).contains(tr("电阻"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).replace\
(QRegExp(tr("\\电阻")), "DCR"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).replace\
(QRegExp("\\Ω"), "ohm"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).replace\
(QRegExp("\\Ω"), ""));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\不平衡度")), "Banlance--"));
} else if (SQL_Item.at(i).contains(tr("反嵌"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\反嵌")), "MAG"));
} else if (SQL_Item.at(i) == (tr("磁旋"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\磁旋")), "DIR"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\正转")), "CW"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\反转")), "CCWW"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\正转")), "CW"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\反转")), "CCW"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\不转")), "NO"));
} else if (SQL_Item.at(i).contains(tr("绝缘"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\绝缘")), "IR"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp("\\Ω"), "ohm"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp("\\Ω"), ""));
} else if (SQL_Item.at(i).contains(tr("交耐"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\交耐")), "ACHV"));
} else if (SQL_Item.at(i).contains(tr("匝间"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\匝间")), "SURGE"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\面积")), " Area"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\差积")), " Diff"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\面积")), " Area"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\差积")), " Diff"));
} else if (SQL_Item.at(i).contains(tr("电感"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\电感")), "IND"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\不平衡度")), "Banlance--"));
} else if (SQL_Item.at(i).contains(tr("电参"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\电参")), "POWER"));
} else if (SQL_Item.at(i) == (tr("转向"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\转向")), "T"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\正转")), "CW"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\反转")), "CCW"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\正转")), "CW"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\反转")), "CCW"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\不转")), "NO"));
} else if (SQL_Item.at(i).contains(tr("堵转"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\堵转")), "BLOCK"));
} else if (SQL_Item.at(i).contains(tr("低启"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\低启")), "LVS"));
} else if (SQL_Item.at(i).contains(tr("PG"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\PG")), "PG"));
} else {
//
}
}
}
if (Ini_Udp_Enable) { // -UDP上传
QString UDP_Data;
for (i = 0; i < SQL_Item.size(); i++) {
UDP_Data += "(" + SQL_Item.at(i) + ")(" + SQL_Param.at(i) + \
")(" + SQL_Result.at(i)+")(" + SQL_Judge.at(i)+")";
} // qDebug() << "UDP_Data"<<UDP_Data;
WriteMessage((6000), (0x04), UDP_Data.toUtf8());
WriteMessage((6000), (0x15), ("free"));
} else {
//
}
if (NetSQL_OpenOk) { // -网络数据库
QSqlQuery query_net(sql_net.dbtwo);
int id = sql_net.selectMax_net(Ini_Factory);
qDebug() << "id--------------------------" << id;
query_net.prepare(QString(("insert into %1 (id,项目,参数,结果,判定)""values(?,?,?,?,?)"))\
.arg(Ini_Factory)); // ,配置,?
for (i = 0; i < SQL_Item.size(); i++) {
id = id+1;
query_net.bindValue(0, id);
query_net.bindValue(1, SQL_Item.at(i));
query_net.bindValue(2, SQL_Param.at(i));
query_net.bindValue(3, SQL_Result.at(i));
query_net.bindValue(4, SQL_Judge.at(i));
query_net.exec();
sql_net.dbtwo.commit();
}
} else {
//
}
system("sync");
qDebug() << "Finsh";
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.28
* brief: 调试数据的保存
******************************************************************************/
void w_Conf::Slot_Save_Debug(QString Name, QString Data)
{
// 保存数据文件进行保存数据(ini)文件进行
QString currentDateTime = QDateTime::currentDateTime().\
toString("yyyy-MM-dd-hh-mm-ss"); // -设置显示格式
QString qname;
QSettings set_Test_File(Test_Debug_path, QSettings::IniFormat);
set_Test_File.setIniCodec("GB2312");
QDir *temp = new QDir;
bool exist = temp->exists(Test_Debug_path);
if (exist) {
qname = QString("%1/%2").arg(currentDateTime).arg(Name);
set_Test_File.setValue(qname, Data);
} else {
system("mkdir /mnt/nandflash/AIP/debug/");
system("touch /mnt/nandflash/AIP/debug/debug.ini");
system("chmod +x /mnt/nandflash/AIP/debug/debug.ini");
qname = QString("%1/%2").arg(currentDateTime).arg(Name);
set_Test_File.setValue(qname, Data);
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.19
* brief: 电阻板测试电阻信息,用于快速设置和测试补偿
******************************************************************************/
QStringList w_Conf::Board_DLR_TestData(can_frame canframe)
{
QStringList Back_QStringList; Back_QStringList.clear();
if ((canframe.data[2] == 1) || (canframe.data[2] == 2)) {
// -档位(1,2)-"mΩ"
Back_QStringList.append(QString::number((canframe.data[3]*256+canframe.data[4])* \
(qPow(10, -(6-canframe.data[2])))*1000)); //
Back_QStringList.append("mΩ");
} else if ((canframe.data[2] == 3) || (canframe.data[2] == 4) || (canframe.data[2] == 5)) {
// -档位(3,4,5)-"Ω"
Back_QStringList.append(QString::number((canframe.data[3]*256+canframe.data[4])*\
(qPow(10, -(6-canframe.data[2]))))); //
Back_QStringList.append("Ω");
} else if ((canframe.data[2] == 6) || (canframe.data[2] == 7) || (canframe.data[2] == 8)) {
// -档位(6,7,8)-"KΩ" 其中(7,8)暂时未用到
Back_QStringList.append(QString::number((canframe.data[3]*256+canframe.data[4])*\
(qPow(10, (canframe.data[2]-6)))/1000)); //
Back_QStringList.append("KΩ");
}
Back_QStringList.append(QString::number(canframe.data[1]));
if (canframe.data[2] < 6) {
Back_QStringList.append(QString::number((canframe.data[3]*256+canframe.data[4])*\
(qPow(10, -(6-canframe.data[2])))));
} else {
Back_QStringList.append(QString::number((canframe.data[3]*256+canframe.data[4])*\
(qPow(10, (canframe.data[2]-6)))));
}
Back_QStringList.append(QString::number(canframe.data[2]));
return Back_QStringList;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.19
* brief: can信息传递到配置页面
******************************************************************************/
void w_Conf::SlOT_can_to_conf(can_frame frame, QStringList Data, int flag)
{
QStringList DLR_Can_Data;
QStringList PWR_Conf_Data;
switch (flag) {
case 1:
WIMP->Pub_Conf_Get_Result(frame, 1);
if ((frame.data[6] == 0) && (!Quick_Set)) { // -采样失败, 快速设置
Pri_Conf_WMessage(tr("采集失败,电机存在击穿的状况\n建议降低电压进行采集"));
} else {
WriteMessage(6000, 0x92, QString::number(frame.data[1]*100+frame.data[3]).toUtf8());
}
break;
case 2:
//
break;
case 3:
if (!Quick_Set) {
return;
}
if (frame.data[3] != 0) { // -主参
return;
}
Result_indl.dat[0] = frame.data[4];
Result_indl.dat[1] = frame.data[5];
Result_indl.dat[2] = frame.data[6];
Result_indl.dat[3] = frame.data[7];
WINDL->Pub_Conf_Set_INDL(QString::number(Result_indl.Result), frame.data[1], 7);
break;
case 5:
/* WBLOCK->Pub_Conf_Set_BLOCK(QString::number(frame.data[3]*256 + frame.data[4]), \
frame.data[5]*256 + frame.data[6], 5); */
PWR_Conf_Data.clear();
PWR_Conf_Data.append(QString::number(frame.data[1]*256 + frame.data[2]));
PWR_Conf_Data.append(QString::number(frame.data[3]*256 + frame.data[4]));
PWR_Conf_Data.append(QString::number(frame.data[5]*256 + frame.data[6]));
if (index_c == 7) {
WPWR->Pub_Conf_Set_PWR(PWR_Conf_Data.at(0), 7);
} else if (index_c == 9) {
WBLOCK->Pub_Conf_Set_BLOCK(PWR_Conf_Data.at(0), 7, 7);
} else if (index_c == 10) {
WLVS->Pub_Conf_Set_LVS(PWR_Conf_Data.at(0), 7);
} else {
//
}
break;
case 6:
DLR_Can_Data = Board_DLR_TestData(frame);
if (Quick_Set) { // -快速设置
if (DLR_Can_Data.at(0).toDouble() < (2*qPow(10, (1+frame.data[2]%3)))) {
// -小于 20,200,2000
AutoSet[frame.data[1]] = DLR_Can_Data;
} else {
//
}
} else {
DLR_Compensate_Back(DLR_Can_Data);
}
break;
default:
//
break;
}
Data.clear();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.28
* brief: 日志数据的保存
******************************************************************************/
void w_Conf::Slot_Save_DayRecoord(QString Text = "", QString GetData = "")
{
QString currentDateTime = QDateTime::currentDateTime().toString \
("yyyy-MM-dd---hh-mm-ss"); // -设置显示格式
QSettings set_Test_File(Test_Day_Record_path, QSettings::IniFormat);
set_Test_File.setIniCodec(QTextCodec::codecForName("GB2312"));
QDir *temp = new QDir;
bool exist = temp->exists(Test_Day_Record_path);
if (exist) {
qDebug() << "Day_Record File exist";
} else {
qDebug() << "Day_Record File Not Exist";
system("mkdir /mnt/nandflash/AIP/dayrecord/");
system("touch /mnt/nandflash/AIP/dayrecord/dayrecord.ini");
system("chmod +x /mnt/nandflash/AIP/dayrecord/dayrecord.ini");
}
QString keyname;
keyname = QString("%1/%2").arg(Text).arg(currentDateTime);
set_Test_File.setValue(keyname, GetData);
QString strstr;
strstr = GetData.replace(" ", "");
// for (int i=0;i<strstr.size()/10;i++) {
// qDebug() << strstr.mid(i*10, 10);
// }
// qDebug() << strstr.size()<<strstr;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.8.16
* brief: 勾选是否进行测试
******************************************************************************/
void w_Conf::Item_Chose_Box_stateChanged(int checked)
{
qDebug() << "*********************** ui->test->currentRow()" << ui->test->currentRow();
if (Item_Chose_Box->isHidden()) {
return;
}
if (checked) {
qDebug() << "green";
ui->test->item(ui->test->currentRow(), 0)->setTextColor(QColor("green"));
} else {
qDebug() << "red";
ui->test->item(ui->test->currentRow(), 0)->setTextColor(QColor("red"));
}
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 电机类型切换
******************************************************************************/
int w_Conf::on_MotorType_currentIndexChanged(int index)
{
if ((model_Type.size() == 0) || (index < 0)) {
return 0;
}
int i = 0;
QString str;
ui->Label_Picture->clear();
QPixmap *pixmap;
pixmap = new QPixmap(QString("/mnt/nandflash/AIP/Model/%1.jpg").arg \
(ui->MotorType->currentText()));
ui->Label_Picture->setPixmap(*pixmap);
QSettings settings(data_path, QSettings::IniFormat);
Ini.Color = settings.value(QString("%1/Color").arg \
(ui->MotorType->currentText())).toString();
for (i = 0; i < Ini_Proj.size(); i++) { // -对端点进行锁定
switch (Ini_Proj.at(i).toInt()) {
case 1: // -电阻
Ini.DLR = settings.value(QString("%1/DLR").arg \
(ui->MotorType->currentText()), "12").toString();
break;
case 2: // -反嵌
Ini.MAG = settings.value(QString("%1/MAG").arg \
(ui->MotorType->currentText()), "12").toString();
break;
case 3: // -绝缘
//
break;
case 4: // -交耐
//
break;
case 5: // -直耐
if (WDCW != NULL) {
WDCW->Slot_DCW_Setpoint("12");
}
break;
case 6: // -匝间
Ini.IMP = settings.value(QString("%1/IMP").arg \
(ui->MotorType->currentText()), "12").toString();
break;
case 7: // -功率
//
break;
case 8: // -电感
Ini.IINDL = settings.value(QString("%1/INDL").arg \
(ui->MotorType->currentText()), "12").toString();
break;
case 9: // -堵转
//
break;
case 10: // -低启
//
break;
case 11: // -霍尔
//
break;
case 12: // -负载
//
break;
case 13: // -空载
//
break;
case 14: // -反电动势
//
break;
}
}
if (ui->MotorType->currentText() == "None") { // -(None)型号时按键全部使能
Ini.Color = "12345678"; // -设置初始值
} else {
//
}
CONF.replace(13, ui->MotorType->currentText());
qColor_BtnList.clear();
colorIdList.clear();
colorIdList_C.clear();
Singal_Conf_to_Main(QStringList(""), ui->MotorType->currentText(), 5, 5);
for (i = 0; i < 8; i++) { // -初始化下拉列表
qColor_BtnList.append(new QToolButton(this));
ui->colrLayout->addWidget(qColor_BtnList[i], i/2, i%2);
btnGroup_Color->addButton(qColor_BtnList[i], i);
qColor_BtnList[i]->setEnabled(true);
colorIdList.append(CONF[i]);
colorIdList_C.append(CONF[i]);
if (Ini.Color.indexOf(QString::number(i+1)) >= 0) {
if (colorIdList[i] == "#000000") {
str = QString("height:90px;width:95px;color: #191919;"\
"border:none;background-color:%1;color:white").arg\
(colorIdList[i]);
} else {
str = QString("height:90px;width:95px;"\
"color: #191919;border:none;background-color:%1").arg\
(colorIdList[i]);
}
} else {
qColor_BtnList[i]->setDisabled(true);
colorIdList_C.replace(i, "#191919");
str = QString("height:90px;width:95px;color: #191919;"\
"border:none;background-color:%1").arg \
(colorIdList_C[i]);
}
qColor_BtnList[i]->setStyleSheet(str);
qColor_BtnList[i]->setText(QString::number(i+1));
}
return true;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.19
* brief: Main传递数据到配置页面
******************************************************************************/
void w_Conf::Pub_main_to_conf(QStringList list, QString str, int value, int flag)
{
int Success = 0;
int i;
switch (flag) {
case 1:
Usart_GetFcous();
break;
case 2:
Usart_Button(value);
break;
case 3:
Ini_System = list;
Conf_User = list[5].toInt();
Save_SystemConf_Data(value);
break;
case 4:
Set_Color(str);
break;
case 5: // 用于系统初始化
thread_sql = new QThread(this);
sql_Client.moveToThread(thread_sql);
connect(thread_sql, SIGNAL(started()), &sql_Client, SLOT(DeviceOpen()));
connect(thread_sql, SIGNAL(finished()), &sql_Client, SLOT(DeviceQuit()));
connect(this, SIGNAL(WConf_WriteSql(QByteArray)), &sql_Client, SLOT(Write(QByteArray)));
thread_sql->start();
Sync_Conf();
break;
case 7:
SlOT_Button_Function_Judge(Qt::Key_A);
break;
case 10:
if (value == 1) {
ui->fileEdit1->setText(str);
on_fileBtnAdd_clicked();
} else if (value == 2) {
on_fileBtnDel_clicked();
} else if (value == 3) {
emit WriteMessage(6000, 0x67, QString(currentFile.join(" ")).toUtf8());
} else if (value == 5) {
for (i = 0; i < currentFile.size(); i++) {
if (ui->fileTab->item(i, 0)->text() == str) { // 设置背景
on_fileTab_cellClicked(i, 0);
}
}
} else {
//
}
break;
case 11:
Conf_Set_User(value);
break;
case 12:
lable_Zero->hide();
break;
case 13:
if (value == 1) {
PC_CONF_Data();
} else if (value == 2) {
PC_SYS_Data();
} else if (value == 3) {
PC_Item_DCR_Data();
} else if (value == 4) {
PC_Item_IR_Data();
} else if (value == 5) {
PC_Item_ACW_Data();
} else if (value == 6) {
PC_Item_IMP_Data();
} else if (value == 7) {
PC_Item_IND_Data();
} else if (value == 11) {
PC_Item_PGHALL_Data();
} else if (value == 12) {
PC_Item_LOAD_Data();
} else if (value == 13) {
PC_Item_NOLOAD_Data();
} else if (value == 14) {
PC_Item_BEMF_Data();
} else if (value == 15) {
PC_Item_MAG_Data();
} else {
//
}
break;
case 15:
qDebug()<<"2017-12-27 Pub_main_to_conf index_c"<<index_c;
if(index_c==7) {
WPWR->Pub_Conf_Set_PWR(list.at(0),7);
}
else if(index_c==9) {
WBLOCK->Pub_Conf_Set_BLOCK(list.at(0),7,7);
}
else if(index_c==10) {
WLVS->Pub_Conf_Set_LVS(list.at(0),7);
}
else {
}
break;
case 16:
if (index_c == 7) {
if (PWR_Test_Usart) {
PWR_Test_Usart = false;
} else {
WPWR->Pub_Conf_Set_PWR(QString(""), 8);
break;
}
if (value == 2) {
Pri_Conf_WMessage("串口不在调试模式,或者串口出现问题");
} else {
Pri_Conf_WMessage("串口 Ok");
}
} else if (index_c == 9) {
WBLOCK->Pub_Conf_Set_BLOCK("", 8, 8);
} else if (index_c == 10) {
WLVS->Pub_Conf_Set_LVS("", 8);
} else {
//
}
break;
case 17:
if (Ini_Set_ImpVolt == QString(tr("noback"))) {
WIMP->Pub_Conf_Set_IMP("", 12);
}
break;
case 18:
for (i = 0; i < currentFile.size(); i++) {
if (ui->fileTab->item(i, 0)->text() == str) { // 设置背景
on_fileTab_cellClicked(i, 0);
}
}
qApp->processEvents(); // 立即显示生效
break;
case 19:
if (WMAG != NULL) {
WMAG->Pub_Conf_Set_MAG(QString::number(value), 10);
} else {
//
}
if (WIMP != NULL) {
WIMP->Pub_Conf_Set_IMP(QString::number(value), 13);
} else {
//
}
break;
case 20:
if (IRACW_Compensate == TestIW_IR) {
if (value == 0) {
return;
}
Success = WIR->IR_Compensate(str.toDouble());
if (Success == 0) {
return;
} else if (Success == 1) {
ui->Key_E->setStyleSheet("background:#00FF00;color:rgb(0, 0, 0);");
ui->Key_E->setText(tr("已补偿"));
} else if (Success == 2) {
Pri_Conf_WMessage(tr(" 补偿错误 "));
} else {
//
}
} else if (IRACW_Compensate == TestIW_ACW) {
if (value == 0) {
return;
}
Success = WACW->ACW_Compensate(str.toDouble());
if (Success == 0) {
return;
} else if (Success == 1) {
ui->Key_E->setStyleSheet("background:#00FF00;color:rgb(0, 0, 0);");
ui->Key_E->setText(tr("已补偿"));
} else if (Success == 2) {
Pri_Conf_WMessage(tr(" 补偿错误 "));
} else {
//
}
} else {
//
}
break;
default:
break;
}
}
void w_Conf::Pub_QbyteArray_conf(QByteArray dat) {
int model_position = 0;
int i = 0;
int j = 0;
dat = dat.remove(0, 5);
QDomDocument docs;
QStringList temp;
docs.setContent(dat);
if (!(docs.elementsByTagName("DCR").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("DCR").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
WDLR->DLR_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("wire_comp2"))) {
RES = WDLR->Copy_DLR_List;
SlOT_Button_Function_Judge(Qt::Key_B);
SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("MAG").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("MAG").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
WMAG->MAG_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("wave"))) {
OPP = WMAG->Copy_MAG_List;
SlOT_Button_Function_Judge(Qt::Key_B);
}
}
} else if (!(docs.elementsByTagName("IR").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("IR").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
WIR->IR_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("volt"))) {
INS = WIR->Copy_IR_List;
SlOT_Button_Function_Judge(Qt::Key_B);
SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("ACW").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("ACW").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
WACW->ACW_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("volt"))) {
ACV = WACW->Copy_ACW_List;
SlOT_Button_Function_Judge(Qt::Key_B);
SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("IMP").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("IMP").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
// qDebug() << "temp"<<temp<<"node.nodeName()"<<node.nodeName();
WIMP->IMP_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("wave"))) {
ITT = WIMP->Copy_IMP_List;
SlOT_Button_Function_Judge(Qt::Key_B);
}
}
} else if (!(docs.elementsByTagName("IND").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("IND").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
WINDL->INDL_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("wire_comp2"))) {
INDL = WINDL->Copy_INDL_List;
SlOT_Button_Function_Judge(Qt::Key_B);
// SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("HALL").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("HALL").at(0).childNodes();
qDebug() << "list.size()" << list.size();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
qDebug() << "Indl temp" << temp << node.nodeName();
WPG->BLDCPG_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("wave"))) {
BLDCPG = WPG->Copy_BLDCPG_List;
SlOT_Button_Function_Judge(Qt::Key_B);
SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("LOAD").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("LOAD").at(0).childNodes();
qDebug() << "list.size()" << list.size();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
qDebug() << "Indl temp" << temp << node.nodeName();
WLOAD->LOAD_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("vsp_volt"))) {
LOAD = WLOAD->Copy_LOAD_List;
SlOT_Button_Function_Judge(Qt::Key_B);
SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("NOLOAD").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("NOLOAD").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
WNoLoad->NOLOAD_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("vsp_volt"))) {
NOLOAD = WNoLoad->Copy_NOLOAD_List;
SlOT_Button_Function_Judge(Qt::Key_B);
SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("BEMF").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("BEMF").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
WBEMF->BEMF_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("volt_vcc"))) {
BEMF = WBEMF->Copy_BEMF_List;
SlOT_Button_Function_Judge(Qt::Key_B);
SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("Conf").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("Conf").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
qDebug() << "Indl temp" << temp << node.nodeName();
if (node.nodeName() == QString(tr("color"))) {
for (j = 0; j < 8; j++) {
iColorBtn = i;
Set_Color(temp.at(i));
}
}
if (node.nodeName() == QString(tr("type"))) {
model_position = model_Type.indexOf(temp.at(0));
ui->MotorType->setCurrentIndex(model_position);
Save_ConfData();
}
}
} else if (!(docs.elementsByTagName("Sys").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("Sys").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
qDebug() << "Indl temp" << temp << node.nodeName();
if (node.nodeName() == QString(tr("Test_Item"))) {
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
QString name_list;
name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setValue(name_list, temp);
test_Inifile = temp;
ui->test->setRowCount(0);
ui->test->setGeometry(305, 20, 131, 39*14+(ui->test->horizontalHeader()->height()));
ui->test->setRowCount(13);
for (i =0 ; i < 13; i++) {
ui->test->setRowHeight(i, 39);
}
Init_test_TableWidget(); // -初始化测试项目
for (i = 1; i <= Count_Item; i++) { // -设置显示, 锁定端子号
btnGroup_Item->button(i)->hide();
}
btnGroup_Item->button(0)->show();
btnGroup_Item->button(20)->show();
for (i = 1; i < Ini_Proj.size(); i++) {
btnGroup_Item->button(Ini_Proj.at(i).toInt())->show();
}
SlOT_Button_Function_Judge(Qt::Key_B);
// SlOT_Button_Function_Judge(Qt::Key_A);
qApp->processEvents();
}
}
} else {
qDebug() << "Error Data";
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.6.10
* brief: 网络数据库打开,数据库窗口显示
******************************************************************************/
void w_Conf::on_SQL_Task_clicked()
{
if (NetSQL_OpenOk) { // -网络数据库打开
SQL_Widget->show();
} else {
Pri_Conf_WMessage(tr("未连接网络\n下载远程数据库失败"));
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.6.10
* brief: 数据库窗口隐藏
******************************************************************************/
void w_Conf::SQL_Widget_autoquit()
{
SQL_Widget->hide();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.6.10
* brief: 数据库查询任务表-生产线-
******************************************************************************/
void w_Conf::SQL_Produce_Plan_textChanged(const QString &text)
{
int i = 0;
if (SQL_Init) {
return;
}
SQL_Task.clear();
QSqlQuery query_net(sql_net.dbtwo);
QString net_str = QString(tr("Select 生产任务编号 from %2 Where 生产线 = '%1'").arg\
(text).arg(Ini_Task_Table));
query_net.exec(net_str);
while (query_net.next()) {
SQL_Task.append(query_net.value(0).toString().trimmed());
}
SQL_Init = true;
SQL_Line_Text.at(0)->text().clear(); // -计划数量清空
SQL_Line_Text.at(1)->text().clear(); // -生产部门清空
SQL_Line_Text.at(2)->text().clear(); // -产品型号清空
SQL_Produce_Number->clear();
for (i = 0; i < SQL_Task.size(); i++) {
SQL_Produce_Number->addItem(QWidget::tr("%1").arg(SQL_Task.at(i)));
}
SQL_Init = false;
SQL_Produce_Number_textChanged(SQL_Produce_Number->currentText());
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.6.10
* brief: 数据库查询任务表-生产任务号-
******************************************************************************/
void w_Conf::SQL_Produce_Number_textChanged(const QString &text)
{
if (SQL_Init) {
return;
}
if (SQL_Produce_Plan->currentText() == "") {
return;
}
SQL_Line_Text.at(0)->text().clear(); // -计划数量清空
SQL_Line_Text.at(1)->text().clear(); // -生产部门清空
SQL_Line_Text.at(2)->text().clear(); // -产品型号清空
SQL_Task.clear();
QSqlQuery query_net(sql_net.dbtwo);
QString net_str = QString(tr("Select 计划数量, 生产部门, 产品型号 from %3 Where "\
"生产线 = '%1' and 生产任务编号 ='%2'").arg \
(SQL_Produce_Plan->currentText()).arg(text).arg(Ini_Task_Table));
query_net.exec(net_str);
while (query_net.next()) {
SQL_Task.append(query_net.value(0).toString().trimmed());
SQL_Task.append(query_net.value(1).toString().trimmed());
SQL_Task.append(query_net.value(2).toString().trimmed());
SQL_Line_Text.at(0)->setText(SQL_Task.at(0));
SQL_Line_Text.at(1)->setText(SQL_Task.at(1));
SQL_Line_Text.at(2)->setText(SQL_Task.at(2));
}
}
void w_Conf::PC_Test_Param_Data(QStringList netdata)
{
int i = 0;
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("Test_Data_Param");
doc.appendChild(root);
QStringList temp;
for (i=0; i < netdata.size()/2; i++) {
temp.append(netdata.at(i));
}
QDomElement Test_1 = doc.createElement("Test_1"); // Test_1
root.appendChild(Test_1);
text = doc.createTextNode(temp.join(","));
Test_1.appendChild(text);
temp.clear();
for (i=0; i < netdata.size()/2; i++) {
temp.append(netdata.at(netdata.size()/2+i));
}
QDomElement Test_2 = doc.createElement("Test_2");
root.appendChild(Test_2);
text = doc.createTextNode(temp.join(","));
Test_2.appendChild(text);
qDebug() << "doc" << doc.toByteArray();
emit WriteMessage(6000, 0x60, doc.toByteArray());
}
void w_Conf::PC_Item_IR_Data() {
int i = 0;
int j = 0;
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("IR");
doc.appendChild(root);
QStringList ir_param;
QStringList ir_param_common;
ir_param.clear();
ir_param_common.clear();
ir_param << tr("test") << tr("port1") << tr("port2") << tr("volt")\
<< tr("min") << tr("max") << tr("time");
ir_param_common << tr("2") << tr("PE") << tr("ALL");
ir_param_common.append(INS.at(20));
ir_param_common.append(INS.at(23));
ir_param_common.append(INS.at(22));
ir_param_common.append(INS.at(21));
int ir_position[] = {36, 30, 31, 32, \
33, 34, 35, \
};
QStringList temp;
for (j = 0; j < ir_param.size(); j++) {
temp.clear();
for (i = 0; i < 4; i++) {
temp.append(RES.at(10*i+ir_position[j]));
}
temp.append(ir_param_common.at(j));
QDomElement test = doc.createElement(ir_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(Qt::Key_3);
}
void w_Conf::PC_Item_ACW_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("ACW");
doc.appendChild(root);
QStringList acw_param;
QStringList acw_param_common;
acw_param.clear();
acw_param_common.clear();
acw_param << tr("test") << tr("port1") << tr("port2") << tr("volt")\
<< tr("min") << tr("max") << tr("time")\
<< tr("freq") << tr("arc");
acw_param_common << tr("2") << tr("PE") << tr("ALL");
acw_param_common.append(ACV.at(20));
acw_param_common.append(ACV.at(23));
acw_param_common.append(ACV.at(24));
acw_param_common.append(ACV.at(21));
acw_param_common.append(ACV.at(1));
acw_param_common.append(ACV.at(0));
int acw_position[] = {40, 30, 31, 32, \
33, 34, 36, \
10, 35};
QStringList temp;
for (int j = 0; j < acw_param.size(); j++) {
temp.clear();
if (j == 7) {
for (int i = 0; i < 4; i++) {
temp.append(ACV.at(acw_position[j]));
}
} else {
for (int i = 0; i < 4; i++) {
temp.append(ACV.at(16*i+acw_position[j]));
}
}
temp.append(acw_param_common.at(j));
QDomElement test = doc.createElement(acw_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(Qt::Key_4);
}
void w_Conf::PC_Item_IMP_Data() {
SlOT_Button_Conf_Judge(Qt::Key_6);
}
void w_Conf::PC_Item_IND_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("IND");
doc.appendChild(root);
QStringList ind_param;
ind_param.clear();
ind_param << tr("test") << tr("port1") << tr("port2") << tr("unit")\
<< tr("min") << tr("max") << tr("qmin") << tr("qmax")\
<< tr("std") << tr("mode") << tr("noun");
int ind_position[] = {38, 30, 31, 37, \
32, 33, 34, 35, \
36};
QStringList temp;
for (int j = 0; j < ind_param.size(); j++) {
temp.clear();
if (j == 9) {
temp.append(INDL.at(0)); // 次数
temp.append(INDL.at(2)); // 频率
temp.append(INDL.at(3)); // 频率
temp.append(INDL.at(6)); // 快测慢测
} else if (j == 10) {
temp.append(INDL.at(1)); // 不平衡度
} else {
for (int i=0; i < 8; i++) {
temp.append(INDL.at(20*i+ind_position[j]));
}
}
QDomElement test = doc.createElement(ind_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
qDebug() << "doc.toByteArray()" << doc.toByteArray();
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(Qt::Key_8);
}
void w_Conf::PC_Item_PGHALL_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("HALL");
doc.appendChild(root);
QStringList fg_param;
fg_param.clear();
fg_param << tr("volt_low_min") << tr("volt_low_max") << tr("volt_up_min") << tr("volt_up_max")\
<< tr("freq_min") << tr("freq_max") << tr("duty_min") << tr("duty_max")\
<< tr("skewing_min") << tr("skewing_max")\
<< tr("count") << tr("vcc_volt") << tr("time");
int fg_position[] = {50, 65, 51, 66, \
52, 67, 53, 68, \
54, 69, \
1, 0, 2};
QStringList temp;
for (int j = 0; j < fg_param.size(); j++) {
temp.clear();
temp.append(BLDCPG.at(fg_position[j]));
QDomElement test = doc.createElement(fg_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(59);
}
void w_Conf::PC_Item_LOAD_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("LOAD");
doc.appendChild(root);
QStringList load_param;
load_param.clear();
load_param << tr("volt") << tr("curr_min") << tr("curr_max") << tr("pwr_min") << tr("pwr_max")\
<< tr("speed_min") << tr("speed_max") << tr("torque") << tr("vcc_volt")\
<< tr("vsp_volt") << tr("time") << tr("sequence");
int load_position[] = {0, 50, 65, 51, 66, \
52, 67, 4, 1, \
2, 3, 110};
QStringList temp;
for (int j = 0; j < load_param.size(); j++) {
temp.clear();
if (j == 11) {
for (int i = 0; i < 14; i++) {
temp.append(LOAD.at(load_position[j]+i));
}
} else {
temp.append(LOAD.at(load_position[j]));
}
QDomElement test = doc.createElement(load_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(60);
}
void w_Conf::PC_Item_NOLOAD_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("NOLOAD");
doc.appendChild(root);
QStringList noload_param;
noload_param.clear();
noload_param << tr("volt") << tr("curr_min") << tr("curr_max") << tr("pwr_min") \
<< tr("pwr_max")\
<< tr("speed_min") << tr("speed_max") << tr("vcc_volt")\
<< tr("vsp_volt") << tr("time") << tr("sequence")\
<< tr("turn");
int noload_position[] = {0, 50, 65, 51, 66, \
52, 67, 1, \
2, 3, 110, \
4};
QStringList temp;
for (int j = 0; j < noload_param.size(); j++) {
temp.clear();
if (j == 10) {
for (int i = 0; i < 10; i++) {
temp.append(NOLOAD.at(noload_position[j]+i));
}
} else {
temp.append(NOLOAD.at(noload_position[j]));
}
QDomElement test = doc.createElement(noload_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(61);
}
void w_Conf::PC_Item_BEMF_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("BEMF");
doc.appendChild(root);
QStringList bemf_param;
bemf_param.clear();
bemf_param << tr("hu_volt_min") << tr("hu_volt_max") << tr("hv_volt_min") << tr("hv_volt_max")\
<< tr("hw_volt_min") << tr("hw_volt_max") << tr("speed") << tr("turn")\
<< tr("skewing") << tr("noun");
int bemf_position[] = {50, 65, 51, 66, \
52, 67, 1, 2, \
3, 0};
QStringList temp;
for (int j = 0; j < bemf_param.size(); j++) {
temp.clear();
temp.append(BEMF.at(bemf_position[j]));
QDomElement test = doc.createElement(bemf_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(62);
}
void w_Conf::PC_Item_DCR_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("DCR");
doc.appendChild(root);
QStringList dcr_param;
dcr_param.clear();
dcr_param << tr("test") << tr("port1") << tr("port2") << tr("wire")\
<< tr("unit") << tr("min") << tr("max") << tr("std")\
<< tr("std_temp") << tr("wire_comp1") << tr("wire_comp2")\
<< tr("temp_comp") << ("noun");
int dcr_position[] = {7, 0, 1, 5, \
9, 2, 3, 4, \
0, 6, 10, \
33, 7};
QStringList temp;
for (int j = 0; j < dcr_param.size(); j++) {
temp.clear();
if ((j == 8) || (j == 11) || (j == 12)) {
temp.append(RES.at(dcr_position[j]));
} else {
for (int i=0; i < 8; i++) {
temp.append(RES.at(25+16*i+dcr_position[j]));
}
}
QDomElement test = doc.createElement(dcr_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(Qt::Key_1);
}
void w_Conf::PC_Item_MAG_Data() {
qDebug() << "Mag Join";
SlOT_Button_Conf_Judge(Qt::Key_2);
}
void w_Conf::PC_SYS_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("Sys");
doc.appendChild(root);
QStringList temp;
for (int i=0; i < test_Inifile.size(); i++) {
temp.append(test_Inifile.at(i));
}
QDomElement Test_Item = doc.createElement("Test_Item");
root.appendChild(Test_Item);
text = doc.createTextNode(temp.join(","));
Test_Item.appendChild(text);
emit WriteMessage(6000, 0x60, doc.toByteArray());
}
void w_Conf::PC_CONF_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("Conf");
doc.appendChild(root);
QStringList temp;
for (int i=0; i < colorIdList_C.size(); i++) {
temp.append(colorIdList_C.at(i));
}
QDomElement color = doc.createElement("color");
root.appendChild(color);
text = doc.createTextNode(temp.join(","));
color.appendChild(text);
temp.clear();
temp.append(ui->MotorType->currentText());
QDomElement type = doc.createElement("type");
root.appendChild(type);
text = doc.createTextNode(temp.join(","));
type.appendChild(text);
emit WriteMessage(6000, 0x60, doc.toByteArray());
}
| 36.772231 | 110 | 0.486184 | Bluce-Song |
0c429aff8c66779da4ad1f05c1768aa976621b05 | 12,024 | hpp | C++ | include/ShaderWriter/VecTypes/Swizzle.hpp | jarrodmky/ShaderWriter | ee9ce00a003bf544f8c8f23b5c07739e21cb3754 | [
"MIT"
] | 148 | 2018-10-11T16:51:37.000Z | 2022-03-26T13:55:08.000Z | include/ShaderWriter/VecTypes/Swizzle.hpp | jarrodmky/ShaderWriter | ee9ce00a003bf544f8c8f23b5c07739e21cb3754 | [
"MIT"
] | 30 | 2019-11-30T11:43:07.000Z | 2022-01-25T21:09:47.000Z | include/ShaderWriter/VecTypes/Swizzle.hpp | jarrodmky/ShaderWriter | ee9ce00a003bf544f8c8f23b5c07739e21cb3754 | [
"MIT"
] | 8 | 2020-04-17T13:18:30.000Z | 2021-11-20T06:24:44.000Z | /*
See LICENSE file in root folder
*/
#ifndef ___SDW_Swizzle_H___
#define ___SDW_Swizzle_H___
#include "ShaderWriter/BaseTypes/Bool.hpp"
#define Writer_UseSwizzle 0
#if defined( RGB )
# undef RGB
#endif
namespace sdw
{
#if Writer_UseSwizzle
template< typename Input, typename Output >
struct Swizzle
: public Output
{
inline Swizzle( std::string const & p_name
, Input * input );
inline Swizzle & operator=( Swizzle const & rhs );
template< typename T > inline Swizzle & operator=( T const & rhs );
inline operator Output()const;
template< typename UInput, typename UOutput > inline Swizzle & operator+=( Swizzle< UInput, UOutput > const & rhs );
template< typename UInput, typename UOutput > inline Swizzle & operator-=( Swizzle< UInput, UOutput > const & rhs );
template< typename UInput, typename UOutput > inline Swizzle & operator*=( Swizzle< UInput, UOutput > const & rhs );
template< typename UInput, typename UOutput > inline Swizzle & operator/=( Swizzle< UInput, UOutput > const & rhs );
inline Swizzle & operator+=( float rhs );
inline Swizzle & operator-=( float rhs );
inline Swizzle & operator*=( float rhs );
inline Swizzle & operator/=( float rhs );
inline Swizzle & operator+=( int rhs );
inline Swizzle & operator-=( int rhs );
inline Swizzle & operator*=( int rhs );
inline Swizzle & operator/=( int rhs );
Input * m_input;
};
template< typename TInput, typename UInput, typename Output > inline Output operator+( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Output > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator-( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Output > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator*( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Output > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator/( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Output > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator+( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Float > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator-( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Float > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator*( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Float > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator/( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Float > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator+( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Int > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator-( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Int > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator*( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Int > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator/( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Int > const & rhs );
template< typename Input, typename Output > inline Output operator+( Swizzle< Input, Output > const & lhs, float rhs );
template< typename Input, typename Output > inline Output operator-( Swizzle< Input, Output > const & lhs, float rhs );
template< typename Input, typename Output > inline Output operator*( Swizzle< Input, Output > const & lhs, float rhs );
template< typename Input, typename Output > inline Output operator/( Swizzle< Input, Output > const & lhs, float rhs );
template< typename Input, typename Output > inline Output operator+( Swizzle< Input, Output > const & lhs, int rhs );
template< typename Input, typename Output > inline Output operator-( Swizzle< Input, Output > const & lhs, int rhs );
template< typename Input, typename Output > inline Output operator*( Swizzle< Input, Output > const & lhs, int rhs );
template< typename Input, typename Output > inline Output operator/( Swizzle< Input, Output > const & lhs, int rhs );
# define Writer_Swizzle( Input, Output, Name )\
Swizzle< Input, Output > Name;
# define Writer_FirstSwizzle( Input, Output, Name )\
Swizzle< Input, Output > Name = Swizzle< Input, Output >( castor::string::stringCast< char >( #Name ), this )
# define Writer_LastSwizzle( Input, Output, Name )\
Swizzle< Input, Output > Name = Swizzle< Input, Output >( castor::string::stringCast< char >( #Name ), this )
# define Swizzle_X x
# define Swizzle_Y y
# define Swizzle_Z z
# define Swizzle_W w
# define Swizzle_R r
# define Swizzle_G g
# define Swizzle_B b
# define Swizzle_A a
# define Swizzle_XY xy
# define Swizzle_XZ xz
# define Swizzle_XW xw
# define Swizzle_YX yx
# define Swizzle_YZ yz
# define Swizzle_YW yw
# define Swizzle_ZX zx
# define Swizzle_ZY zy
# define Swizzle_ZW zw
# define Swizzle_WX wx
# define Swizzle_WY wy
# define Swizzle_WZ wz
# define Swizzle_RG rg
# define Swizzle_RB rb
# define Swizzle_RA ra
# define Swizzle_GR gr
# define Swizzle_GB gb
# define Swizzle_GA ga
# define Swizzle_BR br
# define Swizzle_BG bg
# define Swizzle_BA ba
# define Swizzle_AR ar
# define Swizzle_AG ag
# define Swizzle_AB ab
# define Swizzle_XYZ xyz
# define Swizzle_XYW xyw
# define Swizzle_XZY xzy
# define Swizzle_XZW xzw
# define Swizzle_XWY xwy
# define Swizzle_XWZ xwz
# define Swizzle_YXZ yxz
# define Swizzle_YXW yxw
# define Swizzle_YZX yzx
# define Swizzle_YZW yzw
# define Swizzle_YWX ywx
# define Swizzle_YWZ ywz
# define Swizzle_ZXY zxy
# define Swizzle_ZXW zxw
# define Swizzle_ZYX zyx
# define Swizzle_ZYW zyw
# define Swizzle_ZWX zwx
# define Swizzle_ZWY zwy
# define Swizzle_WXY wxy
# define Swizzle_WXZ wxz
# define Swizzle_WYX wyx
# define Swizzle_WYZ wyz
# define Swizzle_WZX wzx
# define Swizzle_WZY wzy
# define Swizzle_RGB rgb
# define Swizzle_RGA rga
# define Swizzle_RBG rbg
# define Swizzle_RBA rba
# define Swizzle_RAG rag
# define Swizzle_RAB rab
# define Swizzle_GRB grb
# define Swizzle_GRA gra
# define Swizzle_GBR gbr
# define Swizzle_GBA gba
# define Swizzle_GAR gar
# define Swizzle_GAB gab
# define Swizzle_BRG brg
# define Swizzle_BRA bra
# define Swizzle_BGR bgr
# define Swizzle_BGA bga
# define Swizzle_BAR bar
# define Swizzle_BAG bag
# define Swizzle_ARG arg
# define Swizzle_ARB arb
# define Swizzle_AGR agr
# define Swizzle_AGB agb
# define Swizzle_ABR abr
# define Swizzle_ABG abg
# define Swizzle_XYZW xyzw
# define Swizzle_XYWW xyww
# define Swizzle_XYWZ xywz
# define Swizzle_XZYW xzyw
# define Swizzle_XZWY xzwy
# define Swizzle_XWYZ xwyz
# define Swizzle_XWZY xwzy
# define Swizzle_YXZW yxzw
# define Swizzle_YXWZ yxwz
# define Swizzle_YZXW yzxw
# define Swizzle_YZWX yzwx
# define Swizzle_YWXZ ywxz
# define Swizzle_YWZX ywzx
# define Swizzle_ZXYW zxyw
# define Swizzle_ZXWY zxwy
# define Swizzle_ZYXW zyxw
# define Swizzle_ZYWX zywx
# define Swizzle_ZWXY zwxy
# define Swizzle_ZWYX zwyx
# define Swizzle_WXYZ wxyz
# define Swizzle_WXZY wxzy
# define Swizzle_WYXZ wyxz
# define Swizzle_WYZX wyzx
# define Swizzle_WZXY wzxy
# define Swizzle_WZYX wzyx
# define Swizzle_RGBA rgba
# define Swizzle_RGAB rgab
# define Swizzle_RBGA rbga
# define Swizzle_RBAG rbag
# define Swizzle_RAGB ragb
# define Swizzle_RABG rabg
# define Swizzle_GRBA grba
# define Swizzle_GRAB grab
# define Swizzle_GBRA gbra
# define Swizzle_GBAR gbar
# define Swizzle_GARB garb
# define Swizzle_GABR gabr
# define Swizzle_BRGA brga
# define Swizzle_BRAG brag
# define Swizzle_BGRA bgra
# define Swizzle_BGAR bgar
# define Swizzle_BARG barg
# define Swizzle_BAGR bagr
# define Swizzle_ARGB argb
# define Swizzle_ARBG arbg
# define Swizzle_AGRB agrb
# define Swizzle_AGBR agbr
# define Swizzle_ABRG abrg
# define Swizzle_ABGR abgr
#else
# define Writer_Swizzle( Input, Output, Name )\
inline Output Name()const\
{\
auto & shader = findWriterMandat( *this );\
return Output{ shader\
, sdw::makeSwizzle( makeExpr( shader, this->getExpr() )\
, expr::SwizzleKind::e##Name )\
, this->isEnabled() };\
}
# define Writer_FirstSwizzle( Input, Output, Name )\
Writer_Swizzle( Input, Output, Name )
# define Writer_LastSwizzle( Input, Output, Name )\
Writer_Swizzle( Input, Output, Name )
# define Swizzle_X x()
# define Swizzle_Y y()
# define Swizzle_Z z()
# define Swizzle_W w()
# define Swizzle_R r()
# define Swizzle_G g()
# define Swizzle_B b()
# define Swizzle_A a()
# define Swizzle_XY xy()
# define Swizzle_XZ xz()
# define Swizzle_XW xw()
# define Swizzle_YX yx()
# define Swizzle_YZ yz()
# define Swizzle_YW yw()
# define Swizzle_ZX zx()
# define Swizzle_ZY zy()
# define Swizzle_ZW zw()
# define Swizzle_WX wx()
# define Swizzle_WY wy()
# define Swizzle_WZ wz()
# define Swizzle_RG rg()
# define Swizzle_RB rb()
# define Swizzle_RA ra()
# define Swizzle_GR gr()
# define Swizzle_GB gb()
# define Swizzle_GA ga()
# define Swizzle_BR br()
# define Swizzle_BG bg()
# define Swizzle_BA ba()
# define Swizzle_AR ar()
# define Swizzle_AG ag()
# define Swizzle_AB ab()
# define Swizzle_XYZ xyz()
# define Swizzle_XYW xyw()
# define Swizzle_XZY xzy()
# define Swizzle_XZW xzw()
# define Swizzle_XWY xwy()
# define Swizzle_XWZ xwz()
# define Swizzle_YXZ yxz()
# define Swizzle_YXW yxw()
# define Swizzle_YZX yzx()
# define Swizzle_YZW yzw()
# define Swizzle_YWX ywx()
# define Swizzle_YWZ ywz()
# define Swizzle_ZXY zxy()
# define Swizzle_ZXW zxw()
# define Swizzle_ZYX zyx()
# define Swizzle_ZYW zyw()
# define Swizzle_ZWX zwx()
# define Swizzle_ZWY zwy()
# define Swizzle_WXY wxy()
# define Swizzle_WXZ wxz()
# define Swizzle_WYX wyx()
# define Swizzle_WYZ wyz()
# define Swizzle_WZX wzx()
# define Swizzle_WZY wzy()
# define Swizzle_RGB rgb()
# define Swizzle_RGA rga()
# define Swizzle_RBG rbg()
# define Swizzle_RBA rba()
# define Swizzle_RAG rag()
# define Swizzle_RAB rab()
# define Swizzle_GRB grb()
# define Swizzle_GRA gra()
# define Swizzle_GBR gbr()
# define Swizzle_GBA gba()
# define Swizzle_GAR gar()
# define Swizzle_GAB gab()
# define Swizzle_BRG brg()
# define Swizzle_BRA bra()
# define Swizzle_BGR bgr()
# define Swizzle_BGA bga()
# define Swizzle_BAR bar()
# define Swizzle_BAG bag()
# define Swizzle_ARG arg()
# define Swizzle_ARB arb()
# define Swizzle_AGR agr()
# define Swizzle_AGB agb()
# define Swizzle_ABR abr()
# define Swizzle_ABG abg()
# define Swizzle_XYZW xyzw()
# define Swizzle_XYWW xyww()
# define Swizzle_XYWZ xywz()
# define Swizzle_XZYW xzyw()
# define Swizzle_XZWY xzwy()
# define Swizzle_XWYZ xwyz()
# define Swizzle_XWZY xwzy()
# define Swizzle_YXZW yxzw()
# define Swizzle_YXWZ yxwz()
# define Swizzle_YZXW yzxw()
# define Swizzle_YZWX yzwx()
# define Swizzle_YWXZ ywxz()
# define Swizzle_YWZX ywzx()
# define Swizzle_ZXYW zxyw()
# define Swizzle_ZXWY zxwy()
# define Swizzle_ZYXW zyxw()
# define Swizzle_ZYWX zywx()
# define Swizzle_ZWXY zwxy()
# define Swizzle_ZWYX zwyx()
# define Swizzle_WXYZ wxyz()
# define Swizzle_WXZY wxzy()
# define Swizzle_WYXZ wyxz()
# define Swizzle_WYZX wyzx()
# define Swizzle_WZXY wzxy()
# define Swizzle_WZYX wzyx()
# define Swizzle_RGBA rgba()
# define Swizzle_RGAB rgab()
# define Swizzle_RBGA rbga()
# define Swizzle_RBAG rbag()
# define Swizzle_RAGB ragb()
# define Swizzle_RABG rabg()
# define Swizzle_GRBA grba()
# define Swizzle_GRAB grab()
# define Swizzle_GBRA gbra()
# define Swizzle_GBAR gbar()
# define Swizzle_GARB garb()
# define Swizzle_GABR gabr()
# define Swizzle_BRGA brga()
# define Swizzle_BRAG brag()
# define Swizzle_BGRA bgra()
# define Swizzle_BGAR bgar()
# define Swizzle_BARG barg()
# define Swizzle_BAGR bagr()
# define Swizzle_ARGB argb()
# define Swizzle_ARBG arbg()
# define Swizzle_AGRB agrb()
# define Swizzle_AGBR agbr()
# define Swizzle_ABRG abrg()
# define Swizzle_ABGR abgr()
#endif
}
#include "Swizzle.inl"
#endif
| 33.586592 | 167 | 0.747006 | jarrodmky |
0c448186d41aae4579dfff8af273c54520cbe52d | 8,063 | cc | C++ | mindspore/lite/tools/converter/import/mindspore_importer.cc | Vincent34/mindspore | a39a60878a46e7e9cb02db788c0bca478f2fa6e5 | [
"Apache-2.0"
] | 1 | 2021-07-16T12:05:53.000Z | 2021-07-16T12:05:53.000Z | mindspore/lite/tools/converter/import/mindspore_importer.cc | Vincent34/mindspore | a39a60878a46e7e9cb02db788c0bca478f2fa6e5 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/tools/converter/import/mindspore_importer.cc | Vincent34/mindspore | a39a60878a46e7e9cb02db788c0bca478f2fa6e5 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 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.
*/
#include "tools/converter/import/mindspore_importer.h"
#include <memory>
#include <vector>
#include <regex>
#include "tools/converter/parser/parser_utils.h"
#include "tools/converter/import/primitive_adjust.h"
#include "tools/converter/import/mindir_adjust.h"
#include "tools/optimizer/common/gllo_utils.h"
#include "tools/common/tensor_util.h"
namespace mindspore::lite {
namespace {
constexpr size_t kConvWeightIndex = 2;
} // namespace
STATUS MindsporeImporter::Mindir2AnfAdjust(const FuncGraphPtr &func_graph, const converter::Flags &flag) {
auto primitive_adjust_pass = std::make_shared<PrimitiveAdjust>();
primitive_adjust_pass->SetFmkType(flag.fmk);
if (!primitive_adjust_pass->Run(func_graph)) {
MS_LOG(ERROR) << "primitive adjust failed.";
ReturnCode::GetSingleReturnCode()->UpdateReturnCode(RET_ERROR);
return RET_ERROR;
}
auto mindir_adjust_pass = std::make_shared<MindirAdjust>();
mindir_adjust_pass->SetFmkType(flag.fmk);
mindir_adjust_pass->SetQuantType(flag.quantType);
mindir_adjust_pass->SetTrainFlag(flag.trainModel);
if (!mindir_adjust_pass->Run(func_graph)) {
MS_LOG(ERROR) << "mindir adjust failed.";
ReturnCode::GetSingleReturnCode()->UpdateReturnCode(RET_ERROR);
return RET_ERROR;
}
return RET_OK;
}
STATUS MindsporeImporter::WeightFormatTransform(const FuncGraphPtr &graph) {
MS_ASSERT(graph != nullptr);
auto node_list = TopoSort(graph->get_return());
for (auto &node : node_list) {
if (!utils::isa<CNodePtr>(node)) {
continue;
}
auto conv_cnode = node->cast<CNodePtr>();
if (!opt::CheckPrimitiveType(node, prim::kPrimConv2DFusion) &&
!opt::CheckPrimitiveType(node, opt::kPrimConv2DBackpropInputFusion) &&
!opt::CheckPrimitiveType(node, prim::kPrimConv2dTransposeFusion)) {
continue;
}
MS_ASSERT(conv_cnode->inputs().size() > kConvWeightIndex);
int status = HardCodeMindir(conv_cnode, graph);
if (status != lite::RET_OK) {
MS_LOG(ERROR) << "Format hard code failed: " << status << ", node: " << node->fullname_with_scope();
return RET_ERROR;
}
}
return RET_OK;
}
STATUS MindsporeImporter::HardCodeMindir(const CNodePtr &conv_node, const FuncGraphPtr &graph) {
MS_ASSERT(conv_cnode != nullptr);
auto prim = GetValueNode<PrimitivePtr>(conv_node->input(0));
if (prim == nullptr) {
MS_LOG(ERROR) << "Invalid anfnode, which don't have primitive.";
return lite::RET_ERROR;
}
int64_t format = prim->GetAttr(ops::kFormat) != nullptr ? GetValue<int64_t>(prim->GetAttr(ops::kFormat)) : 0;
auto weight_node = conv_node->input(kConvWeightIndex);
schema::Format weight_dst_format = schema::Format::Format_KHWC;
STATUS status = RET_OK;
schema::Format weight_src_format = schema::Format::Format_NUM_OF_FORMAT;
switch (quant_type_) {
case QuantType_AwareTraining:
case QuantType_PostTraining:
case QuantType_WeightQuant:
case QuantType_QUANT_NONE: {
if (format == schema::Format::Format_KHWC) {
weight_src_format = schema::Format::Format_KHWC;
} else {
weight_src_format = schema::Format::Format_KCHW;
}
} break;
default: {
MS_LOG(ERROR) << "Unsupported quantType: " << EnumNameQuantType(quant_type_)
<< ", node: " << conv_node->fullname_with_scope();
return RET_ERROR;
}
}
if (utils::isa<CNodePtr>(weight_node)) {
status = HandleWeightConst(graph, conv_node, weight_node->cast<CNodePtr>(), weight_src_format, weight_dst_format);
if (status != lite::RET_OK) {
MS_LOG(ERROR) << "handle weight-const failed.";
return RET_ERROR;
}
}
weight_node = conv_node->input(kConvWeightIndex);
auto weight_value = opt::GetTensorInfo(weight_node);
if (weight_value != nullptr) {
status = opt::TransFilterFormat(weight_value, weight_src_format, weight_dst_format);
if (status != RET_OK) {
MS_LOG(ERROR) << "TransFilter " << EnumNameFormat(schema::EnumValuesFormat()[weight_dst_format]) << "To"
<< EnumNameFormat(weight_dst_format) << " failed, node : " << conv_node->fullname_with_scope()
<< "quant type:" << quant_type_;
return RET_ERROR;
}
prim->AddAttr(ops::kFormat, MakeValue<int64_t>(weight_dst_format));
auto type_id = static_cast<TypeId>(weight_value->data_type());
auto shape = weight_value->shape();
std::vector<int64_t> shape_vector(shape.begin(), shape.end());
auto abstract = lite::CreateTensorAbstract(shape_vector, type_id);
if (abstract == nullptr) {
MS_LOG(ERROR) << "Create tensor abstarct failed";
return RET_ERROR;
}
weight_node->set_abstract(abstract);
}
if (utils::isa<ParameterPtr>(weight_node)) {
status = HandleWeightSharing(graph, KHWC, weight_node->cast<ParameterPtr>(), weight_src_format, weight_dst_format);
if (status != lite::RET_OK) {
MS_LOG(ERROR) << "handle weight-sharing failed.";
return RET_ERROR;
}
}
return lite::RET_OK;
}
size_t MindsporeImporter::Hex2ByteArray(std::string hex_str, unsigned char *byte_array, size_t max_len) {
std::regex r("[0-9a-fA-F]+");
if (!std::regex_match(hex_str, r)) {
MS_LOG(ERROR) << "Some characters of dec_key not in [0-9a-fA-F]";
return 0;
}
if (hex_str.size() % 2 == 1) {
hex_str.push_back('0');
}
size_t byte_len = hex_str.size() / 2;
if (byte_len > max_len) {
MS_LOG(ERROR) << "the hexadecimal dec_key length exceeds the maximum limit: 64";
return 0;
}
for (size_t i = 0; i < byte_len; ++i) {
size_t p = i * 2;
if (hex_str[p] >= 'a' && hex_str[p] <= 'f') {
byte_array[i] = hex_str[p] - 'a' + 10;
} else if (hex_str[p] >= 'A' && hex_str[p] <= 'F') {
byte_array[i] = hex_str[p] - 'A' + 10;
} else {
byte_array[i] = hex_str[p] - '0';
}
if (hex_str[p + 1] >= 'a' && hex_str[p + 1] <= 'f') {
byte_array[i] = (byte_array[i] << 4) | (hex_str[p + 1] - 'a' + 10);
} else if (hex_str[p] >= 'A' && hex_str[p] <= 'F') {
byte_array[i] = (byte_array[i] << 4) | (hex_str[p + 1] - 'A' + 10);
} else {
byte_array[i] = (byte_array[i] << 4) | (hex_str[p + 1] - '0');
}
}
return byte_len;
}
FuncGraphPtr MindsporeImporter::ImportMindIR(const converter::Flags &flag) {
quant_type_ = flag.quantType;
FuncGraphPtr func_graph;
if (flag.dec_key.size() != 0) {
unsigned char key[32];
const size_t key_len = Hex2ByteArray(flag.dec_key, key, 32);
if (key_len == 0) {
return nullptr;
}
func_graph = LoadMindIR(flag.modelFile, false, key, key_len, flag.dec_mode);
} else {
func_graph = LoadMindIR(flag.modelFile);
}
if (func_graph == nullptr) {
MS_LOG(ERROR) << "get funcGraph failed for fmk:MINDIR";
ReturnCode::GetSingleReturnCode()->UpdateReturnCode(RET_ERROR);
return nullptr;
}
func_graph->set_attr("graph_name", MakeValue("main_graph"));
func_graph->set_attr("fmk", MakeValue(static_cast<int>(converter::FmkType_MS)));
STATUS status;
if ((status = Mindir2AnfAdjust(func_graph, flag)) != RET_OK) {
MS_LOG(ERROR) << "Mindir2AnfAdjust failed.";
ReturnCode::GetSingleReturnCode()->UpdateReturnCode(status);
return nullptr;
}
if ((status = WeightFormatTransform(func_graph)) != RET_OK) {
MS_LOG(ERROR) << "WeightFormatTransform failed.";
ReturnCode::GetSingleReturnCode()->UpdateReturnCode(status);
return nullptr;
}
return func_graph;
}
} // namespace mindspore::lite
| 38.578947 | 119 | 0.676919 | Vincent34 |
0c48d3843cc045a691df4fb5fa11b824127a990c | 2,155 | cpp | C++ | ares/gba/system/system.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 153 | 2020-07-25T17:55:29.000Z | 2021-10-01T23:45:01.000Z | ares/gba/system/system.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 245 | 2021-10-08T09:14:46.000Z | 2022-03-31T08:53:13.000Z | ares/gba/system/system.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | #include <gba/gba.hpp>
namespace ares::GameBoyAdvance {
auto enumerate() -> vector<string> {
return {
"[Nintendo] Game Boy Advance",
"[Nintendo] Game Boy Player",
};
}
auto load(Node::System& node, string name) -> bool {
if(!enumerate().find(name)) return false;
return system.load(node, name);
}
Scheduler scheduler;
BIOS bios;
System system;
#include "bios.cpp"
#include "controls.cpp"
#include "serialization.cpp"
auto System::game() -> string {
if(cartridge.node) {
return cartridge.title();
}
return "(no cartridge connected)";
}
auto System::run() -> void {
scheduler.enter();
if(GameBoyAdvance::Model::GameBoyPlayer()) player.frame();
}
auto System::load(Node::System& root, string name) -> bool {
if(node) unload();
information = {};
if(name.find("Game Boy Advance")) {
information.name = "Game Boy Advance";
information.model = Model::GameBoyAdvance;
}
if(name.find("Game Boy Player")) {
information.name = "Game Boy Player";
information.model = Model::GameBoyPlayer;
}
node = Node::System::create(information.name);
node->setGame({&System::game, this});
node->setRun({&System::run, this});
node->setPower({&System::power, this});
node->setSave({&System::save, this});
node->setUnload({&System::unload, this});
node->setSerialize({&System::serialize, this});
node->setUnserialize({&System::unserialize, this});
root = node;
if(!node->setPak(pak = platform->pak(node))) return false;
scheduler.reset();
controls.load(node);
bios.load(node);
cpu.load(node);
ppu.load(node);
apu.load(node);
cartridgeSlot.load(node);
return true;
}
auto System::save() -> void {
if(!node) return;
cartridge.save();
}
auto System::unload() -> void {
if(!node) return;
save();
bios.unload();
cpu.unload();
ppu.unload();
apu.unload();
cartridgeSlot.unload();
pak.reset();
node.reset();
}
auto System::power(bool reset) -> void {
for(auto& setting : node->find<Node::Setting::Setting>()) setting->setLatch();
bus.power();
player.power();
cpu.power();
ppu.power();
apu.power();
cartridge.power();
scheduler.power(cpu);
}
}
| 21.336634 | 80 | 0.64826 | CasualPokePlayer |
0c4989d25a814a669fb015108e6a2955c27aac80 | 1,759 | cc | C++ | squid/squid3-3.3.8.spaceify/src/tests/testStore.cc | spaceify/spaceify | 4296d6c93cad32bb735cefc9b8157570f18ffee4 | [
"MIT"
] | 4 | 2015-01-20T15:25:34.000Z | 2017-12-20T06:47:42.000Z | squid/squid3-3.3.8.spaceify/src/tests/testStore.cc | spaceify/spaceify | 4296d6c93cad32bb735cefc9b8157570f18ffee4 | [
"MIT"
] | 4 | 2015-05-15T09:32:55.000Z | 2016-02-18T13:43:31.000Z | squid/squid3-3.3.8.spaceify/src/tests/testStore.cc | spaceify/spaceify | 4296d6c93cad32bb735cefc9b8157570f18ffee4 | [
"MIT"
] | null | null | null | #define SQUID_UNIT_TEST 1
#include "squid.h"
#include "testStore.h"
#include "Store.h"
CPPUNIT_TEST_SUITE_REGISTRATION( testStore );
int
TestStore::callback()
{
return 1;
}
StoreEntry*
TestStore::get(const cache_key*)
{
return NULL;
}
void
TestStore::get(String, void (*)(StoreEntry*, void*), void*)
{}
void
TestStore::init()
{}
uint64_t
TestStore::maxSize() const
{
return 3;
}
uint64_t
TestStore::minSize() const
{
return 1;
}
uint64_t
TestStore::currentSize() const
{
return 2;
}
uint64_t
TestStore::currentCount() const
{
return 2;
}
int64_t
TestStore::maxObjectSize() const
{
return 1;
}
void
TestStore::getStats(StoreInfoStats &) const
{
}
void
TestStore::stat(StoreEntry &) const
{
const_cast<TestStore *>(this)->statsCalled = true;
}
StoreSearch *
TestStore::search(String const url, HttpRequest *)
{
return NULL;
}
void
testStore::testSetRoot()
{
StorePointer aStore(new TestStore);
Store::Root(aStore);
CPPUNIT_ASSERT(&Store::Root() == aStore.getRaw());
Store::Root(NULL);
}
void
testStore::testUnsetRoot()
{
StorePointer aStore(new TestStore);
StorePointer aStore2(new TestStore);
Store::Root(aStore);
Store::Root(aStore2);
CPPUNIT_ASSERT(&Store::Root() == aStore2.getRaw());
Store::Root(NULL);
}
void
testStore::testStats()
{
TestStorePointer aStore(new TestStore);
Store::Root(aStore.getRaw());
CPPUNIT_ASSERT(aStore->statsCalled == false);
Store::Stats(NullStoreEntry::getInstance());
CPPUNIT_ASSERT(aStore->statsCalled == true);
Store::Root(NULL);
}
void
testStore::testMaxSize()
{
StorePointer aStore(new TestStore);
Store::Root(aStore.getRaw());
CPPUNIT_ASSERT(aStore->maxSize() == 3);
Store::Root(NULL);
}
| 15.163793 | 59 | 0.682206 | spaceify |
0c4ba09acd9004f5019125826d45f4490b9acaba | 4,657 | cpp | C++ | sslpod/src/v20190605/model/CreateDomainRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | sslpod/src/v20190605/model/CreateDomainRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | sslpod/src/v20190605/model/CreateDomainRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/sslpod/v20190605/model/CreateDomainRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Sslpod::V20190605::Model;
using namespace std;
CreateDomainRequest::CreateDomainRequest() :
m_serverTypeHasBeenSet(false),
m_domainHasBeenSet(false),
m_portHasBeenSet(false),
m_iPHasBeenSet(false),
m_noticeHasBeenSet(false),
m_tagsHasBeenSet(false)
{
}
string CreateDomainRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_serverTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ServerType";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_serverType, allocator);
}
if (m_domainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Domain";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_domain.c_str(), allocator).Move(), allocator);
}
if (m_portHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Port";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_port.c_str(), allocator).Move(), allocator);
}
if (m_iPHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "IP";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_iP.c_str(), allocator).Move(), allocator);
}
if (m_noticeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Notice";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_notice, allocator);
}
if (m_tagsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Tags";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_tags.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
int64_t CreateDomainRequest::GetServerType() const
{
return m_serverType;
}
void CreateDomainRequest::SetServerType(const int64_t& _serverType)
{
m_serverType = _serverType;
m_serverTypeHasBeenSet = true;
}
bool CreateDomainRequest::ServerTypeHasBeenSet() const
{
return m_serverTypeHasBeenSet;
}
string CreateDomainRequest::GetDomain() const
{
return m_domain;
}
void CreateDomainRequest::SetDomain(const string& _domain)
{
m_domain = _domain;
m_domainHasBeenSet = true;
}
bool CreateDomainRequest::DomainHasBeenSet() const
{
return m_domainHasBeenSet;
}
string CreateDomainRequest::GetPort() const
{
return m_port;
}
void CreateDomainRequest::SetPort(const string& _port)
{
m_port = _port;
m_portHasBeenSet = true;
}
bool CreateDomainRequest::PortHasBeenSet() const
{
return m_portHasBeenSet;
}
string CreateDomainRequest::GetIP() const
{
return m_iP;
}
void CreateDomainRequest::SetIP(const string& _iP)
{
m_iP = _iP;
m_iPHasBeenSet = true;
}
bool CreateDomainRequest::IPHasBeenSet() const
{
return m_iPHasBeenSet;
}
bool CreateDomainRequest::GetNotice() const
{
return m_notice;
}
void CreateDomainRequest::SetNotice(const bool& _notice)
{
m_notice = _notice;
m_noticeHasBeenSet = true;
}
bool CreateDomainRequest::NoticeHasBeenSet() const
{
return m_noticeHasBeenSet;
}
string CreateDomainRequest::GetTags() const
{
return m_tags;
}
void CreateDomainRequest::SetTags(const string& _tags)
{
m_tags = _tags;
m_tagsHasBeenSet = true;
}
bool CreateDomainRequest::TagsHasBeenSet() const
{
return m_tagsHasBeenSet;
}
| 23.882051 | 91 | 0.703028 | suluner |
0c4e705ba82a61bd92b2df479ae3e571b063c3ac | 1,079 | cpp | C++ | client/Classes/Model/Effects/DefenceEffect.cpp | plankes-projects/BaseWar | 693f7d02fa324b917b28be58d33bb77a18d77f26 | [
"Apache-2.0"
] | 60 | 2015-01-03T07:31:14.000Z | 2021-12-17T02:39:17.000Z | client/Classes/Model/Effects/DefenceEffect.cpp | plankes-projects/BaseWar | 693f7d02fa324b917b28be58d33bb77a18d77f26 | [
"Apache-2.0"
] | 1 | 2018-08-17T09:59:30.000Z | 2018-08-17T09:59:30.000Z | client/Classes/Model/Effects/DefenceEffect.cpp | plankes-projects/BaseWar | 693f7d02fa324b917b28be58d33bb77a18d77f26 | [
"Apache-2.0"
] | 27 | 2015-01-22T06:55:10.000Z | 2021-12-17T02:39:23.000Z | /*
* Attack.cpp
*
* Created on: May 18, 2013
* Author: planke
*/
#include "DefenceEffect.h"
#include "../Units/Unit.h"
DefenceEffect::~DefenceEffect() {
}
DefenceEffect::DefenceEffect(float timeInMilliseconds, float increasedHPInPercent, float increasedDefenseInPercent) :
Effect(timeInMilliseconds, NOTICK) {
_increasedHPInPercent = increasedHPInPercent;
_increasedDefenseInPercent = increasedDefenseInPercent;
_isHarmful = false;
_GUID = 4;
_isStackAble = true; //if false, only duration is updated
}
void DefenceEffect::onApply(Unit* owner) {
float grow = _increasedHPInPercent / 2;
owner->increaseSizeBy(grow > 1 ? 1 : grow);
owner->increaseHitpointsBy(_increasedHPInPercent);
owner->increaseArmourEffectBy(_increasedDefenseInPercent);
}
void DefenceEffect::perform(Unit* owner) {
//nothing to do
}
void DefenceEffect::onRemoving(Unit* owner) {
float grow = _increasedHPInPercent / 2;
owner->decreaseSizeBy(grow > 1 ? 1 : grow);
owner->decreaseHitpointsBy(_increasedHPInPercent);
owner->decreaseArmourEffectBy(_increasedDefenseInPercent);
}
| 26.317073 | 117 | 0.762743 | plankes-projects |
31b1283cb103db9834c630868c49bcf8acde0ec2 | 2,109 | cc | C++ | src/logtrace.cc | Gear2D/gear2d | 7a9c9c479cbd8f15e5ce9050a43b041d60e8ab63 | [
"MIT"
] | 4 | 2015-05-15T06:30:23.000Z | 2018-06-17T22:34:07.000Z | src/logtrace.cc | Gear2D/gear2d | 7a9c9c479cbd8f15e5ce9050a43b041d60e8ab63 | [
"MIT"
] | null | null | null | src/logtrace.cc | Gear2D/gear2d | 7a9c9c479cbd8f15e5ce9050a43b041d60e8ab63 | [
"MIT"
] | null | null | null | #include "logtrace.h"
#ifdef ANDROID
void logtrace::initandroidlog() {
static bool initialized = false;
if (!initialized) {
std::cout.rdbuf(new androidbuf);
initialized = true;
}
}
#endif
/* logtrace static calls */
std::ostream *& logtrace::logstream() {
static std::ostream * stream = &std::cout;
return stream;
}
int & logtrace::indent() {
static int i = 0;
return i;
}
logtrace::verbosity & logtrace::globalverb() {
static logtrace::verbosity verb = logtrace::error;
return verb;
}
logtrace::verbosity & logtrace::globalverb(const verbosity & newverb) {
globalverb() = newverb;
return globalverb();
}
std::set<std::string> & logtrace::filter() {
static std::set<std::string> filters;
return filters;
}
std::set<std::string> & logtrace::ignore() {
static std::set<std::string> ignores;
return ignores;
}
void logtrace::open(const std::string & filename) {
std::ofstream * filestream = new std::ofstream(filename, std::ofstream::out | std::ofstream::trunc);
if (logstream() != &std::cout) { logstream()->flush(); delete logstream(); }
logstream() = filestream;
}
logtrace::logtrace(const std::string & module, logtrace::verbosity level) : logtrace(module, "", level) { }
logtrace::logtrace(logtrace::verbosity level) : logtrace("", "", level) { }
logtrace::logtrace(const std::string & module, const std::string & trace, logtrace::verbosity level)
: trace(trace)
, tracemodule(module)
, level(level)
, traced(false)
, done(true) {
if (!check()) return;
mark();
}
bool logtrace::check() {
if (globalverb() < level) return false; /* check if verbosity level allows */
/* check to see if there's a filter and if this is string is in there */
if (!filter().empty() && filter().find(tracemodule) == filter().end()) return false;
/* check to see if module is on the ignore list */
if (ignore().find(tracemodule) != ignore().end())
return false;
#ifdef ANDROID
initandroidlog();
#endif
return true;
}
| 26.037037 | 108 | 0.62826 | Gear2D |
31b97800bb28f7b7344e321958e8f2bc7105d464 | 1,224 | hpp | C++ | dev/Basic/long/database/dao/MacroEconomicsDao.hpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 50 | 2018-12-21T08:21:38.000Z | 2022-01-24T09:47:59.000Z | dev/Basic/long/database/dao/MacroEconomicsDao.hpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 2 | 2018-12-19T13:42:47.000Z | 2019-05-13T04:11:45.000Z | dev/Basic/long/database/dao/MacroEconomicsDao.hpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 27 | 2018-11-28T07:30:34.000Z | 2022-02-05T02:22:26.000Z | /*
* MacroEconomicsDao.hpp
*
* Created on: Jan 14, 2015
* Author: gishara
*/
#pragma once
#include "database/dao/SqlAbstractDao.hpp"
#include "database/entity/MacroEconomics.hpp"
namespace sim_mob {
namespace long_term {
/**
* Data Access Object to MacroEconomics table on datasource.
*/
class MacroEconomicsDao : public db::SqlAbstractDao<MacroEconomics> {
public:
MacroEconomicsDao(db::DB_Connection& connection);
virtual ~MacroEconomicsDao();
private:
/**
* Fills the given outObj with all values contained on Row.
* @param result row with data to fill the out object.
* @param outObj to fill.
*/
void fromRow(db::Row& result, MacroEconomics& outObj);
/**
* Fills the outParam with all values to insert or update on datasource.
* @param data to get values.
* @param outParams to put the data parameters.
* @param update tells if operation is an Update or Insert.
*/
void toRow(MacroEconomics& data, db::Parameters& outParams, bool update);
};
}
}
| 27.818182 | 85 | 0.58415 | gusugusu1018 |
31ba65ca6de30d6a73cecd3fdff53c6884fb7e3e | 29,128 | cpp | C++ | src/terminal/ScreenBuffer.cpp | kyawmyomin/Contour | 2e10035e3316cf5e90ad9f3295cfff9df7824801 | [
"Apache-2.0"
] | null | null | null | src/terminal/ScreenBuffer.cpp | kyawmyomin/Contour | 2e10035e3316cf5e90ad9f3295cfff9df7824801 | [
"Apache-2.0"
] | null | null | null | src/terminal/ScreenBuffer.cpp | kyawmyomin/Contour | 2e10035e3316cf5e90ad9f3295cfff9df7824801 | [
"Apache-2.0"
] | null | null | null | /**
* This file is part of the "libterminal" project
* Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <terminal/ScreenBuffer.h>
#include <terminal/InputGenerator.h>
#include <unicode/grapheme_segmenter.h>
#include <unicode/utf8.h>
#include <crispy/times.h>
#include <crispy/algorithm.h>
#include <crispy/utils.h>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <vector>
#if defined(LIBTERMINAL_EXECUTION_PAR)
#include <execution>
#define LIBTERMINAL_EXECUTION_COMMA(par) (std::execution:: par),
#else
#define LIBTERMINAL_EXECUTION_COMMA(par) /*!*/
#endif
using std::accumulate;
using std::cerr;
using std::endl;
using std::get;
using std::holds_alternative;
using std::max;
using std::min;
using std::next;
using std::nullopt;
using std::optional;
using std::string;
using std::vector;
using crispy::for_each;
namespace terminal {
std::string Cell::toUtf8() const
{
return unicode::to_utf8(codepoints_.data(), codepointCount_);
}
std::optional<int> ScreenBuffer::findMarkerBackward(int _currentCursorLine) const
{
if (_currentCursorLine < 0)
return nullopt;
_currentCursorLine = min(_currentCursorLine, historyLineCount() + size_.height);
// main lines
for (int i = _currentCursorLine - historyLineCount() - 1; i >= 0; --i)
if (lines.at(i).marked)
return {historyLineCount() + i};
// saved lines
for (int i = min(_currentCursorLine, historyLineCount()) - 1; i >= 0; --i)
if (savedLines.at(i).marked)
return {i};
return nullopt;
}
std::optional<int> ScreenBuffer::findMarkerForward(int _currentCursorLine) const
{
if (_currentCursorLine < 0)
return nullopt;
for (int i = _currentCursorLine + 1; i < historyLineCount(); ++i)
if (savedLines.at(i).marked)
return {i};
for (int i = _currentCursorLine < historyLineCount()
? 0 : _currentCursorLine - historyLineCount() + 1; i < size_.height; ++i)
if (lines.at(i).marked)
return {historyLineCount() + i};
return nullopt;
}
void ScreenBuffer::resize(Size const& _newSize)
{
if (_newSize.height > size_.height)
{
// Grow line count by splicing available lines from history back into buffer, if available,
// or create new ones until size_.height == _newSize.height.
auto const extendCount = _newSize.height - size_.height;
auto const rowsToTakeFromSavedLines = min(extendCount, static_cast<int>(std::size(savedLines)));
for_each(
crispy::times(rowsToTakeFromSavedLines),
[&](auto) {
savedLines.back().resize(_newSize.width);
lines.emplace_front(std::move(savedLines.back()));
savedLines.pop_back();
}
);
cursor.position.row += rowsToTakeFromSavedLines;
auto const fillLineCount = extendCount - rowsToTakeFromSavedLines;
generate_n(
back_inserter(lines),
fillLineCount,
[=]() { return Line{static_cast<size_t>(_newSize.width), Cell{}}; });
}
else if (_newSize.height < size_.height)
{
// Shrink existing line count to _newSize.height
// by splicing the number of lines to be shrinked by into savedLines bottom.
if (cursor.position.row == size_.height)
{
auto const n = size_.height - _newSize.height;
for_each(
crispy::times(n),
[&](auto) {
lines.front().resize(_newSize.width);
savedLines.emplace_back(std::move(lines.front()));
lines.pop_front();
}
);
clampSavedLines();
}
else
// Hard-cut below cursor by the number of lines to shrink.
lines.resize(_newSize.height);
assert(lines.size() == static_cast<size_t>(_newSize.height));
}
if (_newSize.width > size_.width)
{
// Grow existing columns to _newSize.width.
std::for_each(
begin(lines),
end(lines),
[=](auto& line) { line.resize(_newSize.width); }
);
if (wrapPending)
cursor.position.column++;
wrapPending = false;
}
else if (_newSize.width < size_.width)
{
// Shrink existing columns to _newSize.width.
// Nothing should be done, I think, as we preserve prior (now exceeding) content.
if (cursor.position.column == size_.width)
wrapPending = true;
// truncating tabs
while (!tabs.empty() && tabs.back() > _newSize.width)
tabs.pop_back();
}
// Reset margin to their default.
margin_ = Margin{
Margin::Range{1, _newSize.height},
Margin::Range{1, _newSize.width}
};
// TODO: find out what to do with DECOM mode. Reset it to?
size_ = _newSize;
lastCursorPosition = clampCoordinate(lastCursorPosition);
auto lastLine = next(begin(lines), lastCursorPosition.row - 1);
lastColumn = columnIteratorAt(begin(*lastLine), lastCursorPosition.column);
cursor.position = clampCoordinate(cursor.position);
updateCursorIterators();
}
void ScreenBuffer::setMode(Mode _mode, bool _enable)
{
// TODO: rename this function to indicate this is more an event to be act upon.
// TODO: thse member variables aren't really needed anymore (are they?), remove them.
switch (_mode)
{
case Mode::AutoWrap:
cursor.autoWrap = _enable;
break;
case Mode::LeftRightMargin:
// Resetting DECLRMM also resets the horizontal margins back to screen size.
if (!_enable)
margin_.horizontal = {1, size_.width};
break;
case Mode::Origin:
cursor.originMode = _enable;
break;
case Mode::VisibleCursor:
cursor.visible = _enable;
break;
default:
break;
}
}
void ScreenBuffer::moveCursorTo(Coordinate to)
{
wrapPending = false;
cursor.position = clampToScreen(toRealCoordinate(to));
updateCursorIterators();
}
void ScreenBuffer::setCursor(Cursor const& _cursor)
{
wrapPending = false;
cursor = _cursor;
updateCursorIterators();
}
Cell& ScreenBuffer::at(Coordinate const& _pos) noexcept
{
assert(crispy::ascending(1 - historyLineCount(), _pos.row, size_.height));
assert(crispy::ascending(1, _pos.column, size_.width));
if (_pos.row > 0)
return (*next(begin(lines), _pos.row - 1))[_pos.column - 1];
else
return (*next(rbegin(savedLines), -_pos.row))[_pos.column - 1];
}
void ScreenBuffer::linefeed(int _newColumn)
{
wrapPending = false;
if (realCursorPosition().row == margin_.vertical.to ||
realCursorPosition().row == size_.height)
{
scrollUp(1);
moveCursorTo({cursorPosition().row, _newColumn});
}
else
{
// using moveCursorTo() would embrace code reusage, but due to the fact that it's fully recalculating iterators,
// it may be faster to just incrementally update them.
// moveCursorTo({cursorPosition().row + 1, margin_.horizontal.from});
cursor.position.row++;
cursor.position.column = _newColumn;
currentLine++;
updateColumnIterator();
}
verifyState();
}
void ScreenBuffer::appendChar(char32_t _ch, bool _consecutive)
{
verifyState();
if (wrapPending && cursor.autoWrap)
linefeed(margin_.horizontal.from);
auto const ch =
_ch < 127 ? cursor.charsets.map(static_cast<char>(_ch))
: _ch == 0x7F ? ' ' : _ch;
bool const insertToPrev =
_consecutive
&& !lastColumn->empty()
&& unicode::grapheme_segmenter::nonbreakable(lastColumn->codepoint(lastColumn->codepointCount() - 1), ch);
if (!insertToPrev)
writeCharToCurrentAndAdvance(ch);
else
{
auto const extendedWidth = lastColumn->appendCharacter(ch);
if (extendedWidth > 0)
clearAndAdvance(extendedWidth);
}
}
void ScreenBuffer::clearAndAdvance(int _offset)
{
if (_offset == 0)
return;
auto const availableColumnCount = margin_.horizontal.length() - cursor.position.column;
auto const n = min(_offset, availableColumnCount);
if (n == _offset)
{
assert(n > 0);
cursor.position.column += n;
for (auto i = 0; i < n; ++i)
(currentColumn++)->reset(cursor.graphicsRendition, currentHyperlink);
}
else if (cursor.autoWrap)
{
wrapPending = true;
}
}
void ScreenBuffer::writeCharToCurrentAndAdvance(char32_t _character)
{
Cell& cell = *currentColumn;
cell.setCharacter(_character);
cell.attributes() = cursor.graphicsRendition;
cell.setHyperlink(currentHyperlink);
lastColumn = currentColumn;
lastCursorPosition = cursor.position;
bool const cursorInsideMargin = isModeEnabled(Mode::LeftRightMargin) && isCursorInsideMargins();
auto const cellsAvailable = cursorInsideMargin ? margin_.horizontal.to - cursor.position.column
: size_.width - cursor.position.column;
auto const n = min(cell.width(), cellsAvailable);
if (n == cell.width())
{
assert(n > 0);
cursor.position.column += n;
currentColumn++;
for (int i = 1; i < n; ++i)
(currentColumn++)->reset(cursor.graphicsRendition, currentHyperlink);
verifyState();
}
else if (cursor.autoWrap)
{
wrapPending = true;
verifyState();
}
else
verifyState();
}
void ScreenBuffer::scrollUp(int v_n)
{
scrollUp(v_n, margin_);
}
void ScreenBuffer::scrollUp(int v_n, Margin const& margin)
{
if (margin.horizontal != Margin::Range{1, size_.width})
{
// a full "inside" scroll-up
auto const marginHeight = margin.vertical.length();
auto const n = min(v_n, marginHeight);
if (n < marginHeight)
{
auto targetLine = next(begin(lines), margin.vertical.from - 1); // target line
auto sourceLine = next(begin(lines), margin.vertical.from - 1 + n); // source line
auto const bottomLine = next(begin(lines), margin.vertical.to); // bottom margin's end-line iterator
for (; sourceLine != bottomLine; ++sourceLine, ++targetLine)
{
copy_n(
next(begin(*sourceLine), margin.horizontal.from - 1),
margin.horizontal.length(),
next(begin(*targetLine), margin.horizontal.from - 1)
);
}
}
// clear bottom n lines in margin.
auto const topLine = next(begin(lines), margin.vertical.to - n);
auto const bottomLine = next(begin(lines), margin.vertical.to); // bottom margin's end-line iterator
for_each(
topLine,
bottomLine,
[&](ScreenBuffer::Line& line) {
fill_n(
next(begin(line), margin.horizontal.from - 1),
margin.horizontal.length(),
Cell{{}, cursor.graphicsRendition}
);
}
);
}
else if (margin.vertical == Margin::Range{1, size_.height})
{
// full-screen scroll-up
auto const n = min(v_n, size_.height);
if (n > 0)
{
for_each(
crispy::times(n),
[&](auto) {
savedLines.emplace_back(std::move(lines.front()));
lines.pop_front();
}
);
clampSavedLines();
generate_n(
back_inserter(lines),
n,
[this]() { return Line{static_cast<size_t>(size_.width), Cell{{}, cursor.graphicsRendition}}; }
);
}
}
else
{
// scroll up only inside vertical margin with full horizontal extend
auto const marginHeight = margin.vertical.length();
auto const n = min(v_n, marginHeight);
if (n < marginHeight)
{
rotate(
next(begin(lines), margin.vertical.from - 1),
next(begin(lines), margin.vertical.from - 1 + n),
next(begin(lines), margin.vertical.to)
);
}
for_each(
LIBTERMINAL_EXECUTION_COMMA(par)
next(begin(lines), margin.vertical.to - n),
next(begin(lines), margin.vertical.to),
[&](Line& line) {
fill(begin(line), end(line), Cell{{}, cursor.graphicsRendition});
}
);
}
updateCursorIterators();
}
void ScreenBuffer::scrollDown(int v_n)
{
scrollDown(v_n, margin_);
}
void ScreenBuffer::scrollDown(int v_n, Margin const& _margin)
{
auto const marginHeight = _margin.vertical.length();
auto const n = min(v_n, marginHeight);
if (_margin.horizontal != Margin::Range{1, size_.width})
{
// full "inside" scroll-down
if (n < marginHeight)
{
auto sourceLine = next(begin(lines), _margin.vertical.to - n - 1);
auto targetLine = next(begin(lines), _margin.vertical.to - 1);
auto const sourceEndLine = next(begin(lines), _margin.vertical.from - 1);
while (sourceLine != sourceEndLine)
{
copy_n(
next(begin(*sourceLine), _margin.horizontal.from - 1),
_margin.horizontal.length(),
next(begin(*targetLine), _margin.horizontal.from - 1)
);
--targetLine;
--sourceLine;
}
copy_n(
next(begin(*sourceLine), _margin.horizontal.from - 1),
_margin.horizontal.length(),
next(begin(*targetLine), _margin.horizontal.from - 1)
);
for_each(
next(begin(lines), _margin.vertical.from - 1),
next(begin(lines), _margin.vertical.from - 1 + n),
[_margin, this](Line& line) {
fill_n(
next(begin(line), _margin.horizontal.from - 1),
_margin.horizontal.length(),
Cell{{}, cursor.graphicsRendition}
);
}
);
}
else
{
// clear everything in margin
for_each(
next(begin(lines), _margin.vertical.from - 1),
next(begin(lines), _margin.vertical.to),
[_margin, this](Line& line) {
fill_n(
next(begin(line), _margin.horizontal.from - 1),
_margin.horizontal.length(),
Cell{{}, cursor.graphicsRendition}
);
}
);
}
}
else if (_margin.vertical == Margin::Range{1, size_.height})
{
rotate(
begin(lines),
next(begin(lines), marginHeight - n),
end(lines)
);
for_each(
begin(lines),
next(begin(lines), n),
[this](Line& line) {
fill(
begin(line),
end(line),
Cell{{}, cursor.graphicsRendition}
);
}
);
}
else
{
// scroll down only inside vertical margin with full horizontal extend
rotate(
next(begin(lines), _margin.vertical.from - 1),
next(begin(lines), _margin.vertical.to - n),
next(begin(lines), _margin.vertical.to)
);
for_each(
next(begin(lines), _margin.vertical.from - 1),
next(begin(lines), _margin.vertical.from - 1 + n),
[this](Line& line) {
fill(
begin(line),
end(line),
Cell{{}, cursor.graphicsRendition}
);
}
);
}
updateCursorIterators();
}
void ScreenBuffer::deleteChars(int _lineNo, int _n)
{
auto line = next(begin(lines), _lineNo - 1);
auto column = next(begin(*line), realCursorPosition().column - 1);
auto rightMargin = next(begin(*line), margin_.horizontal.to);
auto const n = min(_n, static_cast<int>(distance(column, rightMargin)));
rotate(
column,
next(column, n),
rightMargin
);
updateCursorIterators();
rightMargin = next(begin(*line), margin_.horizontal.to);
fill(
prev(rightMargin, n),
rightMargin,
Cell{L' ', cursor.graphicsRendition}
);
}
/// Inserts @p _n characters at given line @p _lineNo.
void ScreenBuffer::insertChars(int _lineNo, int _n)
{
auto const n = min(_n, margin_.horizontal.to - cursorPosition().column + 1);
auto line = next(begin(lines), _lineNo - 1);
auto column0 = next(begin(*line), realCursorPosition().column - 1);
auto column1 = next(begin(*line), margin_.horizontal.to - n);
auto column2 = next(begin(*line), margin_.horizontal.to);
rotate(
column0,
column1,
column2
);
if (line == currentLine)
updateColumnIterator();
fill_n(
columnIteratorAt(begin(*line), cursor.position.column),
n,
Cell{L' ', cursor.graphicsRendition}
);
}
void ScreenBuffer::insertColumns(int _n)
{
for (int lineNo = margin_.vertical.from; lineNo <= margin_.vertical.to; ++lineNo)
insertChars(lineNo, _n);
}
void ScreenBuffer::setCurrentColumn(int _n)
{
auto const col = cursor.originMode ? margin_.horizontal.from + _n - 1 : _n;
auto const clampedCol = min(col, size_.width);
cursor.position.column = clampedCol;
updateColumnIterator();
verifyState();
}
bool ScreenBuffer::incrementCursorColumn(int _n)
{
auto const n = min(_n, margin_.horizontal.length() - cursor.position.column);
cursor.position.column += n;
updateColumnIterator();
verifyState();
return n == _n;
}
void ScreenBuffer::clampSavedLines()
{
if (maxHistoryLineCount_.has_value())
while (savedLines.size() > maxHistoryLineCount_.value())
savedLines.pop_front();
}
void ScreenBuffer::clearAllTabs()
{
tabs.clear();
tabWidth = 0;
}
void ScreenBuffer::clearTabUnderCursor()
{
// populate tabs vector in case of default tabWidth is used (until now).
if (tabs.empty() && tabWidth != 0)
for (int column = tabWidth; column <= size().width; column += tabWidth)
tabs.emplace_back(column);
// erase the specific tab underneath
if (auto i = find(begin(tabs), end(tabs), realCursorPosition().column); i != end(tabs))
tabs.erase(i);
}
void ScreenBuffer::setTabUnderCursor()
{
tabs.emplace_back(realCursorPosition().column);
sort(begin(tabs), end(tabs));
}
void ScreenBuffer::verifyState() const
{
#if !defined(NDEBUG)
auto const lrmm = isModeEnabled(Mode::LeftRightMargin);
if (wrapPending &&
((lrmm && cursor.position.column != margin_.horizontal.to)
|| (!lrmm && cursor.position.column != size_.width)))
{
fail(fmt::format(
"Wrap is pending but cursor's column ({}) is not at right side of margin ({}) or screen ({}).",
cursor.position.column, margin_.horizontal.to, size_.width
));
}
if (static_cast<size_t>(size_.height) != lines.size())
fail(fmt::format("Line count mismatch. Actual line count {} but should be {}.", lines.size(), size_.height));
// verify cursor positions
[[maybe_unused]] auto const clampedCursorPos = clampToScreen(cursor.position);
if (cursor.position != clampedCursorPos)
fail(fmt::format("Cursor {} does not match clamp to screen {}.", cursor, clampedCursorPos));
// FIXME: the above triggers on tmux vertical screen split (cursor.column off-by-one)
// verify iterators
[[maybe_unused]] auto const line = next(begin(lines), cursor.position.row - 1);
[[maybe_unused]] auto const col = columnIteratorAt(cursor.position.column);
if (line != currentLine)
fail(fmt::format("Calculated current line does not match."));
else if (col != currentColumn)
fail(fmt::format("Calculated current column does not match."));
if (wrapPending && cursor.position.column != size_.width && cursor.position.column != margin_.horizontal.to)
fail(fmt::format("wrapPending flag set when cursor is not in last column."));
#endif
}
void ScreenBuffer::dumpState(std::string const& _message) const
{
auto const hline = [&]() {
for_each(crispy::times(size_.width), [](auto) { cerr << '='; });
cerr << endl;
};
hline();
cerr << "\033[1;37;41m" << _message << "\033[m" << endl;
hline();
cerr << fmt::format("Rendered screen at the time of failure: {}\n", size_);
cerr << fmt::format("cursor position : {}\n", cursor);
if (cursor.originMode)
cerr << fmt::format("real cursor position : {})\n", toRealCoordinate(cursor.position));
cerr << fmt::format("vertical margins : {}\n", margin_.vertical);
cerr << fmt::format("horizontal margins : {}\n", margin_.horizontal);
hline();
cerr << screenshot();
hline();
// TODO: print more useful debug information
// - screen size
// - left/right margin
// - top/down margin
// - cursor position
// - autoWrap
// - wrapPending
// - ... other output related modes
}
void ScreenBuffer::fail(std::string const& _message) const
{
dumpState(_message);
assert(false);
}
string ScreenBuffer::renderTextLine(int row) const
{
string line;
line.reserve(size_.width);
for (int col = 1; col <= size_.width; ++col)
if (auto const& cell = at({row, col}); cell.codepointCount())
line += cell.toUtf8();
else
line += " "; // fill character
return line;
}
string ScreenBuffer::renderText() const
{
string text;
text.reserve(size_.height * (size_.width + 1));
for (int row = 1; row <= size_.height; ++row)
{
text += renderTextLine(row);
text += '\n';
}
return text;
}
class VTWriter // {{{
{
public:
using Writer = std::function<void(char const*, size_t)>;
explicit VTWriter(Writer writer) : writer_{std::move(writer)} {}
explicit VTWriter(std::ostream& output) : VTWriter{[&](auto d, auto n) { output.write(d, n); }} {}
explicit VTWriter(std::vector<char>& output) : VTWriter{[&](auto d, auto n) { output.insert(output.end(), d, d + n); }} {}
void setCursorKeysMode(KeyMode _mode) noexcept { cursorKeysMode_ = _mode; }
bool normalCursorKeys() const noexcept { return cursorKeysMode_ == KeyMode::Normal; }
bool applicationCursorKeys() const noexcept { return !normalCursorKeys(); }
void write(char32_t v)
{
write(unicode::to_utf8(v));
}
void write(std::string_view const& _s)
{
flush();
writer_(_s.data(), _s.size());
}
template <typename... Args>
void write(std::string_view const& _s, Args&&... _args)
{
write(fmt::format(_s, std::forward<Args>(_args)...));
}
void flush()
{
if (!sgr_.empty())
{
auto const f = flush(sgr_);
sgr_.clear();
writer_(f.data(), f.size());
}
}
string flush(vector<unsigned> const& _sgr)
{
if (_sgr.empty())
return "";
auto const params =
_sgr.size() != 1 || _sgr[0] != 0
? accumulate(begin(_sgr), end(_sgr), string{},
[](auto a, auto b) {
return a.empty() ? fmt::format("{}", b) : fmt::format("{};{}", a, b);
})
: string();
return fmt::format("\033[{}m", params);
}
void sgr_add(unsigned n)
{
if (n == 0)
{
sgr_.clear();
sgr_.push_back(n);
currentForegroundColor_ = DefaultColor{};
currentBackgroundColor_ = DefaultColor{};
currentUnderlineColor_ = DefaultColor{};
}
else
{
if (sgr_.empty() || sgr_.back() != n)
sgr_.push_back(n);
if (sgr_.size() == 16)
{
write(flush(sgr_));
sgr_.clear();
}
}
}
void sgr_add(GraphicsRendition m)
{
sgr_add(static_cast<unsigned>(m));
}
void setForegroundColor(Color const& _color)
{
if (true) // _color != currentForegroundColor_)
{
currentForegroundColor_ = _color;
if (holds_alternative<IndexedColor>(_color))
{
auto const colorValue = get<IndexedColor>(_color);
if (static_cast<unsigned>(colorValue) < 8)
sgr_add(30 + static_cast<unsigned>(colorValue));
else
{
sgr_add(38);
sgr_add(5);
sgr_add(static_cast<unsigned>(colorValue));
}
}
else if (holds_alternative<DefaultColor>(_color))
sgr_add(39);
else if (holds_alternative<BrightColor>(_color))
sgr_add(90 + static_cast<unsigned>(get<BrightColor>(_color)));
else if (holds_alternative<RGBColor>(_color))
{
auto const& rgb = get<RGBColor>(_color);
sgr_add(38);
sgr_add(2);
sgr_add(static_cast<unsigned>(rgb.red));
sgr_add(static_cast<unsigned>(rgb.green));
sgr_add(static_cast<unsigned>(rgb.blue));
}
}
}
void setBackgroundColor(Color const& _color)
{
if (true)//_color != currentBackgroundColor_)
{
currentBackgroundColor_ = _color;
if (holds_alternative<IndexedColor>(_color))
{
auto const colorValue = get<IndexedColor>(_color);
if (static_cast<unsigned>(colorValue) < 8)
sgr_add(40 + static_cast<unsigned>(colorValue));
else
{
sgr_add(48);
sgr_add(5);
sgr_add(static_cast<unsigned>(colorValue));
}
}
else if (holds_alternative<DefaultColor>(_color))
sgr_add(49);
else if (holds_alternative<BrightColor>(_color))
sgr_add(100 + static_cast<unsigned>(get<BrightColor>(_color)));
else if (holds_alternative<RGBColor>(_color))
{
auto const& rgb = get<RGBColor>(_color);
sgr_add(48);
sgr_add(2);
sgr_add(static_cast<unsigned>(rgb.red));
sgr_add(static_cast<unsigned>(rgb.green));
sgr_add(static_cast<unsigned>(rgb.blue));
}
}
}
private:
Writer writer_;
std::vector<unsigned> sgr_;
std::stringstream sstr;
Color currentForegroundColor_ = DefaultColor{};
Color currentUnderlineColor_ = DefaultColor{};
Color currentBackgroundColor_ = DefaultColor{};
KeyMode cursorKeysMode_ = KeyMode::Normal;
};
// }}}
std::string ScreenBuffer::screenshot() const
{
auto result = std::stringstream{};
auto writer = VTWriter(result);
for (int const row : crispy::times(1, size_.height))
{
for (int const col : crispy::times(1, size_.width))
{
Cell const& cell = at({row, col});
if (cell.attributes().styles & CharacterStyleMask::Bold)
writer.sgr_add(GraphicsRendition::Bold);
else
writer.sgr_add(GraphicsRendition::Normal);
// TODO: other styles (such as underline, ...)?
writer.setForegroundColor(cell.attributes().foregroundColor);
writer.setBackgroundColor(cell.attributes().backgroundColor);
if (!cell.codepointCount())
writer.write(U' ');
else
for (char32_t const ch : cell.codepoints())
writer.write(ch);
}
writer.sgr_add(GraphicsRendition::Reset);
writer.write('\r');
writer.write('\n');
}
return result.str();
}
} // end namespace
| 30.596639 | 126 | 0.571787 | kyawmyomin |
31bc1a58d99ba272d9042fc85b1bff354fd28044 | 1,119 | cpp | C++ | EZOJ/1721.cpp | sshockwave/Online-Judge-Solutions | 9d0bc7fd68c3d1f661622929c1cb3752601881d3 | [
"MIT"
] | 6 | 2019-09-30T16:11:00.000Z | 2021-11-01T11:42:33.000Z | EZOJ/1721.cpp | sshockwave/Online-Judge-Solutions | 9d0bc7fd68c3d1f661622929c1cb3752601881d3 | [
"MIT"
] | 4 | 2017-11-21T08:17:42.000Z | 2020-07-28T12:09:52.000Z | EZOJ/1721.cpp | sshockwave/Online-Judge-Solutions | 9d0bc7fd68c3d1f661622929c1cb3752601881d3 | [
"MIT"
] | 4 | 2017-07-26T05:54:06.000Z | 2020-09-30T13:35:38.000Z | #include <iostream>
#include <cstdio>
#include <cstring>
#include <cassert>
using namespace std;
inline bool is_num(char c){
return c>='0'&&c<='9';
}
inline int ni(){
int i=0;char c;
while(!is_num(c=getchar()));
while(i=i*10-'0'+c,is_num(c=getchar()));
return i;
}
const int N=10000010;
int prime[N],ptop=0,mu[N],lambda[N],_lambda[N];
bool np[N];
int main(){
memset(np,0,sizeof(np));
mu[1]=1;
lambda[1]=_lambda[0]=_lambda[1]=0;
for(int i=2;i<N;i++){
if(!np[i]){
prime[ptop++]=i;
mu[i]=-1;
lambda[i]=1;
}
for(int j=0;j<ptop&&i*prime[j]<N;j++){
np[i*prime[j]]=true;
if(i%prime[j]==0){
mu[i*prime[j]]=0;
if((i/prime[j])%prime[j]==0){
lambda[i*prime[j]]=0;
}else{
lambda[i*prime[j]]=mu[i];
}
break;
}else{
mu[i*prime[j]]=-mu[i];
lambda[i*prime[j]]=mu[i]-lambda[i];
}
}
_lambda[i]=_lambda[i-1]+lambda[i];
}
for(int tot=ni();tot--;){
int n=ni(),m=ni();
long long ans=0;
for(int l=1,r,top=min(m,n);l<=top;l=r+1){
r=min(top,min(n/(n/l),m/(m/l)));
ans+=(long long)(n/l)*(m/l)*(_lambda[r]-_lambda[l-1]);
}
printf("%lld\n",ans);
}
}
| 20.345455 | 57 | 0.549598 | sshockwave |
31c12556760721ada46b711e037f588302bcdac7 | 2,432 | hpp | C++ | Gnc/Utils/AckermannConverter/AckermannConverterComponentImpl.hpp | genemerewether/fprime | fcdd071b5ddffe54ade098ca5d451903daba9eed | [
"Apache-2.0"
] | 5 | 2019-10-22T03:41:02.000Z | 2022-01-16T12:48:31.000Z | Gnc/Utils/AckermannConverter/AckermannConverterComponentImpl.hpp | genemerewether/fprime | fcdd071b5ddffe54ade098ca5d451903daba9eed | [
"Apache-2.0"
] | 27 | 2019-02-07T17:58:58.000Z | 2019-08-13T00:46:24.000Z | Gnc/Utils/AckermannConverter/AckermannConverterComponentImpl.hpp | genemerewether/fprime | fcdd071b5ddffe54ade098ca5d451903daba9eed | [
"Apache-2.0"
] | 3 | 2019-01-01T18:44:37.000Z | 2019-08-01T01:19:39.000Z | // ======================================================================
// \title AckermannConverterImpl.hpp
// \author mereweth
// \brief hpp file for AckermannConverter component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
//
// This software may be subject to U.S. export control laws and
// regulations. By accepting this document, the user agrees to comply
// with all U.S. export laws and regulations. User has the
// responsibility to obtain export licenses, or other export authority
// as may be required before exporting such information to foreign
// countries or providing access to foreign persons.
// ======================================================================
#ifndef AckermannConverter_HPP
#define AckermannConverter_HPP
#include "Gnc/Utils/AckermannConverter/AckermannConverterComponentAc.hpp"
namespace Gnc {
class AckermannConverterComponentImpl :
public AckermannConverterComponentBase
{
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object AckermannConverter
//!
AckermannConverterComponentImpl(
#if FW_OBJECT_NAMES == 1
const char *const compName /*!< The component name*/
#else
void
#endif
);
//! Initialize object AckermannConverter
//!
void init(
const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/
);
//! Destroy object AckermannConverter
//!
~AckermannConverterComponentImpl(void);
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for ackermann
//!
void ackermann_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
ROS::ackermann_msgs::AckermannDriveStamped &AckermannDriveStamped
);
};
} // end namespace Gnc
#endif
| 32 | 79 | 0.575658 | genemerewether |
31c2c5f20495c3b6a74d21eb34910702277df60c | 4,518 | hpp | C++ | src/centurion/math/vector3.hpp | twantonie/centurion | 198b80f9e8a29da2ae7d3c15e48ffa1a046165c3 | [
"MIT"
] | 126 | 2020-12-05T00:05:56.000Z | 2022-03-30T15:15:03.000Z | src/centurion/math/vector3.hpp | twantonie/centurion | 198b80f9e8a29da2ae7d3c15e48ffa1a046165c3 | [
"MIT"
] | 46 | 2020-12-27T14:25:22.000Z | 2022-01-26T13:58:11.000Z | src/centurion/math/vector3.hpp | twantonie/centurion | 198b80f9e8a29da2ae7d3c15e48ffa1a046165c3 | [
"MIT"
] | 13 | 2021-01-20T20:50:18.000Z | 2022-03-25T06:59:03.000Z | #ifndef CENTURION_VECTOR3_HEADER
#define CENTURION_VECTOR3_HEADER
#include <ostream> // ostream
#include <string> // string, to_string
#include "../compiler/features.hpp"
#if CENTURION_HAS_FEATURE_FORMAT
#include <format> // format
#endif // CENTURION_HAS_FEATURE_FORMAT
namespace cen {
/// \addtogroup math
/// \{
/**
* \struct vector3
*
* \brief A simple representation of a 3-dimensional vector.
*
* \serializable
*
* \tparam T the representation type, e.g. `float` or `double`.
*
* \since 5.2.0
*/
template <typename T>
struct vector3 final
{
using value_type = T; ///< The type of the vector components.
value_type x{}; ///< The x-coordinate of the vector.
value_type y{}; ///< The y-coordinate of the vector.
value_type z{}; ///< The z-coordinate of the vector.
#if CENTURION_HAS_FEATURE_SPACESHIP
[[nodiscard]] constexpr auto operator<=>(const vector3&) const noexcept = default;
#endif // CENTURION_HAS_FEATURE_SPACESHIP
/**
* \brief Casts the vector to a vector with another representation type.
*
* \tparam U the target vector type.
*
* \return the result vector.
*
* \since 5.2.0
*/
template <typename U>
[[nodiscard]] explicit operator vector3<U>() const noexcept
{
using target_value_type = typename vector3<U>::value_type;
return vector3<U>{static_cast<target_value_type>(x),
static_cast<target_value_type>(y),
static_cast<target_value_type>(z)};
}
};
/**
* \brief Serializes a 3D-vector.
*
* \details This function expects that the archive provides an overloaded `operator()`,
* used for serializing data. This API is based on the Cereal serialization library.
*
* \tparam Archive the type of the archive.
* \tparam T the type of the vector components.
*
* \param archive the archive used to serialize the vector.
* \param vector the vector that will be serialized.
*
* \since 5.3.0
*/
template <typename Archive, typename T>
void serialize(Archive& archive, vector3<T>& vector)
{
archive(vector.x, vector.y, vector.z);
}
/// \name Vector3 comparison operators
/// \{
#if !CENTURION_HAS_FEATURE_SPACESHIP
/**
* \brief Indicates whether or not two 3D vectors are equal.
*
* \tparam T the representation type used by the vectors.
*
* \param lhs the left-hand side vector.
* \param rhs the right-hand side vector.
*
* \return `true` if the vectors are equal; `false` otherwise.
*
* \since 5.2.0
*/
template <typename T>
[[nodiscard]] constexpr auto operator==(const vector3<T>& lhs, const vector3<T>& rhs) noexcept
-> bool
{
return (lhs.x == rhs.x) && (lhs.y == rhs.y) && (lhs.z == rhs.z);
}
/**
* \brief Indicates whether or not two 3D vectors aren't equal.
*
* \tparam T the representation type used by the vectors.
*
* \param lhs the left-hand side vector.
* \param rhs the right-hand side vector.
*
* \return `true` if the vectors aren't equal; `false` otherwise.
*
* \since 5.2.0
*/
template <typename T>
[[nodiscard]] constexpr auto operator!=(const vector3<T>& lhs, const vector3<T>& rhs) noexcept
-> bool
{
return !(lhs == rhs);
}
#endif // CENTURION_HAS_FEATURE_SPACESHIP
/// \} End of vector3 comparison operators
/// \name String conversions
/// \{
/**
* \brief Returns a string that represents a vector.
*
* \tparam T the representation type used by the vector.
*
* \param vector the vector that will be converted to a string.
*
* \return a string that represents the supplied vector.
*
* \since 5.2.0
*/
template <typename T>
[[nodiscard]] auto to_string(const vector3<T>& vector) -> std::string
{
#if CENTURION_HAS_FEATURE_FORMAT
return std::format("vector3{{x: {}, y: {}, z: {}}}", vector.x, vector.y, vector.z);
#else
return "vector3{x: " + std::to_string(vector.x) + ", y: " + std::to_string(vector.y) +
", z: " + std::to_string(vector.z) + "}";
#endif // CENTURION_HAS_FEATURE_FORMAT
}
/// \} End of string conversions
/// \name Streaming
/// \{
/**
* \brief Prints a textual representation of a vector.
*
* \tparam T the representation type used by the vector.
*
* \param stream the stream that will be used.
* \param vector the vector that will be printed.
*
* \return the used stream.
*
* \since 5.2.0
*/
template <typename T>
auto operator<<(std::ostream& stream, const vector3<T>& vector) -> std::ostream&
{
return stream << to_string(vector);
}
/// \} End of streaming
/// \} End of group math
} // namespace cen
#endif // CENTURION_VECTOR3_HEADER
| 24.160428 | 94 | 0.671536 | twantonie |
31c2d177152f49f463f5fdbc04f4f5cb8ea0e6d4 | 2,641 | cpp | C++ | source/engine/geometry/Ray.cpp | compix/Mesh-Decimator | 0c1da7ad4601c5eec1642742068a48933e6fa846 | [
"MIT"
] | 7 | 2017-03-07T14:15:32.000Z | 2020-06-28T21:10:35.000Z | source/engine/geometry/Ray.cpp | compix/Mesh-Decimator | 0c1da7ad4601c5eec1642742068a48933e6fa846 | [
"MIT"
] | null | null | null | source/engine/geometry/Ray.cpp | compix/Mesh-Decimator | 0c1da7ad4601c5eec1642742068a48933e6fa846 | [
"MIT"
] | null | null | null | #include "Ray.h"
#include <engine/rendering/geometry/Mesh.h>
#include "Transform.h"
/**
* Adaptation of the "Slabs Method" from Real-Time Rendering 3rd Edition
*/
bool Ray::intersects(const OBBox& obb, float& t) const
{
float tMin = -FLT_MAX;
float tMax = FLT_MAX;
glm::vec3 obbCenter(obb.model[3]);
glm::vec3 p = obbCenter - origin;
// Check intersections with all axes
for (uint8_t i = 0; i < 3; ++i)
{
glm::vec3 axis = glm::normalize(glm::vec3(obb.model[i]));
float e = glm::dot(axis, p);
float f = glm::dot(axis, direction); // = cos(angle between axis and direction) since axis and direction are unit vectors
if (std::abs(f) > math::EPSILON)
{
// Compute intersection points. This is just simple trigonometry
float t1 = (e + obb.he[i]) / f;
float t2 = (e - obb.he[i]) / f;
if (t1 > t2)
std::swap(t1, t2);
if (t1 > tMin)
tMin = t1;
if (t2 < tMax)
tMax = t2;
// If the ray misses or the obb is "behind" the ray then there is no intersection
if (tMin > tMax || tMax < 0)
return false;
}
// Axis and ray are parallel -> check if ray is outside the slab
else if (-e - obb.he[i] > 0 || -e + obb.he[i] < 0)
return false;
}
if(tMin > 0)
{
t = tMin;
return true;
}
t = tMax;
return true;
}
bool Ray::intersectsTriangle(const glm::vec3& p0, const glm::vec3& p1, const glm::vec3& p2, glm::vec2& uv, float& t) const
{
glm::vec3 e1 = p1 - p0;
glm::vec3 e2 = p2 - p0;
glm::vec3 q = glm::cross(direction, e2);
float a = glm::dot(e1, q);
if (a > -math::EPSILON5 && a < math::EPSILON5)
return false;
float f = 1.f / a;
glm::vec3 s = origin - p0;
uv.x = f * glm::dot(s, q);
if (uv.x < 0.f)
return false;
glm::vec3 r = glm::cross(s, e1);
uv.y = f * glm::dot(direction, r);
if (uv.y < 0.f || (uv.x + uv.y) > 1.f)
return false;
t = f * glm::dot(e2, r);
return true;
}
bool Ray::intersectsSphere(const glm::vec3& pos, const float& radius, float& t) const
{
glm::vec3 toSphere = origin - pos;
float a = glm::dot(direction, direction);
float b = glm::dot(direction, (2.0f * toSphere));
float c = glm::dot(toSphere, toSphere) - radius * radius;
float d = b * b - 4.0f * a * c;
if (d > 0.0f)
{
t = (-b - sqrtf(d)) / (2.0f * a);
if (t > 0.0f)
return true;
}
return false;
}
| 24.229358 | 129 | 0.517986 | compix |
31c395f56ebf021b843d39a805f7d24ab94733b0 | 4,328 | cpp | C++ | src/FalconEngine/Graphics/Renderer/Resource/Texture.cpp | Lywx/FalconEngine | c4d1fed789218d1994908b8dbbcd6c01961f9ef2 | [
"MIT"
] | 6 | 2017-04-17T12:34:57.000Z | 2019-10-19T23:29:59.000Z | src/FalconEngine/Graphics/Renderer/Resource/Texture.cpp | Lywx/FalconEngine | c4d1fed789218d1994908b8dbbcd6c01961f9ef2 | [
"MIT"
] | null | null | null | src/FalconEngine/Graphics/Renderer/Resource/Texture.cpp | Lywx/FalconEngine | c4d1fed789218d1994908b8dbbcd6c01961f9ef2 | [
"MIT"
] | 2 | 2019-12-30T08:28:04.000Z | 2020-08-05T09:58:53.000Z | #include <FalconEngine/Graphics/Renderer/Resource/Texture.h>
#include <FalconEngine/Core/Exception.h>
#include <FalconEngine/Graphics/Renderer/Renderer.h>
#include <FalconEngine/Content/StbLibGuardBegin.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>
#include <FalconEngine/Content/StbLibGuardEnd.h>
namespace FalconEngine
{
/************************************************************************/
/* Constructors and Destructor */
/************************************************************************/
// NOTE(Wuxiang): This default constructor is used in deserialization for texture
// loading.
Texture::Texture() :
mAccessMode(ResourceCreationAccessMode::None),
mAccessUsage(ResourceCreationAccessUsage::None),
mAttachment(),
mDimension(),
mFormat(TextureFormat::None),
mMipmapLevel(0),
mData(nullptr),
mDataSize(0),
mStorageMode(ResourceStorageMode::None),
mType(TextureType::None)
{
}
Texture::Texture(AssetSource assetSource,
const std::string& fileName,
const std::string& filePath,
int width,
int height,
int depth,
TextureFormat format,
TextureType type,
ResourceCreationAccessMode accessMode,
ResourceCreationAccessUsage accessUsage,
ResourceStorageMode storageMode,
int mipmapLevel) :
Asset(assetSource, AssetType::Texture, fileName, filePath),
mAccessMode(accessMode),
mAccessUsage(accessUsage),
mAttachment(),
mDimension(),
mFormat(format),
mMipmapLevel(mipmapLevel),
mStorageMode(storageMode),
mType(type)
{
// Test validity of dimension.
if (width < 1 || height < 1 || depth < 1)
{
FALCON_ENGINE_THROW_RUNTIME_EXCEPTION("Invalid texture dimension.");
}
mDimension[0] = width;
mDimension[1] = height;
mDimension[2] = depth;
// Allocate texture storage.
if (mStorageMode == ResourceStorageMode::Device)
{
mDataSize = 0;
mData = nullptr;
}
else if (mStorageMode == ResourceStorageMode::Host)
{
mDataSize = size_t(mDimension[0]) * size_t(mDimension[1])
* size_t(mDimension[2]) * TexelSize[TextureFormatIndex(mFormat)];
mData = new unsigned char[mDataSize];
}
else
{
FALCON_ENGINE_THROW_ASSERTION_EXCEPTION();
}
}
Texture::~Texture()
{
FALCON_ENGINE_RENDERER_UNBIND(this);
delete[] mData;
}
/************************************************************************/
/* Public Members */
/************************************************************************/
ResourceCreationAccessMode
Texture::GetAccessMode() const
{
return mAccessMode;
}
void
Texture::SetAccessModeInternal(ResourceCreationAccessMode accessMode)
{
mAccessMode = accessMode;
}
ResourceCreationAccessUsage
Texture::GetAccessUsage() const
{
return mAccessUsage;
}
void
Texture::SetAccessUsageInternal(ResourceCreationAccessUsage accessUsage)
{
mAccessUsage = accessUsage;
}
bool
Texture::GetAttachmentEnabled(TextureMode textureMode) const
{
return mAttachment[TextureModeIndex(textureMode)];
}
void
Texture::SetAttachmentEnabled(TextureMode textureMode)
{
mAttachment[TextureModeIndex(textureMode)] = true;
}
void
Texture::ResetAttachmentEnabled(TextureMode textureMode)
{
mAttachment.fill(false);
SetAttachmentEnabled(textureMode);
}
unsigned char *
Texture::GetData()
{
return mData;
}
const unsigned char *
Texture::GetData() const
{
return mData;
}
size_t
Texture::GetDataSize() const
{
return mDataSize;
}
std::array<int, 3>
Texture::GetDimension() const
{
return mDimension;
}
int
Texture::GetDimension(int dimensionIndex) const
{
return mDimension[dimensionIndex];
}
TextureFormat
Texture::GetFormat() const
{
return mFormat;
}
int
Texture::GetMipmapLevel() const
{
return mMipmapLevel;
}
ResourceStorageMode
Texture::GetStorageMode() const
{
return mStorageMode;
}
TextureType Texture::GetTextureType() const
{
return mType;
}
size_t
Texture::GetTexelSize() const
{
return TexelSize[TextureFormatIndex(mFormat)];
}
}
| 22.081633 | 85 | 0.628466 | Lywx |
31c3b7be2ea5407b781e7b2d190574c9957ef388 | 2,258 | cc | C++ | src/ui/lib/escher/test/gtest_escher.cc | winksaville/Fuchsia | a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f | [
"BSD-3-Clause"
] | 3 | 2020-08-02T04:46:18.000Z | 2020-08-07T10:10:53.000Z | src/ui/lib/escher/test/gtest_escher.cc | winksaville/Fuchsia | a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f | [
"BSD-3-Clause"
] | null | null | null | src/ui/lib/escher/test/gtest_escher.cc | winksaville/Fuchsia | a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f | [
"BSD-3-Clause"
] | 1 | 2020-08-07T10:11:49.000Z | 2020-08-07T10:11:49.000Z | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/ui/lib/escher/test/gtest_escher.h"
#include "src/ui/lib/escher/escher_process_init.h"
#include <vulkan/vulkan.hpp>
namespace escher {
namespace test {
Escher* GetEscher() {
EXPECT_FALSE(VK_TESTS_SUPPRESSED());
return EscherEnvironment::GetGlobalTestEnvironment()->GetEscher();
}
void EscherEnvironment::RegisterGlobalTestEnvironment() {
FXL_CHECK(global_escher_environment_ == nullptr);
global_escher_environment_ = static_cast<escher::test::EscherEnvironment*>(
testing::AddGlobalTestEnvironment(new escher::test::EscherEnvironment));
}
EscherEnvironment* EscherEnvironment::GetGlobalTestEnvironment() {
FXL_CHECK(global_escher_environment_ != nullptr);
return global_escher_environment_;
}
void EscherEnvironment::SetUp() {
if (!VK_TESTS_SUPPRESSED()) {
VulkanInstance::Params instance_params(
{{},
{VK_EXT_DEBUG_REPORT_EXTENSION_NAME, VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME,
VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME},
false});
auto validation_layer_name = VulkanInstance::GetValidationLayerName();
if (validation_layer_name) {
instance_params.layer_names.insert(*validation_layer_name);
}
VulkanDeviceQueues::Params device_params(
{{VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME, VK_KHR_MAINTENANCE1_EXTENSION_NAME,
VK_KHR_BIND_MEMORY_2_EXTENSION_NAME, VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME},
{},
vk::SurfaceKHR()});
#ifdef OS_FUCHSIA
device_params.required_extension_names.insert(VK_FUCHSIA_EXTERNAL_SEMAPHORE_EXTENSION_NAME);
#endif
vulkan_instance_ = VulkanInstance::New(instance_params);
vulkan_device_ = VulkanDeviceQueues::New(vulkan_instance_, device_params);
escher_ = std::make_unique<Escher>(vulkan_device_);
escher::GlslangInitializeProcess();
}
}
void EscherEnvironment::TearDown() {
if (!VK_TESTS_SUPPRESSED()) {
escher::GlslangFinalizeProcess();
escher_.reset();
vulkan_device_.reset();
vulkan_instance_.reset();
}
}
} // namespace test
} // namespace escher
| 32.257143 | 100 | 0.760407 | winksaville |
31c8f60900a92de6d519e7caa3f4a3546b425799 | 1,877 | cpp | C++ | Week 8/Assignment 8_2.cpp | BenM-OC/CS10A | 65823fae5c5fa45942cb942450126aca9294e22e | [
"MIT"
] | null | null | null | Week 8/Assignment 8_2.cpp | BenM-OC/CS10A | 65823fae5c5fa45942cb942450126aca9294e22e | [
"MIT"
] | null | null | null | Week 8/Assignment 8_2.cpp | BenM-OC/CS10A | 65823fae5c5fa45942cb942450126aca9294e22e | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
// The purpose of this program is to prompt the user for a number, and then provide the user with the sum of all squares between zero and the number they've entered
int main()
{
int sumOfSquares = 0;
int calcLoopCounter = 0;
int userTopNumber;
//User inputs the max number the program is allowed to square
cout << "Enter a number greater than 0 (less than 1 to quit): ";
cin >> userTopNumber;
//While the value of the max number is greater than 0 this loop is executed
while (userTopNumber > 0) {
//Calcualtion values are reset to zero so each run of the following loop is ran like the first
calcLoopCounter = 0;
sumOfSquares = 0;
//While the calcLoopCounter is less than the max number selected by the user, the program adds one to the value of the calcLoopCounter, and uses the value of the (calcLoopCounter^2) plus the existing value of the sumOfSqaures to calculate the New sumOfSquares.
while (calcLoopCounter < userTopNumber) {
calcLoopCounter++;
sumOfSquares = (calcLoopCounter * calcLoopCounter) + sumOfSquares;
}
//Program informs the user of the sum of each number from 1 to their max number sqaured
cout << "The sum of squares from 1 to " << userTopNumber << " is " << sumOfSquares << endl;
//Program re-prompts for a max number to rerun the previously executed calculations, exiting the loop and program if the value of the max number is less than one.
cout << "Enter a number greater than 0 (less than 1 to quit): ";
cin >> userTopNumber;
}
return 0;
}
/* OUTPUT
[benji@thinktop Week 8]$ ./sumOfSquares.out
Enter a number greater than 0 (less than 1 to quit): 4
The sum of squares from 1 to 4 is 30
Enter a number greater than 0 (less than 1 to quit): 1
The sum of squares from 1 to 1 is 1
Enter a number greater than 0 (less than 1 to quit): 0
[benji@thinktop Week 8]$
*/ | 37.54 | 263 | 0.732019 | BenM-OC |
31cb1ee9c2f7fa49713fd79cfebf07be2cbe60dc | 12,950 | cpp | C++ | src/plugins/lmp/plugins/ppl/tracksselectordialog.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 120 | 2015-01-22T14:10:39.000Z | 2021-11-25T12:57:16.000Z | src/plugins/lmp/plugins/ppl/tracksselectordialog.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 8 | 2015-02-07T19:38:19.000Z | 2017-11-30T20:18:28.000Z | src/plugins/lmp/plugins/ppl/tracksselectordialog.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 33 | 2015-02-07T16:59:55.000Z | 2021-10-12T00:36:40.000Z | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
**********************************************************************/
#include "tracksselectordialog.h"
#include <numeric>
#include <QAbstractItemModel>
#include <QApplication>
#include <QDesktopWidget>
#include <QShortcut>
#include <util/sll/prelude.h>
#include <util/sll/views.h>
#include <util/sll/util.h>
namespace LC
{
namespace LMP
{
namespace PPL
{
class TracksSelectorDialog::TracksModel : public QAbstractItemModel
{
const QStringList HeaderLabels_;
enum Header : uint8_t
{
ScrobbleSummary,
Artist,
Album,
Track,
Date
};
static constexpr uint8_t MaxPredefinedHeader = Header::Date;
const Media::IAudioScrobbler::BackdatedTracks_t Tracks_;
QVector<QVector<bool>> Scrobble_;
public:
TracksModel (const Media::IAudioScrobbler::BackdatedTracks_t&,
const QList<Media::IAudioScrobbler*>&, QObject* = nullptr);
static constexpr uint8_t ColumnSelectAll = Header::ScrobbleSummary;
QModelIndex index (int, int, const QModelIndex& = {}) const override;
QModelIndex parent (const QModelIndex&) const override;
int rowCount (const QModelIndex& = {}) const override;
int columnCount (const QModelIndex&) const override;
QVariant data (const QModelIndex&, int) const override;
QVariant headerData (int, Qt::Orientation, int) const override;
Qt::ItemFlags flags (const QModelIndex& index) const override;
bool setData (const QModelIndex& index, const QVariant& value, int role) override;
QList<TracksSelectorDialog::SelectedTrack> GetSelectedTracks () const;
void MarkAll ();
void UnmarkAll ();
void SetMarked (const QList<QModelIndex>&, bool);
void UnmarkRepeats ();
private:
template<typename Summary, typename Specific>
auto WithCheckableColumns (const QModelIndex& index, Summary&& summary, Specific&& specific) const
{
switch (index.column ())
{
case Header::Artist:
case Header::Album:
case Header::Track:
case Header::Date:
using ResultType_t = std::result_of_t<Summary (int)>;
if constexpr (std::is_same_v<ResultType_t, void>)
return;
else
return ResultType_t {};
case Header::ScrobbleSummary:
return summary (index.row ());
}
return specific (index.row (), index.column () - (MaxPredefinedHeader + 1));
}
void MarkRow (const QModelIndex&, bool);
};
TracksSelectorDialog::TracksModel::TracksModel (const Media::IAudioScrobbler::BackdatedTracks_t& tracks,
const QList<Media::IAudioScrobbler*>& scrobblers, QObject *parent)
: QAbstractItemModel { parent }
, HeaderLabels_
{
[&scrobblers]
{
const QStringList predefined
{
{},
tr ("Artist"),
tr ("Album"),
tr ("Title"),
tr ("Date")
};
const auto& scrobbleNames = Util::Map (scrobblers, &Media::IAudioScrobbler::GetServiceName);
return predefined + scrobbleNames;
} ()
}
, Tracks_ { tracks }
, Scrobble_ { tracks.size (), QVector<bool> (scrobblers.size (), true) }
{
}
QModelIndex TracksSelectorDialog::TracksModel::index (int row, int column, const QModelIndex& parent) const
{
return parent.isValid () ?
QModelIndex {} :
createIndex (row, column);
}
QModelIndex TracksSelectorDialog::TracksModel::parent (const QModelIndex&) const
{
return {};
}
int TracksSelectorDialog::TracksModel::rowCount (const QModelIndex& parent) const
{
return parent.isValid () ?
0 :
Tracks_.size () + 1;
}
int TracksSelectorDialog::TracksModel::columnCount (const QModelIndex& parent) const
{
return parent.isValid () ?
0 :
HeaderLabels_.size ();
}
namespace
{
template<typename H, typename D>
auto WithIndex (const QModelIndex& index, H&& header, D&& data)
{
if (!index.row ())
return header (index);
else
return data (index.sibling (index.row () - 1, index.column ()));
}
QVariant PartialCheck (int enabled, int total)
{
if (!enabled)
return Qt::Unchecked;
else if (enabled == total)
return Qt::Checked;
else
return Qt::PartiallyChecked;
}
}
QVariant TracksSelectorDialog::TracksModel::data (const QModelIndex& srcIdx, int role) const
{
return WithIndex (srcIdx,
[&] (const QModelIndex& index) -> QVariant
{
if (role != Qt::CheckStateRole)
return {};
return WithCheckableColumns (index,
[this] (int)
{
const auto enabled = std::accumulate (Scrobble_.begin (), Scrobble_.end (), 0,
[] (int val, const auto& subvec)
{
return std::accumulate (subvec.begin (), subvec.end (), val);
});
const auto total = Scrobble_.size () * Scrobble_ [0].size ();
return PartialCheck (enabled, total);
},
[this] (int, int column)
{
const auto enabled = std::accumulate (Scrobble_.begin (), Scrobble_.end (), 0,
[column] (int val, const auto& subvec) { return val + subvec.at (column); });
return PartialCheck (enabled, Scrobble_.size ());
});
},
[&] (const QModelIndex& index) -> QVariant
{
switch (role)
{
case Qt::DisplayRole:
{
const auto& record = Tracks_.value (index.row ());
switch (index.column ())
{
case Header::ScrobbleSummary:
return {};
case Header::Artist:
return record.first.Artist_;
case Header::Album:
return record.first.Album_;
case Header::Track:
return record.first.Title_;
case Header::Date:
return record.second.toString ();
}
return {};
}
case Qt::CheckStateRole:
{
return WithCheckableColumns (index,
[&] (int row)
{
const auto& flags = Scrobble_.value (row);
const auto enabled = std::accumulate (flags.begin (), flags.end (), 0);
return PartialCheck (enabled, flags.size ());
},
[&] (int row, int column) -> QVariant
{
return Scrobble_.value (row).value (column) ?
Qt::Checked :
Qt::Unchecked;
});
}
default:
return {};
}
});
}
QVariant TracksSelectorDialog::TracksModel::headerData (int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return {};
switch (orientation)
{
case Qt::Horizontal:
return HeaderLabels_.value (section);
case Qt::Vertical:
return section ?
QString::number (section) :
tr ("All");
default:
return {};
}
}
Qt::ItemFlags TracksSelectorDialog::TracksModel::flags (const QModelIndex& index) const
{
switch (index.column ())
{
case Header::Artist:
case Header::Album:
case Header::Track:
case Header::Date:
return QAbstractItemModel::flags (index);
default:
return Qt::ItemIsSelectable |
Qt::ItemIsEnabled |
Qt::ItemIsUserCheckable;
}
}
bool TracksSelectorDialog::TracksModel::setData (const QModelIndex& srcIdx, const QVariant& value, int role)
{
if (role != Qt::CheckStateRole)
return false;
MarkRow (srcIdx, value.toInt () == Qt::Checked);
return true;
}
QList<TracksSelectorDialog::SelectedTrack> TracksSelectorDialog::TracksModel::GetSelectedTracks () const
{
QList<TracksSelectorDialog::SelectedTrack> result;
for (const auto& pair : Util::Views::Zip<std::pair> (Tracks_, Scrobble_))
if (std::any_of (pair.second.begin (), pair.second.end (), Util::Id))
result.push_back ({ pair.first, pair.second });
return result;
}
void TracksSelectorDialog::TracksModel::MarkAll ()
{
for (int i = 0; i < rowCount (); ++i)
MarkRow (index (i, Header::ScrobbleSummary), true);
}
void TracksSelectorDialog::TracksModel::UnmarkAll ()
{
for (int i = 0; i < rowCount (); ++i)
MarkRow (index (i, Header::ScrobbleSummary), false);
}
void TracksSelectorDialog::TracksModel::SetMarked (const QList<QModelIndex>& indices, bool shouldScrobble)
{
for (const auto& idx : indices)
MarkRow (idx, shouldScrobble);
}
void TracksSelectorDialog::TracksModel::UnmarkRepeats ()
{
const auto asTuple = [] (const auto& pair)
{
const auto& media = pair.first;
return std::tie (media.Artist_, media.Album_, media.Title_);
};
for (auto pos = Tracks_.begin (); pos != Tracks_.end (); )
{
pos = std::adjacent_find (pos, Tracks_.end (), Util::EqualityBy (asTuple));
if (pos == Tracks_.end ())
break;
const auto& referenceInfo = asTuple (*pos);
while (++pos != Tracks_.end () && asTuple (*pos) == referenceInfo)
MarkRow (index (std::distance (Tracks_.begin (), pos) + 1, Header::ScrobbleSummary), false);
}
}
void TracksSelectorDialog::TracksModel::MarkRow (const QModelIndex& srcIdx, bool shouldScrobble)
{
WithIndex (srcIdx,
[&] (const QModelIndex& index)
{
WithCheckableColumns (index,
[&] (int)
{
for (auto& subvec : Scrobble_)
std::fill (subvec.begin (), subvec.end (), shouldScrobble);
},
[&] (int, int column)
{
for (auto& subvec : Scrobble_)
subvec [column] = shouldScrobble;
});
const auto lastRow = rowCount (index.parent ()) - 1;
const auto lastColumn = columnCount (index.parent ()) - 1;
emit dataChanged (createIndex (0, 0), createIndex (lastRow, lastColumn));
},
[&] (const QModelIndex& index)
{
auto& scrobbles = Scrobble_ [index.row ()];
WithCheckableColumns (index,
[&] (int) { std::fill (scrobbles.begin (), scrobbles.end (), shouldScrobble); },
[&] (int, int column) { scrobbles [column] = shouldScrobble; });
const auto lastColumn = columnCount (index.parent ()) - 1;
emit dataChanged (createIndex (0, 0), createIndex (0, lastColumn));
emit dataChanged (index.sibling (index.row (), 0), index.sibling (index.row (), lastColumn));
});
}
TracksSelectorDialog::TracksSelectorDialog (const Media::IAudioScrobbler::BackdatedTracks_t& tracks,
const QList<Media::IAudioScrobbler*>& scrobblers,
QWidget *parent)
: QDialog { parent }
, Model_ { new TracksModel { tracks, scrobblers, this } }
{
Ui_.setupUi (this);
Ui_.Tracks_->setModel (Model_);
FixSize ();
auto withSelected = [this] (bool shouldScrobble)
{
return [this, shouldScrobble]
{
auto indices = Ui_.Tracks_->selectionModel ()->selectedIndexes ();
if (indices.isEmpty ())
return;
const auto notCheckable = [] (const auto& idx) { return !(idx.flags () & Qt::ItemIsUserCheckable); };
if (notCheckable (indices.value (0)))
{
const auto column = indices.value (0).column ();
if (std::all_of (indices.begin (), indices.end (),
[&column] (const auto& idx) { return idx.column () == column; }))
for (auto& idx : indices)
idx = idx.sibling (idx.row (), TracksModel::ColumnSelectAll);
}
indices.erase (std::remove_if (indices.begin (), indices.end (), notCheckable), indices.end ());
Model_->SetMarked (indices, shouldScrobble);
};
};
connect (new QShortcut { QString { "Alt+S" }, this },
&QShortcut::activated,
Ui_.MarkSelected_,
&QPushButton::click);
connect (new QShortcut { QString { "Alt+U" }, this },
&QShortcut::activated,
Ui_.UnmarkSelected_,
&QPushButton::click);
connect (Ui_.MarkAll_,
&QPushButton::clicked,
[this] { Model_->MarkAll (); });
connect (Ui_.UnmarkAll_,
&QPushButton::clicked,
[this] { Model_->UnmarkAll (); });
connect (Ui_.UnmarkRepeats_,
&QPushButton::clicked,
[this] { Model_->UnmarkRepeats (); });
connect (Ui_.MarkSelected_,
&QPushButton::clicked,
withSelected (true));
connect (Ui_.UnmarkSelected_,
&QPushButton::clicked,
withSelected (false));
}
void TracksSelectorDialog::FixSize ()
{
Ui_.Tracks_->resizeColumnsToContents ();
const auto showGuard = Util::MakeScopeGuard ([this] { show (); });
const auto Margin = 50;
int totalWidth = Margin + Ui_.Tracks_->verticalHeader ()->width ();
const auto header = Ui_.Tracks_->horizontalHeader ();
for (int j = 0; j < Model_->columnCount ({}); ++j)
totalWidth += std::max (header->sectionSize (j),
Ui_.Tracks_->sizeHintForIndex (Model_->index (0, j, {})).width ());
totalWidth += Ui_.ButtonsLayout_->sizeHint ().width ();
if (totalWidth < size ().width ())
return;
const auto desktop = qApp->desktop ();
const auto& availableGeometry = desktop->availableGeometry (this);
if (totalWidth > availableGeometry.width ())
return;
setGeometry (QStyle::alignedRect (Qt::LeftToRight,
Qt::AlignCenter,
{ totalWidth, height () },
availableGeometry));
}
QList<TracksSelectorDialog::SelectedTrack> TracksSelectorDialog::GetSelectedTracks () const
{
return Model_->GetSelectedTracks ();
}
}
}
}
| 28.152174 | 114 | 0.643012 | Maledictus |
31d0fc80c060adc580dce5079b4d3c763204f615 | 36,874 | cpp | C++ | gui/tf_editor.cpp | shamanDevel/DiffDVR | 99fbe9f114d0097daf402bde2ae35f18dade335d | [
"BSD-3-Clause"
] | 12 | 2021-08-02T04:51:48.000Z | 2022-01-14T18:02:27.000Z | gui/tf_editor.cpp | shamanDevel/DiffDVR | 99fbe9f114d0097daf402bde2ae35f18dade335d | [
"BSD-3-Clause"
] | 2 | 2021-11-04T14:23:30.000Z | 2022-02-28T10:30:13.000Z | gui/tf_editor.cpp | shamanDevel/DiffDVR | 99fbe9f114d0097daf402bde2ae35f18dade335d | [
"BSD-3-Clause"
] | 4 | 2021-07-16T10:23:45.000Z | 2022-01-04T02:51:43.000Z | #include "tf_editor.h"
#include "visualizer_kernels.h"
#include <algorithm>
#include <cuda_gl_interop.h>
#include <cuMat/src/Context.h>
#include <fstream>
#include <tinyxml2.h>
#include "pytorch_utils.h"
#include "renderer_utils.cuh"
#include "utils.h"
static std::vector<float> linspace(float a, float b, std::size_t N)
{
//contains the endpoint!
//Use N-1 if endpoint should be omitted
float h = (b - a) / static_cast<float>(N);
std::vector<float> xs(N);
std::vector<float>::iterator x;
float val;
for (x = xs.begin(), val = a; x != xs.end(); ++x, val += h) {
*x = val;
}
return xs;
}
TfPartPiecewiseOpacity::TfPartPiecewiseOpacity()
: controlPoints_({ ImVec2(0.45f, 0.0f), ImVec2(0.5f, 0.8f), ImVec2(0.55f, 0.0f) })
, densityAxis_({ 0.45f, 0.5f, 0.55f })
, opacityAxis_({ 0.0f, 0.8f, 0.0f })
{}
void TfPartPiecewiseOpacity::init(const ImRect& rect)
{
tfEditorRect_ = rect;
}
void TfPartPiecewiseOpacity::updateControlPoints(const std::vector<float>& densityAxis, const std::vector<float>& opacityAxis)
{
assert(densityAxis.size() == opacityAxis.size());
assert(densityAxis.size() >= 1 && opacityAxis.size() >= 1);
selectedControlPoint_ = -1;
controlPoints_.clear();
densityAxis_ = densityAxis;
opacityAxis_ = opacityAxis;
int size = densityAxis.size();
for (int i = 0; i < size; ++i)
{
controlPoints_.emplace_back(densityAxis_[i], opacityAxis_[i]);
}
}
void TfPartPiecewiseOpacity::handleIO()
{
isChanged_ = false;
auto mousePosition = ImGui::GetMousePos();
//Early leave if mouse is not on opacity editor and no control point is selected.
if (!TfPiecewiseLinearEditor::testIntersectionRectPoint(tfEditorRect_, mousePosition) && selectedControlPoint_ == -1)
{
return;
}
//0=left, 1=right, 2=middle
bool isLeftDoubleClicked = ImGui::IsMouseDoubleClicked(0);
bool isLeftClicked = ImGui::IsMouseDown(0);
bool isRightClicked = ImGui::IsMouseClicked(1);
bool isLeftReleased = ImGui::IsMouseReleased(0);
if (isLeftDoubleClicked)
{
isChanged_ = true;
controlPoints_.push_back(screenToEditor(mousePosition));
}
else if (isLeftClicked)
{
//Move selected point.
if (selectedControlPoint_ >= 0)
{
isChanged_ = true;
ImVec2 center(std::min(std::max(mousePosition.x, tfEditorRect_.Min.x), tfEditorRect_.Max.x),
std::min(std::max(mousePosition.y, tfEditorRect_.Min.y), tfEditorRect_.Max.y));
controlPoints_[selectedControlPoint_] = screenToEditor(center);
}
//Check whether new point is selected.
else
{
int size = controlPoints_.size();
for (int idx = 0; idx < size; ++idx)
{
auto cp = createControlPointRect(editorToScreen(controlPoints_[idx]));
if (TfPiecewiseLinearEditor::testIntersectionRectPoint(cp, mousePosition))
{
selectedControlPoint_ = idx;
break;
}
}
}
}
else if (isRightClicked)
{
int size = controlPoints_.size();
for (int idx = 0; idx < size; ++idx)
{
auto cp = createControlPointRect(editorToScreen(controlPoints_[idx]));
if (TfPiecewiseLinearEditor::testIntersectionRectPoint(cp, mousePosition) && controlPoints_.size() > 1)
{
isChanged_ = true;
controlPoints_.erase(controlPoints_.begin() + idx);
selectedControlPoint_ = -1;
break;
}
}
}
else if (isLeftReleased)
{
selectedControlPoint_ = -1;
}
}
void TfPartPiecewiseOpacity::render()
{
//Draw the bounding rectangle.
ImGuiWindow* window = ImGui::GetCurrentWindow();
window->DrawList->AddRect(tfEditorRect_.Min, tfEditorRect_.Max, ImColor(ImVec4(0.3f, 0.3f, 0.3f, 1.0f)), 0.0f, ImDrawCornerFlags_All, 1.0f);
//Copy the control points and sort them. We don't sort original one in order not to mess up with control point indices.
auto controlPointsRender = controlPoints_;
std::sort(controlPointsRender.begin(), controlPointsRender.end(),
[](const ImVec2& p1, const ImVec2& p2)
{
return p1.x < p2.x;
});
//Fill densityAxis_ and opacityAxis_ and convert coordinates from editor space to screen space.
densityAxis_.clear();
opacityAxis_.clear();
for (auto& cp : controlPointsRender)
{
densityAxis_.push_back(cp.x);
opacityAxis_.push_back(cp.y);
cp = editorToScreen(cp);
}
//Draw lines between the control points.
int size = controlPointsRender.size();
for (int i = 0; i < size + 1; ++i)
{
auto left = (i == 0) ? ImVec2(tfEditorRect_.Min.x, controlPointsRender.front().y) : controlPointsRender[i - 1];
auto right = (i == size) ? ImVec2(tfEditorRect_.Max.x, controlPointsRender.back().y) : controlPointsRender[i];
window->DrawList->AddLine(left, right, ImColor(ImVec4(1.0f, 1.0f, 1.0f, 1.0f)), 1.0f);
}
//Draw the control points
for (const auto& cp : controlPointsRender)
{
window->DrawList->AddCircleFilled(cp, circleRadius_, ImColor(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), 16);
}
}
ImRect TfPartPiecewiseOpacity::createControlPointRect(const ImVec2& controlPoint)
{
return ImRect(ImVec2(controlPoint.x - circleRadius_, controlPoint.y - circleRadius_),
ImVec2(controlPoint.x + circleRadius_, controlPoint.y + circleRadius_));
}
ImVec2 TfPartPiecewiseOpacity::screenToEditor(const ImVec2& screenPosition)
{
ImVec2 editorPosition;
editorPosition.x = (screenPosition.x - tfEditorRect_.Min.x) / (tfEditorRect_.Max.x - tfEditorRect_.Min.x);
editorPosition.y = 1.0f - (screenPosition.y - tfEditorRect_.Min.y) / (tfEditorRect_.Max.y - tfEditorRect_.Min.y);
return editorPosition;
}
ImVec2 TfPartPiecewiseOpacity::editorToScreen(const ImVec2& editorPosition)
{
ImVec2 screenPosition;
screenPosition.x = editorPosition.x * (tfEditorRect_.Max.x - tfEditorRect_.Min.x) + tfEditorRect_.Min.x;
screenPosition.y = (1.0f - editorPosition.y) * (tfEditorRect_.Max.y - tfEditorRect_.Min.y) + tfEditorRect_.Min.y;
return screenPosition;
}
TfPartTextureOpacity::TfPartTextureOpacity(int resolution)
: resolution_(resolution)
, opacityAxis_(linspace(0, 1, resolution))
{}
void TfPartTextureOpacity::init(const ImRect& rect)
{
resized_ = false;
if (tfEditorRect_.GetWidth() != rect.GetWidth()) {
int N = rect.GetWidth();
resized_ = true;
plot_.resize(N);
for (int i=0; i<N; ++i)
{
float p = i * resolution_ / float(N);
int a = int(p);
float f = p - a;
int a2 = clamp(a, 0, resolution_ - 1);
int b2 = clamp(a + 1, 0, resolution_ - 1);
plot_[i] = lerp(opacityAxis_[a2], opacityAxis_[b2], f);
}
}
tfEditorRect_ = rect;
}
void TfPartTextureOpacity::updateControlPoints(const std::vector<float>& opacities)
{
assert(opacities.size() == opacityAxis_.size());
std::copy(opacities.begin(), opacities.end(), opacityAxis_.begin());
isChanged_ = true;
}
void TfPartTextureOpacity::handleIO()
{
isChanged_ = false;
auto mousePosition = ImGui::GetMousePos();
//Early leave if mouse is not on opacity editor and no control point is selected.
if (!TfPiecewiseLinearEditor::testIntersectionRectPoint(tfEditorRect_, mousePosition) && selectedControlPoint_ == -1)
{
return;
}
//0=left, 1=right, 2=middle
bool isLeftDoubleClicked = ImGui::IsMouseDoubleClicked(0);
bool isLeftClicked = ImGui::IsMouseDown(0);
bool isRightClicked = ImGui::IsMouseClicked(1);
bool isLeftReleased = ImGui::IsMouseReleased(0);
if (isLeftDoubleClicked)
{
}
else if (isLeftClicked)
{
ImVec2 p = screenToEditor(mousePosition);
//Draw line from lastPos_to p
const auto drawLine = [](std::vector<float>& d, const ImVec2& start, const ImVec2& end)
{
int N = d.size();
int xa = clamp(int(std::round(start.x * (N - 1))), 0, N - 1);
int xb = clamp(int(std::round(end.x * (N - 1))), 0, N - 1);
float ya = start.y;
float yb = end.y;
if (xa <= xb)
{
for (int x = xa; x <= xb; ++x)
{
float f = (x - xa) / float(xb - xa);
d[x] = lerp(ya, yb, f);
}
}
else
{
for (int x = xb; x <= xa; ++x)
{
float f = (x - xb) / float(xa - xb);
d[x] = lerp(yb, ya, f);
}
}
};
if (wasClicked_) {
//std::cout << "Line from " << lastPos_.x << "," << lastPos_.y
// << " to " << p.x << "," << p.y << std::endl;
drawLine(plot_, lastPos_, p);
drawLine(opacityAxis_, lastPos_, p);
isChanged_ = true;
}
lastPos_ = p;
wasClicked_ = true;
}
else if (isRightClicked)
{
}
else if (isLeftReleased)
{
wasClicked_ = false;
}
}
void TfPartTextureOpacity::render()
{
//Draw the bounding rectangle.
ImGuiWindow* window = ImGui::GetCurrentWindow();
window->DrawList->AddRect(tfEditorRect_.Min, tfEditorRect_.Max, ImColor(ImVec4(0.3f, 0.3f, 0.3f, 1.0f)), 0.0f, ImDrawCornerFlags_All, 1.0f);
//Draw line
int N = plot_.size();
ImU32 col = ImGui::GetColorU32(ImGuiCol_PlotLines);
for (int i=1; i<N; ++i)
{
ImVec2 a = ImLerp(tfEditorRect_.Min, tfEditorRect_.Max,
ImVec2((i-1)/(N-1.0f), lerp(0.05f, 0.95f, 1-plot_[i-1])));
ImVec2 b = ImLerp(tfEditorRect_.Min, tfEditorRect_.Max,
ImVec2(i / (N - 1.0f), lerp(0.05f, 0.95f, 1-plot_[i])));
window->DrawList->AddLine(a, b, col, thickness_);
}
}
ImVec2 TfPartTextureOpacity::screenToEditor(const ImVec2& screenPosition)
{
ImVec2 editorPosition;
editorPosition.x = (screenPosition.x - tfEditorRect_.Min.x) / (tfEditorRect_.Max.x - tfEditorRect_.Min.x);
editorPosition.y = 1.0f - (screenPosition.y - tfEditorRect_.Min.y) / (tfEditorRect_.Max.y - tfEditorRect_.Min.y);
editorPosition.y = 1 / 18.0f * (20 * editorPosition.y - 1);
editorPosition.x = clamp(editorPosition.x, 0.0f, 1.0f);
editorPosition.y = clamp(editorPosition.y, 0.0f, 1.0f);
return editorPosition;
}
TfPartPiecewiseColor::TfPartPiecewiseColor(ITextureEditor* parent)
: densityAxis_({ 0.0f, 1.0f }), parent_(parent)
{
auto red = renderer::rgbToLab(make_float3(1.0f, 0.0f, 0.0f));
auto white = renderer::rgbToLab(make_float3(1.0f, 1.0f, 1.0f));
controlPoints_.emplace_back(0.0f, red.x, red.y, red.z);
controlPoints_.emplace_back(1.0f, white.x, white.y, white.z);
colorAxis_.push_back(red);
colorAxis_.push_back(white);
}
TfPartPiecewiseColor::~TfPartPiecewiseColor()
{
destroy();
}
void TfPartPiecewiseColor::init(const ImRect& rect, bool showControlPoints)
{
ImGuiColorEditFlags colorFlags = ImGuiColorEditFlags_Float | ImGuiColorEditFlags_InputHSV;
ImGui::ColorEdit3("", &pickedColor_.x, colorFlags);
showControlPoints_ = showControlPoints;
//If editor is created for the first time or its size is changed, create CUDA texture.
if (tfEditorRect_.Min.x == FLT_MAX ||
!(rect.Min.x == tfEditorRect_.Min.x &&
rect.Min.y == tfEditorRect_.Min.y &&
rect.Max.x == tfEditorRect_.Max.x &&
rect.Max.y == tfEditorRect_.Max.y))
{
destroy();
tfEditorRect_ = rect;
auto colorMapWidth = tfEditorRect_.Max.x - tfEditorRect_.Min.x;
auto colorMapHeight = tfEditorRect_.Max.y - tfEditorRect_.Min.y;
glGenTextures(1, &colorMapImage_);
glBindTexture(GL_TEXTURE_2D, colorMapImage_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, colorMapWidth, colorMapHeight, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
//CUMAT_SAFE_CALL(cudaGraphicsGLRegisterImage(&resource_, colorMapImage_, GL_TEXTURE_2D, cudaGraphicsMapFlagsWriteDiscard));
glBindTexture(GL_TEXTURE_2D, 0);
//cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc(8, 8, 8, 8, cudaChannelFormatKindUnsigned);
//CUMAT_SAFE_CALL(cudaMallocArray(&contentArray_, &channelDesc, colorMapWidth, colorMapHeight, cudaArraySurfaceLoadStore));
//cudaResourceDesc resDesc;
//memset(&resDesc, 0, sizeof(resDesc));
//resDesc.resType = cudaResourceTypeArray;
//resDesc.res.array.array = contentArray_;
//CUMAT_SAFE_CALL(cudaCreateSurfaceObject(&content_, &resDesc));
isColorMapInitialized_ = false;
}
}
void TfPartPiecewiseColor::updateControlPoints(const std::vector<float>& densityAxis, const std::vector<float3>& colorAxis)
{
selectedControlPointForMove_ = -1;
selectedControlPointForColor_ = -1;
controlPoints_.clear();
densityAxis_ = densityAxis;
colorAxis_ = colorAxis;
int size = densityAxis.size();
for (int i = 0; i < size; ++i)
{
controlPoints_.emplace_back(densityAxis_[i], colorAxis_[i].x, colorAxis_[i].y, colorAxis_[i].z);
}
isChanged_ = true;
isColorMapInitialized_ = false;
}
void TfPartPiecewiseColor::handleIO()
{
isChanged_ = false;
auto mousePosition = ImGui::GetMousePos();
if (selectedControlPointForColor_ >= 0)
{
auto& cp = controlPoints_[selectedControlPointForColor_];
float3 pickedColorLab;
ImGui::ColorConvertHSVtoRGB(pickedColor_.x, pickedColor_.y, pickedColor_.z, pickedColorLab.x, pickedColorLab.y, pickedColorLab.z);
pickedColorLab = renderer::rgbToLab(pickedColorLab);
if (cp.y != pickedColorLab.x || cp.z != pickedColorLab.y ||
cp.w != pickedColorLab.z)
{
cp.y = pickedColorLab.x;
cp.z = pickedColorLab.y;
cp.w = pickedColorLab.z;
isChanged_ = true;
}
}
//Early leave if mouse is not on color editor.
if (!TfPiecewiseLinearEditor::testIntersectionRectPoint(tfEditorRect_, mousePosition) && selectedControlPointForMove_ == -1)
{
return;
}
//0=left, 1=right, 2=middle
bool isLeftDoubleClicked = ImGui::IsMouseDoubleClicked(0);
bool isLeftClicked = ImGui::IsMouseDown(0);
bool isRightClicked = ImGui::IsMouseClicked(1);
bool isLeftReleased = ImGui::IsMouseReleased(0);
if (isLeftDoubleClicked)
{
isChanged_ = true;
float3 pickedColorLab;
ImGui::ColorConvertHSVtoRGB(pickedColor_.x, pickedColor_.y, pickedColor_.z, pickedColorLab.x, pickedColorLab.y, pickedColorLab.z);
pickedColorLab = renderer::rgbToLab(pickedColorLab);
controlPoints_.emplace_back(screenToEditor(mousePosition.x), pickedColorLab.x, pickedColorLab.y, pickedColorLab.z);
}
else if (isLeftClicked)
{
//Move selected point.
if (selectedControlPointForMove_ >= 0)
{
isChanged_ = true;
float center = std::min(std::max(mousePosition.x, tfEditorRect_.Min.x), tfEditorRect_.Max.x);
controlPoints_[selectedControlPointForMove_].x = screenToEditor(center);
}
//Check whether new point is selected.
else
{
int size = controlPoints_.size();
int idx;
for (idx = 0; idx < size; ++idx)
{
auto cp = createControlPointRect(editorToScreen(controlPoints_[idx].x));
if (TfPiecewiseLinearEditor::testIntersectionRectPoint(cp, mousePosition))
{
selectedControlPointForColor_ = selectedControlPointForMove_ = idx;
auto colorRgb = renderer::labToRgb(make_float3(controlPoints_[selectedControlPointForMove_].y,
controlPoints_[selectedControlPointForMove_].z,
controlPoints_[selectedControlPointForMove_].w));
ImGui::ColorConvertRGBtoHSV(colorRgb.x, colorRgb.y, colorRgb.z, pickedColor_.x, pickedColor_.y, pickedColor_.z);
break;
}
}
//In case of no hit on any control point, unselect for color pick as well.
if (idx == size)
{
selectedControlPointForColor_ = -1;
}
}
}
else if (isRightClicked)
{
int size = controlPoints_.size();
int idx;
for (idx = 0; idx < size; ++idx)
{
auto cp = createControlPointRect(editorToScreen(controlPoints_[idx].x));
if (TfPiecewiseLinearEditor::testIntersectionRectPoint(cp, mousePosition) && controlPoints_.size() > 1)
{
isChanged_ = true;
controlPoints_.erase(controlPoints_.begin() + idx);
selectedControlPointForColor_ = selectedControlPointForMove_ = -1;
break;
}
}
}
else if (isLeftReleased)
{
selectedControlPointForMove_ = -1;
}
}
void TfPartPiecewiseColor::render()
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
//Copy the control points and sort them. We don't sort original one in order not to mess up with control point indices.
auto controlPointsRender = controlPoints_;
std::sort(controlPointsRender.begin(), controlPointsRender.end(),
[](const ImVec4& cp1, const ImVec4& cp2)
{
return cp1.x < cp2.x;
});
//Fill densityAxis_ and colorAxis_.
densityAxis_.clear();
colorAxis_.clear();
for (auto& cp : controlPointsRender)
{
densityAxis_.push_back(cp.x);
colorAxis_.push_back(make_float3(cp.y, cp.z, cp.w));
}
auto colorMapWidth = tfEditorRect_.Max.x - tfEditorRect_.Min.x;
auto colorMapHeight = tfEditorRect_.Max.y - tfEditorRect_.Min.y;
//Write to color map texture.
if (isChanged_ || !isColorMapInitialized_)
{
isColorMapInitialized_ = true;
torch::Tensor colorTensor = parent_->getTextureTensor(
colorMapWidth, 0.0, 1.0, 1.0, false);
const auto acc = colorTensor.accessor<real_t, 3>();
std::vector<unsigned int> pixelData(colorMapWidth * colorMapHeight);
for (int x=0; x<colorMapWidth; ++x)
{
float r = acc[0][x][0];
float g = acc[0][x][1];
float b = acc[0][x][2];
unsigned int rgba = kernel::rgbaToInt(r, g, b, 1.0f);
for (int y=0; y<colorMapHeight; ++y)
{
pixelData[x + colorMapWidth * y] = rgba;
}
}
glBindTexture(GL_TEXTURE_2D, colorMapImage_);
glTexSubImage2D(
GL_TEXTURE_2D, 0, 0, 0, colorMapWidth, colorMapHeight, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV,
pixelData.data());
glBindTexture(GL_TEXTURE_2D, 0);
}
//kernel::fillColorMap(content_, tfTexture_.getTextureObject(), colorMapWidth, colorMapHeight);
////Draw color interpolation between control points.
//cudaArray_t texturePtr = nullptr;
//CUMAT_SAFE_CALL(cudaGraphicsMapResources(1, &resource_, 0));
//CUMAT_SAFE_CALL(cudaGraphicsSubResourceGetMappedArray(&texturePtr, resource_, 0, 0));
//CUMAT_SAFE_CALL(cudaMemcpyArrayToArray(texturePtr, 0, 0, contentArray_, 0, 0, colorMapWidth * colorMapHeight * 4, cudaMemcpyDeviceToDevice));
//CUMAT_SAFE_CALL(cudaGraphicsUnmapResources(1, &resource_, 0));
window->DrawList->AddImage((void*)colorMapImage_, tfEditorRect_.Min, tfEditorRect_.Max);
if (showControlPoints_)
{
//Draw the control points
int cpIndex = 0;
for (const auto& cp : controlPoints_)
{
//If this is the selected control point, use different color.
auto rect = createControlPointRect(editorToScreen(cp.x));
if (selectedControlPointForColor_ == cpIndex++)
{
window->DrawList->AddRect(rect.Min, rect.Max, ImColor(ImVec4(1.0f, 0.8f, 0.1f, 1.0f)), 16.0f, ImDrawCornerFlags_All, 3.0f);
}
else
{
window->DrawList->AddRect(rect.Min, rect.Max, ImColor(ImVec4(1.0f, 1.0f, 1.0f, 1.0f)), 16.0f, ImDrawCornerFlags_All, 2.0f);
}
}
}
}
void TfPartPiecewiseColor::destroy()
{
if (colorMapImage_)
{
glDeleteTextures(1, &colorMapImage_);
colorMapImage_ = 0;
}
//if (content_)
//{
// CUMAT_SAFE_CALL(cudaDestroySurfaceObject(content_));
// content_ = 0;
//}
//if (contentArray_)
//{
// CUMAT_SAFE_CALL(cudaFreeArray(contentArray_));
// contentArray_ = nullptr;
//}
}
ImRect TfPartPiecewiseColor::createControlPointRect(float x)
{
return ImRect(ImVec2(x - 0.5f * cpWidth_, tfEditorRect_.Min.y),
ImVec2(x + 0.5f * cpWidth_, tfEditorRect_.Max.y));
}
float TfPartPiecewiseColor::screenToEditor(float screenPositionX)
{
float editorPositionX;
editorPositionX = (screenPositionX - tfEditorRect_.Min.x) / (tfEditorRect_.Max.x - tfEditorRect_.Min.x);
return editorPositionX;
}
float TfPartPiecewiseColor::editorToScreen(float editorPositionX)
{
float screenPositionX;
screenPositionX = editorPositionX * (tfEditorRect_.Max.x - tfEditorRect_.Min.x) + tfEditorRect_.Min.x;
return screenPositionX;
}
TfPiecewiseLinearEditor::TfPiecewiseLinearEditor()
: editorColor_(this)
{
}
void TfPiecewiseLinearEditor::init(const ImRect& tfEditorOpacityRect, const ImRect& tfEditorColorRect, bool showColorControlPoints)
{
editorOpacity_.init(tfEditorOpacityRect);
editorColor_.init(tfEditorColorRect, showColorControlPoints);
}
void TfPiecewiseLinearEditor::handleIO()
{
editorOpacity_.handleIO();
editorColor_.handleIO();
}
void TfPiecewiseLinearEditor::render()
{
editorOpacity_.render();
editorColor_.render();
}
void TfPiecewiseLinearEditor::saveToFile(const std::string& path, float minDensity, float maxDensity) const
{
const auto& densityAxisOpacity = editorOpacity_.getDensityAxis();
const auto& opacityAxis = editorOpacity_.getOpacityAxis();
const auto& densityAxisColor = editorColor_.getDensityAxis();
const auto& colorAxis = editorColor_.getColorAxis();
assert(densityAxisOpacity.size() == opacityAxis.size());
assert(densityAxisColor.size() == colorAxis.size());
nlohmann::json json;
json["densityAxisOpacity"] = editorOpacity_.getDensityAxis();
json["opacityAxis"] = editorOpacity_.getOpacityAxis();
json["densityAxisColor"] = editorColor_.getDensityAxis();
json["colorAxis"] = editorColor_.getColorAxis();
json["minDensity"] = minDensity;
json["maxDensity"] = maxDensity;
std::ofstream out(path);
out << json;
out.close();
}
void TfPiecewiseLinearEditor::loadFromFile(const std::string& path, float& minDensity, float& maxDensity)
{
if (path.size() > 4 && path.substr(path.size() - 4, 4) == ".xml")
{
//try to load colormap (no opacities)
try
{
auto colormap = loadColormapFromXML(path);
//convert rgb to lab
for (auto& color : colormap.second)
color = renderer::rgbToLab(color);
editorColor_.updateControlPoints(colormap.first, colormap.second);
}
catch (const std::runtime_error& ex)
{
std::cerr << "Unable to load colormap from xml: " << ex.what() << std::endl;
}
}
nlohmann::json json;
std::ifstream file(path);
file >> json;
file.close();
std::vector<float> densityAxisOpacity = json["densityAxisOpacity"];
std::vector<float> opacityAxis = json["opacityAxis"];
std::vector<float> densityAxisColor = json["densityAxisColor"];
std::vector<float3> colorAxis = json["colorAxis"];
minDensity = json["minDensity"];
maxDensity = json["maxDensity"];
assert(densityAxisOpacity.size() == opacityAxis.size());
assert(densityAxisColor.size() == colorAxis.size());
editorOpacity_.updateControlPoints(densityAxisOpacity, opacityAxis);
editorColor_.updateControlPoints(densityAxisColor, colorAxis);
}
nlohmann::json TfPiecewiseLinearEditor::toJson() const
{
const auto& densityAxisOpacity = editorOpacity_.getDensityAxis();
const auto& opacityAxis = editorOpacity_.getOpacityAxis();
const auto& densityAxisColor = editorColor_.getDensityAxis();
const auto& colorAxis = editorColor_.getColorAxis();
//std::vector<nlohmann::json> colorAxis2;
//std::transform(colorAxis.begin(), colorAxis.end(), std::back_inserter(colorAxis2),
// [](float3 color)
//{
// return nlohmann::json::array({ color.x, color.y, color.z });
//});
return {
{"densityAxisOpacity", nlohmann::json(densityAxisOpacity)},
{"opacityAxis", nlohmann::json(opacityAxis)},
{"densityAxisColor", nlohmann::json(densityAxisColor)},
{"colorAxis", nlohmann::json(colorAxis)}
};
}
void TfPiecewiseLinearEditor::fromJson(const nlohmann::json& s)
{
const std::vector<float> densityAxisOpacity = s.at("densityAxisOpacity");
const std::vector<float> opacityAxis = s.at("opacityAxis");
const std::vector<float> densityAxisColor = s.at("densityAxisColor");
const std::vector<float3> colorAxis = s.at("colorAxis");
//std::vector<float3> colorAxis;
//std::transform(colorAxis2.begin(), colorAxis2.end(), std::back_inserter(colorAxis),
// [](nlohmann::json color)
//{
// return make_float3(color[0].get<float>(), color[1].get<float>(), color[2].get<float>());
//});
editorOpacity_.updateControlPoints(densityAxisOpacity, opacityAxis);
editorColor_.updateControlPoints(densityAxisColor, colorAxis);
}
std::pair<std::vector<float>, std::vector<float3>> TfPiecewiseLinearEditor::loadColormapFromXML(const std::string& path)
{
using namespace tinyxml2;
XMLDocument doc;
doc.LoadFileThrow(path.c_str());
const XMLElement* element = doc.FirstChildElementThrow("ColorMaps")
->FirstChildElementThrow("ColorMap");
std::vector<float> positions;
std::vector<float3> rgbColors;
const XMLElement* point = element->FirstChildElementThrow("Point");
do
{
positions.push_back(point->FloatAttribute("x"));
rgbColors.push_back(make_float3(
point->FloatAttribute("r"),
point->FloatAttribute("g"),
point->FloatAttribute("b")
));
point = point->NextSiblingElement("Point");
} while (point != nullptr);
return std::make_pair(positions, rgbColors);
}
bool TfPiecewiseLinearEditor::testIntersectionRectPoint(const ImRect& rect, const ImVec2& point)
{
return (rect.Min.x <= point.x &&
rect.Max.x >= point.x &&
rect.Min.y <= point.y &&
rect.Max.y >= point.y);
}
torch::Tensor TfPiecewiseLinearEditor::getTextureTensor(
int resolution, float minDensity, float maxDensity, float opacityScaling,
bool purgeZeroOpacityRegions) const
{
const auto points = assembleMergedPoints(
minDensity, maxDensity, opacityScaling, purgeZeroOpacityRegions);
return renderer::TFUtils::getTextureTensor(points, resolution);
}
torch::Tensor TfPiecewiseLinearEditor::getPiecewiseTensor(
float minDensity, float maxDensity, float opacityScaling,
bool purgeZeroOpacityRegions) const
{
const auto points = assembleMergedPoints(
minDensity, maxDensity, opacityScaling, purgeZeroOpacityRegions);
return renderer::TFUtils::getPiecewiseTensor(points);
}
std::vector<renderer::TFPoint> TfPiecewiseLinearEditor::assembleMergedPoints(
float minDensity, float maxDensity, float opacityScaling,
bool purgeZeroOpacityRegions) const
{
auto colorValues = getColorAxis();
auto colorPositions = getDensityAxisColor();
auto opacityValues = getOpacityAxis();
auto opacityPositions = getDensityAxisOpacity();
return renderer::TFUtils::assembleFromSettings(colorValues, colorPositions,
opacityValues, opacityPositions, minDensity, maxDensity, opacityScaling,
purgeZeroOpacityRegions);
}
TfTextureEditor::TfTextureEditor()
: editorColor_(this)
{
}
void TfTextureEditor::init(const ImRect& tfEditorOpacityRect, const ImRect& tfEditorColorRect, bool showColorControlPoints)
{
editorOpacity_.init(tfEditorOpacityRect);
editorColor_.init(tfEditorColorRect, showColorControlPoints);
}
void TfTextureEditor::handleIO()
{
editorOpacity_.handleIO();
editorColor_.handleIO();
}
void TfTextureEditor::render()
{
editorOpacity_.render();
editorColor_.render();
}
void TfTextureEditor::saveToFile(const std::string& path, float minDensity, float maxDensity) const
{
nlohmann::json json;
json["opacities"] = editorOpacity_.getOpacityAxis();;
json["densityAxisColor"] = editorColor_.getDensityAxis();
json["colorAxis"] = editorColor_.getColorAxis();
json["minDensity"] = minDensity;
json["maxDensity"] = maxDensity;
std::ofstream out(path);
out << json;
out.close();
}
void TfTextureEditor::loadFromFile(const std::string& path, float& minDensity, float& maxDensity)
{
if (path.size() > 4 && path.substr(path.size() - 4, 4) == ".xml")
{
//try to load colormap (no opacities)
try
{
auto colormap = TfPiecewiseLinearEditor::loadColormapFromXML(path);
//convert rgb to lab
for (auto& color : colormap.second)
color = renderer::rgbToLab(color);
editorColor_.updateControlPoints(colormap.first, colormap.second);
}
catch (const std::runtime_error& ex)
{
std::cerr << "Unable to load colormap from xml: " << ex.what() << std::endl;
}
}
nlohmann::json json;
std::ifstream file(path);
file >> json;
file.close();
std::vector<float> opacities = json["opacities"];
std::vector<float> densityAxisColor = json["densityAxisColor"];
std::vector<float3> colorAxis = json["colorAxis"];
minDensity = json["minDensity"];
maxDensity = json["maxDensity"];
assert(densityAxisOpacity.size() == opacityAxis.size());
assert(densityAxisColor.size() == colorAxis.size());
editorOpacity_.updateControlPoints(opacities);
editorColor_.updateControlPoints(densityAxisColor, colorAxis);
}
nlohmann::json TfTextureEditor::toJson() const
{
const auto& opacities = editorOpacity_.getOpacityAxis();
const auto& densityAxisColor = editorColor_.getDensityAxis();
const auto& colorAxis = editorColor_.getColorAxis();
//std::vector<nlohmann::json> colorAxis2;
//std::transform(colorAxis.begin(), colorAxis.end(), std::back_inserter(colorAxis2),
// [](float3 color)
//{
// return nlohmann::json::array({ color.x, color.y, color.z });
//});
return {
{"opacities", nlohmann::json(opacities)},
{"densityAxisColor", nlohmann::json(densityAxisColor)},
{"colorAxis", nlohmann::json(colorAxis)}
};
}
void TfTextureEditor::fromJson(const nlohmann::json& s)
{
const std::vector<float> opacities = s.at("opacities");
const std::vector<float> densityAxisColor = s.at("densityAxisColor");
const std::vector<float3> colorAxis = s.at("colorAxis");
editorOpacity_.updateControlPoints(opacities);
editorColor_.updateControlPoints(densityAxisColor, colorAxis);
}
torch::Tensor TfTextureEditor::getTextureTensor(
int resolution, float minDensity, float maxDensity, float opacityScaling,
bool purgeZeroOpacityRegions) const
{
auto colorValues = getColorAxis();
auto colorPositions = getDensityAxisColor();
auto opacityValues = getOpacities();
auto opacityPositions = linspace(0, 1, opacityValues.size());
const auto points = renderer::TFUtils::assembleFromSettings(colorValues, colorPositions,
opacityValues, opacityPositions, minDensity, maxDensity, opacityScaling,
purgeZeroOpacityRegions);
return renderer::TFUtils::getTextureTensor(points, resolution);
}
TfGaussianEditor::TfGaussianEditor()
: isChanged_(true)
, points_{
Point{ImVec4(1,0,0,alpha1_), 0.6f, 0.7f, 0.05f},
Point{ImVec4(0,1,0,alpha1_), 0.3f, 0.3f, 0.03f}
}
{
}
void TfGaussianEditor::render(const ImRect& tfEditorRect)
{
//Draw the bounding rectangle.
ImGuiWindow* window = ImGui::GetCurrentWindow();
window->DrawList->AddRect(tfEditorRect.Min, tfEditorRect.Max, ImColor(ImVec4(0.3f, 0.3f, 0.3f, 1.0f)), 0.0f, ImDrawCornerFlags_All, 1.0f);
//draw lines
static const int Samples = 100;
const int numPoints = points_.size();
//mixture
const auto eval = [this, numPoints](float x)
{
float opacity = 0;
float3 color = make_float3(0, 0, 0);
for (int i = 0; i < numPoints; ++i) {
float w = points_[i].opacity * normal(x, points_[i].mean, points_[i].variance);
opacity += w;
color += make_float3(points_[i].color.x, points_[i].color.y, points_[i].color.z) * w;
}
color /= opacity;
return std::make_pair(opacity, ImGui::GetColorU32(ImVec4(color.x, color.y, color.z, alpha2_)));
};
auto [o0, c0] = eval(0);
float x0 = 0;
for (int j = 1; j <= Samples; ++j)
{
float x1 = j / float(Samples);
const auto [o1, c1] = eval(x1);
ImVec2 a = ImLerp(tfEditorRect.Min, tfEditorRect.Max,
ImVec2(x0, 1 - o0));
ImVec2 b = ImLerp(tfEditorRect.Min, tfEditorRect.Max,
ImVec2(x1, 1 - o1));
window->DrawList->AddLine(a, b, c0, thickness2_);
x0 = x1;
o0 = o1;
c0 = c1;
}
//single gaussians
for (int i=0; i<numPoints; ++i)
{
ImU32 col = ImGui::GetColorU32(points_[i].color);
float opacity = points_[i].opacity;
float mean = points_[i].mean;
float variance = points_[i].variance;
float denom = 1.0f / (2 * variance * variance);
float y0 = opacity*expf(-mean * mean * denom);
float x0 = 0;
for (int j=1; j<=Samples; ++j)
{
float x1 = j / float(Samples);
float y1 = opacity*expf(-(x1 - mean) * (x1 - mean) * denom);
if (y0 > 1e-3 || y1 > 1e-3) {
ImVec2 a = ImLerp(tfEditorRect.Min, tfEditorRect.Max,
ImVec2(x0, 1 - y0));
ImVec2 b = ImLerp(tfEditorRect.Min, tfEditorRect.Max,
ImVec2(x1, 1 - y1));
window->DrawList->AddLine(a, b, col, thickness1_);
}
y0 = y1; x0 = x1;
}
}
//draw control points
float minDistance = FLT_MAX;
int bestSelection = -1;
auto mousePosition = ImGui::GetMousePos();
for (int i = 0; i < numPoints; ++i)
{
ImU32 col = ImGui::GetColorU32(points_[i].color);
float opacity = points_[i].opacity;
float mean = points_[i].mean;
auto cp = editorToScreen(tfEditorRect, ImVec2(mean, opacity));
window->DrawList->AddCircleFilled(cp, circleRadius_, col, 16);
window->DrawList->AddCircle(cp, circleRadius_ + 1, ImGui::GetColorU32(ImVec4(0, 0, 0, 1)));
if (i==selectedPoint_)
window->DrawList->AddCircle(cp, circleRadius_ + 2, ImGui::GetColorU32(ImGuiCol_Text));
float dist = ImLengthSqr(ImVec2(mousePosition.x - cp.x, mousePosition.y - cp.y));
if (dist<minDistance)
{
minDistance = dist;
bestSelection = i;
}
}
//handle io
isChanged_ = false;
if (TfPiecewiseLinearEditor::testIntersectionRectPoint(tfEditorRect, mousePosition)
|| draggedPoint_ != -1)
{
bool isLeftDoubleClicked = ImGui::IsMouseDoubleClicked(0);
bool isLeftClicked = ImGui::IsMouseDown(0);
bool isRightClicked = ImGui::IsMouseClicked(1);
bool isLeftReleased = ImGui::IsMouseReleased(0);
auto mouseEditor = screenToEditor(tfEditorRect, mousePosition);
if (isLeftDoubleClicked)
{
isChanged_ = true;
points_.push_back({
ImVec4(1,1,1,alpha1_),
mouseEditor.y,
mouseEditor.x,
0.01f
}
);
selectedPoint_ = points_.size() - 1;
draggedPoint_ = -1;
} else if (isLeftClicked)
{
if (draggedPoint_>=0)
{
//move selected point
isChanged_ = true;
ImVec2 center(std::min(std::max(mousePosition.x, tfEditorRect.Min.x), tfEditorRect.Max.x),
std::min(std::max(mousePosition.y, tfEditorRect.Min.y), tfEditorRect.Max.y));
auto p = screenToEditor(tfEditorRect, center);
points_[draggedPoint_].mean = p.x;
points_[draggedPoint_].opacity = p.y;
} else
{
//select new point for hovering
if (minDistance < (circleRadius_+2)*(circleRadius_+2))
{
draggedPoint_ = bestSelection;
selectedPoint_ = bestSelection;
}
}
} else if (isRightClicked)
{
if (minDistance < (circleRadius_ + 2) * (circleRadius_ + 2))
{
isChanged_ = true;
points_.erase(points_.begin() + bestSelection);
selectedPoint_ = points_.empty() ? -1 : 0;
draggedPoint_ = -1;
}
} else if (isLeftReleased)
{
draggedPoint_ = -1;
}
}
//controls
if (selectedPoint_ >= 0) {
ImGuiColorEditFlags colorFlags = ImGuiColorEditFlags_Float | ImGuiColorEditFlags_InputRGB;
if (ImGui::ColorEdit3("", &points_[selectedPoint_].color.x, colorFlags))
isChanged_ = true;
if (ImGui::SliderFloat("Variance", &points_[selectedPoint_].variance,
0.001f, 0.5f, "%.3f", 2))
isChanged_ = true;
}
}
void TfGaussianEditor::saveToFile(const std::string& path, float minDensity, float maxDensity) const
{
nlohmann::json json;
json["type"] = "GaussianTF";
json["data"] = toJson();
json["minDensity"] = minDensity;
json["maxDensity"] = maxDensity;
std::ofstream out(path);
out << json;
out.close();
}
void TfGaussianEditor::loadFromFile(const std::string& path, float& minDensity, float& maxDensity)
{
nlohmann::json json;
std::ifstream file(path);
file >> json;
file.close();
if (!json.contains("type") || json["type"] != "GaussianTF") {
std::cerr << "Not a gaussian TF!" << std::endl;
return;
//throw std::runtime_error("not a gaussian transfer function");
}
auto data = json["data"];
fromJson(data);
minDensity = json["minDensity"];
maxDensity = json["maxDensity"];
}
nlohmann::json TfGaussianEditor::toJson() const
{
nlohmann::json a = nlohmann::json::array();
for (int i = 0; i < points_.size(); ++i)
{
a.push_back(nlohmann::json::array({
points_[i].color.x,
points_[i].color.y,
points_[i].color.z,
points_[i].opacity,
points_[i].mean,
points_[i].variance
}));
}
return a;
}
void TfGaussianEditor::fromJson(const nlohmann::json& s)
{
assert(s.is_array());
points_.resize(s.size());
for (int i=0; i<s.size(); ++i)
{
auto e = s[i];
assert(e.is_array());
assert(e.size() == 6);
points_[i] = {
ImVec4(e[0], e[1], e[2], alpha1_), e[3], e[4], e[5]
};
}
isChanged_ = true;
}
torch::Tensor TfGaussianEditor::getGaussianTensor(float minDensity, float maxDensity, float opacityScaling) const
{
int numPoints = static_cast<int>(points_.size());
torch::Tensor t = torch::empty(
{ 1, numPoints, 6 },
at::TensorOptions().dtype(real_dtype));
auto acc = t.packed_accessor32<real_t, 3>();
for (int i=0; i<numPoints; ++i)
{
acc[0][i][0] = points_[i].color.x;
acc[0][i][1] = points_[i].color.y;
acc[0][i][2] = points_[i].color.z;
acc[0][i][3] = points_[i].opacity * opacityScaling;
acc[0][i][4] = lerp(minDensity, maxDensity, points_[i].mean);
acc[0][i][5] = points_[i].variance * (maxDensity-minDensity);
}
return t;
}
float TfGaussianEditor::normal(float x, float mean, float variance)
{
return expf(-(x - mean) * (x - mean) / (2 * variance * variance));
}
ImVec2 TfGaussianEditor::screenToEditor(const ImRect& tfEditorRect, const ImVec2& screenPosition)
{
ImVec2 editorPosition;
editorPosition.x = (screenPosition.x - tfEditorRect.Min.x) / (tfEditorRect.Max.x - tfEditorRect.Min.x);
editorPosition.y = 1.0f - (screenPosition.y - tfEditorRect.Min.y) / (tfEditorRect.Max.y - tfEditorRect.Min.y);
return editorPosition;
}
ImVec2 TfGaussianEditor::editorToScreen(const ImRect& tfEditorRect, const ImVec2& editorPosition)
{
ImVec2 screenPosition;
screenPosition.x = editorPosition.x * (tfEditorRect.Max.x - tfEditorRect.Min.x) + tfEditorRect.Min.x;
screenPosition.y = (1.0f - editorPosition.y) * (tfEditorRect.Max.y - tfEditorRect.Min.y) + tfEditorRect.Min.y;
return screenPosition;
}
| 30.37397 | 144 | 0.712643 | shamanDevel |
31d1b04973eb9629f3086e6b27571297e83c5f89 | 13,925 | cpp | C++ | Ivan Krivyakov/WinstaDacl.cpp | arlm/EnumWinstaGui-Sharp | a9bd8a83a3d61f9229172020e12c482219fe537e | [
"MIT"
] | null | null | null | Ivan Krivyakov/WinstaDacl.cpp | arlm/EnumWinstaGui-Sharp | a9bd8a83a3d61f9229172020e12c482219fe537e | [
"MIT"
] | null | null | null | Ivan Krivyakov/WinstaDacl.cpp | arlm/EnumWinstaGui-Sharp | a9bd8a83a3d61f9229172020e12c482219fe537e | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "aclui.h" // platform SDK
#include "aclapi.h" // platform SDK
#include <afxpriv.h>
#pragma comment( lib, "aclui.lib" )
#pragma comment( lib, "comctl32.lib" )
#pragma comment( lib, "advapi32.lib" )
#pragma comment( lib, "user32.lib" )
// here's the access permission masks for window stations
// and desktops, excerpted from winuser.h
/*
#define WINSTA_ENUMDESKTOPS 0x0001L
#define WINSTA_READATTRIBUTES 0x0002L
#define WINSTA_ACCESSCLIPBOARD 0x0004L
#define WINSTA_CREATEDESKTOP 0x0008L
#define WINSTA_WRITEATTRIBUTES 0x0010L
#define WINSTA_ACCESSGLOBALATOMS 0x0020L
#define WINSTA_EXITWINDOWS 0x0040L
#define WINSTA_ENUMERATE 0x0100L
#define WINSTA_READSCREEN 0x0200L
#define DESKTOP_READOBJECTS 0x0001L
#define DESKTOP_CREATEWINDOW 0x0002L
#define DESKTOP_CREATEMENU 0x0004L
#define DESKTOP_HOOKCONTROL 0x0008L
#define DESKTOP_JOURNALRECORD 0x0010L
#define DESKTOP_JOURNALPLAYBACK 0x0020L
#define DESKTOP_ENUMERATE 0x0040L
#define DESKTOP_WRITEOBJECTS 0x0080L
#define DESKTOP_SWITCHDESKTOP 0x0100L
*/
// This table maps window station permissions onto strings.
// Notice the first entry, which includes all permissions; it maps to a string "Full Control".
// I love this feature of being able to provide multiple permissions in one entry,
// if you use it carefully, it's pretty powerful - the access control editor will
// automatically keep the permission checkboxes synchronized, which makes it clear
// to the user what is going on (if they pay close enough attention).
//
// Notice that I included standard permissions - don't forget them...
// Notice that I left some of the more esoteric permissions for the Advanced dialog,
// and that I only show "Full Control" in the basic permissions editor.
// This is consistent with the way the file acl editor works.
SI_ACCESS g_winstaAccess[] = {
// these are the full-blown permissions, listing both winsta and desktop
// permissions (since inheritable desktop ACEs are often found in winsta DACLs)
{ &GUID_NULL, 0x00000001, MAKEINTRESOURCEW( 1), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000002, MAKEINTRESOURCEW( 2), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000004, MAKEINTRESOURCEW( 3), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000008, MAKEINTRESOURCEW( 4), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000010, MAKEINTRESOURCEW( 5), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000020, MAKEINTRESOURCEW( 6), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000040, MAKEINTRESOURCEW( 7), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000080, MAKEINTRESOURCEW( 8), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000100, MAKEINTRESOURCEW( 9), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000200, MAKEINTRESOURCEW(10), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, DELETE, MAKEINTRESOURCEW(30), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, READ_CONTROL, MAKEINTRESOURCEW(31), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, WRITE_DAC, MAKEINTRESOURCEW(32), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, WRITE_OWNER, MAKEINTRESOURCEW(33), SI_ACCESS_SPECIFIC },
// these are a much easier-to-swallow listing of basic rights for window stations
{ &GUID_NULL, 0x000F037F, MAKEINTRESOURCEW(11), SI_ACCESS_GENERAL }, // Full Control
{ &GUID_NULL, 0x00020302, MAKEINTRESOURCEW(12), SI_ACCESS_GENERAL }, // Read
{ &GUID_NULL, 0x000F007C, MAKEINTRESOURCEW(13), SI_ACCESS_GENERAL }, // Write
};
// Here's the corresponding table for desktop permissions
SI_ACCESS g_desktopAccess[] = {
{ &GUID_NULL, 0x00000001, MAKEINTRESOURCEW(21), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000002, MAKEINTRESOURCEW(22), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000004, MAKEINTRESOURCEW(23), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000008, MAKEINTRESOURCEW(24), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000010, MAKEINTRESOURCEW(25), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000020, MAKEINTRESOURCEW(26), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000040, MAKEINTRESOURCEW(27), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000080, MAKEINTRESOURCEW(28), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, 0x00000100, MAKEINTRESOURCEW(29), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, DELETE, MAKEINTRESOURCEW(30), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, READ_CONTROL, MAKEINTRESOURCEW(31), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, WRITE_DAC, MAKEINTRESOURCEW(32), SI_ACCESS_SPECIFIC },
{ &GUID_NULL, WRITE_OWNER, MAKEINTRESOURCEW(33), SI_ACCESS_SPECIFIC },
// these are a much easier-to-swallow listing of basic rights for desktops
{ &GUID_NULL, 0x000F01FF, MAKEINTRESOURCEW(11), SI_ACCESS_GENERAL }, // Full Control
{ &GUID_NULL, 0x000F0051, MAKEINTRESOURCEW(12), SI_ACCESS_GENERAL }, // Read
{ &GUID_NULL, 0x000F01AE, MAKEINTRESOURCEW(13), SI_ACCESS_GENERAL }, // Write
};
// Here's my crufted-up mapping for desktop generic rights
GENERIC_MAPPING g_desktopGenericMapping = {
STANDARD_RIGHTS_READ | DESKTOP_READOBJECTS | DESKTOP_JOURNALRECORD | DESKTOP_ENUMERATE,
STANDARD_RIGHTS_WRITE | DESKTOP_CREATEWINDOW | DESKTOP_CREATEMENU | DESKTOP_HOOKCONTROL | DESKTOP_JOURNALPLAYBACK | DESKTOP_WRITEOBJECTS | DESKTOP_SWITCHDESKTOP,
STANDARD_RIGHTS_EXECUTE,
STANDARD_RIGHTS_REQUIRED | 0x000001FF
};
// Here's my crufted-up mapping for winstation generic rights
GENERIC_MAPPING g_winstaGenericMapping = {
STANDARD_RIGHTS_READ | WINSTA_ENUMDESKTOPS | WINSTA_READATTRIBUTES | WINSTA_ENUMERATE | WINSTA_READSCREEN,
STANDARD_RIGHTS_WRITE | WINSTA_ACCESSCLIPBOARD | WINSTA_CREATEDESKTOP | WINSTA_WRITEATTRIBUTES | WINSTA_ACCESSGLOBALATOMS | WINSTA_EXITWINDOWS,
STANDARD_RIGHTS_EXECUTE,
STANDARD_RIGHTS_REQUIRED | 0x0000037F
};
// This table maps the various inheritance options supported by window stations
// onto human readable strings ("This window station only", "Desktops only", etc.)
// These strings show up in the Advanced DACL editor for window stations, in a dropdown
SI_INHERIT_TYPE g_winstaInheritTypes[] = {
{ &GUID_NULL, 0, MAKEINTRESOURCEW( 40 ) },
{ &GUID_NULL, CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE, MAKEINTRESOURCEW( 41 ) },
{ &GUID_NULL, INHERIT_ONLY_ACE | CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE, MAKEINTRESOURCEW( 42 ) }
};
HINSTANCE g_hInst;
// This base class factors out common implementation between
// the window station and desktop implementations of ISecurityInformation.
// For instance, the Set/GetSecurity calls can be implemented once,
// since they both just call Set/GetSecurityInfo passing a handle
// (of either a winsta or a desktop).
struct CWindowObjectSecurityInfoBase : ISecurityInformation
{
long m_cRefs;
HANDLE m_handle;
DWORD m_grfExtraFlags;
const wchar_t* const m_pszObjectName;
const wchar_t* const m_pszPageTitle;
CWindowObjectSecurityInfoBase( HANDLE h,
DWORD grfExtraFlags,
const wchar_t* pszObjectName,
const wchar_t* pszPageTitle = 0 )
: m_cRefs(0),
m_handle(h),
m_grfExtraFlags( grfExtraFlags ),
m_pszObjectName( pszObjectName ),
m_pszPageTitle( pszPageTitle )
{}
virtual ~CWindowObjectSecurityInfoBase() {}
STDMETHODIMP QueryInterface( REFIID iid, void** ppv )
{
if ( IID_IUnknown == iid || IID_ISecurityInformation == iid )
*ppv = static_cast<ISecurityInformation*>(this);
else return (*ppv = 0), E_NOINTERFACE;
reinterpret_cast<IUnknown*>( *ppv )->AddRef();
return S_OK;
}
STDMETHODIMP_(ULONG) AddRef()
{
return ++m_cRefs;
}
STDMETHODIMP_(ULONG) Release()
{
ULONG n = --m_cRefs;
if ( 0 == n )
delete this;
return n;
}
STDMETHODIMP GetObjectInformation( SI_OBJECT_INFO* poi )
{
// We want to edit the DACL (PERMS), the OWNER,
// and we want the Advanced button
poi->dwFlags = SI_EDIT_OWNER | SI_EDIT_PERMS |
SI_ADVANCED | m_grfExtraFlags;
// this determines the module used to discover stringtable entries
poi->hInstance = g_hInst;
poi->pszServerName = L"";
poi->pszObjectName = const_cast<wchar_t*>( m_pszObjectName );
poi->pszPageTitle = const_cast<wchar_t*>( m_pszPageTitle );
if ( m_pszPageTitle )
poi->dwFlags |= SI_PAGE_TITLE;
return S_OK;
}
STDMETHODIMP GetSecurity( SECURITY_INFORMATION ri, void** ppsd, BOOL bDefault )
{
// map directly onto the winsta/desktop security descriptor
const DWORD err = GetSecurityInfo( m_handle, SE_WINDOW_OBJECT, ri, 0, 0, 0, 0, ppsd );
return err ? HRESULT_FROM_WIN32(err) : S_OK;
}
STDMETHODIMP SetSecurity( SECURITY_INFORMATION ri, void* psd )
{
// map directly onto the winsta/desktop security descriptor
void* pOwner = 0;
void* pGroup = 0;
ACL* pdacl = 0;
ACL* psacl = 0;
BOOL bDefaulted;
BOOL bPresent;
if ( OWNER_SECURITY_INFORMATION & ri )
GetSecurityDescriptorOwner( psd, &pOwner, &bDefaulted );
if ( GROUP_SECURITY_INFORMATION & ri )
GetSecurityDescriptorGroup( psd, &pGroup, &bDefaulted );
if ( DACL_SECURITY_INFORMATION & ri )
GetSecurityDescriptorDacl( psd, &bPresent, &pdacl, &bDefaulted );
if ( SACL_SECURITY_INFORMATION & ri )
GetSecurityDescriptorSacl( psd, &bPresent, &psacl, &bDefaulted );
const DWORD err = SetSecurityInfo( m_handle, SE_WINDOW_OBJECT, ri, pOwner, pGroup, pdacl, psacl );
return err ? HRESULT_FROM_WIN32(err) : S_OK;
}
STDMETHODIMP PropertySheetPageCallback( HWND hwnd, UINT msg, SI_PAGE_TYPE pt )
{
// this is effectively a pass-through from the PropertySheet callback,
// which we don't care about for this sample
return S_OK;
}
};
struct CWinstaSecurityInfo : CWindowObjectSecurityInfoBase
{
CWinstaSecurityInfo( HWINSTA h, const wchar_t* pszObjectTitle, const wchar_t* pszPageTitle = 0 )
: CWindowObjectSecurityInfoBase( h, SI_CONTAINER | SI_NO_ACL_PROTECT,
pszObjectTitle, pszPageTitle )
{}
~CWinstaSecurityInfo()
{
#ifdef _DEBUG
OutputDebugString( "CWinstaSecurityInfo was destroyed\n" );
#endif // _DEBUG
}
STDMETHODIMP GetAccessRights( const GUID*,
DWORD dwFlags,
SI_ACCESS** ppAccess,
ULONG* pcAccesses,
ULONG* piDefaultAccess )
{
// here's where we hand back the winsta permissions->strings mapping
*ppAccess = const_cast<SI_ACCESS*>( g_winstaAccess );
*pcAccesses = sizeof g_winstaAccess / sizeof *g_winstaAccess;
*piDefaultAccess = 0;
return S_OK;
}
STDMETHODIMP MapGeneric( const GUID*, UCHAR* pAceFlags, ACCESS_MASK* pMask )
{
// here's where we hand back the winsta generic permissions mapping
MapGenericMask( pMask, const_cast<GENERIC_MAPPING*>( &g_winstaGenericMapping ) );
return S_OK;
}
STDMETHODIMP GetInheritTypes( SI_INHERIT_TYPE** ppInheritTypes, ULONG* pcInheritTypes )
{
// here's where we hand back the winsta inheritance combinations and string mappings
*ppInheritTypes = g_winstaInheritTypes;
*pcInheritTypes = sizeof g_winstaInheritTypes / sizeof *g_winstaInheritTypes;
return S_OK;
}
};
struct CDesktopSecurityInfo : CWindowObjectSecurityInfoBase
{
CDesktopSecurityInfo( HDESK h, const wchar_t* pszObjectTitle, const wchar_t* pszPageTitle = 0 )
: CWindowObjectSecurityInfoBase( h, 0, pszObjectTitle, pszPageTitle )
{}
~CDesktopSecurityInfo()
{
#ifdef _DEBUG
OutputDebugString( "CDesktopSecurityInfo was destroyed\n" );
#endif // _DEBUG
}
STDMETHODIMP GetAccessRights( const GUID*,
DWORD dwFlags,
SI_ACCESS** ppAccess,
ULONG* pcAccesses,
ULONG* piDefaultAccess )
{
// here's where we hand back the desktop permissions->strings mapping
*ppAccess = const_cast<SI_ACCESS*>( g_desktopAccess );
*pcAccesses = sizeof g_desktopAccess / sizeof *g_desktopAccess;
*piDefaultAccess = 0;
return S_OK;
}
STDMETHODIMP MapGeneric( const GUID*, UCHAR* pAceFlags, ACCESS_MASK* pMask )
{
// here's where we hand back the desktop generic permissions mapping
MapGenericMask( pMask, const_cast<GENERIC_MAPPING*>( &g_desktopGenericMapping ) );
return S_OK;
}
STDMETHODIMP GetInheritTypes( SI_INHERIT_TYPE** ppInheritTypes, ULONG* pcInheritTypes )
{
// Desktops are not containers, and thus have no options for inheritable
// entries in the DACL or SACL. Since we didn't specify SI_CONTAINER in our
// GetObjectInformation call, this function will never be called.
return E_NOTIMPL;
}
};
void EditWinstaSecurity( HWINSTA hWinsta, LPCTSTR Name )
{
USES_CONVERSION;
// Convert our ISecurityInformation implementations into property pages
HPROPSHEETPAGE rghps;
{
CWinstaSecurityInfo* pwsi = new CWinstaSecurityInfo( hWinsta, T2W(Name), L"Window Station" );
pwsi->AddRef();
rghps = CreateSecurityPage( pwsi );
pwsi->Release();
}
// Wrap our two property pages in a modal dialog by calling PropertySheet
PROPSHEETHEADER psh; ZeroMemory( &psh, sizeof psh );
psh.dwSize = sizeof psh;
psh.hInstance = AfxGetInstanceHandle();
psh.pszCaption = Name;
psh.nPages = 1;
psh.phpage = &rghps;
PropertySheet( &psh );
// By the time PropertySheet returns, the property pages have been torn down
// and have released our ISecurityInformation implementations. Watch in the
// VC output window for a debug message that shows they have been destroyed
// correctly.
}
void EditDesktopSecurity( HDESK hDesktop, LPCTSTR Name )
{
USES_CONVERSION;
// Convert our ISecurityInformation implementations into property pages
HPROPSHEETPAGE rghps;
{
CDesktopSecurityInfo* pdsi = new CDesktopSecurityInfo( hDesktop, T2W(Name), L"Desktop" );
pdsi->AddRef();
rghps = CreateSecurityPage( pdsi );
pdsi->Release();
}
// Wrap our two property pages in a modal dialog by calling PropertySheet
PROPSHEETHEADER psh; ZeroMemory( &psh, sizeof psh );
psh.dwSize = sizeof psh;
psh.hInstance = AfxGetInstanceHandle();
psh.pszCaption = Name;
psh.nPages = 1;
psh.phpage = &rghps;
PropertySheet( &psh );
// By the time PropertySheet returns, the property pages have been torn down
// and have released our ISecurityInformation implementations. Watch in the
// VC output window for a debug message that shows they have been destroyed
// correctly.
}
| 38.255495 | 162 | 0.747864 | arlm |
31d2b445465a692fd314c9af51918c773d81c991 | 559 | cpp | C++ | purenessscopeserver/FrameCore/CppUnit/Unit_BaseConnectClient.cpp | freeeyes/PSS | cb6dac549f2fa36c9838b5cb183ba010d56978e3 | [
"Apache-2.0"
] | 213 | 2015-01-08T05:58:52.000Z | 2022-03-22T01:23:37.000Z | purenessscopeserver/FrameCore/CppUnit/Unit_BaseConnectClient.cpp | volute24/PSS | cb6dac549f2fa36c9838b5cb183ba010d56978e3 | [
"Apache-2.0"
] | 33 | 2015-09-11T02:52:03.000Z | 2021-04-12T01:23:48.000Z | purenessscopeserver/FrameCore/CppUnit/Unit_BaseConnectClient.cpp | volute24/PSS | cb6dac549f2fa36c9838b5cb183ba010d56978e3 | [
"Apache-2.0"
] | 126 | 2015-01-08T06:21:05.000Z | 2021-11-19T08:19:12.000Z | #include "Unit_BaseConnectClient.h"
#ifdef _CPPUNIT_TEST
void CUnit_BaseConnectClient::setUp(void)
{
m_u2CommandID = 0x1003;
}
void CUnit_BaseConnectClient::tearDown(void)
{
m_u2CommandID = 0;
}
void CUnit_BaseConnectClient::Test_Common_Send_ConnectError(void)
{
ACE_INET_Addr objAddrServer;
CPostServerData objPostServerData;
ACE_Message_Block* pMb = App_MessageBlockManager::instance()->Create(10);
Common_Send_ConnectError(pMb, objAddrServer, dynamic_cast<IClientMessage*>(&objPostServerData));
m_nTestCount++;
}
#endif
| 19.964286 | 100 | 0.774597 | freeeyes |
31d48a73c081bb3bb53f5f890ef654e987285e4c | 2,940 | cpp | C++ | TAO/docs/tutorials/Quoter/Simple/Impl-Repo/server.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/docs/tutorials/Quoter/Simple/Impl-Repo/server.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/docs/tutorials/Quoter/Simple/Impl-Repo/server.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z |
//=============================================================================
/**
* @file server.cpp
*
* $Id: server.cpp 93650 2011-03-28 08:44:53Z johnnyw $
*
* In this example,
* - Example showing the working of implementation repository.
*
*
* @author Priyanka Gontla
*/
//=============================================================================
#include "Stock_Factory_i.h"
#include "tao/IORTable/IORTable.h"
#include "ace/streams.h"
int ACE_TMAIN (int argc, ACE_TCHAR* argv[])
{
try {
// Initialze the ORB.
CORBA::ORB_var orb = CORBA::ORB_init (argc, argv);
// Get a reference to the RootPOA.
CORBA::Object_var obj = orb->resolve_initial_references ("RootPOA");
// Get the POA_var object from Object_var.
PortableServer::POA_var root_poa =
PortableServer::POA::_narrow (obj.in ());
// Get the POAManager of the RootPOA.
PortableServer::POAManager_var poa_manager =
root_poa->the_POAManager ();
poa_manager->activate ();
// Policies for the childPOA to be created.
CORBA::PolicyList policies;
policies.length (2);
policies[0] =
root_poa->create_id_assignment_policy (PortableServer::USER_ID);
policies[1] =
root_poa->create_lifespan_policy (PortableServer::PERSISTENT);
// Create the childPOA under the RootPOA.
PortableServer::POA_var child_poa =
root_poa->create_POA ("childPOA",
poa_manager.in (),
policies);
// Destroy the policy objects
for (CORBA::ULong i = 0; i != policies.length (); ++i) {
policies[i]->destroy ();
}
// Create an instance of class Quoter_Stock_Factory_i.
Quoter_Stock_Factory_i stock_factory_i;
// Get the Object ID.
PortableServer::ObjectId_var oid =
PortableServer::string_to_ObjectId ("Stock_Factory");
// Activate the Stock_Factory object.
child_poa->activate_object_with_id (oid.in (),
&stock_factory_i);
// Get the object reference.
CORBA::Object_var stock_factory =
child_poa->id_to_reference (oid.in ());
CORBA::Object_var table_object =
orb->resolve_initial_references ("IORTable");
// Stringify all the object referencs.
CORBA::String_var ior = orb->object_to_string (stock_factory.in ());
IORTable::Table_var adapter =
IORTable::Table::_narrow (table_object.in ());
if (CORBA::is_nil (adapter.in ()))
{
ACE_ERROR ((LM_ERROR, "Nil IORTable\n"));
}
else
{
CORBA::String_var ior =
orb->object_to_string (stock_factory.in ());
adapter->bind ("childPOA", ior.in ());
}
orb->run ();
// Destroy POA, waiting until the destruction terminates.
root_poa->destroy (1, 1);
orb->destroy ();
}
catch (CORBA::Exception &) {
cerr << "CORBA exception raised !" << endl;
}
return 0;
}
| 27.222222 | 79 | 0.592517 | cflowe |
31d7740a1cc8ecda041ab5376d9f5d20eebe6147 | 799 | cpp | C++ | lib/mutexp.cpp | williamledda/CPPosix | 235e990731c7cade43a1105dce6705329c56adbe | [
"MIT"
] | null | null | null | lib/mutexp.cpp | williamledda/CPPosix | 235e990731c7cade43a1105dce6705329c56adbe | [
"MIT"
] | null | null | null | lib/mutexp.cpp | williamledda/CPPosix | 235e990731c7cade43a1105dce6705329c56adbe | [
"MIT"
] | null | null | null | /*
* mutexp.cpp
*
* Created on: 11 gen 2018
* Author: william
*/
#include "mutexp.h"
#include <iostream>
namespace cpposix {
MutexP::MutexP() {
/*Both returns always zero. No error check is needed*/
pthread_mutexattr_init(&this->mtx_attr);
pthread_mutex_init(&this->mtx, &this->mtx_attr);
}
MutexP::~MutexP() {
if(pthread_mutex_destroy(&this->mtx) != 0) {
std::cerr << "Error destroying mutex" << std::endl;
}
if(pthread_mutexattr_destroy(&this->mtx_attr) != 0) {
std::cerr << "Error destroying mutex attribute" << std::endl;
}
}
int MutexP::lock(void) {
return pthread_mutex_lock(&this->mtx);
}
int MutexP::unlock(void) {
return pthread_mutex_unlock(&this->mtx);
}
int MutexP::tryLock(void) {
return pthread_mutex_trylock(&this->mtx);
}
} /* namespace cpposix */
| 18.581395 | 63 | 0.674593 | williamledda |
31dbc824948a7a31ecce7e3b96ba48db77e33a51 | 880 | cpp | C++ | source/toy/gadget/HexCharToInt.cpp | ToyAuthor/ToyBox | f517a64d00e00ccaedd76e33ed5897edc6fde55e | [
"Unlicense"
] | 4 | 2017-07-06T22:18:41.000Z | 2021-05-24T21:28:37.000Z | source/toy/gadget/HexCharToInt.cpp | ToyAuthor/ToyBox | f517a64d00e00ccaedd76e33ed5897edc6fde55e | [
"Unlicense"
] | null | null | null | source/toy/gadget/HexCharToInt.cpp | ToyAuthor/ToyBox | f517a64d00e00ccaedd76e33ed5897edc6fde55e | [
"Unlicense"
] | 1 | 2020-08-02T13:00:38.000Z | 2020-08-02T13:00:38.000Z | #include "toy/gadget/HexCharToInt.hpp"
#if TOY_OPTION_RELEASE
#include "toy/Oops.hpp"
#else
#include "toy/Exception.hpp"
#endif
namespace toy{
namespace gadget{
int HexCharToInt(const char code)
{
if ( code<'0' )
{
#if TOY_OPTION_RELEASE
toy::Oops(TOY_MARK);
return 0;
#else
throw toy::Exception(TOY_MARK);
#endif
}
else if ( code>'9' )
{
switch ( code )
{
case 'a': return 10;
case 'A': return 10;
case 'b': return 11;
case 'B': return 11;
case 'c': return 12;
case 'C': return 12;
case 'd': return 13;
case 'D': return 13;
case 'e': return 14;
case 'E': return 14;
case 'f': return 15;
case 'F': return 15;
default:
#if TOY_OPTION_RELEASE
{
toy::Oops(TOY_MARK);
return 0;
}
#else
throw toy::Exception(TOY_MARK);
#endif
}
}
else
{
return code-'0';
}
return 0;
}
}}
| 14.915254 | 38 | 0.589773 | ToyAuthor |