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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
025b5c459cbc7f919cb7454d64cf85f7358edade | e60daaf5dc1d0a8bfe29c09fc407d5d107bbfced | /Test.cpp | 631a7a738b686596746a8612ac8a69791d7db099 | [] | no_license | ashrajesh/ds-flight-planner | 790cd3ed3a72047a60766ef0e677ac6f46b2b38f | a9fc1024c57799f31939deb1df629e6f4dd8e443 | refs/heads/master | 2023-03-01T18:36:52.247801 | 2021-02-08T16:08:58 | 2021-02-08T16:08:58 | 337,130,763 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,264 | cpp | //
// Created by Ashwi on 10/31/2020.
//
// Created by Ashwi on 9/26/2020.
#include "catch.hpp"
#include "stringclass.h"
#include "linkedlist.h"
#include "city_node.h"
#include "stack.h"
#include "adjacency.h"
TEST_CASE("String Class can be utilized", "[stringclass]")
{
my_string(a);
char* test_temp = (char*)"hello world";
my_string data_string = test_temp;
SECTION("Test of default constructor (nothing passed into it)" )
{
my_string(test_string);
REQUIRE(test_string.get_length() == 0);
}
SECTION("Test get_string and get_length")
{
REQUIRE(strcmp(data_string.get_string(), "hello world") == 0);
REQUIRE(strcmp(data_string.get_string(), test_temp) == 0);
REQUIRE(data_string.get_length() == 11);
REQUIRE(a.get_length() == 0);
}
SECTION("Test get_words")
{
my_string raw_word;
char* remove_punctuation_1 = (char*)"hello!";
raw_word = remove_punctuation_1;
REQUIRE(strcmp(raw_word.get_words(), "hello") == 0);
}
SECTION("Test extract_sub")
{
my_string subbed_word;
char* extract_master = (char*)"word(extract me)";
subbed_word = extract_master;
REQUIRE(strcmp(subbed_word.extract_sub(), "extract me") == 0);
}
SECTION("Test get_first_char and ")
{
my_string test_me = (char*)"hello";
REQUIRE(test_me.get_first_char() == 'h');
}
SECTION("Test toLower")
{
my_string upper_case = (char*)"HeLlO WOrLD";
my_string lower_case = upper_case.toLower();
REQUIRE(strcmp(lower_case.get_string(), "hello world") == 0);
REQUIRE(lower_case.get_length() == 11);
}
SECTION("Test operators")
{
my_string test_me;
char* test_array = (char*)"test123";
test_me = test_array;
REQUIRE(strcmp(test_me.get_string(), test_array) == 0);
my_string test_two = test_me;
REQUIRE(bool(test_two == test_me) == true);
my_string test_three = (char*)"321test";
REQUIRE(test_me != test_three);
my_string test_four = test_me + test_three;
REQUIRE(strcmp(test_four.get_string(), "test123321test") == 0);
REQUIRE(test_me[1] == 'e');
}
}
TEST_CASE("LinkedList can be Utilized", "[linkedlist]")
{
/// LINKED LIST TESTS
SECTION("Test push_back, [] operator and getSize") {
linkedlist<int> test_list;
test_list.push_back(1);
test_list.push_back(7);
test_list.push_back(5);
REQUIRE(test_list[0] == 1);
REQUIRE(test_list[1] == 7);
REQUIRE(test_list[2] == 5);
REQUIRE(test_list.getSize() == 3);
}
SECTION("Test remove_duplicates (which also tests swapper, sort_list and indexNode)")
{
linkedlist<int> test_list;
test_list.push_back('c');
test_list.push_back('b');
test_list.push_back('a');
test_list.push_back('c');
test_list.push_back('d');
test_list.push_back('a');
test_list.remove_duplicates();
REQUIRE(test_list.getSize() == 4);
REQUIRE(test_list[0] == 'a');
REQUIRE(test_list[1] == 'b');
REQUIRE(test_list[2] == 'c');
REQUIRE(test_list[3] == 'd');
}
SECTION("Test remove")
{
linkedlist<int> test_list;
test_list.push_back('a');
test_list.push_back('b');
test_list.push_back('c');
test_list.push_back('d');
test_list.push_back('e');
test_list.push_back('f');
REQUIRE(test_list[0] == 'a');
test_list.remove(0);
REQUIRE(test_list[0] == 'b');
REQUIRE(test_list[2] == 'd');
REQUIRE(test_list.getSize() == 5);
test_list.remove(2);
REQUIRE(test_list.getSize() == 4);
REQUIRE(test_list[0] == 'b');
REQUIRE(test_list[1] == 'c');
REQUIRE(test_list[2] == 'e');
REQUIRE(test_list[3] == 'f');
int last = test_list.getSize()-1;
REQUIRE(test_list[last] == 'f');
test_list.remove(last);
REQUIRE(test_list.getSize() == 3);
REQUIRE(test_list[0] == 'b');
REQUIRE(test_list[1] == 'c');
REQUIRE(test_list[2] == 'e');
}
SECTION("Test = operator")
{
linkedlist<int> test_list_one;
test_list_one.push_back(1);
test_list_one.push_back(2);
test_list_one.push_back(3);
test_list_one.push_back(4);
test_list_one.push_back(5);
test_list_one.push_back(6);
linkedlist<int> test_list_two;
test_list_two = test_list_one;
bool is_equal = true;
for(int i = 0; i < test_list_one.getSize(); i++){
if(test_list_two[i] != test_list_one[i]){
is_equal = false;
}
}
REQUIRE(is_equal == true);
}
SECTION("Test = operator with copy constructor")
{
linkedlist<int> test_list_one;
test_list_one.push_back(1);
test_list_one.push_back(2);
test_list_one.push_back(3);
test_list_one.push_back(4);
test_list_one.push_back(5);
test_list_one.push_back(6);
linkedlist<int> test_list_two = test_list_one;
bool is_equal = true;
for(int i = 0; i < test_list_one.getSize(); i++){
if(test_list_two[i] != test_list_one[i]){
is_equal = false;
}
}
REQUIRE(is_equal == true);
}
}
TEST_CASE("Vector can be Utilized", "[vectorclass]")
{
my_vector<int> num_vect;
my_vector<char> alpha_vect;
REQUIRE(alpha_vect.get_vector_size() == 0);
SECTION("Test [] operator and get_vector_size") {
alpha_vect.push_back('h');
alpha_vect.push_back('i');
REQUIRE(alpha_vect[0] == 'h');
REQUIRE(alpha_vect[1] == 'i');
REQUIRE(alpha_vect.get_vector_size() == 2);
}
SECTION("Test push_back functions") {
num_vect.push_back(3);
num_vect.push_back(1);
num_vect.push_back(2);
int vector_sum = 0;
for (int i = 0; i < num_vect.get_vector_size(); i++) {
vector_sum += num_vect[i];
}
REQUIRE(vector_sum == 6);
REQUIRE(num_vect.get_vector_size() == 3);
num_vect.push_back(4, 1);
REQUIRE(num_vect[0] == 3);
REQUIRE(num_vect[1] == 4);
REQUIRE(num_vect[2] == 2);
}
SECTION("Test = operator")
{
my_vector<char> new_vect;
new_vect.push_back('x');
new_vect.push_back('y');
new_vect.push_back('z');
new_vect.push_back('h');
new_vect.push_back('i');
alpha_vect = new_vect;
bool is_equal = true;
for(int i = 0; i < alpha_vect.get_vector_size(); i++){
if(alpha_vect[i] != new_vect[i]){
is_equal = false;
}
}
REQUIRE(is_equal == true);
}
SECTION("Test pop")
{
int last_element;
num_vect.push_back(0);
num_vect.push_back(1);
num_vect.push_back(2);
num_vect.push_back(3);
last_element = num_vect.get_vector_size()-1;
REQUIRE(num_vect.get_vector_size() == 4);
REQUIRE(num_vect[last_element] == 3);
num_vect.vector_pop();
last_element = num_vect.get_vector_size()-1;
REQUIRE(num_vect.get_vector_size() == 3);
REQUIRE(num_vect[last_element] == 2);
}
SECTION("Test remove_at")
{
my_vector<int> remove_vect;
remove_vect.push_back(0);
remove_vect.push_back(1);
remove_vect.push_back(2);
remove_vect.push_back(3);
REQUIRE(remove_vect.get_vector_size() == 4);
remove_vect.remove_at(1);
REQUIRE(remove_vect.get_vector_size() == 3);
REQUIRE(remove_vect[0] == 0);
REQUIRE(remove_vect[1] == 2);
}
}
TEST_CASE("Stack can be Utilized", "[stack]")
{
stack<int> nums;
nums.push_back(3);
nums.push_back(2);
nums.push_back(1);
SECTION("Test peek")
{
REQUIRE(nums.peek() == 1);
}
SECTION("Test isEmpty")
{
stack<int> nums_two;
REQUIRE(nums_two.isEmpty() == true);
nums_two.push_back(0);
REQUIRE(nums_two.isEmpty() == false);
}
SECTION("Test Pop")
{
nums.pop();
REQUIRE(nums.peek() == 2);
nums.pop();
REQUIRE(nums.peek() == 3);
nums.pop();
REQUIRE(nums.isEmpty() == true);
}
}
TEST_CASE("Adjacency List can be Utilized", "[adjacency]")
{
my_string first_city = "Dallas";
city_node city_one;
city_one.set_city_name(first_city);
my_string second_city = "Austin";
city_node city_two;
city_two.set_city_name(second_city);
my_string third_city = "San Antonio";
city_node city_three;
city_three.set_city_name(third_city);
city_one.push_destination("New York", 55, 72, "jetBlue");
city_one.push_destination("Los Angles", 50, 70, "American");
adjacency routes;
routes.add_node(city_one);
routes.add_node(city_two);
routes.add_node(city_three);
REQUIRE(routes.get_size() == 3);
SECTION("Test Index of Cities")
{
REQUIRE(routes.get_index_of_node("Dallas") == 0);
REQUIRE(routes.get_index_of_node("Austin") == 1);
REQUIRE(routes.get_index_of_node("San Antonio") == 2);
REQUIRE(routes.find("San Antonio") == true);
REQUIRE(routes.find("Vegas") == false);
}
SECTION("Test destination stuff")
{ my_string test_1 = routes.get_next_destination("Dallas").get_string();
REQUIRE(strcmp(test_1.get_string(), "New York") == 0);
my_string test_2 = routes.get_next_destination("Dallas").get_string();
REQUIRE(strcmp(test_2.get_string(), "Los Angles") == 0);
routes.get_node("Dallas").reset_temp_index();
my_string test_3 = routes.get_next_destination("Dallas").get_string();
REQUIRE(strcmp(test_3.get_string(), "New York") == 0);
REQUIRE(routes.get_destination_index("Dallas", "New York") == 0);
REQUIRE(routes.get_destination_index("Dallas", "Los Angles") == 1);
}
}
TEST_CASE("City Nodes can be Utilized", "[city_node]")
{
SECTION("City Naming / Identifying Test")
{
my_string cityName = "Dallas";
city_node Dallas;
Dallas.set_city_name(cityName);
REQUIRE(strcmp(Dallas.get_city_name().get_string(), "Dallas") == 0);
my_string cityNametwo = "New York City";
city_node NYC;
NYC.set_city_name(cityNametwo);
REQUIRE(strcmp(NYC.get_city_name().get_string(), "New York City") == 0);
}
SECTION("Destination (simple) Properties Test") {
my_string cityName = "Dallas";
city_node Dallas;
Dallas.set_city_name(cityName);
my_string destination = "Austin";
int cost = 98;
int duration = 47;
my_string airline = "Spirit";
my_string destination_two = "San Antonio";
int cost_two = 53;
int duration_two = 124;
my_string airline_two = "Southwest";
Dallas.push_destination(destination, duration, cost, airline);
Dallas.push_destination(destination_two, duration_two, cost_two, airline_two);
REQUIRE(strcmp(Dallas.get_destination(0).get_string(), "Austin") == 0);
REQUIRE(Dallas.get_cost(0) == 98);
REQUIRE(Dallas.get_duration(0) == 47);
REQUIRE(strcmp(Dallas.get_airline(0).get_string(), "Spirit") == 0);
REQUIRE(strcmp(Dallas.get_destination(1).get_string(), "San Antonio") == 0);
REQUIRE(Dallas.get_cost(1) == 53);
REQUIRE(Dallas.get_duration(1) == 124);
REQUIRE(strcmp(Dallas.get_airline(1).get_string(), "Southwest") == 0);
}
SECTION("Destination (multiple flights for same route) Properties Test")
{
my_string cityName = "Dallas";
city_node Dallas;
Dallas.set_city_name(cityName);
my_vector<my_string> destinations;
my_vector<int> costs;
my_vector<int> durations;
my_vector<my_string> airlines;
destinations.push_back("Austin");
costs.push_back(98);
durations.push_back(47);
airlines.push_back("Spirit");
destinations.push_back("Austin");
costs.push_back(53);
durations.push_back(124);
airlines.push_back("Southwest");
Dallas.push_destination(destinations[0], durations[0], costs[0], airlines[0]);
Dallas.push_same_destination(0, durations[1], costs[1], airlines[1]);
REQUIRE(Dallas.get_many_size(0) == 2);
Dallas.push_destination("New York", 55, 72, "jetBlue");
REQUIRE(Dallas.get_many_size(1) == 1);
REQUIRE(strcmp(Dallas.get_many_airliney(0,0).get_string(), "Spirit") == 0);
REQUIRE(strcmp(Dallas.get_many_airliney(0,1).get_string(), "Southwest") == 0);
REQUIRE(strcmp(Dallas.get_many_airliney(1,0).get_string(), "jetBlue") == 0);
REQUIRE(Dallas.get_many_costy(0,0) == 98);
REQUIRE(Dallas.get_many_costy(0,1) == 53);
REQUIRE(Dallas.get_many_costy(1,0) == 72);
REQUIRE(Dallas.get_many_durationy(0,0) == 47);
REQUIRE(Dallas.get_many_durationy(0,1) == 124);
REQUIRE(Dallas.get_many_durationy(1,0) == 55);
}
} | [
"ashwin.rajesh@gmail.com"
] | ashwin.rajesh@gmail.com |
b4b08cfaec68c01130432e2b1a5d2802150370e8 | 22d8262ab315b8bef0a5189d74fdbd50ba5e990c | /spojprograms/TRICOUNT.CPP | 1cb1de387eef1c17f6516465e7e5c9aa644e0c4a | [] | no_license | kamalsam/spojkamal | b8a71ad4f07914074e955fe0f53698f0d33f4824 | 5d3b7e9b59369c0d5ab4bd0a6b0e22fc88aa952d | refs/heads/master | 2020-05-30T17:09:59.331056 | 2013-03-30T04:44:28 | 2013-03-30T04:44:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 261 | cpp | /*
kamalsam
*/
#include<iostream>
using namespace std;
int main()
{
long long int t,i;
long long int n,result;
cin>>t;
for(i=0;i<t;i++)
{
cin>>n;
result=((n*(n+2)*(2*n+1))/8);
cout<<result<<endl;
}
return 0;
} | [
"kamalsam.21@gmail.com"
] | kamalsam.21@gmail.com |
9bfbff67bd25adbff6b22963be45234d885c6aae | 246b2d5833bb63f084d14eb206b70cea01f74624 | /Defencer.h | 88cf584f99607702f7dfb2ff42b00cb31ef868c2 | [
"MIT"
] | permissive | Robert-xiaoqiang/SplendidSoccer | 3da5542ecca1ad20d5166a2924dbabad5bb696d9 | 2e3b84d45deb655c226c1375b23fbdef457deae6 | refs/heads/master | 2020-03-24T03:39:26.270126 | 2018-07-30T13:00:01 | 2018-07-30T13:00:01 | 142,427,339 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 231 | h | #pragma once
#include "General.h"
#include "OBJParse.h"
#include "Defencer.h"
class Defencer
{
public:
Defencer();
void init();
void render();
OBJParse defencerBody;
private:
//bool checkCollision();
GLuint defencerList;
};
| [
"3160101819@zju.edu.cn"
] | 3160101819@zju.edu.cn |
0f941334de7708285018e5e890a20335292825b3 | 4233f6e626aeba852f31d1e8b2df4e0c7a6bde79 | /src/Util.cpp | c60e8b2c590ce5e6573344c6401f4a3100e23d80 | [] | no_license | Anatole27/quad-rc | 9a1455ae541a5e51c2c19e1766ec42cdac6fcccd | cbfd3b1d15c3c4571e6340c4b1d3927db16ed286 | refs/heads/master | 2021-01-22T06:44:37.352326 | 2018-05-21T12:36:53 | 2018-05-21T12:36:53 | 31,164,870 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 905 | cpp | #include "Util.h"
#include "Arduino.h"
Util::Util()
{
}
void Util::compareAttitudes(float *att1, float *att2, float *dest)
{
dest[0] = att1[0]-att2[0];
for(int i=1;i<4;i++)
{
dest[i] = modulo2pi(att1[i]-att2[i]);
}
}
float Util::modulo2pi(float angle)
{
float angleWrapped = fmod(angle,2*PI);
if(angleWrapped <= -PI){
angleWrapped += 2*PI;
}
else{
if(angleWrapped > PI){
angleWrapped -= 2*PI;
}
}
return angleWrapped;
}
float Util::norm(float* vect, const int n)
{
float norm_ = 0;
for(int i=0;i<n;i++)
{
norm_ += vect[i]*vect[i];
}
norm_ = sqrt(norm_);
return norm_;
}
void Util::normalize(float* vect, const int n)
{
float norm_vect = norm(vect,n);
if(norm_vect != 0)
{
for(int i=0;i<n;i++)
{
vect[i] = vect[i]/norm_vect;
}
}
}
| [
"anatole.verhaegen@gmail.com"
] | anatole.verhaegen@gmail.com |
bfe6ff367acf967f805ed50a260142b82c6d338c | aa2fe37c0c624215d021bb75a139de89066bee23 | /JogoDaVelha/jogo_da_velha.cpp | c30f392aefcf2156725c6dab8a1e28dece601629 | [] | no_license | fonte-nele/Jogos-Console | a2e4cd604a9c73d04dfa578a6eda6c0b17e056d0 | 768b706b6871118945a24d65c6deb96715c36988 | refs/heads/master | 2020-06-08T16:49:59.924634 | 2019-06-22T18:30:41 | 2019-06-22T18:30:41 | 193,267,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,166 | cpp | #include "jogo_da_velha.h"
int cont=1,rest=9;
void criar_matriz(char m[n][n])
{
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
m[i][j] = '0';
}
}
}
string maiusculo(string nome)
{
char ch;
int tam = nome.size();
for(int i=0;i<tam;i++)
{
ch = nome[i];
ch = toupper(ch);
nome[i] = ch;
}
return nome;
}
void imprimir_matriz(char m[n][n], string nome)
{
cout<<"\n\nVez do(a) jogador(a) "<<nome<<endl;
cout<<"\n\nTabuleiro do jogo no momento "<<cont<<":\n"<<endl;
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(m[i][j]=='0')
{
if(j==2)
{
cout<<" ";
}
else
{
cout<<" "<<"//";
}
}
else
{
if(j==2)
{
cout<<" "<<m[i][j];
}
else
{
cout<<" "<<m[i][j]<<" "<<"//";
}
}
}
if(i==2)
{
cout<<endl<<endl;
}
else
{
cout<<endl<<"=============="<<endl;
}
}
cout<<"RESTAM APENAS "<<rest<<" JOGADAS... PENSE BEM...."<<endl;
cont++;
rest--;
}
void preencher_matriz(char m[n][n],string nome,char peca,int lin,int col)
{
m[lin][col] = toupper(peca);
}
bool verificar_matriz(char m[n][n],int lin,int col)
{
if(m[lin][col]=='0')
{
return true;
}
else
{
return false;
}
}
bool verificar_comb(char m[n][n],char peca)
{
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(m[i][j]==peca)
{
if(m[i][j+1]==peca)
{
if(m[i][j+2]==peca)
{
return true;
}
else
{
return false;
}
}
else
{
if(m[i+1][j]==peca)
{
if(m[i+2][j]==peca)
{
return true;
}
else
{
return false;
}
}
else
{
if(m[i+1][j+1]==peca)
{
if(m[i+2][j+2]==peca)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
}
else
{
if(m[i][j+1]==peca)
{
if(m[i+1][j+1]==peca)
{
if(m[i+2][j+1]==peca)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
if(m[i][j+2]==peca)
{
if(m[i+1][j+2]==peca)
{
if(m[i+2][j+2]==peca)
{
return true;
}
else
{
return false;
}
}
else
{
if(m[i+1][j+1]==peca)
{
if(m[i+2][j]==peca)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
else
{
if(m[i+1][j]==peca)
{
if(m[i+1][j+1]==peca)
{
if(m[i+1][j+2]==peca)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
if(m[i+2][j]==peca)
{
if(m[i+2][j+1]==peca)
{
if(m[i+2][j+2]==peca)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
return false;
}
return false;
}
return false;
}
return false;
}
}
}
return false;
}
void ganhador(string nome,string perdedor)
{
cout<<" |||||||||||||| ||| |||||||||||||| ||| |||||||||| |||||||||||||| |||| || |||||||||"<<endl;
cout<<" || || ||| ||| || || ||| ||| || ||| || || || || || "<<endl;
cout<<" || || ||| ||| || || ||| ||| || || || || || || || "<<endl;
cout<<" || || ||| ||| || || ||| ||| || || || || || || || "<<endl;
cout<<" || || ||| ||| || || ||| ||| || || || || || || || "<<endl;
cout<<" |||||||||||||| ||||||||||||||| |||||||||||||| ||||||||||||||| ||||||||||||| |||||||||||||| || || || || "<<endl;
cout<<" || ||| ||| || ||| ||| ||| || || || || || || || "<<endl;
cout<<" || ||| ||| || ||| ||| ||| || || || || || || || "<<endl;
cout<<" || ||| ||| || ||| ||| ||| || ||| || || |||| || "<<endl;
cout<<" || ||| ||| || ||| ||| ||| |||||||||| |||||||||||||| || ||| ||||||| "<<endl;
cout<<"\n\n\n\nO JOGADOR "<<nome<<" GANHOU A PARTIDA!!!!"<<endl<<endl<<endl;
cout<<"\n\nCHUPA "<<perdedor<<" PODE CHORAR!!!"<<endl<<endl<<endl;
} | [
"felipephontinelly@hotmail.com"
] | felipephontinelly@hotmail.com |
b8ca7e30d1717e495be9a43be8d8cdd802db9c18 | 16435c59f0a032ca2baf096bb5068f1cee3519b2 | /code/SC2020_Core/StrategyData.h | 5d32e2c3075815b99132eaefff9dc3e763920abe | [] | no_license | 9matan/spring-challenge-2020 | 1ee1f1ac377d11cdfa0cd3b809629dc0449d5c6e | 7910050ff961e591fb291763ba25397d4bc875d8 | refs/heads/master | 2022-11-25T21:43:17.740231 | 2020-05-17T10:27:27 | 2020-05-17T10:27:27 | 263,113,751 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 271 | h | #pragma once
#include "CodingameUtility\VectorInPlace.h"
#include "GameConfig.h"
namespace SC2020
{
class CBotImpl;
struct SStrategyData
{
CBotImpl const* m_bot;
CVectorInPlace<unsigned int, MAX_PACS_CNT_PER_PLAYER> m_pacIdsOrder;
};
} | [
"oleg.yavorovich@gmail.com"
] | oleg.yavorovich@gmail.com |
84f2d5602babeb6351b0104853a938b88585d356 | a4dbb0a8cd7927f11dfa2e31ce2f53205275cece | /Client/client.h | 82a453234c749586b5ea1e5600517a942e1fe884 | [] | no_license | khadijaAssem/Sockets | a13cc46a548cb294346eb21efcf0acf8be26ac46 | 67df2a456a13a9004590f37eaf36654007b3c9fa | refs/heads/main | 2023-09-05T02:55:59.571089 | 2021-11-12T21:06:04 | 2021-11-12T21:06:04 | 426,775,752 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | h | #pragma once
#ifndef CLIENT_H
#define CLIENT_H
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <filesystem>
// #define PORT "3490" // the port client will be connecting to
class client
{
public:
char *send_recieve_routine(struct messege_content cmd, int sockfd);
void *get_in_addr(struct sockaddr *sa);
int run(char HOSTNAME[], char PORT[], char COMMANDFILE[]);
};
#endif // CLIENT_H | [
"khadegaassem22@gmail.com"
] | khadegaassem22@gmail.com |
4a1597fe784b313a2eeaa8b6158eff4fdcc65947 | a71b70de1877959b73f7e78ee62e9138ec5a2585 | /CF/20120203/E.cpp | 6b416a23d3caf0024db4d0495f462d5f8d8a2adc | [] | no_license | HJWAJ/acm_codes | 38d32c6d12837b07584198c40ce916546085f636 | 5fa3ee82cb5114eb3cfe4e6fa2baba0f476f6434 | refs/heads/master | 2022-01-24T03:00:51.737372 | 2022-01-14T10:04:05 | 2022-01-14T10:04:05 | 151,313,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,184 | cpp | #include<iostream>
#include<iomanip>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<map>
#include<set>
#include<queue>
#include<string>
#include<vector>
using namespace std;
int a[105][105],len[105],sum[105][105];
int dp[105][105];
int ans[105][10005];
int main()
{
int n,m,i,j,k,tmp;
scanf("%d%d",&n,&m);
for(i=0;i<n;i++)
{
scanf("%d",len+i);
sum[i][0]=0;
for(j=0;j<len[i];j++)
{
scanf("%d",&a[i][j]);
sum[i][j+1]=sum[i][j]+a[i][j];
}
}
memset(dp,0,sizeof(dp));
for(i=0;i<n;i++)
for(j=1;j<=len[i];j++)
for(k=0;k<=j;k++)
{
tmp=sum[i][k]+sum[i][len[i]]-sum[i][len[i]-j+k];
if(tmp>dp[i][j])dp[i][j]=tmp;
}
memset(ans,0,sizeof(ans));
for(i=0;i<n;i++)
for(j=0;j<=m;j++)
for(k=0;k<=len[i]&&j+k<=m;k++)
if(ans[i+1][j+k]<ans[i][j]+dp[i][k])
ans[i+1][j+k]=ans[i][j]+dp[i][k];
for(j=1;j<=m;j++)
if(ans[n][j]>ans[n][0])
ans[n][0]=ans[n][j];
printf("%d\n",ans[n][0]);
return 0;
}
| [
"jiawei.hua@dianping.com"
] | jiawei.hua@dianping.com |
ca513efc1c8fb43fdf756b76d5ba12d77f0233be | 85c5b445a0d1ff5264f0b55e4fa81e87dfca4c66 | /abc/abc143/B/B.cpp | 61f6aacfd119c203f14095361025c69f91b7f167 | [] | no_license | ruanluyu/AtCoder | f3f3c8e47f97eb250cce43ace97942dc1ce0c906 | e34e644bd50fb20cad3c07aabb0478036cdcb9c2 | refs/heads/master | 2020-05-27T14:52:34.502755 | 2020-03-02T08:08:47 | 2020-03-02T08:08:47 | 188,670,048 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,850 | cpp | #include<bits/stdc++.h>
using namespace std;
#define REP(i,n) for(long long i=0;i<(n);i++)
#define REP1(i,n) for(long long i=1;i<=(n);i++)
#define REP2D(i,j,h,w) for(long long i=0;i<(h);i++) for(long long j=0;j<(w);j++)
#define REP2D1(i,j,h,w) for(long long i=1;i<=(h);i++) for(long long j=1;j<=(w);j++)
#define PER(i,n) for(long long i=((n)-1);i>=0;i--)
#define PER1(i,n) for(long long i=(n);i>0;i--)
#define FOR(i,a,b) for(long long i=(a);i<(b);i++)
#define FORE(i,a,b) for(long long i=(a);i<=(b);i++)
#define ITE(arr) for(auto ite=(arr).begin();ite!=(arr).end();++ite)
#define ALL(a) ((a).begin()),((a).end())
#define RANGE(a) (a),((a)+sizeof(a))
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
#define YNPRT(b) cout<<((b)?"Yes":"No")<<endl
#define ENTER printf("\n")
#define REV(arr) reverse(ALL(arr))
#define PRT(a) cout<<(a)<<endl
#ifdef DEBUG
#define DBPRT(a) cout << "[Debug] - " << #a << " : " << (a) << endl
#define DBSTART if(1){
#define DBEND }
#else
#define DBPRT(a) do{}while(0)
#define DBSTART if(0){
#define DBEND }
#endif
#define PRTLST(arr,num) REP(_i,num) cout<<_i<<" - "<<arr[_i]<<endl;
#define PRTLST2(arr2,d1,d2) REP(_i,d1) REP(_j,d2) cout<<_i<<","<<_j<<" : "<<arr2[_i][_j]<<endl;
#define PRTLST2D(arr2,d1,d2) do{cout<<"L\t";REP(_i,d2) cout<<_i<<"\t"; cout<<endl; REP(_i,d1){cout<<_i<<"\t";REP(_j,d2){cout<<arr2[_i][_j]<<"\t";}cout<<endl;}}while(0);
#define TOSUM(arr,sum,n) {sum[0]=arr[0];REP1(i,n-1) sum[i]=sum[i-1]+arr[i];}
#define MIN(target,v1) (target)=min(target,v1)
#define MAX(target,v1) (target)=max(target,v1)
#define P1 first
#define P2 second
#define PB push_back
#define UB upper_bound
#define LB lower_bound
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
const int INF_INT = 2147483647;
const ll INF_LL = 9223372036854775807LL;
const ull INF_ULL = 18446744073709551615Ull;
const ll P = 92540646808111039LL;
const int Move[4][2] = {-1,0,0,1,1,0,0,-1};
const int Move_[8][2] = {-1,0,-1,-1,0,1,1,1,1,0,1,-1,0,-1,-1,-1};
template<typename T1,typename T2>
ostream& operator<<(ostream& os,const pair<T1,T2>& p) {os<<"( "<<p.P1<<" , "<<p.P2<<" )";return os;}
template<typename T>
ostream& operator<<(ostream& os,const vector<T>& v) {ITE(v) os << (ite-v.begin()) << " : " << *ite <<endl;return os;}
template<typename T>
ostream& operator<<(ostream& os,const set<T>& v) {os<<" { ";ITE(v) {os<<*ite;if(ite!=--v.end()){os<<" , ";}} os<<" } ";return os;}
template<typename T1,typename T2>
ostream& operator<<(ostream& os,const map<T1,T2>& m) {ITE(m) {os<<ite->P1<<"\t\t|->\t\t"<<ite->P2<<endl;} return os;}
//---------------------
#define MAXN 55
//---------------------
ll n;
ll d[MAXN];
int main(){
cin >> n;
REP(i,n) cin >> d[i];
ll res = 0;
REP(i,n-1) FOR(j,i+1,n){
res += d[i]*d[j];
}
PRT(res);
return 0;
}
| [
"zzstarsound@gmail.com"
] | zzstarsound@gmail.com |
b145eb29410046e6413f3983e34a27bc3433330b | 89f7b6a4f52d25128ed7a237b6f699d612ca5353 | /Lotto.cpp | 56e1a9a1c6192381a3277abbe996f2bc668dec23 | [] | no_license | ArturMalec/Lotto | 6faa57995ed8160dc397498e642b0be2b60cea27 | 3678e73890f47a018ec610b07db04eb0f80dbee3 | refs/heads/master | 2020-05-21T01:35:24.967882 | 2019-05-17T14:48:11 | 2019-05-17T14:48:11 | 185,859,567 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,572 | cpp | #include "Lotto.h"
void Lotto::losowanie_gracza()
{
int INT_LOS = 6;
std::cout << "Podaj swoje liczby do skreslenia od 1 do 49: \n";
do
{
for (int i = 0; i < INT_LOS; i++)
{
std::cout << ">> ";
while (!(std::cin >> lg[i]))
{
std::cerr << "Musisz podac cyfry!" << std::endl;
std::cin.clear();
std::cin.sync();
}
if (lg[i] > 49 || lg[i] < 1)
{
std::cerr << "Liczba musi byc w przedziale od 1 do 49!!\n";
INT_LOS++;
continue;
}
else
{
liczby_gracza.push_back(lg[i]);
}
}
wynik = Lotto::check_gracza(lg, INT_LOS);
if (wynik < INT_LOS)
{
std::cerr << "Liczby nie moga sie powtarzac!!! Sproboj ponownie..." << std::endl;
for (int i = 0; i < INT_LOS; i++)
liczby_gracza.pop_back();
continue;
}
}
while (wynik < INT_LOS);
sort(liczby_gracza.begin(), liczby_gracza.end());
for (int x : liczby_gracza)
{
std::cout << x << ' ';
}
std::cout << std::endl;
}
void Lotto::losowanie_liczb()
{
std::cout << "Losowanie liczb nastapi za 3 sekundy: " << std::endl;
Sleep(3000);
while (licznik < 6)
{
los = rand() % 49 + 1;
if (!(Lotto::check_wylosowane(los, licznik)))
{
tab[licznik] = los;
licznik++;
liczby_losowane.push_back(los);
}
}
std::cout << "Wylosowane liczby w loterii: " << std::endl;
sort(liczby_losowane.begin(), liczby_losowane.end());
for (int x : liczby_losowane)
{
std::cout << x << std::endl;
Sleep(500);
}
std::cout << std::endl;
}
void Lotto::wynik_losowania()
{
const int ITER = 6;
for (int x : liczby_losowane)
{
for (int y : liczby_gracza)
{
if (y == x)
{
zliczanie++;
}
}
}
std::vector<std::string> nazwy {"jedynke","dwojke","trojke",
"czworke","piatke","szostke"};
if (zliczanie == 0)
std::cout << "Nie trafiles nic!" << std::endl;
for (int i = 1; i < ITER; i++)
{
if (zliczanie == i)
std::cout << "Trafiles " << nazwy[i-1] << std::endl;
}
}
bool Lotto::check_wylosowane(int n, int ilosc)
{
for (int i = 0; i < ilosc; i++)
{
if (tab[i] == n)
return true;
}
return false;
}
int Lotto::check_gracza(int t[], int rozmiar)
{
int l = 0;
int p = 0;
while ( l < rozmiar)
{
int z = 0;
for (int k = l+1; k < rozmiar; k++)
{
if (t[l] == t[k])
z++;
}
l=l+z+1;
if (z != 0)
p=p+z+1;
}
return rozmiar-p;
}
| [
"noreply@github.com"
] | ArturMalec.noreply@github.com |
6eb56a7762b9c7c4749d1b21162fdfebf7f6bd7b | a1e9c9d651510907dd24fee4c1093019ac9dddee | /XMPFilesStatic/source/FileHandlers/PostScript_Handler.cpp | 7f97c4f04948f4c86454037533c0f26662883c00 | [
"Apache-2.0"
] | permissive | vb0067/XMPToolkitSDK | 0d36ef00e8222f0dd34e942131328b723110a6ee | 2ab080cfc448a2f81c9633e5048a234da1a62b9e | refs/heads/master | 2021-01-10T02:07:58.630009 | 2015-12-22T08:34:25 | 2015-12-22T08:34:25 | 48,419,780 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59,361 | cpp | // =================================================================================================
// ADOBE SYSTEMS INCORPORATED
// Copyright 2004 Adobe Systems Incorporated
// All Rights Reserved
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
// =================================================================================================
#include "XMP_Environment.h" // ! XMP_Environment.h must be the first included header.
#include "XMP_Const.h"
#include "XMP_IO.hpp"
#include "XMPFiles_Impl.hpp"
#include "XMPFiles_IO.hpp"
#include "XIO.hpp"
#include "PostScript_Handler.hpp"
#include "XMPScanner.hpp"
#include "Scanner_Handler.hpp"
#include <algorithm>
using namespace std;
// =================================================================================================
/// \file PostScript_Handler.cpp
/// \brief File format handler for PostScript and EPS files.
///
// =================================================================================================
// =================================================================================================
// PostScript_MetaHandlerCTor
// ==========================
XMPFileHandler * PostScript_MetaHandlerCTor ( XMPFiles * parent )
{
XMPFileHandler * newHandler = new PostScript_MetaHandler ( parent );
return newHandler;
} // PostScript_MetaHandlerCTor
// =================================================================================================
// PostScript_CheckFormat
// ======================
bool PostScript_CheckFormat ( XMP_FileFormat format,
XMP_StringPtr filePath,
XMP_IO* fileRef,
XMPFiles * parent )
{
IgnoreParam(filePath); IgnoreParam(parent);
XMP_Assert ( (format == kXMP_EPSFile) || (format == kXMP_PostScriptFile) );
return PostScript_Support::IsValidPSFile(fileRef,format) ;
} // PostScript_CheckFormat
// =================================================================================================
// PostScript_MetaHandler::PostScript_MetaHandler
// ==============================================
PostScript_MetaHandler::PostScript_MetaHandler ( XMPFiles * _parent ):dscFlags(0),docInfoFlags(0)
,containsXMPHint(false),fileformat(kXMP_UnknownFile)
{
this->parent = _parent;
this->handlerFlags = kPostScript_HandlerFlags;
this->stdCharForm = kXMP_Char8Bit;
this->psHint = kPSHint_NoMarker;
} // PostScript_MetaHandler::PostScript_MetaHandler
// =================================================================================================
// PostScript_MetaHandler::~PostScript_MetaHandler
// ===============================================
PostScript_MetaHandler::~PostScript_MetaHandler()
{
// ! Inherit the base cleanup.
} // PostScript_MetaHandler::~PostScript_MetaHandler
// =================================================================================================
// PostScript_MetaHandler::FindPostScriptHint
// ==========================================
//
// Search for "%ADO_ContainsXMP:" at the beginning of a line, it must be before "%%EndComments". If
// the XMP marker is found, look for the MainFirst/MainLast/NoMain options.
int PostScript_MetaHandler::FindPostScriptHint()
{
bool found = false;
IOBuffer ioBuf;
XMP_Uns8 ch;
XMP_IO* fileRef = this->parent->ioRef;
XMP_AbortProc abortProc = this->parent->abortProc;
void * abortArg = this->parent->abortArg;
const bool checkAbort = (abortProc != 0);
// Check for the binary EPSF preview header.
fileRef->Rewind();
if ( ! CheckFileSpace ( fileRef, &ioBuf, 4 ) ) return false;
XMP_Uns32 fileheader = GetUns32BE ( ioBuf.ptr );
if ( fileheader == 0xC5D0D3C6 ) {
if ( ! CheckFileSpace ( fileRef, &ioBuf, 30 ) ) return false;
XMP_Uns32 psOffset = GetUns32LE ( ioBuf.ptr+4 ); // PostScript offset.
XMP_Uns32 psLength = GetUns32LE ( ioBuf.ptr+8 ); // PostScript length.
MoveToOffset ( fileRef, psOffset, &ioBuf );
}
// Look for the ContainsXMP comment.
while ( true ) {
if ( checkAbort && abortProc(abortArg) ) {
XMP_Throw ( "PostScript_MetaHandler::FindPostScriptHint - User abort", kXMPErr_UserAbort );
}
if ( ! CheckFileSpace ( fileRef, &ioBuf, kPSContainsXMPString.length() ) ) return kPSHint_NoMarker;
if ( CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSEndCommentString.c_str()), kPSEndCommentString.length() ) ) {
// Found "%%EndComments", don't look any further.
return kPSHint_NoMarker;
} else if ( ! CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsXMPString.c_str()), kPSContainsXMPString.length() ) ) {
// Not "%%EndComments" or "%ADO_ContainsXMP:", skip past the end of this line.
do {
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return kPSHint_NoMarker;
ch = *ioBuf.ptr;
++ioBuf.ptr;
} while ( ! IsNewline ( ch ) );
} else {
// Found "%ADO_ContainsXMP:", look for the main packet location option.
ioBuf.ptr += kPSContainsXMPString.length();
int xmpHint = kPSHint_NoMain; // ! From here on, a failure means "no main", not "no marker".
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return kPSHint_NoMain;
if ( ! IsSpaceOrTab ( *ioBuf.ptr ) ) return kPSHint_NoMain;
while ( true ) {
while ( true ) { // Skip leading spaces and tabs.
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return kPSHint_NoMain;
if ( ! IsSpaceOrTab ( *ioBuf.ptr ) ) break;
++ioBuf.ptr;
}
if ( IsNewline ( *ioBuf.ptr ) ) return kPSHint_NoMain; // Reached the end of the ContainsXMP comment.
if ( ! CheckFileSpace ( fileRef, &ioBuf, 6 ) ) return kPSHint_NoMain;
if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("NoMain"), 6 ) ) {
ioBuf.ptr += 6;
xmpHint = kPSHint_NoMain;
break;
} else if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("MainFi"), 6 ) ) {
ioBuf.ptr += 6;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 3 ) ) return kPSHint_NoMain;
if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("rst"), 3 ) ) {
ioBuf.ptr += 3;
xmpHint = kPSHint_MainFirst;
}
break;
} else if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("MainLa"), 6 ) ) {
ioBuf.ptr += 6;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 2 ) ) return kPSHint_NoMain;
if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("st"), 2 ) ) {
ioBuf.ptr += 2;
xmpHint = kPSHint_MainLast;
}
break;
} else {
while ( true ) { // Skip until whitespace.
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return kPSHint_NoMain;
if ( IsWhitespace ( *ioBuf.ptr ) ) break;
++ioBuf.ptr;
}
}
} // Look for the main packet location option.
// Make sure we found exactly a known option.
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return kPSHint_NoMain;
if ( ! IsWhitespace ( *ioBuf.ptr ) ) return kPSHint_NoMain;
return xmpHint;
} // Found "%ADO_ContainsXMP:".
} // Outer marker loop.
return kPSHint_NoMarker; // Should never reach here.
} // PostScript_MetaHandler::FindPostScriptHint
// =================================================================================================
// PostScript_MetaHandler::FindFirstPacket
// =======================================
//
// Run the packet scanner until we find a valid packet. The first one is the main. For simplicity,
// the state of all snips is checked after each buffer is read. In theory only the last of the
// previous snips might change from partial to valid, but then we would have to special case the
// first pass when there is no previous set of snips. Since we have to get a full report to look at
// the last snip anyway, it costs virtually nothing extra to recheck all of the snips.
bool PostScript_MetaHandler::FindFirstPacket()
{
int snipCount;
bool found = false;
size_t bufPos, bufLen;
XMP_IO* fileRef = this->parent->ioRef;
XMP_Int64 fileLen = fileRef->Length();
XMP_PacketInfo & packetInfo = this->packetInfo;
XMPScanner scanner ( fileLen );
XMPScanner::SnipInfoVector snips;
enum { kBufferSize = 64*1024 };
XMP_Uns8 buffer [kBufferSize];
XMP_AbortProc abortProc = this->parent->abortProc;
void * abortArg = this->parent->abortArg;
const bool checkAbort = (abortProc != 0);
bufPos = 0;
bufLen = 0;
fileRef->Rewind(); // Seek back to the beginning of the file.
bool firstfound=false;
while ( true )
{
if ( checkAbort && abortProc(abortArg) )
{
XMP_Throw ( "PostScript_MetaHandler::FindFirstPacket - User abort", kXMPErr_UserAbort );
}
bufPos += bufLen;
bufLen = fileRef->Read ( buffer, kBufferSize );
if ( bufLen == 0 ) return firstfound; // Must be at EoF, no packets found.
scanner.Scan ( buffer, bufPos, bufLen );
snipCount = scanner.GetSnipCount();
scanner.Report ( snips );
for ( int i = 0; i < snipCount; ++i )
{
if ( snips[i].fState == XMPScanner::eValidPacketSnip )
{
if (!firstfound)
{
if ( snips[i].fLength > 0x7FFFFFFF ) XMP_Throw ( "PostScript_MetaHandler::FindFirstPacket: Oversize packet", kXMPErr_BadXMP );
packetInfo.offset = snips[i].fOffset;
packetInfo.length = (XMP_Int32)snips[i].fLength;
packetInfo.charForm = snips[i].fCharForm;
packetInfo.writeable = (snips[i].fAccess == 'w');
firstPacketInfo=packetInfo;
lastPacketInfo=packetInfo;
firstfound=true;
}
else
{
lastPacketInfo.offset = snips[i].fOffset;
lastPacketInfo.length = (XMP_Int32)snips[i].fLength;
lastPacketInfo.charForm = snips[i].fCharForm;
lastPacketInfo.writeable = (snips[i].fAccess == 'w');
}
}
}
}
return firstfound;
} // FindFirstPacket
// =================================================================================================
// PostScript_MetaHandler::FindLastPacket
// ======================================
//
// Run the packet scanner backwards until we find the start of a packet, or a valid packet. If we
// found a packet start, resume forward scanning to see if it is a valid packet. For simplicity, all
// of the snips are checked on each pass, for much the same reasons as in FindFirstPacket.
bool PostScript_MetaHandler::FindLastPacket()
{
size_t bufPos, bufLen;
XMP_IO* fileRef = this->parent->ioRef;
XMP_Int64 fileLen = fileRef->Length();
XMP_PacketInfo & packetInfo = this->packetInfo;
// ------------------------------------------------------
// Scan the entire file to find all of the valid packets.
XMPScanner scanner ( fileLen );
enum { kBufferSize = 64*1024 };
XMP_Uns8 buffer [kBufferSize];
XMP_AbortProc abortProc = this->parent->abortProc;
void * abortArg = this->parent->abortArg;
const bool checkAbort = (abortProc != 0);
fileRef->Rewind(); // Seek back to the beginning of the file.
for ( bufPos = 0; bufPos < (size_t)fileLen; bufPos += bufLen )
{
if ( checkAbort && abortProc(abortArg) )
{
XMP_Throw ( "PostScript_MetaHandler::FindLastPacket - User abort", kXMPErr_UserAbort );
}
bufLen = fileRef->Read ( buffer, kBufferSize );
if ( bufLen == 0 ) XMP_Throw ( "PostScript_MetaHandler::FindLastPacket: Read failure", kXMPErr_ExternalFailure );
scanner.Scan ( buffer, bufPos, bufLen );
}
// -------------------------------
// Pick the last the valid packet.
int snipCount = scanner.GetSnipCount();
XMPScanner::SnipInfoVector snips ( snipCount );
scanner.Report ( snips );
bool lastfound=false;
for ( int i = 0; i < snipCount; ++i )
{
if ( snips[i].fState == XMPScanner::eValidPacketSnip )
{
if (!lastfound)
{
if ( snips[i].fLength > 0x7FFFFFFF ) XMP_Throw ( "PostScript_MetaHandler::FindLastPacket: Oversize packet", kXMPErr_BadXMP );
packetInfo.offset = snips[i].fOffset;
packetInfo.length = (XMP_Int32)snips[i].fLength;
packetInfo.charForm = snips[i].fCharForm;
packetInfo.writeable = (snips[i].fAccess == 'w');
firstPacketInfo=packetInfo;
lastPacketInfo=packetInfo;
lastfound=true;
}
else
{
lastPacketInfo.offset = snips[i].fOffset;
lastPacketInfo.length = (XMP_Int32)snips[i].fLength;
lastPacketInfo.charForm = snips[i].fCharForm;
lastPacketInfo.writeable = (snips[i].fAccess == 'w');
packetInfo=lastPacketInfo;
}
}
}
return lastfound;
} // PostScript_MetaHandler::FindLastPacket
// =================================================================================================
// PostScript_MetaHandler::setTokenInfo
// ====================================
//
// Function Sets the docInfo flag for tokens(PostScript DSC comments/ Docinfo Dictionary values)
// when parsing the file stream.Also takes note of the token offset from the start of the file
// and the length of the token
void PostScript_MetaHandler::setTokenInfo(TokenFlag tFlag,XMP_Int64 offset,XMP_Int64 length)
{
if (!(docInfoFlags&tFlag)&&tFlag>=kPS_ADOContainsXMP && tFlag<=kPS_EndPostScript)
{
size_t index=0;
XMP_Uns64 flag=tFlag;
while(flag>>=1) index++;
fileTokenInfo[index].offsetStart=offset;
fileTokenInfo[index].tokenlen=length;
docInfoFlags|=tFlag;
}
}
// =================================================================================================
// PostScript_MetaHandler::getTokenInfo
// ====================================
//
// Function returns the token info for the flag, which was collected in parsing the input file
//
PostScript_MetaHandler::TokenLocation& PostScript_MetaHandler::getTokenInfo(TokenFlag tFlag)
{
if ((docInfoFlags&tFlag)&&tFlag>=kPS_ADOContainsXMP && tFlag<=kPS_EndPostScript)
{
size_t index=0;
XMP_Uns64 flag=tFlag;
while(flag>>=1) index++;
return fileTokenInfo[index];
}
return fileTokenInfo[kPS_NoData];
}
// =================================================================================================
// PostScript_MetaHandler::ExtractDSCCommentValue
// ==============================================
//
// Function extracts the DSC comment value when parsing the file.This may be later used to reconcile
//
bool PostScript_MetaHandler::ExtractDSCCommentValue(IOBuffer &ioBuf,NativeMetadataIndex index)
{
XMP_IO* fileRef = this->parent->ioRef;
if ( ! PostScript_Support::SkipTabsAndSpaces(fileRef,ioBuf) ) return false;
if ( !IsNewline ( *ioBuf.ptr ) )
{
do
{
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
nativeMeta[index] += *ioBuf.ptr;
++ioBuf.ptr;
} while ( ! IsNewline ( *ioBuf.ptr) );
if (!PostScript_Support::HasCodesGT127(nativeMeta[index]))
{
dscFlags|=nativeIndextoFlag[index];
}
else
nativeMeta[index].clear();
}
return true;
}
// =================================================================================================
// PostScript_MetaHandler::ExtractContainsXMPHint
// ==============================================
//
// Function extracts the the value of "ADOContainsXMP:" DSC comment's value
//
bool PostScript_MetaHandler::ExtractContainsXMPHint(IOBuffer &ioBuf,XMP_Int64 containsXMPStartpos)
{
XMP_IO* fileRef = this->parent->ioRef;
int xmpHint = kPSHint_NoMain; // ! From here on, a failure means "no main", not "no marker".
//checkfor atleast one whitespace
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
if ( ! IsSpaceOrTab ( *ioBuf.ptr ) ) return false;
//skip extra ones
if ( ! PostScript_Support::SkipTabsAndSpaces(fileRef,ioBuf) ) return false;
if ( IsNewline ( *ioBuf.ptr ) ) return false; // Reached the end of the ContainsXMP comment.
if ( ! CheckFileSpace ( fileRef, &ioBuf, 6 ) ) return false ;
if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("NoMain"), 6 ) )
{
ioBuf.ptr += 6;
if ( ! PostScript_Support::SkipTabsAndSpaces(fileRef,ioBuf) ) return false;
if ( ! IsNewline( *ioBuf.ptr) ) return false;
this->psHint = kPSHint_NoMain;
setTokenInfo(kPS_ADOContainsXMP,containsXMPStartpos,ioBuf.filePos+ioBuf.ptr-ioBuf.data-containsXMPStartpos);
}
else if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("MainFi"), 6 ) )
{
ioBuf.ptr += 6;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 3 ) ) return false;
if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("rst"), 3 ) )
{
ioBuf.ptr += 3;
if ( ! PostScript_Support::SkipTabsAndSpaces(fileRef,ioBuf) ) return false;
if ( ! IsNewline( *ioBuf.ptr) ) return false;
this->psHint = kPSHint_MainFirst;
setTokenInfo(kPS_ADOContainsXMP,containsXMPStartpos,ioBuf.filePos+ioBuf.ptr-ioBuf.data-containsXMPStartpos);
containsXMPHint=true;
}
}
else if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("MainLa"), 6 ) )
{
ioBuf.ptr += 6;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 2 ) ) return false;
if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("st"), 2 ) ) {
ioBuf.ptr += 2;
if ( ! PostScript_Support::SkipTabsAndSpaces(fileRef,ioBuf) ) return false;
if ( ! IsNewline( *ioBuf.ptr) ) return false;
this->psHint = kPSHint_MainLast;
setTokenInfo(kPS_ADOContainsXMP,containsXMPStartpos,ioBuf.filePos+ioBuf.ptr-ioBuf.data-containsXMPStartpos);
containsXMPHint=true;
}
}
else
{
if ( ! PostScript_Support::SkipUntilNewline(fileRef,ioBuf) ) return false;
}
return true;
}
// =================================================================================================
// PostScript_MetaHandler::ExtractDocInfoDict
// ==============================================
//
// Function extracts the the value of DocInfo Dictionary.The keys that are looked in the dictionary
// are Creator, CreationDate, ModDate, Author, Title, Subject and Keywords.Other keys for the
// Dictionary are ignored
bool PostScript_MetaHandler::ExtractDocInfoDict(IOBuffer &ioBuf)
{
XMP_Uns8 ch;
XMP_IO* fileRef = this->parent->ioRef;
XMP_Int64 endofDocInfo=(ioBuf.ptr-ioBuf.data)+ioBuf.filePos;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
if ( IsWhitespace (*ioBuf.ptr))
{
//skip the whitespaces
if ( ! ( PostScript_Support::SkipTabsAndSpaces(fileRef, ioBuf))) return false;
//check the pdfmark
if ( ! CheckFileSpace ( fileRef, &ioBuf, kPSContainsPdfmarkString.length() ) ) return false;
if ( ! CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsPdfmarkString.c_str()), kPSContainsPdfmarkString.length() ) ) return false;
//reverse the direction to collect data
while(true)
{
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
ch=*ioBuf.ptr;
--ioBuf.ptr;
if (ch=='/') break;//slash of /DOCINFO
}
//skip white spaces
while(true)
{
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
if (!IsWhitespace(*ioBuf.ptr)) break;
--ioBuf.ptr;
}
bool findingkey=false;
std::string key, value;
while(true)
{
XMP_Uns32 noOfMarks=0;
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
if (*ioBuf.ptr==')')
{
--ioBuf.ptr;
while(true)
{
//get the string till '('
if (*ioBuf.ptr=='(')
{
if(findingkey)
{
reverse(key.begin(), key.end());
reverse(value.begin(), value.end());
RegisterKeyValue(key,value);
}
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
--ioBuf.ptr;
findingkey=!findingkey;
break;
}
else
{
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
if (findingkey)
key+=*ioBuf.ptr;
else
value+=*ioBuf.ptr;
--ioBuf.ptr;
}
}
}
else if(*ioBuf.ptr=='[')
{
//end of Doc Info parsing
//return;
break;
}
else
{
while(true)
{
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
if (findingkey)
key+=*ioBuf.ptr;
else
value+=*ioBuf.ptr;
--ioBuf.ptr;
if (*ioBuf.ptr=='/')
{
if(findingkey)
{
reverse(key.begin(), key.end());
reverse(value.begin(), value.end());
RegisterKeyValue(key,value);
}
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
--ioBuf.ptr;
findingkey=!findingkey;
break;
}
else if(IsWhitespace(*ioBuf.ptr))
{
//something not expected in Doc Info
break;
}
}
}
while(true)
{
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
if (!IsWhitespace(*ioBuf.ptr)) break;
--ioBuf.ptr;
}
}
fileRef->Rewind();
FillBuffer (fileRef, endofDocInfo, &ioBuf );
return true;
}//white space not after DOCINFO
return false;
}
// =================================================================================================
// PostScript_MetaHandler::ParsePSFile
// ===================================
//
// Main parser for the Post script file.This is where all the DSC comments , Docinfo key value pairs
// and other insertion related Data is looked for and stored
void PostScript_MetaHandler::ParsePSFile()
{
bool found = false;
IOBuffer ioBuf;
XMP_IO* fileRef = this->parent->ioRef;
XMP_AbortProc abortProc = this->parent->abortProc;
void * abortArg = this->parent->abortArg;
const bool checkAbort = (abortProc != 0);
//Determine the file type PS or EPS
if ( ! PostScript_Support::IsValidPSFile(fileRef,this->fileformat) ) return ;
// Check for the binary EPSF preview header.
fileRef->Rewind();
if ( ! CheckFileSpace ( fileRef, &ioBuf, 4 ) ) return ;
XMP_Uns32 fileheader = GetUns32BE ( ioBuf.ptr );
if ( fileheader == 0xC5D0D3C6 )
{
if ( ! CheckFileSpace ( fileRef, &ioBuf, 30 ) ) return ;
XMP_Uns32 psOffset = GetUns32LE ( ioBuf.ptr+4 ); // PostScript offset.
XMP_Uns32 psLength = GetUns32LE ( ioBuf.ptr+8 ); // PostScript length.
setTokenInfo(kPS_EndPostScript,psOffset+psLength,0);
MoveToOffset ( fileRef, psOffset, &ioBuf );
}
while ( true )
{
if ( checkAbort && abortProc(abortArg) ) {
XMP_Throw ( "PostScript_MetaHandler::FindPostScriptHint - User abort", kXMPErr_UserAbort );
}
if ( ! CheckFileSpace ( fileRef, &ioBuf, kPSContainsForString.length() ) ) return ;
if ( (CheckFileSpace ( fileRef, &ioBuf, kPSEndCommentString.length() )&&
CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSEndCommentString.c_str()), kPSEndCommentString.length() )
)|| *ioBuf.ptr!='%' || !(*(ioBuf.ptr+1)>32 && *(ioBuf.ptr+1)<=126 )) // implicit endcomment check
{
if (CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSEndCommentString.c_str()), kPSEndCommentString.length() ))
{
setTokenInfo(kPS_EndComments,ioBuf.filePos+ioBuf.ptr-ioBuf.data,kPSEndCommentString.length());
ioBuf.ptr+=kPSEndCommentString.length();
}
else
{
setTokenInfo(kPS_EndComments,ioBuf.filePos+ioBuf.ptr-ioBuf.data,0);
}
// Found "%%EndComments", look for docInfo Dictionary
// skip past the end of this line.
while(true)
{
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ;
if (! IsWhitespace (*ioBuf.ptr)) break;
++ioBuf.ptr;
}
// search for /DOCINFO
while(true)
{
if ( ! CheckFileSpace ( fileRef, &ioBuf, 5 ) ) return ;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("/DOCI"), 5 )
&& CheckFileSpace ( fileRef, &ioBuf, kPSContainsDocInfoString.length() )
&&CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsDocInfoString.c_str()), kPSContainsDocInfoString.length() ))
{
ioBuf.ptr+=kPSContainsDocInfoString.length();
ExtractDocInfoDict(ioBuf);
}// DOCINFO Not found in document
else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%Beg"), 5 ))
{//possibly one of %%BeginProlog %%BeginSetup %%BeginBinary %%BeginData
// %%BeginDocument %%BeginPageSetup
XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data;
ioBuf.ptr+=5;
if (!CheckFileSpace ( fileRef, &ioBuf, 6 )) return;
if(CheckBytes ( ioBuf.ptr, Uns8Ptr("inProl"), 6 ))
{//%%BeginProlog
ioBuf.ptr+=6;
if (!CheckFileSpace ( fileRef, &ioBuf, 2 ))return;
if(CheckBytes ( ioBuf.ptr, Uns8Ptr("og"), 2 ))
{
ioBuf.ptr+=2;
setTokenInfo(kPS_BeginProlog,begStartpos,13);
}
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inSetu"), 6 ))
{//%%BeginSetup
ioBuf.ptr+=6;
if (!CheckFileSpace ( fileRef, &ioBuf, 1 ))return;
if(CheckBytes ( ioBuf.ptr, Uns8Ptr("p"), 1 ))
{
ioBuf.ptr+=1;
setTokenInfo(kPS_BeginSetup,begStartpos,12);
}
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inBina"), 6 ))
{//%%BeginBinary
ioBuf.ptr+=6;
if (!CheckFileSpace ( fileRef, &ioBuf, 3 ))return;
if(CheckBytes ( ioBuf.ptr, Uns8Ptr("ry"), 3 ))
{
ioBuf.ptr+=3;
//ignore till %%EndBinary
while(true)
{
if (!CheckFileSpace ( fileRef, &ioBuf, 12 ))return;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("%%EndBinary"), 11 ))
{
ioBuf.ptr+=11;
if (IsWhitespace(*ioBuf.ptr))
{
ioBuf.ptr++;
break;
}
}
++ioBuf.ptr;
}
}
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inData"), 6 ))
{//%%BeginData
ioBuf.ptr+=6;
if (!CheckFileSpace ( fileRef, &ioBuf, 1 ))return;
if(CheckBytes ( ioBuf.ptr, Uns8Ptr(":"), 1 ))
{
//ignore till %%EndData
while(true)
{
if (!CheckFileSpace ( fileRef, &ioBuf, 10 ))return;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("%%EndData"), 9 ))
{
ioBuf.ptr+=9;
if (IsWhitespace(*ioBuf.ptr))
{
ioBuf.ptr++;
break;
}
}
++ioBuf.ptr;
}
}
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inDocu"), 6 ))
{// %%BeginDocument
ioBuf.ptr+=6;
if (!CheckFileSpace ( fileRef, &ioBuf, 5 ))return;
if(CheckBytes ( ioBuf.ptr, Uns8Ptr("ment:"), 5 ))
{
ioBuf.ptr+=5;
//ignore till %%EndDocument
while(true)
{
if (!CheckFileSpace ( fileRef, &ioBuf, 14 ))return;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("%%EndDocument"), 13 ))
{
ioBuf.ptr+=13;
if (IsWhitespace(*ioBuf.ptr))
{
ioBuf.ptr++;
break;
}
}
++ioBuf.ptr;
}
}
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inPage"), 6 ))
{// %%BeginPageSetup
ioBuf.ptr+=6;
if (!CheckFileSpace ( fileRef, &ioBuf, 5 ))return;
if(CheckBytes ( ioBuf.ptr, Uns8Ptr("Setup"), 5 ))
{
ioBuf.ptr+=5;
setTokenInfo(kPS_BeginPageSetup,begStartpos,16);
}
}
}
else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%End"), 5 ))
{//possibly %%EndProlog %%EndSetup %%EndPageSetup %%EndPageComments
XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data;
ioBuf.ptr+=5;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 5 ) ) return ;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("Prolo"), 5 ))
{// %%EndProlog
ioBuf.ptr+=5;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("g"), 1 ))
{
ioBuf.ptr+=1;
setTokenInfo(kPS_EndProlog,begStartpos,11);
}
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("Setup"), 5 ))
{//%%EndSetup
ioBuf.ptr+=5;
setTokenInfo(kPS_EndSetup,begStartpos,10);
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("PageS"), 5 ))
{//%%EndPageSetup
ioBuf.ptr+=5;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 4 ) ) return ;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("etup"), 4 ))
{
ioBuf.ptr+=4;
setTokenInfo(kPS_EndPageSetup,begStartpos,14);
}
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("PageC"), 5 ))
{//%%EndPageComments
ioBuf.ptr+=5;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 7 ) ) return ;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("omments"), 7 ))
{
ioBuf.ptr+=7;
setTokenInfo(kPS_EndPageComments,begStartpos,17);
}
}
}
else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%Pag"), 5 ))
{
XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data;
ioBuf.ptr+=5;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 2 ) ) return ;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr(":"), 2 ))
{
ioBuf.ptr+=2;
while(!IsNewline(*ioBuf.ptr))
{
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ;
++ioBuf.ptr;
}
setTokenInfo(kPS_Page,begStartpos,ioBuf.filePos+ioBuf.ptr-ioBuf.data-begStartpos);
}
}
else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%Tra"), 5 ))
{
XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data;
ioBuf.ptr+=5;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 4 ) ) return ;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("iler"), 4 ))
{
ioBuf.ptr+=4;
while(!IsNewline(*ioBuf.ptr)) ++ioBuf.ptr;
setTokenInfo(kPS_Trailer,begStartpos,ioBuf.filePos+ioBuf.ptr-ioBuf.data-begStartpos);
}
}
else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%EOF"), 5 ))
{
ioBuf.ptr+=5;
setTokenInfo(kPS_EOF,ioBuf.filePos+ioBuf.ptr-ioBuf.data,5);
}
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ;
++ioBuf.ptr;
}
//dont have to search after this DOCINFO last thing
return;
}else if (!(kPS_Creator & dscFlags) &&
CheckFileSpace ( fileRef, &ioBuf, kPSContainsForString.length() )&&
CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsForString.c_str()), kPSContainsForString.length() ))
{
ioBuf.ptr+=kPSContainsForString.length();
if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscFor) ) return ;
}
else if (!(kPS_CreatorTool & dscFlags) &&
CheckFileSpace ( fileRef, &ioBuf, kPSContainsCreatorString.length() )&&
CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsCreatorString.c_str()), kPSContainsCreatorString.length() ))
{
ioBuf.ptr+=kPSContainsCreatorString.length();
if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscCreator) ) return ;
}
else if (!(kPS_CreateDate & dscFlags) &&
CheckFileSpace ( fileRef, &ioBuf, kPSContainsCreateDateString.length() )&&
CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsCreateDateString.c_str()), kPSContainsCreateDateString.length() ))
{
ioBuf.ptr+=kPSContainsCreateDateString.length();
if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscCreateDate) ) return ;
}
else if (!(kPS_Title & dscFlags) &&
CheckFileSpace ( fileRef, &ioBuf, kPSContainsTitleString.length() )&&
CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsTitleString.c_str()), kPSContainsTitleString.length() ))
{
ioBuf.ptr+=kPSContainsTitleString.length();
if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscTitle) ) return ;
}
else if( CheckFileSpace ( fileRef, &ioBuf, kPSContainsXMPString.length() )&&
( CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsXMPString.c_str()), kPSContainsXMPString.length() ) )) {
// Found "%ADO_ContainsXMP:", look for the main packet location option.
XMP_Int64 containsXMPStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data;
ioBuf.ptr += kPSContainsXMPString.length();
ExtractContainsXMPHint(ioBuf,containsXMPStartpos);
} // Found "%ADO_ContainsXMP:".
//Some other DSC comments skip past the end of this line.
if ( ! PostScript_Support::SkipUntilNewline(fileRef,ioBuf) ) return ;
} // Outer marker loop.
return ; // Should never reach here.
}
// =================================================================================================
// PostScript_MetaHandler::ReadXMPPacket
// =====================================
//
// Helper method read the raw xmp into a string from a file
void PostScript_MetaHandler::ReadXMPPacket (std::string & xmpPacket )
{
if ( packetInfo.length == 0 ) XMP_Throw ( "ReadXMPPacket - No XMP packet", kXMPErr_BadXMP );
xmpPacket.erase();
xmpPacket.reserve ( packetInfo.length );
xmpPacket.append ( packetInfo.length, ' ' );
XMP_StringPtr packetStr = XMP_StringPtr ( xmpPacket.c_str() ); // Don't set until after reserving the space!
this->parent->ioRef->Seek ( packetInfo.offset, kXMP_SeekFromStart );
this->parent->ioRef->ReadAll ( (char*)packetStr, packetInfo.length );
} // ReadXMPPacket
// =================================================================================================
// PostScript_MetaHandler::RegisterKeyValue
// =========================================
//
// Helper method registers the Key value pairs for the DocInfo dictionary and sets the Appriopriate
// DocInfo flags
void PostScript_MetaHandler::RegisterKeyValue(std::string& key, std::string& value)
{
size_t vallen=value.length();
if (key.length()==0||vallen==0)
{
key.clear();
value.clear();
return;
}
for (size_t index=0;index<vallen;index++)
{
if ((unsigned char)value[index]>127)
{
key.clear();
value.clear();
return;
}
}
switch (key[0])
{
case 'A': // probably Author
{
if (!key.compare("Author"))
{
nativeMeta[kPS_docInfoAuthor]=value;
docInfoFlags|=kPS_Creator;
}
break;
}
case 'C': //probably Creator or CreationDate
{
if (!key.compare("Creator"))
{
nativeMeta[kPS_docInfoCreator]=value;
docInfoFlags|=kPS_CreatorTool;
}
else if (!key.compare("CreationDate"))
{
nativeMeta[kPS_docInfoCreateDate]=value;
docInfoFlags|=kPS_CreateDate;
}
break;
}
case 'T': // probably Title
{
if (!key.compare("Title"))
{
nativeMeta[kPS_docInfoTitle]=value;
docInfoFlags|=kPS_Title;
}
break;
}
case 'S':// probably Subject
{
if (!key.compare("Subject"))
{
nativeMeta[kPS_docInfoSubject]=value;
docInfoFlags|=kPS_Description;
}
break;
}
case 'K':// probably Keywords
{
if (!key.compare("Keywords"))
{
nativeMeta[kPS_docInfoKeywords]=value;
docInfoFlags|=kPS_Subject;
}
break;
}
case 'M': // probably ModDate
{
if (!key.compare("ModDate"))
{
nativeMeta[kPS_docInfoModDate]=value;
docInfoFlags|=kPS_ModifyDate;
}
break;
}
default: //ignore everything else
{
;
}
}
key.clear();
value.clear();
}
// =================================================================================================
// PostScript_MetaHandler::ReconcileXMP
// =========================================
//
// Helper method that facilitates the read time reconcilliation of native metadata
void PostScript_MetaHandler::ReconcileXMP( const std::string &xmpStr, std::string *outStr )
{
SXMPMeta xmp;
xmp.ParseFromBuffer( xmpStr.c_str(), xmpStr.length() );
// Adding creator Toll if any
if (!xmp.DoesPropertyExist ( kXMP_NS_XMP,"CreatorTool" ))
{
if(docInfoFlags&kPS_CreatorTool)
{
xmp.SetProperty( kXMP_NS_XMP, "CreatorTool", nativeMeta[kPS_docInfoCreator] );
}
else if (dscFlags&kPS_CreatorTool)
{
xmp.SetProperty( kXMP_NS_XMP, "CreatorTool", nativeMeta[kPS_dscCreator] );
}
}
if (!xmp.DoesPropertyExist ( kXMP_NS_XMP,"CreateDate" ))
{
if(docInfoFlags&kPS_CreateDate && nativeMeta[kPS_docInfoCreateDate].length()>0)
{
std::string xmpdate=PostScript_Support::ConvertToDate(nativeMeta[kPS_docInfoCreateDate].c_str());
if (xmpdate.length()>0)
{
xmp.SetProperty( kXMP_NS_XMP, "CreateDate", xmpdate );
}
}
else if (dscFlags&kPS_CreateDate&& nativeMeta[kPS_dscCreateDate].length()>0)
{
std::string xmpdate=PostScript_Support::ConvertToDate(nativeMeta[kPS_dscCreateDate].c_str());
xmp.SetProperty( kXMP_NS_XMP, "CreateDate", xmpdate );
}
}
if (!xmp.DoesPropertyExist ( kXMP_NS_XMP,"ModifyDate" ))
{
if(docInfoFlags&kPS_ModifyDate && nativeMeta[kPS_docInfoModDate].length()>0)
{
std::string xmpdate=PostScript_Support::ConvertToDate(nativeMeta[kPS_docInfoModDate].c_str());
if (xmpdate.length()>0)
{
xmp.SetProperty( kXMP_NS_XMP, "ModifyDate", xmpdate );
}
}
}
if (!xmp.DoesPropertyExist ( kXMP_NS_DC,"creator" ))
{
if(docInfoFlags&kPS_Creator)
{
xmp.AppendArrayItem ( kXMP_NS_DC, "creator", kXMP_PropArrayIsOrdered,
nativeMeta[kPS_docInfoAuthor] );
}
else if ( dscFlags&kPS_Creator)
{
xmp.AppendArrayItem ( kXMP_NS_DC, "creator", kXMP_PropArrayIsOrdered,
nativeMeta[kPS_dscFor] );
}
}
if (!xmp.DoesPropertyExist ( kXMP_NS_DC,"title" ))
{
if(docInfoFlags&kPS_Title)
{
xmp.SetLocalizedText( kXMP_NS_DC, "title",NULL,"x-default", nativeMeta[kPS_docInfoTitle] );
}
else if ( dscFlags&kPS_Title)
{
xmp.SetLocalizedText( kXMP_NS_DC, "title",NULL,"x-default", nativeMeta[kPS_dscTitle] );
}
}
if (!xmp.DoesPropertyExist ( kXMP_NS_DC,"description" ))
{
if(docInfoFlags&kPS_Description)
{
xmp.SetLocalizedText( kXMP_NS_DC, "description",NULL,"x-default", nativeMeta[kPS_docInfoSubject] );
}
}
if (!xmp.DoesPropertyExist ( kXMP_NS_DC,"subject" ))
{
if(docInfoFlags&kPS_Subject)
{
xmp.AppendArrayItem( kXMP_NS_DC, "subject", kXMP_PropArrayIsUnordered,
nativeMeta[kPS_docInfoKeywords], kXMP_NoOptions );
}
}
if (packetInfo.length>0)
{
try
{
xmp.SerializeToBuffer( outStr, kXMP_ExactPacketLength|kXMP_UseCompactFormat,packetInfo.length);
}
catch(...)
{
xmp.SerializeToBuffer( outStr, kXMP_UseCompactFormat,0);
}
}
else
{
xmp.SerializeToBuffer( outStr, kXMP_UseCompactFormat,0);
}
}
// =================================================================================================
// PostScript_MetaHandler::CacheFileData
// =====================================
void PostScript_MetaHandler::CacheFileData()
{
this->containsXMP = false;
this->psHint = kPSHint_NoMarker;
ParsePSFile();
if ( this->psHint == kPSHint_MainFirst ) {
this->containsXMP = FindFirstPacket();
} else if ( this->psHint == kPSHint_MainLast ) {
this->containsXMP = FindLastPacket();
}else
{
//find first packet in case of NoMain or absence of hint
//When inserting new packet should be inserted in front
//any other existing packet
FindFirstPacket();
}
if ( this->containsXMP )
{
ReadXMPPacket ( xmpPacket );
}
} // PostScript_MetaHandler::CacheFileData
// =================================================================================================
// PostScript_MetaHandler::ProcessXMP
// ==================================
void PostScript_MetaHandler::ProcessXMP()
{
XMP_Assert ( ! this->processedXMP );
this->processedXMP = true; // Make sure we only come through here once.
std::string xmptempStr=xmpPacket;
//Read time reconciliation with native metadata
try
{
ReconcileXMP(xmptempStr, &xmpPacket);
}
catch(...)
{
}
if ( ! this->xmpPacket.empty() )
{
XMP_StringPtr packetStr = this->xmpPacket.c_str();
XMP_StringLen packetLen = (XMP_StringLen)this->xmpPacket.size();
this->xmpObj.ParseFromBuffer ( packetStr, packetLen );
}
if (xmpPacket.length()>0)
{
this->containsXMP = true; // Assume we had something for the XMP.
}
}
// =================================================================================================
// PostScript_MetaHandler::modifyHeader
// =====================================
//
// Method modifies the header (if one is present) for the postscript offset, tiff offset etc.
// when an XMP update resulted in increase in the file size(non-inplace updates)
void PostScript_MetaHandler::modifyHeader(XMP_IO* fileRef,XMP_Int64 extrabytes,XMP_Int64 offset )
{
//change the header
IOBuffer temp;
fileRef->Rewind();
if ( ! CheckFileSpace ( fileRef, &temp, 4 ) ) return ;
XMP_Uns32 fileheader = GetUns32BE ( temp.ptr );
if ( fileheader == 0xC5D0D3C6 )
{
XMP_Uns8 buffLE[4];
if ( ! CheckFileSpace ( fileRef, &temp, 32 ) ) return ;
XMP_Uns32 psLength = GetUns32LE ( temp.ptr+8 ); // PostScript length.
if (psLength>0)
{
psLength+=extrabytes;
PutUns32LE ( psLength, buffLE);
fileRef->Seek ( 8, kXMP_SeekFromStart );
fileRef->Write(buffLE,4);
}
XMP_Uns32 wmfOffset = GetUns32LE ( temp.ptr+12 ); // WMF offset.
if (wmfOffset>0 && wmfOffset>offset)
{
wmfOffset+=extrabytes;
PutUns32LE ( wmfOffset, buffLE);
fileRef->Seek ( 12, kXMP_SeekFromStart );
fileRef->Write(buffLE,4);
}
XMP_Uns32 tiffOffset = GetUns32LE ( temp.ptr+20 ); // Tiff offset.
if (tiffOffset>0 && tiffOffset>offset)
{
tiffOffset+=extrabytes;
PutUns32LE ( tiffOffset, buffLE);
fileRef->Seek ( 20, kXMP_SeekFromStart );
fileRef->Write(buffLE,4);
}
//set the checksum to 0xFFFFFFFF
XMP_Uns16 checksum=0xFFFF;
PutUns16LE ( checksum, buffLE);
fileRef->Seek ( 28, kXMP_SeekFromStart );
fileRef->Write(buffLE,2);
}
}
// =================================================================================================
// PostScript_MetaHandler::DetermineUpdateMethod
// =============================================
//
// The policy followed to update a Postscript file is
// a) if the update can fit into the existing xpacket size, go for inplace update.
// b) If sub file decode filter is used to embed the metadata expand the metadata
// and the move the rest contents(after the xpacket) by some calc offset.
// c) If some other method is used to embed the xpacket readstring or readline
// insert a new metadata xpacket before the existing xpacket.
// The preference to use these methods is in the same order a , b and then c
// DetermineUpdateMethod helps to decide which method be used for the given
// input file
//
UpdateMethod PostScript_MetaHandler::DetermineUpdateMethod(std::string & outStr)
{
SXMPMeta xmp;
std::string & xmpPacket = this->xmpPacket;
XMP_PacketInfo & packetInfo = this->packetInfo;
xmp.ParseFromBuffer( xmpPacket.c_str(), xmpPacket.length() );
if (packetInfo.length>0)
{
try
{
//First try to fit the modified XMP data into existing XMP packet length
//prefers Inplace
xmp.SerializeToBuffer( &outStr, kXMP_ExactPacketLength|kXMP_UseCompactFormat,packetInfo.length);
}
catch(...)
{
// if it doesnt fit :(
xmp.SerializeToBuffer( &outStr, kXMP_UseCompactFormat,0);
}
}
else
{
// this will be the case for Injecting new metadata
xmp.SerializeToBuffer( &outStr, kXMP_UseCompactFormat,0);
}
if ( this->containsXMPHint && (outStr.size() == (size_t)packetInfo.length) )
{
return kPS_Inplace;
}
else if (this->containsXMPHint && PostScript_Support::IsSFDFilterUsed(this->parent->ioRef,packetInfo.offset))
{
return kPS_ExpandSFDFilter;
}
else
{
return kPS_InjectNew;
}
}
// =================================================================================================
// PostScript_MetaHandler::InplaceUpdate
// =====================================
//
// Method does the inplace update of the metadata
void PostScript_MetaHandler::InplaceUpdate (std::string &outStr,XMP_IO* &tempRef ,bool doSafeUpdate)
{
XMP_IO* fileRef = this->parent->ioRef;
XMP_Int64 pos = 0;
XMP_ProgressTracker* progressTracker = this->parent->progressTracker;
//Inplace update of metadata
if (!doSafeUpdate)
{
if ( progressTracker != 0 ) progressTracker->AddTotalWork ((float) outStr.length() );
fileRef->Seek(packetInfo.offset,kXMP_SeekFromStart);
fileRef->Write((void *)outStr.c_str(), static_cast<XMP_Uns32>(outStr.length()));
}
else
{
if ( ! tempRef ) tempRef=fileRef->DeriveTemp();
pos=fileRef->Length();
if ( progressTracker != 0 ) progressTracker->AddTotalWork ((float) pos );
//copy data till xmp Packet
fileRef->Seek(0,kXMP_SeekFromStart);
XIO::Copy ( fileRef, tempRef, packetInfo.offset, this->parent->abortProc, this->parent->abortArg );
//insert the new XMP packet
fileRef->Seek(packetInfo.offset+packetInfo.length,kXMP_SeekFromStart);
tempRef->Write((void *)outStr.c_str(), static_cast<XMP_Uns32>(outStr.length()));
//copy the rest of data
XIO::Copy ( fileRef, tempRef,pos-packetInfo.offset-packetInfo.length, this->parent->abortProc, this->parent->abortArg );
}
}
// =================================================================================================
// PostScript_MetaHandler::ExpandingSFDFilterUpdate
// ================================================
//
// Method updates the metadata by expanding it
void PostScript_MetaHandler::ExpandingSFDFilterUpdate (std::string &outStr,XMP_IO* &tempRef ,bool doSafeUpdate)
{
//If SubFileDecode Filter is present expanding the
//existing metadata is easy
XMP_IO* fileRef = this->parent->ioRef;
XMP_Int64 pos = 0;
XMP_Int32 extrapacketlength=outStr.length()-packetInfo.length;
XMP_ProgressTracker* progressTracker = this->parent->progressTracker;
if ( progressTracker != 0 ) progressTracker->AddTotalWork ((float) (extrapacketlength + fileRef->Length() -packetInfo.offset+14) );
if (!doSafeUpdate)
{
size_t bufSize=extrapacketlength/(kIOBufferSize) +1*(extrapacketlength!=(kIOBufferSize));
std::vector<IOBuffer> tempfilebuffer1(bufSize);
IOBuffer temp;
XMP_Int64 readpoint=packetInfo.offset+packetInfo.length,writepoint=packetInfo.offset;
fileRef->Seek ( readpoint, kXMP_SeekFromStart );
for(size_t x=0;x<bufSize;x++)
{
tempfilebuffer1[x].len=fileRef->Read(tempfilebuffer1[x].data,kIOBufferSize,false);
readpoint+=tempfilebuffer1[x].len;
}
fileRef->Seek ( writepoint, kXMP_SeekFromStart );
fileRef->Write( (void *)outStr.c_str(), static_cast<XMP_Uns32>(outStr.length()));
writepoint+=static_cast<XMP_Uns32>(outStr.length());
size_t y=0;
bool continueread=(tempfilebuffer1[bufSize-1].len==kIOBufferSize);
size_t loop=bufSize;
while(loop)
{
if(continueread)
{
fileRef->Seek ( readpoint, kXMP_SeekFromStart );
temp.len=fileRef->Read(temp.data,kIOBufferSize,false);
readpoint+=temp.len;
}
fileRef->Seek ( writepoint, kXMP_SeekFromStart );
fileRef->Write(tempfilebuffer1[y].data,tempfilebuffer1[y].len);
writepoint+=tempfilebuffer1[y].len;
if (continueread)
tempfilebuffer1[y]=temp;
else
--loop;
if (temp.len<kIOBufferSize)continueread=false;
y=(y+1)%bufSize;
}
modifyHeader(fileRef,extrapacketlength,packetInfo.offset );
}
else
{
if ( progressTracker != 0 ) progressTracker->AddTotalWork ((float) (packetInfo.offset) );
if ( ! tempRef ) tempRef=fileRef->DeriveTemp();
//copy data till xmp Packet
fileRef->Seek(0,kXMP_SeekFromStart);
XIO::Copy ( fileRef, tempRef, packetInfo.offset, this->parent->abortProc, this->parent->abortArg );
//insert the new XMP packet
fileRef->Seek(packetInfo.offset+packetInfo.length,kXMP_SeekFromStart);
tempRef->Write((void *)outStr.c_str(), static_cast<XMP_Uns32>(outStr.length()));
//copy the rest of data
pos=fileRef->Length();
XIO::Copy ( fileRef, tempRef,pos-packetInfo.offset-packetInfo.length, this->parent->abortProc, this->parent->abortArg );
modifyHeader(tempRef,extrapacketlength,packetInfo.offset );
}
}
// =================================================================================================
// PostScript_MetaHandler::DetermineInsertionOffsets
// =============================================
//
// Method determines the offsets at which the new xpacket and other postscript code be inserted
void PostScript_MetaHandler::DetermineInsertionOffsets(XMP_Int64& ADOhintOffset,XMP_Int64& InjectData1Offset,
XMP_Int64& InjectData3Offset)
{
//find the position to place ADOContainsXMP hint
if(psHint!=kPSHint_MainFirst && (fileformat==kXMP_EPSFile||kXMPFiles_UnknownLength==packetInfo.offset))
{
TokenLocation& tokenLoc= getTokenInfo(kPS_ADOContainsXMP);
if(tokenLoc.offsetStart==-1)
{
TokenLocation& tokenLoc1= getTokenInfo(kPS_EndComments);
if(tokenLoc1.offsetStart==-1)
{
//should never reach here
throw XMP_Error(kXMPErr_BadFileFormat,"%%EndComment Missing");
}
ADOhintOffset=tokenLoc1.offsetStart;
}
else
{
ADOhintOffset= tokenLoc.offsetStart;
}
}
else if (psHint!=kPSHint_MainLast &&fileformat==kXMP_PostScriptFile)
{
TokenLocation& tokenLoc= getTokenInfo(kPS_ADOContainsXMP);
if(tokenLoc.offsetStart==-1)
{
TokenLocation& tokenLoc1= getTokenInfo(kPS_EndComments);
if(tokenLoc1.offsetStart==-1)
{
//should never reach here
throw XMP_Error(kXMPErr_BadFileFormat,"%%EndComment Missing");
}
ADOhintOffset=tokenLoc1.offsetStart;
}
else
{
ADOhintOffset= tokenLoc.offsetStart;
}
}
//Find the location to insert kEPS_Injectdata1
XMP_Uns64 xpacketLoc;
if ( (fileformat == kXMP_PostScriptFile) && (kXMPFiles_UnknownLength != packetInfo.offset) )
{
xpacketLoc = (XMP_Uns64)lastPacketInfo.offset;
TokenLocation& endPagsetuploc = getTokenInfo(kPS_EndPageSetup);
if ( (endPagsetuploc.offsetStart > -1) && (xpacketLoc < (XMP_Uns64)endPagsetuploc.offsetStart) )
{
InjectData1Offset=endPagsetuploc.offsetStart;
}
else
{
TokenLocation& trailerloc= getTokenInfo(kPS_Trailer);
if ( (trailerloc.offsetStart > -1) && (xpacketLoc < (XMP_Uns64)trailerloc.offsetStart) )
{
InjectData1Offset=trailerloc.offsetStart;
}
else
{
TokenLocation& eofloc= getTokenInfo(kPS_EOF);
if ( (eofloc.offsetStart > -1) && (xpacketLoc < (XMP_Uns64)eofloc.offsetStart) )
{
InjectData1Offset=eofloc.offsetStart;
}
else
{
TokenLocation& endPostScriptloc= getTokenInfo(kPS_EndPostScript);
if ( (endPostScriptloc.offsetStart > -1) && (xpacketLoc < (XMP_Uns64)endPostScriptloc.offsetStart) )
{
InjectData1Offset=endPostScriptloc.offsetStart;
}
}
}
}
}
else
{
xpacketLoc = (XMP_Uns64)firstPacketInfo.offset;
TokenLocation& endPagsetuploc = getTokenInfo(kPS_EndPageSetup);
if ( (endPagsetuploc.offsetStart > -1) && (xpacketLoc > (XMP_Uns64)endPagsetuploc.offsetStart) )
{
InjectData1Offset=endPagsetuploc.offsetStart;
}
else
{
TokenLocation& beginPagsetuploc= getTokenInfo(kPS_BeginPageSetup);
if ( (beginPagsetuploc.offsetStart > -1) &&
(xpacketLoc > (XMP_Uns64)(beginPagsetuploc.offsetStart + beginPagsetuploc.tokenlen)) )
{
InjectData1Offset=beginPagsetuploc.offsetStart+beginPagsetuploc.tokenlen;
}
else
{
TokenLocation& endPageCommentsloc= getTokenInfo(kPS_EndPageComments);
if ( (endPageCommentsloc.offsetStart > -1) &&
(xpacketLoc > (XMP_Uns64)(endPageCommentsloc.offsetStart + endPageCommentsloc.tokenlen)) )
{
InjectData1Offset=endPageCommentsloc.offsetStart+endPageCommentsloc.tokenlen;
}
else
{
TokenLocation& pageLoc= getTokenInfo(kPS_Page);
if ( (pageLoc.offsetStart > -1) &&
(xpacketLoc > (XMP_Uns64)(pageLoc.offsetStart + pageLoc.tokenlen)) )
{
InjectData1Offset=pageLoc.offsetStart+pageLoc.tokenlen;
}
else
{
TokenLocation& endSetupLoc= getTokenInfo(kPS_EndSetup);
if ( (endSetupLoc.offsetStart > -1) && (xpacketLoc > (XMP_Uns64)endSetupLoc.offsetStart) )
{
InjectData1Offset=endSetupLoc.offsetStart;
}
else
{
TokenLocation& beginSetupLoc= getTokenInfo(kPS_BeginSetup);
if ( (beginSetupLoc.offsetStart > -1) &&
(xpacketLoc > (XMP_Uns64)(beginSetupLoc.offsetStart + beginSetupLoc.tokenlen)) )
{
InjectData1Offset=beginSetupLoc.offsetStart+beginSetupLoc.tokenlen;
}
else
{
TokenLocation& endPrologLoc= getTokenInfo(kPS_EndProlog);
if ( (endPrologLoc.offsetStart > -1) &&
(xpacketLoc > (XMP_Uns64)(endPrologLoc.offsetStart + endPrologLoc.tokenlen)) )
{
InjectData1Offset=endPrologLoc.offsetStart+endPrologLoc.tokenlen;
}
else
{
TokenLocation& endCommentsLoc= getTokenInfo(kPS_EndComments);
if ( (endCommentsLoc.offsetStart > -1) &&
(xpacketLoc > (XMP_Uns64)(endCommentsLoc.offsetStart + endCommentsLoc.tokenlen)) )
{
InjectData1Offset=endCommentsLoc.offsetStart+endCommentsLoc.tokenlen;
}
else
{
//should never reach here
throw XMP_Error(kXMPErr_BadFileFormat,"%%EndComment Missing");
}
}
}
}
}
}
}
}
}
//Find the location to insert kEPS_Injectdata3
TokenLocation& trailerloc= getTokenInfo(kPS_Trailer);
if(trailerloc.offsetStart>-1 )
{
InjectData3Offset=trailerloc.offsetStart+trailerloc.tokenlen;
}
else
{
TokenLocation& eofloc= getTokenInfo(kPS_EOF);
if(eofloc.offsetStart>-1 )
{
InjectData3Offset=eofloc.offsetStart;
}
else
{
TokenLocation& endPostScriptloc= getTokenInfo(kPS_EndPostScript);
if(endPostScriptloc.offsetStart>-1 )
{
InjectData3Offset=endPostScriptloc.offsetStart;
}
}
}
}
// =================================================================================================
// PostScript_MetaHandler::InsertNewUpdate
// =======================================
//
// Method inserts a new Xpacket in the postscript file.This will be called in two cases
// a) If there is no xpacket in the PS file
// b) If the existing xpacket is embedded using readstring or readline method
void PostScript_MetaHandler::InsertNewUpdate (std::string &outStr,XMP_IO* &tempRef,bool doSafeUpdate )
{
// In this case it is better to have safe update
// as non-safe update implementation is going to be complex
// and more time consuming
// ignoring doSafeUpdate for this update method
//No SubFileDecode Filter
// Need to insert new Metadata before existing metadata
// with SubFileDecode Filter
XMP_IO* fileRef = this->parent->ioRef;
if ( ! tempRef ) tempRef=fileRef->DeriveTemp();
//inject metadata at the right place
XMP_Int64 ADOhintOffset=-1,InjectData1Offset=-1,InjectData3Offset=-1;
DetermineInsertionOffsets(ADOhintOffset,InjectData1Offset,InjectData3Offset);
XMP_Int64 tempInjectData1Offset=InjectData1Offset;
fileRef->Rewind();
XMP_ProgressTracker* progressTracker = this->parent->progressTracker;
if ( progressTracker != 0 )
{
progressTracker->AddTotalWork ((float) ( fileRef->Length() +outStr.length() + 14) );
if (fileformat==kXMP_EPSFile)
{
progressTracker->AddTotalWork ((float) ( kEPS_Injectdata1.length() + kEPS_Injectdata2.length() + kEPS_Injectdata3.length()) );
}
else
{
progressTracker->AddTotalWork ((float) ( kPS_Injectdata1.length() + kPS_Injectdata2.length()) );
}
}
XMP_Int64 totalReadLength=0;
//copy contents from orignal file to Temp File
if(ADOhintOffset!=-1)
{
XIO::Copy(fileRef,tempRef,ADOhintOffset,this->parent->abortProc,this->parent->abortArg);
totalReadLength+=ADOhintOffset;
if (fileformat==kXMP_EPSFile || kXMPFiles_UnknownLength==packetInfo.offset)
{
if ( progressTracker != 0 ) progressTracker->AddTotalWork ((float) ( kPS_XMPHintMainFirst.length()) );
tempRef->Write(kPS_XMPHintMainFirst.c_str(),kPS_XMPHintMainFirst.length());
}
else
{
if ( progressTracker != 0 ) progressTracker->AddTotalWork ((float) ( kPS_XMPHintMainLast.length()) );
tempRef->Write(kPS_XMPHintMainLast.c_str(),kPS_XMPHintMainLast.length());
}
}
InjectData1Offset-=totalReadLength;
XIO::Copy(fileRef,tempRef,InjectData1Offset,this->parent->abortProc,this->parent->abortArg);
totalReadLength+=InjectData1Offset;
if (fileformat==kXMP_EPSFile)
{
tempRef->Write(kEPS_Injectdata1.c_str(),kEPS_Injectdata1.length());
tempRef->Write((void *)outStr.c_str(), static_cast<XMP_Uns32>(outStr.length()));
tempRef->Write(kEPS_Injectdata2.c_str(),kEPS_Injectdata2.length());
}
else
{
tempRef->Write(kPS_Injectdata1.c_str(),kPS_Injectdata1.length());
tempRef->Write((void *)outStr.c_str(), static_cast<XMP_Uns32>(outStr.length()));
tempRef->Write(kPS_Injectdata2.c_str(),kPS_Injectdata2.length());
}
if (InjectData3Offset!=-1)
{
InjectData3Offset-=totalReadLength;
XIO::Copy(fileRef,tempRef,InjectData3Offset,this->parent->abortProc,this->parent->abortArg);
totalReadLength+=InjectData3Offset;
if (fileformat==kXMP_EPSFile)
{
tempRef->Write(kEPS_Injectdata3.c_str(),kEPS_Injectdata3.length());
}
XMP_Int64 remlength=fileRef->Length()-totalReadLength;
XIO::Copy(fileRef,tempRef,remlength,this->parent->abortProc,this->parent->abortArg);
totalReadLength+=remlength;
}
else
{
XMP_Int64 remlength=fileRef->Length()-totalReadLength;
XIO::Copy(fileRef,tempRef,remlength,this->parent->abortProc,this->parent->abortArg);
totalReadLength+=remlength;
if (fileformat==kXMP_EPSFile)
{
tempRef->Write(kEPS_Injectdata3.c_str(),kEPS_Injectdata3.length());
}
}
XMP_Int64 extraBytes;
if (fileformat==kXMP_EPSFile )
{
extraBytes=((ADOhintOffset!=-1)?kPS_XMPHintMainFirst.length():0)+kEPS_Injectdata3.length()+kEPS_Injectdata2.length()+
kEPS_Injectdata1.length()+outStr.length();
}
else
{
extraBytes=((ADOhintOffset!=-1)?(kXMPFiles_UnknownLength!=packetInfo.offset?kPS_XMPHintMainLast.length():kPS_XMPHintMainFirst.length()):0)+kPS_Injectdata2.length()+kPS_Injectdata1.length()+outStr.length();
}
modifyHeader(tempRef,extraBytes,tempInjectData1Offset );
}
// =================================================================================================
// PostScript_MetaHandler::UpdateFile
// ==================================
//
// Virtual Method implementation to update XMP metadata in a PS file
void PostScript_MetaHandler::UpdateFile ( bool doSafeUpdate )
{
IgnoreParam ( doSafeUpdate );
if ( ! this->needsUpdate ) return;
XMP_IO * tempRef = 0;
XMP_IO* fileRef = this->parent->ioRef;
std::string & xmpPacket = this->xmpPacket;
std::string outStr;
if (!fileRef )
{
XMP_Throw ( "Invalid File Refernce Cannot update XMP", kXMPErr_BadOptions );
}
bool localProgressTracking = false;
XMP_ProgressTracker* progressTracker = this->parent->progressTracker;
if ( progressTracker != 0 )
{
if ( ! progressTracker->WorkInProgress() )
{
localProgressTracking = true;
progressTracker->BeginWork ();
}
}
try
{ switch(DetermineUpdateMethod(outStr))
{
case kPS_Inplace:
{
InplaceUpdate ( outStr, tempRef, doSafeUpdate );
break;
}
case kPS_ExpandSFDFilter:
{
ExpandingSFDFilterUpdate ( outStr, tempRef, doSafeUpdate );
break;
}
case kPS_InjectNew:
{
InsertNewUpdate ( outStr, tempRef, doSafeUpdate );
break;
}
case kPS_None:
default:
{
XMP_Throw ( "XMP Write Failed ", kXMPErr_BadOptions );
}
}
}
catch(...)
{
if( tempRef ) fileRef->DeleteTemp();
throw;
}
// rename the modified temp file and then delete the temp file
if ( tempRef ) fileRef->AbsorbTemp();
if ( localProgressTracking ) progressTracker->WorkComplete();
this->needsUpdate = false;
} // PostScript_MetaHandler::UpdateFile
// =================================================================================================
// PostScript_MetaHandler::UpdateFile
// ==================================
//
// Method to write the file with updated XMP metadata to the passed temp file reference
void PostScript_MetaHandler::WriteTempFile ( XMP_IO* tempRef )
{
XMP_IO* origRef = this->parent->ioRef;
XMP_AbortProc abortProc = this->parent->abortProc;
void * abortArg = this->parent->abortArg;
XMP_Int64 fileLen = origRef->Length();
XMP_ProgressTracker* progressTracker = this->parent->progressTracker;
if ( progressTracker != 0 ) progressTracker->BeginWork ((float) fileLen );
origRef->Rewind ( );
tempRef->Truncate ( 0 );
XIO::Copy ( origRef, tempRef, fileLen, abortProc, abortArg );
try
{
this->parent->ioRef = tempRef; // ! Make UpdateFile update the temp.
this->UpdateFile ( false );
this->parent->ioRef = origRef;
}
catch ( ... )
{
this->parent->ioRef = origRef;
throw;
}
if ( progressTracker != 0 ) progressTracker->WorkComplete();
}
// =================================================================================================
| [
"yu@yyx-me.com"
] | yu@yyx-me.com |
86cce92800e45e564b155ee296de26b36542df15 | f68243f40e6dcf4a50954e1fd60627afb6bc6ca4 | /mgfx/app/Asteroids.cpp | 57375a0f6a05878596e880f74aa303801892d35b | [
"MIT"
] | permissive | CitrusForks/mgfx | 2c7fea695dc1ef9a00721f819cacb499eb65237e | e4d146f0e468ed22369a72e3a929ce64b31c818c | refs/heads/master | 2021-06-19T02:10:28.897783 | 2017-06-16T06:49:21 | 2017-06-16T06:49:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,121 | cpp | #include "mgfx_app.h"
#include "graphics2d/ui/window.h"
#include "graphics3d/device/IDevice.h"
#include "file/media_manager.h"
#include "animation/timer.h"
#include "stb/stb_image.h"
#include "json/src/json.hpp"
#include "Asteroids.h"
#include <graphics3d/camera/camera.h>
#include <glm/gtx/vector_angle.hpp>
// This is a simple demo of showing sprites on the screen from a loaded sprite map
// A simple physical simulation manages the velocities of objects and their collisions
// TODO:
// 'Game Levels'
// Oriented rectangle collisions
// Expose more game parameters in the UI
using namespace Mgfx;
using namespace nlohmann;
namespace
{
const float MaxAcceleration = 1000.0f;
const float MaxVelocity = 1000.0f;
struct ShooterWindowData : public BaseWindowData
{
ShooterWindowData(Mgfx::Window* pWindow)
: BaseWindowData(pWindow)
{
}
virtual ~ShooterWindowData()
{
}
// Cleanup window specific stuff
virtual void Free() override
{
m_pWindow->GetDevice()->DestroyTexture(textureQuad);
BaseWindowData::Free();
}
// Sprite texture
uint32_t textureQuad = 0;
glm::uvec2 textureSize;
};
struct Properties
{
float UFOEasySpeed = 120.0f;
float UFOHardSpeed = 200.0f;
float UFOSpawnTime = 10.0f;
float UFOLifeTime = 14.0f;
float UFOFireTime = 1.f;
float UFOLaserSpeed = 200.0f;
float UFOLaserDuration = 2.0f;
float BoulderSpeedRange = 80.0f;
float BoulderMinSpeed = 10.0f;
};
Properties properties;
}
const char* Asteroids::Description() const
{
return R"(A simple asteroids game, built using a sprite map. Oriented rectangles are drawn on the screen using the GPU. They may be blended and sorted in Z.
This is the basics of how you might implement a 2D game on graphics hardware, for example.
This demo shows how to do basic physics, parse a json file for tile coordinates, and handle basic collisions (which could be improved).
Keys: A,D Rotate, W Thrust, SPACE Shoot
)";
}
void Asteroids::CleanUp()
{
m_allEntities.clear();
m_spriteCoords.clear();
m_bigBoulders.clear();
m_mediumBoulders.clear();
m_smallBoulders.clear();
m_stars.clear();
m_numbers.clear();
m_boulders.clear();
m_pShip = nullptr;
m_pFire1 = nullptr;
m_pFire2 = nullptr;
m_pUFO = nullptr;
}
bool Asteroids::Init()
{
m_spCamera = std::make_shared<Camera>(CameraMode::Ortho);
auto spriteData = MediaManager::Instance().LoadAsset("shooter_sprites.json", MediaType::Texture);
json parse = json::parse(spriteData);
m_numbers.resize(10);
for (auto& entry : parse["TextureAtlas"]["SubTexture"])
{
auto x = std::stoi(entry["x"].get<std::string>());
auto y = std::stoi(entry["y"].get<std::string>());
auto width = std::stoi(entry["width"].get<std::string>());
auto height = std::stoi(entry["height"].get<std::string>());
std::string name = entry["name"].get<std::string>();
m_spriteCoords[name] = glm::uvec4(x, y, width, height);
if (name.find("star") == 0)
{
m_stars.push_back(name);
}
else if (name.find("meteor") != std::string::npos)
{
if (name.find("big") != std::string::npos)
{
m_bigBoulders.push_back(name);
}
else if (name.find("small") != std::string::npos)
{
m_mediumBoulders.push_back(name);
}
else if (name.find("tiny") != std::string::npos)
{
m_smallBoulders.push_back(name);
}
}
else if (name.find("playerShip1_blue") != std::string::npos)
{
m_shipName = name;
}
else if (name.find("fire02") != std::string::npos)
{
m_fire1 = name;
}
else if (name.find("fire01") != std::string::npos)
{
m_fire2 = name;
}
else if (name.find("laserBlue03") != std::string::npos)
{
m_laser = name;
}
else if (name.find("powerupRed") != std::string::npos)
{
m_ufoLaser = name;
}
else if (name.find("ufoGreen") != std::string::npos)
{
m_greenUFO = name;
}
else if (name.find("ufoRed") != std::string::npos)
{
m_redUFO = name;
}
else if (name.find("numeral") != std::string::npos)
{
auto prefix = strlen("numeral");
if (name.size() > prefix)
{
auto strNum = name.substr(prefix, 1);
if (strNum[0] >= '0' && strNum[0] <= '9')
{
auto pNum = AddEntity(EntityType::Digit, name);
pNum->sizeScale = 2.0f;
m_numbers[std::stoi(strNum)] = pNum;
}
}
}
}
return true;
}
void Asteroids::RemoveEntity(Entity* spEntity)
{
if (!spEntity)
return;
auto itrFound = m_allEntities.find(spEntity->type);
if (itrFound != m_allEntities.end())
{
// Erase if a boulder
if (spEntity->type == EntityType::BigBoulder ||
spEntity->type == EntityType::MediumBoulder ||
spEntity->type == EntityType::SmallBoulder)
{
m_boulders.erase(spEntity);
}
if (spEntity == m_pUFO)
{
m_pUFO = nullptr;
}
itrFound->second.erase(spEntity);
delete spEntity;
}
}
Entity* Asteroids::AddEntity(EntityType type, HashString spriteName)
{
static uint32_t CurrentID = 0;
auto spEntity = new Entity();
spEntity->id = CurrentID++;
spEntity->type = type;
spEntity->spriteCoords = m_spriteCoords[spriteName];
spEntity->spriteSize = glm::ivec2(m_spriteCoords[spriteName].z, m_spriteCoords[spriteName].w);
spEntity->damage = 0;
spEntity->position = glm::vec3(0.0f);
spEntity->velocity = glm::vec3(0.0f);
spEntity->acceleration = glm::vec3(0.0f);
spEntity->angle = 0.0f;
spEntity->rotationalVelocity = 0.0f;
m_allEntities[type].insert(spEntity);
return spEntity;
}
void Asteroids::SplitBoulder(Entity* boulder)
{
std::vector<Entity*> newBoulders;
switch (boulder->type)
{
case EntityType::BigBoulder:
newBoulders.push_back(AddEntity(EntityType::MediumBoulder, *select_randomly(m_mediumBoulders.begin(), m_mediumBoulders.end())));
newBoulders.push_back(AddEntity(EntityType::MediumBoulder, *select_randomly(m_mediumBoulders.begin(), m_mediumBoulders.end())));
AddExplosion(boulder->position, .65f);
break;
case EntityType::MediumBoulder:
newBoulders.push_back(AddEntity(EntityType::SmallBoulder, *select_randomly(m_smallBoulders.begin(), m_smallBoulders.end())));
newBoulders.push_back(AddEntity(EntityType::SmallBoulder, *select_randomly(m_smallBoulders.begin(), m_smallBoulders.end())));
AddExplosion(boulder->position, .45f);
break;
default:
AddExplosion(boulder->position, .25f);
break;
}
for (auto& child : newBoulders)
{
child->position = boulder->position;
child->velocity = boulder->velocity;
child->rotationalVelocity = boulder->rotationalVelocity * glm::linearRand(2.0f, 3.0f);
child->angle = RandRange(0.0f, 360.0f);
auto currentVelocityLength = length(boulder->velocity);
auto vRand = glm::normalize(glm::linearRand(glm::vec2(-1.0f), glm::vec2(1.0f)));
child->velocity = vRand * currentVelocityLength;
child->sizeScale = 3.0f;
m_boulders.insert(child);
}
RemoveEntity(boulder);
}
Entity* Asteroids::AddUFO(EntityType type)
{
auto pUFO = AddEntity(type, type == EntityType::UFOEasy ? m_greenUFO : m_redUFO);
pUFO->position = GetRandomEntryPoint(pUFO->spriteSize);
if (type == EntityType::UFOEasy)
{
pUFO->velocity = glm::linearRand(glm::vec3(-1.0f) * properties.UFOEasySpeed, glm::vec3(1.0f) * properties.UFOEasySpeed);
}
else
{
pUFO->velocity = glm::linearRand(glm::vec3(-1.0f) * properties.UFOHardSpeed, glm::vec3(1.0f) * properties.UFOHardSpeed);
}
m_ufoTimer.Restart();
m_nextUFOFireTime = properties.UFOFireTime;
return pUFO;
}
void Asteroids::UFOFire()
{
if (!m_pUFO)
{
return;
}
auto pLaser = AddEntity(EntityType::UFOLaser, m_ufoLaser);
pLaser->position = m_pUFO->position;
glm::vec2 laserDir = glm::normalize(m_pShip->position - m_pUFO->position);
float dither = glm::linearRand(-90.0f, 90.0f);
if (fabs(dither) < 10.0f)
{
dither = glm::linearRand(-60.0f, 60.0f);
}
laserDir = glm::rotate(laserDir, glm::radians(dither));
laserDir *= properties.UFOLaserSpeed;
pLaser->velocity = laserDir;
pLaser->angle = glm::linearRand(0.0f, 360.0f);
pLaser->rotationalVelocity = 100.0f;
pLaser->sizeScale = .75f;
pLaser->color = glm::vec4(0.0f, 1.0f, 0.0f, 1.0f);
pLaser->death = properties.UFOLaserDuration;
}
// Find a location around the edge of the world to add an enemy object
glm::vec3 Asteroids::GetRandomEntryPoint(const glm::ivec2& spriteSize) const
{
auto maxSpriteSize = std::max(spriteSize.x, spriteSize.y);
auto maxWorldSize = std::max(m_worldSize.x, m_worldSize.y);
auto location = RandRange(0, int(maxWorldSize));
auto entrySide = RandRange(0, 3);
switch (entrySide)
{
default:
case 0:
return glm::vec3(location, 0.0f, glm::linearRand(.1f, .9f));
case 1:
return glm::vec3(0.0f, location, glm::linearRand(.1f, .9f));
case 2:
return glm::vec3(location, maxSpriteSize + m_worldSize.y, glm::linearRand(.1f, .9f));
case 3:
return glm::vec3(maxSpriteSize + m_worldSize.x, location, glm::linearRand(.1f, .9f));
}
}
Entity* Asteroids::AddBoulder()
{
auto pRock = AddEntity(EntityType::BigBoulder, *select_randomly(m_bigBoulders.begin(), m_bigBoulders.end()));
pRock->position = GetRandomEntryPoint(pRock->spriteSize);
pRock->rotationalVelocity = glm::linearRand(0.0f, 45.0f);
while (fabs(pRock->velocity.x) < properties.BoulderMinSpeed || fabs(pRock->velocity.y) < properties.BoulderMinSpeed)
{
pRock->velocity = glm::linearRand(glm::vec3(-properties.BoulderSpeedRange), glm::vec3(properties.BoulderSpeedRange));
}
pRock->acceleration = glm::vec2(0.0f);
pRock->angle = glm::linearRand(0.0f, 360.0f);
pRock->sizeScale = 1.5f;
m_boulders.insert(pRock);
return pRock;
}
Entity* Asteroids::AddStar()
{
auto pRock = AddEntity(EntityType::Star, *select_randomly(m_stars.begin(), m_stars.end()));
auto maxSpriteSize = std::max(pRock->spriteSize.x, pRock->spriteSize.y);
auto maxWorldSize = std::max(m_worldSize.x, m_worldSize.y);
auto entrySide = RandRange(0, 3);
auto location = RandRange(0, int(maxWorldSize));
// A randomly placed star, with slow rotation, slow velocity and dim color
pRock->rotationalVelocity = glm::linearRand(0.0f, 1.0f);
pRock->position = glm::linearRand(glm::vec3(0.0f), glm::vec3(m_worldSize.x, m_worldSize.y, 0.0f));
pRock->position.z = 0.0f;
pRock->velocity = glm::linearRand(glm::vec3(-3.f), glm::vec3(3.f));
pRock->angle = glm::linearRand(0.0f, 360.0f);
pRock->sizeScale = .25f;
pRock->color = glm::vec4(.75f);
return pRock;
}
void Asteroids::AddExplosion(const glm::vec3& position, float duration)
{
std::vector<Entity*> vecParticles;
vecParticles.push_back(AddStar());
vecParticles.push_back(AddStar());
vecParticles.push_back(AddStar());
vecParticles.push_back(AddStar());
vecParticles.push_back(AddStar());
// particles are fast, bright and don't live long
for (auto& particle : vecParticles)
{
particle->position = position;
particle->death = duration;
particle->color *= 1.5f;
particle->velocity = glm::linearRand(glm::vec3(-500.0f), glm::vec3(500.0f));
}
}
void Asteroids::Restart()
{
// Entity management could be better!
RemoveEntity(m_pShip);
RemoveEntity(m_pUFO);
while (!m_allEntities[EntityType::Star].empty())
{
RemoveEntity(*m_allEntities[EntityType::Star].begin());
}
while (!m_boulders.empty())
{
RemoveEntity(*m_boulders.begin());
}
m_pShip = AddEntity(EntityType::Ship, m_shipName);
m_pShip->position = glm::vec3(m_worldSize.x / 2, m_worldSize.y / 2, 0.0f);
for (int i = 0; i < 5; i++)
{
AddBoulder();
}
for (int i = 0; i < 20; i++)
{
AddStar();
}
m_pFire1 = AddEntity(EntityType::Exhaust, m_fire1);
m_pFire2 = AddEntity(EntityType::Exhaust, m_fire2);
m_gameState = GameState::Spawning;
m_pUFO = nullptr;
m_ufoTimer.Restart();
m_spawnTimer.Restart();
m_score = 0;
m_lives = 3;
}
void Asteroids::ResizeWindow(Mgfx::Window* pWindow)
{
/* Nothing */
}
void Asteroids::AddToWindow(Mgfx::Window* pWindow)
{
auto data = MediaManager::Instance().LoadAsset("shooter_sprites.png", MediaType::Texture);
uint32_t quad = pWindow->GetDevice()->CreateTexture();
int w;
int h;
int comp;
unsigned char* image = stbi_load_from_memory((stbi_uc*)(data.c_str()), int(data.size()), &w, &h, &comp, 4);
if (image)
{
auto textureData = pWindow->GetDevice()->ResizeTexture(quad, glm::uvec2(w, h));
if (textureData.pData)
{
for (auto y = 0; y < h; y++)
{
memcpy(textureData.LinePtr(y, 0), image + y * sizeof(glm::u8vec4) * w, w * sizeof(glm::u8vec4));
}
}
stbi_image_free(image);
}
pWindow->GetDevice()->UpdateTexture(quad);
auto pWindowData = GetWindowData<ShooterWindowData>(pWindow);
pWindowData->AddGeometry(100000 * sizeof(GeometryVertex), 100000 * sizeof(uint32_t));
pWindowData->textureQuad = quad;
pWindowData->textureSize = glm::uvec2(w, h);
m_worldSize = pWindow->GetClientSize();
Restart();
}
void Asteroids::RemoveFromWindow(Mgfx::Window* pWindow)
{
FreeWindowData(pWindow);
}
void Asteroids::DrawGUI(Mgfx::Window* pWindow)
{
if (ImGui::Button("Restart (Some properties required this)"))
{
Restart();
}
ImGui::SliderFloat("UFO Easy Speed", &properties.UFOEasySpeed, 10.0f, 200.0f);
ImGui::SliderFloat("UFO Hard Speed", &properties.UFOHardSpeed, 10.0f, 400.0f);
ImGui::SliderFloat("UFO Spawn Time", &properties.UFOSpawnTime, 1.0f, 60.0f);
ImGui::SliderFloat("UFO Life Time", &properties.UFOLifeTime, 2.0f, 60.0f);
ImGui::SliderFloat("UFO Fire Time", &properties.UFOFireTime, .1f, 5.0f);
ImGui::SliderFloat("UFO Laser Speed", &properties.UFOLaserSpeed, 1.0f, 400.0f);
ImGui::SliderFloat("UFO Laser Duration", &properties.UFOLaserDuration, 1.0f, 10.0f);
ImGui::SliderFloat("Boulder Speed Range", &properties.BoulderSpeedRange, 1.0f, 200.0f);
ImGui::SliderFloat("Boulder Min Speed Range", &properties.BoulderMinSpeed, 1.0f, 100.0f);
if ((properties.BoulderMinSpeed + 1.0f) >= properties.BoulderSpeedRange)
{
properties.BoulderMinSpeed = properties.BoulderSpeedRange - 1.0f;
}
}
void Asteroids::WrapAtBorders()
{
for (auto& entityType : m_allEntities)
{
for (auto& entity : entityType.second)
{
bool wrapped = false;
// Sprite position is origin center, and sprites are double sized !
auto spriteSize = glm::ceil(glm::vec2(entity->spriteSize) / 4.0f);
if (entity->position.x < -spriteSize.x)
{
wrapped = true;
entity->position.x = float(spriteSize.x + m_worldSize.x);
}
if (entity->position.y < -spriteSize.y)
{
wrapped = true;
entity->position.y = float(spriteSize.y + m_worldSize.y);
}
if (entity->position.x > (m_worldSize.x + spriteSize.x))
{
wrapped = true;
entity->position.x = float(-spriteSize.x);
}
if (entity->position.y > (m_worldSize.y + spriteSize.y))
{
wrapped = true;
entity->position.y = float(-spriteSize.y);
}
// Special handling for UFO - kill it inside boundary
if (wrapped && entity == m_pUFO)
{
if (m_ufoTimer.GetDelta(TimerSample::None) > properties.UFOLifeTime)
{
// Force UFO death inside the boundary
m_pUFO->death = .1f;
m_ufoTimer.Restart();
}
}
}
}
}
void Asteroids::HandleInput()
{
auto timeDelta = m_inputTimer.GetDelta();
if (m_gameState != GameState::Playing &&
m_gameState != GameState::Spawning)
{
return;
}
auto shipForward = glm::vec2(cos(glm::radians(m_pShip->angle - 90.0f)), sin(glm::radians(m_pShip->angle - 90.0f)));
if (ImGui::GetIO().KeysDown[SDLK_w])
{
m_pShip->acceleration += shipForward * MaxAcceleration * timeDelta;
m_pShip->acceleration = glm::clamp(m_pShip->acceleration, glm::vec2(-MaxAcceleration), glm::vec2(MaxAcceleration));
}
else
{
m_pShip->acceleration = glm::vec2(0.0f);
}
float angleDelta = std::min(m_keyholdTimer.GetDelta(TimerSample::None) * 2000.0f, 300.0f);
if (ImGui::GetIO().KeysDown[SDLK_a])
{
m_pShip->angle -= angleDelta * timeDelta;
}
else if (ImGui::GetIO().KeysDown[SDLK_d])
{
m_pShip->angle += angleDelta * timeDelta;
}
else
{
m_keyholdTimer.Restart();
}
if (ImGui::GetIO().KeysDown[SDLK_SPACE])
{
if (m_bCanShoot)
{
m_bCanShoot = false;
auto pLaser = AddEntity(EntityType::Laser, m_laser);
pLaser->position = m_pShip->position + glm::vec3(shipForward * float(m_pShip->spriteSize.y *.2f), 0.0);
pLaser->startPosition = pLaser->position;
pLaser->angle = m_pShip->angle;
pLaser->death = .9f;
pLaser->color = glm::vec4(1.0f);
pLaser->velocity = shipForward * 500.0f;
}
}
else
{
m_bCanShoot = true;
}
}
void Asteroids::StepPhysics()
{
const float MaxAcceleration = 1000.0f;
const float MaxVelocity = 1000.0f;
auto timeDelta = m_physicsTimer.GetDelta(TimerSample::None);
// Update physics 50fps
if (timeDelta < 0.02f)
{
return;
}
m_physicsTimer.Restart();
// Slow ship over time
m_pShip->velocity += -m_pShip->velocity * std::min(timeDelta, 1.0f) * .5f;
std::set<Entity*> victims;
for (auto& entityType : m_allEntities)
{
for (auto& entity : entityType.second)
{
entity->age += timeDelta;
entity->velocity += entity->acceleration * timeDelta;
entity->angle += (entity->rotationalVelocity * timeDelta);
entity->position += glm::vec3(entity->velocity, 0.0f) * timeDelta;
if (entity->death != 0.0f && entity->age >= entity->death)
{
victims.insert(entity);
}
}
}
if (m_gameState != GameState::Playing &&
m_gameState != GameState::Spawning)
{
// No colllisions at the end of the game
return;
}
struct Collision
{
Entity* spEntity1;
Entity* spEntity2;
};
std::vector<Collision> collisions;
std::set<Entity*> collidedEntities;
auto HasCollided = [&](Entity* pEntity) { return collidedEntities.find(pEntity) != collidedEntities.end(); };
auto CheckCollision = [&](Entity* spEntity1, Entity* spEntity2)
{
if (HasCollided(spEntity1) || HasCollided(spEntity2))
return false;
auto minSize = std::min(spEntity1->spriteSize.x, spEntity1->spriteSize.y) * .5f;
minSize += std::min(spEntity2->spriteSize.x, spEntity2->spriteSize.y) * .5f;
if (glm::distance(spEntity1->position, spEntity2->position) < minSize)
{
collisions.push_back(Collision{ spEntity1, spEntity2 });
collidedEntities.insert(spEntity1);
collidedEntities.insert(spEntity2);
return true;
}
return false;
};
// Bullet with boulder and UFO
for (auto& bullet : m_allEntities[EntityType::Laser])
{
for (auto& boulder : m_boulders)
{
CheckCollision(bullet, boulder);
}
if (m_pUFO)
{
CheckCollision(bullet, m_pUFO);
}
}
if (m_gameState != GameState::Spawning)
{
// Ship with a boulder
for (auto& boulder : m_boulders)
{
CheckCollision(boulder, m_pShip);
}
for (auto& ufoLaser : m_allEntities[EntityType::UFOLaser])
{
CheckCollision(ufoLaser, m_pShip);
}
}
if (m_pUFO)
{
// Ship with UFO
CheckCollision(m_pUFO, m_pShip);
}
auto HandleCollision = [&](Entity* spEntity)
{
switch (spEntity->type)
{
case EntityType::SmallBoulder:
m_score += 5;
case EntityType::MediumBoulder:
m_score += 5;
case EntityType::BigBoulder:
m_score += 5;
SplitBoulder(spEntity);
break;
case EntityType::UFOHard:
m_score += 20;
case EntityType::UFOEasy:
m_score += 20;
AddExplosion(spEntity->position, .3f);
RemoveEntity(spEntity);
m_ufoTimer.Restart();
break;
case EntityType::Ship:
{
AddExplosion(spEntity->position, 1.0f);
m_gameState = GameState::Spawning;
m_pShip->color.a = 0.0f;
m_pShip->velocity = glm::vec2(0.0f);
m_pShip->position = glm::vec3(m_worldSize.x / 2, m_worldSize.y / 2, 0.0f);
m_spawnTimer.Restart();
m_lives--;
if (m_lives <= 0)
{
m_gameState = GameState::End;
}
}
break;
default:
{
RemoveEntity(spEntity);
}
break;
}
};
for (auto& collision : collisions)
{
HandleCollision(collision.spEntity1);
HandleCollision(collision.spEntity2);
}
for (auto& victim : victims)
{
RemoveEntity(victim);
}
WrapAtBorders();
}
void Asteroids::UpdateGameState()
{
m_pFire1->color = glm::vec4(0.0f);
m_pFire2->color = glm::vec4(0.0f);
// Update visibility of ships thruster
float shipAcceleration = glm::length(m_pShip->acceleration);
if (shipAcceleration != 0.0f)
{
auto shipForward = glm::vec2(cos(glm::radians(m_pShip->angle - 90.0f)), sin(glm::radians(m_pShip->angle - 90.0f)));
// Over a certain speed, change the ship's thruster
if (shipAcceleration > (MaxAcceleration / 5))
{
m_pFire2->position = m_pShip->position - glm::vec3(shipForward * float(m_pShip->spriteSize.y *.4f), 0.0);
m_pFire2->angle = m_pShip->angle;
m_pFire2->color = glm::vec4(1.0f);
}
else
{
m_pFire1->position = m_pShip->position - glm::vec3(shipForward * float(m_pShip->spriteSize.y *.4f), 0.0);
m_pFire1->angle = m_pShip->angle;
m_pFire1->color = glm::vec4(1.0f);
}
}
switch (m_gameState)
{
case GameState::End:
m_pShip->color.a = 0.0f;
m_pFire1->color.a = 0.0f;
m_pFire2->color.a = 0.0f;
return;
break;
case GameState::Spawning:
{
auto delta = m_spawnTimer.GetDelta(TimerSample::None);
if (delta > 3.0f)
{
m_gameState = GameState::Playing;
m_pShip->color.a = 1.0f;
}
else
{
if (delta < .75f)
{
m_pShip->color.a = 0.0f;
}
else
{
m_pShip->color.a = std::cos(glm::radians(delta * 500.0f)) * .5f + .5f;
}
}
}
break;
default:
m_pShip->color.a = 1.0f;
break;
}
// Spawn the UFO if appropriate
auto ufoTime = m_ufoTimer.GetDelta(TimerSample::None);
if (m_pUFO == nullptr)
{
if (ufoTime > properties.UFOSpawnTime)
{
m_pUFO = AddUFO(EntityType::UFOEasy);
}
}
else
{
if (ufoTime >= m_nextUFOFireTime)
{
m_nextUFOFireTime = ufoTime + properties.UFOFireTime;
UFOFire();
}
}
}
void Asteroids::Render(Mgfx::Window* pWindow)
{
m_worldSize = pWindow->GetClientSize();
HandleInput();
StepPhysics();
UpdateGameState();
auto size = pWindow->GetClientSize();
auto pWindowData = GetWindowData<ShooterWindowData>(pWindow);
m_spCamera->SetFilmSize(size);
m_spCamera->SetPositionAndFocalPoint(glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0.0f, 0.0f, 0.0f));
pWindow->GetDevice()->SetCamera(m_spCamera.get());
uint32_t numTextures = RandRange(100, 500);
uint32_t vertexOffset = 0;
uint32_t indexOffset = 0;
auto pVertices = (GeometryVertex*)pWindowData->GetVB()->Map(10000, sizeof(GeometryVertex), vertexOffset);
auto pIndices = (uint32_t*)pWindowData->GetIB()->Map(10000, sizeof(uint32_t), indexOffset);
auto pStartIndices = pIndices;
auto pStartVertices = pVertices;
uint32_t currentVertex = 0;
auto drawSprite = [&](const Entity& entity)
{
if (!pVertices || !pIndices)
{
return;
}
glm::vec3 right = glm::vec3(cos(glm::radians(entity.angle)), sin(glm::radians(entity.angle)), 0.0f);
glm::vec3 down = glm::vec3(cos(glm::radians(entity.angle + 90.0f)), sin(glm::radians(entity.angle + 90.0f)), 0.0f);
glm::vec3 entitySize = glm::vec3(entity.spriteSize.x, entity.spriteSize.y, 0.0f) * .25f * entity.sizeScale;
glm::vec3 quadTopLeft = entity.position - (right * entitySize.x) - (down * entitySize.y);
glm::vec3 quadTopRight = entity.position + (right * entitySize.x) - (down * entitySize.y);
glm::vec3 quadBottomLeft = entity.position - (right * entitySize.x) + (down * entitySize.y);
glm::vec3 quadBottomRight = entity.position + (right * entitySize.x) + (down * entitySize.y);
glm::vec4 spriteTexCoords(entity.spriteCoords.x, entity.spriteCoords.y, (entity.spriteCoords.x + entity.spriteSize.x), (entity.spriteCoords.y + entity.spriteSize.y));
spriteTexCoords += glm::vec4(.5f, .5f, -.5f, -.5f);
spriteTexCoords.x /= pWindowData->textureSize.x;
spriteTexCoords.z /= pWindowData->textureSize.x;
spriteTexCoords.y /= pWindowData->textureSize.y;
spriteTexCoords.w /= pWindowData->textureSize.y;
*pVertices++ = GeometryVertex(quadTopLeft, glm::vec2(spriteTexCoords.x, spriteTexCoords.y), entity.color);
*pVertices++ = GeometryVertex(quadTopRight, glm::vec2(spriteTexCoords.z, spriteTexCoords.y), entity.color);
*pVertices++ = GeometryVertex(quadBottomLeft, glm::vec2(spriteTexCoords.x, spriteTexCoords.w), entity.color);
*pVertices++ = GeometryVertex(quadBottomRight, glm::vec2(spriteTexCoords.z, spriteTexCoords.w), entity.color);
// Quad
*pIndices++ = 0 + currentVertex;
*pIndices++ = 1 + currentVertex;
*pIndices++ = 2 + currentVertex;
*pIndices++ = 2 + currentVertex;
*pIndices++ = 1 + currentVertex;
*pIndices++ = 3 + currentVertex;
currentVertex += 4;
};
// Draw the world
for (auto& entityType : m_allEntities)
{
if (entityType.first == EntityType::Digit)
{
continue;
}
for (auto& entity : entityType.second)
{
drawSprite(*entity);
}
}
auto drawNumber = [&](int number, glm::vec2& pos)
{
std::string text = std::to_string(number);
for (int digit = 0; digit < text.length(); digit++)
{
int index = text[digit] - '0';
// sanity
if (index < 0 || index > 9)
continue;
auto pEntity = m_numbers[index];
pEntity->position = glm::vec3(pos, 0.0f);
pos.x += pEntity->spriteSize.x + 5;
drawSprite(*pEntity);
}
};
glm::vec2 scorePos(15, 15);
drawNumber(m_score, scorePos);
scorePos.x += 80;
drawNumber(m_lives, scorePos);
pWindowData->GetIB()->UnMap();
pWindowData->GetVB()->UnMap();
uint32_t numVertices = uint32_t(pVertices - pStartVertices);
uint32_t numIndices = uint32_t(pIndices - pStartIndices);
pWindow->GetDevice()->BeginGeometry(pWindowData->textureQuad, pWindowData->GetVB(), pWindowData->GetIB());
pWindow->GetDevice()->DrawTriangles(vertexOffset, indexOffset, numVertices, numIndices);
pWindow->GetDevice()->EndGeometry();
}
| [
"cmaughan@snarlsoftware.com"
] | cmaughan@snarlsoftware.com |
a71cb54c237f8d817a337e3c013d2b504b7885a6 | ae8c468438be6c03785dfdd362f7cba23fac4cc5 | /examples_glfwold/117_QuadSubdivOnMesh/main.cpp | 28f6c109625a2498c9a12833927a000107869703 | [
"MIT"
] | permissive | fixedchaos/delfem2 | 75e2ec9b08ced56aae3c027a42aa35361cee9451 | c8a7a000ec6a51c44bc45bc6ad0d0106d9315ade | refs/heads/master | 2022-11-02T11:03:11.851128 | 2020-06-14T07:25:28 | 2020-06-14T07:25:28 | 263,203,162 | 0 | 0 | MIT | 2020-05-12T01:42:10 | 2020-05-12T01:42:09 | null | UTF-8 | C++ | false | false | 6,613 | cpp | /*
* Copyright (c) 2019 Nobuyuki Umetani
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <vector>
#include <string>
#include <cstdlib>
#include "delfem2/mshmisc.h"
#include "delfem2/mshtopo.h"
#include "delfem2/vec3.h"
#include "delfem2/primitive.h"
#include "delfem2/srchuni_v3.h"
// --------------------
// gl related includes
#include <GLFW/glfw3.h>
#include "delfem2/opengl/funcs_glold.h"
#include "delfem2/opengl/glfw/viewer_glfw.h"
namespace dfm2 = delfem2;
// ---------------------------------------------------
std::vector<double> aXYZ;
std::vector<unsigned int> aTri;
const unsigned int nsubdiv = 3;
std::vector<double> aXYZ_Quad;
std::vector<double> aNorm_Quad;
std::vector< std::vector<unsigned int>> aaQuad;
// ---------------------------------------------------
void InitializeProblem() {
dfm2::MeshTri3D_Sphere(aXYZ, aTri,
1.0, 12, 34);
{
const double bbmin[3] = {-1,-1,-1};
const double bbmax[3] = {+1,+1,+1};
aaQuad.resize(1);
dfm2::MeshQuad3_CubeVox(aXYZ_Quad, aaQuad[0],
bbmin, bbmax);
}
for(unsigned int ip=0;ip<aXYZ_Quad.size()/3;++ip){
dfm2::CVec3d p0(aXYZ_Quad[ip*3+0], aXYZ_Quad[ip*3+1], aXYZ_Quad[ip*3+2]);
dfm2::CPointElemSurf<double> pes0 = Nearest_Point_MeshTri3D(p0,
aXYZ, aTri);
dfm2::CVec3d q0 = pes0.Pos_Tri(aXYZ, aTri);
aXYZ_Quad[ip*3+0] = q0.x();
aXYZ_Quad[ip*3+1] = q0.y();
aXYZ_Quad[ip*3+2] = q0.z();
}
dfm2::Normal_MeshQuad3(aNorm_Quad,
aXYZ_Quad, aaQuad[0]);
aaQuad.resize(nsubdiv+1);
for(unsigned int isubdiv=0;isubdiv<nsubdiv;++isubdiv){
std::vector<unsigned int> psup_ind, psup;
std::vector<int> aEdgeFace0;
dfm2::SubdivTopo_MeshQuad(aaQuad[isubdiv+1], psup_ind, psup, aEdgeFace0,
aaQuad[isubdiv].data(), aaQuad[isubdiv].size()/4,
aXYZ_Quad.size()/3);
const unsigned int nv0 = aXYZ_Quad.size()/3;
const unsigned int ne0 = aEdgeFace0.size()/4;
const unsigned int nq0 = aaQuad[isubdiv].size()/4;
aXYZ_Quad.resize((nv0+ne0+nq0)*3);
aNorm_Quad.resize((nv0+ne0+nq0)*3);
{ // enter dangerous zone
const std::vector<unsigned int>& aQuad0 = aaQuad[isubdiv];
const std::vector<double>& aXYZ0 = aXYZ_Quad;
std::vector<double>& aXYZ1 = aXYZ_Quad;
for(unsigned int ie=0;ie<ne0;++ie){
const int iv0 = aEdgeFace0[ie*4+0];
const int iv1 = aEdgeFace0[ie*4+1];
dfm2::AverageTwo3(aXYZ1.data()+(nv0+ie)*3,
aXYZ0.data()+iv0*3, aXYZ0.data()+iv1*3);
dfm2::AverageTwo3(aNorm_Quad.data()+(nv0+ie)*3,
aNorm_Quad.data()+iv0*3, aNorm_Quad.data()+iv1*3);
dfm2::Normalize3(aNorm_Quad.data()+(nv0+ie)*3);
}
for(unsigned int iq=0;iq<nq0;++iq){
const unsigned int iv0 = aQuad0[iq*4+0];
const unsigned int iv1 = aQuad0[iq*4+1];
const unsigned int iv2 = aQuad0[iq*4+2];
const unsigned int iv3 = aQuad0[iq*4+3];
dfm2::AverageFour3(aXYZ1.data()+(nv0+ne0+iq)*3,
aXYZ0.data()+iv0*3, aXYZ0.data()+iv1*3, aXYZ0.data()+iv2*3, aXYZ0.data()+iv3*3);
dfm2::AverageFour3(aNorm_Quad.data()+(nv0+ne0+iq)*3,
aNorm_Quad.data()+iv0*3, aNorm_Quad.data()+iv1*3, aNorm_Quad.data()+iv2*3, aNorm_Quad.data()+iv3*3);
dfm2::Normalize3(aNorm_Quad.data()+(nv0+ne0+iq)*3);
}
}
for(unsigned int ip=nv0;ip<nv0+ne0+nq0;++ip){
const dfm2::CVec3d p0( aXYZ_Quad[ip*3+0], aXYZ_Quad[ip*3+1], aXYZ_Quad[ip*3+2] );
const dfm2::CVec3d n0( aNorm_Quad[ip*3+0], aNorm_Quad[ip*3+1], aNorm_Quad[ip*3+2] );
std::vector<dfm2::CPointElemSurf<double>> aPES = IntersectionLine_MeshTri3(p0, n0,
aTri, aXYZ,
1.0e-3);
std::map<double, dfm2::CPointElemSurf<double>> mapPES;
for(unsigned int ipes=0;ipes<aPES.size();++ipes){
dfm2::CVec3d q0 = aPES[ipes].Pos_Tri(aXYZ, aTri);
double h = (q0-p0)*n0;
mapPES.insert( std::make_pair(-h,aPES[ipes]) );
}
if( !aPES.empty() ){
dfm2::CPointElemSurf<double>& pes0 = mapPES.begin()->second;
dfm2::CVec3d q0 = pes0.Pos_Tri(aXYZ, aTri);
aXYZ_Quad[ip*3+0] = q0.x();
aXYZ_Quad[ip*3+1] = q0.y();
aXYZ_Quad[ip*3+2] = q0.z();
}
}
{ // make normal for new vertices
aNorm_Quad.resize((nv0+ne0+nq0)*3);
std::vector<double> aNorm1;
dfm2::Normal_MeshQuad3(aNorm1,
aXYZ_Quad, aaQuad[isubdiv+1]);
for(unsigned int ip=nv0;ip<nv0+ne0+nq0;++ip){
aNorm_Quad[ip*3+0] = aNorm1[ip*3+0];
aNorm_Quad[ip*3+1] = aNorm1[ip*3+1];
aNorm_Quad[ip*3+2] = aNorm1[ip*3+2];
}
}
}
}
void UpdateProblem() {
}
// -----------------------------------------------------
void myGlutDisplay()
{
::glEnable(GL_LIGHTING);
{ //
::glDisable(GL_TEXTURE_2D);
float gray[4] = {1.0f,0.0f,0.0f,1.f};
::glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, gray);
float shine[4] = {0,0,0,0};
::glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, shine);
::glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 127.0);
dfm2::opengl::DrawMeshQuad3D_FaceNorm(aXYZ_Quad,aaQuad[nsubdiv]);
::glDisable(GL_LIGHTING);
::glColor3d(0.0, 0.0, 0.0);
dfm2::opengl::DrawMeshQuad3D_Edge(aXYZ_Quad,aaQuad[nsubdiv]);
/*
::glDisable(GL_LIGHTING);
::glColor3d(1.0, 1.0, 1.0);
dfm2::opengl::DrawPoints3d_NormVtx(aXYZ_Quad, aNorm_Quad, 0.1);
*/
}
::glDisable(GL_LIGHTING);
::glColor3d(1.0, 1.0, 1.0);
dfm2::opengl::DrawMeshTri3D_Edge(aXYZ, aTri);
::glEnd();
::glEnable(GL_DEPTH_TEST);
}
int main(int argc,char* argv[])
{
// ----------------
dfm2::opengl::CViewer_GLFW viewer;
viewer.Init_oldGL();
viewer.nav.camera.view_height = 1.0;
viewer.nav.camera.camera_rot_mode = delfem2::CCamera<double>::CAMERA_ROT_MODE::TBALL;
dfm2::opengl::setSomeLighting();
InitializeProblem();
UpdateProblem();
int iframe = 0;
while (!glfwWindowShouldClose(viewer.window))
{
iframe += 1;
UpdateProblem();
// -------
viewer.DrawBegin_oldGL();
myGlutDisplay();
viewer.DrawEnd_oldGL();
}
glfwDestroyWindow(viewer.window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| [
"n.umetani@gmail.com"
] | n.umetani@gmail.com |
89c0eb304bb81ef497ac3adb0cfff5047d6ae30f | 168b2238a156a142e5e7f288326c4f08a291e857 | /reactor/s13/EPoller.cc | 1b4de3f03ecf34436f9cf78952c46b0f916e7259 | [
"BSD-3-Clause"
] | permissive | haocoder/recipes | 51acdfffa3e3cae272f965808208fc105f9a1a88 | 8caa231eba9b5006d56801a1cc29e06f2a82e9e7 | refs/heads/master | 2023-03-08T06:15:41.145616 | 2023-02-26T05:31:17 | 2023-02-26T05:31:17 | 231,206,675 | 0 | 0 | BSD-3-Clause | 2020-01-01T11:18:15 | 2020-01-01T11:18:14 | null | UTF-8 | C++ | false | false | 4,345 | cc | // excerpts from http://code.google.com/p/muduo/
//
// 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 "EPoller.h"
#include "Channel.h"
#include "logging/Logging.h"
#include <boost/static_assert.hpp>
#include <assert.h>
#include <errno.h>
#include <poll.h>
#include <sys/epoll.h>
using namespace muduo;
// On Linux, the constants of poll(2) and epoll(4)
// are expected to be the same.
BOOST_STATIC_ASSERT(EPOLLIN == POLLIN);
BOOST_STATIC_ASSERT(EPOLLPRI == POLLPRI);
BOOST_STATIC_ASSERT(EPOLLOUT == POLLOUT);
BOOST_STATIC_ASSERT(EPOLLRDHUP == POLLRDHUP);
BOOST_STATIC_ASSERT(EPOLLERR == POLLERR);
BOOST_STATIC_ASSERT(EPOLLHUP == POLLHUP);
namespace
{
const int kNew = -1;
const int kAdded = 1;
const int kDeleted = 2;
}
EPoller::EPoller(EventLoop* loop)
: ownerLoop_(loop),
epollfd_(::epoll_create1(EPOLL_CLOEXEC)),
events_(kInitEventListSize)
{
if (epollfd_ < 0)
{
LOG_SYSFATAL << "EPoller::EPoller";
}
}
EPoller::~EPoller()
{
::close(epollfd_);
}
Timestamp EPoller::poll(int timeoutMs, ChannelList* activeChannels)
{
int numEvents = ::epoll_wait(epollfd_,
&*events_.begin(),
static_cast<int>(events_.size()),
timeoutMs);
Timestamp now(Timestamp::now());
if (numEvents > 0)
{
LOG_TRACE << numEvents << " events happended";
fillActiveChannels(numEvents, activeChannels);
if (implicit_cast<size_t>(numEvents) == events_.size())
{
events_.resize(events_.size()*2);
}
}
else if (numEvents == 0)
{
LOG_TRACE << " nothing happended";
}
else
{
LOG_SYSERR << "EPoller::poll()";
}
return now;
}
void EPoller::fillActiveChannels(int numEvents,
ChannelList* activeChannels) const
{
assert(implicit_cast<size_t>(numEvents) <= events_.size());
for (int i = 0; i < numEvents; ++i)
{
Channel* channel = static_cast<Channel*>(events_[i].data.ptr);
#ifndef NDEBUG
int fd = channel->fd();
ChannelMap::const_iterator it = channels_.find(fd);
assert(it != channels_.end());
assert(it->second == channel);
#endif
channel->set_revents(events_[i].events);
activeChannels->push_back(channel);
}
}
void EPoller::updateChannel(Channel* channel)
{
assertInLoopThread();
LOG_TRACE << "fd = " << channel->fd() << " events = " << channel->events();
const int index = channel->index();
if (index == kNew || index == kDeleted)
{
// a new one, add with EPOLL_CTL_ADD
int fd = channel->fd();
if (index == kNew)
{
assert(channels_.find(fd) == channels_.end());
channels_[fd] = channel;
}
else // index == kDeleted
{
assert(channels_.find(fd) != channels_.end());
assert(channels_[fd] == channel);
}
channel->set_index(kAdded);
update(EPOLL_CTL_ADD, channel);
}
else
{
// update existing one with EPOLL_CTL_MOD/DEL
int fd = channel->fd();
(void)fd;
assert(channels_.find(fd) != channels_.end());
assert(channels_[fd] == channel);
assert(index == kAdded);
if (channel->isNoneEvent())
{
update(EPOLL_CTL_DEL, channel);
channel->set_index(kDeleted);
}
else
{
update(EPOLL_CTL_MOD, channel);
}
}
}
void EPoller::removeChannel(Channel* channel)
{
assertInLoopThread();
int fd = channel->fd();
LOG_TRACE << "fd = " << fd;
assert(channels_.find(fd) != channels_.end());
assert(channels_[fd] == channel);
assert(channel->isNoneEvent());
int index = channel->index();
assert(index == kAdded || index == kDeleted);
size_t n = channels_.erase(fd);
(void)n;
assert(n == 1);
if (index == kAdded)
{
update(EPOLL_CTL_DEL, channel);
}
channel->set_index(kNew);
}
void EPoller::update(int operation, Channel* channel)
{
struct epoll_event event;
bzero(&event, sizeof event);
event.events = channel->events();
event.data.ptr = channel;
int fd = channel->fd();
if (::epoll_ctl(epollfd_, operation, fd, &event) < 0)
{
if (operation == EPOLL_CTL_DEL)
{
LOG_SYSERR << "epoll_ctl op=" << operation << " fd=" << fd;
}
else
{
LOG_SYSFATAL << "epoll_ctl op=" << operation << " fd=" << fd;
}
}
}
| [
"chenshuo@chenshuo.com"
] | chenshuo@chenshuo.com |
f5f7acd839527b96b0690da2536e304d2ab0d1c7 | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/chromium_org/chrome/browser/ui/search_engines/keyword_editor_controller.cc | a5cfdf419357cb18dcdbf7bb71d3e9bc732bda00 | [
"BSD-3-Clause",
"MIT"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 3,731 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/search_engines/keyword_editor_controller.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/ui/search_engines/template_url_table_model.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/user_metrics.h"
using content::UserMetricsAction;
KeywordEditorController::KeywordEditorController(Profile* profile)
: profile_(profile) {
table_model_.reset(new TemplateURLTableModel(
TemplateURLServiceFactory::GetForProfile(profile)));
}
KeywordEditorController::~KeywordEditorController() {
}
// static
// TODO(rsesek): Other platforms besides Mac should remember window
// placement. http://crbug.com/22269
void KeywordEditorController::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterDictionaryPref(prefs::kKeywordEditorWindowPlacement);
}
int KeywordEditorController::AddTemplateURL(const base::string16& title,
const base::string16& keyword,
const std::string& url) {
DCHECK(!url.empty());
content::RecordAction(UserMetricsAction("KeywordEditor_AddKeyword"));
const int new_index = table_model_->last_other_engine_index();
table_model_->Add(new_index, title, keyword, url);
return new_index;
}
void KeywordEditorController::ModifyTemplateURL(TemplateURL* template_url,
const base::string16& title,
const base::string16& keyword,
const std::string& url) {
DCHECK(!url.empty());
const int index = table_model_->IndexOfTemplateURL(template_url);
if (index == -1) {
// Will happen if url was deleted out from under us while the user was
// editing it.
return;
}
// Don't do anything if the entry didn't change.
if ((template_url->short_name() == title) &&
(template_url->keyword() == keyword) && (template_url->url() == url))
return;
table_model_->ModifyTemplateURL(index, title, keyword, url);
content::RecordAction(UserMetricsAction("KeywordEditor_ModifiedKeyword"));
}
bool KeywordEditorController::CanEdit(const TemplateURL* url) const {
return (url->GetType() != TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION) &&
(!url_model()->is_default_search_managed() ||
(url != url_model()->GetDefaultSearchProvider()));
}
bool KeywordEditorController::CanMakeDefault(const TemplateURL* url) const {
return url_model()->CanMakeDefault(url);
}
bool KeywordEditorController::CanRemove(const TemplateURL* url) const {
return url != url_model()->GetDefaultSearchProvider();
}
void KeywordEditorController::RemoveTemplateURL(int index) {
table_model_->Remove(index);
content::RecordAction(UserMetricsAction("KeywordEditor_RemoveKeyword"));
}
int KeywordEditorController::MakeDefaultTemplateURL(int index) {
return table_model_->MakeDefaultTemplateURL(index);
}
bool KeywordEditorController::loaded() const {
return url_model()->loaded();
}
TemplateURL* KeywordEditorController::GetTemplateURL(int index) {
return table_model_->GetTemplateURL(index);
}
TemplateURLService* KeywordEditorController::url_model() const {
return table_model_->template_url_service();
}
| [
"karun.matharu@gmail.com"
] | karun.matharu@gmail.com |
d2234a4b720d7aff2e262598f5f1636c82ec0761 | 4a399d20f9934c4984bab229a015be69e9189067 | /devel/include/roboy_communication_middleware/RoboyState.h | a16f2727eb1937fc0d8c5e4bbdbc18a71deedc1d | [
"BSD-3-Clause"
] | permissive | Roboy/myoarm_small_FPGA | 09af14c7d82c9e8fc923842ae5aad1be6344bf27 | f2f11bee50078d8a03f352e3b3ef9f3d9244d87a | refs/heads/master | 2021-01-21T03:21:49.777564 | 2017-08-30T22:11:44 | 2017-08-30T22:11:44 | 101,892,113 | 0 | 0 | null | 2017-08-30T14:49:18 | 2017-08-30T14:33:46 | null | UTF-8 | C++ | false | false | 7,775 | h | // Generated by gencpp from file roboy_communication_middleware/RoboyState.msg
// DO NOT EDIT!
#ifndef ROBOY_COMMUNICATION_MIDDLEWARE_MESSAGE_ROBOYSTATE_H
#define ROBOY_COMMUNICATION_MIDDLEWARE_MESSAGE_ROBOYSTATE_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace roboy_communication_middleware
{
template <class ContainerAllocator>
struct RoboyState_
{
typedef RoboyState_<ContainerAllocator> Type;
RoboyState_()
: setPoint()
, actuatorPos()
, actuatorVel()
, tendonDisplacement()
, actuatorCurrent() {
}
RoboyState_(const ContainerAllocator& _alloc)
: setPoint(_alloc)
, actuatorPos(_alloc)
, actuatorVel(_alloc)
, tendonDisplacement(_alloc)
, actuatorCurrent(_alloc) {
(void)_alloc;
}
typedef std::vector<float, typename ContainerAllocator::template rebind<float>::other > _setPoint_type;
_setPoint_type setPoint;
typedef std::vector<float, typename ContainerAllocator::template rebind<float>::other > _actuatorPos_type;
_actuatorPos_type actuatorPos;
typedef std::vector<float, typename ContainerAllocator::template rebind<float>::other > _actuatorVel_type;
_actuatorVel_type actuatorVel;
typedef std::vector<float, typename ContainerAllocator::template rebind<float>::other > _tendonDisplacement_type;
_tendonDisplacement_type tendonDisplacement;
typedef std::vector<float, typename ContainerAllocator::template rebind<float>::other > _actuatorCurrent_type;
_actuatorCurrent_type actuatorCurrent;
typedef boost::shared_ptr< ::roboy_communication_middleware::RoboyState_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::roboy_communication_middleware::RoboyState_<ContainerAllocator> const> ConstPtr;
}; // struct RoboyState_
typedef ::roboy_communication_middleware::RoboyState_<std::allocator<void> > RoboyState;
typedef boost::shared_ptr< ::roboy_communication_middleware::RoboyState > RoboyStatePtr;
typedef boost::shared_ptr< ::roboy_communication_middleware::RoboyState const> RoboyStateConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::roboy_communication_middleware::RoboyState_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::roboy_communication_middleware::RoboyState_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace roboy_communication_middleware
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'roboy_communication_middleware': ['/home/roboy/workspace/myoarm_small_FPGA/src/roboy_communication/middleware/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::roboy_communication_middleware::RoboyState_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::roboy_communication_middleware::RoboyState_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::roboy_communication_middleware::RoboyState_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::roboy_communication_middleware::RoboyState_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::roboy_communication_middleware::RoboyState_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::roboy_communication_middleware::RoboyState_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::roboy_communication_middleware::RoboyState_<ContainerAllocator> >
{
static const char* value()
{
return "a564b9aee3211a3963e685c6ed14e5e1";
}
static const char* value(const ::roboy_communication_middleware::RoboyState_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xa564b9aee3211a39ULL;
static const uint64_t static_value2 = 0x63e685c6ed14e5e1ULL;
};
template<class ContainerAllocator>
struct DataType< ::roboy_communication_middleware::RoboyState_<ContainerAllocator> >
{
static const char* value()
{
return "roboy_communication_middleware/RoboyState";
}
static const char* value(const ::roboy_communication_middleware::RoboyState_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::roboy_communication_middleware::RoboyState_<ContainerAllocator> >
{
static const char* value()
{
return "float32[] setPoint\n\
float32[] actuatorPos\n\
float32[] actuatorVel\n\
float32[] tendonDisplacement\n\
float32[] actuatorCurrent\n\
";
}
static const char* value(const ::roboy_communication_middleware::RoboyState_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::roboy_communication_middleware::RoboyState_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.setPoint);
stream.next(m.actuatorPos);
stream.next(m.actuatorVel);
stream.next(m.tendonDisplacement);
stream.next(m.actuatorCurrent);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct RoboyState_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::roboy_communication_middleware::RoboyState_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::roboy_communication_middleware::RoboyState_<ContainerAllocator>& v)
{
s << indent << "setPoint[]" << std::endl;
for (size_t i = 0; i < v.setPoint.size(); ++i)
{
s << indent << " setPoint[" << i << "]: ";
Printer<float>::stream(s, indent + " ", v.setPoint[i]);
}
s << indent << "actuatorPos[]" << std::endl;
for (size_t i = 0; i < v.actuatorPos.size(); ++i)
{
s << indent << " actuatorPos[" << i << "]: ";
Printer<float>::stream(s, indent + " ", v.actuatorPos[i]);
}
s << indent << "actuatorVel[]" << std::endl;
for (size_t i = 0; i < v.actuatorVel.size(); ++i)
{
s << indent << " actuatorVel[" << i << "]: ";
Printer<float>::stream(s, indent + " ", v.actuatorVel[i]);
}
s << indent << "tendonDisplacement[]" << std::endl;
for (size_t i = 0; i < v.tendonDisplacement.size(); ++i)
{
s << indent << " tendonDisplacement[" << i << "]: ";
Printer<float>::stream(s, indent + " ", v.tendonDisplacement[i]);
}
s << indent << "actuatorCurrent[]" << std::endl;
for (size_t i = 0; i < v.actuatorCurrent.size(); ++i)
{
s << indent << " actuatorCurrent[" << i << "]: ";
Printer<float>::stream(s, indent + " ", v.actuatorCurrent[i]);
}
}
};
} // namespace message_operations
} // namespace ros
#endif // ROBOY_COMMUNICATION_MIDDLEWARE_MESSAGE_ROBOYSTATE_H
| [
"simon.trendel@tum.de"
] | simon.trendel@tum.de |
07b46625bb9c21e0778a42fbdd116eddb58e0594 | 4e0fad4fb8098de7693657f9c276f225f7e2bb68 | /stira/imageanalysis/imageanalysis/HOG.cpp | e2888133151a7b40a6e6582c9a687d3fd2fe21ea | [
"MIT"
] | permissive | JackZhouSz/stira | 6a9b3a0b393c5c10e67fb83719e59d9c8ee891f0 | 60b419f3e478397a8ab43ce9315a259567d94a26 | refs/heads/master | 2023-03-20T12:24:32.860327 | 2017-01-12T16:21:55 | 2017-01-12T16:21:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,565 | cpp | #include "HOG.h"
#include <iostream>
#include "../../imagetools/tools/DrawImageTools.h"
#include "../../imagetools/tools/ImageIO.h"
#include "../../filter/filter/SeparableFilter.h"
namespace stira {
namespace imageanalysis {
using namespace imagedata;
using namespace imagetools;
HOG::HOG( Image* pImage, common::RectangularROI<int> myRoi, int cellWidth, int cellHeight, int nrBins )
{
mpImage = pImage;
mRoi = myRoi;
mCellWidth = cellWidth;
mCellHeight = cellHeight;
mNrBins = nrBins;
}
//--------------------------------------------------------------------------------------------------------------------------
OrientationGrid* HOG::ComputeOrientations( )
{
stira::filter::SeparableFilter sf;
int width = mpImage->GetWidth();
int height = mpImage->GetHeight();
ArrayGrid<double>* pGradientX = new ArrayGrid<double>( width, height );
ArrayGrid<double>* pGradientY = new ArrayGrid<double>( width, height );
double pHX[ 3 ] = { -1.0, 0.0, 1.0 };
sf.SeparableFilter::RunRow( mpImage->GetBands()[0], pGradientX, pHX, 3 );
sf.SeparableFilter::RunColumn( mpImage->GetBands()[0], pGradientY, pHX, 3 );
OrientationGrid* pOrientationGrid = new OrientationGrid(width, height);
for ( int y = 0; y < height; y++ )
{
for (int x = 0; x < width; x++)
{
// result between -180 and 180
double localAngle = atan2( -pGradientY->GetValue(x, y), pGradientX->GetValue(x, y) );
//unsigned gradients: project between 0 and 180 degrees!!
if (localAngle < 0.0) { localAngle += M_PI; }
if (localAngle < 0.0) { localAngle += M_PI; }
if (localAngle > M_PI) { localAngle -= M_PI; }
if (localAngle > M_PI) { localAngle -= M_PI; }
pOrientationGrid->SetAngle( x, y, localAngle );
pOrientationGrid->SetMagnitude( x, y, sqrt( ( pGradientX->GetValue(x, y) * pGradientX->GetValue(x, y) )
+ ( pGradientY->GetValue(x, y) * pGradientY->GetValue(x, y) ) ) );
}
}
delete pGradientX;
delete pGradientY;
return pOrientationGrid;
}
//--------------------------------------------------------------------------------------------------------------------------
std::vector<double> HOG::ComputeHogDescriptorSingleCell( OrientationGrid* pOrientations, int idCellX, int idCellY )
{
std::vector<double> H2 = std::vector<double>( mNrBins, 0.0 );
std::vector<LocalOrientation> vOrientations = pOrientations->GetOrientationVector( idCellX * mCellWidth, idCellY * mCellHeight, (idCellX + 1) * mCellWidth - 1, (idCellY + 1) * mCellHeight - 1 );
int K = vOrientations.size();
double angleStep = M_PI / mNrBins;
// assembling the histogram with 9 bins (range of 20 degrees per bin)
int bin=0;
for ( double ang_lim = angleStep; ang_lim <= M_PI; ang_lim += angleStep )
{
for (int k = 0; k < K; k++)
{
if (vOrientations[k].GetAngle() < ang_lim)
{
vOrientations[k].SetAngle( 100 ); // mark the angle in the vector as processed
H2[bin] += vOrientations[k].GetMagnitude(); // add magnitude of orientation to designated angle bin
}
}
bin++;
}
return H2;
}
//--------------------------------------------------------------------------------------------------------------------------
void HOG::ComputeHogDescriptor( std::vector<double>& descriptorValues )
{
int nrCellsX = mpImage->GetWidth() / mCellWidth; //set here the number of HOG windows per bound box
int nrCellsY = mpImage->GetHeight() / mCellHeight;
OrientationGrid* pOrientations = ComputeOrientations( );
for (int idCellY = 0; idCellY < nrCellsY-1; idCellY++)
{
for (int idCellX = 0; idCellX < nrCellsX-1; idCellX++ )
{
// compute gradient histogram per cell in this block
std::vector<double> H2_cell0 = ComputeHogDescriptorSingleCell( pOrientations, idCellX, idCellY );
std::vector<double> H2_cell1 = ComputeHogDescriptorSingleCell( pOrientations, idCellX, idCellY+1 );
std::vector<double> H2_cell2 = ComputeHogDescriptorSingleCell( pOrientations, idCellX+1, idCellY );
std::vector<double> H2_cell3 = ComputeHogDescriptorSingleCell( pOrientations, idCellX+1, idCellY+1 );
// concatenate cell gradient histograms into a block
H2_cell0.insert( H2_cell0.end(), H2_cell1.begin(), H2_cell1.end() );
H2_cell0.insert( H2_cell0.end(), H2_cell2.begin(), H2_cell2.end() );
H2_cell0.insert( H2_cell0.end(), H2_cell3.begin(), H2_cell3.end() );
// normalize the concatenated vector
common::MathUtils::NormalizeVector( H2_cell0 );
descriptorValues.insert( descriptorValues.end(), H2_cell0.begin(), H2_cell0.end() );
}
}
delete pOrientations;
}
//--------------------------------------------------------------------------------------------------------------------------
\
Image* HOG::VisualizeHogDescriptor( std::vector<double>& descriptorValues,
int winWidth, int winHeight,
double scaleFactor, double viz_factor )
{
Image* pVisualImage = mpImage->Clone();
// dividing 180° into 9 bins, how large (in rad) is one bin?
double radRangeForOneBin = M_PI / (double)(mNrBins);
// prepare data structure: 9 orientation / gradient strenghts for each cell
int cells_in_x_dir = winWidth / mCellWidth;
int cells_in_y_dir = winHeight / mCellHeight;
double*** gradientStrengths = new double**[cells_in_y_dir];
int** cellUpdateCounter = new int*[cells_in_y_dir];
for (int y=0; y<cells_in_y_dir; y++)
{
gradientStrengths[y] = new double*[cells_in_x_dir];
cellUpdateCounter[y] = new int[cells_in_x_dir];
for (int x=0; x<cells_in_x_dir; x++)
{
gradientStrengths[y][x] = new double[mNrBins];
cellUpdateCounter[y][x] = 0;
for (int bin = 0; bin < mNrBins; bin++)
gradientStrengths[y][x][bin] = 0.0;
}
}
// nr of blocks = nr of cells - 1
// since there is a new block on each cell (overlapping blocks!) but the last one
int blocks_in_x_dir = cells_in_x_dir - 1;
int blocks_in_y_dir = cells_in_y_dir - 1;
// compute gradient strengths per cell
int descriptorDataIdx = 0;
for (int blocky=0; blocky<blocks_in_y_dir; blocky++)
{
for (int blockx=0; blockx<blocks_in_x_dir; blockx++)
{
// 4 cells per block ...
for (int cellNr=0; cellNr<4; cellNr++)
{
// compute corresponding cell nr
int cellx = blockx;
int celly = blocky;
if (cellNr==1) celly++;
if (cellNr==2) cellx++;
if (cellNr==3)
{
cellx++;
celly++;
}
for (int bin = 0; bin < mNrBins; bin++)
{
float gradientStrength = descriptorValues[ descriptorDataIdx ];
descriptorDataIdx++;
gradientStrengths[celly][cellx][bin] += gradientStrength;
} // for (all bins)
// note: overlapping blocks lead to multiple updates of this sum!
// we therefore keep track how often a cell was updated,
// to compute average gradient strengths
cellUpdateCounter[celly][cellx]++;
} // for (all cells)
} // for (all block x pos)
} // for (all block y pos)
// compute average gradient strengths
for (int celly = 0; celly < cells_in_y_dir; celly++)
{
for (int cellx = 0; cellx < cells_in_x_dir; cellx++)
{
double NrUpdatesForThisCell = (double)cellUpdateCounter[celly][cellx];
// compute average gradient strenghts for each gradient bin direction
for (int bin = 0; bin < mNrBins; bin++)
{
gradientStrengths[celly][cellx][bin] /= NrUpdatesForThisCell;
}
}
}
std::cout << "descriptorDataIdx = " << descriptorDataIdx << std::endl;
for (int celly = 0; celly < cells_in_y_dir; celly++)
{
for (int cellx = 0; cellx < cells_in_x_dir; cellx++)
{
// draw cell rectangles
int drawX = cellx * mCellWidth;
int drawY = celly * mCellHeight;
int mx = drawX + mCellWidth / 2;
int my = drawY + mCellHeight / 2;
DrawImageTools::DrawRectangle( pVisualImage,
common::Point<int>( drawX * scaleFactor,
drawY * scaleFactor),
common::Point<int>( (drawX + mCellWidth) * scaleFactor,
(drawY + mCellHeight) * scaleFactor),
ColorValue(100,100,100),
false);
// draw in each cell all 9 gradient strengths
for (int bin = 0; bin < mNrBins; bin++)
{
double currentGradStrength = gradientStrengths[celly][cellx][bin];
// no line to draw?
if (currentGradStrength < 0.01 )
{
continue;
}
else
{
double currRad = bin * radRangeForOneBin + radRangeForOneBin/2;
double dirVecX = cos( currRad );
double dirVecY = -sin( currRad );
double maxVecLen = mCellWidth / 2.0;
double scale = viz_factor; // just a visualization scale, to see the lines better
// compute line coordinates
double x1 = mx - dirVecX * currentGradStrength * maxVecLen * scale;
double y1 = my - dirVecY * currentGradStrength * maxVecLen * scale;
double x2 = mx + dirVecX * currentGradStrength * maxVecLen * scale;
double y2 = my + dirVecY * currentGradStrength * maxVecLen * scale;
// draw gradient visual_imagealization
DrawImageTools::DrawLine( pVisualImage,
common::Point<int>( x1 * scaleFactor, y1 * scaleFactor ),
common::Point<int>( x2 * scaleFactor, y2 * scaleFactor ),
ColorValue(0, 255, 0 ) );
}
} // for (all bins)
} // for (cellx)
} // for (celly)
// don't forget to free memory allocated by helper data structures!
for (int y = 0; y < cells_in_y_dir; y++)
{
for (int x=0; x<cells_in_x_dir; x++)
{
delete[] gradientStrengths[y][x];
}
delete[] gradientStrengths[y];
delete[] cellUpdateCounter[y];
}
delete[] gradientStrengths;
delete[] cellUpdateCounter;
return pVisualImage;
}
//--------------------------------------------------------------------------------------------------------------------------
}
}
| [
"filip.rooms@gmail.com"
] | filip.rooms@gmail.com |
804d1f525f2b147143f09d482425ede87a0f5f58 | 7d5119d123d65ccf3a2ead8bbb85fc9263acbb7a | /testing/protocols/h2rfp_client.cpp | 5d0fe552b1847b96c9a848c4b095fdde30d7c4ce | [] | no_license | LeTobi/tobilib | ce5fd1e86acbbab31f469c3f0fd698209c034077 | cca1f359dac60055f319efa232353ffd9c9f83b3 | refs/heads/stage | 2022-05-09T18:35:06.247528 | 2022-04-03T17:14:30 | 2022-04-03T17:14:30 | 145,462,833 | 0 | 0 | null | 2021-05-24T09:21:58 | 2018-08-20T19:41:27 | C++ | UTF-8 | C++ | false | false | 1,719 | cpp | #include "../../protocols/h2rfp.h"
#include <iostream>
using namespace tobilib;
using namespace h2rfp;
TCP_Endpoint endpoint ("localhost",15432);
Response servername;
void read_string(const Message& req)
{
std::cout << "Server is requesting a string: " << std::endl;
std::string input;
std::cin >> input;
JSObject out;
out.put("value",input);
endpoint.respond(req.id,out);
}
void read_int(const Message& req)
{
std::cout << "Server is requesting an integer: " << std::endl;
int input;
std::cin >> input;
JSObject out;
out.put("value",input);
endpoint.respond(req.id,out);
}
void react(const EndpointEvent& ev)
{
if (ev.type == EventType::connected)
{
servername = endpoint.request("getName");
return;
}
if (ev.type != EventType::message)
return;
if (ev.msg.name == "getString")
read_string(ev.msg);
else if (ev.msg.name == "getNumber")
read_int(ev.msg);
else if (ev.msg.name == "ende")
std::cout << "Server informiert: Interaktion ist zu ende." << std::endl;
else
std::cout << "unknown request: " << ev.msg.name << std::endl;
}
int main()
{
std::cout << "H2RFP client supplementary to h2rfp-server" << std::endl;
endpoint.connect();
while (endpoint.status() != EndpointStatus::closed)
{
endpoint.tick();
if (servername.pull(endpoint.responses))
{
std::cout << "verbunden mit " << servername.data.get("name","") << std::endl;
servername.dismiss();
}
while (!endpoint.events.empty())
react(endpoint.events.next());
}
std::cout << "Program finished" << std::endl;
return 0;
} | [
"tohub@bluewin.ch"
] | tohub@bluewin.ch |
029f742300037ac659dd46188aacb6f15cca115b | 8321dcefe5eaa47ebdbe6faf0bf333a84ee85373 | /point.h | 730d4463fd49434a5915298e134d4c7b9bc80f9d | [] | no_license | trekhopton/ASCII_World_Generator | 3df499395ce61f9072a59564456a07b40edf6182 | 256a58d6ad5106d733b7a39a96b94267ee4d9637 | refs/heads/master | 2020-03-27T21:27:11.822604 | 2018-09-03T03:15:56 | 2018-09-03T03:15:56 | 147,145,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 131 | h | #ifndef POINT_H
#define POINT_H
class point{
public:
point();
point(int posX, int posY);
int x;
int y;
};
#endif
| [
"trek.hopton@gmail.com"
] | trek.hopton@gmail.com |
5a93966fb95aee5f8ee6a5ada2a15bb4cc9af8e6 | 88a3ff5a9adab6045edec05d6208ca269f84a52f | /src/hash.h | a599379a4ebed3cb42bd61428965be3adf873bfc | [
"MIT"
] | permissive | 78ZeroBits/litecloud | 2ec4453b821b49d7203155fc11def361238bda79 | 5cc584cd11e46a8d8b626dead3cbef53ed0ef6f7 | refs/heads/master | 2020-03-30T12:01:29.101555 | 2018-10-06T06:12:28 | 2018-10-06T06:12:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,727 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The Litecloud developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_HASH_H
#define BITCOIN_HASH_H
#include "crypto/ripemd160.h"
#include "crypto/sha256.h"
#include "serialize.h"
#include "uint256.h"
#include "version.h"
#include "crypto/sph_blake.h"
#include "crypto/sph_bmw.h"
#include "crypto/sph_groestl.h"
#include "crypto/sph_jh.h"
#include "crypto/sph_keccak.h"
#include "crypto/sph_skein.h"
#include <iomanip>
#include <openssl/sha.h>
#include <sstream>
#include <vector>
using namespace std;
/** A hasher class for Bitcoin's 256-bit hash (double SHA-256). */
class CHash256
{
private:
CSHA256 sha;
public:
static const size_t OUTPUT_SIZE = CSHA256::OUTPUT_SIZE;
void Finalize(unsigned char hash[OUTPUT_SIZE])
{
unsigned char buf[sha.OUTPUT_SIZE];
sha.Finalize(buf);
sha.Reset().Write(buf, sha.OUTPUT_SIZE).Finalize(hash);
}
CHash256& Write(const unsigned char* data, size_t len)
{
sha.Write(data, len);
return *this;
}
CHash256& Reset()
{
sha.Reset();
return *this;
}
};
#ifdef GLOBALDEFINED
#define GLOBAL
#else
#define GLOBAL extern
#endif
GLOBAL sph_blake512_context z_blake;
GLOBAL sph_bmw512_context z_bmw;
GLOBAL sph_groestl512_context z_groestl;
GLOBAL sph_jh512_context z_jh;
GLOBAL sph_keccak512_context z_keccak;
GLOBAL sph_skein512_context z_skein;
#define fillz() \
do { \
sph_blake512_init(&z_blake); \
sph_bmw512_init(&z_bmw); \
sph_groestl512_init(&z_groestl); \
sph_jh512_init(&z_jh); \
sph_keccak512_init(&z_keccak); \
sph_skein512_init(&z_skein); \
} while (0)
#define ZBLAKE (memcpy(&ctx_blake, &z_blake, sizeof(z_blake)))
#define ZBMW (memcpy(&ctx_bmw, &z_bmw, sizeof(z_bmw)))
#define ZGROESTL (memcpy(&ctx_groestl, &z_groestl, sizeof(z_groestl)))
#define ZJH (memcpy(&ctx_jh, &z_jh, sizeof(z_jh)))
#define ZKECCAK (memcpy(&ctx_keccak, &z_keccak, sizeof(z_keccak)))
#define ZSKEIN (memcpy(&ctx_skein, &z_skein, sizeof(z_skein)))
/* ----------- Bitcoin Hash ------------------------------------------------- */
/** A hasher class for Bitcoin's 160-bit hash (SHA-256 + RIPEMD-160). */
class CHash160
{
private:
CSHA256 sha;
public:
static const size_t OUTPUT_SIZE = CRIPEMD160::OUTPUT_SIZE;
void Finalize(unsigned char hash[OUTPUT_SIZE])
{
unsigned char buf[sha.OUTPUT_SIZE];
sha.Finalize(buf);
CRIPEMD160().Write(buf, sha.OUTPUT_SIZE).Finalize(hash);
}
CHash160& Write(const unsigned char* data, size_t len)
{
sha.Write(data, len);
return *this;
}
CHash160& Reset()
{
sha.Reset();
return *this;
}
};
/** Compute the 256-bit hash of a std::string */
inline std::string Hash(std::string input)
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, input.c_str(), input.size());
SHA256_Final(hash, &sha256);
stringstream ss;
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
ss << hex << setw(2) << setfill('0') << (int)hash[i];
}
return ss.str();
}
/** Compute the 256-bit hash of a void pointer */
inline void Hash(void* in, unsigned int len, unsigned char* out)
{
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, in, len);
SHA256_Final(out, &sha256);
}
/** Compute the 256-bit hash of an object. */
template <typename T1>
inline uint256 Hash(const T1 pbegin, const T1 pend)
{
static const unsigned char pblank[1] = {};
uint256 result;
CHash256().Write(pbegin == pend ? pblank : (const unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0])).Finalize((unsigned char*)&result);
return result;
}
/** Compute the 256-bit hash of the concatenation of two objects. */
template <typename T1, typename T2>
inline uint256 Hash(const T1 p1begin, const T1 p1end, const T2 p2begin, const T2 p2end)
{
static const unsigned char pblank[1] = {};
uint256 result;
CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0])).Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0])).Finalize((unsigned char*)&result);
return result;
}
/** Compute the 256-bit hash of the concatenation of three objects. */
template <typename T1, typename T2, typename T3>
inline uint256 Hash(const T1 p1begin, const T1 p1end, const T2 p2begin, const T2 p2end, const T3 p3begin, const T3 p3end)
{
static const unsigned char pblank[1] = {};
uint256 result;
CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0])).Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0])).Write(p3begin == p3end ? pblank : (const unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0])).Finalize((unsigned char*)&result);
return result;
}
/** Compute the 256-bit hash of the concatenation of three objects. */
template <typename T1, typename T2, typename T3, typename T4>
inline uint256 Hash(const T1 p1begin, const T1 p1end, const T2 p2begin, const T2 p2end, const T3 p3begin, const T3 p3end, const T4 p4begin, const T4 p4end)
{
static const unsigned char pblank[1] = {};
uint256 result;
CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0])).Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0])).Write(p3begin == p3end ? pblank : (const unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0])).Write(p4begin == p4end ? pblank : (const unsigned char*)&p4begin[0], (p4end - p4begin) * sizeof(p4begin[0])).Finalize((unsigned char*)&result);
return result;
}
/** Compute the 256-bit hash of the concatenation of three objects. */
template <typename T1, typename T2, typename T3, typename T4, typename T5>
inline uint256 Hash(const T1 p1begin, const T1 p1end, const T2 p2begin, const T2 p2end, const T3 p3begin, const T3 p3end, const T4 p4begin, const T4 p4end, const T5 p5begin, const T5 p5end)
{
static const unsigned char pblank[1] = {};
uint256 result;
CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0])).Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0])).Write(p3begin == p3end ? pblank : (const unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0])).Write(p4begin == p4end ? pblank : (const unsigned char*)&p4begin[0], (p4end - p4begin) * sizeof(p4begin[0])).Write(p5begin == p5end ? pblank : (const unsigned char*)&p5begin[0], (p5end - p5begin) * sizeof(p5begin[0])).Finalize((unsigned char*)&result);
return result;
}
/** Compute the 256-bit hash of the concatenation of three objects. */
template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
inline uint256 Hash(const T1 p1begin, const T1 p1end, const T2 p2begin, const T2 p2end, const T3 p3begin, const T3 p3end, const T4 p4begin, const T4 p4end, const T5 p5begin, const T5 p5end, const T6 p6begin, const T6 p6end)
{
static const unsigned char pblank[1] = {};
uint256 result;
CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0])).Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0])).Write(p3begin == p3end ? pblank : (const unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0])).Write(p4begin == p4end ? pblank : (const unsigned char*)&p4begin[0], (p4end - p4begin) * sizeof(p4begin[0])).Write(p5begin == p5end ? pblank : (const unsigned char*)&p5begin[0], (p5end - p5begin) * sizeof(p5begin[0])).Write(p6begin == p6end ? pblank : (const unsigned char*)&p6begin[0], (p6end - p6begin) * sizeof(p6begin[0])).Finalize((unsigned char*)&result);
return result;
}
/** Compute the 160-bit hash an object. */
template <typename T1>
inline uint160 Hash160(const T1 pbegin, const T1 pend)
{
static unsigned char pblank[1] = {};
uint160 result;
CHash160().Write(pbegin == pend ? pblank : (const unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0])).Finalize((unsigned char*)&result);
return result;
}
/** Compute the 160-bit hash of a vector. */
inline uint160 Hash160(const std::vector<unsigned char>& vch)
{
return Hash160(vch.begin(), vch.end());
}
/** A writer stream (for serialization) that computes a 256-bit hash. */
class CHashWriter
{
private:
CHash256 ctx;
public:
int nType;
int nVersion;
CHashWriter(int nTypeIn, int nVersionIn) : nType(nTypeIn), nVersion(nVersionIn) {}
CHashWriter& write(const char* pch, size_t size)
{
ctx.Write((const unsigned char*)pch, size);
return (*this);
}
// invalidates the object
uint256 GetHash()
{
uint256 result;
ctx.Finalize((unsigned char*)&result);
return result;
}
template <typename T>
CHashWriter& operator<<(const T& obj)
{
// Serialize to this stream
::Serialize(*this, obj, nType, nVersion);
return (*this);
}
};
/** Compute the 256-bit hash of an object's serialization. */
template <typename T>
uint256 SerializeHash(const T& obj, int nType = SER_GETHASH, int nVersion = PROTOCOL_VERSION)
{
CHashWriter ss(nType, nVersion);
ss << obj;
return ss.GetHash();
}
unsigned int MurmurHash3(unsigned int nHashSeed, const std::vector<unsigned char>& vDataToHash);
void BIP32Hash(const unsigned char chainCode[32], unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]);
//int HMAC_SHA512_Init(HMAC_SHA512_CTX *pctx, const void *pkey, size_t len);
//int HMAC_SHA512_Update(HMAC_SHA512_CTX *pctx, const void *pdata, size_t len);
//int HMAC_SHA512_Final(unsigned char *pmd, HMAC_SHA512_CTX *pctx);
/* ----------- Quark Hash ------------------------------------------------ */
template <typename T1>
inline uint256 HashQuark(const T1 pbegin, const T1 pend)
{
sph_blake512_context ctx_blake;
sph_bmw512_context ctx_bmw;
sph_groestl512_context ctx_groestl;
sph_jh512_context ctx_jh;
sph_keccak512_context ctx_keccak;
sph_skein512_context ctx_skein;
static unsigned char pblank[1];
uint512 mask = 8;
uint512 zero = 0;
uint512 hash[9];
sph_blake512_init(&ctx_blake);
// ZBLAKE;
sph_blake512(&ctx_blake, (pbegin == pend ? pblank : static_cast<const void*>(&pbegin[0])), (pend - pbegin) * sizeof(pbegin[0]));
sph_blake512_close(&ctx_blake, static_cast<void*>(&hash[0]));
sph_bmw512_init(&ctx_bmw);
// ZBMW;
sph_bmw512(&ctx_bmw, static_cast<const void*>(&hash[0]), 64);
sph_bmw512_close(&ctx_bmw, static_cast<void*>(&hash[1]));
if ((hash[1] & mask) != zero) {
sph_groestl512_init(&ctx_groestl);
// ZGROESTL;
sph_groestl512(&ctx_groestl, static_cast<const void*>(&hash[1]), 64);
sph_groestl512_close(&ctx_groestl, static_cast<void*>(&hash[2]));
} else {
sph_skein512_init(&ctx_skein);
// ZSKEIN;
sph_skein512(&ctx_skein, static_cast<const void*>(&hash[1]), 64);
sph_skein512_close(&ctx_skein, static_cast<void*>(&hash[2]));
}
sph_groestl512_init(&ctx_groestl);
// ZGROESTL;
sph_groestl512(&ctx_groestl, static_cast<const void*>(&hash[2]), 64);
sph_groestl512_close(&ctx_groestl, static_cast<void*>(&hash[3]));
sph_jh512_init(&ctx_jh);
// ZJH;
sph_jh512(&ctx_jh, static_cast<const void*>(&hash[3]), 64);
sph_jh512_close(&ctx_jh, static_cast<void*>(&hash[4]));
if ((hash[4] & mask) != zero) {
sph_blake512_init(&ctx_blake);
// ZBLAKE;
sph_blake512(&ctx_blake, static_cast<const void*>(&hash[4]), 64);
sph_blake512_close(&ctx_blake, static_cast<void*>(&hash[5]));
} else {
sph_bmw512_init(&ctx_bmw);
// ZBMW;
sph_bmw512(&ctx_bmw, static_cast<const void*>(&hash[4]), 64);
sph_bmw512_close(&ctx_bmw, static_cast<void*>(&hash[5]));
}
sph_keccak512_init(&ctx_keccak);
// ZKECCAK;
sph_keccak512(&ctx_keccak, static_cast<const void*>(&hash[5]), 64);
sph_keccak512_close(&ctx_keccak, static_cast<void*>(&hash[6]));
sph_skein512_init(&ctx_skein);
// SKEIN;
sph_skein512(&ctx_skein, static_cast<const void*>(&hash[6]), 64);
sph_skein512_close(&ctx_skein, static_cast<void*>(&hash[7]));
if ((hash[7] & mask) != zero) {
sph_keccak512_init(&ctx_keccak);
// ZKECCAK;
sph_keccak512(&ctx_keccak, static_cast<const void*>(&hash[7]), 64);
sph_keccak512_close(&ctx_keccak, static_cast<void*>(&hash[8]));
} else {
sph_jh512_init(&ctx_jh);
// ZJH;
sph_jh512(&ctx_jh, static_cast<const void*>(&hash[7]), 64);
sph_jh512_close(&ctx_jh, static_cast<void*>(&hash[8]));
}
return hash[8].trim256();
}
void scrypt_hash(const char* pass, unsigned int pLen, const char* salt, unsigned int sLen, char* output, unsigned int N, unsigned int r, unsigned int p, unsigned int dkLen);
#endif // BITCOIN_HASH_H
| [
"root@vultr.guest"
] | root@vultr.guest |
5dcad93e7e1ba9c0f9151226e4f34bc0206ea9a8 | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/base/pnp/hotplug/rconfirm.cpp | d9c4e53a858aaa2ff05bfaf3ba56262d5fe629a6 | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,135 | cpp | //+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// Copyright (C) Microsoft Corporation, 1997 - 1999
//
// File: rconfirm.c
//
//--------------------------------------------------------------------------
#include "HotPlug.h"
#define NOTIFYICONDATA_SZINFO 256
#define NOTIFYICONDATA_SZINFOTITLE 64
#define WM_NOTIFY_MESSAGE (WM_USER + 100)
extern HMODULE hHotPlug;
DWORD
WaitDlgMessagePump(
HWND hDlg,
DWORD nCount,
LPHANDLE Handles
)
{
DWORD WaitReturn;
MSG Msg;
while ((WaitReturn = MsgWaitForMultipleObjects(nCount,
Handles,
FALSE,
INFINITE,
QS_ALLINPUT
))
== nCount)
{
while (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE)) {
if (!IsDialogMessage(hDlg,&Msg)) {
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
}
}
return WaitReturn;
}
int
InsertDeviceNodeListView(
HWND hwndList,
PDEVICETREE DeviceTree,
PDEVTREENODE DeviceTreeNode,
INT lvIndex
)
{
LV_ITEM lviItem;
TCHAR Buffer[MAX_PATH];
lviItem.mask = LVIF_TEXT | LVIF_PARAM;
lviItem.iItem = lvIndex;
lviItem.iSubItem = 0;
if (SetupDiGetClassImageIndex(&DeviceTree->ClassImageList,
&DeviceTreeNode->ClassGuid,
&lviItem.iImage
))
{
lviItem.mask |= LVIF_IMAGE;
}
lviItem.pszText = FetchDeviceName(DeviceTreeNode);
if (!lviItem.pszText) {
lviItem.pszText = Buffer;
wsprintf(Buffer,
TEXT("%s %s"),
szUnknown,
DeviceTreeNode->Location ? DeviceTreeNode->Location : TEXT("")
);
}
lviItem.lParam = (LPARAM) DeviceTreeNode;
return ListView_InsertItem(hwndList, &lviItem);
}
DWORD
RemoveThread(
PVOID pvDeviceTree
)
{
PDEVICETREE DeviceTree = (PDEVICETREE)pvDeviceTree;
PDEVTREENODE DeviceTreeNode;
DeviceTreeNode = DeviceTree->ChildRemovalList;
return(CM_Request_Device_Eject_Ex(DeviceTreeNode->DevInst,
NULL,
NULL,
0,
0,
DeviceTree->hMachine
));
}
BOOL
OnOkRemove(
HWND hDlg,
PDEVICETREE DeviceTree
)
{
HCURSOR hCursor;
PDEVTREENODE DeviceTreeNode;
HANDLE hThread;
DWORD ThreadId;
DWORD WaitReturn;
PTCHAR DeviceName;
TCHAR szReply[MAX_PATH];
TCHAR Buffer[MAX_PATH];
BOOL bSuccess;
hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT));
DeviceTreeNode = DeviceTree->ChildRemovalList;
DeviceTree->RedrawWait = TRUE;
hThread = CreateThread(NULL,
0,
RemoveThread,
DeviceTree,
0,
&ThreadId
);
if (!hThread) {
return FALSE;
}
//
// disable the ok\cancel buttons
//
EnableWindow(GetDlgItem(hDlg, IDOK), FALSE);
EnableWindow(GetDlgItem(hDlg, IDCANCEL), FALSE);
WaitReturn = WaitDlgMessagePump(hDlg, 1, &hThread);
bSuccess =
(WaitReturn == 0 &&
GetExitCodeThread(hThread, &WaitReturn) &&
WaitReturn == CR_SUCCESS );
SetCursor(hCursor);
DeviceTree->RedrawWait = FALSE;
CloseHandle(hThread);
return bSuccess;
}
#define idh_hwwizard_confirm_stop_list 15321 // "" (SysListView32)
DWORD RemoveConfirmHelpIDs[] = {
IDC_REMOVELIST, idh_hwwizard_confirm_stop_list,
IDC_NOHELP1, NO_HELP,
IDC_NOHELP2, NO_HELP,
IDC_NOHELP3, NO_HELP,
0,0
};
BOOL
InitRemoveConfirmDlgProc(
HWND hDlg,
PDEVICETREE DeviceTree
)
{
HWND hwndList;
PDEVTREENODE DeviceTreeNode;
int lvIndex;
LV_COLUMN lvcCol;
PDEVTREENODE Next;
HICON hIcon;
hIcon = LoadIcon(hHotPlug,MAKEINTRESOURCE(IDI_HOTPLUGICON));
if (hIcon) {
SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
}
DeviceTreeNode = DeviceTree->ChildRemovalList;
if (!DeviceTreeNode) {
return FALSE;
}
DeviceTree->hwndRemove = hDlg;
hwndList = GetDlgItem(hDlg, IDC_REMOVELIST);
ListView_SetImageList(hwndList, DeviceTree->ClassImageList.ImageList, LVSIL_SMALL);
ListView_DeleteAllItems(hwndList);
// Insert a column for the class list
lvcCol.mask = LVCF_FMT | LVCF_WIDTH;
lvcCol.fmt = LVCFMT_LEFT;
lvcCol.iSubItem = 0;
ListView_InsertColumn(hwndList, 0, (LV_COLUMN FAR *)&lvcCol);
SendMessage(hwndList, WM_SETREDRAW, FALSE, 0L);
//
// Walk the removal list and add each of them to the listbox.
//
lvIndex = 0;
do {
InsertDeviceNodeListView(hwndList, DeviceTree, DeviceTreeNode, lvIndex++);
DeviceTreeNode = DeviceTreeNode->NextChildRemoval;
} while (DeviceTreeNode != DeviceTree->ChildRemovalList);
ListView_SetItemState(hwndList, 0, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);
ListView_EnsureVisible(hwndList, 0, FALSE);
ListView_SetColumnWidth(hwndList, 0, LVSCW_AUTOSIZE_USEHEADER);
SendMessage(hwndList, WM_SETREDRAW, TRUE, 0L);
return TRUE;
}
LRESULT CALLBACK
RemoveConfirmDlgProc(
HWND hDlg,
UINT message,
WPARAM wParam,
LPARAM lParam
)
/*++
Routine Description:
DialogProc to confirm user really wants to remove the devices.
Arguments:
standard stuff.
Return Value:
LRESULT
--*/
{
PDEVICETREE DeviceTree=NULL;
BOOL Status = TRUE;
if (message == WM_INITDIALOG) {
DeviceTree = (PDEVICETREE)lParam;
SetWindowLongPtr(hDlg, DWLP_USER, (LONG_PTR)DeviceTree);
if (DeviceTree) {
if (DeviceTree->HideUI) {
PostMessage(hDlg, WUM_EJECTDEVINST, 0, 0);
} else {
InitRemoveConfirmDlgProc(hDlg, DeviceTree);
}
}
return TRUE;
}
//
// retrieve private data from window long (stored there during WM_INITDIALOG)
//
DeviceTree = (PDEVICETREE)GetWindowLongPtr(hDlg, DWLP_USER);
switch (message) {
case WM_DESTROY:
DeviceTree->hwndRemove = NULL;
break;
case WM_CLOSE:
SendMessage (hDlg, WM_COMMAND, IDCANCEL, 0L);
break;
case WM_COMMAND:
switch(wParam) {
case IDOK:
EndDialog(hDlg, OnOkRemove(hDlg, DeviceTree) ? IDOK : IDCANCEL);
break;
case IDCLOSE:
case IDCANCEL:
EndDialog(hDlg, IDCANCEL);
break;
}
break;
case WUM_EJECTDEVINST:
EndDialog(hDlg, OnOkRemove(hDlg, DeviceTree) ? IDOK : IDCANCEL);
break;
case WM_SYSCOLORCHANGE:
break;
case WM_CONTEXTMENU:
WinHelp((HWND)wParam,
TEXT("hardware.hlp"),
HELP_CONTEXTMENU,
(DWORD_PTR)(LPVOID)(PDWORD)RemoveConfirmHelpIDs
);
return FALSE;
case WM_HELP:
OnContextHelp((LPHELPINFO)lParam, RemoveConfirmHelpIDs);
break;
case WM_SETCURSOR:
if (DeviceTree->RedrawWait || DeviceTree->RefreshEvent) {
SetCursor(LoadCursor(NULL, IDC_WAIT));
SetWindowLongPtr(hDlg, DWLP_MSGRESULT, 1);
}
break;
default:
return FALSE;
}
return TRUE;
}
#if UNDOCK_WARNING
#define idh_hwwizard_unsafe_remove_list 15330 // "" (SysListView32)
DWORD SurpriseWarnHelpIDs[] = {
IDC_REMOVELIST, idh_hwwizard_unsafe_remove_list,
IDC_NOHELP1, NO_HELP,
IDC_NOHELP2, NO_HELP,
IDC_NOHELP3, NO_HELP,
IDC_NOHELP4, NO_HELP,
IDC_NOHELP5, NO_HELP,
IDC_STATIC, NO_HELP,
0,0
};
BOOL
InitSurpriseWarnDlgProc(
IN HWND hDlg,
IN PSURPRISE_WARN_COLLECTION SurpriseWarnCollection
)
{
HWND hwndList;
HICON hIcon;
hIcon = LoadIcon(hHotPlug,MAKEINTRESOURCE(IDI_HOTPLUGICON));
if (hIcon) {
SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
}
hwndList = GetDlgItem(hDlg, IDC_REMOVELIST);
SendMessage(hwndList, WM_SETREDRAW, FALSE, 0L);
ListView_DeleteAllItems(hwndList);
DeviceCollectionPopulateListView(
(PDEVICE_COLLECTION) SurpriseWarnCollection,
hwndList
);
ListView_SetItemState(hwndList, 0, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
ListView_EnsureVisible(hwndList, 0, FALSE);
ListView_SetColumnWidth(hwndList, 0, LVSCW_AUTOSIZE_USEHEADER);
SendMessage(hwndList, WM_SETREDRAW, TRUE, 0L);
return TRUE;
}
BOOL
InitSurpriseUndockDlgProc(
IN HWND hDlg,
IN PSURPRISE_WARN_COLLECTION SurpriseWarnCollection
)
{
HICON hIcon;
TCHAR szFormat[512];
TCHAR szMessage[MAX_DEVICE_ID_LEN + 200];
ULONG dockDeviceIndex;
hIcon = LoadIcon(hHotPlug,MAKEINTRESOURCE(IDI_UNDOCKICON));
if (hIcon) {
SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
}
LoadString(hHotPlug, IDS_UNSAFE_UNDOCK, szFormat, SIZECHARS(szFormat));
if (!DeviceCollectionGetDockDeviceIndex(
(PDEVICE_COLLECTION) SurpriseWarnCollection,
&dockDeviceIndex
)) {
return FALSE;
}
if (!DeviceCollectionFormatDeviceText(
(PDEVICE_COLLECTION) SurpriseWarnCollection,
dockDeviceIndex,
szFormat,
SIZECHARS(szMessage),
szMessage
)) {
return FALSE;
}
SetDlgItemText(hDlg, IDC_UNDOCK_MESSAGE, szMessage);
return TRUE;
}
LRESULT CALLBACK
SurpriseWarnDlgProc(
HWND hDlg,
UINT message,
WPARAM wParam,
LPARAM lParam
)
/*++
Routine Description:
DialogProc to confirm user really wants to remove the devices.
Arguments:
standard stuff.
Return Value:
LRESULT
--*/
{
PSURPRISE_WARN_COLLECTION surpriseWarnCollection = NULL;
BOOL status = TRUE;
if (message == WM_INITDIALOG) {
surpriseWarnCollection = (PSURPRISE_WARN_COLLECTION) lParam;
SetWindowLongPtr(hDlg, DWLP_USER, lParam);
status = (surpriseWarnCollection->DockInList) ?
InitSurpriseUndockDlgProc(hDlg, surpriseWarnCollection) :
InitSurpriseWarnDlgProc(hDlg, surpriseWarnCollection);
if (!status) {
EndDialog(hDlg, IDABORT);
}
return TRUE;
}
//
// retrieve private data from window long (stored there during WM_INITDIALOG)
//
surpriseWarnCollection =
(PSURPRISE_WARN_COLLECTION) GetWindowLongPtr(hDlg, DWLP_USER);
switch (message) {
case WM_DESTROY:
break;
case WM_CLOSE:
SendMessage (hDlg, WM_COMMAND, IDCANCEL, 0L);
break;
case WM_COMMAND:
switch(wParam) {
case IDOK:
case IDCLOSE:
surpriseWarnCollection->SuppressSurprise =
IsDlgButtonChecked(hDlg, IDC_SUPPRESS_SURPRISE);
case IDCANCEL:
EndDialog(hDlg, wParam);
break;
}
break;
case WM_SYSCOLORCHANGE:
break;
case WM_HELP:
OnContextHelp((LPHELPINFO)lParam, SurpriseWarnHelpIDs);
break;
case WM_CONTEXTMENU:
WinHelp((HWND)wParam,
TEXT("hardware.hlp"),
HELP_CONTEXTMENU,
(DWORD_PTR)(LPVOID)(PDWORD)SurpriseWarnHelpIDs
);
return FALSE;
case WM_NOTIFY:
switch (((NMHDR FAR *)lParam)->code) {
case LVN_ITEMCHANGED: {
break;
}
}
default:
return FALSE;
}
return TRUE;
}
#endif // UNDOCK_WARNING
#if BUBBLES
LRESULT
CALLBACK
SurpriseWarnBalloonProc(
HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam
)
{
NOTIFYICONDATA nid;
static HICON hHotPlugIcon = NULL;
static BOOL bDialogDisplayed = FALSE;
PSURPRISE_WARN_COLLECTION surpriseWarnCollection;
UINT_PTR timer;
HANDLE hUndockTimer, hUndockEvent;
static BOOL bCheckIfDeviceIsPresent = FALSE;
switch (message) {
case WM_CREATE:
surpriseWarnCollection = (PSURPRISE_WARN_COLLECTION)((CREATESTRUCT*)lParam)->lpCreateParams;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR) surpriseWarnCollection);
//
// Display the hotplug taskbar icon along with the surprise removal warning balloon.
// The balloon will stay up for 60 seconds or until the user clicks on the balloon
// or icon to display the dialog that lists the devices that were surprise removed.
// After the user closes the dialog the balloon and taskbar icon will go away.
//
hHotPlugIcon = LoadIcon(hHotPlug, MAKEINTRESOURCE(IDI_HOTPLUGICON));
ZeroMemory(&nid, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = hWnd;
nid.uID = WM_NOTIFY_MESSAGE;
nid.hIcon = hHotPlugIcon;
nid.uFlags = NIF_MESSAGE | NIF_ICON;
nid.uCallbackMessage = WM_NOTIFY_MESSAGE;
Shell_NotifyIcon(NIM_ADD, &nid);
nid.uVersion = NOTIFYICON_VERSION;
Shell_NotifyIcon(NIM_SETVERSION, &nid);
nid.uFlags = NIF_INFO;
nid.uTimeout = 45000;
nid.dwInfoFlags = NIIF_ERROR;
LoadString(hHotPlug,
IDS_HOTPLUG_TITLE,
nid.szInfoTitle,
SIZECHARS(nid.szInfoTitle)
);
LoadString(hHotPlug,
IDS_HOTPLUG_REMOVE_INFO,
nid.szInfo,
SIZECHARS(nid.szInfo)
);
Shell_NotifyIcon(NIM_MODIFY, &nid);
surpriseWarnCollection->DialogTicker = 0;
OpenGetSurpriseUndockObjects(&hUndockTimer, &hUndockEvent);
if (hUndockTimer) {
if (WaitForSingleObject(hUndockTimer, 0) == WAIT_TIMEOUT) {
//
// The "we're free" event isn't signalled. Nuke this bubble.
//
DestroyWindow(hWnd);
}
CloseHandle(hUndockTimer);
}
if (hUndockEvent) {
CloseHandle(hUndockEvent);
}
SetTimer(hWnd, 0, 250, NULL);
//
// Wait for five seconds before we check to see if the user re-inserted
// the device that we are warning them about.
//
SetTimer(hWnd, TIMERID_DEVICECHANGE, 5000, NULL);
break;
case WM_NOTIFY_MESSAGE:
switch(lParam) {
case NIN_BALLOONTIMEOUT:
DestroyWindow(hWnd);
break;
case NIN_BALLOONUSERCLICK:
case WM_LBUTTONUP:
case WM_RBUTTONUP:
if (!bDialogDisplayed) {
surpriseWarnCollection = (PSURPRISE_WARN_COLLECTION) GetWindowLongPtr(hWnd, GWLP_USERDATA);
//
// Set this so we only display the dialog once!
//
bDialogDisplayed = TRUE;
DialogBoxParam(hHotPlug,
MAKEINTRESOURCE(DLG_SURPRISEWARN),
NULL,
SurpriseWarnDlgProc,
(LPARAM)surpriseWarnCollection
);
DestroyWindow(hWnd);
}
break;
default:
break;
}
break;
case WM_TIMER:
surpriseWarnCollection = (PSURPRISE_WARN_COLLECTION) GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (wParam == TIMERID_DEVICECHANGE) {
KillTimer(hWnd, TIMERID_DEVICECHANGE);
bCheckIfDeviceIsPresent = TRUE;
//
// If all of the devices are present in the machine, then that means
// the user pluged in the device that they just surprise removed,
// so make the balloon go away since the user got the message.
//
if (DeviceCollectionCheckIfAllPresent((PDEVICE_COLLECTION)surpriseWarnCollection)) {
DestroyWindow(hWnd);
}
} else if (wParam == 0) {
surpriseWarnCollection->DialogTicker++;
OpenGetSurpriseUndockObjects(&hUndockTimer, &hUndockEvent);
if (hUndockTimer) {
if (WaitForSingleObject(hUndockTimer, 0) == WAIT_TIMEOUT) {
//
// The "we're free" event isn't signalled. Nuke this bubble.
//
DestroyWindow(hWnd);
}
CloseHandle(hUndockTimer);
}
if (hUndockEvent) {
CloseHandle(hUndockEvent);
}
if (surpriseWarnCollection->DialogTicker >=
surpriseWarnCollection->MaxWaitForDock*4) {
//
// We've waited long enough for this to be associated with a
// surprise undock. Stop wasting CPU cycles polling....
//
KillTimer(hWnd, 0);
}
}
break;
case WM_DEVICECHANGE:
if (DBT_DEVNODES_CHANGED == wParam && bCheckIfDeviceIsPresent) {
SetTimer(hWnd, TIMERID_DEVICECHANGE, 1000, NULL);
}
break;
case WM_DESTROY:
ZeroMemory(&nid, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = hWnd;
nid.uID = WM_NOTIFY_MESSAGE;
Shell_NotifyIcon(NIM_DELETE, &nid);
if (hHotPlugIcon) {
DestroyIcon(hHotPlugIcon);
}
surpriseWarnCollection = (PSURPRISE_WARN_COLLECTION) GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (surpriseWarnCollection->DialogTicker <
surpriseWarnCollection->MaxWaitForDock*4) {
KillTimer(hWnd, 0);
}
PostQuitMessage(0);
break;
default:
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
#endif // BUBBLES
LRESULT CALLBACK
SafeRemovalBalloonProc(
HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam
)
{
NOTIFYICONDATA nid;
static HICON hHotPlugIcon = NULL;
TCHAR szFormat[512];
PDEVICE_COLLECTION safeRemovalCollection;
static BOOL bCheckIfDeviceIsRemoved = FALSE;
switch (message) {
case WM_CREATE:
safeRemovalCollection = (PDEVICE_COLLECTION) ((CREATESTRUCT*)lParam)->lpCreateParams;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR) safeRemovalCollection);
hHotPlugIcon = (HICON)LoadImage(hHotPlug,
MAKEINTRESOURCE(IDI_HOTPLUGICON),
IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON),
0
);
ZeroMemory(&nid, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = hWnd;
nid.uID = WM_NOTIFY_MESSAGE;
nid.hIcon = hHotPlugIcon;
nid.uFlags = NIF_MESSAGE | NIF_ICON;
nid.uCallbackMessage = WM_NOTIFY_MESSAGE;
Shell_NotifyIcon(NIM_ADD, &nid);
nid.uVersion = NOTIFYICON_VERSION;
Shell_NotifyIcon(NIM_SETVERSION, &nid);
nid.uFlags = NIF_INFO;
nid.uTimeout = 10000;
nid.dwInfoFlags = NIIF_INFO;
LoadString(hHotPlug,
IDS_REMOVAL_COMPLETE_TITLE,
nid.szInfoTitle,
SIZECHARS(nid.szInfoTitle)
);
LoadString(hHotPlug, IDS_REMOVAL_COMPLETE_TEXT, szFormat, SIZECHARS(szFormat));
DeviceCollectionFormatDeviceText(
safeRemovalCollection,
0,
szFormat,
SIZECHARS(nid.szInfo),
nid.szInfo
);
Shell_NotifyIcon(NIM_MODIFY, &nid);
SetTimer(hWnd, TIMERID_DEVICECHANGE, 5000, NULL);
break;
case WM_NOTIFY_MESSAGE:
switch(lParam) {
case NIN_BALLOONTIMEOUT:
case NIN_BALLOONUSERCLICK:
DestroyWindow(hWnd);
break;
default:
break;
}
break;
case WM_DEVICECHANGE:
if ((DBT_DEVNODES_CHANGED == wParam) && bCheckIfDeviceIsRemoved) {
SetTimer(hWnd, TIMERID_DEVICECHANGE, 1000, NULL);
}
break;
case WM_TIMER:
if (wParam == TIMERID_DEVICECHANGE) {
KillTimer(hWnd, TIMERID_DEVICECHANGE);
bCheckIfDeviceIsRemoved = TRUE;
safeRemovalCollection = (PDEVICE_COLLECTION) GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (DeviceCollectionCheckIfAllRemoved(safeRemovalCollection)) {
DestroyWindow(hWnd);
}
}
break;
case WM_DESTROY:
ZeroMemory(&nid, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = hWnd;
nid.uID = WM_NOTIFY_MESSAGE;
Shell_NotifyIcon(NIM_DELETE, &nid);
if (hHotPlugIcon) {
DestroyIcon(hHotPlugIcon);
}
PostQuitMessage(0);
break;
default:
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
LRESULT CALLBACK
DockSafeRemovalBalloonProc(
HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam
)
{
NOTIFYICONDATA nid;
static HICON hHotPlugIcon = NULL;
TCHAR szFormat[512];
PDEVICE_COLLECTION safeRemovalCollection;
static BOOL bCheckIfReDocked = FALSE;
BOOL bIsDockStationPresent;
switch (message) {
case WM_CREATE:
safeRemovalCollection = (PDEVICE_COLLECTION) ((CREATESTRUCT*)lParam)->lpCreateParams;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR) safeRemovalCollection);
hHotPlugIcon = (HICON)LoadImage(hHotPlug,
MAKEINTRESOURCE(IDI_UNDOCKICON),
IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON),
0
);
ZeroMemory(&nid, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = hWnd;
nid.uID = WM_NOTIFY_MESSAGE;
nid.hIcon = hHotPlugIcon;
nid.uFlags = NIF_MESSAGE | NIF_ICON;
nid.uCallbackMessage = WM_NOTIFY_MESSAGE;
Shell_NotifyIcon(NIM_ADD, &nid);
nid.uVersion = NOTIFYICON_VERSION;
Shell_NotifyIcon(NIM_SETVERSION, &nid);
nid.uFlags = NIF_INFO;
nid.uTimeout = 10000;
nid.dwInfoFlags = NIIF_INFO;
LoadString(hHotPlug,
IDS_UNDOCK_COMPLETE_TITLE,
nid.szInfoTitle,
SIZECHARS(nid.szInfoTitle)
);
LoadString(hHotPlug, IDS_UNDOCK_COMPLETE_TEXT, szFormat, SIZECHARS(szFormat));
DeviceCollectionFormatDeviceText(
safeRemovalCollection,
0,
szFormat,
SIZECHARS(nid.szInfo),
nid.szInfo
);
Shell_NotifyIcon(NIM_MODIFY, &nid);
SetTimer(hWnd, TIMERID_DEVICECHANGE, 5000, NULL);
break;
case WM_NOTIFY_MESSAGE:
switch(lParam) {
case NIN_BALLOONTIMEOUT:
case NIN_BALLOONUSERCLICK:
DestroyWindow(hWnd);
break;
default:
break;
}
break;
case WM_DEVICECHANGE:
if ((DBT_CONFIGCHANGED == wParam) && bCheckIfReDocked) {
SetTimer(hWnd, TIMERID_DEVICECHANGE, 1000, NULL);
}
break;
case WM_TIMER:
if (wParam == TIMERID_DEVICECHANGE) {
KillTimer(hWnd, TIMERID_DEVICECHANGE);
bCheckIfReDocked = TRUE;
//
// Check if the docking station is now present, this means that the
// user redocked the machine and that we should kill the safe to
// undock balloon.
//
bIsDockStationPresent = FALSE;
CM_Is_Dock_Station_Present(&bIsDockStationPresent);
if (bIsDockStationPresent) {
DestroyWindow(hWnd);
}
}
break;
case WM_DESTROY:
ZeroMemory(&nid, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = hWnd;
nid.uID = WM_NOTIFY_MESSAGE;
Shell_NotifyIcon(NIM_DELETE, &nid);
if (hHotPlugIcon) {
DestroyIcon(hHotPlugIcon);
}
PostQuitMessage(0);
break;
default:
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
BOOL
VetoedRemovalUI(
IN PVETO_DEVICE_COLLECTION VetoedRemovalCollection
)
{
HANDLE hVetoEvent = NULL;
TCHAR szEventName[MAX_PATH];
TCHAR szFormat[512];
TCHAR szMessage[512];
TCHAR szTitle[256];
PTSTR culpritDeviceId;
PTSTR vetoedDeviceInstancePath;
PTCHAR pStr;
ULONG messageBase;
//
// The first device in the list is the device that failed ejection.
// The next "device" is the name of the vetoer. It may in fact not be a
// device.
//
vetoedDeviceInstancePath = DeviceCollectionGetDeviceInstancePath(
(PDEVICE_COLLECTION) VetoedRemovalCollection,
0
);
culpritDeviceId = DeviceCollectionGetDeviceInstancePath(
(PDEVICE_COLLECTION) VetoedRemovalCollection,
1
);
//
// We will now check to see if this same veto message is already being
// displayed. We do this by creating a named event where the name
// contains the three elements that make a veto message unique:
// 1) device instance id
// 2) veto type
// 3) veto operation
//
// If we find an identical veto message already being displayed then we wil
// just go away silently. This prevents multiple identical veto messages
// from showing up on the screen.
//
_snwprintf(szEventName,
SIZECHARS(szEventName),
TEXT("Local\\VETO-%d-%d-%s"),
(DWORD)VetoedRemovalCollection->VetoType,
VetoedRemovalCollection->VetoedOperation,
culpritDeviceId
);
//
// Replace all of the backslashes (except the first one for Local\)
// with pound characters since CreateEvent does not like backslashes.
//
pStr = StrChr(szEventName, TEXT('\\'));
if (pStr) {
pStr++;
}
while (pStr = StrChr(pStr, TEXT('\\'))) {
*pStr = TEXT('#');
}
hVetoEvent = CreateEvent(NULL,
FALSE,
TRUE,
szEventName
);
if (hVetoEvent) {
if (WaitForSingleObject(hVetoEvent, 0) != WAIT_OBJECT_0) {
//
// This means that this veto message is already being displayed
// by another hotplug process...so just go away.
//
CloseHandle(hVetoEvent);
return FALSE;
}
}
//
// Create the veto text
//
switch(VetoedRemovalCollection->VetoedOperation) {
case VETOED_UNDOCK:
case VETOED_WARM_UNDOCK:
messageBase = IDS_DOCKVETO_BASE;
break;
case VETOED_STANDBY:
messageBase = IDS_SLEEPVETO_BASE;
break;
case VETOED_HIBERNATE:
messageBase = IDS_HIBERNATEVETO_BASE;
break;
case VETOED_REMOVAL:
case VETOED_EJECT:
case VETOED_WARM_EJECT:
default:
messageBase = IDS_VETO_BASE;
break;
}
switch(VetoedRemovalCollection->VetoType) {
case PNP_VetoWindowsApp:
if (culpritDeviceId) {
//
// Tell our user the name of the offending application.
//
LoadString(hHotPlug, messageBase+VetoedRemovalCollection->VetoType, szFormat, SIZECHARS(szFormat));
DeviceCollectionFormatDeviceText(
(PDEVICE_COLLECTION) VetoedRemovalCollection,
1,
szFormat,
SIZECHARS(szMessage),
szMessage
);
} else {
//
// No application, use the "some app" message.
//
messageBase += (IDS_VETO_UNKNOWNWINDOWSAPP - IDS_VETO_WINDOWSAPP);
LoadString(hHotPlug, messageBase+VetoedRemovalCollection->VetoType, szMessage, SIZECHARS(szMessage));
}
break;
case PNP_VetoWindowsService:
case PNP_VetoDriver:
case PNP_VetoLegacyDriver:
//
// PNP_VetoWindowsService, PNP_VetoDriver and PNP_VetoLegacyDriver
// are passed through the service manager to get friendlier names.
//
LoadString(hHotPlug, messageBase+VetoedRemovalCollection->VetoType, szFormat, SIZECHARS(szFormat));
//
// For these veto types, entry index 1 is the vetoing service.
//
DeviceCollectionFormatServiceText(
(PDEVICE_COLLECTION) VetoedRemovalCollection,
1,
szFormat,
SIZECHARS(szMessage),
szMessage
);
break;
case PNP_VetoDevice:
if ((VetoedRemovalCollection->VetoedOperation == VETOED_WARM_UNDOCK) &&
(!lstrcmp(culpritDeviceId, vetoedDeviceInstancePath))) {
messageBase += (IDS_DOCKVETO_WARM_EJECT - IDS_DOCKVETO_DEVICE);
}
//
// Fall through.
//
case PNP_VetoLegacyDevice:
case PNP_VetoPendingClose:
case PNP_VetoOutstandingOpen:
case PNP_VetoNonDisableable:
case PNP_VetoIllegalDeviceRequest:
//
// Include the veto ID in the display output
//
LoadString(hHotPlug, messageBase+VetoedRemovalCollection->VetoType, szFormat, SIZECHARS(szFormat));
DeviceCollectionFormatDeviceText(
(PDEVICE_COLLECTION) VetoedRemovalCollection,
1,
szFormat,
SIZECHARS(szMessage),
szMessage
);
break;
case PNP_VetoInsufficientRights:
//
// Use the device itself in the display, but only if we are not
// in the dock case.
//
if ((VetoedRemovalCollection->VetoedOperation == VETOED_UNDOCK)||
(VetoedRemovalCollection->VetoedOperation == VETOED_WARM_UNDOCK)) {
LoadString(hHotPlug, messageBase+VetoedRemovalCollection->VetoType, szMessage, SIZECHARS(szMessage));
break;
}
//
// Fall through.
//
case PNP_VetoInsufficientPower:
case PNP_VetoTypeUnknown:
//
// Use the device itself in the display
//
LoadString(hHotPlug, messageBase+VetoedRemovalCollection->VetoType, szFormat, SIZECHARS(szFormat));
DeviceCollectionFormatDeviceText(
(PDEVICE_COLLECTION) VetoedRemovalCollection,
0,
szFormat,
SIZECHARS(szMessage),
szMessage
);
break;
default:
ASSERT(0);
LoadString(hHotPlug, messageBase+PNP_VetoTypeUnknown, szFormat, SIZECHARS(szFormat));
DeviceCollectionFormatDeviceText(
(PDEVICE_COLLECTION) VetoedRemovalCollection,
0,
szFormat,
SIZECHARS(szMessage),
szMessage
);
break;
}
switch(VetoedRemovalCollection->VetoedOperation) {
case VETOED_EJECT:
case VETOED_WARM_EJECT:
LoadString(hHotPlug, IDS_VETOED_EJECT_TITLE, szFormat, SIZECHARS(szFormat));
break;
case VETOED_UNDOCK:
case VETOED_WARM_UNDOCK:
LoadString(hHotPlug, IDS_VETOED_UNDOCK_TITLE, szFormat, SIZECHARS(szFormat));
break;
case VETOED_STANDBY:
LoadString(hHotPlug, IDS_VETOED_STANDBY_TITLE, szFormat, SIZECHARS(szFormat));
break;
case VETOED_HIBERNATE:
LoadString(hHotPlug, IDS_VETOED_HIBERNATION_TITLE, szFormat, SIZECHARS(szFormat));
break;
default:
ASSERT(0);
//
// Fall through, display something at least...
//
case VETOED_REMOVAL:
LoadString(hHotPlug, IDS_VETOED_REMOVAL_TITLE, szFormat, SIZECHARS(szFormat));
break;
}
switch(VetoedRemovalCollection->VetoedOperation) {
case VETOED_STANDBY:
case VETOED_HIBERNATE:
lstrcpyn(szTitle, szFormat, (int)(min(SIZECHARS(szTitle), lstrlen(szFormat)+1)));
break;
case VETOED_EJECT:
case VETOED_WARM_EJECT:
case VETOED_UNDOCK:
case VETOED_WARM_UNDOCK:
case VETOED_REMOVAL:
default:
DeviceCollectionFormatDeviceText(
(PDEVICE_COLLECTION) VetoedRemovalCollection,
0,
szFormat,
SIZECHARS(szTitle),
szTitle
);
break;
}
MessageBox(NULL, szMessage, szTitle, MB_OK | MB_ICONEXCLAMATION | MB_SETFOREGROUND | MB_TOPMOST);
if (hVetoEvent) {
CloseHandle(hVetoEvent);
}
return TRUE;
}
void
DisplayDriverBlockBalloon(
IN PDEVICE_COLLECTION blockedDriverCollection
)
{
HRESULT hr;
TCHAR szMessage[NOTIFYICONDATA_SZINFO]; // same size as NOTIFYICONDATA.szInfo
TCHAR szFormat[NOTIFYICONDATA_SZINFO]; // same size as NOTIFYICONDATA.szInfo
TCHAR szTitle[NOTIFYICONDATA_SZINFOTITLE]; // same size as NOTIFYICONDATA.szInfoTitle
HICON hicon = NULL;
HANDLE hShellReadyEvent = NULL;
INT ShellReadyEventCount = 0;
GUID guidDB, guidID;
HAPPHELPINFOCONTEXT hAppHelpInfoContext = NULL;
PTSTR Buffer;
ULONG BufferSize;
if (!LoadString(hHotPlug, IDS_BLOCKDRIVER_TITLE, szTitle, SIZECHARS(szTitle))) {
//
// The machine is so low on memory that we can't even get the text strings, so
// just exit.
//
return;
}
szMessage[0] = TEXT('\0');
if (blockedDriverCollection->NumDevices == 1) {
//
// If we only have one device in the list then we will show specific
// information about this blocked driver as well as directly launching the
// help for this blocked driver.
//
if (SdbGetStandardDatabaseGUID(SDB_DATABASE_MAIN_DRIVERS, &guidDB) &&
DeviceCollectionGetGuid((PDEVICE_COLLECTION)blockedDriverCollection,
&guidID,
0)) {
hAppHelpInfoContext = SdbOpenApphelpInformation(&guidDB, &guidID);
Buffer = NULL;
if ((hAppHelpInfoContext) &&
((BufferSize = SdbQueryApphelpInformation(hAppHelpInfoContext,
ApphelpAppName,
NULL,
0)) != 0) &&
(Buffer = (PTSTR)LocalAlloc(LPTR, BufferSize)) &&
((BufferSize = SdbQueryApphelpInformation(hAppHelpInfoContext,
ApphelpAppName,
Buffer,
BufferSize)) != 0)) {
if (LoadString(hHotPlug, IDS_BLOCKDRIVER_FORMAT, szFormat, SIZECHARS(szFormat)) &&
(lstrlen(szFormat) + lstrlen(Buffer) < NOTIFYICONDATA_SZINFO)) {
//
// The app name and format string will fit into the buffer so
// use the format for the balloon message.
//
_snwprintf(szMessage,
SIZECHARS(szMessage),
szFormat,
Buffer);
} else {
//
// The app name is too large to be formated int he balloon
// message, so just show the app name.
//
lstrcpyn(szMessage, Buffer, SIZECHARS(szMessage));
}
}
if (Buffer) {
LocalFree(Buffer);
}
}
}
if (szMessage[0] == TEXT('\0')) {
//
// We either have more than one driver, or an error occured while trying
// to access the specific information about the one driver we received,
// so just show the generic message.
//
if (!LoadString(hHotPlug, IDS_BLOCKDRIVER_MESSAGE, szMessage, SIZECHARS(szMessage))) {
//
// The machine is so low on memory that we can't even get the text strings, so
// just exit.
//
return;
}
}
hicon = (HICON)LoadImage(hHotPlug,
MAKEINTRESOURCE(IDI_BLOCKDRIVER),
IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON),
0
);
//
// Make sure the shell is up and running so we can display the balloon.
//
while ((hShellReadyEvent = OpenEvent(SYNCHRONIZE, FALSE, TEXT("ShellReadyEvent"))) == NULL) {
//
// Sleep for 1 second and then try again.
//
Sleep(5000);
if (ShellReadyEventCount++ > 120) {
//
// We have been waiting for the shell for 10 minutes and it still
// is not around.
//
break;
}
}
if (hShellReadyEvent) {
WaitForSingleObject(hShellReadyEvent, INFINITE);
CloseHandle(hShellReadyEvent);
if (SUCCEEDED(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE))) {
IUserNotification *pun;
hr = CoCreateInstance(CLSID_UserNotification,
NULL,
CLSCTX_INPROC_SERVER,
IID_IUserNotification,
(void**)&pun);
if (SUCCEEDED(hr)) {
pun->SetIconInfo(hicon, szTitle);
pun->SetBalloonInfo(szTitle, szMessage, NIIF_WARNING);
//
// Try once for 20 seconds
//
pun->SetBalloonRetry((20 * 1000), -1, 0);
hr = pun->Show(NULL, 0);
//
// if hr is S_OK then user clicked on the balloon, if it is ERROR_CANCELLED
// then the balloon timedout.
//
if (hr == S_OK) {
if (blockedDriverCollection->NumDevices == 1) {
//
// If we only have one device in the list then just
// launch the help for that blocked driver.
//
BufferSize = SdbQueryApphelpInformation(hAppHelpInfoContext,
ApphelpHelpCenterURL,
NULL,
0);
if (BufferSize && (Buffer = (PTSTR)LocalAlloc(LPTR, BufferSize + (lstrlen(TEXT("HELPCTR.EXE -url ")) * sizeof(TCHAR))))) {
lstrcpy(Buffer, TEXT("HELPCTR.EXE -url "));
BufferSize = SdbQueryApphelpInformation(hAppHelpInfoContext,
ApphelpHelpCenterURL,
(PVOID)&Buffer[lstrlen(TEXT("HELPCTR.EXE -url "))],
BufferSize);
ShellExecute(NULL,
TEXT("open"),
TEXT("HELPCTR.EXE"),
Buffer,
NULL,
SW_SHOWNORMAL);
LocalFree(Buffer);
}
} else {
//
// We have more than one device in the list so launch
// the summary blocked driver page.
//
ShellExecute(NULL,
TEXT("open"),
TEXT("HELPCTR.EXE"),
TEXT("HELPCTR.EXE -url hcp://services/centers/support?topic=hcp://system/sysinfo/sysHealthInfo.htm"),
NULL,
SW_SHOWNORMAL
);
}
}
pun->Release();
}
CoUninitialize();
}
}
if (hicon) {
DestroyIcon(hicon);
}
if (hAppHelpInfoContext) {
SdbCloseApphelpInformation(hAppHelpInfoContext);
}
}
| [
"112426112@qq.com"
] | 112426112@qq.com |
2c3d8858a1f2fde674f41b8fda7c8976241306e7 | 5ac19d80b92609cd3506220675ec45088d92441e | /utils/sim_robots/tribot/tribot.cpp | 97d188f6b26dc886fdd13663241383d16ba5a722 | [] | no_license | pmanoonpong/gorobots_edu | 3d5dc739a3058819fa6e5976c9041b07c944a616 | ee904c0e6c0773490c2d51229a15d00652a2472e | refs/heads/master | 2023-05-25T13:30:37.175280 | 2023-05-19T15:49:37 | 2023-05-19T15:49:37 | 42,652,094 | 3 | 8 | null | 2015-10-02T08:33:08 | 2015-09-17T11:21:12 | null | UTF-8 | C++ | false | false | 3,889 | cpp | #include "tribot.h"
#include <math.h>
#include "toolbox.h"
#include <ode_robots/primitive.h>
namespace lpzrobots {
/**
* Constructor
*/
Tribot::Tribot(const OdeHandle& odeHandle,
const OsgHandle& osgHandle,
const TribotConfig& config,
const std::string& name)
: OdeRobot(odeHandle, osgHandle, name, "1.0"), conf(config)
{
}
Tribot::~Tribot()
{
}
void Tribot::placeIntern(const osg::Matrix& pose)
{
osg::Matrix initialPose;
initialPose = osg::Matrix::translate(osg::Vec3(0, 0, conf.wheelRadius) * pose);
create(initialPose);
}
enum Side {
left,
right
};
Primitive * Tribot::createWheel(int side, const osg::Matrix& pose) {
Primitive* lWheel = new Cylinder(conf.wheelRadius, conf.wheelHeight);
lWheel->setTexture("Images/chess.rgb");
lWheel->init(odeHandle, conf.wheelMass, osgHandle);
double transX = conf.bodyRadius + conf.wheelHeight / 2.0;
if(side == 1) {
transX *= -1.;
}
osg::Matrix lWheelPose =
osg::Matrix::rotate(M_PI / 2.0, 0, 1, 0) *
osg::Matrix::translate(transX, .0, .0) *
pose;
lWheel->setPose(lWheelPose);
objects.push_back(lWheel);
return lWheel;
}
void Tribot::createMotor(std::string name, HingeJoint* joint)
{
auto motor = std::make_shared<AngularMotor1Axis>(odeHandle,
joint,
conf.wheelMotorPower);
motor->setBaseName(name);
motor->setVelovityFactor(conf.wheelMotorMaxSpeed);
addSensor(motor);
addMotor(motor);
}
double Tribot::getWheelToWorldAngle() {
Position left = lWheel->getPosition().toPosition();
Position right = rWheel->getPosition().toPosition();
return toolbox::trimRadian(atan2(left.x - right.x, left.y - right.y) - (M_PI / 2));
}
void Tribot::create(const osg::Matrix& pose)
{
// Set the body type
Primitive* body = new Cylinder(conf.bodyRadius, conf.bodyHeight);
body->setTexture("Images/purple_velour.jpg");
body->init(odeHandle, conf.bodyMass, osgHandle);
body->setPose(pose);
objects.push_back(body);
double noseRadius = 0.1;
double noseHeight = 0.2;
double noseMass = 0.000001;
Primitive* nose = new Cylinder(noseRadius, noseHeight);
nose->setTexture("Images/wood.jpg");
nose->init(odeHandle, noseMass, osgHandle);
double transY = conf.bodyRadius + noseHeight / 2;
osg::Matrix nosePose =
osg::Matrix::rotate(M_PI / 2.0, 0, 1, 0) *
osg::Matrix::translate(.0, transY, conf.bodyHeight / 2) *
pose;
nose->setPose(nosePose);
objects.push_back(nose);
auto* noseJoint = new FixedJoint(body,
nose,
nose->getPosition());
noseJoint->init(odeHandle, osgHandle);
joints.push_back(noseJoint);
// Left Wheel
lWheel = createWheel(0, pose);
auto* bodyLeftWheelJoint = new HingeJoint(body,
lWheel,
lWheel->getPosition(),
Axis(0,0,1) * lWheel->getPose());
bodyLeftWheelJoint->init(odeHandle, osgHandle);
joints.push_back(bodyLeftWheelJoint);
// Right Wheel
rWheel = createWheel(1, pose);
auto* bodyRightWheelJoint = new HingeJoint(body,
rWheel,
rWheel->getPosition(),
Axis(0,0,1) * rWheel->getPose());
bodyRightWheelJoint->init(odeHandle, osgHandle);
joints.push_back(bodyRightWheelJoint);
// Motors
createMotor(std::string("left motor"), bodyLeftWheelJoint);
createMotor(std::string("right motor"), bodyRightWheelJoint);
}
}
| [
"poramate@manoonpong.com"
] | poramate@manoonpong.com |
0828be47c4da85e8590704fe85928482805e1f92 | 1f63dde39fcc5f8be29f2acb947c41f1b6f1683e | /Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/test/video_renderer.h | b9c9d857f3a10c542526e805b355a0e9716fba29 | [
"MIT",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"GPL-1.0-or-later",
"LicenseRef-scancode-takuya-ooura",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown",
"MS-LPL",
"LicenseRef-scancode-google-patent-license-webm"
] | permissive | koobonil/Boss2D | 09ca948823e0df5a5a53b64a10033c4f3665483a | e5eb355b57228a701495f2660f137bd05628c202 | refs/heads/master | 2022-10-20T09:02:51.341143 | 2019-07-18T02:13:44 | 2019-07-18T02:13:44 | 105,999,368 | 7 | 2 | MIT | 2022-10-04T23:31:12 | 2017-10-06T11:57:07 | C++ | UTF-8 | C++ | false | false | 1,540 | h | /*
* Copyright (c) 2013 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef TEST_VIDEO_RENDERER_H_
#define TEST_VIDEO_RENDERER_H_
#include <stddef.h>
#include BOSS_WEBRTC_U_api__videosinkinterface_h //original-code:"api/videosinkinterface.h"
namespace webrtc {
class VideoFrame;
namespace test {
class VideoRenderer : public rtc::VideoSinkInterface<VideoFrame> {
public:
// Creates a platform-specific renderer if possible, or a null implementation
// if failing.
static VideoRenderer* Create(const char* window_title, size_t width,
size_t height);
// Returns a renderer rendering to a platform specific window if possible,
// NULL if none can be created.
// Creates a platform-specific renderer if possible, returns NULL if a
// platform renderer could not be created. This occurs, for instance, when
// running without an X environment on Linux.
static VideoRenderer* CreatePlatformRenderer(const char* window_title,
size_t width, size_t height);
virtual ~VideoRenderer() {}
protected:
VideoRenderer() {}
};
} // namespace test
} // namespace webrtc
#endif // TEST_VIDEO_RENDERER_H_
| [
"slacealic@nate.com"
] | slacealic@nate.com |
a33f180b8616a9c49b02a4c34b97492350d9186b | 00f964ab109f17423617037fe48ab2d823bcde2b | /src/linklayer/ieee80211/mgmt/Ieee80211MgmtAPBase.h | d5654c9cc1ed3cbd675e981646ea0dfe621c820d | [] | no_license | PASER/Simulation-INETMANET | 2c18bc6d076d425a6660ecea699df5ae80f73273 | 47c30f967ce6135c4e07399ecfad32590348f1d3 | refs/heads/master | 2016-08-05T19:57:54.742163 | 2012-12-18T11:30:21 | 2012-12-18T11:30:21 | 7,203,912 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,603 | h | //
// Copyright (C) 2006 Andras Varga
//
// 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/>.
//
#ifndef IEEE80211_MGMT_AP_BASE_H
#define IEEE80211_MGMT_AP_BASE_H
#include "INETDefs.h"
#include "Ieee80211MgmtBase.h"
#include "NotificationBoard.h"
class EtherFrame;
/**
* Used in 802.11 infrastructure mode: abstract base class for management frame
* handling for access points (APs). This class extends Ieee80211MgmtBase
* with utility functions that are useful for implementing AP functionality.
*
* @author Andras Varga
*/
class INET_API Ieee80211MgmtAPBase : public Ieee80211MgmtBase
{
protected:
bool hasRelayUnit;
bool convertToEtherFrameFlag;
protected:
virtual int numInitStages() const {return 2;}
virtual void initialize(int);
/**
* Utility function for APs: sends back a data frame we received from a
* STA to the wireless LAN, after tweaking fromDS/toDS bits and shuffling
* addresses as needed.
*/
virtual void distributeReceivedDataFrame(Ieee80211DataFrame *frame);
/**
* Utility function: converts EtherFrame to Ieee80211Frame. This is needed
* because MACRelayUnit which we use for LAN bridging functionality deals
* with EtherFrames.
*/
virtual Ieee80211DataFrame *convertFromEtherFrame(EtherFrame *ethframe);
/**
* Utility function: converts Ieee80211Frame to EtherFrame. This is needed
* because MACRelayUnit which we use for LAN bridging functionality deals
* with EtherFrames.
*/
virtual EtherFrame *convertToEtherFrame(Ieee80211DataFrame *frame);
/**
* Utility function: send a frame to upperLayerOut.
* If convertToEtherFrameFlag is true, converts the given frame to EtherFrame, deleting the
* original frame, and send the converted frame.
* This function is needed for LAN bridging functionality:
* MACRelayUnit deals with EtherFrames.
*/
virtual void sendToUpperLayer(Ieee80211DataFrame *frame);
};
#endif
| [
"mohamad.sbeiti@tu-dortmund.de"
] | mohamad.sbeiti@tu-dortmund.de |
6757da01e74e002ef793e4127692a2af58a61d83 | 7a38ad59c85669ee2e6bdd186e7521736fa4b096 | /Luogu/P1158/P1158.cpp | 99582b7cea3e77de1400f76333e98763d96aef6d | [] | no_license | sxyugao/Codes | 815947450168e2a8c942c08473e46a208b0b2230 | ba7bfa7727ae90b7228de106ef5106ab275201bd | refs/heads/master | 2022-05-13T20:38:50.471599 | 2022-03-10T02:04:50 | 2022-03-10T02:04:50 | 148,995,649 | 14 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 862 | cpp | #include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
#define gc c = getchar()
int read(){
int x = 0, f = 1; char gc;
for(; !isdigit(c); gc) if(c == '-') f = -1;
for(; isdigit(c); gc) x = x * 10 + c - '0';
return x * f;
}
#undef gc
int sqr(int x){
return x * x;
}
struct Data {
int x, y, d1, d2;
bool operator<(const Data &b) const {
return d1 < b.d1;
}
} a[100005];
int f[100005];
int main(){
int x1 = read(), y1 = read(), x2 = read(), y2 = read();
int n = read();
for(int i = 1; i <= n; i++) {
a[i].x = read(), a[i].y = read();
a[i].d1 = sqr(x1 - a[i].x) + sqr(y1 - a[i].y);
a[i].d2 = sqr(x2 - a[i].x) + sqr(y2 - a[i].y);
}
sort(a + 1, a + n + 1);
for(int i = n; i; i--) f[i] = max(f[i + 1], a[i].d2);
int ans = 0x7fffffff;
for(int i = 1; i <= n; i++) ans = min(a[i].d1 + f[i + 1], ans);
printf("%d", ans);
}
| [
"sxyugao@qq.com"
] | sxyugao@qq.com |
65a972d4092050122c8cc4a0a55e325ee3efdeef | fc9e04fc6d9dae294c909124f294ce2b16d0cc0f | /FrameTL/cg.cpp | c0e1fc7f1c508b795bafc9aa45929a7fbdb2f759 | [
"MIT"
] | permissive | vogeldor/Marburg_Software_Library | 07c5546b5f6222f4ad3855c0667a185a7b710d34 | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | refs/heads/master | 2022-11-15T13:14:37.053345 | 2020-07-16T11:23:47 | 2020-07-16T11:23:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,290 | cpp | // implementation for steepest_descent.h
#include <cmath>
#include <set>
#include <utils/plot_tools.h>
#include <adaptive/apply.h>
#include <numerics/corner_singularity.h>
#include <frame_evaluate.h>
using std::set;
namespace FrameTL{
/*!
*/
template<class VALUE = double>
class Singularity1D_RHS_2
: public Function<1, VALUE>
{
public:
Singularity1D_RHS_2() {};
virtual ~Singularity1D_RHS_2() {};
VALUE value(const Point<1>& p,
const unsigned int component = 0) const
{
return -sin(3.*M_PI*p[0])*9.*M_PI*M_PI - 4.;
}
void vector_value(const Point<1> &p,
Vector<VALUE>& values) const { ; }
};
/*!
special function with steep gradients
near the right end of the interval
*/
template<class VALUE = double>
class Singularity1D_2
: public Function<1, VALUE>
{
public:
Singularity1D_2() {};
virtual ~Singularity1D_2() {};
VALUE value(const Point<1>& p,
const unsigned int component = 0) const
{
if (0. <= p[0] && p[0] < 0.5)
return -sin(3.*M_PI*p[0]) + 2.*p[0]*p[0];
if (0.5 <= p[0] && p[0] <= 1.0)
return -sin(3.*M_PI*p[0]) + 2.*(1-p[0])*(1-p[0]);
return 0.;
}
void vector_value(const Point<1> &p,
Vector<VALUE>& values) const { ; }
};
template <class PROBLEM>
void cg_SOLVE(const PROBLEM& P, const double epsilon,
InfiniteVector<double, typename PROBLEM::Index>& u_epsilon)
{
//typedef DSBasis<2,2> Basis1D;
typedef PBasis<2,2> Basis1D;
Point<2> origin;
origin[0] = 0.0;
origin[1] = 0.0;
CornerSingularity sing2D(origin, 0.5, 1.5);
CornerSingularityRHS singRhs(origin, 0.5, 1.5);
// Singularity1D_RHS_2<double> sing1D;
// Singularity1D_2<double> exactSolution1D;
unsigned int loops = 0;
const int jmax = 4;
typedef typename PROBLEM::Index Index;
double a_inv = P.norm_Ainv();
double kappa = P.norm_A()*a_inv;
double omega_i = a_inv*P.F_norm();
cout << "a_inv = " << a_inv << endl;
cout << "omega_i = " << omega_i << endl;
InfiniteVector<double, Index> xk, rk, zk, pk, Apk, help, f;
map<double,double> log_10_residual_norms;
map<double,double> degrees_of_freedom;
map<double,double> asymptotic;
map<double,double> time_asymptotic;
map<double,double> log_10_L2_error;
double eta = 0.1;
const double tol = 1.0e-6;
const int maxiter = 100;
// first (negative) residual
P.RHS(0., f);
APPLY_COARSE(P, xk, eta, rk, 1.0e-13, jmax, CDD1);
rk -= f;
const double normr0 = l2_norm_sqr(rk);
double normrk = normr0, rhok = 0, oldrhok = 0;
for (int iterations = 1; normrk/normr0 > tol*tol && iterations <= maxiter; iterations++) {
zk = rk;
rhok = rk * zk;
if (iterations == 1) // TODO: shift this case upwards!
pk = zk;
else
pk.sadd(rhok/oldrhok, zk);
APPLY_COARSE(P, pk, eta, Apk, 1.0e-13, jmax, CDD1);
//cout << pk << endl;
const double alpha = rhok/(pk*Apk);
xk.add(-alpha, pk);
rk.add(-alpha, Apk);
normrk = l2_norm_sqr(rk);
cout << "loop: " << iterations << ", " << "residual error = " << sqrt(normrk) << endl;
oldrhok = rhok;
eta *= 0.8;
cout << "eta = " << eta << endl;
u_epsilon = xk;
}
}
}
| [
"keding@mathematik.uni-marburg.de"
] | keding@mathematik.uni-marburg.de |
a4db55250373b69f7e250e95c67d1e5d8044385c | 0a9465576341cd55480de06914d023569f041b6a | /src/xcroscpp/include/ros/message.h | eedd2343da8d4504c6c412e175e72b2ce49a954f | [
"Unlicense"
] | permissive | dogchenya/xc-ros | 95751827e13627afdc186d02d3113b8b0d1e0560 | 43c8b773a552ea610bd03750c9c32d7732f8ea69 | refs/heads/main | 2023-06-11T04:05:44.994499 | 2021-06-30T12:22:44 | 2021-06-30T12:22:44 | 331,613,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,913 | h | #ifndef _XCROSCPP_MESSAGE_H_
#define _XCROSCPP_MESSAGE_H_
#include <map>
#include "ros/macros.h"
#include "ros/assert.h"
#include <string>
#include <string.h>
#include <boost/shared_ptr.hpp>
#include <boost/array.hpp>
#include <stdint.h>
#define ROSCPP_MESSAGE_HAS_DEFINITION
namespace xcros
{
typedef std::map<std::string, std::string> M_string;
/**
* \deprecated This base-class is deprecated in favor of a template-based serialization and traits system
*/
#if 0
class Message
{
public:
typedef boost::shared_ptr<Message> Ptr;
typedef boost::shared_ptr<Message const> ConstPtr;
Message()
{
}
virtual ~Message()
{
}
virtual const std::string __getDataType() const = 0;
virtual const std::string __getMD5Sum() const = 0;
virtual const std::string __getMessageDefinition() const = 0;
inline static std::string __s_getDataType() { ROS_BREAK(); return std::string(""); }
inline static std::string __s_getMD5Sum() { ROS_BREAK(); return std::string(""); }
inline static std::string __s_getMessageDefinition() { ROS_BREAK(); return std::string(""); }
virtual uint32_t serializationLength() const = 0;
virtual uint8_t *serialize(uint8_t *write_ptr, uint32_t seq) const = 0;
virtual uint8_t *deserialize(uint8_t *read_ptr) = 0;
uint32_t __serialized_length;
};
typedef boost::shared_ptr<Message> MessagePtr;
typedef boost::shared_ptr<Message const> MessageConstPtr;
#endif
#define SROS_SERIALIZE_PRIMITIVE(ptr, data) { memcpy(ptr, &data, sizeof(data)); ptr += sizeof(data); }
#define SROS_SERIALIZE_BUFFER(ptr, data, data_size) { if (data_size > 0) { memcpy(ptr, data, data_size); ptr += data_size; } }
#define SROS_DESERIALIZE_PRIMITIVE(ptr, data) { memcpy(&data, ptr, sizeof(data)); ptr += sizeof(data); }
#define SROS_DESERIALIZE_BUFFER(ptr, data, data_size) { if (data_size > 0) { memcpy(data, ptr, data_size); ptr += data_size; } }
} // namespace xcros
#endif | [
"xuchen@gs-robot.com"
] | xuchen@gs-robot.com |
e44da1c62883508cacb627ea358dad3f341c6527 | e33729122169652e176e337470d724ccf05be148 | /class and object-use of this pointer.cpp | 5db29552ebd0885d5ec918c3db06cf7de708ac0a | [] | no_license | asmitarabole07/AllCplusProgrammes | 0abd3bc8669d22ff06cc70633b06ea9986468af2 | 14ad8d4f9d5f2a4bc70c19669623882d2480be8c | refs/heads/main | 2023-07-02T23:41:39.325552 | 2021-08-11T05:29:55 | 2021-08-11T05:29:55 | 394,872,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 387 | cpp | #include <iostream>
using namespace std;
class base{
int a;
public:
void setdata(int a)
{
this->a=a; //this is a keyword which is a pointer which points to the object which invokes the member function
}
void getdata()
{
cout<<"The value of a is : "<<a;
}
};
int main()
{
base b;
b.setdata(4);
b.getdata();
return 0;
}
| [
"asmitarabole07@gmail.com"
] | asmitarabole07@gmail.com |
442735e49132ebdb2f34e99318334312a4b49a80 | 13e87bedfeecf62a2ee92f7dc81b010178910d47 | /CppPrimer/11/wcEx.cpp | 6451b65e4ec0e35db3cda4bf544f141e0df8f01f | [] | no_license | longlinht/SourcesFromBook | fc44e4a2f67bb4df3a6866280c562a82ed83b6bd | 6eea43041800e843a22d4bb0757222d8064b8716 | refs/heads/master | 2021-07-18T03:18:57.075712 | 2021-03-03T07:31:50 | 2021-03-03T07:31:50 | 61,864,811 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,464 | cpp | /*
* This file contains code from "C++ Primer, Fifth Edition", by Stanley B.
* Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the
* copyright and warranty notices given in that book:
*
* "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo."
*
*
* "The authors and publisher have taken care in the preparation of this book,
* but make no expressed or implied warranty of any kind and assume no
* responsibility for errors or omissions. No liability is assumed for
* incidental or consequential damages in connection with or arising out of the
* use of the information or programs contained herein."
*
* Permission is granted for this code to be used for educational purposes in
* association with the book, given proper citation if and when posted or
* reproduced.Any commercial use of this code requires the explicit written
* permission of the publisher, Addison-Wesley Professional, a division of
* Pearson Education, Inc. Send your request for permission, stating clearly
* what code you would like to use, and in what specific way, to the following
* address:
*
* Pearson Education, Inc.
* Rights and Permissions Department
* One Lake Street
* Upper Saddle River, NJ 07458
* Fax: (201) 236-3290
*/
#include <map>
using std::map;
#include <utility>
using std::pair; using std::make_pair;
#include <string>
using std::string;
#include <cstddef>
using std::size_t;
#include <iostream>
using std::cin; using std::cout; using std::endl;
int main()
{
// count number of times each word occurs in the input
map<string, size_t> word_count; // empty map from string to size_t
string word;
while (cin >> word)
++word_count.insert(make_pair(word, 0)).first->second;
for(map<string, size_t>::iterator it = word_count.begin();
it != word_count.end(); ++it) {
pair<const string, size_t> w = *it;
cout << w.first << " occurs " << w.second << " times" << endl;
}
// get iterator positioned on the first element
map<string, size_t>::const_iterator map_it = word_count.begin();
// for each element in the map
while (map_it != word_count.end()) {
// print the element key, value pairs
cout << map_it->first << " occurs "
<< map_it->second << " times" << endl;
++map_it; // increment iterator to denote the next element
}
return 0;
}
| [
"longlinht@gmail.com"
] | longlinht@gmail.com |
d6bd7375c7f2e9c56ff3e4e55834b21625edb7bd | d8cea15cbaa45293ffe8e23d13e4d0b173b70056 | /Ovepoch Origins/MPMissions/DayZ_Epoch_24.Napf/CONFIGS/MissionInit.hpp | c3ba5efa3ac7570ab3e4641430c5cd94f5a6ca29 | [] | no_license | quitanddead/DayZEpoch1Click | 89708d49ee021314498b6c593edb7c2af0d9e0a6 | fa5b514dcb97fa2c4d3a744b5e9c5950445fb7bb | refs/heads/master | 2020-04-03T09:03:10.489683 | 2015-04-16T03:43:45 | 2015-04-16T03:43:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | hpp | //Traders
#include "TRADERS\cfgServerTrader.hpp"
//Loot
#include "LOOT\CfgBuildingLoot.hpp"
//Base Mission Defines
#include "BaseDefines.hpp"
//Defines
#include "defines.hpp"
//RSCTITLES
#include "RcsTitles.hpp"
//Extra RC
#include "extra_rc.hpp"
//GroupManagement
//#include "GROUPMANAGEMENT\groupManagement.hpp"
//SnapBuild
//#include "SNAPBUILD\snappoints.hpp"
| [
"xerxesmmxii@gmail.com"
] | xerxesmmxii@gmail.com |
561f947b7c8bead5dbc00452a0855b99e5e413c4 | 4cec176d8248a827bc8b296859eea3b02cd1a974 | /TankWars/Source/TankWars/Private/TankAimingComponent.cpp | 531747f25e986bf53133bebc9b2ca0aa2f7e2186 | [
"Unlicense"
] | permissive | AlexanderJDupree/TankWars | 01bc6a2118b642007f8a9e8b5dc52ffaeac0b87c | ceca6acafff548d7471cb940122684eff39625da | refs/heads/master | 2021-05-06T01:16:13.780802 | 2018-02-19T17:57:49 | 2018-02-19T17:57:49 | 114,421,238 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,188 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "TankAimingComponent.h"
// Sets default values for this component's properties
UTankAimingComponent::UTankAimingComponent()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
void UTankAimingComponent::setBarrelReference(UStaticMeshComponent * barrelToSet)
{
barrel = barrelToSet;
}
// Called when the game starts
void UTankAimingComponent::BeginPlay()
{
Super::BeginPlay();
// ...
}
// Called every frame
void UTankAimingComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ...
}
void UTankAimingComponent::AimAt(FVector WorldSpaceAim)
{
auto CurrentTankName = GetOwner()->GetName();
auto BarrelLocation = barrel->GetComponentLocation().ToString();
UE_LOG(LogTemp, Warning, TEXT("%sa aiming at %s from %s"), *CurrentTankName, *WorldSpaceAim.ToString(), *BarrelLocation)
}
| [
"alexander.j.dupree@gmail.com"
] | alexander.j.dupree@gmail.com |
dd1326d0c66e1966298c8df3977a00c6b77a947a | 4e00d01e070812e4a04a66e970494bd8f82d6e87 | /Voxel_raycaster/Voxel_raycaster/GUIManager.cpp | e37f0ecdf8a691295f85ccd8dc238cc11d4fc9fb | [] | no_license | joschout/4D-Sparse-Voxel-Octree-Renderer | 7db88f6522def28a95b129ecd474710d62b52e58 | f0a61cf367d8c35157f7400ac10487dca373d92b | refs/heads/master | 2021-09-28T04:02:28.934818 | 2018-11-14T07:52:29 | 2018-11-14T07:52:29 | 47,188,750 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,482 | cpp | //#include "GUIManager.h"
//#include "ImGui/imgui_impl_glfw.h"
//#include <GLFW/glfw3.h>
//#include "util.h"
//#include "GLHandler.h"
//
//
//void GUIManager::setUp()
//{
// // Init GLFW system
// if (!glfwInit()) exit(EXIT_FAILURE);
// // Init window
// window = glfwCreateWindow(render_x, render_y, "Voxel Ray Caster", NULL, NULL);
// if (!window) { glfwTerminate();exit(EXIT_FAILURE); }
// glfwMakeContextCurrent(window);
// glfwSwapInterval(1);
// glfwSetKeyCallback(window, keyboardfunc);
//
// setupTexture(texid, render_context, renderdata);
//
// // Setup ImGui binding
// ImGui_ImplGlfw_Init(window, false);
// ImGuiIO& io = ImGui::GetIO();
// io.FontGlobalScale = 2.5;
//}
//
//
//void GUIManager::display(void)
//{
// ImGui_ImplGlfw_NewFrame();
//
//
// if (showImGuiInfoWindow) {
// ImGui::Begin("General info", &showImGuiInfoWindow);
// ImGui::Text("Data file: %s", datafile.c_str());
// ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
// ImGui::Text("Camera eye: x:%.3f, y:%.3f, z:%.3f", camera.eye[0], camera.eye[1], camera.eye[2]);
// ImGui::Text("Camera gaze: x:%.3f, y:%.3f, z:%.3f", camera.gaze[0], camera.gaze[1], camera.gaze[2]);
// switch (inputformat)
// {
// case OCTREE:
// ImGui::Text("Current renderer: %s", rendername.c_str());
// ImGui::Text("Octree: minPoint: x:%.3f, y:%.3f, z:%.3f", octree->min[0], octree->min[1], octree->min[2]);
// ImGui::Text("Octree: maxPoint: x:%.3f, y:%.3f, z:%.3f", octree->max[0], octree->max[1], octree->max[2]);
// ImGui::Text("Octree size (1 direction): %d", octree->gridlength);
// break;
// case GRID:
// ImGui::Text("Grid: minPoint: x:%.3f, y:%.3f, z:%.3f", grid->min[0], grid->min[1], grid->min[2]);
// ImGui::Text("Grid: maxPoint: x:%.3f, y:%.3f, z:%.3f", grid->max[0], grid->max[1], grid->max[2]);
// ImGui::Text("Grid size (1 direction): %d", grid->gridlength);
// break;
// case TREE4D:
// ImGui::Text("Current renderer: %s", rendername.c_str());
// ImGui::Text("Tree4D: minPoint: x:%.3f, y:%.3f, z:%.3f, t:%.3f", tree4D->min[0], tree4D->min[1], tree4D->min[2], tree4D->min[3]);
// ImGui::Text("Tree4D: maxPoint: x:%.3f, y:%.3f, z:%.3f, t:%.3f", tree4D->max[0], tree4D->max[1], tree4D->max[2], tree4D->max[3]);
// ImGui::Text("Tree4D size (1 direction): %d", tree4D->gridsize_T);
// ImGui::Text("Time step: %.3f", camera_controller.time_step);
// ImGui::Text("Time point: %.3f", camera_controller.time_point);
// ImGui::Text("Min time for pixel: %.3f", tt_min);
// ImGui::Text("Max time for pixel: %.3f", tt_max);
//
//
// ImGui::SliderFloat("time", &(camera_controller.time_point), tree4D->min[3], tree4D->max[3], "%.3f", 1);
// ImGui::SliderFloat("eye movement speed", &(camera_controller.camera_eye_movement_speed), 0, 10, "%.1f", 1);
// ImGui::SliderFloat("gaze movement speed", &(camera_controller.camera_gaze_movement_speed), 0, 10, "%.1f", 1);
// ImGui::SliderFloat("time movement speed", &(camera_controller.time_movement_speed), 0, 10, "%.1f", 1);
// if (ImGui::Button("Depth renderer")) {
// rmanager4D.setCurrentRenderer("depth");
// }
// if (ImGui::Button("#timepoints/pixel renderer")) {
// rmanager4D.setCurrentRenderer("timepoint");
// }
// if (ImGui::Button("write #timepoints/pixel image")) {
// writeTimePointRenderImage();
// }
// if (ImGui::Button("write tree structure")) {
// printTree4D2ToFile_alternate(tree4D, "nodeStructure_tree4d.txt");
// }
//
// break;
// }
// if (ImGui::Button("Reset camera")) {
// initCamera(camera);
// }
// ImGui::End();
// }
//
// if (showImGuiKeyboardHints) {
// ImGui::Begin("Keyboard hints", &showImGuiKeyboardHints);
// ImGui::Text("Arrow Left: Camera eye X - 0.2");
// ImGui::Text("Arrow Right: Camera eye X + 0.2");
// ImGui::Text("Arrow Down: Camera eye Y - 0.2");
// ImGui::Text("Arrow Up: Camera eye Y + 0.2");
// ImGui::Text("Keypad - : Camera eye Z - 0.2");
// ImGui::Text("keypad +: Camera eye Z + 0.2");
// ImGui::Text("W/S: Camera gaze X + 0.2 /- 0.2");
// // ImGui::Text("S: Camera gaze X - 0.2");
// ImGui::Text("A/D: Camera gaze Y + 0.2 /- 0.2");
// // ImGui::Text("D: Camera gaze Y - 0.2");
// ImGui::Text("R/F: Camera gaze Z + 0.2/- 0.2");
// // ImGui::Text("F: Camera gaze Z - 0.2");
// ImGui::End();
// }
//
//
// int width, height;
// glfwGetFramebufferSize(window, &width, &height);
// glViewport(0, 0, width, height);
// glClear(GL_COLOR_BUFFER_BIT);
//
// Timer t = Timer();
//
// camera.computeUVW();
//
// memset(renderdata, 0, render_context.n_x*render_context.n_y * 4);
//
// switch (inputformat)
// {
// case OCTREE:
// rendername = rmanager.getCurrentRenderer()->name;
// rmanager.getCurrentRenderer()->Render(render_context, octree, renderdata);
// break;
// case GRID:
// gridRenderer.Render(render_context, grid, renderdata);
// break;
// case TREE4D:
// rendername = rmanager4D.getCurrentRenderer()->name;
// rmanager4D.getCurrentRenderer()->Render(render_context, tree4D, renderdata, camera_controller.time_point);
// break;
// }
//
//
// generateTexture(texid, render_context, renderdata);
// drawFullsizeQuad();
//
// //TwDraw();
// //glPopMatrix();
// ImGui::Render();
// glfwSwapBuffers(window);
//
// std::stringstream out;
// out << "Voxel Renderer | Rendertime: " << t.getTimeMilliseconds() << " ms | FPS: " << 1000 / t.getTimeMilliseconds();
// std::string s = out.str();
// glfwSetWindowTitle(window, s.c_str());
//} | [
"jonas.schouterden@student.kuleuven.be"
] | jonas.schouterden@student.kuleuven.be |
e5a10bcf841c1ba21eaebc88904b4d8e39ff0c29 | 64e4fabf9b43b6b02b14b9df7e1751732b30ad38 | /src/chromium/gen/gen_combined/components/ui_devtools/base_string_adapter.h | 8171e11c9697d57e180163545919e6d583eff9f8 | [
"BSD-3-Clause"
] | permissive | ivan-kits/skia-opengl-emscripten | 8a5ee0eab0214c84df3cd7eef37c8ba54acb045e | 79573e1ee794061bdcfd88cacdb75243eff5f6f0 | refs/heads/master | 2023-02-03T16:39:20.556706 | 2020-12-25T14:00:49 | 2020-12-25T14:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,507 | h | // This file is generated by Parser_h.template.
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ui_devtools_protocol_BASE_STRING_ADAPTER_H
#define ui_devtools_protocol_BASE_STRING_ADAPTER_H
#include <memory>
#include <string>
#include <vector>
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ref_counted_memory.h"
#include "base/strings/string_number_conversions.h"
#include "components/ui_devtools/devtools_export.h"
namespace base {
class Value;
}
namespace ui_devtools {
namespace protocol {
class Value;
using String = std::string;
using ProtocolMessage = std::string;
class UI_DEVTOOLS_EXPORT StringBuilder {
public:
StringBuilder();
~StringBuilder();
void append(const String&);
void append(char);
void append(const char*, size_t);
String toString();
void reserveCapacity(size_t);
private:
std::string string_;
};
class UI_DEVTOOLS_EXPORT StringUtil {
public:
static String substring(const String& s, unsigned pos, unsigned len) {
return s.substr(pos, len);
}
static String fromInteger(int number) { return base::NumberToString(number); }
static String fromDouble(double number) {
String s = base::NumberToString(number);
if (!s.empty()) { // .123 -> 0.123; -.123 -> -0.123 for valid JSON.
if (s[0] == '.')
s.insert(/*index=*/ 0, /*count=*/ 1, /*ch=*/ '0');
else if (s[0] == '-' && s.size() >= 2 && s[1] == '.')
s.insert(/*index=*/ 1, /*count=*/ 1, /*ch=*/ '0');
}
return s;
}
static double toDouble(const char* s, size_t len, bool* ok) {
double v = 0.0;
*ok = base::StringToDouble(std::string(s, len), &v);
return *ok ? v : 0.0;
}
static size_t find(const String& s, const char* needle) {
return s.find(needle);
}
static size_t find(const String& s, const String& needle) {
return s.find(needle);
}
static const size_t kNotFound = static_cast<size_t>(-1);
static void builderAppend(StringBuilder& builder, const String& s) {
builder.append(s);
}
static void builderAppend(StringBuilder& builder, char c) {
builder.append(c);
}
static void builderAppend(StringBuilder& builder, const char* s, size_t len) {
builder.append(s, len);
}
static void builderAppendQuotedString(StringBuilder& builder,
const String& str);
static void builderReserve(StringBuilder& builder, unsigned capacity) {
builder.reserveCapacity(capacity);
}
static String builderToString(StringBuilder& builder) {
return builder.toString();
}
static std::unique_ptr<Value> parseMessage(const std::string& message, bool binary);
static ProtocolMessage jsonToMessage(String message);
static ProtocolMessage binaryToMessage(std::vector<uint8_t> message);
static String fromUTF8(const uint8_t* data, size_t length) {
return std::string(reinterpret_cast<const char*>(data), length);
}
static String fromUTF16(const uint16_t* data, size_t length);
static const uint8_t* CharactersLatin1(const String& s) { return nullptr; }
static const uint8_t* CharactersUTF8(const String& s) {
return reinterpret_cast<const uint8_t*>(s.data());
}
static const uint16_t* CharactersUTF16(const String& s) { return nullptr; }
static size_t CharacterCount(const String& s) { return s.size(); }
};
// A read-only sequence of uninterpreted bytes with reference-counted storage.
class UI_DEVTOOLS_EXPORT Binary {
public:
Binary(const Binary&);
Binary();
~Binary();
const uint8_t* data() const { return bytes_->front(); }
size_t size() const { return bytes_->size(); }
scoped_refptr<base::RefCountedMemory> bytes() const { return bytes_; }
String toBase64() const;
static Binary fromBase64(const String& base64, bool* success);
static Binary fromRefCounted(scoped_refptr<base::RefCountedMemory> memory);
static Binary fromVector(std::vector<uint8_t> data);
static Binary fromString(std::string data);
static Binary fromSpan(const uint8_t* data, size_t size);
private:
explicit Binary(scoped_refptr<base::RefCountedMemory> bytes);
scoped_refptr<base::RefCountedMemory> bytes_;
};
std::unique_ptr<Value> toProtocolValue(const base::Value* value, int depth);
std::unique_ptr<base::Value> toBaseValue(Value* value, int depth);
} // namespace ui_devtools
} // namespace protocol
#endif // !defined(ui_devtools_protocol_BASE_STRING_ADAPTER_H)
| [
"trofimov_d_a@magnit.ru"
] | trofimov_d_a@magnit.ru |
995252deb9c2a83512d7702753ec3f7994fe4d44 | dc5bedc7b44c70d4fd6fb5cef7d823f01d94060b | /C++/Praktikum-2/Soal-2/PremiumUser.cpp | 7d1efd1ef8ab32d16443f05bac580d3ed15d028e | [] | no_license | pranagusriana/IF2210-OOP | 58bf64651299362f2b6a7ac7c8f8ed80a62ca565 | b8853d6177d44a493f6becb376e116adb8a9e612 | refs/heads/main | 2023-04-14T17:21:58.917699 | 2021-04-22T03:39:25 | 2021-04-22T03:39:25 | 335,897,801 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,750 | cpp | // Nama: Prana Gusriana
// NIM: 13519195
// Tanggal: Kamis, 25 Februari 2021
// File: PremiumUser.cpp
// Praktikum 2: Inheritance dan Polymorphism, Soal 2
#include "User.h"
#include "PremiumUser.h"
#include <iostream>
#include <cstring>
using namespace std;
//ctor, active = true, parameter: nama pengguna
PremiumUser::PremiumUser(char* nm): User(nm){
this->num_of_music_downloaded = 0;
this->active = true;
}
// cctor
PremiumUser::PremiumUser(const PremiumUser& u): User(u.name){
this->num_of_favourite_music = u.getNumOfFavouriteMusic();
this->music_list = new char*[1000];
for (int i = 0; i<this->num_of_favourite_music; i++){
this->music_list[i] = new char[strlen(u.music_list[i])];
strcpy(this->music_list[i], u.music_list[i]);
}
this->num_of_music_downloaded = u.num_of_music_downloaded;
this->active = u.active;
}
PremiumUser::~PremiumUser(){
}
// print kata-kata sbg. berikut: "Music Downloaded: <judul><endl>"
// Contoh:
// Music Downloaded: Loyal - Chris Brown, Lil Wayne, Tyga
//
// Jika akun premium tidak aktif, print: "Activate premium account to download music<endl>"
void PremiumUser::downloadMusic(char* judul_musik){
if(this->active){
this->num_of_music_downloaded++;
cout << "Music Downloaded: " << judul_musik << endl;
} else{
cout << "Activate premium account to download music" << endl;
}
}
void PremiumUser::inactivatePremium(){
this->active = false;
}
void PremiumUser::activatePremium(){
this->active = true;
}
int PremiumUser::getNumOfMusicDownloaded() const{
return this->num_of_music_downloaded;
}
// mengembalikan nilai active
bool PremiumUser::getPremiumStatus() const{
return this->active;
} | [
"pranagusriana@gmail.com"
] | pranagusriana@gmail.com |
d1c2ec6266a0c5eba56f1005ec890b44d69ca2c8 | c7405f0ebda6ff2228f1204a910e325439f0c361 | /filling_a_bottle.cpp | 614a935a565e523551e801abc2d84c8e7d58433c | [] | no_license | kuonanhong/ACM-ICPC-2 | d36b3a4c1509c770b2ccccb7cfd3db1c3ee0531f | b46428c7e2e220f39efa5acbfa11b69e5ea35fa1 | refs/heads/master | 2021-04-30T13:44:23.955501 | 2016-05-25T05:52:40 | 2016-05-25T05:52:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 929 | cpp | #include <iostream>
#include <algorithm>
using namespace std;
struct Stn
{
int x, y, len, vo;
Stn(){}
void gl()
{
len = x * x + y * y;
}
bool operator< (const Stn a) const
{
if (len != a.len)
return len < a.len;
else
return vo > a.vo;
}
};
Stn ary[1005];
int main(int argc, char const *argv[])
{
int n, v;
while (cin >> n >> v)
{
for (int i = 0; i < n; i++)
{
cin >> ary[i].x >> ary[i].y >> ary[i].vo;
ary[i].gl();
}
sort(ary, ary + n);
int cnt = 0;
int ans = 0;
for (int i = 0; i < n && cnt < v; i++)
{
cnt += ary[i].vo;
ans++;
}
if (cnt < v)
cout << "NO" << endl;
else
cout << ans << endl;
}
return 0;
}
/*
3 67
1 1 37
2 2 5
-2 -2 68
3 68
1 1 34
2 2 5
-2 -2 16
*/ | [
"xiong-yang@qq.com"
] | xiong-yang@qq.com |
94a35fe8a8908c1bcf4c2733ed3f1d312d15e7c8 | 4fee08e558e77d16ab915f629df74a0574709e8b | /cpsc585/Havok/Common/Base/Types/Geometry/Aabb/hkAabb.inl | c4b094304ef2d0bd6e2f9ecb990bf0d746cfc598 | [] | no_license | NinjaMeTimbers/CPSC-585-Game-Project | c6fe97818ffa69b26e6e4dce622079068f5831cc | 27a0ce3ef6daabb79e7bdfbe7dcd5635bafce390 | refs/heads/master | 2021-01-21T00:55:51.915184 | 2012-04-16T20:06:05 | 2012-04-16T20:06:05 | 3,392,986 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,965 | inl | /*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2011 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*/
#ifndef HK_DISABLE_MATH_CONSTRUCTORS
inline hkAabb::hkAabb(const hkVector4& min, const hkVector4& max)
: m_min(min), m_max(max)
{
}
#endif
hkBool32 hkAabb::overlaps( const hkAabb& other ) const
{
HK_ASSERT2(0x3f5578fc, isValid() || isEmpty(), "Invalid AABB in hkAabb::overlaps." );
HK_ASSERT2(0x76dd800a, other.isValid() || other.isEmpty(), "Invalid AABB in hkAabb::overlaps.");
hkVector4Comparison mincomp = m_min.lessEqual(other.m_max);
hkVector4Comparison maxcomp = other.m_min.lessEqual(m_max);
hkVector4Comparison both; both.setAnd( mincomp, maxcomp );
return both.allAreSet(hkVector4Comparison::MASK_XYZ);
}
hkBool32 hkAabb::overlapsUpdateSmallestNonExtraHitAabb( const hkAabb& other, hkAabb& smallestNonHitAabbInOut ) const
{
HK_ASSERT2(0x3f5578fc, isValid(), "Invalid AABB in hkAabb::overlaps." );
//HK_ASSERT2(0x76dd800a, other.isValid(), "Invalid AABB in hkAabb::overlaps.");
hkVector4Comparison mincomp = m_min.less(other.m_max);
hkVector4Comparison maxcomp = other.m_min.less(m_max);
hkVector4 newMax; newMax.setMin( smallestNonHitAabbInOut.m_max, other.m_min );
hkVector4 newMin; newMin.setMax( smallestNonHitAabbInOut.m_min, other.m_max );
hkVector4Comparison both; both.setAnd( mincomp, maxcomp );
smallestNonHitAabbInOut.m_min.setSelect( mincomp, smallestNonHitAabbInOut.m_min, newMin );
smallestNonHitAabbInOut.m_max.setSelect( maxcomp, smallestNonHitAabbInOut.m_max, newMax );
return both.allAreSet(hkVector4Comparison::MASK_XYZ);
}
bool hkAabb::contains(const hkAabb& other) const
{
hkVector4Comparison mincomp = m_min.lessEqual(other.m_min);
hkVector4Comparison maxcomp = other.m_max.lessEqual(m_max);
hkVector4Comparison both; both.setAnd( mincomp, maxcomp );
return both.allAreSet(hkVector4Comparison::MASK_XYZ);
}
hkBool32 hkAabb::containsPoint(const hkVector4& other) const
{
hkVector4Comparison mincomp = m_min.lessEqual(other);
hkVector4Comparison maxcomp = other.lessEqual(m_max);
hkVector4Comparison both; both.setAnd( mincomp, maxcomp );
return both.allAreSet(hkVector4Comparison::MASK_XYZ);
}
bool hkAabb::isEmpty() const
{
hkVector4Comparison comp = m_min.greaterEqual(m_max);
return comp.anyIsSet(hkVector4Comparison::MASK_XYZ);
}
void hkAabb::includePoint (const hkVector4& point)
{
m_min.setMin(m_min, point);
m_max.setMax(m_max, point);
}
void hkAabb::includeAabb (const hkAabb& aabb)
{
m_min.setMin(m_min, aabb.m_min);
m_max.setMax(m_max, aabb.m_max);
}
void hkAabb::setFull()
{
m_max = hkVector4::getConstant<HK_QUADREAL_MAX>();
m_min.setNeg<4>(hkVector4::getConstant<HK_QUADREAL_MAX>());
}
void hkAabb::setEmpty()
{
m_min = hkVector4::getConstant<HK_QUADREAL_MAX>();
m_max.setNeg<4>( m_min );
}
void hkAabb::getCenter( hkVector4& c ) const
{
hkVector4 g; g.setAdd( m_min, m_max );
c.setMul( hkVector4::getConstant<HK_QUADREAL_INV_2>(), g);
}
void hkAabb::getHalfExtents( hkVector4& he ) const
{
hkVector4 sub; sub.setSub( m_max, m_min );
he.setMul( hkVector4::getConstant<HK_QUADREAL_INV_2>(), sub );
}
void hkAabb::getVertex(int index, hkVector4& vertex) const
{
HK_ASSERT2(0xF7BD00CA, index >= 0 && index <= 7, "Index out-of-range");
hkVector4Comparison comp; comp.set((hkVector4Comparison::Mask)index);
vertex.setSelect(comp, m_max, m_min);
}
void hkAabb::expandBy( hkSimdRealParameter exp )
{
hkVector4 expansion; expansion.setAll(exp);
m_max.add(expansion);
m_min.sub(expansion);
}
void hkAabb::setExpandBy( const hkAabb& aabb, hkSimdRealParameter exp )
{
hkVector4 expansion; expansion.setAll(exp);
m_max.setAdd( aabb.m_max, expansion );
m_min.setSub( aabb.m_min, expansion );
}
hkBool32 hkAabb::equals(const hkAabb& aabb) const
{
hkVector4Comparison mi = aabb.m_min.equal(m_min);
hkVector4Comparison ma = aabb.m_max.equal(m_max);
hkVector4Comparison co; co.setAnd( mi, ma );
return co.allAreSet( hkVector4Comparison::MASK_XYZ );
}
void hkAabb::setIntersection(const hkAabb& aabb0, const hkAabb& aabb1)
{
m_min.setMax(aabb0.m_min, aabb1.m_min);
m_max.setMin(aabb0.m_max, aabb1.m_max);
}
inline void hkAabbUint32::setInvalid()
{
const int ma = 0x7fffffff;
// SNC warning workaround
hkUint32* minP = m_min;
hkUint32* maxP = m_max;
minP[0] = ma;
minP[1] = ma;
minP[2] = ma;
minP[3] = 0;
maxP[0] = 0;
maxP[1] = 0;
maxP[2] = 0;
maxP[3] = 0;
}
inline void hkAabbUint32::setInvalidY()
{
const int ma = 0x7fff0000;
hkUint32* minP = m_min;
hkUint32* maxP = m_max;
minP[1] = ma;
minP[2] = ma;
minP[3] = 0;
maxP[1] = 0;
maxP[2] = 0;
}
void hkAabbUint32::operator=( const hkAabbUint32& other )
{
hkMemUtil::memCpyOneAligned<sizeof(hkAabbUint32),16>( this, &other );
}
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20110913)
*
* Confidential Information of Havok. (C) Copyright 1999-2011
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"cdebavel@ucalgary.ca"
] | cdebavel@ucalgary.ca |
65cdf84c769bfe393ac06e1b3d03387d06bb89f4 | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/ThirdParty/PhysX/APEX_1.4/framework/include/autogen/BufferF32x3.h | 060a35eddf8a7e5f51e02e18b9d15ba4b74b3018 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 6,802 | 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-2017 NVIDIA Corporation. All rights reserved.
// This file was generated by NvParameterized/scripts/GenParameterized.pl
#ifndef HEADER_BufferF32x3_h
#define HEADER_BufferF32x3_h
#include "NvParametersTypes.h"
#ifndef NV_PARAMETERIZED_ONLY_LAYOUTS
#include "nvparameterized/NvParameterized.h"
#include "nvparameterized/NvParameterizedTraits.h"
#include "NvParameters.h"
#include "NvTraitsInternal.h"
#endif
namespace nvidia
{
namespace apex
{
#if PX_VC
#pragma warning(push)
#pragma warning(disable: 4324) // structure was padded due to __declspec(align())
#endif
namespace BufferF32x3NS
{
struct F32x3_Type;
struct VEC3_DynamicArray1D_Type
{
physx::PxVec3* buf;
bool isAllocated;
int32_t elementSize;
int32_t arraySizes[1];
};
struct F32x3_Type
{
float x;
float y;
float z;
};
struct ParametersStruct
{
VEC3_DynamicArray1D_Type data;
};
static const uint32_t checksum[] = { 0x458b554a, 0x7ed3e930, 0x0299ff33, 0x9d69c11b, };
} // namespace BufferF32x3NS
#ifndef NV_PARAMETERIZED_ONLY_LAYOUTS
class BufferF32x3 : public NvParameterized::NvParameters, public BufferF32x3NS::ParametersStruct
{
public:
BufferF32x3(NvParameterized::Traits* traits, void* buf = 0, int32_t* refCount = 0);
virtual ~BufferF32x3();
virtual void destroy();
static const char* staticClassName(void)
{
return("BufferF32x3");
}
const char* className(void) const
{
return(staticClassName());
}
static const uint32_t ClassVersion = ((uint32_t)0 << 16) + (uint32_t)0;
static uint32_t staticVersion(void)
{
return ClassVersion;
}
uint32_t version(void) const
{
return(staticVersion());
}
static const uint32_t ClassAlignment = 8;
static const uint32_t* staticChecksum(uint32_t& bits)
{
bits = 8 * sizeof(BufferF32x3NS::checksum);
return BufferF32x3NS::checksum;
}
static void freeParameterDefinitionTable(NvParameterized::Traits* traits);
const uint32_t* checksum(uint32_t& bits) const
{
return staticChecksum(bits);
}
const BufferF32x3NS::ParametersStruct& parameters(void) const
{
BufferF32x3* tmpThis = const_cast<BufferF32x3*>(this);
return *(static_cast<BufferF32x3NS::ParametersStruct*>(tmpThis));
}
BufferF32x3NS::ParametersStruct& parameters(void)
{
return *(static_cast<BufferF32x3NS::ParametersStruct*>(this));
}
virtual NvParameterized::ErrorType getParameterHandle(const char* long_name, NvParameterized::Handle& handle) const;
virtual NvParameterized::ErrorType getParameterHandle(const char* long_name, NvParameterized::Handle& handle);
void initDefaults(void);
protected:
virtual const NvParameterized::DefinitionImpl* getParameterDefinitionTree(void);
virtual const NvParameterized::DefinitionImpl* getParameterDefinitionTree(void) const;
virtual void getVarPtr(const NvParameterized::Handle& handle, void*& ptr, size_t& offset) const;
private:
void buildTree(void);
void initDynamicArrays(void);
void initStrings(void);
void initReferences(void);
void freeDynamicArrays(void);
void freeStrings(void);
void freeReferences(void);
static bool mBuiltFlag;
static NvParameterized::MutexType mBuiltFlagMutex;
};
class BufferF32x3Factory : public NvParameterized::Factory
{
static const char* const vptr;
public:
virtual void freeParameterDefinitionTable(NvParameterized::Traits* traits)
{
BufferF32x3::freeParameterDefinitionTable(traits);
}
virtual NvParameterized::Interface* create(NvParameterized::Traits* paramTraits)
{
// placement new on this class using mParameterizedTraits
void* newPtr = paramTraits->alloc(sizeof(BufferF32x3), BufferF32x3::ClassAlignment);
if (!NvParameterized::IsAligned(newPtr, BufferF32x3::ClassAlignment))
{
NV_PARAM_TRAITS_WARNING(paramTraits, "Unaligned memory allocation for class BufferF32x3");
paramTraits->free(newPtr);
return 0;
}
memset(newPtr, 0, sizeof(BufferF32x3)); // always initialize memory allocated to zero for default values
return NV_PARAM_PLACEMENT_NEW(newPtr, BufferF32x3)(paramTraits);
}
virtual NvParameterized::Interface* finish(NvParameterized::Traits* paramTraits, void* bufObj, void* bufStart, int32_t* refCount)
{
if (!NvParameterized::IsAligned(bufObj, BufferF32x3::ClassAlignment)
|| !NvParameterized::IsAligned(bufStart, BufferF32x3::ClassAlignment))
{
NV_PARAM_TRAITS_WARNING(paramTraits, "Unaligned memory allocation for class BufferF32x3");
return 0;
}
// Init NvParameters-part
// We used to call empty constructor of BufferF32x3 here
// but it may call default constructors of members and spoil the data
NV_PARAM_PLACEMENT_NEW(bufObj, NvParameterized::NvParameters)(paramTraits, bufStart, refCount);
// Init vtable (everything else is already initialized)
*(const char**)bufObj = vptr;
return (BufferF32x3*)bufObj;
}
virtual const char* getClassName()
{
return (BufferF32x3::staticClassName());
}
virtual uint32_t getVersion()
{
return (BufferF32x3::staticVersion());
}
virtual uint32_t getAlignment()
{
return (BufferF32x3::ClassAlignment);
}
virtual const uint32_t* getChecksum(uint32_t& bits)
{
return (BufferF32x3::staticChecksum(bits));
}
};
#endif // NV_PARAMETERIZED_ONLY_LAYOUTS
} // namespace apex
} // namespace nvidia
#if PX_VC
#pragma warning(pop)
#endif
#endif
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
9a4518ac912b4d952f12a047f1275ccbff9e8390 | e6bf17b3e658ae3684a3875f2db79fb7ae04b8b8 | /Infoarena/joben.cpp | 46bdd9950b426082931ed557aa50937ca7ce1976 | [] | no_license | stefdasca/CompetitiveProgramming | 8e16dc50e33b309c8802b99da57b46ee98ae0619 | 0dbabcc5fe75177f61d232d475b99e4dbd751502 | refs/heads/master | 2023-07-26T15:05:30.898850 | 2023-07-09T08:47:52 | 2023-07-09T08:47:52 | 150,778,979 | 37 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 643 | cpp | #include<bits/stdc++.h>
using namespace std;
ifstream f("joben.in");
ofstream g("joben.out");
int t,fr[27],fr2[27];
char c1[100002];
int main()
{
f>>t;
for(;t;t--)
{
f>>c1;
int l=strlen(c1);
for(int i=0;i<l;++i)
fr[c1[i]-'a']++;
f>>c1;
for(int i=0;i<l;++i)
fr2[c1[i]-'a']++;
sort(fr,fr+26);
sort(fr2,fr2+26);
bool ok=1;
for(int i=0;i<=25;fr[i]=0,fr2[i]=0,++i)
if(fr[i]!=fr2[i])
ok=0;
if(ok==0)
g<<"NU"<<'\n';
else
g<<"DA"<<'\n';
}
}
| [
"noreply@github.com"
] | stefdasca.noreply@github.com |
33b5e87598be93a19c680f5f5916b9e1b5d16e1f | 5856af8487bad60faf4556775df63528bb206aa8 | /Code/UI/ColorRampComp.cpp | 6f1088f8d3cfd2aed7b5c5326d56135752aa3e47 | [
"MIT"
] | permissive | yorung/fastbirdEngine | 151ddb35cc4c9ee59ba90cd574df98d176e82d86 | eca26d339357a23eaee8416a3fc169a267abc764 | refs/heads/master | 2021-01-15T14:37:59.447624 | 2015-08-31T00:26:41 | 2015-08-31T00:26:41 | 29,778,951 | 0 | 0 | null | 2015-01-24T14:24:42 | 2015-01-24T14:24:41 | null | UTF-8 | C++ | false | false | 4,860 | cpp | #include <UI/StdAfx.h>
#include <UI/ColorRampComp.h>
#include <UI/Button.h>
#include <UI/StaticText.h>
using namespace fastbird;
ColorRampComp::ColorRampComp()
{
mUIObject = gFBEnv->pEngine->CreateUIObject(false, GetRenderTargetSize());
mUIObject->mOwnerUI = this;
mUIObject->mTypeString = ComponentType::ConvertToString(GetType());
}
ColorRampComp::~ColorRampComp()
{
}
void ColorRampComp::GatherVisit(std::vector<IUIObject*>& v)
{
if (!mVisibility.IsVisible())
return;
v.push_back(mUIObject);
__super::GatherVisit(v);
}
bool ColorRampComp::SetProperty(UIProperty::Enum prop, const char* val)
{
switch (prop)
{
case UIProperty::COLOR_RAMP_VALUES:
{
SetColorRampValues(val);
return true;
}
}
return __super::SetProperty(prop, val);
}
bool ColorRampComp::GetProperty(UIProperty::Enum prop, char val[], unsigned bufsize, bool notDefaultOnly)
{
switch (prop)
{
case UIProperty::COLOR_RAMP_VALUES:
{
GetColorRampValues(val, bufsize, 6);
return true;
}
}
return __super::GetProperty(prop, val, bufsize, notDefaultOnly);
}
void ColorRampComp::SetColorRampValues(const char* values)
{
if (!values || strlen(values) == 0)
{
return;
}
auto strs = Split(values, ", ");
if (strs.size() < 2)
{
Log("void ColorRampComp::SetColorRampValues(const char* values) : 'values' should have at least two values.");
assert(0);
return;
}
std::vector<float> ratios;
for (unsigned i = 0; i < strs.size(); i++)
{
ratios.push_back(StringConverter::parseReal(strs[i]));
}
SetColorRampValuesFloats(ratios);
}
void ColorRampComp::GetColorRampValues(char val[], unsigned bufsize, int precision)
{
std::vector<float> values;
GetColorRampValuesFloats(values);
std::string strValues;
int i = 0;
for (auto val : values)
{
strValues += StringConverter::toString(val, precision);
if (i != values.size() - 1)
{
strValues += ",";
}
}
strcpy_s(val, bufsize, strValues.c_str());
}
void ColorRampComp::GetColorRampValuesFloats(std::vector<float>& values)
{
values.clear();
float prevXnpos = -1;
for (unsigned i = 0; i < mBars.size(); i++)
{
auto& npos = mBars[i]->GetNPos();
float xnpos = npos.x;
if (prevXnpos != -1)
xnpos -= prevXnpos;
values.push_back(xnpos);
prevXnpos = npos.x;
}
values.push_back(1.0f - prevXnpos);
}
void ColorRampComp::SetColorRampValuesFloats(const std::vector<float>& values)
{
RemoveAllChild();
mBars.clear();
mTexts.clear();
float prevXPos = -1;
for (unsigned i = 0; i < values.size() - 1; i++)
{
float ratio = values[i];
float xPos = ratio;
if (prevXPos != -1)
{
xPos += prevXPos;
}
auto bar = AddChild(xPos, 0.5f, 0.05f, 1.0f, ComponentType::Button);
bar->SetRuntimeChild(true);
mBars.push_back((Button*)bar);
bar->ModifySize(Vec2I(0, -10));
bar->SetAlign(ALIGNH::CENTER, ALIGNV::MIDDLE);
bar->SetProperty(UIProperty::TEXTUREATLAS, "es/textures/ui.xml");
bar->SetProperty(UIProperty::REGION, "BarComp");
bar->SetProperty(UIProperty::HOVER_IMAGE, "BarCompHover");
bar->SetProperty(UIProperty::DRAGABLE, "1, 0");
float centerXPos;
if (prevXPos == -1)
{
centerXPos = ratio * .5f;
}
else
{
centerXPos = prevXPos + ratio * .5f;
}
auto text = AddChild(centerXPos, 0.5f, 1, 1, ComponentType::StaticText);
text->SetRuntimeChild(true);
text->SetSize(Vec2I(50, 20));
text->SetProperty(UIProperty::TEXT_ALIGN, "center");
text->SetAlign(ALIGNH::CENTER, ALIGNV::MIDDLE);
char buf[255];
sprintf_s(buf, "%d", (int)(ratio * 100));
text->SetText(AnsiToWide(buf));
mTexts.push_back((StaticText*)text);
prevXPos = xPos;
}
float ratio = values.back();
float centerXPos = prevXPos + ratio * .5f;
auto text = AddChild(centerXPos, 0.5f, 1, 1, ComponentType::StaticText);
text->SetRuntimeChild(true);
text->SetSize(Vec2I(50, 20));
text->SetProperty(UIProperty::TEXT_ALIGN, "center");
text->SetAlign(ALIGNH::CENTER, ALIGNV::MIDDLE);
char buf[255];
sprintf_s(buf, "%d", (int)(ratio * 100));
text->SetText(AnsiToWide(buf));
mTexts.push_back((StaticText*)text);
}
void ColorRampComp::OnChildHasDragged()
{
if (mBars.empty())
return;
assert(mBars.size() == mTexts.size()-1);
for (unsigned i = 0; i < mBars.size(); ++i)
{
auto npos = mBars[i]->GetNPos();
float ratio = npos.x;
if (i != 0)
{
ratio -= mBars[i - 1]->GetNPos().x;
}
char buf[255];
sprintf_s(buf, "%d", (int)(ratio * 100));
mTexts[i]->SetText(AnsiToWide(buf));
if (i != 0)
{
mTexts[i]->SetNPos(Vec2(mBars[i - 1]->GetNPos().x + ratio*.5f, 0.5f));
}
else
{
mTexts[i]->SetNPos(Vec2(ratio*.5f, 0.5f));
}
}
float xPos = mBars.back()->GetNPos().x;
char buf[255];
float ratio = 1.0f - xPos;
sprintf_s(buf, "%d", (int)(ratio * 100));
mTexts.back()->SetText(AnsiToWide(buf));
mTexts.back()->SetNPos(Vec2(xPos + ratio*.5f, 0.5f));
// issue the event
OnEvent(UIEvents::EVENT_COLORRAMP_DRAGGED);
}
| [
"jungwan82@gmail.com"
] | jungwan82@gmail.com |
3bfa713ce1ed01d3a5b694f43b34075ce3a6dbab | cd7aec810476a0a2a8b2b7f39bcfacf9e2854a13 | /sorting.c++ | 64db1b8280c4c0322c72907bd86ad4114cbcaeed | [] | no_license | SirawitN/algorithmDesign | 81bfebfc10e75ad8ebf8ee7cfd50148a82a569b7 | 22700ea29f1745f46538e4da9a165ed557d8afad | refs/heads/main | 2023-06-28T16:29:24.379227 | 2021-08-07T05:16:58 | 2021-08-07T05:16:58 | 385,290,814 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,973 | #include <iostream>
#include <vector>
using namespace std;
template <typename T>
void selectionSort(vector<T> &v)
{
for (int i = v.size() - 1; i > 0; i--)
{
int maxIdx = i;
for (int j = 0; j < i; j++)
{
if (v[j] > v[maxIdx])
maxIdx = j;
}
swap(v[i], v[maxIdx]);
}
} // big theta n**2
// ----------------------------------------------------------------
template <typename T>
void fix_down(vector<T> &v, int idx, int &n)
{
T tmp = v[idx];
int c;
while ((c = 2 * idx + 1) < n)
{
if (c + 1 < n && v[c] < v[c + 1])
c++;
if (v[c] < tmp)
break;
v[idx] = v[c];
idx = c;
}
v[idx] = tmp;
}
template <typename T>
void heapSort(vector<T> &v)
{
int n = v.size();
for (int i = n / 2; i >= 0; i--)
fix_down(v, i, n);
for (int j = n - 1; j > 0; j--)
{
swap(v[0], v[j]);
fix_down(v, 0, j);
}
} // O(nlg(n))
//---------------------------------------------------------
template <typename T>
void insertionSort(vector<T> &v)
{
for (int i = v.size() - 2; i >= 0; i--)
{
T tmp = v[i];
int j = i + 1;
for (; j < v.size(); j++)
{
if (tmp < v[j])
break;
v[j - 1] = v[j];
}
v[j - 1] = tmp;
}
} // O(n**2)
//---------------------------------------------------------------
template <typename T>
void shellSort(vector<T> &v)
{
int n = v.size();
vector<int> gaps = {701, 301, 132, 57, 23, 10, 4, 1};
for (int &g : gaps)
{
for (int i = n - 1 - g; i >= 0; i--)
{
T tmp = v[i];
int j = i + g;
for (; j < n; j += g)
{
if (tmp < v[j])
break;
v[j - g] = v[j];
}
v[j - g] = tmp;
}
}
} // time complexity is vary, depends on g in gaps
//------------------------------------------------------------------
template <typename T>
void merge(vector<T> &v, int &start, int &mid, int &stop, vector<T> &tmp)
{
int left = start, right = mid + 1;
for (int i = start; i <= stop; i++)
{
if (left > mid)
{
tmp[i] = v[right++];
continue;
}
if (right > stop)
{
tmp[i] = v[left++];
continue;
}
tmp[i] = (v[left] < v[right]) ? v[left++] : v[right++];
}
for (int j = start; j <= stop; j++)
v[j] = tmp[j];
}
template <typename T>
void mergeSort(vector<T> &v, int start, int stop, vector<T> &tmp)
{
if (start >= stop)
return;
int mid = (start + stop) / 2;
mergeSort(v, start, mid, tmp);
mergeSort(v, mid + 1, stop, tmp);
merge(v, start, mid, stop, tmp);
} // big theta nlg(n)
//-------------------------------------------------------------------------------
template <typename T>
int partition(vector<T> &v, int start, int stop)
{
T pivot = v[start];
int left = start - 1, right = stop + 1;
while (left < right)
{
while (v[++left] < pivot)
{
}
while (v[--right] > pivot)
{
}
if (left < right)
swap(v[left], v[right]);
}
return right;
}
template <typename T>
void quickSort(vector<T> &v, int start, int stop)
{
if (start >= stop)
return;
int p = partition(v, start, stop);
quickSort(v, start, p);
quickSort(v, p + 1, stop);
} // worst case is O(n**2), average case is big theta nlg(n)
//------------------------------------------------------------
int main()
{
vector<int> v;
for (int i = 100; i >= 0; i--)
v.push_back(i);
vector<int> tmp(v.size());
for (int &a : v)
cout << a << " ";
cout << "\n--------------------------------\n";
quickSort(v, 0, v.size() - 1);
for (int &a : v)
cout << a << " ";
return 0;
} | [
"nine_sirawit@hotmail.com"
] | nine_sirawit@hotmail.com | |
9f4f2cdf367a848dbcec98fd110bb650be782282 | 42601706586100441a915e63cab5e1d017dc864c | /OscSender/blocks/Alfrid/include/BatchHelpers.h | cbf3cbf669312b5b8fca790261404d90114044c4 | [] | no_license | yiwenl/CinderSketches | 10f53d49879f387eb81a255986a2e9a8c078615b | b5e0a5b8ebc1c09bc6cf1ff30119d38803d3c11d | refs/heads/master | 2023-01-31T23:10:05.872789 | 2021-10-01T07:11:57 | 2021-10-01T07:11:57 | 236,752,913 | 8 | 2 | null | 2023-01-06T20:38:11 | 2020-01-28T14:22:42 | C++ | UTF-8 | C++ | false | false | 11,168 | h | //
// BatchHelpers.hpp
// Particles002
//
// Created by Yi-Wen LIN on 08/02/2020.
//
#ifndef BatchHelpers_hpp
#define BatchHelpers_hpp
#include "cinder/gl/gl.h"
#include <stdio.h>
using namespace ci;
using namespace ci::app;
using namespace std;
const int NUM_DOTS = 100;
namespace alfrid {
typedef std::shared_ptr<class BatchAxis> BatchAxisRef;
typedef std::shared_ptr<class BatchGridDots> BatchGridDotsRef;
typedef std::shared_ptr<class BatchBall> BatchBallRef;
typedef std::shared_ptr<class BatchPlane> BatchPlaneRef;
class AlfridUtils {
public:
static Ray getLookRay(vec3 pos, mat4 mtxView) {
return getLookRay(pos, mtxView, vec3(0, 0, 1));
}
static Ray getLookRay(vec3 pos, mat4 mtxView, vec3 front) {
vec3 dir = getLookDir(mtxView, front);
return Ray(pos, dir);
}
static vec3 getLookDir(mat4 mtxView) {
return getLookDir(mtxView, vec3(0, 0, 1));
}
static vec3 getLookDir(mat4 mtxView, vec3 front) {
mat3 mtxRot = mat3(mtxView);
mtxRot = glm::transpose(mtxRot);
front = mtxRot * front;
front *= -1.0;
front = normalize(front);
return front;
}
};
class BatchAxis {
public:
BatchAxis() {
}
static BatchAxisRef create() { return std::make_shared<BatchAxis>(); }
void draw() {
gl::ScopedColor scp;
gl::lineWidth(2.0f);
gl::color( ColorA( 1, 0, 0, 1.0f ) );
gl::begin( GL_LINE_STRIP );
gl::vertex( vec3(-1000.0, 0.0, 0.0));
gl::vertex( vec3( 1000.0, 0.0, 0.0));
gl::end();
gl::color( ColorA( 0, 1, 0, 1.0f ) );
gl::begin( GL_LINE_STRIP );
gl::vertex( vec3(0.0, -1000.0, 0.0));
gl::vertex( vec3(0.0, 1000.0, 0.0));
gl::end();
gl::color( ColorA( 0, 0, 1, 1.0f ) );
gl::begin( GL_LINE_STRIP );
gl::vertex( vec3(0.0, 0.0, -1000.0));
gl::vertex( vec3(0.0, 0.0, 1000.0));
gl::end();
}
};
class BatchGridDots {
public:
BatchGridDots() {
_init();
}
void draw(float gap) {
gl::ScopedGlslProg progColor( mShader );
mShader->uniform("uGap", gap);
mBatch->draw();
}
void draw() {
draw(1.0f);
}
static BatchGridDotsRef create() { return std::make_shared<BatchGridDots>(); }
protected:
gl::BatchRef mBatch;
gl::GlslProgRef mShader;
void _init() {
vector<vec3> points;
for(int i = 0; i<NUM_DOTS; i++) {
for(int j = 0; j<NUM_DOTS; j++) {
points.push_back(vec3(i - NUM_DOTS/2, j - NUM_DOTS/2, 0.0f));
points.push_back(vec3(i - NUM_DOTS/2, 0.0f, j - NUM_DOTS/2));
}
}
gl::VboRef mParticleVbo = gl::Vbo::create( GL_ARRAY_BUFFER, points, GL_STREAM_DRAW );
// Describe particle semantics for GPU.
geom::BufferLayout particleLayout;
particleLayout.append( geom::Attrib::POSITION, 3, sizeof( vec3 ), 0);
auto mesh = gl::VboMesh::create( int(points.size()), GL_POINTS, { { particleLayout, mParticleVbo } } );
mShader = gl::GlslProg::create( gl::GlslProg::Format()
.vertex( CI_GLSL(100, precision highp float;
uniform mat4 ciModelViewProjection;
uniform float uGap;
attribute vec4 ciPosition;
void main( void )
{
vec4 pos = ciPosition;
pos.xyz *= uGap;
gl_Position = ciModelViewProjection * pos;
gl_PointSize = 2.0;
}))
.fragment( CI_GLSL(100, precision mediump float;
void main( void )
{
gl_FragColor = vec4( 1.0, 1.0, 1.0, 0.5);
})));
mBatch = gl::Batch::create(mesh, mShader);
}
};
class BatchBall {
public:
BatchBall() {
_init();
}
void draw(vec3 position) {
draw(position, vec3(1.0), vec3(1.0), 1.0);
}
void draw(vec3 position, vec3 scale) {
draw(position, scale, vec3(1.0), 1.0);
}
void draw(vec3 position, vec3 scale, vec3 color) {
draw(position, scale, color, 1.0);
}
void draw(vec3 position, vec3 scale, vec3 color, float opacity) {
gl::ScopedGlslProg progColor( mShader );
mShader->uniform("uPosition", position);
mShader->uniform("uScale", scale);
mShader->uniform("uColor", color);
mShader->uniform("uOpacity", opacity);
mBatch->draw();
}
static BatchBallRef create() { return std::make_shared<BatchBall>(); }
protected:
gl::BatchRef mBatch;
gl::GlslProgRef mShader;
void _init() {
auto sphere = gl::VboMesh::create( geom::Sphere() );
mShader = gl::GlslProg::create( gl::GlslProg::Format()
.vertex( CI_GLSL(100, precision highp float;
uniform mat4 ciModelViewProjection;
uniform mat3 ciNormalMatrix;
attribute vec4 ciPosition;
attribute vec2 ciTexCoord0;
attribute vec3 ciNormal;
uniform vec3 uPosition;
uniform vec3 uScale;
varying highp vec3 Normal;
varying highp vec2 TexCoord0;
void main( void )
{
vec4 pos = ciPosition;
pos.xyz *= uScale;
pos.xyz += uPosition;
gl_Position = ciModelViewProjection * pos;
TexCoord0 = ciTexCoord0;
Normal = ciNormalMatrix * ciNormal;
}))
.fragment( CI_GLSL(100, precision mediump float;
precision highp float;
varying vec3 Normal;
uniform vec3 uColor;
uniform float uOpacity;
const vec3 LIGHT = vec3(0.2, 1.0, 0.6);
void main( void )
{
float d = max(dot(normalize(Normal), normalize(LIGHT)), 0.0);
d = mix(d, 1.0, .25);
gl_FragColor = vec4( uColor * d, uOpacity);
})));
mBatch = gl::Batch::create(sphere, mShader);
}
};
class BatchLine {
public:
BatchLine() {
}
static void draw(vec3 mPointA, vec3 mPointB) {
draw(mPointA, mPointB, vec3(1.0), 1.0f);
}
static void draw(vec3 mPointA, vec3 mPointB, vec3 mColor) {
draw(mPointA, mPointB, mColor, 1.0f);
}
static void draw(vec3 mPointA, vec3 mPointB, vec3 mColor, float mOpacity) {
gl::ScopedColor scp;
gl::lineWidth(2.0f);
gl::color( ColorA( mColor.x, mColor.y, mColor.z, mOpacity ) );
gl::begin( GL_LINE_STRIP );
gl::vertex( mPointA );
gl::vertex( mPointB );
gl::end();
}
};
class BatchPlane {
public:
static BatchPlaneRef create() { return std::make_shared<BatchPlane>(); }
BatchPlane() {
_init();
}
void draw() {
draw(vec3(0.0), vec3(1.0), vec3(1.0), 1.0);
}
void draw(vec3 position) {
draw(position, vec3(1.0), vec3(1.0), 1.0);
}
void draw(vec3 position, vec3 scale) {
draw(position, scale, vec3(1.0), 1.0);
}
void draw(vec3 position, vec3 scale, vec3 color) {
draw(position, scale, color, 1.0);
}
void draw(vec3 position, vec3 scale, vec3 color, float opacity) {
gl::ScopedGlslProg progColor( mShader );
mShader->uniform("uPosition", position);
mShader->uniform("uScale", scale);
mShader->uniform("uColor", color);
mShader->uniform("uOpacity", opacity);
mBatch->draw();
}
protected:
gl::BatchRef mBatch;
gl::GlslProgRef mShader;
// methods
void _init() {
console() << "init batch plane" << endl;
auto plane = gl::VboMesh::create( geom::Plane() );
mShader = gl::GlslProg::create( gl::GlslProg::Format()
.vertex( CI_GLSL(100, precision highp float;
uniform mat4 ciModelViewProjection;
uniform mat3 ciNormalMatrix;
attribute vec4 ciPosition;
attribute vec2 ciTexCoord0;
attribute vec3 ciNormal;
uniform vec3 uPosition;
uniform vec3 uScale;
varying highp vec3 Normal;
varying highp vec2 TexCoord0;
void main( void )
{
vec4 pos = ciPosition;
pos.xyz *= uScale;
pos.xyz += uPosition;
gl_Position = ciModelViewProjection * pos;
TexCoord0 = ciTexCoord0;
Normal = ciNormalMatrix * ciNormal;
}))
.fragment( CI_GLSL(100, precision mediump float;
precision highp float;
varying vec3 Normal;
uniform vec3 uColor;
uniform float uOpacity;
void main( void )
{
gl_FragColor = vec4( uColor, uOpacity);
})));
mBatch = gl::Batch::create(plane, mShader);
}
};
}
#endif /* BatchHelpers_hpp */
| [
"bongiovi015@gmail.com"
] | bongiovi015@gmail.com |
a01f4f0785885d157a8dd39e83f16f101c8a780f | c51febc209233a9160f41913d895415704d2391f | /YorozuyaGSLib/source/_result_csi_goods_list_zocl.cpp | 1760f92cfa930abf900b50c32d68530ad7390175 | [
"MIT"
] | permissive | roussukke/Yorozuya | 81f81e5e759ecae02c793e65d6c3acc504091bc3 | d9a44592b0714da1aebf492b64fdcb3fa072afe5 | refs/heads/master | 2023-07-08T03:23:00.584855 | 2023-06-29T08:20:25 | 2023-06-29T08:20:25 | 463,330,454 | 0 | 0 | MIT | 2022-02-24T23:15:01 | 2022-02-24T23:15:00 | null | UTF-8 | C++ | false | false | 263 | cpp | #include <_result_csi_goods_list_zocl.hpp>
START_ATF_NAMESPACE
int _result_csi_goods_list_zocl::size()
{
using org_ptr = int (WINAPIV*)(struct _result_csi_goods_list_zocl*);
return (org_ptr(0x140304dd0L))(this);
};
END_ATF_NAMESPACE
| [
"b1ll.cipher@yandex.ru"
] | b1ll.cipher@yandex.ru |
8cefbde38456a3a2366822b35d455c7d8198e4f6 | 2c54268cd7fe81e4855a8cabd105ad04c5d8b3c1 | /Codeforces-208A.cpp | 8497aa27c5cbbe6ccc644a0d3db6b52f36e093d4 | [] | no_license | kamrul64577/ACM-Problem-Solve | b253ba73fa466a81a2ef7cc1401d1fa9e24ff79d | 74e629e1f7007b038ce36ed13b175753c999da4d | refs/heads/master | 2020-06-22T01:29:06.169555 | 2020-02-13T16:03:50 | 2020-02-13T16:03:50 | 197,600,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 320 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
int len=s.size();
for(int i=0; i<len; i++)
{
if(s[i]=='W' && s[i+1]=='U' && s[i+2]=='B' )
{
i+=2;
cout<<" ";
}
else
cout<<s[i];
}
}
| [
"noreply@github.com"
] | kamrul64577.noreply@github.com |
25886e757ee934448fcd248544045211609e6185 | 5d3aa2c7603fcb287e764e30fc1ef5983d28ce5b | /Client/Code/StaticObject.h | fbf30857ce171130b8404c6a56d1dea1cb7607f2 | [] | no_license | AlisaCodeDragon/AliceMadnessReturns | f46d3178df90c6ccf6da5c76a83c1f9ac809c28f | 80b322253846c50fc130cd540051a64440fe62e7 | refs/heads/main | 2023-03-18T14:26:37.758657 | 2021-02-08T13:43:35 | 2021-02-08T13:43:35 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,220 | h | #ifndef StaticObject_h__
#define StaticObject_h__
#include "Define.h"
#include "Base.h"
#include "Engine_Define.h"
#include "Export_Function.h"
BEGIN(Client)
class CStaticObject : public Engine::CGameObject
{
protected: // 생성자, 소멸자
explicit CStaticObject(LPDIRECT3DDEVICE9 pGraphicDev);
explicit CStaticObject(const CStaticObject& rhs);
virtual ~CStaticObject(void);
// CGameObject을(를) 통해 상속됨
virtual HRESULT Ready_Object(void) override;
virtual int Update_Object(const _float & _fDeltaTime) override;
virtual void Render_Object(void) override;
public:
static CStaticObject* Create(LPDIRECT3DDEVICE9 pGraphicDev);
_bool SetRenderInfo(const _tchar* _pMeshTag, Engine::RENDERID _eRenderID = Engine::RENDER_NONALPHA);
const _tchar* GetMeshTag() const { return m_tcMeshTag; }
virtual void Free(void);
virtual _bool SaveInfo(HANDLE& _hfOut) override;
virtual _bool LoadInfo(HANDLE& _hfIn) override;
_bool LoadCollidersInfo();
private:
Engine::CStaticMesh* m_pMesh = nullptr;
Engine::CMeshRenderer* m_pRenderer = nullptr;
Engine::CShader* m_pShader = nullptr;
//const _tchar* m_pMeshTag = nullptr;
_tchar m_tcMeshTag[MAX_PATH] = L"";
};
END
#endif // !LogoObject_h__
| [
"batherit0703@naver.com"
] | batherit0703@naver.com |
34b73bc03263b618674067d260c44264d1d61ce9 | ae219d28725c9dd58c200ae76ba3bf3f2a90d557 | /BrowserLauncher/xulrunner-sdk/include/nsPICertNotification.h | 8b6b6a7d7dfbf81f93c1f4c9af56b4e0a7c323af | [] | no_license | pepekinha/src | de1f0c64cf1238e019f4daf7f87d95849304d88e | 5223858f05f6791f1dec30df1dbb91ae3e4f5952 | refs/heads/master | 2021-01-22T01:05:54.659896 | 2014-04-06T01:43:37 | 2014-04-06T01:43:37 | 27,421,524 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,060 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/release-mozilla-1.9.2-xulrunner_win32_build/build/xpinstall/public/nsPICertNotification.idl
*/
#ifndef __gen_nsPICertNotification_h__
#define __gen_nsPICertNotification_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIURI; /* forward declaration */
class nsIPrincipal; /* forward declaration */
/* starting interface: nsPICertNotification */
#define NS_PICERTNOTIFICATION_IID_STR "42cd7162-ea4a-4088-9888-63ea5095869e"
#define NS_PICERTNOTIFICATION_IID \
{0x42cd7162, 0xea4a, 0x4088, \
{ 0x98, 0x88, 0x63, 0xea, 0x50, 0x95, 0x86, 0x9e }}
class NS_NO_VTABLE nsPICertNotification : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_PICERTNOTIFICATION_IID)
/* void onCertAvailable (in nsIURI aURI, in nsISupports aContext, in PRUint32 aStatus, in nsIPrincipal aPrincipal); */
NS_IMETHOD OnCertAvailable(nsIURI *aURI, nsISupports *aContext, PRUint32 aStatus, nsIPrincipal *aPrincipal) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsPICertNotification, NS_PICERTNOTIFICATION_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSPICERTNOTIFICATION \
NS_IMETHOD OnCertAvailable(nsIURI *aURI, nsISupports *aContext, PRUint32 aStatus, nsIPrincipal *aPrincipal);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSPICERTNOTIFICATION(_to) \
NS_IMETHOD OnCertAvailable(nsIURI *aURI, nsISupports *aContext, PRUint32 aStatus, nsIPrincipal *aPrincipal) { return _to OnCertAvailable(aURI, aContext, aStatus, aPrincipal); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSPICERTNOTIFICATION(_to) \
NS_IMETHOD OnCertAvailable(nsIURI *aURI, nsISupports *aContext, PRUint32 aStatus, nsIPrincipal *aPrincipal) { return !_to ? NS_ERROR_NULL_POINTER : _to->OnCertAvailable(aURI, aContext, aStatus, aPrincipal); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class _MYCLASS_ : public nsPICertNotification
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSPICERTNOTIFICATION
_MYCLASS_();
private:
~_MYCLASS_();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(_MYCLASS_, nsPICertNotification)
_MYCLASS_::_MYCLASS_()
{
/* member initializers and constructor code */
}
_MYCLASS_::~_MYCLASS_()
{
/* destructor code */
}
/* void onCertAvailable (in nsIURI aURI, in nsISupports aContext, in PRUint32 aStatus, in nsIPrincipal aPrincipal); */
NS_IMETHODIMP _MYCLASS_::OnCertAvailable(nsIURI *aURI, nsISupports *aContext, PRUint32 aStatus, nsIPrincipal *aPrincipal)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsPICertNotification_h__ */
| [
"highnetlan@gmail.com"
] | highnetlan@gmail.com |
ebfbeb4c65352f8a26d138722fb57685f8d9c7ba | 025b43c582ba84e30bd49fe2e544e9a887eb13f6 | /spj_subset_sums.cpp | 2cc206f509d5e3d4d749b82d24c4e7c7f006109d | [] | no_license | maan19/my-spoj-codes | 4a99ed4eb073ac5a0889e8e4b6bcab209372224b | cba736c5a1f6b215ddb5d7193841097a91a8fce7 | refs/heads/master | 2020-07-19T04:10:07.199151 | 2016-11-16T11:55:00 | 2016-11-16T11:55:00 | 73,915,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 692 | cpp | #include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
int data[109];
void subsum();
int dp[102][100000+3];
int n,sum=0,sum2=0;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(dp,-1,sizeof(dp));
sum2=sum=0;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&data[i]),sum+=data[i];
subsum();
for(int j=0;j<=sum;j++)
if(dp[n][j])
sum2+=j;
printf("%d\n",sum2);
}
}
void subsum()
{
for(int i =0;i<=n;i++)
dp[i][0]=true;
for(int j=1;j<=sum;j++)
dp[1][j]=(data[1]==j);
for(int i=2;i<=n;i++)
{
for(int j=1;j<=sum;j++)
{
if(data[i]>j)
dp[i][j]=dp[i-1][j];
else
dp[i][j]=dp[i-1][j]||dp[i-1][j-data[i]];
}
}
}
| [
"maanj872@gmail.com"
] | maanj872@gmail.com |
b5fd14aeb94aa32c1d4297efe92e6537c43932e5 | 4ec188d31f0b6e89b20302d39dccf02a6c0927af | /tests/application/script/scriptmain.cpp | 07b434be2c0772a9fd2207f84c10419dccb5a7da | [
"Apache-2.0"
] | permissive | huiyugan/gincu | 85ed66099a536228039e7d1d93468fae81aca8d9 | dd9d83cc75561d873fc396d009436ba07219ff4d | refs/heads/master | 2021-09-19T13:15:59.203463 | 2018-07-28T05:46:42 | 2018-07-28T05:46:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,844 | cpp | #include "scenemenu.h"
#include "gincu/scripting/gscriptingmain.h"
#include "gincu/scripting/gscriptingutil.h"
#include "gincu/gresourcemanager.h"
#include "gincu/ecs/gentity.h"
#include "gincu/ecs/gcomponenttransform.h"
#include "gincu/gevent.h"
#include "gincu/geventqueue.h"
#include "gincu/gapplication.h"
#include "cpgf/gmetaclass.h"
#include "cpgf/gmetadefine.h"
#include "cpgf/gmetaapi.h"
#include "cpgf/scriptbind/gscriptbindutil.h"
#include "cpgf/gscopedinterface.h"
#include "cpgf/goutmain.h"
#include <memory>
#include <iostream>
using namespace gincu;
using namespace cpgf;
using namespace std;
namespace {
void exitScriptDemo()
{
SceneMenu::returnToMainMenu();
}
void bindMethod(IScriptObject * scriptObject, const std::string & methodName)
{
GScopedInterface<IMetaMethod> method(static_cast<IMetaMethod *>(metaItemToInterface(getGlobalMetaClass()->getMethod(methodName.c_str()))));
scriptSetValue(scriptObject, methodName.c_str(), GScriptValue::fromMethod(NULL, method.get()));
}
void runScriptMain()
{
GScriptingMain * scriptMain = GScriptingMain::getInstance();
scriptMain->initialize(GScriptLanguage::slLua);
GScopedInterface<IScriptObject> scriptObject(scriptMain->getScriptObject());
GScopedInterface<IMetaService> metaService(scriptMain->getService());
GScopedInterface<IMetaClass> metaClass(metaService->findClassByName("gincu"));
scriptSetValue(scriptObject.get(), "gincu", GScriptValue::fromClass(metaClass.get()));
GDefineMetaGlobal()
._method("exitScriptDemo", &exitScriptDemo)
;
bindMethod(scriptObject.get(), "exitScriptDemo");
scriptMain->executeFile("lua/scriptmain.lua");
}
} //unnamed namespace
G_AUTO_RUN_BEFORE_MAIN(ScriptMain)
{
MenuRegister::getInstance()->registerItem("Script", 3, &runScriptMain, 0xffaaaaff);
}
| [
"wqking@outlook.com"
] | wqking@outlook.com |
ab2e735ae2548384c7c875ac7998605756d21157 | 9b81ce52fecaa1e606e4162a76d00c04440c41ae | /item14.cpp | ae5c223b8f631468a58f828612e690f899bece85 | [] | no_license | zhangyl927/effective-cpp | 6a522486fba279a015fcd5069866fb01248f66dd | a4f8cf67c996655ad4632dc127d50a3c4e2404e3 | refs/heads/master | 2023-02-16T15:16:21.946596 | 2021-01-15T10:02:45 | 2021-01-15T10:02:45 | 329,874,937 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | cpp | #include <iostream>
#include <memory>
class Mutex { };
class Uncopyable
{
public:
Uncopyable() { }
~Uncopyable() { }
private:
Uncopyable(const Uncopyable&);
Uncopyable& operator=(const Uncopyable&);
};
class Lock : private Uncopyable
{
public:
Lock(Mutex* pm) : mutexPtr(pm)
{
std::cout << "Lock construct\n";
lock(mutexPtr);
}
~Lock() { unlock(mutexPtr); }
private:
static void lock(Mutex* pm) { std::cout << "Lock lock\n"; }
static void unlock(Mutex* pm) { pm = nullptr; std::cout << "Lock unlock\n"; }
Mutex* mutexPtr;
};
class Lock_SHA
{
public:
explicit Lock_SHA(Mutex* pm) : mutexPtr(pm, unlock)
{
std::cout << "Lock_SHA constructor\n";
lock(mutexPtr.get());
}
private:
static void lock(Mutex* pm) { std::cout << "Lock_SHA lock\n"; }
static void unlock(Mutex* pm) { pm = nullptr; std::cout << "Lock_SHA unlock\n"; }
std::shared_ptr<Mutex> mutexPtr;
};
int main()
{
Mutex m1;
Lock ml1(&m1);
// Lock ml2(ml1); forbit copy
Lock_SHA ls1(&m1);
Lock_SHA ls2(ls1);
return 0;
}
| [
"sa517511@mail.ustc.edu.cn"
] | sa517511@mail.ustc.edu.cn |
bec87ef1d8640de3ed28c34f662bb3b12500d279 | 84283cea46b67170bb50f22dcafef2ca6ddaedff | /HD Multi-University/8/1009.cpp | e7aca86f4d744a71df3f5f6ecf2e4c3702bf4153 | [] | no_license | ssyze/Codes | b36fedf103c18118fd7375ce7a40e864dbef7928 | 1376c40318fb67a7912f12765844f5eefb055c13 | refs/heads/master | 2023-01-09T18:36:05.417233 | 2020-11-03T15:45:45 | 2020-11-03T15:45:45 | 282,236,294 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,457 | cpp | #include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int maxn = 5e6 + 100;
typedef long long ll;
ll h[maxn], p[maxn], hh[maxn], have[maxn];
int t, n, tot;
char s[maxn];
ll geth(int l, int r, ll* ha) { return (ha[r] - ha[l - 1] * p[r - l + 1] % mod + mod) % mod; }
bool Find(ll x)
{
int idx = lower_bound(have, have + tot, x) - have;
if (idx == tot)
return 0;
else
return have[idx] == x;
}
bool check(int x)
{
tot = 0;
ll cur = 0;
for (int i = 1; i <= x; ++i) cur *= p[1], cur += s[i], cur %= mod;
have[tot++] = cur;
for (int i = 1; i <= x; ++i) {
cur -= s[i] * p[x - 1] % mod;
cur += mod;
cur %= mod;
cur *= p[1];
cur %= mod;
cur += s[i];
cur %= mod;
have[tot++] = cur;
}
sort(have, have + tot);
for (int i = x + 1; i <= n; i += x) {
if (!Find(geth(i, i + x - 1, h))) return 0;
}
return 1;
}
int main()
{
p[0] = 1;
for (int i = 1; i < maxn; ++i) p[i] = p[i - 1] * 13331 % mod;
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
scanf("%s", s + 1);
for (int i = 1; i <= n; ++i) h[i] = h[i - 1] * p[1] + s[i], h[i] %= mod;
for (int i = 2; i <= n / 2 + 1; ++i) {
if (n % i != 0) continue;
if (check(i)) {
puts("Yes");
goto nxt;
}
}
puts("No");
nxt:;
}
}
| [
"46869158+shu-ssyze@users.noreply.github.com"
] | 46869158+shu-ssyze@users.noreply.github.com |
412ba31f8294265b9385cc481d8a9118134d4f75 | 80a6dcd8e0e55b1ec225e4e82d8b1bed100fdcd5 | /HackerRank/hackerland-radio-transmitters.cpp | 2fbdd334237ea6e343bf777f54614ac68c6d0072 | [] | no_license | arnabs542/competitive-programming-1 | 58b54f54cb0b009f1dac600ca1bac5a4c1d7a523 | 3fa3a62277e5cd8a94d1baebb9ac26fe89211da3 | refs/heads/master | 2023-08-14T23:53:22.941834 | 2021-10-14T11:26:21 | 2021-10-14T11:26:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 588 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
ll n, N, k;
cin>>N>>k;
n = 100000;
ll * arr = new ll[n]();
for (ll i = 0; i < N; i++)
{
ll temp;
cin>>temp;
arr[temp-1] = 1;
}
ll p = 0, count = 0;
while(p!=n){
if(!arr[p]){
p++;
}else{
p = min(n-1, p+k);
while(arr[p]==0){
p--;
}
count++;
p = min(n, p+k+1);
}
}
cout<<count<<endl;
delete [] arr;
return 0;
} | [
"nandanwar.adarsh@gmail.com"
] | nandanwar.adarsh@gmail.com |
f6797d0330223c90c9a54bd1cde2aba3c95be31e | 38cc8f98ac4810a82c60cd2b59ed62d09e754ae0 | /CodeForces/702-3/B/main.cpp | b5693ce34e712b4405a5d66042895fff6405072d | [] | no_license | himdhiman/Competitive-Codes | b4b37f1328e7258cc4346c8d5f27e301e871b915 | 43b4a512b1f896dd12560c9883c894415bcb5fd6 | refs/heads/master | 2023-06-29T05:10:27.236649 | 2021-07-26T07:00:52 | 2021-07-26T07:00:52 | 308,596,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 655 | cpp | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int &x : a) {
cin >> x;
}
int res = 0;
vector<int> cnt(3);
for (int x = 0; x <= 2; x++) {
for (int i = 0; i < n; i++) {
if (a[i] % 3 == x) {
cnt[x]++;
}
}
}
while (*min_element(cnt.begin(), cnt.end()) != n / 3) {
for (int i = 0; i < 3; i++) {
if (cnt[i] > n / 3) {
res++;
cnt[i]--;
cnt[(i + 1) % 3]++;
}
}
}
cout << res << endl;
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
} | [
"himanshudhiman9313@gmail.com"
] | himanshudhiman9313@gmail.com |
4fa08769aabc36eeb5097396235fe101a3d3c624 | e0279edbc6619c7c18358a9697ebc1f2dc6ee499 | /Codeforces/841B.cpp | 86e9b9e3462bb614920be0d899a21c940e0573b2 | [] | no_license | tikul/Competitive-Programming | 9e9830301f5f7a4a4553992a9ccc74a8d5d2748e | 83b0afeb8ed85d60787d097120b0af7e99b20b47 | refs/heads/master | 2021-01-01T06:15:19.515610 | 2017-11-14T03:36:20 | 2017-11-14T03:36:20 | 97,393,776 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 853 | cpp | #include <stdio.h>
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <string>
#include <utility>
#include <queue>
#include <unordered_set>
#include <set>
#include <unordered_map>
using namespace std;
#define left(i) i << 1
#define right(i) i << 1 | 1
#define mp make_pair
#define pb push_back
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<pair<int,int>, int> ppi;
int n, a[1000005];
int main(){
cin.sync_with_stdio(0);
cin.tie(0);
cin >> n;
ll tot=0;
bool isOdd = false;
for(int i = 0; i < n; i++){
cin >> a[i];
if(a[i] % 2 == 1){
isOdd = true;
}
tot += a[i];
}
if(tot%2==1){
cout << "First";
}else{
if(isOdd){
cout << "First";
}else{
cout << "Second";
}
}
} | [
"tikul@users.noreply.github.com"
] | tikul@users.noreply.github.com |
295f5d65374e6d4a29df00ba3730a84005ed1285 | 73d648a072775d64db7a4c4711b9da32c69fbece | /hdu/427A.cpp | cf215d78b2253abd54d6523fe39300adaaf91e03 | [] | no_license | 12Dong/acm | e209605c57e8a2d0247ef5c86f50aec1d43e86b3 | 4f0c98fd4649f730db2ab8300ce45d04dd31e766 | refs/heads/master | 2020-12-30T17:51:18.751827 | 2017-10-21T07:30:56 | 2017-10-21T07:30:56 | 90,933,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300 | cpp | #include<iostream>
using namespace std;
//yrrrrrrrrrr
int main()
{
int num;
while(cin >> num)
{
int have=0;
int cur;
int ans=0;
for(int i=0;i<num;i++)
{
cin >> cur;
if(cur>0) have+=cur;
else
{
if(cur+have>=0) have--;
else ans++;
}
}
cout << ans << endl;
}
}
| [
"289663639@qq.com"
] | 289663639@qq.com |
e999594741024b3acea36b44b2c8883741ee50e8 | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/Configuration/UNIX_Configuration_STUB.hxx | 223b112b8c4789e08ae6bd0cb8ad4293f1e264b5 | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,810 | hxx | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#ifdef PEGASUS_OS_STUB
#ifndef __UNIX_CONFIGURATION_PRIVATE_H
#define __UNIX_CONFIGURATION_PRIVATE_H
#endif
#endif
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
9dd6ca1f0fced60da22acb8656aaec6d78c52415 | 429e5c37dc2ea26c1bd328ae607a98a21dddc855 | /src/board_controller/freeeeg32/freeeeg32.cpp | 51b0eaf0041344483a0912c03d7f892d6642e5d3 | [
"MIT"
] | permissive | ElonVampire/brainflow | ffcb4085337fc487a28af8003d24e59144d71318 | 1199dd38438b32aefb6d91352832f54c306ef687 | refs/heads/master | 2023-02-21T23:54:10.049531 | 2021-01-24T23:44:29 | 2021-01-24T23:44:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,145 | cpp | #include <math.h>
#include <string.h>
#include "custom_cast.h"
#include "freeeeg32.h"
#include "serial.h"
#include "timestamp.h"
constexpr int FreeEEG32::num_channels;
constexpr int FreeEEG32::start_byte;
constexpr int FreeEEG32::end_byte;
constexpr double FreeEEG32::ads_gain;
constexpr double FreeEEG32::ads_vref;
FreeEEG32::FreeEEG32 (struct BrainFlowInputParams params)
: Board ((int)BoardIds::FREEEEG32_BOARD, params)
{
serial = NULL;
is_streaming = false;
keep_alive = false;
initialized = false;
}
FreeEEG32::~FreeEEG32 ()
{
skip_logs = true;
release_session ();
}
int FreeEEG32::prepare_session ()
{
if (initialized)
{
safe_logger (spdlog::level::info, "Session already prepared");
return (int)BrainFlowExitCodes::STATUS_OK;
}
if (params.serial_port.empty ())
{
safe_logger (spdlog::level::err, "serial port is empty");
return (int)BrainFlowExitCodes::INVALID_ARGUMENTS_ERROR;
}
serial = new Serial (params.serial_port.c_str ());
int port_open = open_port ();
if (port_open != (int)BrainFlowExitCodes::STATUS_OK)
{
delete serial;
serial = NULL;
return port_open;
}
int set_settings = set_port_settings ();
if (set_settings != (int)BrainFlowExitCodes::STATUS_OK)
{
delete serial;
serial = NULL;
return set_settings;
}
initialized = true;
return (int)BrainFlowExitCodes::STATUS_OK;
}
int FreeEEG32::start_stream (int buffer_size, char *streamer_params)
{
if (is_streaming)
{
safe_logger (spdlog::level::err, "Streaming thread already running");
return (int)BrainFlowExitCodes::STREAM_ALREADY_RUN_ERROR;
}
if (buffer_size <= 0 || buffer_size > MAX_CAPTURE_SAMPLES)
{
safe_logger (spdlog::level::err, "invalid array size");
return (int)BrainFlowExitCodes::INVALID_BUFFER_SIZE_ERROR;
}
if (db)
{
delete db;
db = NULL;
}
if (streamer)
{
delete streamer;
streamer = NULL;
}
int res = prepare_streamer (streamer_params);
if (res != (int)BrainFlowExitCodes::STATUS_OK)
{
return res;
}
db = new DataBuffer (FreeEEG32::num_channels, buffer_size);
if (!db->is_ready ())
{
safe_logger (spdlog::level::err, "unable to prepare buffer");
delete db;
db = NULL;
return (int)BrainFlowExitCodes::INVALID_BUFFER_SIZE_ERROR;
}
serial->flush_buffer ();
keep_alive = true;
streaming_thread = std::thread ([this] { this->read_thread (); });
is_streaming = true;
return (int)BrainFlowExitCodes::STATUS_OK;
}
int FreeEEG32::stop_stream ()
{
if (is_streaming)
{
keep_alive = false;
is_streaming = false;
if (streaming_thread.joinable ())
{
streaming_thread.join ();
}
if (streamer)
{
delete streamer;
streamer = NULL;
}
return (int)BrainFlowExitCodes::STATUS_OK;
}
else
{
return (int)BrainFlowExitCodes::STREAM_THREAD_IS_NOT_RUNNING;
}
}
int FreeEEG32::release_session ()
{
if (initialized)
{
if (is_streaming)
{
stop_stream ();
}
initialized = false;
}
if (serial)
{
serial->close_serial_port ();
delete serial;
serial = NULL;
}
return (int)BrainFlowExitCodes::STATUS_OK;
}
void FreeEEG32::read_thread ()
{
int res;
constexpr int max_size = 200; // random value bigger than package size which is unknown
unsigned char b[max_size] = {0};
// dont know exact package size and it can be changed with new firmware versions, its >=
// min_package_size and we can check start\stop bytes
constexpr int min_package_size = 1 + 32 * 3;
float eeg_scale =
FreeEEG32::ads_vref / float ((pow (2, 23) - 1)) / FreeEEG32::ads_gain * 1000000.;
double package[FreeEEG32::num_channels] = {0.0};
bool first_package_received = false;
while (keep_alive)
{
int pos = 0;
bool complete_package = false;
while ((keep_alive) && (pos < max_size - 2))
{
res = serial->read_from_serial_port (b + pos, 1);
int prev_id = (pos <= 0) ? 0 : pos - 1;
if ((b[pos] == FreeEEG32::start_byte) && (b[prev_id] == FreeEEG32::end_byte) &&
(pos >= min_package_size))
{
complete_package = true;
break;
}
pos += res;
}
if (complete_package)
{
// handle the case that we start reading in the middle of data stream
if (!first_package_received)
{
first_package_received = true;
continue;
}
package[0] = (double)b[0];
for (int i = 0; i < 32; i++)
{
package[i + 1] = eeg_scale * cast_24bit_to_int32 (b + 1 + 3 * i);
}
double timestamp = get_timestamp ();
db->add_data (timestamp, package);
streamer->stream_data (package, FreeEEG32::num_channels, timestamp);
}
else
{
safe_logger (
spdlog::level::trace, "stopped with pos: {}, keep_alive: {}", pos, keep_alive);
}
}
}
int FreeEEG32::open_port ()
{
if (serial->is_port_open ())
{
safe_logger (spdlog::level::err, "port {} already open", serial->get_port_name ());
return (int)BrainFlowExitCodes::PORT_ALREADY_OPEN_ERROR;
}
safe_logger (spdlog::level::info, "openning port {}", serial->get_port_name ());
int res = serial->open_serial_port ();
if (res < 0)
{
return (int)BrainFlowExitCodes::UNABLE_TO_OPEN_PORT_ERROR;
}
safe_logger (spdlog::level::trace, "port {} is open", serial->get_port_name ());
return (int)BrainFlowExitCodes::STATUS_OK;
}
int FreeEEG32::set_port_settings ()
{
#ifdef _WIN32
// windows driver fails to set settings and in fact ignores them, no idea what drivers on others
// OSes do
int timeout_only = true;
#else
int timeout_only = false;
#endif
int res = serial->set_serial_port_settings (1000, timeout_only);
if (res < 0)
{
safe_logger (spdlog::level::err, "Unable to set port settings, res is {}", res);
return (int)BrainFlowExitCodes::SET_PORT_ERROR;
}
#ifndef _WIN32
// looks like stm driver on windows ignores all settings, no need to change them
res = serial->set_custom_baudrate (921600);
if (res < 0)
{
safe_logger (spdlog::level::err, "Unable to set custom baud rate, res is {}", res);
return (int)BrainFlowExitCodes::SET_PORT_ERROR;
}
#endif
safe_logger (spdlog::level::trace, "set port settings");
return (int)BrainFlowExitCodes::STATUS_OK;
}
int FreeEEG32::config_board (std::string config, std::string &response)
{
safe_logger (spdlog::level::err, "FreeEEG32 doesn't support board configuration.");
return (int)BrainFlowExitCodes::UNSUPPORTED_BOARD_ERROR;
}
| [
"noreply@github.com"
] | ElonVampire.noreply@github.com |
f69975aef1d1a1f6bd932d6dd4481968bc13ed09 | 002b6230874dea6e4d76defafc1ae293b5744918 | /tests/Metric.cpp | 200fb5a65f0be0b9148d036395b96ca144da7c5d | [
"MIT"
] | permissive | SCOREC/nektar | f3cf3c44106ac7a2dd678366bb53861e2db67a11 | add6f04b55fad6ab29d08b5b27eefd9bfec60be3 | refs/heads/master | 2021-01-22T23:16:16.440068 | 2015-02-27T17:26:09 | 2015-02-27T17:26:09 | 30,382,914 | 6 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 2,933 | cpp | ///////////////////////////////////////////////////////////////////////////////
//
// File: Metric.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Implementation of the metric base class.
//
///////////////////////////////////////////////////////////////////////////////
#include <Metric.h>
#include <loki/Singleton.h>
#include <boost/algorithm/string.hpp>
using namespace std;
namespace Nektar
{
MetricFactory& GetMetricFactory()
{
typedef Loki::SingletonHolder<MetricFactory,
Loki::CreateUsingNew,
Loki::NoDestroy > Type;
return Type::Instance();
}
/**
* @brief Constructor.
*/
Metric::Metric(TiXmlElement *metric, bool generate) :
m_metric(metric), m_generate(generate)
{
if (!metric->Attribute("id"))
{
cerr << "Metric has no ID" << endl;
}
if (!metric->Attribute("type"))
{
cerr << "Metric has no type" << endl;
}
m_id = atoi(metric->Attribute("id"));
m_type = boost::to_upper_copy(string(metric->Attribute("type")));
}
/**
* @brief Test a line of output from an executible.
*/
bool Metric::Test(std::istream& pStdout, std::istream& pStderr)
{
if (m_generate)
{
v_Generate(pStdout, pStderr);
return true;
}
else
{
return v_Test(pStdout, pStderr);
}
}
}
| [
"dan.a.ibanez@gmail.com"
] | dan.a.ibanez@gmail.com |
2d881174903a79a1c57d0328425dbea1359a4290 | 68e06f34b77a3ba7e6cfb17e9cc441550d4c190b | /lab/Iruegas-Hernan-A00817021-Programa-5/1prg_app.cpp | 552b46bb25883870e7d2be21ce63090a0923cf4e | [] | no_license | HernanIruegas/calidad-software | f492d52e54eba7b5f64543a6728b7f8aa2643bdf | c9d0b9a8e47d6320791a8cf8dfcf9f420926ae0c | refs/heads/master | 2020-04-05T14:52:58.827500 | 2018-11-10T03:48:00 | 2018-11-10T03:48:00 | 156,944,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,775 | cpp | // Programa que calcula el valor de una integral usando el método de Simpson
// Hernán Iruegas Villarreal A00817021
// 18/03/2018
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <math.h> // Para usar la función de square root
#include <cmath>
#include <iomanip> // Para imprimir los números con la precision de 5 decimales deseadas
using namespace std;
#include "Respuesta.h"
#include "Calculo.h"
//_p=Main
//_b=31
//_i
double getP( double dXAux, int iDof, Calculo calculo ){
double diferencia = 0, error = 0.0000001;
int iNumSeg = 20;
Respuesta *pObj1 = new Respuesta( dXAux, iDof, 10 ); // crear primer objeto
pObj1 -> setP( calculo.calculateP( pObj1 ) ); // calcular P para el primer objeto
Respuesta *pObj2 = new Respuesta( dXAux, iDof, 20 ); // crear segundo objeto
pObj2 -> setP( calculo.calculateP( pObj2 ) ); // calcular P para el segundo objeto
diferencia = pObj1 -> getP() - pObj2 -> getP();
while( abs( diferencia ) >= error ){
pObj1 = pObj2;
iNumSeg *= 2;
pObj2 = new Respuesta( dXAux, iDof, iNumSeg );
pObj2 -> setP( calculo.calculateP( pObj2 ) );
diferencia = pObj1 -> getP() - pObj2 -> getP();
}
return pObj2 -> getP();
}
//_i
double getX( double dPOriginal, int iDof, Calculo calculo ){
double dError = 0.00000000001;
double dXAux = 1.0;
double dIncrement = 0.5;
double dPAux = getP( dXAux, iDof, calculo );
double dDiferencia = dPAux - dPOriginal;
double dDiferenciaAux = dDiferencia;
while( abs( dDiferencia ) >= dError ){
dDiferencia > 0 ? dXAux -= dIncrement : dXAux += dIncrement;
if( (dDiferenciaAux > 0 && dDiferencia < 0) || (dDiferenciaAux < 0 && dDiferencia > 0) ){
dIncrement = dIncrement / 2;
}
dPAux = getP( dXAux, iDof, calculo );
dDiferenciaAux = dDiferencia;
dDiferencia = dPAux - dPOriginal;
}
return dXAux;
}
//_i
int main(){
double dP = 0, diferencia = 0, dXAux = 1, dDeltaInc = dXAux / 2;
int iDof = 0;
Calculo calculo;
cout << "Ingrese el valor de p: "; //_m
cin >> dP; //_m
while( dP < 0 || dP > 0.5 ){
cout << "ERROR: dato invalido. Se debe proporcionar un número real con valor entre 0.0 - 0.5 para p"; //_m
cout << "\nIngrese el valor de p: "; //_m
cin >> dP; //_m
}
cout << "Ingrese el valor para los grados de libertad: ";
cin >> iDof;
while( iDof <= 0 || !cin ){
cout << "ERROR: dato invalido. Se debe proporcionar un número entero mayor a cero para los grados de libertad";
cout << "\nIngrese el valor para los grados de libertad: ";
cin >> iDof;
}
//_d=5
double dX = getX( dP, iDof, calculo );
cout << endl;
cout << " p = " << setprecision(5) << fixed << dP << endl;
cout << "dof = " << iDof << endl;
cout << " x = " << setprecision(5) << fixed << dX << endl; //_m
}
| [
"hernaniruegas@hotmail.com"
] | hernaniruegas@hotmail.com |
060c5c2eb9d027e75b46fc48b296679363de7d84 | 4e8548ed98d96146297393e623cb38fbcc77371b | /utils/joiner/joinpartition.h | 5ce90729692f97a295d8c5f48a9d22897b4dbdd2 | [] | no_license | hans511002/erydb_rep | 9d5a0be919e5d026e921c7fbe000dc70dc7d7ab6 | a2c391b3c36745cb690ce33a22d8794371493ef2 | refs/heads/master | 2021-01-15T12:02:01.093382 | 2018-08-09T10:57:26 | 2018-08-09T10:57:26 | 99,639,427 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,751 | h | /* Copyright (C) 2014 EryDB, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2 of
the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA. */
#ifndef JOINPARTITION_H
#define JOINPARTITION_H
#include "rowgroup.h"
#include "hasher.h"
#include "erydbcompress.h"
#include <vector>
#include <fstream>
#include <boost/thread.hpp>
namespace joiner {
class JoinPartition
{
public:
JoinPartition();
JoinPartition(const rowgroup::RowGroup &largeRG,
const rowgroup::RowGroup &smallRG,
const std::vector<uint32_t> &smallkeyCols,
const std::vector<uint32_t> &largeKeyCols,
bool typeless,
bool isAntiWithMatchNulls,
bool hasFEFilter,
uint64_t totalUMMemory,
uint64_t partitionSize);
JoinPartition(const JoinPartition &, bool splitMode);
virtual ~JoinPartition();
// For now, the root node will use the RGData interface, the branches & leaves use
// only the Row interface.
int64_t insertSmallSideRow(const rowgroup::Row &row);
int64_t insertSmallSideRGData(rowgroup::RGData &);
// note, the vector version of this fcn frees the input RGDatas as it goes
int64_t insertSmallSideRGData(std::vector<rowgroup::RGData> &);
int64_t doneInsertingSmallData();
int64_t insertLargeSideRGData(rowgroup::RGData &);
int64_t insertLargeSideRow(const rowgroup::Row &row);
int64_t doneInsertingLargeData();
/* Returns true if there are more partitions to fetch, false otherwise */
bool getNextPartition(std::vector<rowgroup::RGData> *smallData, uint64_t *partitionID,
JoinPartition **jp);
boost::shared_ptr<rowgroup::RGData> getNextLargeRGData();
/* It's important to follow the sequence of operations to maintain the correct
internal state. Right now it doesn't check that you the programmer are doing things
right, it'll likely fail queries or crash if you do things wrong.
This should be made simpler at some point.
On construction, the JP is config'd for small-side reading.
After that's done, call doneInsertingSmallData() and initForLargeSideFeed().
Then, insert the large-side data. When done, call doneInsertingLargeData()
and initForProcessing().
In the processing phase, use getNextPartition() and getNextLargeRGData()
to get the data back out. After processing all partitions, if it's necessary
to process more iterations of the large side, call initForProcessing() again, and
continue as before.
*/
/* Call this before reading into the large side */
void initForLargeSideFeed();
/* Call this between large-side insertion & join processing */
void initForProcessing();
/* Small outer joins need to retain some state after each large-side iteration */
void saveSmallSidePartition(std::vector<rowgroup::RGData> &rgdata);
/* each JP instance stores the sizes of every JP instance below it, so root node has the total. */
int64_t getCurrentDiskUsage() { return smallSizeOnDisk + largeSizeOnDisk; }
int64_t getSmallSideDiskUsage() { return smallSizeOnDisk; }
int64_t getLargeSideDiskUsage() { return largeSizeOnDisk; }
uint64_t getBytesRead();
uint64_t getBytesWritten();
uint64_t getMaxLargeSize() { return maxLargeSize; }
uint64_t getMaxSmallSize() { return maxSmallSize; }
protected:
private:
void initBuffers();
int64_t convertToSplitMode();
int64_t processSmallBuffer();
int64_t processLargeBuffer();
int64_t processSmallBuffer(rowgroup::RGData &);
int64_t processLargeBuffer(rowgroup::RGData &);
rowgroup::RowGroup smallRG;
rowgroup::RowGroup largeRG;
std::vector<uint32_t> smallKeyCols;
std::vector<uint32_t> largeKeyCols;
bool typelessJoin;
uint32_t hashSeed;
std::vector<boost::shared_ptr<JoinPartition> > buckets;
uint32_t bucketCount; // = TotalUMMem / htTargetSize
bool fileMode;
std::fstream smallFile;
std::fstream largeFile;
std::string filenamePrefix;
std::string smallFilename;
std::string largeFilename;
rowgroup::RGData buffer;
rowgroup::Row smallRow;
rowgroup::Row largeRow;
uint32_t nextPartitionToReturn;
uint64_t htSizeEstimate;
uint64_t htTargetSize;
uint64_t uniqueID;
uint64_t smallSizeOnDisk;
uint64_t largeSizeOnDisk;
utils::Hasher_r hasher;
bool rootNode;
/* Not-in antijoin hack. A small-side row with a null join column has to go into every partition or
into one always resident partition (TBD).
If an F&E filter exists, it needs all null rows, if not, it only needs one. */
bool antiWithMatchNulls;
bool needsAllNullRows;
bool gotNullRow;
bool hasNullJoinColumn(rowgroup::Row &);
// which = 0 -> smallFile, which = 1 -> largeFile
void readByteStream(int which, messageqcpp::ByteStream *bs);
uint64_t writeByteStream(int which, messageqcpp::ByteStream &bs);
/* Compression support */
bool useCompression;
compress::ERYDBCompressInterface compressor;
/* TBD: do the reading/writing in one thread, compression/decompression in another */
/* Some stats for reporting */
uint64_t totalBytesRead, totalBytesWritten;
uint64_t maxLargeSize, maxSmallSize;
/* file descriptor reduction */
size_t nextSmallOffset;
size_t nextLargeOffset;
};
}
#endif // JOINPARTITION_H
| [
"hans511002@sohu.com"
] | hans511002@sohu.com |
d103b65924ed1d54456dce49222041ec33e14fc0 | 8a964d9fdb6e7b1f99ce44b7a38ae9615f8399c3 | /codebase/libs/radar/src/radx/RadxApp.cc | 6c4d293a9225f37515ddc2eedbfe308ea506ec25 | [
"BSD-3-Clause"
] | permissive | zhaopingsun/lrose-core | 93edd9b354ba2db08a52c45a6d9fcd561525403e | 98461699e9cfb8b3547a7143491a0cf42671c66f | refs/heads/master | 2021-10-09T22:21:54.872633 | 2019-01-04T06:18:51 | 2019-01-04T06:18:51 | 110,906,414 | 0 | 0 | null | 2017-11-16T01:20:12 | 2017-11-16T01:20:12 | null | UTF-8 | C++ | false | false | 13,002 | cc | // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
// ** Copyright UCAR (c) 1990 - 2016
// ** University Corporation for Atmospheric Research (UCAR)
// ** National Center for Atmospheric Research (NCAR)
// ** Boulder, Colorado, USA
// ** BSD licence applies - redistribution and use in source and binary
// ** forms, with or without modification, are permitted provided that
// ** the following conditions are met:
// ** 1) If the software is modified to produce derivative works,
// ** such modified software should be clearly marked, so as not
// ** to confuse it with the version available from UCAR.
// ** 2) Redistributions of source code must retain the above copyright
// ** notice, this list of conditions and the following disclaimer.
// ** 3) Redistributions in binary form must reproduce the above copyright
// ** notice, this list of conditions and the following disclaimer in the
// ** documentation and/or other materials provided with the distribution.
// ** 4) Neither the name of UCAR nor the names of its contributors,
// ** if any, may be used to endorse or promote products derived from
// ** this software without specific prior written permission.
// ** DISCLAIMER: THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS
// ** OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
// ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
/**
* @file RadxApp.cc
*/
//------------------------------------------------------------------
#include <radar/RadxApp.hh>
#include <radar/RadxAppParms.hh>
#include <radar/RadxAppVolume.hh>
#include <Radx/RadxRay.hh>
#include <rapmath/MathData.hh>
#include <rapmath/VolumeData.hh>
#include <toolsa/LogMsgStreamInit.hh>
#include <toolsa/LogStream.hh>
#include <toolsa/pmu.h>
#include <toolsa/port.h>
//------------------------------------------------------------------
RadxApp::RadxApp(const MathData &sweepData, const MathData &rayData,
const VolumeData &vdata)
{
_ok = false;
_setupUserUnaryOps(sweepData, rayData, vdata);
}
//------------------------------------------------------------------
RadxApp::RadxApp(const RadxAppParms &parms,
const MathData &sweepData, const MathData &rayData,
const VolumeData &vdata)
{
_ok = true;
_setupUserUnaryOps(sweepData, rayData, vdata);
for (size_t i=0; i<parms._volumeBeforeFilters.size(); ++i)
{
_p.parse(parms._volumeBeforeFilters[i], MathParser::VOLUME_BEFORE,
parms._fixedConstants, parms._userData);
}
for (size_t i=0; i<parms._sweepFilters.size(); ++i)
{
_p.parse(parms._sweepFilters[i], MathParser::LOOP2D, parms._fixedConstants,
parms._userData);
}
for (size_t i=0; i<parms._rayFilters.size(); ++i)
{
_p.parse(parms._rayFilters[i], MathParser::LOOP1D, parms._fixedConstants,
parms._userData);
}
for (size_t i=0; i<parms._volumeAfterFilters.size(); ++i)
{
_p.parse(parms._volumeAfterFilters[i], MathParser::VOLUME_AFTER,
parms._fixedConstants, parms._userData);
}
}
//------------------------------------------------------------------
RadxApp::~RadxApp(void)
{
}
//------------------------------------------------------------------
void RadxApp::printOperators(void) const
{
std::string s = _p.sprintBinaryOperators();
printf("Binary operations:\n%s\n", s.c_str());
s = _p.sprintUnaryOperators();
printf("Unary operations:\n%s\n", s.c_str());
}
//------------------------------------------------------------------
bool RadxApp::algInit(const std::string &appName,
const RadxAppParams &p,
void cleanup(int))
{
PMU_auto_init(appName.c_str(), p.instance, 60);
PORTsignal(SIGQUIT, cleanup);
PORTsignal(SIGTERM, cleanup);
PORTsignal(SIGINT, cleanup);
PORTsignal(SIGPIPE, (PORTsigfunc)SIG_IGN);
// set up debugging state for logging
LogMsgStreamInit::init(p.debug_mode == RadxAppParams::DEBUG ||
p.debug_mode == RadxAppParams::DEBUG_VERBOSE,
p.debug_mode == RadxAppParams::DEBUG_VERBOSE,
true, true);
if (p.debug_triggering)
{
LogMsgStreamInit::setThreading(true);
}
LOG(DEBUG) << "setup";
// set the out of storage handler
// set_new_handler(outOfStore);
// check the inputs to make sure on the list somewhere
// return _params.inputsAccountedFor(inputFields);
return true;
}
//------------------------------------------------------------------
void RadxApp::algFinish(void)
{
PMU_auto_unregister();
}
//------------------------------------------------------------------
bool RadxApp::update(const RadxAppParms &P, RadxAppVolume *input)
{
// do the volume commands first
_p.processVolume(input);
// then the loop commands, 1d
_p.clearOutputDebugAll();
for (int ii=0; ii < input->numProcessingNodes(false); ++ii)
{
_p.processOneItem1d(input, ii);
}
// then the loop commands, 2d
for (int ii=0; ii < input->numProcessingNodes(true); ++ii)
{
_p.processOneItem2d(input, ii);
}
_p.setOutputDebugAll();
// do the final volume commands
_p.processVolumeAfter(input);
// trim to wanted outputs
input->trim();
return true;
}
//---------------------------------------------------------------
bool RadxApp::retrieveRay(const std::string &name, const RadxRay &ray,
const std::vector<RayxData> &data, RayxData &r,
bool showError)
{
// try to find the field in the ray first
if (retrieveRay(name, ray, r, false))
{
return true;
}
// try to find the field in the data vector
for (size_t i=0; i<data.size(); ++i)
{
if (data[i].getName() == name)
{
// return a copy of that ray
r = data[i];
return true;
}
}
if (showError)
{
LOG(ERROR) << "Field " << name << " never found";
}
return false;
}
//---------------------------------------------------------------
bool RadxApp::retrieveRay(const std::string &name, const RadxRay &ray,
RayxData &r, const bool showError)
{
// try to find the field in the ray
const vector<RadxField *> &fields = ray.getFields();
for (size_t ifield = 0; ifield < fields.size(); ifield++)
{
if (fields[ifield]->getName() == name)
{
Radx::DataType_t t = fields[ifield]->getDataType();
if (t != Radx::FL32)
{
// need this to pull out values
fields[ifield]->convertToFl32();
}
r = RayxData(name, fields[ifield]->getUnits(),
fields[ifield]->getNPoints(), fields[ifield]->getMissing(),
ray.getAzimuthDeg(), ray.getElevationDeg(),
ray.getGateSpacingKm(), ray.getStartRangeKm(),
*fields[ifield]);
return true;
}
}
if (showError)
{
LOG(ERROR) << "Field " << name << " never found";
}
return false;
}
//---------------------------------------------------------------
bool RadxApp::retrieveAnyRay(const RadxRay &ray, RayxData &r)
{
// try to find the field in the ray
const vector<RadxField *> &fields = ray.getFields();
for (size_t ifield = 0; ifield < fields.size(); ifield++)
{
Radx::DataType_t t = fields[ifield]->getDataType();
if (t != Radx::FL32)
{
// need this to pull out values
fields[ifield]->convertToFl32();
}
r = RayxData(fields[ifield]->getName(), fields[ifield]->getUnits(),
fields[ifield]->getNPoints(), fields[ifield]->getMissing(),
ray.getAzimuthDeg(), ray.getElevationDeg(),
ray.getGateSpacingKm(), ray.getStartRangeKm(),
*fields[ifield]);
return true;
}
LOG(ERROR) << "No fields in ray";
return false;
}
//---------------------------------------------------------------
RayxData *RadxApp::retrieveRayPtr(const std::string &name, const RadxRay &ray,
std::vector<RayxData> &data,
bool &isNew, bool showError)
{
// try to find the field in the ray first
RayxData *r = retrieveRayPtr(name, ray, false);
if (r !=NULL)
{
isNew = true;
return r;
}
// try to find the field in the data vector
for (size_t i=0; i<data.size(); ++i)
{
if (data[i].getName() == name)
{
isNew = false;
return &(data[i]);
}
}
if (showError)
{
LOG(ERROR) << "Field " << name << " never found";
}
return NULL;
}
//---------------------------------------------------------------
RayxData *RadxApp::retrieveRayPtr(const std::string &name, const RadxRay &ray,
const bool showError)
{
// try to find the field in the ray
const vector<RadxField *> &fields = ray.getFields();
for (size_t ifield = 0; ifield < fields.size(); ifield++)
{
if (fields[ifield]->getName() == name)
{
Radx::DataType_t t = fields[ifield]->getDataType();
if (t != Radx::FL32)
{
// need this to pull out values
fields[ifield]->convertToFl32();
}
RayxData *r = new
RayxData(name, fields[ifield]->getUnits(),
fields[ifield]->getNPoints(), fields[ifield]->getMissing(),
ray.getAzimuthDeg(), ray.getElevationDeg(),
ray.getGateSpacingKm(), ray.getStartRangeKm(),
*fields[ifield]);
return r;
}
}
if (showError)
{
LOG(ERROR) << "Field " << name << " never found";
}
return NULL;
}
//---------------------------------------------------------------
RayxData *RadxApp::retrieveAnyRayPtr(const RadxRay &ray)
{
// try to find the field in the ray
const vector<RadxField *> &fields = ray.getFields();
for (size_t ifield = 0; ifield < fields.size(); ifield++)
{
Radx::DataType_t t = fields[ifield]->getDataType();
if (t != Radx::FL32)
{
// need this to pull out values
fields[ifield]->convertToFl32();
}
RayxData *r =
new RayxData(fields[ifield]->getName(), fields[ifield]->getUnits(),
fields[ifield]->getNPoints(), fields[ifield]->getMissing(),
ray.getAzimuthDeg(), ray.getElevationDeg(),
ray.getGateSpacingKm(), ray.getStartRangeKm(),
*fields[ifield]);
return r;
}
LOG(ERROR) << "No fields in ray";
return NULL;
}
//---------------------------------------------------------------
void RadxApp::modifyRayForOutput(RayxData &r, const std::string &name,
const std::string &units,
const double missing)
{
r.changeName(name);
if (units.empty())
{
return;
}
r.changeUnits(units);
r.changeMissing(missing);
}
//---------------------------------------------------------------
void RadxApp::updateRay(const RayxData &r, RadxRay &ray)
{
// add in the one RayxData, then clear out everything else
int nGatesPrimary = ray.getNGates();
Radx::fl32 *data = new Radx::fl32[nGatesPrimary];
string name = r.getName();
r.retrieveData(data, nGatesPrimary);
ray.addField(name, r.getUnits(), r.getNpoints(), r.getMissing(), data, true);
vector<string> wanted;
wanted.push_back(name);
ray.trimToWantedFields(wanted);
delete [] data;
}
//---------------------------------------------------------------
void RadxApp::updateRay(const vector<RayxData> &raydata, RadxRay &ray)
{
// take all the data and add to the ray.
// note that here should make sure not deleting a result (check names)
if (raydata.empty())
{
return;
}
int nGatesPrimary = ray.getNGates();
Radx::fl32 *data = new Radx::fl32[nGatesPrimary];
string name = raydata[0].getName();
raydata[0].retrieveData(data, nGatesPrimary);
ray.addField(name, raydata[0].getUnits(), raydata[0].getNpoints(),
raydata[0].getMissing(), data, true);
vector<string> wanted;
wanted.push_back(name);
ray.trimToWantedFields(wanted);
// now add in all the other ones
for (int i=1; i<(int)raydata.size(); ++i)
{
raydata[i].retrieveData(data, nGatesPrimary);
ray.addField(raydata[i].getName(), raydata[i].getUnits(),
raydata[i].getNpoints(),
raydata[i].getMissing(), data, true);
}
delete [] data;
}
//---------------------------------------------------------------
bool RadxApp::write(RadxAppVolume *vol)
{
return vol->write();
}
//------------------------------------------------------------------
void RadxApp::_setupUserUnaryOps(const MathData &sweepData,
const MathData &rayData,
const VolumeData &vdata)
{
std::vector<std::pair<std::string,std::string> >
userUops = sweepData.userUnaryOperators();
for (size_t i=0; i<userUops.size(); ++i)
{
_p.addUserUnaryOperator(userUops[i].first, userUops[i].second);
}
userUops = rayData.userUnaryOperators();
for (size_t i=0; i<userUops.size(); ++i)
{
_p.addUserUnaryOperator(userUops[i].first, userUops[i].second);
}
userUops = vdata.userUnaryOperators();
for (size_t i=0; i<userUops.size(); ++i)
{
_p.addUserUnaryOperator(userUops[i].first, userUops[i].second);
}
}
| [
"dixon@ucar.edu"
] | dixon@ucar.edu |
0ccaf1840e7a3383fdc4179123468e14723051e5 | f532dfc68d8ad1a6e7b8aaf5b7dbc92fbf0efc62 | /win32_C++/ConsolProj/C_272p_ex08-01.cpp | 9a8492f2193c019a6cd87d68ff926b9ec8742a3d | [] | no_license | NamYoonJae/InhaGame | 691fda687490fb70699f4018ac2888c0b08b5474 | 6e9872436cecccee44f97694f3a047a1d51d86ab | refs/heads/main | 2023-01-19T11:59:35.578386 | 2020-11-26T08:18:34 | 2020-11-26T08:18:34 | 305,272,697 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 325 | cpp | #include "stdafx.h"
#include <conio.h>
#include <windows.h>
int main(void) {
int aList[5] = { 30, 40 , 10, 50, 20 };
int i = 0;
for (i = 0; i < 5; i++) {
if (aList[0]<aList[i]) {
aList[0] = aList[i];
}
}
for (i = 0; i < 5; i++)
printf("%d\t", aList[i]);
putchar('\n');
printf("MAX: %d\n", aList[0]);
} | [
"nyoonjae@naver.com"
] | nyoonjae@naver.com |
046814dea2febfc3975c8f9b6953d7077d7b564c | d79508660fa6ce1199a6a0c42c021f68d0a2fe1d | /Engine/extern/BOOST/include/boost/wave/util/insert_whitespace_detection.hpp | f17950a083023235a8a792070690dba3a8b6bccc | [
"CC0-1.0"
] | permissive | DanielParra159/EngineAndGame | 702ddd14bf15d4387046837e506b10eb837dda27 | 45af7439633054aa6c9a8e75dd0453f9ce297626 | refs/heads/master | 2020-04-04T16:40:34.796899 | 2017-11-25T21:52:56 | 2017-11-25T21:52:56 | 62,506,317 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,234 | hpp | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
Detect the need to insert a whitespace token into the output stream
http://www.boost.org/
Copyright (c) 2001-2010 Hartmut Kaiser. 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)
=============================================================================*/
#if !defined(INSERT_WHITESPACE_DETECTION_HPP_765EF77B_0513_4967_BDD6_6A38148C4C96_INCLUDED)
#define INSERT_WHITESPACE_DETECTION_HPP_765EF77B_0513_4967_BDD6_6A38148C4C96_INCLUDED
#include <boost/wave/wave_config.hpp>
#include <boost/wave/token_ids.hpp>
// this must occur after all of the includes and before any code appears
#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_PREFIX
#endif
///////////////////////////////////////////////////////////////////////////////
namespace boost {
namespace wave {
namespace util {
namespace impl {
// T_IDENTIFIER
template <typename StringT>
inline bool
would_form_universal_char (StringT const &value)
{
if ('u' != value[0] && 'U' != value[0])
return false;
if ('u' == value[0] && value.size() < 5)
return false;
if ('U' == value[0] && value.size() < 9)
return false;
typename StringT::size_type pos =
value.find_first_not_of("0123456789abcdefABCDEF", 1);
if (StringT::npos == pos ||
('u' == value[0] && pos > 5) ||
('U' == value[0] && pos > 9))
{
return true; // would form an universal char
}
return false;
}
template <typename StringT>
inline bool
handle_identifier(boost::wave::token_id prev,
boost::wave::token_id before, StringT const &value)
{
using namespace boost::wave;
switch (static_cast<unsigned int>(prev)) {
case T_IDENTIFIER:
case T_NONREPLACABLE_IDENTIFIER:
case T_COMPL_ALT:
case T_OR_ALT:
case T_AND_ALT:
case T_NOT_ALT:
case T_XOR_ALT:
case T_ANDASSIGN_ALT:
case T_ORASSIGN_ALT:
case T_XORASSIGN_ALT:
case T_NOTEQUAL_ALT:
case T_FIXEDPOINTLIT:
return true;
case T_FLOATLIT:
case T_INTLIT:
case T_PP_NUMBER:
return (value.size() > 1 || (value[0] != 'e' && value[0] != 'E'));
// avoid constructing universal characters (\u1234)
case TOKEN_FROM_ID('\\', UnknownTokenType):
return would_form_universal_char(value);
}
return false;
}
// T_INTLIT
inline bool
handle_intlit(boost::wave::token_id prev, boost::wave::token_id /*before*/)
{
using namespace boost::wave;
switch (static_cast<unsigned int>(prev)) {
case T_IDENTIFIER:
case T_NONREPLACABLE_IDENTIFIER:
case T_INTLIT:
case T_FLOATLIT:
case T_FIXEDPOINTLIT:
case T_PP_NUMBER:
return true;
}
return false;
}
// T_FLOATLIT
inline bool
handle_floatlit(boost::wave::token_id prev,
boost::wave::token_id /*before*/)
{
using namespace boost::wave;
switch (static_cast<unsigned int>(prev)) {
case T_IDENTIFIER:
case T_NONREPLACABLE_IDENTIFIER:
case T_INTLIT:
case T_FLOATLIT:
case T_FIXEDPOINTLIT:
case T_PP_NUMBER:
return true;
}
return false;
}
// <% T_LEFTBRACE
inline bool
handle_alt_leftbrace(boost::wave::token_id prev,
boost::wave::token_id /*before*/)
{
using namespace boost::wave;
switch (static_cast<unsigned int>(prev)) {
case T_LESS: // <<%
case T_SHIFTLEFT: // <<<%
return true;
}
return false;
}
// <: T_LEFTBRACKET
inline bool
handle_alt_leftbracket(boost::wave::token_id prev,
boost::wave::token_id /*before*/)
{
using namespace boost::wave;
switch (static_cast<unsigned int>(prev)) {
case T_LESS: // <<:
case T_SHIFTLEFT: // <<<:
return true;
}
return false;
}
// T_FIXEDPOINTLIT
inline bool
handle_fixedpointlit(boost::wave::token_id prev,
boost::wave::token_id /*before*/)
{
using namespace boost::wave;
switch (static_cast<unsigned int>(prev)) {
case T_IDENTIFIER:
case T_NONREPLACABLE_IDENTIFIER:
case T_INTLIT:
case T_FLOATLIT:
case T_FIXEDPOINTLIT:
case T_PP_NUMBER:
return true;
}
return false;
}
// T_DOT
inline bool
handle_dot(boost::wave::token_id prev, boost::wave::token_id before)
{
using namespace boost::wave;
switch (static_cast<unsigned int>(prev)) {
case T_DOT:
if (T_DOT == before)
return true; // ...
break;
}
return false;
}
// T_QUESTION_MARK
inline bool
handle_questionmark(boost::wave::token_id prev,
boost::wave::token_id /*before*/)
{
using namespace boost::wave;
switch(static_cast<unsigned int>(prev)) {
case TOKEN_FROM_ID('\\', UnknownTokenType): // \?
case T_QUESTION_MARK: // ??
return true;
}
return false;
}
// T_NEWLINE
inline bool
handle_newline(boost::wave::token_id prev,
boost::wave::token_id before)
{
using namespace boost::wave;
switch(static_cast<unsigned int>(prev)) {
case TOKEN_FROM_ID('\\', UnknownTokenType): // \ \n
case T_DIVIDE:
if (T_QUESTION_MARK == before)
return true; // ?/\n // may be \\n
break;
}
return false;
}
inline bool
handle_parens(boost::wave::token_id prev)
{
switch (static_cast<unsigned int>(prev)) {
case T_LEFTPAREN:
case T_RIGHTPAREN:
case T_LEFTBRACKET:
case T_RIGHTBRACKET:
case T_LEFTBRACE:
case T_RIGHTBRACE:
case T_SEMICOLON:
case T_COMMA:
case T_COLON:
// no insertion between parens/brackets/braces and operators
return false;
default:
break;
}
return true;
}
} // namespace impl
class insert_whitespace_detection
{
public:
insert_whitespace_detection(bool insert_whitespace_ = true)
: insert_whitespace(insert_whitespace_),
prev(boost::wave::T_EOF), beforeprev(boost::wave::T_EOF)
{}
template <typename StringT>
bool must_insert(boost::wave::token_id current, StringT const &value)
{
if (!insert_whitespace)
return false; // skip whitespace insertion alltogether
using namespace boost::wave;
switch (static_cast<unsigned int>(current)) {
case T_NONREPLACABLE_IDENTIFIER:
case T_IDENTIFIER:
return impl::handle_identifier(prev, beforeprev, value);
case T_PP_NUMBER:
case T_INTLIT:
return impl::handle_intlit(prev, beforeprev);
case T_FLOATLIT:
return impl::handle_floatlit(prev, beforeprev);
case T_STRINGLIT:
if (TOKEN_FROM_ID('L', IdentifierTokenType) == prev) // 'L'
return true;
break;
case T_LEFTBRACE_ALT:
return impl::handle_alt_leftbrace(prev, beforeprev);
case T_LEFTBRACKET_ALT:
return impl::handle_alt_leftbracket(prev, beforeprev);
case T_FIXEDPOINTLIT:
return impl::handle_fixedpointlit(prev, beforeprev);
case T_DOT:
return impl::handle_dot(prev, beforeprev);
case T_QUESTION_MARK:
return impl::handle_questionmark(prev, beforeprev);
case T_NEWLINE:
return impl::handle_newline(prev, beforeprev);
case T_LEFTPAREN:
case T_RIGHTPAREN:
case T_LEFTBRACKET:
case T_RIGHTBRACKET:
case T_SEMICOLON:
case T_COMMA:
case T_COLON:
switch (static_cast<unsigned int>(prev)) {
case T_LEFTPAREN:
case T_RIGHTPAREN:
case T_LEFTBRACKET:
case T_RIGHTBRACKET:
case T_LEFTBRACE:
case T_RIGHTBRACE:
return false; // no insertion between parens/brackets/braces
default:
if (IS_CATEGORY(prev, OperatorTokenType))
return false;
break;
}
break;
case T_LEFTBRACE:
case T_RIGHTBRACE:
switch (static_cast<unsigned int>(prev)) {
case T_LEFTPAREN:
case T_RIGHTPAREN:
case T_LEFTBRACKET:
case T_RIGHTBRACKET:
case T_LEFTBRACE:
case T_RIGHTBRACE:
case T_SEMICOLON:
case T_COMMA:
case T_COLON:
return false; // no insertion between parens/brackets/braces
case T_QUESTION_MARK:
if (T_QUESTION_MARK == beforeprev)
return true;
if (IS_CATEGORY(prev, OperatorTokenType))
return false;
break;
default:
break;
}
break;
case T_MINUS:
case T_MINUSMINUS:
case T_MINUSASSIGN:
if (T_MINUS == prev || T_MINUSMINUS == prev)
return true;
if (!impl::handle_parens(prev))
return false;
if (T_QUESTION_MARK == prev && T_QUESTION_MARK == beforeprev)
return true;
break;
case T_PLUS:
case T_PLUSPLUS:
case T_PLUSASSIGN:
if (T_PLUS == prev || T_PLUSPLUS == prev)
return true;
if (!impl::handle_parens(prev))
return false;
if (T_QUESTION_MARK == prev && T_QUESTION_MARK == beforeprev)
return true;
break;
case T_DIVIDE:
case T_DIVIDEASSIGN:
if (T_DIVIDE == prev)
return true;
if (!impl::handle_parens(prev))
return false;
if (T_QUESTION_MARK == prev && T_QUESTION_MARK == beforeprev)
return true;
break;
case T_EQUAL:
case T_ASSIGN:
switch (static_cast<unsigned int>(prev)) {
case T_PLUSASSIGN:
case T_MINUSASSIGN:
case T_DIVIDEASSIGN:
case T_STARASSIGN:
case T_SHIFTRIGHTASSIGN:
case T_SHIFTLEFTASSIGN:
case T_EQUAL:
case T_NOTEQUAL:
case T_LESSEQUAL:
case T_GREATEREQUAL:
case T_LESS:
case T_GREATER:
case T_PLUS:
case T_MINUS:
case T_STAR:
case T_DIVIDE:
case T_ORASSIGN:
case T_ANDASSIGN:
case T_XORASSIGN:
case T_OR:
case T_AND:
case T_XOR:
case T_OROR:
case T_ANDAND:
return true;
case T_QUESTION_MARK:
if (T_QUESTION_MARK == beforeprev)
return true;
break;
default:
if (!impl::handle_parens(prev))
return false;
break;
}
break;
case T_GREATER:
if (T_MINUS == prev || T_GREATER == prev)
return true; // prevent -> or >>
if (!impl::handle_parens(prev))
return false;
if (T_QUESTION_MARK == prev && T_QUESTION_MARK == beforeprev)
return true;
break;
case T_LESS:
if (T_LESS == prev)
return true; // prevent <<
// fall through
case T_CHARLIT:
case T_NOT:
case T_NOTEQUAL:
if (!impl::handle_parens(prev))
return false;
if (T_QUESTION_MARK == prev && T_QUESTION_MARK == beforeprev)
return true;
break;
case T_AND:
case T_ANDAND:
if (!impl::handle_parens(prev))
return false;
if (T_AND == prev || T_ANDAND == prev)
return true;
break;
case T_OR:
if (!impl::handle_parens(prev))
return false;
if (T_OR == prev)
return true;
break;
case T_XOR:
if (!impl::handle_parens(prev))
return false;
if (T_XOR == prev)
return true;
break;
case T_COMPL_ALT:
case T_OR_ALT:
case T_AND_ALT:
case T_NOT_ALT:
case T_XOR_ALT:
case T_ANDASSIGN_ALT:
case T_ORASSIGN_ALT:
case T_XORASSIGN_ALT:
case T_NOTEQUAL_ALT:
switch (static_cast<unsigned int>(prev)) {
case T_LEFTPAREN:
case T_RIGHTPAREN:
case T_LEFTBRACKET:
case T_RIGHTBRACKET:
case T_LEFTBRACE:
case T_RIGHTBRACE:
case T_SEMICOLON:
case T_COMMA:
case T_COLON:
// no insertion between parens/brackets/braces and operators
return false;
case T_IDENTIFIER:
if (T_NONREPLACABLE_IDENTIFIER == prev ||
IS_CATEGORY(prev, KeywordTokenType))
{
return true;
}
break;
default:
break;
}
break;
case T_STAR:
if (T_STAR == prev)
return false; // '*****' do not need to be separated
if (T_GREATER== prev &&
(T_MINUS == beforeprev || T_MINUSMINUS == beforeprev)
)
{
return true; // prevent ->*
}
break;
case T_POUND:
if (T_POUND == prev)
return true;
break;
}
// FIXME: else, handle operators separately (will catch to many cases)
// if (IS_CATEGORY(current, OperatorTokenType) &&
// IS_CATEGORY(prev, OperatorTokenType))
// {
// return true; // operators must be delimited always
// }
return false;
}
void shift_tokens (boost::wave::token_id next_id)
{
if (insert_whitespace) {
beforeprev = prev;
prev = next_id;
}
}
private:
bool insert_whitespace; // enable this component
boost::wave::token_id prev; // the previous analyzed token
boost::wave::token_id beforeprev; // the token before the previous
};
///////////////////////////////////////////////////////////////////////////////
} // namespace util
} // namespace wave
} // namespace boost
// the suffix header occurs after all of the code
#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_SUFFIX
#endif
#endif // !defined(INSERT_WHITESPACE_DETECTION_HPP_765EF77B_0513_4967_BDD6_6A38148C4C96_INCLUDED)
| [
"dani.parra.90@gmail.com"
] | dani.parra.90@gmail.com |
420a231f43d9dd10d7efed07c783d72f1b6436ce | 4c36d21c357042cc0f981b90c05ae9f3f03152ec | /jzoj 2289.cpp | 55f9507237332b08b3816a54473af6ae33469e04 | [] | no_license | wwwzbwcom/oi-codes | 09e3192372741815c97821cc96a63b57541db835 | 97dac2e3eacb0c7ce6cf673b52c079bff058dc71 | refs/heads/master | 2023-04-03T17:25:23.237560 | 2021-04-13T07:36:23 | 2021-04-13T08:09:26 | 357,472,761 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,143 | cpp | #include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
struct Matrix
{
int m[210][210];
int y,x;
Matrix(int yi,int xi)
{
for(int i=0;i<210;i++) for(int j=0;j<210;j++) m[i][j]=1e9;
y=yi; x=xi;
}
Matrix operator *(const Matrix &in)const
{
Matrix ans(y,in.x);
for(int i=0;i<y;i++)
for(int j=0;j<in.x;j++)
for(int k=0;k<x;k++)
ans.m[i][j]=min(ans.m[i][j],m[i][k]+in.m[k][j]);
return ans;
}
Matrix operator ^(const int &in)const
{
if(in==1) return *this;
else
{
Matrix tmp=(*this)^(in/2);
if(in%2==0) return tmp*tmp;
else return tmp*tmp*(*this);
}
}
};
int n,t,s,e;
int c[300],u[300],v[300];
int sto[600],sn;
int main()
{
cin>>n>>t>>s>>e;
sto[sn++]=s;
sto[sn++]=e;
for(int i=1;i<=t;i++)
{
cin>>c[i]>>u[i]>>v[i];
sto[sn++]=u[i]; sto[sn++]=v[i];
}
sort(sto,sto+sn);
sn=unique(sto,sto+sn)-sto;
s=lower_bound(sto,sto+sn,s)-sto;
e=lower_bound(sto,sto+sn,e)-sto;
Matrix m(sn,sn);
for(int i=1;i<=t;i++)
{
u[i]=lower_bound(sto,sto+sn,u[i])-sto;
v[i]=lower_bound(sto,sto+sn,v[i])-sto;
m.m[u[i]][v[i]]=m.m[v[i]][u[i]]=c[i];
}
m=m^n;
cout<<m.m[s][e]<<endl;
}
| [
"zbwhome@outlook.com"
] | zbwhome@outlook.com |
c6ddcb486226b6ac3b83cecd9701bc0f9a75f54c | b19ba556fabb0fed9f1503dbbd6b179ff90ecfc0 | /math/Vector3.cpp | 74c837f04477a67639ea04cd197f4bcf3979dec7 | [
"MIT"
] | permissive | nfoste82/engine | d44806ef4b0becc9e5c4edb4e9997fa432956a72 | 9b64077778bf3548a8d1a53bddcaabada7a2957e | refs/heads/master | 2021-01-25T05:50:51.095014 | 2019-11-02T00:34:24 | 2019-11-02T00:34:24 | 80,693,891 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,605 | cpp | #include "Vector3.hpp"
#include <sstream>
const Vector3 Vector3::Right(1.f, 0.f, 0.f);
const Vector3 Vector3::Up(0.f, 1.f, 0.f);
const Vector3 Vector3::Forward(0.f, 0.f, 1.f);
const Vector3 Vector3::Left(-1.f, 0.f, 0.f);
const Vector3 Vector3::Down(0.f, -1.f, 0.f);
const Vector3 Vector3::Backward(0.f, 0.f, -1.f);
const Vector3 Vector3::UnitX(1.f, 0.f, 0.f);
const Vector3 Vector3::UnitY(0.f, 1.f, 0.f);
const Vector3 Vector3::UnitZ(0.f, 0.f, 1.f);
const Vector3 Vector3::Zero(0.0f, 0.0f, 0.0f);
const Vector3 Vector3::One(1.0f, 1.0f, 1.0f);
Vector3::Vector3() :
x(0.0f), y(0.0f), z(0.0f)
{
}
Vector3::Vector3(const float _x, const float _y, const float _z) :
x(_x), y(_y), z(_z)
{
}
// Copy constructor
Vector3::Vector3(const Vector3& rhs) :
x(rhs.x), y(rhs.y), z(rhs.z)
{
}
Vector3::~Vector3()
{
}
Vector3 Vector3::operator+(const Vector3& rhs) const
{
return Vector3(x + rhs.x, y + rhs.y, z + rhs.z);
}
void Vector3::operator+=(const Vector3& rhs)
{
x += rhs.x;
y += rhs.y;
z += rhs.z;
}
Vector3 Vector3::operator-(const Vector3& rhs) const
{
return Vector3(x - rhs.x, y - rhs.y, z - rhs.z);
}
Vector3 Vector3::operator-() const
{
return Vector3(-x, -y, -z);
}
void Vector3::operator-=(const Vector3& rhs)
{
x -= rhs.x;
y -= rhs.y;
z -= rhs.z;
}
void Vector3::operator*=(const int scalar)
{
x *= scalar;
y *= scalar;
z *= scalar;
}
void Vector3::operator*=(const float scalar)
{
x *= scalar;
y *= scalar;
z *= scalar;
}
Vector3 operator*(const Vector3& vector, const int scalar)
{
return Vector3(vector.x * scalar, vector.y * scalar, vector.z * scalar);
}
Vector3 operator*(const Vector3& vector, const float scalar)
{
return Vector3(vector.x * scalar, vector.y * scalar, vector.z * scalar);
}
Vector3 operator*(const int scalar, const Vector3& vector)
{
return Vector3(vector.x * scalar, vector.y * scalar, vector.z * scalar);
}
Vector3 operator*(const float scalar, const Vector3& vector)
{
return Vector3(vector.x * scalar, vector.y * scalar, vector.z * scalar);
}
std::ostream& operator<< (std::ostream& os, const Vector3& vector)
{
std::stringstream stream;
stream << "X: " << vector.x << ", Y: " << vector.y << ", Z: " << vector.z;
os.write(const_cast<char*>(stream.str().c_str()),
static_cast<std::streamsize>(stream.str().size() *
sizeof(char)) );
return os;
}
Vector3 Vector3::Cross(const Vector3& rhs) const
{
return Vector3( (y * rhs.z) - (z * rhs.y),
(z * rhs.x) - (x * rhs.z),
(x * rhs.y) - (y * rhs.x) );
}
float Vector3::Unitize()
{
const float length = Length();
const float inverseLength = 1.0f / length;
x *= inverseLength;
y *= inverseLength;
z *= inverseLength;
return length;
}
void Vector3::Reflect(const Vector3& normal)
{
const float dotProductTimesTwo = Dot(normal) * 2.0f;
x -= dotProductTimesTwo * normal.x;
y -= dotProductTimesTwo * normal.y;
z -= dotProductTimesTwo * normal.z;
}
Vector3 Vector3::Reflect(const Vector3& vector, const Vector3& normal)
{
Vector3 newVector;
const float dotProductTimesTwo = vector.Dot(normal) * 2.0f;
newVector.x = vector.x - (dotProductTimesTwo * normal.x);
newVector.y = vector.y - (dotProductTimesTwo * normal.y);
newVector.z = vector.z - (dotProductTimesTwo * normal.z);
return newVector;
}
Vector3 Vector3::GetLongest(const Vector3& first, const Vector3& second)
{
if (first.LengthSqr() > second.LengthSqr())
{
return first;
}
return second;
}
| [
"nfoster@backflipstudios.com"
] | nfoster@backflipstudios.com |
c605c324559b3a4e93c33b353380e16f50e83dc7 | d52f87ffa9ee7ebef078963baf8d62d852880589 | /play.cpp | 0705d7e56ea3d2dcd5b44c45d180bb834d07634a | [] | no_license | zen3d/lua-music | 74b87666b0a8eb2b53374c73cb30f1634ed63331 | 60011989a35e4c964bea4754df9561808579d15b | refs/heads/master | 2021-12-07T20:12:18.907363 | 2016-01-08T20:49:53 | 2016-01-08T22:57:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,337 | cpp | /*
* =====================================================================================
*
* Filename: play.cpp
*
* Description: Creates the Lua interpreter
*
* Version: 1.0
* Created: 01/08/2016 14:32:34
* Revision: none
* Compiler: cmake
*
* Author: Jake via 'Seven More Languages in Seven Weeks'
* Organization: Thunder February, LTD
*
* =====================================================================================
*/
extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
#include "RtMidi.h"
static RtMidiOut midi;
int midi_send(lua_State* L)
{
double status = lua_tonumber(L, -3);
double data1 = lua_tonumber(L, -2);
double data2 = lua_tonumber(L, -1);
std::vector<unsigned char> message(3);
message[0] = static_cast<unsigned char>(status);
message[1] = static_cast<unsigned char>(data1);
message[2] = static_cast<unsigned char>(data2);
midi.sendMessage(&message);
return 0;
}
int main(int argc, const char* argv[])
{
if (argc < 1) { return -1; }
unsigned int ports = midi.getPortCount();
if (ports < 1) { return -1; }
midi.openPort(0);
lua_State* L = luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, midi_send);
lua_setglobal(L, "midi_send");
luaL_dofile(L, argv[1]);
lua_close(L);
return 0;
}
| [
"jakeworth82@gmail.com"
] | jakeworth82@gmail.com |
29d65e3cd617a1ba643dbd3f65fffb849180df9d | 189f52bf5454e724d5acc97a2fa000ea54d0e102 | /ras/fluidisedBed/1.96/T.air | 2fcd019c4c828978e2b9442056f2ae8ed1985a76 | [] | no_license | pyotr777/openfoam_samples | 5399721dd2ef57545ffce68215d09c49ebfe749d | 79c70ac5795decff086dd16637d2d063fde6ed0d | refs/heads/master | 2021-01-12T16:52:18.126648 | 2016-11-05T08:30:29 | 2016-11-05T08:30:29 | 71,456,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 47,701 | air | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1606+ |
| \\ / A nd | Web: www.OpenFOAM.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "1.96";
object T.air;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 1 0 0 0];
internalField nonuniform List<scalar>
6000
(
528.068
530.663
532.435
538.299
539.131
539.037
537.797
534.757
530.619
527.951
526.426
525.282
525.305
524.805
520.407
518.685
523.478
530.472
536.819
540.171
541.75
542.676
543.077
542.963
542.479
542.134
541.714
538.765
532.589
529.395
588.232
586.71
589.653
593.108
593.957
593.287
592.543
592.787
592.746
589.724
580.189
577.533
578.759
578.099
575.995
576.291
587.078
593.098
594.871
595.442
595.681
595.755
595.801
595.653
595.217
594.808
594.591
593.193
589.332
588.071
596.969
595.475
597.664
598.867
599.242
599.332
599.285
599.337
599.337
598.612
594.704
588.426
587.165
586.816
588.884
593.169
597.543
599.172
599.526
599.587
599.596
599.599
599.594
599.56
599.474
599.261
598.739
597.322
595.592
596.148
598.873
598.487
599.405
599.746
599.833
599.854
599.854
599.856
599.857
599.784
599.273
597.06
591.368
589.635
594.401
598.279
599.462
599.766
599.807
599.788
599.754
599.74
599.743
599.755
599.755
599.73
599.612
599.22
598.572
598.656
599.675
599.548
599.747
599.839
599.855
599.844
599.822
599.809
599.806
599.795
599.7
599.066
596.016
591.35
594.01
598.717
599.583
599.701
599.65
599.597
599.569
599.569
599.617
599.676
599.736
599.771
599.775
599.719
599.564
599.533
599.864
599.819
599.829
599.831
599.802
599.768
599.745
599.725
599.709
599.681
599.6
599.234
597.549
593.348
594.054
598.473
599.321
599.331
599.301
599.349
599.372
599.406
599.469
599.538
599.627
599.72
599.774
599.788
599.768
599.766
599.883
599.841
599.818
599.78
599.742
599.714
599.689
599.665
599.637
599.582
599.439
598.98
597.476
594.11
594.336
597.665
598.5
598.508
598.835
599.08
599.183
599.244
599.331
599.428
599.522
599.616
599.723
599.786
599.79
599.802
599.864
599.8
599.765
599.736
599.713
599.686
599.654
599.614
599.564
599.473
599.239
598.49
596.546
594.491
594.838
596.46
597.148
597.401
598.148
598.719
598.963
599.082
599.194
599.306
599.424
599.552
599.671
599.746
599.781
599.8
599.805
599.766
599.742
599.717
599.688
599.654
599.615
599.565
599.493
599.346
598.966
597.864
596.006
595.179
595.402
595.894
596.322
596.641
597.341
598.258
598.722
598.941
599.084
599.211
599.338
599.483
599.622
599.705
599.747
599.769
599.769
599.755
599.733
599.706
599.675
599.638
599.59
599.525
599.421
599.193
598.589
597.17
595.97
595.68
595.764
595.933
596.15
596.405
596.97
597.953
598.568
598.855
599.021
599.154
599.288
599.444
599.575
599.667
599.722
599.748
599.764
599.755
599.736
599.706
599.674
599.634
599.581
599.502
599.358
599.021
598.176
596.773
596.047
595.927
596.041
596.192
596.367
596.55
596.96
597.854
598.509
598.819
598.992
599.127
599.263
599.413
599.533
599.633
599.698
599.727
599.765
599.756
599.74
599.716
599.685
599.648
599.594
599.503
599.324
598.896
597.924
596.781
596.301
596.302
596.521
596.763
596.947
597.076
597.384
598.064
598.577
598.839
598.996
599.127
599.258
599.394
599.506
599.609
599.682
599.714
599.773
599.765
599.75
599.728
599.699
599.665
599.62
599.539
599.354
598.908
597.978
597.12
596.874
597.032
597.448
597.732
597.773
597.771
597.912
598.316
598.688
598.89
599.027
599.146
599.262
599.381
599.492
599.598
599.676
599.712
599.799
599.786
599.769
599.751
599.724
599.689
599.649
599.59
599.455
599.086
598.331
597.725
597.566
597.762
598.202
598.491
598.472
598.234
598.255
598.53
598.789
598.946
599.066
599.174
599.277
599.383
599.49
599.597
599.68
599.722
599.835
599.833
599.805
599.784
599.763
599.73
599.687
599.638
599.553
599.338
598.812
598.323
598.196
598.304
598.611
598.936
598.912
598.526
598.493
598.694
598.865
598.993
599.106
599.211
599.308
599.404
599.503
599.607
599.695
599.744
599.857
599.86
599.857
599.835
599.818
599.797
599.754
599.711
599.666
599.573
599.207
598.849
598.763
598.794
598.95
599.219
599.235
598.814
598.701
598.793
598.912
599.032
599.147
599.256
599.352
599.444
599.537
599.633
599.719
599.785
599.876
599.879
599.88
599.876
599.863
599.866
599.855
599.831
599.812
599.75
599.522
599.266
599.214
599.245
599.334
599.447
599.396
598.924
598.805
598.845
598.946
599.076
599.204
599.32
599.415
599.503
599.591
599.676
599.754
599.824
599.89
599.89
599.89
599.887
599.884
599.884
599.884
599.875
599.855
599.811
599.711
599.583
599.552
599.55
599.537
599.489
599.328
599.079
598.915
598.905
598.998
599.148
599.286
599.408
599.493
599.576
599.656
599.731
599.793
599.845
599.897
599.897
599.897
599.895
599.892
599.891
599.89
599.881
599.856
599.817
599.763
599.697
599.634
599.557
599.498
599.429
599.405
599.396
599.223
599.083
599.127
599.295
599.453
599.535
599.588
599.658
599.726
599.787
599.836
599.871
599.904
599.904
599.903
599.901
599.898
599.895
599.892
599.881
599.848
599.795
599.731
599.654
599.573
599.523
599.501
599.51
599.548
599.582
599.572
599.531
599.527
599.574
599.659
599.656
599.69
599.746
599.799
599.845
599.878
599.9
599.911
599.91
599.908
599.906
599.903
599.9
599.895
599.881
599.839
599.767
599.685
599.613
599.573
599.564
599.577
599.608
599.644
599.667
599.671
599.663
599.657
599.67
599.7
599.734
599.787
599.84
599.882
599.909
599.917
599.927
599.915
599.914
599.912
599.91
599.907
599.903
599.898
599.883
599.836
599.752
599.67
599.623
599.608
599.617
599.638
599.666
599.693
599.706
599.709
599.706
599.704
599.711
599.727
599.75
599.785
599.844
599.902
599.939
599.949
599.95
599.917
599.916
599.914
599.912
599.909
599.905
599.899
599.886
599.838
599.749
599.68
599.65
599.645
599.659
599.682
599.705
599.72
599.726
599.727
599.727
599.731
599.741
599.752
599.763
599.781
599.816
599.872
599.921
599.955
599.96
599.919
599.918
599.916
599.913
599.909
599.905
599.899
599.889
599.848
599.759
599.698
599.677
599.676
599.691
599.71
599.724
599.733
599.738
599.741
599.745
599.753
599.765
599.772
599.776
599.785
599.802
599.842
599.903
599.948
599.953
599.921
599.92
599.917
599.914
599.909
599.903
599.896
599.887
599.86
599.78
599.718
599.699
599.699
599.712
599.725
599.733
599.739
599.744
599.751
599.76
599.774
599.787
599.789
599.789
599.789
599.797
599.822
599.883
599.94
599.948
599.925
599.923
599.92
599.915
599.909
599.901
599.892
599.882
599.865
599.803
599.734
599.715
599.714
599.725
599.732
599.737
599.743
599.75
599.758
599.769
599.785
599.798
599.801
599.801
599.799
599.799
599.814
599.864
599.929
599.939
599.93
599.93
599.925
599.918
599.91
599.898
599.885
599.873
599.859
599.828
599.758
599.732
599.73
599.736
599.741
599.745
599.75
599.757
599.766
599.778
599.793
599.806
599.81
599.81
599.809
599.806
599.814
599.851
599.917
599.929
599.937
599.948
599.962
599.928
599.913
599.895
599.876
599.863
599.85
599.83
599.786
599.755
599.75
599.753
599.756
599.759
599.763
599.769
599.777
599.788
599.803
599.814
599.818
599.818
599.816
599.814
599.818
599.843
599.9
599.919
599.977
599.98
599.974
599.959
599.925
599.894
599.868
599.853
599.841
599.826
599.798
599.774
599.77
599.773
599.775
599.778
599.781
599.786
599.793
599.801
599.813
599.823
599.827
599.827
599.825
599.823
599.824
599.839
599.87
599.903
599.986
599.983
599.977
599.965
599.945
599.899
599.864
599.846
599.836
599.824
599.804
599.789
599.788
599.79
599.793
599.795
599.799
599.803
599.807
599.814
599.822
599.831
599.836
599.836
599.835
599.833
599.833
599.841
599.855
599.891
599.987
599.985
599.978
599.967
599.954
599.92
599.863
599.841
599.832
599.823
599.81
599.803
599.804
599.806
599.808
599.81
599.813
599.816
599.82
599.825
599.832
599.84
599.846
599.847
599.846
599.844
599.843
599.846
599.854
599.879
599.988
599.986
599.979
599.968
599.952
599.927
599.867
599.837
599.831
599.825
599.819
599.819
599.819
599.821
599.822
599.824
599.826
599.829
599.832
599.836
599.842
599.849
599.855
599.857
599.857
599.856
599.855
599.855
599.857
599.869
599.99
599.987
599.98
599.966
599.949
599.923
599.863
599.837
599.834
599.833
599.834
599.834
599.834
599.835
599.836
599.837
599.838
599.84
599.843
599.847
599.853
599.86
599.866
599.868
599.868
599.868
599.867
599.866
599.861
599.865
599.991
599.988
599.98
599.961
599.935
599.901
599.859
599.847
599.851
599.85
599.85
599.849
599.849
599.849
599.849
599.85
599.851
599.852
599.855
599.858
599.863
599.869
599.876
599.878
599.879
599.879
599.878
599.875
599.865
599.864
599.992
599.989
599.98
599.952
599.914
599.881
599.861
599.862
599.869
599.867
599.865
599.863
599.862
599.862
599.862
599.862
599.863
599.864
599.866
599.869
599.873
599.879
599.885
599.888
599.889
599.889
599.887
599.882
599.87
599.867
599.993
599.99
599.979
599.94
599.897
599.875
599.867
599.877
599.881
599.88
599.877
599.876
599.875
599.875
599.875
599.875
599.876
599.877
599.878
599.88
599.883
599.887
599.892
599.896
599.897
599.897
599.895
599.887
599.879
599.879
599.993
599.99
599.978
599.932
599.891
599.878
599.879
599.888
599.89
599.889
599.888
599.888
599.888
599.889
599.889
599.889
599.89
599.89
599.891
599.892
599.893
599.895
599.898
599.902
599.904
599.905
599.903
599.895
599.889
599.889
599.993
599.99
599.977
599.926
599.894
599.887
599.892
599.897
599.897
599.898
599.9
599.901
599.902
599.903
599.903
599.903
599.903
599.903
599.903
599.903
599.904
599.904
599.905
599.907
599.91
599.911
599.91
599.905
599.9
599.901
599.993
599.99
599.974
599.924
599.902
599.899
599.901
599.904
599.908
599.91
599.912
599.913
599.914
599.914
599.914
599.914
599.914
599.913
599.913
599.913
599.912
599.912
599.912
599.912
599.915
599.917
599.917
599.914
599.911
599.911
599.994
599.989
599.966
599.924
599.91
599.908
599.912
599.916
599.918
599.919
599.92
599.921
599.921
599.921
599.921
599.921
599.921
599.92
599.92
599.919
599.919
599.918
599.917
599.918
599.919
599.921
599.922
599.921
599.92
599.92
599.995
599.988
599.961
599.926
599.918
599.922
599.924
599.925
599.925
599.926
599.926
599.926
599.927
599.926
599.926
599.926
599.925
599.925
599.924
599.924
599.923
599.923
599.922
599.922
599.923
599.925
599.927
599.927
599.927
599.927
599.996
599.987
599.954
599.932
599.931
599.931
599.931
599.931
599.931
599.931
599.931
599.931
599.93
599.93
599.929
599.929
599.928
599.928
599.928
599.927
599.927
599.927
599.927
599.926
599.927
599.929
599.931
599.932
599.932
599.933
599.996
599.985
599.945
599.939
599.937
599.936
599.935
599.935
599.935
599.934
599.934
599.934
599.933
599.932
599.932
599.931
599.93
599.93
599.93
599.93
599.93
599.93
599.93
599.93
599.931
599.933
599.935
599.936
599.937
599.938
599.995
599.964
599.945
599.942
599.94
599.938
599.938
599.938
599.938
599.938
599.937
599.936
599.935
599.934
599.933
599.933
599.932
599.932
599.931
599.932
599.932
599.933
599.933
599.934
599.934
599.936
599.938
599.94
599.941
599.943
599.976
599.949
599.946
599.944
599.942
599.941
599.941
599.941
599.941
599.94
599.94
599.939
599.938
599.936
599.935
599.934
599.933
599.933
599.933
599.933
599.934
599.935
599.936
599.937
599.937
599.939
599.942
599.944
599.945
599.948
599.953
599.95
599.948
599.946
599.943
599.943
599.943
599.944
599.943
599.943
599.942
599.941
599.94
599.938
599.937
599.936
599.934
599.934
599.934
599.935
599.936
599.937
599.938
599.939
599.94
599.942
599.945
599.947
599.949
599.952
599.954
599.953
599.951
599.948
599.945
599.946
599.946
599.946
599.946
599.946
599.945
599.944
599.942
599.941
599.939
599.937
599.935
599.934
599.934
599.937
599.938
599.939
599.941
599.942
599.943
599.945
599.948
599.951
599.953
599.96
599.957
599.956
599.954
599.952
599.95
599.949
599.949
599.949
599.949
599.948
599.947
599.946
599.945
599.943
599.941
599.939
599.937
599.936
599.936
599.937
599.94
599.942
599.943
599.944
599.945
599.947
599.95
599.954
599.957
599.969
599.96
599.959
599.957
599.956
599.954
599.953
599.952
599.952
599.952
599.951
599.95
599.949
599.948
599.946
599.943
599.941
599.94
599.941
599.94
599.94
599.943
599.945
599.946
599.947
599.948
599.949
599.953
599.957
599.961
599.973
599.963
599.963
599.963
599.963
599.959
599.956
599.955
599.955
599.955
599.954
599.953
599.952
599.951
599.952
599.948
599.945
599.944
599.945
599.945
599.945
599.947
599.948
599.949
599.95
599.951
599.951
599.954
599.96
599.966
599.974
599.967
599.968
599.973
599.974
599.967
599.959
599.958
599.958
599.958
599.957
599.957
599.956
599.959
599.969
599.964
599.955
599.951
599.95
599.951
599.952
599.952
599.951
599.952
599.953
599.953
599.954
599.956
599.964
599.97
599.976
599.975
599.986
599.988
599.986
599.976
599.963
599.961
599.961
599.961
599.961
599.96
599.961
599.969
599.975
599.971
599.964
599.96
599.958
599.959
599.962
599.962
599.956
599.955
599.956
599.956
599.957
599.959
599.968
599.974
599.979
599.993
599.989
599.993
599.992
599.987
599.967
599.964
599.964
599.964
599.964
599.964
599.965
599.973
599.975
599.97
599.963
599.959
599.958
599.959
599.963
599.966
599.962
599.959
599.959
599.959
599.96
599.962
599.972
599.978
599.983
599.995
599.997
599.993
599.992
599.987
599.974
599.967
599.967
599.967
599.967
599.967
599.968
599.975
599.975
599.968
599.961
599.957
599.955
599.954
599.956
599.961
599.966
599.962
599.962
599.963
599.963
599.966
599.977
599.985
599.989
599.998
599.996
599.996
599.995
599.993
599.987
599.971
599.97
599.97
599.97
599.97
599.972
599.977
599.976
599.969
599.963
599.961
599.959
599.958
599.957
599.958
599.965
599.965
599.966
599.966
599.967
599.97
599.987
599.993
599.995
599.998
599.998
599.997
599.996
599.996
599.993
599.977
599.974
599.974
599.973
599.973
599.974
599.978
599.975
599.969
599.967
599.966
599.964
599.963
599.961
599.96
599.966
599.97
599.971
599.97
599.971
599.975
599.992
599.996
599.995
599.998
599.998
599.997
599.997
599.997
599.991
599.979
599.978
599.977
599.976
599.976
599.976
599.977
599.973
599.97
599.969
599.968
599.967
599.966
599.963
599.961
599.968
599.977
599.977
599.975
599.977
599.985
599.996
599.997
599.998
599.997
599.997
599.997
599.997
599.996
599.989
599.983
599.981
599.98
599.979
599.977
599.976
599.974
599.972
599.971
599.97
599.97
599.969
599.968
599.965
599.964
599.969
599.982
599.984
599.984
599.987
599.995
599.998
599.998
599.998
599.997
599.998
599.997
599.997
599.994
599.987
599.985
599.983
599.982
599.98
599.976
599.973
599.973
599.973
599.972
599.971
599.971
599.97
599.969
599.968
599.967
599.972
599.986
599.991
599.995
599.997
599.998
599.998
599.998
599.998
599.998
599.998
599.997
599.995
599.99
599.988
599.987
599.985
599.984
599.98
599.974
599.973
599.975
599.975
599.974
599.972
599.971
599.971
599.97
599.97
599.971
599.976
599.989
599.995
599.997
599.996
599.998
599.998
599.998
599.998
599.998
599.997
599.996
599.993
599.991
599.989
599.988
599.987
599.985
599.98
599.975
599.977
599.978
599.977
599.975
599.973
599.972
599.972
599.972
599.973
599.975
599.98
599.99
599.996
599.998
599.998
599.998
599.998
599.998
599.997
599.996
599.997
599.995
599.993
599.991
599.99
599.99
599.988
599.986
599.981
599.981
599.981
599.981
599.98
599.978
599.976
599.976
599.976
599.976
599.977
599.979
599.984
599.991
599.996
599.997
599.998
599.998
599.997
599.997
600.001
599.997
599.996
599.993
599.993
599.991
599.992
599.99
599.987
599.986
599.986
599.987
599.987
599.986
599.984
599.982
599.981
599.982
599.982
599.982
599.983
599.985
599.987
599.991
599.995
599.997
599.997
599.998
599.998
599.999
599.996
599.996
599.994
599.994
599.992
599.995
599.992
599.99
599.983
599.985
599.989
599.99
599.991
599.99
599.989
599.989
599.988
599.989
599.989
599.989
599.99
599.99
599.992
599.993
599.995
599.996
599.997
599.997
599.997
599.998
599.996
599.995
599.993
599.994
599.996
599.995
599.996
599.989
599.98
599.982
599.986
599.989
599.991
599.992
599.992
599.993
599.993
599.993
599.993
599.992
599.993
599.993
599.994
599.994
599.993
599.991
599.992
599.996
599.997
599.998
599.997
599.995
599.993
599.996
599.997
600.002
599.999
599.986
599.977
599.977
599.98
599.983
599.986
599.988
599.99
599.991
599.991
599.991
599.991
599.993
599.992
599.991
599.991
599.989
599.985
599.979
599.981
599.993
599.997
599.998
599.997
599.997
599.996
599.997
600.002
600.002
599.99
599.978
599.971
599.97
599.972
599.975
599.977
599.98
599.982
599.983
599.984
599.984
599.984
599.985
599.984
599.984
599.982
599.98
599.976
599.972
599.974
599.99
599.997
599.997
599.998
599.998
600.001
600
599.995
599.985
599.976
599.969
599.965
599.964
599.965
599.967
599.969
599.971
599.973
599.974
599.975
599.976
599.976
599.976
599.976
599.975
599.974
599.972
599.97
599.969
599.972
599.986
599.996
599.998
599.998
599.997
599.999
599.997
599.983
599.971
599.965
599.961
599.959
599.959
599.959
599.961
599.963
599.965
599.966
599.967
599.968
599.969
599.969
599.969
599.969
599.969
599.968
599.967
599.966
599.967
599.972
599.984
599.994
599.999
599.998
599.997
600.016
599.994
599.975
599.963
599.959
599.957
599.955
599.955
599.955
599.957
599.959
599.961
599.962
599.963
599.964
599.965
599.965
599.965
599.965
599.965
599.964
599.964
599.964
599.966
599.971
599.982
599.991
599.997
599.998
599.996
599.989
599.991
599.979
599.963
599.957
599.955
599.953
599.952
599.953
599.954
599.956
599.958
599.96
599.961
599.962
599.962
599.963
599.963
599.963
599.963
599.962
599.962
599.962
599.964
599.969
599.98
599.989
599.992
599.998
599.993
599.989
599.992
599.985
599.968
599.959
599.955
599.953
599.952
599.952
599.953
599.955
599.957
599.959
599.96
599.961
599.962
599.962
599.962
599.962
599.962
599.961
599.961
599.961
599.962
599.966
599.976
599.99
599.992
599.997
600
599.986
599.993
599.989
599.973
599.962
599.958
599.954
599.952
599.952
599.953
599.955
599.958
599.959
599.96
599.961
599.962
599.962
599.962
599.962
599.962
599.961
599.961
599.961
599.961
599.963
599.973
599.99
599.991
599.995
599.997
599.99
599.993
599.992
599.979
599.967
599.96
599.956
599.953
599.953
599.954
599.956
599.958
599.96
599.961
599.962
599.962
599.963
599.963
599.963
599.962
599.962
599.961
599.961
599.961
599.964
599.976
599.991
599.99
599.992
599.996
599.993
599.992
599.994
599.984
599.971
599.964
599.958
599.955
599.954
599.955
599.957
599.959
599.961
599.962
599.963
599.963
599.964
599.964
599.964
599.964
599.963
599.962
599.962
599.962
599.967
599.982
599.993
599.987
599.994
599.996
599.991
599.992
599.996
599.987
599.974
599.966
599.961
599.957
599.956
599.956
599.958
599.961
599.962
599.963
599.964
599.965
599.965
599.965
599.965
599.965
599.964
599.964
599.963
599.965
599.97
599.987
599.991
599.987
599.995
599.996
599.995
599.995
599.995
599.99
599.977
599.969
599.963
599.959
599.958
599.958
599.96
599.962
599.964
599.964
599.965
599.966
599.966
599.967
599.967
599.966
599.966
599.965
599.965
599.967
599.975
599.994
599.997
599.99
599.995
599.997
599.997
599.997
600
599.994
599.98
599.971
599.965
599.961
599.959
599.96
599.961
599.963
599.965
599.965
599.966
599.967
599.967
599.968
599.968
599.968
599.968
599.967
599.967
599.97
599.979
599.998
600.002
599.993
599.995
599.998
599.998
599.999
600.008
599.996
599.981
599.972
599.966
599.962
599.961
599.961
599.963
599.964
599.965
599.966
599.967
599.968
599.969
599.969
599.97
599.97
599.969
599.968
599.968
599.971
599.98
599.998
600.008
599.996
599.996
599.997
599.998
600.001
600.009
599.994
599.98
599.972
599.967
599.963
599.962
599.962
599.963
599.965
599.966
599.967
599.968
599.969
599.97
599.971
599.971
599.971
599.971
599.97
599.969
599.971
599.979
599.993
600.007
599.997
599.996
599.997
599.999
600.006
600
599.987
599.977
599.971
599.967
599.964
599.963
599.963
599.964
599.966
599.966
599.967
599.968
599.97
599.971
599.972
599.973
599.973
599.972
599.971
599.97
599.971
599.975
599.988
599.999
600
599.997
599.997
599.997
600.003
599.991
599.981
599.974
599.97
599.966
599.964
599.963
599.963
599.964
599.966
599.967
599.968
599.969
599.97
599.972
599.973
599.974
599.974
599.974
599.972
599.971
599.97
599.971
599.977
599.989
599.998
599.996
599.998
599.999
599.992
599.982
599.976
599.971
599.968
599.966
599.964
599.963
599.963
599.965
599.966
599.967
599.968
599.97
599.971
599.973
599.974
599.975
599.976
599.975
599.974
599.971
599.969
599.968
599.972
599.982
599.994
599.996
599.997
599.992
599.98
599.975
599.972
599.97
599.967
599.965
599.964
599.963
599.963
599.965
599.966
599.967
599.968
599.97
599.972
599.974
599.975
599.977
599.977
599.976
599.975
599.972
599.969
599.967
599.967
599.978
599.992
599.998
599.997
599.988
599.975
599.973
599.972
599.97
599.967
599.965
599.964
599.963
599.963
599.965
599.966
599.967
599.968
599.97
599.972
599.974
599.976
599.978
599.978
599.978
599.976
599.973
599.969
599.966
599.965
599.974
599.991
599.999
599.997
599.989
599.98
599.974
599.973
599.972
599.969
599.966
599.964
599.964
599.965
599.965
599.966
599.967
599.968
599.971
599.973
599.975
599.977
599.979
599.979
599.979
599.977
599.974
599.97
599.966
599.966
599.974
599.992
599.997
599.998
599.993
599.985
599.977
599.976
599.975
599.972
599.968
599.965
599.964
599.964
599.966
599.966
599.967
599.968
599.971
599.973
599.975
599.977
599.979
599.98
599.98
599.978
599.975
599.971
599.967
599.967
599.977
599.995
599.995
599.997
599.996
599.99
599.981
599.979
599.979
599.976
599.971
599.967
599.965
599.963
599.963
599.965
599.966
599.968
599.971
599.973
599.976
599.978
599.98
599.981
599.981
599.979
599.976
599.972
599.968
599.968
599.981
599.999
599.996
599.997
599.997
599.993
599.985
599.983
599.984
599.98
599.973
599.967
599.963
599.961
599.961
599.964
599.966
599.968
599.971
599.973
599.976
599.978
599.98
599.982
599.982
599.98
599.977
599.974
599.97
599.97
599.982
599.999
599.996
599.997
599.997
599.994
599.987
599.986
599.988
599.983
599.975
599.967
599.962
599.96
599.961
599.963
599.965
599.968
599.971
599.974
599.976
599.979
599.981
599.982
599.982
599.981
599.979
599.975
599.971
599.972
599.981
599.996
599.997
599.997
599.998
599.994
599.988
599.989
599.991
599.985
599.975
599.967
599.962
599.959
599.96
599.962
599.965
599.968
599.971
599.974
599.977
599.979
599.981
599.983
599.983
599.982
599.979
599.976
599.973
599.973
599.979
599.993
600.005
599.997
600
599.993
599.989
599.991
599.993
599.986
599.976
599.966
599.96
599.958
599.958
599.961
599.964
599.968
599.971
599.974
599.977
599.98
599.982
599.983
599.983
599.983
599.98
599.977
599.975
599.975
599.979
599.99
600.001
599.997
599.998
599.992
599.99
599.993
599.995
599.986
599.975
599.966
599.96
599.957
599.957
599.96
599.964
599.968
599.971
599.975
599.978
599.98
599.982
599.984
599.984
599.983
599.981
599.978
599.976
599.977
599.98
599.989
599.995
599.999
599.997
599.992
599.992
599.995
599.995
599.986
599.974
599.965
599.96
599.957
599.957
599.959
599.964
599.968
599.972
599.975
599.978
599.981
599.983
599.984
599.984
599.983
599.982
599.979
599.977
599.978
599.982
599.99
599.992
599.998
599.995
599.992
599.993
599.996
599.995
599.985
599.974
599.966
599.96
599.957
599.957
599.959
599.964
599.969
599.973
599.976
599.979
599.982
599.983
599.984
599.985
599.984
599.982
599.98
599.978
599.979
599.982
599.99
599.99
599.998
599.995
599.992
599.994
599.996
599.995
599.986
599.975
599.966
599.96
599.957
599.957
599.96
599.964
599.969
599.973
599.977
599.98
599.982
599.984
599.985
599.985
599.984
599.982
599.98
599.979
599.979
599.982
599.988
599.991
599.996
599.994
599.993
599.994
599.996
599.995
599.987
599.976
599.967
599.962
599.959
599.958
599.961
599.965
599.97
599.975
599.978
599.981
599.983
599.985
599.985
599.985
599.984
599.982
599.981
599.979
599.98
599.982
599.987
599.991
599.996
599.994
599.994
599.995
599.996
599.996
599.989
599.978
599.969
599.963
599.961
599.96
599.963
599.967
599.971
599.976
599.98
599.982
599.984
599.986
599.986
599.985
599.984
599.982
599.981
599.98
599.981
599.983
599.988
599.992
599.995
599.995
599.995
599.996
599.998
599.999
599.991
599.98
599.971
599.966
599.963
599.963
599.965
599.969
599.973
599.977
599.981
599.984
599.986
599.986
599.986
599.986
599.984
599.982
599.981
599.981
599.982
599.985
599.989
599.994
599.996
599.996
599.997
599.997
599.999
600
599.993
599.982
599.974
599.969
599.967
599.967
599.968
599.971
599.975
599.979
599.982
599.985
599.987
599.987
599.987
599.986
599.985
599.983
599.982
599.983
599.984
599.986
599.99
599.994
599.997
599.997
599.997
599.997
599.999
600.001
599.994
599.984
599.977
599.973
599.971
599.971
599.972
599.975
599.978
599.981
599.984
599.986
599.988
599.988
599.988
599.987
599.986
599.985
599.984
599.985
599.986
599.988
599.991
599.996
599.998
599.998
599.998
599.997
599.998
600
599.994
599.986
599.981
599.978
599.976
599.976
599.977
599.978
599.981
599.983
599.986
599.988
599.989
599.989
599.989
599.989
599.988
599.987
599.986
599.987
599.989
599.991
599.993
599.994
599.998
599.998
599.998
599.998
599.997
599.999
599.995
599.99
599.986
599.983
599.982
599.981
599.982
599.982
599.984
599.986
599.988
599.989
599.99
599.991
599.991
599.991
599.99
599.989
599.989
599.99
599.992
599.993
599.995
599.995
599.998
599.998
599.998
599.998
599.997
599.998
599.997
599.993
599.991
599.989
599.988
599.987
599.986
599.987
599.988
599.989
599.99
599.991
599.992
599.992
599.993
599.992
599.992
599.992
599.993
599.993
599.995
599.996
599.997
599.996
599.998
599.998
599.998
599.998
599.998
599.999
599.999
599.997
599.995
599.994
599.993
599.992
599.991
599.991
599.991
599.992
599.993
599.993
599.994
599.994
599.995
599.995
599.995
599.995
599.996
599.996
599.997
599.998
599.998
599.997
599.999
599.999
599.999
599.998
599.998
599.999
600
600
599.999
599.998
599.997
599.996
599.995
599.995
599.995
599.995
599.996
599.996
599.996
599.997
599.997
599.998
599.998
599.999
599.999
599.999
599.999
600
599.999
599.998
599.999
599.999
599.999
599.999
599.999
600
600.001
600.001
600.001
600
600
599.999
599.999
599.998
599.998
599.998
599.999
599.999
599.999
599.999
600
600
600.001
600.001
600.001
600.001
600
600
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600.001
600.001
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600.001
600.001
600
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
599.999
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600.001
600.001
600.001
600.001
600
600
600
600
600
599.998
600
600
600
600
599.999
600.001
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.998
600
600
600
600
600.002
600
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600.001
600
600
600
600
599.999
600
600.002
599.999
600
600
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.999
599.999
600
599.999
600
600
600.001
600
600
599.999
600
600
600
600
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600
600
600
600
600
600
600
599.999
599.999
600
600
599.999
600
600
600
600
600
600
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600.001
600
600
599.999
600
600
599.999
599.999
600
600
600.001
600
600
600
600.001
600.001
600
600.001
600.001
600.001
600.001
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
599.999
600
600
600.001
599.999
600
600
600.001
600.001
600.001
600.001
600.001
600
600.001
600.001
600.001
600.001
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
599.999
600
599.999
600
599.999
600
600.001
600.001
600.001
600.001
600
600.001
600.001
600.001
600.001
600
600.001
600.001
600.001
600.001
600.001
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600.001
600.001
600
600
600
600
600.001
600.001
600.001
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
599.999
599.997
599.999
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
599.999
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
599.999
600
600
600.001
600.001
600.001
600.001
600.001
600
600
600
600
600.001
600.001
600.001
600.001
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600
600.001
600.001
600.001
600.001
600
600
600.001
600
600
600.001
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600
600.001
600.001
600.001
600.001
599.999
600
600
600
600
600
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600.001
600
600.001
600
599.999
599.999
600
600
600
600
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600
600
600
600
600
600
600.001
600.001
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
599.999
599.999
600
600
600.001
600.001
600.001
600.001
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600.001
600.001
600.001
600
599.998
599.999
599.999
599.999
600
600.001
600.002
600.002
600.001
600.001
600.001
600.001
600
600
600.001
599.999
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600
599.999
599.999
600
600.002
600.003
600.002
600.001
600.001
600
600.001
600
600
600
600.002
599.999
599.999
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
599.999
600
600.002
600.002
600.002
600.001
600.001
600
600
600.001
600
600
600
599.999
600.001
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600.002
600.003
600.002
600.001
600.001
600.001
600
600
600.001
600
600
600.001
599.999
600
600.001
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600.003
600.003
600.002
600.002
600.001
600.001
600
600.001
600.001
600.001
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.003
600.003
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600
600.001
600.001
600.002
600.002
600.002
600.001
600.001
600.001
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.003
600.002
600
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600.001
600.001
600.002
600.002
600.002
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.003
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600.001
600.001
600.001
600.002
600.002
600.001
600.002
600.001
600.002
600.001
600.001
600.001
600.001
600
600.001
600.002
600.002
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.001
600.001
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600
600.001
600.002
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600.001
600.001
600.002
600.002
600.002
600.002
600.002
599.998
600
600.001
600.002
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.001
600.001
600.001
600.001
600.001
600
599.999
600.003
600.003
600.002
599.999
599.996
599.998
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600
600.001
600
599.996
599.993
599.994
599.994
599.996
599.997
599.999
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600.002
599.997
600.001
600
599.998
599.996
600.004
600.006
599.996
599.999
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600.002
600.012
600.001
600.001
600
600
599.995
599.995
600.001
600.001
600.001
600.001
600.001
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600.002
599.998
600
600.001
600.001
599.996
599.995
599.996
600.002
600.002
600.002
600.002
600.001
600.001
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.003
600.002
600.002
600.002
599.994
600.001
600.001
600.003
600.002
599.997
599.995
600.002
600.003
600.003
600.002
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600.002
599.993
600.001
600.002
600.001
599.999
600.003
600.003
600.003
600.004
600.002
599.998
600.003
600.004
600.003
600.002
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600
600.012
600.001
600.001
600.002
600.004
600.005
600.003
600.002
600.004
600.005
600.006
600.005
600.004
600.002
600.002
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600.003
600.001
599.999
599.995
599.994
600.006
600.003
599.999
600.002
600.003
600.006
600.007
600.005
600.003
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600.002
600.003
600.002
599.995
599.979
599.965
599.951
600.004
600.002
600.004
600.002
600.002
600.004
600.005
600.005
600.003
600.002
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.002
599.999
599.984
599.949
599.957
599.988
599.992
600.003
600.003
600.002
600.002
600.002
600.002
600.003
600.003
600.003
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.003
600.003
600.002
599.999
599.99
599.964
599.928
599.974
600.031
600.064
600.063
600.003
600.003
600.003
600.002
600.002
600.002
600.002
600.003
600.003
600.003
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.003
600.003
600.002
600
599.993
599.972
599.951
599.958
600.012
600.077
600.132
600.162
600.17
600.004
600.001
600.004
600.003
600.002
600.003
600.002
600.003
600.003
600.003
600.003
600.003
600.003
600.002
600.002
600.001
600.001
600
599.998
599.991
599.979
599.97
599.988
600.028
600.072
600.126
600.18
600.22
600.241
600.25
599.992
599.99
599.996
599.999
600.001
600.001
600.002
600.002
600.002
600.002
600
599.996
599.994
599.993
599.991
599.989
599.986
599.98
599.97
599.966
599.993
600.043
600.092
600.139
600.184
600.225
600.262
600.288
600.303
600.309
599.941
599.938
599.959
599.972
599.98
599.986
599.991
599.993
599.992
599.989
599.978
599.967
599.961
599.959
599.959
599.957
599.96
599.971
600.002
600.049
600.1
600.152
600.196
600.235
600.268
600.298
600.323
600.341
600.352
600.356
599.881
599.895
599.897
599.91
599.922
599.933
599.945
599.954
599.962
599.971
599.982
599.995
600.008
600.02
600.03
600.041
600.058
600.086
600.125
600.169
600.212
600.25
600.281
600.308
600.331
600.352
600.369
600.381
600.388
600.392
599.974
599.998
600.002
600
599.998
599.998
600.002
600.02
600.047
600.077
600.103
600.123
600.139
600.151
600.163
600.176
600.194
600.218
600.248
600.279
600.306
600.329
600.347
600.363
600.377
600.391
600.402
600.411
600.417
600.419
600.158
600.184
600.186
600.177
600.168
600.164
600.168
600.184
600.207
600.23
600.25
600.265
600.275
600.284
600.292
600.301
600.313
600.329
600.347
600.365
600.381
600.392
600.399
600.404
600.41
600.418
600.425
600.433
600.441
600.449
600.381
600.377
600.368
600.353
600.339
600.33
600.331
600.343
600.358
600.37
600.38
600.387
600.392
600.396
600.399
600.403
600.408
600.416
600.424
600.432
600.437
600.439
600.436
600.433
600.432
600.434
600.439
600.446
600.457
600.473
600.564
600.538
600.513
600.49
600.471
600.459
600.457
600.467
600.476
600.482
600.485
600.486
600.486
600.485
600.483
600.482
600.481
600.481
600.482
600.481
600.479
600.473
600.462
600.451
600.444
600.441
600.443
600.448
600.459
600.476
600.707
600.661
600.623
600.592
600.568
600.553
600.55
600.559
600.565
600.567
600.566
600.563
600.558
600.553
600.547
600.54
600.535
600.529
600.523
600.516
600.507
600.495
600.478
600.46
600.447
600.44
600.438
600.442
600.451
600.468
600.807
600.745
600.698
600.662
600.635
600.618
600.615
600.624
600.629
600.629
600.625
600.619
600.611
600.602
600.592
600.582
600.572
600.561
600.55
600.538
600.524
600.506
600.485
600.462
600.443
600.432
600.426
600.425
600.43
600.44
600.856
600.791
600.74
600.702
600.674
600.657
600.657
600.667
600.672
600.671
600.665
600.657
600.647
600.635
600.622
600.609
600.595
600.581
600.565
600.549
600.53
600.509
600.484
600.457
600.433
600.416
600.406
600.4
600.397
600.396
600.862
600.802
600.754
600.718
600.691
600.676
600.679
600.691
600.697
600.695
600.689
600.68
600.668
600.654
600.639
600.623
600.606
600.588
600.57
600.55
600.528
600.504
600.476
600.445
600.416
600.395
600.38
600.37
600.361
600.351
600.852
600.793
600.748
600.714
600.689
600.677
600.684
600.699
600.706
600.705
600.699
600.688
600.675
600.66
600.643
600.625
600.606
600.586
600.565
600.543
600.518
600.491
600.461
600.427
600.394
600.369
600.351
600.336
600.322
600.306
600.816
600.764
600.726
600.696
600.674
600.666
600.677
600.694
600.702
600.702
600.696
600.685
600.672
600.656
600.638
600.618
600.598
600.576
600.552
600.527
600.501
600.471
600.439
600.404
600.368
600.34
600.318
600.3
600.283
600.262
600.753
600.716
600.686
600.662
600.645
600.642
600.659
600.678
600.688
600.688
600.683
600.673
600.659
600.642
600.623
600.602
600.58
600.556
600.531
600.505
600.476
600.446
600.412
600.376
600.338
600.307
600.283
600.263
600.244
600.219
600.684
600.659
600.637
600.618
600.605
600.608
600.63
600.652
600.663
600.664
600.66
600.65
600.636
600.619
600.599
600.578
600.554
600.53
600.504
600.476
600.446
600.415
600.38
600.343
600.305
600.271
600.246
600.224
600.204
600.177
600.613
600.598
600.582
600.567
600.558
600.567
600.594
600.617
600.629
600.632
600.628
600.618
600.605
600.587
600.568
600.546
600.522
600.496
600.469
600.441
600.41
600.378
600.344
600.307
600.267
600.233
600.206
600.184
600.164
600.136
600.545
600.536
600.523
600.511
600.504
600.52
600.551
600.576
600.589
600.592
600.589
600.58
600.566
600.549
600.529
600.507
600.483
600.457
600.429
600.4
600.369
600.337
600.302
600.266
600.227
600.191
600.164
600.143
600.123
600.096
600.479
600.473
600.461
600.45
600.446
600.467
600.502
600.527
600.541
600.546
600.543
600.534
600.521
600.504
600.484
600.462
600.437
600.411
600.383
600.354
600.323
600.29
600.257
600.221
600.183
600.147
600.12
600.1
600.081
600.056
600.416
600.409
600.397
600.386
600.383
600.409
600.447
600.474
600.488
600.493
600.491
600.483
600.469
600.453
600.433
600.41
600.385
600.359
600.331
600.302
600.271
600.239
600.206
600.171
600.135
600.1
600.074
600.054
600.038
600.016
600.354
600.346
600.331
600.317
600.317
600.348
600.388
600.414
600.429
600.434
600.432
600.424
600.411
600.394
600.375
600.352
600.327
600.301
600.273
600.244
600.214
600.183
600.151
600.118
600.083
600.05
600.024
600.007
599.993
599.975
600.294
600.28
600.262
600.245
600.247
600.283
600.323
600.349
600.364
600.369
600.367
600.359
600.346
600.33
600.31
600.287
600.263
600.237
600.209
600.181
600.151
600.121
600.091
600.059
600.027
599.996
599.97
599.956
599.945
599.932
600.234
600.213
600.188
600.167
600.173
600.213
600.253
600.278
600.293
600.297
600.295
600.287
600.274
600.257
600.237
600.215
600.191
600.165
600.138
600.111
600.082
600.053
600.024
599.995
599.966
599.937
599.913
599.901
599.895
599.888
600.174
600.142
600.108
600.082
600.094
600.137
600.176
600.2
600.214
600.218
600.215
600.206
600.193
600.176
600.157
600.135
600.111
600.086
600.06
600.033
600.006
599.979
599.952
599.925
599.899
599.873
599.851
599.841
599.84
599.841
600.111
600.066
600.02
599.988
600.008
600.054
600.091
600.114
600.126
600.129
600.125
600.116
600.103
600.086
600.066
600.044
600.021
599.997
599.972
599.946
599.921
599.896
599.872
599.848
599.825
599.803
599.784
599.776
599.779
599.789
600.043
599.981
599.922
599.885
599.912
599.961
599.996
600.017
600.027
600.029
600.024
600.014
600
599.983
599.963
599.942
599.92
599.897
599.873
599.85
599.827
599.804
599.783
599.762
599.743
599.726
599.711
599.704
599.712
599.73
599.969
599.886
599.811
599.77
599.805
599.855
599.888
599.906
599.914
599.914
599.908
599.897
599.882
599.865
599.846
599.826
599.804
599.783
599.761
599.741
599.72
599.701
599.684
599.667
599.653
599.64
599.629
599.625
599.635
599.663
599.886
599.775
599.681
599.641
599.684
599.733
599.763
599.778
599.784
599.781
599.773
599.761
599.746
599.729
599.711
599.692
599.672
599.653
599.634
599.617
599.6
599.585
599.572
599.561
599.551
599.544
599.539
599.538
599.55
599.583
599.787
599.642
599.528
599.496
599.545
599.59
599.616
599.628
599.63
599.625
599.615
599.602
599.587
599.57
599.553
599.536
599.519
599.503
599.488
599.475
599.463
599.453
599.446
599.44
599.437
599.437
599.438
599.443
599.456
599.49
599.666
599.479
599.342
599.327
599.38
599.42
599.441
599.448
599.446
599.438
599.427
599.413
599.398
599.382
599.367
599.353
599.34
599.328
599.319
599.311
599.305
599.302
599.302
599.304
599.309
599.316
599.326
599.338
599.356
599.388
599.514
599.275
599.116
599.122
599.18
599.213
599.228
599.229
599.223
599.212
599.199
599.185
599.171
599.158
599.147
599.137
599.129
599.124
599.121
599.121
599.124
599.13
599.138
599.149
599.163
599.18
599.199
599.221
599.248
599.285
599.314
599.014
598.84
598.872
598.93
598.957
598.964
598.959
598.949
598.935
598.921
598.908
598.897
598.889
598.883
598.88
598.88
598.883
598.89
598.9
598.914
598.93
598.95
598.973
598.998
599.027
599.057
599.091
599.129
599.178
599.044
598.677
598.51
598.565
598.618
598.636
598.634
598.623
598.608
598.593
598.58
598.57
598.564
598.562
598.565
598.572
598.584
598.599
598.619
598.642
598.669
598.7
598.734
598.771
598.811
598.853
598.898
598.945
598.997
599.063
598.67
598.239
598.115
598.182
598.223
598.228
598.217
598.199
598.181
598.166
598.156
598.153
598.156
598.166
598.182
598.204
598.231
598.263
598.299
598.34
598.385
598.434
598.486
598.54
598.597
598.656
598.718
598.782
598.851
598.937
598.139
597.667
597.623
597.693
597.716
597.706
597.683
597.66
597.641
597.631
597.63
597.638
597.657
597.684
597.719
597.761
597.81
597.864
597.923
597.987
598.055
598.126
598.2
598.276
598.354
598.434
598.515
598.599
598.688
598.799
597.374
596.943
596.994
597.057
597.057
597.03
596.998
596.971
596.957
596.957
596.972
597.001
597.043
597.096
597.159
597.23
597.308
597.392
597.481
597.574
597.671
597.77
597.871
597.974
598.077
598.182
598.287
598.393
598.507
598.646
596.307
596.08
596.189
596.223
596.195
596.149
596.11
596.088
596.087
596.108
596.151
596.212
596.29
596.381
596.483
596.594
596.711
596.835
596.962
597.093
597.226
597.36
597.495
597.629
597.764
597.897
598.03
598.164
598.305
598.478
594.932
595.04
595.14
595.12
595.056
594.994
594.956
594.95
594.978
595.039
595.127
595.238
595.369
595.514
595.67
595.835
596.005
596.18
596.357
596.534
596.712
596.889
597.064
597.237
597.408
597.576
597.742
597.907
598.081
598.293
593.526
593.749
593.742
593.644
593.539
593.469
593.45
593.484
593.568
593.693
593.853
594.04
594.247
594.468
594.699
594.935
595.174
595.414
595.653
595.89
596.122
596.351
596.575
596.794
597.007
597.216
597.419
597.621
597.833
598.089
592.002
592.021
591.835
591.638
591.5
591.448
591.482
591.596
591.776
592.008
592.278
592.575
592.89
593.216
593.546
593.876
594.204
594.527
594.843
595.151
595.45
595.741
596.022
596.295
596.558
596.813
597.06
597.304
597.558
597.865
589.898
589.571
589.155
588.866
588.733
588.755
588.908
589.17
589.512
589.909
590.344
590.799
591.264
591.73
592.191
592.642
593.082
593.507
593.917
594.312
594.691
595.054
595.403
595.737
596.057
596.364
596.661
596.953
597.255
597.621
586.688
585.931
585.288
584.971
584.947
585.156
585.549
586.069
586.671
587.32
587.993
588.669
589.338
589.989
590.618
591.222
591.8
592.35
592.873
593.37
593.842
594.289
594.715
595.119
595.503
595.87
596.222
596.566
596.922
597.35
581.365
580.264
579.547
579.42
579.727
580.356
581.188
582.137
583.144
584.166
585.175
586.153
587.09
587.98
588.821
589.613
590.358
591.056
591.712
592.327
592.905
593.448
593.96
594.442
594.897
595.329
595.741
596.143
596.558
597.061
571.713
571.015
570.831
571.414
572.547
573.99
575.583
577.22
578.836
580.389
581.859
583.236
584.518
585.707
586.807
587.824
588.766
589.637
590.444
591.194
591.89
592.538
593.143
593.71
594.241
594.742
595.22
595.683
596.162
596.736
553.627
555.526
557.431
559.918
562.746
565.662
568.508
571.197
573.69
575.974
578.053
579.94
581.649
583.199
584.606
585.885
587.052
588.117
589.093
589.988
590.813
591.574
592.278
592.933
593.543
594.117
594.661
595.189
595.736
596.405
521.958
530.118
537.225
543.692
549.653
555.039
559.826
564.041
567.739
570.981
573.829
576.338
578.556
580.525
582.281
583.852
585.265
586.54
587.695
588.745
589.703
590.579
591.385
592.128
592.817
593.461
594.071
594.662
595.275
596.01
469.835
490.672
508.207
521.858
532.959
542.091
549.645
555.923
561.172
565.598
569.362
572.588
575.378
577.807
579.937
581.817
583.487
584.977
586.314
587.518
588.607
589.596
590.498
591.325
592.087
592.795
593.464
594.113
594.794
595.657
400.135
437.286
470.334
494.711
513.204
527.435
538.55
547.358
554.437
560.205
564.971
568.961
572.341
575.236
577.739
579.921
581.837
583.532
585.038
586.385
587.594
588.684
589.671
590.569
591.391
592.15
592.863
593.555
594.282
595.164
338.078
384.333
430.349
465.612
492.523
512.713
527.866
539.403
548.36
555.454
561.177
565.874
569.789
573.096
575.922
578.362
580.486
582.35
583.997
585.459
586.763
587.931
588.983
589.933
590.795
591.583
592.316
593.023
593.783
594.845
301.778
350.549
401.465
443.156
476.434
501.628
520.187
533.923
544.31
552.364
558.756
563.933
568.201
571.775
574.807
577.409
579.663
581.632
583.362
584.893
586.253
587.467
588.554
589.53
590.408
591.202
591.924
592.595
593.268
594.143
)
;
boundaryField
{
inlet
{
type fixedValue;
value uniform 300;
}
outlet
{
type inletOutlet;
phi phi.air;
inletValue uniform 300;
value nonuniform List<scalar>
30
(
300
350.549
401.464
443.154
476.433
501.627
520.185
533.922
544.309
552.364
558.755
563.932
568.2
571.774
574.807
577.409
579.663
581.631
583.362
584.893
586.253
587.467
588.554
589.529
590.408
591.202
591.924
592.595
593.268
594.143
)
;
}
walls
{
type zeroGradient;
}
frontAndBackPlanes
{
type empty;
}
}
// ************************************************************************* //
| [
"peterbryz@yahoo.com"
] | peterbryz@yahoo.com |
d0b750619d1ab6bf98ec04a5abc60928eb37c8df | 7e791eccdc4d41ba225a90b3918ba48e356fdd78 | /chromium/src/components/web_view/find_controller.h | 825007942049e524e92fb510524ddead877f5002 | [
"BSD-3-Clause"
] | permissive | WiViClass/cef-3.2623 | 4e22b763a75e90d10ebf9aa3ea9a48a3d9ccd885 | 17fe881e9e481ef368d9f26e903e00a6b7bdc018 | refs/heads/master | 2021-01-25T04:38:14.941623 | 2017-06-09T07:37:43 | 2017-06-09T07:37:43 | 93,824,379 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,759 | h | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_WEB_VIEW_FIND_CONTROLLER_H_
#define COMPONENTS_WEB_VIEW_FIND_CONTROLLER_H_
#include <stdint.h>
#include <vector>
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "components/web_view/local_find_options.h"
#include "components/web_view/public/interfaces/web_view.mojom.h"
namespace web_view {
class FindControllerDelegate;
class Frame;
// Contains all the find code used by WebViewImpl.
class FindController {
public:
FindController(FindControllerDelegate* delegate);
~FindController();
// Starts a find session looking for |search_text|. This method will first
// scan through frames one by one to look for the first instance of
// |search_text|, and return the data through
// OnFindInPageSelectionUpdated(). If found, it will highlight all instances
// of the text and report the final total count through
// FindInPageMatchCountUpdated().
void Find(const std::string& search_text, bool forward_direction);
// Unhighlights all find instances on the page.
void StopFinding();
void OnFindInFrameCountUpdated(int32_t request_id,
Frame* frame,
int32_t count,
bool final_update);
void OnFindInPageSelectionUpdated(int32_t request_id,
Frame* frame,
int32_t active_match_ordinal);
void DidDestroyFrame(Frame* frame);
private:
struct MatchData {
int count;
bool final_update;
};
// Callback method invoked by Find().
void OnContinueFinding(int32_t request_id,
const std::string& search_string,
LocalFindOptions options,
uint32_t starting_frame,
uint32_t current_frame,
bool found);
// Returns the next Frame that we want to Find() on. This method will start
// iterating, forward or backwards, from current_frame, and will return
// nullptr once it has gone entirely around the framelist and has returned to
// starting_frame. If |current_frame| doesn't exist, returns nullptr to
// terminate the search process.
Frame* GetNextFrameToSearch(uint32_t starting_frame,
uint32_t current_frame,
bool forward);
// Returns an iterator into |find_frames_in_order_|. Implementation detail of
// GetNextFrameToSearch().
std::vector<Frame*>::iterator GetFrameIteratorById(uint32_t frame_id);
// Our owner.
FindControllerDelegate* delegate_;
// A list of Frames in traversal order to be searched.
std::vector<Frame*> find_frames_in_order_;
// Monotonically increasing find id.
int find_request_id_counter_;
// Current find session number. We keep track of this to prevent recording
// stale callbacks.
int current_find_request_id_;
// The current string we are/just finished searching for. This is used to
// figure out if this is a Find or a FindNext operation (FindNext should not
// increase the request id).
std::string find_text_;
// The string we searched for before |find_text_|.
std::string previous_find_text_;
// The current callback data from various frames.
std::map<Frame*, MatchData> returned_find_data_;
// We keep track of the current frame with the selection.
uint32_t frame_with_selection_;
base::WeakPtrFactory<FindController> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(FindController);
};
} // namespace web_view
#endif // COMPONENTS_WEB_VIEW_FIND_CONTROLLER_H_
| [
"1480868058@qq.com"
] | 1480868058@qq.com |
2e96b7979372c2c7294d4ead98a56cd50fd8596b | 6701eae4550c7cd3d8703565c7be3a5e26248676 | /src/qt/ellocashamountfield.cpp | 7a89f37b363d8fa84ffccb15fbff18b0309ee174 | [
"MIT"
] | permissive | stochastic-thread/bootstrapping-ellocash | 91de56a330090c004af31d861e6d4cfb8d8b9e36 | 9495f1e3741c7f893457e4f6602d6ef0d84b7b3d | refs/heads/master | 2021-09-05T05:00:19.403780 | 2018-01-24T08:09:44 | 2018-01-24T08:09:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,330 | cpp | // Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "ellocashamountfield.h"
#include "ellocashunits.h"
#include "guiconstants.h"
#include "qvaluecombobox.h"
#include <QAbstractSpinBox>
#include <QApplication>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLineEdit>
/** QSpinBox that uses fixed-point numbers internally and uses our own
* formatting/parsing functions.
*/
class AmountSpinBox : public QAbstractSpinBox
{
Q_OBJECT
public:
explicit AmountSpinBox(QWidget* parent) : QAbstractSpinBox(parent),
currentUnit(EllocashUnits::LOC),
singleStep(100000) // satoshis
{
setAlignment(Qt::AlignRight);
connect(lineEdit(), SIGNAL(textEdited(QString)), this, SIGNAL(valueChanged()));
}
QValidator::State validate(QString& text, int& pos) const
{
if (text.isEmpty())
return QValidator::Intermediate;
bool valid = false;
parse(text, &valid);
/* Make sure we return Intermediate so that fixup() is called on defocus */
return valid ? QValidator::Intermediate : QValidator::Invalid;
}
void fixup(QString& input) const
{
bool valid = false;
CAmount val = parse(input, &valid);
if (valid) {
input = EllocashUnits::format(currentUnit, val, false, EllocashUnits::separatorAlways);
lineEdit()->setText(input);
}
}
CAmount value(bool* valid_out = 0) const
{
return parse(text(), valid_out);
}
void setValue(const CAmount& value)
{
lineEdit()->setText(EllocashUnits::format(currentUnit, value, false, EllocashUnits::separatorAlways));
Q_EMIT valueChanged();
}
void stepBy(int steps)
{
bool valid = false;
CAmount val = value(&valid);
val = val + steps * singleStep;
val = qMin(qMax(val, CAmount(0)), EllocashUnits::maxMoney());
setValue(val);
}
void setDisplayUnit(int unit)
{
bool valid = false;
CAmount val = value(&valid);
currentUnit = unit;
if (valid)
setValue(val);
else
clear();
}
void setSingleStep(const CAmount& step)
{
singleStep = step;
}
QSize minimumSizeHint() const
{
if (cachedMinimumSizeHint.isEmpty()) {
ensurePolished();
const QFontMetrics fm(fontMetrics());
int h = lineEdit()->minimumSizeHint().height();
int w = fm.width(EllocashUnits::format(EllocashUnits::LOC, EllocashUnits::maxMoney(), false, EllocashUnits::separatorAlways));
w += 2; // cursor blinking space
QStyleOptionSpinBox opt;
initStyleOption(&opt);
QSize hint(w, h);
QSize extra(35, 6);
opt.rect.setSize(hint + extra);
extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt,
QStyle::SC_SpinBoxEditField, this)
.size();
// get closer to final result by repeating the calculation
opt.rect.setSize(hint + extra);
extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt,
QStyle::SC_SpinBoxEditField, this)
.size();
hint += extra;
hint.setHeight(h);
opt.rect = rect();
cachedMinimumSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this).expandedTo(QApplication::globalStrut());
}
return cachedMinimumSizeHint;
}
private:
int currentUnit;
CAmount singleStep;
mutable QSize cachedMinimumSizeHint;
/**
* Parse a string into a number of base monetary units and
* return validity.
* @note Must return 0 if !valid.
*/
CAmount parse(const QString& text, bool* valid_out = 0) const
{
CAmount val = 0;
bool valid = EllocashUnits::parse(currentUnit, text, &val);
if (valid) {
if (val < 0 || val > EllocashUnits::maxMoney())
valid = false;
}
if (valid_out)
*valid_out = valid;
return valid ? val : 0;
}
protected:
bool event(QEvent* event)
{
if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) {
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_Comma) {
// Translate a comma into a period
QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count());
return QAbstractSpinBox::event(&periodKeyEvent);
}
}
return QAbstractSpinBox::event(event);
}
StepEnabled stepEnabled() const
{
if (isReadOnly()) // Disable steps when AmountSpinBox is read-only
return StepNone;
if (text().isEmpty()) // Allow step-up with empty field
return StepUpEnabled;
StepEnabled rv = 0;
bool valid = false;
CAmount val = value(&valid);
if (valid) {
if (val > 0)
rv |= StepDownEnabled;
if (val < EllocashUnits::maxMoney())
rv |= StepUpEnabled;
}
return rv;
}
Q_SIGNALS:
void valueChanged();
};
#include "ellocashamountfield.moc"
EllocashAmountField::EllocashAmountField(QWidget* parent) : QWidget(parent),
amount(0)
{
amount = new AmountSpinBox(this);
amount->setLocale(QLocale::c());
amount->installEventFilter(this);
amount->setMaximumWidth(170);
QHBoxLayout* layout = new QHBoxLayout(this);
layout->addWidget(amount);
unit = new QValueComboBox(this);
unit->setModel(new EllocashUnits(this));
layout->addWidget(unit);
layout->addStretch(1);
layout->setContentsMargins(0, 0, 0, 0);
setLayout(layout);
setFocusPolicy(Qt::TabFocus);
setFocusProxy(amount);
// If one if the widgets changes, the combined content changes as well
connect(amount, SIGNAL(valueChanged()), this, SIGNAL(valueChanged()));
connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int)));
// Set default based on configuration
unitChanged(unit->currentIndex());
}
void EllocashAmountField::clear()
{
amount->clear();
unit->setCurrentIndex(0);
}
void EllocashAmountField::setEnabled(bool fEnabled)
{
amount->setEnabled(fEnabled);
unit->setEnabled(fEnabled);
}
bool EllocashAmountField::validate()
{
bool valid = false;
value(&valid);
setValid(valid);
return valid;
}
void EllocashAmountField::setValid(bool valid)
{
if (valid)
amount->setStyleSheet("");
else
amount->setStyleSheet(STYLE_INVALID);
}
bool EllocashAmountField::eventFilter(QObject* object, QEvent* event)
{
if (event->type() == QEvent::FocusIn) {
// Clear invalid flag on focus
setValid(true);
}
return QWidget::eventFilter(object, event);
}
QWidget* EllocashAmountField::setupTabChain(QWidget* prev)
{
QWidget::setTabOrder(prev, amount);
QWidget::setTabOrder(amount, unit);
return unit;
}
CAmount EllocashAmountField::value(bool* valid_out) const
{
return amount->value(valid_out);
}
void EllocashAmountField::setValue(const CAmount& value)
{
amount->setValue(value);
}
void EllocashAmountField::setReadOnly(bool fReadOnly)
{
amount->setReadOnly(fReadOnly);
}
void EllocashAmountField::unitChanged(int idx)
{
// Use description tooltip for current unit for the combobox
unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString());
// Determine new unit ID
int newUnit = unit->itemData(idx, EllocashUnits::UnitRole).toInt();
amount->setDisplayUnit(newUnit);
}
void EllocashAmountField::setDisplayUnit(int newUnit)
{
unit->setValue(newUnit);
}
void EllocashAmountField::setSingleStep(const CAmount& step)
{
amount->setSingleStep(step);
}
| [
"arthurcolle@Arthurs-MacBook-Pro.local"
] | arthurcolle@Arthurs-MacBook-Pro.local |
3034ec1474230490cc5f0b17ad91d36c58f62a08 | 9160d5980d55c64c2bbc7933337e5e1f4987abb0 | /base/src/sgpp/base/operation/hash/common/algorithm_sweep/HierarchisationLinearClenshawCurtis.hpp | 0e6164fbe2faa730297eb72727d7d0e364566436 | [
"LicenseRef-scancode-generic-exception",
"BSD-3-Clause"
] | permissive | SGpp/SGpp | 55e82ecd95ac98efb8760d6c168b76bc130a4309 | 52f2718e3bbca0208e5e08b3c82ec7c708b5ec06 | refs/heads/master | 2022-08-07T12:43:44.475068 | 2021-10-20T08:50:38 | 2021-10-20T08:50:38 | 123,916,844 | 68 | 44 | NOASSERTION | 2022-06-23T08:28:45 | 2018-03-05T12:33:52 | C++ | UTF-8 | C++ | false | false | 2,850 | hpp | // Copyright (C) 2008-today The SG++ project
// This file is part of the SG++ project. For conditions of distribution and
// use, please see the copyright notice provided with SG++ or at
// sgpp.sparsegrids.org
#pragma once
#include <sgpp/base/grid/GridStorage.hpp>
#include <sgpp/base/datatypes/DataVector.hpp>
#include <sgpp/base/tools/ClenshawCurtisTable.hpp>
#include <sgpp/base/operation/hash/common/basis/LinearClenshawCurtisBasis.hpp>
#include <sgpp/globaldef.hpp>
namespace sgpp {
namespace base {
/**
* Class that implements the hierarchisation on a polynomial sparse grid. Therefore
* the ()operator has to be implement in order to use the sweep algorithm for
* the grid traversal
*/
class HierarchisationLinearClenshawCurtis {
protected:
typedef GridStorage::grid_iterator grid_iterator;
typedef level_t level_type;
typedef index_t index_type;
/// the grid object
GridStorage& storage;
/// clenshaw curtis points
ClenshawCurtisTable& clenshawCurtisTable;
public:
/**
* Constructor, must be bind to a grid
*
* @param storage the grid storage object of the the grid, on which the hierarchisation should
* be
* executed
*/
explicit HierarchisationLinearClenshawCurtis(GridStorage& storage);
/**
* Destructor
*/
~HierarchisationLinearClenshawCurtis();
/**
* Implements operator() needed by the sweep class during the grid traversal. This function
* is applied to the whole grid.
*
* @param source this DataVector holds the node base coefficients of the function that should be
* applied to the sparse grid
* @param result this DataVector holds the linear base coefficients of the sparse grid's
* ansatz-functions
* @param index a iterator object of the grid
* @param dim current fixed dimension of the 'execution direction'
*/
void operator()(DataVector& source, DataVector& result, grid_iterator& index, size_t dim);
protected:
/**
* Recursive hierarchisaton algorithm, this algorithms works in-place -> source should be equal to
* result
*
* @param source this DataVector holds the node base coefficients of the function that should be
* applied to the sparse grid
* @param result this DataVector holds the linear base coefficients of the sparse grid's
* ansatz-functions
* @param index a iterator object of the grid
* @param dim current fixed dimension of the 'execution direction'
* @param xl position of closest neighbor to the left
* @param fl function value of closest neighbor to the left
* @param xr position of closest neighbor to the right
* @param fr function value of closest neighbor to the right
*/
void rec(DataVector& source, DataVector& result, grid_iterator& index, size_t dim, double xl,
double fl, double xr, double fr);
};
} // namespace base
} // namespace sgpp
| [
"fabian.franzelin@ipvs.uni-stuttgart.de"
] | fabian.franzelin@ipvs.uni-stuttgart.de |
99cabbe8c5b34d8be290ce45f540170ca1706ec8 | 008886b8743c7742b0183c471d66a9d203297391 | /dd.h | c77c028acedcb9802076bbc5387122660f1d3467 | [] | no_license | stamhoffman/shellDD | f54f66659345b27dccb724e8028e8d557fd2dcfd | 46757f5f840d906db7dc6591c0cc99a3f8450ca4 | refs/heads/master | 2020-05-24T13:07:05.854244 | 2019-05-17T22:36:12 | 2019-05-17T22:36:12 | 187,282,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 876 | h | #ifndef DD_H
#define DD_H
#include <QDir>
#include <QFileDialog>
#include <QMainWindow>
#include <QMessageBox>
#include <QString>
#include <QStringList>
#include <QTimer>
#include <QtDebug>
#include <array>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
namespace Ui {
class DD;
}
class DD : public QMainWindow {
Q_OBJECT
public:
explicit DD(QWidget *parent = nullptr);
~DD();
private slots:
void on_pushButton_3_clicked();
void on_pushButton_2_clicked();
void on_pushButton_4_clicked();
void on_pushButton_clicked();
void on_pushButton_5_clicked();
private:
Ui::DD *ui;
QStringList m_DevStringList;
QString m_ISOString;
QFileDialog file_iso;
QTimer *tim;
QMessageBox ok;
void findDevises();
std::string exec(const char *cmd);
char *buffer;
};
#endif // DD_H
| [
"stamhoffman@yandex.ru"
] | stamhoffman@yandex.ru |
977cd156243351fef8686d58563e88e4090b899f | 8ae31e5db1f7c25b6ce1c708655ab55c15dde14e | /比赛/学校/2018-11-2邀请赛/2018-11-2友谊赛/程序/HB-13/wave/wave.cpp | b5bcd8a5b592da226a8b0b0c5613c6dbe8cd345b | [] | no_license | LeverImmy/Codes | 99786afd826ae786b5024a3a73c8f92af09aae5d | ca28e61f55977e5b45d6731bc993c66e09f716a3 | refs/heads/master | 2020-09-03T13:00:29.025752 | 2019-12-16T12:11:23 | 2019-12-16T12:11:23 | 219,466,644 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 523 | cpp | #include<iostream>
#include<cstdio>
const int maxx=50001;
int n,sum=0;
struct data
{
int x,y;
}a[maxx];
int main()
{
freopen("wave.in","r",stdin);
freopen("wave.out","w",stdout);
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d%d",&a[i].x,&a[i].y);
}
for(int i=1;i<=n;i++)
{
if(a[i].x>a[i-1].x)
{
sum+=a[i].x-a[i-1].x;
}
if(a[i].y>a[i-1].y)
{
sum+=a[i].y-a[i-1].y;
}
}
printf("%d",sum);
return 0;
}
| [
"506503360@qq.com"
] | 506503360@qq.com |
1623a5b9161bae0cafd513abccf83fe2f27fdab0 | a0f0efaaaf69d6ccdc2a91596db29f04025f122c | /build/car_db_manager_qtgui/ui_frmShowDialog.h | 780833ac717d42ba683ee1f9d7b5ef0c69ce1b2b | [] | no_license | chiuhandsome/ros_ws_test-git | 75da2723154c0dadbcec8d7b3b1f3f8b49aa5cd6 | 619909130c23927ccc902faa3ff6d04ae0f0fba9 | refs/heads/master | 2022-12-24T05:45:43.845717 | 2020-09-22T10:12:54 | 2020-09-22T10:12:54 | 297,582,735 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,600 | h | /********************************************************************************
** Form generated from reading UI file 'frmShowDialog.ui'
**
** Created by: Qt User Interface Compiler version 5.9.5
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_FRMSHOWDIALOG_H
#define UI_FRMSHOWDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_frmShowDialog
{
public:
QLabel *lb_iconshow;
QLabel *logo_label;
QWidget *widget;
QVBoxLayout *verticalLayout_2;
QLabel *lb_titlename;
QTextEdit *textEdit_context;
QWidget *widget1;
QGridLayout *gridLayout;
QPushButton *btn_cancel;
QPushButton *btn_confirm;
void setupUi(QDialog *frmShowDialog)
{
if (frmShowDialog->objectName().isEmpty())
frmShowDialog->setObjectName(QStringLiteral("frmShowDialog"));
frmShowDialog->resize(500, 334);
lb_iconshow = new QLabel(frmShowDialog);
lb_iconshow->setObjectName(QStringLiteral("lb_iconshow"));
lb_iconshow->setGeometry(QRect(10, 100, 131, 151));
logo_label = new QLabel(frmShowDialog);
logo_label->setObjectName(QStringLiteral("logo_label"));
logo_label->setGeometry(QRect(10, 20, 111, 61));
widget = new QWidget(frmShowDialog);
widget->setObjectName(QStringLiteral("widget"));
widget->setGeometry(QRect(155, 9, 321, 271));
verticalLayout_2 = new QVBoxLayout(widget);
verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2"));
verticalLayout_2->setContentsMargins(0, 0, 0, 0);
lb_titlename = new QLabel(widget);
lb_titlename->setObjectName(QStringLiteral("lb_titlename"));
QFont font;
font.setFamily(QStringLiteral("24pt Ubuntu"));
font.setBold(true);
font.setItalic(false);
font.setWeight(75);
lb_titlename->setFont(font);
lb_titlename->setStyleSheet(QLatin1String("color: blue;\n"
"font: bold,24pt \"Ubuntu\";"));
lb_titlename->setTextFormat(Qt::PlainText);
verticalLayout_2->addWidget(lb_titlename);
textEdit_context = new QTextEdit(widget);
textEdit_context->setObjectName(QStringLiteral("textEdit_context"));
textEdit_context->setStyleSheet(QLatin1String("font: bold,14pt \"Ubuntu\";\n"
"color: Blue;\n"
"background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 yellow, stop:1 rgba(255, 255, 255, 255));"));
textEdit_context->setFrameShape(QFrame::Panel);
textEdit_context->setFrameShadow(QFrame::Sunken);
textEdit_context->setLineWidth(3);
verticalLayout_2->addWidget(textEdit_context);
widget1 = new QWidget(frmShowDialog);
widget1->setObjectName(QStringLiteral("widget1"));
widget1->setGeometry(QRect(270, 290, 203, 34));
gridLayout = new QGridLayout(widget1);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
gridLayout->setContentsMargins(0, 0, 0, 0);
btn_cancel = new QPushButton(widget1);
btn_cancel->setObjectName(QStringLiteral("btn_cancel"));
btn_cancel->setStyleSheet(QLatin1String("font: bold,14pt \"Ubuntu\";\n"
"background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 yellow, stop:1 rgba(255, 255, 255, 255));\n"
"color: fuchsia;"));
QIcon icon;
icon.addFile(QStringLiteral(":/png/resource/tools_png/Back_001.png"), QSize(), QIcon::Normal, QIcon::Off);
btn_cancel->setIcon(icon);
btn_cancel->setIconSize(QSize(24, 24));
gridLayout->addWidget(btn_cancel, 0, 0, 1, 1);
btn_confirm = new QPushButton(widget1);
btn_confirm->setObjectName(QStringLiteral("btn_confirm"));
btn_confirm->setStyleSheet(QLatin1String("font: bold,14pt \"Ubuntu\";\n"
"background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 lightgreen, stop:1 rgba(255, 255, 255, 255));\n"
"color: blue;"));
QIcon icon1;
icon1.addFile(QStringLiteral(":/png/resource/tools_png/Check_001.png"), QSize(), QIcon::Normal, QIcon::Off);
btn_confirm->setIcon(icon1);
btn_confirm->setIconSize(QSize(24, 24));
gridLayout->addWidget(btn_confirm, 0, 1, 1, 1);
retranslateUi(frmShowDialog);
QMetaObject::connectSlotsByName(frmShowDialog);
} // setupUi
void retranslateUi(QDialog *frmShowDialog)
{
frmShowDialog->setWindowTitle(QApplication::translate("frmShowDialog", "Inquire Dialog - Cell Controller", Q_NULLPTR));
lb_iconshow->setText(QApplication::translate("frmShowDialog", "TextLabel", Q_NULLPTR));
logo_label->setText(QApplication::translate("frmShowDialog", "TextLabel", Q_NULLPTR));
lb_titlename->setText(QApplication::translate("frmShowDialog", "TextLabel", Q_NULLPTR));
btn_cancel->setText(QApplication::translate("frmShowDialog", "Cancel", Q_NULLPTR));
btn_confirm->setText(QApplication::translate("frmShowDialog", "Confirm", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class frmShowDialog: public Ui_frmShowDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_FRMSHOWDIALOG_H
| [
"chiuhandsome1966@gmail.com"
] | chiuhandsome1966@gmail.com |
b923da16b44e3d8e86bd235dea15d9dad40ce825 | 1c8e5a1fc7f9dfee4969194c1bd77918eea73095 | /Source/AllProjects/Tests/TestMacroDbg/TestMacroDbg_Type.hpp | e765a79192a5528b73f51fa3578e13fde84dd23a | [] | no_license | naushad-rahman/CIDLib | bcb579a6f9517d23d25ad17a152cc99b7508330e | 577c343d33d01e0f064d76dfc0b3433d1686f488 | refs/heads/master | 2020-04-28T01:08:35.084154 | 2019-03-10T02:03:20 | 2019-03-10T02:03:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 299 | hpp | //
// FILE NAME: TestMacroDbg_Type.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 02/14/2003
//
// COPYRIGHT: $_CIDLib_CopyRight_$
//
// $_CIDLib_CopyRight2_$
//
// DESCRIPTION:
//
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
#pragma CIDLIB_PACK(CIDLIBPACK)
#pragma CIDLIB_POPPACK
| [
"droddey@charmedquark.com"
] | droddey@charmedquark.com |
becb9df6a71954b98610ae7850f1a145ed1b423d | 666f6b121e7d13bb526b13f6b5f11b29634f3c31 | /HelloWorld/main.cpp | 40d85402f862167f0776c49d02b531d29d37948c | [] | no_license | Asmit-Bajaj/Qt-Using-Cpp | 9fa8907f30dd5cdfbcbf746b19e848522aaf48a7 | 97f80598e60e3b115f48109069d5dfd2f963e758 | refs/heads/main | 2023-02-15T03:38:06.551917 | 2021-01-01T10:11:04 | 2021-01-01T10:11:04 | 325,954,677 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 512 | cpp | #include<QApplication>
#include<QLabel>
int main(int argc,char* argv[]){
//here we are defining an object of application
QApplication app(argc,argv);
//creating a label
QLabel *label = new QLabel("Hello World");
//setting the title of window
label->setWindowTitle("My First App");
//defing the width and height
label->resize(400,400);
//showing the label
label->show();
//returns successful completion of application
return app.exec();
}
| [
"noreply@github.com"
] | Asmit-Bajaj.noreply@github.com |
ede1e70cb34fe74d0650bdcf8d9d6e1fad63de4a | 6570bfdb26a41d99620debec5541e789b3c613f3 | /Codechef/April Challenge/dish_of_life.cpp | 7d1ab75124ac0203d3b3b0b42bde3140aade4f10 | [] | no_license | ameet-1997/Competitive_Coding | bc30f37ae034efe7bb63f71241792fc53c323a50 | a9824430cf0458516ddd88655c1eca1f42ff3f0a | refs/heads/master | 2021-05-10T14:07:15.209770 | 2018-01-22T19:22:13 | 2018-01-22T19:22:13 | 118,500,812 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,880 | cpp | #include <bits/stdc++.h>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <utility>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <iomanip>
// setbase - cout << setbase (16); cout << 100 << endl; Prints 64
// setfill - cout << setfill ('x') << setw (5); cout << 77 << endl; prints
// xxx77
// setprecision - cout << setprecision (4) << f << endl; Prints x.xxxx
using namespace std;
#define f(i, a, b) for (int i = a; i < b; i++)
#define rep(i, n) f(i, 0, n)
#define fd(i, a, b) for (int i = a; i >= b; i--)
#define pb push_back
#define mp make_pair
#define vi vector<int>
#define vl vector<ll>
#define ss second
#define ff first
#define ll long long
#define pii pair<int, int>
#define pll pair<ll, ll>
#define sz(a) a.size()
#define inf (1000 * 1000 * 1000 + 5)
#define all(a) a.begin(), a.end()
#define tri pair<int, pii>
#define vii vector<pii>
#define vll vector<pll>
#define viii vector<tri>
#define mod (1000 * 1000 * 1000 + 7)
#define pqueue priority_queue<int>
#define pdqueue priority_queue<int, vi, greater<int> >
// std::ios::sync_with_stdio(false);
int main()
{
// sad, some, all
vi all_covered(100000);
int test;
cin >> test;
while (test--)
{
int n, k; // n islands and k ingredients
cin >> n >> k;
fill(all_covered.begin(), all_covered.begin() + k,
0); // To check if the ingredient i is present or not
vector<vector<int> > islands(100000);
for (int i = 0; i < n; ++i)
{
int number_of_ing;
cin >> number_of_ing;
int temp;
for (int j = 0; j < number_of_ing; ++j)
{
cin >> temp;
all_covered[temp - 1]++;
islands[i].pb(temp - 1);
}
}
int flag = 2;
for (int i = 0; i < k; ++i)
{
if (all_covered[i] == 0)
{
flag = 0;
break;
}
}
if (flag != 0)
{
for (int i = 0; i < n; ++i)
{
int flag1 = 0;
auto it = islands[i].begin();
while (it != islands[i].end())
{
if (all_covered[*it] == 1)
{
flag1 = 1;
break;
}
it++;
}
if (flag1 == 0)
{
flag = 1;
break;
}
}
}
if (flag == 0)
{
cout << "sad\n";
}
else if (flag == 1)
{
cout << "some\n";
}
else
{
cout << "all\n";
}
}
} | [
"ameetsd97@gmail.com"
] | ameetsd97@gmail.com |
bee712a297f0dfaff3c664217b51e95e9f622918 | 069b6c1e4e5a445235f49417ade6e5c3f79bb58d | /branches/2.3x/client/File.cpp | cbe515166d89a7a8710263db3d021cf94a2a7fe4 | [] | no_license | BackupTheBerlios/airdc-svn | 65a99494d5267ecb2ad96f21ead0299e7811131c | 17236498160afe8dc317bb75db374be8234eb541 | refs/heads/master | 2021-01-01T17:56:34.167869 | 2013-10-16T13:01:20 | 2013-10-16T13:01:20 | 40,718,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,849 | cpp | /*
* Copyright (C) 2001-2011 Jacek Sieka, arnetheduck on gmail point com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "stdinc.h"
#include "File.h"
namespace dcpp {
#ifdef _WIN32
File::File(const string& aFileName, int access, int mode, bool isAbsolute) {
dcassert(access == WRITE || access == READ || access == (READ | WRITE));
int m = 0;
if(mode & OPEN) {
if(mode & CREATE) {
m = (mode & TRUNCATE) ? CREATE_ALWAYS : OPEN_ALWAYS;
} else {
m = (mode & TRUNCATE) ? TRUNCATE_EXISTING : OPEN_EXISTING;
}
} else {
if(mode & CREATE) {
m = (mode & TRUNCATE) ? CREATE_ALWAYS : CREATE_NEW;
} else {
dcassert(0);
}
}
DWORD shared = FILE_SHARE_READ | (mode & SHARED ? (FILE_SHARE_WRITE | FILE_SHARE_DELETE) : 0);
string path = aFileName;
if(isAbsolute)
path = Util::FormatPath(aFileName);
h = ::CreateFile(Text::toT(path).c_str(), access, shared, NULL, m, mode & NO_CACHE_HINT ? 0 : FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if(h == INVALID_HANDLE_VALUE) {
throw FileException(Util::translateError(GetLastError()));
}
}
uint32_t File::getLastModified() const noexcept {
FILETIME f = {0};
::GetFileTime(h, NULL, NULL, &f);
return convertTime(&f);
}
uint32_t File::convertTime(FILETIME* f) {
SYSTEMTIME s = { 1970, 1, 0, 1, 0, 0, 0, 0 };
FILETIME f2 = {0};
if(::SystemTimeToFileTime(&s, &f2)) {
ULARGE_INTEGER a,b;
a.LowPart =f->dwLowDateTime;
a.HighPart=f->dwHighDateTime;
b.LowPart =f2.dwLowDateTime;
b.HighPart=f2.dwHighDateTime;
return (a.QuadPart - b.QuadPart) / (10000000LL); // 100ns > s
}
return 0;
}
bool File::isOpen() const noexcept {
return h != INVALID_HANDLE_VALUE;
}
void File::close() noexcept {
if(isOpen()) {
CloseHandle(h);
h = INVALID_HANDLE_VALUE;
}
}
int64_t File::getSize() const noexcept {
LARGE_INTEGER x;
if(!::GetFileSizeEx(h, &x))
return -1;
return x.QuadPart;
}
int64_t File::getPos() const noexcept {
LONG x = 0;
DWORD l = ::SetFilePointer(h, 0, &x, FILE_CURRENT);
return (int64_t)l | ((int64_t)x)<<32;
}
void File::setSize(int64_t newSize) {
int64_t pos = getPos();
setPos(newSize);
setEOF();
setPos(pos);
}
void File::setPos(int64_t pos) noexcept {
LONG x = (LONG) (pos>>32);
::SetFilePointer(h, (DWORD)(pos & 0xffffffff), &x, FILE_BEGIN);
}
void File::setEndPos(int64_t pos) noexcept {
LONG x = (LONG) (pos>>32);
::SetFilePointer(h, (DWORD)(pos & 0xffffffff), &x, FILE_END);
}
void File::movePos(int64_t pos) noexcept {
LONG x = (LONG) (pos>>32);
::SetFilePointer(h, (DWORD)(pos & 0xffffffff), &x, FILE_CURRENT);
}
size_t File::read(void* buf, size_t& len) {
DWORD x;
if(!::ReadFile(h, buf, (DWORD)len, &x, NULL)) {
throw(FileException(Util::translateError(GetLastError())));
}
len = x;
return x;
}
size_t File::write(const void* buf, size_t len) {
DWORD x;
if(!::WriteFile(h, buf, (DWORD)len, &x, NULL)) {
throw FileException(Util::translateError(GetLastError()));
}
dcassert(x == len);
return x;
}
void File::setEOF() {
dcassert(isOpen());
if(!SetEndOfFile(h)) {
throw FileException(Util::translateError(GetLastError()));
}
}
size_t File::flush() {
if(isOpen() && !FlushFileBuffers(h))
throw FileException(Util::translateError(GetLastError()));
return 0;
}
void File::renameFile(const string& source, const string& target) {
if(!::MoveFile(Text::toT(Util::FormatPath(source)).c_str(), Text::toT(Util::FormatPath(target)).c_str())) {
// Can't move, try copy/delete...
copyFile(source, target);
deleteFile(source);
}
}
void File::copyFile(const string& src, const string& target) {
if(!::CopyFile(Text::toT(Util::FormatPath(src)).c_str(), Text::toT(Util::FormatPath(target)).c_str(), FALSE)) {
throw FileException(Util::translateError(GetLastError()));
}
}
void File::deleteFile(const string& aFileName) noexcept
{
::DeleteFile(Text::toT(Util::FormatPath(aFileName)).c_str());
}
int64_t File::getSize(const string& aFileName) noexcept {
WIN32_FIND_DATA fd;
HANDLE hFind;
hFind = FindFirstFile(Text::toT(Util::FormatPath(aFileName)).c_str(), &fd);
if (hFind == INVALID_HANDLE_VALUE) {
return -1;
} else {
FindClose(hFind);
return ((int64_t)fd.nFileSizeHigh << 32 | (int64_t)fd.nFileSizeLow);
}
}
void File::ensureDirectory(const string& aFile) noexcept {
// Skip the first dir...
tstring file;
Text::toT(aFile, file);
tstring::size_type start = file.find_first_of(_T("\\/"));
if(start == string::npos)
return;
start++;
while( (start = file.find_first_of(_T("\\/"), start)) != string::npos) {
::CreateDirectory((Util::FormatPath(file.substr(0, start+1))).c_str(), NULL);
start++;
}
}
bool File::createDirectory(const string& aFile) {
// Skip the first dir...
int result = 0;
tstring file;
Text::toT(aFile, file);
wstring::size_type start = file.find_first_of(L"\\/");
if(start == string::npos)
return false;
start++;
while( (start = file.find_first_of(L"\\/", start)) != string::npos) {
result = CreateDirectory(file.substr(0, start+1).c_str(), NULL);
start++;
}
if(result == 0) {
result = GetLastError();
if(result == ERROR_ALREADY_EXISTS || result == ERROR_SUCCESS)
return false;
else if(result == ERROR_PATH_NOT_FOUND) //we can't recover from this gracefully.
throw FileException(Util::translateError(result));
}
return true;
}
bool File::isAbsolute(const string& path) noexcept {
return path.size() > 2 && (path[1] == ':' || path[0] == '/' || path[0] == '\\');
}
#else // !_WIN32
File::File(const string& aFileName, int access, int mode) {
dcassert(access == WRITE || access == READ || access == (READ | WRITE));
int m = 0;
if(access == READ)
m |= O_RDONLY;
else if(access == WRITE)
m |= O_WRONLY;
else
m |= O_RDWR;
if(mode & CREATE) {
m |= O_CREAT;
}
if(mode & TRUNCATE) {
m |= O_TRUNC;
}
string filename = Text::fromUtf8(aFileName);
struct stat s;
if(lstat(filename.c_str(), &s) != -1) {
if(!S_ISREG(s.st_mode) && !S_ISLNK(s.st_mode))
throw FileException("Invalid file type");
}
h = open(filename.c_str(), m, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if(h == -1)
throw FileException(Util::translateError(errno));
}
uint32_t File::getLastModified() const noexcept {
struct stat s;
if (::fstat(h, &s) == -1)
return 0;
return (uint32_t)s.st_mtime;
}
bool File::isOpen() const noexcept {
return h != -1;
}
void File::close() noexcept {
if(h != -1) {
::close(h);
h = -1;
}
}
int64_t File::getSize() const noexcept {
struct stat s;
if(::fstat(h, &s) == -1)
return -1;
return (int64_t)s.st_size;
}
int64_t File::getPos() const noexcept {
return (int64_t)lseek(h, 0, SEEK_CUR);
}
void File::setPos(int64_t pos) noexcept {
lseek(h, (off_t)pos, SEEK_SET);
}
void File::setEndPos(int64_t pos) noexcept {
lseek(h, (off_t)pos, SEEK_END);
}
void File::movePos(int64_t pos) noexcept {
lseek(h, (off_t)pos, SEEK_CUR);
}
size_t File::read(void* buf, size_t& len) {
ssize_t result = ::read(h, buf, len);
if (result == -1) {
throw FileException(Util::translateError(errno));
}
len = result;
return (size_t)result;
}
size_t File::write(const void* buf, size_t len) {
ssize_t result;
char* pointer = (char*)buf;
ssize_t left = len;
while (left > 0) {
result = ::write(h, pointer, left);
if (result == -1) {
if (errno != EINTR) {
throw FileException(Util::translateError(errno));
}
} else {
pointer += result;
left -= result;
}
}
return len;
}
// some ftruncate implementations can't extend files like SetEndOfFile,
// not sure if the client code needs this...
int File::extendFile(int64_t len) noexcept {
char zero;
if( (lseek(h, (off_t)len, SEEK_SET) != -1) && (::write(h, &zero,1) != -1) ) {
ftruncate(h,(off_t)len);
return 1;
}
return -1;
}
void File::setEOF() {
int64_t pos;
int64_t eof;
int ret;
pos = (int64_t)lseek(h, 0, SEEK_CUR);
eof = (int64_t)lseek(h, 0, SEEK_END);
if (eof < pos)
ret = extendFile(pos);
else
ret = ftruncate(h, (off_t)pos);
lseek(h, (off_t)pos, SEEK_SET);
if (ret == -1)
throw FileException(Util::translateError(errno));
}
void File::setSize(int64_t newSize) {
int64_t pos = getPos();
setPos(newSize);
setEOF();
setPos(pos);
}
size_t File::flush() {
if(isOpen() && fsync(h) == -1)
throw FileException(Util::translateError(errno));
return 0;
}
/**
* ::rename seems to have problems when source and target is on different partitions
* from "man 2 rename":
* EXDEV oldpath and newpath are not on the same mounted filesystem. (Linux permits a
* filesystem to be mounted at multiple points, but rename(2) does not
* work across different mount points, even if the same filesystem is mounted on both.)
*/
void File::renameFile(const string& source, const string& target) {
int ret = ::rename(Text::fromUtf8(source).c_str(), Text::fromUtf8(target).c_str());
if(ret != 0 && errno == EXDEV) {
copyFile(source, target);
deleteFile(source);
} else if(ret != 0)
throw FileException(source + Util::translateError(errno));
}
// This doesn't assume all bytes are written in one write call, it is a bit safer
void File::copyFile(const string& source, const string& target) {
const size_t BUF_SIZE = 64 * 1024;
boost::scoped_array<char> buffer(new char[BUF_SIZE]);
size_t count = BUF_SIZE;
File src(source, File::READ, 0);
File dst(target, File::WRITE, File::CREATE | File::TRUNCATE);
while(src.read(&buffer[0], count) > 0) {
char* p = &buffer[0];
while(count > 0) {
size_t ret = dst.write(p, count);
p += ret;
count -= ret;
}
count = BUF_SIZE;
}
}
void File::deleteFile(const string& aFileName) noexcept {
::unlink(Text::fromUtf8(aFileName).c_str());
}
int64_t File::getSize(const string& aFileName) noexcept {
struct stat s;
if(stat(Text::fromUtf8(aFileName).c_str(), &s) == -1)
return -1;
return s.st_size;
}
void File::ensureDirectory(const string& aFile) noexcept {
string file = Text::fromUtf8(aFile);
string::size_type start = 0;
while( (start = file.find_first_of('/', start)) != string::npos) {
mkdir(file.substr(0, start+1).c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
start++;
}
}
bool File::isAbsolute(const string& path) noexcept {
return path.size() > 1 && path[0] == '/';
}
#endif // !_WIN32
string File::read(size_t len) {
string s(len, 0);
size_t x = read(&s[0], len);
if(x != s.size())
s.resize(x);
return s;
}
string File::read() {
setPos(0);
int64_t sz = getSize();
if(sz == -1)
return Util::emptyString;
return read((uint32_t)sz);
}
StringList File::findFiles(const string& path, const string& pattern) {
StringList ret;
#ifdef _WIN32
WIN32_FIND_DATA data;
HANDLE hFind;
hFind = ::FindFirstFile(Text::toT(Util::FormatPath(path + pattern)).c_str(), &data);
if(hFind != INVALID_HANDLE_VALUE) {
do {
const char* extra = (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? "\\" : "";
ret.push_back(path + Text::fromT(data.cFileName) + extra);
} while(::FindNextFile(hFind, &data));
::FindClose(hFind);
}
#else
DIR* dir = opendir(Text::fromUtf8(path).c_str());
if (dir) {
while (struct dirent* ent = readdir(dir)) {
if (fnmatch(pattern.c_str(), ent->d_name, 0) == 0) {
struct stat s;
stat(ent->d_name, &s);
const char* extra = (s.st_mode & S_IFDIR) ? "/" : "";
ret.push_back(path + Text::toUtf8(ent->d_name) + extra);
}
}
closedir(dir);
}
#endif
return ret;
}
#ifdef _WIN32
FileFindIter::FileFindIter() : handle(INVALID_HANDLE_VALUE) { }
FileFindIter::FileFindIter(const string& path) : handle(INVALID_HANDLE_VALUE) {
handle = ::FindFirstFile(Text::toT(Util::FormatPath(path)).c_str(), &data);
}
FileFindIter::~FileFindIter() {
if(handle != INVALID_HANDLE_VALUE) {
::FindClose(handle);
}
}
FileFindIter& FileFindIter::operator++() {
if(!::FindNextFile(handle, &data)) {
::FindClose(handle);
handle = INVALID_HANDLE_VALUE;
}
return *this;
}
bool FileFindIter::operator!=(const FileFindIter& rhs) const { return handle != rhs.handle; }
FileFindIter::DirData::DirData() { }
string FileFindIter::DirData::getFileName() {
return Text::fromT(cFileName);
}
bool FileFindIter::DirData::isDirectory() {
return (dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) > 0;
}
bool FileFindIter::DirData::isHidden() {
return ((dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) || (cFileName[0] == L'.') || (dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) || (dwFileAttributes & FILE_ATTRIBUTE_OFFLINE));
}
bool FileFindIter::DirData::isLink() {
return false;
}
int64_t FileFindIter::DirData::getSize() {
return (int64_t)nFileSizeLow | ((int64_t)nFileSizeHigh)<<32;
}
uint32_t FileFindIter::DirData::getLastWriteTime() {
return File::convertTime(&ftLastWriteTime);
}
#else // _WIN32
FileFindIter::FileFindIter() {
dir = NULL;
data.ent = NULL;
}
FileFindIter::FileFindIter(const string& path) {
string filename = Text::fromUtf8(path);
dir = opendir(filename.c_str());
if (!dir)
return;
data.base = filename;
data.ent = readdir(dir);
if (!data.ent) {
closedir(dir);
dir = NULL;
}
}
FileFindIter::~FileFindIter() {
if (dir) closedir(dir);
}
FileFindIter& FileFindIter::operator++() {
if (!dir)
return *this;
data.ent = readdir(dir);
if (!data.ent) {
closedir(dir);
dir = NULL;
}
return *this;
}
bool FileFindIter::operator!=(const FileFindIter& rhs) const {
// good enough to to say if it's null
return dir != rhs.dir;
}
FileFindIter::DirData::DirData() : ent(NULL) {}
string FileFindIter::DirData::getFileName() {
if (!ent) return Util::emptyString;
return Text::toUtf8(ent->d_name);
}
bool FileFindIter::DirData::isDirectory() {
struct stat inode;
if (!ent) return false;
if (stat((base + PATH_SEPARATOR + ent->d_name).c_str(), &inode) == -1) return false;
return S_ISDIR(inode.st_mode);
}
bool FileFindIter::DirData::isHidden() {
if (!ent) return false;
// Check if the parent directory is hidden for '.'
if (strcmp(ent->d_name, ".") == 0 && base[0] == '.') return true;
return ent->d_name[0] == '.' && strlen(ent->d_name) > 1;
}
bool FileFindIter::DirData::isLink() {
struct stat inode;
if (!ent) return false;
if (lstat((base + PATH_SEPARATOR + ent->d_name).c_str(), &inode) == -1) return false;
return S_ISLNK(inode.st_mode);
}
int64_t FileFindIter::DirData::getSize() {
struct stat inode;
if (!ent) return false;
if (stat((base + PATH_SEPARATOR + ent->d_name).c_str(), &inode) == -1) return 0;
return inode.st_size;
}
uint32_t FileFindIter::DirData::getLastWriteTime() {
struct stat inode;
if (!ent) return false;
if (stat((base + PATH_SEPARATOR + ent->d_name).c_str(), &inode) == -1) return 0;
return inode.st_mtime;
}
#endif // _WIN32
} // namespace dcpp
| [
"maksis@d6773c42-f83c-be49-aa62-2d473f764b1f"
] | maksis@d6773c42-f83c-be49-aa62-2d473f764b1f |
37f5cc311de6deb16e9385b8dac2e52ee9e7c931 | 7b5ea35475e79fcabbc1d891794335ab083cead7 | /BAY_MONITOR/BAY_IN.ino | ccb2b20c25b75b1c1b5e74d0d0d64c3b066f0e71 | [] | no_license | Camacazzi/LoRA_Carpark_Occupancy_System | aa93b6d7744bdaa235e9d3633b5cda54f16f217d | 95fd17a05c2078bed9c552ca84473b6eab2368dd | refs/heads/master | 2020-07-29T22:04:06.840331 | 2019-10-02T06:51:20 | 2019-10-02T06:51:20 | 209,978,754 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,186 | ino | /*
* Ultrasonic reading code created by Rui Santos, https://randomnerdtutorials.com
*/
#include <lmic.h>
//#include <lmic/oslmic.h>
#include <hal/hal.h>
#include <SPI.h>
#if !defined(DISABLE_INVERT_IQ_ON_RX)
#error This example requires DISABLE_INVERT_IQ_ON_RX to be set. Update \
config.h in the lmic library to set it.
#endif
#define TX_INTERVAL 4000
//#define NODE_TYPE 1
#define SYNC_DURATION 40
int trigPin = 3; // Trigger
int echoPin = 4; // Echo
long duration, cm, inches;
int carcount;
int carpresent;
int movementtrigger = 0;
char transmit[32];
int delaycount = 0;
// Pin mapping
const lmic_pinmap lmic_pins = {
.nss = 10,
.rxtx = LMIC_UNUSED_PIN,
.rst = 9,
.dio = {2, 6, 7},
};
void os_getArtEui (u1_t* buf) { }
void os_getDevEui (u1_t* buf) { }
void os_getDevKey (u1_t* buf) { }
void onEvent (ev_t ev) {
}
osjob_t txjob;
osjob_t timeoutjob;
static void tx_func (osjob_t* job);
// Transmit the given string and call the given function afterwards
void tx(const char *str, osjobcb_t func) {
os_radio(RADIO_RST); // Stop RX first
delay(1); // Wait a bit, without this os_radio below asserts, apparently because the state hasn't changed yet
LMIC.dataLen = 0;
while (*str)
LMIC.frame[LMIC.dataLen++] = *str++;
//LMIC.osjob.func = func;
os_radio(RADIO_TX);
Serial.println("TX");
}
static void txdone_func (osjob_t* job) {
//rx(rx_func);
}
// log text to USART and toggle LED
static void tx_func(osjob_t* job) {
//Two transmission types, 0 for sync packet, 1 for data packet.
//New car has entered!
if(type){
snprintf(transmit, sizeof(transmit), "BAY\\1\\%i", carpresent);
printf("Transmitting packet: %s", transmit);
tx(transmit, txdone_func);
}
else{
//Send sync packet
printf("Sending sync packet");
snprintf(transmit, sizeof(transmit), "SYNC//BAY//1//%i", carpresent);
tx(transmit, txdone_func);
}
}
void setup() {
//Serial Port begin
Serial.begin (9600);
//Define inputs and outputs for sensor
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.println("Starting");
#ifdef VCC_ENABLE
// For Pinoccio Scout boards
pinMode(VCC_ENABLE, OUTPUT);
digitalWrite(VCC_ENABLE, HIGH);
Serial.println(LMIC.freq); //from http://wiki.dragino.com/index.php?title=Lora_Shield
delay(1000);
#endif
pinMode(LED_BUILTIN, OUTPUT);
// initialize runtime env
os_init();
// Set up these settings once, and use them for both TX and RX
//see also void LMIC_setDrTxpow (dr_t dr, s1_t txpow)
// Use a frequency in the g3 which allows 10% duty cycling.
// TODO select different frequencies
LMIC.freq = 915525000;
// Set data rate and transmit power (note: txpow seems to be ignored by the library)
// for loraWAN LMIC_setDrTxpow(DR_SF7,14);
// Maximum TX power use 27;
//TODO cycle through different txpowers
LMIC.txpow = 2; //2 to 15
// Use a medium spread factor. This can be increased up to SF12 for
// better range, but then the interval should be (significantly)
// lowered to comply with duty cycle limits as well.
LMIC.datarate = DR_SF7; //was DR_SF9; //other choices eg DR_SF7 lowest energy w BW125
// This sets CR 4/5, BW125 (except for DR_SF7B, which uses BW250)
LMIC.rps = updr2rps(LMIC.datarate);
Serial.println("Started");
Serial.flush();
// setup initial job
//os_setCallback(&txjob, tx_func);
}
void loop() {
type = 0;
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the signal from the sensor: a HIGH pulse whose
// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// Convert the time into a distance
cm = (duration/2) / 29.1; // Divide by 29.1 or multiply by 0.0343
Serial.print(cm);
Serial.print("cm");
Serial.println();
//Logic is intended to be robust to small variations in distance
//If object is close, acknowledge car is present
if(cm < 50){
if(!carpresent){
carcount++;
}
if(carcount > 10 && carpresent == 0){
carpresent = 1;
movementtrigger = 1;
}
}
//If object is far, decrement count if count is greater than 0
else{
if(carcount == 0 && carpresent == 1){
carpresent = 0;
movementtrigger = 1;
}
else{
carcount--;
}
}
//An object has sat infront of the sensor for long enough, consider it to be a car
if(movementtrigger == 1){
movementtrigger = 0;
count = 0;
delaycount = 0;
type = 1;
os_setCallback(&txjob, tx_func);
Serial.print("Car has entered");
Serial.println();
os_runloop_once();
}
delay(250);
//If go through 4 delays without sending, send sync.
if(!type){
delaycount++;
}
if(delaycount >= SYNC_DURATION){
type = 0;
delaycount = 0;
os_setCallback(&txjob, tx_func);
os_runloop_once();
}
}
| [
"cameron.turner1998@outlook.com"
] | cameron.turner1998@outlook.com |
9db08aee6a6635af46c1d6fb45c46fa4d9aeeb04 | e38e486a80679c025c2dd03396eb03e6c3e07bdf | /Source/UI/TextBox.cpp | c403aeea20581afc000174447cf582c3e7a8c71f | [] | no_license | MattFiler/Planned-Obsolescence | 2cf20cc1308802a36a09e16844d75ae90fd3b842 | e72195bd50d5218bb213c84b059fc7cbbd5fb3ce | refs/heads/master | 2020-04-24T15:32:14.706409 | 2019-02-24T22:56:30 | 2019-02-24T22:56:30 | 172,071,645 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,155 | cpp | #include "TextBox.h"
TextBox::TextBox(Point pos,
ASGE::Renderer* rend,
const std::string& text,
float _width,
float _height,
float _font_size,
ASGE::Colour colour,
Point _padding) :
UI(pos, rend),
displayed_text(text), font_size(_font_size * ScaledSpriteArray::width_scale), font_colour(colour),
padding(_padding)
{
width = _width;
height = _height;
wrapText();
}
TextBox::~TextBox()
{
delete background_sprite;
background_sprite = nullptr;
}
/* Renders this text to screen with its background (if any) */
void TextBox::render(double delta_time)
{
if (background_sprite)
{
renderer->renderSprite(background_sprite->returnNextSprite(delta_time));
}
renderer->renderText(
displayed_text,
static_cast<int>((position.x_pos + padding.x_pos) * ScaledSpriteArray::width_scale),
static_cast<int>((position.y_pos + padding.y_pos + (font_size * 20)) *
ScaledSpriteArray::width_scale),
font_size,
font_colour);
}
/* Sets the sprite that will be rendered behind the text */
void TextBox::setBackgroundSprite(const std::string& sprite_texture_path)
{
background_sprite = createSprite(sprite_texture_path);
background_sprite->setWidth(width);
background_sprite->setHeight(height);
background_sprite->xPos(position.x_pos);
background_sprite->yPos(position.y_pos);
}
/* Replaces the current text with the passed argument */
void TextBox::setText(const std::string& new_text)
{
displayed_text = new_text;
wrapText();
}
/* Horizontally wraps text to stay within the width of this TextBos */
void TextBox::wrapText()
{
// Calculate the max number of characters per line, this is only roughly accurate unfortunately
// Also need to remove the width_scale since all other calculations are done in simulated world
// space
auto char_per_line = static_cast<unsigned long long>(
(width - (2 * padding.x_pos)) / (font_size / ScaledSpriteArray::width_scale));
// Divide by some number, may vary by font, unsure on how to get this part exact
char_per_line /= 22;
unsigned long long str_index = 0;
// While there are characters left to process
while (str_index < displayed_text.size())
{
// Check if any newlines already exist
bool newline_exists = false;
for (unsigned long long i = str_index; i < str_index + char_per_line; i++)
{
if (displayed_text[i] == '\n')
{
newline_exists = true;
str_index = i + 1;
break;
}
}
if (!newline_exists)
{
str_index += char_per_line;
// If there is a full line left
if (str_index < displayed_text.length())
{
// Backtrack to the last space
while (displayed_text[str_index] != ' ')
{
// If the index gets to 0, this is the best we can do so finish here
if (str_index == 0)
{
return;
}
str_index--;
}
// Replace that space with a newline
displayed_text[str_index] = '\n';
str_index++;
}
}
}
} | [
"tobyjones1993@gmail.com"
] | tobyjones1993@gmail.com |
39600b3c9e4c6bf9d1f450ab1e39017b467d55ea | c8a4feaa315917b64f23b56c33e6191053c95ee8 | /src/dominantplanesegmentationcell.cpp | 29f8bb797ade4a037bff9608b5762cb7eaaba95e | [] | no_license | stanislas-brossette/cloud-treatment | 1a195062654eba2d1f01ff24087b441812a8ee0e | 3578d7a31e58ad16d21a43a7585a2e47b651e0aa | refs/heads/master | 2020-06-04T11:11:13.482977 | 2013-05-22T04:03:01 | 2013-05-22T04:03:01 | 8,211,832 | 0 | 0 | null | 2013-04-19T05:58:06 | 2013-02-15T02:41:13 | C++ | UTF-8 | C++ | false | false | 1,979 | cpp | #include <boost/make_shared.hpp>
#include <pcl/filters/extract_indices.h>
#include <pcl/ModelCoefficients.h>
#include <pcl/segmentation/sac_segmentation.h>
#include "dominantplanesegmentationcell.h"
#include "plancloud.h"
DominantPlaneSegmentationCell::DominantPlaneSegmentationCell():
Cell()
{
parameters()["name"] = "DominantPlaneSegmentationCell";
parameters()["max_iteration"] = 100;
parameters()["distance_threshold"] = 0.03;
seg_.setOptimizeCoefficients (false);
seg_.setModelType (pcl::SACMODEL_PLANE);
seg_.setMethodType (pcl::SAC_RANSAC);
initial_cloud_ptr_ = boost::make_shared<pointCloud_t>();
plan_cloud_ptr_ = boost::make_shared<PlanCloud > ();
new_plan_cloud_list_ptr_ = boost::make_shared<planClouds_t >();
}
planCloudsPtr_t DominantPlaneSegmentationCell::compute
(planCloudsPtr_t planCloudListPtr)
{
cell_name_ = boost::get<std::string>(parameters()["name"]);
distance_threshold_ = boost::get<double>(
parameters()["distance_threshold"]);
max_iterations_ = static_cast<int>(
boost::get<double>(parameters()["max_iteration"]));
seg_.setDistanceThreshold (distance_threshold_);
seg_.setMaxIterations (max_iterations_);
for(std::size_t j = 0;j<planCloudListPtr->size(); ++j)
{
// Segmentation of the dominant plane
initial_cloud_ptr_ = planCloudListPtr->at(j).cloud();
seg_.setInputCloud (initial_cloud_ptr_);
pcl::ModelCoefficients::Ptr coefficients (
new pcl::ModelCoefficients ());
pcl::PointIndices::Ptr inliers (new pcl::PointIndices ());
seg_.segment (*inliers, *coefficients);
// Extract the inliers
extract_.setInputCloud (initial_cloud_ptr_);
extract_.setIndices (inliers);
extract_.setNegative (true);
extract_.filter (*(plan_cloud_ptr_->cloud()));
new_plan_cloud_list_ptr_->push_back(*plan_cloud_ptr_);
// extract_.setNegative (false);
// extract_.filter (*(plan_cloud_ptr_->cloud()));
// new_plan_cloud_list_ptr_->push_back(*plan_cloud_ptr_);
}
return new_plan_cloud_list_ptr_;
}
| [
"brossette@lirmm.fr"
] | brossette@lirmm.fr |
3abe7ffb853048d0f948887c1b2d397591d773c5 | 47583682f2a5ed0f4cc96ca4995111fe7f877ac9 | /IR/Translate/IRPrinter.h | 08b3bf655630ef1a5f446c91dc535ce72c15e776 | [
"Apache-2.0"
] | permissive | IKholopov/shishkin_forest | 830a1dcd75a2b10e243f2f4a887c44e870a80654 | d6812ecc305ad35373384fb5a3abdf14502bc148 | refs/heads/master | 2020-03-25T08:45:31.365047 | 2018-05-21T07:17:07 | 2018-06-20T00:04:52 | 143,630,909 | 0 | 0 | Apache-2.0 | 2018-08-05T16:45:31 | 2018-08-05T16:45:30 | null | UTF-8 | C++ | false | false | 1,503 | h | #pragma once
#include "common.h"
#include <fstream>
#include "Framework/DotPrint.h"
#include "IRVisitor.h"
#include "SubtreeWrapper.h"
namespace IRTranslate {
class IRPrinter : public IR::IIRVisitor, private DotPrint {
public:
IRPrinter(std::string filename) :
DotPrint(filename)
{
}
void CreateGraph(IRForest& forest);
void CreateGraph(IRLinearForest& forest);
virtual void Visit(IR::Unaryop* node) override;
virtual void Visit(IR::Binop* node) override;
virtual void Visit(IR::Call* node) override;
virtual void Visit(IR::Const* node) override;
virtual void Visit(IR::Eseq* node) override;
virtual void Visit(IR::Mem* node) override;
virtual void Visit(IR::Name* node) override;
virtual void Visit(IR::Temp* node) override;
virtual void Visit(IR::Exp* node) override;
virtual void Visit(IR::Jump* node) override;
virtual void Visit(IR::JumpC* node) override;
virtual void Visit(IR::LabelStm* node) override;
virtual void Visit(IR::Move* node) override;
virtual void Visit(IR::Seq* node) override;
virtual void Visit(IR::ExpList* node) override;
virtual void Visit(StmWrapper* node) override;
virtual void Visit(ExpWrapper* node) override;
private:
std::string format(IR::Unaryop::TUnaryop op);
std::string format(IR::Binop::TBinop op);
std::string format(const IR::Temp *temp);
std::string format(IR::JumpC::TJumpType type);
std::string format(const IR::Coords& coords);
};
}
| [
"kholopov96@gmail.com"
] | kholopov96@gmail.com |
c03b6f17106eb4032cc5ff205649566bdb06537b | 19eb97436a3be9642517ea9c4095fe337fd58a00 | /private/windows/shell/snapins/devmgr/snapin/componet.cpp | b44073323c37e3e928849fdb351843173521fbe0 | [] | no_license | oturan-boga/Windows2000 | 7d258fd0f42a225c2be72f2b762d799bd488de58 | 8b449d6659840b6ba19465100d21ca07a0e07236 | refs/heads/main | 2023-04-09T23:13:21.992398 | 2021-04-22T11:46:21 | 2021-04-22T11:46:21 | 360,495,781 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,195 | cpp | /*++
Copyright (C) 1997-1999 Microsoft Corporation
Module Name:
componet.cpp
Abstract:
This module implemets CComponent class
Author:
William Hsieh (williamh) created
Revision History:
--*/
#include "devmgr.h"
#include "factory.h"
//
// ctor and dtor
//
CComponent::CComponent(
CComponentData* pComponentData
)
{
m_pComponentData = pComponentData;
m_pHeader = NULL;
m_pConsole = NULL;
m_pResult = NULL;
m_pConsoleVerb = NULL;
m_pCurFolder = NULL;
m_pPropSheetProvider = NULL;
m_pDisplayHelp = NULL;
m_MachineAttached = FALSE;
m_Dirty = FALSE;
m_pControlbar = NULL;
m_pToolbar = NULL;
// increment object count(used by CanUnloadNow)
::InterlockedIncrement(&CClassFactory::s_Objects);
m_Ref = 1;
}
CComponent::~CComponent()
{
// decrement object count(used by CanUnloadNow)
::InterlockedDecrement(&CClassFactory::s_Objects);
}
//
// IUNKNOWN interface
//
ULONG
CComponent::AddRef()
{
::InterlockedIncrement((LONG*)&m_Ref);
return m_Ref;
}
ULONG
CComponent::Release()
{
::InterlockedDecrement((LONG*)&m_Ref);
if (!m_Ref)
{
delete this;
return 0;
}
return m_Ref;
}
STDMETHODIMP
CComponent::QueryInterface(
REFIID riid,
void** ppv
)
{
if (!ppv)
return E_INVALIDARG;
HRESULT hr = S_OK;
if (IsEqualIID(riid, IID_IUnknown))
{
*ppv = (IUnknown*)(IComponent*)this;
}
else if (IsEqualIID(riid, IID_IComponent))
{
*ppv = (IComponent*)this;
}
else if (IsEqualIID(riid, IID_IResultDataCompare))
{
*ppv = (IResultDataCompare*)this;
}
else if (IsEqualIID(riid, IID_IExtendContextMenu))
{
*ppv = (IExtendContextMenu*)this;
}
else if (IsEqualIID(riid, IID_IExtendControlbar))
{
*ppv = (IExtendControlbar*)this;
}
else if (IsEqualIID(riid, IID_IExtendPropertySheet))
{
*ppv = (IExtendPropertySheet*)this;
}
#ifdef PERSIST_VIEW
else if (IsEqualIID(riid, IID_IPersistStream))
{
*ppv = (IPersistStream*)this;
}
#endif
else if (IsEqualIID(riid, IID_ISnapinCallback))
{
*ppv = (ISnapinCallback*)this;
}
else
{
*ppv = NULL;
hr = E_NOINTERFACE;
}
if (SUCCEEDED(hr))
{
AddRef();
}
return hr;
}
//
// IComponent interface implementation
//
STDMETHODIMP
CComponent::GetResultViewType(
MMC_COOKIE cookie,
LPOLESTR* ppViewType,
long* pViewOptions
)
{
if (!ppViewType || !pViewOptions)
return E_INVALIDARG;
HRESULT hr;
try
{
CFolder* pFolder;
pFolder = FindFolder(cookie);
if (pFolder)
return pFolder->GetResultViewType(ppViewType, pViewOptions);
else
return S_OK;
}
catch (CMemoryException* e)
{
e->Delete();
MsgBoxParam(m_pComponentData->m_hwndMain, 0, 0, 0);
return S_FALSE;
}
}
STDMETHODIMP
CComponent::Initialize(
LPCONSOLE lpConsole
)
{
HRESULT hr;
if (!lpConsole)
return E_INVALIDARG;
m_pConsole = lpConsole;
lpConsole->AddRef();
hr = lpConsole->QueryInterface(IID_IHeaderCtrl, (void**)&m_pHeader);
if (SUCCEEDED(hr))
{
lpConsole->SetHeader(m_pHeader);
hr = lpConsole->QueryInterface(IID_IResultData, (void**)&m_pResult);
}
if (SUCCEEDED(hr))
{
hr = lpConsole->QueryConsoleVerb(&m_pConsoleVerb);
}
if (SUCCEEDED(hr))
{
hr = lpConsole->QueryInterface(IID_IPropertySheetProvider,
(void**)&m_pPropSheetProvider);
}
if (SUCCEEDED(hr))
{
hr = lpConsole->QueryInterface(IID_IDisplayHelp, (void**)&m_pDisplayHelp);
}
if (FAILED(hr))
OutputDebugString(TEXT("CComponent::Initialize failed\n"));
return hr;
}
#if DBG
TCHAR *mmcNotifyStr[] = {
TEXT("UNKNOWN"),
TEXT("ACTIVATE"),
TEXT("ADD_IMAGES"),
TEXT("BTN_CLICK"),
TEXT("CLICK"),
TEXT("COLUMN_CLICK"),
TEXT("CONTEXTMENU"),
TEXT("CUTORMOVE"),
TEXT("DBLCLICK"),
TEXT("DELETE"),
TEXT("DESELECT_ALL"),
TEXT("EXPAND"),
TEXT("HELP"),
TEXT("MENU_BTNCLICK"),
TEXT("MINIMIZED"),
TEXT("PASTE"),
TEXT("PROPERTY_CHANGE"),
TEXT("QUERY_PASTE"),
TEXT("REFRESH"),
TEXT("REMOVE_CHILDREN"),
TEXT("RENAME"),
TEXT("SELECT"),
TEXT("SHOW"),
TEXT("VIEW_CHANGE"),
TEXT("SNAPINHELP"),
TEXT("CONTEXTHELP"),
TEXT("INITOCX"),
TEXT("FILTER_CHANGE"),
TEXT("FILTERBTN_CLICK"),
TEXT("RESTORE_VIEW"),
TEXT("PRINT"),
TEXT("PRELOAD"),
TEXT("LISTPAD"),
TEXT("EXPANDSYNC")
};
#endif
STDMETHODIMP
CComponent::Notify(
LPDATAOBJECT lpDataObject,
MMC_NOTIFY_TYPE event,
LPARAM arg,
LPARAM param
)
{
HRESULT hr;
INTERNAL_DATA tID;
#if DBG
UINT i = event - MMCN_ACTIVATE + 1;
if (event > MMCN_EXPANDSYNC || event < MMCN_ACTIVATE)
{
i = 0;
}
//TRACE2(TEXT("Componet:Notify, event = %lx %s\n"), event, mmcNotifyStr[i]);
#endif
try
{
if (DOBJ_CUSTOMOCX == lpDataObject)
{
return OnOcxNotify(event, arg, param);
}
hr = ExtractData(lpDataObject, CDataObject::m_cfSnapinInternal,
(PBYTE)&tID, sizeof(tID));
if (SUCCEEDED(hr))
{
switch(event)
{
case MMCN_ACTIVATE:
hr = OnActivate(tID.cookie, arg, param);
break;
case MMCN_VIEW_CHANGE:
hr = OnViewChange(tID.cookie, arg, param);
break;
case MMCN_SHOW:
hr = OnShow(tID.cookie, arg, param);
break;
case MMCN_CLICK:
hr = OnResultItemClick(tID.cookie, arg, param);
break;
case MMCN_DBLCLICK:
hr = OnResultItemDblClick(tID.cookie, arg, param);
break;
case MMCN_MINIMIZED:
hr = OnMinimize(tID.cookie, arg, param);
break;
case MMCN_BTN_CLICK:
hr = OnBtnClick(tID.cookie, arg, param);
break;
case MMCN_SELECT:
hr = OnSelect(tID.cookie, arg, param);
break;
case MMCN_ADD_IMAGES:
hr = OnAddImages(tID.cookie, (IImageList*)arg, param);
break;
case MMCN_RESTORE_VIEW:
hr = OnRestoreView(tID.cookie, arg, param);
break;
case MMCN_CONTEXTHELP:
hr = OnContextHelp(tID.cookie, arg, param);
break;
default:
hr = S_OK;
break;
}
}
else
{
if (MMCN_ADD_IMAGES == event)
{
OnAddImages(0, (IImageList*)arg, (HSCOPEITEM)param);
}
}
}
catch (CMemoryException* e)
{
e->Delete();
MsgBoxParam(m_pComponentData->m_hwndMain, 0, 0, 0);
hr = E_OUTOFMEMORY;
}
return hr;
}
STDMETHODIMP
CComponent::Destroy(
MMC_COOKIE cookie
)
{
// cookie must point to the static node
ASSERT(0 == cookie);
try
{
DetachAllFoldersFromMachine();
DestroyFolderList(cookie);
if (m_pToolbar)
{
m_pToolbar->Release();
}
if (m_pControlbar)
{
m_pControlbar->Release();
}
// Release the interfaces that we QI'ed
if (m_pConsole != NULL)
{
// Tell the console to release the header control interface
m_pConsole->SetHeader(NULL);
m_pHeader->Release();
m_pResult->Release();
m_pConsoleVerb->Release();
m_pDisplayHelp->Release();
// Release the IFrame interface last
m_pConsole->Release();
}
if (m_pPropSheetProvider)
m_pPropSheetProvider->Release();
}
catch (CMemoryException* e)
{
e->Delete();
MsgBoxParam(m_pComponentData->m_hwndMain, 0, 0, 0);
}
return S_OK;
}
STDMETHODIMP
CComponent::QueryDataObject(
MMC_COOKIE cookie,
DATA_OBJECT_TYPES type,
LPDATAOBJECT* ppDataObject
)
{
try
{
ASSERT(m_pComponentData);
// delegate to IComponentData
return m_pComponentData->QueryDataObject(cookie, type, ppDataObject);
}
catch (CMemoryException* e)
{
e->Delete();
MsgBoxParam(m_pComponentData->m_hwndMain, 0, 0, 0);
return E_OUTOFMEMORY;
}
}
STDMETHODIMP
CComponent::GetDisplayInfo(
LPRESULTDATAITEM pResultDataItem
)
{
try
{
CFolder* pFolder = FindFolder(pResultDataItem->lParam);
if (pFolder)
return pFolder->GetDisplayInfo(pResultDataItem);
else
return S_OK;
}
catch (CMemoryException* e)
{
e->Delete();
MsgBoxParam(m_pComponentData->m_hwndMain, 0, 0, 0);
return E_OUTOFMEMORY;
}
}
STDMETHODIMP
CComponent::CompareObjects(
LPDATAOBJECT lpDataObjectA,
LPDATAOBJECT lpDataObjectB
)
{
try
{
ASSERT(m_pComponentData);
//delegate to ComponentData
return m_pComponentData->CompareObjects(lpDataObjectA, lpDataObjectB);
}
catch (CMemoryException* e)
{
e->Delete();
MsgBoxParam(m_pComponentData->m_hwndMain, 0, 0, 0);
return E_OUTOFMEMORY;
}
}
///////////////////////////////////////////////////////////////////////////
/// IResultDataCompare implementation
///
// This compare is used to sort the item's in the listview.
// lUserParam - user param passed in when IResultData::Sort() was called.
// cookieA -- first item
// cookieB -- second item
// pnResult contains the column on entry. This function has the compared
// result in the location pointed by this parameter.
// the valid compare results are:
// -1 if cookieA "<" cookieB
// 0 if cookieA "==" cookieB
// 1 if cookieA ">" cookieB
//
//
STDMETHODIMP
CComponent::Compare(
LPARAM lUserParam,
MMC_COOKIE cookieA,
MMC_COOKIE cookieB,
int* pnResult
)
{
if (!pnResult)
return E_INVALIDARG;
HRESULT hr;
try
{
int nCol = *pnResult;
CFolder* pFolder = (CFolder*)lUserParam;
if (pFolder)
hr = pFolder->Compare(cookieA, cookieB, nCol, pnResult);
else
hr = m_pCurFolder->Compare(cookieA, cookieB, nCol, pnResult);
}
catch (CMemoryException* e)
{
e->Delete();
MsgBoxParam(m_pComponentData->m_hwndMain, 0, 0, 0);
hr = E_OUTOFMEMORY;
}
return hr;
}
////////////////////////////////////////////////////////////////////////////
/// Snapin's IExtendContextMenu implementation -- delegate to IComponentData
////
// Note that IComponentData also has its own IExtendContextMenu
// interface implementation. The difference is that
// IComponentData only deals with scope items while we only
// deal with result item except for cutomer view menu.
//
//
STDMETHODIMP
CComponent::AddMenuItems(
LPDATAOBJECT lpDataObject,
LPCONTEXTMENUCALLBACK pCallback,
long* pInsertionAllowed
)
{
HRESULT hr;
INTERNAL_DATA tID;
try
{
//
// If lpDataObject is DOBJ_CUSTOMOCX then the user is viewing
// the Action menu.
//
if (DOBJ_CUSTOMOCX == lpDataObject)
{
ASSERT(m_pCurFolder);
hr = m_pCurFolder->m_pScopeItem->AddMenuItems(pCallback, pInsertionAllowed);
}
//
// If we have a valid cookie then the user is using the context menu
// or the View menu
//
else
{
hr = ExtractData(lpDataObject, CDataObject::m_cfSnapinInternal,
reinterpret_cast<BYTE*>(&tID), sizeof(tID)
);
if (SUCCEEDED(hr))
{
ASSERT(m_pCurFolder);
hr = m_pCurFolder->AddMenuItems(GetActiveCookie(tID.cookie),
pCallback, pInsertionAllowed
);
}
}
}
catch (CMemoryException* e)
{
e->Delete();
MsgBoxParam(m_pComponentData->m_hwndMain, 0, 0, 0);
hr = E_OUTOFMEMORY;
}
return hr;
}
STDMETHODIMP
CComponent::Command(
long nCommandID,
LPDATAOBJECT lpDataObject
)
{
INTERNAL_DATA tID;
HRESULT hr;
try
{
//
// Menu item from the Action menu
//
if (DOBJ_CUSTOMOCX == lpDataObject)
{
ASSERT(m_pCurFolder);
hr = m_pCurFolder->m_pScopeItem->MenuCommand(nCommandID);
}
//
// Context menu item or View menu item
//
else
{
hr = ExtractData(lpDataObject, CDataObject::m_cfSnapinInternal,
(PBYTE)&tID, sizeof(tID));
if (SUCCEEDED(hr))
{
ASSERT(m_pCurFolder);
hr = m_pCurFolder->MenuCommand(GetActiveCookie(tID.cookie), nCommandID);
}
}
}
catch (CMemoryException* e)
{
e->Delete();
MsgBoxParam(m_pComponentData->m_hwndMain, 0, 0, 0);
hr = E_OUTOFMEMORY;
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
// IExtendControlbar implementation
//
MMCBUTTON g_SnapinButtons[] =
{
{ 0, IDM_REFRESH, TBSTATE_ENABLED, TBSTYLE_BUTTON, (BSTR)IDS_BUTTON_REFRESH, (BSTR)IDS_TOOLTIP_REFRESH },
{ 0, 0, TBSTATE_ENABLED, TBSTYLE_SEP, NULL, NULL },
{ 1, IDM_ENABLE, TBSTATE_ENABLED, TBSTYLE_BUTTON, (BSTR)IDS_BUTTON_ENABLE, (BSTR)IDS_TOOLTIP_ENABLE },
{ 2, IDM_REMOVE, TBSTATE_ENABLED, TBSTYLE_BUTTON, (BSTR)IDS_BUTTON_REMOVE, (BSTR)IDS_TOOLTIP_REMOVE },
{ 3, IDM_DISABLE, TBSTATE_ENABLED, TBSTYLE_BUTTON, (BSTR)IDS_BUTTON_DISABLE, (BSTR)IDS_TOOLTIP_DISABLE },
};
// The Enable and Disable buttons are interchanged dependent on the state of
// the device. The button array is used to initialize the buttons. Then
// either the enable or disable button is inserted at the ENABLE_INDEX location.
#define SEPARATOR_INDEX 1
#define ENABLE_INDEX 2
#define DISABLE_INDEX 4
#define CBUTTONS_ARRAY ARRAYLEN(g_SnapinButtons)
#define CBUTTONS_VISIBLE CBUTTONS_ARRAY-1
String* g_astrButtonStrings = NULL; // dynamic array of Strings
BOOL g_bLoadedStrings = FALSE;
STDMETHODIMP
CComponent::SetControlbar(
LPCONTROLBAR pControlbar
)
{
if (pControlbar != NULL)
{
// Hold on to the controlbar interface.
if (m_pControlbar)
{
m_pControlbar->Release();
}
m_pControlbar = pControlbar;
m_pControlbar->AddRef();
HRESULT hr = S_FALSE;
if (!m_pToolbar)
{
// Create the Toolbar
hr = m_pControlbar->Create(TOOLBAR, this,
reinterpret_cast<LPUNKNOWN*>(&m_pToolbar));
ASSERT(SUCCEEDED(hr));
// Add the bitmap
HBITMAP hBitmap = ::LoadBitmap(g_hInstance, MAKEINTRESOURCE(IDB_TOOLBAR));
hr = m_pToolbar->AddBitmap(4, hBitmap, 16, 16, RGB(255, 0, 255));
ASSERT(SUCCEEDED(hr));
if (!g_bLoadedStrings)
{
// load strings
g_astrButtonStrings = new String[2*CBUTTONS_ARRAY];
for (UINT i = 0; i < CBUTTONS_ARRAY; i++)
{
if (NULL != g_SnapinButtons[i].lpButtonText &&
g_astrButtonStrings[i*2].LoadString(g_hInstance,
(UINT)((ULONG_PTR)g_SnapinButtons[i].lpButtonText)))
{
g_SnapinButtons[i].lpButtonText =
const_cast<BSTR>((LPCTSTR)(g_astrButtonStrings[i*2]));
}
else
{
g_SnapinButtons[i].lpButtonText = NULL;
}
if (NULL != g_SnapinButtons[i].lpTooltipText &&
g_astrButtonStrings[(i*2)+1].LoadString(g_hInstance,
(UINT)((ULONG_PTR)g_SnapinButtons[i].lpTooltipText)))
{
g_SnapinButtons[i].lpTooltipText =
const_cast<BSTR>((LPCTSTR)(g_astrButtonStrings[(i*2)+1]));
}
else
{
g_SnapinButtons[i].lpTooltipText = NULL;
}
}
g_bLoadedStrings = TRUE;
}
// Add the buttons to the toolbar
hr = m_pToolbar->AddButtons(CBUTTONS_VISIBLE, g_SnapinButtons);
ASSERT(SUCCEEDED(hr));
}
}
return S_OK;
}
STDMETHODIMP
CComponent::ControlbarNotify(
MMC_NOTIFY_TYPE event,
LPARAM arg,
LPARAM param
)
{
switch (event)
{
case MMCN_BTN_CLICK:
// arg - Data object of the currently selected scope or result pane item.
// param - CmdID of the button.
switch (param)
{
case IDM_REFRESH:
case IDM_ENABLE:
case IDM_REMOVE:
case IDM_DISABLE:
// The arg parameter is supposed to be the data object of the
// currently selected scope or result pane item, but it seems
// to always passes 0xFFFFFFFF. So the ScopeItem MenuCommand is
// used because it uses the selected cookie instead.
// Handle toolbar button requests.
return m_pCurFolder->m_pScopeItem->MenuCommand((LONG)param);
default:
break;
}
break;
case MMCN_SELECT:
// param - Data object of the item being selected.
// For select, if the cookie has toolbar items attach the toolbar.
// Otherwise detach the toolbar.
HRESULT hr;
if (LOWORD(arg))
{
// LOWORD(arg) being set indicated this is for the scope pane item.
if (HIWORD(arg))
{
// Detach the Controlbar.
hr = m_pControlbar->Detach(reinterpret_cast<LPUNKNOWN>(m_pToolbar));
ASSERT(SUCCEEDED(hr));
}
else
{
// Attach the Controlbar.
hr = m_pControlbar->Attach(TOOLBAR,
reinterpret_cast<LPUNKNOWN>(m_pToolbar));
ASSERT(SUCCEEDED(hr));
}
}
break;
default:
break;
}
return S_OK;
}
//
// This function updates the toolbar buttons based on the selected cookie type.
//
HRESULT
CComponent::UpdateToolbar(
CCookie* pCookie
)
{
if (!m_pToolbar)
{
return S_OK;
}
BOOL fRemoveHidden = TRUE;
BOOL fRefreshHidden = TRUE;
switch (pCookie->GetType())
{
case COOKIE_TYPE_RESULTITEM_DEVICE:
if(m_pComponentData->m_pMachine->IsLocal() && g_HasLoadDriverNamePrivilege)
{
CDevice* pDevice;
UINT index;
pDevice = (CDevice*)pCookie->GetResultItem();
//
// Device can be disabled
//
if (pDevice->IsDisableable()) {
index = pDevice->IsStateDisabled() ? ENABLE_INDEX : DISABLE_INDEX;
// Delete the current button.
m_pToolbar->DeleteButton(ENABLE_INDEX);
// Insert the enable/disable button based on the device's state.
m_pToolbar->InsertButton(ENABLE_INDEX, &g_SnapinButtons[index]);
}
//
// Device cannot be disabled
//
else
{
// Hide both the enable and disable buttons in case the
// previously selected node was a device.
m_pToolbar->SetButtonState(IDM_ENABLE, HIDDEN, TRUE);
m_pToolbar->SetButtonState(IDM_DISABLE, HIDDEN, TRUE);
}
//
// Only show the uninstall button if the device can be uninstalled.
//
if (pDevice->IsUninstallable()) {
fRemoveHidden = FALSE;
}
// Display refresh (Scan...) button.
fRefreshHidden = FALSE;
break;
}
else
{
// Must be an admin and on the local machine to remove or
// enable/disable a device.
// Fall through to hide the remove and enable/disable buttons.
}
case COOKIE_TYPE_RESULTITEM_RESOURCE_IRQ:
case COOKIE_TYPE_RESULTITEM_RESOURCE_DMA:
case COOKIE_TYPE_RESULTITEM_RESOURCE_IO:
case COOKIE_TYPE_RESULTITEM_RESOURCE_MEMORY:
case COOKIE_TYPE_RESULTITEM_COMPUTER:
case COOKIE_TYPE_RESULTITEM_CLASS:
case COOKIE_TYPE_RESULTITEM_RESTYPE:
// Hide both the enable and disable buttons in case the
// previously selected node was a device.
m_pToolbar->SetButtonState(IDM_ENABLE, HIDDEN, TRUE);
m_pToolbar->SetButtonState(IDM_DISABLE, HIDDEN, TRUE);
// Display refresh (enumerate) button.
fRefreshHidden = FALSE;
break;
default:
break;
}
m_pToolbar->SetButtonState(IDM_REMOVE, HIDDEN, fRemoveHidden);
m_pToolbar->SetButtonState(IDM_REFRESH, HIDDEN, fRefreshHidden);
if (!fRemoveHidden)
{
// The separator appears to be automatically hidden if there are no
// buttons following it. It must be unhidden when additional buttons
// are shown.
m_pToolbar->SetButtonState(0, HIDDEN, FALSE);
}
return S_OK;
}
////////////////////////////////////////////////////////////////////////////
//// Snapin's IExtendPropertySheet implementation
////
STDMETHODIMP
CComponent::QueryPagesFor(
LPDATAOBJECT lpDataObject
)
{
HRESULT hr;
if (!lpDataObject)
return E_INVALIDARG;
INTERNAL_DATA tID;
try
{
hr = ExtractData(lpDataObject, CDataObject::m_cfSnapinInternal,
reinterpret_cast<BYTE*>(&tID), sizeof(tID)
);
if (SUCCEEDED(hr))
{
ASSERT(m_pCurFolder);
hr = m_pCurFolder->QueryPagesFor(GetActiveCookie(tID.cookie));
}
}
catch (CMemoryException* e)
{
e->Delete();
MsgBoxParam(m_pComponentData->m_hwndMain, 0, 0, 0);
hr = S_FALSE;
}
return hr;
}
STDMETHODIMP
CComponent::CreatePropertyPages(
LPPROPERTYSHEETCALLBACK lpProvider,
LONG_PTR handle,
LPDATAOBJECT lpDataObject
)
{
HRESULT hr;
if (!lpProvider || !lpDataObject)
return E_INVALIDARG;
INTERNAL_DATA tID;
try
{
hr = ExtractData(lpDataObject, CDataObject::m_cfSnapinInternal,
reinterpret_cast<BYTE*>(&tID), sizeof(tID)
);
if (SUCCEEDED(hr))
{
ASSERT(m_pCurFolder);
hr = m_pCurFolder->CreatePropertyPages(GetActiveCookie(tID.cookie),
lpProvider, handle
);
}
}
catch (CMemoryException* e)
{
e->Delete();
MsgBoxParam(m_pComponentData->m_hwndMain, 0, 0, 0);
hr = E_OUTOFMEMORY;
}
return hr;
}
#ifdef PERSIST_VIEW
/////////////////////////////////////////////////////////////////////////////
// Snapin's IPersistStream implementation
STDMETHODIMP
CComponent::GetClassID(
CLSID* pClassID
)
{
if(!pClassID)
return E_POINTER;
*pClassID = m_pComponentData->GetCoClassID();
return S_OK;
}
inline
STDMETHODIMP
CComponent::IsDirty()
{
return m_Dirty ? S_OK : S_FALSE;
}
STDMETHODIMP
CComponent::GetSizeMax(
ULARGE_INTEGER* pcbSize
)
{
if (!pcbSize)
return E_INVALIDARG;
// total folders folder signature
int Size = sizeof(int) + m_listFolder.GetCount() * sizeof(FOLDER_SIGNATURE)
+ sizeof(CLSID);
CFolder* pFolder;
POSITION pos = m_listFolder.GetHeadPosition();
while (NULL != pos)
{
pFolder = m_listFolder.GetNext(pos);
ASSERT(pFolder);
Size += pFolder->GetPersistDataSize();
}
ULISet32(*pcbSize, Size);
return S_OK;
}
// save data format
STDMETHODIMP
CComponent::Save(
IStream* pStm,
BOOL fClearDirty
)
{
HRESULT hr = S_OK;
SafeInterfacePtr<IStream> StmPtr(pStm);
int Count, Index;
POSITION pos;
CLSID clsid;
try
{
// write out CLSID
hr = pStm->Write(&CLSID_DEVMGR, sizeof(CLSID), NULL);
if (SUCCEEDED(hr))
{
Count = m_listFolder.GetCount();
CFolder* pFolder;
// write out folder count
hr = pStm->Write(&Count, sizeof(Count), NULL);
if (SUCCEEDED(hr) && Count)
{
pos = m_listFolder.GetHeadPosition();
while (NULL != pos)
{
pFolder = m_listFolder.GetNext(pos);
// write folder signature
FOLDER_SIGNATURE Signature = pFolder->GetSignature();
hr = pStm->Write(&Signature, sizeof(Signature), NULL);
if (SUCCEEDED(hr))
hr = SaveFolderPersistData(pFolder, pStm, fClearDirty);
if (FAILED(hr))
break;
}
}
}
}
catch (CMemoryException* e)
{
e->Delete();
MsgBoxParam(m_pComponentData->m_hwndMain, 0, 0, 0);
hr = E_OUTOFMEMORY;
}
if (fClearDirty)
m_Dirty = FALSE;
return hr;
}
STDMETHODIMP
CComponent::Load(
IStream* pStm
)
{
HRESULT hr = S_OK;
CLSID clsid;
SafeInterfacePtr<IStream> StmPtr(pStm);
ASSERT(pStm);
// read the clsid
try
{
hr = pStm->Read(&clsid, sizeof(clsid), NULL);
if (SUCCEEDED(hr) && clsid == CLSID_DEVMGR)
{
CFolder* pFolder;
int FolderCount;
// folder list must be create before Load.
// DO NOT rely on that IComponent::Initialize comes before IStream::Load
//
ASSERT(m_listFolder.GetCount());
// load folder count
hr = pStm->Read(&FolderCount, sizeof(FolderCount), NULL);
if (SUCCEEDED(hr))
{
ASSERT(m_listFolder.GetCount() == FolderCount);
// get folder signature
// go through every folder
for (int i = 0; i < FolderCount; i++)
{
FOLDER_SIGNATURE Signature;
hr = pStm->Read(&Signature, sizeof(Signature), NULL);
if (SUCCEEDED(hr))
{
POSITION pos;
pos = m_listFolder.GetHeadPosition();
while (NULL != pos)
{
pFolder = m_listFolder.GetNext(pos);
if (pFolder->GetSignature() == Signature)
{
hr = LoadFolderPersistData(pFolder, pStm);
break;
}
}
}
}
}
}
}
catch (CMemoryException* e)
{
e->Delete();
MsgBoxParam(m_pComponentData->m_hwndMain, 0, 0, 0);
hr = E_OUTOFMEMORY;
}
m_Dirty = FALSE;
return hr;
}
HRESULT
CComponent::SaveFolderPersistData(
CFolder* pFolder,
IStream* pStm,
BOOL fClearDirty
)
{
HRESULT hr = S_OK;
PBYTE Buffer;
int Size;
SafeInterfacePtr<IStream> StmPtr(pStm);
try
{
Size = pFolder->GetPersistDataSize();
// always write the length even though it can be 0.
hr = pStm->Write(&Size, sizeof(Size), NULL);
if (SUCCEEDED(hr) && Size)
{
BufferPtr<BYTE> Buffer(Size);
pFolder->GetPersistData(Buffer, Size);
hr = pStm->Write(Buffer, Size, NULL);
}
}
catch (CMemoryException* e)
{
e->Delete();
MsgBoxParam(m_pComponentData->m_hwndMain, 0, 0, 0);
hr = E_OUTOFMEMORY;
}
return hr;
}
HRESULT
CComponent::LoadFolderPersistData(
CFolder* pFolder,
IStream* pStm
)
{
HRESULT hr = S_OK;
PBYTE Buffer;
SafeInterfacePtr<IStream> StmPtr(pStm);
int Size = 0;
hr = pStm->Read(&Size, sizeof(Size), NULL);
if (SUCCEEDED(hr) && Size)
{
BufferPtr<BYTE> Buffer(Size);
hr = pStm->Read(Buffer, Size, NULL);
if (SUCCEEDED(hr))
{
hr = pFolder->SetPersistData(Buffer, Size);
}
}
return hr;
}
#endif // ifdef PERSIST_VIEW
//
// This function attaches the given folder the the machine created
// by the component data. The machine notifies every attached folder
// when there are state changes in the machine.
//
// INPUT:
// pFolder -- the folder to be attached
// ppMachind -- to receive a pointer to the machine
// OUTPUT:
// TRUE if the folder is attached successfully.
// FALSE if the attachment failed.
//
//
BOOL
CComponent::AttachFolderToMachine(
CFolder* pFolder,
CMachine** ppMachine
)
{
if (!pFolder)
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
// Initialize the machine.
if (m_pComponentData->InitializeMachine())
{
*ppMachine = m_pComponentData->m_pMachine;
(*ppMachine)->AttachFolder(pFolder);
return TRUE;
}
return FALSE;
}
//
// This function detaches all the component's folders from the machine
//
void
CComponent::DetachAllFoldersFromMachine()
{
if (m_pComponentData->m_pMachine)
{
CMachine* pMachine = m_pComponentData->m_pMachine;
CFolder* pFolder;
POSITION pos = m_listFolder.GetHeadPosition();
while (NULL != pos)
{
pFolder = m_listFolder.GetNext(pos);
pMachine->DetachFolder(pFolder);
}
}
}
HRESULT
CComponent::CreateFolderList(
CCookie* pCookie
)
{
CCookie* pCookieChild;
CScopeItem* pScopeItem;
CFolder* pFolder;
ASSERT(pCookie);
HRESULT hr = S_OK;
do
{
pScopeItem = pCookie->GetScopeItem();
ASSERT(pScopeItem);
pFolder = pScopeItem->CreateFolder(this);
if (pFolder)
{
m_listFolder.AddTail(pFolder);
pFolder->AddRef();
pCookieChild = pCookie->GetChild();
if (pCookieChild)
hr = CreateFolderList(pCookieChild);
pCookie = pCookie->GetSibling();
}
else
{
hr = E_OUTOFMEMORY;
}
} while (SUCCEEDED(hr) && pCookie);
return hr;
}
BOOL
CComponent::DestroyFolderList(
MMC_COOKIE cookie
)
{
if (!m_listFolder.IsEmpty())
{
POSITION pos = m_listFolder.GetHeadPosition();
while (NULL != pos)
{
CFolder* pFolder = m_listFolder.GetNext(pos);
//
// DONOT delete it!!!!!!!
//
pFolder->Release();
}
m_listFolder.RemoveAll();
}
return TRUE;
}
CFolder*
CComponent::FindFolder(
MMC_COOKIE cookie
)
{
CCookie* pCookie = GetActiveCookie(cookie);
CFolder* pFolder;
POSITION pos = m_listFolder.GetHeadPosition();
while (NULL != pos)
{
pFolder = m_listFolder.GetNext(pos);
if (pCookie->GetScopeItem() == pFolder->m_pScopeItem)
return pFolder;
}
return NULL;
}
int
CComponent::MessageBox(
LPCTSTR Msg,
LPCTSTR Caption,
DWORD Flags
)
{
int Result;
ASSERT(m_pConsole);
if (SUCCEEDED(m_pConsole->MessageBox(Msg, Caption, Flags, &Result)))
return Result;
else
return IDCANCEL;
}
| [
"mehmetyilmaz3371@gmail.com"
] | mehmetyilmaz3371@gmail.com |
31374950ae9f52abe545d678ee47189a96af35f9 | 6d1cd436e2dda96e4f2a91717ac52eaea279a662 | /google/cloud/bigtable/tests/admin_backup_async_future_integration_test.cc | 27c8b1ccbc8eb32730a484405ca2796e32ff9a00 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | renovate-bot/google-cloud-cpp | bd019b886fb23a9c5c36ebc6a336402d9e9d4b86 | fe093fc340988fb354f38f91f497c886b9438272 | refs/heads/master | 2023-08-31T20:37:29.348573 | 2021-05-10T18:38:18 | 2021-05-10T18:38:18 | 198,908,134 | 1 | 0 | Apache-2.0 | 2021-04-23T19:52:31 | 2019-07-25T22:19:53 | C++ | UTF-8 | C++ | false | false | 7,941 | cc | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/bigtable/instance_admin.h"
#include "google/cloud/bigtable/testing/table_integration_test.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/internal/time_utils.h"
#include "google/cloud/testing_util/chrono_literals.h"
#include "google/cloud/testing_util/contains_once.h"
#include "google/cloud/testing_util/status_matchers.h"
#include <google/protobuf/util/time_util.h>
#include <gmock/gmock.h>
// TODO(#5923) - remove after deprecation is completed
#include "google/cloud/internal/disable_deprecation_warnings.inc"
namespace google {
namespace cloud {
namespace bigtable {
inline namespace BIGTABLE_CLIENT_NS {
namespace {
using ::google::cloud::testing_util::ContainsOnce;
using ::testing::Contains;
using ::testing::Not;
namespace btadmin = google::bigtable::admin::v2;
namespace bigtable = google::cloud::bigtable;
class AdminBackupAsyncFutureIntegrationTest
: public bigtable::testing::TableIntegrationTest {
protected:
std::shared_ptr<AdminClient> admin_client_;
std::unique_ptr<TableAdmin> table_admin_;
std::unique_ptr<bigtable::InstanceAdmin> instance_admin_;
void SetUp() override {
if (google::cloud::internal::GetEnv(
"ENABLE_BIGTABLE_ADMIN_INTEGRATION_TESTS")
.value_or("") != "yes") {
GTEST_SKIP();
}
TableIntegrationTest::SetUp();
admin_client_ = CreateDefaultAdminClient(
testing::TableTestEnvironment::project_id(), ClientOptions());
table_admin_ = absl::make_unique<TableAdmin>(
admin_client_, bigtable::testing::TableTestEnvironment::instance_id());
auto instance_admin_client = bigtable::CreateDefaultInstanceAdminClient(
bigtable::testing::TableTestEnvironment::project_id(),
bigtable::ClientOptions());
instance_admin_ =
absl::make_unique<bigtable::InstanceAdmin>(instance_admin_client);
}
};
/// @test Verify that `bigtable::TableAdmin` Backup Async CRUD operations work
/// as expected.
TEST_F(AdminBackupAsyncFutureIntegrationTest,
CreateListGetUpdateRestoreDeleteBackup) {
std::string const table_id = RandomTableId();
CompletionQueue cq;
std::thread pool([&cq] { cq.Run(); });
// verify new table id in current table list
auto previous_table_list =
table_admin_->ListTables(btadmin::Table::NAME_ONLY);
ASSERT_STATUS_OK(previous_table_list);
ASSERT_THAT(
TableNames(*previous_table_list),
Not(Contains(table_admin_->instance_name() + "/tables/" + table_id)))
<< "Table (" << table_id << ") already exists."
<< " This is unexpected, as the table ids are"
<< " generated at random.";
TableConfig table_config({{"fam", GcRule::MaxNumVersions(5)},
{"foo", GcRule::MaxAge(std::chrono::hours(24))}},
{"a1000", "a2000", "b3000", "m5000"});
// create table
ASSERT_STATUS_OK(table_admin_->CreateTable(table_id, table_config));
auto clusters_list =
instance_admin_->ListClusters(table_admin_->instance_id());
ASSERT_STATUS_OK(clusters_list);
std::string const backup_cluster_full_name =
clusters_list->clusters.begin()->name();
std::string const backup_cluster_id = backup_cluster_full_name.substr(
backup_cluster_full_name.rfind('/') + 1,
backup_cluster_full_name.size() - backup_cluster_full_name.rfind('/'));
std::string const backup_id = RandomBackupId();
std::string const backup_full_name =
backup_cluster_full_name + "/backups/" + backup_id;
google::protobuf::Timestamp const expire_time =
google::protobuf::util::TimeUtil::GetCurrentTime() +
google::protobuf::util::TimeUtil::HoursToDuration(12);
google::protobuf::Timestamp const updated_expire_time =
expire_time + google::protobuf::util::TimeUtil::HoursToDuration(12);
future<void> chain =
table_admin_->AsyncListBackups(cq, {})
.then([&](future<StatusOr<std::vector<btadmin::Backup>>> fut) {
StatusOr<std::vector<btadmin::Backup>> result = fut.get();
EXPECT_STATUS_OK(result);
EXPECT_THAT(BackupNames(*result),
Not(Contains(table_admin_->instance_name() +
"/backups/" + backup_id)))
<< "Backup (" << backup_id << ") already exists."
<< " This is unexpected, as the backup ids are"
<< " generated at random.";
return table_admin_->AsyncCreateBackup(
cq, {backup_cluster_id, backup_id, table_id,
google::cloud::internal::ToChronoTimePoint(expire_time)});
})
.then([&](future<StatusOr<btadmin::Backup>> fut) {
StatusOr<btadmin::Backup> result = fut.get();
EXPECT_STATUS_OK(result);
EXPECT_THAT(result->name(), ::testing::HasSubstr(backup_id));
return table_admin_->AsyncGetBackup(cq, backup_cluster_id,
backup_id);
})
.then([&](future<StatusOr<btadmin::Backup>> fut) {
StatusOr<btadmin::Backup> get_result = fut.get();
EXPECT_STATUS_OK(get_result);
EXPECT_EQ(get_result->name(), backup_full_name);
return table_admin_->AsyncUpdateBackup(
cq, {backup_cluster_id, backup_id,
google::cloud::internal::ToChronoTimePoint(
updated_expire_time)});
})
.then([&](future<StatusOr<btadmin::Backup>> fut) {
StatusOr<btadmin::Backup> update_result = fut.get();
EXPECT_STATUS_OK(update_result);
EXPECT_EQ(update_result->name(), backup_full_name);
EXPECT_EQ(update_result->expire_time(), updated_expire_time);
return table_admin_->AsyncDeleteTable(cq, table_id);
})
.then([&](future<Status> fut) {
Status delete_table_result = fut.get();
EXPECT_STATUS_OK(delete_table_result);
return table_admin_->AsyncRestoreTable(
cq, {table_id, backup_cluster_id, backup_id});
})
.then([&](future<StatusOr<btadmin::Table>> fut) {
auto restore_result = fut.get();
EXPECT_STATUS_OK(restore_result);
return table_admin_->AsyncDeleteBackup(cq, backup_cluster_id,
backup_id);
})
.then([&](future<Status> fut) {
Status delete_result = fut.get();
EXPECT_STATUS_OK(delete_result);
});
chain.get();
// verify table was restored
auto current_table_list = table_admin_->ListTables(btadmin::Table::NAME_ONLY);
ASSERT_STATUS_OK(current_table_list);
EXPECT_THAT(
TableNames(*current_table_list),
ContainsOnce(table_admin_->instance_name() + "/tables/" + table_id));
// delete table
EXPECT_STATUS_OK(table_admin_->DeleteTable(table_id));
SUCCEED(); // we expect that previous operations do not fail.
cq.Shutdown();
pool.join();
}
} // namespace
} // namespace BIGTABLE_CLIENT_NS
} // namespace bigtable
} // namespace cloud
} // namespace google
int main(int argc, char* argv[]) {
::testing::InitGoogleMock(&argc, argv);
(void)::testing::AddGlobalTestEnvironment(
new google::cloud::bigtable::testing::TableTestEnvironment);
return RUN_ALL_TESTS();
}
| [
"noreply@github.com"
] | renovate-bot.noreply@github.com |
57d5b12d9ac97103cbc8f4fd92cb35225319a73a | 10a66c8f586bbc7c5e0a07bb3cb8e48f1b7f49bf | /nuno_handson.ino | c3f2322f6768f4841bc9d61848f2276a573f0672 | [
"Apache-2.0"
] | permissive | kitazaki/nuno_handson | 4a8898e7c2b47b986af72fa57c13506d023d7833 | 5793c27cb0c61dab18eda71161f29d7db27f49a4 | refs/heads/master | 2020-12-01T19:58:35.361404 | 2019-12-29T12:55:15 | 2019-12-29T12:55:15 | 230,750,056 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,553 | ino | #include <M5StickC.h>
#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include "MTCH6102.h"
#define ADDR 0x25
MTCH6102 mtch = MTCH6102();
int len = 8;
char *ssid = ""; // HERE //
char *password = ""; // HERE //
const char *endpoint = "broker.shiftr.io";
const int port = 1883;
const char *mqttid = ""; // HERE //
const char *mqttpassword = ""; // HERE //
String modelNum = "M5StickC-";
String rndNum = String(random(0xffff), HEX);
String clientId = String(modelNum + rndNum);
const char *deviceID = clientId.c_str();
char *subTopic = "nuno/midi/out/+/+/+";
char *pubTopic[] = {
"nuno/midi/out/1/noteon/60", // C
"nuno/midi/out/1/noteon/59", // B
"nuno/midi/out/1/noteon/57", // A
"nuno/midi/out/1/noteon/55", // G
"nuno/midi/out/1/noteon/53", // F
"nuno/midi/out/1/noteon/52", // E
"nuno/midi/out/1/noteon/50", // D
"nuno/midi/out/1/noteon/48" // C
};
WiFiClient httpsClient;
PubSubClient mqttClient(httpsClient);
void setup() {
byte data;
Serial.begin(115200);
// Initialize the M5Stack object
M5.begin();
M5.Lcd.setRotation(3); // display size = 80x160, setRotation = 0:M5, 1:Power Btn, 2:up side down, 3:Btn
M5.Lcd.fillScreen(TFT_BLACK);
// WiFi Start
Serial.println("Connecting to ");
Serial.print(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi Connected.");
// MQTT Start
mqttClient.setServer(endpoint, port);
connectMQTT();
//Wire.begin();
mtch.begin();
mtch.writeRegister(MTCH6102_MODE, MTCH6102_MODE_STANDBY);
mtch.writeRegister(MTCH6102_NUMBEROFXCHANNELS, 10 );
mtch.writeRegister(MTCH6102_NUMBEROFYCHANNELS, 3);
mtch.writeRegister(MTCH6102_MODE, MTCH6102_MODE_FULL);
mtch.writeRegister(MTCH6102_CMD, 0x20);
delay(500);
// the operating mode (MODE)
data = mtch.readRegister(MTCH6102_MODE);
Serial.print("MODE: ");
Serial.println(data,BIN);
data = mtch.readRegister(MTCH6102_NUMBEROFXCHANNELS);
Serial.print("NUMBER_OF_X_CHANNELS: ");
Serial.println(data);
data = mtch.readRegister(MTCH6102_NUMBEROFYCHANNELS);
Serial.print("NUMBER_OF_Y_CHANNELS: ");
Serial.println(data);
}
void connectMQTT() {
while (!mqttClient.connected()) {
// if (mqttClient.connect(deviceID)) {
if (mqttClient.connect(deviceID, mqttid, mqttpassword)) {
Serial.println("MQTT Connected.");
int qos = 0;
mqttClient.subscribe(subTopic, qos);
} else {
Serial.print("Failed. Error state=");
Serial.println(mqttClient.state());
delay(1000);
}
}
}
void mqttLoop() {
if (!mqttClient.connected()) {
connectMQTT();
}
mqttClient.loop();
}
int sensStats[10] = {0,0,0,0,0,0,0,0,0};
float sensVals[10] = {0,0,0,0,0,0,0,0,0,0};
void loop() {
byte data;
mqttLoop();
// M5.lcd.clear();
M5.Lcd.setCursor(5, 5);
M5.Lcd.print(" ");
M5.Lcd.setCursor(5, 5);
M5.Lcd.print(clientId);
M5.Lcd.setCursor(5, 15);
M5.Lcd.print(" ");
M5.Lcd.setCursor(5, 15);
//Serial.print("SENSORVALUE_RX <i>: ");
//for (byte i = MTCH6102_SENSORVALUE_RX0; i < MTCH6102_SENSORVALUE_RX0+10; i++) {
for (int i = 0; i < len; i++) {
data = mtch.readRegister(MTCH6102_SENSORVALUE_RX0+i);
sensVals[i] = data;
// Serial.print(data);
// Serial.print(", ");
M5.Lcd.print(data);
M5.Lcd.print(",");
// Low Water Mark
if (sensVals[i] < 150) {
if (sensStats[i] > 0) {
mqttClient.publish(pubTopic[i], "0");
Serial.print(i);
Serial.println(": off Published.");
sensStats[i] = 0;
}
}
// High Water Mark
if (sensVals[i] > 200) {
if (sensStats[i] < 1) {
mqttClient.publish(pubTopic[i], "100");
Serial.print(i);
Serial.println("on Published.");
sensStats[i] = 1;
}
}
}
// Serial.println();
for (int i = 0; i<len; i++){
float prev;
if(i==0){
prev = 0;
}else{
prev=sensVals[i-1];
}
M5.Lcd.drawLine(i*20, 80-(prev/255)*80, (i+1)*20, 80-(sensVals[i]/255)*80, TFT_WHITE);
}
delay(50);
for (int i = 0; i<len; i++){
float prev;
if(i==0){
prev = 0;
}else{
prev=sensVals[i-1];
}
M5.Lcd.drawLine(i*20, 80-(prev/255)*80, (i+1)*20, 80-(sensVals[i]/255)*80, TFT_BLACK);
}
M5.Lcd.println();
//delay(100);
}
| [
"noreply@github.com"
] | kitazaki.noreply@github.com |
9f206382ef2beb239c270e82db6894e7ac72bd81 | 1ec44ab2cab1147a40dc29716e1dd4397b0b803e | /pruebas/Estado/Estado.cpp | 00f1c8f3135f5db3002b90d1d9c875bf946bb2e9 | [] | no_license | RodrigoDeRosa/MultiplayerSonic | aed74f3d8d597cab70f5dc99743b7d46b98388fa | efbab4fae0f1bb884ab0f673f04c3ea15f9f34ea | refs/heads/master | 2022-04-22T21:38:55.802001 | 2020-04-21T18:10:59 | 2020-04-21T18:10:59 | 84,893,169 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 795 | cpp | #include "Estado.hpp"
#include <pthread.h>
#include <unistd.h>
Estado::Estado(){
this->estado = NORMAL;
}
state_type Estado::get(){
return this->estado;
}
void Estado::set(state_type estado){
if(estado == INVENCIBLE) this->setInvencible();
else this->estado = estado;
}
void* state_change(void* arg){
Estado* estado = (Estado*)arg;
sleep(10);
if(estado->get() == INVENCIBLE) estado->set(NORMAL);
return NULL;
}
void Estado::setInvencible(){
this->estado = INVENCIBLE;
pthread_t timeThreadID;
void* timeThread_exit;
pthread_create(&timeThreadID, NULL, state_change, this);
//pthread_join(timeThreadID, &timeThread_exit);
}
void Estado::updateFrame(){
this->frame++;
if(this->frame == 9) this->frame = 0;
}
int Estado::getFrame(){
this->updateFrame();
return this->frame;
} | [
"gftrucco@gmail.com"
] | gftrucco@gmail.com |
b94665d7498b0c6388a560b8b0d9627a6fd6f5a2 | e5091c3a8477fa12e1adfdb1f3d826eb6e9bb2be | /Codeforces/arithmetic_array.cpp | 9f63d127163efce7cff3d3d4247b42c0c436ff67 | [] | no_license | leonardoAnjos16/Competitive-Programming | 1db3793bfaa7b16fc9a2854c502b788a47f1bbe1 | 4c9390da44b2fa3c9ec4298783bfb3258b34574d | refs/heads/master | 2023-08-14T02:25:31.178582 | 2023-08-06T06:54:52 | 2023-08-06T06:54:52 | 230,381,501 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 410 | cpp | #include <bits/stdc++.h>
using namespace std;
#define long long long int
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t; cin >> t;
while (t--) {
int n; cin >> n;
int sum = 0;
for (int i = 0; i < n; i++) {
int a; cin >> a;
sum += a;
}
int ans = sum < n ? 1 : sum - n;
cout << ans << "\n";
}
} | [
"las4@cin.ufpe.br"
] | las4@cin.ufpe.br |
a5ee4aaf8ddb9d0105e2f75a3207156909f56be4 | 82bbd465986abe69898b7d632d758db900656694 | /dedi-shooter-ue4-client/ShooterGame/Source/ShooterGame/Public/Bots/ShooterAIController.h | 18eab7342827e416f28e68c435c1961a78881d67 | [] | no_license | iFunFactory/engine-dedicated-server-example | 17d7016945506579922beb7a1ad78d11861faa67 | 5663a82df4c7cf7426d5142cf2585ebdb99d6d6e | refs/heads/master | 2021-06-10T10:23:34.208769 | 2021-04-27T01:49:32 | 2021-04-30T00:09:13 | 159,611,254 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,152 | h | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "AIController.h"
#include "ShooterAIController.generated.h"
class UBehaviorTreeComponent;
class UBlackboardComponent;
UCLASS(config=Game)
class AShooterAIController : public AAIController
{
GENERATED_UCLASS_BODY()
private:
UPROPERTY(transient)
UBlackboardComponent* BlackboardComp;
/* Cached BT component */
UPROPERTY(transient)
UBehaviorTreeComponent* BehaviorComp;
public:
// Begin AController interface
virtual void GameHasEnded(class AActor* EndGameFocus = NULL, bool bIsWinner = false) override;
virtual void BeginInactiveState() override;
protected:
virtual void OnPossess(class APawn* InPawn) override;
virtual void OnUnPossess() override;
// End APlayerController interface
public:
void Respawn();
void CheckAmmo(const class AShooterWeapon* CurrentWeapon);
void SetEnemy(class APawn* InPawn);
class AShooterCharacter* GetEnemy() const;
/* If there is line of sight to current enemy, start firing at them */
UFUNCTION(BlueprintCallable, Category=Behavior)
void ShootEnemy();
/* Finds the closest enemy and sets them as current target */
UFUNCTION(BlueprintCallable, Category=Behavior)
void FindClosestEnemy();
UFUNCTION(BlueprintCallable, Category = Behavior)
bool FindClosestEnemyWithLOS(AShooterCharacter* ExcludeEnemy);
bool HasWeaponLOSToEnemy(AActor* InEnemyActor, const bool bAnyEnemy) const;
// Begin AAIController interface
/** Update direction AI is looking based on FocalPoint */
virtual void UpdateControlRotation(float DeltaTime, bool bUpdatePawn = true) override;
// End AAIController interface
protected:
// Check of we have LOS to a character
bool LOSTrace(AShooterCharacter* InEnemyChar) const;
int32 EnemyKeyID;
int32 NeedAmmoKeyID;
/** Handle for efficient management of Respawn timer */
FTimerHandle TimerHandle_Respawn;
public:
/** Returns BlackboardComp subobject **/
FORCEINLINE UBlackboardComponent* GetBlackboardComp() const { return BlackboardComp; }
/** Returns BehaviorComp subobject **/
FORCEINLINE UBehaviorTreeComponent* GetBehaviorComp() const { return BehaviorComp; }
};
| [
"sungjin.bae@ifunfactory.com"
] | sungjin.bae@ifunfactory.com |
b8238ffeb9b4d0049206f7acecb8688dd6598bf0 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /components/arc/arc_service_manager.h | dc79627c7fccd6a6253fc34c9b4d8cfe7f392e17 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 3,110 | h | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_ARC_ARC_SERVICE_MANAGER_H_
#define COMPONENTS_ARC_ARC_SERVICE_MANAGER_H_
#include <memory>
#include "base/macros.h"
#include "base/threading/thread_checker.h"
#include "components/account_id/account_id.h"
namespace content {
class BrowserContext;
} // namespace content
namespace arc {
class ArcBridgeService;
// Holds ARC related global information. Specifically, it owns ArcBridgeService
// instance.
// TODO(hidehiko): Consider to migrate into another global ARC class, such as
// ArcSessionManager or ArcServiceLauncher.
class ArcServiceManager {
public:
ArcServiceManager();
~ArcServiceManager();
// Returns the current BrowserContext which ARC is allowed.
// This is workaround to split the dependency from chrome/.
// TODO(hidehiko): Remove this when we move IsArcAllowedForProfile() to
// components/arc.
content::BrowserContext* browser_context() { return browser_context_; }
// TODO(hidehiko): Remove this when we move IsArcAllowedForProfile() to
// components/arc. See browser_context() for details.
void set_browser_context(content::BrowserContext* browser_context) {
browser_context_ = browser_context;
}
// Returns the current AccountID which ARC is allowed.
// This is workaround to split the dependency from chrome/.
// TODO(hidehiko): Remove this when we move IsArcAllowedForProfile() to
// components/arc.
const AccountId& account_id() const { return account_id_; }
// TODO(hidehiko): Remove this when we move IsArcAllowedForProfile() to
// components/arc.
void set_account_id(const AccountId& account_id) { account_id_ = account_id; }
// |arc_bridge_service| can only be accessed on the thread that this
// class was created on.
ArcBridgeService* arc_bridge_service();
// Gets the global instance of the ARC Service Manager. This can only be
// called on the thread that this class was created on.
static ArcServiceManager* Get();
private:
THREAD_CHECKER(thread_checker_);
std::unique_ptr<ArcBridgeService> arc_bridge_service_;
// This holds the pointer to the BrowserContext (practically Profile)
// which is allowed to use ARC.
// This is set just before BrowserContextKeyedService classes are
// instantiated.
// So, in BrowserContextKeyedServiceFactory::BuildServiceInstanceFor(),
// given BrowserContext pointer can be compared to this to check if it is
// allowed to use ARC.
// TODO(hidehiko): Remove this when we move IsArcAllowedForProfile() to
// components/arc. See browser_context() for details.
content::BrowserContext* browser_context_ = nullptr;
// This holds the AccountId corresponding to the |browser_context_|.
// TODO(hidehiko): Remove this when we move IsArcAllowedForProfile() to
// components/arc. See browser_context() for details.
AccountId account_id_;
DISALLOW_COPY_AND_ASSIGN(ArcServiceManager);
};
} // namespace arc
#endif // COMPONENTS_ARC_ARC_SERVICE_MANAGER_H_
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
7d4810ef30e824d41ccc63fb12a3be39e504c2d3 | 7dd5a61a6570bbdcebe5c69b6141b48b10493576 | /src/NJSCosmosLikeUnbondingCpp.cpp | 036a0940f4b331cc43bb8eaa8240bc862ee5d837 | [] | no_license | LedgerHQ/lib-ledger-core-node-bindings | 34af75b6f378445ae16e0437f038ec8859addc9d | ced62d392eff27ab153e8a5f330c92e9cd72b92c | refs/heads/master | 2022-05-01T03:09:43.393318 | 2021-09-30T14:15:34 | 2021-09-30T14:15:34 | 133,928,033 | 14 | 32 | null | 2022-04-10T09:12:52 | 2018-05-18T08:45:23 | C++ | UTF-8 | C++ | false | false | 5,219 | cpp | // AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from wallet.djinni
#include "NJSCosmosLikeUnbondingCpp.hpp"
#include "NJSObjectWrapper.hpp"
#include "NJSHexUtils.hpp"
using namespace v8;
using namespace node;
using namespace std;
NAN_METHOD(NJSCosmosLikeUnbonding::getDelegatorAddress) {
//Check if method called with right number of arguments
if(info.Length() != 0)
{
return Nan::ThrowError("NJSCosmosLikeUnbonding::getDelegatorAddress needs 0 arguments");
}
//Check if parameters have correct types
//Unwrap current object and retrieve its Cpp Implementation
auto cpp_impl = djinni::js::ObjectWrapper<ledger::core::api::CosmosLikeUnbonding>::Unwrap(info.This());
if(!cpp_impl)
{
return Nan::ThrowError("NJSCosmosLikeUnbonding::getDelegatorAddress : implementation of CosmosLikeUnbonding is not valid");
}
auto result = cpp_impl->getDelegatorAddress();
//Wrap result in node object
auto arg_0 = Nan::New<String>(result).ToLocalChecked();
//Return result
info.GetReturnValue().Set(arg_0);
}
NAN_METHOD(NJSCosmosLikeUnbonding::getValidatorAddress) {
//Check if method called with right number of arguments
if(info.Length() != 0)
{
return Nan::ThrowError("NJSCosmosLikeUnbonding::getValidatorAddress needs 0 arguments");
}
//Check if parameters have correct types
//Unwrap current object and retrieve its Cpp Implementation
auto cpp_impl = djinni::js::ObjectWrapper<ledger::core::api::CosmosLikeUnbonding>::Unwrap(info.This());
if(!cpp_impl)
{
return Nan::ThrowError("NJSCosmosLikeUnbonding::getValidatorAddress : implementation of CosmosLikeUnbonding is not valid");
}
auto result = cpp_impl->getValidatorAddress();
//Wrap result in node object
auto arg_0 = Nan::New<String>(result).ToLocalChecked();
//Return result
info.GetReturnValue().Set(arg_0);
}
NAN_METHOD(NJSCosmosLikeUnbonding::getEntries) {
//Check if method called with right number of arguments
if(info.Length() != 0)
{
return Nan::ThrowError("NJSCosmosLikeUnbonding::getEntries needs 0 arguments");
}
//Check if parameters have correct types
//Unwrap current object and retrieve its Cpp Implementation
auto cpp_impl = djinni::js::ObjectWrapper<ledger::core::api::CosmosLikeUnbonding>::Unwrap(info.This());
if(!cpp_impl)
{
return Nan::ThrowError("NJSCosmosLikeUnbonding::getEntries : implementation of CosmosLikeUnbonding is not valid");
}
auto result = cpp_impl->getEntries();
//Wrap result in node object
Local<Array> arg_0 = Nan::New<Array>();
for(size_t arg_0_id = 0; arg_0_id < result.size(); arg_0_id++)
{
auto arg_0_elem = NJSCosmosLikeUnbondingEntry::wrap(result[arg_0_id]);
Nan::Set(arg_0, (int)arg_0_id,arg_0_elem);
}
//Return result
info.GetReturnValue().Set(arg_0);
}
NAN_METHOD(NJSCosmosLikeUnbonding::New) {
//Only new allowed
if(!info.IsConstructCall())
{
return Nan::ThrowError("NJSCosmosLikeUnbonding function can only be called as constructor (use New)");
}
info.GetReturnValue().Set(info.This());
}
Nan::Persistent<ObjectTemplate> NJSCosmosLikeUnbonding::CosmosLikeUnbonding_prototype;
Local<Object> NJSCosmosLikeUnbonding::wrap(const std::shared_ptr<ledger::core::api::CosmosLikeUnbonding> &object) {
Nan::EscapableHandleScope scope;
Local<ObjectTemplate> local_prototype = Nan::New(CosmosLikeUnbonding_prototype);
Local<Object> obj;
if(!local_prototype.IsEmpty())
{
obj = local_prototype->NewInstance(Nan::GetCurrentContext()).ToLocalChecked();
djinni::js::ObjectWrapper<ledger::core::api::CosmosLikeUnbonding>::Wrap(object, obj);
}
else
{
Nan::ThrowError("NJSCosmosLikeUnbonding::wrap: object template not valid");
}
return scope.Escape(obj);
}
NAN_METHOD(NJSCosmosLikeUnbonding::isNull) {
auto cpp_implementation = djinni::js::ObjectWrapper<ledger::core::api::CosmosLikeUnbonding>::Unwrap(info.This());
auto isNull = !cpp_implementation ? true : false;
return info.GetReturnValue().Set(Nan::New<Boolean>(isNull));
}
void NJSCosmosLikeUnbonding::Initialize(Local<Object> target) {
Nan::HandleScope scope;
Local<FunctionTemplate> func_template = Nan::New<FunctionTemplate>(NJSCosmosLikeUnbonding::New);
Local<ObjectTemplate> objectTemplate = func_template->InstanceTemplate();
objectTemplate->SetInternalFieldCount(1);
func_template->SetClassName(Nan::New<String>("NJSCosmosLikeUnbonding").ToLocalChecked());
//SetPrototypeMethod all methods
Nan::SetPrototypeMethod(func_template,"getDelegatorAddress", getDelegatorAddress);
Nan::SetPrototypeMethod(func_template,"getValidatorAddress", getValidatorAddress);
Nan::SetPrototypeMethod(func_template,"getEntries", getEntries);
Nan::SetPrototypeMethod(func_template,"isNull", isNull);
//Set object prototype
CosmosLikeUnbonding_prototype.Reset(objectTemplate);
//Add template to target
Nan::Set(target, Nan::New<String>("NJSCosmosLikeUnbonding").ToLocalChecked(), Nan::GetFunction(func_template).ToLocalChecked());
}
| [
"gerry.agbobada-ext@ledger.fr"
] | gerry.agbobada-ext@ledger.fr |
049ac50a1a20ffc9022539b0ae0741601f172d75 | fcd145b1a12edea260d482583f88311e18b05030 | /Codeforces/271/e.cpp | c8ae6e259b21a45753c3a7743d1e1a9c29ec8360 | [] | no_license | triplemzim/competitive_programming | f7e7cf098b19c3abbf2b3ff6bb6e237122deaaf0 | 3da9560d021b743dd55f5165c0c0bb7e9adbf828 | refs/heads/master | 2021-01-22T23:21:29.082154 | 2017-03-20T22:23:11 | 2017-03-20T22:23:11 | 85,630,988 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,896 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ms(x,val) memset(x,val,sizeof(x))
#define scan(x) scanf("%d",&x)
#define scanL(x) scanf("%I64d",&x)
#define print(x) printf("%d\n",x)
#define debug(x) printf("DEBUG: %d\n",x)
#define printL(x) printf("%I64d\n",x)
#define ull unsigned long long
#define iii long long
#define pi acos(-1)
#define pb push_back
#define PII pair<int,int>
#define vi vector<int>
#define itr_all(c,itr) for(__typeof((c).begin()) itr=(c).begin();itr!=(c).end();itr++)
#define MAPL map<long long, int >
#define MAPI map<int,int>
#define MAPP map< pair<int,int> , int>
#define MP make_pair
#define eps 1e-9
#define inf 100000000000000009
#define MAXN 1000009
#define MOD 1000000007 // 10^9 + 7
template < class T > T gcd(T a , T b ) { if(b==0) return a; else return gcd(b, a%b);}
template < class T > T lcm(T a , T b ) { return a*b / gcd(a, b);}
template < class T > T absolute(T a ) { if(a>0) return a; else return -a;}
inline iii power(iii base,iii p) { iii ans=1; while(p>0) ans*=base,p-=1; return ans;}
iii n,d,num[100009],L[100009];
vector<iii>v(100009,inf);
vector<iii>::iterator it;
int idx;
int find_idx(iii val)
{
int low=0,high=100009,mid=(low+high)/2;
while(low<=high)
{
if(absolute(v[mid]-val)>=d && v[mid]!=inf)
{
low=mid+1;
mid=(high+low)/2;
}
else
{
high=mid-1;
mid=(high+low)/2;
}
// else
// {
// cout<<"kemne"<<endl;
// return 0;
// }
}
return low;
}
int main()
{
map<int,int>mp;
mp[2];
mp[1];
mp[4];
itr_all(mp,itr)
{
cout<<itr->first<<endl;
}
freopen("in.txt","r",stdin);
iii mx=-1,last=inf;
cin>>n>>d;
for (int i = 0; i < n; i++) {
cin>>num[i+1];
}
return 0;
}
| [
"Muhim Muktadir Khan"
] | Muhim Muktadir Khan |
e0912f98346aeed2390ad45f564787423e754fbf | 3ded37602d6d303e61bff401b2682f5c2b52928c | /toy/0601/Classes/Scene/PaintScene.h | 34c95d39db6cd07f78b3d83c9f79435708b3de8d | [] | no_license | CristinaBaby/Demo_CC | 8ce532dcf016f21b442d8b05173a7d20c03d337e | 6f6a7ff132e93271b8952b8da6884c3634f5cb59 | refs/heads/master | 2021-05-02T14:58:52.900119 | 2018-02-09T11:48:02 | 2018-02-09T11:48:02 | 120,727,659 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,711 | h | //
// PaintScene.h
// PaintDress
//
// Created by maxiang on 6/16/15.
//
//
#ifndef __PaintDress__PaintScene__
#define __PaintDress__PaintScene__
#include "cocos2d.h"
#include "cocosGUI.h"
#include "cocos-ext.h"
#include "../Model/v2.0/ScribblePatternNode.h"
#include "../Model/v2.0/ScribbleUtil.h"
#include "../Model/AppConfigs.h"
#include "../Widget/ColorWidget.h"
#include "../Widget/PatternWidget.h"
#include "../Model/ResManager.h"
class PaintScene : public cocos2d::Layer,
public cocos2d::extension::TableViewDataSource,
public cocos2d::extension::TableViewDelegate
{
public:
static cocos2d::Scene* createScene(const Res& res);
static PaintScene* create(const Res& res);
bool init(const Res& res);
PaintScene();
virtual ~PaintScene();
protected:
void backAction();
void doneAction();
void eraserAction();
void selectPenAction();
void selectPatternAction();
void initTableView();
bool setupScribble();
void onSaveSuccess();
/* register touch event */
virtual bool onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *unused_event) override;
virtual void onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *unused_event) override;
virtual void onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *unused_event) override;
virtual void onTouchCancelled(cocos2d::Touch *touch, cocos2d::Event *unused_event) override;
virtual void scrollViewDidScroll(cocos2d::extension::ScrollView* view){};
virtual void scrollViewDidZoom(cocos2d::extension::ScrollView* view){};
virtual void tableCellTouched(cocos2d::extension::TableView* table, cocos2d::extension::TableViewCell* cell);
virtual cocos2d::Size tableCellSizeForIndex(cocos2d::extension::TableView *table, ssize_t idx);
virtual cocos2d::extension::TableViewCell* tableCellAtIndex(cocos2d::extension::TableView *table, ssize_t idx);
virtual ssize_t numberOfCellsInTableView(cocos2d::extension::TableView *table);
protected:
cocos2d::extension::TableView *_penTableView;
cocos2d::extension::TableView *_patternTableView;
cocos2d::ui::Button *_eraserButton;
BasePenWidget *_selectColorPenWidget;
BasePenWidget *_selectPatternPenWidget;
cocos2d::Touch *_beginTouch;
cocos2d::LayerColor *_paintingLayer;
/* scribble */
Sprite *_resPicture;
ScribblePatternNode *_pictureScribble;
Image *_resPicturePixelMask;
int _selectPenIndex;
int _selectPatternIndex;
Res _res;
bool _isColouring;
bool _isSelectEraser;
bool _isDone = false;
cocos2d::CustomCommand _callbackCommand;
cocos2d::BlendFunc _blendFunc;
};
#endif /* defined(__PaintDress__PaintScene__) */
| [
"wuguiling@smalltreemedia.com"
] | wuguiling@smalltreemedia.com |
605cb6487bdd5b21e35de634885a35e46ed2db5e | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/chromium_org/content/browser/gamepad/xbox_data_fetcher_mac.cc | 6619b9b48f7a02997aa13cf1fd42449b4ebee3a1 | [
"MIT",
"BSD-3-Clause"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 20,797 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/gamepad/xbox_data_fetcher_mac.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOCFPlugIn.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/usb/IOUSBLib.h>
#include <IOKit/usb/USB.h>
#include "base/logging.h"
#include "base/mac/foundation_util.h"
namespace {
const int kVendorMicrosoft = 0x045e;
const int kProduct360Controller = 0x028e;
const int kReadEndpoint = 1;
const int kControlEndpoint = 2;
enum {
STATUS_MESSAGE_BUTTONS = 0,
STATUS_MESSAGE_LED = 1,
// Apparently this message tells you if the rumble pack is disabled in the
// controller. If the rumble pack is disabled, vibration control messages
// have no effect.
STATUS_MESSAGE_RUMBLE = 3,
};
enum {
CONTROL_MESSAGE_SET_RUMBLE = 0,
CONTROL_MESSAGE_SET_LED = 1,
};
#pragma pack(push, 1)
struct ButtonData {
bool dpad_up : 1;
bool dpad_down : 1;
bool dpad_left : 1;
bool dpad_right : 1;
bool start : 1;
bool back : 1;
bool stick_left_click : 1;
bool stick_right_click : 1;
bool bumper_left : 1;
bool bumper_right : 1;
bool guide : 1;
bool dummy1 : 1; // Always 0.
bool a : 1;
bool b : 1;
bool x : 1;
bool y : 1;
uint8 trigger_left;
uint8 trigger_right;
int16 stick_left_x;
int16 stick_left_y;
int16 stick_right_x;
int16 stick_right_y;
// Always 0.
uint32 dummy2;
uint16 dummy3;
};
#pragma pack(pop)
COMPILE_ASSERT(sizeof(ButtonData) == 0x12, xbox_button_data_wrong_size);
// From MSDN:
// http://msdn.microsoft.com/en-us/library/windows/desktop/ee417001(v=vs.85).aspx#dead_zone
const int16 kLeftThumbDeadzone = 7849;
const int16 kRightThumbDeadzone = 8689;
const uint8 kTriggerDeadzone = 30;
void NormalizeAxis(int16 x,
int16 y,
int16 deadzone,
float* x_out,
float* y_out) {
float x_val = x;
float y_val = y;
// Determine how far the stick is pushed.
float real_magnitude = std::sqrt(x_val * x_val + y_val * y_val);
// Check if the controller is outside a circular dead zone.
if (real_magnitude > deadzone) {
// Clip the magnitude at its expected maximum value.
float magnitude = std::min(32767.0f, real_magnitude);
// Adjust magnitude relative to the end of the dead zone.
magnitude -= deadzone;
// Normalize the magnitude with respect to its expected range giving a
// magnitude value of 0.0 to 1.0
float ratio = (magnitude / (32767 - deadzone)) / real_magnitude;
// Y is negated because xbox controllers have an opposite sign from
// the 'standard controller' recommendations.
*x_out = x_val * ratio;
*y_out = -y_val * ratio;
} else {
// If the controller is in the deadzone zero out the magnitude.
*x_out = *y_out = 0.0f;
}
}
float NormalizeTrigger(uint8 value) {
return value < kTriggerDeadzone ? 0 :
static_cast<float>(value - kTriggerDeadzone) /
(std::numeric_limits<uint8>::max() - kTriggerDeadzone);
}
void NormalizeButtonData(const ButtonData& data,
XboxController::Data* normalized_data) {
normalized_data->buttons[0] = data.a;
normalized_data->buttons[1] = data.b;
normalized_data->buttons[2] = data.x;
normalized_data->buttons[3] = data.y;
normalized_data->buttons[4] = data.bumper_left;
normalized_data->buttons[5] = data.bumper_right;
normalized_data->buttons[6] = data.back;
normalized_data->buttons[7] = data.start;
normalized_data->buttons[8] = data.stick_left_click;
normalized_data->buttons[9] = data.stick_right_click;
normalized_data->buttons[10] = data.dpad_up;
normalized_data->buttons[11] = data.dpad_down;
normalized_data->buttons[12] = data.dpad_left;
normalized_data->buttons[13] = data.dpad_right;
normalized_data->buttons[14] = data.guide;
normalized_data->triggers[0] = NormalizeTrigger(data.trigger_left);
normalized_data->triggers[1] = NormalizeTrigger(data.trigger_right);
NormalizeAxis(data.stick_left_x,
data.stick_left_y,
kLeftThumbDeadzone,
&normalized_data->axes[0],
&normalized_data->axes[1]);
NormalizeAxis(data.stick_right_x,
data.stick_right_y,
kRightThumbDeadzone,
&normalized_data->axes[2],
&normalized_data->axes[3]);
}
} // namespace
XboxController::XboxController(Delegate* delegate)
: device_(NULL),
interface_(NULL),
device_is_open_(false),
interface_is_open_(false),
read_buffer_size_(0),
led_pattern_(LED_NUM_PATTERNS),
location_id_(0),
delegate_(delegate) {
}
XboxController::~XboxController() {
if (source_)
CFRunLoopSourceInvalidate(source_);
if (interface_ && interface_is_open_)
(*interface_)->USBInterfaceClose(interface_);
if (device_ && device_is_open_)
(*device_)->USBDeviceClose(device_);
}
bool XboxController::OpenDevice(io_service_t service) {
IOCFPlugInInterface **plugin;
SInt32 score; // Unused, but required for IOCreatePlugInInterfaceForService.
kern_return_t kr =
IOCreatePlugInInterfaceForService(service,
kIOUSBDeviceUserClientTypeID,
kIOCFPlugInInterfaceID,
&plugin,
&score);
if (kr != KERN_SUCCESS)
return false;
base::mac::ScopedIOPluginInterface<IOCFPlugInInterface> plugin_ref(plugin);
HRESULT res =
(*plugin)->QueryInterface(plugin,
CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID320),
(LPVOID *)&device_);
if (!SUCCEEDED(res) || !device_)
return false;
UInt16 vendor_id;
kr = (*device_)->GetDeviceVendor(device_, &vendor_id);
if (kr != KERN_SUCCESS)
return false;
UInt16 product_id;
kr = (*device_)->GetDeviceProduct(device_, &product_id);
if (kr != KERN_SUCCESS)
return false;
if (vendor_id != kVendorMicrosoft || product_id != kProduct360Controller)
return false;
// Open the device and configure it.
kr = (*device_)->USBDeviceOpen(device_);
if (kr != KERN_SUCCESS)
return false;
device_is_open_ = true;
// Xbox controllers have one configuration option which has configuration
// value 1. Try to set it and fail if it couldn't be configured.
IOUSBConfigurationDescriptorPtr config_desc;
kr = (*device_)->GetConfigurationDescriptorPtr(device_, 0, &config_desc);
if (kr != KERN_SUCCESS)
return false;
kr = (*device_)->SetConfiguration(device_, config_desc->bConfigurationValue);
if (kr != KERN_SUCCESS)
return false;
// The device has 4 interfaces. They are as follows:
// Protocol 1:
// - Endpoint 1 (in) : Controller events, including button presses.
// - Endpoint 2 (out): Rumble pack and LED control
// Protocol 2 has a single endpoint to read from a connected ChatPad device.
// Protocol 3 is used by a connected headset device.
// The device also has an interface on subclass 253, protocol 10 with no
// endpoints. It is unused.
//
// We don't currently support the ChatPad or headset, so protocol 1 is the
// only protocol we care about.
//
// For more detail, see
// https://github.com/Grumbel/xboxdrv/blob/master/PROTOCOL
IOUSBFindInterfaceRequest request;
request.bInterfaceClass = 255;
request.bInterfaceSubClass = 93;
request.bInterfaceProtocol = 1;
request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
io_iterator_t iter;
kr = (*device_)->CreateInterfaceIterator(device_, &request, &iter);
if (kr != KERN_SUCCESS)
return false;
base::mac::ScopedIOObject<io_iterator_t> iter_ref(iter);
// There should be exactly one USB interface which matches the requested
// settings.
io_service_t usb_interface = IOIteratorNext(iter);
if (!usb_interface)
return false;
// We need to make an InterfaceInterface to communicate with the device
// endpoint. This is the same process as earlier: first make a
// PluginInterface from the io_service then make the InterfaceInterface from
// that.
IOCFPlugInInterface **plugin_interface;
kr = IOCreatePlugInInterfaceForService(usb_interface,
kIOUSBInterfaceUserClientTypeID,
kIOCFPlugInInterfaceID,
&plugin_interface,
&score);
if (kr != KERN_SUCCESS || !plugin_interface)
return false;
base::mac::ScopedIOPluginInterface<IOCFPlugInInterface> interface_ref(
plugin_interface);
// Release the USB interface, and any subsequent interfaces returned by the
// iterator. (There shouldn't be any, but in case a future device does
// contain more interfaces, this will serve to avoid memory leaks.)
do {
IOObjectRelease(usb_interface);
} while ((usb_interface = IOIteratorNext(iter)));
// Actually create the interface.
res = (*plugin_interface)->QueryInterface(
plugin_interface,
CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID300),
(LPVOID *)&interface_);
if (!SUCCEEDED(res) || !interface_)
return false;
// Actually open the interface.
kr = (*interface_)->USBInterfaceOpen(interface_);
if (kr != KERN_SUCCESS)
return false;
interface_is_open_ = true;
CFRunLoopSourceRef source_ref;
kr = (*interface_)->CreateInterfaceAsyncEventSource(interface_, &source_ref);
if (kr != KERN_SUCCESS || !source_ref)
return false;
source_.reset(source_ref);
CFRunLoopAddSource(CFRunLoopGetCurrent(), source_, kCFRunLoopDefaultMode);
// The interface should have two pipes. Pipe 1 with direction kUSBIn and pipe
// 2 with direction kUSBOut. Both pipes should have type kUSBInterrupt.
uint8 num_endpoints;
kr = (*interface_)->GetNumEndpoints(interface_, &num_endpoints);
if (kr != KERN_SUCCESS || num_endpoints < 2)
return false;
for (int i = 1; i <= 2; i++) {
uint8 direction;
uint8 number;
uint8 transfer_type;
uint16 max_packet_size;
uint8 interval;
kr = (*interface_)->GetPipeProperties(interface_,
i,
&direction,
&number,
&transfer_type,
&max_packet_size,
&interval);
if (kr != KERN_SUCCESS || transfer_type != kUSBInterrupt)
return false;
if (i == kReadEndpoint) {
if (direction != kUSBIn)
return false;
if (max_packet_size > 32)
return false;
read_buffer_.reset(new uint8[max_packet_size]);
read_buffer_size_ = max_packet_size;
QueueRead();
} else if (i == kControlEndpoint) {
if (direction != kUSBOut)
return false;
}
}
// The location ID is unique per controller, and can be used to track
// controllers through reconnections (though if a controller is detached from
// one USB hub and attached to another, the location ID will change).
kr = (*device_)->GetLocationID(device_, &location_id_);
if (kr != KERN_SUCCESS)
return false;
return true;
}
void XboxController::SetLEDPattern(LEDPattern pattern) {
led_pattern_ = pattern;
const UInt8 length = 3;
// This buffer will be released in WriteComplete when WritePipeAsync
// finishes.
UInt8* buffer = new UInt8[length];
buffer[0] = static_cast<UInt8>(CONTROL_MESSAGE_SET_LED);
buffer[1] = length;
buffer[2] = static_cast<UInt8>(pattern);
kern_return_t kr = (*interface_)->WritePipeAsync(interface_,
kControlEndpoint,
buffer,
(UInt32)length,
WriteComplete,
buffer);
if (kr != KERN_SUCCESS) {
delete[] buffer;
IOError();
return;
}
}
int XboxController::GetVendorId() const {
return kVendorMicrosoft;
}
int XboxController::GetProductId() const {
return kProduct360Controller;
}
void XboxController::WriteComplete(void* context, IOReturn result, void* arg0) {
UInt8* buffer = static_cast<UInt8*>(context);
delete[] buffer;
// Ignoring any errors sending data, because they will usually only occur
// when the device is disconnected, in which case it really doesn't matter if
// the data got to the controller or not.
if (result != kIOReturnSuccess)
return;
}
void XboxController::GotData(void* context, IOReturn result, void* arg0) {
size_t bytes_read = reinterpret_cast<size_t>(arg0);
XboxController* controller = static_cast<XboxController*>(context);
if (result != kIOReturnSuccess) {
// This will happen if the device was disconnected. The gamepad has
// probably been destroyed by a meteorite.
controller->IOError();
return;
}
controller->ProcessPacket(bytes_read);
// Queue up another read.
controller->QueueRead();
}
void XboxController::ProcessPacket(size_t length) {
if (length < 2) return;
DCHECK(length <= read_buffer_size_);
if (length > read_buffer_size_) {
IOError();
return;
}
uint8* buffer = read_buffer_.get();
if (buffer[1] != length)
// Length in packet doesn't match length reported by USB.
return;
uint8 type = buffer[0];
buffer += 2;
length -= 2;
switch (type) {
case STATUS_MESSAGE_BUTTONS: {
if (length != sizeof(ButtonData))
return;
ButtonData* data = reinterpret_cast<ButtonData*>(buffer);
Data normalized_data;
NormalizeButtonData(*data, &normalized_data);
delegate_->XboxControllerGotData(this, normalized_data);
break;
}
case STATUS_MESSAGE_LED:
if (length != 3)
return;
// The controller sends one of these messages every time the LED pattern
// is set, as well as once when it is plugged in.
if (led_pattern_ == LED_NUM_PATTERNS && buffer[0] < LED_NUM_PATTERNS)
led_pattern_ = static_cast<LEDPattern>(buffer[0]);
break;
default:
// Unknown packet: ignore!
break;
}
}
void XboxController::QueueRead() {
kern_return_t kr = (*interface_)->ReadPipeAsync(interface_,
kReadEndpoint,
read_buffer_.get(),
read_buffer_size_,
GotData,
this);
if (kr != KERN_SUCCESS)
IOError();
}
void XboxController::IOError() {
delegate_->XboxControllerError(this);
}
//-----------------------------------------------------------------------------
XboxDataFetcher::XboxDataFetcher(Delegate* delegate)
: delegate_(delegate),
listening_(false),
source_(NULL),
port_(NULL) {
}
XboxDataFetcher::~XboxDataFetcher() {
while (!controllers_.empty()) {
RemoveController(*controllers_.begin());
}
UnregisterFromNotifications();
}
void XboxDataFetcher::DeviceAdded(void* context, io_iterator_t iterator) {
DCHECK(context);
XboxDataFetcher* fetcher = static_cast<XboxDataFetcher*>(context);
io_service_t ref;
while ((ref = IOIteratorNext(iterator))) {
base::mac::ScopedIOObject<io_service_t> scoped_ref(ref);
XboxController* controller = new XboxController(fetcher);
if (controller->OpenDevice(ref)) {
fetcher->AddController(controller);
} else {
delete controller;
}
}
}
void XboxDataFetcher::DeviceRemoved(void* context, io_iterator_t iterator) {
DCHECK(context);
XboxDataFetcher* fetcher = static_cast<XboxDataFetcher*>(context);
io_service_t ref;
while ((ref = IOIteratorNext(iterator))) {
base::mac::ScopedIOObject<io_service_t> scoped_ref(ref);
base::ScopedCFTypeRef<CFNumberRef> number(
base::mac::CFCastStrict<CFNumberRef>(
IORegistryEntryCreateCFProperty(ref,
CFSTR(kUSBDevicePropertyLocationID),
kCFAllocatorDefault,
kNilOptions)));
UInt32 location_id = 0;
CFNumberGetValue(number, kCFNumberSInt32Type, &location_id);
fetcher->RemoveControllerByLocationID(location_id);
}
}
bool XboxDataFetcher::RegisterForNotifications() {
if (listening_)
return true;
base::ScopedCFTypeRef<CFNumberRef> vendor_cf(CFNumberCreate(
kCFAllocatorDefault, kCFNumberSInt32Type, &kVendorMicrosoft));
base::ScopedCFTypeRef<CFNumberRef> product_cf(CFNumberCreate(
kCFAllocatorDefault, kCFNumberSInt32Type, &kProduct360Controller));
base::ScopedCFTypeRef<CFMutableDictionaryRef> matching_dict(
IOServiceMatching(kIOUSBDeviceClassName));
if (!matching_dict)
return false;
CFDictionarySetValue(matching_dict, CFSTR(kUSBVendorID), vendor_cf);
CFDictionarySetValue(matching_dict, CFSTR(kUSBProductID), product_cf);
port_ = IONotificationPortCreate(kIOMasterPortDefault);
if (!port_)
return false;
source_ = IONotificationPortGetRunLoopSource(port_);
if (!source_)
return false;
CFRunLoopAddSource(CFRunLoopGetCurrent(), source_, kCFRunLoopDefaultMode);
listening_ = true;
// IOServiceAddMatchingNotification() releases the dictionary when it's done.
// Retain it before each call to IOServiceAddMatchingNotification to keep
// things balanced.
CFRetain(matching_dict);
io_iterator_t device_added_iter;
IOReturn ret;
ret = IOServiceAddMatchingNotification(port_,
kIOFirstMatchNotification,
matching_dict,
DeviceAdded,
this,
&device_added_iter);
device_added_iter_.reset(device_added_iter);
if (ret != kIOReturnSuccess) {
LOG(ERROR) << "Error listening for Xbox controller add events: " << ret;
return false;
}
DeviceAdded(this, device_added_iter_.get());
CFRetain(matching_dict);
io_iterator_t device_removed_iter;
ret = IOServiceAddMatchingNotification(port_,
kIOTerminatedNotification,
matching_dict,
DeviceRemoved,
this,
&device_removed_iter);
device_removed_iter_.reset(device_removed_iter);
if (ret != kIOReturnSuccess) {
LOG(ERROR) << "Error listening for Xbox controller remove events: " << ret;
return false;
}
DeviceRemoved(this, device_removed_iter_.get());
return true;
}
void XboxDataFetcher::UnregisterFromNotifications() {
if (!listening_)
return;
listening_ = false;
if (source_)
CFRunLoopSourceInvalidate(source_);
if (port_)
IONotificationPortDestroy(port_);
port_ = NULL;
}
XboxController* XboxDataFetcher::ControllerForLocation(UInt32 location_id) {
for (std::set<XboxController*>::iterator i = controllers_.begin();
i != controllers_.end();
++i) {
if ((*i)->location_id() == location_id)
return *i;
}
return NULL;
}
void XboxDataFetcher::AddController(XboxController* controller) {
DCHECK(!ControllerForLocation(controller->location_id()))
<< "Controller with location ID " << controller->location_id()
<< " already exists in the set of controllers.";
controllers_.insert(controller);
delegate_->XboxDeviceAdd(controller);
}
void XboxDataFetcher::RemoveController(XboxController* controller) {
delegate_->XboxDeviceRemove(controller);
controllers_.erase(controller);
delete controller;
}
void XboxDataFetcher::RemoveControllerByLocationID(uint32 location_id) {
XboxController* controller = NULL;
for (std::set<XboxController*>::iterator i = controllers_.begin();
i != controllers_.end();
++i) {
if ((*i)->location_id() == location_id) {
controller = *i;
break;
}
}
if (controller)
RemoveController(controller);
}
void XboxDataFetcher::XboxControllerGotData(XboxController* controller,
const XboxController::Data& data) {
delegate_->XboxValueChanged(controller, data);
}
void XboxDataFetcher::XboxControllerError(XboxController* controller) {
RemoveController(controller);
}
| [
"karun.matharu@gmail.com"
] | karun.matharu@gmail.com |
c56c88e57fedec6aa7acaf36b8103c9fcbb21a4d | 15511aff7ac01a4e81abb2bfde068c502c2a10d1 | /sketches/client/EarlyDisableWiFi/EarlyDisableWiFi.ino | f86c7cfcb7404fafe0c779e9b5c94a305a0779b0 | [
"MIT"
] | permissive | yangkang411/nodemcu-test-flight | f3f9a86d52d54da43f506b9197f6a848fed8f454 | 7d4fefe0262d3deb904dccc8a082669627f80625 | refs/heads/master | 2023-04-17T05:59:43.841814 | 2021-04-25T18:15:29 | 2021-04-25T18:15:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,511 | ino |
#include <ESP8266WiFi.h>
#include <AddrList.h>
#ifndef STASSID
#define STASSID "Pantera"
#define STAPSK "YEzpe93r"
#endif
// preinit() is called before system startup
// from nonos-sdk's user entry point user_init()
void preinit() {
// Global WiFi constructors are not called yet
// (global class instances like WiFi, Serial... are not yet initialized)..
// No global object methods or C++ exceptions can be called in here!
//The below is a static class method, which is similar to a function, so it's ok.
ESP8266WiFiClass::preinitWiFiOff();
}
void setup() {
Serial.begin(74880);
Serial.setDebugOutput(true);
Serial.println("sleeping 5s");
// during this period, a simple amp meter shows
// an average of 20mA with a Wemos D1 mini
// a DSO is needed to check #2111
delay(5000);
Serial.println("waking WiFi up, sleeping 5s");
WiFi.forceSleepWake();
// amp meter raises to 75mA
delay(5000);
Serial.println("connecting to AP " STASSID);
WiFi.mode(WIFI_STA);
WiFi.begin(STASSID, STAPSK);
for (bool configured = false; !configured;) {
for (auto addr : addrList)
if ((configured = !addr.isLocal() && addr.ifnumber() == STATION_IF)) {
Serial.printf("STA: IF='%s' hostname='%s' addr= %s\n",
addr.ifname().c_str(),
addr.ifhostname(),
addr.toString().c_str());
break;
}
Serial.print('.');
delay(500);
}
// amp meter cycles within 75-80 mA
}
void loop() {
}
| [
"alexander.rogalsky@yandex.ru"
] | alexander.rogalsky@yandex.ru |
2e7c4cd14d69470e1962219333faa3733bd6b1b0 | 02ac923a44b9424757b6d781a978c10b032e6b2c | /REBLMenu.h | a3599ea9d0df1d5a225383277873a18bac766740 | [] | no_license | adamaero/REBL_UI | 77e14e90ca0dbfc750318f835d772c094855ee7e | 21104ac92fdaf38c71e9159b4fc1b6b8a4d412a4 | refs/heads/master | 2020-03-26T02:06:33.054179 | 2018-08-15T16:50:53 | 2018-08-15T16:50:53 | 144,396,948 | 0 | 2 | null | 2018-08-11T15:34:09 | 2018-08-11T15:34:09 | null | UTF-8 | C++ | false | false | 463 | h | /*
* REBLMenu.h
*
* Created on: Oct 10, 2015
* Author: David
*/
#ifndef REBLMENU_H_
#define REBLMENU_H_
#include "Arduino.h"
#include "REBL_UI.h"
#include "MenuClass.h"
//#include "Defines.h"
//#include "REBLInterface.h"
//#include "REBLDisplay.h"
class REBLMenu: public MenuClass {
public:
int updateSelection();
boolean selectionMade();
boolean checkForCancel();
void displayMenu();
};
extern REBLMenu reblMenu;
#endif /* REBLMENU_H_ */
| [
"disco47dave@gmail.com"
] | disco47dave@gmail.com |
527ce7e06e4c22ba21d5684b315cbcb63aa7e5bb | 76988120ead502cc29ffe9cf5ee91e979590d054 | /src/3rdparty/sslworld/sslworld.h | 5ddccc3765408e1278e93271c90aa7f815ba13c6 | [] | no_license | francosaraiva/UVF-GA | a7c5cf27af635b25a39c185edeb849099c0e886c | b7a5a3e99a4b01ff477bb3ba9d3e31df0494637b | refs/heads/master | 2020-12-24T05:33:46.870623 | 2016-11-11T14:14:46 | 2016-11-11T14:14:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,743 | h | /*
grSim - RoboCup Small Size Soccer Robots Simulator
Copyright (C) 2011, Parsian Robotic Center (eew.aut.ac.ir/~parsian/grsim)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SSLWORLD_H
#define SSLWORLD_H
#define ROBOT_COUNT 6
#define WALL_COUNT 10
#include <QTime>
#include "robot.h"
#include "fieldconfig.h"
#include "physics/pworld.h"
#include "physics/pball.h"
#include "physics/pground.h"
#include "physics/pfixedbox.h"
#include "physics/pray.h"
class RobotsFomation {
public:
dReal x[ROBOT_COUNT];
dReal y[ROBOT_COUNT];
RobotsFomation(int type);
void setAll(dReal *xx,dReal *yy);
void resetRobots(Robot** r,int team);
};
class SSLWorld {
private:
dReal last_dt;
public:
SSLWorld(FieldConfig* _cfg,RobotsFomation *form1,RobotsFomation *form2);
virtual ~SSLWorld();
void step(dReal dt=-1);
Robot* robots[ROBOT_COUNT*2];
FieldConfig* cfg;
PWorld* p;
PBall* ball;
PGround* ground;
PRay* ray;
PFixedBox* walls[WALL_COUNT];
QTime *timer;
};
dReal fric(dReal f);
int robotIndex(int robot,int team);
#endif // SSLWORLD_H
| [
"gcaixetaoliveira@gmail.com"
] | gcaixetaoliveira@gmail.com |
49a9b588e9b827b5b3aeb79498e9bdbadd190cba | e6639e720bcdb74a9c072e4a4236ee9171f4b891 | /src/render/FloatingText.h | 1453cb07845f7e77b3277405cb415f4b0cab1c06 | [] | no_license | Sytten/MineDeeper | 7bc3ae466c416f7a3bbb53c2dc865316be091b77 | 40f55c8601508ad73a2a1b9eba80e7c4519461bd | refs/heads/master | 2020-05-19T22:20:18.133321 | 2013-04-20T04:21:12 | 2013-04-20T04:21:12 | 6,573,565 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,583 | h | // ---------------------------------------------------------------------------
// This software is in the public domain, furnished "as is", without technical
// support, and with no warranty, express or implied, as to its usefulness for
// any purpose.
//
// FloatingText.h
// The header file of the FloatingText object. See the cpp file for more
// information about the class.
//
// Author: Sytten
// Creation date: 14/04/2013
// Last modification date: 15/04/2013
// ---------------------------------------------------------------------------
#ifndef FLOATINGTEXT_H
#define FLOATINGTEXT_H
#include <string>
#include <SFML/Graphics.hpp>
class FloatingText
{
public:
enum Orientation{X, Y};
FloatingText(std::string text, std::string fontName, unsigned textSize, sf::Color textColor, sf::Vector2f position, sf::Vector2f targetPosition, sf::Time delay);
FloatingText(std::string text, std::string fontName, unsigned textSize, sf::Color textColor, sf::Vector2f positionRelativeToObject, sf::Rect<float> objectCenteredOn,
FloatingText::Orientation axis, sf::Vector2f targetPositionRelativeToObject, bool stayCenteredOnObject, sf::Time delay);
void update();
sf::Text const& getText(sf::Vector2f cameraPos);
bool isFinished() const { return m_finished; }
private:
sf::Text m_text;
sf::Font m_font;
sf::Clock m_timer;
sf::Vector2f m_position;
sf::Vector2f m_targetPosition;
sf::Vector2f m_movement;
bool m_finished;
};
#endif // FLOATINGTEXT_H
| [
"emilefugulin@hotmail.com"
] | emilefugulin@hotmail.com |
0f9f0d2e9648b4184341584df7988b7a73784851 | 44377496eb00bee35db9ef7c16c698c9f590545d | /src/Position_02.cpp | 5cdb9c717011eca0db6c5fbe591b3b81a41e3759 | [] | no_license | dherraiz/atc_sim_ros | 518c8f27ea87bfb9b2b00c7df799ad8c485e3e93 | c256ab06b6ef89d373c5ec86334c652c10c86fb7 | refs/heads/master | 2021-03-25T23:47:22.391591 | 2020-05-18T08:55:39 | 2020-05-18T08:55:39 | 247,656,113 | 0 | 0 | null | 2020-05-18T08:50:25 | 2020-03-16T09:06:15 | C++ | UTF-8 | C++ | false | false | 3,022 | cpp | /*
* BASED ON:
*
* Position.h & Position.cpp
*
* Created on: 15/07/2014
* Author: paco
*
*/
#include <string>
#include <math.h>
class Position {
public:
Position();
Position(float _x, float _y);
Position(float _x, float _y, float _z);
Position(std::string _name, float _x, float _y);
Position(std::string _name, float _x, float _y, float _z);
virtual ~Position();
std::string get_name() {return name;};
float get_x() {return x;};
float get_y() {return y;};
float get_z() {return z;};
void set_name(std::string _name) {name = check_name(_name);};
void set_x(float _x) {x = _x;};
void set_y(float _y) {y = _y;};
void set_z(float _z) {z = _z;};
float distance(Position pos);
float distanceXY(Position pos);
float distX_EjeBody(Position pos1, Position pos2);
float get_angle(Position pos1, Position pos2);
void angles(Position pos, float &bearing, float &inclination);
private:
std::string name;
float x, y, z;
std::string check_name(std::string name);
};
Position::Position() {
name = "";
x = y = z = 0.0;
}
Position::Position(float _x, float _y)
{
name = "";
x = _x;
y = _y;
z = 0;
}
Position::Position(float _x, float _y, float _z)
{
name = "";
x = _x;
y = _y;
z = _z;
}
Position::Position(std::string _name, float _x, float _y)
{
name = check_name(_name);
x = _x;
y = _y;
z = 0;
}
Position::Position(std::string _name, float _x, float _y, float _z)
{
name = check_name(_name);
x = _x;
y = _y;
z = _z;
}
Position::~Position() {
}
std::string Position::check_name(std::string name)
{
ushort max_length = 5;
std::string aux;
// Limit name to 5 characters
if(name.length() > max_length)
{
aux = name.substr(0, max_length);
}
// Fill name to 5 characters
else if(name.length() < max_length)
{
aux = name.substr(0, name.length());
for(int i=name.length(); i<max_length; i++)
aux += "0";
}
else
{
aux = name;
}
return aux;
}
float
Position::distance(Position pos)
{
return sqrtf( ( (x - pos.get_x()) * (x - pos.get_x()) ) +
( (y - pos.get_y()) * (y - pos.get_y()) ) +
( (z - pos.get_z()) * (z - pos.get_z()) ) );
}
float
Position::distanceXY(Position pos)
{
return sqrtf( ((x-pos.get_x())*(x-pos.get_x())) + ((y-pos.get_y())*(y-pos.get_y())));
}
float
Position::distX_EjeBody(Position pos1, Position pos2)
{
float betta = atan2f(pos1.get_y()-y, pos1.get_x()-x);
return cos(betta)*(pos2.get_x()-pos1.get_x()) + sin(betta)*(pos2.get_y()-pos1.get_y());
}
float
Position::get_angle(Position pos1, Position pos2)
{
float u1, u2, v1, v2;
u1 = pos1.get_x()-x;
u2 = pos1.get_y()-y;
v1 = pos2.get_x()-pos1.get_x();
v2 = pos2.get_y()-pos1.get_y();
return acos((fabs(u1*v1+u2*v2)) / (sqrt(u1*u1+u2*u2)*sqrt(v1*v1+v2*v2)));
}
void
Position::angles(Position pos, float &bearing, float &inclination)
{
float distxy;
distxy = sqrtf( ((x-pos.get_x())*(x-pos.get_x())) + ((y-pos.get_y())*(y-pos.get_y())));
bearing = atan2f(y-pos.get_y(), x-pos.get_x());
inclination = atan2f(pos.get_z()-z, distxy);
}
| [
"noreply@github.com"
] | dherraiz.noreply@github.com |
a833e95f7025762eb226863453919819241e60cb | a1fbf16243026331187b6df903ed4f69e5e8c110 | /cs/engine/xrGame/alife_anomalous_zone.cpp | 984fbb4ce3397b8d880048276fdb20832c1986e7 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | OpenXRay/xray-15 | ca0031cf1893616e0c9795c670d5d9f57ca9beff | 1390dfb08ed20997d7e8c95147ea8e8cb71f5e86 | refs/heads/xd_dev | 2023-07-17T23:42:14.693841 | 2021-09-01T23:25:34 | 2021-09-01T23:25:34 | 23,224,089 | 64 | 23 | NOASSERTION | 2019-04-03T17:50:18 | 2014-08-22T12:09:41 | C++ | UTF-8 | C++ | false | false | 4,174 | cpp | ////////////////////////////////////////////////////////////////////////////
// Module : alife_anomalous_zone.cpp
// Created : 27.10.2005
// Modified : 27.10.2005
// Author : Dmitriy Iassenev
// Description : ALife anomalous zone class
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "xrServer_Objects_ALife_Monsters.h"
#include "ai_space.h"
#include "alife_simulator.h"
#include "alife_time_manager.h"
#include "alife_spawn_registry.h"
#include "alife_graph_registry.h"
#pragma warning(push)
#pragma warning(disable:4995)
#include <malloc.h>
#pragma warning(pop)
CSE_ALifeItemWeapon *CSE_ALifeAnomalousZone::tpfGetBestWeapon(ALife::EHitType &tHitType, float &fHitPower)
{
m_tpCurrentBestWeapon = 0;
m_tTimeID = ai().alife().time_manager().game_time();
fHitPower = 1.0f;//m_maxPower;
tHitType = m_tHitType;
return (m_tpCurrentBestWeapon);
}
ALife::EMeetActionType CSE_ALifeAnomalousZone::tfGetActionType(CSE_ALifeSchedulable *tpALifeSchedulable, int iGroupIndex, bool bMutualDetection)
{
return (ALife::eMeetActionTypeAttack);
}
bool CSE_ALifeAnomalousZone::bfActive()
{
return (false/*fis_zero(m_maxPower,EPS_L)*/ || !interactive());
}
CSE_ALifeDynamicObject *CSE_ALifeAnomalousZone::tpfGetBestDetector()
{
VERIFY2 (false,"This function shouldn't be called");
NODEFAULT;
#ifdef DEBUG
return (0);
#endif
}
/*
void CSE_ALifeAnomalousZone::spawn_artefacts ()
{
VERIFY2 (!m_bOnline,"Cannot spawn artefacts in online!");
float m_min_start_power = pSettings->r_float(name(),"min_start_power");
float m_max_start_power = pSettings->r_float(name(),"max_start_power");
u32 m_min_artefact_count= pSettings->r_u32 (name(),"min_artefact_count");;
u32 m_max_artefact_count= pSettings->r_u32 (name(),"max_artefact_count");;
u32 m_artefact_count;
if (m_min_artefact_count == m_max_artefact_count)
m_artefact_count = m_min_artefact_count;
else
m_artefact_count = randI(m_min_artefact_count,m_max_artefact_count);
if (m_min_start_power == m_max_start_power)
m_maxPower = m_min_start_power;
else
m_maxPower = randF(m_min_start_power,m_max_start_power);
LPCSTR artefacts = pSettings->r_string(name(),"artefacts");
u32 n = _GetItemCount(artefacts);
VERIFY2 (!(n % 2),"Invalid parameters count in line artefacts for anomalous zone");
n >>= 1;
typedef std::pair<shared_str,float> Weight;
typedef buffer_vector<Weight> Weights;
Weights weights (
_alloca(n*sizeof(Weight)),
n
);
for (u32 i=0; i<n; ++i) {
string256 temp0, temp1;
_GetItem ( artefacts, 2*i + 0, temp0 );
_GetItem ( artefacts, 2*i + 1, temp1 );
weights.push_back (
std::make_pair(
temp0,
(float)atof(temp1)
)
);
}
for (u32 ii=0; ii<m_artefact_count; ++ii) {
float fProbability = randF(1.f);
float fSum = 0.f;
for (u16 p=0; p<n; ++p) {
fSum += weights[p].second;
if (fSum > fProbability)
break;
}
if (p < n) {
CSE_Abstract *l_tpSE_Abstract = alife().spawn_item(*weights[p].first,position(),m_tNodeID,m_tGraphID,0xffff);
R_ASSERT3 (l_tpSE_Abstract,"Can't spawn artefact ",*weights[p].first);
CSE_ALifeDynamicObject *i = smart_cast<CSE_ALifeDynamicObject*>(l_tpSE_Abstract);
R_ASSERT2 (i,"Non-ALife object in the 'game.spawn'");
i->m_tSpawnID = m_tSpawnID;
i->m_bALifeControl = true;
ai().alife().spawns().assign_artefact_position(this,i);
Fvector t = i->o_Position ;
u32 p = i->m_tNodeID ;
float q = i->m_fDistance ;
alife().graph().change(i,m_tGraphID,i->m_tGraphID);
i->o_Position = t;
i->m_tNodeID = p;
i->m_fDistance = q;
CSE_ALifeItemArtefact *l_tpALifeItemArtefact = smart_cast<CSE_ALifeItemArtefact*>(i);
R_ASSERT2 (l_tpALifeItemArtefact,"Anomalous zone can't generate non-artefact objects since they don't have an 'anomaly property'!");
l_tpALifeItemArtefact->m_fAnomalyValue = m_maxPower*(1.f - i->o_Position.distance_to(o_Position)/m_offline_interactive_radius);
}
}
}*/
void CSE_ALifeAnomalousZone::on_spawn ()
{
inherited::on_spawn ();
// spawn_artefacts ();
}
| [
"paul-kv@yandex.ru"
] | paul-kv@yandex.ru |
0d6367aafc91d7ba0a6950c6b99cf884ee9b6647 | 667bbfd99d40a077a6cec48208b03b8d10ce3631 | /Step5/canadian/CanadianExperience/CanadianExperience/ImageDrawable.h | dc0ae820d90c8a764b005e9468efd168093b2a20 | [] | no_license | Chanduniverse/CSE-335-Projects | 6cca3cbf5791d21dd031c90484e9a7c09c2501d9 | ae3b79e1314c92e0a599b2100c7ed941593f2a61 | refs/heads/main | 2023-04-24T05:03:07.103104 | 2021-05-10T21:49:24 | 2021-05-10T21:49:24 | 366,182,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 955 | h | /**
* \file ImageDrawable.h
*
* \author Chandan Aralikatti
*
* Class that handles images that are drawables
*
*/
#pragma once
#include "Drawable.h"
#include <memory>
/**
* Class that handles images that are drawables
*
*/
class CImageDrawable :
public CDrawable
{
public:
/** Set the drawable center
* \param pos The new drawable center*/
void SetCenter(Gdiplus::Point pos) { mCenter = pos; }
/** Get the drawable position
* \returns The drawable position*/
Gdiplus::Point GetCenter() const { return mCenter; }
CImageDrawable(const std::wstring& name, const std::wstring& filename);
virtual bool HitTest(Gdiplus::Point pos) override;
virtual void Draw(Gdiplus::Graphics* graphics) override;
private:
/// The image for this drawable
std::unique_ptr<Gdiplus::Bitmap> mImage;
/// The center of this drawable relative to its parent
Gdiplus::Point mCenter = Gdiplus::Point(0, 0);
};
| [
"chand4ara@gmail.com"
] | chand4ara@gmail.com |
23fb058e83c901afa8082aa9902e47a56f8da4bf | 7eee9c5c28806fbf0c71cf0e21e64406862191fa | /Source/Hdn/HdnCharacter.h | 2461975ca04d35802af15ce50207bbb3b48f0870 | [
"MIT"
] | permissive | Hengle/houdini_jam_2020 | 6f4efac2dd10294630faed39679c709d1181732a | 60ff3466ba8099b26c27bc3981c655c7f541c836 | refs/heads/master | 2023-03-24T23:31:35.311753 | 2020-10-14T13:05:24 | 2020-10-14T13:05:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,962 | h | // Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "HdnCharacter.generated.h"
class UHdnStress;
class AHdnEscapeObjective;
class AHdnFlag;
class UHdnSpectrumAnalyzer;
UCLASS(config=Game)
class AHdnCharacter : public ACharacter
{
GENERATED_BODY()
/** Camera boom positioning the camera behind the character */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class USpringArmComponent* CameraBoom;
/** Follow camera */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class UCameraComponent* FollowCamera;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Gameplay", meta = (AllowPrivateAccess = "true"))
UHdnSpectrumAnalyzer* SpectrumAnalyzer;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Gameplay", meta = (AllowPrivateAccess = "true"))
UHdnStress* Stress;
public:
AHdnCharacter();
virtual void BeginPlay() override;
/** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)
float BaseTurnRate;
/** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)
float BaseLookUpRate;
void ActivatedObjective(AHdnFlag* objective) const;
void ActivatedEscape(AHdnEscapeObjective* objective) const;
void ActivateFeral();
protected:
public:
virtual float TakeDamage(float Damage, FDamageEvent const& DamageEvent, AController* EventInstigator,
AActor* DamageCauser) override;
/** Resets HMD orientation in VR. */
void OnResetVR();
/** Called for forwards/backward input */
void MoveForward(float Value);
/** Called for side to side input */
void MoveRight(float Value);
/**
* Called via input to turn at a given rate.
* @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate
*/
void TurnAtRate(float Rate);
/**
* Called via input to turn look up/down at a given rate.
* @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate
*/
void LookUpAtRate(float Rate);
/** Handler for when a touch input begins. */
void TouchStarted(ETouchIndex::Type FingerIndex, FVector Location);
/** Handler for when a touch input stops. */
void TouchStopped(ETouchIndex::Type FingerIndex, FVector Location);
// APawn interface
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
// End of APawn interface
void ChangeScannerFov() const;
FTimerHandle TimerTickHandle;
public:
void TimerTick();
/** Returns CameraBoom subobject **/
FORCEINLINE class USpringArmComponent* GetCameraBoom() const { return CameraBoom; }
/** Returns FollowCamera subobject **/
FORCEINLINE class UCameraComponent* GetFollowCamera() const { return FollowCamera; }
};
| [
"adipamihi@gmail.com"
] | adipamihi@gmail.com |
0776eda0760d5da5ac4879b3428d10ade6bc1e1a | cb88a02fa2ef4092a150b229b5b3779dc89b1586 | /VS2019-C++基础/数组指针/数组指针.cpp | ef331c43a7a29643546c84f10af5878d4a5c63da | [] | no_license | 1765155167/C-Java-Python | f083ed7de36936ff4b20ddcf865b593c353d3abd | aa31d765d3e895dc65bbb770a32c7bc07a64b4bd | refs/heads/master | 2022-06-26T19:55:45.171720 | 2020-04-13T15:20:39 | 2020-04-13T15:20:39 | 205,353,222 | 0 | 0 | null | 2022-06-21T04:12:40 | 2019-08-30T09:45:46 | Python | UTF-8 | C++ | false | false | 1,157 | cpp | // 数组指针.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
typedef int(INT_10)[10];//数组类型
typedef int(*INT_P_10)[10];//数组指针
void fun()
{
std::cout << "fun()..." << std::endl;
}
void test01(void (*abc)())
{
std::cout << "test01()..." << std::endl;
abc();
}
int main()
{
auto abc = fun;//
std::cout << abc << std::endl;
std::cout << fun << std::endl;
std::cout << &fun << std::endl;
test01(abc);
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
| [
"1765155167@qq.com"
] | 1765155167@qq.com |
291d9a5bd84c364c789e76a00c15b68e4a800a46 | 666ca8a64affe25b7664a02d84aa34c82928795c | /perfMedianInt.cxx | 475c9c99686258b240b1b79a6f476ce28661dd45 | [] | no_license | glehmann/fastRankMean | be2c436241687913d011884b44e67aae2bccf1c0 | d2a048c2874b598c54e916cd38e1bd7d68a3f2c3 | refs/heads/master | 2020-05-31T21:10:04.713080 | 2008-04-07T07:16:35 | 2008-04-07T07:16:35 | 3,272,794 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,064 | cxx | #include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkCommand.h"
#include "itkSimpleFilterWatcher.h"
#include "itkNeighborhood.h"
#include "itkRankImageFilter.h"
#include "itkMedianImageFilter.h"
#include "itkTimeProbe.h"
#include <vector>
#include <iomanip>
int main(int, char * argv[])
{
const int dim = 2;
typedef int PType;
typedef itk::Image< PType, dim > IType;
unsigned repeats = (unsigned)atoi(argv[1]);
// set up the radius
typedef std::vector<int> IVec;
IVec rads;
rads.push_back(1);
rads.push_back(5);
rads.push_back(10);
rads.push_back(15);
rads.push_back(20);
rads.push_back(40);
typedef itk::ImageFileReader< IType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[2] );
reader->Update();
std::cout << "radius \t Traditional time \t Huang time" << std::endl;
for (unsigned r = 0; r < rads.size(); r++)
{
itk::TimeProbe HTime, TTime;
int radius = rads[r];
typedef itk::Neighborhood<bool, dim> KType;
KType kernel;
kernel.SetRadius(radius);
for( KType::Iterator kit=kernel.Begin(); kit!=kernel.End(); kit++ )
{
*kit=1;
}
typedef itk::RankImageFilter< IType, IType, KType > FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( reader->GetOutput() );
filter->SetKernel(kernel);
for (unsigned i=0;i<repeats; i++)
{
HTime.Start();
filter->Modified();
filter->Update();
HTime.Stop();
}
typedef itk::MedianImageFilter<IType, IType> MedianFilterType;
MedianFilterType::Pointer median = MedianFilterType::New();
median->SetInput(reader->GetOutput());
median->SetRadius(kernel.GetRadius());
for (unsigned i=0;i<repeats; i++)
{
TTime.Start();
median->Modified();
median->Update();
TTime.Stop();
}
std::cout << std::setprecision(3) << radius << "\t"
<< TTime.GetMeanTime() <<"\t"
<< HTime.GetMeanTime() << std::endl;
}
return 0;
}
| [
"none"
] | none |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.