blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
2ec033fc339a5efec15382909ea222b9c8a524cb
d11b037358cac25636b4908a679074a67d7ec1aa
/tensorflow/compiler/xla/pjrt/tpu_client.h
0709c3b4d387eb1e30c8f4263411377b3a093f05
[ "Apache-2.0" ]
permissive
skye/tensorflow
a89e11fca8afad8f80d2fab68ba77f98a86e287a
b6d0e70f440a090628d2b5ab9c9422e9aae493dc
refs/heads/master
2023-02-09T06:18:15.165557
2020-09-17T18:34:17
2020-09-17T22:10:56
99,622,779
0
0
null
2017-08-11T22:59:36
2017-08-07T21:39:14
C++
UTF-8
C++
false
false
3,137
h
/* Copyright 2020 The TensorFlow Authors. 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. ==============================================================================*/ #ifndef TENSORFLOW_COMPILER_XLA_PJRT_TPU_CLIENT_H_ #define TENSORFLOW_COMPILER_XLA_PJRT_TPU_CLIENT_H_ #include <array> #include <memory> #include <vector> #include "tensorflow/compiler/xla/pjrt/pjrt_client.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/stream_executor/tpu/tpu_platform_interface.h" #include "tensorflow/stream_executor/tpu/tpu_topology.h" namespace xla { class PjRtTpuDevice : public PjRtDevice { public: PjRtTpuDevice(const tensorflow::tpu::TpuCoreLocationExternal core, std::unique_ptr<LocalDeviceState> local_device_state, int host_id, const std::array<int, 3>& coords, std::string device_kind) : PjRtDevice(core.Id(), std::move(local_device_state), /*platform_name=*/"tpu", std::move(device_kind), host_id), core_(core), coords_(coords) {} const std::array<int, 3>& coords() const { return coords_; } int core_on_chip() const { return core_.index(); } const tensorflow::tpu::TpuCoreLocationExternal core() const { return core_; } std::string DebugString() const override { return absl::StrFormat("TPU_%i(host=%i,(%i,%i,%i,%i))", id(), host_id(), coords_[0], coords_[1], coords_[2], core_.index()); } private: const tensorflow::tpu::TpuCoreLocationExternal core_; const std::array<int, 3> coords_; }; class PjRtTpuClient : public PjRtClient { public: PjRtTpuClient(LocalClient* client, std::vector<std::unique_ptr<PjRtDevice>> devices, int host_id, tensorflow::tpu::TpuPlatformInterface* tpu_platform); StatusOr<DeviceAssignment> GetDefaultDeviceAssignment( int num_replicas, int num_partitions) const override; bool EnqueueD2DTransfersOnSrcStream() const override { return tpu_platform_->topology().version() == kTpuV4; } StatusOr<absl::optional<std::string>> ExecutableFingerprint( const PjRtExecutable& executable) const override; private: tensorflow::tpu::TpuPlatformInterface* tpu_platform_; }; StatusOr<std::shared_ptr<PjRtClient>> GetTpuClient(bool asynchronous); Status GetTpuClientArgs(bool asynchronous, LocalClient** local_client, std::vector<std::unique_ptr<PjRtDevice>>* devices, int* host_id, tensorflow::tpu::TpuPlatformInterface** tpu_platform); } // namespace xla #endif // TENSORFLOW_COMPILER_XLA_PJRT_TPU_CLIENT_H_
bb8949ff0a714c999a3688962555864ec87669ab
628f602b019ddceb835f40991939427deb2752e4
/22.01.2018/Source.cpp
62f12d13922b5069cb0a18b83f716317a2ff4bc8
[]
no_license
Konstantin96/LabWork1
443c1df83aec4c27fba779336bc06b15f2df12f7
f4856f927d29220c0092d9d3bcba8a571c3a672b
refs/heads/master
2021-05-10T11:13:02.138380
2018-01-22T04:24:46
2018-01-22T04:24:46
118,405,811
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
12,122
cpp
#include <stdio.h> #include <iostream> #include <locale.h> #include <time.h> #include <Windows.h> #include<ctime> #define sizeArr 20 using namespace std; unsigned short int nz; void main() { setlocale(LC_ALL, ".1251"); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); while (true) { srand(time(0)); cout << "Введите номер задания, для выхода нажмите 0 "; cin >> nz; if (nz == 0) { break; } else if (nz == 1) { /*Написать, программу, которая вычисляет прибыль фирмы за 6 месяцев. Пользователь вводит прибыль фирмы за каждый месяц*/ int sum, prib = 0; for (int i = 1; i <= 6; i++) { cout << "Vvedite summu za " << i << " mesyac :"; cin >> sum; prib += sum; } cout << "Pribyl' =" << prib << endl; } else if (nz == 2) { /*Написать программу, которая выводит одномерный массив в обратном порядке*/ int mas[7]; cout << "Massiv" << endl; for (int i = 0; i < 7; i++) { mas[i] = 1 + rand() % 99; cout << mas[i] << endl; } cout << "Massiv v obtratnom poryadke" << endl; for (int i = 6; 0 <= i; i--) { cout << mas[i] << endl; } } else if (nz == 3) { /*В одномерном массиве, заполненном случайными числами, определить минимальный и максимальный элементы*/ int mas[10], min = 0, max = 0; cout << "Massiv" << endl; for (int i = 0; i < 10; i++) { mas[i] = 1 + rand() % 99; cout << mas[i] << endl; } min = mas[0]; max = mas[0]; cout << "Min element = "; for (int i = 0; i < 10; i++) { if (mas[i] < min) { min = mas[i]; } } cout << min << endl; cout << "Max element = "; for (int i = 0; i < 10; i++) { if (mas[i] > max) { max = mas[i]; } } cout << max << endl; } else if (nz == 4) { /*Пользователь вводит прибыль фирмы за год (12 месяцев). Необходимо определить месяц, в котором прибыль была максимальна и месяц, в котором прибыль была минимальна.*/ int mas[12], ch = 0, min = 0, max = 0; cout << "Pribyl' za god:" << endl; for (int i = 0; i < 12; i++) { ch++; mas[i] = 10000 + rand() % 109000; cout << ch << " mesyac. Pribyl' = " << mas[i] << endl; } min = mas[0]; max = mas[0]; cout << "Min pribyl' = "; for (int i = 0; i < 10; i++) { if (mas[i] < min) { min = mas[i]; } } cout << min << endl; cout << "Max pribyl' = "; for (int i = 0; i < 10; i++) { if (mas[i] > max) { max = mas[i]; } } cout << max << endl; } else if (nz == 5) { /*Написать программу, выполняющую сортировку одномерного массива целых чисел методом пузырька.*/\ cout << "Do sortirivki" << endl; int arrNumber[sizeArr]; for (int i = 0; i <= sizeArr - 1; i++) { arrNumber[i] = 1 + rand() % 99; } for (int i = 0; i <= sizeArr - 1; i++) { cout << "arr[" << i << "] = " << arrNumber[i] << "\n"; } cout << endl; cout << "Posle sortirivki" << endl; for (int i = 0; i < sizeArr - 1; i++) { for (int j = (sizeArr - 1); j > i; j--) { if (arrNumber[j - 1] > arrNumber[j]) { int temp = arrNumber[j - 1]; arrNumber[j - 1] = arrNumber[j]; arrNumber[j] = temp; } } cout << "arr[" << i << "] = " << arrNumber[i] << "\n"; } } else if (nz == 6) { /*3. *Пользователь вводит длину сторон пятиугольника, каждая сторона заноситься в массив, необходимо вычислить периметр пятиугольника (периметр – сумма всех сторон).*/ double sum = 0; for (int i = 0; i < 5; i++) { double temp; cin >> temp; sum += temp; } cout << sum; } else if (nz == 7) { /*Пользователь вводит прибыль фирмы за год (12 месяцев). Затем пользователь вводит диапазон (например, 3 и 6 – поиск между 3-м и 6-м месяцем). Необходимо определить месяц, в котором прибыль была максимальна и месяц, в котором прибыль была минимальна с учетом выбранного диапазона.*/ const char Month[][12] = { "Январь","Февраль","Март","Апрель","Май  ","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь" }; int profit[12]; int begin = 0; int end = 0; int max = begin; int min = begin; for (int i = 0; i < 12; i++) { profit[i] = 10000 + rand() % 109000; cout << "Прибыль в " << Month[i] << "= " << profit[i] << endl; } cout << "\n"; cout << "Введите начальный диапазон месяцев от 1 до 12  : "; cin >> begin; cout << "Введите конечный диапазон месяцев от 1 до 12  : "; cin >> end; for (int i = begin; i <= end; i++) { cout << " " << profit[i]; if (profit[max] <= profit[i]) max = i; if (profit[min] >= profit[i]) min = i; } cout << "\nМаксимальная прибыль в выбраном диапазоне будет в  " << Month[max] << "\t" << profit[max] << "\n\n"; cout << "\nМинимальная прибыль в выбраном диапазоне будет в  " << Month[min] << "\t" << profit[min] << "\n\n"; } else if (nz == 8) { /*В одномерном массиве, состоящем из N вещественных чисел вычислить: • Сумму отрицательных элементов. • Произведение элементов, находящихся между min и max элементами. • Произведение элементов с четными номерами. • Сумму элементов, находящихся между первым и последним отрицательными элементами. */ cout << "Vvedite razmer massiva:"; int n, a; cin >> n; cout << "Vedite" << n << "elements:\n"; for (int i = 0; i < n; i++) { cout << "a[" << i + 1 << "]: "; cin >> a; } int negativ = 0; for (int i = 0; i < n; i++) { if (a < 0) { negativ += a; } } cout << "Summa otricatel'nyh elementov = " << negativ << endl; int max = a, i_max, min = a, i_min; for (int i = 1; i < n; i++) { if (a > max) { max = a; i_max = i; } if (a < min) { min = a; i_min = i; } } i_min++; i_max--; int mult = 1; for (int i = i_min; i < i_max; i++) { mult *= a; } cout << "Произведение элементов, находящихся между min и max элементами =" << mult << endl; mult = 1; for (int i = 1; i < n; i += 2) { mult *= a; } cout << "Произведение элементов с четными номерами =" << mult << endl; for (int i = 0; i < n; i++) { if (a < 0) { i_min = i; break; } } for (int i = n - 1; i > i_min; i--) { if (a < 0) { i_max = i; break; } } i_min++; mult = 1; for (int i = i_min; i < i_max; i++) { mult *= a; } cout << "Сумму элементов, находящихся между первым и последним отрицательными элементами =" << mult << endl; } else if (nz == 9) { /*Написать программу, копирующую последовательно элементы одного массива размером 10 элементов в 2 массива размером 5 элементов каждый*/ int mas[10], masa[5], masb[5]; cout << "Massiv 1" << endl; for (int i = 0; i < 10; i++) { mas[i] = 1 + rand() % 99; cout << mas[i] << endl; } cout << endl; cout << "Massiv 2" << endl; for (int i = 0; i < 5; i++) { masa[i] = mas[i]; cout << masa[i] << endl; } cout << endl; cout << "Massiv 3" << endl; for (int i = 5; i < 10; i++) { masb[i] = mas[i]; cout << masb[i] << endl; } } else if (nz == 10) { /*17. *Написать программу, копирующую последовательно элементы 2-х массивов размером 5 элементов каждый в один массив размером 10 элементов.*/ int mas[10] = { 0 }, masa[5], masb[5]; cout << "Massiv 1" << endl; for (int i = 0; i < 5; i++) { masa[i] = 1 + rand() % 99; cout << masa[i] << endl; } cout << endl; cout << "Massiv 2" << endl; for (int i = 0; i < 5; i++) { masb[i] = 1 + rand() % 99; cout << masb[i] << endl; } cout << endl; cout << "Massiv 3" << endl; for (int i = 0; i < 5; i++) { mas[i] = masa[i]; } for (int i = 5; i < 10; i++) { mas[i] = masb[i]; cout << mas[i] << endl; } } else if (nz == 11) { /*В двухмерном массиве целых числе посчитать: a) сумму всех элементов массива b) среднее арифметическое всех элементов массива c) минимальный элемент d) максимальный элемент */ int mas[5][5], sum = 0, sr = 0, min = 0, max = 0; cout << "Massiv" << endl; for (int i = 0; i < 5; i++) { mas[i][5] = 1 + rand() % 99; for (int j = 0; j < 5; j++) { mas[i][j] = 1 + rand() % 99; cout << mas[i][j] << "\t"; } cout << endl; } cout << "Summa vseh elementov massiva = "; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { sum += mas[i][j]; } } cout << sum << endl; cout << endl; cout << "Srednee arifm = "; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { sr = sum / mas[i][j]; } } cout << sr << endl; cout << endl; cout << "Min element = "; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; i++) { if (mas[i][j] < min) { min = mas[i][j]; } }cout << endl; cout << "Min element = "; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; i++) { if (mas[i][j] < min) { min = mas[i][j]; } } } cout << min << endl; cout << endl; } cout << endl; cout << endl; cout << endl; cout << "Max element = "; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; i++) { if (mas[i][j] > min) { max = mas[i][j]; } } } cout << max << endl; cout << endl; } else if (nz == 12) { /*Заполнить двухмерный массив 8х8 значениями 0 и 1 случайным образом, но так, чтобы нулей было в два раза больше, чем единичек.*/ int array[8][8]; int null = 0, ed = 0; for (int i = 0; i <8; i++) { for (int j = 0; j < 8; j++) { array[i][j] = rand() % 2; cout <<" " <<array[i][j]; if (array[i][j] == 0) null++; if (array[i][j] == 1) ed++; } cout << "\n\n"; } cout << " Количесвто нулей в массиве равно: " << null; cout << "\n "; cout << "Количесвто единиц в массиве равно: " << ed; cout << "\n\n "; } } }
[ "Клюкинк@227_11" ]
Клюкинк@227_11
a394ed9b09e15788461ff79b76eaa0814f05a02e
6b39242e9ebc1e62b8f6ae6fe5def95bd1a59b4f
/剑指offer/删除链表中重复的结点[+].cpp
c4797ecdbeecad2ffc21eb5d68feb7f08896df47
[]
no_license
vachelch/Online-Judge
128d32e86aee04dbb4077f23b7c01379fe6d0aba
8a5cfc47cf3c5a2830b33a334a6acbc3f30ea0e1
refs/heads/master
2020-05-05T02:24:13.863187
2019-04-05T07:27:33
2019-04-05T07:27:33
179,636,392
0
0
null
null
null
null
UTF-8
C++
false
false
3,581
cpp
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; */ // stupid method class Solution { public: ListNode* deleteDuplication(ListNode* pHead) { if (pHead == NULL) return NULL; ListNode* head = pHead; ListNode* cur = pHead; set<int> values; set<int> repeat; while(cur){ if (values.find(cur->val) != values.end()) repeat.insert(cur->val); else values.insert(cur->val); cur = cur->next; } cur = head; while(cur && repeat.find(cur->val) != repeat.end()) cur = cur->next; head = cur; if (head == NULL) return NULL; while(cur->next){ if (repeat.find(cur->next->val) != repeat.end()) cur->next = cur->next->next; else cur = cur->next; } return head; } }; // recursion, mine class Solution { public: int repeated; ListNode* noDuplicate(ListNode* pHead) { if (pHead == NULL) return NULL; ListNode* list = noDuplicate(pHead->next); if (list == NULL) { if (pHead->val == repeated) return NULL; pHead->next = NULL; return pHead; } if(pHead->val == list->val){ repeated = pHead->val; list = list->next; return list; } else if (pHead->val == repeated){ return list; } else{ pHead->next = list; return pHead; } } ListNode* deleteDuplication(ListNode* pHead){ if (pHead == NULL) return NULL; repeated = pHead->val - 1; return noDuplicate(pHead); } }; // three pointer; class Solution { public: ListNode* deleteDuplication(ListNode* pHead) { if (pHead == NULL) return NULL; ListNode* head = new ListNode(0); head->next = pHead; pHead = pHead->next; ListNode* pre = head; ListNode* tail = head->next; ListNode* last = head->next; while(pHead){ if(pHead->val == last->val){ if(tail->val == pHead->val){ tail = pre; } } else{ tail->next = pHead; pre = tail; tail = pHead; } last = pHead; pHead = pHead->next; } tail->next = NULL; return head->next; } }; // recursion, provided by discussion board public class Solution { public ListNode deleteDuplication(ListNode pHead) { if (pHead == null || pHead.next == null) { // 只有0个或1个结点,则返回 return pHead; } if (pHead.val == pHead.next.val) { // 当前结点是重复结点 ListNode pNode = pHead.next; while (pNode != null && pNode.val == pHead.val) { // 跳过值与当前结点相同的全部结点,找到第一个与当前结点不同的结点 pNode = pNode.next; } return deleteDuplication(pNode); // 从第一个与当前结点不同的结点开始递归 } else { // 当前结点不是重复结点 pHead.next = deleteDuplication(pHead.next); // 保留当前结点,从下一个结点开始递归 return pHead; } } }
fba3eb00576456892bcf6a29899ececcd89e35b5
0d60761aaa0832c422f12409d8befebf9bcdf162
/Qt-learning/day.1/1.2.hello-Manual/main.cpp
b08439364570c6ad90b90eb459fa445727277dc6
[]
no_license
kingrobotzhou/test-code
d0364307ab0e2fcd6ae53f3668106b0a9474f3e6
477e1f9a7742654a65bc1ae4a14a972cc9996566
refs/heads/master
2021-09-13T15:39:41.687978
2018-05-01T17:08:46
2018-05-01T17:08:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
804
cpp
#include <QApplication> #include <QWidget> #include <QLabel> #include <QLayout> class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); private: QLabel *label; }; #define W 320 #define H 240 Widget::Widget(QWidget *parent) : QWidget(parent) { label = new QLabel(this); label->setText(QString("Hello Qt World")); label->setAlignment(Qt::AlignCenter); this->setMaximumSize(W,H); this->setMinimumSize(W,H); label->move(W/4,H/4); label->setMaximumSize(W/2,H/2); label->setMinimumSize(W/2,H/2); label->show(); } Widget::~Widget() { label->deleteLater(); } int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); } #include "main.moc"
8b8fe3f1e025e6498252455de6d0051d67f0e33e
b269392cc4727b226e15b3f08e9efb41a7f4b048
/CodeForces/CodeForces 804A.cpp
d4b5b3e51d57002887c3dcad9ce036c6c1b7dbcc
[]
no_license
ThoseBygones/ACM_Code
edbc31b95077e75d3b17277d843cc24b6223cc0c
2e8afd599b8065ae52b925653f6ea79c51a1818f
refs/heads/master
2022-11-12T08:23:55.232349
2022-10-30T14:17:23
2022-10-30T14:17:23
91,112,483
1
0
null
null
null
null
UTF-8
C++
false
false
203
cpp
#include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d",&n); int ans=0; if(n%2) ans=n/2; else ans=n/2-1; printf("%d\n",ans); return 0; }
689202803f9bdded447af621eb8a93fce4793c03
870becd7f96bade4f43eebb54cb6623c5120e38f
/src/croc/base/leakdetector.hpp
937c2a952b854bf5666350241cbb8e00bbb13a7b
[]
no_license
redchew-fork/Croc
fd09cfeab9d00d45b1440222a5351428bfd8856b
1fa0693d17d0c565920dfa672104d92b4016d4bf
refs/heads/master
2021-09-17T11:32:47.726015
2017-10-21T17:21:35
2017-10-21T17:21:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,165
hpp
#ifndef CROC_BASE_LEAKDETECTOR_HPP #define CROC_BASE_LEAKDETECTOR_HPP #ifndef CROC_LEAK_DETECTOR # define TYPEID_PARAM # define TYPEID_ARG # define LEAK_DETECT(x) #else // else, rest of module! #include <typeinfo> #include <map> #include "croc/base/sanity.hpp" #define TYPEID_PARAM ,const std::type_info& ti #define TYPEID_ARG ,ti #define LEAK_DETECT(x) x namespace croc { struct LeakMemBlock { size_t len; const std::type_info* ti; }; struct LeakDetector { typedef std::map<void*, LeakMemBlock> BlockMap; typedef BlockMap::iterator iter; BlockMap nurseryBlocks; BlockMap rcBlocks; BlockMap rawBlocks; void init(); void cleanup(); void newRaw(void* ptr, size_t size TYPEID_PARAM); void newNursery(void* ptr, size_t size TYPEID_PARAM); void newRC(void* ptr, size_t size TYPEID_PARAM); void freeRaw(void* ptr TYPEID_PARAM); void freeNursery(void* obj TYPEID_PARAM); void freeRC(void* obj TYPEID_PARAM); void checkRawExists(void* ptr TYPEID_PARAM); void relocateRaw(void* oldPtr, void* newPtr, size_t newSize TYPEID_PARAM); void clearNursery(); void makeRC(void* obj); void dumpBlocks(); }; } #endif #endif
b0ce230d4942bc0419d17bdaee3fe07399ac460c
12278a7a3675012e7834b3dfe305782fc4a826c3
/multisprite.cpp
01a890da7bcb0c3311122f92e27351bfae8c2e52
[]
no_license
epompeii/tipiCat
0c6a0b7b90d5e208331e12a79be79a5d41502c1c
0cc2a3d68bad1aa57ef0da3506932c080255f00a
refs/heads/master
2021-01-19T18:55:43.815527
2014-04-25T00:13:23
2014-04-25T00:13:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,142
cpp
#include "multisprite.h" #include "gamedata.h" #include "frameFactory.h" void MultiSprite::advanceFrame(Uint32 ticks) { timeSinceLastFrame += ticks; if (timeSinceLastFrame > frameInterval) { currentFrame = (currentFrame+1) % numberOfFrames; timeSinceLastFrame = 0; } } MultiSprite::MultiSprite( const std::string& name) : Drawable(name, snow.snowfall(Y()), snow.snowRate(name)), snow(), angle(snow.getAngle()), scale(snow.getScale()), frames( FrameFactory::getInstance().getFrames(name) ), worldWidth(Gamedata::getInstance().getXmlInt("world/width")), worldHeight(Gamedata::getInstance().getXmlInt("world/height")), currentFrame(0), numberOfFrames( Gamedata::getInstance().getXmlInt(name+"/frames") ), frameInterval( Gamedata::getInstance().getXmlInt(name+"/frameInterval") ), timeSinceLastFrame( 0 ), frameWidth(frames[0]->getWidth()), frameHeight(frames[0]->getHeight()) { } MultiSprite::MultiSprite(const MultiSprite& s) : Drawable(s), snow(), angle(snow.getAngle()), scale(snow.getScale()), frames(s.frames), worldWidth( s.worldWidth ), worldHeight( s.worldHeight ), currentFrame(s.currentFrame), numberOfFrames( s.numberOfFrames ), frameInterval( s.frameInterval ), timeSinceLastFrame( s.timeSinceLastFrame ), frameWidth( s.frameWidth ), frameHeight( s.frameHeight ) { } void MultiSprite::draw() const { Uint32 x = static_cast<Uint32>(X()); Uint32 y = static_cast<Uint32>(Y()); frames[currentFrame]->draw(x, y,0,scale,false); } void MultiSprite::update(Uint32 ticks) { advanceFrame(ticks); Vector2f incr = getVelocity() * static_cast<float>(ticks) * 0.001; setPosition(getPosition() + incr); if ( Y() < 0) { velocityY( abs( velocityY() ) ); } if ( Y() > worldHeight-frameHeight) { //velocityY( -abs( velocityY() ) ); if(scale > .5 ){ velocityX( 0 ); velocityY( 0 ); } else{ setPosition(Vector2f(X(),0)); } } if ( X() < 0) { velocityX( abs( velocityX() ) ); } if ( X() > worldWidth-frameWidth) { velocityX( -abs( velocityX() ) ); } } void MultiSprite::update(Uint32 ticks, float catAt) { advanceFrame(ticks); Vector2f incr = getVelocity() * static_cast<float>(ticks) * 0.001; setPosition(getPosition() + incr); if ( Y() < 0) { velocityY( abs( velocityY() ) ); } if ( Y() > worldHeight-frameHeight) { //velocityY( -abs( velocityY() ) ); if(scale > .5 ){ if(X() < catAt - 320){ //std::cout << "CatAt:" << catAt << std::endl; // std::cout << "X():" << X() << std::endl; //std::cout << "Move To:" << X()+4240 << std::endl; velocityX( 0 ); velocityY( 0 ); setPosition(Vector2f(X()+4240,Y())); } else{ velocityX( 0 ); velocityY( 0 ); } } else{ if(X() < catAt - 320){ // std::cout << "CatAt:" << catAt << std::endl; // std::cout << "X():" << X() << std::endl; // std::cout << "Move To:" << X()+4240 << std::endl; setPosition(Vector2f(X()+4240,0)); } else{ setPosition(Vector2f(X(),0)); } } } }
331946fdc82e7b911ffc2d6ec2caab688ce28809
27e89ae7f3ab461318d136d9f4af4bdea92df07f
/code/mips_pls/mainwindow.h
11aab4911add03ca83fbbe3f21e992453d906211
[]
no_license
Yeeef/mips_assembler
231dbcc9210a6e0a1d4be684e1647fff269d8b53
a2bed7997cf3c82cf55ba08a224b2996bc140abf
refs/heads/master
2020-03-16T15:49:48.154900
2019-11-29T18:35:50
2019-11-29T18:35:50
132,760,433
1
0
null
null
null
null
UTF-8
C++
false
false
1,526
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QtGui> #include <QtWidgets> #include "assemble.h" #include "disassemble.h" #include "editor.h" class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget * parent = 0); ~MainWindow(); QString bin_content; private: void open(); void saveFile(); void openFile(); void saveAsFile(); void assemble(); void disassemble(); //void createFile(); void closeEvent(QCloseEvent *event); /* status */ bool isSaved; bool isLocated; bool isAssembled; bool bin_coe; //true : bin /* file path */ QString path; QString outpath; QString disassemble_outpath; /* action */ QAction *disassembleAction; QAction *assembleAction; QAction *createAction; QAction *openAction; QAction *saveAction; QAction *saveAsAction; /* console */ /* QTextEdit * inputConsole; QTextEdit * AsmConsole; QTextEdit * infoConsole; */ CodeEditor * inputConsole; CodeEditor * AsmConsole; CodeEditor * infoConsole; /* manager */ assemble_manager assembler; disassemble_manager disassembler; void setActions(); void setConnects(); void layoutSettings(); }; class EventLabel : public QLabel { Q_OBJECT protected: //重载了三个函数 void mouseMoveEvent(QMouseEvent * event); void mousePressEvent(QMouseEvent * event); void mouseReleaseEvent(QMouseEvent * event); }; #endif // MAINWINDOW_H
76411940b5ee4deeb8db62211d0822677f602ec4
8c16c3e33d9191428efe86672c4aa8bbc2c628dd
/StrikeVR_17/Plugins/ArenaLiveAPI/Source/ArenaLiveAPI/Public/StrikerExampleClasses/SimpleBurstWeapon.cpp
39c9e892afa268f5911d0403a08378ef868d1888
[]
no_license
Sakyapanchen/StrikeVR_test
5015d3917fe3dac40a6d76b8dc78640cde5a7157
ab8d134b317cac68eb3a210cd316f575d1ad5db5
refs/heads/master
2020-03-06T15:48:32.085608
2018-03-27T14:06:20
2018-03-27T14:06:20
126,962,369
0
0
null
null
null
null
UTF-8
C++
false
false
1,316
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "SimpleBurstWeapon.h" #include "BlasterManager.h" #include "Blaster.h" #include "BlasterInput.h" USimpleBurstWeapon::USimpleBurstWeapon() { } USimpleBurstWeapon::~USimpleBurstWeapon() { } void USimpleBurstWeapon::BeginPlay() { Super::BeginPlay(); ResetBurstState(); } void USimpleBurstWeapon::TickComponent(float deltaTime, enum ELevelTick tickType, FActorComponentTickFunction * thisTickFunction) { Super::TickComponent(deltaTime, tickType, thisTickFunction); if (!IsConnected()) return; auto * input = GetBlasterInput(); if (input->GetButton(EBlasterButtons::Trigger)) { const float delay = mInBurst ? FireRate : FireDelay; if (IsReadyToFire(delay) && mShotCount > 0) { mInBurst = true; --mShotCount; if (!Fire()) { mShotCount = 0; mInBurst = false; } } } if (input->GetButtonUp(EBlasterButtons::Trigger)) { ResetBurstState(); } } void USimpleBurstWeapon::OnActivated() { Super::OnActivated(); } void USimpleBurstWeapon::OnDeactivated() { Super::OnDeactivated(); } void USimpleBurstWeapon::OnEventPointReached(FHapticEventPointArgs args) { Super::OnEventPointReached(args); } void USimpleBurstWeapon::ResetBurstState() { mInBurst = false; mShotCount = 3; }
9daa1190906e8b78c47b44649b13a041048eb13b
01e9c183ef3cad1e00d088204200654e02fdb2f0
/chapter01-STL-Practice/queue.cpp
c68e2bb845ce4767ee8bf486762ba91c21cd80b4
[]
no_license
dailiang/algorithm-in-cpp
1d878d8400558bdeebf00c63a371addc7d5d2b5c
9d018fa32deee9a323d6839f3e8db82cd105e5a2
refs/heads/master
2016-09-06T05:25:35.044301
2013-05-18T04:00:23
2013-05-18T04:00:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
338
cpp
#include<iostream> #include<queue> using namespace std; int main() { queue<int> q; q.push(1); q.push(2); q.push(3); q.push(9); cout << q.size() << endl; cout << q.empty() << endl; cout << q.front() << endl; cout << q.back() << endl; while(!q.empty()) { cout << q.front() << " "; q.pop(); } return 0; }
31e66f761582d40f4f1d5b7a832e19c65e776a5b
cbbcfcb52e48025cb6c83fbdbfa28119b90efbd2
/codeforces/460/C.cpp
632deb2d0145ca49d2430eb1d5a1ff2497fb0f91
[]
no_license
dmehrab06/Time_wasters
c1198b9f2f24e06bfb2199253c74a874696947a8
a158f87fb09d880dd19582dce55861512e951f8a
refs/heads/master
2022-04-02T10:57:05.105651
2019-12-05T20:33:25
2019-12-05T20:33:25
104,850,524
0
1
null
null
null
null
UTF-8
C++
false
false
2,934
cpp
/*-------property of the half blood prince-----*/ #include <bits/stdc++.h> #include <dirent.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/detail/standard_policies.hpp> #define MIN(X,Y) X<Y?X:Y #define MAX(X,Y) X>Y?X:Y #define ISNUM(a) ('0'<=(a) && (a)<='9') #define ISCAP(a) ('A'<=(a) && (a)<='Z') #define ISSML(a) ('a'<=(a) && (a)<='z') #define ISALP(a) (ISCAP(a) || ISSML(a)) #define MXX 10000000000 #define MNN -MXX #define ISVALID(X,Y,N,M) ((X)>=1 && (X)<=(N) && (Y)>=1 && (Y)<=(M)) #define LLI long long int #define VI vector<int> #define VLLI vector<long long int> #define MII map<int,int> #define SI set<int> #define PB push_back #define MSI map<string,int> #define PII pair<int,int> #define PLLI pair<LLI,LLI> #define PDD pair<double,double> #define FREP(i,I,N) for(int (i)=(int)(I);(i)<=(int)(N);(i)++) #define eps 0.0000000001 #define RFREP(i,N,I) for(int (i)=(int)(N);(i)>=(int)(I);(i)--) #define SORTV(VEC) sort(VEC.begin(),VEC.end()) #define SORTVCMP(VEC,cmp) sort(VEC.begin(),VEC.end(),cmp) #define REVV(VEC) reverse(VEC.begin(),VEC.end()) #define INRANGED(val,l,r) (((l)<(val) || fabs((val)-(l))<eps) && ((val)<(r) || fabs((val)-(r))<eps)) #define INRANGEI(val,l,r) ((val)>=(l) && (val)<=(r)) #define MSET(a,b) memset(a,b,sizeof(a)) using namespace std; using namespace __gnu_pbds; //int dx[]={1,0,-1,0};int dy[]={0,1,0,-1}; //4 Direction //int dx[]={1,1,0,-1,-1,-1,0,1};int dy[]={0,1,1,1,0,-1,-1,-1};//8 direction //int dx[]={2,1,-1,-2,-2,-1,1,2};int dy[]={1,2,2,1,-1,-2,-2,-1};//Knight Direction //int dx[]={2,1,-1,-2,-1,1};int dy[]={0,1,1,0,-1,-1}; //Hexagonal Direction //typedef tree < int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update > ordered_set; char seat[2001][2001]; LLI rowcheck(int r, int n, int m, int k){ LLI way = 0; int cur = 0; FREP(i,0,m-1){ if(seat[r][i]=='.'){ cur++; } else{ way+=(max(0,cur-(k-1))); cur = 0; } } way+=(max(0,cur-(k-1))); return way; } LLI colcheck(int c, int n, int m, int k){ LLI way = 0; int cur = 0; FREP(i,0,n-1){ if(seat[i][c]=='.'){ cur++; } else{ way+=(max(0,cur-(k-1))); cur = 0; } } way+=(max(0,cur-(k-1))); return way; } LLI solve(int n, int m,int k){ LLI tot = 0; FREP(i,0,n-1)tot+=rowcheck(i,n,m,k); FREP(i,0,m-1)tot+=colcheck(i,n,m,k); return tot; } void takeinp(int n, int m){ FREP(i,0,(n-1))scanf("%s",seat[i]); } int main(){ int n,m,k; scanf("%d %d %d",&n,&m,&k); takeinp(n,m); if(k==1){ int cnt = 0; FREP(i,0,(n-1)){ FREP(j,0,(m-1)){ if(seat[i][j]=='.'){ cnt++; } } } cout<<cnt<<"\n"; } else{ cout<<solve(n,m,k)<<"\n"; } }
e0112d1bda548bf09873cde146b0322c20c73c8d
33417f62ea9cc9b89df6ed9e805f18fe5aa67b18
/myoMotorAPI_CAN/source/MotorDriverCAN.cpp
20417cbedc0890a0ce44ab34de2107dcba61177b
[ "BSD-3-Clause" ]
permissive
IPA-Mags-TB/myorobotics
bece4b521f2e7842d607208cecb97fb2ab56c70c
6499cff6241d6b61ba75e59da4d646ccf095d7c9
refs/heads/master
2021-05-01T06:53:11.782020
2016-07-28T08:33:34
2016-07-28T08:33:34
63,763,105
0
0
null
2016-07-20T08:10:46
2016-07-20T08:10:46
null
UTF-8
C++
false
false
5,796
cpp
/* Copyright (c) 2016, Fraunhofer Institute for Manufacturing Engineering and Automation (IPA) 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 MyoMotorAPI_CAN 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 "MotorDriverCAN.h" #include "KvaserCanInterface.h" KvaserCanInterface* MotorDriverCAN::canInterface; std::map<int, MotorDriverCAN*> MotorDriverCAN::canMessageMap; CHANNEL_HANDLE MotorDriverCAN::busHandle; MotorDriverCAN::MotorDriverCAN(int motorRXID, int motorTXID) { if (canInterface == NULL) { cout << "init can" << endl; initCAN(); } setMessageIDs(motorRXID, motorTXID); } void MotorDriverCAN::setMessageIDs(int motorRXID, int motorTXID) { // create new entry in canMessageMap for motorTXID canMessageMap.insert(std::pair<int, MotorDriverCAN*>(motorTXID, this)); MotorDriverCAN::motorRXID = motorRXID; MotorDriverCAN::motorTXID = motorTXID; } MotorDriverCAN* MotorDriverCAN::getObjectFromMessageID(int ID) { return canMessageMap[ID]; } STATUS_CODE MotorDriverCAN::initCAN() { canInterface = new KvaserCanInterface(); string errorStr; STATUS_CODE status; // open new CAN channel CHANNEL_HANDLE busHandle = canInterface->openCanChannel(0); if (busHandle > -1) { cout << "CAN Bus available" << endl; // if channel available, configure CAN interface to use 1M Baudrate and non-silent mode status = canInterface->configureCanChannel(busHandle, CAN_BAUDRATE__1M, 0); // print errors if applicable and start CAN channel canInterface->getErrorText(status, errorStr); canInterface->connectCanChannel(busHandle); cout << "CAN configured, 1Mbit/s, status is: " << errorStr << endl; // Set method to handle incoming data status = canInterface->setUprxCallback(busHandle, MotorDriverCAN::handleRXData); canInterface->getErrorText(status, errorStr); cout << "Rx call-back set-up: " << errorStr << endl; } else cout << "not available CAN" << endl; } void MotorDriverCAN::handleRXData(canNotifyData * rxNotifyData) { int handle; long id; char data[8]; unsigned int dlc, flags; unsigned long timestamp; STATUS_CODE stat; // Read incoming CAN Data and proceed if no error while (canERR_NOMSG != canRead(MotorDriverCAN::busHandle, &id, data, &dlc, &flags, &timestamp)) { // check if recieved CAN mesage ID corresponds to a motorTXID - corresponds to motorDataMain if(canMessageMap[id] !=NULL) { // Buffer data into motoDataMain buffer for(int i=0;i<8;i++) { canMessageMap[id]->dats2.data[i]= data[i]; } // write buffer to STRUCT_SENSOR_VALUES canMessageMap[id]->sV.position = canMessageMap[id]->dats2.s.encoderPosition; canMessageMap[id]->sV.velocity = canMessageMap[id]->dats2.s.omega; } // check if recieved CAN mesage ID corresponds to a motorTXID + 1 - corresponds to motorDataAux else if(canMessageMap[id-1] !=NULL) { // Buffer data into motoDataAux buffer for(int i=0;i<8;i++) { canMessageMap[id-1]->dats.data[i]= data[i]; } // write buffer to STRUCT_SENSOR_VALUES canMessageMap[id-1]->sV.current = canMessageMap[id-1]->dats.s.current; canMessageMap[id-1]->sV.displacement = canMessageMap[id-1]->dats.s.displacement; } } } STATUS_CODE MotorDriverCAN::sendDutyCycle(int dutyCycle) { CAN_MESSAGE canSentMessage; // set parameters for CAN message - see generic CAN protocol canSentMessage.dlc=8; canSentMessage.messageID=motorRXID; canSentMessage.extended=0; // setup motorCommand struct for sending over CAN MotorDriverCAN::motorCommand.s.dutyCycle = dutyCycle; MotorDriverCAN::motorCommand.s.free = 0; // write motorCommand struct to canMessage data structure for (int j=0;j<8;j++) { canSentMessage.data8[j]=MotorDriverCAN::motorCommand.data[j]; } // send canMessage MotorDriverCAN::canInterface->sendCanMessage(MotorDriverCAN::busHandle,canSentMessage); } STRUCT_SENSOR_VALUES MotorDriverCAN::getSensorValues() { return sV; } MotorDriverCAN::~MotorDriverCAN() { MotorDriverCAN::sendDutyCycle(0); }
c5abdd2e42eeee40bc3d99f14f2e2ed80f3da69e
bc347751fa792175321b872a52cce4c95d2b8f1d
/InventorySystem/Source/InventorySystem/ItemClasses/Item_Base.cpp
9e44cd662ef9b72bbb5a360f86020276c4911e89
[]
no_license
szm429006/-UE4-InventorySystem
d9d88676d852e9e0705590c851111383d6dc1a0d
a23360763f0f17c7058875bf2af939ac1cfa68cd
refs/heads/master
2020-03-30T06:22:45.110978
2018-07-18T04:26:40
2018-07-18T04:26:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
713
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "Item_Base.h" #include "Components/Component_Inventory.h" //#include <Engine.h> // Sets default values AItem_Base::AItem_Base() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = false; } void AItem_Base::InitializeItem(UComponent_Inventory* _pInventory, int _Index) { m_pInventory = _pInventory; m_Index = _Index; } void AItem_Base::EventOnUsed() { m_pInventory->RemoveItemAtIndex(m_Index, 1); Destroy(); } // Called when the game starts or when spawned void AItem_Base::BeginPlay() { Super::BeginPlay(); }
ec2250affcbad4a179cc3165e4a946518c9551d4
b591fbbd37b9b5e81d8f308f61d607fe7b145ed7
/include/RE/G/GFxLog.h
1327d8117fd82345048ef2310d86a3b85fb372ec
[ "MIT" ]
permissive
aquilae/CommonLibSSE
f6a1d321b16f2eb1e296f1154d697bd4bed549b6
b8e6a72875b22c91dd125202dfc6a54f91cda597
refs/heads/master
2023-02-02T16:45:00.368879
2020-12-15T03:58:22
2020-12-15T03:58:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
529
h
#pragma once #include "RE/G/GFxLogBase.h" #include "RE/G/GFxState.h" namespace RE { class GFxLog : public GFxState, // 00 public GFxLogBase<GFxLog> // 18 { public: inline static constexpr auto RTTI = RTTI_GFxLog; GFxLog(); virtual ~GFxLog() = default; // 00 // add virtual void LogMessageVarg(LogMessageType a_messageType, const char* a_fmt, std::va_list a_argList); // 01 void LogMessageByType(LogMessageType a_messageType, const char* a_fmt, ...); }; static_assert(sizeof(GFxLog) == 0x20); }
0d9a3d661ec08758a0c8eb5592fb36b2ce5fe2f5
3c89aad5a33b6377fc8a1ac329b15396a0ea9d54
/rtda/heap/RunTimeConstantPool.cpp
a3790254930c67f73dab7bb783daa0522a33948d
[]
no_license
luili16/TinyJvm
93733cfd75f758c6c0518a668c644ddfd754e1b7
2ff9a1fcae41aef1e8555856a979beebeec00f19
refs/heads/main
2023-02-16T05:06:09.800018
2021-01-14T02:55:29
2021-01-14T02:55:29
315,226,777
1
0
null
null
null
null
UTF-8
C++
false
false
3,960
cpp
// // Created by 刘立新 on 2020/12/28. // #include "RunTimeConstantPool.h" #include "../classfile/ClassFile.h" #include "../classfile/ConstantClassInfo.h" #include "../common/ErrorCode.h" #include <locale> #include <codecvt> #include <iostream> std::string toUtf8(std::u16string& mUtf8) { std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert; std::string utf8 = convert.to_bytes(mUtf8); return utf8; } rtda::heap::Class *rtda::heap::RunTimeConstantPool::getClass(std::u16string &className) { auto classes = this->sharedPool->find(className); if (classes == this->sharedPool->end()) { std::string u8ClassName = toUtf8(className); auto classData = this->classPath->readClass(u8ClassName); if (classData->empty()) { std::cerr << "className: " << u8ClassName << " not found. "; exit(common::ErrorCode::ClassNotFoundException); } auto reader = class_file::ClassReader(*classData); const class_file::ClassFile* classFile = class_file::ClassFile::read(reader); auto aClass = new Class(); aClass->accessFlags = classFile->getAccessFlags(); aClass->constantPool = classFile->getConstantPool(); aClass->name = classFile->getConstantPool()->getConstantUtf8Info(dynamic_cast<const class_file::ConstantClassInfo*>(classFile->getConstantPool()->getConstantInfo(classFile->getThisClass()))->nameIndex)->decodeMUTF8(); if (classFile->getSuperClass() != 0) { auto nameIndex = dynamic_cast<const class_file::ConstantClassInfo*>(classFile->getConstantPool()->getConstantInfo(classFile->getSuperClass()))->nameIndex; aClass->superClassName = classFile->getConstantPool()->getConstantUtf8Info(nameIndex)->decodeMUTF8(); // ugly code! how to fix? aClass->superClass = this->getClass(*(aClass->superClassName)); } else { // this class is java.lang.Object aClass->superClassName = std::make_shared<std::u16string>(); } aClass->fieldsCount = classFile->getFieldsCount(); aClass->fields = new Field*[aClass->fieldsCount]; const class_file::Fields* fields = classFile->getFields(); for (int i = 0; i < aClass->fieldsCount; i++) { auto fieldInfo = fields->getFieldInfo(i); aClass->fields[i] = Field::newField(classFile->getConstantPool(), fieldInfo); aClass->fields[i]->accessFlags = fieldInfo->getAccessFlags(); aClass->fields[i]->thisClass = aClass; aClass->fields[i]->resolveField(); } aClass->methodsLen = classFile->getMethodsCount(); aClass->methods = new Method*[aClass->methodsLen]; const class_file::Methods* methods = classFile->getMethods(); for (int i = 0; i < aClass->methodsLen; i++) { auto methodInfo = methods->getMethodInfo(i); aClass->methods[i] = new Method(classFile->getConstantPool(),methodInfo); aClass->methods[i]->thisClass = aClass; } this->sharedPool->insert({className, aClass}); // throw class not found exception? return aClass; } return classes->second; } rtda::heap::RunTimeConstantPool::RunTimeConstantPool(std::shared_ptr<class_path::ClassPath>& classPath) { this->classPath = classPath; } rtda::heap::RunTimeConstantPool::~RunTimeConstantPool() { delete this->sharedPool; this->sharedPool = nullptr; } void rtda::heap::RunTimeConstantPool::globalInit(std::shared_ptr<class_path::ClassPath>& classPath) { instance = new RunTimeConstantPool(classPath); } void rtda::heap::RunTimeConstantPool::globalDestroy() { delete instance; instance = nullptr; } rtda::heap::RunTimeConstantPool *rtda::heap::RunTimeConstantPool::getInstance() { return RunTimeConstantPool::instance; } rtda::heap::RunTimeConstantPool* rtda::heap::RunTimeConstantPool::instance = nullptr;
948bff9312cc69822d00fdf6839210865a2741cd
0a842a2e1d5ce41f1955954f010f68ca991f811a
/GUI/moc_dialog.cpp
c4038a2efc9de183057fed9d6a985c01c0f17d13
[]
no_license
gohwaikien/ircchatserver
c074171be77c68dd7d69ea6c32c2c308cdd5117c
c5a1bb248c0a9eba5acfe7beab70e59899299780
refs/heads/master
2020-03-22T18:59:04.017121
2018-07-11T15:37:03
2018-07-11T15:37:03
140,496,104
0
0
null
null
null
null
UTF-8
C++
false
false
5,382
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'dialog.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "dialog.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'dialog.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.9.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_Dialog_t { QByteArrayData data[15]; char stringdata0[185]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_Dialog_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_Dialog_t qt_meta_stringdata_Dialog = { { QT_MOC_LITERAL(0, 0, 6), // "Dialog" QT_MOC_LITERAL(1, 7, 10), // "sendAction" QT_MOC_LITERAL(2, 18, 0), // "" QT_MOC_LITERAL(3, 19, 13), // "newUserAction" QT_MOC_LITERAL(4, 33, 11), // "loginAction" QT_MOC_LITERAL(5, 45, 11), // "timerAction" QT_MOC_LITERAL(6, 57, 11), // "refreshRoom" QT_MOC_LITERAL(7, 69, 18), // "refreshUsersInRoom" QT_MOC_LITERAL(8, 88, 15), // "refreshMessages" QT_MOC_LITERAL(9, 104, 8), // "add_user" QT_MOC_LITERAL(10, 113, 11), // "create_room" QT_MOC_LITERAL(11, 125, 16), // "createRoomAction" QT_MOC_LITERAL(12, 142, 15), // "enterRoomAction" QT_MOC_LITERAL(13, 158, 10), // "enter_room" QT_MOC_LITERAL(14, 169, 15) // "leaveRoomAction" }, "Dialog\0sendAction\0\0newUserAction\0" "loginAction\0timerAction\0refreshRoom\0" "refreshUsersInRoom\0refreshMessages\0" "add_user\0create_room\0createRoomAction\0" "enterRoomAction\0enter_room\0leaveRoomAction" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_Dialog[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 13, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 79, 2, 0x08 /* Private */, 3, 0, 80, 2, 0x08 /* Private */, 4, 0, 81, 2, 0x08 /* Private */, 5, 0, 82, 2, 0x08 /* Private */, 6, 0, 83, 2, 0x08 /* Private */, 7, 0, 84, 2, 0x08 /* Private */, 8, 0, 85, 2, 0x08 /* Private */, 9, 0, 86, 2, 0x08 /* Private */, 10, 0, 87, 2, 0x08 /* Private */, 11, 0, 88, 2, 0x08 /* Private */, 12, 0, 89, 2, 0x08 /* Private */, 13, 0, 90, 2, 0x08 /* Private */, 14, 0, 91, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void Dialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Dialog *_t = static_cast<Dialog *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->sendAction(); break; case 1: _t->newUserAction(); break; case 2: _t->loginAction(); break; case 3: _t->timerAction(); break; case 4: _t->refreshRoom(); break; case 5: _t->refreshUsersInRoom(); break; case 6: _t->refreshMessages(); break; case 7: _t->add_user(); break; case 8: _t->create_room(); break; case 9: _t->createRoomAction(); break; case 10: _t->enterRoomAction(); break; case 11: _t->enter_room(); break; case 12: _t->leaveRoomAction(); break; default: ; } } Q_UNUSED(_a); } const QMetaObject Dialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_Dialog.data, qt_meta_data_Dialog, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *Dialog::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *Dialog::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_Dialog.stringdata0)) return static_cast<void*>(this); return QDialog::qt_metacast(_clname); } int Dialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 13) qt_static_metacall(this, _c, _id, _a); _id -= 13; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 13) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 13; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
a4848080e91ad59543dc89304b725e94cc6000d5
7366c0a86de8b77cdae6f02f49c59f12a929d972
/OpenGL/TestOpenGL/TestOpenGL/main3.cpp
dd82095f7a6539f56ea12f84e0529132ddcc3c4e
[ "MIT" ]
permissive
ndlwill/iOS
9094a1c035ad278cfc0a36da059308e8478f987a
16db4fd12e41e286605a6837697b8808a74b2672
refs/heads/master
2023-08-21T04:29:32.157676
2023-08-07T09:30:10
2023-08-07T09:30:10
128,955,536
5
7
NOASSERTION
2023-07-16T19:30:57
2018-04-10T15:28:40
C++
UTF-8
C++
false
false
5,287
cpp
// // main3.cpp // TestOpenGL // // Created by ndl on 2019/12/28. // Copyright © 2019 ndl. All rights reserved. // #include <GLUT/GlUT.h> #include "math3d.h" void draw() { ////-----------------画正方形------------------------- // //1.设置清屏颜色 红、绿、蓝、透明度 // /* // 在windows 颜色成分取值范围:0-255之间 // 在iOS、OS 颜色成分取值范围:0-1之间浮点值 // */ // glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // // // /* // 清除缓存区对数值进行预置 // 参数:指定将要清楚的缓存区的遮罩的按位或运算。 // GL_COLOR_BUFFER_BIT: 指示当前激活的用来进行颜色写入缓存区 // GL_DEPTH_BUFFER_BIT:指示深度缓存区 // GL_STENCIL_BUFFER_BIT:指示模板缓存区 // // 每个缓存区的清楚值根据这个缓存区的清楚值设置不同。 // // 错误: // 如果设定不是以上三个参考值,返回GL_INVALID_VALUE // */ // //glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); // glClear(GL_COLOR_BUFFER_BIT); // // // // //设置颜色 // glColor3f(1.0f, 0.0f, 0.0f); // // // //设置绘图是的坐标系统 // //左、右、上、下、近、远 // glOrtho(0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f); // // // //开始渲染 // glBegin(GL_POLYGON); // // //设置多边形的4个顶点 // glVertex3f(0.25f, 0.25f, 0.0f); // glVertex3f(0.75f, 0.25f, 0.0f); // glVertex3f(0.75f, 0.75f, 0.0f); // glVertex3f(0.25f, 0.75f, 0.0f); // // // //结束渲染 // glEnd(); // // //强制刷新缓存区,保证绘制命令得以执行 // glFlush(); //----------------------画圆--------------------------------- glClearColor(0.0f, 1.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); //设置颜色 glColor3f(1.0f, 0.0f, 0.0f); //开始渲染 glBegin(GL_POLYGON); const int n = 55;//当n为3时为三角形;n为4时是四边形,n为5时为五边形。。。。。 const GLfloat R = 0.5f;//圆的半径 const GLfloat pi = 3.1415926f; for (int i = 0; i < n; i++) { glVertex2f(R*cos(2 * pi / n*i), R*sin(2 * pi / n*i)); } //结束渲染 glEnd(); //强制刷新缓存区,保证绘制命令得以执行 glFlush(); //// ------------------------五角形----------------------------- // ///* // 设五角星的五个顶点分布位置关系如下: // A // E B // // D C // 首先,根据余弦定理列方程,计算五角星的中心到顶点的距离a // (假设五角星对应正五边形的边长为.0) // a = 1 / (2-2*cos(72*Pi/180)); // 然后,根据正弦和余弦的定义,计算B的x坐标bx和y坐标by,以及C的y坐标 // (假设五角星的中心在坐标原点) // bx = a * cos(18 * Pi/180); // by = a * sin(18 * Pi/180); // cy = -a * cos(18 * Pi/180); // 五个点的坐标就可以通过以上四个量和一些常数简单的表示出来 // */ // const GLfloat Pi = 3.1415926536f; // GLfloat a = 1 / (2-2*cos(72*Pi/180)); // GLfloat bx = a * cos(18 * Pi/180); // GLfloat by = a * sin(18 * Pi/180); // GLfloat cy = -a * cos(18 * Pi/180); // GLfloat // PointA[2] = { 0, a }, // PointB[2] = { bx, by }, // PointC[2] = { 0.5, cy }, // PointD[2] = { -0.5, cy }, // PointE[2] = { -bx, by }; // // glClear(GL_COLOR_BUFFER_BIT); // // 按照A->C->E->B->D->A的顺序,可以一笔将五角星画出 // glBegin(GL_LINE_LOOP); // glVertex2fv(PointA); // glVertex2fv(PointC); // glVertex2fv(PointE); // glVertex2fv(PointB); // glVertex2fv(PointD); // glEnd(); // glFlush(); //----------- 画出正弦函数的图形--------------- /* 由于OpenGL默认坐标值只能从-1到1,(可以修改,但方法留到以后讲) 所以我们设置一个因子factor,把所有的坐标值等比例缩小, 这样就可以画出更多个正弦周期 试修改factor的值,观察变化情况 */ // const GLfloat factor = 0.1f; // GLfloat x; // glClear(GL_COLOR_BUFFER_BIT); // glBegin(GL_LINES); // glVertex2f(-1.0f, 0.0f); // glVertex2f(1.0f, 0.0f); // 以上两个点可以画x轴 // glVertex2f(0.0f, -1.0f); // glVertex2f(0.0f, 1.0f); // 以上两个点可以画y轴 // glEnd(); // glBegin(GL_LINE_STRIP); // for(x=-1.0f/factor; x<1.0f/factor; x+=0.01f) // { // glVertex2f(x*factor, sin(x)*factor); // } // glEnd(); // glFlush(); } // MARK: 绘制图形 int main(int argc,const char *argv[]) { //1.初始化一个GLUT库 glutInit(&argc, (char **)argv); //2.创建一个窗口并制定窗口名 glutCreateWindow("CC_Window"); //3.注册一个绘图函数,操作系统在必要时刻就会对窗体进行重绘制操作 //它设置了一个显示回调(diplay callback),即GLUT在每次更新窗口内容的时候回自动调用该例程 glutDisplayFunc(draw); //这是一个无限执行的循环,它会负责一直处理窗口和操作系统的用户输入等操作。(注意:不会执行在glutMainLoop()之后的所有命令。) glutMainLoop(); return 0; }
abcf7a5fef4de98bdd01798c858a3785fe565564
1358852988ac63f5e505cd0f9e247b8a6bff6c8b
/Request.h
2b5a6ec45cc6495e6690a90ee0af9e2e974cbaf7
[]
no_license
michaelpidde/nginept
2688a799fbd6aa0bf83a6e8c711c35a3ca4bc4ef
d2f38d02226fcb0f8539d8cb0626516342821029
refs/heads/master
2021-01-15T15:24:09.353426
2016-12-12T06:42:49
2016-12-12T06:42:49
63,513,702
0
0
null
null
null
null
UTF-8
C++
false
false
1,373
h
#ifndef _REQUEST_H_ #define _REQUEST_H_ #include <vector> #include "Config.h" #include "knownhost.h" namespace Network { class Request { public: Request(Config &config); ~Request(); struct request { std::string method; std::string resource; std::string httpVersion; }; struct response { std::string headers; std::vector<char> body; bool binary; }; struct requestContext { Request::request request; std::string host = ""; std::string accept = ""; std::string encoding = ""; std::string agent = ""; std::string referer = ""; }; std::vector<std::string> binTypes { "jpg","jpeg", "gif", "png", "bmp", "ico" }; response handle(std::string buffer); private: Config *config; knownHost getKnownHost(std::string host); requestContext parseHeaders(std::string buffer); request parseRequest(std::string buffer); std::string htmlTemplate(std::string title, std::string body); void logError(std::string line); void log(std::string line); std::string rcToString(requestContext &rc); void status200(response &response, bool binary, std::string extension); void status404(response &response, std::string &requestedFile); void status405(response &response, std::string &method); void status500(response &response); }; } #endif /*_REQUEST_H_*/
f717b80f6a62ce3b19fcc4d7471a08d8a024c965
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/ds/security/base/lsa/security/driver/lsamem.cxx
8f823253e9578fdfc029c6fec6535f3068dd4778
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,076
cxx
//+----------------------------------------------------------------------- // // Microsoft Windows // // Copyright (c) Microsoft Corporation 1992 - 2000 // // File: lsamem.cxx // // Contents: Shared memory between ksec and lsa // // // History: 7-19-00 Richardw Created // //------------------------------------------------------------------------ #include "secpch2.hxx" extern "C" { #include <zwapi.h> #include <spmlpc.h> #include <lpcapi.h> #include <spmlpcp.h> #include "ksecdd.h" } // // At this time, it is unlikely that we'd have more than one // of these, but in the event that it becomes a high-demand // list, having it in a structure should make it easier to // make per-processor. // typedef struct _KSEC_LSA_MEMORY_CONTROL { LIST_ENTRY List ; ULONG Count ; ULONG Present ; ULONG HighWater ; // KEVENT Block ; FAST_MUTEX Lock ; } KSEC_LSA_MEMORY_CONTROL, * PKSEC_LSA_MEMORY_CONTROL ; #define KSEC_MAX_LSA_MEMORY_BLOCKS 1024 PKSEC_LSA_MEMORY_CONTROL LsaMemoryControl ; NTSTATUS KsecInitLsaMemory( VOID ) { NTSTATUS Status ; LsaMemoryControl = (PKSEC_LSA_MEMORY_CONTROL) ExAllocatePool( NonPagedPool, sizeof( KSEC_LSA_MEMORY_CONTROL ) ); if ( !LsaMemoryControl ) { return STATUS_NO_MEMORY ; } InitializeListHead( &LsaMemoryControl->List ); Status = ExInitializeFastMutex( &LsaMemoryControl->Lock ); if ( !NT_SUCCESS( Status ) ) { ExFreePool( LsaMemoryControl ); return Status ; } // KeInitializeEvent( &LsaMemoryControl->Block ); LsaMemoryControl->Count = 0 ; LsaMemoryControl->HighWater = 0 ; LsaMemoryControl->Present = 0 ; return STATUS_SUCCESS ; } VOID KsecpFreeLsaMemory( PKSEC_LSA_MEMORY LsaMemory, BOOLEAN Force ) { SIZE_T Size = 0 ; KeEnterCriticalRegion(); ExAcquireFastMutex( &LsaMemoryControl->Lock ); if ( LsaMemoryControl->Present * 2 > LsaMemoryControl->Count ) { // // If the present count is half of the total count, dump // this entry. // Force = TRUE ; } if ( !Force ) { LsaMemoryControl->Present ++ ; InsertHeadList( &LsaMemoryControl->List, &LsaMemory->List ); } else { LsaMemoryControl->Count -- ; } ExReleaseFastMutex( &LsaMemoryControl->Lock ); KeLeaveCriticalRegion(); if ( Force ) { ZwFreeVirtualMemory( KsecLsaProcessHandle, &LsaMemory->Region, &Size, MEM_RELEASE ); ExFreePool( LsaMemory ); } } PKSEC_LSA_MEMORY KsecAllocLsaMemory( SIZE_T Size ) { PKSEC_LSA_MEMORY LsaMemory = NULL ; PKSEC_LSA_MEMORY_HEADER Header ; PLIST_ENTRY Scan ; SIZE_T NewSize ; SIZE_T Reservation ; NTSTATUS Status ; KAPC_STATE ApcState ; if ( Size < 8192 ) { Size = 8192 ; } if ( Size > 64 * 1024 ) { return NULL ; } ASSERT( LsaMemoryControl ); KeEnterCriticalRegion(); ExAcquireFastMutex( &LsaMemoryControl->Lock ); Scan = LsaMemoryControl->List.Flink ; while ( Scan != &LsaMemoryControl->List ) { LsaMemory = CONTAINING_RECORD( Scan, KSEC_LSA_MEMORY, List ); if ( LsaMemory->Commit >= Size ) { RemoveEntryList( &LsaMemory->List ); LsaMemoryControl->Present-- ; break; } LsaMemory = NULL ; Scan = Scan->Flink; } if ( LsaMemory == NULL ) { if ( !IsListEmpty( &LsaMemoryControl->List ) ) { Scan = RemoveHeadList( &LsaMemoryControl->List ); LsaMemoryControl->Present-- ; LsaMemory = CONTAINING_RECORD( Scan, KSEC_LSA_MEMORY, List ); } } if ( LsaMemory == NULL ) { // // Still nothing there. See if it is OK for us to allocate // another one. if ( LsaMemoryControl->Count < KSEC_MAX_LSA_MEMORY_BLOCKS ) { LsaMemory = (PKSEC_LSA_MEMORY) ExAllocatePool( PagedPool, sizeof( KSEC_LSA_MEMORY ) ); if ( LsaMemory ) { LsaMemory->Commit = 0 ; LsaMemory->Size = 0 ; LsaMemory->Region = 0 ; LsaMemoryControl->Count ++ ; if ( LsaMemoryControl->Count > LsaMemoryControl->HighWater ) { LsaMemoryControl->HighWater = LsaMemoryControl->Count ; } } } else { // // In the future, we can use that block event in the // control structure to wait for to be returned to the // list. However, the likelyhood of having all the // requests outstanding is pretty slim. We'll probably // get normal memory failures long before that. // NOTHING ; } } ExReleaseFastMutex( &LsaMemoryControl->Lock ); KeLeaveCriticalRegion(); if ( LsaMemory ) { if ( LsaMemory->Commit < Size ) { NewSize = Size ; if ( LsaMemory->Size < Size ) { // // Need to make our reservation: // Reservation = 64 * 1024 ; // 64K Status = ZwAllocateVirtualMemory( KsecLsaProcessHandle, &LsaMemory->Region, 0, &Reservation, MEM_RESERVE, PAGE_NOACCESS ); if ( NT_SUCCESS( Status ) ) { LsaMemory->Size = Reservation ; } } Status = ZwAllocateVirtualMemory( KsecLsaProcessHandle, &LsaMemory->Region, 0, &NewSize, MEM_COMMIT, PAGE_READWRITE ); if ( NT_SUCCESS( Status ) ) { LsaMemory->Commit = NewSize ; } else { if ( LsaMemory->Region ) { KsecpFreeLsaMemory( LsaMemory, TRUE ); } else { ExFreePool( LsaMemory ); } LsaMemory = NULL ; } } if ( LsaMemory ) { // // Initialize the memory block for the LSA: // ASSERT( LsaMemory->Region != NULL ); Header = (PKSEC_LSA_MEMORY_HEADER) LsaMemory->Region ; KeStackAttachProcess( (PRKPROCESS) KsecLsaProcess, &ApcState ); __try { // // Initialize the structure in the LSA space. This // protects the driver from bugs in the LSA process // stomping on the fields. // Header->Commit = (ULONG) LsaMemory->Commit ; Header->Consumed = sizeof( KSEC_LSA_MEMORY_HEADER ); Header->Preserve = (USHORT) Header->Consumed ; Header->Size = (ULONG) LsaMemory->Size ; Header->MapCount = 0 ; Status = STATUS_SUCCESS ; } __except( EXCEPTION_EXECUTE_HANDLER ) { // // An exception here indicates that the memory in user // mode is bad. // Status = GetExceptionCode(); } KeUnstackDetachProcess( &ApcState ); if ( !NT_SUCCESS( Status ) ) { KsecpFreeLsaMemory( LsaMemory, TRUE ); LsaMemory = NULL ; } } } return LsaMemory ; } VOID KsecFreeLsaMemory( PKSEC_LSA_MEMORY LsaMemory ) { if ( !LsaMemory ) { DebugLog((DEB_TRACE, " KsecFreeLsaMemory called with NULL\n" )); return; } KsecpFreeLsaMemory( LsaMemory, FALSE ); } NTSTATUS KsecCopyPoolToLsa( PKSEC_LSA_MEMORY LsaMemory, SIZE_T LsaOffset, PVOID Pool, SIZE_T PoolSize ) { NTSTATUS Status = STATUS_SUCCESS ; KAPC_STATE ApcState ; PKSEC_LSA_MEMORY_HEADER Header ; ASSERT( LsaOffset < LsaMemory->Commit ); ASSERT( LsaOffset < LsaMemory->Size ); ASSERT( PoolSize < LsaMemory->Commit ); KeStackAttachProcess( (PRKPROCESS) KsecLsaProcess, &ApcState ); __try { RtlCopyMemory( (PUCHAR) LsaMemory->Region + LsaOffset, Pool, PoolSize ); Header = (PKSEC_LSA_MEMORY_HEADER) LsaMemory->Region ; if ( Header->MapCount < KSEC_LSA_MAX_MAPS ) { Header->PoolMap[ Header->MapCount ].Offset = (USHORT) LsaOffset; Header->PoolMap[ Header->MapCount ].Size = (USHORT) PoolSize ; Header->PoolMap[ Header->MapCount ].Pool = Pool ; Header->MapCount++ ; } } __except( EXCEPTION_EXECUTE_HANDLER ) { // // An exception here indicates that the memory in user // mode is bad. // Status = GetExceptionCode(); } KeUnstackDetachProcess( &ApcState ); return Status ; } NTSTATUS KsecCopyLsaToPool( PVOID Pool, PKSEC_LSA_MEMORY LsaMemory, PVOID LsaBuffer, SIZE_T Size ) { NTSTATUS Status = STATUS_SUCCESS ; KAPC_STATE ApcState ; ULONG LsaOffset ; PUCHAR Scratch ; LsaOffset = (ULONG) ((PUCHAR) LsaBuffer - (PUCHAR) LsaMemory->Region) ; ASSERT( LsaOffset < LsaMemory->Commit ); ASSERT( LsaOffset < LsaMemory->Size ); ASSERT( Size < LsaMemory->Commit ); KeStackAttachProcess( (PRKPROCESS) KsecLsaProcess, &ApcState ); __try { RtlCopyMemory( Pool, LsaBuffer, Size ); } __except( EXCEPTION_EXECUTE_HANDLER ) { // // An exception here indicates that the memory in user // mode is bad. // Status = GetExceptionCode(); } KeUnstackDetachProcess( &ApcState ); return Status ; }
3f365aa893a01401c451ff3a77643474281d3984
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/StepVisual_PreDefinedCurveFont.hxx
22f7f8259d642f60f91b0eaf67e649e9fe1d1a2c
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
1,093
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _StepVisual_PreDefinedCurveFont_HeaderFile #define _StepVisual_PreDefinedCurveFont_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Handle_StepVisual_PreDefinedCurveFont_HeaderFile #include <Handle_StepVisual_PreDefinedCurveFont.hxx> #endif #ifndef _StepVisual_PreDefinedItem_HeaderFile #include <StepVisual_PreDefinedItem.hxx> #endif class StepVisual_PreDefinedCurveFont : public StepVisual_PreDefinedItem { public: //! Returns a PreDefinedCurveFont <br> Standard_EXPORT StepVisual_PreDefinedCurveFont(); DEFINE_STANDARD_RTTI(StepVisual_PreDefinedCurveFont) protected: private: }; // other Inline functions and methods (like "C++: function call" methods) #endif
d8e6e4b7e0cdc4a65978153d1c8c73268500f90f
c955730b68bd4ba2d9255183cfef092bd1ef2524
/CPP/light.cpp
3467d91d98682d8e666fe7eb641a21222ca25196
[]
no_license
Manvi07/Competitive-programming
b6e95c2e8bc9673d9e23e784c460d50ed3754ab1
7b59d89988667b115500482691b3ae89c397d753
refs/heads/master
2020-05-19T06:12:07.019076
2020-05-08T09:22:16
2020-05-08T09:22:16
184,867,764
1
0
null
null
null
null
UTF-8
C++
false
false
371
cpp
#include<bits/stdc++.h> using namespace std; int main() { long long int n,m; cin>>n>>m; long long int num; list<long long int>l; int dif=0; for(int i=0;i<n;i++) { cin>>num; l.push_back(num); if(i>0 and i%2==0) {dif=max(dif,l[i]-l[i-1]);int k=i-1;} } list<long long int>::iterator it=l.begin(); long long int ans=*it; return 0; }
45d1a1305d1a064eade15d9aa76c9dde70353d67
ecbee786f8ec083a81cb9414215cbb015a4b7871
/GCU_Programming1_Coursework/cButtonController.h
8561bb41ead6df99943de3ef7810f214e863efc8
[]
no_license
JanRiebe/SDL_Racing_Game
ecd5a218342e468e1e59abe2df1ca82cb73a99c5
4385e7547a72c10e0b15d0a7836f34c72dc2c851
refs/heads/master
2020-04-04T19:22:12.266799
2018-12-10T10:46:42
2018-12-10T10:46:42
156,203,185
0
0
null
null
null
null
UTF-8
C++
false
false
473
h
#pragma once #include "IInputChannelListener.h" #include <stack> using namespace std; class cSpriteButton; class cButtonController : public IInputChannelListener { private: cSpriteButton* test; stack<cSpriteButton*> buttonsAbove; cSpriteButton* cursor; // the currently selected button stack<cSpriteButton*> buttonsBelow; public: cButtonController(cSpriteButton* b); ~cButtonController(); void addButton(cSpriteButton* b); void OnEvent(AbstractEvent e); };
df0b286dabf2f321cf4ea521b6b1d3b615161185
016fb9eeb1482a3f820905d65ec6ddff03459b6c
/12th_constructor_2/Sofabed3.cpp
0ed0b8a5f4669ec4856eb971987f9df430ffb407
[]
no_license
Koh84/CPP_revision
cd165a565a34443cbe674fb8b6299f8c8adb1381
a1dd0cf04bb42eed9e5f2da79198b3cc69563f4e
refs/heads/master
2020-12-12T07:36:17.483902
2020-01-27T10:15:00
2020-01-27T10:15:00
234,071,248
0
0
null
null
null
null
UTF-8
C++
false
false
1,666
cpp
#include <stdio.h> #include <iostream> #include <string.h> #include <unistd.h> using namespace std; class Furniture{ private: int weight; public: void setWeight(int weight) { this->weight = weight; } int getWeight(void) const { return weight; } Furniture(){cout<<"Furniture()"<<endl;} }; class Vertification3C{ public: Vertification3C(){cout<<"Vertification3C()"<<endl;} }; class Sofa : virtual public Furniture, virtual public Vertification3C { private: int a; public: void watchTV(void) { cout<<"watch TV"<<endl; } Sofa(){cout<<"Sofa()"<<endl;} }; class Bed : virtual public Furniture, virtual public Vertification3C{ private: int b; public: void sleep(void) { cout<<"sleep"<<endl; } Bed(){cout<<"Bed()"<<endl;} }; class Sofabed : public Sofa, public Bed { private: int c; public: Sofabed(){cout<<"Sofabed()"<<endl;} Sofabed(char *abc){cout<<"Sofabed(char *abc)"<<endl;} }; class LeftRightCom{ public: LeftRightCom(){cout<<"LeftRightCom()"<<endl;} LeftRightCom(char *abc){cout<<"LeftRightCom(char *abc)"<<endl;} }; class Date{ public: Date(){cout<<"Date()"<<endl;} Date(char *abc){cout<<"Date(char *abc)"<<endl;} }; class Type{ public: Type(){cout<<"Type()"<<endl;} Type(char *abc){cout<<"Type(char *abc)"<<endl;} }; class LeftRightSofabed : public Sofabed, virtual public LeftRightCom { private: Date date; Type type; public: LeftRightSofabed(){cout<<"LeftRightSofabed()"<<endl;} LeftRightSofabed(char *str1, char *str2, char *str3) : Sofabed(str1), LeftRightCom(str2), date(str3) { cout<<"LeftRightSofabed()"<<endl; } }; int main(int argc, char **argv) { LeftRightSofabed s("abc","2342","yyy"); return 0; }
[ "book@book-virtual-machine.(none)" ]
book@book-virtual-machine.(none)
865759911891dcb560e706697d2a890e1144f70a
e7e497b20442a4220296dea1550091a457df5a38
/main_project/socialgraph/PUKFeed/PUKFeedUpdate/src/ReadFriendListUtil.cpp
6577bd667b39656f7a8266a14c9a3f38d61f7257
[]
no_license
gunner14/old_rr_code
cf17a2dedf8dfcdcf441d49139adaadc770c0eea
bb047dc88fa7243ded61d840af0f8bad22d68dee
refs/heads/master
2021-01-17T18:23:28.154228
2013-12-02T23:45:33
2013-12-02T23:45:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,999
cpp
#include "ReadFriendListUtil.h" using namespace std; using namespace readfriend; using namespace MyUtil; using namespace com::xiaonei::xce; void ReadFriendListUtil::GetFriendList(const std::vector<int>& idList, std::map<int, std::vector<int> >& result) { time_t phrase_start = 0, phrase_end = 0; phrase_start = time(NULL); TaskManager::instance().config(TASK_LEVEL_READ_FRIEND, ThreadPoolConfig(0, 100)); int task_size = 0; long wait = 0; long count = 0; for (vector<int>::const_iterator iter = idList.begin(); iter != idList.end(); ++iter) { ++count; pair<map<int, vector<int> >::iterator, bool> tmp = result.insert(make_pair<int, vector<int> >(*iter, vector<int>())); TaskManager::instance().execute(new ReadFriendTask(*iter, tmp.first->second)); while ((task_size = TaskManager::instance().size(TASK_LEVEL_READ_FRIEND)) > 10000) { wait += 2; sleep(2); fprintf(stderr, "TASK_LEVEL_READ_FRIEND: sleep %ld second, %ld / %ld.\r", wait, count, idList.size()); } } //sleep(2); fprintf(stderr, "\nRead user friendlist completed\n"); while (TaskManager::instance().size(TASK_LEVEL_READ_FRIEND) > 0) { fprintf(stderr, "final left TASK_LEVEL_READ_FRIEND size = %d.\n", task_size); sleep(2); } phrase_end = time(NULL); fprintf(stderr, "size of idList = %ld, size of result = %ld, using %.1fm\n", idList.size(), result.size(), (phrase_end - phrase_start)/60.0); //sleep(3); // //for (map<int, vector<int> >::iterator iter = result.begin(); // iter != result.end(); ++iter) { // cout << iter->first << " : " << endl; // for (vector<int>::iterator it = iter->second.begin(); // it != iter->second.end(); ++it) { // cout << *it << " "; // } // cout << endl; //} } void ReadFriendListUtil::GetFriendListSynchronism(const std::vector<int>& idList, std::map<int, std::vector<int> >& result) { long count = 0; for (vector<int>::const_iterator iter = idList.begin(); iter != idList.end(); ++iter) { if (++count % 1000 == 0) { fprintf(stderr, "GetFriendListSynchronism %ld / %ld.\r", count, idList.size()); } pair<map<int, vector<int> >::iterator, bool> tmp = result.insert(make_pair<int, vector<int> >(*iter, vector<int>())); string tableName = TableName::RelationTableName(*iter); string pattern = TableName::RelationPattern(*iter); Statement sql; sql << "SELECT * FROM " << tableName << " WHERE host=" << *iter; try { QueryRunner("relation_friendrank", CDbRServer, pattern).query(sql, FriendRelationReadHandler(tmp.first->second)); } catch (Ice::Exception& e) { cout << "[ReadFriendTask] Connection Exception: " << e.what(); } catch (std::exception& e) { cout << "[ReadFriendTask] Std Exception: " << e.what(); } catch (...) { cout << "[ReadFriendTask] Unknown Exception" << endl; } sort(tmp.first->second.begin(), tmp.first->second.end()); //好友列表按id递增排序 } } //--------------------------------------------------------------- void ReadFriendTask::handle() { string tableName = TableName::RelationTableName(_userId); string pattern = TableName::RelationPattern(_userId); Statement sql; sql << "SELECT * FROM " << tableName << " WHERE host=" << _userId; try { QueryRunner("relation_friendrank", CDbRServer, pattern).query(sql, FriendRelationReadHandler(_friendList)); } catch (Ice::Exception& e) { cout << "[ReadFriendTask] Connection Exception: " << e.what(); } catch (std::exception& e) { cout << "[ReadFriendTask] Std Exception: " << e.what(); } catch (...) { cout << "[ReadFriendTask] Unknown Exception" << endl; } sort(_friendList.begin(), _friendList.end()); //好友列表按id递增排序 //cout << _friendList.size() << endl; } //--------------------------------------------------------------- bool FriendRelationReadHandler::handle(mysqlpp::Row& row) const { if ((int)_friendList.size() < 2000) { //cout << row["guest"] << endl; _friendList.push_back((int)row["guest"]); } return true; }
9e69c905662636c5ce766578b057394113f595e1
081207834468897520a327260165c64466aefb8a
/src/primitives/block.cpp
af1b73475a1ce7f849f2093c20a6b4bfb2c5f39e
[ "MIT" ]
permissive
gotaproblem/AuxPowCoin
eb61cd8dc03d021d3317ffb178ea6a685c74cb7c
eea038edf893677e85ca45eed047ff81092d3a0f
refs/heads/master
2021-12-12T17:46:50.535108
2021-12-11T07:23:48
2021-12-11T07:23:48
227,309,159
0
0
null
null
null
null
UTF-8
C++
false
false
1,848
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "primitives/block.h" #include "hash.h" #include "crypto/scrypt.h" #include "tinyformat.h" #include "utilstrencodings.h" #include "crypto/common.h" /* uint256 CBlockHeader::GetHash() const { return SerializeHash(*this); } */ uint256 CBlockHeader::GetPoWHash() const { uint256 thash; scrypt_1024_1_1_256(BEGIN(nVersion), BEGIN(thash)); return thash; } void CBlockHeader::SetAuxpow (CAuxPow* apow) { if (apow) { auxpow.reset(apow); SetAuxpowVersion(true); } else { auxpow.reset(); SetAuxpowVersion(false); } } std::string CBlock::ToString() const { std::stringstream s; s << strprintf("CBlock(hash=%s, ver=0x%08x, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n", GetHash().ToString(), nVersion, hashPrevBlock.ToString(), hashMerkleRoot.ToString(), nTime, nBits, nNonce, vtx.size()); for (unsigned int i = 0; i < vtx.size(); i++) { s << " " << vtx[i]->ToString() << "\n"; } return s.str(); } int64_t GetBlockWeight(const CBlock& block) { // This implements the weight = (stripped_size * 4) + witness_size formula, // using only serialization with and without witness data. As witness_size // is equal to total_size - stripped_size, this formula is identical to: // weight = (stripped_size * 3) + total_size. return ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * (WITNESS_SCALE_FACTOR - 1) + ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION); }
c11b6c53d5f47d71cb740b4708a8a81111978d36
f0b7bcc41298354b471a72a7eeafe349aa8655bf
/codebase/apps/radar/src/Qmap2Cidd/Args.cc
b5e6e34a3824b257be6cb02cf2ed1446a6f78e3c
[ "BSD-3-Clause" ]
permissive
NCAR/lrose-core
23abeb4e4f1b287725dc659fb566a293aba70069
be0d059240ca442883ae2993b6aa112011755688
refs/heads/master
2023-09-01T04:01:36.030960
2023-08-25T00:41:16
2023-08-25T00:41:16
51,408,988
90
53
NOASSERTION
2023-08-18T21:59:40
2016-02-09T23:36:25
C++
UTF-8
C++
false
false
3,783
cc
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* // ** Copyright UCAR (c) 1990 - 2016 // ** University Corporation for Atmospheric Research (UCAR) // ** National Center for Atmospheric Research (NCAR) // ** Boulder, Colorado, USA // ** BSD licence applies - redistribution and use in source and binary // ** forms, with or without modification, are permitted provided that // ** the following conditions are met: // ** 1) If the software is modified to produce derivative works, // ** such modified software should be clearly marked, so as not // ** to confuse it with the version available from UCAR. // ** 2) Redistributions of source code must retain the above copyright // ** notice, this list of conditions and the following disclaimer. // ** 3) 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. // ** 4) Neither the name of UCAR nor the names of its contributors, // ** if any, may be used to endorse or promote products derived from // ** this software without specific prior written permission. // ** DISCLAIMER: THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS // ** OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED // ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* ////////////////////////////////////////////////////////// // Args.cc : command line args // // Mike Dixon, RAP, NCAR, // P.O.Box 3000, Boulder, CO, 80307-3000, USA // ////////////////////////////////////////////////////////// #include "Args.hh" #include "Params.hh" #include <cstring> #include <toolsa/umisc.h> using namespace std; // Constructor Args::Args (const string &prog_name) { _progName = prog_name; } // Destructor Args::~Args () { TDRP_free_override(&override); } // Parse command line // Returns 0 on success, -1 on failure int Args::parse (const int argc, const char **argv) { char tmp_str[BUFSIZ]; // intialize int iret = 0; TDRP_init_override(&override); // loop through args for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "--") || !strcmp(argv[i], "-h") || !strcmp(argv[i], "-help") || !strcmp(argv[i], "-man")) { _usage(cout); exit (0); } else if (!strcmp(argv[i], "-debug")) { sprintf(tmp_str, "debug = DEBUG_NORM;"); TDRP_add_override(&override, tmp_str); } else if (!strcmp(argv[i], "-verbose")) { sprintf(tmp_str, "debug = DEBUG_VERBOSE;"); TDRP_add_override(&override, tmp_str); } else if (!strcmp(argv[i], "-name")) { if (i < argc - 1) { sprintf(tmp_str, "map_name = %s;", argv[++i]); TDRP_add_override(&override, tmp_str); } else { iret = -1; } } // if } // i if (iret) { _usage(cerr); } return (iret); } void Args::_usage(ostream &out) { out << "Change map file from Qweensland to CIDD format" << endl; out << "Usage: " << _progName << " < qlandmap > ciddmap\n" << "options:\n" << " [ --, -h, -help, -man ] produce this list.\n" << " [ -debug ] print debug messages\n" << " [ -name ? ] map name\n" << " [ -verbose ] print verbose debug messages\n" << endl; Params::usage(out); }
63f68e8bd5083b409022690ae4d69c448330604a
aa522865a9c209856766e1b9b00a178483c9f88c
/src/qt/bitcoinunits.h
d582baca2576b5f01eda38ddf43d08213383a75f
[ "MIT" ]
permissive
FerretCoinDeveloper/FerretCoin
f49343c1808abe477153de95925360ada88da1e2
0c74c93ef67b648d653e4eabbad00a94a9d2ea1c
refs/heads/master
2020-05-19T15:38:33.450046
2019-05-15T02:05:29
2019-05-15T02:05:29
185,088,786
1
1
MIT
2019-05-15T02:05:30
2019-05-05T22:24:21
C++
UTF-8
C++
false
false
4,327
h
#ifndef BITCOINUNITS_H #define BITCOINUNITS_H #include "util.h" #include <QString> #include <QAbstractListModel> // U+2009 THIN SPACE = UTF-8 E2 80 89 #define REAL_THIN_SP_CP 0x2009 #define REAL_THIN_SP_UTF8 "\xE2\x80\x89" #define REAL_THIN_SP_HTML "&thinsp;" // U+200A HAIR SPACE = UTF-8 E2 80 8A #define HAIR_SP_CP 0x200A #define HAIR_SP_UTF8 "\xE2\x80\x8A" #define HAIR_SP_HTML "&#8202;" // U+2006 SIX-PER-EM SPACE = UTF-8 E2 80 86 #define SIXPEREM_SP_CP 0x2006 #define SIXPEREM_SP_UTF8 "\xE2\x80\x86" #define SIXPEREM_SP_HTML "&#8198;" // U+2007 FIGURE SPACE = UTF-8 E2 80 87 #define FIGURE_SP_CP 0x2007 #define FIGURE_SP_UTF8 "\xE2\x80\x87" #define FIGURE_SP_HTML "&#8199;" // QMessageBox seems to have a bug whereby it doesn't display thin/hair spaces // correctly. Workaround is to display a space in a small font. If you // change this, please test that it doesn't cause the parent span to start // wrapping. #define HTML_HACK_SP "<span style='white-space: nowrap; font-size: 6pt'> </span>" // Define THIN_SP_* variables to be our preferred type of thin space #define THIN_SP_CP REAL_THIN_SP_CP #define THIN_SP_UTF8 REAL_THIN_SP_UTF8 #define THIN_SP_HTML HTML_HACK_SP /** FerretCoin unit definitions. Encapsulates parsing and formatting and serves as list model for drop-down selection boxes. */ class FerretCoinUnits: public QAbstractListModel { Q_OBJECT public: explicit FerretCoinUnits(QObject *parent); /** FerretCoin units. @note Source: https://en.bitcoin.it/wiki/Units . Please add only sensible ones */ enum Unit { FRTC, mFRTC, uFRTC }; enum SeparatorStyle { separatorNever, separatorStandard, separatorAlways }; //! @name Static API //! Unit conversion and formatting ///@{ //! Get list of units, for drop-down box static QList<Unit> availableUnits(); //! Is unit ID valid? static bool valid(int unit); //! Short name static QString name(int unit); //! Longer description static QString description(int unit); //! Number of Satoshis (1e-8) per unit static qint64 factor(int unit); //! Number of amount digits (to represent max number of coins) static int amountDigits(int unit); //! Number of decimals left static int decimals(int unit); //! Format as string static QString format(int unit, const CAmount& amount, bool plussign=false, SeparatorStyle separators=separatorStandard); static QString simpleFormat(int unit, const CAmount& amount, bool plussign=false, SeparatorStyle separators=separatorStandard); //! Format as string (with unit) static QString formatWithUnit(int unit, const CAmount& amount, bool plussign=false, SeparatorStyle separators=separatorStandard); static QString formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign=false, SeparatorStyle separators=separatorStandard); //! Format as string (with unit) but floor value up to "digits" settings static QString floorWithUnit(int unit, const CAmount& amount, bool plussign=false, SeparatorStyle separators=separatorStandard); static QString floorHtmlWithUnit(int unit, const CAmount& amount, bool plussign=false, SeparatorStyle separators=separatorStandard); //! Parse string to coin amount static bool parse(int unit, const QString &value, CAmount *val_out); //! Gets title for amount column including current display unit if optionsModel reference available */ static QString getAmountColumnTitle(int unit); ///@} //! @name AbstractListModel implementation //! List model for unit drop-down selection box. ///@{ enum RoleIndex { /** Unit identifier */ UnitRole = Qt::UserRole }; int rowCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; ///@} static QString removeSpaces(QString text) { text.remove(' '); text.remove(QChar(THIN_SP_CP)); #if (THIN_SP_CP != REAL_THIN_SP_CP) text.remove(QChar(REAL_THIN_SP_CP)); #endif return text; } //! Return maximum number of base units (Satoshis) static CAmount maxMoney(); private: QList<FerretCoinUnits::Unit> unitlist; }; typedef FerretCoinUnits::Unit FerretCoinUnit; #endif // BITCOINUNITS_H
7aa8a50ca2d32dbda567320103fbac8347846ce8
a1fbf16243026331187b6df903ed4f69e5e8c110
/cs/sdk/3d_sdk/maya/ver-2008/devkit/plug-ins/hlslFXShader.h
693524ff3d3707505c74bf3bcf2db39742c642e7
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
OpenXRay/xray-15
ca0031cf1893616e0c9795c670d5d9f57ca9beff
1390dfb08ed20997d7e8c95147ea8e8cb71f5e86
refs/heads/xd_dev
2023-07-17T23:42:14.693841
2021-09-01T23:25:34
2021-09-01T23:25:34
23,224,089
64
23
NOASSERTION
2019-04-03T17:50:18
2014-08-22T12:09:41
C++
UTF-8
C++
false
false
6,941
h
//- // ========================================================================== // Copyright (C) 2005 ATI Technologies Inc. All rights reserved. // // Copyright (C) 1995 - 2006 Autodesk, Inc. and/or its licensors. All // rights reserved. // // The coded instructions, statements, computer programs, and/or related // material (collectively the "Data") in these files contain unpublished // information proprietary to Autodesk, Inc. ("Autodesk") and/or its // licensors, which is protected by U.S. and Canadian federal copyright // law and by international treaties. // // The Data is provided for use exclusively by You. You have the right // to use, modify, and incorporate this Data into other products for // purposes authorized by the Autodesk software license agreement, // without fee. // // The copyright notices in the Software and this entire statement, // including the above license grant, this restriction and the // following disclaimer, must be included in all copies of the // Software, in whole or in part, and all derivative works of // the Software, unless such copies or derivative works are solely // in the form of machine-executable object code generated by a // source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. // AUTODESK DOES NOT MAKE AND HEREBY DISCLAIMS ANY EXPRESS OR IMPLIED // WARRANTIES INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF // NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR // PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE, OR // TRADE PRACTICE. IN NO EVENT WILL AUTODESK AND/OR ITS LICENSORS // BE LIABLE FOR ANY LOST REVENUES, DATA, OR PROFITS, OR SPECIAL, // DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES, EVEN IF AUTODESK // AND/OR ITS LICENSORS HAS BEEN ADVISED OF THE POSSIBILITY // OR PROBABILITY OF SUCH DAMAGES. // // ========================================================================== //+ //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef HLSL_FX_SHADER_H #define HLSL_FX_SHADER_H #include <vector> #include <string> #include <IAshliFX.h> #include <IAshli.h> #include "Shader.h" #include "Observer.h" #include "glExtensions.h" class hlslFXShader : public shader { struct uniform; public: hlslFXShader( ); virtual ~hlslFXShader(); // // Shader loading and management routines // // These routines are intended to deal with the realities of deferred processing // in the Maya environemnt. The shader file ideally needs to be parsed and parameters // extracted prior to the availability of a GL context. This forces shader compilation // to be defered until first use. // bool createFromFile( const char *filename); bool createFromFX( IAshliFX *fx); protected: bool parseParameters( const IAshliFX *fx); DataType parseUniformType( const char *type); Semantic parseUniformSemantic( const char *semantic); SamplerType parseSamplerType( const char *type); void parseExpression( uniform &u, const char *exp); void updateHandles(); //configure the handles for the uniforms, etc. bool buildShaders(); //build the shaders that we had to defer compilation on const char* getVertexShader( int pass); const char* getPixelShader( int pass); public: virtual bool valid(); virtual int passCount(); virtual int techniqueCount(); virtual const char* techniqueName( int n); virtual bool build(); virtual void bind(); virtual void setShapeDependentState(); virtual void unbind(); virtual void setTechnique( int t); virtual void setPass( int p); //need to have queries for attribs and uniforms virtual int uniformCount(); virtual int samplerCount(); virtual int attributeCount(); virtual const char* uniformName(int i); virtual DataType uniformType(int i); virtual Semantic uniformSemantic(int i); virtual float* uniformDefault(int i); virtual const char* samplerName(int i); virtual SamplerType samplerType(int i); virtual const char* attributeName(int i); virtual DataType attributeType(int i); virtual int attributeHandle(int i) {return 0;}; //need set functions for current values virtual void updateUniformBool( int i, bool val); virtual void updateUniformInt( int i, int val); virtual void updateUniformFloat( int i, float val); virtual void updateUniformBVec( int i, const bool* val); virtual void updateUniformIVec( int i, const int* val); virtual void updateUniformVec( int i, const float* val); virtual void updateUniformMat( int i, const float* val); virtual void updateUniformMat( int i, const double* val); virtual void updateSampler( int i, unsigned int val); //predefined attributes virtual bool usesColor(); virtual bool usesNormal(); virtual bool usesTexCoord( int set); virtual bool usesTangent(); virtual bool usesBinormal(); virtual int tangentSlot(); virtual int binormalSlot(); //error reporting virtual const char* errorString(); private: void deleteShaders(); std::vector<GLuint> m_fShader; std::vector<GLuint> m_vShader; //these are to hold the ASHLI/ASHLIFX data int m_techniqueCount; std::vector<std::string> m_techniqueNames; std::vector<int> m_passCount; //per technique std::vector<int> m_techniqueOffset; //where does this technique begin std::vector<std::string> m_vertexShaders; // vertex shader strings std::vector<std::string> m_fragmentShaders; // fragment shader strings std::vector<std::string> m_orgVertexShaders; // vertex shader strings std::vector<std::string> m_orgFragmentShaders; // fragment shader strings std::vector<passState*> m_stateList; bool m_valid; struct uniform { std::string name; //should switch to a string or MString DataType type; Semantic usage; //handles semantic values std::vector<int> fReg; //will need to switch to a vector to handle Multipass std::vector<int> vReg; //will need to switch to a vector to handle Multipass float fVal[16]; float defaultVal[16]; bool dirty; }; struct attribute { std::string name; DataType type; std::vector<int> handle; }; struct sampler { std::string name; SamplerType type; GLuint texObject; std::vector<int> texUnit; //will need to switch to a vector to handle Multipass bool dirty; }; std::vector<uniform> m_uniformList; std::vector<attribute> m_attributeList; std::vector<sampler> m_samplerList; bool m_stale; bool m_color; bool m_normal; bool m_tangent; bool m_binormal; unsigned int m_texMask; int m_tangentSlot; int m_binormalSlot; int m_activePass; int m_activeTechnique; std::string m_error; }; #endif //GLSL_FX_SHADER_H
7fc83396ba15a97508dc4cecd21459ed8dc559af
b8c09fd775188630948f8face6ce7617ea97f9a7
/src/api/apihandler.cpp
05ccf7ca998d71911a1d9be9a58d02284b5bc949
[ "MIT" ]
permissive
stlcours/nitroshare-desktop
9dce4498e4cae5e2371767539f5be2b1a213b71d
5f0da7d2da47a29c3e7281ecc86d9683fcd38e79
refs/heads/master
2021-07-17T18:27:13.800678
2017-10-26T08:10:13
2017-10-26T08:10:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,871
cpp
/** * The MIT License (MIT) * * Copyright (c) 2015 Nathan Osman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. **/ #include <QFileInfo> #include <QStringList> #include "apihandler.h" #if QHTTPENGINE_VERSION_MAJOR >= 1 # include <QJsonDocument> # include <QJsonObject> #endif ApiHandler::ApiHandler(const QString &token) : mToken(token) { #if QHTTPENGINE_VERSION_MAJOR >= 1 registerMethod("version", this, &ApiHandler::version); registerMethod("sendItems", this, &ApiHandler::sendItems); #endif } #if QHTTPENGINE_VERSION_MAJOR < 1 QVariantMap ApiHandler::version(const QVariantMap &params) { return { { "version", PROJECT_VERSION } }; } QVariantMap ApiHandler::sendItems(const QVariantMap &params) { // Queue the items for transfer emit itemsQueued(params.value("items").toStringList()); return QVariantMap(); } #else void ApiHandler::version(QHttpEngine::Socket *socket) { QJsonObject object; object.insert("version", PROJECT_VERSION); socket->writeJson(QJsonDocument(object)); } void ApiHandler::sendItems(QHttpEngine::Socket *socket) { QJsonDocument document; if (socket->readJson(document)) { emit itemsQueued( document.object().toVariantMap().value("items").toStringList() ); socket->writeJson(QJsonDocument()); } else { socket->writeError(QHttpEngine::Socket::BadRequest); } } #endif #if QHTTPENGINE_VERSION_MAJOR < 1 void ApiHandler::process(QHttpSocket *socket, const QString &path) { // Ensure that the correct authentication token was provided if (socket->headers().value("X-Auth-Token") != mToken) { socket->writeError(QHttpSocket::Forbidden); return; } // If authenticated, have QObjectHandler process the request QObjectHandler::process(socket, path); } #endif
7395032aeb50ef5208d460c4daa6d088a43eee73
fba24bbef8b1f1184cc5e254eb8e6a104c8ca26a
/src/main.cpp
bb5ebae726b11b26f5487bd6bcbed6fad5b3e79a
[ "MIT" ]
permissive
MichaelX99/Lane_Tracker
e3df72bbaea0af722faf314fabfbd7c1a6653f85
384f182ffe2bd26f47fd172908e4f20c4f75ae48
refs/heads/master
2021-01-25T13:36:42.374993
2018-04-30T14:04:54
2018-04-30T14:04:54
123,596,712
2
0
MIT
2018-04-30T14:04:55
2018-03-02T15:35:30
Jupyter Notebook
UTF-8
C++
false
false
186
cpp
#include <ros/ros.h> #include <Particle_Filter.h> int main(int argc, char *argv[]) { ros::init(argc, argv, "particle_filter"); Particle_Filter pf; ros::spin(); return 0; }
1ba38a8b3e58ae95c95ec9edbf73e03804f7973d
4239e7e34596b54085683a4e656b3ec3f66360b4
/codeforces/976A.cpp
0e048482f29bb4b3ed1b11b4b98305b8a45764a3
[]
no_license
LeonardoGaldino/ProblemsICPC
a528d0a9e0014a9e4e8d3ca42afc97256109e1d3
3aa6a71826141ee96127a759f71d175b8926f41c
refs/heads/master
2021-04-12T10:20:54.193139
2018-05-03T17:55:25
2018-05-03T17:55:25
126,362,894
0
0
null
null
null
null
UTF-8
C++
false
false
460
cpp
// Linear pass solution #include <bits/stdc++.h> #define fr(i,st,nd,q) for(int i = st ; i < nd ; i += q) #define PII pair<int,int> #define VI vector<int> #define INF 0x3f3f3f3f #define EPS 1e-10 using namespace std; int main() { string inp; int n; cin >> n >> inp; if(inp == "0") cout << "0" << endl; else { string out = "1"; for(int i = 1 ; i < n ; ++i){ if(inp[i] == '0') out.push_back('0'); } cout << out << endl; } return 0; }
407890e2cbfc7588f6a7ddc6e5bbe744de98af94
568d0dd27cd773427c7eafb4f99793caa763e12c
/shell/src/FiltersCommand.cpp
088fddd97c686da52d7c5729b46a026dc1f98e97
[]
no_license
guolianzhu/libadblockplus
1b9db8a88c2dd59702facdcb83e782633ddafc6b
6f186cf50a06e4fa19653780cd8d2532805b26af
refs/heads/master
2021-01-25T00:47:46.204264
2015-08-25T13:54:33
2015-08-25T13:54:33
44,963,042
1
0
null
2015-10-26T11:03:27
2015-10-26T11:03:27
null
UTF-8
C++
false
false
3,283
cpp
/* * This file is part of Adblock Plus <https://adblockplus.org/>, * Copyright (C) 2006-2015 Eyeo GmbH * * Adblock Plus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * Adblock Plus 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 Adblock Plus. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <sstream> #include "FiltersCommand.h" namespace { typedef std::vector<AdblockPlus::FilterPtr> FilterList; void ShowFilterList(const FilterList& filters) { for (FilterList::const_iterator it = filters.begin(); it != filters.end(); it++) { std::string type; switch ((*it)->GetType()) { case AdblockPlus::Filter::TYPE_BLOCKING: type = "blocking"; break; case AdblockPlus::Filter::TYPE_EXCEPTION: type = "exception"; break; case AdblockPlus::Filter::TYPE_ELEMHIDE: type = "elemhide"; break; case AdblockPlus::Filter::TYPE_ELEMHIDE_EXCEPTION: type = "elemhideexception"; break; case AdblockPlus::Filter::TYPE_COMMENT: type = "comment"; break; case AdblockPlus::Filter::TYPE_INVALID: type = "invalid"; break; default: type = "(unknown type)"; break; } std::cout << (*it)->GetProperty("text")->AsString() << " - " << type << std::endl; } } } FiltersCommand::FiltersCommand(AdblockPlus::FilterEngine& filterEngine) : Command("filters"), filterEngine(filterEngine) { } void FiltersCommand::operator()(const std::string& arguments) { std::istringstream argumentStream(arguments); std::string action; argumentStream >> action; if (!action.size()) { ShowFilters(); return; } if (action == "add") { std::string text; std::getline(argumentStream, text); if (text.size()) AddFilter(text); else ShowUsage(); } else if (action == "remove") { std::string text; std::getline(argumentStream, text); if (text.size()) RemoveFilter(text); else ShowUsage(); } else throw NoSuchCommandError(name + " " + action); } std::string FiltersCommand::GetDescription() const { return "List and manage custom filters"; } std::string FiltersCommand::GetUsage() const { return name + " [add FILTER|remove FILTER]"; } void FiltersCommand::ShowFilters() { ShowFilterList(filterEngine.GetListedFilters()); } void FiltersCommand::AddFilter(const std::string& text) { AdblockPlus::FilterPtr filter = filterEngine.GetFilter(text); filter->AddToList(); } void FiltersCommand::RemoveFilter(const std::string& text) { AdblockPlus::FilterPtr filter = filterEngine.GetFilter(text); if (!filter->IsListed()) { std::cout << "No such filter '" << text << "'" << std::endl; return; } filter->RemoveFromList(); }
22fa647946fd96d39ecbb2231cc413fa25eec4c1
2c11eeb69439f5e298e9c445e30298d6090b5c86
/day00/ex01/phonebook.cpp
2953b735c1ee81772717231a118cad6d5896d561
[]
no_license
tstelfox/CPP
bb4af2d52db7cfe3dcd3dfd546de484eeba6ddf7
0099a4804e401110154a8ecadecf274bc6565a66
refs/heads/main
2023-07-24T00:39:15.086612
2021-09-10T11:23:35
2021-09-10T11:23:35
312,568,964
1
0
null
null
null
null
UTF-8
C++
false
false
3,278
cpp
/* ************************************************************************** */ /* */ /* :::::::: */ /* phonebook.cpp :+: :+: */ /* +:+ */ /* By: tmullan <[email protected]> +#+ */ /* +#+ */ /* Created: 2020/11/15 16:44:58 by tmullan #+# #+# */ /* Updated: 2020/11/29 15:19:17 by tmullan ######## odam.nl */ /* */ /* ************************************************************************** */ #include <iostream> #include "phonebook.hpp" phonebook::phonebook( void ) { std::cout << "contact slot has been created" << std::endl; return; } phonebook::~phonebook ( void ) { std::cout << "contact slot has been deleted" << std::endl; return; } void phonebook::set_firstname ( std::string buff) { this->_first_name.assign(buff); } void phonebook::set_lastname ( std::string buff) { this->_last_name.assign(buff); } void phonebook::set_nickname ( std::string buff) { this->_nickname.assign(buff); } void phonebook::set_login ( std::string buff) { this->_login.assign(buff); } void phonebook::set_postaladdress ( std::string buff) { this->_postal_address.assign(buff); } void phonebook::set_emailaddress ( std::string buff) { this->_email_address.assign(buff); } void phonebook::set_phonenumber ( std::string buff) { this->_phone_number.assign(buff); } void phonebook::set_birthday ( std::string buff) { this->_birthday_date.assign(buff); } void phonebook::set_favouritemeal ( std::string buff) { this->_favourite_meal.assign(buff); } void phonebook::set_underwear ( std::string buff) { this->_underwear_colour.assign(buff); } void phonebook::set_darkestsecret ( std::string buff) { this->_darkest_secret.assign(buff); } void phonebook::column_padding ( std::string content ) const { if (content.length() > 10) { content.resize (9); std::cout << content << "."; } else std::cout << std::setw (10) << content; } void phonebook::full_contact ( void ) const { std::cout << "First Name: " << _first_name << std::endl << "Last Name: " << _last_name << std::endl << "Nickname: " << _nickname << std::endl << "Login: " << _login << std::endl << "Postal Address: " << _postal_address << std::endl << "Email address: " << _email_address << std::endl << "Phone Number: " << _phone_number << std::endl << "Birthday: " << _birthday_date << std::endl << "Favourite meal: " << _favourite_meal << std::endl << "Colour of yer knickers: " << _underwear_colour << std::endl << "Darkest Secret: " << _darkest_secret << std::endl; } void phonebook::get_details ( int i ) const { std::string index = std::to_string(i); column_padding(index); std::cout << "|"; column_padding(this->_first_name); std::cout << "|"; column_padding(this->_last_name); std::cout << "|"; column_padding(this->_nickname); std::cout << std::endl; }
12bc1687eb24879e6fedc007681cd324e0e970c0
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/BOPCol_NCVector.hxx
01af8c745aff0a0d2d050994fcb3018a89da6cea
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
1,749
hxx
// Created by: Peter KURNEV // Copyright (c) 1999-2013 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef BOPCol_NCVector_HeaderFile #define BOPCol_NCVector_HeaderFile #include <Standard.hxx> #include <NCollection_Vector.hxx> #include <NCollection_BaseAllocator.hxx> //======================================================================= //class : BOPCol_NCVector //purpose : //======================================================================= template <class Type> class BOPCol_NCVector : public NCollection_Vector<Type> { public: BOPCol_NCVector(const Standard_Integer theIncrement=256, const Handle_NCollection_BaseAllocator& theAlloc = NULL) : NCollection_Vector<Type>(theIncrement, theAlloc) { }; // BOPCol_NCVector(const BOPCol_NCVector& theOther) : NCollection_Vector<Type>(theOther) { }; // Type& Append1 () { Type& anAppended = *(Type* )NCollection_BaseVector::expandV (NCollection_BaseCollection<Type>::myAllocator, NCollection_Vector<Type>::myLength); return anAppended; } // Standard_Integer Extent() const { return NCollection_Vector<Type>::myLength; } protected: }; #endif
beed193414ee6465430e1b200bd7ee5b486945d7
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/third_party/WebKit/Source/core/paint/ReplacedPainter.cpp
54029e1514c5bc75c01434ced044b02b12cea5db
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "Apache-2.0", "MIT" ]
permissive
webosce/chromium53
f8e745e91363586aee9620c609aacf15b3261540
9171447efcf0bb393d41d1dc877c7c13c46d8e38
refs/heads/webosce
2020-03-26T23:08:14.416858
2018-08-23T08:35:17
2018-09-20T14:25:18
145,513,343
0
2
Apache-2.0
2019-08-21T22:44:55
2018-08-21T05:52:31
null
UTF-8
C++
false
false
5,515
cpp
// 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 "core/paint/ReplacedPainter.h" #include "core/layout/LayoutReplaced.h" #include "core/layout/api/SelectionState.h" #include "core/layout/svg/LayoutSVGRoot.h" #include "core/paint/BoxPainter.h" #include "core/paint/LayoutObjectDrawingRecorder.h" #include "core/paint/ObjectPainter.h" #include "core/paint/PaintInfo.h" #include "core/paint/PaintLayer.h" #include "core/paint/RoundedInnerRectClipper.h" #include "wtf/Optional.h" namespace blink { static bool shouldApplyViewportClip(const LayoutReplaced& layoutReplaced) { return !layoutReplaced.isSVGRoot() || toLayoutSVGRoot(&layoutReplaced)->shouldApplyViewportClip(); } void ReplacedPainter::paint(const PaintInfo& paintInfo, const LayoutPoint& paintOffset) { LayoutPoint adjustedPaintOffset = paintOffset + m_layoutReplaced.location(); if (!shouldPaint(paintInfo, adjustedPaintOffset)) return; LayoutRect borderRect(adjustedPaintOffset, m_layoutReplaced.size()); if (m_layoutReplaced.style()->visibility() == VISIBLE && m_layoutReplaced.hasBoxDecorationBackground() && (paintInfo.phase == PaintPhaseForeground || paintInfo.phase == PaintPhaseSelection)) m_layoutReplaced.paintBoxDecorationBackground(paintInfo, adjustedPaintOffset); if (paintInfo.phase == PaintPhaseMask) { m_layoutReplaced.paintMask(paintInfo, adjustedPaintOffset); return; } if (paintInfo.phase == PaintPhaseClippingMask && (!m_layoutReplaced.hasLayer() || !m_layoutReplaced.layer()->hasCompositedClippingMask())) return; if (shouldPaintSelfOutline(paintInfo.phase)) { ObjectPainter(m_layoutReplaced).paintOutline(paintInfo, adjustedPaintOffset); return; } if (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseSelection && !m_layoutReplaced.canHaveChildren() && paintInfo.phase != PaintPhaseClippingMask) return; if (paintInfo.phase == PaintPhaseSelection) if (m_layoutReplaced.getSelectionState() == SelectionNone) return; { Optional<RoundedInnerRectClipper> clipper; bool completelyClippedOut = false; if (m_layoutReplaced.style()->hasBorderRadius()) { if (borderRect.isEmpty()) { completelyClippedOut = true; } else if (shouldApplyViewportClip(m_layoutReplaced)) { // Push a clip if we have a border radius, since we want to round the foreground content that gets painted. FloatRoundedRect roundedInnerRect = m_layoutReplaced.style()->getRoundedInnerBorderFor(borderRect, LayoutRectOutsets( -(m_layoutReplaced.paddingTop() + m_layoutReplaced.borderTop()), -(m_layoutReplaced.paddingRight() + m_layoutReplaced.borderRight()), -(m_layoutReplaced.paddingBottom() + m_layoutReplaced.borderBottom()), -(m_layoutReplaced.paddingLeft() + m_layoutReplaced.borderLeft())), true, true); clipper.emplace(m_layoutReplaced, paintInfo, borderRect, roundedInnerRect, ApplyToDisplayList); } } if (!completelyClippedOut) { if (paintInfo.phase == PaintPhaseClippingMask) { BoxPainter(m_layoutReplaced).paintClippingMask(paintInfo, adjustedPaintOffset); } else { m_layoutReplaced.paintReplaced(paintInfo, adjustedPaintOffset); } } } // The selection tint never gets clipped by border-radius rounding, since we want it to run right up to the edges of // surrounding content. bool drawSelectionTint = paintInfo.phase == PaintPhaseForeground && m_layoutReplaced.getSelectionState() != SelectionNone && !paintInfo.isPrinting(); if (drawSelectionTint && !LayoutObjectDrawingRecorder::useCachedDrawingIfPossible(paintInfo.context, m_layoutReplaced, DisplayItem::SelectionTint)) { LayoutRect selectionPaintingRect = m_layoutReplaced.localSelectionRect(); selectionPaintingRect.moveBy(adjustedPaintOffset); IntRect selectionPaintingIntRect = pixelSnappedIntRect(selectionPaintingRect); LayoutObjectDrawingRecorder drawingRecorder(paintInfo.context, m_layoutReplaced, DisplayItem::SelectionTint, selectionPaintingIntRect); paintInfo.context.fillRect(selectionPaintingIntRect, m_layoutReplaced.selectionBackgroundColor()); } } bool ReplacedPainter::shouldPaint(const PaintInfo& paintInfo, const LayoutPoint& adjustedPaintOffset) const { if (paintInfo.phase != PaintPhaseForeground && !shouldPaintSelfOutline(paintInfo.phase) && paintInfo.phase != PaintPhaseSelection && paintInfo.phase != PaintPhaseMask && paintInfo.phase != PaintPhaseClippingMask) return false; // If we're invisible or haven't received a layout yet, just bail. // But if it's an SVG root, there can be children, so we'll check visibility later. if (!m_layoutReplaced.isSVGRoot() && m_layoutReplaced.style()->visibility() != VISIBLE) return false; LayoutRect paintRect(m_layoutReplaced.visualOverflowRect()); paintRect.unite(m_layoutReplaced.localSelectionRect()); paintRect.moveBy(adjustedPaintOffset); if (!paintInfo.cullRect().intersectsCullRect(paintRect)) return false; return true; } } // namespace blink
869b265d9af7079f0d385e10e83be6fc620e04a9
8cf32b4cbca07bd39341e1d0a29428e420b492a6
/libraries/fc/include/fc/static_variant.hpp
b472e2866f1a341506cc947b2467e75bd9948906
[ "MIT" ]
permissive
cubetrain/CubeTrain
e1cd516d5dbca77082258948d3c7fc70ebd50fdc
b930a3e88e941225c2c54219267f743c790e388f
refs/heads/master
2020-04-11T23:00:50.245442
2018-12-17T16:07:16
2018-12-17T16:07:16
156,970,178
0
0
null
null
null
null
UTF-8
C++
false
false
13,994
hpp
/** This source adapted from https://github.com/kmicklas/variadic-static_variant * * Copyright (C) 2013 Kenneth Micklas * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **/ #pragma once #include <stdexcept> #include <typeinfo> #include <fc/exception/exception.hpp> #include <boost/core/typeinfo.hpp> namespace fc { // Implementation details, the user should not import this: namespace impl { template<int N, typename... Ts> struct storage_ops; template<typename X, typename... Ts> struct position; template<int Pos, typename... Ts> struct type_at; template<typename... Ts> struct type_info; template<typename StaticVariant> struct copy_construct { typedef void result_type; StaticVariant& sv; copy_construct( StaticVariant& s ):sv(s){} template<typename T> void operator()( const T& v )const { sv.init(v); } }; template<typename StaticVariant> struct move_construct { typedef void result_type; StaticVariant& sv; move_construct( StaticVariant& s ):sv(s){} template<typename T> void operator()( T& v )const { sv.init( std::move(v) ); } }; template<int N, typename T, typename... Ts> struct storage_ops<N, T&, Ts...> { static void del(int n, void *data) {} static void con(int n, void *data) {} template<typename visitor> static typename visitor::result_type apply(int n, void *data, visitor& v) {} template<typename visitor> static typename visitor::result_type apply(int n, void *data, const visitor& v) {} template<typename visitor> static typename visitor::result_type apply(int n, const void *data, visitor& v) {} template<typename visitor> static typename visitor::result_type apply(int n, const void *data, const visitor& v) {} }; template<int N, typename T, typename... Ts> struct storage_ops<N, T, Ts...> { static void del(int n, void *data) { if(n == N) reinterpret_cast<T*>(data)->~T(); else storage_ops<N + 1, Ts...>::del(n, data); } static void con(int n, void *data) { if(n == N) new(reinterpret_cast<T*>(data)) T(); else storage_ops<N + 1, Ts...>::con(n, data); } template<typename visitor> static typename visitor::result_type apply(int n, void *data, visitor& v) { if(n == N) return v(*reinterpret_cast<T*>(data)); else return storage_ops<N + 1, Ts...>::apply(n, data, v); } template<typename visitor> static typename visitor::result_type apply(int n, void *data, const visitor& v) { if(n == N) return v(*reinterpret_cast<T*>(data)); else return storage_ops<N + 1, Ts...>::apply(n, data, v); } template<typename visitor> static typename visitor::result_type apply(int n, const void *data, visitor& v) { if(n == N) return v(*reinterpret_cast<const T*>(data)); else return storage_ops<N + 1, Ts...>::apply(n, data, v); } template<typename visitor> static typename visitor::result_type apply(int n, const void *data, const visitor& v) { if(n == N) return v(*reinterpret_cast<const T*>(data)); else return storage_ops<N + 1, Ts...>::apply(n, data, v); } }; template<int N> struct storage_ops<N> { static void del(int n, void *data) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid."); } static void con(int n, void *data) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } template<typename visitor> static typename visitor::result_type apply(int n, void *data, visitor& v) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } template<typename visitor> static typename visitor::result_type apply(int n, void *data, const visitor& v) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } template<typename visitor> static typename visitor::result_type apply(int n, const void *data, visitor& v) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } template<typename visitor> static typename visitor::result_type apply(int n, const void *data, const visitor& v) { FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." ); } }; template<typename X> struct position<X> { static const int pos = -1; }; template<typename X, typename... Ts> struct position<X, X, Ts...> { static const int pos = 0; }; template<typename X, typename T, typename... Ts> struct position<X, T, Ts...> { static const int pos = position<X, Ts...>::pos != -1 ? position<X, Ts...>::pos + 1 : -1; }; template<typename T, typename... Ts> struct type_at<0, T, Ts...> { using type = T; }; template<int Pos, typename T, typename... Ts> struct type_at<Pos, T, Ts...> { using type = typename type_at<Pos - 1, Ts...>::type; }; template<typename T, typename... Ts> struct type_info<T&, Ts...> { static const bool no_reference_types = false; static const bool no_duplicates = position<T, Ts...>::pos == -1 && type_info<Ts...>::no_duplicates; static const size_t size = type_info<Ts...>::size > sizeof(T&) ? type_info<Ts...>::size : sizeof(T&); static const size_t count = 1 + type_info<Ts...>::count; }; template<typename T, typename... Ts> struct type_info<T, Ts...> { static const bool no_reference_types = type_info<Ts...>::no_reference_types; static const bool no_duplicates = position<T, Ts...>::pos == -1 && type_info<Ts...>::no_duplicates; static const size_t size = type_info<Ts...>::size > sizeof(T) ? type_info<Ts...>::size : sizeof(T&); static const size_t count = 1 + type_info<Ts...>::count; }; template<> struct type_info<> { static const bool no_reference_types = true; static const bool no_duplicates = true; static const size_t count = 0; static const size_t size = 0; }; } // namespace impl template<typename... Types> class static_variant { static_assert(impl::type_info<Types...>::no_reference_types, "Reference types are not permitted in static_variant."); static_assert(impl::type_info<Types...>::no_duplicates, "static_variant type arguments contain duplicate types."); alignas(Types...) char storage[impl::type_info<Types...>::size]; int _tag; template<typename X> void init(X&& x) { _tag = impl::position<std::decay_t<X>, Types...>::pos; new(storage) std::decay_t<X>( std::forward<X>(x) ); } template<typename StaticVariant> friend struct impl::copy_construct; template<typename StaticVariant> friend struct impl::move_construct; public: template<typename X> struct tag { static_assert( impl::position<X, Types...>::pos != -1, "Type not in static_variant." ); static const int value = impl::position<X, Types...>::pos; }; static_variant() { _tag = 0; impl::storage_ops<0, Types...>::con(0, storage); } template<typename... Other> static_variant( const static_variant<Other...>& cpy ) { cpy.visit( impl::copy_construct<static_variant>(*this) ); } static_variant( const static_variant& cpy ) { cpy.visit( impl::copy_construct<static_variant>(*this) ); } static_variant( static_variant&& mv ) { mv.visit( impl::move_construct<static_variant>(*this) ); } template<typename X> static_variant(X&& v) { static_assert( impl::position<std::decay_t<X>, Types...>::pos != -1, "Type not in static_variant." ); init(std::forward<X>(v)); } ~static_variant() { impl::storage_ops<0, Types...>::del(_tag, storage); } template<typename X> static_variant& operator=(const X& v) { static_assert( impl::position<X, Types...>::pos != -1, "Type not in static_variant." ); this->~static_variant(); init(v); return *this; } static_variant& operator=( const static_variant& v ) { if( this == &v ) return *this; this->~static_variant(); v.visit( impl::copy_construct<static_variant>(*this) ); return *this; } static_variant& operator=( static_variant&& v ) { if( this == &v ) return *this; this->~static_variant(); v.visit( impl::move_construct<static_variant>(*this) ); return *this; } friend bool operator == ( const static_variant& a, const static_variant& b ) { return a.which() == b.which(); } friend bool operator < ( const static_variant& a, const static_variant& b ) { return a.which() < b.which(); } template<typename X> X& get() { static_assert( impl::position<X, Types...>::pos != -1, "Type not in static_variant." ); if(_tag == impl::position<X, Types...>::pos) { void* tmp(storage); return *reinterpret_cast<X*>(tmp); } else { FC_THROW_EXCEPTION( fc::assert_exception, "static_variant does not contain a value of type ${t}", ("t",fc::get_typename<X>::name()) ); // std::string("static_variant does not contain value of type ") + typeid(X).name() // ); } } template<typename X> const X& get() const { static_assert( impl::position<X, Types...>::pos != -1, "Type not in static_variant." ); if(_tag == impl::position<X, Types...>::pos) { const void* tmp(storage); return *reinterpret_cast<const X*>(tmp); } else { FC_THROW_EXCEPTION( fc::assert_exception, "static_variant does not contain a value of type ${t}", ("t",fc::get_typename<X>::name()) ); } } template<typename visitor> typename visitor::result_type visit(visitor& v) { return impl::storage_ops<0, Types...>::apply(_tag, storage, v); } template<typename visitor> typename visitor::result_type visit(const visitor& v) { return impl::storage_ops<0, Types...>::apply(_tag, storage, v); } template<typename visitor> typename visitor::result_type visit(visitor& v)const { return impl::storage_ops<0, Types...>::apply(_tag, storage, v); } template<typename visitor> typename visitor::result_type visit(const visitor& v)const { return impl::storage_ops<0, Types...>::apply(_tag, storage, v); } static uint32_t count() { return impl::type_info<Types...>::count; } void set_which( uint32_t w ) { FC_ASSERT( w < count() ); this->~static_variant(); try { _tag = w; impl::storage_ops<0, Types...>::con(_tag, storage); } catch ( ... ) { _tag = 0; impl::storage_ops<0, Types...>::con(_tag, storage); } } int which() const {return _tag;} template<typename X> bool contains() const { return which() == tag<X>::value; } template<typename X> static constexpr int position() { return impl::position<X, Types...>::pos; } template<int Pos, std::enable_if_t<Pos < impl::type_info<Types...>::size,int> = 1> using type_at = typename impl::type_at<Pos, Types...>::type; }; template<typename Result> struct visitor { typedef Result result_type; }; struct from_static_variant { variant& var; from_static_variant( variant& dv ):var(dv){} typedef void result_type; template<typename T> void operator()( const T& v )const { to_variant( v, var ); } }; struct to_static_variant { const variant& var; to_static_variant( const variant& dv ):var(dv){} typedef void result_type; template<typename T> void operator()( T& v )const { from_variant( var, v ); } }; template<typename... T> void to_variant( const fc::static_variant<T...>& s, fc::variant& v ) { variant tmp; variants vars(2); vars[0] = s.which(); s.visit( from_static_variant(vars[1]) ); v = std::move(vars); } template<typename... T> void from_variant( const fc::variant& v, fc::static_variant<T...>& s ) { auto ar = v.get_array(); if( ar.size() < 2 ) return; s.set_which( ar[0].as_uint64() ); s.visit( to_static_variant(ar[1]) ); } template<typename... T> struct get_typename { static const char* name() { return BOOST_CORE_TYPEID(static_variant<T...>).name(); } }; } // namespace fc
a6b27981c5075ccd7d7464d03a66748583471e40
323f1525b0e62062bd0c355075a3e961d41ce498
/TRICKTRT.cpp
83d5c114f0904b74437bd50e3ca6d8d8c077a16d
[]
no_license
kushagrasingh/Spoj
0572c243e32345bb87c118cc249b04e5b713df7d
52b5882b176c77bf1f4e250c2f5401542babdbbf
refs/heads/master
2020-05-17T20:34:21.589398
2014-05-30T08:20:22
2014-05-30T08:20:22
20,227,745
0
0
null
null
null
null
UTF-8
C++
false
false
1,461
cpp
#include <cstdio> #include <cmath> typedef struct { double x, y; } Point; const int MAX = 50000; const double EPS = 1e-12; Point P[MAX]; int n; inline double distsq(const Point &a, const Point &b) { return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); } double cost(double x) { Point p = {x, 0}; double dist, mx = 0.0; for(int i = 0; i < n; i++) { dist = distsq(p, P[i]); if(dist > mx) mx = dist; } return mx; } double ternary(double lt, double rt) { int cnt = 64; double ltthrd, rtthrd; while(cnt--) { ltthrd = (2.0 * lt + rt) / 3.0; rtthrd = (lt + 2.0 * rt) / 3.0; if(cost(ltthrd) < cost(rtthrd)) rt = rtthrd; else lt = ltthrd; } return (lt + rt) / 2.0; } int main() { double xmax, xmin, xsol; while(scanf("%d", &n) == 1 && n) { for(int i = 0; i < n; i++) { scanf("%lf %lf", &P[i].x, &P[i].y); if(!i) xmax = xmin = P[i].x; else { if(xmax < P[i].x) xmax = P[i].x; if(xmin > P[i].x) xmin = P[i].x; } } xsol = ternary(xmin, xmax); printf("%.9lf %.9lf\n", xsol + EPS, sqrt(cost(xsol)) + EPS); } return 0; }
532fcdd5c33c431dd56de4c8f8119ac5e7271bd2
f7bdcfeb1e7d4e95837c326ee4d0c1e65bddeb75
/upsilon-eventgen-simplified/Lcore.h
db318640febaf2209598131cc9f3305c7ba72782
[]
no_license
Gregtom3/VM_Subthreshold
132841dfd9b4245692c30e13afeaa483f0922705
2f12a18198c82f82afe319b489e7600a59ca48d6
refs/heads/main
2023-06-27T04:46:59.619916
2021-07-20T16:59:29
2021-07-20T16:59:29
364,624,996
0
0
null
null
null
null
UTF-8
C++
false
false
16,647
h
#ifndef _LCORE_H_ #define _LCORE_H_ #include <iostream> #include <fstream> #include <cmath> #include <gsl/gsl_integration.h> #include "TROOT.h" #include "TStyle.h" //#include "TSystem.h" #include "TString.h" #include "TRandom.h" #include "TRandom3.h" #include "TGenPhaseSpace.h" #include "TLorentzVector.h" #include "TFile.h" //#include "TTree.h" #include "TF1.h" #include "Math/Functor.h" #include "Math/WrappedTF1.h" #include "Math/GSLIntegrator.h" #include "Math/Interpolator.h" #include "Math/WrappedParamFunction.h" #include "Math/Integrator.h" #include "Math/IntegratorMultiDim.h" #include "Math/AllIntegrationTypes.h" #include "Math/SpecFuncMathCore.h" #include "TCanvas.h" #include "TH1D.h" #include "TH2D.h" #include "TH3D.h" #include "TH2F.h" #include "TH3F.h" #include "TF1.h" #include "TGraph.h" #include "TGraph2D.h" #include "TLegend.h" #include "Lparticle.h" using namespace std; using namespace ROOT; const double Mp = PARTICLE::proton.M(); namespace NUCLEAR{ int flag = 0; double A = 1.0; double Z = 1.0; double (* fMomentum)(const double * p0, const double * par); double (* fEnergy)(const double * E0, const double * par); double Momentum_D(const double * p0, const double * par){//non-normalized double p = p0[0]; double a = 0.0456; double b = 0.2719; double result = pow(1.0 / (p * p + a * a) - 1.0 / (p * p + b * b), 2);//C. Weiss 2014 return p * p * result; } int SetNuclear(const char * nuclear = "p"){ flag = 1; if (strcmp(nuclear, "D") == 0){ flag = 2; fMomentum = &Momentum_D; } else { cout << "No matching nuclear! Set to proton!" << endl; flag = 0; } return 0; } } namespace UPSILONMODEL{//Model of Upsilon (1S) production //Heavily inspired by the source code of the lAger event generator (see https://eicweb.phy.anl.gov/monte_carlo/lager/-/blob/master/src/lager/gen/lA/oleksii_2vmp.cc) // Relevant source paper https://journals.aps.org/prd/abstract/10.1103/PhysRevD.102.014016 int vflag = 1; const double Mv = 9.46030; //https://pdg.lbl.gov/2014/listings/rpp2014-list-upsilon-1S.pdf const double Mp = 0.938272; const double C_el = 13.8e-3; const double nu_el = 8.88; const double b_el = 1.27; const double a_el = 1.38; const double C_inel = 18.7; const double nu_inel = 20.90; const double b_inel = 3.53; const double a_inel = 1.2; const double f = 0.238; const double alpha = 1./137.; const double e = sqrt(4.0*M_PI*alpha); // electric charge const double epsilon = 0.0001; const double numax = 2000000.0; // maximum bound for infinite integration const double khbar = 4.135667662e-15 / TMath::TwoPi(); // Speed of light (m/s) const double kc = 299792458.; // hhbarc (fm * GeV) const double khbarc = khbar * kc * 1e6; // khbarc2 (nb * GeV^2, using 1fm^2 = 10mb^2 =1e7nb^2) const double khbarc2 = khbarc * khbarc * 1e7; TF1 *_f1 = 0; // gsl workspace for integration of Dispersion integral gsl_integration_workspace * _w = gsl_integration_workspace_alloc(2048); gsl_function _F; // Event variables double eventb0=0.0; double eventB=0.0; double eventA=0.0; double ImaginaryT(const double s){ double nu = 0.5*(s-Mp*Mp-Mv*Mv); double Disc_el = 0.0; double Disc_inel = 0.0; if(nu>nu_el) Disc_el = C_el*pow(1.0-nu_el/nu,b_el)*pow(nu/nu_el,a_el); if(nu>nu_inel) Disc_inel = C_inel*pow(1.0-nu_inel/nu,b_inel)*pow(nu/nu_inel,a_inel); return Disc_el+Disc_inel; } double ImaginaryT_nu(const double nu){ double Disc_el = 0.0; double Disc_inel = 0.0; if(nu>nu_el) Disc_el = C_el*pow(1.0-nu_el/nu,b_el)*pow(nu/nu_el,a_el); if(nu>nu_inel) Disc_inel = C_inel*pow(1.0-nu_inel/nu,b_inel)*pow(nu/nu_inel,a_inel); return Disc_el+Disc_inel; } double dispersion_integral(double x, void *p) { double nuPRIME = x; double nu = *(double *) p; double s = 2*nu + Mp*Mp + Mv*Mv; return (ImaginaryT_nu(nuPRIME)/nuPRIME - ImaginaryT_nu(nu)/nu)/((nuPRIME*nuPRIME-nu*nu)); } double RealT(const double s){ double nu = 0.5*(s-Mp*Mp-Mv*Mv); double T0 = 20.5; // Can be set to 0, 20.5, or 87, see paper for details _F.params = &nu; double result, error; gsl_integration_qagiu(&_F, nu_el, 0, 1e-8, 2048, _w, &result, &error); result+= ImaginaryT(nu)/nu * std::log(std::fabs((nu_el+nu)/(nu_el-nu))) / (2 * nu); return T0 + 2.0/M_PI * nu*nu * result; } double B(double *xx, double *par) { double b = xx[0]; double tmin = par[0]; double tmax = par[1]; double sigma = par[2]; double A = par[3]; return (b - A*exp(b*tmax)/sigma + A*exp(b*tmin)/sigma); } double (*dSigmaY1S)(const double, const double); // W , t double tmax(const double Mv, const double Mp, const double W) { double s = W*W; double qvp = sqrt((0.25/s)*(s-pow(Mv+Mp,2))*(s-pow(Mv-Mp,2))); double qgp = (s-Mp*Mp)/(2.0*sqrt(s)); return Mv * Mv -2.0 * qgp * ( sqrt ( qvp * qvp + Mv * Mv ) - qvp ); // less negative } double tmin(const double Mv, const double Mp, const double W) { double s = W*W; double qvp = sqrt((0.25/s)*(s-pow(Mv+Mp,2))*(s-pow(Mv-Mp,2))); double qgp = (s-Mp*Mp)/(2.0*sqrt(s)); return Mv * Mv -2.0 * qgp * ( sqrt ( qvp * qvp + Mv * Mv ) + qvp ); // more negative } void set_B(const double Mv, const double Mp, const double W) { double s = W*W; double nu = 0.5*(s-Mp*Mp-Mv*Mv); double qvp = sqrt((0.25/s)*(s-pow(Mv+Mp,2))*(s-pow(Mv-Mp,2))); double qgp = (s-Mp*Mp)/(2.0*sqrt(s)); double coeff = pow(e*f/Mv,2)/(64.0*M_PI*s*qgp*qgp); double ReT = RealT(s); double ImT = ImaginaryT(s); double dodt_t0 = coeff * (ReT*ReT + ImT*ImT) * 3.89e5; // units nb/GeV^2 double A = dodt_t0; double tmin_ = tmin(Mv,Mp,W); double tmax_ = tmax(Mv,Mp,W); double sigma_el = (std::pow(e * f / Mv, 2) * 1 / (2 * W * qgp) * (qvp / qgp) * C_el * std::pow(1 - nu_el / nu, b_el) * std::pow(nu / nu_el, a_el) * khbarc2); // units nb _f1->SetParameters(tmin_,tmax_,sigma_el,A); double B = _f1->GetX(0.0,0.5,10); // units 1/GeV^2 // Set the event A and event B eventA = A; eventB = B; } void set_b0() { double W = (Mv+Mp)*(1.05); double s = W*W; double nu = 0.5*(s-Mp*Mp-Mv*Mv); double qvp = sqrt((0.25/s)*(s-pow(Mv+Mp,2))*(s-pow(Mv-Mp,2))); double qgp = (s-Mp*Mp)/(2.0*sqrt(s)); double coeff = pow(e*f/Mv,2)/(64.0*M_PI*s*qgp*qgp); double ReT = RealT(s); double ImT = ImaginaryT(s); double dodt_t0 = coeff * (ReT*ReT + ImT*ImT) * 3.89e5; // units nb/GeV^2 double A = dodt_t0; double tmin_ = tmin(Mv,Mp,W); double tmax_ = tmax(Mv,Mp,W); double sigma_el = (std::pow(e * f / Mv, 2) * 1 / (2 * W * qgp) * (qvp / qgp) * C_el * std::pow(1 - nu_el / nu, b_el) * std::pow(nu / nu_el, a_el) * khbarc2); // units nb _f1->SetParameters(tmin_,tmax_,sigma_el,A); double b0 = _f1->GetX(0.0,0.5,10); // units 1/GeV^2 // Set the event b0 eventb0 = b0; } double dSigmaY1S_v1(const double W, const double t){ set_B(Mv,Mp,W); return eventA * exp(eventB*t); // units nb/GeV^2 } double dSigmaY1S_v2(const double W, const double t){ double jac = exp(-eventb0*t)/eventb0; return eventA*exp(eventB*t) * jac; // dsigma_dexp_b0t } int SetModel(const char * model = "v1"){ if (strcmp(model, "v1") == 0) { vflag = 1; dSigmaY1S = &dSigmaY1S_v1; _f1 = new TF1("B_func",B,0,10,4); _F.function = &dispersion_integral; } else if (strcmp(model, "v2") == 0) { vflag = 2; dSigmaY1S = &dSigmaY1S_v2; set_b0(); _f1 = new TF1("B_func",B,0,10,4); _F.function = &dispersion_integral; } else { cout << "No matching model! Set to v1 model!" << endl; dSigmaY1S = &dSigmaY1S_v1; vflag = 1; } return 0; } } namespace GENERATE{ TRandom3 random(0); TGenPhaseSpace GenPhase; double Weight = 0.0; TF1 * TF_fBremsstrahlung; TF1 * TF_fMomentum; TF1 * TF_fEnergy; bool do_PomLQCD = false; /* Bremsstrahlung photon */ int fail = 0; /* Nucleon from a nuclear target */ double GetNucleon(TLorentzVector * P){ if (NUCLEAR::flag > 0){ double p = TF_fMomentum->GetRandom(); double cth = random.Uniform(-1.0, 1.0); double phi = random.Uniform(-M_PI, M_PI); double sth = sqrt(1.0 - cth * cth); if (NUCLEAR::flag == 1){ double dE = TF_fEnergy->GetRandom(); P->SetXYZT(p * sth * cos(phi), p * sth * sin(phi), p * cth, sqrt(p * p + Mp * Mp) - dE); } else {//flag = 2, deuteron double E = 2.0 * Mp - sqrt(Mp * Mp + p * p); P->SetXYZT(p * sth * cos(phi), p * sth * sin(phi), p * cth, E); } } else //flag = 0, proton P->SetXYZT(0.0, 0.0, 0.0, Mp); return 1.0; } double cthrange[2] = {-1.0, 1.0}; double perange[2] = {0.0, 10.0}; /* Added 5/19/2021 for Upsilon Production Model based on Slyvester */ double Q2range[2] = {0.0, 10.0}; double Wrange[2] = {0.0, 9999.0}; double trange[2] = {-100.0, 0.0}; double yrange[2] = {0.1,0.8}; double VirtualPhoton(TLorentzVector * ki, TLorentzVector * kf){ //ki: e, N; kf: e', gamma double m = PARTICLE::e.M(); double mp = ki[1].M(); double mY = PARTICLE::upsilon1S.M(); // Step 1.) Select event Q2, y double Q2 = random.Uniform(Q2range[0],Q2range[1]); // double W2 = random.Uniform(pow(Wrange[0],2),pow(Wrange[1],2)); double y = random.Uniform(yrange[0],yrange[1]); // Step 2.) Boost both e & N into "N" rest frame where the kinematics are easier TVector3 beta = ki[1].BoostVector(); ki[0].Boost(-beta); ki[1].Boost(-beta); // Step 2.5) Rotate the vectors such that the z direction points along ki[0]'s momentum TVector3 direction(1.0,0,0); direction.SetPhi(ki[0].Phi()); direction.SetTheta(ki[0].Theta()/2.0); ki[0].Rotate(M_PI,direction); // Step 3.) Calculate the energy, momentum, etc. of the scattered e- and gamma* double _Ee = ki[0].E(); double W2 = (2 * ki[1].M() * _Ee * y - Q2 + ki[1].M()*ki[1].M()); double _Eg = (W2 - mp * mp + Q2) / ( 2.0 * mp); double _Eeprime = _Ee - _Eg; if(_Eeprime < 0) { return 0; // impossible event } if ((W2 < mp * mp) || (sqrt(W2) < Wrange[0]) || (sqrt(W2) > Wrange[1])) { return 0;//below the lowest state } double _Pe = sqrt(_Ee*_Ee - m * m); double _Peprime = sqrt(_Eeprime*_Eeprime - m * m); double _th = M_PI-std::acos((-Q2 - 2 * m * m + 2 * _Ee * _Eeprime) / (2 * _Pe * _Peprime)); if(isnan(_th)) { return 0; } double _cth= cos(_th); double _sth = sqrt(1.0 - _cth * _cth); double _phi = random.Uniform(-M_PI, M_PI); kf[0].SetXYZM(_Peprime * _sth * cos(_phi) , _Peprime * _sth * sin(_phi) , -_Peprime * _cth, m);//e' in "N" rest frame kf[1] = ki[0]-kf[0]; // virtual photon in "N" rest frame // Step 3.5) Unrotate the vectors ki[0].Rotate(M_PI,direction); kf[0].Rotate(M_PI,direction); kf[1].Rotate(M_PI,direction); // Step 4.) Boost back into originial frame ki[0].Boost(beta); ki[1].Boost(beta); kf[0].Boost(beta); kf[1].Boost(beta); double alpha_em = 1.0 / 137.0; // double volume = 2.0 * M_PI * abs(Q2range[1] - Q2range[0]) * abs(yrange[1] - yrange[0]); double gy = ki[1].M() * sqrt(Q2) / (ki[1] * ki[0]); double epsilon = (1.0 - y - 0.25 * gy * gy) / (1.0 - y + 0.5 * y * y + 0.25 * gy * gy); double dipole = pow((mY*mY)/(Q2+mY*mY),2.575); // Equation A4 double R = pow((2.164*mY*mY + Q2)/(2.164*mY*mY),2.131) - 1.0; double gammaT = alpha_em/(2*M_PI)*(1.0+pow(1.0-y,2))/(y*Q2); return (1.0 + epsilon * R) * dipole * gammaT; } /* Upsilon1S productions */ double Upsilon1SElectroproduction(TLorentzVector * ki, TLorentzVector *kf){ //ki: e, N; kf: e', Psi2S, N' double weight1 = VirtualPhoton(ki, kf);//Generate scattered electron if (weight1 == 0) return 0; double mp = ki[1].M(); TLorentzVector Pout = kf[1] + ki[1]; // q + N double W = Pout.M(); double W2 = W * W; double Q2 = -(kf[1]*kf[1]); double Mup = PARTICLE::upsilon1S.RandomM(); if (W < Mup + Mp) { return 0; //below the threshold } // Step 1.) Set & Get the b0 & B for the event UPSILONMODEL::set_B(Mup,mp,W); double B = UPSILONMODEL::eventB; double b0 = UPSILONMODEL::eventb0; // Step 2.) Generate a t value within the range from a distribution // v1 --> Uniform // v2 --> Expontential double t = 0.0; if(UPSILONMODEL::vflag == 1) t = random.Uniform(trange[0],trange[1]); else if(UPSILONMODEL::vflag == 2) t = (1.0/b0)*std::log(random.Uniform(exp(b0*trange[0]),exp(b0*trange[1]))); // Step 3.) Calculate beta s.t. we boost into the q + N rest C.O.M frame TVector3 beta = Pout.BoostVector(); // Step 3.5) Calculate axis of rotation such that final state particles are created in a frame where "p" lies along the z-axis ki[1].Boost(-beta); kf[1].Boost(-beta); TVector3 direction(1.0,0,0); direction.SetPhi(ki[1].Phi()); direction.SetTheta(ki[1].Theta()/2.0); kf[1].Boost(beta); ki[1].Boost(beta); // Step 4.) Calculate the final state particles in the C.O.M frame // From lAger's code // t --> "target" // r --> "recoil" // v --> "vector meson" const double Et_cm = (W2 + Q2 + mp*mp) / (2. * W); const double Pt_cm = sqrt(Et_cm * Et_cm - mp*mp); const double Er_cm = (W2 - Mup*Mup + Mp*Mp) / (2. * W); const double Pr_cm = sqrt(Er_cm * Er_cm - Mp*Mp); const double Ev_cm = (W2 + Mup*Mup - Mp*Mp) / (2. * W); const double Pv_cm = sqrt(Ev_cm * Ev_cm - Mup*Mup); // Step 5.) From the generated "t", get the "theta" of the scattered p in this frame const double ctheta_cm = (t + 2 * Et_cm * Er_cm - mp * mp - Mp * Mp) / (2 * Pt_cm * Pr_cm); if(ctheta_cm>1.0||ctheta_cm<-1.0) { return 0; } const double theta_cm = std::acos(ctheta_cm); const double phi_cm = random.Uniform(0, TMath::TwoPi()); const double stheta_cm = sqrt(1.0 - ctheta_cm * ctheta_cm); const double theta_cm2 = TMath::Pi() - theta_cm; const double ctheta_cm2 = std::cos(theta_cm2); const double stheta_cm2 = std::sin(theta_cm2); // Step 6.) Set the VM and p' in this C.O.M frame kf[1].SetXYZM(Pv_cm * stheta_cm2 * cos(phi_cm), Pv_cm * stheta_cm2 * sin(phi_cm), Pv_cm * ctheta_cm2, Mup); kf[2].SetXYZM(-Pr_cm * stheta_cm * cos(phi_cm), Pr_cm * stheta_cm * sin(-phi_cm), Pr_cm * ctheta_cm, Mp); // Step 6.5) Rotate the VM and p' such that p is on the z-axis kf[1].Rotate(M_PI,direction); kf[2].Rotate(M_PI,direction); // Step 7.) Boost these particles back into the original frame kf[1].Boost(beta); kf[2].Boost(beta); // double volume = exp(b0*trange[1])-exp(b0*trange[0]); // Need to include flux factor because of moving target in this frame? // double weight2 = UPSILONMODEL::dSigmaY1S(W,t); return weight1*weight2; } double Event_eN2eNee_Upsilon1S(TLorentzVector * ki, TLorentzVector * kf){ //ki: e, N; kf: e', N', [e+, e-] TLorentzVector kf1[3];//e', Y1S, N' double weight = Upsilon1SElectroproduction(ki, kf1); kf[0] = kf1[0];//e' kf[1] = kf1[2];//N' double mass[2] = {PARTICLE::e.M(), PARTICLE::e.M()}; GenPhase.SetDecay(kf1[1], 2, mass); GenPhase.Generate(); kf[2] = *GenPhase.GetDecay(0);//e+ kf[3] = *GenPhase.GetDecay(1);//e- double Mup = kf1[1].M(); double Ep = kf1[2] * kf1[1] / Mup;//recoil proton energy in Upsilon1S rest frame double p = sqrt(Ep * Ep - Mp * Mp);//recoil proton momentum in Upsilon1S rest frame double l = sqrt(pow(Mup * Mup - kf[2] * kf[2] - kf[3] * kf[3], 2) - 4.0 * (kf[2] * kf[2]) * (kf[3] * kf[3])) / (2.0 * Mup);//decayed lepton momentum in Upsilon1S rest frame double cth = (Ep * Mup / 2.0 - kf[2] * kf[1]) / (p * l);//cos(theta) between final lepton and final proton in Upsilon1S rest frame double y = (ki[0].E() - kf[0].E()) / ki[0].E(); double Q2 = - (ki[0] - kf[0]) * (ki[0] - kf[0]); double gy = sqrt(Q2) / ki[0].E(); double epsilon = (1.0 - y - 0.25 * gy * gy) / (1.0 - y + 0.5 * y * y + 0.25 * gy * gy); double R = pow(1.0 + Q2 / 2.164 / pow(Mup,2), 2.131) - 1.0; double r = epsilon * R / (1.0 + epsilon * R); double wth = 3.0 / 4.0 * (1.0 + r + (1.0 - 3.0 * r) * pow(cth,2)); double branch = 2.38e-2;//Branch ratio to e+e- (Y1S) return weight * wth * branch; } } #endif
aa1cb52ed2e7c19552339386533c301b49309ac6
72a08996beb7ba253ba9f6a03dbe00651aa3f835
/Source/Urho3D/Graphics/Light.cpp
353cb7714072f182597c2e267df5152af5ab1c35
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
whztt07/rbfx
3da41e3e8a9d29e9480fde40abd7475b3636c8c1
ddf22512edf17c7ca3282c3216ef78fc00a53ef0
refs/heads/master
2020-04-16T06:23:08.390059
2019-01-05T11:39:33
2019-01-05T11:39:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,358
cpp
// // Copyright (c) 2008-2018 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "../Precompiled.h" #include "../Core/Context.h" #include "../Core/Profiler.h" #include "../Graphics/Camera.h" #include "../Graphics/DebugRenderer.h" #include "../Graphics/Graphics.h" #include "../Graphics/Light.h" #include "../Graphics/OctreeQuery.h" #include "../Graphics/Texture2D.h" #include "../Graphics/TextureCube.h" #include "../IO/Log.h" #include "../Resource/ResourceCache.h" #include "../Scene/Node.h" #include "../DebugNew.h" namespace Urho3D { extern const char* SCENE_CATEGORY; static const char* typeNames[] = { "Directional", "Spot", "Point", nullptr }; void BiasParameters::Validate() { constantBias_ = Clamp(constantBias_, -1.0f, 1.0f); slopeScaledBias_ = Clamp(slopeScaledBias_, -16.0f, 16.0f); normalOffset_ = Max(normalOffset_, 0.0f); } void CascadeParameters::Validate() { for (unsigned i = 0; i < MAX_CASCADE_SPLITS; ++i) splits_[i] = Max(splits_[i], 0.0f); fadeStart_ = Clamp(fadeStart_, M_EPSILON, 1.0f); } void FocusParameters::Validate() { quantize_ = Max(quantize_, SHADOW_MIN_QUANTIZE); minView_ = Max(minView_, SHADOW_MIN_VIEW); } Light::Light(Context* context) : Drawable(context, DRAWABLE_LIGHT), lightType_(DEFAULT_LIGHTTYPE), shadowBias_(BiasParameters(DEFAULT_CONSTANTBIAS, DEFAULT_SLOPESCALEDBIAS)), shadowCascade_(CascadeParameters(DEFAULT_SHADOWSPLIT, 0.0f, 0.0f, 0.0f, DEFAULT_SHADOWFADESTART)), shadowFocus_(FocusParameters(true, true, true, DEFAULT_SHADOWQUANTIZE, DEFAULT_SHADOWMINVIEW)), lightQueue_(nullptr), temperature_(DEFAULT_TEMPERATURE), lightRad_(DEFAULT_RADIUS), lightLength_(DEFAULT_LENGTH), specularIntensity_(DEFAULT_SPECULARINTENSITY), brightness_(DEFAULT_BRIGHTNESS), range_(DEFAULT_RANGE), fov_(DEFAULT_LIGHT_FOV), aspectRatio_(1.0f), fadeDistance_(0.0f), shadowFadeDistance_(0.0f), shadowIntensity_(0.0f), shadowResolution_(1.0f), shadowNearFarRatio_(DEFAULT_SHADOWNEARFARRATIO), shadowMaxExtrusion_(DEFAULT_SHADOWMAXEXTRUSION), perVertex_(false), usePhysicalValues_(false) { } Light::~Light() = default; void Light::RegisterObject(Context* context) { context->RegisterFactory<Light>(SCENE_CATEGORY); URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT); URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Light Type", GetLightType, SetLightType, LightType, typeNames, DEFAULT_LIGHTTYPE, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Color", GetColor, SetColor, Color, Color::WHITE, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Specular Intensity", GetSpecularIntensity, SetSpecularIntensity, float, DEFAULT_SPECULARINTENSITY, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Brightness Multiplier", GetBrightness, SetBrightness, float, DEFAULT_BRIGHTNESS, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Temperature", GetTemperature, SetTemperature, float, DEFAULT_TEMPERATURE, AM_DEFAULT); URHO3D_ATTRIBUTE("Use Physical Values", bool, usePhysicalValues_, false, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Radius", GetRadius, SetRadius, float, DEFAULT_RADIUS, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Length", GetLength, SetLength, float, DEFAULT_LENGTH, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Range", GetRange, SetRange, float, DEFAULT_RANGE, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Spot FOV", GetFov, SetFov, float, DEFAULT_LIGHT_FOV, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Spot Aspect Ratio", GetAspectRatio, SetAspectRatio, float, 1.0f, AM_DEFAULT); URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Attenuation Texture", GetRampTextureAttr, SetRampTextureAttr, ResourceRef, ResourceRef(Texture2D::GetTypeStatic()), AM_DEFAULT); URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Light Shape Texture", GetShapeTextureAttr, SetShapeTextureAttr, ResourceRef, ResourceRef(Texture2D::GetTypeStatic()), AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT); URHO3D_ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT); URHO3D_ATTRIBUTE("Per Vertex", bool, perVertex_, false, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Fade Distance", GetFadeDistance, SetFadeDistance, float, 0.0f, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Shadow Fade Distance", GetShadowFadeDistance, SetShadowFadeDistance, float, 0.0f, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Shadow Intensity", GetShadowIntensity, SetShadowIntensity, float, 0.0f, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Shadow Resolution", GetShadowResolution, SetShadowResolution, float, 1.0f, AM_DEFAULT); URHO3D_ATTRIBUTE_EX("Focus To Scene", bool, shadowFocus_.focus_, ValidateShadowFocus, true, AM_DEFAULT); URHO3D_ATTRIBUTE_EX("Non-uniform View", bool, shadowFocus_.nonUniform_, ValidateShadowFocus, true, AM_DEFAULT); URHO3D_ATTRIBUTE_EX("Auto-Reduce Size", bool, shadowFocus_.autoSize_, ValidateShadowFocus, true, AM_DEFAULT); URHO3D_ATTRIBUTE_EX("CSM Splits", Vector4, shadowCascade_.splits_, ValidateShadowCascade, Vector4(DEFAULT_SHADOWSPLIT, 0.0f, 0.0f, 0.0f), AM_DEFAULT); URHO3D_ATTRIBUTE_EX("CSM Fade Start", float, shadowCascade_.fadeStart_, ValidateShadowCascade, DEFAULT_SHADOWFADESTART, AM_DEFAULT); URHO3D_ATTRIBUTE_EX("CSM Bias Auto Adjust", float, shadowCascade_.biasAutoAdjust_, ValidateShadowCascade, DEFAULT_BIASAUTOADJUST, AM_DEFAULT); URHO3D_ATTRIBUTE_EX("View Size Quantize", float, shadowFocus_.quantize_, ValidateShadowFocus, DEFAULT_SHADOWQUANTIZE, AM_DEFAULT); URHO3D_ATTRIBUTE_EX("View Size Minimum", float, shadowFocus_.minView_, ValidateShadowFocus, DEFAULT_SHADOWMINVIEW, AM_DEFAULT); URHO3D_ATTRIBUTE_EX("Depth Constant Bias", float, shadowBias_.constantBias_, ValidateShadowBias, DEFAULT_CONSTANTBIAS, AM_DEFAULT); URHO3D_ATTRIBUTE_EX("Depth Slope Bias", float, shadowBias_.slopeScaledBias_, ValidateShadowBias, DEFAULT_SLOPESCALEDBIAS, AM_DEFAULT); URHO3D_ATTRIBUTE_EX("Normal Offset", float, shadowBias_.normalOffset_, ValidateShadowBias, DEFAULT_NORMALOFFSET, AM_DEFAULT); URHO3D_ATTRIBUTE("Near/Farclip Ratio", float, shadowNearFarRatio_, DEFAULT_SHADOWNEARFARRATIO, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Max Extrusion", GetShadowMaxExtrusion, SetShadowMaxExtrusion, float, DEFAULT_SHADOWMAXEXTRUSION, AM_DEFAULT); URHO3D_ATTRIBUTE("View Mask", int, viewMask_, DEFAULT_VIEWMASK, AM_DEFAULT); URHO3D_ATTRIBUTE("Light Mask", int, lightMask_, DEFAULT_LIGHTMASK, AM_DEFAULT); } void Light::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results) { // Do not record a raycast result for a directional light, as it would block all other results if (lightType_ == LIGHT_DIRECTIONAL) return; float distance = query.maxDistance_; switch (query.level_) { case RAY_AABB: Drawable::ProcessRayQuery(query, results); return; case RAY_OBB: { Matrix3x4 inverse(node_->GetWorldTransform().Inverse()); Ray localRay = query.ray_.Transformed(inverse); distance = localRay.HitDistance(GetWorldBoundingBox().Transformed(inverse)); if (distance >= query.maxDistance_) return; } break; case RAY_TRIANGLE: if (lightType_ == LIGHT_SPOT) { distance = query.ray_.HitDistance(GetFrustum()); if (distance >= query.maxDistance_) return; } else { distance = query.ray_.HitDistance(Sphere(node_->GetWorldPosition(), range_)); if (distance >= query.maxDistance_) return; } break; case RAY_TRIANGLE_UV: URHO3D_LOGWARNING("RAY_TRIANGLE_UV query level is not supported for Light component"); return; } // If the code reaches here then we have a hit RayQueryResult result; result.position_ = query.ray_.origin_ + distance * query.ray_.direction_; result.normal_ = -query.ray_.direction_; result.distance_ = distance; result.drawable_ = this; result.node_ = node_; result.subObject_ = M_MAX_UNSIGNED; results.Push(result); } void Light::UpdateBatches(const FrameInfo& frame) { switch (lightType_) { case LIGHT_DIRECTIONAL: // Directional light affects the whole scene, so it is always "closest" distance_ = 0.0f; break; default: distance_ = frame.camera_->GetDistance(node_->GetWorldPosition()); break; } } void Light::DrawDebugGeometry(DebugRenderer* debug, bool depthTest) { Color color = GetEffectiveColor(); if (debug && IsEnabledEffective()) { switch (lightType_) { case LIGHT_DIRECTIONAL: { Vector3 start = node_->GetWorldPosition(); Vector3 end = start + node_->GetWorldDirection() * 10.f; for (int i = -1; i < 2; ++i) { for (int j = -1; j < 2; ++j) { Vector3 offset = Vector3::UP * (5.f * i) + Vector3::RIGHT * (5.f * j); debug->AddSphere(Sphere(start + offset, 0.1f), color, depthTest); debug->AddLine(start + offset, end + offset, color, depthTest); } } } break; case LIGHT_SPOT: debug->AddFrustum(GetFrustum(), color, depthTest); break; case LIGHT_POINT: debug->AddSphere(Sphere(node_->GetWorldPosition(), range_), color, depthTest); break; } } } void Light::SetLightType(LightType type) { lightType_ = type; OnMarkedDirty(node_); MarkNetworkUpdate(); } void Light::SetPerVertex(bool enable) { perVertex_ = enable; MarkNetworkUpdate(); } void Light::SetColor(const Color& color) { color_ = Color(color.r_, color.g_, color.b_, 1.0f); MarkNetworkUpdate(); } void Light::SetTemperature(float temperature) { temperature_ = Clamp(temperature, 1000.0f, 10000.0f); MarkNetworkUpdate(); } void Light::SetRadius(float radius) { lightRad_ = radius; MarkNetworkUpdate(); } void Light::SetLength(float length) { lightLength_ = length; MarkNetworkUpdate(); } void Light::SetUsePhysicalValues(bool enable) { usePhysicalValues_ = enable; MarkNetworkUpdate(); } void Light::SetSpecularIntensity(float intensity) { specularIntensity_ = Max(intensity, 0.0f); MarkNetworkUpdate(); } void Light::SetBrightness(float brightness) { brightness_ = brightness; MarkNetworkUpdate(); } void Light::SetRange(float range) { range_ = Max(range, 0.0f); OnMarkedDirty(node_); MarkNetworkUpdate(); } void Light::SetFov(float fov) { fov_ = Clamp(fov, 0.0f, M_MAX_FOV); OnMarkedDirty(node_); MarkNetworkUpdate(); } void Light::SetAspectRatio(float aspectRatio) { aspectRatio_ = Max(aspectRatio, M_EPSILON); OnMarkedDirty(node_); MarkNetworkUpdate(); } void Light::SetShadowNearFarRatio(float nearFarRatio) { shadowNearFarRatio_ = Clamp(nearFarRatio, 0.0f, 0.5f); MarkNetworkUpdate(); } void Light::SetShadowMaxExtrusion(float extrusion) { shadowMaxExtrusion_ = Max(extrusion, 0.0f); MarkNetworkUpdate(); } void Light::SetFadeDistance(float distance) { fadeDistance_ = Max(distance, 0.0f); MarkNetworkUpdate(); } void Light::SetShadowBias(const BiasParameters& parameters) { shadowBias_ = parameters; shadowBias_.Validate(); MarkNetworkUpdate(); } void Light::SetShadowCascade(const CascadeParameters& parameters) { shadowCascade_ = parameters; shadowCascade_.Validate(); MarkNetworkUpdate(); } void Light::SetShadowFocus(const FocusParameters& parameters) { shadowFocus_ = parameters; shadowFocus_.Validate(); MarkNetworkUpdate(); } void Light::SetShadowFadeDistance(float distance) { shadowFadeDistance_ = Max(distance, 0.0f); MarkNetworkUpdate(); } void Light::SetShadowIntensity(float intensity) { shadowIntensity_ = Clamp(intensity, 0.0f, 1.0f); MarkNetworkUpdate(); } void Light::SetShadowResolution(float resolution) { shadowResolution_ = Clamp(resolution, 0.125f, 1.0f); MarkNetworkUpdate(); } void Light::SetRampTexture(Texture* texture) { rampTexture_ = texture; MarkNetworkUpdate(); } void Light::SetShapeTexture(Texture* texture) { shapeTexture_ = texture; MarkNetworkUpdate(); } Color Light::GetColorFromTemperature() const { // Approximate Planckian locus in CIE 1960 UCS float u = (0.860117757f + 1.54118254e-4f * temperature_ + 1.28641212e-7f * temperature_ * temperature_) / (1.0f + 8.42420235e-4f * temperature_ + 7.08145163e-7f * temperature_ * temperature_); float v = (0.317398726f + 4.22806245e-5f * temperature_ + 4.20481691e-8f * temperature_ * temperature_) / (1.0f - 2.89741816e-5f * temperature_ + 1.61456053e-7f * temperature_ * temperature_); float x = 3.0f * u / (2.0f * u - 8.0f * v + 4.0f); float y = 2.0f * v / (2.0f * u - 8.0f * v + 4.0f); float z = 1.0f - x - y; float y_ = 1.0f; float x_ = y_ / y * x; float z_ = y_ / y * z; float red = 3.2404542f * x_ + -1.5371385f * y_ + -0.4985314f * z_; float green = -0.9692660f * x_ + 1.8760108f * y_ + 0.0415560f * z_; float blue = 0.0556434f * x_ + -0.2040259f * y_ + 1.0572252f * z_; return Color(red, green, blue); } Color Light::GetEffectiveColor() const { if (usePhysicalValues_) { // Light color in kelvin. Color tempColor = GetColorFromTemperature(); // Light brightness in lumens float energy = (brightness_ * 4.0f * M_PI) * 16.0f / (100.0f * 100.0f) / M_PI; return Color(tempColor.r_ * color_.r_ * energy, tempColor.g_ * color_.g_ * energy, tempColor.b_ * color_.b_ * energy, 1.0f); } else { return Color(color_ * brightness_, 1.0f); } } Frustum Light::GetFrustum() const { // Note: frustum is unaffected by node or parent scale Matrix3x4 frustumTransform(node_ ? Matrix3x4(node_->GetWorldPosition(), node_->GetWorldRotation(), 1.0f) : Matrix3x4::IDENTITY); Frustum ret; ret.Define(fov_, aspectRatio_, 1.0f, M_MIN_NEARCLIP, range_, frustumTransform); return ret; } Frustum Light::GetViewSpaceFrustum(const Matrix3x4& view) const { // Note: frustum is unaffected by node or parent scale Matrix3x4 frustumTransform(node_ ? Matrix3x4(node_->GetWorldPosition(), node_->GetWorldRotation(), 1.0f) : Matrix3x4::IDENTITY); Frustum ret; ret.Define(fov_, aspectRatio_, 1.0f, M_MIN_NEARCLIP, range_, view * frustumTransform); return ret; } int Light::GetNumShadowSplits() const { unsigned ret = 1; if (shadowCascade_.splits_[1] > shadowCascade_.splits_[0]) { ++ret; if (shadowCascade_.splits_[2] > shadowCascade_.splits_[1]) { ++ret; if (shadowCascade_.splits_[3] > shadowCascade_.splits_[2]) ++ret; } } return (int)Min(ret, MAX_CASCADE_SPLITS); } const Matrix3x4& Light::GetVolumeTransform(Camera* camera) { if (!node_) return Matrix3x4::IDENTITY; switch (lightType_) { case LIGHT_DIRECTIONAL: volumeTransform_ = GetFullscreenQuadTransform(camera); break; case LIGHT_SPOT: { float yScale = tanf(fov_ * M_DEGTORAD * 0.5f) * range_; float xScale = aspectRatio_ * yScale; volumeTransform_ = Matrix3x4(node_->GetWorldPosition(), node_->GetWorldRotation(), Vector3(xScale, yScale, range_)); } break; case LIGHT_POINT: volumeTransform_ = Matrix3x4(node_->GetWorldPosition(), Quaternion::IDENTITY, range_); break; } return volumeTransform_; } void Light::SetRampTextureAttr(const ResourceRef& value) { auto* cache = GetSubsystem<ResourceCache>(); rampTexture_ = static_cast<Texture*>(cache->GetResource(value.type_, value.name_)); } void Light::SetShapeTextureAttr(const ResourceRef& value) { auto* cache = GetSubsystem<ResourceCache>(); shapeTexture_ = static_cast<Texture*>(cache->GetResource(value.type_, value.name_)); } ResourceRef Light::GetRampTextureAttr() const { return GetResourceRef(rampTexture_, Texture2D::GetTypeStatic()); } ResourceRef Light::GetShapeTextureAttr() const { return GetResourceRef(shapeTexture_, lightType_ == LIGHT_POINT ? TextureCube::GetTypeStatic() : Texture2D::GetTypeStatic()); } void Light::OnWorldBoundingBoxUpdate() { switch (lightType_) { case LIGHT_DIRECTIONAL: // Directional light always sets humongous bounding box not affected by transform worldBoundingBox_.Define(-M_LARGE_VALUE, M_LARGE_VALUE); break; case LIGHT_SPOT: // Frustum is already transformed into world space worldBoundingBox_.Define(GetFrustum()); break; case LIGHT_POINT: { const Vector3& center = node_->GetWorldPosition(); Vector3 edge(range_, range_, range_); worldBoundingBox_.Define(center - edge, center + edge); } break; } } void Light::SetIntensitySortValue(float distance) { // When sorting lights globally, give priority to directional lights so that they will be combined into the ambient pass if (!IsNegative()) { if (lightType_ != LIGHT_DIRECTIONAL) sortValue_ = Max(distance, M_MIN_NEARCLIP) / GetIntensityDivisor(); else sortValue_ = M_EPSILON / GetIntensityDivisor(); } else { // Give extra priority to negative lights in the global sorting order so that they're handled first, right after ambient. // Positive lights are added after them if (lightType_ != LIGHT_DIRECTIONAL) sortValue_ = -Max(distance, M_MIN_NEARCLIP) * GetIntensityDivisor(); else sortValue_ = -M_LARGE_VALUE * GetIntensityDivisor(); } } void Light::SetIntensitySortValue(const BoundingBox& box) { // When sorting lights for object's maximum light cap, give priority based on attenuation and intensity switch (lightType_) { case LIGHT_DIRECTIONAL: sortValue_ = 1.0f / GetIntensityDivisor(); break; case LIGHT_SPOT: { Vector3 centerPos = box.Center(); Vector3 lightPos = node_->GetWorldPosition(); Vector3 lightDir = node_->GetWorldDirection(); Ray lightRay(lightPos, lightDir); Vector3 centerProj = lightRay.Project(centerPos); float centerDistance = (centerProj - lightPos).Length(); Ray centerRay(centerProj, centerPos - centerProj); float centerAngle = centerRay.HitDistance(box) / centerDistance; // Check if a corner of the bounding box is closer to the light ray than the center, use its angle in that case Vector3 cornerPos = centerPos + box.HalfSize() * Vector3(centerPos.x_ < centerProj.x_ ? 1.0f : -1.0f, centerPos.y_ < centerProj.y_ ? 1.0f : -1.0f, centerPos.z_ < centerProj.z_ ? 1.0f : -1.0f); Vector3 cornerProj = lightRay.Project(cornerPos); float cornerDistance = (cornerProj - lightPos).Length(); float cornerAngle = (cornerPos - cornerProj).Length() / cornerDistance; float spotAngle = Min(centerAngle, cornerAngle); float maxAngle = tanf(fov_ * M_DEGTORAD * 0.5f); float spotFactor = Min(spotAngle / maxAngle, 1.0f); // We do not know the actual range attenuation ramp, so take only spot attenuation into account float att = Max(1.0f - spotFactor * spotFactor, M_EPSILON); sortValue_ = 1.0f / GetIntensityDivisor(att); } break; case LIGHT_POINT: { Vector3 centerPos = box.Center(); Vector3 lightPos = node_->GetWorldPosition(); Vector3 lightDir = (centerPos - lightPos).Normalized(); Ray lightRay(lightPos, lightDir); float distance = lightRay.HitDistance(box); float normDistance = distance / range_; float att = Max(1.0f - normDistance * normDistance, M_EPSILON); sortValue_ = 1.0f / GetIntensityDivisor(att); } break; } } void Light::SetLightQueue(LightBatchQueue* queue) { lightQueue_ = queue; } Matrix3x4 Light::GetFullscreenQuadTransform(Camera* camera) { Matrix3x4 quadTransform; Vector3 near, far; // Position the directional light quad in halfway between far & near planes to prevent depth clipping camera->GetFrustumSize(near, far); quadTransform.SetTranslation(Vector3(0.0f, 0.0f, (camera->GetNearClip() + camera->GetFarClip()) * 0.5f)); quadTransform.SetScale(Vector3(far.x_, far.y_, 1.0f)); // Will be oversized, but doesn't matter (gets frustum clipped) return camera->GetEffectiveWorldTransform() * quadTransform; } }
9ee481bfcfbd60768b1933ccc0ec88362f49b1a9
696e35ccdf167c3f6b1a7f5458406d3bb81987c9
/chrome/browser/ui/tab_ui_helper.cc
23d43fb0639bb78c072774e1d079be7e8b8fe977
[ "BSD-3-Clause" ]
permissive
mgh3326/iridium-browser
064e91a5e37f4e8501ea971483bd1c76297261c3
e7de6a434d2659f02e94917be364a904a442d2d0
refs/heads/master
2023-03-30T16:18:27.391772
2019-04-24T02:14:32
2019-04-24T02:14:32
183,128,065
0
0
BSD-3-Clause
2019-11-30T06:06:02
2019-04-24T02:04:51
null
UTF-8
C++
false
false
5,353
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/tab_ui_helper.h" #include "build/build_config.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/favicon/favicon_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/session_restore.h" #include "chrome/grit/generated_resources.h" #include "components/favicon/core/favicon_service.h" #include "components/keyed_service/core/service_access_type.h" #include "components/url_formatter/url_formatter.h" #include "content/public/browser/invalidate_type.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/resources/grit/ui_resources.h" namespace { base::string16 FormatUrlToSubdomain(const GURL& url) { base::string16 formated_url = url_formatter::FormatUrl( url, url_formatter::kFormatUrlOmitTrivialSubdomains, net::UnescapeRule::SPACES, nullptr, nullptr, nullptr); return base::UTF8ToUTF16(GURL(formated_url).host()); } } // namespace TabUIHelper::TabUIData::TabUIData(const GURL& url) : title(FormatUrlToSubdomain(url)), favicon(ui::ResourceBundle::GetSharedInstance().GetImageNamed( IDR_DEFAULT_FAVICON)) {} TabUIHelper::TabUIHelper(content::WebContents* contents) : WebContentsObserver(contents), weak_ptr_factory_(this) {} TabUIHelper::~TabUIHelper() {} base::string16 TabUIHelper::GetTitle() const { const base::string16& contents_title = web_contents()->GetTitle(); if (!contents_title.empty()) return contents_title; if (tab_ui_data_) return tab_ui_data_->title; #if defined(OS_MACOSX) return l10n_util::GetStringUTF16(IDS_BROWSER_WINDOW_MAC_TAB_UNTITLED); #else return base::string16(); #endif } gfx::Image TabUIHelper::GetFavicon() const { if (ShouldUseFaviconFromHistory() && tab_ui_data_) return tab_ui_data_->favicon; return favicon::TabFaviconFromWebContents(web_contents()); } bool TabUIHelper::ShouldHideThrobber() const { // Hiding throbber and using favicon from history is desired when a new // background tab's initial navigation is delayed, so the user has a way to // see what the tab is. if (ShouldUseFaviconFromHistory()) return true; // We also want to hide a background tab's throbber during page load if it is // created by session restore. A restored tab's favicon is already fetched // by |SessionRestoreDelegate|. if (created_by_session_restore_ && !was_active_at_least_once_) return true; return false; } void TabUIHelper::NotifyInitialNavigationDelayed(bool is_navigation_delayed) { DCHECK(web_contents()->GetController().IsInitialNavigation()); is_navigation_delayed_ = is_navigation_delayed; if (!is_navigation_delayed_) return; tab_ui_data_ = std::make_unique<TabUIData>(web_contents()->GetVisibleURL()); web_contents()->NotifyNavigationStateChanged(content::INVALIDATE_TYPE_TAB); // When fetching favicon from history, we first try the exact URL, and then // fall back to the host. FetchFaviconFromHistory(web_contents()->GetVisibleURL(), base::Bind(&TabUIHelper::OnURLFaviconFetched, weak_ptr_factory_.GetWeakPtr())); } void TabUIHelper::DidStopLoading() { // Reset the properties after the initial navigation finishes loading, so that // latter navigations are not affected. is_navigation_delayed_ = false; created_by_session_restore_ = false; tab_ui_data_.reset(); } bool TabUIHelper::ShouldUseFaviconFromHistory() const { return web_contents()->GetController().IsInitialNavigation() && is_navigation_delayed_ && !was_active_at_least_once_; } void TabUIHelper::FetchFaviconFromHistory( const GURL& url, const favicon_base::FaviconImageCallback& callback) { Profile* profile = Profile::FromBrowserContext(web_contents()->GetBrowserContext()); favicon::FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(profile, ServiceAccessType::EXPLICIT_ACCESS); // |favicon_service| might be null when testing. if (favicon_service) { favicon_service->GetFaviconImageForPageURL(url, callback, &favicon_tracker_); } } void TabUIHelper::OnURLFaviconFetched( const favicon_base::FaviconImageResult& favicon) { if (!ShouldUseFaviconFromHistory()) return; if (!favicon.image.IsEmpty()) { UpdateFavicon(favicon); return; } FetchFaviconFromHistory(web_contents()->GetVisibleURL().GetWithEmptyPath(), base::Bind(&TabUIHelper::OnHostFaviconFetched, weak_ptr_factory_.GetWeakPtr())); } void TabUIHelper::OnHostFaviconFetched( const favicon_base::FaviconImageResult& favicon) { if (!ShouldUseFaviconFromHistory()) return; if (!favicon.image.IsEmpty()) UpdateFavicon(favicon); } void TabUIHelper::UpdateFavicon( const favicon_base::FaviconImageResult& favicon) { if (tab_ui_data_) { tab_ui_data_->favicon = favicon.image; web_contents()->NotifyNavigationStateChanged(content::INVALIDATE_TYPE_TAB); } } WEB_CONTENTS_USER_DATA_KEY_IMPL(TabUIHelper)
145e52e026f3ada3e34ce50356dab6d5ebc8f86c
12b377946d78de96d4096e55874933fe9bb38619
/ash/mus/sysui_application.cc
571523ef93c0a7b35eaed001462f20c47de34e91
[ "BSD-3-Clause" ]
permissive
neuyang/chromium
57c0c6ef86e933bc5de11a9754e5ef6f9752badb
afb8f54b782055923cadd711452c2448f3f7b5b4
refs/heads/master
2023-02-20T21:47:59.999916
2016-04-20T21:38:20
2016-04-20T21:41:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,178
cc
// Copyright 2016 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 "ash/mus/sysui_application.h" #include <map> #include <set> #include <string> #include <vector> #include "ash/desktop_background/desktop_background_controller.h" #include "ash/host/ash_window_tree_host_init_params.h" #include "ash/host/ash_window_tree_host_platform.h" #include "ash/mus/keyboard_ui_mus.h" #include "ash/mus/shelf_delegate_mus.h" #include "ash/mus/shell_delegate_mus.h" #include "ash/mus/stub_context_factory.h" #include "ash/root_window_settings.h" #include "ash/shell.h" #include "ash/shell_init_params.h" #include "ash/shell_window_ids.h" #include "base/bind.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "base/threading/sequenced_worker_pool.h" #include "components/mus/public/cpp/property_type_converters.h" #include "components/resource_provider/public/cpp/resource_loader.h" #include "mash/wm/public/interfaces/ash_window_type.mojom.h" #include "mash/wm/public/interfaces/container.mojom.h" #include "ui/aura/env.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" #include "ui/message_center/message_center.h" #include "ui/platform_window/stub/stub_window.h" #include "ui/views/mus/aura_init.h" #include "ui/views/mus/native_widget_mus.h" #include "ui/views/mus/window_manager_connection.h" #include "ui/views/views_delegate.h" #if defined(OS_CHROMEOS) #include "chromeos/audio/cras_audio_handler.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "device/bluetooth/dbus/bluez_dbus_manager.h" #include "ui/events/devices/device_data_manager.h" #endif using views::ViewsDelegate; namespace ash { namespace sysui { namespace { const char kResourceFileStrings[] = "ash_resources_strings.pak"; const char kResourceFile100[] = "ash_resources_100_percent.pak"; const char kResourceFile200[] = "ash_resources_200_percent.pak"; // Tries to determine the corresponding mash container from widget init params. mash::wm::mojom::Container GetContainerId( const views::Widget::InitParams& params) { const int id = params.parent->id(); if (id == kShellWindowId_DesktopBackgroundContainer) return mash::wm::mojom::Container::USER_BACKGROUND; // mash::wm::ShelfLayout manages both the shelf and the status area. if (id == kShellWindowId_ShelfContainer || id == kShellWindowId_StatusContainer) { return mash::wm::mojom::Container::USER_SHELF; } // Determine the container based on Widget type. switch (params.type) { case views::Widget::InitParams::Type::TYPE_BUBBLE: return mash::wm::mojom::Container::BUBBLES; case views::Widget::InitParams::Type::TYPE_MENU: return mash::wm::mojom::Container::MENUS; case views::Widget::InitParams::Type::TYPE_TOOLTIP: return mash::wm::mojom::Container::TOOLTIPS; default: return mash::wm::mojom::Container::COUNT; } } // Tries to determine the corresponding ash window type from the ash container // for the widget. mash::wm::mojom::AshWindowType GetAshWindowType(aura::Window* container) { DCHECK(container); int id = container->id(); if (id == kShellWindowId_ShelfContainer) return mash::wm::mojom::AshWindowType::SHELF; if (id == kShellWindowId_StatusContainer) return mash::wm::mojom::AshWindowType::STATUS_AREA; return mash::wm::mojom::AshWindowType::COUNT; } // Creates a StubWindow, which means this window never receives any input event, // or displays anything to the user. class AshWindowTreeHostMus : public AshWindowTreeHostPlatform { public: explicit AshWindowTreeHostMus(const gfx::Rect& initial_bounds) : AshWindowTreeHostPlatform() { std::unique_ptr<ui::PlatformWindow> window(new ui::StubWindow(this)); window->SetBounds(initial_bounds); SetPlatformWindow(std::move(window)); } ~AshWindowTreeHostMus() override {} void OnBoundsChanged(const gfx::Rect& bounds) override { if (platform_window()) AshWindowTreeHostPlatform::OnBoundsChanged(bounds); } }; AshWindowTreeHost* CreateWindowTreeHostMus( const AshWindowTreeHostInitParams& init_params) { return new AshWindowTreeHostMus(init_params.initial_bounds); } // Responsible for setting up a RootWindowSettings object for the root-window // created for the views::Widget objects. class NativeWidgetFactory { public: NativeWidgetFactory() { ViewsDelegate* views_delegate = ViewsDelegate::GetInstance(); DCHECK(views_delegate); views_delegate->set_native_widget_factory(base::Bind( &NativeWidgetFactory::InitNativeWidget, base::Unretained(this))); } ~NativeWidgetFactory() { ViewsDelegate::GetInstance()->set_native_widget_factory( ViewsDelegate::NativeWidgetFactory()); } private: views::NativeWidget* InitNativeWidget( const views::Widget::InitParams& params, views::internal::NativeWidgetDelegate* delegate) { std::map<std::string, std::vector<uint8_t>> properties; if (params.parent) { mash::wm::mojom::Container container = GetContainerId(params); if (container != mash::wm::mojom::Container::COUNT) { properties[mash::wm::mojom::kWindowContainer_Property] = mojo::ConvertTo<std::vector<uint8_t>>( static_cast<int32_t>(container)); } mash::wm::mojom::AshWindowType type = GetAshWindowType(params.parent); if (type != mash::wm::mojom::AshWindowType::COUNT) { properties[mash::wm::mojom::kAshWindowType_Property] = mojo::ConvertTo<std::vector<uint8_t>>(static_cast<int32_t>(type)); } } // AshInit installs a stub implementation of ui::ContextFactory, so that the // AshWindowTreeHost instances created do not actually show anything to the // user. However, when creating a views::Widget instance, the // WindowManagerConnection creates a WindowTreeHostMus instance, which // creates a ui::Compositor, and it needs a real ui::ContextFactory // implementation. So, unset the context-factory here temporarily when // creating NativeWidgetMus. But restore the stub instance afterwards, so // that it is used when new AshWindowTreeHost instances are created (e.g. // when a new monitor is attached). ui::ContextFactory* factory = aura::Env::GetInstance()->context_factory(); aura::Env::GetInstance()->set_context_factory(nullptr); views::NativeWidgetMus* native_widget = static_cast<views::NativeWidgetMus*>( views::WindowManagerConnection::Get()->CreateNativeWidgetMus( properties, params, delegate)); aura::Env::GetInstance()->set_context_factory(factory); // TODO: Set the correct display id here. InitRootWindowSettings(native_widget->GetRootWindow())->display_id = Shell::GetInstance() ->display_manager() ->GetPrimaryDisplayCandidate() .id(); return native_widget; } DISALLOW_COPY_AND_ASSIGN(NativeWidgetFactory); }; } // namespace class AshInit { public: AshInit() : worker_pool_(new base::SequencedWorkerPool(2, "AshWorkerPool")) { ui::RegisterPathProvider(); } ~AshInit() { worker_pool_->Shutdown(); } aura::Window* root() { return ash::Shell::GetPrimaryRootWindow(); } void Initialize(::shell::Connector* connector) { InitializeResourceBundle(connector); aura_init_.reset(new views::AuraInit(connector, "views_mus_resources.pak")); views::WindowManagerConnection::Create(connector); gfx::Screen* screen = gfx::Screen::GetScreen(); DCHECK(screen); gfx::Size size = screen->GetPrimaryDisplay().bounds().size(); // Uninstall the ScreenMus installed by WindowManagerConnection, so that ash // installs and uses the ScreenAsh. This can be removed once ash learns to // talk to mus for managing displays. gfx::Screen::SetScreenInstance(nullptr); // Install some hook so that the WindowTreeHostMus created for widgets can // be hooked up correctly. native_widget_factory_.reset(new NativeWidgetFactory()); ash::AshWindowTreeHost::SetFactory(base::Bind(&CreateWindowTreeHostMus)); ash_delegate_ = new ShellDelegateMus; InitializeComponents(); ash::ShellInitParams init_params; init_params.delegate = ash_delegate_; init_params.context_factory = new StubContextFactory; init_params.blocking_pool = worker_pool_.get(); init_params.in_mus = true; init_params.keyboard_factory = base::Bind(&KeyboardUIMus::Create, connector); ash::Shell::CreateInstance(init_params); ash::Shell::GetInstance()->CreateShelf(); ash::Shell::GetInstance()->UpdateAfterLoginStatusChange( ash::user::LOGGED_IN_USER); ash::Shell::GetPrimaryRootWindow()->GetHost()->Show(); SetupWallpaper(SkColorSetARGB(255, 0, 255, 0)); } void InitializeResourceBundle(::shell::Connector* connector) { if (ui::ResourceBundle::HasSharedInstance()) return; std::set<std::string> resource_paths; resource_paths.insert(kResourceFileStrings); resource_paths.insert(kResourceFile100); resource_paths.insert(kResourceFile200); resource_provider::ResourceLoader loader(connector, resource_paths); if (!loader.BlockUntilLoaded()) return; // Load ash resources and en-US strings; not 'common' (Chrome) resources. // TODO(msw): Check ResourceBundle::IsScaleFactorSupported; load 300% etc. ui::ResourceBundle::InitSharedInstanceWithPakFileRegion( loader.ReleaseFile(kResourceFileStrings), base::MemoryMappedFile::Region::kWholeFile); ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); rb.AddDataPackFromFile(loader.ReleaseFile(kResourceFile100), ui::SCALE_FACTOR_100P); rb.AddDataPackFromFile(loader.ReleaseFile(kResourceFile200), ui::SCALE_FACTOR_200P); } void SetupWallpaper(SkColor color) { SkBitmap bitmap; bitmap.allocN32Pixels(16, 16); bitmap.eraseColor(color); #if !defined(NDEBUG) // In debug builds we generate a simple pattern that allows visually // notice if transparency is broken. { SkAutoLockPixels alp(bitmap); *bitmap.getAddr32(0, 0) = SkColorSetRGB(0, 0, 0); } #endif gfx::ImageSkia wallpaper = gfx::ImageSkia::CreateFrom1xBitmap(bitmap); ash::Shell::GetInstance() ->desktop_background_controller() ->SetWallpaperImage(wallpaper, wallpaper::WALLPAPER_LAYOUT_TILE); } void InitializeComponents() { message_center::MessageCenter::Initialize(); #if defined(OS_CHROMEOS) ui::DeviceDataManager::CreateInstance(); chromeos::DBusThreadManager::Initialize(); bluez::BluezDBusManager::Initialize( chromeos::DBusThreadManager::Get()->GetSystemBus(), chromeos::DBusThreadManager::Get()->IsUsingStub( chromeos::DBusClientBundle::BLUETOOTH)); chromeos::CrasAudioHandler::InitializeForTesting(); #endif } private: scoped_refptr<base::SequencedWorkerPool> worker_pool_; std::unique_ptr<views::AuraInit> aura_init_; ShellDelegateMus* ash_delegate_ = nullptr; std::unique_ptr<NativeWidgetFactory> native_widget_factory_; DISALLOW_COPY_AND_ASSIGN(AshInit); }; SysUIApplication::SysUIApplication() {} SysUIApplication::~SysUIApplication() {} void SysUIApplication::Initialize(::shell::Connector* connector, const ::shell::Identity& identity, uint32_t id) { ash_init_.reset(new AshInit()); ash_init_->Initialize(connector); } bool SysUIApplication::AcceptConnection(::shell::Connection* connection) { connection->AddInterface<mash::shelf::mojom::ShelfController>(this); return true; } void SysUIApplication::Create( ::shell::Connection* connection, mojo::InterfaceRequest<mash::shelf::mojom::ShelfController> request) { mash::shelf::mojom::ShelfController* shelf_controller = static_cast<ShelfDelegateMus*>(Shell::GetInstance()->GetShelfDelegate()); shelf_controller_bindings_.AddBinding(shelf_controller, std::move(request)); } } // namespace sysui } // namespace ash
6c5b1cf35d74495f6761cc64f2a4e975f2443ddf
c8942368a2dd8afe94f3854c46d18c7d8c832b14
/gen-cpp/litescreen_constants.cpp
a36e17765e43e10b93857b98965144b9f4df8049
[]
no_license
ayusun/litescreen
31cee9cf272956450ab9754663d91b9b01156238
6a3d11a1c68ec7d522a74b935f4093c8f1903b2a
refs/heads/master
2021-01-18T16:28:06.413871
2014-07-03T20:26:57
2014-07-03T20:26:57
21,475,827
3
0
null
null
null
null
UTF-8
C++
false
true
376
cpp
/** * Autogenerated by Thrift Compiler (1.0.0-dev) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "litescreen_constants.h" namespace thrift { namespace litescreen { const litescreenConstants g_litescreen_constants; litescreenConstants::litescreenConstants() { FROM_LINUX = 0; FROM_WINDOWS = 1; } }} // namespace
9be14fe36c0a5a8d2cc9459ae6c28a8c8cdded09
07e6fc323f657d1fbfc24f861a278ab57338b80a
/cpp/common/dynamics/DynamicControl.h
98999991bd84abc2cc34733d6176e9715bc3b0c4
[ "MIT" ]
permissive
ProkopHapala/SimpleSimulationEngine
99cf2532501698ee8a03b2e40d1e4bedd9a12609
47543f24f106419697e82771289172d7773c7810
refs/heads/master
2022-09-05T01:02:42.820199
2022-08-28T10:22:41
2022-08-28T10:22:41
40,007,027
35
4
null
null
null
null
UTF-8
C++
false
false
2,570
h
#ifndef DynamicControl_h #define DynamicControl_h #include <cstddef> #include <math.h> //typedef void (*ForceFunction)( int n, double * xs, double * dfs ); class DynamicControl{ public: //double * x = NULL; // pointer to input //double * y = NULL; // pointer to output double x = 0.0; // current value of control double dxdt_max = 1.0; // maximim speed of control movement double xmin = -1.0; // minimum value of control double xmax = 1.0; // maximum value of control double y0 = 0.0; // target value of output double oy = 0.0; // previous value o output double dydx = 1.0; // derivative of output with respect to constrol; this could eventually be recalculated for each target y0 double T = 0.0; // for second order dynamics double K = 1.0; double damp = 0.8; // axuliary double vy,ovy; // ==== functions void setup( double y0_, double xmin_, double xmax_, double K_ ){ y0=y0_; xmin=xmin_; xmax=xmax_; K=K_; } double dx_O1( double y, double dt ){ // first order dynamical controler // dydt = 0; // TODO : we should modify this to consider observed output change rate "dydt" probely double dxmax = dxdt_max*dt; //double dymax = dxmax*dydx; //double dydt = (y-oy); oy = y; // this is for second order double dy = y0-y; double dyT = (y-oy)*T; if( (dy*dyT)>0 ){ dy-=dyT; if((dy*dyT)<0) dy=0.0; }; double dx = _clamp( dy/dydx, -dxmax, dxmax); oy=y; //double dx = _clamp( dydt, -dymax,dymax ) / dydx; x += dx; //double x_ = _clamp( x+dx, xmin,xmax ); //dx = x_-x; //x = x_; return dx; }; double dx_O2( double y, double dt ){ // first order dynamical controler // y_ = y + vy*t + k*x*t**2 //::::| y(t+T) = y0 // vy*T + (y-y0) + k*x*T**2 = 0 // x = ((y0-y)-vy*T)/(k*T**2) double dy = y0-y; vy = (y-oy)/dt; dy -= (vy*T)*damp; double x_ = dy/(T*T*K); double dx = x_-x; oy=y;ovy=vy; x+=dx; return dx; }; void x_O1( double y, double dt ){ // first order dynamical controler // y_ = y + vy*t + k*x*t**2 //::::| y(t+T) = y0 // vy*T + (y-y0) + k*x*T**2 = 0 // x = ((y0-y)-vy*T)/(k*T**2) double dy = y0-y; ovy=(y-oy)/dt; oy=y; //x=K*dy; x=_clamp( K*dy, xmin, xmax ); }; }; #endif
8243156b3003a6f3162f0f749d791e1fe0142ef1
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1674486_0/C++/kenv07/main.cpp
5aea01a90cfaa63acfcdbcd248184231ea783e9e
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,863
cpp
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; int fi[1100], next[1100], ed[1100], flag[1100], dui[1100]; bool biao[1100], ans; int main() { freopen("A.in", "r", stdin); freopen("A.out", "w", stdout); int t, n, m, q, w, x, tou, wei, k, j; cin >> t; for (int qw = 1; qw <= t; qw ++) { memset(fi, 0, sizeof(fi)); memset(next, 0, sizeof(next)); m = 0; cin >> n; ans = false; for (int i = 1; i <= n; i ++) { cin >> w; for (int k = 1;k <= w; k ++) { cin >> x; m ++; ed[m] = x; next[m] = fi[i]; fi[i] = m; } } for (int i = 1; i <= n; i ++) { ans = false; memset(flag, 0, sizeof(flag)); tou = 0; wei = 1; dui[wei] = i; memset(biao, true, sizeof(biao)); biao[i] = false; while (tou != wei){ tou ++; j = fi[dui[tou]]; while (j != 0){ flag[ed[j]] ++; if (flag[ed[j]] > 1){ ans = true; break; } if (biao[ed[j]] == true) { wei ++; dui[wei] = ed[j]; } j = next[j]; if (ans == true) break; } } if (ans == true) break; } if (ans == true) cout << "Case #" << qw << ": " << "Yes" << endl; else cout << "Case #" << qw << ": " << "No" << endl; } return 0; }
244cdcc613ac3940c610bc788aef7cbc01e8bff1
ace9852d2b85f5fa083f18d3eb421f508d54cc9d
/include/common/io.h
89647ae098ca206a815aaaf8c9de15142f8aabe1
[]
no_license
zbyue/ByOS
19ef746b9a061e4b3c63621a7e62f24726b0ed30
c287356814167c3d7836f2e563bd551eca721b5a
refs/heads/main
2023-04-29T08:16:30.912024
2021-05-11T07:17:08
2021-05-11T07:17:08
321,974,153
1
0
null
null
null
null
UTF-8
C++
false
false
1,463
h
#ifndef __BYOS__COMMON__IO_H #define __BYOS__COMMON__IO_H #include "types.h" namespace byos { namespace common { inline void printf(int8_t* str) { static uint16_t* VideoMemory = (uint16_t*)0xb8000; static uint8_t x = 0, y = 0; for(int i = 0; str[i] != '\0'; ++i) { switch(str[i]) { case '\n': y++; x = 0; break; default: VideoMemory[80*y+x] = (VideoMemory[80*y+x] & 0xFF00) | str[i]; x++; break; } if(x >= 80) { y++; x = 0; } if(y >= 25) { for(y=0; y < 25; ++y) { for(x=0; x < 80; ++x) { VideoMemory[80*y+x] = (VideoMemory[80*y+x] & 0xFF00) | ' '; } } x = 0; y = 0; } } } inline void printfHex(uint8_t key) { char* foo = "00"; char* hex = "0123456789ABCDEF"; foo[0] = hex[(key >> 4) & 0x0F]; foo[1] = hex[key & 0x0F]; printf(foo); } } } #endif
a26f9f5da523633f09b6d6543b29314b0d90859c
90a50773ad9d10f586aa92a7be7e8dc88d392a15
/atcoder/abc041/A/main.cpp
5a403c3af0905bb631720ef9292c5a241cce75dc
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yukirin/coder
e0eebc55886fd4a4a62bab80ae6bd980bb0e8409
3a04e9d19011b126bf4b3b0e6d089e6746fb58d5
refs/heads/master
2022-09-27T05:06:34.144714
2022-09-19T14:10:37
2022-09-19T14:10:37
86,316,125
1
1
null
null
null
null
UTF-8
C++
false
false
2,933
cpp
#include <bits/stdc++.h> #ifdef _DEBUG #define debug(x) cerr << "line: " << __LINE__ << ", func: " << __func__ << " -> " << #x << " = " << x << endl #else #define debug(x) #endif #define all(s) begin(s), end(s) #define rall(s) rbegin(s), rend(s) #define rep(i, a, b) for (int i = (a); i < (b); i++) #define rrep(i, a, b) for (int i = ((a) - 1); i >= (b); i--) #define pb push_back #define sz(a) int((a).size()) #define put(a) ((cout) << (a) << (endl)) #define putf(a, n) ((cout) << (fixed) << (setprecision(n)) << (a) << (endl)) #define deg2rad(x) (((x) * PI) / (180.0)) #define rad2deg(x) (((x) * (180.0)) / PI) #define fi first #define se second using namespace std; using ll = long long; using ull = unsigned long long; using ld = long double; using i_i = pair<int, int>; using ll_ll = pair<ll, ll>; using d_ll = pair<double, ll>; using ll_d = pair<ll, double>; using d_d = pair<double, double>; template <class T> using vec = vector<T>; static constexpr ll LL_INF = 1LL << 60; static constexpr int I_INF = 1 << 28; static constexpr double PI = static_cast<double>(3.14159265358979323846264338327950288); static constexpr double EPS = numeric_limits<double>::epsilon(); static map<type_index, const char* const> scanType = { {typeid(int), "%d"}, {typeid(ll), "%lld"}, {typeid(double), "%lf"}, {typeid(char), "%c"}}; template <class T> static void scan(vector<T>& v); [[maybe_unused]] static void scan(vector<string>& v, bool isWord = true); template <class T> static inline bool chmax(T& a, T b); template <class T> static inline bool chmin(T& a, T b); template <class T> static inline T gcd(T a, T b); template <class T> static inline T lcm(T a, T b); template <class A, size_t N, class T> static void Fill(A (&arr)[N], const T& val); template <class T> T mod(T a, T m); int main(int argc, char* argv[]) { std::string s; std::cin >> s; long long i; scanf("%lld",&i); return 0; } template <class T> static void scan(vector<T>& v) { auto tFormat = scanType[typeid(T)]; for (T& n : v) { scanf(tFormat, &n); } } static void scan(vector<string>& v, bool isWord) { if (isWord) { for (auto& n : v) { cin >> n; } return; } int i = 0, size = v.size(); string s; getline(cin, s); if (s.size() != 0) { i++; v[0] = s; } for (; i < size; ++i) { getline(cin, v[i]); } } template <class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } template <class T> inline T gcd(T a, T b) { return __gcd(a, b); } template <class T> inline T lcm(T a, T b) { T c = min(a, b), d = max(a, b); return c * (d / gcd(c, d)); } template <class A, size_t N, class T> void Fill(A (&arr)[N], const T& val) { std::fill((T*)arr, (T*)(arr + N), val); } template <class T> T mod(T a, T m) { return (a % m + m) % m; }
0b145c46ba2ef44c0b90d2b310bb4a6a9df96836
272fc3b60892532e0146eb97cba5d6b70a43bcbc
/Imputoop.cpp
14f8a94a65e1af01aae6426e8bd231eef4924dba
[]
no_license
MiguelMuenala/EjemplosC_Cpp
23d8a913c5ec7a0e04902f7c263967d52d395e9e
8969552589318f51173914764e987dfaf9259637
refs/heads/master
2020-05-23T06:08:55.300343
2019-07-10T16:03:14
2019-07-10T16:03:14
186,661,460
1
0
null
null
null
null
UTF-8
C++
false
false
555
cpp
#include <iostream> //#include <string.h> using std::cin; using std::cout; using std::endl; void Foo() { cout << "Hello World!" << endl; } int main(int argc, char** argv) { char input = 0; cout << "Hello! This is a console application." << endl; cout << "Press q to quit, press a to execute foo." << endl; while(1) { cin >> input; if(input == 'a'||input == 'A') { Foo(); } else if(input == 'q' || input == 'q') { break; } else if(input != '\n') { cout << "Unknown command '" << input << "'! Ignoring...\n"; } } return 0; }
7a6afbfd2f9c67657f22a328d7782704d6d44251
192cb00315721ae89048635db6651cc5920fc3d5
/jni/jni_detections/jni_pedestrian_det.cpp
ecf04a5fe85ad759148cf0462f444c950910ad2e
[ "MIT" ]
permissive
memoiry/live-detecion-android-engine
9cc079cea53a9cd18621deb9bcbf65fd45ee2e2a
53bef4df4cf6bb4d0011639013f8500dcce76e18
refs/heads/master
2021-01-20T00:07:57.338548
2017-08-24T08:10:33
2017-08-24T08:10:33
101,270,480
1
0
null
null
null
null
UTF-8
C++
false
false
4,509
cpp
/* * jni_people_det.cpp using google-style * * Created on: Oct 20, 2015 * Author: Nanyun * * Copyright (c) 2015 Nanyun. All rights reserved. */ #include <android/bitmap.h> #include <jni_common/jni_bitmap2mat.h> #include <jni_common/jni_primitives.h> #include <jni_common/jni_fileutils.h> #include <jni_common/jni_utils.h> #include <detector.h> #include <jni.h> using namespace cv; extern JNI_VisionDetRet *g_pJNI_VisionDetRet; namespace { #define JAVA_NULL 0 using DetectorPtr = OpencvHOGDetctor *; class JNI_PedestrianDet { public: JNI_PedestrianDet(JNIEnv *env) { jclass clazz = env->FindClass(CLASSNAME_PEDESTRIAN_DET); mNativeContext = env->GetFieldID(clazz, "mNativeDetContext", "J"); env->DeleteLocalRef(clazz); } DetectorPtr getDetectorPtrFromJava(JNIEnv *env, jobject thiz) { DetectorPtr const p = (DetectorPtr)env->GetLongField(thiz, mNativeContext); return p; } void setDetectorPtrToJava(JNIEnv *env, jobject thiz, jlong ptr) { env->SetLongField(thiz, mNativeContext, ptr); } jfieldID mNativeContext; }; // Protect getting/setting and creating/deleting pointer between java/native std::mutex gLock; std::shared_ptr<JNI_PedestrianDet> getJNI_PedestrianDet(JNIEnv *env) { static std::once_flag sOnceInitflag; static std::shared_ptr<JNI_PedestrianDet> sJNI_PedestrianDet; std::call_once(sOnceInitflag, [env]() { sJNI_PedestrianDet = std::make_shared<JNI_PedestrianDet>(env); }); return sJNI_PedestrianDet; } DetectorPtr const getDetectorPtr(JNIEnv *env, jobject thiz) { std::lock_guard<std::mutex> lock(gLock); return getJNI_PedestrianDet(env)->getDetectorPtrFromJava(env, thiz); } // The function to set a pointer to java and delete it if newPtr is empty void setDetectorPtr(JNIEnv *env, jobject thiz, DetectorPtr newPtr) { std::lock_guard<std::mutex> lock(gLock); DetectorPtr oldPtr = getJNI_PedestrianDet(env)->getDetectorPtrFromJava(env, thiz); if (oldPtr != JAVA_NULL) { DLOG(INFO) << "setMapManager delete old ptr : " << oldPtr; delete oldPtr; } if (newPtr != JAVA_NULL) { DLOG(INFO) << "setMapManager set new ptr : " << newPtr; } getJNI_PedestrianDet(env)->setDetectorPtrToJava(env, thiz, (jlong)newPtr); } } // end unnamespace #ifdef __cplusplus extern "C" { #endif // ======================================================== // JNI Mapping Methods // ======================================================== #define DLIB_JNI_METHOD(METHOD_NAME) \ Java_com_nanyun_dlib_PedestrianDet_##METHOD_NAME jobjectArray getDetRet(JNIEnv *env, DetectorPtr detectorPtr, const int &size) { LOG(INFO) << "getDetRet"; jobjectArray jDetRetArray = JNI_VisionDetRet::createJObjectArray(env, size); for (int i = 0; i < size; i++) { jobject jDetRet = JNI_VisionDetRet::createJObject(env); env->SetObjectArrayElement(jDetRetArray, i, jDetRet); cv::Rect rect = detectorPtr->getResult()[i]; g_pJNI_VisionDetRet->setRect(env, jDetRet, rect.x, rect.y, rect.x + rect.width, rect.y + rect.height); g_pJNI_VisionDetRet->setLabel(env, jDetRet, "Pedestrian"); } return jDetRetArray; } JNIEXPORT jobjectArray JNICALL DLIB_JNI_METHOD(jniDetect)(JNIEnv *env, jobject thiz, jstring jImgPath) { LOG(INFO) << "jniPeopleDet"; std::string path = jniutils::convertJStrToString(env, jImgPath); cv::Mat src_img = cv::imread(path, CV_LOAD_IMAGE_COLOR); DetectorPtr detPtr = getDetectorPtr(env, thiz); int size = detPtr->det(src_img); LOG(INFO) << "jniPeopleDet size: " << size; return getDetRet(env, detPtr, size); } JNIEXPORT jobjectArray JNICALL DLIB_JNI_METHOD(jniBitmapDetect)(JNIEnv *env, jobject thiz, jobject bitmap) { LOG(INFO) << "jniBitmapPeopleDet"; cv::Mat rgbaMat; cv::Mat bgrMat; jniutils::ConvertBitmapToRGBAMat(env, bitmap, rgbaMat, true); cv::cvtColor(rgbaMat, bgrMat, cv::COLOR_RGBA2BGR); DetectorPtr detPtr = getDetectorPtr(env, thiz); jint size = detPtr->det(bgrMat); LOG(INFO) << "jniBitmapPeopleDet size: " << size; return getDetRet(env, detPtr, size); } jint JNIEXPORT JNICALL DLIB_JNI_METHOD(jniInit)(JNIEnv *env, jobject thiz) { LOG(INFO) << "jniInit"; DetectorPtr detPtr = new OpencvHOGDetctor(); setDetectorPtr(env, thiz, detPtr); ; return JNI_OK; return JNI_OK; } jint JNIEXPORT JNICALL DLIB_JNI_METHOD(jniDeInit)(JNIEnv *env, jobject thiz) { LOG(INFO) << "jniDeInit"; return JNI_OK; } #ifdef __cplusplus } #endif
43f4c06946f08e5197cfd4c3532019ca4e0323a4
3f3a42f429f8bcd769644148b24c3b0e6e2589ed
/U2_3D/Src/collision/U2IntectRaySphere3D.h
2f066c9ab3bb05e5959874fed9e3eac414519781
[]
no_license
DanielNeander/my-3d-engine
d10ad3e57a205f6148357f47467b550c7e0e0f33
7f0babbfdf0b719ea4b114a89997d3e52bcb2b6c
refs/heads/master
2021-01-10T17:58:25.691360
2013-04-24T07:37:31
2013-04-24T07:37:31
53,236,587
3
0
null
null
null
null
UTF-8
C++
false
false
1,198
h
/************************************************************************ module : U2IntectRaySphere3D Author : Yun sangyong Desc : GT, Section 7.7: The Method of Separating Axes ************************************************************************/ #pragma once #ifndef U2_INTECTRAYSPHERE3D_H #define U2_INTECTRAYSPHERE3D_H #include <U2_3D/src/U2_3DLibType.h> #include "U2Intersector.h" #include <U2_3D/src/Main/U2Ray3D.h> #include "U2Sphere.h" class U2_3D U2IntectRaySphere3D : public U2Intersector { public: U2IntectRaySphere3D(const U2Ray3D& ray, const U2Sphere& sphere); inline const U2Ray3D& GetRay() const { return *m_pRay; } inline const U2Sphere& GetSphere() const { return *m_pSphere; } virtual bool Test (); virtual bool Find (); inline int GetCnt() const { return m_iCnt; } inline const D3DXVECTOR3& GetPoint(int i) const { U2ASSERT(0 <= i && i < m_iCnt); return m_aPoint[i]; } inline float GetRayT(int i) const { U2ASSERT(0 <= i && i < m_iCnt); return m_afRayT[i]; } private: const U2Ray3D* m_pRay; const U2Sphere* m_pSphere; int m_iCnt; D3DXVECTOR3 m_aPoint[2]; float m_afRayT[2]; }; #endif
49351c388da4194b27ae08a561a505d99807d870
90a50773ad9d10f586aa92a7be7e8dc88d392a15
/atcoder/abc129/D/main.cpp
cbff5e018ec89032d5f7dc9e50a0e63f8d12d1dc
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yukirin/coder
e0eebc55886fd4a4a62bab80ae6bd980bb0e8409
3a04e9d19011b126bf4b3b0e6d089e6746fb58d5
refs/heads/master
2022-09-27T05:06:34.144714
2022-09-19T14:10:37
2022-09-19T14:10:37
86,316,125
1
1
null
null
null
null
UTF-8
C++
false
false
3,390
cpp
#include <bits/stdc++.h> #ifdef _DEBUG #define debug(x) cerr << "line: " << __LINE__ << ", func: " << __func__ << " -> " << #x << " = " << x << endl #else #define debug(x) #endif #define all(s) begin(s), end(s) #define rall(s) rbegin(s), rend(s) #define rep(i, a, b) for (int i = (a); i < (b); i++) #define rrep(i, a, b) for (int i = ((a)-1); i >= (b); i--) #define pb push_back #define sz(a) int((a).size()) #define put(a) ((cout) << (a) << (endl)) using namespace std; using ll = long long; using ull = unsigned long long; using i_i = pair<int, int>; using ll_ll = pair<ll, ll>; using d_ll = pair<double, ll>; using ll_d = pair<ll, double>; using d_d = pair<double, double>; static constexpr ll LL_INF = 1LL << 60; static constexpr int I_INF = 1 << 28; static constexpr double PI = static_cast<double>(3.14159265358979323846264338327950288); static constexpr double EPS = numeric_limits<double>::epsilon(); static map<type_index, const char* const> scanType = { {typeid(int), "%d"}, {typeid(ll), "%lld"}, {typeid(double), "%lf"}, {typeid(char), "%c"}}; template <class T> static void scan(vector<T>& v); [[maybe_unused]] static void scan(vector<string>& v, bool isWord = true); template <class T> static inline bool chmax(T& a, T b); template <class T> static inline bool chmin(T& a, T b); template <class T> static inline T gcd(T a, T b); template <class T> static inline T lcm(T a, T b); template <class A, size_t N, class T> static void Fill(A (&arr)[N], const T& val); ll grid[2005][2005]; int main(int argc, char* argv[]) { long long H; scanf("%lld", &H); long long W; scanf("%lld", &W); std::vector<std::string> S(H); for (int i = 0; i < H; i++) { std::cin >> S[i]; } rep(side, 0, 2) rep(i, 0, H) { ll count = 0; int j = (side ? 0 : W - 1); int last = (side ? W : -1); int next = (side ? 1 : -1); for (; j != last; j += next) { if (S[i][j] == '#') { count = 0; continue; } grid[i][j] += count; count++; } } rep(side, 0, 2) rep(i, 0, W) { ll count = 0; int j = (side ? 0 : H - 1); int last = (side ? H : -1); int next = (side ? 1 : -1); for (; j != last; j += next) { if (S[j][i] == '#') { count = 0; continue; } grid[j][i] += count; count++; } } ll ans = 0; rep(i, 0, H) rep(j, 0, W) { if (S[i][j] == '#') continue; chmax(ans, grid[i][j] + 1); } put(ans); return 0; } template <class T> static void scan(vector<T>& v) { auto tFormat = scanType[typeid(T)]; for (T& n : v) { scanf(tFormat, &n); } } static void scan(vector<string>& v, bool isWord) { if (isWord) { for (auto& n : v) { cin >> n; } return; } int i = 0, size = v.size(); string s; getline(cin, s); if (s.size() != 0) { i++; v[0] = s; } for (; i < size; ++i) { getline(cin, v[i]); } } template <class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } template <class T> inline T gcd(T a, T b) { return __gcd(a, b); } template <class T> inline T lcm(T a, T b) { return (a * b) / gcd(a, b); } template <class A, size_t N, class T> void Fill(A (&arr)[N], const T& val) { std::fill((T*)arr, (T*)(arr + N), val); }
903f6e3b430b711de8ceff0c0489cfbfffc0b2b2
f4bfa0d7977f5fb67d0d0fa83c9ab067a2398aa3
/Color_Generator.cpp
bbcc83fca1499db166e6e556343acfb24d5f6f0d
[ "MIT" ]
permissive
Julioalbornozv/Langton-Anthill
f13d69ad57a59217f9c4cd27a9cea5c8e720f314
343afc86ccc0fbf9bf3bd0791733db4685949a56
refs/heads/master
2020-07-05T23:14:25.545042
2019-12-26T20:04:34
2019-12-26T20:04:34
202,812,705
0
0
null
null
null
null
UTF-8
C++
false
false
3,970
cpp
/*** * @file Color_Generator.cpp * Color factory */ // Copyright 2019 by Julio Albornoz <[email protected]> // The License.txt file describes the conditions under which this // software may be distributed. #include "Generators.h" #include <algorithm> #include <fstream> #include <sstream> Color_Generator::Color_Generator(Config* config){ /*** * Class responsible of creating the color palette used by the program * * @param config: Configuration parameters * * @field size: Ruleset length * @field base: Number of colors used to generate the colors * @field interp: Color interpolation method * @field shuffle: Determines if the generated colors are shuffled after generation * @field save: Determines if generated data is saved after the simulation * @field palette: List of colors values for each tile (0-255) */ size = config->length; base = config->base; interp = config->interp; shuffle = config->shuffle; write = config->Csave; scheme = config->scheme; if (scheme == "RANDOM"){ random_palette(base); } else if (scheme == "LOAD"){ load(); } generate_colors(); } Color_Generator::~Color_Generator(){ delete palette; } void Color_Generator::load(std::string path){ /*** * Loads a palette from a txt file * * @param path: Path of the ant source file */ std::ifstream file(path); std::string line; std::vector<glm::vec3>* colors = new std::vector<glm::vec3>; while (std::getline(file, line)){ std::stringstream linestream(line); std::string val; glm::vec3 col; for (int i = 0; i < 3; i++){ getline(linestream, val, '\t'); col[i] = std::stoi(val); } colors->push_back(col); } palette = colors; file.close(); } void Color_Generator::save(std::string path){ /*** * Saves the current palette into a file * * @param path: Path of the backup file */ std::ofstream file(path); std::vector<glm::vec3> colors = *palette; for (unsigned int i = 0; i < size; i++){ glm::vec3 color = colors[i]; file << (int)color[0] << '\t' << (int)color[1] << '\t' << (int)color[2] << '\n'; } file.close(); } void Color_Generator::random_palette(unsigned int n){ /*** * Generates a random color palette * * @param n: Number of colors to generate */ std::vector<glm::vec3>* colors = new std::vector<glm::vec3>; for (unsigned int i = 0; i < n; i++){ colors->push_back(glm::vec3(rand() % 256, rand() % 256, rand() % 256)); } palette = colors; } std::vector<glm::vec3>* Color_Generator::fill_palette(){ /*** * This method extends the existing palette to a target number of colors. * * @return Numpy array with the new colorset */ unsigned int n = palette->size(); std::vector<glm::vec3>* colors = new std::vector<glm::vec3>; if (interp == "RGB"){ int req = size - n ; int gaps[n-1]; std::fill(&gaps[0], &gaps[n-1], (req/(n-1))); for (unsigned int i = 0; i < (req % (n-1)); i++){ //Adds remainder gaps[i]++; } std::vector<glm::vec3> pal = *palette; for (unsigned int j = 0; j < n-1; j++){ linspace(pal[j], pal[j+1], gaps[j], colors); } colors->push_back(pal[n-1]); } else{ std::vector<glm::vec3> pal = *palette; for (unsigned int i = 0; i < size; i++){ colors->push_back(pal[i%n]); } } if (shuffle){ std::random_shuffle(colors->begin(), colors->end()); } return colors; } void Color_Generator::linspace(glm::vec3 A, glm::vec3 B, int num, std::vector<glm::vec3>* vector){ /*** * Generates num-1 colors between colors A and B, returns a vector including A and the generated colors * */ glm::vec3 steps = (B - A)/(float)(num + 1); for (int i = 0; i < num+1; i++){ vector->push_back(A + steps * (float)i); } } void Color_Generator::generate_colors(){ /*** * Generates a color palette based on the given parameters and saves it * inside the object self.palette field */ unsigned int n = palette->size(); if (n < (size)-1){ palette = fill_palette(); } }
7c8d2e6b08e84ddd19742d595ada7ddeeb04b3c4
50ebe28f14bc7f40d8a7c7a39f054d7dad9fbeb3
/lib/VM/DecoratedObject.cpp
55bd949c1312174866b8158e2fcccbc5d806a750
[ "MIT" ]
permissive
sakurafisch/hermes
b3092c17ff1ef5b9e2c022bf2536a08879ed4181
2cb83fac34c404a9e877a36e145708425529f042
refs/heads/main
2023-08-30T02:40:50.907293
2021-11-02T00:02:08
2021-11-02T00:04:06
423,512,068
0
0
MIT
2021-11-01T15:13:59
2021-11-01T15:13:58
null
UTF-8
C++
false
false
2,572
cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "hermes/VM/DecoratedObject.h" #include "hermes/VM/Runtime-inline.h" namespace hermes { namespace vm { //===----------------------------------------------------------------------===// // class DecoratedObject size_t DecoratedObject::Decoration::getMallocSize() const { return sizeof *this; } const ObjectVTable DecoratedObject::vt{ VTable( CellKind::DecoratedObjectKind, cellSize<DecoratedObject>(), DecoratedObject::_finalizeImpl, nullptr, /* markWeak */ DecoratedObject::_mallocSizeImpl), DecoratedObject::_getOwnIndexedRangeImpl, DecoratedObject::_haveOwnIndexedImpl, DecoratedObject::_getOwnIndexedPropertyFlagsImpl, DecoratedObject::_getOwnIndexedImpl, DecoratedObject::_setOwnIndexedImpl, DecoratedObject::_deleteOwnIndexedImpl, DecoratedObject::_checkAllOwnIndexedImpl, }; void DecoratedObjectBuildMeta(const GCCell *cell, Metadata::Builder &mb) { mb.addJSObjectOverlapSlots(JSObject::numOverlapSlots<DecoratedObject>()); ObjectBuildMeta(cell, mb); mb.setVTable(&DecoratedObject::vt.base); } // static PseudoHandle<DecoratedObject> DecoratedObject::create( Runtime *runtime, Handle<JSObject> parentHandle, std::unique_ptr<Decoration> decoration, unsigned int additionalSlotCount) { const size_t reservedSlots = numOverlapSlots<DecoratedObject>() + additionalSlotCount; auto *cell = runtime->makeAFixed<DecoratedObject, HasFinalizer::Yes>( runtime, &vt, parentHandle, runtime->getHiddenClassForPrototype(*parentHandle, reservedSlots), std::move(decoration)); auto self = JSObjectInit::initToPseudoHandle(runtime, cell); // Allocate a propStorage if the number of additional slots requires it. auto selfWithSlots = runtime->ignoreAllocationFailure( JSObject::allocatePropStorage(std::move(self), runtime, reservedSlots)); return PseudoHandle<DecoratedObject>::vmcast(std::move(selfWithSlots)); } // static void DecoratedObject::_finalizeImpl(GCCell *cell, GC *) { auto *self = vmcast<DecoratedObject>(cell); self->~DecoratedObject(); } // static size_t DecoratedObject::_mallocSizeImpl(GCCell *cell) { DecoratedObject *self = vmcast<DecoratedObject>(cell); if (const Decoration *deco = self->getDecoration()) { return deco->getMallocSize(); } return 0; } } // namespace vm } // namespace hermes
247c0cc139bc7bdfdeef65475b84ce2639ea3483
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/wheel/WheelGobal/src/WheelGobalPrecompiledHeaders.cpp
2a9cb9585c7af59ebbbe83d61916cbba687f5b56
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
531
cpp
#include "WheelGobalStableHeaders.h" #include "WheelUIInterface.h" using namespace Orz; WheelUIInterface::WheelUIInterface(void):_listener(NULL) { } WheelUIInterface::~WheelUIInterface(void) {} void WheelNullUI::setTheTime(int second){} void WheelNullUI::setLogoShow(bool show){} void WheelNullUI::setStartVisible(bool visible){} void WheelNullUI::runWinner(void){} void WheelNullUI::setEndUIVisible(bool visible){} void WheelNullUI::update(TimeType interval){} void WheelNullUI::addBottom(void){}
1c4134ff0a95a12bee92e8ef1ad6ec870550ebca
61adafe92a3aac95a34fc768c4870ebdc84716fb
/ROSS_greedy/test_ross_greedy.cpp
955f70f181b997ffe6ab30e9faa8cbf72c99eaa9
[]
no_license
ulyssis/ross-
21e54527494d6fb041948ee827775a54c579b622
ca8b9f8b5c17727972993db4e3725fb232cd4527
refs/heads/master
2020-05-17T05:22:07.751872
2017-09-16T19:53:01
2017-09-16T19:53:01
35,556,611
0
0
null
null
null
null
UTF-8
C++
false
false
5,564
cpp
#include "distance.h" #include <iostream> #include "clusters.h" #include<time.h> int main() { using namespace Clustering; Clustering::Points ps; Clustering::Channel_allnode v_all; float sum_average_CCC=0; float sum_average_OCC=0; float sum_number_clusters=0; float sum_average_size=0; float sum_cv_size=0; float sum_cv_CCC=0; float sum_cv_OCC=0; unsigned int SumUpdateRound=0; std::vector<float> distr(100,0); std::vector<float> accum_numCCC(100,0); std::vector<float> accum_numOCC(100,0); std::vector<float> clustersize_cdf; std::vector<float> numCCC_cdf; std::vector<float> numOCC_cdf; //store data in every run to cacalate the confidence interval std::vector<float> container; for(unsigned int seed=0; seed<50; seed++) { srand(seed); //void randomInit (Points & ps, unsigned int GeoDim, unsigned int NumCR, unsigned int NumPR) // Clustering::randomInit(ps, 2, 100, 70); Clustering::randomInit(ps, 2, 100, 30); Clustering::Clusters clusters(ps); //private member _ps is initialized here! clusters.computeDistance(); //private member _dis is initialized here! //void channelRandomInit(unsigned int ChDim, double RadiusPR, double RadiusCR); clusters.channelRandomInit(10,10,10); clusters.ClusteringPhaseI(); clusters.OutputClustersAfterPhaseI(); clusters.ClusteringPhaseII(); //accumulation! sum_average_CCC = sum_average_CCC + clusters.average_CCC; sum_average_OCC = sum_average_OCC + clusters.average_OCC; // //to caculate standard deviation of 50 average_OCC(s) // container.push_back(clusters.average_OCC); sum_number_clusters= sum_number_clusters + clusters.number_clusters; sum_average_size=sum_average_size+clusters.average_size; sum_cv_size=sum_cv_size+clusters.cv_size; sum_cv_CCC=sum_cv_CCC+clusters.cv_CCC; sum_cv_OCC=sum_cv_OCC+clusters.cv_OCC; SumUpdateRound=SumUpdateRound+clusters.UpdateRound; for(unsigned int i=0; i<distr.size(); i++) { distr[i]=distr[i]+clusters.size_distr[i]; } for(unsigned int i=0; i<accum_numCCC.size(); i++) { accum_numCCC[i]=accum_numCCC[i]+clusters.CCC_distr[i]; } for(unsigned int i=0; i<accum_numOCC.size(); i++) { accum_numOCC[i]=accum_numOCC[i]+clusters.OCC_distr[i]; } clusters.clearall(); //clear ps ps.clear(); } // std::cout<<"final output of ROSS is:"<<std::endl; // std::cout<<"average_OCC = "<<sum_average_CCC/50<<"\n"; // std::cout<<"average_CCC = "<<sum_average_OCC/50<<"\n"; // std::cout<<"number_clusters = "<<sum_number_clusters/50<<"\n"; // std::cout<<"average_size = "<<sum_average_size/50<<"\n"; // std::cout<<"cv_size = "<<sum_cv_size/50<<"\n"; // std::cout<<"cv_CCC = "<<sum_cv_CCC/50<<"\n"; // std::cout<<"cv_OCC = "<<sum_cv_OCC/50<<"\n"; std::cout<<std::endl; std::cout<<sum_average_CCC/50<<"\n"; std::cout<<sum_average_OCC/50<<"\n"; std::cout<<sum_number_clusters/50<<"\n"; std::cout<<sum_average_size/50<<"\n"; std::cout<<sum_cv_size/50<<"\n"; std::cout<<sum_cv_CCC/50<<"\n"; std::cout<<sum_cv_OCC/50<<"\n"; std::cout<<SumUpdateRound/50<<"\n"; // CDF of size of clusters for(unsigned int i=0; i<distr.size(); i++) { distr[i]=distr[i]/50; } unsigned int j=distr.size(); while(!distr[j-1]) { if(distr.back()==0.0) { distr.pop_back(); } j--; } //output the number of nodes grouped into clusters with certain size for(unsigned int k=0; k<distr.size(); k++) { std::cout<<distr[k]*k<<"\t"; } std::cout<<std::endl; //output cdf of number of nodes according to clusters size clustersize_cdf.push_back(0); for(unsigned int k=0; k<distr.size(); k++) { float pre_cum=clustersize_cdf.back(); clustersize_cdf.push_back(pre_cum+(distr[k+1]*(k+1))); std::cout<<clustersize_cdf[k]<<"\n"; } std::cout<<std::endl; //output standard deviation of 50 average_OCC(s) // for(unsigned int l=0; l<container.size(); l++) // { // std::cout<<container[l]<<","; // } std::cout<<std::endl; // CDF of number of CCC for(unsigned int i=0; i<accum_numCCC.size(); i++) { accum_numCCC[i]=accum_numCCC[i]/50; } unsigned int jj=accum_numCCC.size(); while(!accum_numCCC[jj-1]) { if(accum_numCCC.back()==0.0) { accum_numCCC.pop_back(); } jj--; } float firstnum=accum_numCCC[0]; numCCC_cdf.push_back(firstnum); std::cout<<"there output the series of accumulative numbers: "<<"\n"; for(unsigned int k=0; k<accum_numCCC.size(); k++) { float pre_cum=numCCC_cdf.back(); numCCC_cdf.push_back(pre_cum+(accum_numCCC[k+1])); std::cout<<numCCC_cdf[k]<<"\n"; } // CDF of number of OCC for(unsigned int i=0; i<accum_numOCC.size(); i++) { accum_numOCC[i]=accum_numOCC[i]/50; } unsigned int jjj=accum_numOCC.size(); while(!accum_numOCC[jjj-1]) { if(accum_numOCC.back()==0.0) { accum_numOCC.pop_back(); } jjj--; } float firstnum2=accum_numOCC[0]; numOCC_cdf.push_back(firstnum2); std::cout<<"there output the series of accumulative numbers: "<<"\n"; for(unsigned int k=0; k<accum_numOCC.size(); k++) { float pre_cum=numOCC_cdf.back(); numOCC_cdf.push_back(pre_cum+(accum_numOCC[k+1])); std::cout<<numOCC_cdf[k]<<"\n"; } //clear containers! }
f4b05a3976fa868fb44395abdf5dabac05b2f35b
adb7e87ba4c78f3af727794f62392066298091e8
/Patterns/VisitorTarget.h
d808ddb0319eb70c9ffc539e5993d0c397bfd068
[]
no_license
rangefree/cpp_patterns
d9cf7c083734c4f43b0de9a3d89eef86d985c12e
57d11ee275ace7233a7922ac48619de7a4c48d96
refs/heads/master
2021-01-06T02:08:31.783793
2020-02-17T20:08:33
2020-02-17T20:08:33
241,197,467
0
0
null
null
null
null
UTF-8
C++
false
false
333
h
#pragma once #include <iostream> using namespace std; class Visitor; class SpecificVisitor; class Target { public: void accept(Visitor& rV); }; class Target1 : public Target { public: void accept(Visitor& rV); void accept(SpecificVisitor& rV); }; class Target2 : public Target { public: void accept(SpecificVisitor& rV); };
0b6a491d1961c6016126e3810c288218db2bd47c
de4956b310d50443eb59c2622da3f7204cc5273b
/Client/CServerPassword.cpp
d1e8362aac24a6f6d222296c934e04039ef31f7f
[]
no_license
natelo/Mafia-2-Multiplayer
0969f93b9fe7963dd7e8c47cb392c0a9b4adf67b
8585161b4e4255d91a28fef1086ed1393faef0a8
refs/heads/master
2023-03-09T06:16:32.696257
2019-05-04T09:43:00
2019-05-04T09:43:00
340,209,123
0
1
null
null
null
null
UTF-8
C++
false
false
3,023
cpp
/************************************************************* * * Solution : Mafia 2 Multiplayer * Project : Client * File : CServerPassword.cpp * Developers : AaronLad <[email protected]> * ***************************************************************/ #include "BaseInc.h" #include "CCore.h" #include "Math/CVector3.h" #include "CString.h" #include "CGUI.h" #include "CGUICallback.h" #include "gui_impl/CGUI_Impl.h" #include "gui_impl/CGUIElement_Impl.h" #include "gui_impl/CGUILabel_Impl.h" #include "gui_impl/CGUIEdit_Impl.h" #include "gui_impl/CGUIWindow_Impl.h" #include "gui_impl/CGUIButton_Impl.h" #include "CServerPassword.h" bool CServerPassword::Event_OnSubmitClick ( CGUIElement_Impl * pElement ) { // Do we have a submit button handler? if ( m_pfnSubmitHandler ) { // Call the submit button handler m_pfnSubmitHandler ( m_pEdit->GetText (), m_pSubmitHandlerUserData ); } return true; } bool CServerPassword::Event_OnCancelClick ( CGUIElement_Impl * pElement ) { // Hide the server password window SetVisible ( false ); return true; } CServerPassword::CServerPassword ( CGUI_Impl * pGUI ) { // Create the main window m_pWindow = pGUI->CreateWnd ( "Password Protected Server" ); m_pWindow->SetSize ( Vector2 ( 260, 120 ) ); m_pWindow->SetPosition ( Vector2 ( (pGUI->GetResolution().fX / 2) - 150, (pGUI->GetResolution().fY / 2) - 95 ) ); m_pWindow->SetVisible ( false ); m_pWindow->SetAlwaysOnTop ( true ); m_pWindow->SetSizingEnabled ( false ); m_pWindow->SetAlpha ( 1.0f ); // Create the label m_pLabel = pGUI->CreateLabel ( "Please enter the server password:", NULL, m_pWindow.get() ); m_pLabel->SetSize ( Vector2 ( 200, 20 ) ); m_pLabel->SetPosition ( Vector2 ( 20, 25 ) ); // Create the edit m_pEdit = pGUI->CreateEdit ( "", m_pWindow.get() ); m_pEdit->SetSize ( Vector2( 220, 24 ) ); m_pEdit->SetPosition ( Vector2 ( 18, 50 ) ); m_pEdit->SetMasked ( true ); // Create the submit button m_pSubmit = pGUI->CreateButton ( "Connect", m_pWindow.get() ); m_pSubmit->SetSize ( Vector2 ( 75, 20 ) ); m_pSubmit->SetPosition ( Vector2 ( 18, 85 ) ); m_pSubmit->SetClickHandler ( GUI_CALLBACK( &CServerPassword::Event_OnSubmitClick, this ) ); // Create the cancel button m_pCancel = pGUI->CreateButton ( "Cancel", m_pWindow.get() ); m_pCancel->SetSize ( Vector2 ( 75, 20 ) ); m_pCancel->SetPosition ( Vector2 ( 100, 85 ) ); m_pCancel->SetClickHandler ( GUI_CALLBACK( &CServerPassword::Event_OnCancelClick, this ) ); } CServerPassword::~CServerPassword ( void ) { } void CServerPassword::SetVisible ( bool bVisible ) { // Set the main window visible m_pWindow->SetVisible ( bVisible ); // Are we showing the window? if ( bVisible ) { // Bring it to the front m_pWindow->BringToFront (); } else { // Clear the text input m_pEdit->SetText ( "" ); } } void CServerPassword::OnScreenSizeChange ( float fX, float fY ) { // Adjust the window position m_pWindow->SetPosition ( Vector2 ( (fX / 2) - 150.0f, (fY / 2) - 95.0f ) ); }
[ "nate@8cfec0bd-d3a4-4003-b275-27d06a529d82" ]
nate@8cfec0bd-d3a4-4003-b275-27d06a529d82
35716b9be8940cec355a5ea46d428f3b02eda5a8
809c826cdd7f487040d860e7e02bb7b0e1abb8d3
/wowViewerLib/src/gapi/vulkan/shaders/GWMOShaderPermutationVLK.cpp
0459c0780ed905dec923f093d95ac87316422298
[]
no_license
Deamon87/WebWowViewerCpp
5d6fa3313c70695b966c1ebd5be7bf3613001f01
1ef6762657660a34e2964c5e7b94208e2828de3d
refs/heads/master
2023-05-25T07:56:33.281130
2023-05-21T01:07:31
2023-05-21T01:07:31
94,208,407
48
18
null
2023-09-08T17:05:49
2017-06-13T12:03:36
C++
UTF-8
C++
false
false
233
cpp
// // Created by Deamon on 7/27/2018. // #include "GWMOShaderPermutationVLK.h" GWMOShaderPermutationVLK::GWMOShaderPermutationVLK(std::string &shaderName, IDevice *device) : GShaderPermutationVLK(shaderName,device) {}
63c8ba2be80cd871b6abecee914cdf50aba5fce7
a6fa102df9c1ebe1c0f669943dcafd1680472061
/main.cc
ab12bcfb8e65482b601664a854c60e1d66b282cd
[]
no_license
nikki93/raylib-test
8065478f29ef55155086da4e8fbc1cbc228deb23
bbf03dc55efd69c05b6bfb2272a7ab1528f1983f
refs/heads/master
2022-08-02T20:53:58.263169
2020-05-21T01:55:25
2020-05-21T01:55:25
265,729,852
0
0
null
null
null
null
UTF-8
C++
false
false
1,184
cc
#include <cmath> #if defined(PLATFORM_WEB) #include <emscripten/emscripten.h> #endif #include "fmt/format.h" #include "raylib.h" #include "rlgl.h" int main() { InitWindow(800, 450, "raylib-test"); auto texture = LoadTexture("assets/avatar.png"); auto x = 100.0f, y = 100.0f; static auto update = [&]() { auto dt = GetFrameTime(); if (IsKeyDown(KEY_LEFT)) { x -= 400 * dt; } if (IsKeyDown(KEY_RIGHT)) { x += 400 * dt; } if (IsKeyDown(KEY_UP)) { y -= 400 * dt; } if (IsKeyDown(KEY_DOWN)) { y += 400 * dt; } }; static auto draw = [&]() { ClearBackground(Color { 0xdd, 0xdf, 0xf8, 0xff }); rlPushMatrix(); rlTranslatef(x, y, 0); DrawTexture(texture, 0, 0, GREEN); rlPopMatrix(); rlPushMatrix(); rlTranslatef(x + 20, y + 20, 0); DrawTexture(texture, 0, 0, RED); rlPopMatrix(); }; static auto frame = []() { update(); BeginDrawing(); draw(); EndDrawing(); }; #if defined(PLATFORM_WEB) emscripten_set_main_loop(frame, 0, true); #else SetTargetFPS(120); while (!WindowShouldClose()) { frame(); } #endif CloseWindow(); return 0; }
882a0e905139ef6bfa5a0fe27ba6429087ae5f22
15f6b119c19db8471210fc99650a1974c27fbc4c
/C/462C.cpp
e8e97217b09ced680619535031511d1a66db1317
[]
no_license
AsifWatson/codeforces
8d1afd7f56fe84836e770d2de68f9caad596480b
ee38a5e8c19a54588fecf4f26986975e258e3b6b
refs/heads/master
2021-07-12T23:33:54.021007
2021-02-28T14:06:09
2021-02-28T14:06:09
234,949,673
1
0
null
null
null
null
UTF-8
C++
false
false
2,168
cpp
/***********************************************************| | /\ /-------| ----- |-----------| | | / \ / | | | | / \ | | | | | / \ |----| | |-------| | | / ------ \ |-----| | | | | / \ | | | | | / \ / | | | | --- --- |---------/ ----- ----- | | | | Codeforces = Asif_Watson || Codechef = asif_watson | | Mail = [email protected] | | CSTE, Noakhali Science and Technology University(11) | | | ************************************************************/ #include "bits/stdc++.h" #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define all(v) v.begin(),v.end() #define allre(v) v.rbegin(),v.rend() #define sp(x,y) fixed<<setprecision(y)<<x #define max3(a,b,c) max(a,max(b,c)) #define min3(a,b,c) min(a,min(b,c)) using namespace std; const double pi = acos(-1.0); const double EPS = 1e-6; const int MOD = (int)1e9+7; template <class T> inline T bigmod(T p,T e,T M,T ret=1) { for(; e>0; e>>=1){if(e&1)ret=(ret*p)%M; p=(p*p)%M;} return ret; } template <class T> inline T gcd(T x,T y){if(y==0)return x; return gcd(y,x%y);} template <class T> inline T lcm(T x,T y){return ((x/gcd(x,y))*y);} bool Reverse(long long a,long long b){return a>b;} bool compare(pair<long long,long long> a,pair<long long,long long> b) { if(a.first==b.first)return a.second>b.second; return a.first<b.first; } int main() { IOS long long n; cin>>n; long long a[n]; for(int i=0; i<n; i++)cin>>a[i]; sort(a,a+n); if(n==1)cout<<a[0]<<endl; else if(n==2)cout<<(a[0]+a[1])*2<<endl; else { long long mul=1,ans=0; for(int i=0; i<n-1; i++)ans+=(a[i]*++mul); ans+=a[n-1]*mul; cout<<ans<<endl; } return 0; }
2c33a3bbe7d96653dbc3eef2a8a68937a62815fe
7f3993e24b0289d7b8424c69b318f230d4dc9667
/ogle/sources/renderer/perspective_camera.cc
32ba91fb4dd8b6546b39a2b68fda5f97f86627f8
[ "MIT" ]
permissive
damlaren/ogle
e3821f66425b10d629f665964399ca875d73bc8e
9496c41b07e4559bae5c806eb9139bd41cbd3749
refs/heads/master
2021-01-23T19:46:33.992262
2018-09-16T05:45:38
2018-09-16T05:45:38
45,319,649
2
0
null
2016-05-16T02:46:19
2015-10-31T21:55:12
C++
UTF-8
C++
false
false
1,467
cc
/** * @file perspective_camera.cc * @brief Implementation of perspective_camera.h. */ #include "renderer/perspective_camera.h" #include <cmath> #include "easylogging++.h" // NOLINT #include "geometry/transformation_matrix.h" namespace ogle { PerspectiveCamera::PerspectiveCamera(const float near_clip, const float far_clip, const Angle vertical_fov, const float aspect_ratio) : Camera(), near_clip_(near_clip), far_clip_(far_clip), vertical_fov_(vertical_fov) { if (near_clip_ >= far_clip_) { LOG(ERROR) << "Near clip plane must be closer than far."; } if (near_clip_ < 0) { LOG(ERROR) << "Near clip plane must be at positive distance."; } set_aspect_ratio(aspect_ratio); } Matrix44f PerspectiveCamera::GetViewMatrix(const Transform &transform) const { return TransformationMatrix::ViewMatrix3D( transform.world_position(), transform.world_front(), transform.world_up()); } Matrix44f PerspectiveCamera::GetProjectionMatrix() const { return TransformationMatrix::PerspectiveMatrix3D( near_clip_, far_clip_, vertical_fov_, aspect_ratio_); } void PerspectiveCamera::set_aspect_ratio(const float aspect_ratio) { if (aspect_ratio <= 0 || std::isnan(aspect_ratio)) { LOG(ERROR) << "Invalid aspect ratio set: " << aspect_ratio; } else { aspect_ratio_ = aspect_ratio; } } } // namespace ogle
11e96a76e105cfd8ee2e223ced2f23a499e4763b
baa1ae2afa8968d726f8cfd12135f8f9b691832e
/code/game-mslug/src/GameMetalSlug.h
a2943f5d5929f4c0dc6e4e92fd1413d70a9af1da
[]
no_license
germix/germix-games
ffaf1ebb360c389463a7438ee3c6cc33b031280c
db315cd54f06a7a646bc6789b9651ef39816643d
refs/heads/master
2022-04-05T07:32:56.040835
2019-11-19T11:06:03
2019-11-19T11:06:03
222,627,542
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
659
h
//////////////////////////////////////////////////////////////////////////////////////////////////// // // GameMetalSlug // // Germán Martínez // //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef ___GameMetalSlug_h___ #define ___GameMetalSlug_h___ #include <mach/Game.h> #include <gamelib/ScreenManager.h> class GameMetalSlug : public Game { ScreenManager smgr; public: GameMetalSlug(); ~GameMetalSlug(); public: virtual void init(Machine* mach); virtual void close(Machine* mach); virtual void update(Machine* mach, double dt); virtual void render(Machine* mach, Graphics* gr); }; #endif
3926c606bd4c6b3044e2deea735a6c1c410557e4
9aea0a5c92fc25c8867408e59f5740e74594b8aa
/op.hpp
4e69265c99b67e90deb33523499b14c5d7cf0d45
[]
no_license
Felipe-Assis/Optimization-UFRJ
24689aee817afe37af3bd70438d01ef78f3a8f15
689c068e2ee9937bce375e333301ba372268cabd
refs/heads/master
2021-08-22T17:27:21.852940
2017-11-30T20:31:50
2017-11-30T20:31:50
110,744,644
0
0
null
null
null
null
UTF-8
C++
false
false
3,370
hpp
#include <valarray> std::valarray< std::valarray<double> > multVetor(std::valarray<double> V1, std::valarray<double> V2) { //Multipica V1 por V2 transposto, retorna uma matriz double l1[3] = {V1[0]*V2[0], V1[0]*V2[1], V1[0]*V2[2]}; //linha 1 da matriz double l2[3] = {V1[1]*V2[0], V1[1]*V2[1], V1[1]*V2[2]}; //linha 2 da matriz double l3[3] = {V1[2]*V2[0], V1[2]*V2[1], V1[2]*V2[2]}; //linha 3 da matriz std::valarray< std::valarray<double> > M (3); std::valarray<double> a (l1, 3); std::valarray<double> b (l2, 3); std::valarray<double> c (l3, 3); //=== M[0] = a; M[1] = b; M[2] = c; return M; } std::valarray<double> multVetMatriz(std::valarray<double> V1, std::valarray< std::valarray<double> > M1, int n =3) { //Multiplica um vetor linha por uma matriz //Resulta em um vetor linha std::valarray<double> V (n); for (int i=0; i<n; i++){ V[i] = 0; for (int j=0; j<n; j++){ V[i] += V1[j]*M1[j][i]; } } return V; } std::valarray<double> multMatVet(std::valarray< std::valarray<double> > M1, std::valarray<double> V1, int n =3) { std::valarray<double> V (n); for (int i=0; i<n; i++){ V[i] = (M1[i]*V1).sum(); } return V; } std::valarray< std::valarray<double> > multMatriz(std::valarray< std::valarray<double> > M1, std::valarray< std::valarray<double> > M2, int n =3) { //Multipica duas matrizes M1 e M2 std::valarray< std::valarray<double> > M (n); std::valarray<double> zero (0.0,n); for (int i=0; i<n; i++) { M[i] = zero; } for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ for (int k=0; k<n; k++){ M[i][j] += M1[i][k]*M2[k][j]; } } } return M; } std::valarray< std::valarray<double> > divMatriz(std::valarray< std::valarray<double> > M1, double divisor=1, int n=3) { for (int i=0; i<n; i++){ M1[i] = M1[i]/divisor; } return M1; } std::valarray< std::valarray<double> > somaMatriz(std::valarray< std::valarray<double> > M1, std::valarray< std::valarray<double> > M2, int n=3) { std::valarray< std::valarray<double> > M (3); for (int i=0; i<n; i++){ M[i] = M1[i]+M2[i]; } return M; } std::valarray< std::valarray<double> > subMatriz(std::valarray< std::valarray<double> > M1, std::valarray< std::valarray<double> > M2, int n=3) { std::valarray< std::valarray<double> > M (3); for (int i=0; i<n; i++){ M[i] = M1[i]-M2[i]; } return M; } std::valarray< std::valarray<double> > multEscalar(std::valarray< std::valarray<double> > M1, double a, int n=3) { for (int i=0; i<n; i++){ M1[i] = M1[i]*a; } return M1; } std::valarray< std::valarray<double> > getIdentidade(int n = 3) { std::valarray< std::valarray<double> > M (n); std::valarray<double> l (0.0,n); for (int i=0; i<n; i++){ M[i] = l; M[i][i] = 1.0; } return M; } void printMatriz(std::valarray< std::valarray<double> > M, int n=3) { for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ std::cout << M[i][j] <<" "; } std::cout <<""<<std::endl; } } void printVetor(std::valarray <double> V, int n=3) { std::cout<<"[ "; for (int i=0; i<n; i++){ std::cout << V[i] << " "; } std::cout << "]"<<std::endl; }
67d23933fbd7b5e7a6635d4070573f8855aa0933
49c6645e3bad0b61ea530c9eacf83ee98e52b73c
/tutor/10.16/uva10418.cpp
7accf19bc905d40f77be9e9ffe284659a1fc9bdd
[]
no_license
agron911/Cpp-practice
3b08d5986944dd6678d135c4d042258822a54ee9
0c3e123e3b3d32d8a2806b7265483504d79a3ad4
refs/heads/master
2020-09-23T17:58:56.031226
2019-12-03T07:16:42
2019-12-03T07:16:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,069
cpp
#include<iostream> #include<cstdio> using namespace std; int dx[8]={0,0,1,-1,1,-1,1,-1}; int dy[8]={1,-1,0,0,-1,1,1,-1}; int main(){ int x,y,count=1; string s; int flag=0; while(cin>>x>>y && x /*(x!=0)*/ ){ string arr[101]={}; int num[101][101]={}; if(flag==1){ cout<<"\n"; } for(int i=1;i<=x;i++){ cin>>arr[i]; arr[i]=" "+arr[i]; for(int j=1;j<=y;j++){ if(arr[i][j]=='*'){ for(int c=0;c<8;c++){ int nx=i+dx[c]; int ny=j+dy[c]; num[nx][ny]++; } } } } printf("Field #%d:\n",count); for(int i=1;i<=x;i++){ for(int j=1;j<=y;j++){ if(arr[i][j]=='*'){ cout<<"*"; } else{ cout<<num[i][j]; } } cout<<endl; } count++;flag=1; } }
496386924b28c06b95898d87fb28ef4b147576ac
349fe789ab1e4e46aae6812cf60ada9423c0b632
/FIB_DataModule/SprKlient/UDMSprGrpKlientCF.h
21fbfb30065f35cd76c58068b84dedc7a9d08d08
[]
no_license
presscad/ERP
a6acdaeb97b3a53f776677c3a585ca860d4de980
18ecc6c8664ed7fc3f01397d587cce91fc3ac78b
refs/heads/master
2020-08-22T05:24:15.449666
2019-07-12T12:59:13
2019-07-12T12:59:13
216,326,440
1
0
null
2019-10-20T07:52:26
2019-10-20T07:52:26
null
UTF-8
C++
false
false
1,181
h
#ifndef UDMSprGrpKlientCFH #define UDMSprGrpKlientCFH #include "GlobalInterface.h" //--------------------------------------------------------------- class TDMSprGrpKlientCF : public IkanClassFactory { public: TDMSprGrpKlientCF(); ~TDMSprGrpKlientCF(); int NumRefs; virtual int kanQueryInterface(REFIID id_interface, void ** ppv); virtual int kanAddRef(void); virtual int kanRelease(void); virtual int kanCreateInstance(REFIID id_interface, void ** ppv); }; //--------------------------------------------------------------- #endif
82e1184945f6951708f404961be733f8f887114c
825baeebcab670220ee929252c78a42fe2c5fc7f
/dragonpoop_prealpha/dragonpoop/gfx/model/model_instance/model_instance.h
8da36f262a3fd38bef413ecbd998d284da637635
[]
no_license
rvaughn4/dragonpoop_prealpha
45e381cd06eea83aa022decf730688085e2b87a3
e16b41838a42fed417cfeef075509f744fe6f38a
refs/heads/master
2016-09-05T11:36:02.701048
2015-07-25T02:15:20
2015-07-25T02:15:20
37,826,187
0
0
null
null
null
null
UTF-8
C++
false
false
3,999
h
#ifndef dragonpoop_model_instance_h #define dragonpoop_model_instance_h #include "../model_component/model_component_type.h" #include "../model_component/model_component.h" namespace dragonpoop { class shared_obj_ref; class shared_obj_writelock; class model_instance_ref; class model_instance_readlock; class model_instance_writelock; class model_readlock; class model_group_instance_ref; class model_triangle_instance_ref; class model_animation_instance_ref; class model_joint_instance_ref; class model_instance : public model_component { private: shared_obj_ref *r; protected: //generate read lock virtual shared_obj_readlock *genReadLock( shared_obj *p, dpmutex_readlock *l ); //generate write lock virtual shared_obj_writelock *genWriteLock( shared_obj *p, dpmutex_writelock *l ); //generate ref virtual shared_obj_ref *genRef( shared_obj *p, std::shared_ptr<shared_obj_refkernal> *k ); //do background processing virtual void onRun( dpthread_lock *thd, gfx_writelock *g, model_writelock *m, model_component_writelock *l ); //returns true if has renderer bool hasRenderer( void ); //set renderer void setRenderer( shared_obj_writelock *r ); //get renderer shared_obj_ref *getRenderer( void ); //create group instances void makeGroups( dpthread_lock *thd, model_writelock *ml ); //destroy group instances void killGroups( void ); //sync group instances void syncGroups( model_writelock *ml ); //get group instances unsigned int getGroups( std::list<model_group_instance_ref *> *l ); //get group instances by parent unsigned int getGroupsByParent( dpid parent_id, std::list<model_group_instance_ref *> *l ); //create triangle instances void makeTriangles( dpthread_lock *thd, model_writelock *ml ); //destroy triangle instances void killTriangles( void ); //sync triangle instances void syncTriangles( model_writelock *ml ); //get triangle instances unsigned int getTriangles( std::list<model_triangle_instance_ref *> *l ); //get triangle instances by group unsigned int getTrianglesByGroup( dpid group_id, std::list<model_triangle_instance_ref *> *l ); //create animation instances void makeAnimations( dpthread_lock *thd, model_writelock *ml ); //destroy animation instances void killAnimations( void ); //sync animation instances void syncAnimations( dpthread_lock *thd, model_writelock *ml ); //get animation instances unsigned int getAnimations( std::list<model_animation_instance_ref *> *l ); //create joint instances void makeJoints( dpthread_lock *thd, model_writelock *ml ); //destroy joint instances void killJoints( void ); //sync joint instances void syncJoints( dpthread_lock *thd, model_writelock *ml ); //get joint instances unsigned int getJoints( std::list<model_joint_instance_ref *> *l ); public: //ctor model_instance( dpthread_lock *thd, model_writelock *ml, dpid id ); //dtor virtual ~model_instance( void ); //release list returned by getGroups() static void releaseGetGroups( std::list<model_group_instance_ref *> *l ); //release list returned by getTriangles() static void releaseGetTriangles( std::list<model_triangle_instance_ref *> *l ); //release list returned by getAnimations() static void releaseGetAnimations( std::list<model_animation_instance_ref *> *l ); //release list returned by getJoints() static void releaseGetJoints( std::list<model_joint_instance_ref *> *l ); friend class model_instance_readlock; friend class model_instance_writelock; }; }; #endif
81dda37183f0c5394bb3258e02f2670abf3f6b7f
8722f2da8bc1a6b3e16ce5759f67ca292c0a7341
/src/beast/beast/utility/impl/Journal.cpp
5d30544087de3c7ca9cbea5e67d01b19a7afa955
[ "MIT", "MIT-Wu", "ISC", "BSL-1.0" ]
permissive
waynezu/vpal20
010fbec860b6c4d8c775b8d637730580e842d597
8deef35521417cd4405d7bbadd030b89bd4fb91b
refs/heads/master
2020-12-25T21:35:01.584301
2014-10-27T03:58:56
2014-10-27T03:58:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,983
cpp
//------------------------------------------------------------------------------ /* Portions of this file are from Vpallab: https://github.com/vpallabs Copyright (c) 2013 - 2014 - Vpallab.com. Please visit http://www.vpallab.com/ This file is part of Beast: https://github.com/vinniefalco/Beast Copyright 2013, Vinnie Falco <[email protected]> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <beast/utility/Journal.h> #include <beast/module/core/memory/SharedSingleton.h> namespace beast { //------------------------------------------------------------------------------ // A Sink that does nothing. class NullJournalSink : public Journal::Sink { public: bool active (Journal::Severity) const { return false; } bool console() const { return false; } void console (bool) { } Journal::Severity severity() const { return Journal::kDisabled; } void severity (Journal::Severity) { } void write (Journal::Severity, std::string const&) { } }; //------------------------------------------------------------------------------ Journal::Sink& Journal::getNullSink () { return *SharedSingleton <NullJournalSink>::get ( SingletonLifetime::neverDestroyed); } //------------------------------------------------------------------------------ Journal::Sink::Sink () : m_level (kWarning) , m_console (false) { } Journal::Sink::~Sink () { } bool Journal::Sink::active (Severity level) const { return level >= m_level; } bool Journal::Sink::console () const { return m_console; } void Journal::Sink::console (bool output) { m_console = output; } Journal::Severity Journal::Sink::severity () const { return m_level; } void Journal::Sink::severity (Severity level) { m_level = level; } //------------------------------------------------------------------------------ Journal::ScopedStream::ScopedStream (Stream const& stream) : m_sink (stream.sink ()) , m_level (stream.severity ()) , m_active (stream.active ()) { init (); } Journal::ScopedStream::ScopedStream (ScopedStream const& other) : m_sink (other.m_sink) , m_level (other.m_level) , m_active (other.m_active) { init (); } Journal::ScopedStream::ScopedStream ( Stream const& stream, std::ostream& manip (std::ostream&)) : m_sink (stream.sink ()) , m_level (stream.severity ()) , m_active (stream.active ()) { init (); if (active ()) m_ostream << manip; } Journal::ScopedStream::~ScopedStream () { if (active ()) { std::string const& s (m_ostream.str()); if (! s.empty ()) { if (s == "\n") m_sink.write (m_level, ""); else m_sink.write (m_level, s); } } } void Journal::ScopedStream::init () { // Modifiers applied from all ctors m_ostream << std::boolalpha << std::showbase //<< std::hex ; } std::ostream& Journal::ScopedStream::operator<< (std::ostream& manip (std::ostream&)) const { return m_ostream << manip; } std::ostringstream& Journal::ScopedStream::ostream () const { return m_ostream; } //------------------------------------------------------------------------------ Journal::Stream::Stream () : m_sink (&getNullSink ()) , m_level (kDisabled) , m_disabled (true) { } Journal::Stream::Stream (Sink& sink, Severity level, bool active) : m_sink (&sink) , m_level (level) , m_disabled (! active) { bassert (level != kDisabled); } Journal::Stream::Stream (Stream const& stream, bool active) : m_sink (&stream.sink ()) , m_level (stream.severity ()) , m_disabled (! active) { } Journal::Stream::Stream (Stream const& other) : m_sink (other.m_sink) , m_level (other.m_level) , m_disabled (other.m_disabled) { } Journal::Sink& Journal::Stream::sink () const { return *m_sink; } Journal::Severity Journal::Stream::severity () const { return m_level; } bool Journal::Stream::active () const { return ! m_disabled && m_sink->active (m_level); } Journal::Stream& Journal::Stream::operator= (Stream const& other) { m_sink = other.m_sink; m_level = other.m_level; return *this; } Journal::ScopedStream Journal::Stream::operator<< ( std::ostream& manip (std::ostream&)) const { return ScopedStream (*this, manip); } //------------------------------------------------------------------------------ Journal::Journal () : m_sink (&getNullSink()) , m_level (kDisabled) , trace (stream (kTrace)) , debug (stream (kDebug)) , info (stream (kInfo)) , warning (stream (kWarning)) , error (stream (kError)) , fatal (stream (kFatal)) { } Journal::Journal (Sink& sink, Severity level) : m_sink (&sink) , m_level (level) , trace (stream (kTrace)) , debug (stream (kDebug)) , info (stream (kInfo)) , warning (stream (kWarning)) , error (stream (kError)) , fatal (stream (kFatal)) { } Journal::Journal (Journal const& other) : m_sink (other.m_sink) , m_level (other.m_level) , trace (stream (kTrace)) , debug (stream (kDebug)) , info (stream (kInfo)) , warning (stream (kWarning)) , error (stream (kError)) , fatal (stream (kFatal)) { } Journal::Journal (Journal const& other, Severity level) : m_sink (other.m_sink) , m_level (std::max (other.m_level, level)) , trace (stream (kTrace)) , debug (stream (kDebug)) , info (stream (kInfo)) , warning (stream (kWarning)) , error (stream (kError)) , fatal (stream (kFatal)) { } Journal::~Journal () { } Journal::Sink& Journal::sink() const { return *m_sink; } Journal::Stream Journal::stream (Severity level) const { return Stream (*m_sink, level, level >= m_level); } bool Journal::active (Severity level) const { if (level == kDisabled) return false; if (level < m_level) return false; return m_sink->active (level); } Journal::Severity Journal::severity () const { return m_level; } }
f6b07200e5d08b0dc5cc0326789f10fd11232117
4508566a6dc2af865b2cdb25f0ae093422586c76
/client/task/compiler_flag_utils.h
2c15ce6e868e53705925a171f91d5df72bb7f1f9
[ "BSD-3-Clause" ]
permissive
dzeromsk/goma
687239094e7a5bbbc4d131eb1b63446f791eb11b
350f67319eb985013515b533f03f2f95570c37d3
refs/heads/master
2020-03-27T06:43:57.094414
2019-03-18T04:49:09
2019-03-19T13:26:11
146,130,866
4
0
null
null
null
null
UTF-8
C++
false
false
600
h
// Copyright 2019 The Goma Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Functions for initializing or otherwise manipulating CompilerFlags after // they are parsed, as part of the CompileTask process. #ifndef DEVTOOLS_GOMA_CLIENT_TASK_COMPILER_FLAG_UTILS_H_ #define DEVTOOLS_GOMA_CLIENT_TASK_COMPILER_FLAG_UTILS_H_ namespace devtools_goma { class ClangTidyFlags; void InitClangTidyFlags(ClangTidyFlags* flags); } // namespace devtools_goma #endif // DEVTOOLS_GOMA_CLIENT_TASK_COMPILER_FLAG_UTILS_H_
54dc56169b76d52f6322a6e1d5e78fe111b4214b
724ddc05b5577021cef39c5f82228a4e66ca1dff
/catkin_ws/devel/include/srrg_core_ros/ImageMapNodeMsg.h
7e44c2b0caeed0d569c879abf3a2e13a1c695382
[]
no_license
serenaferracci/FiRo-Robot-Cercatore
7df8cabd50f7f49a8890fc882c4745c90fc46854
d7cae408f860ede756bb35b78a527747b12b8c10
refs/heads/master
2022-04-10T13:12:48.854240
2020-03-04T09:09:42
2020-03-04T09:09:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,832
h
// Generated by gencpp from file srrg_core_ros/ImageMapNodeMsg.msg // DO NOT EDIT! #ifndef SRRG_CORE_ROS_MESSAGE_IMAGEMAPNODEMSG_H #define SRRG_CORE_ROS_MESSAGE_IMAGEMAPNODEMSG_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <geometry_msgs/Pose.h> namespace srrg_core_ros { template <class ContainerAllocator> struct ImageMapNodeMsg_ { typedef ImageMapNodeMsg_<ContainerAllocator> Type; ImageMapNodeMsg_() : id(0) , timestamp(0.0) , transform() , parents() , topic() , seq(0) , camera_info(0) { } ImageMapNodeMsg_(const ContainerAllocator& _alloc) : id(0) , timestamp(0.0) , transform(_alloc) , parents(_alloc) , topic(_alloc) , seq(0) , camera_info(0) { (void)_alloc; } typedef int32_t _id_type; _id_type id; typedef double _timestamp_type; _timestamp_type timestamp; typedef ::geometry_msgs::Pose_<ContainerAllocator> _transform_type; _transform_type transform; typedef std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other > _parents_type; _parents_type parents; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _topic_type; _topic_type topic; typedef int32_t _seq_type; _seq_type seq; typedef int32_t _camera_info_type; _camera_info_type camera_info; typedef boost::shared_ptr< ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> const> ConstPtr; }; // struct ImageMapNodeMsg_ typedef ::srrg_core_ros::ImageMapNodeMsg_<std::allocator<void> > ImageMapNodeMsg; typedef boost::shared_ptr< ::srrg_core_ros::ImageMapNodeMsg > ImageMapNodeMsgPtr; typedef boost::shared_ptr< ::srrg_core_ros::ImageMapNodeMsg const> ImageMapNodeMsgConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> & v) { ros::message_operations::Printer< ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace srrg_core_ros namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'srrg_core_ros': ['/home/serena/catkin_ws/src/srrg_core_ros/msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> > { static const char* value() { return "e985cff8cfffd7e6dc32c72765456daa"; } static const char* value(const ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xe985cff8cfffd7e6ULL; static const uint64_t static_value2 = 0xdc32c72765456daaULL; }; template<class ContainerAllocator> struct DataType< ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> > { static const char* value() { return "srrg_core_ros/ImageMapNodeMsg"; } static const char* value(const ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> > { static const char* value() { return "int32 id\n\ float64 timestamp\n\ geometry_msgs/Pose transform\n\ int32[] parents\n\ string topic\n\ int32 seq\n\ int32 camera_info\n\ ================================================================================\n\ MSG: geometry_msgs/Pose\n\ # A representation of pose in free space, composed of position and orientation. \n\ Point position\n\ Quaternion orientation\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Point\n\ # This contains the position of a point in free space\n\ float64 x\n\ float64 y\n\ float64 z\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Quaternion\n\ # This represents an orientation in free space in quaternion form.\n\ \n\ float64 x\n\ float64 y\n\ float64 z\n\ float64 w\n\ "; } static const char* value(const ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.id); stream.next(m.timestamp); stream.next(m.transform); stream.next(m.parents); stream.next(m.topic); stream.next(m.seq); stream.next(m.camera_info); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct ImageMapNodeMsg_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::srrg_core_ros::ImageMapNodeMsg_<ContainerAllocator>& v) { s << indent << "id: "; Printer<int32_t>::stream(s, indent + " ", v.id); s << indent << "timestamp: "; Printer<double>::stream(s, indent + " ", v.timestamp); s << indent << "transform: "; s << std::endl; Printer< ::geometry_msgs::Pose_<ContainerAllocator> >::stream(s, indent + " ", v.transform); s << indent << "parents[]" << std::endl; for (size_t i = 0; i < v.parents.size(); ++i) { s << indent << " parents[" << i << "]: "; Printer<int32_t>::stream(s, indent + " ", v.parents[i]); } s << indent << "topic: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.topic); s << indent << "seq: "; Printer<int32_t>::stream(s, indent + " ", v.seq); s << indent << "camera_info: "; Printer<int32_t>::stream(s, indent + " ", v.camera_info); } }; } // namespace message_operations } // namespace ros #endif // SRRG_CORE_ROS_MESSAGE_IMAGEMAPNODEMSG_H
b6d7a15b7724b6842129701a87e76e9cd03cff31
4764318065e8eaa8a964a5beadaa964cba3a18e2
/Programowanie Obiektowe/16_Powtorzenie/3i4i5.cpp
5c64e172b7a977dca838365e244bcc03820bcf47
[ "MIT" ]
permissive
GrPe/UMCS-Public
847cc5b7ef76b75fbd67b1eae59a855261be649b
20caaf471bc03e77e88b104eddc1f6d80168115a
refs/heads/master
2020-04-26T09:34:07.523505
2019-10-03T12:03:45
2019-10-03T12:03:45
173,460,077
2
2
null
null
null
null
WINDOWS-1250
C++
false
false
3,308
cpp
#include <list> #include <string> #include <sstream> #include <stdexcept> // do out_of_range #include <iostream>// do ostream i maina using namespace std; class StringList { list<string> listOfStrings; //operatory poza klasą musza byc zaprzyjaznione friend StringList operator+(const StringList& stringList,string str); friend StringList operator-(const StringList& stringList, string str); //do zadania 4 friend ostream& operator<<(ostream& os, StringList& stringList); //przydaloby sie cos co przechowa nam informacje, ktore slowo obecnie mamy przekazywac int pozycja{ 0 }; string getSlowo(); // metoda która bedzie zwracala nam odpowiednie slowo z listy }; StringList operator+(const StringList& stringList, string str) { StringList newStringList = stringList; // tworzymy nowy obiekt newStringList.listOfStrings.push_back(str); // twochę dlugie ale po prostu dodajemy napis do listy return newStringList; } StringList operator-(const StringList& stringList, string str) { StringList newStringList = stringList; // szukamy napisu w liscie. Fukcja find zwraca nam iterator na znaleziony element list<string>::iterator iter = find(newStringList.listOfStrings.begin(), newStringList.listOfStrings.end(), str); if (iter != newStringList.listOfStrings.end()) // albo iterator za ostatni element ( end() ) jesli nic nie znajdzie { newStringList.listOfStrings.erase(iter); // usuwamy element z listy } return newStringList; } //zadanie 4 //implentacja naszej metody //Metoda nieoptymalna ale w miare łatwa i logiczna i dziala :> string StringList::getSlowo() { auto iter = listOfStrings.begin(); stringstream ss(*iter); string wyraz; for (int i = 0; i < pozycja+1; i++) // petla wczytuje wyrazy az nie dojdzie do tego, który chcemy dostac { if (!(ss >> wyraz)) // wczytujemy wyraz i jeśli się nie uda przestawiamy sie na następny napis { iter++; // przestawiamy //zadanie 5 --------------------------------------------------- //sprawdzamy czy wyszlismy poza zakres listy i jeśli tak to rzucamy wyjatek if (iter == listOfStrings.end()) { pozycja = 0; throw out_of_range("String List Out Of Range"); //wracamy na poczatek } //koniec 5 ---------------------------------------------------- ss = stringstream(*iter); // tworzymy nowy strumien i--; // zmiejszamy licznik, bo w koncu nie udało nam się nic wczytac } } pozycja++; // przestawiamy pozycje o jeden do przodu return wyraz; // zwracamy nasz wyraz; } //operator<< zawsze zwraca ostream i jako pierwszy parametr przyjmuje ostream ostream& operator<<(ostream& os, StringList& stringList) { os << stringList.getSlowo(); //Uwaga. Uzywamy naszego "os" a nie cout !!! return os; } int main() { StringList stringList; stringList = stringList + "Ala"; stringList = stringList + "ma"; stringList = stringList + "kota"; stringList = stringList + "i"; stringList = stringList + "psa"; stringList = stringList - "psa"; stringList = stringList - "psa"; //zadanie 4 i 5 try { cout << stringList << endl; cout << stringList << endl; cout << stringList << endl; cout << stringList << endl; cout << stringList << endl; } catch (exception& ex) // lapiemy wyjatek :) { cout << ex.what() << endl; } cout << stringList << endl; return 0; }
7816beec972c1d8629d8b9a006d779456f000d47
d4100eddb658f1dadc262e7ee4f996bafed87160
/src/engine/material.hpp
723ffb8c50796a83447a725d4d7ab978ba83e443
[]
no_license
MrDanTheMan/labour-day
be851db78069f02d9e4eaa0b1d2e5c535d5499e2
f0fb0662fa246db19922d86ec5ca1fd1238221a5
refs/heads/master
2021-06-25T13:51:05.113118
2020-11-18T01:47:36
2020-11-18T01:47:36
213,165,982
0
0
null
2020-11-18T01:47:37
2019-10-06T12:38:53
C++
UTF-8
C++
false
false
710
hpp
#ifndef MATERIAL_HPP_ #define MATERIAL_HPP_ #include "shaderprog.hpp" #include "shaderparam.hpp" #include "types.hpp" #include "texture2d.hpp" #include <map> #include <vector> #include "debugging.hpp" namespace Engine { class Material : public IResource { public: Material(const ShaderProg &shader); Material(const Material &rhs) = delete; ShaderParamCollection* const ShaderParameters(); const ShaderParamCollection* const ShaderParameters() const; const ShaderProg* Shader() const; virtual void Unload() override; private: std::unique_ptr<ShaderParamCollection> m_params; const ShaderProg *m_shader; }; } #endif
a828edd7ab7cf90b67426780bc06f97d4e258061
fc33c65cdb4933b349c4513e5701ba7d3cd53df9
/include/ans/uuid_class.hpp
c6be484ee2d51df83c1ecb101dceba918b2631af
[]
no_license
Answeror/ans
ff9abbc1c7fa977a3bcd77c2d753f1de7947a3da
7cc5ce6876c0b488a56e0bc7dbc7bbe1fdcb2996
refs/heads/master
2021-01-20T06:25:13.715741
2012-10-15T15:17:05
2012-10-15T15:17:05
1,858,037
0
0
null
null
null
null
UTF-8
C++
false
false
692
hpp
#ifndef ANS_UUID_CLASS_HPP #define ANS_UUID_CLASS_HPP #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> namespace ans { class uuid_class : public boost::uuids::uuid { public: struct uuid_extractor { const boost::uuids::uuid & operator ()(const boost::uuids::uuid &arg) { return arg; } }; public: uuid_class() : boost::uuids::uuid(boost::uuids::random_generator()()) {} explicit uuid_class(boost::uuids::uuid const& u) : boost::uuids::uuid(u) {} public: const boost::uuids::uuid & uuid() const { return static_cast<const boost::uuids::uuid&>(*this); } }; } // ans #endif
[ "Answeror@.(none)" ]
Answeror@.(none)
c23ed35b86891f6267c912cb855370ae89a13253
cea74570a5a2511e68e4ba968220cd4bbb13c516
/OpenSauce/shared/Include/blamlib/Halo1/hs/hs_runtime.cpp
77f2e93f8d52972288ec567fbdd49d5b644ec7fe
[]
no_license
Dwood15/OpenSauce_Upgrade
80bbc88fbf34340323d28ccd03623a103a27e714
d48cf4819ed371beb4f6e9426f8ab8bcd67fe2b3
refs/heads/master
2021-05-04T18:35:39.132266
2018-02-18T01:26:48
2018-02-18T01:26:48
120,191,658
5
0
null
null
null
null
UTF-8
C++
false
false
14,132
cpp
/* Yelo: Open Sauce SDK See license\OpenSauce\OpenSauce for specific license information */ #include "Common/Precompile.hpp" #include <blamlib/Halo1/hs/hs_runtime.hpp> #include <blamlib/Halo1/game/game_time.hpp> #include <blamlib/Halo1/hs/hs_library_internal.hpp> #include <blamlib/Halo1/hs/hs_structures.hpp> #include <blamlib/Halo1/hs/hs_runtime_structures.hpp> #include <blamlib/Halo1/hs/hs_threads.hpp> #include <blamlib/Halo1/hs/hs_types.hpp> #include <blamlib/Halo1/hs/object_lists.hpp> #include <blamlib/Halo1/main/editor.hpp> #include <blamlib/Halo1/objects/objects.hpp> #include <blamlib/Halo1/scenario/scenario.hpp> #include <blamlib/Halo1/scenario/scenario_definitions.hpp> #include <YeloLib/Halo1/hs/hs_library_definitions_yelo.hpp> #include <blamlib/Halo1/hs/hs_library_internal_runtime.inl> namespace Yelo { namespace blam { using namespace Scripting; /*static*/ void hs_global_reconcile_read(int32 global_index); // TODO static s_hs_value_union hs_global_evaluate(int32 global_index) { hs_global_reconcile_read(global_index); bool is_internal = (global_index & Enums::_hs_global_index_is_external_mask) == 0; global_index &= Enums::_hs_global_index_mask; // the global is internal, so it comes after all the defined external globals in the hs_globals array if (is_internal) { global_index += CAST(int32, c_hs_library::GetExternalGlobals().size()); } datum_index hs_global_index; hs_global_index.index = CAST(datum_index::index_t, global_index); return HsGlobals()[hs_global_index]->value; } void hs_evaluate(datum_index thread_index, datum_index expression_index, s_hs_value_union* destination) { s_hs_thread_datum* thread = hs_thread_get(thread_index); const hs_syntax_node* expression = thread->GetSyntax(expression_index); YELO_HS_THREAD_VALID_STACK(thread); YELO_ASSERT(destination); // engine doesn't do this. I kinda want to make destination a ref... if (TEST_FLAG(expression->flags, Flags::_hs_syntax_node_primitive_bit)) { if (TEST_FLAG(expression->flags, Flags::_hs_syntax_node_global_index_bit)) { int16 global_index = expression->value.int16; auto global_value = hs_global_evaluate(global_index); *destination = hs_cast(thread_index, hs_global_get_type(global_index), expression->type, global_value); } else // else, it's a constant { *destination = hs_cast(thread_index, expression->constant_type, expression->type, expression->value); } } else { thread->StackPush(); thread->flags |= FLAG(Flags::_hs_thread_datum_has_new_stack_frame_bit); auto* stack_frame = thread->stack_frame; stack_frame->source_expression = expression_index; stack_frame->result_reference = destination; } } static s_hs_value_union* hs_arguments_evaluate(datum_index thread_index, size_t formal_parameters_count, const Enums::hs_type* formal_parameters, bool initialize_stack) { s_hs_thread_datum* thread = hs_thread_get(thread_index); auto* formal_parameters_values = thread->StackAllocate<s_hs_value_union>(formal_parameters_count); auto* argument_index = thread->StackAllocate<uint32>(); auto* expression_index = thread->StackAllocate<datum_index>(); if (initialize_stack) { *argument_index = 0; const auto* call_expression = thread->GetFrameSyntax(); datum_index first_arg_expression_index = call_expression->value.ToExpressionIndex(); *expression_index = thread->GetSyntax(first_arg_expression_index)->next_expression; } if (*argument_index < formal_parameters_count) { YELO_HS_RUNTIME_ASSERT(!expression_index->IsNull(), thread, "corrupted syntax tree."); if (YELO_HS_THREAD_SCRIPT_ERROR( thread->GetSyntax(*expression_index)->type==formal_parameters[*argument_index], thread, "unexpected actual parameters")) { return formal_parameters_values; } hs_evaluate(thread_index, *expression_index, &formal_parameters_values[*argument_index]); // set the args evaluator state to the next parameter const auto* parameter_expression = thread->GetSyntax(*expression_index); *expression_index = parameter_expression->next_expression; (*argument_index)++; // we haven't evaluated all the parameters just yet return nullptr; } // the last parameter's next_expression index should be NONE, so this should be true at this point YELO_HS_RUNTIME_ASSERT(expression_index->IsNull(), thread, "corrupted syntax tree."); return formal_parameters_values; } static void hs_script_evaluate(datum_index thread_index, bool initialize_stack, int16 script_index) { s_hs_thread_datum* thread = hs_thread_get(thread_index); datum_index root_expression_index = global_scenario_get()->scripts[script_index].script.root_expression_index; auto* result = thread->StackAllocate<s_hs_value_union>(); if (initialize_stack) { hs_evaluate(thread_index, root_expression_index, result); } else { hs_return(thread_index, *result); } } static void hs_function_evaluate(datum_index thread_index, bool initialize_stack, int16 function_index) { auto* function = hs_function_get(function_index); YELO_ASSERT(function->evaluate); function->evaluate(function_index, thread_index, initialize_stack); } void hs_call_evaluate(datum_index thread_index) { s_hs_thread_datum* thread = hs_thread_get(thread_index); const hs_syntax_node* expression = thread->GetFrameSyntax(); bool initialize_stack = TEST_FLAG(thread->flags, Flags::_hs_thread_datum_has_new_stack_frame_bit); SET_FLAG(thread->flags, Flags::_hs_thread_datum_has_new_stack_frame_bit, false); if (expression->IsScriptCall()) { hs_script_evaluate(thread_index, initialize_stack, expression->script_index); } else // else, a function index { hs_function_evaluate(thread_index, initialize_stack, expression->function_index); } } // take hs_runtime_globals as a parameter until we define it in our own code static void hs_thread_main(datum_index thread_index, s_hs_runtime_globals& hs_runtime_globals) { hs_runtime_globals.executing_thread_index = thread_index.index; s_hs_thread_datum* thread = hs_thread_get(thread_index); bool delete_thread; thread->Main(thread_index, hs_runtime_globals.enabled, delete_thread); if (delete_thread) HsThreads().Delete(thread_index); hs_runtime_globals.executing_thread_index = NONE; } static void hs_runtime_garbage_collect_nodes() { // only try to gc twice a second const auto k_update_rate = K_TICKS_PER_SECOND / 2; auto game_time = blam::game_time_get(); if (game_time / k_update_rate) hs_nodes_garbage_collect(); } void hs_runtime_update() { auto hs_runtime_globals = HsRuntimeGlobals(); if (!hs_runtime_globals->enabled) return; auto game_time = blam::game_time_get(); bool gc_nodes = false; // NOTE: engine seems to use a for(;;) using data_next_index() on threads for (auto thread : HsThreads()) { // execute all threads related to console commands if (thread->type == Enums::_hs_thread_type_runtime_evaluate) { gc_nodes = true; } // by default, the editor doesn't run game scripts else if (!hs_runtime_globals->run_game_scripts || game_in_editor()) continue; if (thread->NotKilledOrDormant() && thread->NotSleeping(game_time)) { hs_thread_main(thread.index, *hs_runtime_globals); } // something executed in the thread which disabled the runtime, stop updating if (!hs_runtime_globals->enabled) break; } object_lists_garbage_collect(); if (gc_nodes) hs_runtime_garbage_collect_nodes(); } s_hs_value_union* hs_macro_function_evaluate(int16 function_index, datum_index thread_index, bool initialize_stack) { const auto* function = hs_function_get(function_index); return hs_arguments_evaluate(thread_index, CAST(size_t, function->paramc), function->params, initialize_stack); } void hs_return(datum_index thread_index, s_hs_value_union value) { s_hs_thread_datum* thread = hs_thread_get(thread_index); // engine did this after it the hs_syntax_get call, but that makes no sense! YELO_HS_THREAD_VALID_STACK(thread); const hs_syntax_node* call_expression = thread->GetSyntax(thread->stack_frame->source_expression); Enums::hs_type actual_type; if (call_expression->IsScriptCall()) { const auto& script = global_scenario_get()->scripts[call_expression->script_index]; actual_type = script.script.return_type; } else // hs_function call { const hs_function_definition* function = hs_function_get(call_expression->function_index); actual_type = function->return_type; } *thread->stack_frame->previous->result_reference = hs_cast(thread_index, actual_type, call_expression->type, value); thread->StackPop(); } static bool hs_object_type_can_cast(Enums::hs_object_type actual_type, Enums::hs_object_type desired_type) { YELO_ASSERT(actual_type >= 0 && actual_type < Enums::k_number_of_hs_object_types); YELO_ASSERT(desired_type >= 0 && desired_type < Enums::k_number_of_hs_object_types); auto actual_type_mask = k_hs_object_type_masks[actual_type]; auto desired_type_mask = k_hs_object_type_masks[desired_type]; return (actual_type_mask & desired_type) == desired_type; } bool hs_can_cast(Enums::hs_type actual_type, Enums::hs_type desired_type) { YELO_ASSERT(actual_type==Enums::_hs_passthrough || hs_type_valid(actual_type)); YELO_ASSERT(hs_type_valid(desired_type)); if (actual_type == Enums::_hs_passthrough || actual_type == desired_type) return true; // desired object is an object reference else if (hs_type_is_object(desired_type)) { auto desired_object_type = CAST(Enums::hs_object_type, desired_type - Enums::_hs_type_object__first); // can the desired object type be casted to the actual object type? if (hs_type_is_object(actual_type)) { auto actual_object_type = CAST(Enums::hs_object_type, actual_type - Enums::_hs_type_object__first); return hs_object_type_can_cast(actual_object_type, desired_object_type); } // can the desired object type be casted to the actual object type via an object name? else if (hs_type_is_object_name(actual_type)) { auto actual_object_type = CAST(Enums::hs_object_type, actual_type - Enums::_hs_type_object_name__first); return hs_object_type_can_cast(actual_object_type, desired_object_type); } // no other means of converting an hs object return false; } // desired type is an object name else if (hs_type_is_object_name(desired_type)) { auto desired_object_type = CAST(Enums::hs_object_type, desired_type - Enums::_hs_type_object_name__first); // can the desired named object type be casted to the actual object type via an object name? if (hs_type_is_object_name(actual_type)) { auto actual_object_type = CAST(Enums::hs_object_type, actual_type - Enums::_hs_type_object_name__first); return hs_object_type_can_cast(actual_object_type, desired_object_type); } // no other means of converting an hs object return false; } return k_hs_typecasting_procedures[actual_type][desired_type] != nullptr; } s_hs_value_union hs_cast(datum_index thread_index, Enums::hs_type actual_type, Enums::hs_type desired_type, s_hs_value_union value) { YELO_HS_RUNTIME_ASSERT(hs_can_cast(actual_type, desired_type), hs_thread_get(thread_index), "bad typecast."); if (actual_type == desired_type || actual_type == Enums::_hs_passthrough) return value; else if (!hs_type_is_object_name(desired_type) && hs_type_is_object(desired_type) && hs_type_is_object_name(actual_type)) { value.datum = object_index_from_name_index(value.int16); return value; } return k_hs_typecasting_procedures[actual_type][desired_type](value); } static datum_index hs_thread_new(Enums::hs_thread_type type, hs_script_index_t script = hs_script_index_t::k_null) { YELO_ASSERT(type>=0 && type<Enums::k_number_of_hs_thread_types); YELO_ASSERT(type!=Enums::_hs_thread_type_script || !script.IsNull()); datum_index thread_index = HsThreads().New(); if (thread_index.IsNull()) return thread_index; s_hs_thread_datum* thread = hs_thread_get(thread_index); thread->Initialize(type); if (type == Enums::_hs_thread_type_script) thread->InitializeForScript(script); return thread_index; } s_hs_value_union hs_runtime_evaluate(datum_index expression_index, datum_index script_container_index) { // TODO: update code when containers come online auto hs_runtime_globals = HsRuntimeGlobals(); if (!hs_runtime_globals->enabled || expression_index.IsNull()) return k_none_value_union; datum_index thread_index = hs_thread_new(Enums::_hs_thread_type_runtime_evaluate); if (thread_index.IsNull()) { // NOTE: added parameters to error. still need a better description to display YELO_ERROR_FAILURE("there are not enough threads to execute that command (%X in %X).", expression_index, script_container_index); return k_none_value_union; } s_hs_thread_datum* thread = hs_thread_get(thread_index); hs_evaluate(thread_index, expression_index, &thread->result); if (TEST_FLAG(thread->flags, Flags::_hs_thread_datum_has_new_stack_frame_bit)) { hs_thread_main(thread_index, *hs_runtime_globals); return k_none_value_union; } return thread->result; } datum_index hs_find_thread_by_script(hs_script_index_t script) { // TODO: update code when containers come online // NOTE: engine seems to use a for(;;) using data_next_index() on threads for (auto thread : HsThreads()) { // NOTE: engine doesn't validate type before comparing the index if (thread->type == Enums::_hs_thread_type_script && thread->script_index == script.script_index) { return thread.index; } } return datum_index::null; } }; };
512a15e5d57d1b5c6c36611fb53934670ecf992d
fd03d6970e04a671ee13c955914ce52760bc48a8
/src/main.cpp
661b3eb8e29f2229b43b504bd33f225f7b0577db
[]
no_license
hanbinhu/HGSPICE
103b1997817d2168283d9c853aaed604fb9b3864
80fb4d41235bbd1cfad46e9fb36eedd29ca85abd
refs/heads/master
2020-04-11T09:57:59.630741
2017-07-08T21:22:10
2017-07-08T21:22:10
22,645,976
1
0
null
null
null
null
UTF-8
C++
false
false
451
cpp
#include <iostream> #include "Ckt.h" #include "SpParser.hpp" extern FILE *yyin; using namespace std; int main(int argc, char *argv[]) { if(argc != 2) cout << "Usage: HGSPICE <Test Circuit>" << endl; else { if (!(yyin = fopen(argv[1], "r"))) { cout << argv[1] << " doesn't exist." << endl; exit(1); } Ckt *pObj = new Ckt(); yy::SpParser spiceParser(pObj); spiceParser.parse(); pObj->Summarize(); delete pObj; } return 0; }
02a40553aad072a44990babf7b9c63b6cfd6514e
fcc3517ce21174a87a3d9ae66ea897bc009557bc
/SakuraGUI/SakuraListBox.cpp
489d8d4ad83c609c36ecc97771a61e945a84dd97
[]
no_license
Alopex6414/SakuraGUI
f144db5c3fcd70c66ba4d268de1fa3a67da758bd
ff9856c54728cb6cd4dc2a3d67d5b92f47b4d17b
refs/heads/master
2020-04-03T15:42:50.270496
2018-12-05T02:26:11
2018-12-05T02:26:11
155,373,808
0
0
null
null
null
null
GB18030
C++
false
false
20,076
cpp
/* * COPYRIGHT NOTICE * Copyright(c) 2018, Team Shanghai Dream Equinox * All rights reserved. * * @file SakuraListBox.cpp * @brief This File is SakuraGUI DLL Project. * @author Alopex/Helium * @version v1.00a * @date 2018-12-04 v1.00a alopex Create Project. */ #include "SakuraDialog.h" #include "SakuraListBox.h" // SakuraGUI 列表框派生类(UI) //------------------------------------------------------------------ // @Function: CSakuraListBox() // @Purpose: CSakuraListBox构造函数 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ CSakuraListBox::CSakuraListBox(CSakuraDialog* pDialog) { m_eType = SAKURA_CONTROL_LISTBOX; m_pDialog = pDialog; m_dwStyle = 0; m_nSBWidth = 16; m_nSelected = -1; m_nSelStart = 0; m_bDrag = false; m_nBorder = 6; m_nMargin = 5; m_nTextHeight = 0; } //------------------------------------------------------------------ // @Function: ~CSakuraListBox() // @Purpose: CSakuraListBox析构函数 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ CSakuraListBox::~CSakuraListBox() { RemoveAllItems(); } //------------------------------------------------------------------ // @Function: OnInit() // @Purpose: CSakuraListBox控件初始化 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ HRESULT SAKURALISTBOX_CALLMETHOD CSakuraListBox::OnInit() { return m_pDialog->InitControl(&m_ScrollBar); } //------------------------------------------------------------------ // @Function: CanHaveFocus() // @Purpose: CSakuraListBox是否拥有焦点 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ bool SAKURALISTBOX_CALLMETHOD CSakuraListBox::CanHaveFocus() { return (m_bVisible && m_bEnabled); } //------------------------------------------------------------------ // @Function: HandleKeyboard() // @Purpose: CSakuraListBox键盘消息响应 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ bool SAKURALISTBOX_CALLMETHOD CSakuraListBox::HandleKeyboard(UINT uMsg, WPARAM wParam, LPARAM lParam) { if (!m_bEnabled || !m_bVisible) { return false; } if (m_ScrollBar.HandleKeyboard(uMsg, wParam, lParam)) { return true; } switch (uMsg) { case WM_KEYDOWN: switch (wParam) { case VK_UP: case VK_DOWN: case VK_NEXT: case VK_PRIOR: case VK_HOME: case VK_END: { if (m_Items.size() == 0) { return true; } int nOldSelected = m_nSelected; switch (wParam) { case VK_UP: { --m_nSelected; break; } case VK_DOWN: { ++m_nSelected; break; } case VK_NEXT: { m_nSelected += m_ScrollBar.GetPageSize() - 1; break; } case VK_PRIOR: { m_nSelected -= m_ScrollBar.GetPageSize() - 1; break; } case VK_HOME: { m_nSelected = 0; break; } case VK_END: { m_nSelected = m_Items.size() - 1; break; } } if (m_nSelected < 0) { m_nSelected = 0; } if (m_nSelected >= (int)m_Items.size()) { m_nSelected = m_Items.size() - 1; } if (nOldSelected != m_nSelected) { if (m_dwStyle & MULTISELECTION) { for (int i = 0; i < (int)m_Items.size(); ++i) { CSakuraListBoxItem* pItem = m_Items[i]; pItem->bSelected = false; } if (GetKeyState(VK_SHIFT) < 0) { int nEnd = __max(m_nSelStart, m_nSelected); for (int n = __min(m_nSelStart, m_nSelected); n <= nEnd; ++n) { m_Items[n]->bSelected = true; } } else { m_Items[m_nSelected]->bSelected = true; m_nSelStart = m_nSelected; } } else { m_nSelStart = m_nSelected; } m_ScrollBar.ShowItem(m_nSelected); m_pDialog->SendEvent(EVENT_LISTBOX_SELECTION, true, this); } return true; } case VK_SPACE: m_pDialog->SendEvent(EVENT_LISTBOX_ITEM_DBLCLK, true, this); return true; } break; } return false; } //------------------------------------------------------------------ // @Function: HandleMouse() // @Purpose: CSakuraListBox鼠标消息响应 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ bool SAKURALISTBOX_CALLMETHOD CSakuraListBox::HandleMouse(UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam) { if (!m_bEnabled || !m_bVisible) { return false; } if (WM_LBUTTONDOWN == uMsg) { if (!m_bHasFocus) { m_pDialog->RequestFocus(this); } } if (m_ScrollBar.HandleMouse(uMsg, pt, wParam, lParam)) { return true; } switch (uMsg) { case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: if (m_Items.size() > 0 && PtInRect(&m_rcSelection, pt)) { int nClicked; if (m_nTextHeight) { nClicked = m_ScrollBar.GetTrackPos() + (pt.y - m_rcText.top) / m_nTextHeight; } else { nClicked = -1; } if (nClicked >= m_ScrollBar.GetTrackPos() && nClicked < (int)m_Items.size() && nClicked < m_ScrollBar.GetTrackPos() + m_ScrollBar.GetPageSize()) { m_bDrag = true; if (uMsg == WM_LBUTTONDBLCLK) { m_pDialog->SendEvent(EVENT_LISTBOX_ITEM_DBLCLK, true, this); return true; } m_nSelected = nClicked; if (!(wParam & MK_SHIFT)) { m_nSelStart = m_nSelected; } if (m_dwStyle & MULTISELECTION) { CSakuraListBoxItem* pSelItem = m_Items.at(m_nSelected); if ((wParam & (MK_SHIFT | MK_CONTROL)) == MK_CONTROL) { pSelItem->bSelected = !pSelItem->bSelected; } else if ((wParam & (MK_SHIFT | MK_CONTROL)) == MK_SHIFT) { int nBegin = __min(m_nSelStart, m_nSelected); int nEnd = __max(m_nSelStart, m_nSelected); for (int i = 0; i < nBegin; ++i) { CSakuraListBoxItem* pItem = m_Items.at(i); pItem->bSelected = false; } for (int i = nEnd + 1; i < (int)m_Items.size(); ++i) { CSakuraListBoxItem* pItem = m_Items.at(i); pItem->bSelected = false; } for (int i = nBegin; i <= nEnd; ++i) { CSakuraListBoxItem* pItem = m_Items.at(i); pItem->bSelected = true; } } else if ((wParam & (MK_SHIFT | MK_CONTROL)) == (MK_SHIFT | MK_CONTROL)) { int nBegin = __min(m_nSelStart, m_nSelected); int nEnd = __max(m_nSelStart, m_nSelected); bool bLastSelected = m_Items.at(m_nSelStart)->bSelected; for (int i = nBegin + 1; i < nEnd; ++i) { CSakuraListBoxItem* pItem = m_Items.at(i); pItem->bSelected = bLastSelected; } pSelItem->bSelected = true; m_nSelected = m_nSelStart; } else { for (int i = 0; i < (int)m_Items.size(); ++i) { CSakuraListBoxItem* pItem = m_Items.at(i); pItem->bSelected = false; } pSelItem->bSelected = true; } } m_pDialog->SendEvent(EVENT_LISTBOX_SELECTION, true, this); } return true; } break; case WM_LBUTTONUP: { m_bDrag = false; if (m_nSelected != -1) { int nEnd = __max(m_nSelStart, m_nSelected); for (int n = __min(m_nSelStart, m_nSelected) + 1; n < nEnd; ++n) { m_Items[n]->bSelected = m_Items[m_nSelStart]->bSelected; } m_Items[m_nSelected]->bSelected = m_Items[m_nSelStart]->bSelected; if (m_nSelStart != m_nSelected) { m_pDialog->SendEvent(EVENT_LISTBOX_SELECTION, true, this); } m_pDialog->SendEvent(EVENT_LISTBOX_SELECTION_END, true, this); } return false; } case WM_MOUSEMOVE: if (m_bDrag) { int nItem; if (m_nTextHeight) { nItem = m_ScrollBar.GetTrackPos() + (pt.y - m_rcText.top) / m_nTextHeight; } else { nItem = -1; } if (nItem >= (int)m_ScrollBar.GetTrackPos() && nItem < (int)m_Items.size() && nItem < m_ScrollBar.GetTrackPos() + m_ScrollBar.GetPageSize()) { m_nSelected = nItem; m_pDialog->SendEvent(EVENT_LISTBOX_SELECTION, true, this); } else if (nItem < (int)m_ScrollBar.GetTrackPos()) { m_ScrollBar.Scroll(-1); m_nSelected = m_ScrollBar.GetTrackPos(); m_pDialog->SendEvent(EVENT_LISTBOX_SELECTION, true, this); } else if (nItem >= m_ScrollBar.GetTrackPos() + m_ScrollBar.GetPageSize()) { m_ScrollBar.Scroll(1); m_nSelected = __min((int)m_Items.size(), m_ScrollBar.GetTrackPos() + m_ScrollBar.GetPageSize()) - 1; m_pDialog->SendEvent(EVENT_LISTBOX_SELECTION, true, this); } } break; case WM_MOUSEWHEEL: { UINT uLines; SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &uLines, 0); int nScrollAmount = int((short)HIWORD(wParam)) / WHEEL_DELTA * uLines; m_ScrollBar.Scroll(-nScrollAmount); return true; } } return false; } //------------------------------------------------------------------ // @Function: MsgProc() // @Purpose: CSakuraListBox消息处理函数 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ bool SAKURALISTBOX_CALLMETHOD CSakuraListBox::MsgProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { return false; } //------------------------------------------------------------------ // @Function: Render() // @Purpose: CSakuraListBox渲染控件 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ void SAKURALISTBOX_CALLMETHOD CSakuraListBox::Render() { if (m_bVisible == false) { return; } m_vecElements.at(0)->GetTextureBlend().Blend(SAKURA_STATE_NORMAL); m_vecElements.at(0)->GetFontBlend().Blend(SAKURA_STATE_NORMAL, _T(""), &m_rcBoundingBox); m_vecElements.at(1)->GetTextureBlend().Blend(SAKURA_STATE_NORMAL); m_vecElements.at(1)->GetFontBlend().Blend(SAKURA_STATE_NORMAL, _T(""), &m_rcBoundingBox); if (m_Items.size() > 0) { RECT rc = m_rcText; RECT rcSel = m_rcSelection; rc.bottom = rc.top + m_pDialog->GetManager()->GetFontNode(0)->nFontSize; m_nTextHeight = rc.bottom - rc.top; static bool bSBInit; if (!bSBInit) { if (m_nTextHeight) { m_ScrollBar.SetPageSize((m_rcText.bottom - m_rcText.top) / m_nTextHeight); } else { m_ScrollBar.SetPageSize((m_rcText.bottom - m_rcText.top)); } bSBInit = true; } rc.right = m_rcText.right; for (int i = m_ScrollBar.GetTrackPos(); i < (int)m_Items.size(); ++i) { if (rc.bottom > m_rcText.bottom) { break; } CSakuraListBoxItem* pItem = m_Items.at(i); bool bSelectedStyle = false; if (!(m_dwStyle & MULTISELECTION) && i == m_nSelected) { bSelectedStyle = true; } else if (m_dwStyle & MULTISELECTION) { if (m_bDrag && ((i >= m_nSelected && i < m_nSelStart) || (i <= m_nSelected && i > m_nSelStart))) { bSelectedStyle = m_Items[m_nSelStart]->bSelected; } else if (pItem->bSelected) { bSelectedStyle = true; } } if (bSelectedStyle) { rcSel.top = rc.top; rcSel.bottom = rc.bottom; m_vecElements.at(1)->GetFontBlend().Blend(SAKURA_STATE_NORMAL, pItem->strText, &rcSel); } else { m_vecElements.at(0)->GetFontBlend().Blend(SAKURA_STATE_NORMAL, pItem->strText, &rc); } OffsetRect(&rc, 0, m_nTextHeight); } } } //------------------------------------------------------------------ // @Function: UpdateRects() // @Purpose: CSakuraListBox更新控件区域 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ void SAKURALISTBOX_CALLMETHOD CSakuraListBox::UpdateRects() { CSakuraControl::UpdateRects(); m_rcSelection = m_rcBoundingBox; m_rcSelection.right -= m_nSBWidth; InflateRect(&m_rcSelection, -m_nBorder, -m_nBorder); m_rcText = m_rcSelection; InflateRect(&m_rcText, -m_nMargin, 0); m_ScrollBar.SetLocation(m_rcBoundingBox.right - m_nSBWidth, m_rcBoundingBox.top); m_ScrollBar.SetSize(m_nSBWidth, m_nHeight); CUFont* pFontNode = m_pDialog->GetManager()->GetFontNode(0); if (pFontNode && pFontNode->nFontSize) { m_ScrollBar.SetPageSize((m_rcText.bottom - m_rcText.top) / pFontNode->nFontSize); m_ScrollBar.ShowItem(m_nSelected); } } //------------------------------------------------------------------ // @Function: GetStyle() // @Purpose: CSakuraListBox获取列表框样式 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ DWORD SAKURALISTBOX_CALLMETHOD CSakuraListBox::GetStyle() const { return m_dwStyle; } //------------------------------------------------------------------ // @Function: GetSize() // @Purpose: CSakuraListBox获取长度 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ int SAKURALISTBOX_CALLMETHOD CSakuraListBox::GetSize() const { return m_Items.size(); } //------------------------------------------------------------------ // @Function: SetStyle() // @Purpose: CSakuraListBox设置列表框样式 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ void SAKURALISTBOX_CALLMETHOD CSakuraListBox::SetStyle(DWORD dwStyle) { m_dwStyle = dwStyle; } //------------------------------------------------------------------ // @Function: GetScrollBarWidth() // @Purpose: CSakuraListBox获取滚动条宽度 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ int SAKURALISTBOX_CALLMETHOD CSakuraListBox::GetScrollBarWidth() const { return m_nSBWidth; } //------------------------------------------------------------------ // @Function: SetScrollBarWidth() // @Purpose: CSakuraListBox设置滚动条宽度 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ void SAKURALISTBOX_CALLMETHOD CSakuraListBox::SetScrollBarWidth(int nWidth) { m_nSBWidth = nWidth; UpdateRects(); } //------------------------------------------------------------------ // @Function: SetBorder() // @Purpose: CSakuraListBox设置边框宽度 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ void SAKURALISTBOX_CALLMETHOD CSakuraListBox::SetBorder(int nBorder, int nMargin) { m_nBorder = nBorder; m_nMargin = nMargin; } //------------------------------------------------------------------ // @Function: AddItem() // @Purpose: CSakuraListBox添加项 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ HRESULT SAKURALISTBOX_CALLMETHOD CSakuraListBox::AddItem(const WCHAR * wszText, void * pData) { CSakuraListBoxItem* pNewItem = new CSakuraListBoxItem(); if (!pNewItem) { return E_OUTOFMEMORY; } wcscpy_s(pNewItem->strText, 256, wszText); pNewItem->pData = pData; SetRect(&pNewItem->rcActive, 0, 0, 0, 0); pNewItem->bSelected = false; m_Items.push_back(pNewItem); m_ScrollBar.SetTrackRange(0, m_Items.size()); return S_OK; } //------------------------------------------------------------------ // @Function: InsertItem() // @Purpose: CSakuraListBox插入项 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ HRESULT SAKURALISTBOX_CALLMETHOD CSakuraListBox::InsertItem(int nIndex, const WCHAR * wszText, void * pData) { CSakuraListBoxItem* pNewItem = new CSakuraListBoxItem(); if (!pNewItem) { return E_OUTOFMEMORY; } wcscpy_s(pNewItem->strText, 256, wszText); pNewItem->pData = pData; SetRect(&pNewItem->rcActive, 0, 0, 0, 0); pNewItem->bSelected = false; m_Items.insert(m_Items.begin() + nIndex, pNewItem); m_ScrollBar.SetTrackRange(0, m_Items.size()); return S_OK; } //------------------------------------------------------------------ // @Function: RemoveItem() // @Purpose: CSakuraListBox移除项 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ void SAKURALISTBOX_CALLMETHOD CSakuraListBox::RemoveItem(int nIndex) { if (nIndex < 0 || nIndex >= (int)m_Items.size()) { return; } CSakuraListBoxItem* pItem = m_Items.at(nIndex); SAFE_DELETE(pItem); m_Items.erase(m_Items.begin() + nIndex); m_ScrollBar.SetTrackRange(0, m_Items.size()); if (m_nSelected >= (int)m_Items.size()) { m_nSelected = m_Items.size() - 1; } m_pDialog->SendEvent(EVENT_LISTBOX_SELECTION, true, this); } //------------------------------------------------------------------ // @Function: RemoveItemByData() // @Purpose: CSakuraListBox移除项(值索引) // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ void SAKURALISTBOX_CALLMETHOD CSakuraListBox::RemoveItemByData(void * pData) { } //------------------------------------------------------------------ // @Function: RemoveAllItems() // @Purpose: CSakuraListBox移除所有项 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ void SAKURALISTBOX_CALLMETHOD CSakuraListBox::RemoveAllItems() { for (int i = 0; i < m_Items.size(); ++i) { CSakuraListBoxItem* pItem = m_Items.at(i); SAFE_DELETE(pItem); } m_Items.clear(); m_ScrollBar.SetTrackRange(0, 1); } //------------------------------------------------------------------ // @Function: GetItem() // @Purpose: CSakuraListBox获取值 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ CSakuraListBoxItem *SAKURALISTBOX_CALLMETHOD CSakuraListBox::GetItem(int nIndex) { if (nIndex < 0 || nIndex >= (int)m_Items.size()) { return NULL; } return m_Items[nIndex]; } //------------------------------------------------------------------ // @Function: GetSelectedIndex() // @Purpose: CSakuraListBox获取值选中索引 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ int SAKURALISTBOX_CALLMETHOD CSakuraListBox::GetSelectedIndex(int nPreviousSelected) { if (nPreviousSelected < -1) { return -1; } if (m_dwStyle & MULTISELECTION) { for (int i = nPreviousSelected + 1; i < (int)m_Items.size(); ++i) { CSakuraListBoxItem* pItem = m_Items.at(i); if (pItem->bSelected) { return i; } } return -1; } else { return m_nSelected; } } //------------------------------------------------------------------ // @Function: GetSelectedItem() // @Purpose: CSakuraListBox获取值选中项 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ CSakuraListBoxItem *SAKURALISTBOX_CALLMETHOD CSakuraListBox::GetSelectedItem(int nPreviousSelected) { return GetItem(GetSelectedIndex(nPreviousSelected)); } //------------------------------------------------------------------ // @Function: SelectItem() // @Purpose: CSakuraListBox选中项 // @Since: v1.00a // @Para: None // @Return: None //------------------------------------------------------------------ void SAKURALISTBOX_CALLMETHOD CSakuraListBox::SelectItem(int nNewIndex) { if (m_Items.size() == 0) { return; } int nOldSelected = m_nSelected; m_nSelected = nNewIndex; if (m_nSelected < 0) { m_nSelected = 0; } if (m_nSelected >= (int)m_Items.size()) { m_nSelected = m_Items.size() - 1; } if (nOldSelected != m_nSelected) { if (m_dwStyle & MULTISELECTION) { m_Items[m_nSelected]->bSelected = true; } m_nSelStart = m_nSelected; m_ScrollBar.ShowItem(m_nSelected); } m_pDialog->SendEvent(EVENT_LISTBOX_SELECTION, true, this); }
c5da07acae3c30de58b1736f98b3d03a14f549c2
4708a9f25c9913d210649f301987400409b550a9
/test-compile/missing_time_advance_function_fails_compile_test.cpp
797577c81d8a3bc5265497a51dc86d88d1d8c89a
[ "BSD-2-Clause" ]
permissive
cruizm/cadmium
96f55bfee92416ffcacde3e916c2e9af960d2b0b
2b239ccd38021d9e70228623b306ecff413f2e60
refs/heads/master
2020-12-28T04:38:53.333496
2019-09-17T02:31:36
2019-09-17T02:31:36
68,709,558
0
0
NOASSERTION
2019-10-29T23:55:56
2016-09-20T12:28:30
C++
UTF-8
C++
false
false
2,554
cpp
/** * Copyright (c) 2013-2016, Damian Vicino * Carleton University, Universite de Nice-Sophia Antipolis * 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. * * 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. */ /** * Test that an atomic model with no time advance function fails compilation on atomic_model_assert */ #include<cadmium/modeling/ports.hpp> #include<cadmium/concept/atomic_model_assert.hpp> #include<tuple> #include<cadmium/modeling/message_bag.hpp> /** * This model has no logic, only used for structural validation tests */ template<typename TIME> struct atomic_model_missing_time_advance_function { struct in : public cadmium::in_port<int>{}; struct out : public cadmium::out_port<int>{}; constexpr atomic_model_missing_time_advance_function() noexcept {} using state_type=int; state_type state=0; using input_ports=std::tuple<in>; using output_ports=std::tuple<out>; void internal_transition(){} void external_transition(TIME e, typename cadmium::make_message_bags<input_ports>::type mbs){} void confluence_transition(TIME e, typename cadmium::make_message_bags<input_ports>::type mbs){} typename cadmium::make_message_bags<output_ports>::type output() const{} }; int main(){ cadmium::concept::atomic_model_assert<atomic_model_missing_time_advance_function>(); }
a181dfb9a248ace3cd6393dffaa9d66add184a8a
6f337a5291d732c80b401ec91bb0907bf10950ca
/object.h
5ef379dda06e9751edbd0c01391006d8620999aa
[]
no_license
kikejosan/voxelUniforme
d27541d10cb088ce9fd655317d0ec744d8535681
83f9e51a78c7c0e102d2d3984668631a40baeb4d
refs/heads/master
2020-04-19T01:24:53.459276
2019-02-04T09:04:12
2019-02-04T09:04:12
167,871,541
0
0
null
null
null
null
UTF-8
C++
false
false
1,683
h
/* object.h * * Interaccion y Visualizacion de la Informacion. * * Practice 2. * Ray tracing. * * Jose Pascual Molina Masso. * Escuela Superior de Ingenieria Informatica de Albacete. */ #ifndef _OBJECT_H_ #define _OBJECT_H_ #include "glm/vec3.hpp" // glm::vec3 #include "shadinfo.h" #include "material.h" //#include "BBox.h" class BBox; /****************/ /* Object class */ /****************/ class Object { public: /* Computes the nearest intersection point between a ray and the object, in the direction of the ray. Returns the t value of that point if it is positive, otherwise returns 0. */ virtual float NearestInt(const glm::vec3& pos, const glm::vec3& dir) = 0; /* Returns the color of the object at the intersection point with the ray */ virtual glm::vec3 Shade(ShadingInfo &shadInfo) = 0; /* Draw the object with OpenGL */ virtual void Draw() = 0; /* Get Bounding Box from the object selected */ virtual BBox GetBox()= 0; virtual glm::vec3 getCenter() = 0; virtual float getRadius() = 0; Material *pMaterial; }; /****************/ /* Sphere class */ /****************/ class Sphere : public Object { public: /* Constructor */ Sphere(const glm::vec3& Center, float Radius, Material *pMat); /* Inherited functions that are implemented in this class */ virtual float NearestInt(const glm::vec3& pos, const glm::vec3& dir); virtual glm::vec3 Shade(ShadingInfo &shadInfo); virtual void Draw(); virtual BBox GetBox(); virtual glm::vec3 getCenter(); virtual float getRadius(); //private: glm::vec3 center; // Center coordinates float radius; // Radius }; #endif // !defined _OBJECT_H_
221feafa230315cf3a5148122a0591fc23874c9f
5378e2af66e80778cd0c86d14abbab1e841bf6b1
/Progs/binary-tree.cpp
58fe212d127c96e301c0648118173e9692dfa3ab
[]
no_license
Naresh-Nelavalli/Practice-programs
a938351fc5dfaf42660413d8307a4366739ca62d
5f6a7fa7242c43ea0d1721c23569b9bfe97a4179
refs/heads/master
2021-10-29T12:24:42.617619
2021-10-25T20:39:30
2021-10-25T20:39:30
43,388,904
0
0
null
null
null
null
UTF-8
C++
false
false
2,029
cpp
// Binary Execution - Insertion , Sorting and Deleting the values # include <iostream> # include <cstdlib> using namespace std; class btree{ public: struct node{ int data; node* lnode; node* rnode; }; //btree() node* root; node* CreateNode(int data); void AddNode1(int data); void ShowNode1(); void ShowNode(node* root); void AddNode(int data,node* ptr); }; btree::node* btree::CreateNode(int data) { node* n =new node; n-> data = data; n-> lnode=NULL; n-> rnode=NULL; return n; } void btree::AddNode1(int data) { AddNode(data,root); } void btree::AddNode(int data, node* ptr ) { if (root==NULL) { root = CreateNode(data); } else if (data < ptr->data) { if (ptr->lnode != NULL) { AddNode(data,ptr->lnode); } else { ptr->lnode = CreateNode(data); } } else if (data > ptr->data) { if (ptr->rnode != NULL) { AddNode(data,ptr->rnode); } else { ptr->rnode = CreateNode(data); } } else { cout<<"there are aleardy value in key"; } } void btree::ShowNode1() { ShowNode(root); } void btree::ShowNode(node* ptr) { if (root=NULL) { cout<< " Hey !!! Tree your tried to serach is Empty "; } else { if(ptr->lnode!=NULL) { ShowNode(ptr->lnode); } cout<<" Data in give nodes are :" << ptr->data; if(ptr->rnode!=NULL) { ShowNode(ptr->rnode); cout<<ptr->data; } } } int main() { char option; int key; btree b1; /* while (option != 'e') { cout << " Please select option below : "<< "\n"; cout << " (I)nsert an element "<< "\n"; cout << " (S)how element "<< "\n"; cout << " (E)xit - Take me away "<< "\n"; cin >> option; if (option=='e') { return(1); } if (option=='i') { cout << "Enter the value of key :"; cin >> key; } if (option=='s') { ShowNode() } return 0; } int b[15]={2,80,30,14,23,56,17,16,96,78,36,69,99,55,22}; for(int i=0;i<15;i++) { b1.AddNode1(b[i]); } for(int i=0;i<15;i++) { b1.ShowNode1(); }*/ b1.ShowNode1(); return 0; }
e1e0e2437df334d73c3a3dfc104734ad3dd31c1e
1e7671d2c479fbc227042988eed97552de750857
/TextLineGameThing2/TextLineGameThing2/Item.h
85cd7d8678554f280c96964409f87ce70fae9197
[]
no_license
AllenCN/Projects
e01561035fc2c9f974af54bb15e88d090287382b
a2695ff87bea41fbe2e8281d998798589f529f4d
refs/heads/master
2020-06-13T03:37:05.998396
2017-01-21T21:13:23
2017-01-21T21:13:23
75,453,690
0
0
null
null
null
null
UTF-8
C++
false
false
221
h
#pragma once #include "Noun.h" class Item : public Noun { public: Item(); Item(vector<string> line1, vector<string> data); virtual ~Item(); int hpUp; int mpUp; string use_sentence; bool isKeyItem = false; };
90fd6a96a9d98cecca0dc43fd0b2073857b29ca5
7c37f348d8d8a2305d6bf57ed77fffcedc97433b
/DS-Cpp/stack.cpp
1ed8bf050bbbc578fb0ff94db84cff164718c5e2
[]
no_license
Riya-code/CodeBag
77d3473e24a2a16c75dfe14bf3b152006c46007e
95cbccee5c673e774823518ded869e2055f50498
refs/heads/main
2023-01-04T07:48:26.335717
2020-11-01T15:08:27
2020-11-01T15:08:27
304,252,052
0
3
null
2020-10-19T15:29:38
2020-10-15T07:58:46
C++
UTF-8
C++
false
false
260
cpp
#include <bits/stdc++.h> using namespace std; void show( stack <int> s) { while (!s.empty()){ cout<<s.top(); s.pop(); } } int main() { stack <int> s; s.push(0); s.push(5); s.push(2); s.push(1); show(s); return 0; }
[ "rj220699@gmailcom" ]
rj220699@gmailcom
dd7b697373b9b4c042407339a69877be8fcda913
ece30e7058d8bd42bc13c54560228bd7add50358
/DataCollector/mozilla/xulrunner-sdk/include/mozilla/dom/NodeInfoInlines.h
970b6e53d39c1b260ac2021f3effa6b13e6d22bb
[ "Apache-2.0" ]
permissive
andrasigneczi/TravelOptimizer
b0fe4d53f6494d40ba4e8b98cc293cb5451542ee
b08805f97f0823fd28975a36db67193386aceb22
refs/heads/master
2022-07-22T02:07:32.619451
2018-12-03T13:58:21
2018-12-03T13:58:21
53,926,539
1
0
Apache-2.0
2022-07-06T20:05:38
2016-03-15T08:16:59
C++
UTF-8
C++
false
false
4,218
h
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef mozilla_dom_NodeInfoInlines_h___ #define mozilla_dom_NodeInfoInlines_h___ #include "nsIAtom.h" #include "nsIDOMNode.h" #include "nsDOMString.h" #include "nsGkAtoms.h" namespace mozilla { namespace dom { inline bool NodeInfo::Equals(NodeInfo *aNodeInfo) const { return aNodeInfo == this || aNodeInfo->Equals(mInner.mName, mInner.mPrefix, mInner.mNamespaceID); } inline bool NodeInfo::NameAndNamespaceEquals(NodeInfo *aNodeInfo) const { return aNodeInfo == this || aNodeInfo->Equals(mInner.mName, mInner.mNamespaceID); } inline bool NodeInfo::Equals(const nsAString& aName) const { return mInner.mName->Equals(aName); } inline bool NodeInfo::Equals(const nsAString& aName, const nsAString& aPrefix) const { return mInner.mName->Equals(aName) && (mInner.mPrefix ? mInner.mPrefix->Equals(aPrefix) : aPrefix.IsEmpty()); } inline bool NodeInfo::Equals(const nsAString& aName, int32_t aNamespaceID) const { return mInner.mNamespaceID == aNamespaceID && mInner.mName->Equals(aName); } inline bool NodeInfo::Equals(const nsAString& aName, const nsAString& aPrefix, int32_t aNamespaceID) const { return mInner.mName->Equals(aName) && mInner.mNamespaceID == aNamespaceID && (mInner.mPrefix ? mInner.mPrefix->Equals(aPrefix) : aPrefix.IsEmpty()); } inline bool NodeInfo::QualifiedNameEquals(nsIAtom* aNameAtom) const { MOZ_ASSERT(aNameAtom, "Must have name atom"); if (!GetPrefixAtom()) { return Equals(aNameAtom); } return aNameAtom->Equals(mQualifiedName); } } // namespace dom } // namespace mozilla inline void CheckValidNodeInfo(uint16_t aNodeType, nsIAtom *aName, int32_t aNamespaceID, nsIAtom* aExtraName) { MOZ_ASSERT(aNodeType == nsIDOMNode::ELEMENT_NODE || aNodeType == nsIDOMNode::ATTRIBUTE_NODE || aNodeType == nsIDOMNode::TEXT_NODE || aNodeType == nsIDOMNode::CDATA_SECTION_NODE || aNodeType == nsIDOMNode::PROCESSING_INSTRUCTION_NODE || aNodeType == nsIDOMNode::COMMENT_NODE || aNodeType == nsIDOMNode::DOCUMENT_NODE || aNodeType == nsIDOMNode::DOCUMENT_TYPE_NODE || aNodeType == nsIDOMNode::DOCUMENT_FRAGMENT_NODE || aNodeType == UINT16_MAX, "Invalid nodeType"); MOZ_ASSERT((aNodeType == nsIDOMNode::PROCESSING_INSTRUCTION_NODE || aNodeType == nsIDOMNode::DOCUMENT_TYPE_NODE) == !!aExtraName, "Supply aExtraName for and only for PIs and doctypes"); MOZ_ASSERT(aNodeType == nsIDOMNode::ELEMENT_NODE || aNodeType == nsIDOMNode::ATTRIBUTE_NODE || aNodeType == UINT16_MAX || aNamespaceID == kNameSpaceID_None, "Only attributes and elements can be in a namespace"); MOZ_ASSERT(aName && aName != nsGkAtoms::_empty, "Invalid localName"); MOZ_ASSERT(((aNodeType == nsIDOMNode::TEXT_NODE) == (aName == nsGkAtoms::textTagName)) && ((aNodeType == nsIDOMNode::CDATA_SECTION_NODE) == (aName == nsGkAtoms::cdataTagName)) && ((aNodeType == nsIDOMNode::COMMENT_NODE) == (aName == nsGkAtoms::commentTagName)) && ((aNodeType == nsIDOMNode::DOCUMENT_NODE) == (aName == nsGkAtoms::documentNodeName)) && ((aNodeType == nsIDOMNode::DOCUMENT_FRAGMENT_NODE) == (aName == nsGkAtoms::documentFragmentNodeName)) && ((aNodeType == nsIDOMNode::DOCUMENT_TYPE_NODE) == (aName == nsGkAtoms::documentTypeNodeName)) && ((aNodeType == nsIDOMNode::PROCESSING_INSTRUCTION_NODE) == (aName == nsGkAtoms::processingInstructionTagName)), "Wrong localName for nodeType"); } #endif /* mozilla_dom_NodeInfoInlines_h___ */
cf18769858d1908b0671f7e0ab8576b4300a551a
e07300ca3777e5173e676daa6addc1cc53ac5033
/practica_graficador/AssemblyInfo.cpp
4a0f0559d2afd4fca915e3f6faa1e18f897cd8da
[]
no_license
Ariel44r/plotter-Copy
05b6689b59e9463ea3968b57a577a5d47fef7e4b
2a03297a3355e2e7444eb5b534bdc8fb58d52ddb
refs/heads/master
2021-01-22T23:53:59.951016
2017-03-21T08:24:39
2017-03-21T08:24:39
85,679,199
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,415
cpp
#include "stdafx.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; // // La información general sobre un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos atributos para modificar la información // asociada con un ensamblado. // [assembly:AssemblyTitleAttribute("practica_graficador")]; [assembly:AssemblyDescriptionAttribute("")]; [assembly:AssemblyConfigurationAttribute("")]; [assembly:AssemblyCompanyAttribute("")]; [assembly:AssemblyProductAttribute("practica_graficador")]; [assembly:AssemblyCopyrightAttribute("Copyright (c) 2015")]; [assembly:AssemblyTrademarkAttribute("")]; [assembly:AssemblyCultureAttribute("")]; // // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión // mediante el asterisco ('*'), como se muestra a continuación: [assembly:AssemblyVersionAttribute("1.0.*")]; [assembly:ComVisible(false)]; [assembly:CLSCompliantAttribute(true)]; [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
54df9bc261cbf5a7b38e663d2367048a36581daa
c97afe68da875335a8aa82ff9233fe675caa89d2
/Classes/mahjong-algorithm/stringify.h
6f03ab3b26cf8fbbee68fbbf648990ab5e674faf
[ "MIT" ]
permissive
cfzvzv/ChineseOfficialMahjongHelper
db2f35534e90386f63b0fc574ceae646aa1b24b3
b15b77d991bbd161d073d14087aa7f2f02bd7c04
refs/heads/master
2020-03-19T10:04:14.352679
2018-05-26T10:14:57
2018-05-26T10:14:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,039
h
/**************************************************************************** Copyright (c) 2016-2018 Jeff Wang <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef __MAHJONG_ALGORITHM__STRINGIFY_H__ #define __MAHJONG_ALGORITHM__STRINGIFY_H__ #include "tile.h" namespace mahjong { /** * @brief 字符串格式: * - 数牌:万=m 条=s 饼=p。后缀使用小写字母,一连串同花色的数牌可合并使用用一个后缀,如123m、678s等等。 * - 字牌:东南西北=ESWN,中发白=CFP。使用大写字母。亦兼容天凤风格的后缀z,但按中国习惯顺序567z为中发白。 * - 吃、碰、杠用英文[],可选用逗号+数字表示供牌来源。数字的具体规则如下: * - 吃:表示第几张牌是由上家打出,如[567m,2]表示57万吃6万(第2张)。对于不指定数字的,默认为吃第1张。 * - 碰:表示由哪家打出,1为上家,2为对家,3为下家,如[999s,3]表示碰下家的9条。对于不指定数字的,默认为碰上家。 * - 杠:与碰类似,但对于不指定数字的,则认为是暗杠。例如:[SSSS]表示暗杠南;[8888p,1]表示明杠上家的8饼。 * - 范例 * - [EEEE][CCCC][FFFF][PPPP]NN * - 1112345678999s9s * - [WWWW,1][444s]45m678pFF6m * - [EEEE]288s349pSCFF2p * - [123p,1][345s,2][999s,3]6m6pEW1m * - 356m18s1579pWNFF9p */ /** * @addtogroup stringify * @{ */ /** * @name error codes * @{ * 解析牌的错误码 */ #define PARSE_NO_ERROR 0 ///< 无错误 #define PARSE_ERROR_ILLEGAL_CHARACTER -1 ///< 非法字符 #define PARSE_ERROR_NO_SUFFIX_AFTER_DIGIT -2 ///< 数字后面缺少后缀 #define PARSE_ERROR_WRONG_TILES_COUNT_FOR_FIXED_PACK -3 ///< 副露包含错误的牌数目 #define PARSE_ERROR_CANNOT_MAKE_FIXED_PACK -4 ///< 无法正确解析副露 #define PARSE_ERROR_TOO_MANY_FIXED_PACKS -5 ///< 过多组副露(一副合法手牌最多4副露) /** * @} */ /** * @brief 解析牌 * @param [in] str 字符串 * @param [out] tiles 牌 * @param [in] max_cnt 牌的最大数量 * @retval > 0 实际牌的数量 * @retval == 0 失败 */ intptr_t parse_tiles(const char *str, tile_t *tiles, intptr_t max_cnt); /** * @brief 字符串转换为手牌结构和上牌 * @param [in] str 字符串 * @param [out] hand_tiles 手牌结构 * @param [out] serving_tile 上的牌 * @retval PARSE_NO_ERROR 无错误 * @retval PARSE_ERROR_ILLEGAL_CHARACTER 非法字符 * @retval PARSE_ERROR_NO_SUFFIX_AFTER_DIGIT 数字后面缺少后缀 * @retval PARSE_ERROR_WRONG_TILES_COUNT_FOR_FIXED_PACK 副露包含错误的牌数目 * @retval PARSE_ERROR_CANNOT_MAKE_FIXED_PACK 无法正确解析副露 * @retval PARSE_ERROR_TOO_MANY_FIXED_PACKS 过多组副露(一副合法手牌最多4副露) */ intptr_t string_to_tiles(const char *str, hand_tiles_t *hand_tiles, tile_t *serving_tile); /** * @brief 牌转换为字符串 * @param [in] tiles 牌 * @param [in] tile_cnt 牌的数量 * @param [out] str 字符串 * @param [in] max_size 字符串最大长度 * @return intptr_t 写入的字符串数 */ intptr_t tiles_to_string(const tile_t *tiles, intptr_t tile_cnt, char *str, intptr_t max_size); /** * @brief 牌组转换为字符串 * @param [in] packs 牌组 * @param [in] pack_cnt 牌组的数量 * @param [out] str 字符串 * @param [in] max_size 字符串最大长度 * @return intptr_t 写入的字符串数 */ intptr_t packs_to_string(const pack_t *packs, intptr_t pack_cnt, char *str, intptr_t max_size); /** * @brief 手牌结构转换为字符串 * @param [in] hand_tiles 手牌结构 * @param [out] str 字符串 * @param [in] max_size 字符串最大长度 * @return intptr_t 写入的字符串数 */ intptr_t hand_tiles_to_string(const hand_tiles_t *hand_tiles, char *str, intptr_t max_size); /** * end group * @} */ } #endif
54fe3d5368b61caaa68a779061cfd7c65e861149
e08ebd3daae7d0c9a578aced6be490ef9c560fdc
/Source/Atomic/Scene/ValueAnimationInfo.h
ccc1c10c1acaee6d8107b85ebae1ece9f0d3d426
[ "MIT", "BSD-3-Clause", "Zlib", "LicenseRef-scancode-openssl", "LicenseRef-scancode-khronos", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "NTP" ]
permissive
bryant1410/AtomicGameEngine
86070cb6f575c9d6fdb0de12b66ac1ec295e55c8
51286ffc4102dcf2b633d36d5c0cb2dae9817302
refs/heads/master
2021-01-19T19:56:23.085734
2017-04-17T03:41:20
2017-04-17T03:41:20
88,465,101
1
0
null
2017-04-17T03:41:21
2017-04-17T03:41:21
null
UTF-8
C++
false
false
3,499
h
// // Copyright (c) 2008-2016 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #pragma once #include "../Container/RefCounted.h" #include "../Scene/AnimationDefs.h" namespace Atomic { class Object; class ValueAnimation; struct VAnimEventFrame; /// Base class for a value animation instance, which includes animation runtime information and updates the target object's value automatically. class ATOMIC_API ValueAnimationInfo : public RefCounted { ATOMIC_REFCOUNTED(ValueAnimationInfo) public: /// Construct without target object. ValueAnimationInfo(ValueAnimation* animation, WrapMode wrapMode, float speed); /// Construct with target object. ValueAnimationInfo(Object* target, ValueAnimation* animation, WrapMode wrapMode, float speed); /// Copy construct. ValueAnimationInfo(const ValueAnimationInfo& other); /// Destruct. ~ValueAnimationInfo(); /// Advance time position and apply. Return true when the animation is finished. No-op when the target object is not defined. bool Update(float timeStep); /// Set time position and apply. Return true when the animation is finished. No-op when the target object is not defined. bool SetTime(float time); /// Set wrap mode. void SetWrapMode(WrapMode wrapMode) { wrapMode_ = wrapMode; } /// Set speed. void SetSpeed(float speed) { speed_ = speed; } /// Return target object. Object* GetTarget() const; /// Return animation. ValueAnimation* GetAnimation() const { return animation_; } /// Return wrap mode. WrapMode GetWrapMode() const { return wrapMode_; } /// Return time position. float GetTime() const { return currentTime_; } /// Return speed. float GetSpeed() const { return speed_; } protected: /// Apply new animation value to the target object. Called by Update(). virtual void ApplyValue(const Variant& newValue); /// Calculate scaled time. float CalculateScaledTime(float currentTime, bool& finished) const; /// Return event frames. void GetEventFrames(float beginTime, float endTime, PODVector<const VAnimEventFrame*>& eventFrames); /// Target object. WeakPtr<Object> target_; /// Attribute animation. SharedPtr<ValueAnimation> animation_; /// Wrap mode. WrapMode wrapMode_; /// Animation speed. float speed_; /// Current time. float currentTime_; /// Last scaled time. float lastScaledTime_; }; }
e72d4d621e23a4c70b9c0eeadb1f29e003a5634a
77a08ec51aa16191986a739267fd9d4379bbb208
/homework/CandC++/1427405052-E11.cpp
cb8a2876ce68c1475d8060d723df353bb9ec7a2f
[]
no_license
cenariusxz/ACM-Coding
8f698203db802f79578921b311b38346950ef0ca
dc09ac9adfb4b80d463bdc93f52b479a957154e6
refs/heads/master
2023-06-24T13:12:13.279255
2021-07-26T01:24:36
2021-07-26T01:24:36
185,567,471
0
0
null
null
null
null
UTF-8
C++
false
false
5,421
cpp
#include<iostream> #include<cmath> #include<cstdlib> #include<ctime> using namespace std; #define pi 3.14159 class Circle{ //Circle类 private: double x,y,r; //横纵坐标以及半径 public: void Set_o(double,double); //初始化圆心坐标 void Set_r(double); //初始化半径 double Cal_S()const; //计算圆面积 double Cal_C()const; //计算圆周长 double Get_x()const; //获得圆心横坐标 double Get_y()const; //获得圆心纵坐标 double Get_r()const; //获得半径 friend Circle operator+(const Circle&,const Circle&); //加号重载 friend Circle operator-(const Circle&,const Circle&); //减号重载 friend Circle& operator++(Circle&); //前自增重载 friend Circle operator++(Circle&,int); //后自增重载 friend Circle& operator--(Circle&); //前自减重载 friend Circle operator--(Circle&,int); //后自减重载 friend ostream& operator<<(ostream&,const Circle&); //流输出重载 friend bool operator>(const Circle&,const Circle&); //大于号重载 friend bool operator<(const Circle&,const Circle&); //小于号重载 friend bool operator==(const Circle&,const Circle&); //判等重载 friend bool operator!=(const Circle&,const Circle&); //不等重载 friend bool operator&(const Circle&,const Circle&); //位与重载 friend int operator|(const Circle&,const Circle&); //位或重载 }; void Circle::Set_o(double xx,double yy){ //设置圆心坐标函数 x=xx; y=yy; } void Circle::Set_r(double rr){ //设置半径函数 r=rr; } double Circle::Cal_S()const{ //计算面积函数 return pi*r*r; } double Circle::Cal_C()const{ //计算周长函数 return 2*pi*r; } double Circle::Get_x()const{ //获得圆心横坐标函数 return x; } double Circle::Get_y()const{ //获得圆心纵坐标函数 return y; } double Circle::Get_r()const{ //获得半径函数 return r; } Circle operator+(const Circle& c1,const Circle& c2){ //加号重载 Circle a; a.x=c1.x; a.y=c1.y; a.r=c1.r+c2.r; return a; } Circle operator-(const Circle& c1,const Circle& c2){ //减号重载 Circle a; a.x=c1.x; a.y=c1.y; a.r=sqrt(abs(c1.r*c1.r-c2.r*c2.r)); return a; } Circle& operator++(Circle& c){ //前自增重载 c.r+=1; return c; } Circle operator++(Circle& c,int){ //后自增重载 Circle a(c); c.r+=1; return a; } Circle& operator--(Circle& c){ //前自减重载 c.r-=1; return c; } Circle operator--(Circle& c,int){ //后自减重载 Circle a(c); c.r-=1; return a; } ostream& operator<<(ostream& o,const Circle& c){ //流输出重载 o<<"圆心坐标:("<<c.x<<","<<c.y<<")"<<endl; o<<"圆的半径:"<<c.r<<endl; o<<"圆的周长:"<<c.Cal_C()<<endl; o<<"圆的面积:"<<c.Cal_S()<<endl; } bool operator>(const Circle& c1,const Circle& c2){ //大于号重载 return c1.r>c2.r?1:0; } bool operator<(const Circle& c1,const Circle& c2){ //小于号重载 return c1.r<c2.r?1:0; } bool operator==(const Circle& c1,const Circle& c2){ //判等重载 return (c1.x==c2.x&&c1.y==c2.y&&c1.r==c2.r)?1:0; } bool operator!=(const Circle& c1,const Circle& c2){ //不等重载 return (c1.x!=c2.x||c1.y!=c2.y||c1.r!=c2.r)?1:0; } bool operator&(const Circle& c1,const Circle& c2){ //位与重载 return (c1.x==c2.x&&c1.y==c2.y)?1:0; } int operator|(const Circle& c1,const Circle& c2){ //位或重载 double d=sqrt((c1.x-c2.x)*(c1.x-c2.x)+(c1.y-c2.y)*(c1.y-c2.y)); if(d<c1.r+c2.r&&d>abs(c1.r-c2.r))return 1; else if(d==c1.r+c2.r||d==abs(c1.r-c2.r))return 2; else if(d>c1.r+c2.r)return 3; else if(d<abs(c1.r-c2.r))return 4; } int main(){ srand(time(NULL)); Circle C1; //生成C1圆 Circle C2; //生成C2圆 C1.Set_o(rand()%20,rand()%20); //不断随机生成两圆直到相离 C1.Set_r(rand()%20+1); C2.Set_o(rand()%20,rand()%20); C2.Set_r(rand()%20+1); while((C1|C2)!=3||C1>C2){ C1.Set_o(rand()%20,rand()%20); C1.Set_r(rand()%20+1); C2.Set_o(rand()%20,rand()%20); C2.Set_r(rand()%20+1); } //计算圆的各个值 double v2=1,v1,r1=C1.Get_r(),x1=C1.Get_x(),y1=C1.Get_y(),r2=C2.Get_r(),x2=C2.Get_x(),y2=C2.Get_y(); double d=sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); double dx=(x2-x1)/d,dy=(y2-y1)/d; v1=(r2*r2)/(r1*r1); d-=(r1+r2); if(d<1e-5)d=0; int time=0; //输出初始状态圆 cout<<"time:"<<time++<<endl; cout<<"C1: O("<<x1<<","<<y1<<")"<<" r="<<r1<<" v="<<v1<<endl; cout<<"C2: O("<<x2<<","<<y2<<")"<<" r="<<r2<<" v="<<v2<<endl; cout<<"距离:"<<d<<endl; double dd=d; bool f=0; while((C1|C2)==3&&r1>1e-5&&r2>1e-5){ //循环模拟圆的运动直到不相离或圆消失 if(r1>1)C1--; //改变两圆半径 else C1=C1-C1; r1=C1.Get_r(); if(r2>1)C2--; else C2=C2-C2; r2=C2.Get_r(); C1.Set_o(x1+dx*v1,y1+dy*v1); //改变两圆圆心坐标 C2.Set_o(x2-dx*v2,y2-dy*v2); x1=C1.Get_x(); y1=C1.Get_y(); x2=C2.Get_x(); y2=C2.Get_y(); d=sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))-r1-r2; //计算两圆距离和速度 if(d<1e-5)d=0; if(r1<1e-5)v1=0; else v1=(r2*r2)/(r1*r1); if(r2<1e-5)v2=0; cout<<"time:"<<time++<<endl; //输出两圆状态 cout<<"C1: O("<<x1<<","<<y1<<")"<<" r="<<r1<<" v="<<v1<<endl; cout<<"C2: O("<<x2<<","<<y2<<")"<<" r="<<r2<<" v="<<v2<<endl; cout<<"距离:"<<d<<endl; if(d-dd>1e-5){ f=1; break; } dd=d; } if(f||(C1|C2)!=3)cout<<"相撞"<<endl; //判定是否能相撞 else cout<<"未相撞"<<endl; }
d973426302986038a1372ec65c3003fdac3ce377
ef1175cfe6d9c58dd573618a0b71bd31767dc3d3
/src/rpc/server.h
7bbbbcf907fd6f78d8cef485997cc53b05268463
[ "MIT" ]
permissive
SBDomains/PRONTO
78e7671e6b7a2ecdba09498e8fcd18c0e750f6be
199daa248fa4e0ab9102c887bc7f252813af8795
refs/heads/master
2020-04-15T06:39:08.087072
2019-01-11T17:18:05
2019-01-11T17:18:05
164,467,850
2
0
null
null
null
null
UTF-8
C++
false
false
6,190
h
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_RPCSERVER_H #define BITCOIN_RPCSERVER_H #include "amount.h" #include "rpc/protocol.h" #include "uint256.h" #include <list> #include <map> #include <stdint.h> #include <string> #include <boost/function.hpp> #include <univalue.h> class CRPCCommand; namespace RPCServer { void OnStarted(boost::function<void ()> slot); void OnStopped(boost::function<void ()> slot); void OnPreCommand(boost::function<void (const CRPCCommand&)> slot); void OnPostCommand(boost::function<void (const CRPCCommand&)> slot); } class CBlockIndex; class CNetAddr; /** Wrapper for UniValue::VType, which includes typeAny: * Used to denote don't care type. Only used by RPCTypeCheckObj */ struct UniValueType { UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {} UniValueType() : typeAny(true) {} bool typeAny; UniValue::VType type; }; class JSONRPCRequest { public: UniValue id; std::string strMethod; UniValue params; bool fHelp; std::string URI; std::string authUser; JSONRPCRequest() { id = NullUniValue; params = NullUniValue; fHelp = false; } void parse(const UniValue& valRequest); }; /** Query whether RPC is running */ bool IsRPCRunning(); /** * Set the RPC warmup status. When this is done, all RPC calls will error out * immediately with RPC_IN_WARMUP. */ void SetRPCWarmupStatus(const std::string& newStatus); /* Mark warmup as done. RPC calls will be processed from now on. */ void SetRPCWarmupFinished(); /* returns the current warmup state. */ bool RPCIsInWarmup(std::string *statusOut); /** * Type-check arguments; throws JSONRPCError if wrong type given. Does not check that * the right number of arguments are passed, just that any passed are the correct type. */ void RPCTypeCheck(const UniValue& params, const std::list<UniValue::VType>& typesExpected, bool fAllowNull=false); /** * Type-check one argument; throws JSONRPCError if wrong type given. */ void RPCTypeCheckArgument(const UniValue& value, UniValue::VType typeExpected); /* Check for expected keys/value types in an Object. */ void RPCTypeCheckObj(const UniValue& o, const std::map<std::string, UniValueType>& typesExpected, bool fAllowNull = false, bool fStrict = false); /** Opaque base class for timers returned by NewTimerFunc. * This provides no methods at the moment, but makes sure that delete * cleans up the whole state. */ class RPCTimerBase { public: virtual ~RPCTimerBase() {} }; /** * RPC timer "driver". */ class RPCTimerInterface { public: virtual ~RPCTimerInterface() {} /** Implementation name */ virtual const char *Name() = 0; /** Factory function for timers. * RPC will call the function to create a timer that will call func in *millis* milliseconds. * @note As the RPC mechanism is backend-neutral, it can use different implementations of timers. * This is needed to cope with the case in which there is no HTTP server, but * only GUI RPC console, and to break the dependency of pcserver on httprpc. */ virtual RPCTimerBase* NewTimer(boost::function<void(void)>& func, int64_t millis) = 0; }; /** Set the factory function for timers */ void RPCSetTimerInterface(RPCTimerInterface *iface); /** Set the factory function for timer, but only, if unset */ void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface); /** Unset factory function for timers */ void RPCUnsetTimerInterface(RPCTimerInterface *iface); /** * Run func nSeconds from now. * Overrides previous timer <name> (if any). */ void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds); typedef UniValue(*rpcfn_type)(const JSONRPCRequest& jsonRequest); class CRPCCommand { public: std::string category; std::string name; rpcfn_type actor; bool okSafeMode; std::vector<std::string> argNames; }; /** * PRONTO RPC command dispatcher. */ class CRPCTable { private: std::map<std::string, const CRPCCommand*> mapCommands; public: CRPCTable(); const CRPCCommand* operator[](const std::string& name) const; std::string help(const std::string& name) const; /** * Execute a method. * @param request The JSONRPCRequest to execute * @returns Result of the call. * @throws an exception (UniValue) when an error happens. */ UniValue execute(const JSONRPCRequest &request) const; /** * Returns a list of registered commands * @returns List of registered commands. */ std::vector<std::string> listCommands() const; /** * Appends a CRPCCommand to the dispatch table. * Returns false if RPC server is already running (dump concurrency protection). * Commands cannot be overwritten (returns false). */ bool appendCommand(const std::string& name, const CRPCCommand* pcmd); }; extern CRPCTable tableRPC; /** * Utilities: convert hex-encoded Values * (throws error if not hex). */ extern uint256 ParseHashV(const UniValue& v, std::string strName); extern uint256 ParseHashO(const UniValue& o, std::string strKey); extern std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName); extern std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey); extern int64_t nWalletUnlockTime; extern CAmount AmountFromValue(const UniValue& value); extern UniValue ValueFromAmount(const CAmount& amount); extern double GetDifficulty(const CBlockIndex* blockindex = NULL); extern std::string HelpRequiringPassphrase(); extern std::string HelpExampleCli(const std::string& methodname, const std::string& args); extern std::string HelpExampleRpc(const std::string& methodname, const std::string& args); extern void EnsureWalletIsUnlocked(); bool StartRPC(); void InterruptRPC(); void StopRPC(); std::string JSONRPCExecBatch(const UniValue& vReq); void RPCNotifyBlockChange(bool ibd, const CBlockIndex *); #endif // BITCOIN_RPCSERVER_H
9b6abdeca638b5d48ac2c054d14381f0d8da2bc0
6c591d6c47b989f39b48f66e2fec8a3ee3664b64
/TRT_wBatch.cpp
e32c3acf5b128ddc863299851e25d8d6ae3eea2c
[]
no_license
tonydp03/CNN_CMS-Tracker
5f2bd954cc4bab75d9fcd6416e3274d9f7365d85
916e85ebc1e3bf673247938fd91eee08a2f781f0
refs/heads/master
2021-07-25T19:49:00.051512
2020-04-21T08:35:46
2020-04-21T08:35:46
157,004,384
0
1
null
null
null
null
UTF-8
C++
false
false
7,914
cpp
/* A simple C++ program to import an UFF model, read input data from a HDF file and make fast inference on GPU with NVIDIA TensorRT */ #include <algorithm> #include <chrono> #include <cstdlib> #include <cuda_runtime_api.h> #include <fstream> #include <iostream> #include <string> #include <sys/stat.h> #include <unordered_map> #include <cassert> #include <vector> #include <ctime> #include "NvInfer.h" #include "NvUffParser.h" #include "NvUtils.h" #include "H5Cpp.h" using namespace H5; using namespace nvuffparser; using namespace nvinfer1; #include "common.h" #define MAX_WORKSPACE (1 << 20) #define maxBatchSize 60000 //define the data info const H5std_string FILE_NAME("pixel_only_data_test.h5"); const H5std_string DATASET_NAME_DATA("data/block0_values"); const H5std_string DATASET_NAME_LABELS("labels/block0_values"); // Attributes of the model static const int INPUT_CH = 20; static const int INPUT_H = 16; static const int INPUT_W = 16; static const int OUTPUT_SIZE = 2; const char* INPUT_TENSOR_NAME = "hit_shape_input"; const char* OUTPUT_TENSOR_NAME = "output/Softmax"; const std::string dir{"./"}; const std::string fileName{dir + "pixel_only_final.uff"}; int main(int argc, char** argv){ std::cout << "*** MODEL TO IMPORT: " << fileName << "\n"; std::cout << "*** DATASET FILE: " << FILE_NAME << "\n"; std::cout << "*** MAX WORKSPACE: " << MAX_WORKSPACE << "\n"; std::cout << "*** MAX BATCHSIZE: " << maxBatchSize << std::endl; int batchSize = 30000; std::cout << "*** Number of images to process (batchSize): " << batchSize << std::endl; float ms; Logger gLogger; // object for warning and error reports // *** IMPORTING THE MODEL *** std::cout << "*** IMPORTING THE UFF MODEL ***" << std::endl; // Create the builder and the network IBuilder* builder = createInferBuilder(gLogger); INetworkDefinition* network = builder->createNetwork(); // Create the UFF parser IUffParser* parser = createUffParser(); assert(parser); // Declare the network inputs and outputs of the model to the parser parser->registerInput(INPUT_TENSOR_NAME, DimsCHW(20, 16, 16), UffInputOrder::kNCHW); parser->registerOutput(OUTPUT_TENSOR_NAME); // Parse the imported model to populate the network parser->parse(fileName.c_str(), *network, nvinfer1::DataType::kFLOAT); // use kHALF for FP16 std::cout << "*** IMPORTING DONE ***" << std::endl; // *** BUILDING THE ENGINE *** std::cout << "*** BUILDING THE ENGINE ***" << std::endl; //Build the engine using the builder object builder->setMaxBatchSize(maxBatchSize); builder->setMaxWorkspaceSize(MAX_WORKSPACE); //builder->setFp16Mode(true); //16-bit kernels are permitted --useful for GPUs supporting full FP16 operations ICudaEngine* engine = builder->buildCudaEngine(*network); assert(engine); std::cout << "*** BUILDING DONE ***" << std::endl; // Destroy network, builder and parser network->destroy(); builder->destroy(); parser->destroy(); // *** SERIALIZE THE ENGINE HERE IF NEEDED FOR LATER USE *** // *** PERFORMING INFERENCE *** std::cout << "*** PERFORMING INFERENCE ***" << std::endl; // Create a context to store intermediate activation values IExecutionContext *context = engine->createExecutionContext(); assert(context); // Create the input and the output buffers on Host float *output = new float[batchSize * OUTPUT_SIZE]; //Open the file and the dataset H5File file( FILE_NAME, H5F_ACC_RDONLY ); DataSet dataset = file.openDataSet( DATASET_NAME_DATA ); //Get dataspace of the dataset DataSpace dataspace = dataset.getSpace(); //Get the number of dimensions in the dataspace int rank = dataspace.getSimpleExtentNdims(); hsize_t dims[2]; int status_n = dataspace.getSimpleExtentDims(dims, NULL); std::cout << "Rank: " << rank << "\n"; std::cout << "Dimensions: " << dims[0] << " " << dims[1] << std::endl; //Define the memory space to read dataset DataSpace memspace(rank,dims); std::cout << "MEMSPACE CREATED" << std::endl; //Read dataset back and display float *input_data = new float[dims[0] * dims[1]]; dataset.read(input_data, PredType::NATIVE_FLOAT, memspace, dataspace); std::cout << "DATASET READ" << std::endl; int i(0); //srand(time(NULL)); //i = rand() % dims[0]; std::cout << "Starting from Image number: " << i << std::endl; // Engine requires exactly IEngine::getNbBindings() number of buffers int nbBindings = engine->getNbBindings(); assert(nbBindings == 2); // 1 input and 1 output void* buffers[nbBindings]; const int inputIndex = engine->getBindingIndex(INPUT_TENSOR_NAME); const int outputIndex = engine->getBindingIndex(OUTPUT_TENSOR_NAME); // Create GPU buffers on device CHECK(cudaMalloc(&buffers[inputIndex], batchSize * INPUT_CH * INPUT_H * INPUT_W * sizeof(float))); CHECK(cudaMalloc(&buffers[outputIndex], batchSize * OUTPUT_SIZE * sizeof(float))); // Create stream //cudaStream_t stream; //CHECK(cudaStreamCreate(&stream)); // Copy the data from host to device //CHECK(cudaMemcpyAsync(buffers[inputIndex], &input_data[i * dims[1]], batchSize * INPUT_CH * INPUT_H * INPUT_W * sizeof(float), cudaMemcpyHostToDevice, stream)); auto t_start = std::chrono::high_resolution_clock::now(); CHECK(cudaMemcpy(buffers[inputIndex], &input_data[i * dims[1]], batchSize * INPUT_CH * INPUT_H * INPUT_W * sizeof(float), cudaMemcpyHostToDevice)); // Enqueue the kernels on a CUDA stream for the asynchronous execution //context->enqueue(batchSize, buffers, stream, nullptr); context->execute(batchSize, buffers); // This is a synchronous execution of the kernel //cudaStreamSynchronize(stream); // Copy the data from device to host //CHECK(cudaMemcpyAsync(output, buffers[outputIndex], batchSize * OUTPUT_SIZE * sizeof(float), cudaMemcpyDeviceToHost, stream)); CHECK(cudaMemcpy(output, buffers[outputIndex], batchSize * OUTPUT_SIZE * sizeof(float), cudaMemcpyDeviceToHost)); auto t_end = std::chrono::high_resolution_clock::now(); ms = std::chrono::duration<float, std::milli>(t_end - t_start).count(); // Synchronize //cudaStreamSynchronize(stream); // Release buffers //cudaStreamDestroy(stream); CHECK(cudaFree(buffers[inputIndex])); CHECK(cudaFree(buffers[outputIndex])); // Destroy the context and the engine context->destroy(); engine->destroy(); // Print the time of execution and histogram of the output distribution std::cout << "\n*** OUTPUT ***\n\n" << std::endl; // Create a dataset for labels DataSet dataset_lb = file.openDataSet( DATASET_NAME_LABELS ); //Get dataspace of the dataset DataSpace dataspace_lb = dataset_lb.getSpace(); //Get the number of dimensions in the dataspace int rank_lb = dataspace_lb.getSimpleExtentNdims(); hsize_t dims_lb[2]; int status_n_lb = dataspace_lb.getSimpleExtentDims(dims_lb, NULL); std::cout << "Rank: " << rank_lb << "\n"; std::cout << "Dimensions: " << dims_lb[0] << " " << dims_lb[1] << std::endl; //Define the memory space to read dataset DataSpace memspace_lb(rank_lb,dims_lb); std::cout << "MEMSPACE CREATED" << std::endl; //Read dataset back and display float *label_output = new float[dims_lb[0] * dims_lb[1]]; dataset_lb.read(label_output, PredType::NATIVE_FLOAT, memspace_lb, dataspace_lb); std::cout << "DATASET FOR LABELS READ" << std::endl; for(i = 0; i < batchSize; i++){ std::cout << "Image n: " << i << "\n"; std::cout << "y_pred = (" << output[2*i] << "," << output[2*i+1] << ") | y_true = (" << label_output[2*i] << "," << label_output[2*i+1] << ")\n"; } std::cout << "\nTime to perform inference: " << ms << "ms\n" << std::endl; delete[] input_data; delete[] output; delete[] label_output; shutdownProtobufLibrary(); return 0; }
7e3dcffdcdb1172d455d470c42e540813e47b3a5
259579927768372f2642bf04b03e8c38bf4182b0
/common/FiducialFinder.h
34df01c2f7e5bde9f4073ba0b4ac2c4cf71be115
[]
no_license
oomojola/ReactivisionControl
1a4a03dd7bc788e1fc4cf72c1877a88642187a79
64f05bc737c70c227e373174e95d1f047b85efea
refs/heads/master
2021-01-22T05:10:12.491449
2010-08-27T16:35:40
2010-08-27T16:35:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,335
h
/* reacTIVision fiducial tracking framework FiducialFinder.h Copyright (C) 2005-2008 Martin Kaltenbrunner <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef FIDUCIALFINDER #define FIDUCIALFINDER #include <vector> #include <list> #include <sstream> #include <string> #include "FrameProcessor.h" #include "TuioServer.h" #include "MidiServer.h" #include "FiducialObject.h" #include "PortVideoSDL.h" #include "floatpoint.h" #ifdef __APPLE__ #include <CoreFoundation/CFBundle.h> #endif class FiducialFinder: public FrameProcessor { public: FiducialFinder(MessageServer *server, const char* grid_cfg):dmap(0) { this->message_server = server; if (server->getType()==TUIO_SERVER) { tuio_server = (TuioServer*)server; midi_server = NULL; } else if (server->getType()==MIDI_SERVER) { midi_server = (MidiServer*)server; tuio_server = NULL; } if (strcmp(grid_cfg, "none" ) == 0 ) { #ifdef __APPLE__ char path[1024]; CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef mainBundleURL = CFBundleCopyBundleURL( mainBundle); CFStringRef cfStringRef = CFURLCopyFileSystemPath( mainBundleURL, kCFURLPOSIXPathStyle); CFStringGetCString( cfStringRef, path, 1024, kCFStringEncodingASCII); CFRelease( mainBundleURL); CFRelease( cfStringRef); sprintf(full_path,"%s/Contents/Resources/calibration.grid",path); grid_config = full_path; #else grid_config = "./calibration.grid"; #endif } else grid_config = grid_cfg; calibration = false; totalframes = 0; session_id = 0; currentSetting = INV_NONE; show_settings = false; } ~FiducialFinder() { if (dmap) delete[] dmap; } virtual void process(unsigned char *src, unsigned char *dest, SDL_Surface *display) = 0; bool init(int w, int h, int sb ,int db); void toggleFlag(int flag); void finish(); protected: std::list<FiducialObject> fiducialList; int session_id; long totalframes; const char* grid_config; int cell_width, cell_height; int grid_size_x, grid_size_y; #ifdef __APPLE__ char full_path[1024]; #endif bool calibration, show_grid, empty_grid; ShortPoint* dmap; void drawObject(int id, int xpos, int ypos, SDL_Surface *display,int state); void drawGrid(unsigned char *src, unsigned char *dest, SDL_Surface *display); void drawGUI(SDL_Surface *display); void computeGrid(); TuioServer *tuio_server; MidiServer *midi_server; MessageServer *message_server; void sendTuioMessages(); void sendMidiMessages(); MessageListener::DisplayMode prevMode; bool show_settings; private: enum InvertSetting { INV_NONE, INV_XPOS, INV_YPOS, INV_ANGLE }; int currentSetting; }; #endif
3cb2bd4edcaff9a3367c9f4828e6a03a7e7c7d19
4f1f1c8b906bebe10810525e58f9c1688eebc63b
/AtCoder/nikkei2019-ex/nikkei2019ex_b.cpp
1b92d674113fee22832a1a563f87d0939d295c65
[]
no_license
stone725/CompetitiveProgramming
40ef3c6c9f9c8952366b1449805d21dc0c44d6dd
d6558c718e1dce384ca5accaf7253412849d590f
refs/heads/master
2023-01-07T11:11:19.128446
2023-01-01T01:39:39
2023-01-01T01:39:39
194,200,546
0
0
null
null
null
null
UTF-8
C++
false
false
158
cpp
#include <iostream> #include <cmath> using namespace std; int main() { int n; cin >> n; int ans = sqrt(n); cout << ans << "\n"; }
3f7dd16b017a17cd8666fb9e8bb3fb5ff2af54f9
14f6b2dba1d1a630d53e3e7e2c152b0f419d3da2
/src/unitTests/AlbumTests.cxx
111e24f80c2b25b1cb3ac7b1ec775c2e11e3229a
[]
no_license
bozhi91/SingAlong
b60bb978048bde319a34716a3bfde146e01b5030
c90f1b6e30b9a7ff75f657447ce4e221575c9d5e
refs/heads/master
2021-01-11T22:13:01.523949
2017-01-14T11:32:55
2017-01-14T11:32:55
78,935,913
0
0
null
null
null
null
UTF-8
C++
false
false
951
cxx
#include "MiniCppUnit.hxx" #include "SingAlong.hxx" class AlbumTests : public TestFixture<AlbumTests> { public: TEST_FIXTURE( AlbumTests ) { TEST_CASE( testTitle_byDefault ); TEST_CASE( testTitle_afterModifying ); TEST_CASE( testListed_byDefault ); TEST_CASE( testListed_afterListing ); TEST_CASE( testListed_afterUnlisting ); } void testTitle_byDefault() { Album album; ASSERT_EQUALS( "-- Untitled --", album.title() ); } void testTitle_afterModifying() { Album album; album.title( "A title" ); ASSERT_EQUALS( "A title", album.title() ); } void testListed_byDefault() { Album album; ASSERT_EQUALS( false, album.isListed() ); } void testListed_afterListing() { Album album; album.list(); ASSERT_EQUALS( true, album.isListed() ); } void testListed_afterUnlisting() { Album album; album.list(); album.unlist(); ASSERT_EQUALS( false, album.isListed() ); } }; REGISTER_FIXTURE( AlbumTests )
439730d05cbe9219b45cef56b7a366bdde4cb2e9
7ed28dffc9e1287cf504fdef5967a85fe9f564e7
/AtCoder/ABC144/b.cpp
163ed29ef0720755094be2549be88214dc74f419
[ "MIT" ]
permissive
Takumi1122/data-structure-algorithm
0d9cbb921315c94d559710181cdf8e3a1b8e62e5
6b9f26e4dbba981f034518a972ecfc698b86d837
refs/heads/master
2021-06-29T20:30:37.464338
2021-04-17T02:01:44
2021-04-17T02:01:44
227,387,243
0
0
null
2020-02-23T12:27:52
2019-12-11T14:37:49
C++
UTF-8
C++
false
false
396
cpp
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (n); ++i) using namespace std; using ll = long long; using P = pair<int, int>; int main() { int n; cin >> n; map<int, bool> mp; for (int i = 1; i <= 9; i++) { for (int j = 1; j <= 9; j++) { mp[i * j] = true; } } if (mp[n]) { cout << "Yes" << endl; } else { cout << "No" << endl; } return 0; }
7fa9b2de44c0f3f30c6a656fc920b50f9bb5deff
561ef87c682feea936a1622ddfb07e6aa7182807
/http/run_http_session_test.cc
43aca619e79756fbfd215bf945382d9c1350d40d
[]
no_license
deltadev/dpj
80d5b584a0baa01aee007439f3c29e89d3a892f0
93c879c9a5696b305a1a0b39058093cfd3294d8f
HEAD
2016-09-05T23:10:26.209537
2014-09-29T21:27:01
2014-09-29T21:27:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
775
cc
#include <iostream> #include "dpj_utils.h" #include "http_session.h" int main(int argc, const char * argv[]) { try { dpj::http::session session("localhost", "80"); unsigned status_code = session.request("GET", "/"); std::cout << "did request, got status: " << status_code << "\n\n"; auto hdrs = session.read_headers(); dpj::http::print_headers(hdrs); auto body = session.read_body(dpj::str::cast<int>(hdrs["Content-Length"])); std::cout << "body returned:\n\n" << std::string(body.begin(), body.end()) << "\n\n"; } catch (std::system_error & e) { std::cerr << "system_error: " << e.what() << '\n'; } catch (std::exception& e) { std::cerr << "exception: " << e.what() << '\n'; } return 0; }
db6e85e9f28acd1fd748a147f01d40d72d7fd93a
421e4085596dfb79610c7331998612c437dffce6
/src/BasicParticle.cpp
6f7ed11f2fb7d3ec9ba9360918e726adade3daa5
[]
no_license
CS343-ZachIsaac/Project1
66dfaf8add055b6cd77a85c1874a7b4d1e91eaca
327a66e736b7893f0be9a145760281e5f5bec349
refs/heads/main
2023-03-04T01:33:38.515598
2021-02-15T20:20:19
2021-02-15T20:20:19
338,895,287
0
0
null
null
null
null
UTF-8
C++
false
false
1,369
cpp
#include "BasicParticle.h" float BasicParticle::getLife() const { return life; } void BasicParticle::setLife(float _life) { this->life = _life; } void BasicParticle::setRotation(float newRotation) { rotation = newRotation; } void BasicParticle::setBrightness(float newBrightness) { brightness = newBrightness; } void BasicParticle::setPosition(glm::vec3 newPosition) { position = newPosition; } void BasicParticle::setVelocity(glm::vec3 newVelocity) { velocity = newVelocity; } void BasicParticle::setScale(glm::vec3 newScale) { scale = newScale; } void BasicParticle::setColor(glm::vec4 newColor) { color = newColor; } void BasicParticle::setSprite(int newSprite) { sprite = newSprite; } void BasicParticle::update(float dt) { //Life decrease by 0.5f per dt which is 0.5 per second life -= dt * 0.5f; //update position, velocity, etc } int BasicParticle::getSprite() const { return sprite; } float BasicParticle::getRotation() const { return rotation; } float BasicParticle::getBrightness() const { return brightness; } glm::vec3 BasicParticle::getPosition() const { return position; } glm::vec3 BasicParticle::getVelocity() const { return velocity; } glm::vec3 BasicParticle::getScale() const { return scale; } glm::vec4 BasicParticle::getColor() const { return color; }
83350a967aa4064998fab5c434bbabf8d7576c7a
fcb09d6661a9079500b2c1d5e5542fc1a8d938f6
/DataStructureSourceCode/图/邻接多重表-图/图的邻接多重表存储.cpp
35cdecd7c8e16833cdfd66a00778c9819ac11942
[]
no_license
NameSunKaiPeng/DataStructure
34fca80f18a6edcc766277471d980294362846b8
464e5858b8731b9682da1a1400fac24d0357826b
refs/heads/main
2023-03-18T02:46:31.380482
2021-03-12T16:31:36
2021-03-12T16:31:36
null
0
0
null
null
null
null
GB18030
C++
false
false
10,104
cpp
# include <stdio.h> # include <malloc.h> # include <stdlib.h> # include <string.h> # define MAX_NAME 3 # define MAX_VERTEX_NUM 20 typedef int InfoType; typedef char VertexType[MAX_NAME]; typedef enum VisitIf { unvisited, visited } VisitIf; typedef struct EBox { VisitIf mark; int ivex, jvex; struct EBox * ilink, * jlink; InfoType * info; } EBox; typedef struct VexBox { VertexType data; EBox * firstedge; } VexBox, AMList[MAX_VERTEX_NUM]; typedef struct AMLGraph { AMList adjmulist; int vexnum, edgenum; } AMLGraph; int LocateVex(AMLGraph, VertexType); void CreateUDG(AMLGraph &); void DestroyUDG(AMLGraph &); VertexType& GetVex(AMLGraph, int); bool PutVex(AMLGraph &, VertexType, VertexType); int FirstAdjVex(AMLGraph, VertexType); int NextAdjVex(AMLGraph, VertexType, VertexType); bool InsertVex(AMLGraph &, VertexType); bool DeleteVex(AMLGraph &, VertexType); bool InsertArc(AMLGraph &, VertexType, VertexType); bool DeleteArc(AMLGraph &, VertexType, VertexType); void DFS(AMLGraph, int); void DFSTraverse(AMLGraph, void(*Visit)(VertexType)); void BFSTraverse(AMLGraph, void(*Visit)(VertexType)); void MarkUnvizited(AMLGraph); void Display(AMLGraph); void visit(VertexType s) { printf("%s ", s); } int main(void) { AMLGraph G; VertexType v = {'A'}; VertexType w = {'C'}; VertexType u = {'Z'}; VertexType x = {'H'}; char * p; int i; CreateUDG(G); // p = GetVex(G, 3); // printf("%s\n", p); // PutVex(G, v, x); // p = GetVex(G, 0); // printf("%s\n", p); // i = FirstAdjVex(G, v); // printf("%d\n", i); // i = NextAdjVex(G, v, x); // printf("%d\n", i); // Display(G); // InsertVex(G, u); // Display(G); // Display(G); // DeleteVex(G, w); // Display(G); // Display(G); // InsertArc(G, x, w); // Display(G); // Display(G); // DeleteArc(G, x, w); // Display(G); // DFSTraverse(G, visit); // BFSTraverse(G, visit); // Display(G); // DestroyUDG(G); return 0; } int LocateVex(AMLGraph G, VertexType u) { int i; for(i = 0; i < G.vexnum; ++i) { if(strcmp(u, G.adjmulist[i].data) == 0) { return i; } } return -1; } void CreateUDG(AMLGraph & G) { int i, j, k; int IncInfo; VertexType va, vb; EBox * p; printf("请输入无向图的顶点数,边数,是否为带权图(是:1, 否:0):"); scanf("%d,%d,%d", &G.vexnum, &G.edgenum, &IncInfo); printf("请输入%d个顶点的值(<%d个字符):\n", G.vexnum, MAX_NAME); for(i = 0; i < G.vexnum; ++i) { scanf("%s", G.adjmulist[i].data); G.adjmulist[i].firstedge = NULL; } printf("请输入%d条边的两个顶点:\n", G.edgenum); for(k = 0; k < G.edgenum; ++k) { scanf("%s%s%*c", va, vb); i = LocateVex(G, va); j = LocateVex(G, vb); p = (EBox *)malloc(sizeof(EBox)); p->mark = unvisited; p->ivex = i; p->ilink = G.adjmulist[i].firstedge; G.adjmulist[i].firstedge = p; p->jvex = j; p->jlink = G.adjmulist[j].firstedge; G.adjmulist[j].firstedge = p; if(IncInfo) { p->info = (InfoType *)malloc(sizeof(InfoType)); printf("请输入该边的权值:"); scanf("%d", p->info); } else { p->info = NULL; } } } void DestroyUDG(AMLGraph & G) { int i; for(i = G.vexnum - 1; i >= 0; --i) { DeleteVex(G, G.adjmulist[i].data); } } VertexType& GetVex(AMLGraph G, int v) { if(v < 0 || v >= G.vexnum) { exit(-1); } return G.adjmulist[v].data; } bool PutVex(AMLGraph & G, VertexType v, VertexType value) { int i; i = LocateVex(G, v); if(i < 0) { return false; } strcpy(G.adjmulist[i].data, value); return true; } int FirstAdjVex(AMLGraph G, VertexType v) { int i; i = LocateVex(G, v); if(i < 0) { return -1; } if(G.adjmulist[i].firstedge) { if(G.adjmulist[i].firstedge->ivex == i) { return G.adjmulist[i].firstedge->jvex; } else { return G.adjmulist[i].firstedge->ivex; } } else { return -1; } } int NextAdjVex(AMLGraph G, VertexType v, VertexType w) { int i, j; EBox * p; i = LocateVex(G, v); j = LocateVex(G, w); if(i < 0 || j < 0) { return -1; } p = G.adjmulist[i].firstedge; while(p) { if(p->ivex == i && p->jvex != j) { p = p->ilink; } else if(p->jvex == i && p->ivex != j) { p = p->jlink; } else { break; } } if(p && p->ivex == i && p->jvex == j) { p = p->ilink; if(p && p->ivex == i) { return p->jvex; } else if(p && p->jvex == i) { return p->ivex; } } if(p && p->jvex == i && p->ivex == j) { p = p->jlink; if(p && p->ivex == i) { return p->jvex; } else if(p && p->jvex == i) { return p->ivex; } } return -1; } bool InsertVex(AMLGraph & G, VertexType v) { if(G.vexnum == MAX_VERTEX_NUM) { return false; } if(LocateVex(G, v) >= 0) { return false; } strcpy(G.adjmulist[G.vexnum].data, v); G.adjmulist[G.vexnum].firstedge = NULL; G.vexnum++; return true; } //邻接多重表的删除顶点函数功能有误 bool DeleteVex(AMLGraph & G, VertexType v) { int i, j; EBox * p; i = LocateVex(G, v); if(i < 0) { return false; } for(j = 0; j < G.vexnum; ++j) { DeleteArc(G, v, G.adjmulist[j].data); } for(j = i + 1; j < G.vexnum; ++j) { G.adjmulist[j - 1] = G.adjmulist[j]; } G.vexnum--; for(j = i; j < G.vexnum; ++j) { p = G.adjmulist[j].firstedge; while(p) { if(p->ivex == j + 1) { p->ivex--; p = p->ilink; } else { p->jvex--; p = p->jlink; } } } return true; } bool InsertArc(AMLGraph & G, VertexType v, VertexType w) { int i, j; int IncInfo; EBox * p; i = LocateVex(G, v); j = LocateVex(G, w); if(i < 0 || j < 0) { return false; } p = (EBox *)malloc(sizeof(EBox)); p->mark = unvisited; p->ivex = i; p->ilink = G.adjmulist[i].firstedge; G.adjmulist[i].firstedge = p; p->jvex = j; p->jlink = G.adjmulist[j].firstedge; G.adjmulist[j].firstedge = p; printf("该边是否有权值(是:1, 否:0):"); scanf("%d", &IncInfo); if(IncInfo) { p->info = (InfoType *)malloc(sizeof(InfoType)); printf("请输入该边的权值:"); scanf("%d", p->info); } else { p->info = NULL; } G.edgenum++; return true; } bool DeleteArc(AMLGraph & G, VertexType v, VertexType w) { int i, j; EBox * p, * q; i = LocateVex(G, v); j = LocateVex(G, w); if(i < 0 || j < 0) { return false; } p = G.adjmulist[i].firstedge; if(p && p->jvex == j) { G.adjmulist[i].firstedge = p->ilink; } else if(p && p->ivex == j) { G.adjmulist[i].firstedge = p->jlink; } else { while(p) { if(p->ivex == i && p->jvex != j) { q = p; p = p->ilink; } else if(p->jvex == i && p->ivex != j) { q = p; p = p->jlink; } else { break; } } if(!p) { return false; } if(p->ivex == i && p->jvex == j) { if(q->ivex == i) { q->ilink = p->ilink; } else { q->jlink = p->ilink; } } else if(p->jvex == i && p->ivex == j) { if(q->ivex == i) { q->ilink = p->jlink; } else { q->jlink = p->jlink; } } } p = G.adjmulist[j].firstedge; if(p && p->jvex == i) { G.adjmulist[j].firstedge = p->ilink; } else if(p && p->ivex == i) { G.adjmulist[j].firstedge = p->jlink; } else { while(p) { if(p->ivex == j && p->jvex != i) { q = p; p = p->ilink; } else if(p->jvex == j && p->ivex != i) { q = p; p = p->jlink; } else { break; } } if(!p) { return false; } if(p->ivex == j && p->jvex == i) { if(q->ivex == j) { q->ilink = p->ilink; } else { q->jlink = p->ilink; } } else if(p->jvex == j && p->ivex == i) { if(q->ivex == j) { q->ilink = p->jlink; } else { q->jlink = p->jlink; } } } if(p->info) { free(p->info); } free(p); G.edgenum--; return true; } bool visite[MAX_VERTEX_NUM]; void(*VisitFunc)(VertexType); void DFS(AMLGraph G, int v) { int j; EBox * p; visite[v] = true; VisitFunc(G.adjmulist[v].data); p = G.adjmulist[v].firstedge; while(p) { j = p->ivex == v ? p->jvex : p->ivex; if(!visite[j]) { DFS(G, j); } p = p->ivex == v ? p->ilink : p->jlink; } } void DFSTraverse(AMLGraph G, void(*Visit)(VertexType)) { int v; VisitFunc = Visit; for(v = 0; v < G.vexnum; ++v) { visite[v] = false; } for(v = 0; v < G.vexnum; ++v) { if(!visite[v]) { DFS(G, v); } } printf("\n"); } # include "AMLGraphQueue.cpp" void BFSTraverse(AMLGraph G, void(*Visit)(VertexType)) { int v, u, w; Queue q; for(v = 0; v < G.vexnum; ++v) { visite[v] = false; } initQueue(&q); for(v = 0; v < G.vexnum; ++v) { if(!visite[v]) { visite[v] = true; Visit(G.adjmulist[v].data); enqueue(&q, v); while(!emptyQueue(&q)) { dequeue(&q, &u); for(w = FirstAdjVex(G, G.adjmulist[u].data); w >= 0; w = NextAdjVex(G, G.adjmulist[u].data, G.adjmulist[w].data)) { if(!visite[w]) { visite[w] = true; Visit(G.adjmulist[w].data); enqueue(&q, w); } } } } } printf("\n"); destroyQueue(&q); } void MarkUnvizited(AMLGraph G) { int i; EBox * p; for(i = 0; i < G.vexnum; ++i) { p = G.adjmulist[i].firstedge; while(p) { p->mark = unvisited; if(p->ivex == i) { p = p->ilink; } else { p = p->jlink; } } } } void Display(AMLGraph G) { int i; EBox * p; MarkUnvizited(G); printf("%d个顶点:\n", G.vexnum); for(i = 0; i < G.vexnum; ++i) { printf("%s ", G.adjmulist[i].data); } printf("\n%d条边:\n", G.edgenum); for(i = 0; i < G.vexnum; ++i) { p = G.adjmulist[i].firstedge; while(p) { if(p->ivex == i) { if(!p->mark) { printf("%s-%s ", G.adjmulist[i].data, G.adjmulist[p->jvex].data); p->mark = visited; if(p->info) { printf("权值:%d ", *(p->info)); } } p = p->ilink; } else { if(!p->mark) { printf("%s-%s ", G.adjmulist[p->ivex].data, G.adjmulist[i].data); p->mark = visited; if(p->info) { printf("权值:%d ", *(p->info)); } } p = p->jlink; } } printf("\n"); } }
bb03c8689cac77e42c3b67a079348aeb318250f4
c3f0a169cd8681ed170e100baf65166f2d5bde4b
/v2/testVS/testVS/utils.cpp
2dd35e11c82069d6cd64a9df9fddf21037459462
[]
no_license
jasong-ovo/winAutoRunMonitor_dev
eef6e36557871affc6f61349c2b3dcb3b8bcfc38
d738242eb8bf7a0fc07c77aa11ec2c35ef3d9cdc
refs/heads/master
2023-05-19T19:05:39.022632
2021-06-07T09:58:35
2021-06-07T09:58:35
371,363,120
0
0
null
null
null
null
GB18030
C++
false
false
1,971
cpp
#include "utils.h" wstring get_path_in_quotation(LPBYTE pPath) { wstring path; path = (TCHAR *)pPath; wstring modified_path; int start_point, end_point; start_point = path.find(L'\"', 0) + 1; end_point = path.find(L'\"', start_point); modified_path = path.substr(start_point, end_point - start_point ); return modified_path; } wstring get_path_end_with_exe(LPBYTE pPath) { wstring path; path = (TCHAR *)pPath; wstring modified_path; int start_point, end_point; if (path.find(L'\"') != path.npos) start_point = 1; else start_point = 0; end_point = path.find(L"exe"); modified_path = path.substr(start_point, end_point + 3 - start_point); return modified_path; } wstring get_path_end_with_sys(LPBYTE pPath) { wstring path; path = (TCHAR *)pPath; wstring modified_path; if (path.find(L"exe") != path.npos) return get_path_end_with_exe(pPath); modified_path = path; return modified_path; } wstring string2wstring(string str) { wstring result; //获取缓冲区大小,并申请空间,缓冲区大小按字符计算 int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0); TCHAR* buffer = new TCHAR[len + 1]; //多字节编码转换成宽字节编码 MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len); buffer[len] = '\0'; //添加字符串结尾 //删除缓冲区并返回值 result.append(buffer); delete[] buffer; return result; } //将wstring转换成string string wstring2string(wstring wstr) { string result; //获取缓冲区大小,并申请空间,缓冲区大小事按字节计算的 int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL); char* buffer = new char[len + 1]; //宽字节编码转换成多字节编码 WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL); buffer[len] = '\0'; //删除缓冲区并返回值 result.append(buffer); delete[] buffer; return result; }
ee176523f989c80774a6fff0b4b2b52d274471d5
bd272076b30b7843e398c40257b5688f43dec69b
/TwoSum_001/two_sum.h
8e1286eeeb4e2f458c852eec329747cc40113522
[]
no_license
YCHEN-NYU/ClionProjects
95c5ad59a0059c0ae2eecc6b9962787acb53b440
d677ca7e1df3b72e28f9b04b95d1646cc2e6cf12
refs/heads/master
2021-01-18T18:18:12.632996
2016-12-20T19:33:45
2016-12-20T19:33:45
68,966,893
0
0
null
null
null
null
UTF-8
C++
false
false
469
h
// // Created by YiYi on 11/4/16. // #ifndef TWOSUM_001_TWO_SUM_H #define TWOSUM_001_TWO_SUM_H #include <iostream> #include <vector> using namespace std; class two_sum { private: vector<int> vect_in, vect_value, vect_index; int target; public: void _init_vect(vector<int> vect_input); // initialize vector void _init_target(int target_input); // initialize target void find_two_sum(); void print_two_sum(); }; #endif //TWOSUM_001_TWO_SUM_H
830f39ffef901a8e58e726250c0b5a78bb3e990b
96fbd842b7ef83805b0e1f23bb7f74dad33d9ac3
/src/game/Player_Plane.cpp
6671c43d4aaf1a1dfd184e304d5efd0fb9e55a10
[]
no_license
Crasader/Thunder-cocos2d
d8ef2ea5a4c26369514f2bf1cd2fbf06ea801cb1
c381e234bc4eb71d9b2648952e9c73b723930f24
refs/heads/master
2020-12-04T17:26:27.393048
2019-02-03T02:23:42
2019-02-03T02:23:42
null
0
0
null
null
null
null
GB18030
C++
false
false
933
cpp
#include "Player_Plane.h" PlayerPlane * PlayerPlane::createWithProperty(PropertyManager * _property){ PlayerPlane* playerPlane = new PlayerPlane(); if (playerPlane && playerPlane->init(_property)) { playerPlane->autorelease(); return playerPlane; } else { CC_SAFE_DELETE(playerPlane); } return nullptr; } bool PlayerPlane::init(PropertyManager * _property){ this->property = _property; this->property->retain(); //默认飞行动画 ArmatureDataManager::getInstance()->addArmatureFileInfo(property->getDataName()); armature = Armature::create(property->getArmatureName()); armature->getAnimation()->play("default"); this->addChild(armature); //载入默认位置 this->setPosition(property->getDefaultPosition()); //定时自动射击 this->schedule(schedule_selector(PlayerPlane::shooting), property->getShootingInterval()); return true; } void PlayerPlane::shooting(float dt){ log("shooting"); }
72825e220e2e1df61737416fb417524c82e61d32
8f33c02d67f18b8167ae652a6fcc02c0a01943d1
/CGameView.h
961775e543f73ee7f64923af4aa05748377494a6
[]
no_license
miquelgalianallorca/BehaviorExercise
c6485ecbd2653a52aeb5bc9f94a29a07980626eb
bd7bbacb30d1a6a50056d66429b8bb40dd57c14d
refs/heads/master
2021-09-16T05:23:40.180167
2018-03-13T21:01:29
2018-03-13T21:01:29
125,101,291
0
0
null
null
null
null
UTF-8
C++
false
false
242
h
#pragma once class CGameServer; struct Message; class CGameView { public: void Init(CGameServer* _server); virtual void Update() {} virtual void StateChanged(Message *command) {} protected: CGameServer *server; };
3966eac79b940f067403b7403e799bd1ffd3e542
c9ec9bd7cef67f49da579a9ee508167c8c08a41a
/CIM_Framework/CIMFramework/include/CimAnonymous.h
f8330a4c0a62916b333e334732a4bc92462b44d3
[ "Apache-2.0" ]
permissive
intel/lms
e02d559f0407f42222a97a25482891373918fec6
3527c534c0c5ea3577b78c192811f01a6cf9a707
refs/heads/master
2023-08-16T18:04:17.618338
2023-06-16T03:35:42
2023-07-18T10:32:08
180,466,574
23
11
Apache-2.0
2023-07-18T10:32:09
2019-04-09T23:50:31
C++
UTF-8
C++
false
false
923
h
//---------------------------------------------------------------------------- // // Copyright (c) Intel Corporation, 2003 - 2021 All Rights Reserved. // // File: CimAnonymous.h // // Contents: Class which represent unknown received class form the FW, definitions. // //---------------------------------------------------------------------------- #ifndef CIMANONYMOUS_H #define CIMANONYMOUS_H 1 #include "CimBase.h" namespace Intel { namespace Manageability { namespace Cim { namespace Typed { class CIMFRAMEWORK_API CimAnonymous : public CimBase { public: CimAnonymous(ICimWsmanClient *client, const string &objectName, const string &nameSpace, const string &prefix, const string &resourceURI); CimAnonymous(const CimObject &object); virtual ~CimAnonymous(); CimObject GetUnTyped() const; string Serialize() const; void Deserialize(const string &xml); }; }; }; }; }; #endif // CIMANONYMOUS_H
a102fe11f1460b3a25f1db6c67b3a63e1a019005
a13177c2e7d70aa80e535bc1c363ffa3a8ee0862
/16p1/main.cpp
475514389c808d34c1e72e4abdd8f9efba6bb857
[]
no_license
xffox/adventofcode-2017
a75802ec05bbc9d8dffcc6dc6eb769d5be23e720
f10b881c9dd0b720d20fec3dd1b06790cb4368de
refs/heads/master
2021-05-14T14:30:40.422957
2018-01-02T04:10:49
2018-01-02T04:10:49
115,972,990
0
0
null
null
null
null
UTF-8
C++
false
false
3,048
cpp
#include <iostream> #include <cassert> #include <sstream> #include <cstddef> #include <string> #include <vector> #include <unordered_map> using namespace std; namespace { size_t parseValue(const string &s) { stringstream ss(s); size_t res = 0; ss>>res; return res; } vector<string> split(const string &str, char sep) { vector<string> res; for(size_t p = 0; p < str.size();) { auto nextPos = str.find(sep, p); if(nextPos == string::npos) { nextPos = str.size(); } res.push_back(str.substr(p, nextPos-p)); while(nextPos < str.size() && str[nextPos] == sep) ++nextPos; p = nextPos; } return res; } class solve { static constexpr size_t SZ = 16; public: solve() :posits() { for(size_t i = 0; i < 16; ++i) { const auto c = 'a' + i; posits[c] = i; } } void spin(size_t sz) { const auto begin = SZ - sz; for(auto &p : posits) { if(p.second < begin) { p.second = sz + p.second; } else { p.second = p.second - begin; } } } void swapPos(size_t a, size_t b) { for(auto &p : posits) { if(p.second == a) { p.second = b; } else if(p.second == b) { p.second = a; } } } void swapName(char a, char b) { auto &left = posits[a]; auto &right = posits[b]; const auto t = left; left = right; right =t; } string getState() const { string res(SZ, '\0'); for(const auto &p : posits) { res[p.second] = p.first; } return res; } private: using posmap = unordered_map<char, size_t>; posmap posits; }; } int main() { string s; getline(cin, s); const auto inp = split(s, ','); solve solve; for(const auto &c : inp) { if(c[0] == 's') { const auto sz = parseValue(c.substr(1)); solve.spin(sz); } else if(c[0] == 'x') { const auto parts = split(c.substr(1), '/'); assert(parts.size() == 2); solve.swapPos(parseValue(parts[0]), parseValue(parts[1])); } else if(c[0] == 'p') { assert(c.size() == 4); solve.swapName(c[1], c[3]); } else { assert(false); } } cout<<solve.getState()<<endl; return 0; }
0c45713daa7d55c369de3406d6ad220a2090fb28
078a3198a5dd67ec209f68364047ae07601a0c6d
/third-party/TGUI-master/src/TGUI/Picture.cpp
874984e2b4a67301834fa63d33cefa8ce1639bc4
[ "Zlib" ]
permissive
IMACoconut/ImaKart
5f69b58dedb3b2f2e30f865b20855551f5f5c95f
27c214cf72d3bacb5f0c978a367523a75bf36a45
refs/heads/master
2016-08-06T21:34:16.454325
2014-02-26T21:47:54
2014-02-26T21:47:54
13,675,237
1
0
null
null
null
null
UTF-8
C++
false
false
9,770
cpp
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // TGUI - Texus's Graphical User Interface // Copyright (C) 2012-2013 Bruno Van de Velde ([email protected]) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <TGUI/Picture.hpp> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace tgui { ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Picture::Picture() { m_Callback.widgetType = Type_Picture; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Picture::Picture(const Picture& copy) : ClickableWidget (copy), m_LoadedFilename(copy.m_LoadedFilename) { // Copy the texture TGUI_TextureManager.copyTexture(copy.m_Texture, m_Texture); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Picture::~Picture() { // Remove the texture (if we are the only one using it) if (m_Texture.data != nullptr) TGUI_TextureManager.removeTexture(m_Texture); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Picture& Picture::operator= (const Picture& right) { // Make sure it is not the same widget if (this != &right) { Picture temp(right); this->ClickableWidget::operator=(right); std::swap(m_LoadedFilename, temp.m_LoadedFilename); std::swap(m_Texture, temp.m_Texture); } return *this; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Picture* Picture::clone() { return new Picture(*this); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Picture::load(const std::string& filename) { m_LoadedFilename = filename; // When everything is loaded successfully, this will become true. m_Loaded = false; m_Size.x = 0; m_Size.y = 0; // Make sure that the filename isn't empty if (filename.empty()) return false; // If we have already loaded a texture then first delete it if (m_Texture.data != nullptr) TGUI_TextureManager.removeTexture(m_Texture); // Try to load the texture from the file if (TGUI_TextureManager.getTexture(filename, m_Texture)) { m_Loaded = true; // Remember the size of the texture setSize(static_cast<float>(m_Texture.getSize().x),static_cast<float>( m_Texture.getSize().y)); return true; } else // The texture was not loaded return false; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const std::string& Picture::getLoadedFilename() const { return m_LoadedFilename; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Picture::setPosition(float x, float y) { Transformable::setPosition(x, y); m_Texture.sprite.setPosition(x, y); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Picture::setSize(float width, float height) { m_Size.x = width; m_Size.y = height; if (m_Loaded) m_Texture.sprite.setScale(m_Size.x / m_Texture.getSize().x, m_Size.y / m_Texture.getSize().y); else TGUI_OUTPUT("TGUI warning: Picture::setSize called while Picture wasn't loaded yet."); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Picture::setSmooth(bool smooth) { if (m_Loaded) m_Texture.data->texture.setSmooth(smooth); else TGUI_OUTPUT("TGUI warning: Picture::setSmooth called while Picture wasn't loaded yet."); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Picture::isSmooth() const { if (m_Loaded) return m_Texture.data->texture.isSmooth(); else { TGUI_OUTPUT("TGUI warning: Picture::isSmooth called while Picture wasn't loaded yet."); return false; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Picture::setTransparency(unsigned char transparency) { ClickableWidget::setTransparency(transparency); m_Texture.sprite.setColor(sf::Color(255, 255, 255, m_Opacity)); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Picture::mouseOnWidget(float x, float y) { // Don't do anything when the image wasn't loaded if (m_Loaded == false) return false; // Check if the mouse is on top of the picture if (getTransform().transformRect(sf::FloatRect(0, 0, m_Size.x, m_Size.y)).contains(x, y)) { sf::Vector2f scaling; scaling.x = m_Size.x / m_Texture.getSize().x; scaling.y = m_Size.y / m_Texture.getSize().y; // Only return true when the pixel under the mouse isn't transparent if (!m_Texture.isTransparentPixel(static_cast<unsigned int>((x - getPosition().x) / scaling.x), static_cast<unsigned int>((y - getPosition().y) / scaling.y))) return true; } if (m_MouseHover == true) mouseLeftWidget(); m_MouseHover = false; return false; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Picture::setProperty(std::string property, const std::string& value) { property = toLower(property); if (property == "filename") { load(value); } else if (property == "smooth") { if ((value == "true") || (value == "True")) setSmooth(true); else if ((value == "false") || (value == "False")) setSmooth(false); else TGUI_OUTPUT("TGUI error: Failed to parse 'Smooth' property."); } else // The property didn't match return ClickableWidget::setProperty(property, value); // You pass here when one of the properties matched return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Picture::getProperty(std::string property, std::string& value) const { property = toLower(property); if (property == "filename") value = getLoadedFilename(); else if (property == "smooth") value = isSmooth() ? "true" : "false"; else // The property didn't match return ClickableWidget::getProperty(property, value); // You pass here when one of the properties matched return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::list< std::pair<std::string, std::string> > Picture::getPropertyList() const { auto list = ClickableWidget::getPropertyList(); list.push_back(std::pair<std::string, std::string>("Filename", "string")); list.push_back(std::pair<std::string, std::string>("Smooth", "bool")); return list; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Picture::draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(m_Texture, states); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////