blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
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 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b05d214360db8179c89dda9fa5cda25333ea10d4 | 196f8f99d6e6348a5ee24f827db1d3a09a74c6e6 | /EASYPROB/main.cpp | ad26188f91ee58ae0c4ea80a5fcd42d66f2ac344 | [] | no_license | gagan86nagpal/SPOJ-200 | a8259cb5b9eb6392589b25580ecc32c265f44736 | b7ac87787a9ec89fbf9db86493398d309efe103f | refs/heads/master | 2021-09-06T16:13:38.141265 | 2018-02-08T12:10:47 | 2018-02-08T12:10:47 | 111,628,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 778 | cpp | #include <iostream>
using namespace std;
int main()
{
string _1 = "2(0)";
string _2 = "2";
string _4 = "2(2)";
string _8 = "2(2+2(0))";
string _16= "2(2(2))";
string _32 = "2(2(2)+2(0))";
string _64 = "2(2(2)+2)";
string _128 ="2(2(2)+2+2(0))";
string _256="2(2(2+2(0)))";
string _1024 = "2(2(2+2(0))+2)";
string _16384="2(2(2+2(0))+2(2)+2)";
cout<<"137="<<_128+"+"+_8+"+"+_1<<"\n";
cout<<"1315="<<_1024+"+"+_256+"+"+_32+"+"+_2+"+"+_1<<"\n";
cout<<"73="<<_64+"+"+_8+"+"+_1<<"\n";
cout<<"136="<<_128+"+"+_8<<"\n";
cout<<"255="<<_128+"+"+_64+"+"+_32+"+"+_16+"+"+_8+"+"+_4+"+"+_2+"+"+_1<<"\n";
cout<<"1384="<<_1024+"+"+_256+"+"+_64+"+"+_32+"+"+_8<<"\n";
cout<<"16385="<<_16384+"+"+_1<<"\n";
return 0;
}
| [
"gagannagpal68@gmail.com"
] | gagannagpal68@gmail.com |
fca4e54a36ddb510133087c3cc89ca8cedb84eae | c14dc51c2ca9095d5c2281cef66fb52e89e2ed37 | /Inc/Instruction.h | a7a1d342c37b6cec471891998ca99a9406dd769d | [] | no_license | houssemba/M1If12-Compilation | 01aba3f43ca6b477f88f6df700c9105dd226fe06 | d9aa362ea6071591daa6c8bcbb16471f01c65ecd | refs/heads/master | 2020-05-17T23:03:20.960996 | 2013-06-27T13:48:25 | 2013-06-27T13:48:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 530 | h | #ifndef __INSTRUCTION_H
#define __INSTRUCTION_H
#include "Code3ad.hpp"
#include "Operande.hpp"
class Instruction
{
private:
int etiquetteIdent;
bool _hasEtiquette;
CodeInstruction operation;
Operande oRes;
Operande o1;
Operande o2;
public:
Instruction(CodeInstruction operation, Operande oRes, Operande o1, Operande o2);// sans etiquette
Instruction(CodeInstruction operation, Operande oRes, Operande o1, Operande o2, int etiquette); // avec etiquette
void printToStd();
};
#endif
| [
"houssem@belhadjahmed.com"
] | houssem@belhadjahmed.com |
adc88e7bed175f6689cab7ead1c12584e6b7f7b8 | b042ef2e3d51e16dc74f0f888b420121956750c5 | /Practice C++.cpp | dbc15a66a3e27fad9f23c24b13df6a12285cd017 | [] | no_license | SorymYiMRX/C-C-Practice | 14e51c329c86168275ea4e264f19c554dab92b14 | dbf9595243d1f72be74a79f2f7fbfc46c93175db | refs/heads/main | 2023-02-09T20:37:43.305649 | 2021-01-08T05:39:29 | 2021-01-08T05:39:29 | 317,801,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,258 | cpp | #include <stdio.h>
#include <iostream>
#include <conio.h>
#include <malloc.h>
#define LESSONS 3 // p140
int print(void)
{
printf("------------------------------------------------------------------------------------------------------------------------\n");
printf("-----------------------------------------hahahahahahahaahhahahahahaahah-------------------------------------------------\n");
printf("------------------------------------------------------------------------------------------------------------------------\n");
return 0;
}
void BMI(void)
{
float hight;
int weight;
double BMI;
printf("키를 입력하세요.\n");
scanf_s("%f", &hight);
printf("몸무계를 입력하세요.\n");
scanf_s("%d", &weight);
BMI = weight / (hight * hight);
printf("\n당신의 비만지수는 %f 입니다. \n", BMI);
if (BMI < 18.5)
{
printf("당신은 체중미달입니다.\n");
}
else if (BMI < 23.0)
{
printf("당신은 표준체중입니다.\n");
}
else if (BMI < 25.0)
{
printf("당신은 과체중입니다.\n");
}
else if (BMI < 30.0)
{
printf("당신은 비만입니다 입니다.\n");
}
}
void fnVal()
{
int val;
int max;
int val1 = 3, val2 = 2;
printf("max value = %d\n", val1 > val2 ? val1 : val2);
if (val1 > val2)
{
printf("%d\n", val1);
}
else
{
printf("%d\n", val2);
}
val = 5;
val = val++ + ++val;
printf("%d\n", val);
val = 5;
printf("전위형 증가: %d\n", ++val); // 6가 된 후 출력
val = 1;
printf("후위형 증가: %d\n", val++); // 출력 후 2가 됨
val = 13;
printf("전위형 감소: %d\n", --val); // 0이 된 후 출력
val = 1;
printf("후위형 감소: %d\n", val--); // 출력 후 0이 됨
}
int fnVal2()
{
unsigned char fourBitVall = 0x05, fourBitVa12 = 0x07;
unsigned char eightBitVal;
eightBitVal = fourBitVall << 4;
eightBitVal |= fourBitVa12;
printf("%x, %x -> %x\n", fourBitVall, fourBitVa12, eightBitVal);
return 0;
}
void datatype(void)
{
unsigned long one = 2500000000;
unsigned long two = 2500000000;
unsigned long three = (one + two);
typedef unsigned int UNT;
UNT ui;
ui = three;
printf("%u", ui);
}
void cost(void)
{
int year = 365;
int age;
printf("나이를 입력하세요.:");
scanf_s("%d", &age);
int val = (year * age) * 3 * 3000;
printf("지금까지 먹은 밥값은 = %d", val);
}
void CandF(void)
{
int F1, C1;
for (C1 = 10; C1 <= 10; )
{
F1 = (9 * C1 / 5) + 32;
printf("섭씨 %3d도: 화씨 %3d도\n", C1, F1);
++C1;
}
}
void gugudan(void)
{
int a, i;
for (a = 2; a <= 9; a++)
{
for (i = 1; i <= 9; i++)
{
printf("%d * %d = %d\n", a, i, a * i);
}
}
}
void gugudancustom1(void)
{
int a, i, e;
printf("시작할 단을 입력하세요.\n최소 1단까지:");
scanf_s("%d", &a);
do {
printf("마지막 단을 입력하세요.\n최대 9단까지:");
scanf_s("%d", &e);
} while (e > 9 || e < a);
for (; a <= e; a++)
{
for (i = 1; i <= 9; i++)
{
printf("[%d x %d] = %d\n", a, i, a * i);
}
}
}
void gugudancustom2(void)
{
int a, i;
for (i = 1;i<= 9; i++)
{
for (a = 2; a <= 5; a++)
{
printf("%dx%d=%2d ", a, i, a * i);
}
printf("\n");
}
printf("---------------------------\n");
for (i = 1; i <= 9; i++)
{
for (a = 6; a <= 9; a++)
{
printf("%dx%d=%2d ", a, i, a * i);
}
printf("\n");
}
}
void gugudancustom3(void)
{
int a, i, k=1;
for (k = 1; k <= 6; k+=4)
{
for (i = 1; i <= 9; i++)
{
for (a = 1; a < 5; a++)
{
printf("%dx%d=%2d ", a+k, i, (a+k) * i);
}
printf("\n");
}
printf("\n");
}
}
void printstar01(void)
{
int row, col;
char str[2] = "*";
for (row = 0; row < 10; row++)
{
for (col = 0; col <= row; col++)
{
printf("%c", str[0]);
}
printf("\n");
}
}
void printstar02(void)
{
int row, col;
char str = '*';
for (row = 0; row <= 10; row++)
{
for (col = 10-row; col >=0; col--)
{
printf("%c", str);
}
printf("\n");
}
}
void printstar03(void)
{
int row, col;
char str[2] = "*";
int sw = 1;
if (sw != 0)
{
for (row = 1; row <= 10; row++)
{
for (col = 0; col <= 10-row; col++)
{
printf(" ");
}
for (col = 0; col <= row; col++)
{
printf("%c", str[0]);
}
printf("\n");
}
}
{
for (row = 10; row >= 0; row--)
{
for (col = 0; col <= row; col++)
{
printf(" ");
}
for (col = row; col <= 10; col++)
{
printf("%c", str[0]);
}
printf("\n");
}
}
}
void printstar04(void)
{
int row, col;
char str[2] = "*";
for (row = 10; row >= 0; row--)
{
for (col = 0; col <= row; col++)
{
printf(" ");
}
for (col = row; col <= 10; col++)
{
printf("%c", str[0]);
}
printf("\n");
}
}
void scorecirculator(void)
{
int students, s, sum = 0;
// int *score = NULL;
char str[100] = { NULL, };
int score[10];
printf("성적 처리할 학생 수를 입력하세요 (최대10명까지): ");
// scanf_s("&d", &students);
gets_s(str);
students = atoi(str);
// score = (int*)malloc(sizeof(int) * students);
if (students >= 10) students = 10;
printf("학생의 성적을 입력하세요.\n");
for (s = 0; s < students; s++)
{
fflush(stdin);
printf("%d번 학생: ", s + 1);
gets_s(str);
score[s] = atoi(str);
printf("\n");
}
printf("----------------------\n");
for (s = 0; s < students; s++)
{
sum += score[s];
printf("%d번 학생: %3d\n", s + 1, score[s]);
}
printf("----------------------\n");
printf("총점: %3d\n", sum);
printf("평균: %3.2f 점\n", (double)sum / students);
// free(score);
}
void p140(void)
{
int students; // 학생 수
int sum = 0; // 합계
int 1, s; // for루프를 위한 임시변수
int scoer[][LESSONS] = {
{85, 90, 95}, //1번째 학생의 점수
{70, 82, 60}, //2번째 학생의 점수
{92, 82, 60}, //3번째 학생의 점수
{94, 75, 79}, //4번째 학생의 점수
{95, 68, 78}, //5번째 학생의 점수
{82, 79, 88}, //6번째 학생의 점수
{68, 80, 95}, //7번째 학생의 점수
{78, 84, 92} };
students = sizeof(scoer) / sizeof(scoer[0]); //학생 수 계산
for (1 = 0; 1 < LESSONS; 1++) //과목 수만큼 루프
{
sum = 0;
for (s = 0; s < students; s++) //학생 수만큼 루프
{
sum += scoer[s][1]; //과목별 총합 계산
}
printf("[%d] Total: %d, ", 1, sum);
printf("Average: %0.2f\n", (double)sum / students);
}
}
int main(void)
{
p140();
printf("이용해 주셔서 감사합니다.\n이 창을 닫으려면 아무 키나 누르세요...\n");
_getch();
return 0;
}
| [
"noreply@github.com"
] | SorymYiMRX.noreply@github.com |
865c6b323941d9f85a0867eba854331316643217 | 075a7009c123d9a282b476577d20f75a24a8aed8 | /torch/csrc/jit/runtime/register_ops_utils.h | 495dcc8698b97abb226868cd8b59b7a3cea9690a | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | waldow90/pytorch | b98c17f11b117e8b6bb17ea909529f8d8a9a0f90 | d0f2079b5e0247c38e731f5e7e7dba835aef644f | refs/heads/master | 2022-11-15T04:10:03.825667 | 2020-07-03T09:44:32 | 2020-07-03T09:52:14 | 276,874,185 | 0 | 1 | NOASSERTION | 2020-07-03T10:35:07 | 2020-07-03T10:35:06 | null | UTF-8 | C++ | false | false | 21,024 | h | #pragma once
#include <aten/src/ATen/Context.h>
#include <c10/core/DeviceType.h>
#include <torch/csrc/autograd/autograd.h>
#include <torch/csrc/autograd/edge.h>
#include <torch/csrc/autograd/function.h>
#include <torch/csrc/autograd/generated/variable_factories.h>
#include <torch/csrc/autograd/profiler.h>
#include <torch/csrc/autograd/variable.h>
#include <torch/csrc/jit/api/compilation_unit.h>
#include <torch/csrc/jit/codegen/fuser/interface.h>
#include <torch/csrc/jit/frontend/error_report.h>
#include <torch/csrc/jit/ir/ir.h>
#include <torch/csrc/jit/runtime/custom_operator.h>
#include <torch/csrc/jit/runtime/graph_executor.h>
#include <torch/csrc/jit/runtime/jit_exception.h>
#include <torch/csrc/jit/runtime/logging.h>
#include <torch/csrc/jit/runtime/operator.h>
#include <torch/csrc/jit/runtime/print_handler.h>
#include <torch/csrc/jit/runtime/profiling_record.h>
#include <torch/csrc/jit/runtime/vararg_functions.h>
#include <torch/csrc/jit/serialization/pickle.h>
#include <ATen/ExpandUtils.h>
#include <ATen/Parallel.h>
#include <ATen/WrapDimUtils.h>
#include <ATen/core/Dict.h>
#include <ATen/core/ivalue.h>
#include <c10/core/thread_pool.h>
#include <c10/util/SmallVector.h>
#include <c10/util/math_compat.h>
#include <c10/util/string_utils.h>
namespace torch {
namespace jit {
inline c10::AliasAnalysisKind aliasAnalysisFromSchema() {
return c10::AliasAnalysisKind::FROM_SCHEMA;
}
inline c10::AliasAnalysisKind aliasAnalysisConservative() {
return c10::AliasAnalysisKind::CONSERVATIVE;
}
inline c10::AliasAnalysisKind aliasAnalysisSpecialCase() {
return c10::AliasAnalysisKind::INTERNAL_SPECIAL_CASE;
}
template <class T>
c10::List<T> make_result_list(const TypePtr& elemType) {
return c10::List<T>();
}
template <>
c10::impl::GenericList make_result_list<IValue>(const TypePtr& elemType);
inline void noop(Stack* n) {}
// using the rules from python_arg_parser FunctionParameter::check
// tensor cannot have grad set, tensor must be 0 dim,
// and if the dest is an int the source must be integral type
void checkImplicitTensorToNum(const at::Tensor& t, bool toInt);
// Convert the tensor pointed to by \p data to a nested list. \p dim is the
// number of dimensions in the tensor and \p cur_dim is the dimension being
// processed by the current invocation. \p ty is the expected output IR type of
// the operation. \p is the scalar type of \p data. \p sizes and \p strides are
// the sizes and strides of the tensor operand and \p element_size is the size
// in bytes of one tensor element.
IValue tensorToListRecursive(
char* data,
int64_t cur_dim,
int64_t num_tensor_dims,
TypePtr ty,
at::ScalarType scalar_ty,
at::IntArrayRef sizes,
at::IntArrayRef strides,
size_t element_size);
static int64_t floordiv(int64_t a, int64_t b) {
if (b == 0) {
throw std::runtime_error("division by 0");
}
if ((a > 0) == (b > 0)) {
// simple case, both have same sign
return a / b;
} else {
// in python division rounds down, it doesn't not truncate like in c++
auto r = lldiv(a, b);
return (r.rem) ? r.quot - 1 : r.quot;
}
}
TORCH_API void checkDoubleInRange(double a);
static int64_t floor(double a) {
checkDoubleInRange(a);
return std::floor(a);
}
static int64_t ceil(double a) {
checkDoubleInRange(a);
return std::ceil(a);
}
static int64_t gcd(int64_t a, int64_t b) {
while (b != 0) {
int64_t r = a % b;
a = b;
b = r;
}
// in python gcd returns non-negative values
return std::abs(a);
}
int64_t partProduct(int n, int m);
void loop(int n, int64_t& p, int64_t& r);
int nminussumofbits(int v);
int64_t factorial(int n);
static const double degToRad = std::acos(-1.0) / 180.0;
static const double radToDeg = 180.0 / std::acos(-1.0);
double degrees(double x);
double radians(double x);
// reference function THPVariable_to in python_variable_methods.cpp
static at::Tensor to_dispatch(
at::Tensor self,
c10::optional<at::Device> device,
c10::optional<at::ScalarType> scalarType,
bool non_blocking,
bool copy) {
if (device && device->is_cuda()) {
at::globalContext().lazyInitCUDA();
}
if (!device && !scalarType && !copy) {
return self;
} else if (!device) {
return self.to(*scalarType, non_blocking, copy);
} else if (!scalarType) {
return self.to(*device, non_blocking, copy);
} else {
return self.to(*device, *scalarType, non_blocking, copy);
}
}
// Convert an python index (which may be negative) into an index usable for a
// C++ container
int64_t normalizeIndex(int64_t idx, int64_t list_size);
// Equivalent to list.at(idx)
template <typename T>
T getItem(const c10::List<T>& list, int64_t idx) {
const int64_t list_size = list.size();
const int64_t normalized_idx = normalizeIndex(idx, list_size);
if (normalized_idx < 0 || normalized_idx >= list_size) {
throw std::out_of_range("list index out of range");
}
return list.get(normalized_idx);
}
template <typename T>
void setItem(const c10::List<T>& list, int64_t idx, T&& value) {
const int64_t list_size = list.size();
const int64_t normalized_idx = normalizeIndex(idx, list_size);
if (normalized_idx < 0 || normalized_idx >= list_size) {
throw std::out_of_range("list index out of range");
}
list.set(normalized_idx, std::move(value));
}
void listAppend(Stack* stack);
void listReverse(Stack* stack);
template <typename T>
void minList(Stack* stack) {
c10::List<T> a = pop(stack).to<c10::List<T>>();
c10::List<T> b = pop(stack).to<c10::List<T>>();
size_t min_size = std::min(a.size(), b.size());
for (size_t i = 0; i < min_size; i++) {
if (a[i] == b[i]) {
continue;
}
push(stack, a[i] < b[i] ? a : b);
return;
}
push(stack, b.size() < a.size() ? b : a);
}
template <typename T>
void maxList(Stack* stack) {
c10::List<T> a = pop(stack).to<c10::List<T>>();
c10::List<T> b = pop(stack).to<c10::List<T>>();
size_t min_size = std::min(a.size(), b.size());
for (size_t i = 0; i < min_size; i++) {
if (a[i] == b[i]) {
continue;
}
push(stack, a[i] > b[i] ? a : b);
return;
}
push(stack, b.size() > a.size() ? b : a);
}
void listPopImpl(Stack* stack, const char* empty_message);
void listPop(Stack* stack);
void listClear(Stack* stack);
void listDelete(Stack* stack);
void listInsert(Stack* stack);
template <typename T>
void listRemove(Stack* stack) {
T elem = pop(stack).to<T>();
c10::List<T> list = pop(stack).to<c10::List<T>>();
auto pos = std::find(list.begin(), list.end(), elem);
if (pos != list.end()) {
list.erase(pos);
} else {
AT_ERROR("list.remove(x): x not in list");
}
}
template <typename T>
void listMin(Stack* stack) {
c10::List<T> list = pop(stack).to<c10::List<T>>();
size_t list_size = list.size();
if (list_size == 0) {
throw std::runtime_error("min() arg is an empty sequence");
}
T min_elem = list[0];
for (size_t i = 1; i < list_size; ++i) {
T elem = list[i];
min_elem = elem < min_elem ? elem : min_elem;
}
stack->push_back(min_elem);
}
template <typename T>
void listMax(Stack* stack) {
c10::List<T> list = pop(stack).to<c10::List<T>>();
size_t list_size = list.size();
if (list_size == 0) {
throw std::runtime_error("max() arg is an empty sequence");
}
T max_elem = list[0];
for (size_t i = 1; i < list_size; ++i) {
T elem = list[i];
max_elem = elem > max_elem ? elem : max_elem;
}
stack->push_back(max_elem);
}
template <>
void listRemove<at::Tensor>(Stack* stack);
template <typename T>
void listIndex(Stack* stack) {
T elem = pop(stack).to<T>();
c10::List<T> list = pop(stack).to<c10::List<T>>();
auto pos = std::find(list.begin(), list.end(), elem);
if (pos != list.end()) {
push(stack, static_cast<int64_t>(std::distance(list.begin(), pos)));
} else {
AT_ERROR("'", elem, "' is not in list");
}
}
template <>
void listIndex<at::Tensor>(Stack* stack);
template <typename T>
void listCount(Stack* stack) {
T elem = pop(stack).to<T>();
c10::List<T> list = pop(stack).to<c10::List<T>>();
const int64_t count = std::count(list.begin(), list.end(), elem);
push(stack, count);
}
template <>
void listCount<at::Tensor>(Stack* stack);
void listExtend(Stack* stack);
void listCopy(Stack* stack);
void listSelect(Stack* stack);
void listLen(Stack* stack);
template <typename T>
void listEq(Stack* stack) {
c10::List<T> b = pop(stack).to<c10::List<T>>();
c10::List<T> a = pop(stack).to<c10::List<T>>();
push(stack, a == b);
}
template <typename T>
void listNe(Stack* stack) {
c10::List<T> b = pop(stack).to<c10::List<T>>();
c10::List<T> a = pop(stack).to<c10::List<T>>();
push(stack, a != b);
}
inline bool tensor_list_equal(
const c10::List<at::Tensor>& a,
const c10::List<at::Tensor>& b) {
if (a.size() != b.size()) {
return false;
}
for (size_t i = 0; i < a.size(); ++i) {
at::Tensor a_element = a[i];
at::Tensor b_element = b[i];
// This preserves Python's semantics, which uses eq() to compare two
// elements, then passes the result to bool().
// see: https://docs.python.org/3.4/reference/datamodel.html#object.__ge__
const auto cmp_result = a_element.eq(b_element);
if (!cmp_result.is_nonzero()) {
return false;
}
}
return true;
}
// Specialization for at::Tensor, since it doesn't define operator==
template <>
void listEq<at::Tensor>(Stack* stack);
// Specialization for at::Tensor, since it doesn't define operator==
template <>
void listNe<at::Tensor>(Stack* stack);
void listList(Stack* stack);
template <typename T>
void listContains(Stack* stack) {
auto key = pop(stack).to<T>();
auto list = pop(stack).to<c10::List<T>>();
for (const T& item : list) {
if (item == key) {
push(stack, true);
return;
}
}
push(stack, false);
}
void listAdd(Stack* stack);
void listInplaceAdd(Stack* stack);
void listMulIntLeftInPlace(Stack* stack);
void listMulIntLeft(Stack* stack);
void listMulIntRight(Stack* stack);
void listSlice(Stack* stack);
template <typename T>
void listSort(Stack* stack) {
bool reverse = pop(stack).toBool();
c10::List<T> list = pop(stack).to<c10::List<T>>();
std::sort(list.begin(), list.end(), [reverse](const T& a, const T& b) {
// FBCode errors without this check - "strict weak ordering"
// TODO: remove when possible, since it just slows down
// sorting and doesn't do anything useful
if (a == b) {
return false;
}
return (a < b) != reverse;
});
}
// Specialization for at::Tensor
template <>
void listSort<at::Tensor>(Stack* stack);
template <typename T>
void listCopyAndSort(Stack* stack) {
c10::List<T> list = pop(stack).to<c10::List<T>>();
auto list_copied = list.copy();
std::sort(list_copied.begin(), list_copied.end(), [](const T& a, const T& b) {
// "strict weak ordering" issue - see other sort
if (a == b) {
return false;
}
return a < b;
});
push(stack, list_copied);
}
// Specialization for at::Tensor
template <>
void listCopyAndSort<at::Tensor>(Stack* stack);
void listSetItem(Stack* stack);
#define DEFINE_GENERIC_BINARY_OP(aten_op, op, result) \
Operator( \
#aten_op ".int_int(int a, int b) -> " #result, \
[](Stack* stack) { \
int64_t a, b; \
pop(stack, a, b); \
push(stack, op); \
}, \
aliasAnalysisFromSchema()), \
Operator( \
#aten_op ".float_float(float a, float b) -> " #result, \
[](Stack* stack) { \
double a, b; \
pop(stack, a, b); \
push(stack, op); \
}, \
aliasAnalysisFromSchema())
// define implementations for primitive number ops
#define DEFINE_GENERIC_OP(aten_op, int_op, float_op, int_result, float_result) \
Operator( \
#aten_op ".int(int a, int b) -> " #int_result, \
[](Stack* stack) { \
int64_t a, b; \
pop(stack, a, b); \
push(stack, int_op); \
}, \
aliasAnalysisFromSchema()), \
Operator( \
#aten_op ".float(float a, float b) -> " #float_result, \
[](Stack* stack) { \
double a, b; \
pop(stack, a, b); \
push(stack, float_op); \
}, \
aliasAnalysisFromSchema())
#define DEFINE_INT_FLOAT_OP(aten_op, op, result) \
Operator( \
#aten_op ".int_float(int a, float b) -> " #result, \
[](Stack* stack) { \
int64_t a; \
double b; \
pop(stack, a, b); \
push(stack, op); \
}, \
aliasAnalysisFromSchema()), \
Operator( \
#aten_op ".float_int(float a, int b) -> " #result, \
[](Stack* stack) { \
double a; \
int64_t b; \
pop(stack, a, b); \
push(stack, op); \
}, \
aliasAnalysisFromSchema())
#define DEFINE_INT_OP(aten_op, op) \
Operator( \
#aten_op "(int a, int b) -> int", \
[](Stack* stack) { \
int64_t a, b; \
pop(stack, a, b); \
push(stack, op); /* NOLINT(hicpp-signed-bitwise) */ \
}, \
aliasAnalysisFromSchema())
#define DEFINE_STR_CMP_OP(aten_op, op) \
Operator( \
#aten_op ".str(str a, str b) -> bool", \
[](Stack* stack) { \
auto b = pop(stack).toStringRef(); \
auto a = pop(stack).toStringRef(); \
push(stack, op); \
}, \
aliasAnalysisFromSchema())
// define a primitive op over Scalar operands.
// it's necessary to register this overload following
// int/float variations to avoid trapping Scalar args
// in unintended implicit conversions
#define DEFINE_SCALAR_BINARY_OP(aten_op, int_op, float_op, result) \
Operator( \
#aten_op "(Scalar a, Scalar b) -> " #result, \
[](Stack* stack) { \
IValue x, y; \
pop(stack, x, y); \
if (x.isDouble()) { \
if (y.isDouble()) { \
double a = x.toDouble(); \
double b = y.toDouble(); \
push(stack, float_op); \
} else { \
double a = x.toDouble(); \
int64_t b = y.toInt(); \
push(stack, float_op); \
} \
} else { \
if (y.isDouble()) { \
int64_t a = x.toInt(); \
double b = y.toDouble(); \
push(stack, float_op); \
} else { \
int64_t a = x.toInt(); \
int64_t b = y.toInt(); \
push(stack, int_op); \
} \
} \
}, \
aliasAnalysisFromSchema())
#define DEFINE_BINARY_OP(aten_op, op) \
DEFINE_GENERIC_OP(aten_op, op, op, int, float), \
DEFINE_INT_FLOAT_OP(aten_op, op, float), \
DEFINE_SCALAR_BINARY_OP(aten_op, op, op, Scalar)
#define DEFINE_BINARY_FLOAT_OP(aten_op, op) \
DEFINE_GENERIC_OP(aten_op, op, op, float, float), \
DEFINE_INT_FLOAT_OP(aten_op, op, float), \
DEFINE_SCALAR_BINARY_OP(aten_op, op, op, float)
#define DEFINE_COMPARISON_OP(aten_op, op) \
DEFINE_GENERIC_OP(aten_op, op, op, bool, bool), \
DEFINE_INT_FLOAT_OP(aten_op, op, bool), \
DEFINE_SCALAR_BINARY_OP(aten_op, op, op, bool), \
DEFINE_STR_CMP_OP(aten_op, op)
#define DEFINE_UNARY_INT_OP(aten_op, op, result) \
Operator( \
#aten_op ".int(int a) -> " #result, \
[](Stack* stack) { \
int64_t a; \
pop(stack, a); \
push(stack, op); \
}, \
aliasAnalysisFromSchema())
#define DEFINE_UNARY_FLOAT_OP(aten_op, op, result) \
Operator( \
#aten_op ".float(float a) -> " #result, \
[](Stack* stack) { \
double a; \
pop(stack, a); \
push(stack, op); \
}, \
aliasAnalysisFromSchema())
#define DEFINE_UNARY_OP(aten_op, op, int_result, float_result) \
DEFINE_UNARY_INT_OP(aten_op, op, int_result), \
DEFINE_UNARY_FLOAT_OP(aten_op, op, float_result), \
Operator( \
#aten_op ".Scalar(Scalar a) -> Scalar", \
[](Stack* stack) { \
IValue x; \
pop(stack, x); \
if (x.isDouble()) { \
double a = x.toDouble(); \
push(stack, static_cast<float_result>(op)); \
} else { \
int64_t a = x.toInt(); \
push(stack, static_cast<int_result>(op)); \
} \
}, \
aliasAnalysisFromSchema())
#define DEFINE_BOOL_OP(aten_op, op) \
Operator( \
#aten_op ".bool(bool a, bool b) -> bool", \
[](Stack* stack) { \
bool a, b; \
pop(stack, a, b); \
push(stack, op); \
}, \
aliasAnalysisFromSchema())
} // namespace jit
} // namespace torch
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
9b36ec19d42c81b44564e2b2b7738d766a91d18d | 60597b6b2139312d73a6e087107f55f028d145e8 | /AdaBoostAlgorithm.h | f811fca00839cc245e9070ebfd121a9ce2f15cd3 | [] | no_license | MichalKonradSulek/PSZT2CPP | 7f1ebed28e84f08408a800502db8ae7a8d6b6589 | 5cfb73f9166418cef006b7fa69a296a82fcebd68 | refs/heads/master | 2020-12-21T22:51:16.677133 | 2020-01-30T12:23:41 | 2020-01-30T12:23:41 | 236,590,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,419 | h | //
// Created by michalsulek on 29.01.2020.
//
#ifndef PSZT2_ADABOOSTALGORITHM_H
#define PSZT2_ADABOOSTALGORITHM_H
#include "Stump.h"
/** \file Stump.h
* Plik zawierający klasę z algorytmem AdaBoost.
*/
/** \class AdaBoostAlgorithm
* Klasa realizuje działanie algorytmu AdaBoost opartego na drzewach decyzyjnych o głębokości 1.
* Wybór drzew dokonywany jest na podstawie minimalizacji ważonych ilości błędnych decyzji. Każde kolejne krzewo tworzone jest
* z uwzględnieniem błędów popełnionych przez drzewo poprzednie. W tym celu każdemu przykładowi, wykorzystywanemu do
* trenowania algorytmu przypisywana jest waga, która jest zwiększana, gdy przykład został sklasyfikowany źle
* i zmniejszana, gdy został sklasyfikowany dobrze. Następnie, przy wyborze kolejnego drzewa, przypadki z większą
* wagą mają większy wpływ na jego kształt
*/
class AdaBoostAlgorithm {
private:
StumpCreator createStump(const Samples& samples, const std::vector<double>& weightsOfSamples) const; ///<metoda tworząca kolejne drzewo decyzyjne, zwracająca kreatora tego drzewa. Drzewo jest tworzone w następujący sposób: dla każdej cechy tworzone jest drzewo, a następnie wybierane takie o najmniejszym współczynniku Giniego
double calculateAmountOfSay(const std::vector<double>& weightsOfSamples, const std::vector<bool>& tableOfCorrectClassification) const; ///<metoda licząca wpływ drzewa na ostateczną decyzję algorytmu (wagę drzewa), na podstawie ilości podejmowanych poprawnych decyzji
void recalculateWeights(std::vector<double>& weightsOfSamples, const std::vector<bool>& tableOfCorrectClassification, double amountOfSay) const; ///<metoda aktualizując wagi przykładów
void normalizeWeights(std::vector<double>& weightsOfSamples) const; ///<metoda ormalizująca wagi przykładów tak, by ich suma była równa 1
std::vector<DecisionStump> stumps_; ///<drzewa decyzyjne
std::vector<double> amountOfSay_; ///<wagi drzew
double dividingValueOfPredictedAttribute_ = 0; ///<zmienna przechhowująca liczbę, dzielącą szukaną cechę na dwie klasy
public:
void trainAlgorithm(const Samples& samples, size_t numberOfStumps, double dividingValueOfPredictedAttribute); ///<metoda trenująca algorytm
double prediction(const RecordWithoutResult& record) const; ///<metoda zwracająca predykcję algorytmu
};
#endif //PSZT2_ADABOOSTALGORITHM_H
| [
"michal2sulek@gmail.com"
] | michal2sulek@gmail.com |
e44f11158a8db2ee8bd163f32a6ad20479c3c83a | e7babe1b4a743eac59ca64c581cec584498fd652 | /chap.4-10/sample11.cpp | 10ef8a03312490dfadcf6979053bed7954ffbdb2 | [] | no_license | originalhumanbeing/cpp_basic | e66f3d03657f7e3c7dffa05ed1db156b7ae543a9 | ca84f40732d6fea9d472ae78433c562ca6e5bfb5 | refs/heads/master | 2020-05-29T08:54:20.945068 | 2016-09-30T12:59:46 | 2016-09-30T12:59:46 | 69,268,897 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 191 | cpp | #include <iostream>
using namespace std;
int main()
{
int num1=5;
int num2=4;
double div;
div=(double)num1/(double)num2;
cout << "5/4´Â " << div << "ÀÔ´Ï´Ù. \n";
return 0;
} | [
"han.hyunjung17@gmail.com"
] | han.hyunjung17@gmail.com |
3b783d6244bf8b6a44741f6f987b2405fe6741aa | a7d1b1158f5b8ffdfc7e2b6f1a24dfd234bcded6 | /C_expedtion/inheritance/3_4/Infantry.h | 135bb813f03b13c70205cbdde997beff7196109c | [] | no_license | Ferrymania/Cplusplus_learning | 56f44c4dc47b66deea3319275a122fbda4e66930 | 99cd1451075b57aa125931e40e9f2d2aaa6d98eb | refs/heads/master | 2020-03-22T02:35:10.849423 | 2018-07-05T12:39:00 | 2018-07-05T12:39:00 | 139,380,335 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 105 | h | #include <iostream>
#include "Soldier.h"
class Infantry:public Soldier
{
public:
void attack();
};
| [
"904655716@qq.com"
] | 904655716@qq.com |
94e2f250e74efab169ed9d0a99589a1d1475f78a | 900ba17e05cf00f13590b1883c35f0b8633cef1d | /Card Flip/Model/deck.cpp | 4c8221373405768e8e58b8bffb0fbdfb5bf5092e | [] | no_license | nikunj3011/Qt-projects | d68879107fa8f74cd19747a4158ee6c80758a6a4 | 57b7c06782abd810347c9315112bbbb023f74e5b | refs/heads/main | 2023-04-01T10:34:52.375807 | 2021-04-01T06:12:30 | 2021-04-01T06:12:30 | 353,593,066 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 978 | cpp | #include "deck.h"
#include "card.h"
#include <algorithm>
#include <stdexcept>
Deck::Deck()
{
if (_deck.size() != 0)
_deck.clear();
for (auto f : Card::faces)
for (auto s : Card::suits)
_deck.push_back(std::make_shared<Card>(Card(f,s)));
_topOfDeck = _deck.size() -1;
}
bool Deck::isEmpty() const
{
return (_topOfDeck < 0);
}
CardPtr Deck::drawCard(){
if(isEmpty())
return nullptr;
else
return _deck[_topOfDeck--];
}
void Deck::shuffle()
{
std::for_each(_deck.begin(),
_deck.end(),
[](CardPtr& e)
{
if (e->isFlipped())
{
e->flip();
}
else
{
e->setMatched(false);
}
});
for (size_t i=0;i<_deck.size();++i)
{
swap(_deck[i], _deck[i + (rand() % (_deck.size()-i))]);
}
_topOfDeck = _deck.size()-1;
}
| [
"noreply@github.com"
] | nikunj3011.noreply@github.com |
aad0ff918ac02b691097b57364359b4f417d45c0 | cd416734b3ed2ce14e28bb342b8ddf3cad992f74 | /tests/oeedger8r/host/teststring.cpp | 7e15c755a20cddc43b69ba7872bc301e0d91e07c | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | kernullist/openenclave | 261b030ce36dde3cc065e45a58ad49e3a472f81f | c7c3edf41e7fcbfd6528a36eb0e06b4257979679 | refs/heads/master | 2020-03-31T20:19:28.489012 | 2018-10-11T00:39:41 | 2018-10-11T00:39:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,868 | cpp | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "../edltestutils.h"
#include <openenclave/host.h>
#include <openenclave/internal/tests.h>
#include <wchar.h>
#include "string_u.c"
void test_string_edl_ecalls(oe_enclave_t* enclave)
{
const char* str_value = "Hello, World\n";
char str[50];
sprintf(str, "%s", str_value);
// char*
OE_TEST(ecall_string_fun1(enclave, str) == OE_OK);
OE_TEST(strcmp(str, str_value) == 0);
// const char*. (char* is passed in)
OE_TEST(ecall_string_fun2(enclave, str) == OE_OK);
OE_TEST(strcmp(str, str_value) == 0);
// char* in/out
OE_TEST(ecall_string_fun3(enclave, str) == OE_OK);
OE_TEST(strcmp(str, "Goodbye\n") == 0);
// Restore value.
sprintf(str, "%s", str_value);
// char* user check.
OE_TEST(ecall_string_fun5(enclave, str) == OE_OK);
OE_TEST(strcmp(str, "Hello") == 0);
// char* user check.
OE_TEST(ecall_string_fun6(enclave, str) == OE_OK);
OE_TEST(strcmp(str, "Hello") == 0);
// Multiple string params. One null.
OE_TEST(ecall_string_fun7(enclave, str, NULL) == OE_OK);
printf("=== test_string_edl_ecalls passed\n");
}
void ocall_string_fun1(char* s)
{
ocall_string_fun1_args_t args;
check_type<char*>(args.s);
check_type<size_t>(args.s_len);
// Check that s has been copied over.
// strcmp should not crash.
OE_TEST(strcmp(s, "Hello, World\n") == 0);
}
void ocall_string_fun2(const char* s)
{
ocall_string_fun2_args_t args;
// constness is discarded when marshaling.
check_type<char*>(args.s);
check_type<size_t>(args.s_len);
// Check that s has been copied over.
// strcmp should not crash.
OE_TEST(strcmp(s, "Hello, World\n") == 0);
}
void ocall_string_fun3(char* s)
{
ocall_string_fun3_args_t args;
check_type<char*>(args.s);
check_type<size_t>(args.s_len);
// Check that s has been copied over.
// strcmp should not crash.
OE_TEST(strcmp(s, "Hello, World\n") == 0);
// Write to s. Check on enclave side for new value.
const char* new_s = "Goodbye\n";
memcpy(s, new_s, strlen(new_s) + 1);
}
void ocall_string_fun5(char* s)
{
ocall_string_fun5_args_t args;
check_type<char*>(args.s);
// User check implies no s_len field is created.
assert_no_field_s_len<ocall_string_fun5_args_t>();
// Change value to Hello.
s[5] = '\0';
}
void ocall_string_fun6(const char* s)
{
ocall_string_fun6_args_t args;
// constness is discarded when marshaling.
check_type<char*>(args.s);
// User check implies no s_len field is created.
assert_no_field_s_len<ocall_string_fun6_args_t>();
}
void ocall_string_fun7(char* s1, char* s2)
{
ocall_string_fun7_args_t args;
check_type<char*>(args.s1);
check_type<size_t>(args.s1_len);
check_type<char*>(args.s2);
check_type<size_t>(args.s2_len);
OE_TEST(s1 != NULL);
OE_TEST(s2 == NULL);
}
void test_wstring_edl_ecalls(oe_enclave_t* enclave)
{
const wchar_t* str_value = L"Hello, World\n";
wchar_t str[50];
swprintf(str, 50, L"%S", str_value);
// wchar_t*
OE_TEST(ecall_wstring_fun1(enclave, str) == OE_OK);
OE_TEST(wcscmp(str, str_value) == 0);
// const wchar_t*. (wchar_t* is passed in)
OE_TEST(ecall_wstring_fun2(enclave, str) == OE_OK);
OE_TEST(wcscmp(str, str_value) == 0);
// wchar_t* in/out
OE_TEST(ecall_wstring_fun3(enclave, str) == OE_OK);
OE_TEST(wcscmp(str, L"Goodbye\n") == 0);
// Restore value.
swprintf(str, 50, L"%S", str_value);
// wchar_t* user check.
OE_TEST(ecall_wstring_fun5(enclave, str) == OE_OK);
OE_TEST(wcscmp(str, L"Hello") == 0);
// wchar_t* user check.
OE_TEST(ecall_wstring_fun6(enclave, str) == OE_OK);
OE_TEST(wcscmp(str, L"Hello") == 0);
// Multiple wstring params. One null.
OE_TEST(ecall_wstring_fun7(enclave, str, NULL) == OE_OK);
printf("=== test_string_edl_ecalls passed\n");
}
void ocall_wstring_fun1(wchar_t* s)
{
ocall_wstring_fun1_args_t args;
check_type<wchar_t*>(args.s);
check_type<size_t>(args.s_len);
// Check that s has been copied over.
// strcmp should not crash.
OE_TEST(wcscmp(s, L"Hello, World\n") == 0);
}
void ocall_wstring_fun2(const wchar_t* s)
{
ocall_wstring_fun2_args_t args;
// constness is discarded when marshaling.
check_type<wchar_t*>(args.s);
check_type<size_t>(args.s_len);
// Check that s has been copied over.
// strcmp should not crash.
OE_TEST(wcscmp(s, L"Hello, World\n") == 0);
}
void ocall_wstring_fun3(wchar_t* s)
{
ocall_wstring_fun3_args_t args;
check_type<wchar_t*>(args.s);
check_type<size_t>(args.s_len);
// Check that s has been copied over.
// strcmp should not crash.
OE_TEST(wcscmp(s, L"Hello, World\n") == 0);
// Write to s. Check on enclave side for new value.
const wchar_t* new_s = L"Goodbye\n";
memcpy(s, new_s, (wcslen(new_s) + 1) * sizeof(wchar_t));
}
void ocall_wstring_fun5(wchar_t* s)
{
ocall_wstring_fun5_args_t args;
check_type<wchar_t*>(args.s);
// User check implies no s_len field is created.
assert_no_field_s_len<ocall_wstring_fun5_args_t>();
// Change value to Hello.
s[5] = L'\0';
}
void ocall_wstring_fun6(const wchar_t* s)
{
ocall_wstring_fun6_args_t args;
// constness is discarded when marshaling.
check_type<wchar_t*>(args.s);
// User check implies no s_len field is created.
assert_no_field_s_len<ocall_wstring_fun6_args_t>();
}
void ocall_wstring_fun7(wchar_t* s1, wchar_t* s2)
{
ocall_wstring_fun7_args_t args;
check_type<wchar_t*>(args.s1);
check_type<size_t>(args.s1_len);
check_type<wchar_t*>(args.s2);
check_type<size_t>(args.s2_len);
OE_TEST(s1 != NULL);
OE_TEST(s2 == NULL);
}
| [
"anakrish@microsoft.com"
] | anakrish@microsoft.com |
a7bcc51dec5c3117802b15caffd10d6428e2d31c | 83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1 | /v8_7_5/src/profiler/tick-sample.cc | dca3e2d04504bf0bda47522c2af7e006d6e70f2c | [
"Apache-2.0",
"bzip2-1.0.6",
"BSD-3-Clause",
"SunPro"
] | permissive | cool2528/miniblink49 | d909e39012f2c5d8ab658dc2a8b314ad0050d8ea | 7f646289d8074f098cf1244adc87b95e34ab87a8 | refs/heads/master | 2020-06-05T03:18:43.211372 | 2019-06-01T08:57:37 | 2019-06-01T08:59:56 | 192,294,645 | 2 | 0 | Apache-2.0 | 2019-06-17T07:16:28 | 2019-06-17T07:16:27 | null | UTF-8 | C++ | false | false | 11,975 | cc | // Copyright 2013 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/profiler/tick-sample.h"
#include "include/v8-profiler.h"
#include "src/asan.h"
#include "src/counters.h"
#include "src/frames-inl.h"
#include "src/heap/heap-inl.h" // For MemoryAllocator::code_range.
#include "src/msan.h"
#include "src/simulator.h"
#include "src/vm-state-inl.h"
namespace v8 {
namespace {
bool IsSamePage(i::Address ptr1, i::Address ptr2) {
const uint32_t kPageSize = 4096;
i::Address mask = ~static_cast<i::Address>(kPageSize - 1);
return (ptr1 & mask) == (ptr2 & mask);
}
// Check if the code at specified address could potentially be a
// frame setup code.
bool IsNoFrameRegion(i::Address address) {
struct Pattern {
int bytes_count;
i::byte bytes[8];
int offsets[4];
};
static Pattern patterns[] = {
#if V8_HOST_ARCH_IA32
// push %ebp
// mov %esp,%ebp
{3, {0x55, 0x89, 0xE5}, {0, 1, -1}},
// pop %ebp
// ret N
{2, {0x5D, 0xC2}, {0, 1, -1}},
// pop %ebp
// ret
{2, {0x5D, 0xC3}, {0, 1, -1}},
#elif V8_HOST_ARCH_X64
// pushq %rbp
// movq %rsp,%rbp
{4, {0x55, 0x48, 0x89, 0xE5}, {0, 1, -1}},
// popq %rbp
// ret N
{2, {0x5D, 0xC2}, {0, 1, -1}},
// popq %rbp
// ret
{2, {0x5D, 0xC3}, {0, 1, -1}},
#endif
{0, {}, {}}
};
i::byte* pc = reinterpret_cast<i::byte*>(address);
for (Pattern* pattern = patterns; pattern->bytes_count; ++pattern) {
for (int* offset_ptr = pattern->offsets; *offset_ptr != -1; ++offset_ptr) {
int offset = *offset_ptr;
if (!offset || IsSamePage(address, address - offset)) {
MSAN_MEMORY_IS_INITIALIZED(pc - offset, pattern->bytes_count);
if (!memcmp(pc - offset, pattern->bytes, pattern->bytes_count))
return true;
} else {
// It is not safe to examine bytes on another page as it might not be
// allocated thus causing a SEGFAULT.
// Check the pattern part that's on the same page and
// pessimistically assume it could be the entire pattern match.
MSAN_MEMORY_IS_INITIALIZED(pc, pattern->bytes_count - offset);
if (!memcmp(pc, pattern->bytes + offset, pattern->bytes_count - offset))
return true;
}
}
}
return false;
}
} // namespace
namespace internal {
namespace {
#if defined(USE_SIMULATOR)
class SimulatorHelper {
public:
// Returns true if register values were successfully retrieved
// from the simulator, otherwise returns false.
static bool FillRegisters(Isolate* isolate, v8::RegisterState* state);
};
bool SimulatorHelper::FillRegisters(Isolate* isolate,
v8::RegisterState* state) {
Simulator* simulator = isolate->thread_local_top()->simulator_;
// Check if there is active simulator.
if (simulator == nullptr) return false;
#if V8_TARGET_ARCH_ARM
if (!simulator->has_bad_pc()) {
state->pc = reinterpret_cast<void*>(simulator->get_pc());
}
state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp));
state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::r11));
#elif V8_TARGET_ARCH_ARM64
state->pc = reinterpret_cast<void*>(simulator->pc());
state->sp = reinterpret_cast<void*>(simulator->sp());
state->fp = reinterpret_cast<void*>(simulator->fp());
#elif V8_TARGET_ARCH_MIPS || V8_TARGET_ARCH_MIPS64
if (!simulator->has_bad_pc()) {
state->pc = reinterpret_cast<void*>(simulator->get_pc());
}
state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp));
state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::fp));
#elif V8_TARGET_ARCH_PPC
if (!simulator->has_bad_pc()) {
state->pc = reinterpret_cast<void*>(simulator->get_pc());
}
state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp));
state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::fp));
#elif V8_TARGET_ARCH_S390
if (!simulator->has_bad_pc()) {
state->pc = reinterpret_cast<void*>(simulator->get_pc());
}
state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp));
state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::fp));
#endif
if (state->sp == 0 || state->fp == 0) {
// It possible that the simulator is interrupted while it is updating
// the sp or fp register. ARM64 simulator does this in two steps:
// first setting it to zero and then setting it to the new value.
// Bailout if sp/fp doesn't contain the new value.
//
// FIXME: The above doesn't really solve the issue.
// If a 64-bit target is executed on a 32-bit host even the final
// write is non-atomic, so it might obtain a half of the result.
// Moreover as long as the register set code uses memcpy (as of now),
// it is not guaranteed to be atomic even when both host and target
// are of same bitness.
return false;
}
return true;
}
#endif // USE_SIMULATOR
} // namespace
} // namespace internal
//
// StackTracer implementation
//
DISABLE_ASAN void TickSample::Init(Isolate* v8_isolate,
const RegisterState& reg_state,
RecordCEntryFrame record_c_entry_frame,
bool update_stats,
bool use_simulator_reg_state) {
this->update_stats = update_stats;
SampleInfo info;
RegisterState regs = reg_state;
if (!GetStackSample(v8_isolate, ®s, record_c_entry_frame, stack,
kMaxFramesCount, &info, use_simulator_reg_state)) {
// It is executing JS but failed to collect a stack trace.
// Mark the sample as spoiled.
pc = nullptr;
return;
}
state = info.vm_state;
pc = regs.pc;
frames_count = static_cast<unsigned>(info.frames_count);
has_external_callback = info.external_callback_entry != nullptr;
if (has_external_callback) {
external_callback_entry = info.external_callback_entry;
} else if (frames_count) {
// sp register may point at an arbitrary place in memory, make
// sure sanitizers don't complain about it.
ASAN_UNPOISON_MEMORY_REGION(regs.sp, sizeof(void*));
MSAN_MEMORY_IS_INITIALIZED(regs.sp, sizeof(void*));
// Sample potential return address value for frameless invocation of
// stubs (we'll figure out later, if this value makes sense).
// TODO(petermarshall): This read causes guard page violations on Windows.
// Either fix this mechanism for frameless stubs or remove it.
// tos =
// i::ReadUnalignedValue<void*>(reinterpret_cast<i::Address>(regs.sp));
tos = nullptr;
} else {
tos = nullptr;
}
}
bool TickSample::GetStackSample(Isolate* v8_isolate, RegisterState* regs,
RecordCEntryFrame record_c_entry_frame,
void** frames, size_t frames_limit,
v8::SampleInfo* sample_info,
bool use_simulator_reg_state) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
sample_info->frames_count = 0;
sample_info->vm_state = isolate->current_vm_state();
sample_info->external_callback_entry = nullptr;
if (sample_info->vm_state == GC) return true;
i::Address js_entry_sp = isolate->js_entry_sp();
if (js_entry_sp == 0) return true; // Not executing JS now.
#if defined(USE_SIMULATOR)
if (use_simulator_reg_state) {
if (!i::SimulatorHelper::FillRegisters(isolate, regs)) return false;
}
#else
USE(use_simulator_reg_state);
#endif
DCHECK(regs->sp);
// Check whether we interrupted setup/teardown of a stack frame in JS code.
// Avoid this check for C++ code, as that would trigger false positives.
if (regs->pc &&
isolate->heap()->memory_allocator()->code_range().contains(
reinterpret_cast<i::Address>(regs->pc)) &&
IsNoFrameRegion(reinterpret_cast<i::Address>(regs->pc))) {
// The frame is not setup, so it'd be hard to iterate the stack. Bailout.
return false;
}
i::ExternalCallbackScope* scope = isolate->external_callback_scope();
i::Address handler = i::Isolate::handler(isolate->thread_local_top());
// If there is a handler on top of the external callback scope then
// we have already entrered JavaScript again and the external callback
// is not the top function.
if (scope && scope->scope_address() < handler) {
i::Address* external_callback_entry_ptr =
scope->callback_entrypoint_address();
sample_info->external_callback_entry =
external_callback_entry_ptr == nullptr
? nullptr
: reinterpret_cast<void*>(*external_callback_entry_ptr);
}
i::SafeStackFrameIterator it(isolate, reinterpret_cast<i::Address>(regs->fp),
reinterpret_cast<i::Address>(regs->sp),
js_entry_sp);
if (it.done()) return true;
size_t i = 0;
if (record_c_entry_frame == kIncludeCEntryFrame &&
(it.top_frame_type() == internal::StackFrame::EXIT ||
it.top_frame_type() == internal::StackFrame::BUILTIN_EXIT)) {
frames[i++] = reinterpret_cast<void*>(isolate->c_function());
}
i::RuntimeCallTimer* timer =
isolate->counters()->runtime_call_stats()->current_timer();
for (; !it.done() && i < frames_limit; it.Advance()) {
while (timer && reinterpret_cast<i::Address>(timer) < it.frame()->fp() &&
i < frames_limit) {
frames[i++] = reinterpret_cast<void*>(timer->counter());
timer = timer->parent();
}
if (i == frames_limit) break;
if (it.frame()->is_interpreted()) {
// For interpreted frames use the bytecode array pointer as the pc.
i::InterpretedFrame* frame =
static_cast<i::InterpretedFrame*>(it.frame());
// Since the sampler can interrupt execution at any point the
// bytecode_array might be garbage, so don't actually dereference it. We
// avoid the frame->GetXXX functions since they call BytecodeArray::cast,
// which has a heap access in its DCHECK.
i::Address bytecode_array = i::Memory<i::Address>(
frame->fp() + i::InterpreterFrameConstants::kBytecodeArrayFromFp);
i::Address bytecode_offset = i::Memory<i::Address>(
frame->fp() + i::InterpreterFrameConstants::kBytecodeOffsetFromFp);
// If the bytecode array is a heap object and the bytecode offset is a
// Smi, use those, otherwise fall back to using the frame's pc.
if (HAS_HEAP_OBJECT_TAG(bytecode_array) && HAS_SMI_TAG(bytecode_offset)) {
frames[i++] = reinterpret_cast<void*>(
bytecode_array + i::Internals::SmiValue(bytecode_offset));
continue;
}
}
frames[i++] = reinterpret_cast<void*>(it.frame()->pc());
}
sample_info->frames_count = i;
return true;
}
namespace internal {
void TickSample::Init(Isolate* isolate, const v8::RegisterState& state,
RecordCEntryFrame record_c_entry_frame, bool update_stats,
bool use_simulator_reg_state) {
v8::TickSample::Init(reinterpret_cast<v8::Isolate*>(isolate), state,
record_c_entry_frame, update_stats,
use_simulator_reg_state);
if (pc == nullptr) return;
timestamp = base::TimeTicks::HighResolutionNow();
}
void TickSample::print() const {
PrintF("TickSample: at %p\n", this);
PrintF(" - state: %s\n", StateToString(state));
PrintF(" - pc: %p\n", pc);
PrintF(" - stack: (%u frames)\n", frames_count);
for (unsigned i = 0; i < frames_count; i++) {
PrintF(" %p\n", stack[i]);
}
PrintF(" - has_external_callback: %d\n", has_external_callback);
PrintF(" - %s: %p\n",
has_external_callback ? "external_callback_entry" : "tos", tos);
PrintF(" - update_stats: %d\n", update_stats);
PrintF("\n");
}
} // namespace internal
} // namespace v8
| [
"22249030@qq.com"
] | 22249030@qq.com |
fcc1ba4a88f5d5c2b10ab1b1bfe859d95a76a3e4 | dd629803899abbb8b6d8b4503b3591bb7eae6e73 | /include/forge/imaging/hio/types.h | 1a0fead3334f84b80357918df1b8ffa3e0c88074 | [] | no_license | furby-tm/Winggverse | 8d78bb691d2e5eecc5197845e9cbfb98f45c58bd | 0dc9db7057f52fca3e52e73491e24f298d108106 | refs/heads/main | 2023-04-21T17:32:20.350636 | 2021-04-30T04:24:30 | 2021-04-30T04:24:30 | 362,732,238 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,597 | h | #line 1 "C:/Users/tyler/dev/WINGG/forge/imaging/hio/types.h"
/*
* Copyright 2021 Forge. All Rights Reserved.
*
* The use of this software is subject to the terms of the
* Forge license agreement provided at the time of installation
* or download, or which otherwise accompanies this software in
* either electronic or hard copy form.
*
* Portions of this file are derived from original work by Pixar
* distributed with Universal Scene Description, a project of the
* Academy Software Foundation (ASWF). https://www.aswf.io/
*
* Original Copyright (C) 2016-2021 Pixar.
* Modifications copyright (C) 2020-2021 ForgeXYZ LLC.
*
* Forge. The Animation Software & Motion Picture Co.
*/
#ifndef FORGE_IMAGING_HIO_TYPES_H
#define FORGE_IMAGING_HIO_TYPES_H
#include "forge/forge.h"
#include "forge/imaging/hio/api.h"
#include <stdlib.h>
#include <cinttypes>
FORGE_NAMESPACE_BEGIN
class GfVec3i;
/// \enum HioFormat
///
/// HioFormat describes the memory format of image buffers used in Hio.
///
/// For reference, see:
/// https://www.khronos.org/registry/vulkan/specs/1.1/html/vkspec.html#VkFormat
enum HioFormat
{
HioFormatInvalid=-1,
// UNorm8 - a 1-byte value representing a float between 0 and 1.
// float value = (unorm / 255.0f);
HioFormatUNorm8=0,
HioFormatUNorm8Vec2,
HioFormatUNorm8Vec3,
HioFormatUNorm8Vec4,
// SNorm8 - a 1-byte value representing a float between -1 and 1.
// float value = max(snorm / 127.0f, -1.0f);
HioFormatSNorm8,
HioFormatSNorm8Vec2,
HioFormatSNorm8Vec3,
HioFormatSNorm8Vec4,
// Float16 - a 2-byte IEEE half-precision float.
HioFormatFloat16,
HioFormatFloat16Vec2,
HioFormatFloat16Vec3,
HioFormatFloat16Vec4,
// Float32 - a 4-byte IEEE float.
HioFormatFloat32,
HioFormatFloat32Vec2,
HioFormatFloat32Vec3,
HioFormatFloat32Vec4,
// Double64 - a 8-byte IEEE double.
HioFormatDouble64,
HioFormatDouble64Vec2,
HioFormatDouble64Vec3,
HioFormatDouble64Vec4,
// UInt16 - a 2-byte unsigned short integer.
HioFormatUInt16,
HioFormatUInt16Vec2,
HioFormatUInt16Vec3,
HioFormatUInt16Vec4,
// Int16 - a 2-byte signed short integer.
HioFormatInt16,
HioFormatInt16Vec2,
HioFormatInt16Vec3,
HioFormatInt16Vec4,
// UInt32 - a 4-byte unsigned integer.
HioFormatUInt32,
HioFormatUInt32Vec2,
HioFormatUInt32Vec3,
HioFormatUInt32Vec4,
// Int32 - a 4-byte signed integer.
HioFormatInt32,
HioFormatInt32Vec2,
HioFormatInt32Vec3,
HioFormatInt32Vec4,
// UNorm8 SRGB - a 1-byte value representing a float between 0 and 1.
HioFormatUNorm8srgb,
HioFormatUNorm8Vec2srgb,
HioFormatUNorm8Vec3srgb,
HioFormatUNorm8Vec4srgb,
// BPTC compressed. 3-component, 4x4 blocks, signed floating-point
HioFormatBC6FloatVec3,
// BPTC compressed. 3-component, 4x4 blocks, unsigned floating-point
HioFormatBC6UFloatVec3,
// BPTC compressed. 4-component, 4x4 blocks, unsigned byte.
// Representing a float between 0 and 1.
HioFormatBC7UNorm8Vec4,
// BPTC compressed. 4-component, 4x4 blocks, unsigned byte, sRGB.
// Representing a float between 0 and 1.
HioFormatBC7UNorm8Vec4srgb,
// S3TC/DXT compressed. 4-component, 4x4 blocks, unsigned byte
// Representing a float between 0 and 1.
HioFormatBC1UNorm8Vec4,
// S3TC/DXT compressed. 4-component, 4x4 blocks, unsigned byte
// Representing a float between 0 and 1.
HioFormatBC3UNorm8Vec4,
HioFormatCount
};
/// \enum HioAddressDimension
///
/// Available texture sampling dimensions.
///
enum HioAddressDimension
{
HioAddressDimensionU,
HioAddressDimensionV,
HioAddressDimensionW
};
/// \enum HioAddressMode
///
/// Various modes used during sampling of a texture.
///
enum HioAddressMode
{
HioAddressModeClampToEdge = 0,
HioAddressModeMirrorClampToEdge,
HioAddressModeRepeat,
HioAddressModeMirrorRepeat,
HioAddressModeClampToBorderColor
};
/// \enum HioColorChannelType
///
/// Various color channel representation formats.
///
enum HioType
{
HioTypeUnsignedByte,
HioTypeUnsignedByteSRGB,
HioTypeSignedByte,
HioTypeUnsignedShort,
HioTypeSignedShort,
HioTypeUnsignedInt,
HioTypeInt,
HioTypeHalfFloat,
HioTypeFloat,
HioTypeDouble,
HioTypeCount
};
/// Returns the HioFormat of containing nChannels of HioType type.
HIO_API
HioFormat HioGetFormat(uint32_t nchannels,
HioType type,
bool isSRGB);
/// Return the HioType corresponding to the given HioFormat
HIO_API
HioType HioGetHioType(HioFormat);
/// Return the count of components (channels) in the given HioFormat.
HIO_API
int HioGetComponentCount(HioFormat format);
/// Return the size in bytes for a component (channel) in the given HioFormat.
HIO_API
size_t HioGetDataSizeOfType(HioFormat hioFormat);
/// Return the size in bytes for a component (channel) in the given HioType.
HIO_API
size_t HioGetDataSizeOfType(HioType type);
/// Returns the size of bytes per pixel for the given HioFormat
HIO_API
size_t HioGetDataSizeOfFormat(HioFormat format,
size_t *blockWidth = nullptr,
size_t *blockHeight = nullptr);
/// Return if the given format is compressed.
HIO_API
bool HioIsCompressed(HioFormat format);
/// Calculate the byte size of texture. If compressed, takes block size
/// into account.
HIO_API
size_t HioGetDataSize(const HioFormat hioFormat, const GfVec3i &dimensions);
FORGE_NAMESPACE_END
#endif
| [
"tyler@tylerfurby.com"
] | tyler@tylerfurby.com |
e6723f4e35f526982035267b583331febf95d097 | be3167504c0e32d7708e7d13725c2dbc9232f2cb | /mameppk/src/emu/bus/c64/dela_ep7x8.h | d1deb8a2da01ffe6ea58742214ed0d1580c307a2 | [] | no_license | sysfce2/MAME-Plus-Plus-Kaillera | 83b52085dda65045d9f5e8a0b6f3977d75179e78 | 9692743849af5a808e217470abc46e813c9068a5 | refs/heads/master | 2023-08-10T06:12:47.451039 | 2016-08-01T09:44:21 | 2016-08-01T09:44:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,927 | h | // license:BSD-3-Clause
// copyright-holders:Curt Coder
/**********************************************************************
Dela 7x8K EPROM cartridge emulation
**********************************************************************/
#pragma once
#ifndef __DELA_EP7X8__
#define __DELA_EP7X8__
#include "emu.h"
#include "bus/generic/slot.h"
#include "bus/generic/carts.h"
#include "exp.h"
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
// ======================> c64_dela_ep7x8_cartridge_device
class c64_dela_ep7x8_cartridge_device : public device_t,
public device_c64_expansion_card_interface
{
public:
// construction/destruction
c64_dela_ep7x8_cartridge_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
// optional information overrides
virtual machine_config_constructor device_mconfig_additions() const;
protected:
// device-level overrides
virtual void device_start();
virtual void device_reset();
// device_c64_expansion_card_interface overrides
virtual UINT8 c64_cd_r(address_space &space, offs_t offset, UINT8 data, int sphi2, int ba, int roml, int romh, int io1, int io2);
virtual void c64_cd_w(address_space &space, offs_t offset, UINT8 data, int sphi2, int ba, int roml, int romh, int io1, int io2);
private:
required_device<generic_slot_device> m_eprom1;
required_device<generic_slot_device> m_eprom2;
required_device<generic_slot_device> m_eprom3;
required_device<generic_slot_device> m_eprom4;
required_device<generic_slot_device> m_eprom5;
required_device<generic_slot_device> m_eprom6;
required_device<generic_slot_device> m_eprom7;
UINT8 m_bank;
};
// device type definition
extern const device_type C64_DELA_EP7X8;
#endif
| [
"mameppk@199a702f-54f1-4ac0-8451-560dfe28270b"
] | mameppk@199a702f-54f1-4ac0-8451-560dfe28270b |
0d578ce304d99810003a29463e2cf74917a90177 | b8d116c857b13991366b58674a4dd1a96412b5bf | /src/materialsystem/stdshaders/BlurFilterX.cpp | 6962cc7f0d49686008966842692ef80c4b406e13 | [
"MIT"
] | permissive | SCell555/hl2-asw-port | 6eaa2a4f1f68f1dfb603657d469c42c85b2d9d1a | 16441f599c6b2d3fd051ee2805cc08680dedbb03 | refs/heads/master | 2021-01-17T18:21:59.547507 | 2016-05-12T17:09:21 | 2016-05-12T17:09:21 | 49,386,904 | 3 | 1 | null | 2016-01-10T21:45:46 | 2016-01-10T21:45:44 | null | WINDOWS-1252 | C++ | false | false | 3,104 | cpp | //===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#include "BaseVSShader.h"
#include "blurfilter_vs20.inc"
#include "blurfilter_ps20b.inc"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
BEGIN_VS_SHADER_FLAGS( BlurFilterX, "Help for BlurFilterX", SHADER_NOT_EDITABLE )
BEGIN_SHADER_PARAMS
SHADER_PARAM( KERNEL, SHADER_PARAM_TYPE_INTEGER, "0", "Kernel type" )
END_SHADER_PARAMS
SHADER_INIT
{
if( params[BASETEXTURE]->IsDefined() )
{
LoadTexture( BASETEXTURE );
}
if ( !( params[ KERNEL ]->IsDefined() ) )
{
params[ KERNEL ]->SetIntValue( 0 );
}
}
SHADER_FALLBACK
{
return 0;
}
SHADER_DRAW
{
SHADOW_STATE
{
pShaderShadow->EnableDepthWrites( false );
pShaderShadow->EnableAlphaWrites( true );
pShaderShadow->EnableTexture( SHADER_SAMPLER0, true );
pShaderShadow->VertexShaderVertexFormat( VERTEX_POSITION, 1, 0, 0 );
pShaderShadow->EnableSRGBRead( SHADER_SAMPLER0, false );
pShaderShadow->EnableSRGBWrite( false );
DECLARE_STATIC_VERTEX_SHADER( blurfilter_vs20 );
SET_STATIC_VERTEX_SHADER_COMBO( KERNEL, params[ KERNEL ]->GetIntValue() ? 1 : 0 );
SET_STATIC_VERTEX_SHADER( blurfilter_vs20 );
DECLARE_STATIC_PIXEL_SHADER( blurfilter_ps20b );
SET_STATIC_PIXEL_SHADER_COMBO( KERNEL, params[ KERNEL ]->GetIntValue() );
SET_STATIC_PIXEL_SHADER_COMBO( CLEAR_COLOR, false );
SET_STATIC_PIXEL_SHADER( blurfilter_ps20b );
if ( IS_FLAG_SET( MATERIAL_VAR_ADDITIVE ) )
EnableAlphaBlending( SHADER_BLEND_ONE, SHADER_BLEND_ONE );
}
DYNAMIC_STATE
{
BindTexture( SHADER_SAMPLER0, BASETEXTURE, -1 );
float v[4];
// The temp buffer is 1/4 back buffer size
ITexture *src_texture = params[BASETEXTURE]->GetTextureValue();
int width = src_texture->GetActualWidth();
float dX = 1.0f / width;
// Tap offsets
v[0] = 1.3366f * dX;
v[1] = 0.0f;
v[2] = 0;
v[3] = 0;
pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_0, v, 1 );
v[0] = 3.4295f * dX;
v[1] = 0.0f;
pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_1, v, 1 );
v[0] = 5.4264f * dX;
v[1] = 0.0f;
pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_2, v, 1 );
v[0] = 7.4359f * dX;
v[1] = 0.0f;
pShaderAPI->SetPixelShaderConstant( 0, v, 1 );
v[0] = 9.4436f * dX;
v[1] = 0.0f;
pShaderAPI->SetPixelShaderConstant( 1, v, 1 );
v[0] = 11.4401f * dX;
v[1] = 0.0f;
pShaderAPI->SetPixelShaderConstant( 2, v, 1 );
v[0] = v[1] = v[2] = v[3] = 1.0;
pShaderAPI->SetPixelShaderConstant( 3, v, 1 );
v[0] = v[1] = v[2] = v[3] = 0.0;
v[0] = dX;
pShaderAPI->SetPixelShaderConstant( 4, v, 1 );
DECLARE_DYNAMIC_VERTEX_SHADER( blurfilter_vs20 );
SET_DYNAMIC_VERTEX_SHADER( blurfilter_vs20 );
DECLARE_DYNAMIC_PIXEL_SHADER( blurfilter_ps20b );
SET_DYNAMIC_PIXEL_SHADER( blurfilter_ps20b );
}
Draw();
}
END_SHADER
| [
"kubci.rusnk645@gmail.com"
] | kubci.rusnk645@gmail.com |
c25c26e4a8b39df8d596953f37f0c58e2b196734 | 2297fdd397a5a4571cd8272263b6cafbb1cd4b8b | /Contributor Corner/Himanshi/RomanToInteger.cpp | a25820e6edbbf8e704a9e8ba0ebd16bae686e7b1 | [
"MIT"
] | permissive | Ayonijakaushik19/Algorithmic-Treasure-Original | b331c2499a37f95d751b4803930a68e6b6ac286a | ae299d6188ee75439d140a354828164c416d6e21 | refs/heads/master | 2023-02-12T20:46:59.616385 | 2021-01-17T14:32:03 | 2021-01-17T14:32:03 | 385,998,572 | 2 | 0 | MIT | 2021-07-14T16:04:56 | 2021-07-14T16:04:55 | null | UTF-8 | C++ | false | false | 1,080 | cpp | //Question Link
//https://practice.geeksforgeeks.org/problems/roman-number-to-integer/0
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int value(char c)
{
if(c == 'I')
return 1;
else if(c == 'V')
return 5;
else if(c == 'X')
return 10;
else if(c == 'L')
return 50;
else if(c == 'C')
return 100;
else if(c == 'D')
return 500;
else if(c == 'M')
return 1000;
else
return -1;
}
int getRoman(string s)
{
int n = s.length();
int r = 0, x, y;
for(int i=0; i<n; i++)
{
if(i == n-1)
{
x = value(s[i]);
r += x;
return r;
}
else
{
x = value(s[i]);
y = value(s[i+1]);
if(x >= y)
r += x;
else
r -= x;
}
}
}
int main()
{
int t;
cin >> t;
while(t--)
{
string s;
cin >> s;
cout << getRoman(s) << endl;
}
return 0;
}
| [
"abhijittripathy99@gmail.com"
] | abhijittripathy99@gmail.com |
adf6bc1e166398acfc662a2edb03bcdb076ac833 | 2997b79fdeeb2d8a03ef7ec713a15338ffb3dd74 | /Idle/Idle.cpp | 1a8ac4691aed8e39893d275e9cf44567215e46f6 | [] | no_license | goodpaperman/gallery | bc3d9d0d00530fdb495dc93d5ce7aeb0a9486f6a | 75da45e9254522c412ce1ad63a195e417fc336e0 | refs/heads/master | 2020-05-30T11:00:05.886882 | 2019-06-01T03:40:15 | 2019-06-01T03:40:15 | 189,686,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,978 | cpp | // Idle.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "Idle.h"
#include "IdleDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CIdleApp
BEGIN_MESSAGE_MAP(CIdleApp, CWinApp)
//{{AFX_MSG_MAP(CIdleApp)
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CIdleApp construction
CIdleApp::CIdleApp()
{
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CIdleApp object
CIdleApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CIdleApp initialization
BOOL CIdleApp::InitInstance()
{
// Standard initialization
CIdleDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
}
else if (nResponse == IDCANCEL)
{
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
BOOL CIdleApp::OnIdle(LONG lCount)
{
// CG: The following code inserted by 'Idle Time Processing' component.
// Note: Do not perform lengthy tasks during OnIdle because your
// application cannot process user input until OnIdle returns.
// call the base class
BOOL bBaseIdle = CWinApp::OnIdle(lCount);
BOOL bMoreIdle = TRUE;
if (lCount == 0)
{
// TODO: add code to perform important idle time processing
TRACE("Idle: %d", lCount);
}
else if (lCount == 100)
{
// TODO: add code to perform less important tasks during idle
TRACE("Idle: %d", lCount);
}
else if (lCount == 1000)
{
// TODO: add code to perform occasional tasks during idle
bMoreIdle = bBaseIdle;
TRACE("Idle: %d", lCount);
}
// return FALSE when there is no more idle processing to do
return bMoreIdle;
}
| [
"haihai107@126.com"
] | haihai107@126.com |
5b2dfa55b168e13518e420bccb0872fe26998351 | e217eaf05d0dab8dd339032b6c58636841aa8815 | /Ifc2x3/src/OpenInfraPlatform/Ifc2x3/entity/include/IfcSurfaceStyleRefraction.h | 3fdfe5fe82b008298a37c0a6f98c07b7b8608093 | [] | no_license | bigdoods/OpenInfraPlatform | f7785ebe4cb46e24d7f636e1b4110679d78a4303 | 0266e86a9f25f2ea9ec837d8d340d31a58a83c8e | refs/heads/master | 2021-01-21T03:41:20.124443 | 2016-01-26T23:20:21 | 2016-01-26T23:20:21 | 57,377,206 | 0 | 1 | null | 2016-04-29T10:38:19 | 2016-04-29T10:38:19 | null | UTF-8 | C++ | false | false | 1,678 | h | /*! \verbatim
* \copyright Copyright (c) 2014 Julian Amann. All rights reserved.
* \date 2014-04-26 17:30
* \author Julian Amann <julian.amann@tum.de> (https://www.cms.bgu.tum.de/en/team/amann)
* \brief This file is part of the BlueFramework.
* \endverbatim
*/
#pragma once
#include <vector>
#include <map>
#include <sstream>
#include <string>
#include "../../model/shared_ptr.h"
#include "../../model/Ifc2x3Object.h"
#include "IfcSurfaceStyleElementSelect.h"
namespace OpenInfraPlatform
{
namespace Ifc2x3
{
class IfcReal;
//ENTITY
class IfcSurfaceStyleRefraction : public IfcSurfaceStyleElementSelect, public Ifc2x3Entity
{
public:
IfcSurfaceStyleRefraction();
IfcSurfaceStyleRefraction( int id );
~IfcSurfaceStyleRefraction();
// method setEntity takes over all attributes from another instance of the class
virtual void setEntity( shared_ptr<Ifc2x3Entity> other );
virtual void getStepLine( std::stringstream& stream ) const;
virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const;
virtual void readStepData( std::vector<std::string>& args, const std::map<int,shared_ptr<Ifc2x3Entity> >& map );
virtual void setInverseCounterparts( shared_ptr<Ifc2x3Entity> ptr_self );
virtual void unlinkSelf();
virtual const char* classname() const { return "IfcSurfaceStyleRefraction"; }
// IfcSurfaceStyleRefraction -----------------------------------------------------------
// attributes:
shared_ptr<IfcReal> m_RefractionIndex; //optional
shared_ptr<IfcReal> m_DispersionFactor; //optional
};
} // end namespace Ifc2x3
} // end namespace OpenInfraPlatform
| [
"planung.cms.bv@tum.de"
] | planung.cms.bv@tum.de |
f303c40ad4deb9acbc38ebddd9dd754fcef71018 | b957ed321f7594340e2d455f807da856e411e18f | /laser/LaserDef.h | 57d22044b81c54f254504f415ce772454a97b1d6 | [] | no_license | yrewzjs/SADS | a4d7fe8b2637fabae68976ddb43119fd438cc000 | 77ede95518af1b3ab3564cb8339c14487a2445a9 | refs/heads/master | 2020-05-17T09:55:33.004304 | 2019-04-26T15:15:21 | 2019-04-26T15:15:21 | 175,948,504 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,453 | h | #ifndef _LASERDEF_H_
#define _LASERDEF_H_
#define SENSOR_REQ_ERROR _T("")
#define SENSOR_GROUP_REQ_ERROR _T("")
#define SENSOR_REQ_ERROR_DATA -999.98
/************ 激光传感器安装位置与其id的对应关系 ****************
激光传感器 General布局
D1(10) | D0(09) E0(11) | E1(12)
| |
| C0(06) B0(03) A0(00) |
————————————————
C1(07) B1(04) A1(01)
C2(08) B2(05) A2(02)
激光传感器 Roof布局
———————————
F1(14) | F0(13) G0(15) | G1(16)
H1(18) | H0(17) J0(19) | J1(20)
*************************************/
#define SENSOR_NUMBER 21
/************ 激光传感器 SensorMark ****************
1、传感器编号是和配置文件强相关的,强烈不同意更改
2、增加传感器或删除传感器,注意对应的配置文件需对应变化。
**/
enum SensorMark
{ //General
A0 = 0, //A0,传感器id=0
A1 = 1, //A1 传感器id=1
A2 = 2, //A2
B0 = 3, //B0
B1 = 4, //B1
B2 = 5, //B2
C0 = 6, //C0
C1 = 7, //C1
C2 = 8, //C2
D0 = 9, //D0
D1 = 10, //D1
E0 = 11, //E0
E1 = 12, //E1
//Roof
F0 = 13, //F0
F1 = 14, //F1
G0 = 15, //G0
G1 = 16, //G1
H0 = 17,
H1 = 18,
J0 = 19,
J1 = 20
};
/************ 激光传感器 DeltaMark ****************
1、DeltaMark编号与Calculate::UpdataDeltaArr()方法强耦合在一起的,强烈不同意更改
2、若发生更改,注意该方法的更改,该方法是数据运算的核心,若出现对应错误等逻辑问题,很难发现弥补。
**/
#define DELTA_NUMBER 18
enum DeltaMark
{ //General
A2_A0 = 0, //A2-A0,传感器A2 与 传感器A0 测量值做差 被减数在前面
B2_B0 = 1,
C2_C0 = 2,
A2_A1 = 3,
B2_B1 = 4,
C2_C1 = 5,
D1_D0 = 6,
E1_E0 = 7,
D0_E0 = 8,
C0_A0 = 9,
D0_C0 = 10,
E0_A0 = 11,
//Roof
F1_F0 = 12,
G1_G0 = 13,
F0_G0 = 14,
H0_J0 = 15,
F0_H0 = 16,
G0_J0 = 17,
};
enum LaserState
{
STOPPED, //关闭
EMITTING, //开启
PARTSTOPPED, //部分关闭
};
enum SensorBrand
{
SICK, //sick
KEYENCE, //keyence
};
struct ranging_struct
{
double cali_v[SENSOR_NUMBER]; // 标定值数组
double meas_v[SENSOR_NUMBER]; // 测量值数组
double real_v[SENSOR_NUMBER]; // 真实值数组
};
class LaserDef
{
public:
static CString ParseDeltaMark(DeltaMark mark);
static CString ParseSensorMark(int mark);
};
#endif
| [
"zhangjstj@163.com"
] | zhangjstj@163.com |
83e4cf94f804db581b53b15f11a9593368d1fdf9 | ae956d4076e4fc03b632a8c0e987e9ea5ca89f56 | /SDK/MRMesh_structs.h | 39da9de9154ebf672b68cbf6fa4763e45d1bc2a5 | [] | no_license | BrownBison/Bloodhunt-BASE | 5c79c00917fcd43c4e1932bee3b94e85c89b6bc7 | 8ae1104b748dd4b294609717142404066b6bc1e6 | refs/heads/main | 2023-08-07T12:04:49.234272 | 2021-10-02T15:13:42 | 2021-10-02T15:13:42 | 638,649,990 | 1 | 0 | null | 2023-05-09T20:02:24 | 2023-05-09T20:02:23 | null | UTF-8 | C++ | false | false | 1,115 | h | #pragma once
// Name: bbbbbbbbbbbbbbbbbbbbbbblod, Version: 1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Enums
//---------------------------------------------------------------------------
// Enum MRMesh.EMeshTrackerVertexColorMode
enum class MRMesh_EMeshTrackerVertexColorMode : uint8_t
{
EMeshTrackerVertexColorMode__None = 0,
EMeshTrackerVertexColorMode__Confidence = 1,
EMeshTrackerVertexColorMode__Block = 2,
EMeshTrackerVertexColorMode__EMeshTrackerVertexColorMode_MAX = 3,
};
//---------------------------------------------------------------------------
// Script Structs
//---------------------------------------------------------------------------
// ScriptStruct MRMesh.MRMeshConfiguration
// 0x0001
struct FMRMeshConfiguration
{
unsigned char UnknownData_Y2GW[0x1]; // 0x0000(0x0001) MISSED OFFSET (PADDING)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"69031575+leoireo@users.noreply.github.com"
] | 69031575+leoireo@users.noreply.github.com |
d332b870a9d64952ed4da28fc0d5ecea8158252e | 5ffe39f3e7c42e77423dbadd8297329d41b5ce53 | /codeforces/A. Filling Diamonds.cpp | b80140a91f831951699ac5775c3b341ad9b36120 | [] | no_license | MnSakibOvi/competitive-programming | dd521b1e13926858a59ed9685cc29e734b1537ba | dd5918c7fd4333fc0acb957f84502a89d075d1cb | refs/heads/main | 2023-08-15T22:42:17.445947 | 2021-10-23T11:06:47 | 2021-10-23T11:06:47 | 376,104,374 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 267 | cpp |
#include<bits/stdc++.h>
using namespace std;
void solve();
void multipleTestCase()
{
int t;
cin>>t;
while(t--)
solve();
}
int main()
{
multipleTestCase();
return 0;
}
void solve()
{
long long int n;
cin>>n;
cout<<n<<endl;
}
| [
"mnsakib1812@gmail.com"
] | mnsakib1812@gmail.com |
7e071e770c6f893c5d7ad7a448c6e7eedcf6fc7c | 3e2a2e96c22b18c669d7d8816db3c2c73d9f46f3 | /src/zsbp/accumulatorcheckpoints.h | 3cc5a17424ee419e348fa7f837802612a53325a9 | [
"MIT"
] | permissive | sbpaycoin/sbpay | d433e96ac580031352b644a80b15cd2532e7cc2b | d2865a73c01d46245bbfe64bf4c01b7fc3cbf962 | refs/heads/master | 2022-11-12T13:54:37.647900 | 2020-07-13T05:00:56 | 2020-07-13T05:00:56 | 275,895,543 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 729 | h | // Copyright (c) 2018 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef SBPay_ACCUMULATORCHECKPOINTS_H
#define SBPay_ACCUMULATORCHECKPOINTS_H
#include <libzerocoin/bignum.h>
#include <univalue/include/univalue.h>
namespace AccumulatorCheckpoints
{
typedef std::map<libzerocoin::CoinDenomination, CBigNum> Checkpoint;
extern std::map<int, Checkpoint> mapCheckpoints;
UniValue read_json(const std::string& jsondata);
bool LoadCheckpoints(const std::string& strNetwork);
Checkpoint GetClosestCheckpoint(const int& nHeight, int& nHeightCheckpoint);
}
#endif //SBPay_ACCUMULATORCHECKPOINTS_H
| [
"67603068+sbpaycoin@users.noreply.github.com"
] | 67603068+sbpaycoin@users.noreply.github.com |
4353f10e69f58481404bcd065b69b6632a3910fe | cec716697fae96a627a705d9559d70df9c30930f | /Grasp_Manipulation/manipulability/src/manip_doc_23June18.cpp | 411fe05356f9f1449d5006bbac604f5fb9e5084b | [] | no_license | KING1360/mobman | 048e211d9c41ce0360d487b1d53ff60ad287fe85 | c6761c8ec35e49368c642a4106f98b199a23494f | refs/heads/master | 2020-03-26T08:09:22.736801 | 2018-08-15T16:09:14 | 2018-08-15T16:09:14 | 144,688,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,257 | cpp | #include <ros/ros.h>
#include "std_msgs/String.h"
#include <boost/scoped_ptr.hpp>
#include <kdl/chain.hpp>
#include <kdl/chainjnttojacsolver.hpp>
#include <kdl/chainfksolverpos_recursive.hpp>
#include <kdl/frames.hpp>
#include <kdl/jacobian.hpp>
#include <kdl/jntarray.hpp>
#include <kdl_parser/kdl_parser.hpp>
#include <sensor_msgs/JointState.h>
#include <kdl/chainfksolver.hpp>
#include <kdl/frames_io.hpp>
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <iostream>
using namespace std;
using namespace KDL;
int main(int argc, char **argv)
{
ros::init(argc, argv, "manip");
ros::NodeHandle n;
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
ros::Publisher joint_msg_pub = n.advertise<sensor_msgs::JointState>("leg_joints_states", 1);
ros::Rate loop_rate(10);
std::string robot_desc_string;
sensor_msgs::JointState joint_msg;
//n.param("robot_description", robot_desc_string, std::string());
if (n.getParam("robot_description", robot_desc_string))
{
//ROS_INFO("Got param: %s", robot_desc_string.c_str());
}
else
{
ROS_ERROR("Failed to get param 'my_param'");
}
KDL::Tree my_tree;
if (!kdl_parser::treeFromString(robot_desc_string, my_tree) ){
ROS_ERROR("Failed to construct kdl tree!");
return false;
}
else
{
ROS_INFO("Got the tree!");
}
KDL::Chain chain;
float myinput;
scanf ("%e",&myinput);
/*
//Definition of a kinematic chain & add segments to the chain
chain.addSegment(Segment(Joint(Joint::RotZ),Frame(Vector(0.0,0.0,1.020))));
chain.addSegment(Segment(Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.480))));
chain.addSegment(Segment(Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.645))));
chain.addSegment(Segment(Joint(Joint::RotZ)));
chain.addSegment(Segment(Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.120))));
chain.addSegment(Segment(Joint(Joint::RotZ)));
// Create solver based on kinematic chain
ChainFkSolverPos_recursive fksolver = ChainFkSolverPos_recursive(chain);
// Create joint array
unsigned int nj = chain.getNrOfJoints();
KDL::JntArray jointpositions = JntArray(nj);
// Assign some values to the joint positions
for(unsigned int i=0;i<nj;i++){
float myinput;
printf ("Enter the position of joint %i: ",i);
scanf ("%e",&myinput);
jointpositions(i)=(double)myinput;
}
// Create the frame that will contain the results
KDL::Frame cartpos;
// Calculate forward position kinematics
bool kinematics_status;
kinematics_status = fksolver.JntToCart(jointpositions,cartpos);
if(kinematics_status>=0){
std::cout << cartpos <<std::endl;
printf("%s \n","Succes, thanks KDL!");
}else{
printf("%s \n","Error: could not calculate forward kinematics :(");
}
*/
// ROS_INFO("I have read the robot description \n", my_tree.getNrOfJoints());
// kdl_parser::treeFromString(robot_desc_string, my_tree);
cout << "What's your name?\n ";
// kdl_parser::treeFromString(robot_desc_string, my_tree);
cout << "Schunk?\n ";
//KDL::Chain chain;
my_tree.getChain("arm_base_link", "arm_7_link", chain);
// Create solver based on kinematic chain
ChainFkSolverPos_recursive fksolver = ChainFkSolverPos_recursive(chain);
// Create joint array
int nj = chain.getNrOfJoints();
KDL::JntArray jointpositions = JntArray(nj);
printf("%s \n","Number of Joints==");
cout<< nj ;
printf("\n %s \n","This was the Number of Joint");
// Assign some values to the joint positions
for(unsigned int i=0;i<nj;i++){
float myinput;
printf ("\nEnter the position of joint %i: ",i);
//scanf ("%e",&myinput);
//jointpositions(i)=(double)myinput;
jointpositions(i)=0;
}
// Create the frame that will contain the results
KDL::Frame cartpos;
// Calculate forward position kinematics
bool kinematics_status;
kinematics_status = fksolver.JntToCart(jointpositions,cartpos);
if(kinematics_status>=0){
std::cout << "\n This is joint position= \n"<<cartpos <<std::endl;
printf("%s \n","Succes, thanks KDL!");
}else{
printf("%s \n","Error: could not calculate forward kinematics :(");
}
int segmentNR;
KDL::Jacobian J_;
J_.resize(chain.getNrOfJoints());
std::cout << "\n No. of rows of Jacobian = \n"<<J_.rows() << "\n No. of columns of Jacobian = \n"<<J_.columns() << ";\n \n"<<std::endl;
// ChainJntToJacSolver Jsolver = ChainJntToJacSolver(chain);
// int tmp_ = Jsolver.JntToJac(jointpositions,J_);
// std::cout << "\n found Jacobian = \n"<<tmp_ <<endl;
// boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_solver_;
// jnt_to_jac_solver_.reset(new KDL::ChainJntToJacSolver(chain));
// jnt_to_jac_solver_->JntToJac(jointpositions, J_);
std::cout << "\n Jacobian = \n"<<J_.data << "\n \n"<<std::endl;
KDL::JntArray joint_pos(chain.getNrOfJoints());
KDL::Frame cart_pos;
KDL::ChainFkSolverPos_recursive fk_solver(chain);
fk_solver.JntToCart(joint_pos, cart_pos);
KDL::JntArray q_init(chain.getNrOfJoints());
for (unsigned int i = 0 ; i < 6 ; i++)
{
xdot_(i) = 0;
for (unsigned int j = 0 ; j < kdl_chain_.getNrOfJoints() ; j++)
xdot_(i) += J_(i,j) * qdot_.qdot(j);
}
//ROS_INFO(joint_pos.data);
//cout<< joint_pos.data<<"HAHADDD";
//my_tree.getChain("base_link", "tool", chain);
// KDL::JntArray joint_pos(cahin.getNrOfJoints());
// KDL::Frame cart_pos;
// KDL::ChainFkSolverPos_recursive fk_solver(chain);
// fk_solver.JntToCart(joint_pos, cart_pos);
// KDL class and functions
KDL::Vector v1(1,2,1);
KDL::Vector v2(v1);
KDL::Vector v3= KDL::Vector::Zero();
cout<< v1.x()<<"\n Here you go!\n";
v2 = 2*v1;
//v1 = v1/2;
double a=dot(v1,v2);
cout<<"\n v1.x ="<< v1.x()<<"; v1.y ="<< v1.y()<<" v1.z ="<< v1.z();
cout<<"\n v2.x ="<< v2.x()<<"; v2.y ="<< v2.y()<<" v2.z ="<< v2.z();
cout<<"\n A= !\n"<< a;
cout<< v2.x()<<"\n Here you go2222222222!\n"<<"\n";
KDL::Rotation r1 = KDL::Rotation::Identity();
cout<<"\n r1 ="<< r1(1,1);
KDL::Rotation r3=KDL::Rotation::RotX(.2);
KDL::Rotation r6=KDL::Rotation::RPY(.2,1,1);
r1.SetInverse();
KDL::Rotation r7 = r1.Inverse();
KDL::Vector v5 = r1*v1;
cout<<"\n V511 ="<< v5(0);cout<<"; r12 ="<< v2(1);cout<<"; r13 ="<< v2(2);
KDL::Rotation r5 = r1*r3;
KDL::Rotation r2 = r5.Inverse();
cout<<"\n r11 ="<< r2(0,0);cout<<"; r12 ="<< r2(1,0);cout<<"; r13 ="<< r2(2,0);
cout<<"\n r21 ="<< r2(0,1);cout<<"; r22 ="<< r2(1,1);cout<<"; r23 ="<< r2(2,1);
cout<<"\n r31 ="<< r2(0,2);cout<<"; r32 ="<< r2(1,2);cout<<"; r33 ="<< r2(2,2)<<"\n";
//FRAMES
KDL::Frame f1;
f1 = KDL::Frame::Identity();
KDL::Frame f2(r5,v1);
f2 = f1.Inverse();
cout<<"\n f11 ="<< f2(0,0);cout<<"; r12 ="<< f2(1,0);cout<<"; f13 ="<< f2(2,0);cout<<"; f14 ="<< f2(3,0);
cout<<"\n f21 ="<< f2(0,1);cout<<"; r22 ="<< f2(1,1);cout<<"; f23 ="<< f2(2,1);cout<<"; f23 ="<< f2(3,1);
cout<<"\n f31 ="<< f2(0,2);cout<<"; r32 ="<< f2(1,2);cout<<"; f33 ="<< f2(2,2);cout<<"; f33 ="<< f2(3,2);
cout<<"\n f31 ="<< f2(0,3);cout<<"; r32 ="<< f2(1,3);cout<<"; f33 ="<< f2(2,3);cout<<"; f33 ="<< f2(3,3)<<"\n";
// cout<<"\n f31 ="<< f2(0,3);cout<<"; r32 ="<< f2(1,3);cout<<"; f33 ="<< f2(2,3);cout<<"; f33 ="<< f2(3,3);<<"\n";
cout<< "\nF2.M = "<<f2.M(1,1);cout<< "\nF2.P = "<<f2.p(1);
Frame f3 = f1*f2;
Twist t1;
Twist t2(v1,v2);
Twist t3 = Twist::Zero();
double vx = t2.vel.x();
cout<< "\n VX = "<< vx <<"\n";
Wrench w1(v1,v2);
Wrench w2 = Wrench::Zero();
Wrench w3 = w1+w2;
double wx = w3.force.x();
cout<< "\n WX = "<< wx <<"\n";
std::string s1;
n.param<std::string>("my_Pa", s1, "Hey this is it!");
ROS_INFO("Got it! %s", s1.c_str());
std::string s;
/*
if (n.getParam("my_Pa", s) ) {
ROS_INFO("Got it! %s", s.c_str());
}
else{
ROS_ERROR("Failed haha!!!");
}*/
int count = 0;
while (ros::ok())
{
std_msgs::String msg;
std::stringstream ss;
ss << "hello world "<<count;
//msg.data = ss.str();
msg.data = ss.str();
ROS_INFO("%s", msg.data.c_str());
chatter_pub.publish(msg);
//joint_msg_pub.publish(joint_pos);
ros::spinOnce();
loop_rate.sleep();
++count;
}
return 0;
}
| [
"a.ghalamzanesfahani@bham.ac.uk"
] | a.ghalamzanesfahani@bham.ac.uk |
c10aebc03e1cdcaaa20e642246d4bb7b5d5003e0 | f8065889eb04b83d6e708a3b6331a058d83d0337 | /Tarea2_Ayudantia_Paralela/Funciones.cpp | cc69c54c63bcd838c0fa09fe6785bc21840e09f3 | [] | no_license | michhelhernandez/Ayudantia_Paralela_2019 | ff0f6d6d97b8d2824d6044316b1b9d28297a4ad5 | 605544f3e38fd1abe90f027a0de576f023ae9c3a | refs/heads/master | 2020-05-17T17:21:55.888394 | 2019-06-01T06:05:47 | 2019-06-01T06:05:47 | 183,850,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,349 | cpp | #include <iostream>
#include <math.h>
#define tam 100000
void Llenar_Random(int A[]) //Ingresa 100000 valores random a un arreglo de enteros.
{
srand(time(NULL));
for (int i=0;i<tam;i++)
A[i]=1+rand() % (1000); // Se almacena un numero aleatorio entre 1 y 1000.
}
void Mostrar_Arreglo(int A[]) //Muestra el arreglo.
{
for(int i=0;i<tam;i++)
std::cout<<"Elemento "<<i<<": "<<A[i]<<std::endl;
}
void Calcular_Sumatorias(int A[],int& cantidad_total,double& suma,double& suma_cuadrada) //Calcula la sumatoria, cantidad total y sumatoria al cuadrado de los numeros en el arreglo.
{
for (int i=0;i<tam;i++)
{
cantidad_total++;
suma=suma+A[i];
suma_cuadrada=suma_cuadrada+(A[i]*A[i]);
}
}
double Promedio(int cantidad,double sumatoria) //Calcula y retorna el promedio.
{
double media=0;
if (cantidad!=0)
media=(sumatoria/cantidad);
return media;
}
double Desviacion(int cant,double suma_cuadrada,double promedio) //Calcula y retorna la desviacion estandar poblacional.
{
double desv=0;
if(cant!=0)
desv=sqrt( (suma_cuadrada/cant) - (promedio*promedio) ); //Se calcula la desviacion de forma "simplificada".
return desv;
}
double Varianza(double desviacion) //Calcula y retorna la varianza.
{
return (desviacion*desviacion);
}
| [
"michhelhernandez@hotmail.com"
] | michhelhernandez@hotmail.com |
b1910675392b896ef97947b3896213d30d00305d | 19b9be2641ff9f032454bd4534affd90716c852c | /src/Decimal.h | ef96553bbc1afc3cb40f80d09f9a1ce58ae66dac | [
"BSL-1.0"
] | permissive | maksverver/MSc | 4db9ce5fdb4e179e5cf5896acbc36b2362326672 | f49543afb74eba43c931e3829dffd8975118bbe7 | refs/heads/master | 2021-01-01T15:30:52.885666 | 2014-02-11T22:56:27 | 2014-02-11T22:56:27 | 34,076,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,141 | h | // Copyright (c) 2009-2013 University of Twente
// Copyright (c) 2009-2013 Michael Weber <michaelw@cs.utwente.nl>
// Copyright (c) 2009-2013 Maks Verver <maksverver@geocities.com>
// Copyright (c) 2009-2013 Eindhoven University of Technology
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef DECIMAL_H_INCLUDED
#define DECIMAL_H_INCLUDED
#include <string>
#include <sstream>
//! Arbitrary-precision natural numbers with an internal decimal representation.
class Decimal
{
static std::string str(unsigned i)
{
std::ostringstream oss;
oss << i;
return oss.str();
}
public:
/*! Construct a Decimal from a string.
\param t A string consisting of decimal digits without leading zeros. */
Decimal(const std::string &t) : s(t) { }
//! Construct a Decimal from an unsigned integer.
Decimal(const unsigned i) : s(str(i)) { }
//! Copy constructor.
Decimal(const Decimal &d) : s(d.s) { }
//! Assignment operator.
Decimal &operator=(const Decimal &d) { s = d.s; return *this; }
//! Returns the underlying decimal representation as a std::string.
const std::string &str() const { return s; }
//! Returns a character pointer to underlying decimal representation.
const char *c_str() const { return s.c_str(); }
//! Returns the length of the underlying decimal representation.
size_t size() const { return s.size(); }
//! Returns the result of adding this number to the given argument.
Decimal operator+(const Decimal &d) const;
//! Returns the result of multiplying this number with the given argument.
Decimal operator*(const Decimal &d) const;
private:
/*! Returns the digit at the `i`-th position, counted from the left.
This is equivalent to `str()[i]` which means that `i` must be between
`0` and `size()`, exclusive! */
char operator[](size_t i) const { return s[i]; }
std::string s; //! internal representation as a decimal number
};
#endif /* ndef DECIMAL_H_INCLUDED */
| [
"maksverver@geocities.com"
] | maksverver@geocities.com |
12d1eaa6aee813976fbf9dd2c881c26f8f498926 | cafe801758da2ab7df15f2b3b37d311bc6db02f7 | /iron/udp_proxy/test/rrm_test.cc | 1d33e26f6ea7f295222efee48e9d4bf0f6881e2f | [
"MIT"
] | permissive | raytheonbbn/IRON | a79da13afe8c2752407cdd82773ef3988c2959b1 | 7c4fcb15622d8029efc48e9323efbf385cbf2e63 | refs/heads/master | 2023-04-03T23:45:24.356042 | 2021-03-31T14:50:35 | 2021-03-31T14:50:35 | 275,175,579 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,680 | cc | // IRON: iron_headers
/*
* Distribution A
*
* Approved for Public Release, Distribution Unlimited
*
* EdgeCT (IRON) Software Contract No.: HR0011-15-C-0097
* DCOMP (GNAT) Software Contract No.: HR0011-17-C-0050
* Copyright (c) 2015-20 Raytheon BBN Technologies Corp.
*
* This material is based upon work supported by the Defense Advanced
* Research Projects Agency under Contracts No. HR0011-15-C-0097 and
* HR0011-17-C-0050. Any opinions, findings and conclusions or
* recommendations expressed in this material are those of the author(s)
* and do not necessarily reflect the views of the Defense Advanced
* Research Project Agency.
*
* 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.
*/
/* IRON: end */
#include <cppunit/extensions/HelperMacros.h>
#include "rrm.h"
#include "four_tuple.h"
#include "log.h"
#include "packet_pool_heap.h"
#include "unused.h"
using ::iron::Log;
using ::iron::Rrm;
namespace
{
const char* UNUSED(kClassName) = "RrmTester";
}
//============================================================================
class RrmTest : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(RrmTest);
CPPUNIT_TEST(TestRrmCreation);
CPPUNIT_TEST(TestRrmFill);
CPPUNIT_TEST(TestRrmGetFlowFourTuple);
CPPUNIT_TEST(TestRrmGetFlowDstPort);
CPPUNIT_TEST_SUITE_END();
private:
iron::PacketPoolHeap pkt_pool_;
iron::Packet* rrm_;
iron::FourTuple four_tuple_;
public:
//==========================================================================
void setUp()
{
Log::SetDefaultLevel("FEWIA");
CPPUNIT_ASSERT(pkt_pool_.Create(8));
uint32_t saddr = htonl(10);
uint32_t daddr = htonl(100);
uint16_t sport = htons(4500);
uint16_t dport = htons(5500);
four_tuple_.Set(saddr, sport, daddr, dport);
rrm_ = Rrm::CreateNewRrm(pkt_pool_, four_tuple_);
}
//==========================================================================
void tearDown()
{
pkt_pool_.Recycle(rrm_);
Log::SetDefaultLevel("FE");
}
//==========================================================================
void TestRrmCreation()
{
LogD(kClassName, __func__,
"Testing RRM creation.\n");
CPPUNIT_ASSERT(rrm_->GetLengthInBytes() == sizeof(struct iphdr) +
sizeof(struct udphdr) + 4);
// Check the src/dst addresses are flipped in RRM.
uint32_t addr;
rrm_->GetIpSrcAddr(addr);
CPPUNIT_ASSERT(addr == four_tuple_.dst_addr_nbo());
rrm_->GetIpDstAddr(addr);
CPPUNIT_ASSERT(addr == four_tuple_.src_addr_nbo());
uint16_t port;
rrm_->GetSrcPort(port);
CPPUNIT_ASSERT(port == four_tuple_.src_port_nbo());
rrm_->GetDstPort(port);
CPPUNIT_ASSERT(port == htons(Rrm::kDefaultRrmPort));
uint8_t* buf = rrm_->GetBuffer(rrm_->GetIpPayloadOffset());
memcpy(&port, buf, sizeof(port));
CPPUNIT_ASSERT(port == four_tuple_.dst_port_nbo());
}
//==========================================================================
void TestRrmFill()
{
LogD(kClassName, __func__,
"Testing RRM fill.\n");
CPPUNIT_ASSERT(rrm_->GetLengthInBytes() == sizeof(struct iphdr) +
sizeof(struct udphdr) + 4);
uint64_t tot_bytes = 100000;
uint64_t rel_bytes = 2000;
uint32_t tot_pkts = 300;
uint32_t rel_pkts = 3;
uint32_t loss_rate = 5;
Rrm::FillReport(rrm_, tot_bytes, tot_pkts, rel_bytes, rel_pkts, loss_rate);
uint64_t this_tot_bytes;
uint64_t this_rel_bytes;
uint32_t this_tot_pkts;
uint32_t this_rel_pkts;
uint32_t this_loss_rate;
Rrm::GetReport(rrm_, this_tot_bytes, this_tot_pkts, this_rel_bytes,
this_rel_pkts, this_loss_rate);
CPPUNIT_ASSERT(this_tot_bytes == tot_bytes);
CPPUNIT_ASSERT(this_rel_bytes == rel_bytes);
CPPUNIT_ASSERT(this_tot_pkts == tot_pkts);
CPPUNIT_ASSERT(this_rel_pkts == rel_pkts);
CPPUNIT_ASSERT(this_loss_rate == loss_rate);
}
//==========================================================================
void TestRrmGetFlowFourTuple()
{
LogD(kClassName, __func__,
"Testing RRM getting flow four tuple.\n");
iron::FourTuple four_tuple(0, 0, 0, 0);
Rrm::GetFlowFourTuple(rrm_, four_tuple);
CPPUNIT_ASSERT(four_tuple == four_tuple_);
}
//==========================================================================
void TestRrmGetFlowDstPort()
{
LogD(kClassName, __func__,
"Testing RRM getting dst port.\n");
uint16_t flow_dst_port = 0;
flow_dst_port = ntohs(Rrm::GetFlowDstPort(rrm_));
CPPUNIT_ASSERT(flow_dst_port == 5500);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(RrmTest);
| [
"greg.lauer@raytheon.com"
] | greg.lauer@raytheon.com |
be5e57670eadff632fef6d69287539171afde39c | e0744c97a2b4fd26f5ba6a38ba1f87a7ba9e8bc5 | /CrazyDarts2Android/app/src/main/cpp/EditorMenuMotion.hpp | a12b724268600cf55feaeae6f487c5c5117854b2 | [] | no_license | jsj2008/Metal-Game-Engine | f05ff4ec9d5c05523a774ee2ab1464f15a55c0fe | ad9520516f800126d6c48b1241e18b29aa06ae03 | refs/heads/master | 2022-03-07T14:47:51.337422 | 2019-09-23T06:15:10 | 2019-09-23T06:15:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,202 | hpp | //
// EditorMenuMotion.hpp
// Crazy Darts 2 Mac
//
// Created by Nicholas Raptis on 4/13/19.
// Copyright © 2019 Froggy Studios. All rights reserved.
//
#ifndef EditorMenuMotion_hpp
#define EditorMenuMotion_hpp
#include "ToolMenu.hpp"
#include "EditorMenuMotionTypePanel.hpp"
#include "LevelMotionControllerBlueprint.hpp"
class GameEditor;
class GamePermanentEditor;
class EditorMenuMotion : public ToolMenu {
public:
EditorMenuMotion(GameEditor *pEditor);
EditorMenuMotion(GamePermanentEditor *pEditor);
void Init();
virtual ~EditorMenuMotion();
virtual void Layout() override;
virtual void Notify(void *pSender, const char *pNotification) override;
virtual void Update() override;
void CheckSlicePanels();
bool mIsForPermSpawn;
GameEditor *mEditor;
GamePermanentEditor *mPermEditor;
LevelMotionControllerBlueprint *mMotionController;
ToolMenuPanel *mPanelMainControls;
ToolMenuSectionRow *mRowMain1;
ToolMenuSectionRow *mRowMain2;
ToolMenuSectionRow *mRowMain3;
UIButton *mButtonAddNegate;
UIButton *mButtonAddRotate;
UIButton *mButtonAddOscillateV;
UIButton *mButtonAddOscillateH;
UIButton *mButtonAddOscillateRotation;
UIButton *mButtonRemoveAll;
UIButton *mButtonRemoveFirst;
UIButton *mButtonRemoveLast;
ToolMenuPanel *mPanelTypes;
FList mTypePanelList;
//EditorMenuMotionTypePanel *
};
#endif /* EditorMenuMotion_hpp */
| [
"nraptis@gmail.com"
] | nraptis@gmail.com |
dc0d2f154f2997c2eb1828622cbbfc778b1b4e19 | 7c919da550660351db4d269651d269c9765a9d36 | /src/primitives/block.h | 41fc319bb4b365b4f3add1125a1a9020e7a5b053 | [
"MIT"
] | permissive | wyh136/innoket | f7673b8a1fd885598db949bd1bf7ac871beef005 | 27efcc929371de0eb8ea16420e2e6c63e207bcb5 | refs/heads/master | 2021-04-15T14:24:51.482275 | 2018-03-25T11:16:12 | 2018-03-25T11:16:12 | 126,707,143 | 0 | 0 | null | 2018-03-25T14:42:21 | 2018-03-25T14:42:20 | null | UTF-8 | C++ | false | false | 5,643 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Copyright (c) 2015-2017 The IKT developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_PRIMITIVES_BLOCK_H
#define BITCOIN_PRIMITIVES_BLOCK_H
#include "primitives/transaction.h"
#include "keystore.h"
#include "serialize.h"
#include "uint256.h"
/** The maximum allowed size for a serialized block, in bytes (network rule) */
static const unsigned int MAX_BLOCK_SIZE_CURRENT = 2000000;
static const unsigned int MAX_BLOCK_SIZE_LEGACY = 1000000;
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*/
class CBlockHeader
{
public:
// header
static const int32_t CURRENT_VERSION=4;
int32_t nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
uint32_t nTime;
uint32_t nBits;
uint32_t nNonce;
uint256 nAccumulatorCheckpoint;
CBlockHeader()
{
SetNull();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
//zerocoin active, header changes to include accumulator checksum
if(nVersion > 3)
READWRITE(nAccumulatorCheckpoint);
}
void SetNull()
{
nVersion = CBlockHeader::CURRENT_VERSION;
hashPrevBlock.SetNull();
hashMerkleRoot.SetNull();
nTime = 0;
nBits = 0;
nNonce = 0;
nAccumulatorCheckpoint = 0;
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const;
int64_t GetBlockTime() const
{
return (int64_t)nTime;
}
};
class CBlock : public CBlockHeader
{
public:
// network and disk
std::vector<CTransaction> vtx;
// ppcoin: block signature - signed by one of the coin base txout[N]'s owner
std::vector<unsigned char> vchBlockSig;
// memory only
mutable CScript payee;
mutable std::vector<uint256> vMerkleTree;
CBlock()
{
SetNull();
}
CBlock(const CBlockHeader &header)
{
SetNull();
*((CBlockHeader*)this) = header;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(*(CBlockHeader*)this);
READWRITE(vtx);
if(vtx.size() > 1 && vtx[1].IsCoinStake())
READWRITE(vchBlockSig);
}
void SetNull()
{
CBlockHeader::SetNull();
vtx.clear();
vMerkleTree.clear();
payee = CScript();
vchBlockSig.clear();
}
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrevBlock;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
block.nAccumulatorCheckpoint = nAccumulatorCheckpoint;
return block;
}
// ppcoin: two types of block: proof-of-work or proof-of-stake
bool IsProofOfStake() const
{
return (vtx.size() > 1 && vtx[1].IsCoinStake());
}
bool IsProofOfWork() const
{
return !IsProofOfStake();
}
bool SignBlock(const CKeyStore& keystore);
bool CheckBlockSignature() const;
std::pair<COutPoint, unsigned int> GetProofOfStake() const
{
return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, nTime) : std::make_pair(COutPoint(), (unsigned int)0);
}
// Build the in-memory merkle tree for this block and return the merkle root.
// If non-NULL, *mutated is set to whether mutation was detected in the merkle
// tree (a duplication of transactions in the block leading to an identical
// merkle root).
uint256 BuildMerkleTree(bool* mutated = NULL) const;
std::vector<uint256> GetMerkleBranch(int nIndex) const;
static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex);
std::string ToString() const;
void print() const;
};
/** Describes a place in the block chain to another node such that if the
* other node doesn't have the same branch, it can find a recent common trunk.
* The further back it is, the further before the fork it may be.
*/
struct CBlockLocator
{
std::vector<uint256> vHave;
CBlockLocator() {}
CBlockLocator(const std::vector<uint256>& vHaveIn)
{
vHave = vHaveIn;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
}
void SetNull()
{
vHave.clear();
}
bool IsNull()
{
return vHave.empty();
}
};
#endif // BITCOIN_PRIMITIVES_BLOCK_H
| [
"36470139+Innoket@users.noreply.github.com"
] | 36470139+Innoket@users.noreply.github.com |
f7b4c5b4626d7af6da51efd8a2fee75d903a5510 | b71136d14603e25a0637de413d2316f96272e148 | /cpsc3200/RockyMountain2015/FlippingCards.cpp | fa70335f1168bc08d424192fe28260680f96876d | [] | no_license | JSwidinsky/CompetitiveProgramming | 34df380b26fad53191a07c692298d68394b4fd48 | 3742a1c5f9b422f2957ad7d67fed4fbfb6981455 | refs/heads/master | 2020-09-24T07:48:34.797284 | 2020-05-21T17:45:29 | 2020-05-21T17:45:29 | 225,705,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,986 | cpp | #include <bits/stdc++.h>
using namespace std;
#define debug(a) cerr << #a << " = " << (a) << endl;
#define fst first
#define snd second
#define sz(x) (int)(x).size()
#define all(X) begin(X), end(X)
typedef long long int ll;
typedef unsigned long long int ull;
typedef pair<int, int> pii;
template<typename T, typename U> ostream& operator<<(ostream& o, const pair<T, U>& x) {
o << "(" << x.fst << ", " << x.snd << ")"; return o;
}
template<typename T> ostream& operator<<(ostream& o, const vector<T>& x) {
o << "["; int b = 0; for (auto& a : x) o << (b++ ? ", " : "") << a; o << "]"; return o;
}
template<typename T> ostream& operator<<(ostream& o, const set<T>& x) {
o << "{"; int b = 0; for (auto& a : x) o << (b++ ? ", " : "") << a; o << "}"; return o;
}
template<typename T, typename U> ostream& operator<<(ostream& o, const map<T, U>& x) {
o << "{"; int b = 0; for (auto& a : x) o << (b++ ? ", " : "") << a; o << "}"; return o;
}
struct UF {
int n; vector<int> A;
UF (int n) : n(n), A(n) { iota(begin(A), end(A), 0); }
int find (int a) { return a == A[a] ? a : A[a] = find(A[a]); }
bool connected (int a, int b) { return find(a) == find(b); }
void merge (int a, int b) { A[find(b)] = find(a); }
};
/*
In this problem, we want to find each strongly connected component
and then count the number of cycles in each of the components
If the number of cycles is < 2, then it is possible, else it is not
*/
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int t; cin >> t;
while(t--) {
int n; cin >> n;
UF uf(2*n);
vector<int> cnt(2*n, 0);
for(int i = 0; i < n; ++i) {
int a, b; cin >> a >> b;
--a; --b;
if(uf.connected(a,b)) {
cnt[uf.find(a)]++;
}
else {
cnt[uf.find(a)] += cnt[uf.find(b)];
uf.merge(a,b);
}
}
bool b = true;
for(int i = 0; i < 2*n; ++i) {
b = b && (cnt[uf.find(i)] < 2);
}
cout << (b ? "possible" : "impossible") << endl;
}
}
| [
"swidinjo@gmail.com"
] | swidinjo@gmail.com |
dce853b87afa2ab0390ada9372acc5593895c880 | bf437a984f4176f99ff1a8c6a7f60a64259b2415 | /src/inet/physicallayer/idealradio/IdealReception.cc | d0663e92a1434a61b9c93d824251ba38163cb0ba | [] | no_license | kvetak/ANSA | b8bcd25c9c04a09d5764177e7929f6d2de304e57 | fa0f011b248eacf25f97987172d99b39663e44ce | refs/heads/ansainet-3.3.0 | 2021-04-09T16:36:26.173317 | 2017-02-16T12:43:17 | 2017-02-16T12:43:17 | 3,823,817 | 10 | 16 | null | 2017-02-16T12:43:17 | 2012-03-25T11:25:51 | C++ | UTF-8 | C++ | false | false | 1,855 | cc | //
// Copyright (C) 2013 OpenSim Ltd.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//
#include "inet/physicallayer/idealradio/IdealReception.h"
namespace inet {
namespace physicallayer {
Register_Enum(inet::physicallayer::IdealReception::Power,
(IdealReception::POWER_UNDETECTABLE,
IdealReception::POWER_DETECTABLE,
IdealReception::POWER_INTERFERING,
IdealReception::POWER_RECEIVABLE));
IdealReception::IdealReception(const IRadio *radio, const ITransmission *transmission, const simtime_t startTime, const simtime_t endTime, const Coord startPosition, const Coord endPosition, const EulerAngles startOrientation, const EulerAngles endOrientation, const Power power) :
ReceptionBase(radio, transmission, startTime, endTime, startPosition, endPosition, startOrientation, endOrientation),
power(power)
{
}
std::ostream& IdealReception::printToStream(std::ostream& stream, int level) const
{
stream << "IdealReception";
if (level >= PRINT_LEVEL_INFO)
stream << ", power = " << cEnum::get(opp_typename(typeid(IdealReception::Power)))->getStringFor(power) + 6;
return ReceptionBase::printToStream(stream, level);
}
} // namespace physicallayer
} // namespace inet
| [
"ivesely@fit.vutbr.cz"
] | ivesely@fit.vutbr.cz |
4b0d55cea598685f2fa4680e8cde8b862419824b | a272e5059a6c29236ed8b6e14abcd151f468775a | /PAN SYSTEM/Insert.cpp | f156890e3bf20059d64c1d510de4a55603b60faa | [] | no_license | RAJAGOPAL10/file-structure | 288ef7cb1aa4047a3b6acea0c0459256d1178ab0 | f04eb1cbeca6637950c71499130fee58fce5c894 | refs/heads/master | 2020-07-30T07:15:04.256558 | 2019-09-22T11:10:56 | 2019-09-22T11:10:56 | 210,130,223 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,872 | cpp | // Insert.cpp : implementation file
//
#include "pch.h"
#include "mybank.h"
#include "Insert.h"
#include "afxdialogex.h"
#include "Option.h"
#include<string>
#include "Header1.h"
IMPLEMENT_DYNAMIC(Insert, CDialogEx)
Insert::Insert(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_DIALOG2, pParent)
, acno(_T(""))
, name(_T(""))
, address(_T(""))
, balance(_T(""))
{
}
Insert::~Insert()
{
}
void Insert::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, acno);
DDX_Text(pDX, IDC_EDIT2, name);
DDX_Text(pDX, IDC_EDIT3, address);
// DDX_Control(pDX, IDC_EDIT4, balance);
DDX_Text(pDX, IDC_EDIT4, balance);
}
BEGIN_MESSAGE_MAP(Insert, CDialogEx)
ON_EN_CHANGE(IDC_EDIT2, &Insert::OnEnChangeEdit2)
ON_BN_CLICKED(IDC_BUTTON1, &Insert::OnBnClickedButton1)
ON_BN_CLICKED(IDC_BUTTON2, &Insert::OnBnClickedButton2)
END_MESSAGE_MAP()
// Insert message handlers
void Insert::OnEnChangeEdit2()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CDialogEx::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here
}
void Insert::OnBnClickedButton1()
{
UpdateData(TRUE);
std::string values[4];
values[0] = (CT2CA)acno;
values[1] = (CT2CA)name;
values[2] = (CT2CA)address;
values[3] = (CT2CA)balance;
CString c;
std::string res=add(values);
smi();
c = res.c_str();
MessageBeep(1);
MessageBox(c);
Option o;
o.DoModal();
this->OnOK();
// TODO: Add your control notification handler code here
}
void Insert::OnBnClickedButton2()
{
// TODO: Add your control notification handler code here
Option o;
o.DoModal();
this->OnOK();
}
| [
"noreply@github.com"
] | RAJAGOPAL10.noreply@github.com |
f28b221a549d054f233b5e1a7f3262ef90883b97 | 3afc56e97427a81416228e5c51d205aa1ee112d9 | /test/include/foxy/test/helpers/ssl_ctx.cpp | d37ce43be67901e69b9f220ddb33ebae1988dbf8 | [
"BSL-1.0"
] | permissive | launchdarkly/foxy | 98b952dc06c510781dc52bc7f4d8d090525e54ed | 7f4ac0495ad2ed9cd0eca5994743d677ac1d2636 | refs/heads/develop | 2023-05-27T21:24:17.955399 | 2020-12-22T15:44:42 | 2020-12-22T15:44:42 | 635,520,707 | 0 | 0 | BSL-1.0 | 2023-05-18T23:08:51 | 2023-05-02T21:51:56 | null | UTF-8 | C++ | false | false | 6,412 | cpp | //
// Copyright (c) 2018-2019 Christian Mazakas (christian dot mazakas at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/LeonineKing1199/foxy
//
#include <foxy/utility.hpp>
#include <foxy/test/helpers/ssl_ctx.hpp>
#include <boost/asio/buffer.hpp>
namespace ssl = boost::asio::ssl;
namespace asio = boost::asio;
auto
foxy::test::make_server_ssl_ctx() -> boost::asio::ssl::context
{
auto ctx = ssl::context(ssl::context::method::tlsv12_server);
auto const cert = boost::string_view(
"-----BEGIN CERTIFICATE-----\n"
"MIIDWzCCAkMCFEkgH0LSdOVvLn/i+NRjXLmhgXjGMA0GCSqGSIb3DQEBCwUAMHsx\n"
"CzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRMwEQYDVQQHDApTYWNy\n"
"YW1lbnRvMSAwHgYDVQQKDBdDb2RlciBpbiBhIENhdmUgU3R1ZGlvczEgMB4GA1UE\n"
"AwwXQ29kZXIgaW4gYSBDYXZlIFN0dWRpb3MwHhcNMTkwOTE1MjM0MjQzWhcNMjQw\n"
"OTEzMjM0MjQzWjBZMQswCQYDVQQGEwJVUzETMBEGA1UECAwKU29tZS1TdGF0ZTEh\n"
"MB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMRIwEAYDVQQDDAkxMjcu\n"
"MC4wLjEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDhXSGTS78ZuAJN\n"
"ou764hvCOP9yY02sgCcZJ0Ykni8SK/cE0USCe1VEiWgwcedLAJgRvkEhtvinsSFk\n"
"mUGkmaOy+dwg0lgjmuIlhsi3rA2ngprjcLVqPriwNfVBhkKb+cztwjnrNomxq/Ab\n"
"/sX2lDAb6VbfVTNnmMT5QbOljzYf82gWc6pYcm5pixooQBD+W52ehq/jpPMYvoqY\n"
"Vqnz/XKT8NvO3bMhbG2hgKxlocpznog61ih9N39OISbdLDbNXNrkpFfs/ST3I2mK\n"
"5juVyQuBoJftJOHc+xtlPRcJfRMWSigGrXc4Nv61GJgBv+PwqpJpwjHe/bEc2h8D\n"
"JJpZ1tuZAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAJWIJoWb035YgXRrW8Qd0TWy\n"
"n3DmFdN0AEaS7JVrA8zqpGNwZmShvLV4YEEasO/NHXU0qpxuoiKhAAB+e/QEutBP\n"
"o5gopns4T3irRJYb++RDaVbJwpl1VmenSRDkg5wQT6ZoH3l4coxrD8nbF2mOz3jP\n"
"VGuG0JhT80rGuOyHVgRz2ilRMgsBc0svPcIo9oNHFQnDCp4uArBhRp+LEK72nZ3J\n"
"X75SCLwET3fg5QCsfvGQp9cvBqgMWYL9NhXD68xkLlzoWVoGZeM4Pe/QS9A/Eyqu\n"
"m48CeYe3QQpC395iTjgn0eW6Y/Qaicu7znwIfaVPS+049Lp/HdKL4jFjiv2Kt/A=\n"
"-----END CERTIFICATE-----\n");
auto const key = boost::string_view(
"-----BEGIN RSA PRIVATE KEY-----\n"
"MIIEpQIBAAKCAQEA4V0hk0u/GbgCTaLu+uIbwjj/cmNNrIAnGSdGJJ4vEiv3BNFE\n"
"gntVRIloMHHnSwCYEb5BIbb4p7EhZJlBpJmjsvncINJYI5riJYbIt6wNp4Ka43C1\n"
"aj64sDX1QYZCm/nM7cI56zaJsavwG/7F9pQwG+lW31UzZ5jE+UGzpY82H/NoFnOq\n"
"WHJuaYsaKEAQ/ludnoav46TzGL6KmFap8/1yk/Dbzt2zIWxtoYCsZaHKc56IOtYo\n"
"fTd/TiEm3Sw2zVza5KRX7P0k9yNpiuY7lckLgaCX7STh3PsbZT0XCX0TFkooBq13\n"
"ODb+tRiYAb/j8KqSacIx3v2xHNofAySaWdbbmQIDAQABAoIBAQDJ7AgJUfUHtjda\n"
"GILHh5AXlbpLY25VAP4HK4lNhe3m+j15s4cO4jKkFfmkbmouaXnXbAAvlSF2Ht8s\n"
"o6SNNpvV4Mm7HryaKkw2E24EI8SYMg1Ve8cQSuJv/+ifrQxBdLCI113Nwi/dYZDh\n"
"hIUbSetRFuEfedd1GwxhyNyNmqOEO4R6dnt1rTmFhtXqHaUWbrCuTp5t3JrnQQO+\n"
"jPgLd35G9A1hjXQ0CFUzkd1JuVJdx/U6nN4JKWc2qimQ8t1YpPQ0v8I6Q2DrPmIe\n"
"pY7bh7wheZ2JwsJ0spgtTfUwCP3LZfQ/UW5BdjHtxnwlyuoHWLB8dgD8XfJHvwd4\n"
"+p1HN7YBAoGBAPiIMOUk3rU2hOklLU3TvpD4/GtzhO08KR9T4XrPG4lMJ2/fx4OG\n"
"XqYFWA1hkY7f1Lc9L1LxeOUAfNEagC7K9nz8ESVa8ink4X2F1IwIyDAU19aTvYK4\n"
"9e4LrM9C9td6BQF0r3jemmN1qjV1naRWj4z8MlW3O2hBRo9RijOVMrQ1AoGBAOgi\n"
"uI9v8mJXtrDeTAjVbSqnfw0Ra3WXi1ONfOXvPjldnCHCmwsv7PRpET/jvPZrWvaB\n"
"96RpiEMcClDCaJX62zhEtCk/2Or2xvSureCnRavzmFmKF2Ehjom0ova6rImlmdWh\n"
"u2NpfxXb/nR9mBClrElG47diW4qucHpiNo4aEa5VAoGAdAjx+yoZqLWJnGi1HC8O\n"
"PBVjlK9ckn6SHIRHM9VaX+HkT8FFH00vB4hbMfQpx3ENmXfBjpIbBaASpnYe/rnY\n"
"F0aAotYxVgn8lWRUdgTrojc5Bn/37P56I+fjiOkU4kmf6KwX+PDFWEZpb4g4T6/y\n"
"WbqtrYNdAzHmxacmRSsVfzkCgYEA3cAVSEhrZdBen9SrE6E1+JIqx0QFwD51BOrb\n"
"Dhed/FTVClcJnwU4OT6JENwvrcJeEa+T7oY1ec42eHFOUT9i3Pycke8A+2ukIScg\n"
"yMNhxeIcfiRxMwNIU3mwVzt6CL+eFbq69DtaAHq4N3WmpvhsfU9vxsX5pp/+qJpb\n"
"fSGgFEUCgYEA6iyrZxQ5QDIZMqzJYXsB6FW4TnAB5sEUTWzoOfsvs3iRMB/y/yhp\n"
"pG1N/bFkTnAmwU8/Hp9ZozFXMUxb3AHnWMeg6YPhTYvUj5X1NzsCvSR3KX+V/crC\n"
"84+kQvgny42OaKjwmvTbRCqv7/iOZzSqCSwMytcFVx11NO4+FMFSUp4=\n"
"-----END RSA PRIVATE KEY-----\n");
ctx.set_options(ssl::context::default_workarounds | ssl::context::no_sslv2 |
ssl::context::single_dh_use);
ctx.use_certificate_chain(asio::buffer(cert.data(), cert.size()));
ctx.use_private_key(asio::buffer(key.data(), key.size()), ssl::context::file_format::pem);
return ctx;
}
auto
foxy::test::make_client_ssl_ctx() -> boost::asio::ssl::context
{
auto ctx = ssl::context(ssl::context::method::tlsv12_client);
foxy::certify::enable_https_verification(ctx);
ctx.set_verify_mode(ssl::context::verify_peer | ssl::context::verify_fail_if_no_peer_cert);
ctx.load_verify_file("root-cas.pem");
// This is our root CA that was used to sign the server's certificate
//
auto const root_ca = boost::string_view(
"-----BEGIN CERTIFICATE-----\n"
"MIID1zCCAr+gAwIBAgIUBzm5/pOjqdVMVfoTQgGf8RxiuAkwDQYJKoZIhvcNAQEL\n"
"BQAwezELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExEzARBgNVBAcM\n"
"ClNhY3JhbWVudG8xIDAeBgNVBAoMF0NvZGVyIGluIGEgQ2F2ZSBTdHVkaW9zMSAw\n"
"HgYDVQQDDBdDb2RlciBpbiBhIENhdmUgU3R1ZGlvczAeFw0xOTA5MTUyMzI4MDha\n"
"Fw0yNDA5MTMyMzI4MDhaMHsxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9y\n"
"bmlhMRMwEQYDVQQHDApTYWNyYW1lbnRvMSAwHgYDVQQKDBdDb2RlciBpbiBhIENh\n"
"dmUgU3R1ZGlvczEgMB4GA1UEAwwXQ29kZXIgaW4gYSBDYXZlIFN0dWRpb3MwggEi\n"
"MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDDBUCUPopmLtS8Zpd9zMz0+9Br\n"
"iP4DqRfciqe9ltRBJGvFVaXpyDjknQPcl+cfKiw/4DKRDUnb6EmGk3v8PcVtPIF7\n"
"ko59URmMelgxdhQSW6oraUGp0xE9UVsRVJYNpnnqAg0rUwwTKAKJx+7aAx75eWEn\n"
"seWFZK7plZwGFDkvEvAgKsXDSZGjTqgcsbpWaJQ1o3XRhNcIfakhe6pA4hVlIBqM\n"
"NgeDqCwLgvnRwqNtfFPNCcjizIngX7Jc48MhtgcGKKYo1ddUwE9lj32kB5rpk5wt\n"
"a6fPkvWYDFu2gWDgtxxEO0bJJkFxPRbppNHxQp00h8ojk+QFDePCd9EAGGPDAgMB\n"
"AAGjUzBRMB0GA1UdDgQWBBQIo4VHujILmom1rPijIu1U8ndLZDAfBgNVHSMEGDAW\n"
"gBQIo4VHujILmom1rPijIu1U8ndLZDAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3\n"
"DQEBCwUAA4IBAQBcnGgLMMRhLq0WuoedkxG/G6zuStoDiuGtKzg0TYvdgegOjpHl\n"
"PsCQmCEUcPMFoo+ohqlZMwoLTZNv02JpRaiBGbOFFNvLQM/cyQ5neGb+o5zmoJAW\n"
"jG5gzY1mQB3KGq+tP/IBvvdGkq7aqC3Qmnvqr5+3qO6sFzQlXGuH6Qwai8mZJhLB\n"
"zV6lehqLWuFiWfmAe08V9jDSaMR4mQEYPdi4vkxu8L1/yI12tptdkYoTleQ+qJiy\n"
"CGwuI6o0hcJWpOEJBkut35FagHqjL54ORLUYQ13kRIaHQkSQ8UgAEa/TbhGDqqjU\n"
"bPbxZffpGVFTPP02ILYH3/cS6hN1vjltNk/4\n"
"-----END CERTIFICATE-----\n");
ctx.add_certificate_authority(asio::const_buffer(root_ca.data(), root_ca.size()));
return ctx;
}
| [
"noreply@github.com"
] | launchdarkly.noreply@github.com |
6a73b99bf397ca45cd79a700a3322a9f33743512 | 2c004b31679a90fc71121ad3a3215abdd486e19e | /Segundo Parcial/Tarea4/Ejercicio2/Ejercicio2/DispositivoToken.h | a38958957e8a53d4b935a00a57a34c51aa113668 | [] | no_license | colina118/Estructura | ae51c0e2ec104c102d0abf22f5c633c8942dc663 | b74eaf42775a6d3aa1ee591f87df60cdaa4f834f | refs/heads/master | 2021-01-01T18:07:51.265565 | 2015-05-12T19:28:08 | 2015-05-12T19:28:08 | 29,313,291 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 467 | h | #include <iostream>
#include <string>
namespace mike{
class DispositivoToken
{
std::string ip;
std::string modelo;
int numero;
public:
DispositivoToken();
DispositivoToken(std::string _ip, std::string _modelo, int _numero)
: ip(_ip), modelo(_modelo), numero(_numero)
{}
friend std::ostream & operator <<(std::ostream & os, DispositivoToken &);
bool operator != (DispositivoToken & dispo);
bool operator == (DispositivoToken & dispo);
};
} | [
"mikehill2010@gmail.com"
] | mikehill2010@gmail.com |
db30d76108c9bf11d8bdf40e0320df748d0b0ded | a234f3a0a996e922e8bd3da10116777dc1c34866 | /lrm_wrappers/src/zigzag_filter.cpp | e098ba8bae57e7eb212ca6473443279123949c5e | [] | no_license | Aand1/lrm_carina | d3cccbc5f78c37643ccd6e232f5e147d797ccffe | 76de955e3f2349f24436196c8a82d38340028225 | refs/heads/master | 2021-01-20T14:28:51.725555 | 2014-06-17T02:34:05 | 2014-06-17T02:34:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,768 | cpp | /*
* Copyright (C) 2012, Laboratorio de Robotica Movel - ICMC/USP
* Rafael Luiz Klaser <rlklaser@gmail.com>
* http://lrm.icmc.usp.br
*
* Apoio FAPESP: 2012/04555-4
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file zigzag_filter.cpp
* @brief
* @author Rafael Luiz Klaser <rlklaser@gmail.com>
* @date Sep 30, 2013
*
*/
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/point_types.h>
#include <pcl/ros/conversions.h>
#include <pcl_ros/transforms.h>
#include <tf/transform_listener.h>
#include <tf/message_filter.h>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/assign.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <math.h>
using namespace boost::accumulators;
typedef pcl::PointCloud<pcl::PointXYZRGB>::iterator itrtor;
ros::Publisher pc_pub;
ros::Publisher pc_rem_pub;
sensor_msgs::PointCloud2 cloud_out;
void pointcloudCallback(const sensor_msgs::PointCloud2::ConstPtr& msg) {
if (pc_pub.getNumSubscribers() == 0)// && pc_rem_pub.getNumSubscribers())
return;
pcl::PointCloud<pcl::PointXYZRGB> cloud;
pcl::PointCloud<pcl::PointXYZRGB> cloud_out;
pcl::PointCloud<pcl::PointXYZRGB> cloud_rem_out;
sensor_msgs::PointCloud2 msg_out;
pcl::fromROSMsg(*msg, cloud);
double min_x = 99999999;
double max_x = 0;
long qtd = 0;
double x;
double tot = 0;
double mean = 0;
double var = 0;
double stdev = 0;
double centered_x;
itrtor end = cloud.points.end();
for (itrtor itr = cloud.points.begin(); itr != end; ++itr )
{
qtd++;
x = itr->x;
tot += x;
if(x>max_x) max_x = x;
if(x<min_x) min_x = x;
}
tot = tot - (min_x * qtd);
mean = tot / qtd;
tot = 0;
for (itrtor itr = cloud.points.begin(); itr != end; ++itr )
{
x = itr->x;
centered_x = x-min_x;
tot += (centered_x-mean)*(centered_x-mean);
}
var = tot / qtd;
stdev = sqrt(var);
qtd = 0;
for (itrtor itr = cloud.points.begin(); itr != end; ++itr )
{
x = itr->x;
centered_x = x-min_x;
if( centered_x > (mean-stdev) && centered_x < (mean+stdev)) {
cloud_out.points.push_back(*itr);
}
else {
cloud_rem_out.points.push_back(*itr);
qtd++;
}
}
pcl::toROSMsg(cloud_out, msg_out);
msg_out.header = msg->header;
pc_pub.publish(msg_out);
pcl::toROSMsg(cloud_rem_out, msg_out);
msg_out.header = msg->header;
pc_rem_pub.publish(msg_out);
//std::cout << "removed " << qtd << std::endl;
}
int main(int argc, char** argv) {
ros::init(argc, argv, "zigzag_filter_node");
ros::NodeHandle nh;
ros::NodeHandle nh_priv("~");
ros::Subscriber pc_sub = nh.subscribe("points_in", 100, pointcloudCallback);
//ros::Subscriber pc_sub = nh.subscribe("/cloud/points_cluster", 1, pointcloudCallback);
pc_pub = nh.advertise<sensor_msgs::PointCloud2>(nh_priv.getNamespace() + "/points_out", 1);
pc_rem_pub = nh.advertise<sensor_msgs::PointCloud2>(nh_priv.getNamespace() + "/points_out_removed", 1);
ros::spin();
return 0;
}
| [
"rlklaser@icmc.usp.br"
] | rlklaser@icmc.usp.br |
120cf1acc95aa93d5eb40d24fbdce9d5e6f424ef | e48c6ed286669dab8471c653c001c5d91bbf59e0 | /hackerblocks1/ARRAYS-WAVE PRINT ROW WISE.cpp | 2ac9135ce8333a96e456076c184409e9159f74fe | [] | no_license | bdugersuren/Launchpad | 55565e9e039385b4ce2ed39718a7f1c1a9a9e643 | e93f32d200917b10568a2bd8dbc3b73c72bb6ee0 | refs/heads/master | 2023-04-14T17:44:37.766974 | 2021-05-03T15:55:04 | 2021-05-03T15:55:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 974 | cpp | /*
Take as input a two-d array. Wave print it row-wise.
Input Format:
Two integers M(row) and N(column) and further M * N integers(2-d array numbers).
Constraints:
Both M and N are between 1 to 10.
Output Format:
All M * N integers are seperated by commas with 'END' written in the end(as shown in example).
Sample Input:
4 4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
Sample Output:
11, 12, 13, 14, 24, 23, 22, 21, 31, 32, 33, 34, 44, 43, 42, 41, END
*/
#include<iostream>
using namespace std;
int main()
{
int m,n;
cin>>m;
cin>>n;
int a[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>a[i][j];
}
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(i%2==0)
{
cout<<a[i][j]<<", ";
}
else
{
cout<<a[i][n-1-j]<<", ";
}
}
}
cout<<"END";
return 0;
}
| [
"ishaansharma1998@gmail.com"
] | ishaansharma1998@gmail.com |
2d30806b58f75dbfaec762c2b08eb21f0c2b7d64 | d32f3d77c52a1d41fc77272be5a3582856157fa1 | /cpp/DataStructure/HW3/nhay.cpp | 6c93b016f8dca6306a2ea003760bb813579e334e | [] | no_license | gkzhb/code | c4afc019f7f465845b0b0ef40d08f30c1fd247d6 | 73ab7fb0e156a5904b82811df805b66af36b38c0 | refs/heads/master | 2020-03-18T01:48:59.518692 | 2019-06-15T11:48:40 | 2019-06-15T11:48:40 | 134,161,057 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 775 | cpp | // time limit exceeded
#include <iostream>
#include <vector>
#include <string>
#include <cstdio>
using namespace std;
void preprocessing(vector<int> &next, const string &s)
{
int i = 0, j = -1;
next[0] = -1;
while (i < s.size())
if (-1 == j || s[i] == s[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
int kmp(string a)
{
int i = 0, j = 0;
vector<int> next(a.size() + 1, 0);
preprocessing(next, a);
char c;
while ((c = getchar()) == '\n')
;
while (c != '\n')
{
if (-1 == i || a[i] == c)
{
i++;
j++;
c = getchar();
}
else
i = next[i];
if (i == a.size())
{
cout << j - i << endl;
i = next[i];
}
}
return -1;
}
int main(void)
{
string s;
while (cin)
{
cin >> s;
cin >> s;
kmp(s);
}
return 0;
} | [
"zhb896579388@163.com"
] | zhb896579388@163.com |
8d6dca2c2c6ca804acb24a0a222543eae74b62f7 | 500d9a3048560023bd989dbf5d770e0b8abf224d | /BZOJ/3156 防御准备/3156.cpp | 1804b8ebcbd954051ddb229fcfd060ec19e05483 | [] | no_license | hilbertanjou/OJ | 2138bd349607adebd7674861e00dad57a23724bd | 641f412d904edd66e97befdabcc32b7076729a53 | refs/heads/master | 2020-12-30T23:33:13.961562 | 2013-08-23T09:44:49 | 2013-08-23T09:44:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 683 | cpp | #include <cstdio>
typedef long long LL;
const int MAXN = 1111111;
int a[MAXN], q[MAXN];
LL f[MAXN], g[MAXN];
inline LL calc(int i, int j) {
return g[j] - LL(i) * j;
}
int main() {
int n, l = 0, r = 0;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
for (; l < r && calc(i, q[l + 1]) < calc(i, q[l]); ++l);
f[i] = a[i] + (LL(i) * i - i >> 1) + calc(i, q[l]);
g[i] = f[i] + (LL(i) * i + i >> 1);
for (; r && (q[r] - q[r - 1]) * (g[i] - g[q[r]]) - (i - q[r]) * (g[q[r]] - g[q[r - 1]]) <= 0; --r);
q[++r] = i;
if (l > r)
l = r;
}
printf("%lld\n", f[n]);
return 0;
}
| [
"xy_xuyi@foxmail.com"
] | xy_xuyi@foxmail.com |
e6d9fa102768bc492c53e50dbcdffc585a98a150 | 2a594aeb45cf16333d83421ae3c11f9ef39dc8bc | /leecode-II/CloneGraph/源.cpp | 76d4f65f15cb9a2354337565600ce95f6fa75e12 | [
"MIT"
] | permissive | lisnb/leetcode | 9bcd40c9fd8a84ed30e4a91edc7451220ffef676 | 7875e4ff20412b663c59e57f76d08cd62b91481c | refs/heads/master | 2020-06-04T05:32:52.595221 | 2015-08-20T14:39:46 | 2015-08-20T14:39:46 | 22,034,965 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 813 | cpp | #include "../leecode-II/leetcode.h"
#include <algorithm>
#include <deque>
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
typedef _leetcode_undirectedgraphnode<int> UndirectedGraphNode;
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == nullptr)
return nullptr;
if (cache.find(node->label) == cache.end())
{
cache[node->label] = new UndirectedGraphNode(node->label);
for (auto nei : node->neighbors)
{
cache[node->label]->neighbors.push_back(cloneGraph(nei));
}
}
return cache[node->label];
}
private:
unordered_map<int, UndirectedGraphNode *> cache;
}; | [
"lisnb.h@hotmail.com"
] | lisnb.h@hotmail.com |
d15bb44d11df4fbd6311370817a5b49a4e99dcc5 | 8b957ec62991c367dfc6c9247ada90860077b457 | /src/qt/rpcconsole.h | 1c679a1ecac3f667c6f041b2a214d594c75c23db | [
"MIT"
] | permissive | valuero-org/valuero | 113f29046bd63c8b93160604452a99ed51367942 | c0a8d40d377c39792e5a79d4a67f00bc592aef87 | refs/heads/master | 2020-05-24T17:44:46.409378 | 2019-09-09T10:18:59 | 2019-09-09T10:18:59 | 187,392,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,204 | h | // Copyright (c) 2012-2019 The Bitcoin Core developers
// Copyright (c) 2017-2019 The Raven Core developers
// Copyright (c) 2018-2019 The Rito Core developers
// Copyright (c) 2019 The Valuero developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef VAL_QT_RPCCONSOLE_H
#define VAL_QT_RPCCONSOLE_H
#include "guiutil.h"
#include "peertablemodel.h"
#include "net.h"
#include <QWidget>
#include <QCompleter>
#include <QThread>
class ClientModel;
class PlatformStyle;
class RPCTimerInterface;
namespace Ui {
class RPCConsole;
}
QT_BEGIN_NAMESPACE
class QMenu;
class QItemSelection;
QT_END_NAMESPACE
/** Local Valuero RPC console. */
class RPCConsole: public QWidget
{
Q_OBJECT
public:
explicit RPCConsole(const PlatformStyle *platformStyle, QWidget *parent);
~RPCConsole();
static bool RPCParseCommandLine(std::string &strResult, const std::string &strCommand, bool fExecute, std::string * const pstrFilteredOut = nullptr);
static bool RPCExecuteCommandLine(std::string &strResult, const std::string &strCommand, std::string * const pstrFilteredOut = nullptr) {
return RPCParseCommandLine(strResult, strCommand, true, pstrFilteredOut);
}
void setClientModel(ClientModel *model);
enum MessageClass {
MC_ERROR,
MC_DEBUG,
CMD_REQUEST,
CMD_REPLY,
CMD_ERROR
};
enum TabTypes {
TAB_INFO = 0,
TAB_CONSOLE = 1,
TAB_GRAPH = 2,
TAB_PEERS = 3
};
protected:
virtual bool eventFilter(QObject* obj, QEvent *event);
void keyPressEvent(QKeyEvent *);
private Q_SLOTS:
void on_lineEdit_returnPressed();
void on_tabWidget_currentChanged(int index);
/** open the debug.log from the current datadir */
void on_openDebugLogfileButton_clicked();
/** change the time range of the network traffic graph */
void on_sldGraphRange_valueChanged(int value);
/** update traffic statistics */
void updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut);
void resizeEvent(QResizeEvent *event);
void showEvent(QShowEvent *event);
void hideEvent(QHideEvent *event);
/** Show custom context menu on Peers tab */
void showPeersTableContextMenu(const QPoint& point);
/** Show custom context menu on Bans tab */
void showBanTableContextMenu(const QPoint& point);
/** Hides ban table if no bans are present */
void showOrHideBanTableIfRequired();
/** clear the selected node */
void clearSelectedNode();
public Q_SLOTS:
void clear(bool clearHistory = true);
void fontBigger();
void fontSmaller();
void setFontSize(int newSize);
/** Append the message to the message widget */
void message(int category, const QString &message, bool html = false);
/** Set number of connections shown in the UI */
void setNumConnections(int count);
/** Set network state shown in the UI */
void setNetworkActive(bool networkActive);
/** Set number of blocks and last block date shown in the UI */
void setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool headers);
/** Set size (number of transactions and memory usage) of the mempool in the UI */
void setMempoolSize(long numberOfTxs, size_t dynUsage);
/** Go forward or back in history */
void browseHistory(int offset);
/** Scroll console view to end */
void scrollToEnd();
/** Handle selection of peer in peers list */
void peerSelected(const QItemSelection &selected, const QItemSelection &deselected);
/** Handle selection caching before update */
void peerLayoutAboutToChange();
/** Handle updated peer information */
void peerLayoutChanged();
/** Disconnect a selected node on the Peers tab */
void disconnectSelectedNode();
/** Ban a selected node on the Peers tab */
void banSelectedNode(int bantime);
/** Unban a selected node on the Bans tab */
void unbanSelectedNode();
/** set which tab has the focus (is visible) */
void setTabFocus(enum TabTypes tabType);
Q_SIGNALS:
// For RPC command executor
void stopExecutor();
void cmdRequest(const QString &command);
private:
void startExecutor();
void setTrafficGraphRange(int mins);
/** show detailed information on ui about selected node */
void updateNodeDetail(const CNodeCombinedStats *stats);
enum ColumnWidths
{
ADDRESS_COLUMN_WIDTH = 200,
SUBVERSION_COLUMN_WIDTH = 150,
PING_COLUMN_WIDTH = 80,
BANSUBNET_COLUMN_WIDTH = 200,
BANTIME_COLUMN_WIDTH = 250
};
Ui::RPCConsole *ui;
ClientModel *clientModel;
QStringList history;
int historyPtr;
QString cmdBeforeBrowsing;
QList<NodeId> cachedNodeids;
const PlatformStyle *platformStyle;
RPCTimerInterface *rpcTimerInterface;
QMenu *peersTableContextMenu;
QMenu *banTableContextMenu;
int consoleFontSize;
QCompleter *autoCompleter;
QThread thread;
/** Update UI with latest network info from model. */
void updateNetworkState();
};
#endif // VAL_QT_RPCCONSOLE_H
| [
"rishabhworking@gmail.com"
] | rishabhworking@gmail.com |
d46ee2f16c1489e91cd8494117167a6b5d03af23 | 45b242225b117852d0b4f3768ed845614e3e96ed | /src/DGL_SkyBox.h | b4e57dde15aa8d96fa74cd065ddbd707219bad71 | [
"Apache-2.0"
] | permissive | da0x/xr.desktop | d7da667470d3bb75ad59759d0fc7d66a36021f83 | 218a7cff7a9be5865cf786d7cad31da6072f7348 | refs/heads/master | 2021-05-28T02:15:19.583099 | 2014-12-14T20:20:44 | 2014-12-14T20:20:44 | 28,004,479 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,547 | h | //C++
/*
----------------------------------------------------
The Desktop Project
------------------
Copyright 2004 Daher Alfawares
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 ___DSKYBOX_H
#define ___DSKYBOX_H
/*
TODO List:
- ...
*/
namespace DGL {
class SkyBox {
private:
float SkyboxWidth,SkyboxHeight,SkyboxLength;
DGL::Texture top,bottom,left,right,front,back;
public:
void InitSkybox(char *name){
LogPrint(va("SkyBox '%s' Initializations:",name));
DGL::Texture::Filter skyfilter(Texture::Filter::FilterName::TRILINEAR, true);
top .Build(va("textures/skies/%sTop.jpg", name), skyfilter);
bottom .Build(va("textures/skies/%sBottom.jpg", name), skyfilter);
left .Build(va("textures/skies/%sLeft.jpg", name), skyfilter);
right .Build(va("textures/skies/%sRight.jpg", name), skyfilter);
front .Build(va("textures/skies/%sFront.jpg", name), skyfilter);
back .Build(va("textures/skies/%sBack.jpg", name), skyfilter);
SkyboxWidth = 12.0f;
SkyboxLength = 12.0f;
SkyboxHeight = 8.0f;
}
void Render(){
DMacro_TraceEnter(SkyBox::Render);
float x,y,z;
glPushAttrib(GL_ENABLE_BIT|GL_LIGHTING_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
x = - this->SkyboxWidth / 2.0f;
y = - this->SkyboxHeight / 2.0f;
z = - this->SkyboxLength / 2.0f;
Color::ColorWhite().MakeCurrent();
glPushMatrix();
float m[4][4];
glGetFloatv(GL_MODELVIEW_MATRIX, (float *)m);
m[3][0] = m[3][1] = m[3][2] = 0.0f;
glLoadMatrixf( (float *)m);
glBindTexture( GL_TEXTURE_2D, this->back);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, this->front);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z + SkyboxLength);
glEnd();
glBindTexture( GL_TEXTURE_2D, this->top);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, this->bottom);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y, z + SkyboxLength);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, this->left);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, this->right);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glEnd();
glPopAttrib();
glPopMatrix();
DMacro_TraceLeave();
}
void Destroy()
{
this->top.Delete();
this->bottom.Delete();
this->left.Delete();
this->right.Delete();
this->front.Delete();
this->back.Delete();
}
};
class SkyBox_HalfDom {
protected:
float SkyboxWidth,SkyboxHeight,SkyboxLength;
DGL::Texture top,left,right,front,back;
public:
void InitSkybox(char *name){
LogPrint(va("SkyBox '%s' Initializations:",name));
DGL::Texture::Filter skyfilter(Texture::Filter::FilterName::TRILINEAR, true);
top .Build(va("textures/skies/%sTop.jpg", name), skyfilter);
left .Build(va("textures/skies/%sLeft.jpg", name), skyfilter);
right .Build(va("textures/skies/%sRight.jpg", name), skyfilter);
front .Build(va("textures/skies/%sFront.jpg", name), skyfilter);
back .Build(va("textures/skies/%sBack.jpg", name), skyfilter);
SkyboxWidth = 12.0f;
SkyboxLength = 12.0f;
SkyboxHeight = 6.0f;
}
void Render(){
DMacro_TraceEnter(SkyBox_HalfDom::Render);
float x,y,z;
glPushAttrib(GL_ENABLE_BIT|GL_LIGHTING_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
x = - SkyboxWidth / 2.0f;
y = 0.0f;
z = - SkyboxLength / 2.0f;
Color::ColorWhite().MakeCurrent();
glPushMatrix();
float m[4][4];
glGetFloatv(GL_MODELVIEW_MATRIX, (float *)m);
m[3][0] = m[3][1] = m[3][2] = 0.0f;
glLoadMatrixf( (float *)m);
glBindTexture( GL_TEXTURE_2D, back);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, front);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z + SkyboxLength);
glEnd();
glBindTexture( GL_TEXTURE_2D, top);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, left);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, right);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glEnd();
glPopAttrib();
glPopMatrix();
DMacro_TraceLeave();
}
void Destroy()
{
this->top.Delete();
this->left.Delete();
this->right.Delete();
this->front.Delete();
this->back.Delete();
}
};
////////////////////////////////
// static skybox
class SkyBox_static {
protected:
float SkyboxWidth,SkyboxHeight,SkyboxLength;
DGL::Texture top,left,right,front,back;
public:
void InitSkybox(char *name, float width, float length, float height){
LogPrint(va("SkyBox '%s' Initializations:",name));
DGL::Texture::Filter skyfilter(Texture::Filter::FilterName::TRILINEAR, true);
top .Build(va("textures/skies/%sTop.jpg", name), skyfilter);
left .Build(va("textures/skies/%sLeft.jpg", name), skyfilter);
right .Build(va("textures/skies/%sRight.jpg", name), skyfilter);
front .Build(va("textures/skies/%sFront.jpg", name), skyfilter);
back .Build(va("textures/skies/%sBack.jpg", name), skyfilter);
SkyboxWidth = width;
SkyboxLength = length;
SkyboxHeight = height;
}
void Render(){
DMacro_TraceEnter(SkyBox_static::Render);
float x,y,z;
glPushAttrib(GL_ENABLE_BIT|GL_LIGHTING_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
// glDisable(GL_DEPTH_TEST);
x = - SkyboxWidth / 2.0f;
y = 0.0f;
z = - SkyboxLength / 2.0f;
Color::ColorWhite().MakeCurrent();
glBindTexture( GL_TEXTURE_2D, back);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, front);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z + SkyboxLength);
glEnd();
glBindTexture( GL_TEXTURE_2D, top);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, left);
glBegin(GL_QUADS);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x, y + SkyboxHeight, z);
glEnd();
glBindTexture( GL_TEXTURE_2D, right);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x + SkyboxWidth, y, z + SkyboxLength);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z + SkyboxLength);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x + SkyboxWidth, y + SkyboxHeight, z);
glEnd();
glPopAttrib();
glPopMatrix();
DMacro_TraceLeave();
}
void Destroy()
{
this->top.Delete();
this->left.Delete();
this->right.Delete();
this->front.Delete();
this->back.Delete();
}
};
}//namespace DGL
#endif // ___DSKYBOX_H | [
"daher.alfawares@live.com"
] | daher.alfawares@live.com |
1f4cf9c5d1be3dfded878eb7a5ed612632a3cbae | 81579ab7a84235148dba4ad5d25e9c6c87add87d | /Chapter2/Lab-2.4.23(2)/Lab-2.4.23(2)/stdafx.cpp | d7e1ce6a6b0d246b0ec2a91dc960b099962b3dc1 | [] | no_license | kostya911/C-Ess-KI3 | 56a649bfb735e87bdfb27f6e5d24dbb291acecb0 | 441815ebd33fba28b6e3d29fc1008b011dca7e7c | refs/heads/master | 2021-05-08T02:59:42.050196 | 2017-12-19T22:11:31 | 2017-12-19T22:11:31 | 108,099,734 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Lab-2.4.23(2).pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"noreply@github.com"
] | kostya911.noreply@github.com |
9bb476606913caccb4028aa3f7d29dbe6130f0fb | 5fbfe741e7823f7eafd819177d6ad075bd9598d9 | /SpaceShipGame/SimpleSfmlEngine/dataTypes/clock.hpp | 5028d0a2a409ed6aa776a3b50be502628f4bdb1c | [] | no_license | OfficialLahusa/SpaceShip | 062a81b69b55199906296d7f5724eb42e688864a | 991a50478cae564015d1424a196cf6c1676e501a | refs/heads/master | 2021-06-27T03:01:22.018966 | 2020-11-17T13:51:29 | 2020-11-17T13:51:29 | 166,654,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 704 | hpp | #pragma once
#include <chrono>
namespace sse
{
class clock
{
public:
clock()
:m_start(std::chrono::steady_clock::now())
{
}
template<typename T>
T restart()
{
const std::chrono::steady_clock::time_point old = m_start;
m_start = std::chrono::steady_clock::now();
const std::chrono::duration<T> elapsedTime = m_start - old;
return elapsedTime.count();
}
void restart()
{
m_start = std::chrono::steady_clock::now();
}
template<typename T>
T getElapsedTime()
{
const std::chrono::duration<T> elapsedTime = std::chrono::steady_clock::now() - m_start;
return elapsedTime.count();
}
private:
std::chrono::steady_clock::time_point m_start;
};
} | [
"lassehuber@outlook.de"
] | lassehuber@outlook.de |
17d798aed4c5b79e3d1fb37e5c4ab7908408f032 | f4a2658af992523f8cda62eb3d17c4424f6f8432 | /C++/1006.cpp | 325c95c446e95eb5649d4734353fe21bde1d624e | [] | no_license | vmf91/uri-solutions | 520442d9def5e5aca8542df5807d4a844b6a9ce6 | b0db3377fe09cf96b069bb3ff5e98e0333cf6c29 | refs/heads/master | 2020-12-10T22:32:47.959572 | 2020-06-11T03:47:00 | 2020-06-11T03:47:00 | 233,731,059 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 244 | cpp | #include <iostream>
#include <iomanip>
using namespace std;
int main() {
double a, b, c;
cin >> a;
cin >> b;
cin >> c;
cout << fixed << setprecision(1);
cout << "MEDIA = " << (a * 2 + b * 3 + c * 5)/(2 + 3 + 5) << endl;
return 0;
} | [
"vmf91@hotmail.com"
] | vmf91@hotmail.com |
64dc35fe593ddd5564730b71e5558c02627b45af | e8dd43ab1d079b921e8b5d246fec7c8afbe12b1e | /animecheat.pw - Copy/b1g pasta/sdk/interfaces/CInput.hpp | a307a8869f548ea0b3fa1685e5b459b2c0f351ea | [] | no_license | hvhgodsmile/some-bs-no-one-works-on | 3031940ab9ec5f2ef806ae10679bb13e2c0dea43 | 8134a772aba3653604da5b16864a9af6299821d3 | refs/heads/master | 2020-05-03T00:16:13.056717 | 2019-03-29T03:09:15 | 2019-03-29T03:09:15 | 178,305,079 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,048 | hpp | #pragma once
#include "../misc/CUserCmd.hpp"
#define MULTIPLAYER_BACKUP 150
class bf_write;
class bf_read;
class CInput
{
public:
virtual void Init_All(void);
virtual void Shutdown_All(void);
virtual int GetButtonBits(int);
virtual void CreateMove(int sequence_number, float input_sample_frametime, bool active);
virtual void ExtraMouseSample(float frametime, bool active);
virtual bool WriteUsercmdDeltaToBuffer(bf_write *buf, int from, int to, bool isnewcommand);
virtual void EncodeUserCmdToBuffer(bf_write& buf, int slot);
virtual void DecodeUserCmdFromBuffer(bf_read& buf, int slot);
inline CUserCmd* GetUserCmd(int sequence_number);
inline CVerifiedUserCmd* GetVerifiedCmd(int sequence_number);
bool m_fTrackIRAvailable;
bool m_fMouseInitialized;
bool m_fMouseActive;
bool m_fJoystickAdvancedInit;
char pad_0x08[0x2C];
char pad_0x00[0x0C];
void* m_pKeys;
char pad_0x38[0x64];
int pad_0x41;
int pad_0x42;
bool m_fCameraInterceptingMouse;
bool m_fCameraInThirdPerson;
bool m_fCameraMovingWithMouse;
Vector m_vecCameraOffset;
bool m_fCameraDistanceMove;
int m_nCameraOldX;
int m_nCameraOldY;
int m_nCameraX;
int m_nCameraY;
bool m_CameraIsOrthographic;
Vector m_angPreviousViewAngles;
Vector m_angPreviousViewAnglesTilt;
float m_flLastForwardMove;
int m_nClearInputState;
char pad_0xE4[0x8];
CUserCmd* m_pCommands;
CVerifiedUserCmd* m_pVerifiedCommands;
};
CUserCmd* CInput::GetUserCmd(int sequence_number)
{
return &m_pCommands[sequence_number % MULTIPLAYER_BACKUP];
}
CVerifiedUserCmd* CInput::GetVerifiedCmd(int sequence_number)
{
return &m_pVerifiedCommands[sequence_number % MULTIPLAYER_BACKUP];
} | [
"49047029+hvhgodsmile@users.noreply.github.com"
] | 49047029+hvhgodsmile@users.noreply.github.com |
aa87d20e9e53b2726acab79fc34392e4faa16afd | 0128e628cce2b62c6d93d7dc495a9b490be68b2e | /Screen.cpp | 9713b76137e6714c613c6a7fd20fdc9a0d7d550c | [] | no_license | Muhsal-droid/Hangman-game-Code | 0e8ee449d66ca83e1c00629f2c1f78ba2e17d110 | a611b22e6c16cc36f1d96244cec28ffd2aaab9fb | refs/heads/main | 2023-04-24T04:49:13.208158 | 2021-05-12T03:14:02 | 2021-05-12T03:14:02 | 366,578,217 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,768 | cpp | #include <iostream>
#include <vector>
#include <stdlib.h>
#include "Screen.h"
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using namespace std;
// Member Functions()
void Screen :: printScreen()
{
if (mode == 1)
{
cout << "_______________________________________ \n";
cout <<"| ___________________________________ /|\n";
cout <<"|***********************************| |\n";
cout <<"| _ | |\n";
cout <<"|~ _--/ ---- ~ | |\n";
cout << "| / / --- | |\n";
cout <<" | / | | - | |\n";
cout <<" | / | WELCOME | - | |\n";
cout <<" | | | _______ | | | |\n";
cout <<" | | | - - | | | |\n";
cout <<" | now hi | | _/ / | |\n";
cout <<" | bye -__| |__- / | |\n";
cout <<" | hello _/ | |\n";
cout <<" | --__ __-- | |\n";
cout <<" | --| |-- | |\n";
cout <<" | | | | |\n";
cout <<" | | |\n";
cout <<" | | | |\n";
cout <<" | | |\n";
cout <<" | READY FOR HANGMAN ? | |\n";
cout <<" |_ _ | |\n";
cout <<" | | |\n";
cout <<" |~ ********(Has 3 LEVELS)*******~ | |\n";
cout <<"| ----------------------------------- \n";
cout <<" ---------------------------------------\n";
}else if (mode == 2)
{
cout << "_______________________________________ \n";
cout <<"| ___________________________________ /|\n";
cout <<"|***********************************| |\n";
cout <<"| _ | |\n";
cout <<"|~ _--/ ---- ~ | |\n";
cout << "| / / --- | |\n";
cout <<" | / | | - | |\n";
cout <<" | / | Game has Ended| - | |\n";
cout <<" | | | _______ | | | |\n";
cout <<" | | | - - | | | |\n";
cout <<" | now hi | | _/ / | |\n";
cout <<" | bye -__| |__- / | |\n";
cout <<" | hello _/ | |\n";
cout <<" | --__ __-- | |\n";
cout <<" | --| |-- | |\n";
cout <<" | | | | |\n";
cout <<" | | |\n";
cout <<" | | | |\n";
cout <<" | | |\n";
cout <<" | SEE YOU LATER !!!!!!!! | |\n";
cout <<" |_ _ | |\n";
cout <<" | | |\n";
cout <<" |~*************( BYE )*******~**** | |\n";
cout <<"| ----------------------------------- \n";
cout <<" ---------------------------------------\n";
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | [
"noreply@github.com"
] | Muhsal-droid.noreply@github.com |
ca8789855bcf56d446ac2e9ee577703c34959e3e | 06cbc74aac6be71a48d4b800178583f5eaa8f3e0 | /Lab1/APPOO_1.2/APPOO_1.2/Phone.hpp | 1da59e48e249245eda4e2a71b548a0da52127340 | [] | no_license | MihaiCapra/APPOO | 0a761d56a5c1153a331a7b611df7f346ccc48d16 | 0632b9b01d1bd65c5409a5aa78aee2d28ba6a877 | refs/heads/master | 2021-01-18T23:34:49.969857 | 2017-05-23T05:29:17 | 2017-05-23T05:29:17 | 87,119,670 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | hpp | #pragma once
class Phone
{
public:
Phone(): brand(""), model(""),color(""),price(0){}
~Phone() {}
friend std::istream&operator >> (std::istream &in, Phone &obj);
friend std::ostream&operator <<(std::ostream &out, Phone &obj);
std::string getBrand();
std::string getModel();
std::string getColor();
double getPrice();
private:
std::string brand,model,color;
double price;
}; | [
"mihai.capra27@gmail.com"
] | mihai.capra27@gmail.com |
38304845978031d8922d01d9a976f638a2d801a6 | fbe68d84e97262d6d26dd65c704a7b50af2b3943 | /third_party/virtualbox/src/VBox/Additions/os2/VBoxSF/VBoxSFFile.cpp | 4c9873e8023d6af000cf87aceea813931a399d3e | [
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference",
"CDDL-1.0",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"GPL-2.0-or-later",
"MPL-1.0",
"LicenseRef-scancode-generic-exception",
"Apache-2.0",
"OpenSSL"
] | permissive | thalium/icebox | c4e6573f2b4f0973b6c7bb0bf068fe9e795fdcfb | 6f78952d58da52ea4f0e55b2ab297f28e80c1160 | refs/heads/master | 2022-08-14T00:19:36.984579 | 2022-02-22T13:10:31 | 2022-02-22T13:10:31 | 190,019,914 | 585 | 109 | MIT | 2022-01-13T20:58:15 | 2019-06-03T14:18:12 | C++ | UTF-8 | C++ | false | false | 7,418 | cpp | /** $Id: VBoxSFFile.cpp $ */
/** @file
* VBoxSF - OS/2 Shared Folders, the file level IFS EPs.
*/
/*
* Copyright (c) 2007 knut st. osmundsen <bird-src-spam@anduin.net>
*
* 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.
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_DEFAULT
#include "VBoxSFInternal.h"
#include <VBox/log.h>
#include <iprt/assert.h>
DECLASM(int)
FS32_OPENCREATE(PCDFSI pcdfsi, PVBOXSFCD pcdfsd, PCSZ pszName, USHORT iCurDirEnd,
PSFFSI psffsi, PVBOXSFFSD psffsd, ULONG uOpenMode, USHORT fOpenFlag,
PUSHORT puAction, USHORT fAttr, PBYTE pbEABuf, PUSHORT pfGenFlag)
{
NOREF(pcdfsi); NOREF(pcdfsd); NOREF(pszName); NOREF(iCurDirEnd); NOREF(psffsi); NOREF(psffsd); NOREF(uOpenMode);
NOREF(fOpenFlag); NOREF(puAction); NOREF(fAttr); NOREF(pbEABuf); NOREF(pfGenFlag);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_CLOSE(ULONG uType, ULONG fIoFlags, PSFFSI psffsi, PVBOXSFFSD psffsd)
{
NOREF(uType); NOREF(fIoFlags); NOREF(psffsi); NOREF(psffsd);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_COMMIT(ULONG uType, ULONG fIoFlags, PSFFSI psffsi, PVBOXSFFSD psffsd)
{
NOREF(uType); NOREF(fIoFlags); NOREF(psffsi); NOREF(psffsd);
return ERROR_NOT_SUPPORTED;
}
extern "C" APIRET APIENTRY
FS32_CHGFILEPTRL(PSFFSI psffsi, PVBOXSFFSD psffsd, LONGLONG off, ULONG uMethod, ULONG fIoFlags)
{
NOREF(psffsi); NOREF(psffsd); NOREF(off); NOREF(uMethod); NOREF(fIoFlags);
return ERROR_NOT_SUPPORTED;
}
/** Forwards the call to FS32_CHGFILEPTRL. */
extern "C" APIRET APIENTRY
FS32_CHGFILEPTR(PSFFSI psffsi, PVBOXSFFSD psffsd, LONG off, ULONG uMethod, ULONG fIoFlags)
{
return FS32_CHGFILEPTRL(psffsi, psffsd, off, uMethod, fIoFlags);
}
DECLASM(int)
FS32_FILEINFO(ULONG fFlag, PSFFSI psffsi, PVBOXSFFSD psffsd, ULONG uLevel,
PBYTE pbData, ULONG cbData, ULONG fIoFlags)
{
NOREF(fFlag); NOREF(psffsi); NOREF(psffsd); NOREF(uLevel); NOREF(pbData); NOREF(cbData); NOREF(fIoFlags);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_NEWSIZEL(PSFFSI psffsi, PVBOXSFFSD psffsd, LONGLONG cbFile, ULONG fIoFlags)
{
NOREF(psffsi); NOREF(psffsd); NOREF(cbFile); NOREF(fIoFlags);
return ERROR_NOT_SUPPORTED;
}
extern "C" APIRET APIENTRY
FS32_READ(PSFFSI psffsi, PVBOXSFFSD psffsd, PVOID pvData, PULONG pcb, ULONG fIoFlags)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pvData); NOREF(pcb); NOREF(fIoFlags);
return ERROR_NOT_SUPPORTED;
}
extern "C" APIRET APIENTRY
FS32_WRITE(PSFFSI psffsi, PVBOXSFFSD psffsd, PVOID pvData, PULONG pcb, ULONG fIoFlags)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pvData); NOREF(pcb); NOREF(fIoFlags);
return ERROR_NOT_SUPPORTED;
}
extern "C" APIRET APIENTRY
FS32_READFILEATCACHE(PSFFSI psffsi, PVBOXSFFSD psffsd, ULONG fIoFlags, LONGLONG off, ULONG pcb, KernCacheList_t **ppCacheList)
{
NOREF(psffsi); NOREF(psffsd); NOREF(fIoFlags); NOREF(off); NOREF(pcb); NOREF(ppCacheList);
return ERROR_NOT_SUPPORTED;
}
extern "C" APIRET APIENTRY
FS32_RETURNFILECACHE(KernCacheList_t *pCacheList)
{
NOREF(pCacheList);
return ERROR_NOT_SUPPORTED;
}
/* oddments */
DECLASM(int)
FS32_CANCELLOCKREQUESTL(PSFFSI psffsi, PVBOXSFFSD psffsd, struct filelockl *pLockRange)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pLockRange);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_CANCELLOCKREQUEST(PSFFSI psffsi, PVBOXSFFSD psffsd, struct filelock *pLockRange)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pLockRange);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_FILELOCKSL(PSFFSI psffsi, PVBOXSFFSD psffsd, struct filelockl *pUnLockRange,
struct filelockl *pLockRange, ULONG cMsTimeout, ULONG fFlags)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pUnLockRange); NOREF(pLockRange); NOREF(cMsTimeout); NOREF(fFlags);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_FILELOCKS(PSFFSI psffsi, PVBOXSFFSD psffsd, struct filelock *pUnLockRange,
struct filelock *pLockRange, ULONG cMsTimeout, ULONG fFlags)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pUnLockRange); NOREF(pLockRange); NOREF(cMsTimeout); NOREF(fFlags);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_IOCTL(PSFFSI psffsi, PVBOXSFFSD psffsd, USHORT uCategory, USHORT uFunction,
PVOID pvParm, USHORT cbParm, PUSHORT pcbParmIO,
PVOID pvData, USHORT cbData, PUSHORT pcbDataIO)
{
NOREF(psffsi); NOREF(psffsd); NOREF(uCategory); NOREF(uFunction); NOREF(pvParm); NOREF(cbParm); NOREF(pcbParmIO);
NOREF(pvData); NOREF(cbData); NOREF(pcbDataIO);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_FILEIO(PSFFSI psffsi, PVBOXSFFSD psffsd, PBYTE pbCmdList, USHORT cbCmdList,
PUSHORT poffError, USHORT fIoFlag)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pbCmdList); NOREF(cbCmdList); NOREF(poffError); NOREF(fIoFlag);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_NMPIPE(PSFFSI psffsi, PVBOXSFFSD psffsd, USHORT uOpType, union npoper *pOpRec,
PBYTE pbData, PCSZ pszName)
{
NOREF(psffsi); NOREF(psffsd); NOREF(uOpType); NOREF(pOpRec); NOREF(pbData); NOREF(pszName);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_OPENPAGEFILE(PULONG pfFlags, PULONG pcMaxReq, PCSZ pszName, PSFFSI psffsi, PVBOXSFFSD psffsd,
USHORT uOpenMode, USHORT fOpenFlags, USHORT fAttr, ULONG uReserved)
{
NOREF(pfFlags); NOREF(pcMaxReq); NOREF(pszName); NOREF(psffsi); NOREF(psffsd); NOREF(uOpenMode); NOREF(fOpenFlags);
NOREF(fAttr); NOREF(uReserved);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_SETSWAP(PSFFSI psffsi, PVBOXSFFSD psffsd)
{
NOREF(psffsi); NOREF(psffsd);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_ALLOCATEPAGESPACE(PSFFSI psffsi, PVBOXSFFSD psffsd, ULONG cb, USHORT cbWantContig)
{
NOREF(psffsi); NOREF(psffsd); NOREF(cb); NOREF(cbWantContig);
return ERROR_NOT_SUPPORTED;
}
DECLASM(int)
FS32_DOPAGEIO(PSFFSI psffsi, PVBOXSFFSD psffsd, struct PageCmdHeader *pList)
{
NOREF(psffsi); NOREF(psffsd); NOREF(pList);
return ERROR_NOT_SUPPORTED;
}
| [
"benoit.amiaux@gmail.com"
] | benoit.amiaux@gmail.com |
03ebd084bae37915607d1340ba47b82377a64121 | 1de1a8934bb0e4413c54f475a6e68bf2313f131a | /Histo 2 neshta/main.cpp | 28456178d3ac9f153e670ffdb6d77ced1901da26 | [] | no_license | todorov9898/grafika | d369575eb88d162c3ecfd4764af9d62d2b4fd960 | b5c45eab082b8a8b4e6103fe9c979b9cc412a30a | refs/heads/master | 2020-09-27T07:49:48.064941 | 2019-12-07T06:46:16 | 2019-12-07T06:46:16 | 226,468,016 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,541 | cpp | #include <iostream>
#include<graphics.h>
#include<string>
using namespace std;
//histo 2 neshta
void MinMax(int n, double a[],double &Min, double &Max)
{
Max = a[0]; Min = a[0];
for (int i = 0; i < n; i++)
{
if (a[i] > Max) Max = a[i];
if (a[i] < Min) Min = a[i];
}
}
void Histo(int dir,int x0, int y0,double a[],double b[],double s,int ds,int dc,double amin,int n)
{
if(dir==0)
for(int i=0;i<n;i++)
{
setfillstyle(3,3+i);
bar(x0+(i+1)*(ds+dc)-dc,y0-a[i]/s,x0+(i+1)*(dc+ds),y0);
setfillstyle(1,3+i);
bar(x0+(i+1)*(ds+dc)-dc,y0+b[i]/s,x0+(i+1)*(dc+ds),y0);
}
if(dir==1)
for(int i=0;i<n;i++)
{
setfillstyle(3,3+i);
bar(x0,y0-(i+1)*(ds+dc),x0+a[i]/s,y0-(i+1)*(ds+dc)+dc);
setfillstyle(1,3+i);
bar(x0,y0-(i+1)*(ds+dc),x0-b[i]/s,y0-(i+1)*(ds+dc)+dc);
}
}
int main()
{
int n=6;
double a[6]={0.3,1.1,0.5,0.9,0.7,1.2};
double b[6]={0.6,0.4,0.5,0.9,0.8,0.1};
char char1[6][10]={"hrana","transport","stoki","kola","tok","voda"};
int x0=100,y0=600, p=50, Ds=40, Dc=40;
double amin, amax;
double bmin, bmax;
MinMax(n,a,amin,amax);
MinMax(n,b,bmin,bmax);
cout<<amax<<" "<<bmax;
if(amin>0) amin=0;
if(amax<0) amax=0;
if(bmin>0) bmin=0;
if(bmax<0) bmax=0;
double S=(amax-bmax)/p;
double yop=y0-(bmax/S);
double xop=x0+(bmax/S);
initwindow(800,700);
Histo(1,xop,y0,a,b,S,Ds,Dc,amin,n);
getch();
}
| [
"noreply@github.com"
] | todorov9898.noreply@github.com |
60bebf6f7448ddc77bded4656fbdb4ae179985b6 | cac15913ccad3c0ca2de77d8d12809ef4fe21e57 | /Source/ThirdPersonCamera/ThirdPersonCameraGameMode.h | b7287cab8e32fe0daa0ce368505f536d2f4a757c | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | ArnaudSpicht/third-person-camera | 431d6b2ee276c296fe1ff348c7c2ca559201cd44 | 7bedf626d15820d0ff3563b503729d8e2ce5aaa9 | refs/heads/develop | 2020-03-13T15:21:12.026161 | 2018-08-13T06:47:37 | 2018-08-13T06:47:37 | 131,175,154 | 0 | 0 | MIT | 2018-08-13T06:48:26 | 2018-04-26T15:23:11 | C++ | UTF-8 | C++ | false | false | 270 | h | #pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "ThirdPersonCameraGameMode.generated.h"
UCLASS(minimalapi)
class AThirdPersonCameraGameMode : public AGameModeBase
{
GENERATED_BODY()
public:
AThirdPersonCameraGameMode();
};
| [
"dev@npruehs.de"
] | dev@npruehs.de |
03a5ea2507f3f491900424c757dd0098ff6bfb99 | db1292c07e591e8456f11601dba20c0068c9cecc | /tensorflow/compiler/xla/service/hlo_module_config.h | f375210e65fa6b5c52766e83d8d513336b35056e | [
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | mkuchnik/PlumberTensorflow | e4c8e66713b9bccfe24c0e80a54794ae2c413e7b | 08bf144ec13b0c27f2a02aaba975546506ee0f6a | refs/heads/main | 2023-04-18T21:08:15.080909 | 2022-02-24T01:12:48 | 2022-02-25T01:26:10 | 459,011,882 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 12,573 | h | /* Copyright 2017 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_SERVICE_HLO_MODULE_CONFIG_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_HLO_MODULE_CONFIG_H_
#include <string>
#include "absl/types/optional.h"
#include "tensorflow/compiler/xla/debug_options_flags.h"
#include "tensorflow/compiler/xla/service/computation_layout.h"
#include "tensorflow/compiler/xla/service/computation_placer.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/xla.pb.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
namespace xla {
enum class FusionConfigCollection {
kOff, // Do not collect configuration.
kPerEdge, // Collect per-edge configuration.
kPerNode, // Collect per-node configuration.
};
// This class gathers all settings and values which affect the compiled
// executable outside of the HLO code itself. This include layouts of inputs and
// outputs to the module and settings such as HLO profiling. Together the
// HloModule and HloModuleConfig unambiguously determine a particular
// executable.
class HloModuleConfig {
public:
// Represents a pair of input and output of the entry computation that can be
// considered as the original and updated values of a variable maintained by
// the caller, and that can be transparently sharded by XLA as an internal
// optimization. If sharded, XLA will create separate sharding/unsharding
// programs, and the caller is responsible to call the XLA-generated
// sharding/unsharding programs before and after the sharded main program.
//
// If the variable is not updated and there is not a corresponding output, use
// {-1} as the output_shape_index.
//
// The sharding/unsharding programs will include all the input/output pairs in
// shardable_value_update_pairs() as a flat tuple in their inputs/outputs,
// sorted by (input_parameter_number, parameter_shape_index).
//
// A typical usage pattern is to shard the variables first, then repeatedly
// invoke the main program, and finally invoke the unsharding program before
// they are used in full-shape.
struct ShardableValueUpdatePair {
int64 input_parameter_number;
ShapeIndex parameter_shape_index;
ShapeIndex output_shape_index;
};
// A configuration can be created either with, or without an entry
// ComputationLayout. The default ctor creates it without -- in this case
// accessing entry_computation_layout will CHECK-fail. The ctor accepting a
// ProgramShape creates a computation layout using this shape.
// The layouts in the ProgramShape will be reset to default unless
// ignore_layouts is set to false.
HloModuleConfig() { debug_options_ = DefaultDebugOptionsIgnoringFlags(); }
explicit HloModuleConfig(const ProgramShape& program_shape,
bool ignore_layouts = true);
explicit HloModuleConfig(ComputationLayout entry_computation_layout);
// Checks if this config has an entry computation layout already.
bool has_entry_computation_layout() const {
return entry_computation_layout_.has_value();
}
// Sets the entry_computation_layout's parameter and result shapes for this
// config, according to the given program shape. The parameters and result
// are set to default layout.
void SetDefaultComputationLayout(const ProgramShape& program_shape);
// Same as above but if the given program contains layout for parameters or
// result, the entry_computation_layout's layout is updated accordingly.
void SetComputationLayoutIfExists(const ProgramShape& program_shape);
// Returns a constant reference to the layout of the entry computation.
// Assumes the layout was set.
const ComputationLayout& entry_computation_layout() const {
CHECK(entry_computation_layout_.has_value());
return *entry_computation_layout_;
}
// Returns a mutable pointer to the layout of the entry computation.
// Assumes the layout was set.
ComputationLayout* mutable_entry_computation_layout() {
CHECK(entry_computation_layout_.has_value());
return &(*entry_computation_layout_);
}
// Returns whether to enable HLO-level profiling.
bool hlo_profiling_enabled() const {
return debug_options_.xla_hlo_profile();
}
bool cpu_traceme_enabled() const {
return debug_options_.xla_cpu_enable_xprof_traceme();
}
// Sets/returns the module seed set during execution.
void set_seed(uint64 seed) { seed_ = seed; }
uint64 seed() const { return seed_; }
// Set the launch id of the program. Launch id identifies a set of programs
// that should be launched together.
void set_launch_id(uint64 launch_id) { launch_id_ = launch_id; }
int32 launch_id() const { return launch_id_; }
void set_replica_count(int64_t replica_count) {
replica_count_ = replica_count;
}
int64 replica_count() const { return replica_count_; }
void set_num_partitions(int64_t num_partitions) {
num_partitions_ = num_partitions;
}
int64 num_partitions() const { return num_partitions_; }
const std::vector<bool> param_requires_broadcast_via_collectives() const {
return param_requires_broadcast_via_collectives_;
}
void set_param_requires_broadcast_via_collectives(
const std::vector<bool> require_broadcast) {
param_requires_broadcast_via_collectives_ = std::move(require_broadcast);
}
void set_use_spmd_partitioning(bool use_spmd_partitioning) {
use_spmd_partitioning_ = use_spmd_partitioning;
}
bool use_spmd_partitioning() const { return use_spmd_partitioning_; }
// If enabled, deduplicate equivalent hlos into function calls to reduce code
// size.
void set_deduplicate_hlo(bool deduplicate_hlo) {
deduplicate_hlo_ = deduplicate_hlo;
}
bool deduplicate_hlo() const { return deduplicate_hlo_; }
// Return a string which unambiguously represents all the fields of this data
// structure. Used for generating a cache key for storing the compiled
// executable.
string compilation_cache_key() const;
const DebugOptions& debug_options() const { return debug_options_; }
void set_debug_options(const DebugOptions& debug_options) {
debug_options_ = debug_options;
}
// Sets/returns the number of intra op threads for this module.
void set_intra_op_parallelism_threads(
const int intra_op_parallelism_threads) {
intra_op_parallelism_threads_ = intra_op_parallelism_threads;
}
int64 intra_op_parallelism_threads() const {
return intra_op_parallelism_threads_;
}
// Checks if this config has a static device assignment.
bool has_static_device_assignment() const {
return static_device_assignment_.has_value();
}
// Getter and setter of the compile-time known device assignment.
const DeviceAssignment& static_device_assignment() const {
CHECK(static_device_assignment_.has_value());
return *static_device_assignment_;
}
void set_static_device_assignment(const DeviceAssignment& device_assignment) {
static_device_assignment_ = device_assignment;
}
const std::vector<ShardableValueUpdatePair> shardable_value_update_pairs()
const {
return shardable_value_update_pairs_;
}
void set_shardable_value_update_pairs(
std::vector<ShardableValueUpdatePair> pairs) {
shardable_value_update_pairs_ = std::move(pairs);
}
// Whether input and output buffers are aliased if the associated parameter is
// passed-through XLA modules without being changed.
bool alias_passthrough_params() const { return alias_passthrough_params_; }
void set_alias_passthrough_params(bool alias_passthrough_params) {
alias_passthrough_params_ = alias_passthrough_params;
}
bool content_aware_computation_sorting() const {
return content_aware_computation_sorting_;
}
void set_content_aware_computation_sorting(
bool content_aware_computation_sorting) {
content_aware_computation_sorting_ = content_aware_computation_sorting;
}
FusionConfigCollection fusion_config_collection() const {
return fusion_config_collection_;
}
void set_fusion_config_collection(
FusionConfigCollection fusion_config_collection) {
fusion_config_collection_ = fusion_config_collection;
}
const std::vector<std::vector<bool>>& fusion_config() const {
return fusion_config_;
}
std::vector<std::vector<bool>>* mutable_fusion_config() {
return &fusion_config_;
}
const std::vector<std::vector<int64>>& dot_config() const {
return dot_config_;
}
std::vector<std::vector<int64>>* mutable_dot_config() { return &dot_config_; }
const std::vector<std::vector<std::vector<int64>>>& layout_config() const {
return layout_config_;
}
std::vector<std::vector<std::vector<int64>>>* mutable_layout_config() {
return &layout_config_;
}
const std::vector<std::vector<bool>>& phase_ordering_config() const {
return phase_ordering_config_;
}
std::vector<std::vector<bool>>* mutable_phase_ordering_config() {
return &phase_ordering_config_;
}
const int phase_index() const { return phase_index_; }
void set_phase_index(const int phase_index) { phase_index_ = phase_index; }
private:
// If you add new members, be sure to update compilation_cache_key.
absl::optional<ComputationLayout> entry_computation_layout_;
// Module/graph-level seed handle.
uint64 seed_ = 0;
// Program id that identifies a set of program to be launched together.
int32 launch_id_ = 0;
// The number of replicas (data parallelism) to compile this binary for.
int64 replica_count_ = 1;
// The number of partitions (model parallelism) to compile this binary for.
int64 num_partitions_ = 1;
// Whether to broadcast args across all replicas. One entry per arg.
std::vector<bool> param_requires_broadcast_via_collectives_;
// Whether to use SPMD (true) or MPMD (false) when num_partitions_ > 0 and XLA
// needs to partition the module.
bool use_spmd_partitioning_ = false;
// If enabled, deduplicate equivalent hlos into function calls to reduce code
// size.
bool deduplicate_hlo_ = false;
// The target maximum parallelism at which to partition HLOs for parallel
// execution on the CPU backend.
int64 intra_op_parallelism_threads_ = -1;
DebugOptions debug_options_;
// Compile-time known device assignment.
absl::optional<DeviceAssignment> static_device_assignment_;
std::vector<ShardableValueUpdatePair> shardable_value_update_pairs_;
bool alias_passthrough_params_ = false;
bool content_aware_computation_sorting_ = true;
FusionConfigCollection fusion_config_collection_ =
FusionConfigCollection::kOff;
// TODO(b/155665133): Consolidate fusion, dot, and layout config into a proto
// similar to backend config.
// Custom fusion configuration, where fusion_config_[c][v] control if node v
// in computation c must be fused to all its consumers (true) or not (false).
std::vector<std::vector<bool>> fusion_config_;
// Custom dot canonicalization configuration, where dot_config_[v] control
// how to convert dot operation v (sorted topologically and by computation) to
// convolution.
std::vector<std::vector<int64>> dot_config_;
// Layout configuration, where layout_config_[v][i] controls the layout
// decision i of operation v.
std::vector<std::vector<std::vector<int64>>> layout_config_;
// Phase ordering configuration, where phase_ordering_config[v][i] controls
// whether a specific pass with index i (e.g. 0 = DCE, 1 = CSE, etc.) is
// inserted after pass v in pipeline. See tuning::PhaseOrderingConfig for
// details on what indices (i) correspond to which passes.
std::vector<std::vector<bool>> phase_ordering_config_;
// Index (v) corresponding to current passes being added for phase ordering.
// This is the variable that stores state to allow us to use the same
// config across functions during compilation.
int phase_index_;
};
} // namespace xla
#endif // TENSORFLOW_COMPILER_XLA_SERVICE_HLO_MODULE_CONFIG_H_
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
74fb8f8384b6e0d7b70c1ef55eeb2573b184d7bf | 22172c29a36537e27fd273406eaec993daa8b371 | /eeprom_i2c.cpp | 8771436bd67cb6475c28f9a72ae4c36383a7a06e | [
"MIT"
] | permissive | stuwilkins/eeprom_i2c | 33fcb0863c7f381d674427ebc43b2fcfae67ecd0 | 42d9e12dbcf781fb709c090f1d44702969098491 | refs/heads/master | 2020-03-25T15:48:49.661878 | 2019-01-20T17:41:09 | 2019-01-20T17:41:09 | 143,902,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,163 | cpp | /*
* =====================================================================================
*
* Filename: eeprom_i2c.cpp
*
* Description:
*
* Version: 1.0
* Created: 07/14/2018 13:05:17
* Revision: none
* Compiler: gcc
*
* Author: Stuart B. Wilkins (sbw), stuwilkins@mac.com
* Organization:
*
* =====================================================================================
*/
#include <Wire.h>
#include <uCRC16Lib.h>
#include <eeprom_i2c.h>
EEPROM_I2C::EEPROM_I2C(uint8_t addr)
{
_addr = addr;
}
int EEPROM_I2C::begin(void)
{
Wire.begin();
Wire.setClock(400000);
_chunk = 4;
return OK;
}
int EEPROM_I2C::writeIfDiff(uint16_t offset, uint8_t *data, int size, bool crc, bool verify)
{
if(size > EEPROM_BUFFER_SIZE)
{
return BUFFER_ERROR;
}
uint8_t _buffer[EEPROM_BUFFER_SIZE];
read(offset, _buffer, size, crc);
if(memcmp(_buffer, data, size))
{
if(verify)
{
writeAndVerify(offset, data, size, crc);
} else {
write(offset, data, size, crc);
}
} else {
return NO_WRITE;
}
return OK;
}
int EEPROM_I2C::writeAndVerify(uint16_t offset, uint8_t *data, int size, bool crc, int retries)
{
if(size > EEPROM_BUFFER_SIZE)
{
return BUFFER_ERROR;
}
int ok = retries;
while(ok)
{
write(offset, data, size, crc);
uint8_t _buffer[EEPROM_BUFFER_SIZE];
read(offset, _buffer, size, crc);
if(!memcmp(_buffer, data, size))
{
return OK;
}
ok--;
}
return VERIFY_FAILED;
}
void EEPROM_I2C::_write(uint16_t offset, uint8_t *data, int chunk)
{
Wire.beginTransmission(_addr);
Wire.write((int)(offset >> 8));
Wire.write((int)(offset & 0xFF));
for(int j=0;j<chunk;j++)
{
Wire.write((int)data[j]);
}
Wire.endTransmission();
delay(5);
}
int EEPROM_I2C::write(uint16_t offset, uint8_t *data, int size, bool crc)
{
uint8_t *ptr = data;
uint16_t _offset = offset;
for(int i = 0;i<size;i+=_chunk){
int _c = (size - i) > _chunk ? _chunk : (size - i);
_write(_offset, ptr, _c);
_offset += _c;
ptr += _c;
}
if(crc)
{
uint16_t c_crc = uCRC16Lib::calculate((char*)data, size);
_write(_offset, (uint8_t*)(&c_crc), sizeof(c_crc));
}
return OK;
}
void EEPROM_I2C::_read(uint16_t offset, uint8_t* data, int chunk)
{
Wire.beginTransmission(_addr);
Wire.write(offset >> 8);
Wire.write(offset & 0xFF);
Wire.endTransmission();
Wire.requestFrom(_addr, chunk);
int j=0;
while(Wire.available())
{
data[j++] = Wire.read();
}
}
int EEPROM_I2C::read(uint16_t offset, uint8_t* data, int size, bool crc)
{
uint8_t *data_ptr = data;
uint16_t _offset = offset;
for(int i = 0;i<size;i+=_chunk)
{
int _c = (size - i) > _chunk ? _chunk : (size - i);
_read(_offset, data_ptr, _c);
data_ptr += _c;
_offset += _c;
}
if(crc)
{
uint16_t c_crc, r_crc;
_read(_offset, (uint8_t*)(&r_crc), sizeof(r_crc));
c_crc = uCRC16Lib::calculate((char*)data, size);
if(c_crc != r_crc)
{
return VERIFY_FAILED;
}
}
return OK;
}
| [
"swilkins@bnl.gov"
] | swilkins@bnl.gov |
68dee00ea29895bdc5c7f97260a0969c619e92de | ccae3c9b20fa3c895042a1c7aa0815fd0faec141 | /trunk/TestCode/DekTecTest/ZQASIRenderFilter/ASIDevConfig.h | d612af581c002efc747d7fe50e17cdea19a11fc5 | [] | no_license | 15831944/TxUIProject | 7beaf17eb3642bcffba2bbe8eaa7759c935784a0 | e90f3319ad0e57c0012e0e3a7e457851c2c6f0f1 | refs/heads/master | 2021-12-03T10:05:27.018212 | 2014-05-16T08:16:17 | 2014-05-16T08:16:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 322 | h | #pragma once
#include "IASIDevPreConfig.h"
class CASIDevConfig :
public IASIDevPreConfig
{
public:
CASIDevConfig(void);
~CASIDevConfig(void);
DECLARE_IUNKNOWN
STDMETHODIMP set_param (
devparam *paramIn //
) PURE;
STDMETHODIMP get_param (
devparam *paramOut //
) PURE;
devparam m_DevParam;
};
| [
"tyxwgy@sina.com"
] | tyxwgy@sina.com |
fc53e0ba9b7729d7a0aa0d498855708ca2b3ce3f | b05c7621964da47f7807ba6e38c221fcb84a7420 | /Five/ChatEdit.cpp | c60d58ccdfb85f7f8e063608171e69bfbdbdaab2 | [] | no_license | F-Yong/Five | 2ca95586bee386b8c900e21bc51f33fa44678891 | a54f3a0728752bc74e49635e6720357ccdeadc80 | refs/heads/master | 2020-03-18T21:11:46.549967 | 2018-05-29T09:11:42 | 2018-05-29T09:11:42 | 135,265,598 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,392 | cpp | // ChatEdit.cpp : implementation file
//
#include "stdafx.h"
#include "five.h"
#include "ChatEdit.h"
#include "Table.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CChatEdit
CChatEdit::CChatEdit()
{
}
CChatEdit::~CChatEdit()
{
}
BEGIN_MESSAGE_MAP(CChatEdit, CEdit)
//{{AFX_MSG_MAP(CChatEdit)
ON_WM_KEYDOWN()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CChatEdit message handlers
void CChatEdit::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
// TODO: Add your message handler code here and/or call default
if ( '6' == nChar )
{
CTable *pTable = (CTable *)( AfxGetMainWnd()->GetDlgItem( IDC_TABLE ) );
// 发送聊天信息
TCHAR str[128];
GetWindowText( str, 128 );
pTable->Chat( str );
// 写入聊天记录
CEdit *pEdit = (CEdit *)( AfxGetMainWnd()->GetDlgItem( IDC_EDT_CHAT ) );
CString strAdd;
strAdd.Format( _T("你 说:%s\r\n"), str );
pEdit->SetSel( -1, -1, TRUE );
pEdit->ReplaceSel( str );
SetWindowText( _T("") );
}
else
{
CEdit::OnKeyDown(nChar, nRepCnt, nFlags);
}
}
| [
"noreply@github.com"
] | F-Yong.noreply@github.com |
a18b8f80aea76bd869847aed0e146fa6f0c24548 | 4dc775f76236beffc15eae55fdcdcf187bc4afaa | /src/qt/rpcconsole.cpp | f12d8de798d4d737011fa7593c50cd921a8ae7de | [
"MIT"
] | permissive | EnceladusProject/Enceladus_Coin | 21e15fc63211af078667ca80623fe0a30b6359e9 | 0ba1477f56e05c83b294d22adbb3bc8cdd05607c | refs/heads/master | 2020-04-01T11:13:46.405359 | 2018-11-10T16:22:21 | 2018-11-10T16:22:21 | 153,153,251 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,202 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The Enceladus developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcconsole.h"
#include "ui_rpcconsole.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "peertablemodel.h"
#include "chainparams.h"
#include "main.h"
#include "rpcclient.h"
#include "rpcserver.h"
#include "util.h"
#include "json/json_spirit_value.h"
#include <openssl/crypto.h>
#ifdef ENABLE_WALLET
#include <db_cxx.h>
#endif
#include <QDir>
#include <QKeyEvent>
#include <QScrollBar>
#include <QThread>
#include <QTime>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
// TODO: add a scrollback limit, as there is currently none
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_HISTORY = 50;
const QSize ICON_SIZE(24, 24);
const int INITIAL_TRAFFIC_GRAPH_MINS = 30;
// Repair parameters
const QString SALVAGEWALLET("-salvagewallet");
const QString RESCAN("-rescan");
const QString ZAPTXES1("-zapwallettxes=1");
const QString ZAPTXES2("-zapwallettxes=2");
const QString UPGRADEWALLET("-upgradewallet");
const QString REINDEX("-reindex");
const struct {
const char* url;
const char* source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{NULL, NULL}};
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor : public QObject
{
Q_OBJECT
public slots:
void request(const QString& command);
signals:
void reply(int category, const QString& command);
};
#include "rpcconsole.moc"
/**
* Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
*
* - Arguments are delimited with whitespace
* - Extra whitespace at the beginning and end and between arguments will be ignored
* - Text can be "double" or 'single' quoted
* - The backslash \c \ is used as escape character
* - Outside quotes, any character can be escaped
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
* @param[out] args Parsed arguments will be appended to this list
* @param[in] strCommand Command line to split
*/
bool parseCommandLine(std::vector<std::string>& args, const std::string& strCommand)
{
enum CmdParseState {
STATE_EATING_SPACES,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED
} state = STATE_EATING_SPACES;
std::string curarg;
foreach (char ch, strCommand) {
switch (state) {
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES: // Handle runs of whitespace
switch (ch) {
case '"':
state = STATE_DOUBLEQUOTED;
break;
case '\'':
state = STATE_SINGLEQUOTED;
break;
case '\\':
state = STATE_ESCAPE_OUTER;
break;
case ' ':
case '\n':
case '\t':
if (state == STATE_ARGUMENT) // Space ends argument
{
args.push_back(curarg);
curarg.clear();
}
state = STATE_EATING_SPACES;
break;
default:
curarg += ch;
state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch (ch) {
case '\'':
state = STATE_ARGUMENT;
break;
default:
curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch (ch) {
case '"':
state = STATE_ARGUMENT;
break;
case '\\':
state = STATE_ESCAPE_DOUBLEQUOTED;
break;
default:
curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch;
state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if (ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch;
state = STATE_DOUBLEQUOTED;
break;
}
}
switch (state) // final state
{
case STATE_EATING_SPACES:
return true;
case STATE_ARGUMENT:
args.push_back(curarg);
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void RPCExecutor::request(const QString& command)
{
std::vector<std::string> args;
if (!parseCommandLine(args, command.toStdString())) {
emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
}
if (args.empty())
return; // Nothing to do
try {
std::string strPrint;
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
json_spirit::Value result = tableRPC.execute(
args[0],
RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
// Format result reply
if (result.type() == json_spirit::null_type)
strPrint = "";
else if (result.type() == json_spirit::str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
} catch (json_spirit::Object& objError) {
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
} catch (std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false)));
}
} catch (std::exception& e) {
emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
RPCConsole::RPCConsole(QWidget* parent) : QDialog(parent),
ui(new Ui::RPCConsole),
clientModel(0),
historyPtr(0),
cachedNodeid(-1)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nRPCConsoleWindow", this->size(), this);
#ifndef Q_OS_MAC
ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
#endif
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
ui->messagesWidget->installEventFilter(this);
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear()));
// Wallet Repair Buttons
connect(ui->btn_salvagewallet, SIGNAL(clicked()), this, SLOT(walletSalvage()));
connect(ui->btn_rescan, SIGNAL(clicked()), this, SLOT(walletRescan()));
connect(ui->btn_zapwallettxes1, SIGNAL(clicked()), this, SLOT(walletZaptxes1()));
connect(ui->btn_zapwallettxes2, SIGNAL(clicked()), this, SLOT(walletZaptxes2()));
connect(ui->btn_upgradewallet, SIGNAL(clicked()), this, SLOT(walletUpgrade()));
connect(ui->btn_reindex, SIGNAL(clicked()), this, SLOT(walletReindex()));
// set library version labels
ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
#ifdef ENABLE_WALLET
ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
ui->wallet_path->setText(QString::fromStdString(GetDataDir().string() + QDir::separator().toLatin1() + GetArg("-wallet", "wallet.dat")));
#else
ui->label_berkeleyDBVersion->hide();
ui->berkeleyDBVersion->hide();
#endif
startExecutor();
setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);
ui->peerHeading->setText(tr("Select a peer to view detailed information."));
clear();
}
RPCConsole::~RPCConsole()
{
GUIUtil::saveWindowGeometry("nRPCConsoleWindow", this);
emit stopExecutor();
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent* event)
{
if (event->type() == QEvent::KeyPress) // Special key handling
{
QKeyEvent* keyevt = static_cast<QKeyEvent*>(event);
int key = keyevt->key();
Qt::KeyboardModifiers mod = keyevt->modifiers();
switch (key) {
case Qt::Key_Up:
if (obj == ui->lineEdit) {
browseHistory(-1);
return true;
}
break;
case Qt::Key_Down:
if (obj == ui->lineEdit) {
browseHistory(1);
return true;
}
break;
case Qt::Key_PageUp: /* pass paging keys to messages widget */
case Qt::Key_PageDown:
if (obj == ui->lineEdit) {
QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
return true;
}
break;
default:
// Typing in messages widget brings focus to line edit, and redirects key there
// Exclude most combinations and keys that emit no text, except paste shortcuts
if (obj == ui->messagesWidget && ((!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) {
ui->lineEdit->setFocus();
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
}
}
return QDialog::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel* model)
{
clientModel = model;
ui->trafficGraph->setClientModel(model);
if (model) {
// Keep up to date with client
setNumConnections(model->getNumConnections());
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(model->getNumBlocks());
connect(model, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int)));
setMasternodeCount(model->getMasternodeCountString());
connect(model, SIGNAL(strMasternodesChanged(QString)), this, SLOT(setMasternodeCount(QString)));
updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent());
connect(model, SIGNAL(bytesChanged(quint64, quint64)), this, SLOT(updateTrafficStats(quint64, quint64)));
// set up peer table
ui->peerWidget->setModel(model->getPeerTableModel());
ui->peerWidget->verticalHeader()->hide();
ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->peerWidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
// connect the peerWidget selection model to our peerSelected() handler
connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
this, SLOT(peerSelected(const QItemSelection&, const QItemSelection&)));
connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged()));
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientName->setText(model->clientName());
ui->buildDate->setText(model->formatBuildDate());
ui->startupTime->setText(model->formatClientStartupTime());
ui->networkName->setText(QString::fromStdString(Params().NetworkIDString()));
}
}
static QString categoryClass(int category)
{
switch (category) {
case RPCConsole::CMD_REQUEST:
return "cmd-request";
break;
case RPCConsole::CMD_REPLY:
return "cmd-reply";
break;
case RPCConsole::CMD_ERROR:
return "cmd-error";
break;
default:
return "misc";
}
}
/** Restart wallet with "-salvagewallet" */
void RPCConsole::walletSalvage()
{
buildParameterlist(SALVAGEWALLET);
}
/** Restart wallet with "-rescan" */
void RPCConsole::walletRescan()
{
buildParameterlist(RESCAN);
}
/** Restart wallet with "-zapwallettxes=1" */
void RPCConsole::walletZaptxes1()
{
buildParameterlist(ZAPTXES1);
}
/** Restart wallet with "-zapwallettxes=2" */
void RPCConsole::walletZaptxes2()
{
buildParameterlist(ZAPTXES2);
}
/** Restart wallet with "-upgradewallet" */
void RPCConsole::walletUpgrade()
{
buildParameterlist(UPGRADEWALLET);
}
/** Restart wallet with "-reindex" */
void RPCConsole::walletReindex()
{
buildParameterlist(REINDEX);
}
/** Build command-line parameter list for restart */
void RPCConsole::buildParameterlist(QString arg)
{
// Get command-line arguments and remove the application name
QStringList args = QApplication::arguments();
args.removeFirst();
// Remove existing repair-options
args.removeAll(SALVAGEWALLET);
args.removeAll(RESCAN);
args.removeAll(ZAPTXES1);
args.removeAll(ZAPTXES2);
args.removeAll(UPGRADEWALLET);
args.removeAll(REINDEX);
// Append repair parameter to command line.
args.append(arg);
// Send command-line arguments to BitcoinGUI::handleRestart()
emit handleRestart(args);
}
void RPCConsole::clear()
{
ui->messagesWidget->clear();
history.clear();
historyPtr = 0;
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for (int i = 0; ICON_MAPPING[i].url; ++i) {
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
ui->messagesWidget->document()->setDefaultStyleSheet(
"table { }"
"td.time { color: #808080; padding-top: 3px; } "
"td.message { font-family: Courier, Courier New, Lucida Console, monospace; font-size: 12px; } " // Todo: Remove fixed font-size
"td.cmd-request { color: #006060; } "
"td.cmd-error { color: red; } "
"b { color: #006060; } ");
message(CMD_REPLY, (tr("Welcome to the ENCP RPC console.") + "<br>" +
tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")),
true);
}
void RPCConsole::reject()
{
// Ignore escape keypress if this is not a seperate window
if (windowType() != Qt::Widget)
QDialog::reject();
}
void RPCConsole::message(int category, const QString& message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if (html)
out += message;
else
out += GUIUtil::HtmlEscape(message, true);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::setNumConnections(int count)
{
if (!clientModel)
return;
QString connections = QString::number(count) + " (";
connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
ui->numberOfConnections->setText(connections);
}
void RPCConsole::setNumBlocks(int count)
{
ui->numberOfBlocks->setText(QString::number(count));
if (clientModel)
ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
}
void RPCConsole::setMasternodeCount(const QString& strMasternodes)
{
ui->masternodeCount->setText(strMasternodes);
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
ui->lineEdit->clear();
if (!cmd.isEmpty()) {
message(CMD_REQUEST, cmd);
emit cmdRequest(cmd);
// Remove command, if already in history
history.removeOne(cmd);
// Append command to history
history.append(cmd);
// Enforce maximum history size
while (history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
historyPtr += offset;
if (historyPtr < 0)
historyPtr = 0;
if (historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if (historyPtr < history.size())
cmd = history.at(historyPtr);
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
QThread* thread = new QThread;
RPCExecutor* executor = new RPCExecutor();
executor->moveToThread(thread);
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int, QString)), this, SLOT(message(int, QString)));
// Requests from this object must go to executor
connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
// On stopExecutor signal
// - queue executor for deletion (in execution thread)
// - quit the Qt event loop in the execution thread
connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
// Queue the thread for deletion (in this thread) when it is finished
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread->start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if (ui->tabWidget->widget(index) == ui->tab_console) {
ui->lineEdit->setFocus();
}
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar* scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_sldGraphRange_valueChanged(int value)
{
const int multiplier = 5; // each position on the slider represents 5 min
int mins = value * multiplier;
setTrafficGraphRange(mins);
}
QString RPCConsole::FormatBytes(quint64 bytes)
{
if (bytes < 1024)
return QString(tr("%1 B")).arg(bytes);
if (bytes < 1024 * 1024)
return QString(tr("%1 KB")).arg(bytes / 1024);
if (bytes < 1024 * 1024 * 1024)
return QString(tr("%1 MB")).arg(bytes / 1024 / 1024);
return QString(tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
}
void RPCConsole::setTrafficGraphRange(int mins)
{
ui->trafficGraph->setGraphRangeMins(mins);
ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60));
}
void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
{
ui->lblBytesIn->setText(FormatBytes(totalBytesIn));
ui->lblBytesOut->setText(FormatBytes(totalBytesOut));
}
void RPCConsole::showInfo()
{
ui->tabWidget->setCurrentIndex(0);
show();
}
void RPCConsole::showConsole()
{
ui->tabWidget->setCurrentIndex(1);
show();
}
void RPCConsole::showNetwork()
{
ui->tabWidget->setCurrentIndex(2);
show();
}
void RPCConsole::showPeers()
{
ui->tabWidget->setCurrentIndex(3);
show();
}
void RPCConsole::showRepair()
{
ui->tabWidget->setCurrentIndex(4);
show();
}
void RPCConsole::showConfEditor()
{
GUIUtil::openConfigfile();
}
void RPCConsole::showMNConfEditor()
{
GUIUtil::openMNConfigfile();
}
void RPCConsole::peerSelected(const QItemSelection& selected, const QItemSelection& deselected)
{
Q_UNUSED(deselected);
if (!clientModel || selected.indexes().isEmpty())
return;
const CNodeCombinedStats* stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row());
if (stats)
updateNodeDetail(stats);
}
void RPCConsole::peerLayoutChanged()
{
if (!clientModel)
return;
const CNodeCombinedStats* stats = NULL;
bool fUnselect = false;
bool fReselect = false;
if (cachedNodeid == -1) // no node selected yet
return;
// find the currently selected row
int selectedRow;
QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes();
if (selectedModelIndex.isEmpty())
selectedRow = -1;
else
selectedRow = selectedModelIndex.first().row();
// check if our detail node has a row in the table (it may not necessarily
// be at selectedRow since its position can change after a layout change)
int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeid);
if (detailNodeRow < 0) {
// detail node dissapeared from table (node disconnected)
fUnselect = true;
cachedNodeid = -1;
ui->peerHeading->setText(tr("Select a peer to view detailed information."));
} else {
if (detailNodeRow != selectedRow) {
// detail node moved position
fUnselect = true;
fReselect = true;
}
// get fresh stats on the detail node.
stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
}
if (fUnselect && selectedRow >= 0) {
ui->peerWidget->selectionModel()->select(QItemSelection(selectedModelIndex.first(), selectedModelIndex.last()),
QItemSelectionModel::Deselect);
}
if (fReselect) {
ui->peerWidget->selectRow(detailNodeRow);
}
if (stats)
updateNodeDetail(stats);
}
void RPCConsole::updateNodeDetail(const CNodeCombinedStats* stats)
{
// Update cached nodeid
cachedNodeid = stats->nodeStats.nodeid;
// update the detail ui with latest node information
QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName));
if (!stats->nodeStats.addrLocal.empty())
peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
ui->peerHeading->setText(peerAddrDetails);
ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices));
ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastSend) : tr("never"));
ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastRecv) : tr("never"));
ui->peerBytesSent->setText(FormatBytes(stats->nodeStats.nSendBytes));
ui->peerBytesRecv->setText(FormatBytes(stats->nodeStats.nRecvBytes));
ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nTimeConnected));
ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime));
ui->peerVersion->setText(QString("%1").arg(stats->nodeStats.nVersion));
ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound"));
ui->peerHeight->setText(QString("%1").arg(stats->nodeStats.nStartingHeight));
// This check fails for example if the lock was busy and
// nodeStateStats couldn't be fetched.
if (stats->fNodeStateStatsAvailable) {
// Ban score is init to 0
ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior));
// Sync height is init to -1
if (stats->nodeStateStats.nSyncHeight > -1)
ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
else
ui->peerSyncHeight->setText(tr("Unknown"));
} else {
ui->peerBanScore->setText(tr("Fetching..."));
ui->peerSyncHeight->setText(tr("Fetching..."));
}
ui->detailWidget->show();
}
void RPCConsole::resizeEvent(QResizeEvent* event)
{
QWidget::resizeEvent(event);
}
void RPCConsole::showEvent(QShowEvent* event)
{
QWidget::showEvent(event);
if (!clientModel)
return;
// start PeerTableModel auto refresh
clientModel->getPeerTableModel()->startAutoRefresh();
}
void RPCConsole::hideEvent(QHideEvent* event)
{
QWidget::hideEvent(event);
if (!clientModel)
return;
// stop PeerTableModel auto refresh
clientModel->getPeerTableModel()->stopAutoRefresh();
}
void RPCConsole::showBackups()
{
GUIUtil::showBackups();
}
| [
""
] | |
2cb950b064d18a201b742c79140713f61844c657 | cb3b8fda8f03642e50fa5bc84438a594128930a2 | /src/system/kernel/core/processor/mips_common/Disassembler.cc | 122c54285a2ace3d03ca280eaf85f2cca9c86d29 | [
"ISC"
] | permissive | OuluLinux/pedigree | fbb83055d0afd1e620f48d8cfd89a2bf88235701 | 4f02647d8237cc19cff3c20584c0fdd27b14a7d4 | refs/heads/master | 2022-12-28T15:49:01.918113 | 2013-05-25T02:20:01 | 2013-05-25T02:20:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,091 | cc | /*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and 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 "Disassembler.h"
const char *g_pOpcodes[64] = {
0, // Special
0, // RegImm
"j ",
"jal ",
"beq ",
"bne ",
"blez ",
"bgtz ",
"addi ", // 8
"addiu ",
"slti ",
"sltiu ",
"andi ",
"ori ",
"xori ",
"lui ",
"cop0 ", // 16
"cop1 ",
"cop2 ",
"cop3 ",
"beql ",
"bnel ",
"blezl ",
"bgtzl ",
0, // 24
0,
0,
0,
0,
0,
0,
0,
"lb ", // 32
"lh ",
"lwl ",
"lw ",
"lbu ",
"lhu ",
"lwr ",
0,
"sb ", // 40
"sh ",
"swl ",
"sw ",
0,
0,
"swr ",
"cache ",
"ll ", // 48
"lwc1 ",
"lwc2 ",
"lwc3 ",
0,
"ldc1 ",
"ldc2 ",
"ldc3 ",
"sc ", // 56
"swc1 ",
"swc2 ",
"swc3 ",
0,
"sdc1 ",
"sdc2 ",
"sdc3 "
};
const char *g_pSpecial[64] = {
"sll ",
0,
"srl ",
"sra ",
"sllv ",
0,
"srlv ",
"srav ",
"jr ", // 8
"jalr ",
0,
0,
"syscall",
"break ",
0,
"sync ",
"mfhi ", // 16
"mthi ",
"mflo ",
"mtlo ",
0,
0,
0,
0,
"mult ", // 24
"multu ",
"div ",
"divu ",
0,
0,
0,
0,
"add ", // 32
"addu ",
"sub ",
"subu ",
"and ",
"or ",
"xor ",
"nor ",
0, // 40
0,
"slt ",
"sltu ",
0,
0,
0,
0,
"tge ", // 48
"tgeu ",
"tlt ",
"tltu ",
"teq ",
0,
"tne ",
0,
0, // 56
0,
0,
0,
0,
0,
0,
0
};
const char *g_pRegimm[32] = {
"bltz ",
"bgez ",
"bltzl ",
"bgezl ",
0,
0,
0,
0,
"tgei ", // 8
"tgeiu ",
"tlti ",
"tltiu ",
"teqi ",
0,
"tnei ",
0,
"bltzal", // 16
"bgezal",
"bltzall",
"bgezall",
0,
0,
0,
0,
0, // 24
0,
0,
0,
0,
0,
0,
0
};
const char *g_pCopzRs[32] = {
"mfc",
0,
"cfc",
0,
"mtc",
0,
"ctc",
0,
"bc", // 8
0,
0,
0,
0,
0,
0,
0,
"co", // 16
"co",
"co",
"co",
"co",
"co",
"co",
"co",
"co", // 24
"co",
"co",
"co",
"co",
"co",
"co",
"co"
};
const char *g_pCopzRt[32] = {
"f",
"t",
"fl",
"tl",
0,
0,
0,
0,
0, // 8
0,
0,
0,
0,
0,
0,
0,
0, // 16
0,
0,
0,
0,
0,
0,
0,
0, // 24
0,
0,
0,
0,
0,
0,
0
};
const char *g_pCp0Function[64] = {
0,
"tlbr",
"tlbwi",
0,
0,
0,
"tlbwr",
0,
"tlbp", // 8
0,
0,
0,
0,
0,
0,
0,
"rfe", // 16
0,
0,
0,
0,
0,
0,
0,
"eret", // 24
0,
0,
0,
0,
0,
0,
0,
0, // 32
0,
0,
0,
0,
0,
0,
0,
0, // 40
0,
0,
0,
0,
0,
0,
0,
0, // 48
0,
0,
0,
0,
0,
0,
0,
0, // 56
0,
0,
0,
0,
0,
0,
0
};
const char *g_pRegisters[32] = {
"zero",
"at",
"v0",
"v1",
"a0",
"a1",
"a2",
"a3",
"t0",
"t1",
"t2",
"t3",
"t4",
"t5",
"t6",
"t7",
"s0",
"s1",
"s2",
"s3",
"s4",
"s5",
"s6",
"s7",
"t8",
"t9",
"k0",
"k1",
"gp",
"sp",
"fp",
"ra"
};
MipsDisassembler::MipsDisassembler()
: m_nLocation(0)
{
}
MipsDisassembler::~MipsDisassembler()
{
}
void MipsDisassembler::setLocation(uintptr_t nLocation)
{
m_nLocation = nLocation;
}
uintptr_t MipsDisassembler::getLocation()
{
return m_nLocation;
}
void MipsDisassembler::setMode(size_t nMode)
{
}
void MipsDisassembler::disassemble(LargeStaticString &text)
{
uint32_t nInstruction = * reinterpret_cast<uint32_t*> (m_nLocation);
m_nLocation += 4;
// SLL $zero, $zero, 0 == nop.
if (nInstruction == 0)
{
text += "nop";
return;
}
// Grab the instruction opcode.
int nOpcode = (nInstruction >> 26) & 0x3F;
// Handle special opcodes.
if (nOpcode == 0)
{
disassembleSpecial(nInstruction, text);
}
else if (nOpcode == 1)
{
disassembleRegImm(nInstruction, text);
}
else
{
disassembleOpcode(nInstruction, text);
}
}
void MipsDisassembler::disassembleSpecial(uint32_t nInstruction, LargeStaticString & text)
{
// Special instructions are R-Types.
uint32_t nRs = (nInstruction >> 21) & 0x1F;
uint32_t nRt = (nInstruction >> 16) & 0x1F;
uint32_t nRd = (nInstruction >> 11) & 0x1F;
uint32_t nShamt = (nInstruction >> 6) & 0x1F;
uint32_t nFunct = nInstruction & 0x3F;
if (g_pSpecial[nFunct] == 0)
return;
switch (nFunct)
{
case 00: // SLL
case 02: // SRL
case 03: // SRA
text += g_pSpecial[nFunct];
text += " ";
text += g_pRegisters[nRd];
text += ", ";
text += g_pRegisters[nRt];
text += ", ";
text += nShamt;
break;
case 04: // SLLV
case 06: // SRLV
case 07: // SRAV
text += g_pSpecial[nFunct];
text += " ";
text += g_pRegisters[nRd];
text += ", ";
text += g_pRegisters[nRt];
text += ", ";
text += g_pRegisters[nRs];
break;
case 010: // JR
text += "jr ";
text += g_pRegisters[nRs];
break;
case 011: // JALR
{
text += "jalr ";
if (nRd != 31)
{
text += g_pRegisters[nRd];
text += ", ";
}
text += g_pRegisters[nRs];
break;
}
case 014: // SYSCALL
case 015: // BREAK
case 017: // SYNC
text += g_pSpecial[nFunct];
break;
case 020: // MFHI
case 022: // MFLO
text += g_pSpecial[nFunct];
text += " ";
text += g_pRegisters[nRd];
break;
case 021: // MTHI
case 023: // MTLO
text += g_pSpecial[nFunct];
text += " ";
text += g_pRegisters[nRs];
break;
case 030: // MULT
case 031: // MULTU
case 032: // DIV
case 033: // DIVU
case 060: // TGE
case 061: // TGEU
case 062: // TLT
case 063: // TLTU
case 064: // TEQ
case 065: // TNE
text += g_pSpecial[nFunct];
text += " ";
text += g_pRegisters[nRs];
text += ", ";
text += g_pRegisters[nRt];
break;
case 041: // ADDU
if (nRt == 0)
{
// If this is an add of zero, it is actually a "move".
text += "move ";
text += g_pRegisters[nRd];
text += ", ";
text += g_pRegisters[nRs];
break;
}
// Fall through.
default:
{
text += g_pSpecial[nFunct];
text += " ";
text += g_pRegisters[nRd];
text += ", ";
text += g_pRegisters[nRs];
text += ", ";
text += g_pRegisters[nRt];
}
};
}
void MipsDisassembler::disassembleRegImm(uint32_t nInstruction, LargeStaticString & text)
{
uint32_t nRs = (nInstruction >> 21)&0x1F;
uint32_t nOp = (nInstruction >> 16)&0x1F;
uint16_t nImmediate = nInstruction & 0xFFFF;
uint32_t nTarget = (nImmediate << 2) + m_nLocation;
switch (nOp)
{
case 010: // TGEI
case 011: // TGEIU
case 012: // TLTI
case 013: // TLTIU
case 014: // TEQI
case 016: // TNEI
text += g_pRegimm[nOp];
text += " ";
text += g_pRegisters[nRs];
text += ", ";
text.append(static_cast<int16_t>(nImmediate), 10);
break;
default:
text += g_pRegimm[nOp];
text += " ";
text += g_pRegisters[nRs];
text += ", 0x";
text.append(nTarget, 16);
};
}
void MipsDisassembler::disassembleOpcode(uint32_t nInstruction, LargeStaticString & text)
{
// Opcode instructions are J-Types, or I-Types.
// Jump target is the lower 26 bits shifted left 2 bits, OR'd with the high 4 bits of the delay slot.
uint32_t nTarget = ((nInstruction & 0x03FFFFFF)<<2) | (m_nLocation & 0xF0000000);
uint16_t nImmediate = nInstruction & 0x0000FFFF;
uint32_t nRt = (nInstruction >> 16) & 0x1F;
uint32_t nRs = (nInstruction >> 21) & 0x1F;
int nOpcode = (nInstruction >> 26) & 0x3F;
switch (nOpcode)
{
case 02: // J
case 03: // JAL
text += g_pOpcodes[nOpcode];
text += " 0x";
text.append(nTarget, 16);
break;
case 006: // BLEZ
case 007: // BGTZ
case 026: // BLEZL
case 027: // BGTZL
text += g_pOpcodes[nOpcode];
text += " ";
text += g_pRegisters[nRs];
text += ", 0x";
text.append( (static_cast<uint32_t>(nImmediate) << 2)+m_nLocation, 16);
break;
case 004: // BEQ
case 005: // BNE
case 024: // BEQL
case 025: // BNEL
text += g_pOpcodes[nOpcode];
text += " ";
text += g_pRegisters[nRs];
text += ", ";
text += g_pRegisters[nRt];
text += ", 0x";
text.append( (static_cast<uint32_t>(nImmediate) << 2)+m_nLocation, 16);
break;
case 010: // ADDI
case 011: // ADDIU
case 012: // SLTI
case 013: // SLTIU
case 014: // ANDI
case 015: // ORI
case 016: // XORI
text += g_pOpcodes[nOpcode];
text += " ";
text += g_pRegisters[nRt];
text += ", ";
text += g_pRegisters[nRs];
text += ", ";
text.append(static_cast<short>(nImmediate), 10);
break;
case 017: // LUI
text += "lui ";
text += g_pRegisters[nRt];
text += ", 0x";
text.append(nImmediate, 16);
break;
case 020: // COP0
case 021: // COP1
case 022: // COP2
case 023: // COP3
{
if (nRs == 8) // BC
{
text += g_pCopzRs[nRs];
text.append( static_cast<unsigned char>(nOpcode&0x3));
text += g_pCopzRt[nRt];
text += ", 0x";
text.append( (nImmediate<<2)+m_nLocation, 16);
}
else if (nOpcode == 020 /* CP0 */ && nRs >= 16 /* CO */)
{
text += g_pCp0Function[nInstruction&0x1F];
}
else
{
text += g_pCopzRs[nRs];
text.append( static_cast<unsigned char>(nOpcode&0x3));
text += " ";
text += g_pRegisters[nRt];
text += ", ";
text.append( ((nInstruction>>11)&0x1F), 10);
}
break;
}
default:
text += g_pOpcodes[nOpcode];
text += " ";
text += g_pRegisters[nRt];
text += ", ";
text.append(static_cast<short>(nImmediate), 10);
text += "(";
text += g_pRegisters[nRs];
text += ")";
break;
}
}
| [
"mankeyrabbit@8f46629d-ec43-0410-9b68-4d101553c41d"
] | mankeyrabbit@8f46629d-ec43-0410-9b68-4d101553c41d |
2b53c5a5d0be95e878dae379db37f83fedd95660 | 6d0c83e5935251fca6108c75e19666737edafe29 | /include/frame.hpp | 272973e0e354543a38a8e35ca135e4e6654edca8 | [
"BSD-3-Clause"
] | permissive | ssincak/webmPlayer | 7a64951bbf91e966d76a58134fd6138628c5738b | 45d444f5c6cc2effb8558b3aa77e7ddb9d4296e9 | refs/heads/master | 2023-05-29T17:19:44.849366 | 2021-02-14T20:09:48 | 2021-02-14T20:09:48 | 338,888,425 | 6 | 1 | BSD-3-Clause | 2023-05-16T22:37:48 | 2021-02-14T19:50:43 | C | UTF-8 | C++ | false | false | 1,029 | hpp | #ifndef _UVPX_FRAME_H_
#define _UVPX_FRAME_H_
#include <cstdio>
#include <memory>
#include "dll_defines.hpp"
namespace uvpx
{
class UVPX_EXPORT Frame
{
private:
unsigned char *m_y;
unsigned char *m_u;
unsigned char *m_v;
size_t m_ySize;
size_t m_uvSize;
size_t m_width;
size_t m_height;
size_t m_displayWidth;
size_t m_displayHeight;
double m_time;
public:
Frame(size_t width, size_t height);
~Frame();
void copy(Frame *dst);
unsigned char *y() const;
unsigned char *u() const;
unsigned char *v() const;
size_t ySize() const;
size_t uvSize() const;
size_t yPitch() const;
size_t uvPitch() const;
size_t width() const;
size_t height() const;
size_t displayWidth() const;
size_t displayHeight() const;
void setTime(double time);
double time() const;
};
}
#endif // _UVPX_FRAME_H_
| [
"s.sincak@gmail.com"
] | s.sincak@gmail.com |
d23d2f014efcb1a74325e66d63078f25af814844 | 7319661bce6b667b9db71d1cafd6bdaee9f1e264 | /code/test/test1.cpp | f607d7a06daef7b3be7e37160575e271030f7238 | [] | no_license | Silmarillli/ObjectOrientedSoftware | cef77e0282b90d7f70ef3791ea57d6d9f1d278f6 | 63319c4d71359e47e4777c6ee00f80eb8435f9ed | refs/heads/master | 2020-03-24T20:54:36.278670 | 2018-07-31T11:16:43 | 2018-07-31T11:16:43 | 142,900,734 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,588 | cpp | #include <string>
#include <ostream>
#include <iostream>
#include <string>
#include "Debug.h"
#include "Instance.h"
using std::cout;
using std::cerr;
using std::endl;
using std::string;
int main(int argc, char *argv[]) {
Ptr<Instance::Manager> manager = shippingInstanceManager();
if (manager == NULL) {
cerr << "Unexpected NULL manager." << endl;
return 1;
}
Ptr<Instance> stats = manager->instanceNew("myStats", "Stats");
if (stats == NULL) {
cerr << "Unexpected NULL stats." << endl;
return 1;
}
Ptr<Instance> conn = manager->instanceNew("myConn", "Conn");
Ptr<Instance> fleet = manager->instanceNew("myFleet", "Fleet");
fleet->attributeIs("Boat, speed", "20");
fleet->attributeIs("Boat, capacity", "1000");
fleet->attributeIs("Boat, cost", "30");
fleet->attributeIs("Truck, speed", "60");
fleet->attributeIs("Truck, capacity", "50");
fleet->attributeIs("Truck, cost", "20");
fleet->attributeIs("Plane, speed", "700");
fleet->attributeIs("Plane, capacity", "200");
fleet->attributeIs("Plane, cost", "60");
Ptr<Instance> customer1 = manager->instanceNew("customer1", "Customer");
Ptr<Instance> port1 = manager->instanceNew("port1", "Port");
Ptr<Instance> port2 = manager->instanceNew("port2", "Port");
Ptr<Instance> port3 = manager->instanceNew("port3", "Port");
Ptr<Instance> planeTerminal1 = manager->instanceNew("planeTerminal1", "Plane terminal");
Ptr<Instance> truckTerminal1 = manager->instanceNew("truckTerminal1", "Truck terminal");
Ptr<Instance> boatTerminal1 = manager->instanceNew("boatTerminal1", "Boat terminal");
Ptr<Instance> planeSegA = manager->instanceNew("planeSegA", "Plane segment");
Ptr<Instance> planeSegB = manager->instanceNew("planeSegB", "Plane segment");
Ptr<Instance> planeSegC = manager->instanceNew("planeSegC", "Plane segment");
Ptr<Instance> planeSegD = manager->instanceNew("planeSegD", "Plane segment");
Ptr<Instance> planeSegE = manager->instanceNew("planeSegE", "Plane segment");
Ptr<Instance> planeSegF = manager->instanceNew("planeSegF", "Plane segment");
Ptr<Instance> planeSegG = manager->instanceNew("planeSegG", "Plane segment");
Ptr<Instance> planeSegH = manager->instanceNew("planeSegH", "Plane segment");
Ptr<Instance> planeSegX = manager->instanceNew("planeSegX", "Plane segment");
Ptr<Instance> truckSegA = manager->instanceNew("truckSegA", "Truck segment");
Ptr<Instance> truckSegB = manager->instanceNew("truckSegB", "Truck segment");
Ptr<Instance> truckSegC = manager->instanceNew("truckSegC", "Truck segment");
Ptr<Instance> truckSegD = manager->instanceNew("truckSegD", "Truck segment");
Ptr<Instance> truckSegX = manager->instanceNew("truckSegX", "Truck segment");
Ptr<Instance> boatSegA = manager->instanceNew("boatSegA", "Boat segment");
Ptr<Instance> boatSegB = manager->instanceNew("boatSegB", "Boat segment");
Ptr<Instance> boatSegC = manager->instanceNew("boatSegC", "Boat segment");
Ptr<Instance> boatSegD = manager->instanceNew("boatSegD", "Boat segment");
Ptr<Instance> boatSegX = manager->instanceNew("boatSegX", "Boat segment");
Ptr<Instance> boatSegY = manager->instanceNew("boatSegY", "Boat segment");
planeSegA->attributeIs("return segment", "planeSegB");
planeSegA->attributeIs("source", "customer1");
planeSegB->attributeIs("source", "planeTerminal1");
planeSegA->attributeIs("expedite support", "yes");
planeSegA->attributeIs("length", "300.0");
planeSegA->attributeIs("difficulty", "4.0");
planeSegB->attributeIs("expedite support", "yes");
planeSegB->attributeIs("length", "400.0");
planeSegB->attributeIs("difficulty", "2.0");
planeSegC->attributeIs("return segment", "planeSegD");
planeSegC->attributeIs("source", "planeTerminal1");
planeSegD->attributeIs("source", "port1");
planeSegC->attributeIs("length", "800");
planeSegD->attributeIs("length", "800");
planeSegE->attributeIs("return segment", "planeSegF");
planeSegE->attributeIs("source", "planeTerminal1");
planeSegF->attributeIs("source", "port2");
planeSegE->attributeIs("length", "1000");
planeSegF->attributeIs("length", "1200");
planeSegE->attributeIs("expedite support", "yes");
planeSegF->attributeIs("expedite support", "yes");
planeSegG->attributeIs("return segment", "planeSegH");
planeSegG->attributeIs("source", "port1");
planeSegH->attributeIs("source", "port2");
planeSegG->attributeIs("length", "2000");
planeSegH->attributeIs("length", "2000");
planeSegX->attributeIs("return segment", "");
planeSegX->attributeIs("source", "planeTerminal1");
planeSegX->attributeIs("length", "1337");
truckSegA->attributeIs("return segment", "truckSegB");
truckSegA->attributeIs("source", "customer1");
truckSegA->attributeIs("length", "250");
truckSegA->attributeIs("difficulty", "4.0");
truckSegB->attributeIs("length", "250.0");
truckSegB->attributeIs("difficulty", "4.0");
truckSegB->attributeIs("source", "truckTerminal1");
truckSegC->attributeIs("return segment", "truckSegD");
truckSegC->attributeIs("source", "truckTerminal1");
truckSegC->attributeIs("expedite support", "yes");
truckSegD->attributeIs("source", "port1");
truckSegC->attributeIs("length", "200");
truckSegD->attributeIs("length", "200");
truckSegX->attributeIs("source", "port3");
truckSegX->attributeIs("length", "500");
boatSegA->attributeIs("return segment", "boatSegB");
boatSegA->attributeIs("source", "port1");
boatSegB->attributeIs("source", "boatTerminal1");
boatSegA->attributeIs("length", "1300");
boatSegB->attributeIs("length", "1400");
boatSegC->attributeIs("return segment", "boatSegD");
boatSegC->attributeIs("source", "boatTerminal1");
boatSegD->attributeIs("source", "port2");
boatSegC->attributeIs("length", "900");
boatSegD->attributeIs("length", "900");
boatSegX->attributeIs("return segment", "boatSegY");
boatSegX->attributeIs("source", "customer1");
boatSegY->attributeIs("source", "");
boatSegX->attributeIs("length", "200");
boatSegY->attributeIs("length", "200");
cout << "LOCATIONS:" << endl;
cout << "Customers: " << stats->attribute("Customer") << endl;
cout << "Ports: " << stats->attribute("Port") << endl;
cout << "Truck terminals: " << stats->attribute("Truck terminal") << endl;
cout << "Boat terminals: " << stats->attribute("Boat terminal") << endl;
cout << "Plane terminals: " << stats->attribute("Plane terminal") << endl;
cout << endl;
cout << "SEGMENTS:" << endl;
cout << "Truck segments: " << stats->attribute("Truck segment") << endl;
cout << "Boat segments: " << stats->attribute("Boat segment") << endl;
cout << "Plane segments: " << stats->attribute("Plane segment") << endl;
cout << endl;
cout << "EXPEDITE SUPPORT:" << endl;
cout << "Exp %: " << stats->attribute("expedite percentage") << endl;
cout << endl;
cout << "FLEET STATS:" << endl;
cout << "Boat speed: " << fleet->attribute("Boat, speed") << endl;
cout << "Boat cost: " << fleet->attribute("Boat, cost") << endl;
cout << "Boat capacity: " << fleet->attribute("Boat, capacity") << endl;
cout << "Plane speed: " << fleet->attribute("Plane, speed") << endl;
cout << "Plane cost: " << fleet->attribute("Plane, cost") << endl;
cout << "Plane capacity: " << fleet->attribute("Plane, capacity") << endl;
cout << "Truck speed: " << fleet->attribute("Truck, speed") << endl;
cout << "Truck cost: " << fleet->attribute("Truck, cost") << endl;
cout << "Truck capacity: " << fleet->attribute("Truck, capacity") << endl;
cout << endl;
cout << "explore customer1 : expedited " << endl;
cout << conn->attribute("explore customer1 : expedited");
cout << endl;
cout << "explore customer1 : cost 150000 time 1000" << endl;
cout << conn->attribute("explore customer1 : cost 150000 time 1000");
cout << endl;
cout << "connect customer1 : port2" << endl;
cout << conn->attribute("connect customer1 : port2");
cout << endl;
cout << "Removing myConn" << endl;
manager->instanceDel("myConn");
cout << "Making secondConn" << endl;
Ptr<Instance> secondConn = manager->instanceNew("secondConn", "Conn");
cout << "connect customer1 : port2" << endl;
cout << secondConn->attribute("connect customer1 : port2");
cout << "Done!" << endl;
return 0;
}
| [
"jishnu.nishaanth@gmail.com"
] | jishnu.nishaanth@gmail.com |
158f28dd90325d169263144298c7b75be50ee2f7 | 0c7e20a002108d636517b2f0cde6de9019fdf8c4 | /Sources/Elastos/Packages/Apps/Calculator/inc/elastos/droid/calculator2/CCalculatorPadLayout.h | 75eeb2ceb72a909b13f61d4d95fc58111cd0edcf | [
"Apache-2.0"
] | permissive | kernal88/Elastos5 | 022774d8c42aea597e6f8ee14e80e8e31758f950 | 871044110de52fcccfbd6fd0d9c24feefeb6dea0 | refs/heads/master | 2021-01-12T15:23:52.242654 | 2016-10-24T08:20:15 | 2016-10-24T08:20:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 533 | h | #ifndef _ELASTOS_DROID_CALCULATOR2_CCALCULATORPADLAYOUT_H__
#define _ELASTOS_DROID_CALCULATOR2_CCALCULATORPADLAYOUT_H__
#include "_Elastos_Droid_Calculator2_CCalculatorPadLayout.h"
#include "elastos/droid/calculator2/CalculatorPadLayout.h"
namespace Elastos {
namespace Droid {
namespace Calculator2 {
CarClass(CCalculatorPadLayout), public CalculatorPadLayout
{
public:
CAR_OBJECT_DECL()
};
} // namespace Calculator2
} // namespace Droid
} // namespace Elastos
#endif // _ELASTOS_DROID_CALCULATOR2_CCALCULATORPADLAYOUT_H__ | [
"bao.rongzhen@kortide.com"
] | bao.rongzhen@kortide.com |
fbb25f84020137d214bef66e31d7972a8c169a6f | 3e2af944f53e2640e147c17acac703af16548c8f | /logic/animation.cpp | 28dcc9267c1304231e9f8bc9a45026684017f9a4 | [] | no_license | jneem/anim | 5d0721342c254907b5bfc0c2609ecdadd209c62a | ce0c362def116046f56abdd79a915c57d998008b | refs/heads/master | 2020-05-30T22:47:15.690850 | 2019-08-31T19:20:34 | 2019-08-31T19:20:34 | 189,998,899 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,486 | cpp | #include "animation.h"
#include "changingpath.h"
#include "snippet.h"
#include <QDebug>
#include <QPainterPath>
Animation::Animation(QObject *parent) : QObject(parent)
{
}
// After adding a snippet to an animation, you must never modify it again. Otherwise, updatedPaths might not be correct.
void Animation::addSnippet(Snippet *s)
{
Q_ASSERT(!snippets.contains(s));
snippets.insert(s);
emit snippetAdded(s);
}
void
Animation::removeSnippet(Snippet *s)
{
Q_ASSERT(snippets.contains(s));
snippets.remove(s);
emit snippetRemoved(s);
}
QVector<RenderedPath>
Animation::updatedPaths(qint64 prev_t, qint64 cur_t)
{
QVector<RenderedPath> ret;
// TODO: we're looping over all snippets here, but we could be more efficient.
for (Snippet *s : snippets) {
QVector<RenderedPath> v;
if (dirty_snippets.contains(s)) {
v = s->changedPaths(s->startTime(), cur_t);
} else {
v = s->changedPaths(prev_t, cur_t);
}
ret.append(std::move(v));
}
dirty_snippets.clear();
return ret;
}
qint64 Animation::endTime() const
{
// TODO: this is inefficient
qint64 ret = 0;
for (Snippet *s : snippets) {
ret = std::max(ret, s->endTime());
}
return ret;
}
void Animation::warpSnippet(Snippet *s, qint64 old_time, qint64 new_time)
{
Q_ASSERT(snippets.contains(s));
dirty_snippets.insert(s);
s->addLerp(old_time, new_time);
emit snippetChanged(s);
}
| [
"joeneeman@gmail.com"
] | joeneeman@gmail.com |
e7b7499a41722c463f91fa6bdcc8b5aedc013221 | c683a0aa9853c826197eac66d42e1a1f1901afec | /Engine/Engine/Core/Bitmap.cpp | 91a686d2b741adc90b7585c4a81688d5bb4ace2d | [] | no_license | poonasp257/Ping-pong | 1cb17f403bd3742422691fe0ffca916fafa5fee8 | 54ce8cc053b1aac414a4127867bbc866065d283a | refs/heads/master | 2020-09-01T16:33:46.093080 | 2019-11-11T03:47:16 | 2019-11-11T03:47:16 | 219,004,934 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,982 | cpp | #include "stdafx.h"
Bitmap::Bitmap() : vertexBuffer(nullptr), indexBuffer(nullptr),
texture(std::make_shared<Texture>()){
}
Bitmap::~Bitmap() {
texture.reset();
if (indexBuffer) {
indexBuffer->Release();
indexBuffer = nullptr;
}
if (vertexBuffer) {
vertexBuffer->Release();
vertexBuffer = nullptr;
}
}
bool Bitmap::initialize(ID3D11Device* device, int screenWidth, int screenHeight, const WCHAR* textureFilename, int
bitmapWidth, int bitmapHeight) {
bool result;
this->screenWidth = screenWidth;
this->screenHeight = screenHeight;
this->bitmapWidth = bitmapWidth;
this->bitmapHeight = bitmapHeight;
previousPosX = -1;
previousPosY = -1;
result = initializeBuffers(device);
if (!result) return false;
result = loadTexture(device, textureFilename);
if (!result) return false;
return true;
}
bool Bitmap::render(ID3D11DeviceContext* deviceContext, int positionX, int positionY) {
bool result = updateBuffers(deviceContext, positionX, positionY);
if (!result) return false;
renderBuffers(deviceContext);
return true;
}
int Bitmap::getIndexCount() const {
return indexCount;
}
ID3D11ShaderResourceView* Bitmap::getTexture() {
return texture->getTexture();
}
bool Bitmap::initializeBuffers(ID3D11Device* device) {
VertexType* vertices;
unsigned long* indices;
D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
D3D11_SUBRESOURCE_DATA vertexData, indexData;
HRESULT result;
vertexCount = 6;
indexCount = vertexCount;
vertices = new VertexType[vertexCount];
if (!vertices) return false;
indices = new unsigned long[indexCount];
if (!indices) return false;
memset(vertices, 0, (sizeof(VertexType) * vertexCount));
for (int i = 0; i < indexCount; i++) {
indices[i] = i;
}
vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexBufferDesc.ByteWidth = sizeof(VertexType) * vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &vertexBuffer);
if (FAILED(result)) return false;
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long) * indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
indexData.pSysMem = indices;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
result = device->CreateBuffer(&indexBufferDesc, &indexData, &indexBuffer);
if (FAILED(result)) return false;
delete[] vertices;
vertices = 0;
delete[] indices;
indices = 0;
return true;
}
bool Bitmap::updateBuffers(ID3D11DeviceContext* deviceContext, int positionX, int positionY) {
float left, right, top, bottom;
VertexType* vertices;
D3D11_MAPPED_SUBRESOURCE mappedResource;
VertexType* verticesPtr;
HRESULT result;
if ((positionX == previousPosX)
&& (positionY == previousPosY)) return true;
previousPosX = positionX;
previousPosY = positionY;
left = (float)((screenWidth / 2) * -1) + (float)positionX;
right = left + (float)bitmapWidth;
top = (float)(screenHeight / 2) - (float)positionY;
bottom = top - (float)bitmapHeight;
vertices = new VertexType[vertexCount];
if (!vertices) return false;
vertices[0].position = D3DXVECTOR3(left, top, 0.0f);
vertices[0].texture = D3DXVECTOR2(0.0f, 0.0f);
vertices[1].position = D3DXVECTOR3(right, bottom, 0.0f);
vertices[1].texture = D3DXVECTOR2(1.0f, 1.0f);
vertices[2].position = D3DXVECTOR3(left, bottom, 0.0f);
vertices[2].texture = D3DXVECTOR2(0.0f, 1.0f);
vertices[3].position = D3DXVECTOR3(left, top, 0.0f);
vertices[3].texture = D3DXVECTOR2(0.0f, 0.0f);
vertices[4].position = D3DXVECTOR3(right, top, 0.0f);
vertices[4].texture = D3DXVECTOR2(1.0f, 0.0f);
vertices[5].position = D3DXVECTOR3(right, bottom, 0.0f);
vertices[5].texture = D3DXVECTOR2(1.0f, 1.0f);
result = deviceContext->Map(vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result)) return false;
verticesPtr = (VertexType*)mappedResource.pData;
memcpy(verticesPtr, (void*)vertices, (sizeof(VertexType) * vertexCount));
deviceContext->Unmap(vertexBuffer, 0);
delete[] vertices;
vertices = 0;
return true;
}
void Bitmap::renderBuffers(ID3D11DeviceContext* deviceContext) {
unsigned int stride;
unsigned int offset;
stride = sizeof(VertexType);
offset = 0;
deviceContext->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset);
deviceContext->IASetIndexBuffer(indexBuffer, DXGI_FORMAT_R32_UINT, 0);
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
bool Bitmap::loadTexture(ID3D11Device* device, const WCHAR* filename) {
bool result = texture->initialize(device, filename);
if (!result) return false;
return true;
} | [
"poonasp257@gmail.com"
] | poonasp257@gmail.com |
11473bdeb4be52359799066dc2bfba6c54b171e2 | 6ea50d800eaf5690de87eea3f99839f07c662c8b | /ver.0.14.0/ChestScreen.h | e58072107dcb2e9b276edc45046e7c41fbdede9c | [] | no_license | Toku555/MCPE-Headers | 73eefeab8754a9ce9db2545fb0ea437328cade9e | b0806aebd8c3f4638a1972199623d1bf686e6497 | refs/heads/master | 2021-01-15T20:53:23.115576 | 2016-09-01T15:38:27 | 2016-09-01T15:38:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,183 | h | #pragma once
class ChestScreen{
public:
void _buttonClicked(Button &);
void _controllerDirectionChanged(int,StickDirection);
void _controllerDirectionHeld(int,StickDirection);
void _drawSlotItemAt(Tessellator &,ItemInstance const*,int,int,bool);
void _entityCheck(void);
void _getChestEntity(void);
void _getContainer(void);
void _getInventory(void);
void _handleAddItem(FillingContainer *,FillingContainer *,int);
void _handleBulkItemMovementRequest(Touch::InventoryPane &);
void _handleRenderPane(Touch::InventoryPane &,Tessellator &,int,int,float);
void _init(void);
void _setupPane(void);
void _updateSelectedIndexes(StickDirection);
void addItem(Touch::InventoryPane &,int);
void containerChanged(int);
void getItems(Touch::InventoryPane const&);
void handleBackEvent(bool);
void handleButtonPress(short);
void handleButtonRelease(short);
void handleScrollWheel(float);
void init(void);
void isAllowed(int);
void onInternetUpdate(void);
void render(int,int,float);
void renderGameBehind(void);
void setupPositions(void);
void tick(void);
void ~ChestScreen();
void ~ChestScreen();
};
| [
"sinigami3427@gmail.com"
] | sinigami3427@gmail.com |
a86fb49db5ea4e893d2c88cb9af041ab78f86102 | 73c71311c08cb8d58b75dcd06c7a31f8b097b956 | /ewk/unittest/utc_blink_ewk_view_web_application_icon_urls_get_func.cpp | 615359cb894c1a51e8a1d2abf3fc4f2116268c4d | [
"BSD-3-Clause"
] | permissive | crosswalk-project/chromium-efl | 47927f6e17c0553d3756d9b9ca5c3e783b3641b8 | 3c1af10d16e2df57e8584378b79f0ff3335eb99d | refs/heads/efl/crosswalk-10/39.0.2171.19 | 2023-03-23T12:34:43.754226 | 2014-12-15T23:47:39 | 2014-12-15T23:47:39 | 27,436,290 | 9 | 14 | null | 2015-01-21T08:10:49 | 2014-12-02T14:33:10 | C++ | UTF-8 | C++ | false | false | 2,809 | cpp | // Copyright 2014 Samsung Electronics. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "utc_blink_ewk_base.h"
#include <map>
class utc_blink_ewk_view_web_application_icon_urls_get : public utc_blink_ewk_base
{
protected:
void LoadFinished(Evas_Object *)
{
EventLoopStop(Success);
}
static void webAppUrlsGetCallback(Eina_List *urls, utc_blink_ewk_view_web_application_icon_urls_get *owner)
{
ASSERT_TRUE(NULL != owner);
utc_message("[webAppUrlsGetCallback] :: ");
ASSERT_EQ(owner->expectedUrls.size(), eina_list_count(urls));
Eina_List *l = 0;
void *d = 0;
EINA_LIST_FOREACH(urls, l, d) {
const char* size = ewk_web_application_icon_data_size_get(static_cast<Ewk_Web_App_Icon_Data *>(d));
ASSERT_TRUE(NULL != size);
const char* url = ewk_web_application_icon_data_url_get(static_cast<Ewk_Web_App_Icon_Data *>(d));
ASSERT_TRUE(NULL != url);
utc_message("[URLS]: %s ; %s", size, url);
ASSERT_STREQ(owner->GetResourceUrl(owner->expectedUrls[size].c_str()).c_str(), url);
}
owner->EventLoopStop(Success);
}
protected:
std::map<std::string, std::string> expectedUrls;
static const char * const webAppUrlsPage;
static const char * const noUrlsPage;
};
const char * const utc_blink_ewk_view_web_application_icon_urls_get::webAppUrlsPage = "ewk_view_web_application/web_app_urls_get.html";
const char * const utc_blink_ewk_view_web_application_icon_urls_get::noUrlsPage = "<html><body></body></html>";
TEST_F(utc_blink_ewk_view_web_application_icon_urls_get, WEB_APP_URLS_PAGE)
{
ASSERT_EQ(EINA_TRUE, ewk_view_url_set(GetEwkWebView(), GetResourceUrl(webAppUrlsPage).c_str()));
ASSERT_EQ(Success, EventLoopStart());
expectedUrls["64x64"] = "ewk_view_web_application/tizen-icon1.png";
expectedUrls["128x128"] = "ewk_view_web_application/tizen-icon2.png";
expectedUrls["144x144"] = "ewk_view_web_application/tizen-icon3.png";
ASSERT_EQ(EINA_TRUE, ewk_view_web_application_icon_urls_get(GetEwkWebView(),
(void(*)(Eina_List*,void*))webAppUrlsGetCallback,
this));
ASSERT_EQ(Success, EventLoopStart());
}
TEST_F(utc_blink_ewk_view_web_application_icon_urls_get, NO_URLS_PAGE)
{
ASSERT_EQ(EINA_TRUE, ewk_view_html_string_load(GetEwkWebView(), noUrlsPage, 0, 0));
ASSERT_EQ(Success, EventLoopStart());
ASSERT_EQ(EINA_TRUE, ewk_view_web_application_icon_urls_get(GetEwkWebView(),
(void(*)(Eina_List*,void*))webAppUrlsGetCallback,
this));
ASSERT_EQ(Success, EventLoopStart());
}
| [
"a1.gomes@samsung.com"
] | a1.gomes@samsung.com |
504a63c4bacd6e8bc3aeb11828eaf22dfbb91878 | 5094f4c1029ea2a1e525a82c8c6ed1bd1119bea5 | /test.cc | 48e78ce447662268c1c49b5871bea9fce8086c3e | [
"BSD-3-Clause"
] | permissive | xuefeng529/evcpp | d3dcef90392735d8fece7f845abf04e6f289a129 | bccf9b47830ad6f98223e2166321b3609164fbc6 | refs/heads/master | 2020-06-12T17:30:42.411685 | 2015-02-25T07:21:59 | 2015-02-25T07:21:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 513 | cc | // Copyright 2010, Shuo Chen. All rights reserved.
// http://github.com/chenshuo/evcpp
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
#include "evcpp.h"
void onConnect(evcpp::TcpConnectionPtr conn)
{
printf("onConnect %zd\n", conn.use_count());
}
int main()
{
evcpp::EventLoop loop;
evcpp::Listener listener(&loop, 1234);
listener.setNewConnectionCallback(onConnect);
loop.loop();
}
| [
"chenshuo@chenshuo.com"
] | chenshuo@chenshuo.com |
c2283514b616badbd5d4dfdb8a6dc5e5b4cd39ea | 50aa6227fb65ef56e230d890711ad248a2a6634f | /Saturn/include/Graphics/Sprite.hpp | e460abf383d31b0744e8477e85e7453521f44dd7 | [
"MIT"
] | permissive | Tackwin/BossRoom | 7b63fb354a9261fa56306bbb8cbb0fa3c34ea1ad | ecad5853e591b9edc54e75448547e20e14964f72 | refs/heads/master | 2021-01-19T19:52:17.076149 | 2019-01-10T04:33:27 | 2019-01-10T04:33:27 | 67,225,299 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | hpp | #pragma once
#include "Concepts/Delete.hpp"
#include "FrameBuffer.hpp"
#include "Transform.hpp"
#include "Texture.hpp"
#include "VAO.hpp"
struct SpriteInfo {
Texture* texture;
Transform transform;
VAO mesh;
};
class Sprite : NoCopy {
public:
Sprite();
Sprite(const Sprite&& that);
Sprite& operator=(const Sprite&& that);
void set_texture(const std::string& key);
void render(const FrameBuffer& target) const;
private:
SpriteInfo _info;
}; | [
"tackwinbrx@hotmail.fr"
] | tackwinbrx@hotmail.fr |
a6d6020788fe4312a4bcbeea600aaf347b030c59 | e2b51bd4959f9ff9a5d946355401c2b45d866c66 | /V21/Prediction.h | 2096ba182ce8bc8d67513e5e34a2ac53aa5c6943 | [] | no_license | BrandTime/Vault21 | 91be552cfffa72b825fe81343150b350cb4a735e | ed85ab7a36b9ede72bedbf3d940e5280bc9f678f | refs/heads/master | 2023-03-17T11:32:53.637385 | 2021-02-12T12:34:41 | 2021-02-12T12:34:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,168 | h | #pragma once
#include "stdafx.h"
#include "ObjectManager.h"
#include "NetClient.h"
#include "Geometry.h"
#include "ManagerTemplate.h"
namespace HACKUZAN {
class PredOutPut
{
public:
Vector3 CastPosition;
Vector3 UnitPosition;
std::vector<GameObject*> CollisionObjects;
HitChance HitsChance = HitChance::Immobile;
PredOutPut(Vector3 castposition, Vector3 unitposition, std::vector<GameObject*> collisionobjects, HitChance hitchance)
{
CastPosition = castposition;
UnitPosition = unitposition;
CollisionObjects = collisionobjects;
HitsChance = hitchance;
}
PredOutPut() {};
};
inline Vector3 PredGetUnitPosition(GameObject* target, float delay)
{
delay = delay + NetClient::Instance->GetPing() / 1000;
std::vector<Vector3> waypoint = target->GetWaypointList();
if (waypoint.size() == 1)
return waypoint.front();
if (target->IsDashing() && PredAllDashData[target->NetworkId] != nullptr)
{
auto data = PredAllDashData[target->NetworkId];
float dashdistance = delay * data->dashSpeed;
return dashdistance >= Distance(target, data->end) ? data->end
: Extend(target->Position, data->end, dashdistance);
}
float distance = target->MoveSpeed * delay;
for (int i = 1; i < waypoint.size(); i = i + 1)
{
float waydistance = Distance(waypoint[i - 1], waypoint[i]);
if (waydistance >= distance)
{
return Extend(waypoint[i - 1], waypoint[i], distance);
}
if (i = waypoint.size() - 1)
return waypoint[i];
distance = distance - waydistance;
}
return target->Position;
}
inline vector<GameObject*> PredGetCollisions(Vector3 From, Vector3 To, int ColiFlag, GameObject* target, float spelldelay, float spellspeed, float spellradius)
{
vector<GameObject*> Collisons;
if (ColiFlag & kCollidesWithHeroes || ColiFlag & kCollidesWithMinions)
{
//GGame->PrintChat("a");
SArray<GameObject*> Heroes;
SArray<GameObject*> Minions;
SArray<GameObject*> AllUnits;
auto aibase_list = HACKUZAN::GameObject::GetAIBases();
for (size_t i = 0; i < aibase_list->size; i++)
{
auto unit = aibase_list->entities[i];
if (unit && unit->Hero() && unit->IsAlly() && unit->Alive() && unit->NetworkId != target->NetworkId) {
if (ColiFlag & kCollidesWithHeroes)
{
Heroes.Add(unit);
}
}
if (unit && unit->Minion() && unit->IsAlly() && unit->Alive() && unit->NetworkId == target->NetworkId) {
if (ColiFlag & kCollidesWithMinions)
{
if (Distance(From, unit->Position) + 500 <= 600) {
Minions.Add(unit);
}
}
}
}
AllUnits.AddRange(Heroes);
AllUnits.AddRange(Minions);
for (GameObject* hero : AllUnits.elems)
{
float delay = spelldelay + Distance(From, hero->Position) / spellspeed;
Vector3 pred = PredGetUnitPosition(hero, delay);
float mindistance = hero->GetBoundingRadius() + spellradius / 2 + 25;
if (Distance(hero->Position, From, To, true) < mindistance
|| Distance(pred, From, To, true) < mindistance
|| GetSegmentSegmentIntersections(From, To, hero->Position, pred))
{
Collisons.push_back(hero);
}
}
}
if (ColiFlag & kCollidesWithYasuoWall)
{
GameObject* Wall;
SArray<GameObject*> AllUnits;
auto aibase_list = HACKUZAN::GameObject::GetAIBases();
for (size_t i = 0; i < aibase_list->size; i++)
{
auto unit = aibase_list->entities[i];
if (unit) {
AllUnits.Add(unit);
}
}
AllUnits = AllUnits.Where([&](GameObject* i) {return i != nullptr && Contains(i->Name, "w_windwall_enemy_"); });
if (AllUnits.Any()) {
Wall = AllUnits.FirstOrDefault();
float length = 300 + 5 * 5;
Vector3 direction = Pendicular(Normalize((Wall->Position - PredLastYasuoWallCastPos)));
Vector3 WallStart = ToVec3((ToVec2(Wall->Position) + length * ToVec2(direction) / 2));
Vector3 WallEnd = ToVec3((ToVec2(Wall->Position) - length * ToVec2(direction) / 2));
float mindistance = 50 + spellradius / 2 + 50;
if (Distance(WallStart, From, To, true) < mindistance
|| Distance(WallEnd, From, To, true) < mindistance
|| GetSegmentSegmentIntersections(From, To, WallStart, WallEnd))
{
Collisons.push_back(Wall);
}
}
}
return Collisons;
}
inline PredOutPut PredGetPrediction(Vector3 startpos, float spellspeed, float spellrange, float spelldelay, GameObject* target, int collisionFlags, float spellradius)
{
if (target != nullptr) {
PredOutPut output;
output.HitsChance = HitChance::Impossible;
std::vector<Vector3> waypoint = target->GetWaypointList();
Vector3 RangeCheckFrom = startpos;
if (waypoint.size() == 1)
{
output.CastPosition = waypoint[0];
output.UnitPosition = waypoint[0];
output.HitsChance = HitChance::High;
}
float speed = target->IsDashing() && PredAllDashData[target->NetworkId] != nullptr ? PredAllDashData[target->NetworkId]->dashSpeed : target->MoveSpeed;
float realspelldelay = spelldelay; /*> spell->Radius() / 2.f / speed ? spell->GetDelay() - spell->Radius() / 2.f / speed : 0.f;*/
float time = 0.f;
for (int i = 1; i < waypoint.size(); i = i + 1)
{
float distance = Distance(waypoint[i - 1], waypoint[i]);
for (float j = 0; j <= distance; j = j + 5)
{
Vector3 Position = Extend(waypoint[i - 1], waypoint[i], j);
//time = Vector3(Position - RangeCheckFrom).Length() / spellspeed;
//time += realspelldelay;
float spelldistance = Distance(RangeCheckFrom, Position);
float targettime = time + j / speed;
float spelltime = realspelldelay + spelldistance / spellspeed;
if (abs(targettime - spelltime) < 10 / target->MoveSpeed)
{
output.CastPosition = Position;
output.UnitPosition = Position;
output.HitsChance = HitChance::High;
goto ABC;
}
}
time = time + distance / target->MoveSpeed;
}
ABC:
if (output.HitsChance > HitChance::Impossible)
{
if (PredAllNewPathTicks[target->NetworkId] != 0 && ClockFacade::GameTickCount() - PredAllNewPathTicks[target->NetworkId] < 100)
output.HitsChance = HitChance::VeryHigh;
if (Distance(target, RangeCheckFrom) <= 300)
output.HitsChance = HitChance::VeryHigh;
if (target->IsDashing())
output.HitsChance = HitChance::Dashing;
else if (waypoint.size() == 1 && (target->FindBuffType(BuffType::Stun) || target->FindBuffType(BuffType::Knockup) || target->FindBuffType(BuffType::Knockback) || target->FindBuffType(BuffType::Charm) || target->FindBuffType(BuffType::Flee) ||
target->FindBuffType(BuffType::Snare) || target->FindBuffType(BuffType::Fear) || target->FindBuffType(BuffType::Taunt) || target->FindBuffType(BuffType::Polymorph)))
output.HitsChance = HitChance::Immobile;
if (Distance(output.CastPosition, RangeCheckFrom) > spellrange && spellrange != 0)
{
output.HitsChance = HitChance::OutOfRange;
}
auto collisionobjects = PredGetCollisions(RangeCheckFrom, output.CastPosition, collisionFlags, target, spelldelay, spellspeed, spellradius);
if (collisionobjects.size() != 0)
{
output.HitsChance = HitChance::Collision;
}
output.CollisionObjects = collisionobjects;
return output;
}
output.CastPosition = waypoint.back();
output.UnitPosition = waypoint.back();
output.HitsChance = HitChance::Impossible;
output.CollisionObjects = PredGetCollisions(RangeCheckFrom, output.CastPosition, collisionFlags, target, spelldelay, spellspeed, spellradius);
return output;
}
}
//cast
inline bool CastPrediction(kSpellSlot slot, Vector3 startpos, float spellspeed, float spellrange, float spellradius, float spelldelay, GameObject* target, int collFlags, HitChance MinHitChance = HitChance::Medium)
{
PredOutPut pred = PredGetPrediction(startpos, spellspeed, spellrange, spelldelay, target, collFlags, spellradius);
if (pred.HitsChance >= MinHitChance)
{
ObjectManager::Player->CastSpellPos(slot, (DWORD)ObjectManager::Player, pred.CastPosition);
Draw.Line(startpos, pred.CastPosition, 2, IM_COL32(255, 255, 69, 255));
Draw.DrawCircle3D(pred.CastPosition, 30, spellradius, IM_COL32(255, 255, 69, 255));
return true;
}
return false;
}
} | [
"53059806+walangtayoexb@users.noreply.github.com"
] | 53059806+walangtayoexb@users.noreply.github.com |
2749e6df919ca99ae8c9cfd2132574d3707878bc | 8b877fd49a93d461588b85918728114effe2a847 | /GUI/GUIwithconnections/WidgetsUsed/Compass/compass.cpp | 096f46ee4237f7d02bf66ecccb6546c296f6a868 | [] | no_license | NaviPolytechnique/GUI | 301da3ef0ab9154a0853d058519b5abf6211d5ae | ae85f8bed7b815a7d2d3208ab561ceb22e7133aa | refs/heads/master | 2016-08-12T16:09:57.381982 | 2016-03-23T21:18:55 | 2016-03-23T21:18:55 | 44,568,567 | 3 | 1 | null | 2015-12-22T10:41:57 | 2015-10-19T22:47:53 | C++ | UTF-8 | C++ | false | false | 2,008 | cpp | #include "compass.h"
#include "ui_compass.h"
Compass::Compass(QWidget *parent) :
QDialog(parent),
ui(new Ui::Compass)
{
ui->setupUi(this);
mCompassGauge = new QcGaugeWidget;
mCompassGauge->addBackground(79);
QcBackgroundItem *bkg1 = mCompassGauge->addBackground(72);
bkg1->clearrColors();
bkg1->addColor(0.1,Qt::black);
bkg1->addColor(1.0,Qt::white);
QcBackgroundItem *bkg2 = mCompassGauge->addBackground(68);
bkg2->clearrColors();
bkg2->addColor(0.1,Qt::white);
bkg2->addColor(1.0,Qt::black);
QcLabelItem *w = mCompassGauge->addLabel(60);
w->setText("W");
w->setAngle(0);
w->setColor(Qt::white);
QcLabelItem *n = mCompassGauge->addLabel(60);
n->setText("N");
n->setAngle(90);
n->setColor(Qt::white);
QcLabelItem *e = mCompassGauge->addLabel(60);
e->setText("E");
e->setAngle(180);
e->setColor(Qt::white);
QcLabelItem *s = mCompassGauge->addLabel(60);
s->setText("S");
s->setAngle(270);
s->setColor(Qt::white);
QcDegreesItem *deg = mCompassGauge->addDegrees(50);
deg->setStep(5);
deg->setMaxDegree(270);
deg->setMinDegree(-75);
deg->setColor(Qt::white);
mCompassNeedle = mCompassGauge->addNeedle(60);
mCompassNeedle->setNeedle(QcNeedleItem::CompassNeedle);
mCompassNeedle->setValueRange(0,360);
mCompassNeedle->setMaxDegree(360);
mCompassNeedle->setMinDegree(0);
mCompassGauge->addBackground(6);
mCompassGauge->addGlass(68);
ui->compass->addWidget(mCompassGauge);
}
void Compass::MAJCompass(QString DroneStatusMAJ){
//roll
QStringList LED=DroneStatusMAJ.split(",");
QString s1yaw=LED[2];
QStringList s2yaw=s1yaw.split( ".");
QString s3yaw=s2yaw.at(0);
int yaw=s3yaw.toInt();
while (yaw<(-90)|| yaw > 270 ){
if (yaw<(-90)){
yaw+=360;
}
else{
yaw-=360;
}
}
mCompassNeedle->setCurrentValue(yaw+90);
}
Compass::~Compass()
{
delete ui;
}
| [
"mr.pierrely@gmail.com"
] | mr.pierrely@gmail.com |
75aeb5c350c6ca7a3d61b6653dcdcd76a4dda1db | 9c677a1775705f7c8f683d1f89d47e9ed15a32ee | /ACM/天梯训练赛/天梯训练赛1/a.cpp | 626edcede3d0f320c98d3aa4f93c0bb61497865a | [] | no_license | nc-77/algorithms | 16e00a0f8ce60f9b998b9ee4ccc69bcfdb5aa832 | ced943900a2756a76b2c197002010dc9e08b79c4 | refs/heads/main | 2023-05-26T20:11:25.762015 | 2021-06-08T07:16:30 | 2021-06-08T07:16:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 712 | cpp | #include<bits/stdc++.h>
#define ll long long int
using namespace std;
ll gcd(ll x,ll y)
{
return y==0? x:gcd(y,x%y);
}
int main()
{
int n;
cin>>n;
ll x1,y1;
scanf("%lld/%lld",&x1,&y1);
n--;
while(n--)
{
ll x2,y2;
scanf("%lld/%lld",&x2,&y2);
//cout<<x1<<y1<<x2<<y2<<endl;
ll lcm=y1*y2/gcd(y1,y2);
x1=x1*lcm/y1+x2*lcm/y2;
y1=lcm;
if(x1)
{
ll g=gcd(fabs(x1),fabs(y1));
x1=x1/g;
y1=y1/g;
}
}
if(x1)
{
ll g=gcd(fabs(x1),fabs(y1));
x1=x1/g;
y1=y1/g;
}
ll zs=x1/y1;
x1=x1-zs*y1;
if(zs&&x1)
cout<<fabs(zs)<<" "<<x1<<"/"<<y1<<endl;
if(zs&&!x1) cout<<zs<<endl;
if(!zs&&x1) cout<<x1<<"/"<<y1<<endl;
else if(!zs&&!x1) cout<<"0"<<endl;
}
| [
"291993554@qq.com"
] | 291993554@qq.com |
fe883928796c1fd961e88a56d7ef30a692af7dcb | e3adfda1a3873b2eeec04eed34a9e0cf007760a7 | /CRM-system/CRM-system_client/include/CRM-system_client.h | 8d0cf12e5b5c5befeb0a5cef43f159802239cfd1 | [
"MIT"
] | permissive | polupanovaanna/CRM-system | 0ebc9a6eae68f6c1a994396bf929dd94144fee41 | d08e7b37e24ec514a45ea664d4ad775bed085480 | refs/heads/master | 2023-05-04T14:39:41.506201 | 2021-05-28T20:40:34 | 2021-05-28T20:40:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,413 | h | #ifndef CRM_SYSTEM_STORAGEDATABASE_H
#define CRM_SYSTEM_STORAGEDATABASE_H
#include <iostream>
#include <memory>
#include <string>
#include <cstdio>
#include <vector>
#include "people.h"
#include <grpc++/grpc++.h>
#include "CRM-system.grpc.pb.h"
#include <stdexcept>
#include "storage.h"
namespace repositories {
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using namespace crm_system;
struct DataExistsException : StorageException{
explicit DataExistsException(const std::string& arg);
};
struct DataNotExistsException : StorageException{
explicit DataNotExistsException(const std::string& arg);
};
struct ManagerException : std::runtime_error{
explicit ManagerException(const std::string& arg);
};
struct ClientException : std::runtime_error{
explicit ClientException(const std::string& arg);
};
struct ManagerDataBase_client : ManagerRepository {
private:
std::unique_ptr<CRMService::Stub> stub_;
public:
ManagerDataBase_client();
// ManagerDataBase_client(std::shared_ptr<Channel> channel);
void addManager(const people::Manager &manager) const override;
void getManager(people::Manager &inputManager, const std::string &inputEmail) const override;
[[nodiscard]] bool isCorrectPassword(const std::string &inputEmail, const std::string &inputPassword) const override;
std::string managerInfo(people::Manager &manager) const override;
~ManagerDataBase_client() override = default;
};
struct ClientDataBase_client : ClientRepository {
private:
std::unique_ptr<CRMService::Stub> stub_;
public:
ClientDataBase_client();
// ClientDataBase_client(std::shared_ptr<Channel> channel);
void addClient(const people::Client &client, const std::string &managerEmail) const override;
void deleteClient(const std::string &clientEmail, const std::string &managerEmail) const override;
void updateAllClients(people::Manager &manager) const override;
[[nodiscard]] std::string clientInfo(const people::Client &client) const override;
[[nodiscard]] std::vector<std::string> getDealProcess(const people::Client &client) const override;
~ClientDataBase_client() override = default;
};
} // namespace repositories
#endif //CRM_SYSTEM_STORAGEDATABASE_H
| [
"ddemon2002@mail.ru"
] | ddemon2002@mail.ru |
017a66f4d9898012e3124efef99454570e89cd31 | 463a2089420c04245a715d171ad490e2e6abaedd | /leetcode/e-m-h/easy/easy167.cpp | fd2545cd782f4e419566fb6ec64373e6e4c8d55f | [] | no_license | faa678/coding | 9c86ec2936b17d426fe2d03708116042950f46ef | 0b43fbb6397b6e8ac335d2f7e20d7fdda247fc34 | refs/heads/master | 2022-01-30T14:09:34.213640 | 2022-01-03T13:17:08 | 2022-01-03T13:17:08 | 220,933,942 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,155 | cpp | /*
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
*/
#include<iostream>
#include<vector>
using namespace std;
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> empty;
int len = numbers.size();
if(len < 2)return empty;
vector<int> result;
int i = 0, j = len - 1;
while(i < j){
if(numbers[i] + numbers[j] == target){
result.emplace_back(i);
result.push_back(j);
return result;
}
else if(numbers[i] + numbers[j] < target) i++;
else j--;
}
return empty;
}
//result.emplace_back()更加高效 | [
"2532506036@qq.com"
] | 2532506036@qq.com |
4bb94af72fc98157a4f731aa605f9edc816b5311 | e8307413bff4b74a4949597d130738b85ad61e0e | /PlateDemo/mythread.cpp | 2abda93884a7e0aea110024aadcc5032ee7dc750 | [] | no_license | isliulin/SCPark | 3ec0b5ddf1ef31b434965b86d70b4ba69851ba40 | e9e83072fa35eff672585fcf3dae94eaee953413 | refs/heads/master | 2021-05-30T04:59:37.253340 | 2016-01-08T02:56:14 | 2016-01-08T02:56:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 328 | cpp | #include "mythread.h"
#include "MainWindow.h"
CMyThread::CMyThread(QObject *parent) :
QThread(parent)
{
}
void CMyThread::run( )
{
MainWindow* pMulti = ( MainWindow* ) parent( );
quint8 data[ 704 * 576 * 4 ];
ULONG lSize = 704 * 576 * 4;
while ( true ) {
pMulti->Recognize( data, lSize );
}
}
| [
"Anne081031@hotmail.com"
] | Anne081031@hotmail.com |
0f8983822ec6ea0ee29dff236908887888dc74cd | 013c7539d6fb9ffc30740a33691aac902b11b06e | /practive/NCU/18summer/7.17/D.cpp | 9d3651a6d9a0fa8415559f0fc81eb199206ad2e0 | [] | no_license | eternity6666/life-in-acm | 1cc4ebaa65af62219130d53c9be534ad31b361e2 | e279121a28e179d0de33674b9ce10c6763d78d32 | refs/heads/master | 2023-04-13T07:50:58.231217 | 2023-04-09T09:23:24 | 2023-04-09T09:23:24 | 127,930,873 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 901 | cpp | #include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <set>
#include <map>
#include <fstream>
#include <sstream>
using namespace std;
// #define usefre
double calculate1(int);
double calculate2(int);
int main()
{
#ifdef usefre
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
int t;
cin>>t;
while(t--)
{
int numCase=0;
int m,n;
while(cin>>n>>m)
{
cout<<"Case #"<<++numCase<<": ";
double nAns=calculate1(n);
double mAns=calculate2(m);
printf("%.6lf %.6lf\n",nAns,mAns);
}
}
}
double calculate1(int n)
{
double ans=0;
if(n == 1) ans = 1.0;
else ans=1.0/2.0;
return ans;
}
double calculate2(int m)
{
double ans=0;
ans=(double)(1+m)/2/m;
return ans;
} | [
"1462928058@qq.com"
] | 1462928058@qq.com |
be26d26c67bdb2e48add41007aa9e893e0a126cc | 4d49d4d59c9517fe99884cd69ad88644265c6755 | /week3/Group3/boj4779_seongbin9786.cpp | a1015c8d5eac148327b7f5d8158dd0049782f5b0 | [] | no_license | all1m-algorithm-study/2021-1-Algorithm-Study | 3f34655dc0a3d8765143f4230adaa96055d13626 | 73c7cac1824827cb6ed352d49c0ead7003532a35 | refs/heads/main | 2023-06-03T18:45:28.852381 | 2021-06-11T06:28:44 | 2021-06-11T06:28:44 | 348,433,854 | 8 | 16 | null | 2021-06-11T06:28:45 | 2021-03-16T17:23:37 | Python | UTF-8 | C++ | false | false | 2,576 | cpp | #include <iostream>
#include <math.h>
/*
[Silver 3]
칸토어 집합
칸토어 집합은 0과 1사이의 실수로 이루어진 집합으로,
구간 [0, 1]에서 시작해서 각 구간을 3등분하여 가운데
구간을 반복적으로 제외하는 방식으로 만든다.
집합이 유한
칸토어 집합의 근사
----
걍 - 패턴 구하는 재귀 문제이다.
제거되는 형태가 이진 탐색 (중간은 제거되니깐 삼진 탐색은 아니다.)
----
1. -가 3N개 있는 문자열에서 시작한다. (중간값이 없을 일이 없다.)
2. 문자열을 3등분 한 뒤, 가운데 문자열을 공백으로 바꾼다.
이렇게 하면, 선(문자열) 2개가 남는다.
3. 이제 각 선(문자열)을 3등분 하고, 가운데 문자열을 공백으로 바꾼다.
이 과정은 모든 선의 길이가 1일때 까지 계속 한다.
예를 들어, N=3인 경우, 길이가 27인 문자열로 시작한다.
----
EXAMPLE
NUM=3
N=27
===>1/3을 1/3시점부터 제거한다.
===>27/3=9 => idx=9면, no no
===> idx=8[9번째니까]부터9개 제거
===> 이후 idx=0, idx=17 부터 시작 (ok)
근데 이거 애초에
buf 만들고 지우고 이러지 말고
끝까지 간 다음 출력만 하면 되는 것 아닌가?
----
틀린 이유:
입력을 여러 줄로 이루어져 있다. 각 줄에 N이 주어진다. 파일의 끝에서 입력을 멈춘다. N은 0보다 크거나 같고, 12보다 작거나 같은 정수이다.
입력이 여러 개였음;;
*/
using namespace std;
int N;
void c(int begin, int end, int depth, bool fill)
{
if (depth == 0)
{
while (begin++ < end)
cout << (fill ? '-' : ' '); // 괄호 안 치면 111 로 나오는건 뭐야?
return;
}
int tmp = (end - begin) / 3;
c(begin, begin + tmp, depth - 1, true);
c(begin + tmp, begin + tmp * 2, 0, false); // depth=0으로 바로 줘야 함. 더 깊이 안들어가니까
c(begin + tmp * 2, begin + tmp * 3, depth - 1, true);
}
// 입력 받을 개수를 안 주면 어떻게 함?
// 신기한 거 많네 ㅋㅋ
// 이런식으로 푸는 문제도 있구만
int main()
{
int NUM;
while (true)
{
// cin으로 입력받은 값이 없으면
// cin.eof()는 true를 반환한다. 당연히 그렇지 않으면 false 반환
cin >> N;
if (cin.eof() == true)
break;
NUM = (int)pow(3, N);
c(0, NUM, N, true);
cout << "\n";
}
return 0;
}
| [
"seongbin9786@gmail.com"
] | seongbin9786@gmail.com |
7430fb9858dfabc056d089e86b467b5e1eb5d934 | 53da158ef8f73d422fde06c5a711b81b40e5ef0b | /ModuleTextures.cpp | 493a3ff95294dcdaa391bbb0615af5894ddd2518 | [] | no_license | lluissr/Graphics | 843fa4779bd071088f5ed8ddaa19384e43fa13ce | 48c6f762a3cc53643331c1a020e1ab95963b4d54 | refs/heads/master | 2020-04-01T11:30:37.186561 | 2018-10-15T19:25:59 | 2018-10-15T19:25:59 | 153,165,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,582 | cpp | #include "Globals.h"
#include "Application.h"
#include "ModuleRender.h"
#include "ModuleTextures.h"
#include "SDL/include/SDL.h"
#include "SDL_image/include/SDL_image.h"
#pragma comment( lib, "SDL_image/libx86/SDL2_image.lib" )
using namespace std;
ModuleTextures::ModuleTextures()
{
}
// Destructor
ModuleTextures::~ModuleTextures()
{
IMG_Quit();
}
// Called before render is available
bool ModuleTextures::Init()
{
LOG("Init Image library");
bool ret = true;
// load support for the PNG image format
int flags = IMG_INIT_PNG;
int init = IMG_Init(flags);
if((init & flags) != flags)
{
LOG("Could not initialize Image lib. IMG_Init: %s", IMG_GetError());
ret = false;
}
return ret;
}
bool ModuleTextures::Start()
{
return true;
}
// Called before quitting
bool ModuleTextures::CleanUp()
{
LOG("Freeing textures and Image library");
for(list<SDL_Texture*>::iterator it = textures.begin(); it != textures.end(); ++it)
SDL_DestroyTexture(*it);
textures.clear();
return true;
}
// Load new texture from file path
SDL_Texture* const ModuleTextures::Load(const char* path)
{
SDL_Texture* texture = NULL;
SDL_Surface* surface = IMG_Load(path);
if(surface == NULL)
{
LOG("Could not load surface with path: %s. IMG_Load: %s", path, IMG_GetError());
}
else
{
texture = SDL_CreateTextureFromSurface(App->renderer->renderer, surface);
if(texture == NULL)
{
LOG("Unable to create texture from surface! SDL Error: %s\n", SDL_GetError());
}
else
{
textures.push_back(texture);
}
SDL_FreeSurface(surface);
}
return texture;
}
| [
"lluissr@gmail.com"
] | lluissr@gmail.com |
3db517066a1a2416324e8d3150c4f15e966385b0 | 7bd42fe780d5da06e52799fae4983fbd2606475b | /OOS_HA2/Aufg.1/Labyrinth.cpp | 020fde50cd625d95e064c330cd628897fbd8a1c9 | [] | no_license | encoit01/Cpp | 3f699d4e6a411392f7fa1474f2baec77bf6e78b3 | b8f63dc83e7148bd65201fffae35651c3ac1386e | refs/heads/main | 2023-04-18T22:41:40.600556 | 2021-05-08T13:44:39 | 2021-05-08T13:44:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,275 | cpp |
#include "Labyrinth.hpp"
#include <iostream>
using namespace std;
void Labyrinth::initialisieren()
{
for (int i = 0; i < kZeilen; i++) {
for (int j = 0; j < kSpalten; j++) {
labyrinth[i][j] = MAUER;
}
}
for (int i = 0; i < kZeilen; i++) {
labyrinth[i][kSpalten] = NL;
}
for (int i = 0; i < kSpalten; i++) {
labyrinth[i][kSpalten + 1] = EOS;
}
}
void Labyrinth::drucken()
{
system("cls");
for (int i = 0; i < kZeilen;i++) {
for (int j = 0; j < kSpalten + 1; j++) {
cout << labyrinth[i][j];
}
}
Labyrinth::legeMuenzen();
}
void Labyrinth::erzeugen()
{
char c = 'x';
int posx = kSpalten / 2;
int posy = kZeilen / 2;
labyrinth[posy][posx] = ICH;
drucken();
while (c != 'q') {
drucken();
cout << "Laufen mit Pfeiltasten. Beenden mit q." << endl;
labyrinth[posy][posx] = WEG;
c = _getch();
switch (int(c)) {
// oben
case 72: posy = max(1, posy - 1); break;
// links
case 75: posx = max(1, posx - 1); break;
// rechts
case 77: posx = min(kSpalten - 2, posx + 1); break;
// unten
case 80: posy = min(kZeilen - 2, posy + 1); break;
// q = quit
case 113: break;
}
labyrinth[posy][posx] = ICH;
}
}
Labyrinth::Labyrinth()
{
labSpalten = kSpalten;
labZeilen = kZeilen;
labAnzGeister = kAnzGeister;
muenzen = 0;
initialisieren();
}
int Labyrinth::getZeilen()
{
return labZeilen;
}
int Labyrinth::getSpalten()
{
return labSpalten;
}
int Labyrinth::getAnzGeister()
{
return labAnzGeister;
}
int Labyrinth::getMuenzen()
{
return muenzen;
}
void Labyrinth::legeMuenzen()
{
for (int i = 0; i < kZeilen; i++) {
for (int j = 0; j < kSpalten; j++) {
if (labyrinth[i][j] == WEG)
{
labyrinth[i][j] = MUENZE;
muenzen++;
}
}
}
}
void Labyrinth::zeichneChar(char c, Position pos)
{
labyrinth[pos.posx][pos.posy] = c;
}
void Labyrinth::zeichneChar(char c, Position posalt, Position posneu)
{
zeichneChar(c, posneu);
labyrinth[posalt.posx][posalt.posy] = WEG;
}
char Labyrinth::getZeichenAnPos(Position pos)
{
char erg = labyrinth[pos.posx][pos.posy];
return erg;
}
bool Labyrinth::istMuenzeAnPos(Position pos)
{
if (labyrinth[pos.posx][pos.posy] == MUENZE)
{
return true;
}
else
{
return false;
}
} | [
"encoit01@hs-esslingen.de"
] | encoit01@hs-esslingen.de |
9765102133079989c7038198ce9f92092215dd10 | 9c22a7f4e39ec744d68eac3d5ea9db5c7b2013d7 | /src/appleseed/renderer/kernel/rendering/final/pixelsampler.h | 153cdbd711137ba30c5b6c9d2c9b7349cd621d93 | [
"MIT"
] | permissive | jotpandher/appleseed | 4b6b7f30ce816280c3502d710920e39c740f5d51 | c74bd03e314d3a9fd7dd0cbaeb2f1374ae4b546f | refs/heads/master | 2021-01-15T12:54:13.278636 | 2014-11-23T14:14:01 | 2014-11-23T14:14:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,191 | h |
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// 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 APPLESEED_RENDERER_KERNEL_RENDERING_FINAL_PIXELSAMPLER_H
#define APPLESEED_RENDERER_KERNEL_RENDERING_FINAL_PIXELSAMPLER_H
// appleseed.foundation headers.
#include "foundation/core/concepts/noncopyable.h"
#include "foundation/math/vector.h"
#include "foundation/platform/compiler.h"
// Standard headers.
#include <cstddef>
#include <vector>
namespace renderer
{
//
// A strictly deterministic pixel sampler.
//
// Reference:
//
// Strictly Deterministic Sampling Methods in Computer Graphics
// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.88.7937
//
class PixelSampler
: public foundation::NonCopyable
{
public:
// Initialize the pixel sampler for a given subpixel grid size.
void initialize(const size_t subpixel_grid_size);
// Compute the position of a pixel sample and optionally the initial instance
// number of the corresponding sampling context, given the integer coordinates
// of the subpixel grid cell containing the sample. The coordinates of the
// pixel sample are expressed in continous image space
// (https://github.com/appleseedhq/appleseed/wiki/Terminology).
void sample(
const int sx,
const int sy,
foundation::Vector2d& sample_position) const;
void sample(
const int sx,
const int sy,
foundation::Vector2d& sample_position,
size_t& initial_instance) const;
private:
size_t m_subpixel_grid_size;
double m_rcp_subpixel_grid_size; // 1.0 / subpixel_grid_size
double m_rcp_period; // 1.0 / m_period
size_t m_log_period; // log2(m_period)
size_t m_period; // m_sigma.size()
size_t m_period_mask; // m_period - 1
std::vector<size_t> m_sigma; // 2^N * radical_inverse_base2(0..N-1)
};
//
// PixelSampler class implementation.
//
FORCE_INLINE void PixelSampler::sample(
const int sx,
const int sy,
foundation::Vector2d& sample_position) const
{
// Compute the sample coordinates in image space.
if (m_subpixel_grid_size == 1)
{
sample_position[0] = sx + 0.5;
sample_position[1] = sy + 0.5;
}
else
{
const size_t j = sx & m_period_mask;
const size_t k = sy & m_period_mask;
const size_t sigma_j = m_sigma[j];
const size_t sigma_k = m_sigma[k];
sample_position[0] = (sx + sigma_k * m_rcp_period) * m_rcp_subpixel_grid_size;
sample_position[1] = (sy + sigma_j * m_rcp_period) * m_rcp_subpixel_grid_size;
}
}
FORCE_INLINE void PixelSampler::sample(
const int sx,
const int sy,
foundation::Vector2d& sample_position,
size_t& initial_instance) const
{
const size_t j = sx & m_period_mask;
const size_t k = sy & m_period_mask;
const size_t sigma_k = m_sigma[k];
// Compute the initial instance number of the sampling context.
initial_instance = (j << m_log_period) + sigma_k;
// Compute the sample coordinates in image space.
if (m_subpixel_grid_size == 1)
{
sample_position[0] = sx + 0.5;
sample_position[1] = sy + 0.5;
}
else
{
const size_t sigma_j = m_sigma[j];
sample_position[0] = (sx + sigma_k * m_rcp_period) * m_rcp_subpixel_grid_size;
sample_position[1] = (sy + sigma_j * m_rcp_period) * m_rcp_subpixel_grid_size;
}
}
} // namespace renderer
#endif // !APPLESEED_RENDERER_KERNEL_RENDERING_FINAL_PIXELSAMPLER_H
| [
"beaune@aist.enst.fr"
] | beaune@aist.enst.fr |
6427094ae25268a18c99a84737d009687fb23a4c | 108c8fa38da3371571068f353888f20d8fd729c0 | /voxel-cutting/Transformer_Cutting/OpenGLView/processHoleMesh.h | 05e83c2acf3a3de3e0fe28224e3f68c36663d78f | [] | no_license | pigoblock/TFYP | 2dd0acf1bb5591fb31b2d78a1bed764cd4a7d166 | 11ba29fd0d75a6b92080fd80b24064898b8f980f | refs/heads/master | 2021-01-17T10:07:10.149542 | 2016-04-19T07:41:53 | 2016-04-19T07:41:53 | 41,845,421 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | h | #pragma once
#include "Graphics\Surfaceobj.h"
class processHoleMesh
{
public:
processHoleMesh();
~processHoleMesh();
void processMeshSTL(char* path);
SurfaceObj * getBiggestWaterTightPart();
void drawSeparatePart() const;
private:
SurfaceObjPtr originalSurface;
std::vector<arrayInt> independentObj;
std::vector<bool> isWaterTightArray;
};
typedef std::shared_ptr<processHoleMesh> processHoleMeshPtr; | [
"kowanling@hotmail.com"
] | kowanling@hotmail.com |
e86c7181b12fb9c4309776318dbca661480d4c7a | a00f687b64637c80e88166ee4b0f957ef705b9c1 | /src/qt/askpassphrasedialog.cpp | 9621f60e783699dc9c4153c137851f1ec43828c7 | [
"MIT"
] | permissive | xenixcoin/xenixcoin | 9e7b95f48968c16ea9f135fdf865557a8e4ceb71 | 99d9eda1489d6e43a3c00225165506c61e480b20 | refs/heads/master | 2020-07-01T21:45:09.865765 | 2017-02-01T04:07:39 | 2017-02-01T04:07:39 | 74,255,598 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 10,001 | cpp | #include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
extern bool fWalletUnlockStakingOnly;
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case UnlockStaking:
ui->stakingCheckBox->setChecked(true);
ui->stakingCheckBox->show();
// fallthru
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("xenixcoin will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your coins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case UnlockStaking:
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked();
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case UnlockStaking:
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
| [
"xenixcoin@mail.com"
] | xenixcoin@mail.com |
a42897852f2cda134f5a7ad8403c9e081a62ceda | e000dfb2e1ddfe62598da937d2e0d40d6efff61b | /venusmmi/app/Cosmos/MusicPlayer/vapp_music_player_ncentercell.cpp | 931ce515ee90dfd3eac62b88be2f7053fcd9b72e | [] | no_license | npnet/KJX_K7 | 9bc11e6cd1d0fa5996bb20cc6f669aa087bbf592 | 35dcd3de982792ae4d021e0e94ca6502d1ff876e | refs/heads/master | 2023-02-06T09:17:46.582670 | 2020-12-24T02:55:29 | 2020-12-24T02:55:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,607 | cpp | /*****************************************************************************
* Copyright Statement:
* --------------------
* This software is protected by Copyright and the information contained
* herein is confidential. The software may not be copied and the information
* contained herein may not be used or disclosed except with the written
* permission of MediaTek Inc. (C) 2008
*
* BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
* NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S
* SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
* BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE
* LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE
* WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF
* LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND
* RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER
* THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC).
*
*****************************************************************************/
/*******************************************************************************
* Filename:
* ---------
* vapp_music_player_ncentercell.cpp
*
* Project:
* --------
* FTO Music Player notification center cell class
*
* Description:
* ------------
*
*
* Author:
* -------
* -------
*
*============================================================================
* HISTORY
* Below this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
*------------------------------------------------------------------------------
* removed!
*
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
*------------------------------------------------------------------------------
* Upper this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
*============================================================================
****************************************************************************/
#include "mmi_features.h"
#ifdef __COSMOS_MUSICPLY__
#ifdef __MMI_NCENTER_SUPPORT__
/*****************************************************************************
* Include
*****************************************************************************/
#include "vcp_global_popup.h"
#include "vapp_music_player_ncentercell.h"
#include "vapp_music_player.h"
#include "vapp_music_player_util.h"
#include "mmi_rp_vapp_music_player_def.h"
#include "vsrv_ncenter.h"
/* Pluto MMI headers */
#ifdef __cplusplus
extern "C"
{
#endif
#include "UCMSrvGProt.h"
#ifdef __cplusplus
}
#endif
/*****************************************************************************
* Event receiver functions
*****************************************************************************/
VfxBool g_close_exit_popup = TRUE;
#ifdef __cplusplus
extern "C"
{
#endif
void vapp_music_player_update_cell()
{
MMI_TRACE(TRACE_GROUP_2, TRC_VAPP_MUSICPLY_NCENTER_UPDATE_CELL);
VsrvNGroupSingleTitle *group;
VSRV_NGROUP_CREATE_EX(group, VsrvNGroupSingleTitle, (VAPP_MUSIC_PLAYER));
group->setTitle(VFX_WSTR_RES(STR_ID_VAPP_MUSIC_PLAYER));
VsrvNotificationCustom *notify = NULL;
VSRV_NOTIFICATION_CREATE_EX(notify, VsrvNotificationCustom, (VAPP_MUSIC_PLAYER, 0));
notify->setAutoLaunch(VFX_FALSE);
notify->setAutoClose(VFX_FALSE);
//notify->setIntentCallback(vapp_music_player_Intent_callback, NULL, 0);
notify->addCustomViewInfo(VFX_OBJ_CLASS_INFO(VappMusicPlayerNcenterCustomerCell),VSRV_NVIEWER_TYPE_GENERAL,NULL,0);
notify->setHeight(NCENTER_H);
notify->notify();
}
mmi_ret vapp_music_player_on_open_close(mmi_event_struct *evt)
{
VappMusicPlayerOpenCloseEvtStruct *openCloseEvt = (VappMusicPlayerOpenCloseEvtStruct*) evt;
MMI_TRACE(TRACE_GROUP_2, TRC_VAPP_MUSICPLY_NCENTER_ON_OPEN_CLOSE, openCloseEvt->isOpen);
if(openCloseEvt->isOpen)
{
// do nothing
}
else
{
VSRV_NOTIFICATION_CLOSE_EX((VsrvNGroupId)VAPP_MUSIC_PLAYER, 0);
}
return MMI_RET_OK;
}
mmi_ret vapp_music_player_on_show_hide(mmi_event_struct *evt)
{
//MMI_TRACE(TRACE_GROUP_2, TRC_VAPP_MUSICPLY_NCENTER_ON_SHOW_HIDE, showHideEvt->isShow);
vapp_music_player_update_cell();
return MMI_RET_OK;
}
mmi_ret vapp_music_player_on_play_start_stop(mmi_event_struct *evt)
{
VsrvNCenter *srvNCenter = VFX_OBJ_GET_INSTANCE(VsrvNCenter);
if (srvNCenter && !srvNCenter->queryNGroup(VAPP_MUSIC_PLAYER))
{
return MMI_RET_OK;
}
// MMI_TRACE(TRACE_GROUP_2, TRC_VAPP_MUSICPLY_NCENTER_ON_PLAY_START_STOP, playEvt->isPlayStart);
vapp_music_player_update_cell();
return MMI_RET_OK;
}
#ifdef __cplusplus
}
#endif
static mmi_ret cancel_global_popup(mmi_event_struct *evt)
{
music_player_cancel_popup_event_struct *evnt = (music_player_cancel_popup_event_struct *)evt;
VfxS32 popuphandle = evnt->popup_handle;
if (popuphandle != NULL && g_close_exit_popup)
{
vcp_global_popup_cancel(popuphandle);
}
g_close_exit_popup = TRUE;
return MMI_RET_OK;
}
static MMI_BOOL VappMusicPlayerNCellCallback(mmi_scenario_id scen_id, void *user_data)
{
//dummy
return MMI_TRUE;
}
/*****************************************************************************
* Music Player Widget Base Panel Class
*****************************************************************************/
VFX_IMPLEMENT_CLASS("VappNcenterMusicPlayerBase", VappNcenterMusicPlayerBase, VfxControl);
VappNcenterMusicPlayerBase::~VappNcenterMusicPlayerBase()
{
/* Disconnect app signal */
if(m_mplayerSrv != NULL)
{
m_mplayerSrv->m_signalOnPrevNext.disconnect(this, &VappNcenterMusicPlayerBase::onPrevNext);
}
/* Disconnect playback singal */
if(m_ctrlPlayback != NULL)
{
m_ctrlPlayback->m_signalPlaybackStateChange.disconnect(this, &VappNcenterMusicPlayerBase::onPlaybackStateChange);
m_ctrlPlayback->m_signalMDICallback.disconnect(this, &VappNcenterMusicPlayerBase::onMDICallback);
}
}
void VappNcenterMusicPlayerBase::getAppControl(void)
{
m_mplayerSrv = getMusicPlayerSrv();
if(m_mplayerSrv)
{
m_mplayerSrv->m_signalOnPrevNext.connect(this, &VappNcenterMusicPlayerBase::onPrevNext);
/* Get playback control and connect state change */
m_ctrlPlayback = m_mplayerSrv->getCtrlPlayback();
m_ctrlPlayback->m_signalPlaybackStateChange.connect(this, &VappNcenterMusicPlayerBase::onPlaybackStateChange);
m_ctrlPlayback->m_signalMDICallback.connect(this, &VappNcenterMusicPlayerBase::onMDICallback);
}
}
void VappNcenterMusicPlayerBase::onPlayPause(void)
{
if(m_ctrlPlayback != NULL)
{
m_ctrlPlayback->setIsAppMode(TRUE);
PlaybackStateEnum state;
state = m_ctrlPlayback->getPlayState();
MMI_TRACE(MMI_MEDIA_TRC_G2_APP, TRC_VAPP_WIDGET_MUSICPLY_INFO_PANEL_BTN_CLICK, state);
if(PB_STATE_PLAY == state ||
PB_STATE_PAUSE == state ||
PB_STATE_OPEN == state ||
PB_STATE_STOP == state ||
PB_STATE_CLOSE == state ||
PB_STATE_SWITCHING_PLAY == state ||
PB_STATE_SWITCHING_NOT_PLAY == state ||
PB_STATE_INTERRUPTED == state ||
PB_STATE_BT_CONNECTING_WHILE_PLAYING == state)
{
/* Stop the song if the song is not pausable */
if ((state == PB_STATE_PLAY || state == PB_STATE_BT_CONNECTING_WHILE_PLAYING) &&
!m_ctrlPlayback->isSongPausable(NULL))
{
m_ctrlPlayback->stop();
}
else if (m_ctrlPlayback->m_playStateBeforeSeek == PB_STATE_PAUSE)
{
// do seek while pasued
if(m_mplayerSrv)
{
m_mplayerSrv->setPlayAfterSwitchSong(VFX_TRUE);
}
m_ctrlPlayback->play();
}
else
{
if(m_mplayerSrv)
{
m_mplayerSrv->setPlayAfterSwitchSong(VFX_TRUE);
}
m_ctrlPlayback->playpause();
}
}
}
}
void VappNcenterMusicPlayerBase::onPrev(void)
{
if(m_mplayerSrv != NULL && isValidState())
{
/* Control music player to previous song */
m_mplayerSrv->onPrev(VFX_TRUE);
}
}
void VappNcenterMusicPlayerBase::onNext(void)
{
if(m_mplayerSrv != NULL && isValidState())
{
/* Control music player to next song */
m_mplayerSrv->onNext(NEXT, VFX_TRUE);
}
}
VfxBool VappNcenterMusicPlayerBase::isValidState(void)
{
if((m_mplayerSrv == NULL) || (m_mplayerSrv && (m_mplayerSrv->getActiveCount() == 0)))
{
return VFX_FALSE;
}
return VFX_TRUE;
}
/*****************************************************************************
* Music PlayerVappNcenterMusicPlayerInfoPanel Class
*****************************************************************************/
VFX_IMPLEMENT_CLASS("VappNcenterMusicPlayerInfoPanel", VappNcenterMusicPlayerInfoPanel, VappNcenterMusicPlayerBase)
VappNcenterMusicPlayerInfoPanel::~VappNcenterMusicPlayerInfoPanel()
{
/* Deregister app event callback */
mmi_frm_cb_dereg_event(EVT_ID_SRV_UCM_STATUS_CHANGE,(mmi_proc_func)&VappNcenterMusicPlayerInfoPanel::staticEventHandler, this);
}
void VappNcenterMusicPlayerInfoPanel::onInit()
{
VfxFrame::onInit();
initUI();
getAppControl();
updateButton();
updatePanel();
mmi_frm_cb_reg_event(EVT_ID_SRV_UCM_STATUS_CHANGE,(mmi_proc_func)&VappNcenterMusicPlayerInfoPanel::staticEventHandler, this);
}
void VappNcenterMusicPlayerInfoPanel::initUI()
{
this->setPos(PANEL_X, PANEL_Y);
this->setSize(NCENTER_PANEL_W, NCENTER_PANEL_H);
this->setAlignParent(VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE);
VFX_OBJ_CREATE(m_background, VfxImageFrame, this);
m_background->setResId(IMG_ID_VAPP_MUSICPLY_BTN_BG_PANEL_NC);
m_background->setRect(0, 0, this->getSize().width, this->getSize().height);
m_background->setAlignParent(VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE);
m_background->setContentPlacement(VFX_FRAME_CONTENT_PLACEMENT_TYPE_RESIZE);
// icon
VFX_OBJ_CREATE(m_icon, VfxImageFrame, this);
m_icon->setPos(ICON_X, ICON_Y);
m_icon->setAlignParent(VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_NONE,VFX_FRAME_ALIGNER_MODE_NONE);
m_icon->setResId(IMG_ID_VAPP_MUSICPLY_NCENTER_ICON);
// btn_close
VFX_OBJ_CREATE(m_close_btn, VcpImageButton, this);
m_close_btn->setAnchor(1.0f, 0.0f);
m_close_btn->setPos(NCENTER_PANEL_W-ICON_X, ICON_Y);
m_close_btn->setSize(VAPP_NCENTER_ONGOING_CELL_CLOSE_BUTTON_WIDTH,VAPP_NCENTER_ONGOING_CELL_CLOSE_BUTTON_HEIGHT);
m_close_btn->setAlignParent(VFX_FRAME_ALIGNER_MODE_NONE,VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_SIDE,VFX_FRAME_ALIGNER_MODE_NONE);
m_close_btn->setId(BTN_COLSE);
m_close_btn->setImage(VcpStateImage(VAPP_IMG_NCENTER_CLOSE_ICON));
m_close_btn->m_signalClicked.connect(this,&VappNcenterMusicPlayerInfoPanel::onButtonClicked);
// Song title
VFX_OBJ_CREATE(m_textTitle, VfxTextFrame, this);
m_textTitle->setSize(NCENTER_PANEL_W-TEXT_X*2,m_textTitle->getSize().height);
m_textTitle->setFont(VfxFontDesc(VFX_FONT_DESC_VF_SIZE(FONT_SIZE)));
m_textTitle->setPos(TEXT_X, TEXT_Y);
m_textTitle->setTruncateMode(VfxTextFrame::TRUNCATE_MODE_END);
m_textTitle->setAlignParent(VFX_FRAME_ALIGNER_MODE_SIDE, VFX_FRAME_ALIGNER_MODE_SIDE, VFX_FRAME_ALIGNER_MODE_SIDE, VFX_FRAME_ALIGNER_MODE_NONE);
/* Create button */
VFX_OBJ_CREATE(m_prev_btn,VcpButton,this);
m_prev_btn->setId(BTN_PREV);
m_prev_btn->setPos(PRAV_NEXT_BTN_X, PRAV_NEXT_BTN_Y);
m_prev_btn->setImage(VcpStateImage(IMG_ID_VAPP_MUSICPLY_BTN_PREV_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PREV_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PREV_D_NC, 0));
m_prev_btn->setBgImageList(VcpStateImage(IMG_ID_VAPP_MUSICPLY_BTN_BG2_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_BG2_D_NC, IMG_ID_VAPP_MUSICPLY_BTN_BG2_N_NC, 0));
m_prev_btn->setSize(PRAV_NEXT_BTN_SIZE, PRAV_NEXT_BTN_SIZE);
m_prev_btn->setAlignParent(VFX_FRAME_ALIGNER_MODE_MID, VFX_FRAME_ALIGNER_MODE_SIDE, VFX_FRAME_ALIGNER_MODE_NONE, VFX_FRAME_ALIGNER_MODE_NONE);
m_prev_btn->setPlacement(VCP_BUTTON_PLACEMENT_IMAGE_ONLY);
m_prev_btn->setMargin(0,0,0,0);
m_prev_btn->m_signalClicked.connect(this, &VappNcenterMusicPlayerInfoPanel::onButtonClicked);
m_prev_btn->setFuzzy(VFX_FALSE);
VFX_OBJ_CREATE(m_play_btn,VcpButton,this);
m_play_btn->setId(BTN_PLAY);
m_play_btn->setAnchor(0.5f, 0.0f);
m_play_btn->setPos(VAPP_NCENTER_ONGOING_CELL_WIDTH/2, PLAY_BTN_Y);
m_play_btn->setImage(VcpStateImage(IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_D_NC, 0));
m_play_btn->setBgImageList(VcpStateImage(IMG_ID_VAPP_MUSICPLY_BTN_BG1_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_BG1_D_NC, IMG_ID_VAPP_MUSICPLY_BTN_BG1_N_NC, 0));
m_play_btn->setSize(PLAY_BTN_W, PLAY_BTN_H);
m_play_btn->setIsAutoResized(VFX_FALSE);
m_play_btn->setAlignParent(VFX_FRAME_ALIGNER_MODE_MID, VFX_FRAME_ALIGNER_MODE_SIDE, VFX_FRAME_ALIGNER_MODE_NONE, VFX_FRAME_ALIGNER_MODE_NONE);
m_play_btn->setPlacement(VCP_BUTTON_PLACEMENT_IMAGE_ONLY);
m_play_btn->setMargin(0,0,0,0);
m_play_btn->m_signalClicked.connect(this, &VappNcenterMusicPlayerInfoPanel::onButtonClicked);
m_play_btn->setFuzzy(VFX_FALSE);
VFX_OBJ_CREATE(m_next_btn,VcpButton,this);
m_next_btn->setId(BTN_NEXT);
m_next_btn->setAnchor(1.0f, 0.0f);
m_next_btn->setPos(NCENTER_PANEL_W-PRAV_NEXT_BTN_X, PRAV_NEXT_BTN_Y);
m_next_btn->setImage(VcpStateImage(IMG_ID_VAPP_MUSICPLY_BTN_NEXT_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_NEXT_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_NEXT_D_NC, 0));
m_next_btn->setBgImageList(VcpStateImage(IMG_ID_VAPP_MUSICPLY_BTN_BG2_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_BG2_D_NC, IMG_ID_VAPP_MUSICPLY_BTN_BG2_N_NC, 0));
m_next_btn->setSize(PRAV_NEXT_BTN_SIZE, PRAV_NEXT_BTN_SIZE);
m_next_btn->setAlignParent(VFX_FRAME_ALIGNER_MODE_NONE, VFX_FRAME_ALIGNER_MODE_SIDE, VFX_FRAME_ALIGNER_MODE_MID, VFX_FRAME_ALIGNER_MODE_NONE);
m_next_btn->setPlacement(VCP_BUTTON_PLACEMENT_IMAGE_ONLY);
m_next_btn->setMargin(0,0,0,0);
m_next_btn->m_signalClicked.connect(this, &VappNcenterMusicPlayerInfoPanel::onButtonClicked);
m_next_btn->setFuzzy(VFX_FALSE);
}
void VappNcenterMusicPlayerInfoPanel::destroyUI()
{
VFX_OBJ_CLOSE(m_textTitle);
VFX_OBJ_CLOSE(m_background);
VFX_OBJ_CLOSE(m_icon);
VFX_OBJ_CLOSE(m_close_btn);
VFX_OBJ_CLOSE(m_play_btn);
VFX_OBJ_CLOSE(m_prev_btn);
VFX_OBJ_CLOSE(m_next_btn);
sendPostCloseExitpopup();
}
void VappNcenterMusicPlayerInfoPanel::sendPostCloseExitpopup()
{
if ( m_popup_id != NULL)
{
music_player_cancel_popup_event_struct postInvoke;
MMI_FRM_INIT_EVENT(&postInvoke, 0);
postInvoke.popup_handle = m_popup_id;
MMI_FRM_POST_EVENT(&postInvoke, (mmi_proc_func)&cancel_global_popup, NULL);
}
}
void VappNcenterMusicPlayerInfoPanel::onButtonClicked(VfxObject* obj, VfxId id)
{
/* if(srv_ucm_query_call_count(SRV_UCM_CALL_STATE_ALL, SRV_UCM_CALL_TYPE_NO_CSD, NULL) > 0)
{
return;
}*/
switch(id)
{
case BTN_PLAY:
onPlayPause();
break;
case BTN_PREV:
onPrev();
break;
case BTN_NEXT:
onNext();
break;
case BTN_COLSE:
onCloseButtonClick();
default:
break;
}
}
void VappNcenterMusicPlayerInfoPanel::onPlaybackStateChange(PlaybackStateEnum state)
{
switch(state)
{
case PB_STATE_NONE:
/* Check if app clear its active list */
if(!isValidState())
{
updatePanel();
return;
}
break;
case PB_STATE_OPEN:
updatePanel();
break;
case PB_STATE_PLAY:
updateButton();
break;
case PB_STATE_PAUSE:
updateButton();
break;
case PB_STATE_STOP:
updateButton();
break;
case PB_STATE_CLOSE:
updatePanel();
break;
case PB_STATE_PLAYBACK_FAIL:
updateButton();
break;
default:
updateButton();
break;
}
}
void VappNcenterMusicPlayerInfoPanel::onMDICallback(VfxS32 result)
{
switch (result)
{
case VAPP_MUSICPLY_INTERRUPT_CB_RESUME:
if(m_popup_id != NULL)
{
g_close_exit_popup = FALSE;
}
break;
default:
break;
}
}
void VappNcenterMusicPlayerInfoPanel::onCloseButtonClick()
{
mmi_frm_nmgr_notify_by_app(MMI_SCENARIO_ID_DEFAULT, MMI_EVENT_WARNING, &VappMusicPlayerNCellCallback, this);
m_popup_id = vcp_global_popup_show_confirm_two_button_id(
GRP_ID_ROOT,
VCP_POPUP_TYPE_WARNING,
STR_ID_VAPP_MUSIC_PLAYER_POPUP_CLOSE_HINT,
STR_GLOBAL_OK,
STR_GLOBAL_CANCEL,
VCP_POPUP_BUTTON_TYPE_WARNING,
VCP_POPUP_BUTTON_TYPE_CANCEL,
&VappNcenterMusicPlayerInfoPanel::onConfirmButtonClick,
(void*)this);
}
VfxS32 VappNcenterMusicPlayerInfoPanel::getPopupID()
{
return m_popup_id;
}
void VappNcenterMusicPlayerInfoPanel::updatePanel()
{
if(isValidState())
{
srv_plst_media_details_struct detail_info;
//VFX_ALLOC_MEM(detail_info, sizeof(srv_plst_media_details_struct), this);
if(m_mplayerSrv->getCurrDetailInfo(&detail_info))
{
m_textTitle->setString(VFX_WSTR_MEM(detail_info.title));
}
else
{
m_textTitle->setString(STR_ID_VAPP_MUSIC_PLAYER_PLAYLIST_NO_SONG);
}
//VFX_FREE_MEM(detail_info);
}
else
{
m_textTitle->setString(STR_ID_VAPP_MUSIC_PLAYER_PLAYLIST_NO_SONG);
}
updateButton();
}
void VappNcenterMusicPlayerInfoPanel::onConfirmButtonClick(VfxId id, void *userData)
{
VappNcenterMusicPlayerInfoPanel *cell =(VappNcenterMusicPlayerInfoPanel*)userData;
if (id == VCP_CONFIRM_POPUP_BUTTON_USER_1)
{
// close APP
VappMusicPlayerApp *app = getMusicPlayerApp();
if (app)
{
app->goToRoot();
}
VappMusicPlayerService *srv = getMusicPlayerSrv();
if (srv)
{
srv->closeMusicPlayer();
}
}
else if (id == VCP_CONFIRM_POPUP_BUTTON_USER_2)
{
vcp_global_popup_cancel(cell->getPopupID());
}
}
void VappNcenterMusicPlayerInfoPanel::updateButton(void)
{
VcpStateImage imgListPlayBtn;
VfxBool in_call = VFX_FALSE;
if(srv_ucm_query_call_count(SRV_UCM_CALL_STATE_ALL, SRV_UCM_CALL_TYPE_NO_CSD, NULL) > 0)
{
in_call = VFX_TRUE;
}
if(in_call || (m_ctrlPlayback == NULL) || !isValidState())
{
imgListPlayBtn.setImage(IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_D_NC, 0);
m_play_btn->setIsDisabled(VFX_TRUE);
m_prev_btn->setIsDisabled(VFX_TRUE);
m_next_btn->setIsDisabled(VFX_TRUE);
}
else
{
VfxBool isPlayImage = VFX_TRUE;
if (m_ctrlPlayback)
{
isPlayImage = m_ctrlPlayback->getPlayPauseState();
}
if(isPlayImage)
{
imgListPlayBtn.setImage(IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_D_NC, 0);
}
else
{
imgListPlayBtn.setImage(IMG_ID_VAPP_MUSICPLY_BTN_PAUSE_NC, IMG_ID_VAPP_MUSICPLY_BTN_PAUSE_NC, 0, 0);
}
// Check if need to disable play icon
// Playback fail or interrupted in playback fail state, do not enable UI
InterruptStruct interrupt = m_ctrlPlayback->getInterruptedInfo();
PlaybackStateEnum state = m_ctrlPlayback->getPlayState();
if (( state == PB_STATE_PLAYBACK_FAIL) || (interrupt.isInterrupted && (interrupt.state == PB_STATE_PLAYBACK_FAIL)))
{
m_play_btn->setIsDisabled(VFX_TRUE);
}
else
{
m_play_btn->setIsDisabled(VFX_FALSE);
}
// Set button unhittable when switching play
if (state == PB_STATE_SWITCHING_PLAY || state == PB_STATE_SWITCHING_NOT_PLAY || state == PB_STATE_SEEKING)
{
// Make button up when change song
m_play_btn->setState(VCP_BUTTON_STATE_NORMAL);
m_play_btn->setIsUnhittable(VFX_TRUE);
m_prev_btn->setState(VCP_BUTTON_STATE_NORMAL);
m_prev_btn->setIsUnhittable(VFX_TRUE);
m_next_btn->setState(VCP_BUTTON_STATE_NORMAL);
m_next_btn->setIsUnhittable(VFX_TRUE);
}
else
{
m_play_btn->setIsUnhittable(VFX_FALSE);
m_prev_btn->setIsUnhittable(VFX_FALSE);
m_next_btn->setIsUnhittable(VFX_FALSE);
}
m_prev_btn->setIsDisabled(VFX_FALSE);
m_next_btn->setIsDisabled(VFX_FALSE);
}
m_play_btn->setImage(imgListPlayBtn);
}
mmi_ret VappNcenterMusicPlayerInfoPanel::staticEventHandler(mmi_event_struct *evt)
{
switch(evt->evt_id)
{
case EVT_ID_SRV_UCM_STATUS_CHANGE:
{
VappNcenterMusicPlayerInfoPanel* ncenter = (VappNcenterMusicPlayerInfoPanel*) evt->user_data;
if(ncenter->m_play_btn)
{
VcpStateImage imgListPlayBtn;
imgListPlayBtn.setImage(IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_N_NC, IMG_ID_VAPP_MUSICPLY_BTN_PLAY_D_NC, 0);
ncenter->m_play_btn->setImage(imgListPlayBtn);
if(srv_ucm_query_call_count(SRV_UCM_CALL_STATE_ALL, SRV_UCM_CALL_TYPE_NO_CSD, NULL) > 0)
{
ncenter->m_play_btn->setIsDisabled(VFX_TRUE);
ncenter->m_prev_btn->setIsDisabled(VFX_TRUE);
ncenter->m_next_btn->setIsDisabled(VFX_TRUE);
}
else
{
if(ncenter->isValidState())
{
ncenter->m_play_btn->setIsDisabled(VFX_FALSE);
ncenter->m_prev_btn->setIsDisabled(VFX_FALSE);
ncenter->m_next_btn->setIsDisabled(VFX_FALSE);
}
}
}
break;
}
default:
break;
}
return MMI_RET_OK;
}
/*****************************************************************************
* Music Player NCenter BaseCell Class
*****************************************************************************/
VFX_IMPLEMENT_CLASS("VappMusicPlayerNcenterCustomerCell",VappMusicPlayerNcenterCustomerCell, VsrvNCell);
void VappMusicPlayerNcenterCustomerCell::onCreateView(void *viewData,VfxU32 viewDataSize)
{
VsrvNCell::onCreateView(viewData, viewDataSize);
this->setSize(VAPP_NCENTER_ONGOING_CELL_WIDTH, NCENTER_H);
VFX_OBJ_CREATE(m_playback_panel, VappNcenterMusicPlayerInfoPanel, this);
}
void VappMusicPlayerNcenterCustomerCell::onCloseView()
{
m_playback_panel->destroyUI();
VFX_OBJ_CLOSE(m_playback_panel);
VsrvNCell::onCloseView();
}
#endif//__MMI_NCENTER_SUPPORT
#endif //__COSMOS_MUSICPLY__
| [
"3447782@qq.com"
] | 3447782@qq.com |
580e82dd33f2e05f0ec4e86e57394d12b8570e30 | 41704dd9a57c4f84e639e7ee2610e5cd71a5826a | /Castlevania/Boss3.cpp | a1e5eef769eff6ed2173252b9fbde5f6ba08ad89 | [] | no_license | GameCastleVania/CSVNL | b373f213b720c316a5784e7506a7bfaa3edf7723 | 65a452d1b36c8c40ce754fcf5affcab2ac665f24 | refs/heads/master | 2020-06-11T10:12:56.490391 | 2017-01-04T20:28:26 | 2017-01-04T20:28:26 | 75,696,672 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,295 | cpp | #include "Boss3.h"
extern int Boss3HP;
Boss3::Boss3()
{
}
Boss3::Boss3(float X, float Y)
{
PosX = x = X;
PosY = y = Y + 10;
LRight = true;
exploded = false;
shooting = true;
wasHit = false;
hitTime = 0;
isDead = 0;
type = 4;
HP = 16;
vx = 2;
vy = 0;
CRec = RecF(x, y, 32, 80);
}
Boss3::~Boss3()
{
}
void Boss3::Init(LPDIRECT3DDEVICE9 _d3ddv, CSimon * _simon, BulletManager * _bulletManager, Explosion * _explosion)
{
d3ddv = _d3ddv;
simon = _simon;
bulletManager = _bulletManager;
explosion = _explosion;
Boss3L = new Sprite(d3ddv, "resource\\image\\boss\\BMap3\\BossLv3left.png", 32, 80, 2, 2);
Boss3R = new Sprite(d3ddv, "resource\\image\\boss\\BMap3\\BossLv3right.png", 32, 80, 2, 2);
}
void Boss3::Update()
{
if (stopUpdate == false && _stopUpdate == false)
{
Boss3HP = HP;
float _x = simon->GetX() - 32;
float _y = simon->GetY() - 32;
if (_x > 4900) // o giua 2 con booss
{
ready = true;
}
if (ready)
{
if (!wasHit)
{
if (!checkDir)
{
if (setVel)
{
if (x < _x)
vx = 1.3;
else
vx = -1.3;
setVel = false;
}
if (vx > 0 && x > _x || vx < 0 && x < _x)
{
checkDir = true;
setVel = true;
}
}
else
{
if (setVel)
{
vx = -vx;
setVel = false;
}
_Time++;
if (_Time > 100 || x > 5100 || x < 4700)
{
vx = 0;
if (_Time > 120)
{
checkDir = false;
setVel = true;
if (shooting)
{
if (LRight)
BulletShoot(3.0f, 3.1f);
else
BulletShoot(-3.0f, 3.1f);
}
_Time = 0;
}
}
}
if (vx > 0)
LRight = true;
else
LRight = false;
DWORD now = GetTickCount();
if (now - last_time > 1000 / 5)
{
if (!LRight)
Boss3L->NextRepeat();
else
Boss3R->NextRepeat();
last_time = now;
}
}
else
{
if (vx != 0)
vxbackup = vx;
if (vy != 0)
vybackup = vy;
vx = 0;
vy = 0;
hitTime++;
if (hitTime > 30)
{
hitTime = 0;
vx = vxbackup;
vy = vybackup;
wasHit = false;
Hit = true;
}
}
x += vx;
}
}
if (!exploded && HP <= 0)
{
explosion->Get(11, x, y, 7);
explosion->Get(11, x + 25, y, 7);
explosion->Get(11, x + 50, y, 7);
explosion->Get(11, x, y - 25, 7);
explosion->Get(11, x + 25, y - 25, 7);
explosion->Get(11, x + 50, y - 25, 7);
explosion->Get(12, 4800, 132, 7);
exploded = true;
visible = false;
shooting = false;
ready = false;
}
UpdateRec();
}
void Boss3::UpdateGunPoint()
{
}
void Boss3::Draw(int vpx, int vpy)
{
if (visible)
{
if (!exploded)
{
if (LRight)
Boss3R->Render(x + 32, y + 32, vpx, vpy);
else
Boss3L->Render(x + 32, y + 32, vpx, vpy);
}
}
}
void Boss3::BulletShoot(float _vx, float _vy)
{
bulletManager->Get(3, x, y, _vx, _vy);
}
void Boss3::UpdateRec()
{
if (HP > 0)
{
CRec = RecF(x, y, 32, 80);
}
else
{
CRec = RecF(0, 0, 0, 0);
}
if (visible == false)
CRec = RecF(0, 0, 0, 0);
}
void Boss3::Destroy()
{
HP = 0;
}
| [
"13520592@gm.uit.edu.vn"
] | 13520592@gm.uit.edu.vn |
cca95cc4f2ab243cde8f0712ed0cdecf4720df05 | fec25167d6f425342cd26be40050131bfff34b49 | /shared/hamming.cpp | 235629d4436938206ee2b5554221f47744412e9e | [
"Unlicense"
] | permissive | DeNiCoN/TIK | 65accae707cfb847583719e496cb7857c2983d9d | 3f622e1a18cc217ff702020f065587e3d10ad1e3 | refs/heads/main | 2023-04-21T22:54:03.399766 | 2021-05-19T08:10:37 | 2021-05-19T08:10:37 | 357,243,464 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,433 | cpp | #include "hamming.hpp"
#include <bitset>
#include <fstream>
#include "bit_getter.hpp"
#include "bit_writer.hpp"
namespace tik
{
namespace hamming
{
enum class Type
{
NORMAL,
EXTENDED
};
void encode(const std::filesystem::path& from,
const std::filesystem::path& to)
{
std::ifstream input(from, std::ios::binary);
std::ofstream output(to, std::ios::binary);
output.put(char(Type::EXTENDED));
utils::BitGetter bit_getter(input);
while (bit_getter)
{
std::bitset<4> code;
std::bitset<16> out;
for (unsigned i = 0; i < 11; ++i)
{
if (bit_getter.get())
{
unsigned mapped;
if (i == 0)
mapped = 3;
else if (i < 4)
mapped = i + 4;
else
mapped = i + 5;
out[mapped] = true;
code ^= mapped;
}
}
out[1] = code[0];
out[2] = code[1];
out[4] = code[2];
out[8] = code[3];
out[0] = out.count() % 2;
uint16_t o = out.to_ulong();
output.write(reinterpret_cast<const char*>(&o), sizeof(o));
}
}
void encode_not_extended(const std::filesystem::path& from,
const std::filesystem::path& to)
{
std::ifstream input(from, std::ios::binary);
std::ofstream output(to, std::ios::binary);
output.put(char(Type::NORMAL));
utils::BitGetter bit_getter(input);
while (bit_getter)
{
std::bitset<4> code;
std::bitset<16> out;
for (unsigned i = 0; i < 11; ++i)
{
if (bit_getter.get())
{
unsigned mapped;
if (i == 0)
mapped = 3;
else if (i < 4)
mapped = i + 4;
else
mapped = i + 5;
out[mapped] = true;
code ^= mapped;
}
}
out[1] = code[0];
out[2] = code[1];
out[4] = code[2];
out[8] = code[3];
uint16_t o = out.to_ulong();
output.write(reinterpret_cast<const char*>(&o), sizeof(o));
}
}
void decode(const std::filesystem::path& from,
const std::filesystem::path& to)
{
std::ifstream input(from, std::ios::binary);
std::ofstream output(to, std::ios::binary);
utils::BitWriter bit_writer(output);
bit_writer.discard_last() = true;
unsigned char type_char = input.get();
if (type_char > 2)
{
std::cerr << "Unknown type" << std::endl;
throw std::exception();
}
Type type = static_cast<Type>(type_char);
uint16_t current;
while(input.read(reinterpret_cast<char*>(¤t), sizeof(current)))
{
std::bitset<sizeof(current) * 8> current_set = current;
std::size_t flip = 0;
for (std::size_t i = 0; i < current_set.size(); ++i)
{
if (current_set[i])
flip ^= i;
}
if (type == Type::NORMAL)
{
current_set.flip(flip);
}
else if(type == Type::EXTENDED)
{
if (current_set.count() % 2)
{
//single error
current_set.flip(flip);
}
else
{
if (flip)
{
//double
std::cerr << "double error" << std::endl;
}
}
}
std::bitset<11> result;
result[0] = current_set[3];
result[1] = current_set[5];
result[2] = current_set[6];
result[3] = current_set[7];
result[4] = current_set[9];
result[5] = current_set[10];
result[6] = current_set[11];
result[7] = current_set[12];
result[8] = current_set[13];
result[9] = current_set[14];
result[10] = current_set[15];
bit_writer.write(result);
}
}
void check(const std::filesystem::path& input_file, std::ostream& log_stream)
{
std::ifstream input(input_file, std::ios::binary);
unsigned char type_char = input.get();
if (type_char > 2)
{
log_stream << "Wrong header\n";
return;
}
Type type = static_cast<Type>(type_char);
if (type == Type::NORMAL)
{
log_stream << "Hamming(15, 11)\n";
}
else
{
log_stream << "Hamming(16, 11)\n";
}
uint16_t current;
std::size_t cur_code_index = 0;
while(input.read(reinterpret_cast<char*>(¤t), sizeof(current)))
{
std::bitset<sizeof(current) * 8> current_set = current;
std::size_t flip = 0;
for (std::size_t i = 0; i < current_set.size(); ++i)
{
if (current_set[i])
flip ^= i;
}
if (type == Type::NORMAL)
{
if (flip)
{
log_stream << "Single error at codeword " << cur_code_index + 1
<< " bit " << flip << " (" << cur_code_index * 16 + flip
<< ")\n";
}
}
else if(type == Type::EXTENDED)
{
if (current_set.count() % 2)
{
//single error
if (flip)
{
log_stream << "Single error at codeword " << cur_code_index + 1
<< " bit " << flip << " (" << cur_code_index * 16 + flip
<< ")\n";
}
}
else
{
if (flip)
{
log_stream << "Double error at codeword " << cur_code_index + 1
<< "\n";
}
}
}
cur_code_index++;
}
}
}
}
| [
"denicon1234@gmail.com"
] | denicon1234@gmail.com |
7ece2a2d0cec39b419ef176054d383f24a2df42a | 3538f87f9f3c2797455902ed229c0d747a890850 | /src/HTTP/UrlClient.h | 5f737b057ff4ebca2ceed5329b4099bb2aa40b12 | [
"Apache-2.0"
] | permissive | cflep/cuberite | fb2103460067fbf6949858880f7fabde8cd80e2e | 6bbbc52d0201493a9bf4c1f5b1d05dd76240c4bf | refs/heads/master | 2023-08-10T18:10:16.132234 | 2021-09-23T20:49:34 | 2021-09-23T20:49:34 | 317,042,628 | 1 | 0 | NOASSERTION | 2021-02-11T12:36:46 | 2020-11-29T21:03:50 | C++ | UTF-8 | C++ | false | false | 6,180 | h |
// UrlClient.h
// Declares the cUrlClient class for high-level URL interaction
/*
Options that can be set via the Options parameter to the cUrlClient calls:
"MaxRedirects": The maximum number of allowed redirects before the client refuses a redirect with an error
"OwnCert": The client certificate to use, if requested by the server. Any string that can be parsed by cX509Cert.
"OwnPrivKey": The private key appropriate for OwnCert. Any string that can be parsed by cCryptoKey.
"OwnPrivKeyPassword": The password for OwnPrivKey. If not present or empty, no password is assumed.
Behavior:
- If a redirect is received, and redirection is allowed, the redirection is reported via OnRedirecting() callback
and the request is restarted at the redirect URL, without reporting any of the redirect's headers nor body
- If a redirect is received and redirection is not allowed (maximum redirection attempts have been reached),
the OnRedirecting() callback is called with the redirect URL and then the request terminates with an OnError() callback,
without reporting the redirect's headers nor body.
*/
#pragma once
#include "../OSSupport/Network.h"
class cUrlClient
{
public:
/** Callbacks that are used for progress and result reporting. */
class cCallbacks
{
public:
// Force a virtual destructor in descendants:
virtual ~cCallbacks() {}
/** Called when the TCP connection is established. */
virtual void OnConnected(cTCPLink & a_Link) {}
/** Called for TLS connections, when the server certificate is received.
Return true to continue with the request, false to abort.
The default implementation does nothing and continues with the request.
TODO: The certificate parameter needs a representation! */
virtual bool OnCertificateReceived() { return true; }
/** Called for TLS connections, when the TLS handshake has been completed.
An empty default implementation is provided so that clients don't need to reimplement it unless they are interested in the event. */
virtual void OnTlsHandshakeCompleted() { }
/** Called after the entire request has been sent to the remote peer. */
virtual void OnRequestSent() {}
/** Called after the first line of the response is parsed, unless the response is an allowed redirect. */
virtual void OnStatusLine(const AString & a_HttpVersion, int a_StatusCode, const AString & a_Rest) {}
/** Called when a single HTTP header is received and parsed, unless the response is an allowed redirect
Called once for each incoming header. */
virtual void OnHeader(const AString & a_Key, const AString & a_Value) {}
/** Called when the HTTP headers have been fully parsed, unless the response is an allowed redirect.
There will be no more OnHeader() calls. */
virtual void OnHeadersFinished() {}
/** Called when the next fragment of the response body is received, unless the response is an allowed redirect.
This can be called multiple times, as data arrives over the network. */
virtual void OnBodyData(const void * a_Data, size_t a_Size) {}
/** Called after the response body has been fully reported by OnBody() calls, unless the response is an allowed redirect.
There will be no more OnBody() calls. */
virtual void OnBodyFinished() {}
/** Called when an asynchronous error is encountered. */
virtual void OnError(const AString & a_ErrorMsg) {}
/** Called when a redirect is to be followed.
This is called even if the redirecting is prohibited by the options; in such an event, this call will be
followed by OnError().
If a response indicates a redirect (and the request allows redirecting), the regular callbacks
OnStatusLine(), OnHeader(), OnHeadersFinished(), OnBodyData() and OnBodyFinished() are not called
for such a response; instead, the redirect is silently attempted. */
virtual void OnRedirecting(const AString & a_NewLocation) {}
};
typedef std::unique_ptr<cCallbacks> cCallbacksPtr;
/** Used for HTTP status codes. */
enum eHTTPStatus
{
HTTP_STATUS_OK = 200,
HTTP_STATUS_MULTIPLE_CHOICES = 300, // MAY have a redirect using the "Location" header
HTTP_STATUS_MOVED_PERMANENTLY = 301, // redirect using the "Location" header
HTTP_STATUS_FOUND = 302, // redirect using the "Location" header
HTTP_STATUS_SEE_OTHER = 303, // redirect using the "Location" header
HTTP_STATUS_TEMPORARY_REDIRECT = 307, // redirect using the "Location" header
};
/** Makes a network request to the specified URL, using the specified method (if applicable).
The response is reported via the a_ResponseCallback callback, in a single call.
The metadata about the response (HTTP headers) are reported via a_InfoCallback before the a_ResponseCallback call.
If there is an asynchronous error, it is reported in via the a_ErrorCallback.
If there is an immediate error (misformatted URL etc.), the function returns false and an error message.
a_Headers contains additional headers to use for the request.
a_Body specifies optional body to include with the request, if applicable.
a_Options contains various options for the request that govern the request behavior, but aren't sent to the server,
such as the proxy server, whether to follow redirects, and client certificate for TLS. */
static std::pair<bool, AString> Request(
const AString & a_Method,
const AString & a_URL,
cCallbacksPtr && a_Callbacks,
AStringMap && a_Headers,
AString && a_Body,
AStringMap && a_Options
);
/** Alias for Request("GET", ...) */
static std::pair<bool, AString> Get(
const AString & a_URL,
cCallbacksPtr && a_Callbacks,
AStringMap a_Headers = AStringMap(),
const AString & a_Body = AString(),
AStringMap a_Options = AStringMap()
);
/** Alias for Request("POST", ...) */
static std::pair<bool, AString> Post(
const AString & a_URL,
cCallbacksPtr && a_Callbacks,
AStringMap && a_Headers,
AString && a_Body,
AStringMap && a_Options
);
/** Alias for Request("PUT", ...) */
static std::pair<bool, AString> Put(
const AString & a_URL,
cCallbacksPtr && a_Callbacks,
AStringMap && a_Headers,
AString && a_Body,
AStringMap && a_Options
);
};
| [
"github@xoft.cz"
] | github@xoft.cz |
78c99dff372d89ccd5e36d8a9f82b99c6d7358d5 | 9de18ef120a8ae68483b866c1d4c7b9c2fbef46e | /third_party/concurrentqueue/benchmarks/boost/type_traits/is_rvalue_reference.hpp | 93cd0bf187047d4930ad02d98a1724c349761a0d | [
"BSL-1.0",
"BSD-2-Clause",
"LicenseRef-scancode-free-unknown",
"Zlib"
] | permissive | google/orbit | 02a5b4556cd2f979f377b87c24dd2b0a90dff1e2 | 68c4ae85a6fe7b91047d020259234f7e4961361c | refs/heads/main | 2023-09-03T13:14:49.830576 | 2023-08-25T06:28:36 | 2023-08-25T06:28:36 | 104,358,587 | 2,680 | 325 | BSD-2-Clause | 2023-08-25T06:28:37 | 2017-09-21T14:28:35 | C++ | UTF-8 | C++ | false | false | 882 | hpp |
// (C) John Maddock 2010.
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
//
// See http://www.boost.org/libs/type_traits for most recent version including documentation.
#ifndef BOOST_TT_IS_RVALUE_REFERENCE_HPP_INCLUDED
#define BOOST_TT_IS_RVALUE_REFERENCE_HPP_INCLUDED
#include <boost/type_traits/config.hpp>
// should be the last #include
#include <boost/type_traits/detail/bool_trait_def.hpp>
namespace boost {
BOOST_TT_AUX_BOOL_TRAIT_DEF1(is_rvalue_reference,T,false)
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
BOOST_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC1_1(typename T,is_rvalue_reference,T&&,true)
#endif
} // namespace boost
#include <boost/type_traits/detail/bool_trait_undef.hpp>
#endif // BOOST_TT_IS_REFERENCE_HPP_INCLUDED
| [
"pierric.gimmig@gmail.com"
] | pierric.gimmig@gmail.com |
d1f54a7b90e1f26ee95b9cb428eb77f382c2d04b | dffec5fe339883a8b84be0122eef6a3c64a4fa07 | /src/ctrl/colorpicker.h | 6df1264df4cce43af021633f8b9d3cceae8c8cdf | [] | no_license | ongbe/Memmon | 0e346b161c9b6538f6135eb87a60c14648de7e27 | 6bfbc6158a9b6d0d39ff4795a47501071855454f | refs/heads/master | 2021-01-18T14:29:45.299538 | 2013-02-17T14:51:01 | 2013-02-17T14:51:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 363 | h | #ifndef COLORPICKER_H
#define COLORPICKER_H
#include <QObject>
#include <QColor>
#include <QTime>
#define COLORPICKER_INCREMENT 5
#define COLORPICKER_INIT_INDEX 10
class ColorPicker
{
public:
ColorPicker();
QColor GetColor();
void Reset();
int m_nIndex;
QList<QColor> m_clrList;
void SetStartIndex(int index);
};
#endif // COLORPICKER_H
| [
"kimtaikee@gmail.com"
] | kimtaikee@gmail.com |
9ba8ba81069de290222c8b734e4d7c602a3c1431 | 5e34b73f3b5b57aa9fab98591adc451ea04d5ff2 | /groups/bsl/bslstl/bslstl_multimap.h | 285456eb033d30a172ee35ddf0ea7ecd63770b86 | [
"MIT"
] | permissive | yangg86/bsl | ff0f3e505f5daea975fc93092c54ab9a7e68db37 | ae1c8ab60f8daff69718bda575d044ebdeae484b | refs/heads/master | 2021-01-20T22:55:42.547882 | 2012-11-13T21:03:57 | 2012-11-13T21:03:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 85,716 | h | // bslstl_multimap.h -*-C++-*-
#ifndef INCLUDED_BSLSTL_MULTIMAP
#define INCLUDED_BSLSTL_MULTIMAP
#ifndef INCLUDED_BSLS_IDENT
#include <bsls_ident.h>
#endif
BSLS_IDENT("$Id: $")
//@PURPOSE: Provide an STL-compliant multimap class.
//
//@CLASSES:
// bsl::multimap STL-compatible multimap template
//
//@SEE_ALSO: bslstl_map, bslstl_multiset
//
//@DESCRIPTION: This component defines a single class template 'multimap',
// implementing the standard container holding an ordered sequence of key-value
// pairs (possibly having duplicate keys), and presenting a mapping from the
// keys (of a template parameter type, 'KEY') to their associated values (of
// another template parameter type, 'VALUE').
//
// An instantiation of 'multimap' is an allocator-aware, value-semantic type
// whose salient attributes are its size (number of key-value pairs) and the
// ordered sequence of key-value pairs the multimap contains. If 'multimap' is
// instantiated with either a key type or mapped-value type that is not itself
// value-semantic, then it will not retain all of its value-semantic qualities.
// In particular, if a either the key or value type cannot be tested for
// equality, then a 'multimap' containing that type cannot be tested for
// equality. It is even possible to instantiate 'multimap' with a key or
// mapped-value type that does not have a copy-constructor, in which case the
// 'multimap' will not be copyable.
//
// A 'multimap' meets the requirements of an associative container with
// bidirectional iterators in the C++11 standard [23.2.4]. The 'multimap'
// implemented here adheres to the C++11 standard, except that it does not have
// interfaces that take rvalue references, 'initializer_lists', 'emplace', or
// operations taking a variadic number of template parameters. Note that
// excluded C++11 features are those that require (or are greatly simplified
// by) C++11 compiler support.
//
///Requirements on 'KEY' and 'VALUE'
///---------------------------------
// A 'multimap' is a fully "Value-Semantic Type" (see {'bsldoc_glossary'}) only
// if the supplied 'KEY' and 'VALUE' template parameters are themselves fully
// value-semantic. It is possible to instantiate a 'multimap' with 'KEY' and
// 'VALUE' parameter arguments that do not provide a full set of value-semantic
// operations, but then some methods of the container may not be instantiable.
// The following terminology, adopted from the C++11 standard, is used in the
// function documentation of 'multimap' to describe a function's requirements
// for the 'KEY' and 'VALUE' template parameters. These terms are also defined
// in section [17.6.3.1] of the C++11 standard. Note that, in the context of a
// 'multimap' instantiation, the requirements apply specifically to the
// multimap's entry type, 'value_type', which is an alias for 'bsl::pair<KEY,
// VALUE>'.
//
//: "default-constructible": The type provides a default constructor.
//:
//: "copy-constructible": The type provides a copy constructor.
//:
//: "equality-comparable": The type provides an equality-comparison operator
//: that defines an equivalence relationship and is both reflexive and
//: transitive.
//:
//: "less-than-comparable": The type provides a less-than operator, which
//: defines a strict weak ordering relation on values of the type.
//
///Memory Allocation
///-----------------
// The type supplied as a multimap's 'ALLOCATOR' template parameter determines
// how that multimap will allocate memory. The 'multimap' template supports
// allocators meeting the requirements of the C++11 standard [17.6.3.5], in
// addition it supports scoped-allocators derived from the 'bslma::Allocator'
// memory allocation protocol. Clients intending to use 'bslma' style
// allocators should use the template's default 'ALLOCATOR' type: The default
// type for the 'ALLOCATOR' template parameter, 'bsl::allocator', provides a
// C++11 standard-compatible adapter for a 'bslma::Allocator' object.
//
///'bslma'-Style Allocators
/// - - - - - - - - - - - -
// If the (template parameter) type 'ALLOCATOR' of an 'multimap' instantiation'
// is 'bsl::allocator', then objects of that multimap type will conform to the
// standard behavior of a 'bslma'-allocator-enabled type. Such a multimap
// accepts an optional 'bslma::Allocator' argument at construction. If the
// address of a 'bslma::Allocator' object is explicitly supplied at
// construction, it will be used to supply memory for the 'multimap' throughout
// its lifetime; otherwise, the multimap will use the default allocator
// installed at the time of the multimap's construction (see 'bslma_default').
// In addition to directly allocating memory from the indicated
// 'bslma::Allocator', a multimap supplies that allocator's address to the
// constructors of contained objects of the (template parameter) types 'KEY'
// and 'VALUE', if respectively, the types define the
// 'bslma::UsesBslmaAllocator' trait.
//
///Operations
///----------
// This section describes the run-time complexity of operations on instances
// of 'multimap':
//..
// Legend
// ------
// 'K' - (template parameter) type 'KEY' of the 'multimap'
// 'V' - (template parameter) type 'VALUE' of the 'multimap'
// 'a', 'b' - two distinct objects of type 'multimap<K, V>'
// 'n', 'm' - number of elements in 'a' and 'b' respectively
// 'value_type' - 'multimap<K, V>::value_type'
// 'c' - comparator providing an ordering for objects of type 'K'
// 'al - an STL-style memory allocator
// 'i1', 'i2' - two iterators defining a sequence of 'value_type' objects
// 'k' - an object of type 'K'
// 'v' - an object of type 'V'
// 'p1', 'p2' - two iterators belonging to 'a'
// distance(i1,i2) - the number of elements in the range [i1, i2)
//
// +----------------------------------------------------+--------------------+
// | Operation | Complexity |
// +====================================================+====================+
// | multimap<K, V> a; (default construction) | O[1] |
// | multimap<K, V> a(al); | |
// | multimap<K, V> a(c, al); | |
// +----------------------------------------------------+--------------------+
// | multimap<K, V> a(b); (copy construction) | O[n] |
// | multimap<K, V> a(b, al); | |
// +----------------------------------------------------+--------------------+
// | multimap<K, V> a(i1, i2); | O[N] if [i1, i2) |
// | multimap<K, V> a(i1, i2, al); | is sorted with |
// | multimap<K, V> a(i1, i2, c, al); | 'a.value_comp()', |
// | | O[N * log(N)] |
// | | otherwise, where N |
// | | is distance(i1,i2) |
// +----------------------------------------------------+--------------------+
// | a.~multimap<K, V>(); (destruction) | O[n] |
// +----------------------------------------------------+--------------------+
// | a = b; (assignment) | O[n] |
// +----------------------------------------------------+--------------------+
// | a.begin(), a.end(), a.cbegin(), a.cend(), | O[1] |
// | a.rbegin(), a.rend(), a.crbegin(), a.crend() | |
// +----------------------------------------------------+--------------------+
// | a == b, a != b | O[n] |
// +----------------------------------------------------+--------------------+
// | a < b, a <= b, a > b, a >= b | O[n] |
// +----------------------------------------------------+--------------------+
// | a.swap(b), swap(a,b) | O[1] if 'a' and |
// | | 'b' use the same |
// | | allocator, |
// | | O[n + m] otherwise |
// +----------------------------------------------------+--------------------+
// | a.size() | O[1] |
// +----------------------------------------------------+--------------------+
// | a.max_size() | O[1] |
// +----------------------------------------------------+--------------------+
// | a.empty() | O[1] |
// +----------------------------------------------------+--------------------+
// | get_allocator() | O[1] |
// +----------------------------------------------------+--------------------+
// | a.insert(value_type(k, v)) | O[log(n)] |
// +----------------------------------------------------+--------------------+
// | a.insert(p1, value_type(k, v)) | amortized constant |
// | | if the value is |
// | | inserted right |
// | | before p1, |
// | | O[log(n)] |
// | | otherwise |
// +----------------------------------------------------+--------------------+
// | a.insert(i1, i2) | O[log(N) * |
// | | distance(i1,i2)] |
// | | |
// | | where N is |
// | | n + distance(i1,i2)|
// +----------------------------------------------------+--------------------+
// | a.erase(p1) | amortized constant |
// +----------------------------------------------------+--------------------+
// | a.erase(k) | O[log(n) + |
// | | a.count(k)] |
// +----------------------------------------------------+--------------------+
// | a.erase(p1, p2) | O[log(n) + |
// | | distance(p1, p2)] |
// +----------------------------------------------------+--------------------+
// | a.erase(p1, p2) | O[log(n) + |
// | | distance(p1, p2)] |
// +----------------------------------------------------+--------------------+
// | a.clear() | O[n] |
// +----------------------------------------------------+--------------------+
// | a.key_comp() | O[1] |
// +----------------------------------------------------+--------------------+
// | a.value_comp() | O[1] |
// +----------------------------------------------------+--------------------+
// | a.find(k) | O[log(n)] |
// +----------------------------------------------------+--------------------+
// | a.count(k) | O[log(n) + |
// | | a.count(k)] |
// +----------------------------------------------------+--------------------+
// | a.lower_bound(k) | O[log(n)] |
// +----------------------------------------------------+--------------------+
// | a.upper_bound(k) | O[log(n)] |
// +----------------------------------------------------+--------------------+
// | a.equal_range(k) | O[log(n)] |
// +----------------------------------------------------+--------------------+
//..
//
///Usage
///-----
// In this section we show intended use of this component.
//
///Example 1: Creating a Phone Book
/// - - - - - - - - - - - - - - - -
// In this example, we will define a class 'PhoneBook', that provides a mapping
// of names to phone numbers. The 'PhoneBook' class will be implemented using
// a 'bsl::multimap', and will supply manipulators, allowing a client to add or
// remove entries from the phone book, as well as accessors, allowing clients
// to efficiently lookup entries by name, and to iterate over the entries in
// the phone book in sorted order.
//
// Note that this example uses a type 'string' that is based on the standard
// type 'string' (see 'bslstl_string'). For the sake of brevity, the
// implementation of 'string' is not explored here.
//
// First, we define an alias for a pair of 'string' objects that we will use to
// represent names in the phone book:
//..
// typedef bsl::pair<string, string> FirstAndLastName;
// // This 'typedef' provides an alias for a pair of 'string' objects,
// // whose 'first' and 'second' elements refer to the first and last
// // names of a person, respectively.
//..
// Then, we define a comparison functor for 'FirstAndLastName' objects (note
// that this comparator is required because we intend for the last name to
// take precedence over the first name in the ordering of entries maintained
// by the phone book, which differs from the behavior supplied by 'operator<'
// for 'pair'):
//..
// struct FirstAndLastNameLess {
// // This 'struct' defines an ordering on 'FirstAndLastName' values,
// // allowing them to be included in sorted containers such as
// // 'bsl::multimap'. Note that last name (the 'second' member of a
// // 'FirstAndLastName' value) takes precedence over first name in the
// // ordering defined by this functor.
//
// bool operator()(const FirstAndLastName& lhs,
// const FirstAndLastName& rhs) const
// // Return 'true' if the value of the specified 'lhs' is less than
// // (ordered before) the value of the specified 'rhs', and 'false'
// // otherwise. The 'lhs' value is considered less than the 'rhs'
// // value if the second value in the 'lhs' pair (the last name) is
// // less than the second value in the 'rhs' pair or, if the second
// // values are equal, if the first value in the 'lhs' pair (the
// // first name) is less than the first value in the 'rhs' pair.
// {
// int cmp = std::strcmp(lhs.second.c_str(), rhs.second.c_str());
// if (0 == cmp) {
// cmp = std::strcmp(lhs.first.c_str(), rhs.first.c_str());
// }
// return cmp < 0;
// }
// };
//..
// Next, we define the public interface for 'PhoneBook':
//..
// class PhoneBook {
// // This class provides a mapping of a person's name to their phone
// // number. Names within a 'Phonebook' are represented using a using
// // 'FirstAndLastName' object, and phone numbers are represented using a
// // 'bsls::Types::Uint64' value.
//
//..
// Here, we create a type alias, 'NameToNumberMap', for a 'bsl::multimap' that
// will serve as the data member for a 'PhoneBook'. A 'NameToNumberMap' has
// keys of type 'FirstAndLastName', mapped-values of type
// 'bsls::Types::Uint64', and a comparator of type 'FirstAndLastNameLess'. We
// use the default 'ALLOCATOR' template parameter as we intend to use
// 'PhoneBook' with 'bslma' style allocators:
//..
// // PRIVATE TYPES
// typedef bsl::multimap<FirstAndLastName,
// bsls::Types::Uint64,
// FirstAndLastNameLess> NameToNumberMap;
// // This 'typedef' is an alias for a mapping between names and phone
// // numbers.
//
// // DATA
// NameToNumberMap d_nameToNumber; // mapping of names to phone numbers
//
// // FRIENDS
// friend bool operator==(const PhoneBook& lhs, const PhoneBook& rhs);
//
// public:
// // PUBLIC TYPES
// typedef bsls::Types::Uint64 PhoneNumber;
// // This 'typedef' provides an alias for the type of an unsigned
// // integers used to represent phone-numbers in a 'PhoneBook'.
//
// typedef NameToNumberMap::const_iterator ConstIterator;
// // This 'typedef' provides an alias for the type of an iterator
// // providing non-modifiable access to the entries in a 'PhoneBook'.
//
// // CREATORS
// PhoneBook(bslma::Allocator *basicAllocator = 0);
// // Create an empty 'PhoneBook' object. Optionally specify a
// // 'basicAllocator' used to supply memory. If 'basicAllocator' is
// // 0, the currently installed default allocator is used.
//
// PhoneBook(const PhoneBook& original,
// bslma::Allocator *basicAllocator = 0);
// // Create a 'PhoneBook' object having the same value as the
// // specified 'original' object. Optionally specify a
// // 'basicAllocator' used to supply memory. If 'basicAllocator' is
// // 0, the currently installed default allocator is used.
//
// //! ~PhoneBook() = default;
// // Destroy this object.
//
// // MANIPULATORS
// PhoneBook& operator=(const PhoneBook& rhs);
// // Assign to this object the value of the specified 'rhs' object,
// // and return a reference providing modifiable access to this
// // object.
//
// void addEntry(const FirstAndLastName& name, PhoneNumber number);
// // Add an entry to this phone book having the specified 'name' and
// // 'number'. The behavior is undefined unless 'name.first' and
// // 'name.end' are non-empty strings.
//
// int removeEntry(const FirstAndLastName& name, PhoneNumber number);
// // Remove the entries from this phone book having the specified
// // 'name' and 'number', if they exists, and return the number of
// // removed entries; otherwise, return 0 with no other effects.
//
// // ACCESSORS
// bsl::pair<ConstIterator, ConstIterator> lookupByName(
// const FirstAndLastName& name) const;
// // Return a pair of iterators to the ordered sequence of entries
// // held in this phone book having the specified 'name', where the
// // first iterator is position at the start of the sequence, and the
// // second is positioned one past the last entry in the sequence.
// // If 'name' does not exist in this phone book, then the two
// // returned iterators will have the same value.
//
// ConstIterator begin() const;
// // Return an iterator providing non-modifiable access to the first
// // entry in the ordered sequence of entries held in this phone
// // book, or the past-the-end iterator if this phone book is empty.
//
// ConstIterator end() const;
// // Return an iterator providing non-modifiable access to the
// // past-the-end entry in the ordered sequence of entries maintained
// // by this phone book.
//
// int numEntries() const;
// // Return the number of entries contained in this phone book.
// };
//..
// Then, we declare the free operators for 'PhoneBook':
//..
// inline
// bool operator==(const PhoneBook& lhs, const PhoneBook& rhs);
// // Return 'true' if the specified 'lhs' and 'rhs' objects have the same
// // value, and 'false' otherwise. Two 'PhoneBook' objects have the
// // same value if they have the same number of entries, and each
// // corresponding entry, in their respective ordered sequence of
// // entries, is the same.
//
// inline
// bool operator!=(const PhoneBook& lhs, const PhoneBook& rhs);
// // Return 'true' if the specified 'lhs' and 'rhs' objects do not have
// // the same value, and 'false' otherwise. Two 'PhoneBook' objects do
// // not have the same value if they either differ in their number of
// // contained entries, or if any of the corresponding entries, in their
// // respective ordered sequences of entries, is not the same.
//..
// Now, we define the implementations methods of the 'PhoneBook' class:
//..
// // CREATORS
// inline
// PhoneBook::PhoneBook(bslma::Allocator *basicAllocator)
// : d_nameToNumber(FirstAndLastNameLess(), basicAllocator)
// {
// }
//..
// Notice that, on construction, we pass the contained 'bsl::multimap'
// ('d_nameToNumber'), a default constructed 'FirstAndLastNameLess' object that
// it will use to perform comparisons, and the allocator supplied to
// 'PhoneBook' at construction'.
//..
// inline
// PhoneBook::PhoneBook(const PhoneBook& original,
// bslma::Allocator *basicAllocator)
// : d_nameToNumber(original.d_nameToNumber, basicAllocator)
// {
// }
//
// // MANIPULATORS
// inline
// PhoneBook& PhoneBook::operator=(const PhoneBook& rhs)
// {
// d_nameToNumber = rhs.d_nameToNumber;
// return *this;
// }
//
// inline
// void PhoneBook::addEntry(const FirstAndLastName& name, PhoneNumber number)
// {
// BSLS_ASSERT(!name.first.empty());
// BSLS_ASSERT(!name.second.empty());
//
// d_nameToNumber.insert(NameToNumberMap::value_type(name, number));
// }
//
// inline
// int PhoneBook::removeEntry(const FirstAndLastName& name,
// PhoneNumber number)
// {
//
// bsl::pair<NameToNumberMap::iterator, NameToNumberMap::iterator> range =
// d_nameToNumber.equal_range(name);
//
// NameToNumberMap::iterator itr = range.first;
// int numRemovedEntries = 0;
//
// while (itr != range.second) {
// if (itr->second == number) {
// itr = d_nameToNumber.erase(itr);
// ++numRemovedEntries;
// }
// else {
// ++itr;
// }
// }
//
// return numRemovedEntries;
// }
//
// // ACCESSORS
// inline
// bsl::pair<PhoneBook::ConstIterator, PhoneBook::ConstIterator>
// PhoneBook::lookupByName(const FirstAndLastName& name) const
// {
// return d_nameToNumber.equal_range(name);
// }
//
// inline
// PhoneBook::ConstIterator PhoneBook::begin() const
// {
// return d_nameToNumber.begin();
// }
//
// inline
// PhoneBook::ConstIterator PhoneBook::end() const
// {
// return d_nameToNumber.end();
// }
//
// inline
// int PhoneBook::numEntries() const
// {
// return d_nameToNumber.size();
// }
//..
// Finally, we implement the free operators for 'PhoneBook':
//..
// inline
// bool operator==(const PhoneBook& lhs, const PhoneBook& rhs)
// {
// return lhs.d_nameToNumber == rhs.d_nameToNumber;
// }
//
// inline
// bool operator!=(const PhoneBook& lhs, const PhoneBook& rhs)
// {
// return !(lhs == rhs);
// }
//..
#if defined(BSL_OVERRIDES_STD) && !defined(BSL_STDHDRS_PROLOGUE_IN_EFFECT)
#error "include <bsl_map.h> instead of <bslstl_multimap.h> in \
BSL_OVERRIDES_STD mode"
#endif
#ifndef INCLUDED_BSLSCM_VERSION
#include <bslscm_version.h>
#endif
#ifndef INCLUDED_BSLSTL_ALLOCATOR
#include <bslstl_allocator.h>
#endif
#ifndef INCLUDED_BSLSTL_PAIR
#include <bslstl_pair.h>
#endif
#ifndef INCLUDED_BSLSTL_MAPCOMPARATOR
#include <bslstl_mapcomparator.h>
#endif
#ifndef INCLUDED_BSLSTL_STDEXCEPTUTIL
#include <bslstl_stdexceptutil.h>
#endif
#ifndef INCLUDED_BSLSTL_TREEITERATOR
#include <bslstl_treeiterator.h>
#endif
#ifndef INCLUDED_BSLSTL_TREENODE
#include <bslstl_treenode.h>
#endif
#ifndef INCLUDED_BSLSTL_TREENODEPOOL
#include <bslstl_treenodepool.h>
#endif
#ifndef INCLUDED_BSLALG_SWAPUTIL
#include <bslalg_swaputil.h>
#endif
#ifndef INCLUDED_BSLALG_RANGECOMPARE
#include <bslalg_rangecompare.h>
#endif
#ifndef INCLUDED_BSLALG_RBTREEANCHOR
#include <bslalg_rbtreeanchor.h>
#endif
#ifndef INCLUDED_BSLALG_RBTREENODE
#include <bslalg_rbtreenode.h>
#endif
#ifndef INCLUDED_BSLALG_RBTREEUTIL
#include <bslalg_rbtreeutil.h>
#endif
#ifndef INCLUDED_BSLALG_TYPETRAITHASSTLITERATORS
#include <bslalg_typetraithasstliterators.h>
#endif
#ifndef INCLUDED_FUNCTIONAL
#include <functional>
#define INCLUDED_FUNCTIONAL
#endif
namespace bsl {
// ==============
// class multimap
// ==============
template <class KEY,
class VALUE,
class COMPARATOR = std::less<KEY>,
class ALLOCATOR = bsl::allocator<bsl::pair<const KEY, VALUE> > >
class multimap {
// This class template implements a value-semantic container type holding
// an ordered sequence of key-value pairs having possibly duplicate keys
// that provide a mapping from keys (of the template parameter type, 'KEY')
// to their associated values (of another template parameter type,
// 'VALUE').
//
// This class:
//: o supports a complete set of *value-semantic* operations
//: o except for 'bdex' serialization
//: o is *exception-neutral* (agnostic except for the 'at' method)
//: o is *alias-safe*
//: o is 'const' *thread-safe*
// For terminology see {'bsldoc_glossary'}.
// PRIVATE TYPES
typedef bsl::pair<const KEY, VALUE> ValueType;
// This typedef is an alias for the type of key-value pair objects
// maintained by this multimap.
typedef BloombergLP::bslstl::MapComparator<KEY, VALUE, COMPARATOR>
Comparator;
// This typedef is an alias for the comparator used internally by this
// multimap.
typedef BloombergLP::bslstl::TreeNode<ValueType> Node;
// This typedef is an alias for the type of nodes held by the tree (of
// nodes) used to implement this multimap.
typedef BloombergLP::bslstl::TreeNodePool<ValueType, ALLOCATOR>
NodeFactory;
// This typedef is an alias for the factory type used to create and
// destroy 'Node' objects.
typedef typename bsl::allocator_traits<ALLOCATOR> AllocatorTraits;
// This typedef is an alias for the allocator traits type associated
// with this container.
struct DataWrapper : public Comparator {
// This struct is wrapper around the comparator and allocator data
// members. It takes advantage of the empty-base optimization (EBO) so
// that if the allocator is stateless, it takes up no space.
//
// TBD: This struct should eventually be replaced by the use of a
// general EBO-enabled component that provides a 'pair'-like
// interface or a 'tuple'.
NodeFactory d_pool; // pool of 'Node' objects
explicit DataWrapper(const COMPARATOR& comparator,
const ALLOCATOR& allocator);
// Create a 'DataWrapper' object with the specified 'comparator'
// and 'allocator'.
};
// DATA
DataWrapper d_compAndAlloc;
// comparator and pool of 'Node'
// objects
BloombergLP::bslalg::RbTreeAnchor d_tree; // balanced tree of 'Node'
// objects
private:
// PRIVATE MANIPULATORS
NodeFactory& nodeFactory();
// Return a reference providing modifiable access to the
// node-allocator for this tree.
Comparator& comparator();
// Return a reference providing modifiable access to the
// comparator for this tree.
void quickSwap(multimap& other);
// Efficiently exchange the value and comparator of this object with
// the value of the specified 'other' object. This method provides
// the no-throw exception-safety guarantee. The behavior is undefined
// unless this object was created with the same allocator as 'other'.
// PRIVATE ACCESSORS
const NodeFactory& nodeFactory() const;
// Return a reference providing non-modifiable access to the
// node-allocator for this tree.
const Comparator& comparator() const;
// Return a reference providing non-modifiable access to the
// comparator for this tree.
public:
// PUBLIC TYPES
typedef KEY key_type;
typedef VALUE mapped_type;
typedef bsl::pair<const KEY, VALUE> value_type;
typedef COMPARATOR key_compare;
typedef ALLOCATOR allocator_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef typename AllocatorTraits::size_type size_type;
typedef typename AllocatorTraits::difference_type difference_type;
typedef typename AllocatorTraits::pointer pointer;
typedef typename AllocatorTraits::const_pointer const_pointer;
typedef BloombergLP::bslstl::TreeIterator<value_type,
Node,
difference_type> iterator;
typedef BloombergLP::bslstl::TreeIterator<const value_type,
Node,
difference_type> const_iterator;
typedef bsl::reverse_iterator<iterator> reverse_iterator;
typedef bsl::reverse_iterator<const_iterator> const_reverse_iterator;
class value_compare {
// This nested class defines a mechanism for comparing two objects of
// the (template parameter) type 'COMPARATOR'. Note that this class
// exactly matches its definition in the C++11 standard [23.4.5.1];
// otherwise we would have implemented it as a separate component-local
// class.
// FRIENDS
friend class multimap;
protected:
COMPARATOR comp; // we would not have elected to make this data
// member protected ourselves
value_compare(COMPARATOR c) : comp(c) {}
// Create a 'value_compare' object that will delegate to the
// specified 'comparator' for comparisons.
public:
typedef bool result_type;
// This 'typedef' is an alias for the result type of a call to
// the overload of 'operator()' (the comparison function) provided
// by a 'multimap::value_compare' object.
typedef value_type first_argument_type;
// This 'typedef' is an alias for the type of the first parameter
// of the overload of 'operator()' (the comparison function)
// provided by a 'multimap::value_compare' object.
typedef value_type second_argument_type;
// This 'typedef' is an alias for the type of the second parameter
// of the overload of 'operator()' (the comparison function)
// provided by a 'multimap::value_compare' object.
bool operator()(const value_type& x, const value_type& y) const
// Return 'true' if the specified 'x' object is ordered before the
// specified 'y' object, as determined by the comparator supplied
// at construction.
{
return comp(x.first, y.first);
}
};
public:
// CREATORS
explicit multimap(const COMPARATOR& comparator = COMPARATOR(),
const ALLOCATOR& allocator = ALLOCATOR())
// Construct an empty multimap. Optionally specify a 'comparator' used
// to order key-value pairs contained in this object. If 'comparator'
// is not supplied, a default-constructed object of the (template
// parameter) type 'COMPARATOR' is used. Optionally specify an
// 'allocator' used to supply memory. If 'allocator' is not supplied,
// a default-constructed object of the (template parameter) type
// ALLOCATOR' is used. If the 'ALLOCATOR' argument is of type
// 'bsl::allocator' (the default), then 'allocator', if supplied,
// shall be convertible to 'bslma::Allocator *'. If the 'ALLOCATOR'
// argument is of type 'bsl::allocator' and 'allocator' is not
// supplied, the currently installed default allocator will be used to
// supply memory.
: d_compAndAlloc(comparator, allocator)
, d_tree()
{
// The implementation is placed here in the class definition to
// workaround an AIX compiler bug, where the constructor can fail to
// compile because it is unable to find the definition of the default
// argument. This occurs when a templatized class wraps around the
// container and the comparator is defined after the new class.
}
explicit multimap(const ALLOCATOR& allocator);
// Construct an empty multimap that will use the specified 'allocator'
// to supply memory. Use a default-constructed object of the (template
// parameter) type 'COMPARATOR' to order the key-value pairs contained
// in this multimap. If the template parameter 'ALLOCATOR' argument is
// of type 'bsl::allocator' (the default) then 'allocator' shall be
// convertible to 'bslma::Allocator *'.
multimap(const multimap& original);
// Construct a multimap having the same value as the specified
// 'original'. Use a copy of 'original.key_comp()' to order the
// key-value pairs contained in this multimap. Use the allocator
// returned by 'bsl::allocator_traits<ALLOCATOR>::
// select_on_container_copy_construction(original.allocator())' to
// allocate memory. If the (template parameter) type 'ALLOCATOR' is
// of type 'bsl::allocator' (the default), the currently installed
// default allocator will be used to supply memory. This method
// requires that the (template parameter) types 'KEY' and 'VALUE'
// both be "copy-constructible" (see {Requirements on 'KEY' and
// 'VALUE'}).
multimap(const multimap& original, const ALLOCATOR& allocator);
// Construct a multimap having the same value as that of the specified
// 'original' that will use the specified 'allocator' to supply memory.
// Use a copy of 'original.key_comp()' to order the key-value pairs
// contained in this multimap. If the template parameter 'ALLOCATOR'
// argument is of type 'bsl::allocator' (the default) then 'allocator'
// shall be convertible to 'bslma::Allocator *'. This method requires
// that the (template parameter) types 'KEY' and 'VALUE' both be
// "copy-constructible" (see {Requirements on 'KEY' and 'VALUE'}).
template <class INPUT_ITERATOR>
multimap(INPUT_ITERATOR first,
INPUT_ITERATOR last,
const COMPARATOR& comparator = COMPARATOR(),
const ALLOCATOR& allocator = ALLOCATOR());
// Construct a multimap, and insert each 'value_type' object in the
// sequence starting at the specified 'first' element, and ending
// immediately before the specified 'last' element, ignoring those
// pairs having a key that appears earlier in the sequence. Optionally
// specify a 'comparator' used to order key-value pairs contained in
// this object. If 'comparator' is not supplied, a default-constructed
// object of the (template parameter) type 'COMPARATOR' is used.
// Optionally specify a 'allocator' used to supply memory. If
// 'allocator' is not supplied, a default-constructed object of the
// (template parameter) type 'ALLOCATOR' is used. If the template
// parameter 'ALLOCATOR' argument is of type 'bsl::allocator' (the
// default) then 'allocator', if supplied, shall be convertible to
// 'bslma::Allocator *'. If the template parameter 'ALLOCATOR'
// argument is of type 'bsl::allocator' and 'allocator' is not
// supplied, the currently installed default allocator will be used to
// supply memory. If the sequence 'first' and 'last' is ordered
// according to the identified 'comparator' then this operation will
// have O[N] complexity, where N is the number of elements between
// 'first' and 'last', otherwise this operation will have O[N * log(N)]
// complexity. The (template parameter) type 'INPUT_ITERATOR' shall
// meet the requirements of an input iterator defined in the C++11
// standard [24.2.3] providing access to values of a type convertible
// to 'value_type'. The behavior is undefined unless 'first' and
// 'last' refer to a sequence of valid values where 'first' is at a
// position at or before 'last'. This method requires that the
// (template parameter) types 'KEY' and 'VALUE' both be
// "copy-constructible" (see {Requirements on 'KEY' and 'VALUE'}).
~multimap();
// Destroy this object;
// MANIPULATORS
multimap& operator=(const multimap& rhs);
// Assign to this object the value and comparator of the specified
// 'rhs' object, propagate to this object the allocator of 'rhs' if the
// 'ALLOCATOR' type has trait 'propagate_on_container_copy_assignment',
// and return a reference providing modifiable access to this object.
// This method requires that the (template parameter) types 'KEY' and
// 'VALUE' both be "copy-constructible" (see {Requirements on 'KEY' and
// 'VALUE'}).
iterator begin();
// Return an iterator providing modifiable access to the first
// 'value_type' object in the ordered sequence of 'value_type' objects
// maintained by this multimap, or the 'end' iterator if this multimap
// is empty.
iterator end();
// Return an iterator providing modifiable access to the past-the-end
// element in the ordered sequence of 'value_type' objects maintained
// by this multimap.
reverse_iterator rbegin();
// Return a reverse iterator providing modifiable access to the last
// 'value_type' object in the ordered sequence of 'value_type' objects
// maintained by this multimap, or 'rend' if this multimap is empty.
reverse_iterator rend();
// Return a reverse iterator providing modifiable access to the
// prior-to-the-beginning element in the ordered sequence of
// 'value_type' objects maintained by this multimap.
iterator insert(const value_type& value);
// Insert the specified 'value' into this multimap. If a range
// containing elements equivalent to 'value' already exist, insert
// 'value' at the end of that range. Return an iterator referring to
// the newly inserted 'value_type' object. This method requires that
// the (template parameter) types 'KEY' and 'VALUE' both be
// "copy-constructible" (see {Requirements on 'KEY' and 'VALUE'}).
iterator insert(const_iterator hint, const value_type& value);
// Insert the specified 'value' into this multimap as close as possible
// to the position just prior to the specified 'hint' (in amortized
// constant time if the specified 'hint' is a valid immediate successor
// to the key of 'value'). If 'hint' is not a valid immediate
// successor to the key of 'value', this operation will have O[log(N)]
// complexity, where 'N' is the size of this multimap. The behavior is
// undefined unless 'hint' is a valid iterator into this multimap.
// This method requires that the (template parameter) types 'KEY' and
// 'VALUE' both be "copy-constructible" (see {Requirements on 'KEY' and
// 'VALUE'}).
template <class INPUT_ITERATOR>
void insert(INPUT_ITERATOR first, INPUT_ITERATOR last);
// Insert into this multimap the value of each 'value_type' object in
// the range starting at the specified 'first' iterator and ending
// immediately before the specified 'last' iterator. The (template
// parameter) type 'INPUT_ITERATOR' shall meet the requirements of an
// input iterator defined in the C++11 standard [24.2.3] providing
// access to values of a type convertible to 'value_type'. This method
// requires that the (template parameter) types 'KEY' and 'VALUE' both
// be "copy-constructible" (see {Requirements on 'KEY' and 'VALUE'}).
iterator erase(const_iterator position);
// Remove from this multimap the 'value_type' object at the specified
// 'position', and return an iterator referring to the element
// immediately following the removed element, or to the past-the-end
// position if the removed element was the last element in the sequence
// of elements maintained by this multimap. The behavior is undefined
// unless 'position' refers to a 'value_type' object in this multimap.
size_type erase(const key_type& key);
// Remote from this multimap all 'value_type' objects having the
// specified 'key', if they exist, and return the number of erased
// objects; otherwise, if there is no 'value_type' objects having
// 'key', return 0 with no other effect.
iterator erase(const_iterator first, const_iterator last);
// Remove from this multimap the 'value_type' objects starting at the
// specified 'first' position up to, but including the specified 'last'
// position, and return 'last'. The behavior is undefined unless
// 'first' and 'last' either refer to elements in this multimap or are
// the 'end' iterator, and the 'first' position is at or before the
// 'last' position in the ordered sequence provided by this container.
void swap(multimap& other);
// Exchange the value of this object as well as its comparator with
// those of the specified 'other' object. Additionally if
// 'bslstl::AllocatorTraits<ALLOCATOR>::propagate_on_container_swap' is
// 'true' then exchange the allocator of this object with that of the
// 'other' object, and do not modify either allocator otherwise. This
// method provides the no-throw exception-safety guarantee and
// guarantees O[1] complexity. The behavior is undefined is unless
// either this object was created with the same allocator as 'other' or
// 'propagate_on_container_swap' is 'true'.
void clear();
// Remove all entries from this multimap. Note that the multimap is
// empty after this call, but allocated memory may be retained for
// future use.
iterator find(const key_type& key);
// Return an iterator providing modifiable access to the first
// 'value_type' object having the specified 'key' in ordered sequence
// maintained by this multimap, if such an object exists; otherwise,
// return the past-the-end ('end') iterator.
iterator lower_bound(const key_type& key);
// Return an iterator providing modifiable access to the first (i.e.,
// ordered least) 'value_type' object in this multimap whose key is
// greater-than or equal-to the specified 'key', and the past-the-end
// iterator if this multimap does not contain a 'value_type' object
// whose key is greater-than or equal-to 'key'. Note that this
// function returns the *first* position before which a 'value_type'
// object having 'key' could be inserted into the ordered sequence
// maintained by this multimap, while preserving its ordering.
iterator upper_bound(const key_type& key);
// Return an iterator providing modifiable access to the first (i.e.,
// ordered least) 'value_type' object in this multimap whose key is
// greater than the specified 'key', and the past-the-end iterator if
// this multimap does not contain a 'value_type' object whose key is
// greater-than 'key'. Note that this function returns the *last*
// position before which a 'value_type' object having 'key' could be
// inserted into the ordered sequence maintained by this multimap,
// while preserving its ordering.
bsl::pair<iterator,iterator> equal_range(const key_type& x);
// Return a pair of iterators providing modifiable access to the
// sequence of 'value_type' objects in this multimap having the
// specified 'key', where the the first iterator is positioned at the
// start of the sequence, and the second is positioned one past the end
// of the sequence. The first returned iterator will be
// 'lower_bound(key)'; the second returned iterator will be
// 'upper_bound(key)'; and, if this multimap contains no 'value_type'
// objects having 'key', then the two returned iterators will have the
// same value.
// ACCESSORS
allocator_type get_allocator() const;
// Return (a copy of) the allocator used for memory allocation by this
// multimap.
const_iterator begin() const;
// Return an iterator providing non-modifiable access to the first
// 'value_type' object in the ordered sequence of 'value_type' objects
// maintained by this multimap, or the 'end' iterator if this multimap
// is empty.
const_iterator end() const;
// Return an iterator providing non-modifiable access to the
// past-the-end element in the ordered sequence of 'value_type' objects
// maintained by this multimap.
const_reverse_iterator rbegin() const;
// Return a reverse iterator providing non-modifiable access to the
// last 'value_type' object in the ordered sequence of 'value_type'
// objects maintained by this multimap, or 'rend' if this multimap is
// empty.
const_reverse_iterator rend() const;
// Return a reverse iterator providing non-modifiable access to the
// prior-to-the-beginning element in the ordered sequence of
// 'value_type' objects maintained by this multimap.
const_iterator cbegin() const;
// Return an iterator providing non-modifiable access to the first
// 'value_type' object in the ordered sequence of 'value_type' objects
// maintained by this multimap, or the 'cend' iterator if this multimap
// is empty.
const_iterator cend() const;
// Return an iterator providing non-modifiable access to the
// past-the-end element in the ordered sequence of 'value_type' objects
// maintained by this multimap.
const_reverse_iterator crbegin() const;
// Return a reverse iterator providing non-modifiable access to the
// last 'value_type' object in the ordered sequence of 'value_type'
// objects maintained by this multimap, or 'rend' if this multimap is
// empty.
const_reverse_iterator crend() const;
// Return a reverse iterator providing non-modifiable access to the
// prior-to-the-beginning element in the ordered sequence of
// 'value_type' objects maintained by this multimap.
bool empty() const;
// Return 'true' if this multimap contains no elements, and 'false'
// otherwise.
size_type size() const;
// Return the number of elements in this multimap.
size_type max_size() const;
// Return a theoretical upper bound on the largest number of elements
// that this multimap could possibly hold. Note that there is no
// guarantee that the multimap can successfully grow to the returned
// size, or even close to that size without running out of resources.
key_compare key_comp() const;
// Return the key-comparison functor (or function pointer) used by this
// multimap; if a comparator was supplied at construction, return its
// value, otherwise return a default constructed 'key_compare' object.
// Note that this comparator compares objects of type 'KEY', which is
// the key part of the 'value_type' objects contained in this multimap.
value_compare value_comp() const;
// Return a functor for comparing two 'value_type' objects by comparing
// their respective keys using 'key_comp()'. Note that this
// comparator compares objects of type 'value_type' (i.e.,
// 'bsl::pair<KEY, VALUE>').
const_iterator find(const key_type& key) const;
// Return an iterator providing non-modifiable access to the first
// 'value_type' object having the specified 'key' in ordered sequence
// maintained by this multimap, if such an object exists; otherwise,
// return the past-the-end ('end') iterator.
size_type count(const key_type& key) const;
// Return the number of 'value_type' objects within this multimap
// having the specified 'key'.
const_iterator lower_bound(const key_type& key) const;
// Return an iterator providing non-modifiable access to the first
// (i.e., ordered least) 'value_type' object in this multimap whose key
// is greater-than or equal-to the specified 'key', and the
// past-the-end iterator if this multimap does not contain a
// 'value_type' object whose key is greater-than or equal-to 'key'.
// Note that this function returns the *first* position before which a
// 'value_type' object having 'key' could be inserted into the ordered
// sequence maintained by this multimap, while preserving its ordering.
const_iterator upper_bound(const key_type& key) const;
// Return an iterator providing non-modifiable access to the first
// (i.e., ordered least) 'value_type' object in this multimap whose key
// is greater than the specified 'key', and the past-the-end iterator
// if this multimap does not contain a 'value_type' object whose key is
// greater-than 'key'. Note that this function returns the *last*
// position before which a 'value_type' object having 'key' could be
// inserted into the ordered sequence maintained by this multimap,
// while preserving its ordering.
bsl::pair<const_iterator,const_iterator> equal_range(
const key_type& x) const;
// Return a pair of iterators providing non-modifiable access to the
// sequence of 'value_type' objects in this multimap having the
// specified 'key', where the the first iterator is positioned at the
// start of the sequence, and the second is positioned one past the end
// of the sequence. The first returned iterator will be
// 'lower_bound(key)'; the second returned iterator will be
// 'upper_bound(key)'; and, if this multimap contains no 'value_type'
// objects having 'key', then the two returned iterators will have the
// same value.
// NOT IMPLEMENTED
// The following methods are defined by the C++11 standard, but they
// are not implemented as they require some level of C++11 compiler
// support not currently available on all supported platforms.
// multimap(multimap<KEY,VALUE,COMPARATOR,ALLOCATOR>&& original);
// multimap(multimap&&, const ALLOCATOR&);
// multimap(initializer_list<value_type>,
// const COMPARATOR& = COMPARATOR(),
// const ALLOCATOR& = ALLOCATOR());
// multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>&
// operator=(multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>&& rhs);
// multimap& operator=(initializer_list<value_type>);
// template <class... Args> pair<iterator, bool> emplace(Args&&... args);
// template <class... Args> iterator emplace_hint(const_iterator position,
// Args&&... args);
// template <class P> iterator insert(P&& value);
// template <class P>
// iterator insert(const_iterator position, P&&);
// void insert(initializer_list<value_type>);
};
} // namespace bsl
// ============================================================================
// TYPE TRAITS
// ============================================================================
// Type traits for STL *ordered* containers:
//: o An ordered container defines STL iterators.
//: o An ordered container uses 'bslma' allocators if the parameterized
//: 'ALLOCATOR' is convertible from 'bslma::Allocator*'.
namespace BloombergLP {
namespace bslalg {
template <typename KEY,
typename VALUE,
typename COMPARATOR,
typename ALLOCATOR>
struct HasStlIterators<bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR> >
: bsl::true_type
{};
}
namespace bslma {
template <typename KEY,
typename VALUE,
typename COMPARATOR,
typename ALLOCATOR>
struct UsesBslmaAllocator<bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR> >
: bsl::is_convertible<Allocator*, ALLOCATOR>
{};
}
} // namespace BloombergLP
namespace bsl {
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
bool operator==(const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs);
// Return 'true' if the specified 'lhs' and 'rhs' objects have the same
// value, and 'false' otherwise. Two 'multimap' objects have the same
// value if they have the same number of key-value pairs, and each
// key-value pair that is contained in one of the objects is also contained
// in the other object. This method requires that the (template parameter)
// types 'KEY' and 'VALUE' both be "equality-comparable" (see {Requirements
// on 'KEY' and 'VALUE'}).
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
bool operator!=(const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs);
// Return 'true' if the specified 'lhs' and 'rhs' objects do not have the
// same value, and 'false' otherwise. Two 'multimap' objects do not have
// the same value if they do not have the same number of key-value pairs,
// or some key-value pair that is contained in one of the objects is not
// also contained in the other object. This method requires that the
// (template parameter) types 'KEY' and 'VALUE' types both be
// "equality-comparable" (see {Requirements on 'KEY' and 'VALUE'}).
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
bool operator<(const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs);
// Return 'true' if the specified 'lhs' value is less than the specified
// 'rhs' value, and 'false' otherwise. A multimap, 'lhs', has a value that
// is less than that of 'rhs', if, for the first non-equal corresponding
// key-value pairs in their respective sequences, the 'lhs' key-value pair
// is less than the 'rhs' pair, or, if the keys of all of their
// corresponding key-value pairs compare equal, 'lhs' has fewer key-value
// pairs than 'rhs'. This method requires that the (template parameter)
// types 'KEY' and 'VALUE' types both be "less-than-comparable" (see
// {Requirements on 'KEY' and 'VALUE'}).
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
bool operator>(const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs);
// Return 'true' if the specified 'lhs' value is greater than the specified
// 'rhs' value, and 'false' otherwise. A multimap, 'lhs', has a value that
// is greater than that of 'rhs', if, for the first non-equal corresponding
// key-value pairs in their respective sequences, the 'lhs' key-value pair
// is greater than the 'rhs' pair, or, if the keys of all of their
// corresponding key-value pairs compare equal, 'lhs' has more key-value
// pairs than 'rhs'. This method requires that the (template parameter)
// types 'KEY' and 'VALUE' both be "less-than-comparable" (see
// {Requirements on 'KEY' and 'VALUE'}).
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
bool operator<=(const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs);
// Return 'true' if the specified 'lhs' value is less-than or equal-to the
// specified 'rhs' value, and 'false' otherwise. A multimap, 'lhs', has a
// value that is less-than or equal-to that of 'rhs', if, for the first
// non-equal corresponding key-value pairs in their respective sequences,
// the 'lhs' key-value pair is less than the 'rhs' pair, or, if the keys of
// all of their corresponding key-value pairs compare equal, 'lhs' has
// less-than or equal number of key-value pairs as 'rhs'. This method
// requires that the (template parameter) types 'KEY' and 'VALUE' both be
// "less-than-comparable" (see {Requirements on 'KEY' and 'VALUE'}).
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
bool operator>=(const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs);
// Return 'true' if the specified 'lhs' value is greater-than or equal-to
// the specified 'rhs' value, and 'false' otherwise. A multimap, 'lhs',
// has a value that is greater-than or equal-to that of 'rhs', if, for the
// first non-equal corresponding key-value pairs in their respective
// sequences, the 'lhs' key-value pair is greater than the 'rhs' pair, or,
// if the keys of all of their corresponding key-value pairs compare equal,
// 'lhs' has greater-than or equal number of key-value pairs as 'rhs'.
// This method requires that the (template parameter) types 'KEY' and
// 'VALUE' types both be "less-than-comparable" (see {Requirements on 'KEY'
// and 'VALUE'}).
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
void swap(multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& a,
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& b);
// Swap both the value and the comparator of the specified 'a' object with
// the value and comparator of the specified 'b' object. Additionally if
// 'bslstl::AllocatorTraits<ALLOCATOR>::propagate_on_container_swap' is
// 'true' then exchange the allocator of 'a' with that of 'b', and do not
// modify either allocator otherwise. This method provides the no-throw
// exception-safety guarantee and guarantees O[1] complexity. The
// behavior is undefined is unless either this object was created with the
// same allocator as 'other' or 'propagate_on_container_swap' is 'true'.
// ===========================================================================
// TEMPLATE AND INLINE FUNCTION DEFINITIONS
// ===========================================================================
// -----------------
// class DataWrapper
// -----------------
// CREATORS
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::DataWrapper::DataWrapper(
const COMPARATOR& comparator,
const ALLOCATOR& allocator)
: ::bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::Comparator(comparator)
, d_pool(allocator)
{
}
// --------------
// class multimap
// --------------
// PRIVATE MANIPULATORS
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::NodeFactory&
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::nodeFactory()
{
return d_compAndAlloc.d_pool;
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::Comparator&
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::comparator()
{
return d_compAndAlloc;
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
void multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::quickSwap(multimap& other)
{
BloombergLP::bslalg::RbTreeUtil::swap(&d_tree, &other.d_tree);
nodeFactory().swap(other.nodeFactory());
// Work around to avoid the 1-byte swap problem on AIX for an empty class
// under empty-base optimization.
if (sizeof(NodeFactory) != sizeof(DataWrapper)) {
comparator().swap(other.comparator());
}
}
// PRIVATE ACCESSORS
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
const typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::NodeFactory&
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::nodeFactory() const
{
return d_compAndAlloc.d_pool;
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
const typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::Comparator&
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::comparator() const
{
return d_compAndAlloc;
}
// CREATORS
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
template <class INPUT_ITERATOR>
inline
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::multimap(
INPUT_ITERATOR first,
INPUT_ITERATOR last,
const COMPARATOR& comparator,
const ALLOCATOR& allocator)
: d_compAndAlloc(comparator, allocator)
, d_tree()
{
if (first != last) {
BloombergLP::bslalg::RbTreeUtilTreeProctor<NodeFactory> proctor(
&d_tree,
&nodeFactory());
// The following loop guarantees amortized linear time to insert an
// ordered sequence of values (as required by the standard). If the
// values are in sorted order, we are guaranteed the next node can be
// inseted as the right child of the previous node, and can call
// 'insertAt' without 'findUniqueInsertLocation'.
insert(*first);
BloombergLP::bslalg::RbTreeNode *prevNode = d_tree.rootNode();
while (++first != last) {
// The values are not in order, so insert them normally.
const value_type& value = *first;
if (this->comparator()(value.first, *prevNode)) {
insert(value);
insert(++first, last);
break;
}
BloombergLP::bslalg::RbTreeNode *node = nodeFactory().createNode(
value);
BloombergLP::bslalg::RbTreeUtil::insertAt(&d_tree,
prevNode,
false,
node);
prevNode = node;
}
proctor.release();
}
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::multimap(const multimap& original)
: d_compAndAlloc(original.comparator().keyComparator(),
AllocatorTraits::select_on_container_copy_construction(
original.nodeFactory().allocator()))
, d_tree()
{
if (0 < original.size()) {
nodeFactory().reserveNodes(original.size());
BloombergLP::bslalg::RbTreeUtil::copyTree(&d_tree,
original.d_tree,
&nodeFactory());
}
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::multimap(
const ALLOCATOR& allocator)
: d_compAndAlloc(COMPARATOR(), allocator)
, d_tree()
{
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::multimap(
const multimap& original,
const ALLOCATOR& allocator)
: d_compAndAlloc(original.comparator().keyComparator(), allocator)
, d_tree()
{
if (0 < original.size()) {
nodeFactory().reserveNodes(original.size());
BloombergLP::bslalg::RbTreeUtil::copyTree(&d_tree,
original.d_tree,
&nodeFactory());
}
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::~multimap()
{
clear();
}
// MANIPULATORS
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>&
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::operator=(const multimap& rhs)
{
if (BSLS_PERFORMANCEHINT_PREDICT_LIKELY(this != &rhs)) {
if (AllocatorTraits::propagate_on_container_copy_assignment::VALUE) {
multimap other(rhs, rhs.nodeFactory().allocator());
BloombergLP::bslalg::SwapUtil::swap(
&nodeFactory().allocator(),
&other.nodeFactory().allocator());
quickSwap(other);
}
else {
multimap other(rhs, nodeFactory().allocator());
quickSwap(other);
}
}
return *this;
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::begin()
{
return iterator(d_tree.firstNode());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::end()
{
return iterator(d_tree.sentinel());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::reverse_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::rbegin()
{
return reverse_iterator(end());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::reverse_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::rend()
{
return reverse_iterator(begin());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::insert(const value_type& value)
{
bool leftChild;
BloombergLP::bslalg::RbTreeNode *insertLocation =
BloombergLP::bslalg::RbTreeUtil::findInsertLocation(&leftChild,
&d_tree,
this->comparator(),
value.first);
BloombergLP::bslalg::RbTreeNode *node = nodeFactory().createNode(value);
BloombergLP::bslalg::RbTreeUtil::insertAt(&d_tree,
insertLocation,
leftChild,
node);
return iterator(node);
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
template <class INPUT_ITERATOR>
inline
void multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::insert(INPUT_ITERATOR first,
INPUT_ITERATOR last)
{
while (first != last) {
insert(*first);
++first;
}
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::insert(const_iterator hint,
const value_type& value)
{
BloombergLP::bslalg::RbTreeNode *hintNode =
const_cast<BloombergLP::bslalg::RbTreeNode *>(hint.node());
bool leftChild;
BloombergLP::bslalg::RbTreeNode *insertLocation =
BloombergLP::bslalg::RbTreeUtil::findInsertLocation(&leftChild,
&d_tree,
this->comparator(),
value.first,
hintNode);
BloombergLP::bslalg::RbTreeNode *node = nodeFactory().createNode(value);
BloombergLP::bslalg::RbTreeUtil::insertAt(&d_tree,
insertLocation,
leftChild,
node);
return iterator(node);
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::erase(const_iterator position)
{
BSLS_ASSERT_SAFE(position != end());
BloombergLP::bslalg::RbTreeNode *node =
const_cast<BloombergLP::bslalg::RbTreeNode *>(position.node());
BloombergLP::bslalg::RbTreeNode *result =
BloombergLP::bslalg::RbTreeUtil::next(node);
BloombergLP::bslalg::RbTreeUtil::remove(&d_tree, node);
nodeFactory().deleteNode(node);
return iterator(result);
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::size_type
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::erase(const key_type& key)
{
size_type count = 0;
const_iterator first = find(key);
if (first != end()) {
const_iterator last = upper_bound(key);
while (first != last) {
first = erase(first);
++count;
}
}
return count;
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::erase(const_iterator first,
const_iterator last)
{
while (first != last) {
first = erase(first);
}
return iterator(last.node());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
void multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::swap(multimap& other)
{
if (AllocatorTraits::propagate_on_container_swap::VALUE) {
BloombergLP::bslalg::SwapUtil::swap(&nodeFactory().allocator(),
&other.nodeFactory().allocator());
quickSwap(other);
}
else {
// C++11 behavior: undefined for unequal allocators
// BSLS_ASSERT(allocator() == other.allocator());
// backward compatible behavior: swap with copies
if (BSLS_PERFORMANCEHINT_PREDICT_LIKELY(
nodeFactory().allocator() == other.nodeFactory().allocator())) {
quickSwap(other);
}
else {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
multimap thisCopy(*this, other.nodeFactory().allocator());
multimap otherCopy(other, nodeFactory().allocator());
quickSwap(otherCopy);
other.quickSwap(thisCopy);
}
}
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
void multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::clear()
{
BSLS_ASSERT_SAFE(d_tree.firstNode());
if (d_tree.rootNode()) {
BSLS_ASSERT_SAFE(0 < d_tree.numNodes());
BSLS_ASSERT_SAFE(d_tree.firstNode() != d_tree.sentinel());
BloombergLP::bslalg::RbTreeUtil::deleteTree(&d_tree, &nodeFactory());
}
#if defined(BSLS_ASSERT_SAFE_IS_ACTIVE)
else {
BSLS_ASSERT_SAFE(0 == d_tree.numNodes());
BSLS_ASSERT_SAFE(d_tree.firstNode() == d_tree.sentinel());
}
#endif
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::find(const key_type& key)
{
return iterator(BloombergLP::bslalg::RbTreeUtil::find(d_tree,
this->comparator(),
key));
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::lower_bound(const key_type& key)
{
return iterator(BloombergLP::bslalg::RbTreeUtil::lowerBound(
d_tree,
this->comparator(),
key));
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::upper_bound(const key_type& key)
{
return iterator(BloombergLP::bslalg::RbTreeUtil::upperBound(
d_tree,
this->comparator(),
key));
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bsl::pair<typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator,
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::iterator>
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::equal_range(const key_type& key)
{
iterator startIt = lower_bound(key);
iterator endIt = startIt;
if (endIt != end() && !comparator()(key, *endIt.node())) {
endIt = upper_bound(key);
}
return bsl::pair<iterator, iterator>(startIt, endIt);
}
// ACCESSORS
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::allocator_type
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::get_allocator() const
{
return nodeFactory().allocator();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::begin() const
{
return cbegin();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::end() const
{
return cend();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_reverse_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::rbegin() const
{
return crbegin();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_reverse_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::rend() const
{
return crend();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::cbegin() const
{
return const_iterator(d_tree.firstNode());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::cend() const
{
return const_iterator(d_tree.sentinel());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_reverse_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::crbegin() const
{
return const_reverse_iterator(end());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_reverse_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::crend() const
{
return const_reverse_iterator(begin());
}
// capacity:
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bool multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::empty() const
{
return 0 == d_tree.numNodes();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::size_type
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::size() const
{
return d_tree.numNodes();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::size_type
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::max_size() const
{
return AllocatorTraits::max_size(get_allocator());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::key_compare
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::key_comp() const
{
return comparator().keyComparator();
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::value_compare
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::value_comp() const
{
return value_compare(key_comp());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::find(const key_type& key) const
{
return const_iterator(
BloombergLP::bslalg::RbTreeUtil::find(d_tree, this->comparator(), key));
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE,COMPARATOR, ALLOCATOR>::size_type
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::count(const key_type& key) const
{
int cnt = 0;
const_iterator it = lower_bound(key);
while (it != end() && !comparator()(key, *it.node())) {
++it;
++cnt;
}
return cnt;
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::lower_bound(
const key_type& key) const
{
return iterator(BloombergLP::bslalg::RbTreeUtil::lowerBound(
d_tree,
this->comparator(),
key));
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::upper_bound(
const key_type& key) const
{
return const_iterator(BloombergLP::bslalg::RbTreeUtil::upperBound(
d_tree,
this->comparator(),
key));
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bsl::pair<typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator,
typename multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::const_iterator>
multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>::equal_range(
const key_type& key) const
{
const_iterator startIt = lower_bound(key);
const_iterator endIt = startIt;
if (endIt != end() && !comparator()(key, *endIt.node())) {
endIt = upper_bound(key);
}
return bsl::pair<const_iterator, const_iterator>(startIt, endIt);
}
} // close namespace bslstl
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bool bsl::operator==(
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs)
{
return BloombergLP::bslalg::RangeCompare::equal(lhs.begin(),
lhs.end(),
lhs.size(),
rhs.begin(),
rhs.end(),
rhs.size());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bool bsl::operator!=(
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs)
{
return !(lhs == rhs);
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bool bsl::operator<(
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs)
{
return 0 > BloombergLP::bslalg::RangeCompare::lexicographical(lhs.begin(),
lhs.end(),
lhs.size(),
rhs.begin(),
rhs.end(),
rhs.size());
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bool bsl::operator>(
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs)
{
return rhs < lhs;
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bool bsl::operator<=(
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs)
{
return !(rhs < lhs);
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
bool bsl::operator>=(
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& lhs,
const bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& rhs)
{
return !(lhs < rhs);
}
template <class KEY, class VALUE, class COMPARATOR, class ALLOCATOR>
inline
void bsl::swap(bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& a,
bsl::multimap<KEY, VALUE, COMPARATOR, ALLOCATOR>& b)
{
a.swap(b);
}
#endif
// ----------------------------------------------------------------------------
// Copyright (C) 2012 Bloomberg L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| [
"abeels@bloomberg.net"
] | abeels@bloomberg.net |
a6d833e83b9e83fb852dd8fa42629044deb22a43 | 75c587b8ff471dcf12500fe80895a579c402bf9a | /test/QTestableAutomationRequestTest.cpp | 66740a114cfcd30b482d09b143304664e66cac1b | [] | no_license | gja/qTestable | ebaf7e9769b637a5add5ad86db5193e32ec2b67b | b545a78657634922a23271200edb9d663464ae8d | refs/heads/master | 2021-01-13T01:49:05.923575 | 2011-03-20T05:49:38 | 2011-03-20T05:49:38 | 1,386,653 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,925 | cpp | #include <QTest>
#include "QTestableAutomationRequest.h"
using namespace QTestable;
class QTestableAutomationRequestTest : public QObject
{
Q_OBJECT
private slots:
void ShouldBeAbleToParseARequestWithoutArguments_data()
{
QTest::addColumn<QString>("request");
QTest::addColumn<bool>("isValid");
QTest::addColumn<QString>("targetClass");
QTest::addColumn<QString>("targetObject");
QTest::addColumn<QString>("command");
QTest::newRow("An Empty Request")<<""<<false<<""<<""<<"";
QTest::newRow("An Request Without Arguments")<<"button/click/myButton"<<true<<"button"<<"myButton"<<"click";
QTest::newRow("An Request Child In The Target")<<"button/click/myButton/child"<<true<<"button"<<"myButton/child"<<"click";
QTest::newRow("An Request With Arguments To be ignored")<<"button/click/myButton?foo=bar"<<true<<"button"<<"myButton"<<"click";
}
void ShouldBeAbleToParseARequestWithoutArguments()
{
QFETCH(QString, request);
QFETCH(bool, isValid);
QFETCH(QString, targetClass);
QFETCH(QString, targetObject);
QFETCH(QString, command);
QTestableAutomationRequest parser(request);
QCOMPARE(isValid, parser.isValid());
QCOMPARE(targetClass, parser.targetClass());
QCOMPARE(targetObject, parser.targetObject());
QCOMPARE(command, parser.command());
QCOMPARE(request, parser.originalRequest());
QCOMPARE(isValid ? QString("") : QString("Invalid Request"), parser.errorMessage());
}
void ShouldBeAbleToParseARequestWithArguments()
{
QTestableAutomationRequest request("foo/bar/baz?q1=a1&q2=a2");
QCOMPARE(request.argument("q1"), QString("a1"));
QCOMPARE(request.argument("q2"), QString("a2"));
QCOMPARE(request.argument("invalid"), QString(""));
}
};
QTEST_MAIN(QTestableAutomationRequestTest)
#include "QTestableAutomationRequestTest.moc"
| [
"tejas@gja.in"
] | tejas@gja.in |
257e9409fcbf13082f3e0367bed0cd614d57a42e | 5997e1375927f887e4fc1e5b06cc16edc069a395 | /hdf5_wrapper/template/src/write_attribute.inc | 64e15e306ea9dff3a8877b2f17a0d2d54d0031b8 | [
"MIT"
] | permissive | galtay/urchin | 1f37d42c1cfdf7902942b04efbaff114a2c43538 | fc111c16065f58141bc9d9b2629ee058c41df2db | refs/heads/main | 2022-12-05T10:40:46.246680 | 2020-09-04T21:19:33 | 2020-09-04T21:19:33 | 292,947,741 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,883 | inc | subroutine SUB_NAME (ifile,name,arr,overwrite)
!
! Read an n-D array dataset from an open file. This assumes some
! preprocessor variables have been set - see
! write_attribute_preprocessor.F90.
!
implicit none
integer, parameter :: LEN_STR = 256
integer, parameter :: MAX_NEST = 10
character(len=*), intent(in) :: name
integer,intent(in) :: ifile
integer :: hdf_err
integer(hid_t) :: loc_id, attr_id, dspace_id
integer(hid_t) :: dtype_id
#ifndef SCALAR
integer(hsize_t) :: dimensions(NDIMS)
ARR_TYPE , dimension ARRAY_DIM :: arr
#else
ARR_TYPE :: arr
#endif
character(len=LEN_STR) :: loc_name
character(len=LEN_STR) :: attr_name
integer :: nslash
integer :: itype,i
logical, optional :: overwrite
!
if(ifile.lt.1.or.ifile.gt.nfilemax)call hdf5_abort( &
'Invalid file handle in write_attribute',name=name)
if(file_id(ifile).lt.0) then
call hdf5_abort('File is not open in hdf5_write_attribute()!',&
name=name)
endif
!
if(read_only(ifile))call hdf5_abort( &
"Attempt to write attribute to read only file!", &
name=name,fname=fname_table(ifile))
! Generate array of dimensions:
#ifndef SCALAR
do i=1,NDIMS
dimensions(i) = ubound(arr,i) - lbound(arr,i) + 1
enddo
#endif
! Split name into path and attribute name
nslash=index(name,"/",.true.)
if(nslash.eq.0) then
call hdf5_abort('Invalid attribute name in write_attribute!', &
name=name,fname=fname_table(ifile))
endif
loc_name=name(1:nslash-1)
attr_name=name(nslash+1:len_trim(name))
! Try to open loc_name as a group and as a dataset
itype=1
call h5eset_auto_f(0, hdf_err)
call h5dopen_f(file_id(ifile),loc_name,loc_id,hdf_err)
if(hdf_err.lt.0)then
call h5gopen_f(file_id(ifile),loc_name, loc_id, hdf_err)
if(hdf_err.lt.0) then
call hdf5_abort('Unable to open attribute parent object in write_attribute!', &
name=name,fname=fname_table(ifile))
endif
itype=2
end if
if (HDF_ERROR_SUPPRESS .eq. 0) call h5eset_auto_f(1, hdf_err)
! Now we can write the data:
#ifndef SCALAR
call h5screate_simple_f(NDIMS,dimensions,dspace_id,hdf_err)
#else
call h5screate_f(H5S_SCALAR_F, dspace_id, hdf_err)
#endif
if(hdf_err.lt.0)call hdf5_abort('Unable to open dataspace in write_data()!', &
name=name,fname=fname_table(ifile))
#ifndef STRING
call h5tcopy_f( NATIVE_TYPE, dtype_id, hdf_err)
if(hdf_err.lt.0) then
call hdf5_abort('Unable to open datatype in write_attribute()!', &
name=name,fname=fname_table(ifile))
endif
#else
call h5tcopy_f( H5T_NATIVE_CHARACTER, dtype_id, hdf_err)
call h5tset_size_f(dtype_id, INT(LEN(arr),KIND=SIZE_T), hdf_err)
#endif
! If overwrite is set, delete any attribute at this location
if(present(overwrite))then
if(overwrite)then
call h5eset_auto_f(0, hdf_err)
call h5adelete_f(loc_id,attr_name,hdf_err)
if (HDF_ERROR_SUPPRESS .eq. 0) call h5eset_auto_f(1, hdf_err)
endif
endif
call h5acreate_f(loc_id, attr_name, dtype_id, dspace_id, &
attr_id, hdf_err, H5P_DEFAULT_F)
if(hdf_err.lt.0) then
call hdf5_abort('Unable to open attribute in write_attribute()!', &
name=name,fname=fname_table(ifile))
endif
!Here we call the C version of the routine
CALL write_hdf5_attribute(attr_id, dtype_id, arr,hdf_err)
if (HDF_VERBOSITY .ge. 1) then
write(*,*)'[hdf5_write_attribute] Writing attribute ',trim(attr_name)
endif
if(hdf_err.lt.0) then
call hdf5_abort('Unable to write attribute in write_attribute()!', &
name=name,fname=fname_table(ifile))
endif
if(itype.eq.1)then
call h5dclose_f(loc_id,hdf_err)
if(hdf_err.lt.0) then
call hdf5_abort('Unable to close dataset in write_attribute()!', &
name=name,fname=fname_table(ifile))
endif
else
call h5gclose_f(loc_id,hdf_err)
if(hdf_err.lt.0) then
call hdf5_abort('Unable to close group in write_attribute()!', &
name=name,fname=fname_table(ifile))
endif
end if
call h5tclose_f(dtype_id,hdf_err)
call h5sclose_f(dspace_id,hdf_err)
call h5aclose_f(attr_id, hdf_err)
end subroutine SUB_NAME
| [
"gabriel@kensho.com"
] | gabriel@kensho.com |
811fa85045fa60482d0e07020a7b8cb8b020e922 | cb80a8562d90eb969272a7ff2cf52c1fa7aeb084 | /inletTest3/0.118/uniform/cumulativeContErr | b8b82ee2a0700f0ea4e6c7692331f48a23ccb6b3 | [] | no_license | mahoep/inletCFD | eb516145fad17408f018f51e32aa0604871eaa95 | 0df91e3fbfa60d5db9d52739e212ca6d3f0a28b2 | refs/heads/main | 2023-08-30T22:07:41.314690 | 2021-10-14T19:23:51 | 2021-10-14T19:23:51 | 314,657,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 958 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v2006 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class uniformDimensionedScalarField;
location "0.118/uniform";
object cumulativeContErr;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
value -0.00137922;
// ************************************************************************* //
| [
"mhoeper3234@gmail.com"
] | mhoeper3234@gmail.com | |
3d316e72c7f5274478932575ed375aa09361e246 | 3db588f4b1e21035610daa5d937d9571f690b249 | /School Attendance System/SchoolAttendanceSystem/SchoolAttendanceSystem/SchoolAttendanceSystemDlg.h | 16c2cdc25bb8777b84ecde24553eb7d196554189 | [] | no_license | sanketjaind/Projects | 1d6cd1abc04c368c13a92e75eb5019854fcb656c | 02e035ad09e93ff971f52019fc706f3a0c5e9e44 | refs/heads/master | 2022-04-25T13:26:57.421503 | 2020-04-25T07:10:18 | 2020-04-25T07:10:18 | 258,704,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,070 | h |
// SchoolAttendanceSystemDlg.h : header file
//
#pragma once
#include "inc.h"
#include "StaffMenu.h"
#include "AdminPanel.h"
#include "CheckAttendance.h"
// CSchoolAttendanceSystemDlg dialog
class CSchoolAttendanceSystemDlg : public CDialogEx, public inc
{
// Construction
public:
CSchoolAttendanceSystemDlg(CWnd* pParent = NULL); // standard constructor
StaffMenu StaffMenu;
AdminPanel admin;
CheckAttendance Check;
// Dialog Data
enum { IDD = IDD_SCHOOLATTENDANCESYSTEM_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedRadio1();
afx_msg void OnBnClickedOk();
afx_msg void OnBnClickedRadio2();
afx_msg void OnBnClickedRadio3();
afx_msg void OnEnChangeEdit1();
CString username;
CString pass;
afx_msg void OnEnChangeEdit2();
};
| [
"sanketjaind@gmail.com"
] | sanketjaind@gmail.com |
1f7e6ac9a107e15e4390de2cce108744afb49d82 | ec8db7de14c3b159be388d9cd84b7ffb2759fa0f | /libraries/protocol/odyssey_operations.cpp | 65cae767efa5aacdef922e88188b796497d6e596 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | lucien-tronlab/odyssey | 48264db827cf8e0d8f29713b9b33e89bc0389f79 | 9ea6771aff74f922d8d98fd36dd003a49d8e778a | refs/heads/master | 2021-01-22T04:23:33.782797 | 2017-11-10T03:51:21 | 2017-11-10T03:51:21 | 102,265,342 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 22,161 | cpp | #include <odyssey/protocol/odyssey_operations.hpp>
#include <fc/io/json.hpp>
#include <locale>
namespace odyssey { namespace protocol {
bool inline is_asset_type( asset asset, asset_symbol_type symbol )
{
return asset.symbol == symbol;
}
void account_create_operation::validate() const
{
validate_account_name( new_account_name );
FC_ASSERT( is_asset_type( fee, ODYSSEY_SYMBOL ), "Account creation fee must be ODYSSEY" );
owner.validate();
active.validate();
if ( json_metadata.size() > 0 )
{
FC_ASSERT( fc::is_utf8(json_metadata), "JSON Metadata not formatted in UTF8" );
FC_ASSERT( fc::json::is_valid(json_metadata), "JSON Metadata not valid JSON" );
}
FC_ASSERT( fee >= asset( 0, ODYSSEY_SYMBOL ), "Account creation fee cannot be negative" );
}
void account_create_with_delegation_operation::validate() const
{
validate_account_name( new_account_name );
validate_account_name( creator );
FC_ASSERT( is_asset_type( fee, ODYSSEY_SYMBOL ), "Account creation fee must be ODYSSEY" );
FC_ASSERT( is_asset_type( delegation, VESTS_SYMBOL ), "Delegation must be VESTS" );
owner.validate();
active.validate();
posting.validate();
if( json_metadata.size() > 0 )
{
FC_ASSERT( fc::is_utf8(json_metadata), "JSON Metadata not formatted in UTF8" );
FC_ASSERT( fc::json::is_valid(json_metadata), "JSON Metadata not valid JSON" );
}
FC_ASSERT( fee >= asset( 0, ODYSSEY_SYMBOL ), "Account creation fee cannot be negative" );
FC_ASSERT( delegation >= asset( 0, VESTS_SYMBOL ), "Delegation cannot be negative" );
}
void account_update_operation::validate() const
{
validate_account_name( account );
/*if( owner )
owner->validate();
if( active )
active->validate();
if( posting )
posting->validate();*/
if ( json_metadata.size() > 0 )
{
FC_ASSERT( fc::is_utf8(json_metadata), "JSON Metadata not formatted in UTF8" );
FC_ASSERT( fc::json::is_valid(json_metadata), "JSON Metadata not valid JSON" );
}
}
void comment_operation::validate() const
{
FC_ASSERT( title.size() < 256, "Title larger than size limit" );
FC_ASSERT( fc::is_utf8( title ), "Title not formatted in UTF8" );
FC_ASSERT( body.size() > 0, "Body is empty" );
FC_ASSERT( fc::is_utf8( body ), "Body not formatted in UTF8" );
if( parent_author.size() )
validate_account_name( parent_author );
validate_account_name( author );
validate_permlink( parent_permlink );
validate_permlink( permlink );
if( json_metadata.size() > 0 )
{
FC_ASSERT( fc::json::is_valid(json_metadata), "JSON Metadata not valid JSON" );
}
}
struct comment_options_extension_validate_visitor
{
comment_options_extension_validate_visitor() {}
typedef void result_type;
void operator()( const comment_payout_beneficiaries& cpb ) const
{
cpb.validate();
}
};
void comment_payout_beneficiaries::validate()const
{
uint32_t sum = 0;
FC_ASSERT( beneficiaries.size(), "Must specify at least one beneficiary" );
FC_ASSERT( beneficiaries.size() < 128, "Cannot specify more than 127 beneficiaries." ); // Require size serializtion fits in one byte.
validate_account_name( beneficiaries[0].account );
FC_ASSERT( beneficiaries[0].weight <= ODYSSEY_100_PERCENT, "Cannot allocate more than 100% of rewards to one account" );
sum += beneficiaries[0].weight;
FC_ASSERT( sum <= ODYSSEY_100_PERCENT, "Cannot allocate more than 100% of rewards to a comment" ); // Have to check incrementally to avoid overflow
for( size_t i = 1; i < beneficiaries.size(); i++ )
{
validate_account_name( beneficiaries[i].account );
FC_ASSERT( beneficiaries[i].weight <= ODYSSEY_100_PERCENT, "Cannot allocate more than 100% of rewards to one account" );
sum += beneficiaries[i].weight;
FC_ASSERT( sum <= ODYSSEY_100_PERCENT, "Cannot allocate more than 100% of rewards to a comment" ); // Have to check incrementally to avoid overflow
FC_ASSERT( beneficiaries[i - 1] < beneficiaries[i], "Benficiaries must be specified in sorted order (account ascending)" );
}
}
void comment_options_operation::validate()const
{
validate_account_name( author );
FC_ASSERT( percent_odyssey_dollars <= ODYSSEY_100_PERCENT, "Percent cannot exceed 100%" );
FC_ASSERT( max_accepted_payout.symbol == SBD_SYMBOL, "Max accepted payout must be in SBD" );
FC_ASSERT( max_accepted_payout.amount.value >= 0, "Cannot accept less than 0 payout" );
validate_permlink( permlink );
for( auto& e : extensions )
e.visit( comment_options_extension_validate_visitor() );
}
void delete_comment_operation::validate()const
{
validate_permlink( permlink );
validate_account_name( author );
}
void challenge_authority_operation::validate()const
{
validate_account_name( challenger );
validate_account_name( challenged );
FC_ASSERT( challenged != challenger, "cannot challenge yourself" );
}
void prove_authority_operation::validate()const
{
validate_account_name( challenged );
}
void vote_operation::validate() const
{
validate_account_name( voter );
validate_account_name( author );\
FC_ASSERT( abs(weight) <= ODYSSEY_100_PERCENT, "Weight is not a ODYSSEY percentage" );
validate_permlink( permlink );
}
void transfer_operation::validate() const
{ try {
validate_account_name( from );
validate_account_name( to );
FC_ASSERT( amount.symbol != VESTS_SYMBOL, "transferring of Odyssey Power (STMP) is not allowed." );
FC_ASSERT( amount.amount > 0, "Cannot transfer a negative amount (aka: stealing)" );
FC_ASSERT( memo.size() < ODYSSEY_MAX_MEMO_SIZE, "Memo is too large" );
FC_ASSERT( fc::is_utf8( memo ), "Memo is not UTF8" );
} FC_CAPTURE_AND_RETHROW( (*this) ) }
void transfer_to_vesting_operation::validate() const
{
validate_account_name( from );
FC_ASSERT( is_asset_type( amount, ODYSSEY_SYMBOL ), "Amount must be ODYSSEY" );
if ( to != account_name_type() ) validate_account_name( to );
FC_ASSERT( amount > asset( 0, ODYSSEY_SYMBOL ), "Must transfer a nonzero amount" );
}
void withdraw_vesting_operation::validate() const
{
validate_account_name( account );
FC_ASSERT( is_asset_type( vesting_shares, VESTS_SYMBOL), "Amount must be VESTS" );
}
void set_withdraw_vesting_route_operation::validate() const
{
validate_account_name( from_account );
validate_account_name( to_account );
FC_ASSERT( 0 <= percent && percent <= ODYSSEY_100_PERCENT, "Percent must be valid odyssey percent" );
}
void witness_update_operation::validate() const
{
validate_account_name( owner );
FC_ASSERT( url.size() > 0, "URL size must be greater than 0" );
FC_ASSERT( fc::is_utf8( url ), "URL is not valid UTF8" );
FC_ASSERT( fee >= asset( 0, ODYSSEY_SYMBOL ), "Fee cannot be negative" );
props.validate();
}
void account_witness_vote_operation::validate() const
{
validate_account_name( account );
validate_account_name( witness );
}
void account_witness_proxy_operation::validate() const
{
validate_account_name( account );
if( proxy.size() )
validate_account_name( proxy );
FC_ASSERT( proxy != account, "Cannot proxy to self" );
}
void custom_operation::validate() const {
/// required auth accounts are the ones whose bandwidth is consumed
FC_ASSERT( required_auths.size() > 0, "at least on account must be specified" );
}
void custom_json_operation::validate() const {
/// required auth accounts are the ones whose bandwidth is consumed
FC_ASSERT( (required_auths.size() + required_posting_auths.size()) > 0, "at least on account must be specified" );
FC_ASSERT( id.size() <= 32, "id is too long" );
FC_ASSERT( fc::is_utf8(json), "JSON Metadata not formatted in UTF8" );
FC_ASSERT( fc::json::is_valid(json), "JSON Metadata not valid JSON" );
}
void custom_binary_operation::validate() const {
/// required auth accounts are the ones whose bandwidth is consumed
FC_ASSERT( (required_owner_auths.size() + required_active_auths.size() + required_posting_auths.size()) > 0, "at least on account must be specified" );
FC_ASSERT( id.size() <= 32, "id is too long" );
for( const auto& a : required_auths ) a.validate();
}
fc::sha256 pow_operation::work_input()const
{
auto hash = fc::sha256::hash( block_id );
hash._hash[0] = nonce;
return fc::sha256::hash( hash );
}
void pow_operation::validate()const
{
props.validate();
validate_account_name( worker_account );
FC_ASSERT( work_input() == work.input, "Determninistic input does not match recorded input" );
work.validate();
}
struct pow2_operation_validate_visitor
{
typedef void result_type;
template< typename PowType >
void operator()( const PowType& pow )const
{
pow.validate();
}
};
void pow2_operation::validate()const
{
props.validate();
work.visit( pow2_operation_validate_visitor() );
}
struct pow2_operation_get_required_active_visitor
{
typedef void result_type;
pow2_operation_get_required_active_visitor( flat_set< account_name_type >& required_active )
: _required_active( required_active ) {}
template< typename PowType >
void operator()( const PowType& work )const
{
_required_active.insert( work.input.worker_account );
}
flat_set<account_name_type>& _required_active;
};
void pow2_operation::get_required_active_authorities( flat_set<account_name_type>& a )const
{
if( !new_owner_key )
{
pow2_operation_get_required_active_visitor vtor( a );
work.visit( vtor );
}
}
void pow::create( const fc::ecc::private_key& w, const digest_type& i )
{
input = i;
signature = w.sign_compact(input,false);
auto sig_hash = fc::sha256::hash( signature );
public_key_type recover = fc::ecc::public_key( signature, sig_hash, false );
work = fc::sha256::hash(recover);
}
void pow2::create( const block_id_type& prev, const account_name_type& account_name, uint64_t n )
{
input.worker_account = account_name;
input.prev_block = prev;
input.nonce = n;
auto prv_key = fc::sha256::hash( input );
auto input = fc::sha256::hash( prv_key );
auto signature = fc::ecc::private_key::regenerate( prv_key ).sign_compact(input);
auto sig_hash = fc::sha256::hash( signature );
public_key_type recover = fc::ecc::public_key( signature, sig_hash );
fc::sha256 work = fc::sha256::hash(std::make_pair(input,recover));
pow_summary = work.approx_log_32();
}
void equihash_pow::create( const block_id_type& recent_block, const account_name_type& account_name, uint32_t nonce )
{
input.worker_account = account_name;
input.prev_block = recent_block;
input.nonce = nonce;
auto seed = fc::sha256::hash( input );
proof = fc::equihash::proof::hash( ODYSSEY_EQUIHASH_N, ODYSSEY_EQUIHASH_K, seed );
pow_summary = fc::sha256::hash( proof.inputs ).approx_log_32();
}
void pow::validate()const
{
FC_ASSERT( work != fc::sha256() );
FC_ASSERT( public_key_type(fc::ecc::public_key( signature, input, false )) == worker );
auto sig_hash = fc::sha256::hash( signature );
public_key_type recover = fc::ecc::public_key( signature, sig_hash, false );
FC_ASSERT( work == fc::sha256::hash(recover) );
}
void pow2::validate()const
{
validate_account_name( input.worker_account );
pow2 tmp; tmp.create( input.prev_block, input.worker_account, input.nonce );
FC_ASSERT( pow_summary == tmp.pow_summary, "reported work does not match calculated work" );
}
void equihash_pow::validate() const
{
validate_account_name( input.worker_account );
auto seed = fc::sha256::hash( input );
FC_ASSERT( proof.n == ODYSSEY_EQUIHASH_N, "proof of work 'n' value is incorrect" );
FC_ASSERT( proof.k == ODYSSEY_EQUIHASH_K, "proof of work 'k' value is incorrect" );
FC_ASSERT( proof.seed == seed, "proof of work seed does not match expected seed" );
FC_ASSERT( proof.is_valid(), "proof of work is not a solution", ("block_id", input.prev_block)("worker_account", input.worker_account)("nonce", input.nonce) );
FC_ASSERT( pow_summary == fc::sha256::hash( proof.inputs ).approx_log_32() );
}
void feed_publish_operation::validate()const
{
validate_account_name( publisher );
FC_ASSERT( ( is_asset_type( exchange_rate.base, ODYSSEY_SYMBOL ) && is_asset_type( exchange_rate.quote, SBD_SYMBOL ) )
|| ( is_asset_type( exchange_rate.base, SBD_SYMBOL ) && is_asset_type( exchange_rate.quote, ODYSSEY_SYMBOL ) ),
"Price feed must be a ODYSSEY/SBD price" );
exchange_rate.validate();
}
void limit_order_create_operation::validate()const
{
validate_account_name( owner );
FC_ASSERT( ( is_asset_type( amount_to_sell, ODYSSEY_SYMBOL ) && is_asset_type( min_to_receive, SBD_SYMBOL ) )
|| ( is_asset_type( amount_to_sell, SBD_SYMBOL ) && is_asset_type( min_to_receive, ODYSSEY_SYMBOL ) ),
"Limit order must be for the ODYSSEY:SBD market" );
(amount_to_sell / min_to_receive).validate();
}
void limit_order_create2_operation::validate()const
{
validate_account_name( owner );
FC_ASSERT( amount_to_sell.symbol == exchange_rate.base.symbol, "Sell asset must be the base of the price" );
exchange_rate.validate();
FC_ASSERT( ( is_asset_type( amount_to_sell, ODYSSEY_SYMBOL ) && is_asset_type( exchange_rate.quote, SBD_SYMBOL ) ) ||
( is_asset_type( amount_to_sell, SBD_SYMBOL ) && is_asset_type( exchange_rate.quote, ODYSSEY_SYMBOL ) ),
"Limit order must be for the ODYSSEY:SBD market" );
FC_ASSERT( (amount_to_sell * exchange_rate).amount > 0, "Amount to sell cannot round to 0 when traded" );
}
void limit_order_cancel_operation::validate()const
{
validate_account_name( owner );
}
void convert_operation::validate()const
{
validate_account_name( owner );
/// only allow conversion from SBD to ODYSSEY, allowing the opposite can enable traders to abuse
/// market fluxuations through converting large quantities without moving the price.
FC_ASSERT( is_asset_type( amount, SBD_SYMBOL ), "Can only convert SBD to ODYSSEY" );
FC_ASSERT( amount.amount > 0, "Must convert some SBD" );
}
void report_over_production_operation::validate()const
{
validate_account_name( reporter );
validate_account_name( first_block.witness );
FC_ASSERT( first_block.witness == second_block.witness );
FC_ASSERT( first_block.timestamp == second_block.timestamp );
FC_ASSERT( first_block.signee() == second_block.signee() );
FC_ASSERT( first_block.id() != second_block.id() );
}
void escrow_transfer_operation::validate()const
{
validate_account_name( from );
validate_account_name( to );
validate_account_name( agent );
FC_ASSERT( fee.amount >= 0, "fee cannot be negative" );
FC_ASSERT( sbd_amount.amount >= 0, "sbd amount cannot be negative" );
FC_ASSERT( odyssey_amount.amount >= 0, "odyssey amount cannot be negative" );
FC_ASSERT( sbd_amount.amount > 0 || odyssey_amount.amount > 0, "escrow must transfer a non-zero amount" );
FC_ASSERT( from != agent && to != agent, "agent must be a third party" );
FC_ASSERT( (fee.symbol == ODYSSEY_SYMBOL) || (fee.symbol == SBD_SYMBOL), "fee must be ODYSSEY or SBD" );
FC_ASSERT( sbd_amount.symbol == SBD_SYMBOL, "sbd amount must contain SBD" );
FC_ASSERT( odyssey_amount.symbol == ODYSSEY_SYMBOL, "odyssey amount must contain ODYSSEY" );
FC_ASSERT( ratification_deadline < escrow_expiration, "ratification deadline must be before escrow expiration" );
if ( json_meta.size() > 0 )
{
FC_ASSERT( fc::is_utf8(json_meta), "JSON Metadata not formatted in UTF8" );
FC_ASSERT( fc::json::is_valid(json_meta), "JSON Metadata not valid JSON" );
}
}
void escrow_approve_operation::validate()const
{
validate_account_name( from );
validate_account_name( to );
validate_account_name( agent );
validate_account_name( who );
FC_ASSERT( who == to || who == agent, "to or agent must approve escrow" );
}
void escrow_dispute_operation::validate()const
{
validate_account_name( from );
validate_account_name( to );
validate_account_name( agent );
validate_account_name( who );
FC_ASSERT( who == from || who == to, "who must be from or to" );
}
void escrow_release_operation::validate()const
{
validate_account_name( from );
validate_account_name( to );
validate_account_name( agent );
validate_account_name( who );
validate_account_name( receiver );
FC_ASSERT( who == from || who == to || who == agent, "who must be from or to or agent" );
FC_ASSERT( receiver == from || receiver == to, "receiver must be from or to" );
FC_ASSERT( sbd_amount.amount >= 0, "sbd amount cannot be negative" );
FC_ASSERT( odyssey_amount.amount >= 0, "odyssey amount cannot be negative" );
FC_ASSERT( sbd_amount.amount > 0 || odyssey_amount.amount > 0, "escrow must release a non-zero amount" );
FC_ASSERT( sbd_amount.symbol == SBD_SYMBOL, "sbd amount must contain SBD" );
FC_ASSERT( odyssey_amount.symbol == ODYSSEY_SYMBOL, "odyssey amount must contain ODYSSEY" );
}
void request_account_recovery_operation::validate()const
{
validate_account_name( recovery_account );
validate_account_name( account_to_recover );
new_owner_authority.validate();
}
void recover_account_operation::validate()const
{
validate_account_name( account_to_recover );
FC_ASSERT( !( new_owner_authority == recent_owner_authority ), "Cannot set new owner authority to the recent owner authority" );
FC_ASSERT( !new_owner_authority.is_impossible(), "new owner authority cannot be impossible" );
FC_ASSERT( !recent_owner_authority.is_impossible(), "recent owner authority cannot be impossible" );
FC_ASSERT( new_owner_authority.weight_threshold, "new owner authority cannot be trivial" );
new_owner_authority.validate();
recent_owner_authority.validate();
}
void change_recovery_account_operation::validate()const
{
validate_account_name( account_to_recover );
validate_account_name( new_recovery_account );
}
void transfer_to_savings_operation::validate()const {
validate_account_name( from );
validate_account_name( to );
FC_ASSERT( amount.amount > 0 );
FC_ASSERT( amount.symbol == ODYSSEY_SYMBOL || amount.symbol == SBD_SYMBOL );
FC_ASSERT( memo.size() < ODYSSEY_MAX_MEMO_SIZE, "Memo is too large" );
FC_ASSERT( fc::is_utf8( memo ), "Memo is not UTF8" );
}
void transfer_from_savings_operation::validate()const {
validate_account_name( from );
validate_account_name( to );
FC_ASSERT( amount.amount > 0 );
FC_ASSERT( amount.symbol == ODYSSEY_SYMBOL || amount.symbol == SBD_SYMBOL );
FC_ASSERT( memo.size() < ODYSSEY_MAX_MEMO_SIZE, "Memo is too large" );
FC_ASSERT( fc::is_utf8( memo ), "Memo is not UTF8" );
}
void cancel_transfer_from_savings_operation::validate()const {
validate_account_name( from );
}
void decline_voting_rights_operation::validate()const
{
validate_account_name( account );
}
void reset_account_operation::validate()const
{
validate_account_name( reset_account );
validate_account_name( account_to_reset );
FC_ASSERT( !new_owner_authority.is_impossible(), "new owner authority cannot be impossible" );
FC_ASSERT( new_owner_authority.weight_threshold, "new owner authority cannot be trivial" );
new_owner_authority.validate();
}
void set_reset_account_operation::validate()const
{
validate_account_name( account );
if( current_reset_account.size() )
validate_account_name( current_reset_account );
validate_account_name( reset_account );
FC_ASSERT( current_reset_account != reset_account, "new reset account cannot be current reset account" );
}
void claim_reward_balance_operation::validate()const
{
validate_account_name( account );
FC_ASSERT( is_asset_type( reward_odyssey, ODYSSEY_SYMBOL ), "Reward Odyssey must be ODYSSEY" );
FC_ASSERT( is_asset_type( reward_sbd, SBD_SYMBOL ), "Reward Odyssey must be SBD" );
FC_ASSERT( is_asset_type( reward_vests, VESTS_SYMBOL ), "Reward Odyssey must be VESTS" );
FC_ASSERT( reward_odyssey.amount >= 0, "Cannot claim a negative amount" );
FC_ASSERT( reward_sbd.amount >= 0, "Cannot claim a negative amount" );
FC_ASSERT( reward_vests.amount >= 0, "Cannot claim a negative amount" );
FC_ASSERT( reward_odyssey.amount > 0 || reward_sbd.amount > 0 || reward_vests.amount > 0, "Must claim something." );
}
void delegate_vesting_shares_operation::validate()const
{
validate_account_name( delegator );
validate_account_name( delegatee );
FC_ASSERT( delegator != delegatee, "You cannot delegate VESTS to yourself" );
FC_ASSERT( is_asset_type( vesting_shares, VESTS_SYMBOL ), "Delegation must be VESTS" );
FC_ASSERT( vesting_shares >= asset( 0, VESTS_SYMBOL ), "Delegation cannot be negative" );
}
} } // odyssey::protocol
| [
"keelson@tronlab.com"
] | keelson@tronlab.com |
13483a798c60e427aa70bca5f51436b18d12fada | cfa625b06d4924a6b69d5b9add2c19da0ba4f92c | /PhysX_3.4/Samples/SampleBase/RenderBoxActor.h | 448ab361dad63bc54d100ff5877b5282a55ac065 | [] | no_license | ldotn/simple-physx | a731775fe27281b55b03d646f72dd275eaa4befa | a065a9c734c134074c63c80a9109a398b22d040c | refs/heads/master | 2022-03-22T20:49:42.997588 | 2019-12-01T15:45:01 | 2019-12-01T15:49:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,160 | h | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef RENDER_BOX_ACTOR_H
#define RENDER_BOX_ACTOR_H
#include "RenderBaseActor.h"
#include "foundation/PxVec3.h"
namespace SampleRenderer
{
class Renderer;
}
class RenderBoxActor : public RenderBaseActor
{
public:
RenderBoxActor(SampleRenderer::Renderer& renderer, const PxVec3& extents, const PxReal* uvs=NULL);
RenderBoxActor(const RenderBoxActor&);
virtual ~RenderBoxActor();
};
#endif
| [
"pachesantiago@gmail.com"
] | pachesantiago@gmail.com |
712ce1ac0b05b218e7ea51a70df3d8ae87a087f7 | 3c6331c46dbf3537ef9a1d382f2121bd98299abb | /ReferenceSwap/ReferenceSwap/ReferenceSwap.cpp | daace0b11da1d256f23e70fe3e99710510a6da0a | [] | no_license | awbwd4/jaekk | 179b1e98b89561a4cd1fd55dd688bee9eb914254 | ddd65f717bdea093e6625a99672a59fb7a29ada2 | refs/heads/master | 2021-10-09T15:11:39.278530 | 2018-12-30T07:03:18 | 2018-12-30T07:03:18 | 112,326,924 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,394 | cpp | // ReferenceSwap.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다.
//
#include "pch.h"
#include <iostream>
using namespace std;
//참조 전달이므로 호출자 변수의 값을 변경할 수 있다.
void Swap(int &a, int &b) {
int nTmp = a;
a = b;
b = nTmp;
}
int main()
{
int x = 10, y = 20;
Swap(x, y);
cout << "x : " << x << endl;
cout << "y : " << y << endl;
return 0;
//포인터는 앵간하면 사용하지 말자!!!
}
// 프로그램 실행: <Ctrl+F5> 또는 [디버그] > [디버깅하지 않고 시작] 메뉴
// 프로그램 디버그: <F5> 키 또는 [디버그] > [디버깅 시작] 메뉴
// 시작을 위한 팁:
// 1. [솔루션 탐색기] 창을 사용하여 파일을 추가/관리합니다.
// 2. [팀 탐색기] 창을 사용하여 소스 제어에 연결합니다.
// 3. [출력] 창을 사용하여 빌드 출력 및 기타 메시지를 확인합니다.
// 4. [오류 목록] 창을 사용하여 오류를 봅니다.
// 5. [프로젝트] > [새 항목 추가]로 이동하여 새 코드 파일을 만들거나, [프로젝트] > [기존 항목 추가]로 이동하여 기존 코드 파일을 프로젝트에 추가합니다.
// 6. 나중에 이 프로젝트를 다시 열려면 [파일] > [열기] > [프로젝트]로 이동하고 .sln 파일을 선택합니다.
| [
"awbwd4@gmail.com"
] | awbwd4@gmail.com |
d5e11a2527b2c59523b9783bdd8267dbf583d14f | 00c528f1ac1223d264fccba7633c6cd40f8ef104 | /io.cpp | 35349bcce437e13e4d6ada422fbe5165c04efbe3 | [] | no_license | lyinch/ncurses-howto | cb5011053438c9f4e5e79cfc2db25ca6b9a33b59 | da16d4a98d5aa6be0b456bb6d990fabdc8779912 | refs/heads/master | 2020-05-30T12:03:59.083040 | 2019-06-06T13:11:21 | 2019-06-06T13:11:21 | 189,722,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,535 | cpp | #include <iostream>
#include <ncurses.h>
int main() {
int ch;
initscr(); // start cursed mode
raw(); // Send all keys to the program instantly
//cbreak(); // Disable terminal buffering, but let terminal handle interrupt keys normally
noecho(); // don't print user input
keypad(stdscr,TRUE); // enable reading of function keys F1,... and arrow keys
addch('a');
addch('b' | A_BOLD);
addch('c' | A_BLINK);
printw("Print at the cursor \n");
printw("Print %s at the cursor \n","formatted text");
mvprintw(10,2,"Print %s at the cursor at coordinates y: %d x: %d \n","formatted text",10,2);
addstr("Print full string to screen \n");
addnstr("Print only the first 5 characters...",5);
mvprintw(20,0,"Type any key \n");
ch = getch();
if(ch == KEY_UP)
printw("Arrow UP pressed");
else{
printw("The key pressed is ");
attron(A_UNDERLINE); // activate attribute
printw("%c", ch);
attroff(A_UNDERLINE); // turn attribute off
printw("\n");
}
refresh(); // print buffer to screen
printw("Type a string \n");
refresh();
char str[80];
getstr(str);
printw("Your string is: %s \n",str);
refresh();
int age = 0;
printw("How old are you \n");
refresh();
scanw("%d",&age);
printw("You are %d years old \n",age);
mvprintw(LINES-2,0,"We can print at the bottom with the LINES value");
refresh();
getch();
endwin();
return 0;
} | [
"backes.thierry@gmail.com"
] | backes.thierry@gmail.com |
7caa7967d5227dbf322a3863fd42311860f3febc | 4e035c6d51fa19cbdf4f584867b55e7813b69869 | /include/Rendering/SRenderTargetViewDesc.h | 2c95de5fcf46471c864b4de9d9ef1adde4570355 | [] | no_license | ipoopedmypantsuups/HitmanAbsolutionSDK | d28ec117f8da8c2f1bab3068a17c7143c5f83ea4 | c4a211550dc66687df9bdae5d4c0bf665d48f5ad | refs/heads/main | 2023-03-08T05:04:24.939062 | 2021-02-20T08:07:30 | 2021-02-20T08:07:30 | 359,103,783 | 0 | 0 | null | 2021-04-18T09:50:59 | 2021-04-18T09:50:58 | null | UTF-8 | C++ | false | false | 821 | h | #pragma once
#include "ERenderFormat.h"
class SRenderTargetViewDesc
{
public:
ERenderFormat eFormat;
enum EViewDimension
{
VIEW_DIMENSION_TEXTURE2D = 0x1,
VIEW_DIMENSION_TEXTURE2DMS = 0x2,
VIEW_DIMENSION_TEXTURE2DARRAY = 0x3,
VIEW_DIMENSION_TEXTURE3D = 0x4,
} eViewDimension;
union
{
struct SViewTexture2D
{
unsigned int nMipSlice;
} viewTexture2D;
struct SViewTexture2DArray
{
unsigned int nMipSlice;
unsigned int nFirstArraySlice;
unsigned int nArraySize;
} viewTexture2DArray;
struct SViewTexture3D
{
unsigned int nMipSlice;
unsigned int nFirstWSlice;
unsigned int nWSize;
} viewTexture3D;
};
};
| [
"pavle_nis@yahoo.com"
] | pavle_nis@yahoo.com |
e2c839299ef7a2aea2ff63aca8944c5c588f6882 | a6e16f8b4e3e9dfb7a8b6f323b7e35fb82537222 | /Various/Modula 2/Holger Kleinschmidt/M2POSX14/SRC/SIG.IPP | 21ddba9ac93759ca306fee37b5735f019efb3b3c | [] | no_license | pjones1063/Atari_ST_Sources | 59cd4af5968d20eb3bf16836fc460f018aa05e7c | fe7d2d16d3919274547efbd007f5e0ec1557396d | refs/heads/master | 2020-09-04T20:21:44.756895 | 2019-10-30T12:54:05 | 2019-10-30T12:54:05 | 219,878,695 | 2 | 0 | null | 2019-11-06T00:40:39 | 2019-11-06T00:40:39 | null | UTF-8 | C++ | false | false | 22,244 | ipp | IMPLEMENTATION MODULE sig;
__IMP_SWITCHES__
__DEBUG__
#ifdef HM2
#ifdef __LONG_WHOLE__
(*$!i+: Modul muss mit $i- uebersetzt werden! *)
(*$!w+: Modul muss mit $w- uebersetzt werden! *)
#else
(*$!i-: Modul muss mit $i+ uebersetzt werden! *)
(*$!w-: Modul muss mit $w+ uebersetzt werden! *)
#endif
#endif
(*****************************************************************************)
(* Basiert auf der MiNTLIB von Eric R. Smith und anderen *)
(* --------------------------------------------------------------------------*)
(* 14-Mai-94, Holger Kleinschmidt *)
(*****************************************************************************)
VAL_INTRINSIC
CAST_IMPORT
FROM SYSTEM IMPORT
(* TYPE *) ADDRESS,
(* PROC *) ADR;
FROM PORTAB IMPORT
(* CONST*) NULL,
(* TYPE *) UNSIGNEDWORD, SIGNEDLONG, UNSIGNEDLONG, WORDSETRANGE, WORDSET;
FROM types IMPORT
(* CONST*) ClkTck,
(* TYPE *) int, unsigned, signedlong, pidT;
IMPORT e;
FROM pLONGSET IMPORT
(* PROC *) UNIONlong, DIFFlong, INCLlong, EXCLlong, INlong;
FROM DosSystem IMPORT
(* VAR *) BASEP,
(* PROC *) SysClock, DosPid, MiNTVersion;
FROM DosSupport IMPORT
(* CONST*) MINSIG, MAXSIG,
(* VAR *) SIGMASK, SIGPENDING, SIGHANDLER;
FROM OSCALLS IMPORT
(* PROC *) Pkill, Psigpause, Psigblock, Psigsetmask, Psigpending, Pause,
Psignal, Psigaction, Pterm, Talarm, Tmalarm, Fselect, Pgetpid,
Syield, Pgetpgrp;
(*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*)
TYPE
LONGsigset = RECORD
CASE TAG_COLON BOOLEAN OF
FALSE: sigset : sigsetT;
|TRUE : siglong : UNSIGNEDLONG;
END;
END;
VAR
MiNT : BOOLEAN;
hasMask : BOOLEAN; (* Werden 'Psigblock' und 'Psigsetmask' unterstuetzt ? *)
#if !((defined HM2) || (defined TDIM2))
VAR
Wrapper : RECORD
code1 : UNSIGNEDLONG;
code2 : UNSIGNEDWORD;
code3 : UNSIGNEDWORD;
call : SigHandler;
code4 : UNSIGNEDWORD;
END;
#endif
VAR
Catch : UNSIGNEDWORD;
(*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*)
PROCEDURE sigemptyset ((* -- /AUS *) VAR set : sigsetT );
BEGIN
set[0] := WORDSET{};
set[1] := WORDSET{};
END sigemptyset;
(*---------------------------------------------------------------------------*)
PROCEDURE sigfillset ((* -- /AUS *) VAR set : sigsetT );
BEGIN
set[0] := WORDSET{0..15};
set[1] := WORDSET{0..15};
END sigfillset;
(*---------------------------------------------------------------------------*)
PROCEDURE sigaddset ((* EIN/AUS *) VAR set : sigsetT;
(* EIN/ -- *) sig : int ): int;
VAR cast : LONGsigset;
BEGIN
IF (sig < 0) OR (sig >= NSIG) THEN
e.errno := e.EINVAL;
RETURN(-1);
END;
cast.sigset := set;
INCLlong(cast.siglong, VAL(UNSIGNEDWORD,sig));
set := cast.sigset;
RETURN(0);
END sigaddset;
(*---------------------------------------------------------------------------*)
PROCEDURE sigdelset ((* EIN/AUS *) VAR set : sigsetT;
(* EIN/ -- *) sig : int ): int;
VAR cast : LONGsigset;
BEGIN
IF (sig < 0) OR (sig >= NSIG) THEN
e.errno := e.EINVAL;
RETURN(-1);
END;
cast.sigset := set;
EXCLlong(cast.siglong, VAL(UNSIGNEDWORD,sig));
set := cast.sigset;
RETURN(0);
END sigdelset;
(*---------------------------------------------------------------------------*)
PROCEDURE sigismember ((* EIN/ -- *) set : sigsetT;
(* EIN/ -- *) sig : int ): int;
VAR cast : LONGsigset;
BEGIN
IF (sig < 0) OR (sig >= NSIG) THEN
e.errno := e.EINVAL;
RETURN(-1);
END;
cast.sigset := set;
RETURN(INT(INlong(VAL(UNSIGNEDWORD,sig), cast.siglong)));
END sigismember;
(*---------------------------------------------------------------------------*)
#if (defined HM2)
(*$E+*)
#endif
(* Ohne MiNT fuer alle Compiler, mit MiNT nur fuer LPR, SPC und MM
* noetig.
*)
PROCEDURE dispatch ((* EIN/ -- *) sig : UNSIGNEDLONG );
VAR handler : SignalHandler;
BEGIN
handler.long := SIGHANDLER[VAL(UNSIGNEDWORD,sig)].HANDLER;
handler.proc(sig);
END dispatch;
#if (defined HM2)
(*$E=*)
#endif
(*---------------------------------------------------------------------------*)
PROCEDURE kill ((* EIN/ -- *) pid : pidT;
(* EIN/ -- *) sig : int ): int;
VAR handler : SignalHandler;
res : INTEGER;
savemask : UNSIGNEDLONG;
BEGIN
IF (sig < 0) OR (sig >= NSIG) THEN
e.errno := e.EINVAL;
RETURN(-1);
END;
IF Pkill(pid, sig, res) THEN
RETURN(0);
ELSIF res <> e.eINVFN THEN
(* 'Pkill'-Aufruf wird unterstuetzt, anderer Fehler *)
e.errno := res;
RETURN(-1);
ELSE
(* 'Pkill'-Aufruf wird nicht unterstuetzt *)
IF (pid < 0) OR (pid > 0) AND (pid <> DosPid(BASEP)) THEN
e.errno := e.ESRCH;
RETURN(-1);
END;
handler.long := SIGHANDLER[VAL(UNSIGNEDWORD,sig)].HANDLER;
IF (sig = SIGNULL) OR (handler.long = SigIgn) THEN
(* Signal wird ignoriert *)
RETURN(0);
ELSIF (sig <> SIGKILL) (* kann nicht maskiert werden *)
AND (sig <> SIGSTOP) (* -""- *)
AND (sig <> SIGCONT) (* -""- *)
AND INlong(VAL(UNSIGNEDWORD,sig), SIGMASK)
THEN
(* Falls Signal in der Signalmaske gesetzt -> nur vermerken *)
INCLlong(SIGPENDING, VAL(UNSIGNEDWORD,sig));
RETURN(0);
ELSE
EXCLlong(SIGPENDING, VAL(UNSIGNEDWORD,sig));
IF handler.long = SigDfl THEN
(* Kein Handler installiert -> Defaultaktion *)
IF (sig=SIGCONT) OR (sig=SIGCHLD) OR (sig=SIGWINCH) OR (sig=SIGFPE) THEN
(* Defaultaktion: Signal ignorieren *)
RETURN(0);
ELSE
(* Defaultaktion: Programm beenden *)
Pterm(VAL(CARDINAL,sig) * 256); (* Signal in obere 8 Bit *)
END;
ELSE
(* Installierten Signalhandler ausfuehren, Signalmaske solange
* aendern.
*)
savemask := SIGMASK;
SIGMASK := UNIONlong(SIGMASK, SIGHANDLER[VAL(UNSIGNEDWORD,sig)].MASK);
(* Zusaetzlich ist das behandelte Signal blockiert *)
INCLlong(SIGMASK, VAL(UNSIGNEDWORD,sig));
handler.proc(VAL(UNSIGNEDLONG,sig));
(* Alte Signalmaske wiederherstellen *)
SIGMASK := savemask;
RETURN(0);
END;
END;
END;
END kill;
(*---------------------------------------------------------------------------*)
PROCEDURE DeliverUnblocked;
(**)
VAR __REG__ unblocked : UNSIGNEDLONG;
__REG__ sig : UNSIGNEDWORD;
__REG__ void : INTEGER;
BEGIN
unblocked := DIFFlong(SIGPENDING, SIGMASK);
IF unblocked <> VAL(UNSIGNEDLONG,0) THEN
FOR sig := 1 TO NSIG - 1 DO
IF INlong(sig, unblocked) THEN
void := kill(0, INT(sig));
END;
END;
END;
END DeliverUnblocked;
(*---------------------------------------------------------------------------*)
PROCEDURE signal ((* EIN/ -- *) sig : int;
(* EIN/ -- *) handler : SignalHandler;
(* -- /AUS *) VAR old : SignalHandler ): int;
VAR func : ADDRESS;
prev : ADDRESS;
void : INTEGER;
BEGIN
IF (sig < 0) OR (sig >= NSIG) THEN
e.errno := e.EINVAL;
old.long := SigErr;
RETURN(-1);
END;
#if !((defined HM2) || (defined TDIM2))
WITH handler DO WITH SIGHANDLER[VAL(UNSIGNEDWORD,sig)] DO
old.long := HANDLER;
HANDLER := long;
IF (long = SigDfl) OR (long = SigIgn) THEN
func := CAST(ADDRESS,long);
ELSE
func := ADR(Wrapper);
END;
END; END;
#else
func := CAST(ADDRESS,handler.long);
#endif
IF Psignal(sig, func, prev) THEN
#if !((defined HM2) || (defined TDIM2))
IF prev <> ADR(Wrapper) THEN
old.long := CAST(SIGNEDLONG,prev);
END;
#else
old.long := CAST(SIGNEDLONG,prev);
#endif
RETURN(0);
ELSIF CAST(SIGNEDLONG,prev) <> VAL(SIGNEDLONG,e.eINVFN) THEN
(* 'Psignal'-Aufruf wird unterstuetzt, anderer Fehler *)
#if !((defined HM2) || (defined TDIM2))
(* Geaenderten Handler restaurieren *)
SIGHANDLER[VAL(UNSIGNEDWORD,sig)].HANDLER := old.long;
#endif
e.errno := INT(CAST(SIGNEDLONG,prev));
old.long := SigErr;
RETURN(-1);
ELSE
(* 'Psignal'-Aufruf wird nicht unterstuetzt *)
WITH SIGHANDLER[VAL(UNSIGNEDWORD,sig)] DO
#if (defined HM2) || (defined TDIM2)
old.long := HANDLER;
HANDLER := handler.long;
#endif
MASK := 0;
END;
(* Blockierung fuer behandeltes Signal aufheben und evtl. anstehendes
* Signal ausfuehren.
*)
EXCLlong(SIGMASK, VAL(UNSIGNEDWORD,sig));
DeliverUnblocked;
RETURN(0);
END;
END signal;
(*---------------------------------------------------------------------------*)
PROCEDURE sigaction ((* EIN/ -- *) sig : int;
(* EIN/ -- *) act : SigactionPtr;
(* EIN/ -- *) oact : SigactionPtr ): int;
VAR oldh : SIGNEDLONG;
tmp : SigactionRec;
res : INTEGER;
mask : LONGsigset;
BEGIN
IF (sig < 0) OR (sig >= NSIG) THEN
e.errno := e.EINVAL;
RETURN(-1);
END;
#if !((defined HM2) || (defined TDIM2))
WITH SIGHANDLER[VAL(UNSIGNEDWORD,sig)] DO
oldh := HANDLER;
IF act <> NULL THEN
(* act^ nicht veraendern, nur eine Kopie *)
tmp := act^;
act := CAST(SigactionPtr,ADR(tmp));
WITH tmp.saHandler DO
HANDLER := long;
IF (long <> SigDfl) AND (long <> SigIgn) THEN
long := CAST(SIGNEDLONG,ADR(Wrapper));
END;
END;
END;
END;
#endif
IF Psigaction(sig, act, oact, res) THEN
#if !((defined HM2) || (defined TDIM2))
IF oact <> NULL THEN
WITH oact^.saHandler DO
IF CAST(ADDRESS,long) = ADR(Wrapper) THEN
long := oldh;
END;
END;
END;
#endif
RETURN(0);
ELSIF res <> e.eINVFN THEN
(* 'Psigaction'-Aufruf wird unterstuetzt, anderer Fehler *)
#if !((defined HM2) || (defined TDIM2))
(* Geaenderten Handler restaurieren *)
SIGHANDLER[VAL(UNSIGNEDWORD,sig)].HANDLER := oldh;
#endif
e.errno := res;
RETURN(-1);
ELSE
(* 'Psigaction'-Aufruf wird nicht unterstuetzt *)
WITH SIGHANDLER[VAL(UNSIGNEDWORD,sig)] DO
IF oact <> NULL THEN
WITH oact^ DO
#if (defined HM2) || (defined TDIM2)
saHandler.long := HANDLER;
#else
saHandler.long := oldh;
#endif
saFlags := CAST(SaFlags,FLAGS);
mask.siglong := MASK;
saMask := mask.sigset;
END;
END;
IF act <> NULL THEN
WITH act^ DO
#if (defined HM2) || (defined TDIM2)
HANDLER := saHandler.long;
#endif
FLAGS := CAST(WORDSET,saFlags);
(* Innerhalb des Handlers zusaetzlich die angegebene Signalmaske
* beruecksichtigen.
*)
mask.sigset := saMask;
MASK := mask.siglong;
END;
END;
END; (* WITH SIGHANDLER *)
(* Blockierung fuer behandeltes Signal aufheben und evtl. anstehendes
* Signal ausfuehren.
*)
EXCLlong(SIGMASK, VAL(UNSIGNEDWORD,sig));
DeliverUnblocked;
RETURN(0);
END;
END sigaction;
(*---------------------------------------------------------------------------*)
PROCEDURE raise ((* EIN/ -- *) sig : int ): int;
VAR pid : INTEGER;
BEGIN
pid := Pgetpid();
IF pid < 0 THEN
(* 'Pgetpid'-Aufruf wird nicht unterstuetzt *)
RETURN(kill(0, sig));
ELSE
RETURN(kill(pid, sig));
END;
END raise;
(*---------------------------------------------------------------------------*)
PROCEDURE killpg ((* EIN/ -- *) pgrp : pidT;
(* EIN/ -- *) sig : int ): int;
BEGIN
IF pgrp < 0 THEN
e.errno := e.EINVAL;
RETURN(-1);
END;
IF Pgetpgrp() <> e.eINVFN THEN
(* Prozessgruppen werden unterstuetzt *)
RETURN(kill(-pgrp, sig));
ELSE
RETURN(kill(pgrp, sig));
END;
END killpg;
(*---------------------------------------------------------------------------*)
PROCEDURE sigprocmask ((* EIN/ -- *) how : SigBlockType;
(* EIN/ -- *) set : SigsetPtr;
(* EIN/ -- *) oset : SigsetPtr ): int;
VAR old : UNSIGNEDLONG;
mask : LONGsigset;
cast : LONGsigset;
BEGIN
mask.siglong := SIGMASK;
CASE how OF
SigBlock:
IF hasMask THEN
IF set = NULL THEN
mask.siglong := 0;
ELSE
mask.sigset := set^;
END;
mask.siglong := Psigblock(mask.siglong);
IF oset <> NULL THEN
oset^ := mask.sigset;
END;
ELSE
IF oset <> NULL THEN
oset^ := mask.sigset;
END;
IF set <> NULL THEN
cast.sigset := set^;
SIGMASK := UNIONlong(SIGMASK, cast.siglong);
END;
END;
|SigUnBlock:
IF hasMask THEN
mask.siglong := Psigblock(0);
END;
IF oset <> NULL THEN
oset^ := mask.sigset;
END;
IF set <> NULL THEN
cast.sigset := set^;
mask.siglong := DIFFlong(mask.siglong, cast.siglong);
IF hasMask THEN
old := Psigsetmask(mask.siglong);
ELSE
SIGMASK := mask.siglong;
DeliverUnblocked;
END;
END;
ELSE (* SigSetMask *)
IF hasMask THEN
IF set = NULL THEN
mask.siglong := Psigblock(0);
ELSE
mask.sigset := set^;
mask.siglong := Psigsetmask(mask.siglong);
END;
IF oset <> NULL THEN
oset^ := mask.sigset;
END;
ELSE
IF oset <> NULL THEN
oset^ := mask.sigset;
END;
IF set <> NULL THEN
mask.sigset := set^;
SIGMASK := mask.siglong;
DeliverUnblocked;
END;
END;
END;
RETURN(0);
END sigprocmask;
(*---------------------------------------------------------------------------*)
PROCEDURE sigpending ((* -- /AUS *) VAR set : sigsetT ): int;
VAR pending : LONGsigset;
res : SIGNEDLONG;
BEGIN
res := Psigpending();
IF res < VAL(SIGNEDLONG,0) THEN
(* 'Psigpending'-Aufruf wird nicht unterstuetzt *)
pending.siglong := SIGPENDING;
ELSE
pending.siglong := res;
END;
set := pending.sigset;
RETURN(0);
END sigpending;
(*---------------------------------------------------------------------------*)
PROCEDURE pause;
VAR void : INTEGER;
BEGIN
void := Pause();
e.errno := e.EINTR;
END pause;
(*---------------------------------------------------------------------------*)
PROCEDURE sigsuspend ((* EIN/ -- *) sigmask : sigsetT );
VAR mask : LONGsigset;
old : UNSIGNEDLONG;
BEGIN
mask.sigset := sigmask;
IF Psigpause(mask.siglong) < 0 THEN
(* 'Psigpause'-Aufruf wird nicht unterstuetzt *)
old := SIGMASK;
SIGMASK := mask.siglong;
DeliverUnblocked;
SIGMASK := old;
END;
e.errno := e.EINTR;
END sigsuspend;
(*---------------------------------------------------------------------------*)
PROCEDURE alarm ((* EIN/ -- *) sec : unsigned ): unsigned;
CONST MAXSEC = LC(2147483);
VAR secs : SIGNEDLONG;
rem : SIGNEDLONG;
BEGIN
IF VAL(UNSIGNEDLONG,sec) > MAXSEC THEN
(* sonst gibts Ueberlauf in MiNT *)
sec := VAL(unsigned,MAXSEC);
END;
rem := Talarm(VAL(SIGNEDLONG,sec));
IF rem < VAL(SIGNEDLONG,0) THEN
(* 'Talarm'-Aufruf wird nicht unterstuetzt *)
RETURN(0);
ELSE
RETURN(VAL(CARDINAL,rem));
END;
END alarm;
(*---------------------------------------------------------------------------*)
PROCEDURE sleep ((* EIN/ -- *) seconds : unsigned ): unsigned;
CONST MAXSEC = LC(2147483);
VAR until : UNSIGNEDLONG;
voidB : BOOLEAN;
voidL : UNSIGNEDLONG;
voidA : ADDRESS;
alarmSecs : SIGNEDLONG;
secs : SIGNEDLONG;
remain : SIGNEDLONG;
oldHandler : ADDRESS;
oldMask : UNSIGNEDLONG;
cast : LONGsigset;
res : INTEGER;
BEGIN
IF seconds = 0 THEN
RETURN(0);
END;
IF VAL(UNSIGNEDLONG,seconds) > MAXSEC THEN
(* sonst gibts Ueberlauf in MiNT *)
seconds := VAL(CARDINAL,MAXSEC);
END;
secs := VAL(SIGNEDLONG,seconds);
IF MiNT THEN
(* Das folgende Algorithmus stammt aus der MiNTLib: *)
alarmSecs := Talarm(0);
oldMask := Psigblock(0FFFFFFFFH);
voidB := Psignal(ORD(SIGALRM), ADR(Catch), oldHandler);
voidL := Psigblock(0FFFFFFFFH);
until := SysClock() DIV ClkTck + VAL(UNSIGNEDLONG,seconds);
IF (alarmSecs > VAL(SIGNEDLONG,0)) AND (alarmSecs < secs) THEN
voidL := Talarm(alarmSecs);
ELSE
voidL := Talarm(secs);
END;
EXCLlong(oldMask, VAL(UNSIGNEDWORD,SIGALRM));
res := Psigpause(oldMask);
alarmSecs := Talarm(0);
voidB := Psignal(ORD(SIGALRM), ADR(Catch), voidA);
res := Syield();
voidL := Psigblock(0FFFFFFFFH);
remain := CAST(SIGNEDLONG,until) - CAST(SIGNEDLONG,SysClock() DIV ClkTck);
IF alarmSecs > VAL(SIGNEDLONG,0) THEN
DEC(alarmSecs, secs - remain);
IF alarmSecs > VAL(SIGNEDLONG,0) THEN
voidL := Talarm(alarmSecs);
ELSE
voidB := Pkill(Pgetpid(), ORD(SIGALRM), res);
END;
END;
voidB := Psignal(ORD(SIGALRM), oldHandler, voidA);
voidL := Psigsetmask(oldMask);
res := Syield();
IF remain > VAL(SIGNEDLONG,0) THEN
RETURN(VAL(CARDINAL,remain));
ELSE
RETURN(0);
END;
ELSE
until := SysClock() + VAL(UNSIGNEDLONG,seconds) * ClkTck;
REPEAT
UNTIL SysClock() >= until;
RETURN(0);
END;
END sleep;
(*---------------------------------------------------------------------------*)
PROCEDURE usleep ((* EIN/ -- *) useconds : signedlong ): signedlong;
VAR until : UNSIGNEDLONG;
voidB : BOOLEAN;
voidL : UNSIGNEDLONG;
voidA : ADDRESS;
alarmMSecs : SIGNEDLONG;
mSecs : SIGNEDLONG;
remain : SIGNEDLONG;
oldHandler : ADDRESS;
oldMask : UNSIGNEDLONG;
cast : LONGsigset;
res : INTEGER;
BEGIN
mSecs := useconds DIV VAL(SIGNEDLONG,1000);
IF mSecs <= VAL(SIGNEDLONG,0) THEN
RETURN(0);
END;
(* 'useconds': Zeit in Millisekunden *)
IF MiNT THEN
(* Das folgende Algorithmus stammt aus der MiNTLib: *)
alarmMSecs := Tmalarm(0);
oldMask := Psigblock(0FFFFFFFFH);
voidB := Psignal(ORD(SIGALRM), ADR(Catch), oldHandler);
voidL := Psigblock(0FFFFFFFFH);
until := SysClock() * VAL(UNSIGNEDLONG,5) + CAST(UNSIGNEDLONG,mSecs);
IF (alarmMSecs > VAL(SIGNEDLONG,0)) AND (alarmMSecs < mSecs) THEN
voidL := Tmalarm(alarmMSecs);
ELSE
voidL := Tmalarm(mSecs);
END;
EXCLlong(oldMask, VAL(UNSIGNEDWORD,SIGALRM));
res := Psigpause(oldMask);
alarmMSecs := Tmalarm(0);
voidB := Psignal(ORD(SIGALRM), ADR(Catch), voidA);
res := Syield();
voidL := Psigblock(0FFFFFFFFH);
remain := CAST(SIGNEDLONG,until) - CAST(SIGNEDLONG,SysClock() * LC(5));
IF alarmMSecs > VAL(SIGNEDLONG,0) THEN
DEC(alarmMSecs, mSecs - remain);
IF alarmMSecs > VAL(SIGNEDLONG,0) THEN
voidL := Tmalarm(alarmMSecs);
ELSE
voidB := Pkill(Pgetpid(), ORD(SIGALRM), res);
END;
END;
voidB := Psignal(ORD(SIGALRM), oldHandler, voidA);
voidL := Psigsetmask(oldMask);
res := Syield();
IF remain > VAL(SIGNEDLONG,0) THEN
RETURN(VAL(UNSIGNEDLONG,remain) * VAL(UNSIGNEDLONG,1000));
ELSE
RETURN(0);
END;
ELSE
until := SysClock() + VAL(UNSIGNEDLONG,mSecs) DIV LC(5);
REPEAT
UNTIL SysClock() >= until;
END;
RETURN(0);
END usleep;
(*---------------------------------------------------------------------------*)
PROCEDURE sigmask ((* EIN/ -- *) sig : int ): UNSIGNEDLONG;
VAR cast : LONGsigset;
BEGIN
cast.siglong := 0H;
INCLlong(cast.siglong, VAL(UNSIGNEDWORD,sig));
RETURN(cast.siglong);
END sigmask;
(*---------------------------------------------------------------------------*)
PROCEDURE sigsetmask ((* EIN/ -- *) mask : UNSIGNEDLONG ): UNSIGNEDLONG;
VAR old : UNSIGNEDLONG;
BEGIN
IF hasMask THEN
RETURN(Psigsetmask(mask));
ELSE
(* 'Psigsetmask'-Aufruf wird nicht unterstuetzt *)
old := SIGMASK;
SIGMASK := mask;
DeliverUnblocked;
RETURN(old);
END;
END sigsetmask;
(*---------------------------------------------------------------------------*)
PROCEDURE sigblock ((* EIN/ -- *) mask : UNSIGNEDLONG ): UNSIGNEDLONG;
VAR old : UNSIGNEDLONG;
BEGIN
IF hasMask THEN
RETURN(Psigblock(mask));
ELSE
(* 'Psigblock'-Aufruf wird nicht unterstuetzt *)
old := SIGMASK;
SIGMASK := UNIONlong(SIGMASK, mask);
RETURN(old);
END;
END sigblock;
(*---------------------------------------------------------------------------*)
PROCEDURE sigpause ((* EIN/ -- *) mask : UNSIGNEDLONG );
(**)
VAR old : UNSIGNEDLONG;
BEGIN
IF Psigpause(mask) < 0 THEN
(* 'Psigpause'-Aufruf wird nicht unterstuetzt *)
old := SIGMASK;
SIGMASK := mask;
DeliverUnblocked;
SIGMASK := old;
END;
e.errno := e.EINTR;
END sigpause;
(*===========================================================================*)
CONST
EINVFN = 0FFFFFFE0H; (* = e.EINVFN als (UN)SIGNEDLONG-Konstante *)
BEGIN (* sig *)
MiNT := MiNTVersion() > 0;
hasMask := Psigblock(0) <> EINVFN;
(* Wenn der 'Psigblock'-Aufruf unterstuetzt wird, kann dieses Bitmuster
* nicht auftreten, weil SIGSTOP (Bit 17) und SIGCONT (Bit 19) nicht
* blockiert werden/sein koennen. Es wird angenommen, dass das Ergebnis
* des Tests auch fuer 'Psigsetmask' gilt.
*)
#if !((defined HM2) || (defined TDIM2))
WITH Wrapper DO
code1 := 202F0004H; (* move.l 4(SP),D0 *)
#ifdef MM2
code2 := 26C0H; (* move.l D0,(A3)+ *)
#else
code2 := 2F00H; (* move.l D0,-(SP) *)
#endif
code3 := 4EB9H; (* jsr ... *)
call := dispatch; (* ... dispatch *)
code4 := 4E75H; (* rts *)
END;
#endif
Catch := 4E75H; (* rts, ein sehr einfacher Signalhandler... *)
END sig.
| [
"ggn.dbug@gmail.com"
] | ggn.dbug@gmail.com |
dff3385bf1f1780ba8bfb4638607036dcc603998 | 82a4227df30a4dd54d1160a0b361b9eb5336cb66 | /mission/lib/px4_traj_pose_control.cpp | c192ab75a252a9ff8489481efe71b4dab5d66a4b | [] | no_license | myboyhood/laser_plane | 35703e1fd8a6d97c77705d53d3c7d11d75e67404 | 363c3c86de8997149f77496ec97753e1303d18f8 | refs/heads/master | 2023-03-01T17:05:36.449344 | 2021-01-19T03:54:06 | 2021-01-19T03:54:06 | 276,531,228 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,980 | cpp | //
// Created by wzy on 2020/9/1.
//
#include <mission_core.h>
using namespace Eigen;
Vector3d delta_xyz;
void mission_core::px4_waypoint_calculate(Vector3d start_p,Vector3d end_p){
waypoint_count = 0;
step_x = (end_p[0] - start_p[0])/xyz_step_count*1.0;
step_y = (end_p[1] - start_p[1])/xyz_step_count*1.0;
step_z = (end_p[2] - start_p[2])/xyz_step_count*1.0;
x_waypoints.clear();
y_waypoints.clear();
z_waypoints.clear();
for (int i = 1; i <= xyz_step_count; ++i) {
x_waypoints.push_back(start_p[0] + i*step_x);
y_waypoints.push_back(start_p[1] + i*step_y);
z_waypoints.push_back(start_p[2] + i*step_z);
}
}
void mission_core::px4_traj_track_control(bool with_time_back_){
// if(with_time_back_)
// {
// //decide number of timecount_for_backhome
// if (get_traj){
// timecount_for_backhome = 0;
// }
// else{
// timecount_for_backhome = -150;
// }
// }
while(ros::ok()){
ros::spinOnce();
// if(with_time_back_){
// //add timecount_for_backhome for break the track while
// timecount_for_backhome += 1;
// ROS_WARN("timecount_for_backhome: %d", timecount_for_backhome);
// if (timecount_for_backhome > maxtime)
// break;
// }
px4_target_x = car_pos[0]-distance_car_drone[0]*cos(yaw_rotate) + x_pos_home_origin;
px4_target_y = car_pos[1]-distance_car_drone[1]*sin(yaw_rotate) + y_pos_home_origin;
ROS_WARN("x_pos_planehome_origin: %f", x_pos_home_origin);
ROS_WARN("y_pos_planehome_origin: %f", y_pos_home_origin);
ROS_WARN("car_pos0: %f",car_pos[0]);
ROS_WARN("car_pos1: %f", car_pos[1]);
ROS_WARN("px4 target x : %f" , px4_target_x);
ROS_WARN("px4 target y : %f", px4_target_y);
ROS_WARN("odom curr x: %f", odom_msg.pose.pose.position.x);
ROS_WARN("odom curr y: %f", odom_msg.pose.pose.position.y);
px4_waypoint_calculate(curr_p, Vector3d(px4_target_x,px4_target_y,home_hover_height));
if(fabs(x_waypoints[waypoint_count]-curr_p[0]) > 0.2 || fabs(y_waypoints[waypoint_count]-curr_p[1]) > 0.2 || fabs(z_waypoints[waypoint_count]-curr_p[2]) > 0.2)
{
ROS_INFO("reaching the %d trajectory point", waypoint_count);
// ROS_INFO("3m_after_car_pos_x: %f", car_pos[0]);
// ROS_INFO("3m_after_car_pos_y: %f", car_pos[1]);
// ROS_INFO("3m_after_car_pos_z: %f", car_pos[2]);
px4_position_msg.pose.position.x = x_waypoints[waypoint_count];
px4_position_msg.pose.position.y = y_waypoints[waypoint_count];
px4_position_msg.pose.position.z = z_waypoints[waypoint_count];
// ROS_INFO("px4_position_msg.pose.position.x: %f",);
// ROS_INFO("px4_position_msg.pose.position.y: %f",px4_position_msg.pose.position.y);
// ROS_INFO("px4_position_msg.pose.position.z: %f",px4_position_msg.pose.position.z);
ROS_WARN("error_x: %f",px4_position_msg.pose.position.x - odom_msg.pose.pose.position.x);
ROS_WARN("error_y: %f",px4_position_msg.pose.position.y - odom_msg.pose.pose.position.y);
}
else{
if (waypoint_count < (xyz_step_count-1)){
waypoint_count += 1;
}
px4_position_msg.pose.position.x = x_waypoints[waypoint_count];
px4_position_msg.pose.position.y = y_waypoints[waypoint_count];
px4_position_msg.pose.position.z = z_waypoints[waypoint_count];
}
ROS_WARN("px4_position_msg.pose.position.x: %f",px4_position_msg.pose.position.x);
ROS_WARN("px4_position_msg.pose.position.y: %f",px4_position_msg.pose.position.y);
ROS_WARN("px4_position_msg.pose.position.z: %f",px4_position_msg.pose.position.z);
px4_setpoint_position_pub.publish(px4_position_msg);
rate.sleep();
}
} | [
"noreply@github.com"
] | myboyhood.noreply@github.com |
f93e64068ce9c22c43d16a66b2343e873fc4eb34 | 0288d2fff958e5b7dbc0c4e3d765bfb842a885af | /PA1/pa1-b/09.cpp | 10e05f568e4542d2de5d592cd0a55884d5132f1e | [] | no_license | georgao35/DSA | e0daf1e0eec57abb750a896b3a9b1faa206d514b | c6e13917bf7c1122db83423473c220359a633fef | refs/heads/master | 2023-02-05T20:10:30.680401 | 2021-01-01T04:02:53 | 2021-01-01T04:02:53 | 295,629,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,520 | cpp | #include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
char a[1 << 22]; // 不分块的珠子
int realn; // 珠子总长度
const int cut = 1 << 11; // 分块时每一块的长度
const int sec = 1 << 12; // 每块最大长度
char p[1 << 12][sec]; // 分的块
int plen[1 << 12]; // 每一块的长度
int pn; // 块数
struct Rank {
int first, second;
};
// a to p:将 a 切分成 p
void a2p() {
if (realn == 0) {
pn = 1;
plen[0] = 0;
return;
}
int i = 0, j = 0;
for (; j < realn; i++, j += cut) {
int m = realn - j < cut ? realn - j : cut;
memcpy(p[i], &a[j], m);
plen[i] = m;
}
pn = i;
}
// p to a:将 p “组装”回 a
void p2a() {
int old_realn = realn;
realn = 0;
for (int i = 0; i < pn; i++) {
memcpy(&a[realn], p[i], plen[i]);
realn += plen[i];
}
}
// 调试用:打印所有块,每块一行
void viewp() {
for (int i = 0; i < pn; i++) {
for (int j = 0; j < plen[i]; j++)
putchar(p[i][j]);
putchar('\n');
}
}
Rank find(int rank) {
int group = 0;
while (group < pn - 1 && rank > plen[group]) {
rank -= plen[group];
group++;
}
return {group, rank};
}
inline char &get(Rank pos) {
return p[pos.first][pos.second];
}
// 在 p 上计算珠子的插入和消除
void play(int rank, char ch) {
Rank pos = find(rank);
char *cur = &get(pos);
int succ_len = plen[pos.first] - pos.second;
if (succ_len > 0) {
memmove(cur + 1, cur, succ_len);
}
*cur = ch;
realn++;
plen[pos.first]++;
// 块过长,重组
if (plen[pos.first] >= sec) {
p2a();
a2p();
pos = find(rank);
}
Rank l = pos, r = pos;
Rank lbound, rbound;
int dis = 0;
int decrease = 0;
while (1) {
while (l.first >= 0 && get(l) == ch) {
l.second--;
dis++;
while (l.second < 0 && l.first >= 0) {
l.first--;
if (l.first >= 0)
l.second += plen[l.first];
}
}
while (r.first < pn && get(r) == ch) {
r.second++;
dis++;
while (r.second >= plen[r.first] && r.first < pn) {
r.second -= plen[r.first];
r.first++;
}
}
if (dis > 3) {
decrease += dis - 1;
lbound = l;
rbound = r;
ch = get(l);
dis = 1;
} else {
break;
}
}
if (decrease > 0) {
realn -= decrease;
l = lbound;
r = rbound;
if (l.first >= 0) {
plen[l.first] = l.second + 1;
}
if (r.first < pn) {
int len = plen[r.first] - r.second;
if (len > 0) {
memmove(&p[r.first][0], &p[r.first][r.second], len);
}
plen[r.first] = len;
}
for (int i = l.first + 1; i < r.first; i++)
plen[i] = 0;
}
}
int main() {
int n;
fgets(a, sizeof(a), stdin);
realn = strlen(a);
while (realn > 0 && (a[realn - 1] == '\n' || a[realn - 1] == '\r'))
realn--;
a2p();
scanf("%d", &n);
while (n--) {
char buf[16];
char &ch = buf[0];
int rank;
scanf("%d%s", &rank, &ch);
play(rank, ch);
}
p2a();
a[realn] = '\0';
puts(a);
return 0;
}
| [
"gaojy19@mails.tsinghua.edu.cn"
] | gaojy19@mails.tsinghua.edu.cn |
226017edc0e5b4ff31b7768be38abdba9d537036 | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-17222.cpp | 92849642b5b422ab961b14e59f26c544761781b1 | [] | no_license | TeamVault/tauCFI | e0ac60b8106fc1bb9874adc515fc01672b775123 | e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10 | refs/heads/master | 2023-05-30T20:57:13.450360 | 2021-06-14T09:10:24 | 2021-06-14T09:10:24 | 154,563,655 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,402 | cpp | struct c0;
void __attribute__ ((noinline)) tester0(c0* p);
struct c0
{
bool active0;
c0() : active0(true) {}
virtual ~c0()
{
tester0(this);
active0 = false;
}
virtual void f0(){}
};
void __attribute__ ((noinline)) tester0(c0* p)
{
p->f0();
}
struct c1;
void __attribute__ ((noinline)) tester1(c1* p);
struct c1 : virtual c0
{
bool active1;
c1() : active1(true) {}
virtual ~c1()
{
tester1(this);
c0 *p0_0 = (c0*)(c1*)(this);
tester0(p0_0);
active1 = false;
}
virtual void f1(){}
};
void __attribute__ ((noinline)) tester1(c1* p)
{
p->f1();
if (p->active0)
p->f0();
}
struct c2;
void __attribute__ ((noinline)) tester2(c2* p);
struct c2 : virtual c0, virtual c1
{
bool active2;
c2() : active2(true) {}
virtual ~c2()
{
tester2(this);
c0 *p0_0 = (c0*)(c2*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c1*)(c2*)(this);
tester0(p0_1);
c1 *p1_0 = (c1*)(c2*)(this);
tester1(p1_0);
active2 = false;
}
virtual void f2(){}
};
void __attribute__ ((noinline)) tester2(c2* p)
{
p->f2();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
}
struct c3;
void __attribute__ ((noinline)) tester3(c3* p);
struct c3 : c2, virtual c0
{
bool active3;
c3() : active3(true) {}
virtual ~c3()
{
tester3(this);
c0 *p0_0 = (c0*)(c2*)(c3*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c1*)(c2*)(c3*)(this);
tester0(p0_1);
c0 *p0_2 = (c0*)(c3*)(this);
tester0(p0_2);
c1 *p1_0 = (c1*)(c2*)(c3*)(this);
tester1(p1_0);
c2 *p2_0 = (c2*)(c3*)(this);
tester2(p2_0);
active3 = false;
}
virtual void f3(){}
};
void __attribute__ ((noinline)) tester3(c3* p)
{
p->f3();
if (p->active2)
p->f2();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
}
struct c4;
void __attribute__ ((noinline)) tester4(c4* p);
struct c4 : virtual c1, virtual c2
{
bool active4;
c4() : active4(true) {}
virtual ~c4()
{
tester4(this);
c0 *p0_0 = (c0*)(c1*)(c4*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c2*)(c4*)(this);
tester0(p0_1);
c0 *p0_2 = (c0*)(c1*)(c2*)(c4*)(this);
tester0(p0_2);
c1 *p1_0 = (c1*)(c4*)(this);
tester1(p1_0);
c1 *p1_1 = (c1*)(c2*)(c4*)(this);
tester1(p1_1);
c2 *p2_0 = (c2*)(c4*)(this);
tester2(p2_0);
active4 = false;
}
virtual void f4(){}
};
void __attribute__ ((noinline)) tester4(c4* p)
{
p->f4();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
if (p->active2)
p->f2();
}
int __attribute__ ((noinline)) inc(int v) {return ++v;}
int main()
{
c0* ptrs0[25];
ptrs0[0] = (c0*)(new c0());
ptrs0[1] = (c0*)(c1*)(new c1());
ptrs0[2] = (c0*)(c2*)(new c2());
ptrs0[3] = (c0*)(c1*)(c2*)(new c2());
ptrs0[4] = (c0*)(c2*)(c3*)(new c3());
ptrs0[5] = (c0*)(c1*)(c2*)(c3*)(new c3());
ptrs0[6] = (c0*)(c3*)(new c3());
ptrs0[7] = (c0*)(c1*)(c4*)(new c4());
ptrs0[8] = (c0*)(c2*)(c4*)(new c4());
ptrs0[9] = (c0*)(c1*)(c2*)(c4*)(new c4());
for (int i=0;i<10;i=inc(i))
{
tester0(ptrs0[i]);
delete ptrs0[i];
}
c1* ptrs1[25];
ptrs1[0] = (c1*)(new c1());
ptrs1[1] = (c1*)(c2*)(new c2());
ptrs1[2] = (c1*)(c2*)(c3*)(new c3());
ptrs1[3] = (c1*)(c4*)(new c4());
ptrs1[4] = (c1*)(c2*)(c4*)(new c4());
for (int i=0;i<5;i=inc(i))
{
tester1(ptrs1[i]);
delete ptrs1[i];
}
c2* ptrs2[25];
ptrs2[0] = (c2*)(new c2());
ptrs2[1] = (c2*)(c3*)(new c3());
ptrs2[2] = (c2*)(c4*)(new c4());
for (int i=0;i<3;i=inc(i))
{
tester2(ptrs2[i]);
delete ptrs2[i];
}
c3* ptrs3[25];
ptrs3[0] = (c3*)(new c3());
for (int i=0;i<1;i=inc(i))
{
tester3(ptrs3[i]);
delete ptrs3[i];
}
c4* ptrs4[25];
ptrs4[0] = (c4*)(new c4());
for (int i=0;i<1;i=inc(i))
{
tester4(ptrs4[i]);
delete ptrs4[i];
}
return 0;
}
| [
"ga72foq@mytum.de"
] | ga72foq@mytum.de |
085ebc07e08990451e76a6a1d35d5ba2e7919144 | bf9efdf9c30b8730d7e0aa2cbdcf2045fa14bcec | /arduino/ros_lib/asv_msgs/Heading.h | 9cf6f03dd256b878aaec12b9340ed7a033584810 | [
"MIT"
] | permissive | championway/asv_ros | d91ae81853904302300df0ef442436774a519a00 | 4ded50c48077e1e63586cd32be2354633c163975 | refs/heads/master | 2023-07-08T18:47:15.759512 | 2021-08-10T17:48:23 | 2021-08-10T17:48:23 | 215,058,858 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,485 | h | #ifndef _ROS_asv_msgs_Heading_h
#define _ROS_asv_msgs_Heading_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
namespace asv_msgs
{
class Heading : public ros::Msg
{
public:
typedef float _phi_type;
_phi_type phi;
typedef float _speed_type;
_speed_type speed;
Heading():
phi(0),
speed(0)
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
union {
float real;
uint32_t base;
} u_phi;
u_phi.real = this->phi;
*(outbuffer + offset + 0) = (u_phi.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_phi.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_phi.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_phi.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->phi);
union {
float real;
uint32_t base;
} u_speed;
u_speed.real = this->speed;
*(outbuffer + offset + 0) = (u_speed.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_speed.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_speed.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_speed.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->speed);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
union {
float real;
uint32_t base;
} u_phi;
u_phi.base = 0;
u_phi.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_phi.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_phi.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_phi.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->phi = u_phi.real;
offset += sizeof(this->phi);
union {
float real;
uint32_t base;
} u_speed;
u_speed.base = 0;
u_speed.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_speed.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_speed.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_speed.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->speed = u_speed.real;
offset += sizeof(this->speed);
return offset;
}
const char * getType(){ return "asv_msgs/Heading"; };
const char * getMD5(){ return "8fe8a91eef3de9ae7860b3f07a1529db"; };
};
}
#endif | [
"cpwearth.eed03@g2.nctu.edu.tw"
] | cpwearth.eed03@g2.nctu.edu.tw |
c75f928de8c74e5c06aa5e4ebe794fc6b5c3996e | 53a4b38250794b8745bf0a478e340c94df2e4802 | /projects/compiler-rt/test/asan/TestCases/Posix/stack-use-after-return.cc | 237c880f8e613a9c2e8348521b704d9a7c2c7e90 | [
"NCSA",
"MIT"
] | permissive | steleman/flang7 | 8ac9b0f4c9aa3f3660463c0fa5b191e27806ccc7 | b1835583939b41ba3ef91080498fba12e582340f | refs/heads/master | 2020-05-20T01:09:00.314856 | 2020-01-10T23:45:50 | 2020-01-10T23:45:50 | 185,304,403 | 0 | 0 | NOASSERTION | 2019-05-07T02:17:53 | 2019-05-07T02:17:53 | null | UTF-8 | C++ | false | false | 3,970 | cc | // RUN: %clangxx_asan -O0 %s -pthread -o %t && %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O1 %s -pthread -o %t && %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O2 %s -pthread -o %t && %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O3 %s -pthread -o %t && %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck %s
// RUN: %env_asan_opts=detect_stack_use_after_return=0 %run %t
// Regression test for a CHECK failure with small stack size and large frame.
// RUN: %clangxx_asan -O3 %s -pthread -o %t -DkSize=10000 -DUseThread -DkStackSize=131072 && %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck --check-prefix=THREAD %s
//
// Test that we can find UAR in a thread other than main:
// RUN: %clangxx_asan -DUseThread -O2 %s -pthread -o %t && %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck --check-prefix=THREAD %s
//
// Test the max_uar_stack_size_log/min_uar_stack_size_log flag.
//
// RUN: %env_asan_opts=detect_stack_use_after_return=1:max_uar_stack_size_log=20:verbosity=1 not %run %t 2>&1 | FileCheck --check-prefix=CHECK-20 %s
// RUN: %env_asan_opts=detect_stack_use_after_return=1:min_uar_stack_size_log=24:max_uar_stack_size_log=24:verbosity=1 not %run %t 2>&1 | FileCheck --check-prefix=CHECK-24 %s
// This test runs out of stack on AArch64.
// UNSUPPORTED: aarch64
// stack size log lower than expected
// XFAIL: freebsd
// FIXME: Fix this test for dynamic runtime on arm linux.
// UNSUPPORTED: (arm-linux || armhf-linux) && asan-dynamic-runtime
#include <limits.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef kSize
# define kSize 1
#endif
#ifndef UseThread
# define UseThread 0
#endif
#ifndef kStackSize
# define kStackSize 0
#endif
__attribute__((noinline))
char *Ident(char *x) {
fprintf(stderr, "1: %p\n", x);
return x;
}
__attribute__((noinline))
char *Func1() {
char local[kSize];
return Ident(local);
}
__attribute__((noinline))
void Func2(char *x) {
fprintf(stderr, "2: %p\n", x);
*x = 1;
// CHECK: WRITE of size 1 {{.*}} thread T0
// CHECK: #0{{.*}}Func2{{.*}}stack-use-after-return.cc:[[@LINE-2]]
// CHECK: is located in stack of thread T0 at offset
// CHECK: 'local'{{.*}} <== Memory access at offset {{16|32}} is inside this variable
// THREAD: WRITE of size 1 {{.*}} thread T{{[1-9]}}
// THREAD: #0{{.*}}Func2{{.*}}stack-use-after-return.cc:[[@LINE-6]]
// THREAD: is located in stack of thread T{{[1-9]}} at offset
// THREAD: 'local'{{.*}} <== Memory access at offset {{16|32}} is inside this variable
// CHECK-20: T0: FakeStack created:{{.*}} stack_size_log: 20
// CHECK-24: T0: FakeStack created:{{.*}} stack_size_log: 24
}
void *Thread(void *unused) {
Func2(Func1());
return NULL;
}
int main(int argc, char **argv) {
#if UseThread
pthread_attr_t attr;
pthread_attr_init(&attr);
if (kStackSize > 0) {
size_t desired_stack_size = kStackSize;
if (desired_stack_size < PTHREAD_STACK_MIN) {
desired_stack_size = PTHREAD_STACK_MIN;
}
int ret = pthread_attr_setstacksize(&attr, desired_stack_size);
if (ret != 0) {
fprintf(stderr, "pthread_attr_setstacksize returned %d\n", ret);
abort();
}
size_t stacksize_check;
ret = pthread_attr_getstacksize(&attr, &stacksize_check);
if (ret != 0) {
fprintf(stderr, "pthread_attr_getstacksize returned %d\n", ret);
abort();
}
if (stacksize_check != desired_stack_size) {
fprintf(stderr, "Unable to set stack size to %d, the stack size is %d.\n",
(int)desired_stack_size, (int)stacksize_check);
abort();
}
}
pthread_t t;
pthread_create(&t, &attr, Thread, 0);
pthread_attr_destroy(&attr);
pthread_join(t, 0);
#else
Func2(Func1());
#endif
return 0;
}
| [
"stefan.teleman@cavium.com"
] | stefan.teleman@cavium.com |
d74fc193a4bd0a5848eb006d980b44e22bd429e4 | aafa842bd4e19d0c4b49d82777015322d5f28302 | /Curseur.h | 39518a0da8e1035d9309a28e673ac5e090e6fe13 | [] | no_license | carodak/Gomoku | b967aeb915835c593ecd56b1bdc81b1dbc2530a3 | a30ecb9e770490aa76828392933b223d106845b3 | refs/heads/master | 2021-06-27T23:25:33.081315 | 2020-09-11T21:58:45 | 2020-09-11T21:58:45 | 151,996,493 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 759 | h | #ifndef CURSEUR_H
#define CURSEUR_H
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include "Cellule.h"
#include "Pions.h"
class Curseur
{
public:
Curseur(sf::Event &event);
//Accesseurs en lecture
float getX() const;
float getY() const;
//Accesseurs en écriture
void setX(sf::Event);
void setY(sf::Event);
//Autres
void Pion_cree_apres_click(Pions &, sf::Event, sf::RenderWindow &, Cellule &,int &, bool&, bool&);
void playsound(int);
void restriction(Pions &,sf::RenderWindow&,Cellule&);
private:
float position_souris_x; //Coordonnées du curseur dans la fenêtre de jeu
float position_souris_y;
};
#endif // CURSEUR_H
| [
"xialah@MacBook-Pro.local"
] | xialah@MacBook-Pro.local |
a425505928a38703ce15162f0f61d059cd7d654a | 9300cbc7fd196b7f503783e1280f7bf263ebacc9 | /robot/Patte.cpp | 932848f92554f08b4051542cdfd15cd2b01c16ac | [] | no_license | cipion/Porjet_Hexapod | 604233ef35d38d272dfa099bc9d77cb92ec0e4d5 | ad6f6c629f434430893b0398da988435a056be61 | refs/heads/master | 2020-03-29T14:41:09.238379 | 2015-01-22T20:28:58 | 2015-01-22T20:28:58 | 27,351,014 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,702 | cpp | #include "Patte.h"
#define M_Pi 3.14159265359
Patte::Patte()
{
}
Patte::~Patte()
{}
Patte::Patte(SerialRPi liaison, int Step, char IDCoxa, char IDFemur, char IDTibia) {
initStep = Step;
step = Step;
servoCoxa = new AX12(liaison, IDCoxa);
servoFemur = new AX12(liaison, IDFemur);
servoTibia = new AX12(liaison, IDTibia);
}
bool Patte::testAngle(int angle) {
return ( (angle >= 0) && (angle < 360) );
}
bool Patte::testLongueur(double longueur) {
return ( (longueur >= 0) && (longueur <= Robot.LONGUEUR_MAX) );
}
void Patte::setPosAll(char PosCoxa, char PosFemur, char PosTibia)
{
setPosCoxa(PosCoxa);
setPosFemur(PosFemur);
setPosTibia(PosTibia);
}
void Patte::setPosAll(char PosCoxa, char PosFemur, char PosTibia, char vitesse)
{
setPosCoxa(PosCoxa, vitesse);
setPosFemur(PosFemur, vitesse);
setPosTibia(PosTibia, vitesse);
}
void Patte::setGroundAll() {
if(step > (Robot.STEP_MAX/2))
;// TODO
}
void Patte::upDateDroiteMov(int angle, double longueur, char vitesse)
{
if(!testAngle(angle))
std::cout<<"Erreur angle droite mouvement : " << angle<< std::endl;
if(!testLongueur(longueur))
std::cout<<"Erreur longueur droite mouvement : " << longueur<< std::endl;
StructPatte w_position;
if(longueur != 0)
w_position = getPoint(angle, longueur);
else
w_position = getPointMiddle();
servoCoxa.setPositionExtrapol(w_position.getAngleCoxa(), vitesse);
servoFemur.setPositionExtrapol(w_position.getAngleFemur(), vitesse);
servoTibia.setPositionExtrapol(w_position.getAngleTibia(), vitesse);
step++;
if(step > Robot.STEP_MAX)
step = 0;
}
void Patte::setPosCoxa(char position)
{
if((position < 405) || (position > 620))
std::cout<<"Erreur angle servomoteur Coxa : " << (int)position<< std::endl;
servoCoxa.setPosition(position);
}
void Patte::setPosCoxa(char position, char vitesse)
{
if((position < 405) || (position > 620))
std::cout<<"Erreur angle servomoteur Coxa : " << (int)position<< std::endl;
servoCoxa.setPositionExtrapol(position, vitesse);
}
void Patte::setPosFemur(char position)
{
if((position < 300) || (position > 700))
std::cout<<"Erreur angle servomoteur Femur : " << (int)position<< std::endl;
servoFemur.setPosition(position);
}
void Patte::setPosFemur(char position, char vitesse)
{
if((position < 300) || (position > 700))
std::cout<<"Erreur angle servomoteur Coxa : " << (int)position<< std::endl;
servoFemur.setPositionExtrapol(position, vitesse);
}
void Patte::setPosTibia(char position)
{
if((position < 220) || (position > 710))
std::cout<<"Erreur angle servomoteur Tibia : " <<(int)position<< std::endl;
servoTibia.setPosition(position);
}
void Patte::setPosTibia(char position, char vitesse)
{
if((position < 220) || (position > 710))
std::cout<<"Erreur angle servomoteur Coxa : " << (int)position<< std::endl;
servoTibia.setPositionExtrapol(position, vitesse);
}
void Patte::resetStep() {
step = initStep;
}
static StructPatte Patte::upPatte(StructPatte position) {
position.setAngleFemur((char)(position.getAngleFemur() - Robot.VAL_UP_PATTE));
//position.setAngleTibia((char)(position.getAngleTibia() - Robot.VAL_UP_PATTE));
return position;
}
static StructPatte Patte::getPointMiddle() {
return new StructPatte((char)512, (char)575, (char)362);
}
static StructPatte Patte::getPointTop(int angle, double longueur) {
double longueurDemiCarre = ((longueur / 2) * (longueur / 2));
double w_dist1 = sqrt( longueurDemiCarre + 19321 - (longueur * 139 * cos((M_Pi *(angle)) / 180)) );
double w_dist2 = sqrt( ((w_dist1 - 52) * (w_dist1 - 52)) + 13225 );
char angleCoxa;
if(angle > 180)
angleCoxa = (char)(512 + (((180 * (acos( (((w_dist1 * w_dist1) + 19321 - longueurDemiCarre) / (2 * 139 * w_dist1)) ))/ M_Pi) * 256) / 75));
else
angleCoxa = (char)(512 - (((180 * (acos( (((w_dist1 * w_dist1) + 19321 - longueurDemiCarre) / (2 * 139 * w_dist1)) )) / M_Pi) * 256) / 75));
char angleFemur = (char)(556 + ((((180 * (acos( ((w_dist2 * w_dist2) - 13200) / (134 * w_dist2) ))/ M_Pi + 180 * (Math.acos(115 / w_dist2))/ M_Pi ) - 90) * 256) / 75));
char angleTibia = (char)(512 - (((138 - 180 *(acos( (22178 - (w_dist2 * w_dist2)) / 17822 ))/ M_Pi) * 256) / 75));
return new StructPatte(angleCoxa, angleFemur, angleTibia);
}
static Patte::StructPatte getPointBottom(int angle, double longueur) {
double longueurDemiCarre = ((longueur / 2) * (longueur / 2));
double w_dist1 = sqrt( longueurDemiCarre + 19321 - (longueur * 139 * cos(M_Pi *(180-angle) / 180)) );
double w_dist2 = sqrt( ((w_dist1 - 52) * (w_dist1 - 52)) + 13225 );
char angleCoxa;
if(angle > 180)
angleCoxa = (char)(512 - (((180 *(acos( (((w_dist1 * w_dist1) + 19321 - longueurDemiCarre) / (2 * 139 * w_dist1)) ))/ M_Pi) * 256) / 75));
else
angleCoxa = (char)(512 + (((180 *(acos( (((w_dist1 * w_dist1) + 19321 - longueurDemiCarre) / (2 * 139 * w_dist1)) ))/ M_Pi) * 256) / 75));
char angleFemur = (char)(556 + ((((180 * (acos( ((w_dist2 * w_dist2) - 13200) / (134 * w_dist2) ))/ M_Pi + 180 * (Math.acos(115 / w_dist2))/ M_Pi ) - 90) * 256) / 75));
char angleTibia = (char)(512 - (((138 - 180 *(acos( (22178 - (w_dist2 * w_dist2)) / 17822 ))/ M_Pi) * 256) / 75));
return new StructPatte(angleCoxa, angleFemur, angleTibia);
}
StructPatte Patte::getPoint(int angle, double longueur) {
int demiStep = (Robot.STEP_MAX/2);
int quartStep = (Robot.STEP_MAX/4);
int w_step = abs(step - demiStep);
StructPatte w_middle = getPointMiddle();
StructPatte w_extrem;
if(w_step < quartStep)
{
w_extrem = getPointTop(angle, longueur);
}
else if(w_step > quartStep)
{
w_step = demiStep - w_step;
w_extrem = getPointBottom(angle, longueur);
}
else
{
if((step > demiStep) && (step < Robot.STEP_MAX))
return upPatte(w_middle);
else
return w_middle;
}
StructPatte w_position = new StructPatte((char)( (((quartStep - w_step) * w_extrem.getAngleCoxa()) + (w_step * w_middle.getAngleCoxa())) / quartStep ),
(char)( (((quartStep - w_step) * w_extrem.getAngleFemur()) + (w_step * w_middle.getAngleFemur())) / quartStep ),
(char)( (((quartStep - w_step) * w_extrem.getAngleTibia()) + (w_step * w_middle.getAngleTibia())) / quartStep ));
// On leve la patte pour pisser
if((step > demiStep) && (step < Robot.STEP_MAX))
w_position = upPatte(w_position);
return w_position;
}
| [
"thomas.gache@yahoo.fr"
] | thomas.gache@yahoo.fr |
cab303b87853fef00684bc26586cde4e01c915c0 | bff9ee7f0b96ac71e609a50c4b81375768541aab | /src/external/armadillo/tests/gen_randu.cpp | c2811c4e21ca8dc1ae52089932983ee48409f2d2 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause"
] | permissive | rohitativy/turicreate | d7850f848b7ccac80e57e8042dafefc8b949b12b | 1c31ee2d008a1e9eba029bafef6036151510f1ec | refs/heads/master | 2020-03-10T02:38:23.052555 | 2018-04-11T02:20:16 | 2018-04-11T02:20:16 | 129,141,488 | 1 | 0 | BSD-3-Clause | 2018-04-11T19:06:32 | 2018-04-11T19:06:31 | null | UTF-8 | C++ | false | false | 1,670 | cpp | // Copyright 2015 Conrad Sanderson (http://conradsanderson.id.au)
// Copyright 2015 National ICT Australia (NICTA)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------
#include <numerics/armadillo.hpp>
#include "catch.hpp"
using namespace arma;
TEST_CASE("gen_randu_1")
{
const uword n_rows = 100;
const uword n_cols = 101;
mat A(n_rows,n_cols, fill::randu);
mat B(n_rows,n_cols); B.randu();
mat C; C.randu(n_rows,n_cols);
REQUIRE( (accu(A)/A.n_elem) == Approx(0.5).epsilon(0.01) );
REQUIRE( (accu(B)/A.n_elem) == Approx(0.5).epsilon(0.01) );
REQUIRE( (accu(C)/A.n_elem) == Approx(0.5).epsilon(0.01) );
REQUIRE( (mean(vectorise(A))) == Approx(0.5).epsilon(0.01) );
}
TEST_CASE("gen_randu_2")
{
mat A(50,60,fill::zeros);
A(span(1,48),span(1,58)).randu();
REQUIRE( accu(A.head_cols(1)) == Approx(0.0) );
REQUIRE( accu(A.head_rows(1)) == Approx(0.0) );
REQUIRE( accu(A.tail_cols(1)) == Approx(0.0) );
REQUIRE( accu(A.tail_rows(1)) == Approx(0.0) );
REQUIRE( mean(vectorise(A(span(1,48),span(1,58)))) == Approx(double(0.5)).epsilon(0.01) );
}
| [
"znation@apple.com"
] | znation@apple.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.