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
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
1e67190757339e8f0154a38cd44689a6b7e9c50c
fcf0fa7c5ad67035e67ebc6fef0dfeea1535baaa
/Lab 04/seg/pymmseg/mmseg-cpp/rules.h
41d1313b6f9c6cbaaecec506354f5e65a6878775
[ "MIT" ]
permissive
marridG/2019-EE208
214193d171bcbed3c3bc8da50d938fc59493aea9
dd5de4719636a166addb765d1ac319b55cfbeb14
refs/heads/master
2022-04-19T13:34:25.141322
2020-04-08T06:01:23
2020-04-08T06:01:23
210,758,386
5
4
null
null
null
null
UTF-8
C++
false
false
1,938
h
#ifndef _RULES_H_ #define _RULES_H_ #include <vector> #include <algorithm> #include "chunk.h" namespace rmmseg { template <typename Cmp> void take_highest(std::vector<Chunk> &chunks, Cmp &cmp) { unsigned int i = 1, j; Chunk& max = chunks[0]; for (j = 1; j < chunks.size(); ++j) { int rlt = cmp(chunks[j], max); if (rlt > 0) i = 0; if (rlt >= 0) std::swap(chunks[i++], chunks[j]); } chunks.erase(chunks.begin()+i, chunks.end()); } struct MMCmp_t { int operator()(Chunk &a, Chunk &b) { return a.total_length() - b.total_length(); } } MMCmp; void mm_filter(std::vector<Chunk> &chunks) { take_highest(chunks, MMCmp); } struct LAWLCmp_t { int operator()(Chunk &a, Chunk &b) { double rlt = a.average_length() - b.average_length(); if (rlt == 0) return 0; if (rlt > 0) return 1; return -1; } } LAWLCmp; void lawl_filter(std::vector<Chunk> &chunks) { take_highest(chunks, LAWLCmp); } struct SVWLCmp_t { int operator()(Chunk &a, Chunk& b) { double rlt = a.variance() - b.variance(); if (rlt == 0) return 0; if (rlt < 0) return 1; return -1; } } SVWLCmp; void svwl_filter(std::vector<Chunk> &chunks) { take_highest(chunks, SVWLCmp); } struct LSDMFOCWCmp_t { int operator()(Chunk &a, Chunk& b) { return a.degree_of_morphemic_freedom() - b.degree_of_morphemic_freedom(); } } LSDMFOCWCmp; void lsdmfocw_filter(std::vector<Chunk> &chunks) { take_highest(chunks, LSDMFOCWCmp); } } #endif /* _RULES_H_ */
[ "1687450542@qq.com" ]
1687450542@qq.com
2ad14e6da8c009359d8aba55784278e3cf253db8
f3e103ada2dec2842c981f5b5653e9510288d2bb
/Bai1_HelloWorld/Bai2_Ham/Bai2_Ham.cpp
bd223001d8cda8a1d1ef1545e4c14f250b585099
[]
no_license
ducnhan17032005/hoc-cpp
07ac613c37009a698f84449c14576441e1f95814
3219db12a575d290acceb2cb977affa5935cbd58
refs/heads/main
2023-05-30T16:43:30.589832
2021-06-04T15:22:02
2021-06-04T15:22:02
372,265,607
0
0
null
null
null
null
UTF-8
C++
false
false
1,120
cpp
#pragma once #include <iostream> #include <string> // standard : thu vien chuan #include "tinhtoan.h" using namespace std; //viet chuong trinh nhap vao a b. Lua chon 4 option +, - , *, / va tinh //dung ham // vi du // Nhap so a: 2 // Nhap so b: 3 // Chon cong thuc tinh 1. + , 2 - , 3 * , 4 /, 0 - exit // In ra ket qua: Ket qua la: 5 // tao file caculator.h chua 4 ham tinh + , - , *, / void menu() { int choice; int a; int b; do { cout << "a = "; cin >> a; cout << "b = "; cin >> b; cout << "__________tinh gia tri_________" << endl; cout << "(1) a + b" << endl; cout << "(2) a - b" << endl; cout << "(3) a * b" << endl; cout << "(4) a / b" << endl; cout << "__________________________________" << endl; cout << "vui long nhap choice: "; cin >> choice; switch (choice) { case 1: cout << tong(a, b) << endl; break; case 2: cout << hieu(a, b) << endl; break; case 3: cout << tich(a, b) << endl; break; case 4: cout << thuong(a, b) << endl; break; default: break; } } while (choice != 0); } int main() { menu(); system("pause"); }
[ "tranductb100@gmail.com" ]
tranductb100@gmail.com
f7712fe93df98b9dcbf99ba4685aa251f09ea18d
d96333ca6eb18677c2579c1114fb047cc799bf13
/indeedb.cpp
cfdf150d2dd9387134a8d670cf616d4ab78fa439
[]
no_license
zaburo-ch/icpc_practice
e8fe735857689f685ea86435346963731f5dcd18
fc275c0d0a0b8feba786059fa1f571563d8e432e
refs/heads/master
2021-01-19T05:03:31.891988
2015-06-28T17:39:00
2015-06-28T17:39:00
21,899,426
0
0
null
null
null
null
UTF-8
C++
false
false
987
cpp
#include <iostream> #include <stdio.h> #include <sstream> #include <string> #include <vector> #include <map> #include <queue> #include <algorithm> #include <set> #include <math.h> #include <utility> #include <stack> #include <string.h> using namespace std; typedef pair<int,int> P; const int INF = ~(1<<31) / 2; int N,K; int A[6]; int ans = INF; bool used[6]; void dfs(int pos,int v){ if(pos==N){ ans = min(ans,abs(v-K)); } if (pos==0){ for(int i=0;i<N;i++){ used[i] = true; dfs(pos+1,A[i]); used[i] = false; } }else{ for(int i=0;i<N;i++){ if(!used[i]){ used[i] = true; dfs(pos+1,v+A[i]); dfs(pos+1,v*A[i]); used[i] = false; } } } } int main(){ cin >> N >> K; for(int i=0;i<N;i++){ cin >> A[i]; } fill(used,used+N,false); dfs(0,0); cout << ans << endl; return 0; }
[ "musharna000@gmail.com" ]
musharna000@gmail.com
d2ee622e7ab16d200a28cee778248819edc3fe91
45628c68bbb40c598cdfd589d292cf7f419f8e87
/STL/introSTL.cpp
3935951549f507498ee75aca4103e270d8581825
[]
no_license
sajib581/Data-Structure-and-Algorithms
98a1f9914480221f741ba962eb533c97b0228382
77a480cbe46a2f40a5f0b575a7ae9910c25e5e28
refs/heads/master
2022-11-10T17:46:00.908919
2020-06-26T05:07:17
2020-06-26T05:07:17
272,315,142
0
0
null
null
null
null
UTF-8
C++
false
false
150
cpp
#include<iostream> #include<stdio.h> #include<string> using namespace std ; int main() { cout<<"Introduction to STL"<<endl ; return 0 ; }
[ "sajibdas581@gmail.com" ]
sajibdas581@gmail.com
7d14f3ab8d5443202faf908bb44425f2ecb1272b
2b0b07242be5ea756aba992e171b43fbee9bfada
/BOJ/10718/10718.cpp14.cpp
8a893bcc1a5e7594ca6bb8a2981b7bc78cfa1b4d
[]
no_license
newdaytrue/PS
28f138a5e8fd4024836ea7c2b6ce59bea91dbad7
afffef30fcb59f6abfee2d5b8f00a304e8d80c91
refs/heads/master
2020-03-22T13:01:46.555651
2018-02-13T18:25:34
2018-02-13T18:25:34
140,078,090
1
0
null
2018-07-07T11:21:44
2018-07-07T11:21:44
null
UTF-8
C++
false
false
233
cpp
#include <stdio.h> #include <iostream> #include <algorithm> #include <cstring> #include <string> using namespace std; int main() { printf("강한친구 대한육군\n"); printf("강한친구 대한육군\n"); return 0; }
[ "bsj0206@naver.com" ]
bsj0206@naver.com
578a1888eea7b12bb9f401f7716d4e6e73336154
b5881a2a068172e356c308ca469b8670e44c3ea6
/ortools/math_opt/cpp/streamable_solver_init_arguments.cc
0e03bc59cafb4eb0f7a9e88026c325d0c0c234c2
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
permissive
bhoeferlin/or-tools
b675fecece9a788cae58ab87f2ba774b9b307728
dfdcfb58d7228fa0ae6d0182ba9b314c7122519f
refs/heads/master
2022-02-21T16:38:31.999088
2022-02-08T14:27:44
2022-02-08T14:27:44
141,839,304
0
0
Apache-2.0
2020-11-06T17:03:34
2018-07-21T19:08:59
C++
UTF-8
C++
false
false
1,633
cc
// Copyright 2010-2021 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 "ortools/math_opt/cpp/streamable_solver_init_arguments.h" #include <optional> #include <type_traits> #include "ortools/math_opt/parameters.pb.h" #include "ortools/math_opt/solvers/gurobi.pb.h" namespace operations_research { namespace math_opt { GurobiInitializerProto::ISVKey GurobiISVKey::Proto() const { GurobiInitializerProto::ISVKey isv_key_proto; isv_key_proto.set_name(name); isv_key_proto.set_application_name(application_name); isv_key_proto.set_expiration(expiration); isv_key_proto.set_key(key); return isv_key_proto; } GurobiInitializerProto StreamableGurobiInitArguments::Proto() const { GurobiInitializerProto params_proto; if (isv_key) { *params_proto.mutable_isv_key() = isv_key->Proto(); } return params_proto; } SolverInitializerProto StreamableSolverInitArguments::Proto() const { SolverInitializerProto params_proto; if (gurobi) { *params_proto.mutable_gurobi() = gurobi->Proto(); } return params_proto; } } // namespace math_opt } // namespace operations_research
[ "corentinl@google.com" ]
corentinl@google.com
521839af3ecc75f422599b63a8da4cdaadf9af5e
a3d9310e2f785dd79b714bd68e1cbaebf71953c4
/dm/stlport/stlport/stl/_bvector.h
6f4f7ddec8f4b69684466e80b1277f3b295041b9
[ "LicenseRef-scancode-stlport-4.5" ]
permissive
lukakostic/Brainfuck-To-C-To-Exe-With-Python2
7bd29fb47e3f19de86a9fd49484f1c1d81820e01
6a119f59da00644fa9dd206078186e8c3a3b3910
refs/heads/master
2020-03-27T05:59:17.351841
2018-09-16T00:04:16
2018-09-16T00:04:16
146,069,434
1
0
null
null
null
null
UTF-8
C++
false
false
27,053
h
/* * * Copyright (c) 1994 * Hewlett-Packard Company * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Copyright (c) 1997 * Moscow Center for SPARC Technology * * Copyright (c) 1999 * Boris Fomitchev * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * */ /* NOTE: This is an internal header file, included by other STL headers. * You should not attempt to use it directly. */ #ifndef _STLP_INTERNAL_BVECTOR_H #define _STLP_INTERNAL_BVECTOR_H #ifndef _STLP_INTERNAL_VECTOR_H # include <stl/_vector.h> # endif #define __WORD_BIT (int(CHAR_BIT*sizeof(unsigned int))) _STLP_BEGIN_NAMESPACE struct _Bit_reference { unsigned int* _M_p; unsigned int _M_mask; _Bit_reference(unsigned int* __x, unsigned int __y) : _M_p(__x), _M_mask(__y) {} public: _Bit_reference() : _M_p(0), _M_mask(0) {} operator bool() const { return !(!(*_M_p & _M_mask)); } _Bit_reference& operator=(bool __x) { if (__x) *_M_p |= _M_mask; else *_M_p &= ~_M_mask; return *this; } _Bit_reference& operator=(const _Bit_reference& __x) { return *this = bool(__x); } bool operator==(const _Bit_reference& __x) const { return bool(*this) == bool(__x); } bool operator<(const _Bit_reference& __x) const { return !bool(*this) && bool(__x); } void flip() { *_M_p ^= _M_mask; } }; inline void swap(_Bit_reference __x, _Bit_reference& __y) { bool __tmp = (bool)__x; __x = __y; __y = __tmp; } struct _Bit_iterator_base; struct _Bit_iterator_base { typedef ptrdiff_t difference_type; unsigned int* _M_p; unsigned int _M_offset; void _M_bump_up() { if (_M_offset++ == __WORD_BIT - 1) { _M_offset = 0; ++_M_p; } } void _M_bump_down() { if (_M_offset-- == 0) { _M_offset = __WORD_BIT - 1; --_M_p; } } _Bit_iterator_base() : _M_p(0), _M_offset(0) {} _Bit_iterator_base(unsigned int* __x, unsigned int __y) : _M_p(__x), _M_offset(__y) {} // _Bit_iterator_base( const _Bit_iterator_base& __x) : _M_p(__x._M_p), _M_offset(__x._M_offset) {} // _Bit_iterator_base& operator = ( const _Bit_iterator_base& __x) { _M_p = __x._M_p ; _M_offset = __x._M_offset ; return *this; } void _M_advance (difference_type __i) { difference_type __n = __i + _M_offset; _M_p += __n / __WORD_BIT; __n = __n % __WORD_BIT; if (__n < 0) { _M_offset = (unsigned int) __n + __WORD_BIT; --_M_p; } else _M_offset = (unsigned int) __n; } difference_type _M_subtract(const _Bit_iterator_base& __x) const { return __WORD_BIT * (_M_p - __x._M_p) + _M_offset - __x._M_offset; } }; inline bool _STLP_CALL operator==(const _Bit_iterator_base& __x, const _Bit_iterator_base& __y) { return __y._M_p == __x._M_p && __y._M_offset == __x._M_offset; } inline bool _STLP_CALL operator!=(const _Bit_iterator_base& __x, const _Bit_iterator_base& __y) { return __y._M_p != __x._M_p || __y._M_offset != __x._M_offset; } inline bool _STLP_CALL operator<(const _Bit_iterator_base& __x, const _Bit_iterator_base& __y) { return __x._M_p < __y._M_p || (__x._M_p == __y._M_p && __x._M_offset < __y._M_offset); } inline bool _STLP_CALL operator>(const _Bit_iterator_base& __x, const _Bit_iterator_base& __y) { return operator <(__y , __x); } inline bool _STLP_CALL operator<=(const _Bit_iterator_base& __x, const _Bit_iterator_base& __y) { return !(__y < __x); } inline bool _STLP_CALL operator>=(const _Bit_iterator_base& __x, const _Bit_iterator_base& __y) { return !(__x < __y); } template <class _Ref, class _Ptr> struct _Bit_iter : public _Bit_iterator_base { typedef _Ref reference; typedef _Ptr pointer; typedef _Bit_iter<_Ref, _Ptr> _Self; typedef random_access_iterator_tag iterator_category; typedef bool value_type; typedef ptrdiff_t difference_type; typedef size_t size_type; _Bit_iter(unsigned int* __x, unsigned int __y) : _Bit_iterator_base(__x, __y) {} _Bit_iter() {} _Bit_iter(const _Bit_iter<_Bit_reference, _Bit_reference*>& __x): _Bit_iterator_base((const _Bit_iterator_base&)__x) {} // _Self& operator = (const _Bit_iter<_Bit_reference, _Bit_reference*>& __x) // { (_Bit_iterator_base&)*this = (const _Bit_iterator_base&)__x; return *this; } reference operator*() const { return _Bit_reference(_M_p, 1UL << _M_offset); } _Self& operator++() { _M_bump_up(); return *this; } _Self operator++(int) { _Self __tmp = *this; _M_bump_up(); return __tmp; } _Self& operator--() { _M_bump_down(); return *this; } _Self operator--(int) { _Self __tmp = *this; _M_bump_down(); return __tmp; } _Self& operator+=(difference_type __i) { _M_advance(__i); return *this; } _Self& operator-=(difference_type __i) { *this += -__i; return *this; } _Self operator+(difference_type __i) const { _Self __tmp = *this; return __tmp += __i; } _Self operator-(difference_type __i) const { _Self __tmp = *this; return __tmp -= __i; } difference_type operator-(const _Self& __x) const { return _M_subtract(__x); } reference operator[](difference_type __i) { return *(*this + __i); } }; template <class _Ref, class _Ptr> inline _Bit_iter<_Ref,_Ptr> _STLP_CALL operator+(ptrdiff_t __n, const _Bit_iter<_Ref, _Ptr>& __x) { return __x + __n; } # ifdef _STLP_USE_OLD_HP_ITERATOR_QUERIES inline random_access_iterator_tag iterator_category(const _Bit_iterator_base&) {return random_access_iterator_tag();} inline ptrdiff_t* distance_type(const _Bit_iterator_base&) {return (ptrdiff_t*)0;} inline bool* value_type(const _Bit_iter<_Bit_reference, _Bit_reference*>&) {return (bool*)0;} inline bool* value_type(const _Bit_iter<bool, const bool*>&) {return (bool*)0;} # endif typedef _Bit_iter<bool, const bool*> _Bit_const_iterator; typedef _Bit_iter<_Bit_reference, _Bit_reference*> _Bit_iterator; // Bit-vector base class, which encapsulates the difference between // old SGI-style allocators and standard-conforming allocators. template <class _Alloc> class _Bvector_base { public: _STLP_FORCE_ALLOCATORS(bool, _Alloc) typedef typename _Alloc_traits<bool, _Alloc>::allocator_type allocator_type; typedef unsigned int __chunk_type; typedef typename _Alloc_traits<__chunk_type, _Alloc>::allocator_type __chunk_allocator_type; allocator_type get_allocator() const { return _STLP_CONVERT_ALLOCATOR((const __chunk_allocator_type&)_M_end_of_storage, bool); } static allocator_type __get_dfl_allocator() { return allocator_type(); } _Bvector_base(const allocator_type& __a) : _M_start(), _M_finish(), _M_end_of_storage(_STLP_CONVERT_ALLOCATOR(__a, __chunk_type), (__chunk_type*)0) { } ~_Bvector_base() { _M_deallocate(); } protected: unsigned int* _M_bit_alloc(size_t __n) { return _M_end_of_storage.allocate((__n + __WORD_BIT - 1)/__WORD_BIT); } void _M_deallocate() { if (_M_start._M_p) _M_end_of_storage.deallocate(_M_start._M_p, _M_end_of_storage._M_data - _M_start._M_p); } _Bit_iterator _M_start; _Bit_iterator _M_finish; _STLP_alloc_proxy<__chunk_type*, __chunk_type, __chunk_allocator_type> _M_end_of_storage; }; // The next few lines are confusing. What we're doing is declaring a // partial specialization of vector<T, Alloc> if we have the necessary // compiler support. Otherwise, we define a class bit_vector which uses // the default allocator. #if defined(_STLP_CLASS_PARTIAL_SPECIALIZATION) && ! defined(_STLP_NO_BOOL) && ! defined (__SUNPRO_CC) # define _STLP_VECBOOL_TEMPLATE # define __BVEC_TMPL_HEADER template <class _Alloc> #else # undef _STLP_VECBOOL_TEMPLATE # ifdef _STLP_NO_BOOL # define __BVEC_TMPL_HEADER # else # define __BVEC_TMPL_HEADER _STLP_TEMPLATE_NULL # endif # if !(defined(__MRC__)||(defined(__SC__)&&!defined(__DMC__))) //*TY 12/17/2000 - # define _Alloc _STLP_DEFAULT_ALLOCATOR(bool) # else # define _Alloc allocator<bool> # endif #endif #ifdef _STLP_NO_BOOL # define __BVECTOR_QUALIFIED bit_vector # define __BVECTOR bit_vector #else # ifdef _STLP_VECBOOL_TEMPLATE # define __BVECTOR_QUALIFIED __WORKAROUND_DBG_RENAME(vector) <bool, _Alloc> # else # define __BVECTOR_QUALIFIED __WORKAROUND_DBG_RENAME(vector) <bool, allocator<bool> > # endif #if defined (_STLP_PARTIAL_SPEC_NEEDS_TEMPLATE_ARGS) # define __BVECTOR __BVECTOR_QUALIFIED #else # define __BVECTOR __WORKAROUND_DBG_RENAME(vector) #endif #endif __BVEC_TMPL_HEADER class __BVECTOR_QUALIFIED : public _Bvector_base<_Alloc > { typedef _Bvector_base<_Alloc > _Base; typedef __BVECTOR_QUALIFIED _Self; public: typedef bool value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Bit_reference reference; typedef bool const_reference; typedef _Bit_reference* pointer; typedef const bool* const_pointer; typedef random_access_iterator_tag _Iterator_category; typedef _Bit_iterator iterator; typedef _Bit_const_iterator const_iterator; #if defined ( _STLP_CLASS_PARTIAL_SPECIALIZATION ) typedef _STLP_STD::reverse_iterator<const_iterator> const_reverse_iterator; typedef _STLP_STD::reverse_iterator<iterator> reverse_iterator; #else /* _STLP_CLASS_PARTIAL_SPECIALIZATION */ # if defined (_STLP_MSVC50_COMPATIBILITY) typedef _STLP_STD::reverse_iterator<const_iterator, value_type, const_reference, const_pointer, difference_type> const_reverse_iterator; typedef _STLP_STD::reverse_iterator<iterator, value_type, reference, reference*, difference_type> reverse_iterator; # else typedef _STLP_STD::reverse_iterator<const_iterator, value_type, const_reference, difference_type> const_reverse_iterator; typedef _STLP_STD::reverse_iterator<iterator, value_type, reference, difference_type> reverse_iterator; # endif #endif /* _STLP_CLASS_PARTIAL_SPECIALIZATION */ # ifdef _STLP_VECBOOL_TEMPLATE typedef typename _Bvector_base<_Alloc >::allocator_type allocator_type; typedef typename _Bvector_base<_Alloc >::__chunk_type __chunk_type ; # else typedef _Bvector_base<_Alloc >::allocator_type allocator_type; typedef _Bvector_base<_Alloc >::__chunk_type __chunk_type ; # endif protected: void _M_initialize(size_type __n) { unsigned int* __q = this->_M_bit_alloc(__n); this->_M_end_of_storage._M_data = __q + (__n + __WORD_BIT - 1)/__WORD_BIT; this->_M_start = iterator(__q, 0); this->_M_finish = this->_M_start + difference_type(__n); } void _M_insert_aux(iterator __position, bool __x) { if (this->_M_finish._M_p != this->_M_end_of_storage._M_data) { __copy_backward(__position, this->_M_finish, this->_M_finish + 1, random_access_iterator_tag(), (difference_type*)0 ); *__position = __x; ++this->_M_finish; } else { size_type __len = size() ? 2 * size() : __WORD_BIT; unsigned int* __q = this->_M_bit_alloc(__len); iterator __i = copy(begin(), __position, iterator(__q, 0)); *__i++ = __x; this->_M_finish = copy(__position, end(), __i); this->_M_deallocate(); this->_M_end_of_storage._M_data = __q + (__len + __WORD_BIT - 1)/__WORD_BIT; this->_M_start = iterator(__q, 0); } } #ifdef _STLP_MEMBER_TEMPLATES template <class _InputIterator> void _M_initialize_range(_InputIterator __first, _InputIterator __last, const input_iterator_tag &) { this->_M_start = iterator(); this->_M_finish = iterator(); this->_M_end_of_storage._M_data = 0; for ( ; __first != __last; ++__first) push_back(*__first); } template <class _ForwardIterator> void _M_initialize_range(_ForwardIterator __first, _ForwardIterator __last, const forward_iterator_tag &) { size_type __n = distance(__first, __last); _M_initialize(__n); // copy(__first, __last, _M_start); copy(__first, __last, this->_M_start); // dwa 12/22/99 -- resolving ambiguous reference. } template <class _InputIterator> void _M_insert_range(iterator __pos, _InputIterator __first, _InputIterator __last, const input_iterator_tag &) { for ( ; __first != __last; ++__first) { __pos = insert(__pos, *__first); ++__pos; } } template <class _ForwardIterator> void _M_insert_range(iterator __position, _ForwardIterator __first, _ForwardIterator __last, const forward_iterator_tag &) { if (__first != __last) { size_type __n = distance(__first, __last); if (capacity() - size() >= __n) { __copy_backward(__position, end(), this->_M_finish + difference_type(__n), random_access_iterator_tag(), (difference_type*)0 ); copy(__first, __last, __position); this->_M_finish += difference_type(__n); } else { size_type __len = size() + (max)(size(), __n); unsigned int* __q = this->_M_bit_alloc(__len); iterator __i = copy(begin(), __position, iterator(__q, 0)); __i = copy(__first, __last, __i); this->_M_finish = copy(__position, end(), __i); this->_M_deallocate(); this->_M_end_of_storage._M_data = __q + (__len + __WORD_BIT - 1)/__WORD_BIT; this->_M_start = iterator(__q, 0); } } } #endif /* _STLP_MEMBER_TEMPLATES */ public: iterator begin() { return this->_M_start; } const_iterator begin() const { return this->_M_start; } iterator end() { return this->_M_finish; } const_iterator end() const { return this->_M_finish; } reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } size_type size() const { return size_type(end() - begin()); } size_type max_size() const { return size_type(-1); } size_type capacity() const { return size_type(const_iterator(this->_M_end_of_storage._M_data, 0) - begin()); } bool empty() const { return begin() == end(); } reference operator[](size_type __n) { return *(begin() + difference_type(__n)); } const_reference operator[](size_type __n) const { return *(begin() + difference_type(__n)); } void _M_range_check(size_type __n) const { if (__n >= this->size()) __stl_throw_range_error("vector<bool>"); } reference at(size_type __n) { _M_range_check(__n); return (*this)[__n]; } const_reference at(size_type __n) const { _M_range_check(__n); return (*this)[__n]; } explicit __BVECTOR(const allocator_type& __a = allocator_type()) : _Bvector_base<_Alloc >(__a) {} __BVECTOR(size_type __n, bool __val, const allocator_type& __a = allocator_type()) : _Bvector_base<_Alloc >(__a) { _M_initialize(__n); fill(this->_M_start._M_p, (__chunk_type*)(this->_M_end_of_storage._M_data), __val ? ~0 : 0); } explicit __BVECTOR(size_type __n) : _Bvector_base<_Alloc >(allocator_type()) { _M_initialize(__n); fill(this->_M_start._M_p, (__chunk_type*)(this->_M_end_of_storage._M_data), 0); } __BVECTOR(const _Self& __x) : _Bvector_base<_Alloc >(__x.get_allocator()) { _M_initialize(__x.size()); copy(__x.begin(), __x.end(), this->_M_start); } #if defined (_STLP_MEMBER_TEMPLATES) template <class _Integer> void _M_initialize_dispatch(_Integer __n, _Integer __x, const __true_type&) { _M_initialize(__n); fill(this->_M_start._M_p, this->_M_end_of_storage._M_data, __x ? ~0 : 0); } template <class _InputIterator> void _M_initialize_dispatch(_InputIterator __first, _InputIterator __last, const __false_type&) { _M_initialize_range(__first, __last, _STLP_ITERATOR_CATEGORY(__first, _InputIterator)); } # ifdef _STLP_NEEDS_EXTRA_TEMPLATE_CONSTRUCTORS // Check whether it's an integral type. If so, it's not an iterator. template <class _InputIterator> __BVECTOR(_InputIterator __first, _InputIterator __last) : _Base(allocator_type()) { typedef typename _Is_integer<_InputIterator>::_Integral _Integral; _M_initialize_dispatch(__first, __last, _Integral()); } # endif template <class _InputIterator> __BVECTOR(_InputIterator __first, _InputIterator __last, const allocator_type& __a _STLP_ALLOCATOR_TYPE_DFL) : _Base(__a) { typedef typename _Is_integer<_InputIterator>::_Integral _Integral; _M_initialize_dispatch(__first, __last, _Integral()); } #else /* _STLP_MEMBER_TEMPLATES */ __BVECTOR(const_iterator __first, const_iterator __last, const allocator_type& __a = allocator_type()) : _Bvector_base<_Alloc >(__a) { size_type __n = distance(__first, __last); _M_initialize(__n); copy(__first, __last, this->_M_start); } __BVECTOR(const bool* __first, const bool* __last, const allocator_type& __a = allocator_type()) : _Bvector_base<_Alloc >(__a) { size_type __n = distance(__first, __last); _M_initialize(__n); copy(__first, __last, this->_M_start); } #endif /* _STLP_MEMBER_TEMPLATES */ ~__BVECTOR() { } __BVECTOR_QUALIFIED& operator=(const __BVECTOR_QUALIFIED& __x) { if (&__x == this) return *this; if (__x.size() > capacity()) { this->_M_deallocate(); _M_initialize(__x.size()); } copy(__x.begin(), __x.end(), begin()); this->_M_finish = begin() + difference_type(__x.size()); return *this; } // assign(), a generalized assignment member function. Two // versions: one that takes a count, and one that takes a range. // The range version is a member template, so we dispatch on whether // or not the type is an integer. void _M_fill_assign(size_t __n, bool __x) { if (__n > size()) { fill(this->_M_start._M_p, (__chunk_type*)(this->_M_end_of_storage._M_data), __x ? ~0 : 0); insert(end(), __n - size(), __x); } else { erase(begin() + __n, end()); fill(this->_M_start._M_p, (__chunk_type*)(this->_M_end_of_storage._M_data), __x ? ~0 : 0); } } void assign(size_t __n, bool __x) { _M_fill_assign(__n, __x); } #ifdef _STLP_MEMBER_TEMPLATES template <class _InputIterator> void assign(_InputIterator __first, _InputIterator __last) { typedef typename _Is_integer<_InputIterator>::_Integral _Integral; _M_assign_dispatch(__first, __last, _Integral()); } template <class _Integer> void _M_assign_dispatch(_Integer __n, _Integer __val, const __true_type&) { _M_fill_assign((size_t) __n, (bool) __val); } template <class _InputIter> void _M_assign_dispatch(_InputIter __first, _InputIter __last, const __false_type&) { _M_assign_aux(__first, __last, _STLP_ITERATOR_CATEGORY(__first, _InputIter)); } template <class _InputIterator> void _M_assign_aux(_InputIterator __first, _InputIterator __last, const input_iterator_tag &) { iterator __cur = begin(); for ( ; __first != __last && __cur != end(); ++__cur, ++__first) *__cur = *__first; if (__first == __last) erase(__cur, end()); else insert(end(), __first, __last); } template <class _ForwardIterator> void _M_assign_aux(_ForwardIterator __first, _ForwardIterator __last, const forward_iterator_tag &) { size_type __len = distance(__first, __last); if (__len < size()) erase(copy(__first, __last, begin()), end()); else { _ForwardIterator __mid = __first; advance(__mid, size()); copy(__first, __mid, begin()); insert(end(), __mid, __last); } } #endif /* _STLP_MEMBER_TEMPLATES */ void reserve(size_type __n) { if (capacity() < __n) { unsigned int* __q = this->_M_bit_alloc(__n); _Bit_iterator __z(__q, 0); this->_M_finish = copy(begin(), end(), __z); this->_M_deallocate(); this->_M_start = iterator(__q, 0); this->_M_end_of_storage._M_data = __q + (__n + __WORD_BIT - 1)/__WORD_BIT; } } reference front() { return *begin(); } const_reference front() const { return *begin(); } reference back() { return *(end() - 1); } const_reference back() const { return *(end() - 1); } void push_back(bool __x) { if (this->_M_finish._M_p != this->_M_end_of_storage._M_data) { *(this->_M_finish) = __x; ++this->_M_finish; } else _M_insert_aux(end(), __x); } void swap(__BVECTOR_QUALIFIED& __x) { _STLP_STD::swap(this->_M_start, __x._M_start); _STLP_STD::swap(this->_M_finish, __x._M_finish); _STLP_STD::swap(this->_M_end_of_storage, __x._M_end_of_storage); } iterator insert(iterator __position, bool __x = bool()) { difference_type __n = __position - begin(); if (this->_M_finish._M_p != this->_M_end_of_storage._M_data && __position == end()) { *(this->_M_finish) = __x; ++this->_M_finish; } else _M_insert_aux(__position, __x); return begin() + __n; } #if defined ( _STLP_MEMBER_TEMPLATES ) template <class _Integer> void _M_insert_dispatch(iterator __pos, _Integer __n, _Integer __x, const __true_type&) { _M_fill_insert(__pos, (size_type) __n, (bool) __x); } template <class _InputIterator> void _M_insert_dispatch(iterator __pos, _InputIterator __first, _InputIterator __last, const __false_type&) { _M_insert_range(__pos, __first, __last, _STLP_ITERATOR_CATEGORY(__first, _InputIterator)); } // Check whether it's an integral type. If so, it's not an iterator. template <class _InputIterator> void insert(iterator __position, _InputIterator __first, _InputIterator __last) { typedef typename _Is_integer<_InputIterator>::_Integral _Is_Integral; _M_insert_dispatch(__position, __first, __last, _Is_Integral()); } #else /* _STLP_MEMBER_TEMPLATES */ void insert(iterator __position, const_iterator __first, const_iterator __last) { if (__first == __last) return; size_type __n = distance(__first, __last); if (capacity() - size() >= __n) { __copy_backward(__position, end(), this->_M_finish + __n, random_access_iterator_tag(), (difference_type*)0 ); copy(__first, __last, __position); this->_M_finish += __n; } else { size_type __len = size() + (max)(size(), __n); unsigned int* __q = this->_M_bit_alloc(__len); iterator __i = copy(begin(), __position, iterator(__q, 0)); __i = copy(__first, __last, __i); this->_M_finish = copy(__position, end(), __i); this->_M_deallocate(); this->_M_end_of_storage._M_data = __q + (__len + __WORD_BIT - 1)/__WORD_BIT; this->_M_start = iterator(__q, 0); } } void insert(iterator __position, const bool* __first, const bool* __last) { if (__first == __last) return; size_type __n = distance(__first, __last); if (capacity() - size() >= __n) { __copy_backward(__position, end(), this->_M_finish + __n, random_access_iterator_tag(), (difference_type*)0 ); copy(__first, __last, __position); this->_M_finish += __n; } else { size_type __len = size() + (max)(size(), __n); unsigned int* __q = this->_M_bit_alloc(__len); iterator __i = copy(begin(), __position, iterator(__q, 0)); __i = copy(__first, __last, __i); this->_M_finish = copy(__position, end(), __i); this->_M_deallocate(); this->_M_end_of_storage._M_data = __q + (__len + __WORD_BIT - 1)/__WORD_BIT; this->_M_start = iterator(__q, 0); } } #endif /* _STLP_MEMBER_TEMPLATES */ void _M_fill_insert(iterator __position, size_type __n, bool __x) { if (__n == 0) return; if (capacity() - size() >= __n) { __copy_backward(__position, end(), this->_M_finish + difference_type(__n), random_access_iterator_tag(), (difference_type*)0 ); fill(__position, __position + difference_type(__n), __x); this->_M_finish += difference_type(__n); } else { size_type __len = size() + (max)(size(), __n); unsigned int* __q = this->_M_bit_alloc(__len); iterator __i = copy(begin(), __position, iterator(__q, 0)); fill_n(__i, __n, __x); this->_M_finish = copy(__position, end(), __i + difference_type(__n)); this->_M_deallocate(); this->_M_end_of_storage._M_data = __q + (__len + __WORD_BIT - 1)/__WORD_BIT; this->_M_start = iterator(__q, 0); } } void insert(iterator __position, size_type __n, bool __x) { _M_fill_insert(__position, __n, __x); } void pop_back() { --this->_M_finish; } iterator erase(iterator __position) { if (__position + 1 != end()) copy(__position + 1, end(), __position); --this->_M_finish; return __position; } iterator erase(iterator __first, iterator __last) { this->_M_finish = copy(__last, end(), __first); return __first; } void resize(size_type __new_size, bool __x = bool()) { if (__new_size < size()) erase(begin() + difference_type(__new_size), end()); else insert(end(), __new_size - size(), __x); } void flip() { for (unsigned int* __p = this->_M_start._M_p; __p != this->_M_end_of_storage._M_data; ++__p) *__p = ~*__p; } void clear() { erase(begin(), end()); } }; # if defined ( _STLP_NO_BOOL ) || defined (__HP_aCC) // fixed soon (03/17/2000) __BVEC_TMPL_HEADER inline void swap(__BVECTOR_QUALIFIED& __x, __BVECTOR_QUALIFIED& __y) { __x.swap(__y); } __BVEC_TMPL_HEADER inline bool _STLP_CALL operator==(const __BVECTOR_QUALIFIED& __x, const __BVECTOR_QUALIFIED& __y) { return (__x.size() == __y.size() && equal(__x.begin(), __x.end(), __y.begin())); } __BVEC_TMPL_HEADER inline bool _STLP_CALL operator<(const __BVECTOR_QUALIFIED& __x, const __BVECTOR_QUALIFIED& __y) { return lexicographical_compare(__x.begin(), __x.end(), __y.begin(), __y.end()); } _STLP_RELOPS_OPERATORS( __BVEC_TMPL_HEADER, __BVECTOR_QUALIFIED ) # endif /* NO_BOOL */ #if !defined (_STLP_NO_BOOL) // This typedef is non-standard. It is provided for backward compatibility. typedef __WORKAROUND_DBG_RENAME(vector) <bool, allocator<bool> > bit_vector; #endif _STLP_END_NAMESPACE #undef _Alloc #undef _STLP_VECBOOL_TEMPLATE #undef __BVECTOR #undef __BVECTOR_QUALIFIED #undef __BVEC_TMPL_HEADER # undef __WORD_BIT #endif /* _STLP_INTERNAL_BVECTOR_H */ // Local Variables: // mode:C++ // End:
[ "3luka1@gmail.com" ]
3luka1@gmail.com
8d62d96deab6cf3079526ce2feced20934ca328d
c244fd2cdb00bb7850aeb332e450f9531e75c3e3
/src/util/outkinematics.cxx
0847da2c8c41e25bf2c6e642b0a8664888a82308
[]
no_license
matplo/jetty
22dbc215d349d18bc99d9a70391f0eb6a4b49dea
d5c3414341c03ea7487c6cbdf872be7c648791c4
refs/heads/master
2021-01-25T10:56:19.107389
2017-11-10T23:33:01
2017-11-10T23:33:01
93,893,930
1
3
null
2017-07-18T04:22:35
2017-06-09T20:18:55
C++
UTF-8
C++
false
false
2,589
cxx
#include "outkinematics.h" #include <Pythia8/Pythia.h> #include <iostream> #include <sstream> #include <iomanip> #include <cmath> #include <string> namespace PyUtil { // OutKinematics implementation OutKinematics::OutKinematics(const Pythia8::Pythia &pythia, bool includeHard) : i_p_z({pythia.event[1].pz(), pythia.event[2].pz()}) , f_p_z({0, 0}) , d_p_z({0, 0}) , mA(0.93827) , mB(0.93827) { _calculate(pythia, includeHard); } OutKinematics::OutKinematics() : i_p_z({0, 0}) , f_p_z({0, 0}) , d_p_z({0, 0}) , mA(0.93827) , mB(0.93827) { ; } OutKinematics::OutKinematics(const OutKinematics &o) : i_p_z({0, 0}) , f_p_z({0, 0}) , d_p_z({0, 0}) , mA(0.93827) , mB(0.93827) { i_p_z = o.i_p_z; f_p_z = o.f_p_z; d_p_z = o.d_p_z; mA = o.mA; mB = o.mB; } void OutKinematics::_calculate(const Pythia8::Pythia &pythia, bool includeHard) { auto &event = pythia.event; for (unsigned int i = 0; i < event.size(); i++) { auto &p = event[i]; auto im = has_beam_mother(p); if (im > 0) { // cout << i << " " << pypart_to_str(p) << endl; if (im == 1 || im == 3) { // cout << " mother: " << 1 << " " << pypart_to_str(event[1]) << endl; f_p_z[0] += p.pz(); } if (im == 2 || im == 3) { // cout << " mother: " << 2 << " " << pypart_to_str(event[2]) << endl; f_p_z[1] += p.pz(); } } } if (pythia.info.code() == 101) // non-diffractive { if (pythia.info.hasSub() && includeHard == true) { //f_p_z[0] += event[3].pz(); //incoming partons to the hard process //f_p_z[1] += event[4].pz(); //incoming partons to the hard process f_p_z[0] += event[5].pT(); //outgoing partons to the hard process f_p_z[1] += event[6].pT(); //outgoing partons to the hard process } } for ( int i : {0, 1}) { d_p_z[i] = std::fabs(i_p_z[i] - f_p_z[i]); // std::cout << "=> remaining p_z_" << i+1 << " = " << f_p_z[i] << " delta p_z = " << d_p_z[i] << std::endl; } } double OutKinematics::sqrts(double eA, double eB, double _mA, double _mB) const { double _eA = std::fabs(eA); double _eB = std::fabs(eB); double _pA = std::sqrt(_eA * _eA - _mA * _mA); double _pB = std::sqrt(_eB * _eB - _mB * _mB); double eCM = std::sqrt( std::pow(_eA + _eB, 2.) - std::pow(_pA + (-1. * _pB), 2.) ); return eCM; } double OutKinematics::sqrts(double eA, double eB) const { return sqrts(eA, eB, mA, mB); } double OutKinematics::sqrts_i() const { return sqrts(i_p_z[0], i_p_z[1]); } double OutKinematics::sqrts_f() const { return sqrts(f_p_z[0], f_p_z[1]); } };
[ "ploskon@gmail.com" ]
ploskon@gmail.com
acfcaf8a52654e02276ea0982c97de07b57e16c9
281f9726f082a5e0883d360f0aaa21ba71b9854e
/lib/AFE-Web-Server/AFE-Web-Server.h
e2edc8ebd72d3c220c2b0f279bcc58739f4f0f7c
[ "MIT" ]
permissive
tschaban/nxtBikeMonitor
9e7eb37abe7a0d7d2e7cfd81556e9ca138f69fa1
f4299d4835ce096bfbb0f90ea5f3a8c33302e340
refs/heads/master
2020-04-20T12:51:58.499319
2019-02-10T22:39:05
2019-02-10T22:39:05
168,853,888
0
0
null
null
null
null
UTF-8
C++
false
false
2,319
h
/* AFE Firmware for smart home devices LICENSE: https://github.com/tschaban/AFE-Firmware/blob/master/LICENSE DOC: https://www.smartnydom.pl/afe-firmware-pl/ */ #ifndef _AFE_Web_Server_h #define _AFE_Web_Server_h #if defined(ARDUINO) && ARDUINO >= 100 #include "arduino.h" #else #include "WProgram.h" #endif #include <AFE-Configuration-Panel.h> #include <AFE-Data-Access.h> #include <AFE-Defaults.h> #include <AFE-OTA.h> #include <ESP8266WebServer.h> #ifdef DEBUG #include <Streaming.h> #endif class AFEWebServer { private: AFEDataAccess Data; ESP8266WebServer server; AFEConfigurationPanel ConfigurationPanel; ESP8266HTTPUpdateServer httpUpdater; // Class used for firmware upgrade AFEDevice Device; HTTPCOMMAND httpCommand; // It stores last HTTP API request boolean receivedHTTPCommand = false; // Once HTTP API requet is recieved it's set to true boolean _refreshConfiguration = false; // when it's set to true device // configuration is refreshed. Required // by generate() method /* Method pushes HTML site from WebServer */ void publishHTML(String page); /* Method gets url Option parameter value */ String getOptionName(); /* Method gets url cmd parameter value */ uint8_t getCommand(); /* Methods get POST data (for saveing) */ DEVICE getDeviceData(); NETWORK getNetworkData(); RELAY getRelayData(uint8_t id); SWITCH getSwitchData(uint8_t id); LED getLEDData(uint8_t id); uint8_t getSystemLEDData(); DS18B20 getDS18B20Data(); NTC10K getNTC10KData(); public: AFEWebServer(); /* Method initialize WebServer and Updater server */ void begin(); /* Method listens for HTTP requests */ void listener(); /* Method adds URL for listen */ void handle(const char *uri, ESP8266WebServer::THandlerFunction handler); /* Method generate HTML side. It reads also data from HTTP requests arguments * and pass them to Configuration Panel class */ void generate(); /* Method listens for HTTP API requests. If get True command is in httpCommand */ boolean httpAPIlistener(); /* Method reads HTTP API Command */ HTTPCOMMAND getHTTPCommand(); /* Method pushes JSON response to HTTP API request */ void sendJSON(String json); }; #endif
[ "github@adrian.czabanowski.com" ]
github@adrian.czabanowski.com
62624a15b0da4a59a54180cb0fb43266346092e6
7c2420e0a7c8b28a425a7ed5466b527cb4f27d9b
/sources/degg/include/J4DEgg.hh
10905570e2323d927e1cc4a00e9221af51ed6454
[]
no_license
nobuchiba1006/DOUMEKI
d1705054b95b79f9089ec5cff427513bd9fd5745
7c17ba485b616df5e15764d148d4fec358d7b480
refs/heads/main_woroot
2023-07-30T15:16:59.589294
2021-09-30T02:52:06
2021-09-30T02:52:06
411,891,541
0
0
null
2021-09-30T02:52:06
2021-09-30T02:07:10
C++
UTF-8
C++
false
false
1,559
hh
// $Id: J4DEgg.hh,v 1.1.1.1 2004/08/26 07:04:26 hoshina Exp $ #ifndef __J4DEgg__hh #define __J4DEgg__hh //************************************************************************* //* -------------------- //* J4DEgg //* -------------------- //* (Description) //* J4DEgg discribes the spherical region for DEgg. //* It is filled with the air. //* Mother class : J4VDEggDetectorComponent //* //* (Update Record) //* 2003/09/27 K.Hoshina Original version. //************************************************************************* #include "J4EggOkamotoGlass.hh" #include "J4DEggInside.hh" #include "J4VDetectorComponent.hh" class G4VSolid; //===================================================================== //--------------------- // class definition //--------------------- class J4DEgg : public J4VDetectorComponent { public: J4DEgg(J4VDetectorComponent *parent = 0, G4int nclones = 1, G4int nbrothers = 1, G4int me = 0, G4int copyno = -1 ); virtual ~J4DEgg(); virtual void InstallIn(J4VComponent *mother, G4RotationMatrix *prot = 0, const G4ThreeVector &tlate = G4ThreeVector() ); virtual void Draw() ; virtual void Print() const ; private: void Assemble(); void Cabling (); private: static G4String fFirstName; J4EggOkamotoGlass * fOkamoto; J4DEggInside * fInside; J4DEggInside * fInsideDown; }; #endif
[ "shimizu@hepburn.s.chiba-u.ac.jp" ]
shimizu@hepburn.s.chiba-u.ac.jp
29fe6191f5431b69e4774e25c1b532cbdea1e9bf
8b7fdf5100ebd616eb5ac9f2b14d1c8d6c4c0d8e
/frameworks/core/components/data_panel/render_data_panel.h
ae13a3f26a917a011a6eb860c2a5e34a207012a7
[ "Apache-2.0" ]
permissive
openharmony-sig-ci/ace_ace_engine
13f2728bce323b67ac94a34d2e9c0a941227c402
05ebe2d6d2674777f5dc64fd735088dcf1a42cd9
refs/heads/master
2023-07-25T02:26:10.854405
2021-09-10T01:48:59
2021-09-10T01:48:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,126
h
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_DATA_PANEL_RENDER_DATA_PANEL_H #define FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_DATA_PANEL_RENDER_DATA_PANEL_H #include <chrono> #include "core/animation/animator.h" #include "core/animation/curve_animation.h" #include "core/components/data_panel/data_panel_component.h" #include "core/pipeline/base/component.h" #include "core/pipeline/base/render_node.h" namespace OHOS::Ace { class RenderDataPanel : public RenderNode { DECLARE_ACE_TYPE(RenderDataPanel, RenderNode); public: ~RenderDataPanel() override = default; void Update(const RefPtr<Component>& component) override; static RefPtr<RenderNode> Create(); virtual void PlayAnimation() = 0; virtual void StopAnimation() = 0; protected: RenderDataPanel(); const Size Measure(); void PerformLayout() override; virtual void PrepareAnimation() = 0; void OnVisibleChanged() override; void OnHiddenChanged(bool hidden) override; void AnimationChanged(); MeasureType measureType_ = MeasureType::PARENT; ChartType type_ = ChartType::LINE; Dimension thickness_; Color backgroundTrack_ = Color::FromString("#08000000"); bool autoScale_ = false; RefPtr<Animator> animator_; RefPtr<Animator> progressTransitionController_; double rotateAngle_ = 0.0; double sweepDegree_ = 0.0; double percent_ = 0.0; bool useEffect_ = false; bool animationInitialized_ = false; bool isUserSetPlay_ = false; double previousPercentValue_ = 0.0; double percentChange_ = 0.0; std::chrono::steady_clock::time_point previousUpdateTime_ = std::chrono::steady_clock::now(); std::chrono::duration<double> animationDuring_; bool needReplayAnimation_ = false; private: // data panel default height and width Dimension height_; Dimension width_; }; class RenderProgressDataPanel : public RenderDataPanel { DECLARE_ACE_TYPE(RenderProgressDataPanel, RenderDataPanel); public: static RefPtr<RenderNode> Create(); void Update(const RefPtr<Component>& component) override; const Color& GetStartColor() const { return startColor_; } const Color& GetEndColor() const { return endColor_; } bool IsRepaintBoundary() const override { return true; } void PlayAnimation() override { if (animator_) { animator_->Play(); isUserSetPlay_ = true; } if (!isLoading_ && progressTransitionController_) { progressTransitionController_->Play(); isUserSetPlay_ = true; } } void StopAnimation() override { if (animator_) { animator_->Stop(); isUserSetPlay_ = false; } if (!isLoading_ && progressTransitionController_) { progressTransitionController_->Stop(); isUserSetPlay_ = false; } } protected: void PrepareAnimation() override; double GetProgress() const { return progress_; } private: Color startColor_; Color endColor_; double progress_ = 0.0; bool isLoading_ = false; RefPtr<CurveAnimation<double>> animation_; RefPtr<CurveAnimation<double>> transitionAnimation_; }; class RenderPercentageDataPanel : public RenderDataPanel { DECLARE_ACE_TYPE(RenderPercentageDataPanel, RenderDataPanel); public: static RefPtr<RenderNode> Create(); void Update(const RefPtr<Component>& component) override; void PlayAnimation() override { if (animator_) { animator_->Play(); isUserSetPlay_ = true; } } void StopAnimation() override { if (animator_) { animator_->Pause(); isUserSetPlay_ = false; } } protected: void PrepareAnimation() override; double GetTotalValue() const { return totalValue_; } const std::vector<Segment>& GetSegments() const { return segments_; } double GetStartDegree() const { return startDegree_; } double GetSweepDegree() const { return sweepDegree_; } double animationPercent_ = 0.0; private: double startDegree_ = 0.0; double sweepDegree_ = 360.0; std::vector<Segment> segments_; double totalValue_ = 0.0; RefPtr<CurveAnimation<double>> animation_; }; } // namespace OHOS::Ace #endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_DATA_PANEL_RENDER_DATA_PANEL_H
[ "mamingshuai1@huawei.com" ]
mamingshuai1@huawei.com
1b818946b8c09f00e394cae7446b48053edad0b4
227ff335db9362cd0303f2dd4368c62ed16fbf74
/CPPWorkspace/SFMLTest/main.cpp
236fe87026a409b5d6c895ccc6f02ed790bd60cc
[]
no_license
jearmstrong21/OldJavaProjects
81ffa3f03ca41ce766b73cb43bb1cf89d08670f2
0bf7b004b97487f6962ed0f4711a7ca7d20ee293
refs/heads/master
2020-05-03T12:35:05.421923
2019-03-31T02:01:22
2019-03-31T02:01:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
73
cpp
#include <iostream> int main() { printf("Hello World!"); return 0; }
[ "jarmstrong21@saddleback.edu" ]
jarmstrong21@saddleback.edu
bb838631ec76bd63a61f2c0de76d416eb10bf6a0
e99c20155e9b08c7e7598a3f85ccaedbd127f632
/ sjtu-project-pipe/thirdparties/VTK.Net/src/Filtering/vtkCachedStreamingDemandDrivenPipeline.cxx
f658b32cf7c4ec9463f1a5b85806c2db37c74c11
[ "BSD-3-Clause" ]
permissive
unidevop/sjtu-project-pipe
38f00462d501d9b1134ce736bdfbfe4f9d075e4a
5a09f098db834d5276a2921d861ef549961decbe
refs/heads/master
2020-05-16T21:32:47.772410
2012-03-19T01:24:14
2012-03-19T01:24:14
38,281,086
1
1
null
null
null
null
UTF-8
C++
false
false
10,654
cxx
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkCachedStreamingDemandDrivenPipeline.cxx,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkCachedStreamingDemandDrivenPipeline.h" #include "vtkInformationIntegerKey.h" #include "vtkInformationIntegerVectorKey.h" #include "vtkObjectFactory.h" #include "vtkAlgorithm.h" #include "vtkAlgorithmOutput.h" #include "vtkImageData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkPointData.h" vtkCxxRevisionMacro(vtkCachedStreamingDemandDrivenPipeline, "$Revision: 1.6 $"); vtkStandardNewMacro(vtkCachedStreamingDemandDrivenPipeline); //---------------------------------------------------------------------------- vtkCachedStreamingDemandDrivenPipeline ::vtkCachedStreamingDemandDrivenPipeline() { this->CacheSize = 0; this->Data = NULL; this->Times = NULL; this->SetCacheSize(10); } //---------------------------------------------------------------------------- vtkCachedStreamingDemandDrivenPipeline ::~vtkCachedStreamingDemandDrivenPipeline() { this->SetCacheSize(0); } //---------------------------------------------------------------------------- void vtkCachedStreamingDemandDrivenPipeline::SetCacheSize(int size) { int idx; if (size == this->CacheSize) { return; } this->Modified(); // free the old data for (idx = 0; idx < this->CacheSize; ++idx) { if (this->Data[idx]) { this->Data[idx]->Delete(); this->Data[idx] = NULL; } } if (this->Data) { delete [] this->Data; this->Data = NULL; } if (this->Times) { delete [] this->Times; this->Times = NULL; } this->CacheSize = size; if (size == 0) { return; } this->Data = new vtkDataObject* [size]; this->Times = new unsigned long [size]; for (idx = 0; idx < size; ++idx) { this->Data[idx] = NULL; this->Times[idx] = 0; } } //---------------------------------------------------------------------------- void vtkCachedStreamingDemandDrivenPipeline ::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "CacheSize: " << this->CacheSize << "\n"; } //---------------------------------------------------------------------------- int vtkCachedStreamingDemandDrivenPipeline::Update() { return this->Superclass::Update(); } //---------------------------------------------------------------------------- int vtkCachedStreamingDemandDrivenPipeline::Update(int port) { if(!this->UpdateInformation()) { return 0; } if(port >= 0 && port < this->Algorithm->GetNumberOfOutputPorts()) { int retval = 1; // some streaming filters can request that the pipeline execute multiple // times for a single update do { retval = this->PropagateUpdateExtent(port) && this->UpdateData(port) && retval; } while (this->ContinueExecuting); return retval; } else { return 1; } } //---------------------------------------------------------------------------- int vtkCachedStreamingDemandDrivenPipeline ::NeedToExecuteData(int outputPort, vtkInformationVector** inInfoVec, vtkInformationVector* outInfoVec) { // If no port is specified, check all ports. This behavior is // implemented by the superclass. if(outputPort < 0) { return this->Superclass::NeedToExecuteData(outputPort, inInfoVec, outInfoVec); } // Does the superclass want to execute? We must skip our direct superclass // because it looks at update extents but does not know about the cache if(this->vtkDemandDrivenPipeline::NeedToExecuteData(outputPort, inInfoVec, outInfoVec)) { return 1; } // Has the algorithm asked to be executed again? if(this->ContinueExecuting) { return 1; } // First look through the cached data to see if it is still valid. int i; unsigned long pmt = this->GetPipelineMTime(); for (i = 0; i < this->CacheSize; ++i) { if (this->Data[i] && this->Times[i] < pmt) { this->Data[i]->Delete(); this->Data[i] = NULL; this->Times[i] = 0; } } // We need to check the requested update extent. Get the output // port information and data information. We do not need to check // existence of values because it has already been verified by // VerifyOutputInformation. vtkInformation* outInfo = outInfoVec->GetInformationObject(outputPort); vtkDataObject* dataObject = outInfo->Get(vtkDataObject::DATA_OBJECT()); vtkInformation* dataInfo = dataObject->GetInformation(); if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_PIECES_EXTENT) { int updatePiece = outInfo->Get(UPDATE_PIECE_NUMBER()); int updateNumberOfPieces = outInfo->Get(UPDATE_NUMBER_OF_PIECES()); int updateGhostLevel = outInfo->Get(UPDATE_NUMBER_OF_GHOST_LEVELS()); // check to see if any data in the cache fits this request for (i = 0; i < this->CacheSize; ++i) { if (this->Data[i]) { dataInfo = this->Data[i]->GetInformation(); // Check the unstructured extent. If we do not have the requested // piece, we need to execute. int dataPiece = dataInfo->Get(vtkDataObject::DATA_PIECE_NUMBER()); int dataNumberOfPieces = dataInfo->Get(vtkDataObject::DATA_NUMBER_OF_PIECES()); int dataGhostLevel = dataInfo->Get(vtkDataObject::DATA_NUMBER_OF_GHOST_LEVELS()); if (dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_PIECES_EXTENT && dataPiece == updatePiece && dataNumberOfPieces == updateNumberOfPieces && dataGhostLevel == updateGhostLevel) { // we have a matching data we must copy it to our output, but for // now we don't support polydata return 1; } } } } else if (dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_3D_EXTENT) { // Check the structured extent. If the update extent is outside // of the extent and not empty, we need to execute. int dataExtent[6]; int updateExtent[6]; outInfo->Get(UPDATE_EXTENT(), updateExtent); // check to see if any data in the cache fits this request for (i = 0; i < this->CacheSize; ++i) { if (this->Data[i]) { dataInfo = this->Data[i]->GetInformation(); dataInfo->Get(vtkDataObject::DATA_EXTENT(), dataExtent); if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_3D_EXTENT && !(updateExtent[0] < dataExtent[0] || updateExtent[1] > dataExtent[1] || updateExtent[2] < dataExtent[2] || updateExtent[3] > dataExtent[3] || updateExtent[4] < dataExtent[4] || updateExtent[5] > dataExtent[5]) && (updateExtent[0] <= updateExtent[1] && updateExtent[2] <= updateExtent[3] && updateExtent[4] <= updateExtent[5])) { // we have a match // Pass this data to output. vtkImageData *id = vtkImageData::SafeDownCast(dataObject); vtkImageData *id2 = vtkImageData::SafeDownCast(this->Data[i]); if (id && id2) { id->SetExtent(dataExtent); id->GetPointData()->PassData(id2->GetPointData()); // not sure if we need this dataObject->DataHasBeenGenerated(); return 0; } } } } } // We do need to execute return 1; } //---------------------------------------------------------------------------- int vtkCachedStreamingDemandDrivenPipeline ::ExecuteData(vtkInformation* request, vtkInformationVector** inInfoVec, vtkInformationVector* outInfoVec) { // only works for one in one out algorithms if (request->Get(FROM_OUTPUT_PORT()) != 0) { vtkErrorMacro("vtkCachedStreamingDemandDrivenPipeline can only be used for algorithms with one output and one input"); return 0; } // first do the ususal thing int result = this->Superclass::ExecuteData(request, inInfoVec, outInfoVec); // then save the newly generated data unsigned long bestTime = VTK_LARGE_INTEGER; int bestIdx = 0; // Save the image in cache. // Find a spot to put the data. for (int i = 0; i < this->CacheSize; ++i) { if (this->Data[i] == NULL) { bestIdx = i; bestTime = 0; break; } if (this->Times[i] < bestTime) { bestIdx = i; bestTime = this->Times[i]; } } vtkInformation* outInfo = outInfoVec->GetInformationObject(0); vtkDataObject* dataObject = outInfo->Get(vtkDataObject::DATA_OBJECT()); if (this->Data[bestIdx] == NULL) { this->Data[bestIdx] = dataObject->NewInstance(); } this->Data[bestIdx]->ReleaseData(); vtkImageData *id = vtkImageData::SafeDownCast(dataObject); if (id) { vtkInformation* inInfo = inInfoVec[0]->GetInformationObject(0); vtkImageData *input = vtkImageData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); id->SetExtent(input->GetExtent()); id->GetPointData()->PassData(input->GetPointData()); id->DataHasBeenGenerated(); } vtkImageData *id2 = vtkImageData::SafeDownCast(this->Data[bestIdx]); if (id && id2) { id2->SetExtent(id->GetExtent()); id2->SetScalarType(id->GetScalarType()); id2->SetNumberOfScalarComponents( id->GetNumberOfScalarComponents()); id2->GetPointData()->SetScalars( id->GetPointData()->GetScalars()); } this->Times[bestIdx] = dataObject->GetUpdateTime(); return result; }
[ "useminmin@gmail.com" ]
useminmin@gmail.com
ad5bb2612b61287429e194d202e4bf8e51fde1e4
fc90d57ce2958cc608f2615b5e9b655ca62a2352
/SpaceWars/Source Code/Bullet.cpp
d30cc91aa1b4eb820430c9dbc39608d6c2fb89ce
[]
no_license
ash9991win/SDL-Games
a95fa917d2bacb6fd00ff18fdc52b40c8295d53c
d278579c2fb8e0da4c898d335e73b176641d6223
refs/heads/master
2021-01-10T13:57:46.198478
2016-04-08T12:15:00
2016-04-08T12:15:00
55,774,687
0
0
null
null
null
null
UTF-8
C++
false
false
1,366
cpp
#include"Bullet.h" Bullet::Bullet() { mPosx = 0; mPosy = 0; mVelx = 0; mVely = 0; mdamage = 0; mobjecttexture = 0; } //Change the Y coordinate void Bullet::move() { //Since the bullet moves up, the Y coordinate is decreased by the velocity of the bullet. mPosy -= BULLET_VEL; //Update the collider of the bullet collider.x = mPosx; collider.y = mPosy; collider.w = 4; collider.h = 30; } void Bullet::reset() { mPosx = 0; mPosy = 0; mVelx = 0; mVely = 0; collider = { 0, 0, 0, 0 }; } //Draw onto the screen void Bullet::render() { SDL_Rect coord; SDL_SetRenderDrawColor(current_renderer, 0xFF, 0xFF, 0xFF, 0xff); //Draw the bullet only if the render flag is set and the HIT flag is not. If the render flag is set, it means the player has pressed space. If the HIT flag is set, it meaans the bullet has struck an asteroid. if (render_flag && !isHit) { //Reset the collider collider = { 0, 0, 0, 0 }; coord.x = mPosx + 10; coord.y = mPosy; coord.w = 5; coord.h = 40; SDL_RenderCopy(current_renderer, mobjecttexture, NULL, &coord); } } void Bullet::setRenderFlag(bool flag) { render_flag = flag; } bool Bullet::getRenderFlag() { return render_flag; } void Bullet::setHit(bool value) { isHit = value; }
[ "ash9991win@gmail.com" ]
ash9991win@gmail.com
b2faa53e5619ff2fd0a801267244e75a9cb1059b
578ab9a52db104742cc23c758d386a8cff885706
/export/android/obj/include/sys/FileSystem.h
c7210b3084e8296adab699e609a76ad7fc847fbb
[]
no_license
evo0705/SpaceWar
a16695d9ae57c6ae7a17f9cbbefe7188701493d7
97a5a894977c56cda8d3d61866d7d6e237e1cbd9
refs/heads/master
2021-01-17T23:17:28.000163
2017-03-07T15:32:04
2017-03-07T15:32:04
84,214,718
0
0
null
null
null
null
UTF-8
C++
false
false
1,335
h
#ifndef INCLUDED_sys_FileSystem #define INCLUDED_sys_FileSystem #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS1(sys,FileSystem) namespace sys{ class HXCPP_CLASS_ATTRIBUTES FileSystem_obj : public hx::Object{ public: typedef hx::Object super; typedef FileSystem_obj OBJ_; FileSystem_obj(); Void __construct(); public: inline void *operator new( size_t inSize, bool inContainer=false,const char *inName="sys.FileSystem") { return hx::Object::operator new(inSize,inContainer,inName); } static hx::ObjectPtr< FileSystem_obj > __new(); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); //~FileSystem_obj(); HX_DO_RTTI_ALL; static bool __GetStatic(const ::String &inString, Dynamic &outValue, hx::PropertyAccess inCallProp); static void __register(); ::String __ToString() const { return HX_HCSTRING("FileSystem","\xab","\xe2","\x17","\xca"); } static void __boot(); static bool exists( ::String path); static Dynamic exists_dyn(); static Void deleteFile( ::String path); static Dynamic deleteFile_dyn(); static Dynamic sys_exists; static Dynamic &sys_exists_dyn() { return sys_exists;} static Dynamic file_delete; static Dynamic &file_delete_dyn() { return file_delete;} }; } // end namespace sys #endif /* INCLUDED_sys_FileSystem */
[ "evo0705@gmail.com" ]
evo0705@gmail.com
824f78f080dc7244c41b2ee5270122aace202ce8
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-mediaconnect/source/model/StartFlowRequest.cpp
dcfe0d40ab77ceb134af754fc6e1f153f3b482ad
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
501
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/mediaconnect/model/StartFlowRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::MediaConnect::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; StartFlowRequest::StartFlowRequest() : m_flowArnHasBeenSet(false) { } Aws::String StartFlowRequest::SerializePayload() const { return {}; }
[ "sdavtaker@users.noreply.github.com" ]
sdavtaker@users.noreply.github.com
fa1707d53278b119a1ccc1fbd6c5f6a9f2e11f71
18f5fef20524b01c1ba90925f3328d4a9337df7c
/src/main.cpp
9a4e679680689ded65e11429c32ce0138833a563
[ "MIT" ]
permissive
foxfoot/XML-to-HTML-converter
4c6e443b59f35aad725376ce50030e9fa8b75b23
32449d33dd09c0ebd6678296feb25624793c32d1
refs/heads/main
2023-02-17T03:14:37.121273
2021-01-16T21:34:00
2021-01-16T21:34:00
330,021,044
0
0
null
null
null
null
UTF-8
C++
false
false
1,848
cpp
/** MIT License Copyright (c) 2021 foxfoot Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include "CDCatalog.hpp" void helper() { std::cout << "usage: xml2html <XML file name> <HTML file name>" << std::endl << "This file is to convert the source XML file to the target HTML file." << std::endl; } int main(int argc, char *argv[]) { if(argc != 3) { helper(); return 1; } std::string xmlFileName(argv[1]); std::string htmlFileName(argv[2]); if(xmlFileName == htmlFileName) { std::cout << "The XML file name can not be the same as the HTML file name." << std::endl; return 2; } CDCatalog catalog; if (!catalog.load(argv[1])) { return 3; } if (!catalog.toHTMLFile(argv[2])) { return 4; } return 0; }
[ "foxfoot2002@hotmail.com" ]
foxfoot2002@hotmail.com
7102a2d3198bdcc8dd7b1886a3b5df5a91a3a456
1aeaf760e3ce0e298963854e0aef8be6bef6ec61
/Translator/Translator.cpp
034d575b888e6e4e94552f275204eb4505a67ba6
[]
no_license
jamescoll/cpp_portfolio
b7742f49ac9bd8f20ebdb293a46da75d409c7afe
c2ff80d9da0fd46baef9856f1ca50007ee9c8313
refs/heads/master
2016-09-03T07:29:41.726708
2013-08-13T00:36:34
2013-08-13T00:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,909
cpp
/* * Translator.cpp * * Created on: 6 Apr 2013 * Author: James Coll */ #include "Translator.h" #include <iostream> #include <fstream> #include <map> #include <algorithm> #include <string.h> using namespace std; Translator::Translator(const char filename[]) { // we don't want to do file io in the constructor this->LoadDictionary(filename); } void Translator::LoadDictionary(const char filename[]) { //open the dictionary file fstream infile; infile.open(filename, ios::in); if (infile.fail()) { cerr<<"Problem opening dictionary file"; return; } string line, english, elfish; //go through the file line by line dealing with the problematic tabs and whitespaces //we're going to use two maps to store the dictionary //this turns out to be more efficient than using one map and a reverse find while(infile.good()) { getline(infile, line); if(!line.empty()) { //this gets me all the English words by hunting for whitespace and tabs unsigned found = line.find_first_of(" \t"); english = line.substr(0, found); //we'll dump what's left in elfish and then remove the whitespaces and tabs from it elfish = line.substr(found, string::npos); elfish.erase(remove(elfish.begin(), elfish.end(), '\t'), elfish.end()); elfish.erase(remove(elfish.begin(), elfish.end(), ' '), elfish.end()); //now place these into a map engtoelfdictionary.insert(std::pair<string, string>(english, elfish)); elftoengdictionary.insert(std::pair<string, string>(elfish, english)); //now create capital pairs english[0] = toupper(english[0]); elfish[0] = toupper(elfish[0]); //populate the map with capitalized pairs - this saves on work later engtoelfdictionary.insert(std::pair<string, string>(english, elfish)); elftoengdictionary.insert(std::pair<string, string>(elfish, english)); } } return; } void Translator::toElvish(char translatedLine[], const char lineToTranslate[]) { string inputLine(lineToTranslate); string tmp, trans; for(int i = 0; i<inputLine.size()+1; i++) { if(isalpha(inputLine[i])||inputLine[i]=='-') { tmp += inputLine[i]; } else { //probably need to check if this is empty or not if(!tmp.empty()) { if(engtoelfdictionary.count(tmp)==1) { trans += engtoelfdictionary[tmp]; }//this is our special case words 'already translated' else { tmp.insert(tmp.begin(), '*'); tmp.insert(tmp.end(), '*'); trans += tmp; } } trans += inputLine[i]; tmp.clear(); } } //this translates our string back into a character array char *ch=new char[trans.size()+1]; ch[trans.size()]=0; memcpy(ch,trans.c_str(),trans.size()); strcpy(translatedLine, ch); } void Translator::toEnglish(char translatedLine[], const char lineToTranslate[]) { string inputLine(lineToTranslate); string tmp, trans; bool bTranslate = true; for(int i = 0; i<inputLine.size()+1; i++) { if(inputLine[i]=='*') { //we can flip this each time a first star is encountered //this saves on a look-up bTranslate = !bTranslate; } else if(isalpha(inputLine[i])||inputLine[i]=='-') { tmp += inputLine[i]; } else { //check if this is empty or not //we need to look up all of the words which have two meanings if(!tmp.empty()) { if(elftoengdictionary.count(tmp)==1&&bTranslate) { trans += elftoengdictionary[tmp]; } else { trans += tmp; } } trans += inputLine[i]; tmp.clear(); } } //this translates our string back into a character array char *ch=new char[trans.size()+1]; ch[trans.size()]=0; memcpy(ch,trans.c_str(),trans.size()); strcpy(translatedLine, ch); }
[ "james.evin.coll@gmail.com" ]
james.evin.coll@gmail.com
252edb5d86c060cbeaec3a159c9acb0e481a743a
7b1ca7f608b1f7e2da794943ada796ad241350c2
/component/tileset/tileset_tabber.cpp
8771f143fd611061455edbc535e26cfd95d89c18
[]
no_license
Meldrion/Ignis-Editor
4facac31075107b292b5460459a701a22150a27b
9f7ac25070c5cd55ca7335cc9dee87f26932359e
refs/heads/master
2016-08-12T16:59:04.528825
2015-12-21T12:10:19
2015-12-21T12:10:19
48,265,273
0
0
null
null
null
null
UTF-8
C++
false
false
1,204
cpp
#include "tileset_tabber.h" Tileset_Tabber::Tileset_Tabber(QWidget* parent) : QTabWidget(parent) { } QSize Tileset_Tabber::sizeHint() const { return QSize(300,350); } /* void Tileset_Tabber::activeSceneChanged(Abstract_Scene* scene) { this->deleteAllocatedGUIComponents(); GameLevelScene* game_level_scene = dynamic_cast<GameLevelScene*>(scene); if (game_level_scene) { QVector<Tileset*> tilesets = game_level_scene->getTilesets(); for (QVector<Tileset*>::iterator it = tilesets.begin();it != tilesets.end();++it) { Tileset_Canvas_Tab* ts_tab = new Tileset_Canvas_Tab(*it,this); // Add the new Tileset Widget to the Tabber this->addTab(ts_tab,(*it)->getName()); // Add the new Tileset Widget to the Vector with all the ts_widgets inside it this->m_tileset_tabs.append(ts_tab); } } }*/ void Tileset_Tabber::deleteAllocatedGUIComponents() { this->clear(); // Delete all the Tileset Canvases that do still exists for (QVector<Tileset_Canvas_Tab*>::iterator it = this->m_tileset_tabs.begin(); it != this->m_tileset_tabs.end();++it) { delete *it; } }
[ "fabien.steines@gmail.com" ]
fabien.steines@gmail.com
fb5ee0f835536089418432c187eb8d1847ce8b7c
210a310287047f30925c29381e1fd7fddf11a21c
/modules/fpga/include/opencv2/fpga/hal/intrin_cpp.hpp
6e18ffe511a6c62f28b5bb2093a352bd483a9337
[ "BSD-3-Clause" ]
permissive
ZebulonJiang/opencv-fpga
9108936cec5a5a3583dce97826adc27bda7d5cf0
ba9d09f6df8747b23ef6015a614466f80cf91340
refs/heads/master
2020-03-28T03:10:44.443890
2017-08-24T01:01:48
2017-08-24T01:01:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
53,482
hpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_HAL_INTRIN_CPP_HPP #define OPENCV_HAL_INTRIN_CPP_HPP #include <limits> #include <cstring> #include <algorithm> #include "opencv2/fpga/saturate.hpp" namespace cv { /** @addtogroup core_hal_intrin "Universal intrinsics" is a types and functions set intended to simplify vectorization of code on different platforms. Currently there are two supported SIMD extensions: __SSE/SSE2__ on x86 architectures and __NEON__ on ARM architectures, both allow working with 128 bit registers containing packed values of different types. In case when there is no SIMD extension available during compilation, fallback C++ implementation of intrinsics will be chosen and code will work as expected although it could be slower. ### Types There are several types representing 128-bit register as a vector of packed values, each type is implemented as a structure based on a one SIMD register. - cv::v_uint8x16 and cv::v_int8x16: sixteen 8-bit integer values (unsigned/signed) - char - cv::v_uint16x8 and cv::v_int16x8: eight 16-bit integer values (unsigned/signed) - short - cv::v_uint32x4 and cv::v_int32x4: four 32-bit integer values (unsgined/signed) - int - cv::v_uint64x2 and cv::v_int64x2: two 64-bit integer values (unsigned/signed) - int64 - cv::v_float32x4: four 32-bit floating point values (signed) - float - cv::v_float64x2: two 64-bit floating point valies (signed) - double @note cv::v_float64x2 is not implemented in NEON variant, if you want to use this type, don't forget to check the CV_SIMD128_64F preprocessor definition: @code #if CV_SIMD128_64F //... #endif @endcode ### Load and store operations These operations allow to set contents of the register explicitly or by loading it from some memory block and to save contents of the register to memory block. - Constructors: @ref v_reg::v_reg(const _Tp *ptr) "from memory", @ref v_reg::v_reg(_Tp s0, _Tp s1) "from two values", ... - Other create methods: @ref v_setall_s8, @ref v_setall_u8, ..., @ref v_setzero_u8, @ref v_setzero_s8, ... - Memory operations: @ref v_load, @ref v_load_aligned, @ref v_load_halves, @ref v_store, @ref v_store_aligned, @ref v_store_high, @ref v_store_low ### Value reordering These operations allow to reorder or recombine elements in one or multiple vectors. - Interleave, deinterleave (2, 3 and 4 channels): @ref v_load_deinterleave, @ref v_store_interleave - Expand: @ref v_load_expand, @ref v_load_expand_q, @ref v_expand - Pack: @ref v_pack, @ref v_pack_u, @ref v_rshr_pack, @ref v_rshr_pack_u, @ref v_pack_store, @ref v_pack_u_store, @ref v_rshr_pack_store, @ref v_rshr_pack_u_store - Recombine: @ref v_zip, @ref v_recombine, @ref v_combine_low, @ref v_combine_high - Extract: @ref v_extract ### Arithmetic, bitwise and comparison operations Element-wise binary and unary operations. - Arithmetics: @ref operator +(const v_reg &a, const v_reg &b) "+", @ref operator -(const v_reg &a, const v_reg &b) "-", @ref operator *(const v_reg &a, const v_reg &b) "*", @ref operator /(const v_reg &a, const v_reg &b) "/", @ref v_mul_expand - Non-saturating arithmetics: @ref v_add_wrap, @ref v_sub_wrap - Bitwise shifts: @ref operator <<(const v_reg &a, int s) "<<", @ref operator >>(const v_reg &a, int s) ">>", @ref v_shl, @ref v_shr - Bitwise logic: @ref operator&(const v_reg &a, const v_reg &b) "&", @ref operator |(const v_reg &a, const v_reg &b) "|", @ref operator ^(const v_reg &a, const v_reg &b) "^", @ref operator ~(const v_reg &a) "~" - Comparison: @ref operator >(const v_reg &a, const v_reg &b) ">", @ref operator >=(const v_reg &a, const v_reg &b) ">=", @ref operator <(const v_reg &a, const v_reg &b) "<", @ref operator <=(const v_reg &a, const v_reg &b) "<=", @ref operator==(const v_reg &a, const v_reg &b) "==", @ref operator !=(const v_reg &a, const v_reg &b) "!=" - min/max: @ref v_min, @ref v_max ### Reduce and mask Most of these operations return only one value. - Reduce: @ref v_reduce_min, @ref v_reduce_max, @ref v_reduce_sum - Mask: @ref v_signmask, @ref v_check_all, @ref v_check_any, @ref v_select ### Other math - Some frequent operations: @ref v_sqrt, @ref v_invsqrt, @ref v_magnitude, @ref v_sqr_magnitude - Absolute values: @ref v_abs, @ref v_absdiff ### Conversions Different type conversions and casts: - Rounding: @ref v_round, @ref v_floor, @ref v_ceil, @ref v_trunc, - To float: @ref v_cvt_f32, @ref v_cvt_f64 - Reinterpret: @ref v_reinterpret_as_u8, @ref v_reinterpret_as_s8, ... ### Matrix operations In these operations vectors represent matrix rows/columns: @ref v_dotprod, @ref v_matmul, @ref v_transpose4x4 ### Usability Most operations are implemented only for some subset of the available types, following matrices shows the applicability of different operations to the types. Regular integers: | Operations\\Types | uint 8x16 | int 8x16 | uint 16x8 | int 16x8 | uint 32x4 | int 32x4 | |-------------------|:-:|:-:|:-:|:-:|:-:|:-:| |load, store | x | x | x | x | x | x | |interleave | x | x | x | x | x | x | |expand | x | x | x | x | x | x | |expand_q | x | x | | | | | |add, sub | x | x | x | x | x | x | |add_wrap, sub_wrap | x | x | x | x | | | |mul | | | x | x | x | x | |mul_expand | | | x | x | x | | |compare | x | x | x | x | x | x | |shift | | | x | x | x | x | |dotprod | | | | x | | | |logical | x | x | x | x | x | x | |min, max | x | x | x | x | x | x | |absdiff | x | x | x | x | x | x | |reduce | | | | | x | x | |mask | x | x | x | x | x | x | |pack | x | x | x | x | x | x | |pack_u | x | | x | | | | |unpack | x | x | x | x | x | x | |extract | x | x | x | x | x | x | |cvt_flt32 | | | | | | x | |cvt_flt64 | | | | | | x | |transpose4x4 | | | | | x | x | Big integers: | Operations\\Types | uint 64x2 | int 64x2 | |-------------------|:-:|:-:| |load, store | x | x | |add, sub | x | x | |shift | x | x | |logical | x | x | |extract | x | x | Floating point: | Operations\\Types | float 32x4 | float 64x2 | |-------------------|:-:|:-:| |load, store | x | x | |interleave | x | | |add, sub | x | x | |mul | x | x | |div | x | x | |compare | x | x | |min, max | x | x | |absdiff | x | x | |reduce | x | | |mask | x | x | |unpack | x | x | |cvt_flt32 | | x | |cvt_flt64 | x | | |sqrt, abs | x | x | |float math | x | x | |transpose4x4 | x | | @{ */ template<typename _Tp, int n> struct v_reg { //! @cond IGNORED typedef _Tp lane_type; typedef v_reg<typename V_TypeTraits<_Tp>::int_type, n> int_vec; typedef v_reg<typename V_TypeTraits<_Tp>::abs_type, n> abs_vec; enum { nlanes = n }; // !@endcond /** @brief Constructor Initializes register with data from memory @param ptr pointer to memory block with data for register */ explicit v_reg(const _Tp* ptr) { for( int i = 0; i < n; i++ ) s[i] = ptr[i]; } /** @brief Constructor Initializes register with two 64-bit values */ v_reg(_Tp s0, _Tp s1) { s[0] = s0; s[1] = s1; } /** @brief Constructor Initializes register with four 32-bit values */ v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3) { s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; } /** @brief Constructor Initializes register with eight 16-bit values */ v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, _Tp s4, _Tp s5, _Tp s6, _Tp s7) { s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; s[4] = s4; s[5] = s5; s[6] = s6; s[7] = s7; } /** @brief Constructor Initializes register with sixteen 8-bit values */ v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, _Tp s4, _Tp s5, _Tp s6, _Tp s7, _Tp s8, _Tp s9, _Tp s10, _Tp s11, _Tp s12, _Tp s13, _Tp s14, _Tp s15) { s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; s[4] = s4; s[5] = s5; s[6] = s6; s[7] = s7; s[8] = s8; s[9] = s9; s[10] = s10; s[11] = s11; s[12] = s12; s[13] = s13; s[14] = s14; s[15] = s15; } /** @brief Default constructor Does not initialize anything*/ v_reg() {} /** @brief Copy constructor */ v_reg(const v_reg<_Tp, n> & r) { for( int i = 0; i < n; i++ ) s[i] = r.s[i]; } /** @brief Access first value Returns value of the first lane according to register type, for example: @code{.cpp} v_int32x4 r(1, 2, 3, 4); int v = r.get0(); // returns 1 v_uint64x2 r(1, 2); uint64_t v = r.get0(); // returns 1 @endcode */ _Tp get0() const { return s[0]; } //! @cond IGNORED _Tp get(const int i) const { return s[i]; } v_reg<_Tp, n> high() const { v_reg<_Tp, n> c; int i; for( i = 0; i < n/2; i++ ) { c.s[i] = s[i+(n/2)]; c.s[i+(n/2)] = 0; } return c; } static v_reg<_Tp, n> zero() { v_reg<_Tp, n> c; for( int i = 0; i < n; i++ ) c.s[i] = (_Tp)0; return c; } static v_reg<_Tp, n> all(_Tp s) { v_reg<_Tp, n> c; for( int i = 0; i < n; i++ ) c.s[i] = s; return c; } template<typename _Tp2, int n2> v_reg<_Tp2, n2> reinterpret_as() const { size_t bytes = std::min(sizeof(_Tp2)*n2, sizeof(_Tp)*n); v_reg<_Tp2, n2> c; std::memcpy(&c.s[0], &s[0], bytes); return c; } _Tp s[n]; //! @endcond }; /** @brief Sixteen 8-bit unsigned integer values */ typedef v_reg<uchar, 16> v_uint8x16; /** @brief Sixteen 8-bit signed integer values */ typedef v_reg<schar, 16> v_int8x16; /** @brief Eight 16-bit unsigned integer values */ typedef v_reg<ushort, 8> v_uint16x8; /** @brief Eight 16-bit signed integer values */ typedef v_reg<short, 8> v_int16x8; /** @brief Four 32-bit unsigned integer values */ typedef v_reg<unsigned, 4> v_uint32x4; /** @brief Four 32-bit signed integer values */ typedef v_reg<int, 4> v_int32x4; /** @brief Four 32-bit floating point values (single precision) */ typedef v_reg<float, 4> v_float32x4; /** @brief Two 64-bit floating point values (double precision) */ typedef v_reg<double, 2> v_float64x2; /** @brief Two 64-bit unsigned integer values */ typedef v_reg<uint64, 2> v_uint64x2; /** @brief Two 64-bit signed integer values */ typedef v_reg<int64, 2> v_int64x2; //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_BIN_OP(bin_op) \ template<typename _Tp, int n> inline v_reg<_Tp, n> \ operator bin_op (const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ { \ v_reg<_Tp, n> c; \ for( int i = 0; i < n; i++ ) \ c.s[i] = saturate_cast<_Tp>(a.s[i] bin_op b.s[i]); \ return c; \ } \ template<typename _Tp, int n> inline v_reg<_Tp, n>& \ operator bin_op##= (v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ { \ for( int i = 0; i < n; i++ ) \ a.s[i] = saturate_cast<_Tp>(a.s[i] bin_op b.s[i]); \ return a; \ } /** @brief Add values For all types. */ OPENCV_HAL_IMPL_BIN_OP(+) /** @brief Subtract values For all types. */ OPENCV_HAL_IMPL_BIN_OP(-) /** @brief Multiply values For 16- and 32-bit integer types and floating types. */ OPENCV_HAL_IMPL_BIN_OP(*) /** @brief Divide values For floating types only. */ OPENCV_HAL_IMPL_BIN_OP(/) //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_BIT_OP(bit_op) \ template<typename _Tp, int n> inline v_reg<_Tp, n> operator bit_op \ (const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ { \ v_reg<_Tp, n> c; \ typedef typename V_TypeTraits<_Tp>::int_type itype; \ for( int i = 0; i < n; i++ ) \ c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int((itype)(V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) bit_op \ V_TypeTraits<_Tp>::reinterpret_int(b.s[i]))); \ return c; \ } \ template<typename _Tp, int n> inline v_reg<_Tp, n>& operator \ bit_op##= (v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ { \ typedef typename V_TypeTraits<_Tp>::int_type itype; \ for( int i = 0; i < n; i++ ) \ a.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int((itype)(V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) bit_op \ V_TypeTraits<_Tp>::reinterpret_int(b.s[i]))); \ return a; \ } /** @brief Bitwise AND Only for integer types. */ OPENCV_HAL_IMPL_BIT_OP(&) /** @brief Bitwise OR Only for integer types. */ OPENCV_HAL_IMPL_BIT_OP(|) /** @brief Bitwise XOR Only for integer types.*/ OPENCV_HAL_IMPL_BIT_OP(^) /** @brief Bitwise NOT Only for integer types.*/ template<typename _Tp, int n> inline v_reg<_Tp, n> operator ~ (const v_reg<_Tp, n>& a) { v_reg<_Tp, n> c; for( int i = 0; i < n; i++ ) { c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int(~V_TypeTraits<_Tp>::reinterpret_int(a.s[i])); } return c; } //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_MATH_FUNC(func, cfunc, _Tp2) \ template<typename _Tp, int n> inline v_reg<_Tp2, n> func(const v_reg<_Tp, n>& a) \ { \ v_reg<_Tp2, n> c; \ for( int i = 0; i < n; i++ ) \ c.s[i] = cfunc(a.s[i]); \ return c; \ } /** @brief Square root of elements Only for floating point types.*/ OPENCV_HAL_IMPL_MATH_FUNC(v_sqrt, std::sqrt, _Tp) //! @cond IGNORED OPENCV_HAL_IMPL_MATH_FUNC(v_sin, std::sin, _Tp) OPENCV_HAL_IMPL_MATH_FUNC(v_cos, std::cos, _Tp) OPENCV_HAL_IMPL_MATH_FUNC(v_exp, std::exp, _Tp) OPENCV_HAL_IMPL_MATH_FUNC(v_log, std::log, _Tp) //! @endcond /** @brief Absolute value of elements Only for floating point types.*/ OPENCV_HAL_IMPL_MATH_FUNC(v_abs, (typename V_TypeTraits<_Tp>::abs_type)std::abs, typename V_TypeTraits<_Tp>::abs_type) /** @brief Round elements Only for floating point types.*/ OPENCV_HAL_IMPL_MATH_FUNC(v_round, cvRound, int) /** @brief Floor elements Only for floating point types.*/ OPENCV_HAL_IMPL_MATH_FUNC(v_floor, cvFloor, int) /** @brief Ceil elements Only for floating point types.*/ OPENCV_HAL_IMPL_MATH_FUNC(v_ceil, cvCeil, int) /** @brief Truncate elements Only for floating point types.*/ OPENCV_HAL_IMPL_MATH_FUNC(v_trunc, int, int) //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_MINMAX_FUNC(func, cfunc) \ template<typename _Tp, int n> inline v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ { \ v_reg<_Tp, n> c; \ for( int i = 0; i < n; i++ ) \ c.s[i] = cfunc(a.s[i], b.s[i]); \ return c; \ } //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(func, cfunc) \ template<typename _Tp, int n> inline _Tp func(const v_reg<_Tp, n>& a) \ { \ _Tp c = a.s[0]; \ for( int i = 1; i < n; i++ ) \ c = cfunc(c, a.s[i]); \ return c; \ } /** @brief Choose min values for each pair Scheme: @code {A1 A2 ...} {B1 B2 ...} -------------- {min(A1,B1) min(A2,B2) ...} @endcode For all types except 64-bit integer. */ OPENCV_HAL_IMPL_MINMAX_FUNC(v_min, std::min) /** @brief Choose max values for each pair Scheme: @code {A1 A2 ...} {B1 B2 ...} -------------- {max(A1,B1) max(A2,B2) ...} @endcode For all types except 64-bit integer. */ OPENCV_HAL_IMPL_MINMAX_FUNC(v_max, std::max) /** @brief Find one min value Scheme: @code {A1 A2 A3 ...} => min(A1,A2,A3,...) @endcode For 32-bit integer and 32-bit floating point types. */ OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(v_reduce_min, std::min) /** @brief Find one max value Scheme: @code {A1 A2 A3 ...} => max(A1,A2,A3,...) @endcode For 32-bit integer and 32-bit floating point types. */ OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(v_reduce_max, std::max) //! @cond IGNORED template<typename _Tp, int n> inline void v_minmax( const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, v_reg<_Tp, n>& minval, v_reg<_Tp, n>& maxval ) { for( int i = 0; i < n; i++ ) { minval.s[i] = std::min(a.s[i], b.s[i]); maxval.s[i] = std::max(a.s[i], b.s[i]); } } //! @endcond //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_CMP_OP(cmp_op) \ template<typename _Tp, int n> \ inline v_reg<_Tp, n> operator cmp_op(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ { \ typedef typename V_TypeTraits<_Tp>::int_type itype; \ v_reg<_Tp, n> c; \ for( int i = 0; i < n; i++ ) \ c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int((itype)-(int)(a.s[i] cmp_op b.s[i])); \ return c; \ } /** @brief Less-than comparison For all types except 64-bit integer values. */ OPENCV_HAL_IMPL_CMP_OP(<) /** @brief Greater-than comparison For all types except 64-bit integer values. */ OPENCV_HAL_IMPL_CMP_OP(>) /** @brief Less-than or equal comparison For all types except 64-bit integer values. */ OPENCV_HAL_IMPL_CMP_OP(<=) /** @brief Greater-than or equal comparison For all types except 64-bit integer values. */ OPENCV_HAL_IMPL_CMP_OP(>=) /** @brief Equal comparison For all types except 64-bit integer values. */ OPENCV_HAL_IMPL_CMP_OP(==) /** @brief Not equal comparison For all types except 64-bit integer values. */ OPENCV_HAL_IMPL_CMP_OP(!=) //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_ADD_SUB_OP(func, bin_op, cast_op, _Tp2) \ template<typename _Tp, int n> \ inline v_reg<_Tp2, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ { \ typedef _Tp2 rtype; \ v_reg<rtype, n> c; \ for( int i = 0; i < n; i++ ) \ c.s[i] = cast_op(a.s[i] bin_op b.s[i]); \ return c; \ } /** @brief Add values without saturation For 8- and 16-bit integer values. */ OPENCV_HAL_IMPL_ADD_SUB_OP(v_add_wrap, +, (_Tp), _Tp) /** @brief Subtract values without saturation For 8- and 16-bit integer values. */ OPENCV_HAL_IMPL_ADD_SUB_OP(v_sub_wrap, -, (_Tp), _Tp) //! @cond IGNORED template<typename T> inline T _absdiff(T a, T b) { return a > b ? a - b : b - a; } //! @endcond /** @brief Absolute difference Returns \f$ |a - b| \f$ converted to corresponding unsigned type. Example: @code{.cpp} v_int32x4 a, b; // {1, 2, 3, 4} and {4, 3, 2, 1} v_uint32x4 c = v_absdiff(a, b); // result is {3, 1, 1, 3} @endcode For 8-, 16-, 32-bit integer source types. */ template<typename _Tp, int n> inline v_reg<typename V_TypeTraits<_Tp>::abs_type, n> v_absdiff(const v_reg<_Tp, n>& a, const v_reg<_Tp, n> & b) { typedef typename V_TypeTraits<_Tp>::abs_type rtype; v_reg<rtype, n> c; const rtype mask = std::numeric_limits<_Tp>::is_signed ? (1 << (sizeof(rtype)*8 - 1)) : 0; for( int i = 0; i < n; i++ ) { rtype ua = a.s[i] ^ mask; rtype ub = b.s[i] ^ mask; c.s[i] = _absdiff(ua, ub); } return c; } /** @overload For 32-bit floating point values */ inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) { v_float32x4 c; for( int i = 0; i < c.nlanes; i++ ) c.s[i] = _absdiff(a.s[i], b.s[i]); return c; } /** @overload For 64-bit floating point values */ inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) { v_float64x2 c; for( int i = 0; i < c.nlanes; i++ ) c.s[i] = _absdiff(a.s[i], b.s[i]); return c; } /** @brief Inversed square root Returns \f$ 1/sqrt(a) \f$ For floating point types only. */ template<typename _Tp, int n> inline v_reg<_Tp, n> v_invsqrt(const v_reg<_Tp, n>& a) { v_reg<_Tp, n> c; for( int i = 0; i < n; i++ ) c.s[i] = 1.f/std::sqrt(a.s[i]); return c; } /** @brief Magnitude Returns \f$ sqrt(a^2 + b^2) \f$ For floating point types only. */ template<typename _Tp, int n> inline v_reg<_Tp, n> v_magnitude(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { v_reg<_Tp, n> c; for( int i = 0; i < n; i++ ) c.s[i] = std::sqrt(a.s[i]*a.s[i] + b.s[i]*b.s[i]); return c; } /** @brief Square of the magnitude Returns \f$ a^2 + b^2 \f$ For floating point types only. */ template<typename _Tp, int n> inline v_reg<_Tp, n> v_sqr_magnitude(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { v_reg<_Tp, n> c; for( int i = 0; i < n; i++ ) c.s[i] = a.s[i]*a.s[i] + b.s[i]*b.s[i]; return c; } /** @brief Multiply and add Returns \f$ a*b + c \f$ For floating point types only. */ template<typename _Tp, int n> inline v_reg<_Tp, n> v_muladd(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c) { v_reg<_Tp, n> d; for( int i = 0; i < n; i++ ) d.s[i] = a.s[i]*b.s[i] + c.s[i]; return d; } /** @brief Dot product of elements Multiply values in two registers and sum adjacent result pairs. Scheme: @code {A1 A2 ...} // 16-bit x {B1 B2 ...} // 16-bit ------------- {A1B1+A2B2 ...} // 32-bit @endcode Implemented only for 16-bit signed source type (v_int16x8). */ template<typename _Tp, int n> inline v_reg<typename V_TypeTraits<_Tp>::w_type, n/2> v_dotprod(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { typedef typename V_TypeTraits<_Tp>::w_type w_type; v_reg<w_type, n/2> c; for( int i = 0; i < (n/2); i++ ) c.s[i] = (w_type)a.s[i*2]*b.s[i*2] + (w_type)a.s[i*2+1]*b.s[i*2+1]; return c; } /** @brief Multiply and expand Multiply values two registers and store results in two registers with wider pack type. Scheme: @code {A B C D} // 32-bit x {E F G H} // 32-bit --------------- {AE BF} // 64-bit {CG DH} // 64-bit @endcode Example: @code{.cpp} v_uint32x4 a, b; // {1,2,3,4} and {2,2,2,2} v_uint64x2 c, d; // results v_mul_expand(a, b, c, d); // c, d = {2,4}, {6, 8} @endcode Implemented only for 16- and unsigned 32-bit source types (v_int16x8, v_uint16x8, v_uint32x4). */ template<typename _Tp, int n> inline void v_mul_expand(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, v_reg<typename V_TypeTraits<_Tp>::w_type, n/2>& c, v_reg<typename V_TypeTraits<_Tp>::w_type, n/2>& d) { typedef typename V_TypeTraits<_Tp>::w_type w_type; for( int i = 0; i < (n/2); i++ ) { c.s[i] = (w_type)a.s[i]*b.s[i]; d.s[i] = (w_type)a.s[i+(n/2)]*b.s[i+(n/2)]; } } //! @cond IGNORED template<typename _Tp, int n> inline void v_hsum(const v_reg<_Tp, n>& a, v_reg<typename V_TypeTraits<_Tp>::w_type, n/2>& c) { typedef typename V_TypeTraits<_Tp>::w_type w_type; for( int i = 0; i < (n/2); i++ ) { c.s[i] = (w_type)a.s[i*2] + a.s[i*2+1]; } } //! @endcond //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_SHIFT_OP(shift_op) \ template<typename _Tp, int n> inline v_reg<_Tp, n> operator shift_op(const v_reg<_Tp, n>& a, int imm) \ { \ v_reg<_Tp, n> c; \ for( int i = 0; i < n; i++ ) \ c.s[i] = (_Tp)(a.s[i] shift_op imm); \ return c; \ } /** @brief Bitwise shift left For 16-, 32- and 64-bit integer values. */ OPENCV_HAL_IMPL_SHIFT_OP(<<) /** @brief Bitwise shift right For 16-, 32- and 64-bit integer values. */ OPENCV_HAL_IMPL_SHIFT_OP(>>) /** @brief Sum packed values Scheme: @code {A1 A2 A3 ...} => sum{A1,A2,A3,...} @endcode For 32-bit integer and 32-bit floating point types.*/ template<typename _Tp, int n> inline typename V_TypeTraits<_Tp>::sum_type v_reduce_sum(const v_reg<_Tp, n>& a) { typename V_TypeTraits<_Tp>::sum_type c = a.s[0]; for( int i = 1; i < n; i++ ) c += a.s[i]; return c; } /** @brief Get negative values mask Returned value is a bit mask with bits set to 1 on places corresponding to negative packed values indexes. Example: @code{.cpp} v_int32x4 r; // set to {-1, -1, 1, 1} int mask = v_signmask(r); // mask = 3 <== 00000000 00000000 00000000 00000011 @endcode For all types except 64-bit. */ template<typename _Tp, int n> inline int v_signmask(const v_reg<_Tp, n>& a) { int mask = 0; for( int i = 0; i < n; i++ ) mask |= (V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0) << i; return mask; } /** @brief Check if all packed values are less than zero Unsigned values will be casted to signed: `uchar 254 => char -2`. For all types except 64-bit. */ template<typename _Tp, int n> inline bool v_check_all(const v_reg<_Tp, n>& a) { for( int i = 0; i < n; i++ ) if( V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) >= 0 ) return false; return true; } /** @brief Check if any of packed values is less than zero Unsigned values will be casted to signed: `uchar 254 => char -2`. For all types except 64-bit. */ template<typename _Tp, int n> inline bool v_check_any(const v_reg<_Tp, n>& a) { for( int i = 0; i < n; i++ ) if( V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0 ) return true; return false; } /** @brief Bitwise select Return value will be built by combining values a and b using the following scheme: If the i-th bit in _mask_ is 1 select i-th bit from _a_ else select i-th bit from _b_ */ template<typename _Tp, int n> inline v_reg<_Tp, n> v_select(const v_reg<_Tp, n>& mask, const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { typedef V_TypeTraits<_Tp> Traits; typedef typename Traits::int_type int_type; v_reg<_Tp, n> c; for( int i = 0; i < n; i++ ) { int_type m = Traits::reinterpret_int(mask.s[i]); c.s[i] = Traits::reinterpret_from_int((Traits::reinterpret_int(a.s[i]) & m) | (Traits::reinterpret_int(b.s[i]) & ~m)); } return c; } /** @brief Expand values to the wider pack type Copy contents of register to two registers with 2x wider pack type. Scheme: @code int32x4 int64x2 int64x2 {A B C D} ==> {A B} , {C D} @endcode */ template<typename _Tp, int n> inline void v_expand(const v_reg<_Tp, n>& a, v_reg<typename V_TypeTraits<_Tp>::w_type, n/2>& b0, v_reg<typename V_TypeTraits<_Tp>::w_type, n/2>& b1) { for( int i = 0; i < (n/2); i++ ) { b0.s[i] = a.s[i]; b1.s[i] = a.s[i+(n/2)]; } } //! @cond IGNORED template<typename _Tp, int n> inline v_reg<typename V_TypeTraits<_Tp>::int_type, n> v_reinterpret_as_int(const v_reg<_Tp, n>& a) { v_reg<typename V_TypeTraits<_Tp>::int_type, n> c; for( int i = 0; i < n; i++ ) c.s[i] = V_TypeTraits<_Tp>::reinterpret_int(a.s[i]); return c; } template<typename _Tp, int n> inline v_reg<typename V_TypeTraits<_Tp>::uint_type, n> v_reinterpret_as_uint(const v_reg<_Tp, n>& a) { v_reg<typename V_TypeTraits<_Tp>::uint_type, n> c; for( int i = 0; i < n; i++ ) c.s[i] = V_TypeTraits<_Tp>::reinterpret_uint(a.s[i]); return c; } //! @endcond /** @brief Interleave two vectors Scheme: @code {A1 A2 A3 A4} {B1 B2 B3 B4} --------------- {A1 B1 A2 B2} and {A3 B3 A4 B4} @endcode For all types except 64-bit. */ template<typename _Tp, int n> inline void v_zip( const v_reg<_Tp, n>& a0, const v_reg<_Tp, n>& a1, v_reg<_Tp, n>& b0, v_reg<_Tp, n>& b1 ) { int i; for( i = 0; i < n/2; i++ ) { b0.s[i*2] = a0.s[i]; b0.s[i*2+1] = a1.s[i]; } for( ; i < n; i++ ) { b1.s[i*2-n] = a0.s[i]; b1.s[i*2-n+1] = a1.s[i]; } } /** @brief Load register contents from memory @param ptr pointer to memory block with data @return register object @note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x16, int ==> cv::v_int32x4, etc. */ template<typename _Tp> inline v_reg<_Tp, V_SIMD128Traits<_Tp>::nlanes> v_load(const _Tp* ptr) { return v_reg<_Tp, V_SIMD128Traits<_Tp>::nlanes>(ptr); } /** @brief Load register contents from memory (aligned) similar to cv::v_load, but source memory block should be aligned (to 16-byte boundary) */ template<typename _Tp> inline v_reg<_Tp, V_SIMD128Traits<_Tp>::nlanes> v_load_aligned(const _Tp* ptr) { return v_reg<_Tp, V_SIMD128Traits<_Tp>::nlanes>(ptr); } /** @brief Load register contents from two memory blocks @param loptr memory block containing data for first half (0..n/2) @param hiptr memory block containing data for second half (n/2..n) @code{.cpp} int lo[2] = { 1, 2 }, hi[2] = { 3, 4 }; v_int32x4 r = v_load_halves(lo, hi); @endcode */ template<typename _Tp> inline v_reg<_Tp, V_SIMD128Traits<_Tp>::nlanes> v_load_halves(const _Tp* loptr, const _Tp* hiptr) { v_reg<_Tp, V_SIMD128Traits<_Tp>::nlanes> c; for( int i = 0; i < c.nlanes/2; i++ ) { c.s[i] = loptr[i]; c.s[i+c.nlanes/2] = hiptr[i]; } return c; } /** @brief Load register contents from memory with double expand Same as cv::v_load, but result pack type will be 2x wider than memory type. @code{.cpp} short buf[4] = {1, 2, 3, 4}; // type is int16 v_int32x4 r = v_load_expand(buf); // r = {1, 2, 3, 4} - type is int32 @endcode For 8-, 16-, 32-bit integer source types. */ template<typename _Tp> inline v_reg<typename V_TypeTraits<_Tp>::w_type, V_SIMD128Traits<_Tp>::nlanes / 2> v_load_expand(const _Tp* ptr) { typedef typename V_TypeTraits<_Tp>::w_type w_type; v_reg<w_type, V_SIMD128Traits<w_type>::nlanes> c; for( int i = 0; i < c.nlanes; i++ ) { c.s[i] = ptr[i]; } return c; } /** @brief Load register contents from memory with quad expand Same as cv::v_load_expand, but result type is 4 times wider than source. @code{.cpp} char buf[4] = {1, 2, 3, 4}; // type is int8 v_int32x4 r = v_load_q(buf); // r = {1, 2, 3, 4} - type is int32 @endcode For 8-bit integer source types. */ template<typename _Tp> inline v_reg<typename V_TypeTraits<_Tp>::q_type, V_SIMD128Traits<_Tp>::nlanes / 4> v_load_expand_q(const _Tp* ptr) { typedef typename V_TypeTraits<_Tp>::q_type q_type; v_reg<q_type, V_SIMD128Traits<q_type>::nlanes> c; for( int i = 0; i < c.nlanes; i++ ) { c.s[i] = ptr[i]; } return c; } /** @brief Load and deinterleave (2 channels) Load data from memory deinterleave and store to 2 registers. Scheme: @code {A1 B1 A2 B2 ...} ==> {A1 A2 ...}, {B1 B2 ...} @endcode For all types except 64-bit. */ template<typename _Tp, int n> inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, v_reg<_Tp, n>& b) { int i, i2; for( i = i2 = 0; i < n; i++, i2 += 2 ) { a.s[i] = ptr[i2]; b.s[i] = ptr[i2+1]; } } /** @brief Load and deinterleave (3 channels) Load data from memory deinterleave and store to 3 registers. Scheme: @code {A1 B1 C1 A2 B2 C2 ...} ==> {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...} @endcode For all types except 64-bit. */ template<typename _Tp, int n> inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, v_reg<_Tp, n>& b, v_reg<_Tp, n>& c) { int i, i3; for( i = i3 = 0; i < n; i++, i3 += 3 ) { a.s[i] = ptr[i3]; b.s[i] = ptr[i3+1]; c.s[i] = ptr[i3+2]; } } /** @brief Load and deinterleave (4 channels) Load data from memory deinterleave and store to 4 registers. Scheme: @code {A1 B1 C1 D1 A2 B2 C2 D2 ...} ==> {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...}, {D1 D2 ...} @endcode For all types except 64-bit. */ template<typename _Tp, int n> inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, v_reg<_Tp, n>& b, v_reg<_Tp, n>& c, v_reg<_Tp, n>& d) { int i, i4; for( i = i4 = 0; i < n; i++, i4 += 4 ) { a.s[i] = ptr[i4]; b.s[i] = ptr[i4+1]; c.s[i] = ptr[i4+2]; d.s[i] = ptr[i4+3]; } } /** @brief Interleave and store (2 channels) Interleave and store data from 2 registers to memory. Scheme: @code {A1 A2 ...}, {B1 B2 ...} ==> {A1 B1 A2 B2 ...} @endcode For all types except 64-bit. */ template<typename _Tp, int n> inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { int i, i2; for( i = i2 = 0; i < n; i++, i2 += 2 ) { ptr[i2] = a.s[i]; ptr[i2+1] = b.s[i]; } } /** @brief Interleave and store (3 channels) Interleave and store data from 3 registers to memory. Scheme: @code {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...} ==> {A1 B1 C1 A2 B2 C2 ...} @endcode For all types except 64-bit. */ template<typename _Tp, int n> inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c) { int i, i3; for( i = i3 = 0; i < n; i++, i3 += 3 ) { ptr[i3] = a.s[i]; ptr[i3+1] = b.s[i]; ptr[i3+2] = c.s[i]; } } /** @brief Interleave and store (4 channels) Interleave and store data from 4 registers to memory. Scheme: @code {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...}, {D1 D2 ...} ==> {A1 B1 C1 D1 A2 B2 C2 D2 ...} @endcode For all types except 64-bit. */ template<typename _Tp, int n> inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c, const v_reg<_Tp, n>& d) { int i, i4; for( i = i4 = 0; i < n; i++, i4 += 4 ) { ptr[i4] = a.s[i]; ptr[i4+1] = b.s[i]; ptr[i4+2] = c.s[i]; ptr[i4+3] = d.s[i]; } } /** @brief Store data to memory Store register contents to memory. Scheme: @code REG {A B C D} ==> MEM {A B C D} @endcode Pointer can be unaligned. */ template<typename _Tp, int n> inline void v_store(_Tp* ptr, const v_reg<_Tp, n>& a) { for( int i = 0; i < n; i++ ) ptr[i] = a.s[i]; } /** @brief Store data to memory (lower half) Store lower half of register contents to memory. Scheme: @code REG {A B C D} ==> MEM {A B} @endcode */ template<typename _Tp, int n> inline void v_store_low(_Tp* ptr, const v_reg<_Tp, n>& a) { for( int i = 0; i < (n/2); i++ ) ptr[i] = a.s[i]; } /** @brief Store data to memory (higher half) Store higher half of register contents to memory. Scheme: @code REG {A B C D} ==> MEM {C D} @endcode */ template<typename _Tp, int n> inline void v_store_high(_Tp* ptr, const v_reg<_Tp, n>& a) { for( int i = 0; i < (n/2); i++ ) ptr[i] = a.s[i+(n/2)]; } /** @brief Store data to memory (aligned) Store register contents to memory. Scheme: @code REG {A B C D} ==> MEM {A B C D} @endcode Pointer __should__ be aligned by 16-byte boundary. */ template<typename _Tp, int n> inline void v_store_aligned(_Tp* ptr, const v_reg<_Tp, n>& a) { for( int i = 0; i < n; i++ ) ptr[i] = a.s[i]; } /** @brief Combine vector from first elements of two vectors Scheme: @code {A1 A2 A3 A4} {B1 B2 B3 B4} --------------- {A1 A2 B1 B2} @endcode For all types except 64-bit. */ template<typename _Tp, int n> inline v_reg<_Tp, n> v_combine_low(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { v_reg<_Tp, n> c; for( int i = 0; i < (n/2); i++ ) { c.s[i] = a.s[i]; c.s[i+(n/2)] = b.s[i]; } return c; } /** @brief Combine vector from last elements of two vectors Scheme: @code {A1 A2 A3 A4} {B1 B2 B3 B4} --------------- {A3 A4 B3 B4} @endcode For all types except 64-bit. */ template<typename _Tp, int n> inline v_reg<_Tp, n> v_combine_high(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { v_reg<_Tp, n> c; for( int i = 0; i < (n/2); i++ ) { c.s[i] = a.s[i+(n/2)]; c.s[i+(n/2)] = b.s[i+(n/2)]; } return c; } /** @brief Combine two vectors from lower and higher parts of two other vectors @code{.cpp} low = cv::v_combine_low(a, b); high = cv::v_combine_high(a, b); @endcode */ template<typename _Tp, int n> inline void v_recombine(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, v_reg<_Tp, n>& low, v_reg<_Tp, n>& high) { for( int i = 0; i < (n/2); i++ ) { low.s[i] = a.s[i]; low.s[i+(n/2)] = b.s[i]; high.s[i] = a.s[i+(n/2)]; high.s[i+(n/2)] = b.s[i+(n/2)]; } } /** @brief Vector extract Scheme: @code {A1 A2 A3 A4} {B1 B2 B3 B4} ======================== shift = 1 {A2 A3 A4 B1} shift = 2 {A3 A4 B1 B2} shift = 3 {A4 B1 B2 B3} @endcode Restriction: 0 <= shift < nlanes Usage: @code v_int32x4 a, b, c; c = v_extract<2>(a, b); @endcode For integer types only. */ template<int s, typename _Tp, int n> inline v_reg<_Tp, n> v_extract(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) { v_reg<_Tp, n> r; const int shift = n - s; int i = 0; for (; i < shift; ++i) r.s[i] = a.s[i+s]; for (; i < n; ++i) r.s[i] = b.s[i-shift]; return r; } /** @brief Round Rounds each value. Input type is float vector ==> output type is int vector.*/ template<int n> inline v_reg<int, n> v_round(const v_reg<float, n>& a) { v_reg<int, n> c; for( int i = 0; i < n; i++ ) c.s[i] = cvRound(a.s[i]); return c; } /** @brief Floor Floor each value. Input type is float vector ==> output type is int vector.*/ template<int n> inline v_reg<int, n> v_floor(const v_reg<float, n>& a) { v_reg<int, n> c; for( int i = 0; i < n; i++ ) c.s[i] = cvFloor(a.s[i]); return c; } /** @brief Ceil Ceil each value. Input type is float vector ==> output type is int vector.*/ template<int n> inline v_reg<int, n> v_ceil(const v_reg<float, n>& a) { v_reg<int, n> c; for( int i = 0; i < n; i++ ) c.s[i] = cvCeil(a.s[i]); return c; } /** @brief Trunc Truncate each value. Input type is float vector ==> output type is int vector.*/ template<int n> inline v_reg<int, n> v_trunc(const v_reg<float, n>& a) { v_reg<int, n> c; for( int i = 0; i < n; i++ ) c.s[i] = (int)(a.s[i]); return c; } /** @overload */ template<int n> inline v_reg<int, n*2> v_round(const v_reg<double, n>& a) { v_reg<int, n*2> c; for( int i = 0; i < n; i++ ) { c.s[i] = cvRound(a.s[i]); c.s[i+n] = 0; } return c; } /** @overload */ template<int n> inline v_reg<int, n*2> v_floor(const v_reg<double, n>& a) { v_reg<int, n> c; for( int i = 0; i < n; i++ ) { c.s[i] = cvFloor(a.s[i]); c.s[i+n] = 0; } return c; } /** @overload */ template<int n> inline v_reg<int, n*2> v_ceil(const v_reg<double, n>& a) { v_reg<int, n> c; for( int i = 0; i < n; i++ ) { c.s[i] = cvCeil(a.s[i]); c.s[i+n] = 0; } return c; } /** @overload */ template<int n> inline v_reg<int, n*2> v_trunc(const v_reg<double, n>& a) { v_reg<int, n> c; for( int i = 0; i < n; i++ ) { c.s[i] = cvCeil(a.s[i]); c.s[i+n] = 0; } return c; } /** @brief Convert to float Supported input type is cv::v_int32x4. */ template<int n> inline v_reg<float, n> v_cvt_f32(const v_reg<int, n>& a) { v_reg<float, n> c; for( int i = 0; i < n; i++ ) c.s[i] = (float)a.s[i]; return c; } /** @brief Convert to double Supported input type is cv::v_int32x4. */ template<int n> inline v_reg<double, n> v_cvt_f64(const v_reg<int, n*2>& a) { v_reg<double, n> c; for( int i = 0; i < n; i++ ) c.s[i] = (double)a.s[i]; return c; } /** @brief Convert to double Supported input type is cv::v_float32x4. */ template<int n> inline v_reg<double, n> v_cvt_f64(const v_reg<float, n*2>& a) { v_reg<double, n> c; for( int i = 0; i < n; i++ ) c.s[i] = (double)a.s[i]; return c; } /** @brief Transpose 4x4 matrix Scheme: @code a0 {A1 A2 A3 A4} a1 {B1 B2 B3 B4} a2 {C1 C2 C3 C4} a3 {D1 D2 D3 D4} =============== b0 {A1 B1 C1 D1} b1 {A2 B2 C2 D2} b2 {A3 B3 C3 D3} b3 {A4 B4 C4 D4} @endcode */ template<typename _Tp> inline void v_transpose4x4( v_reg<_Tp, 4>& a0, const v_reg<_Tp, 4>& a1, const v_reg<_Tp, 4>& a2, const v_reg<_Tp, 4>& a3, v_reg<_Tp, 4>& b0, v_reg<_Tp, 4>& b1, v_reg<_Tp, 4>& b2, v_reg<_Tp, 4>& b3 ) { b0 = v_reg<_Tp, 4>(a0.s[0], a1.s[0], a2.s[0], a3.s[0]); b1 = v_reg<_Tp, 4>(a0.s[1], a1.s[1], a2.s[1], a3.s[1]); b2 = v_reg<_Tp, 4>(a0.s[2], a1.s[2], a2.s[2], a3.s[2]); b3 = v_reg<_Tp, 4>(a0.s[3], a1.s[3], a2.s[3], a3.s[3]); } //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_INIT_ZERO(_Tpvec, _Tp, suffix) \ inline _Tpvec v_setzero_##suffix() { return _Tpvec::zero(); } //! @name Init with zero //! @{ //! @brief Create new vector with zero elements OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint8x16, uchar, u8) OPENCV_HAL_IMPL_C_INIT_ZERO(v_int8x16, schar, s8) OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint16x8, ushort, u16) OPENCV_HAL_IMPL_C_INIT_ZERO(v_int16x8, short, s16) OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint32x4, unsigned, u32) OPENCV_HAL_IMPL_C_INIT_ZERO(v_int32x4, int, s32) OPENCV_HAL_IMPL_C_INIT_ZERO(v_float32x4, float, f32) OPENCV_HAL_IMPL_C_INIT_ZERO(v_float64x2, double, f64) OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint64x2, uint64, u64) OPENCV_HAL_IMPL_C_INIT_ZERO(v_int64x2, int64, s64) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_INIT_VAL(_Tpvec, _Tp, suffix) \ inline _Tpvec v_setall_##suffix(_Tp val) { return _Tpvec::all(val); } //! @name Init with value //! @{ //! @brief Create new vector with elements set to a specific value OPENCV_HAL_IMPL_C_INIT_VAL(v_uint8x16, uchar, u8) OPENCV_HAL_IMPL_C_INIT_VAL(v_int8x16, schar, s8) OPENCV_HAL_IMPL_C_INIT_VAL(v_uint16x8, ushort, u16) OPENCV_HAL_IMPL_C_INIT_VAL(v_int16x8, short, s16) OPENCV_HAL_IMPL_C_INIT_VAL(v_uint32x4, unsigned, u32) OPENCV_HAL_IMPL_C_INIT_VAL(v_int32x4, int, s32) OPENCV_HAL_IMPL_C_INIT_VAL(v_float32x4, float, f32) OPENCV_HAL_IMPL_C_INIT_VAL(v_float64x2, double, f64) OPENCV_HAL_IMPL_C_INIT_VAL(v_uint64x2, uint64, u64) OPENCV_HAL_IMPL_C_INIT_VAL(v_int64x2, int64, s64) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_REINTERPRET(_Tpvec, _Tp, suffix) \ template<typename _Tp0, int n0> inline _Tpvec \ v_reinterpret_as_##suffix(const v_reg<_Tp0, n0>& a) \ { return a.template reinterpret_as<_Tp, _Tpvec::nlanes>(); } //! @name Reinterpret //! @{ //! @brief Convert vector to different type without modifying underlying data. OPENCV_HAL_IMPL_C_REINTERPRET(v_uint8x16, uchar, u8) OPENCV_HAL_IMPL_C_REINTERPRET(v_int8x16, schar, s8) OPENCV_HAL_IMPL_C_REINTERPRET(v_uint16x8, ushort, u16) OPENCV_HAL_IMPL_C_REINTERPRET(v_int16x8, short, s16) OPENCV_HAL_IMPL_C_REINTERPRET(v_uint32x4, unsigned, u32) OPENCV_HAL_IMPL_C_REINTERPRET(v_int32x4, int, s32) OPENCV_HAL_IMPL_C_REINTERPRET(v_float32x4, float, f32) OPENCV_HAL_IMPL_C_REINTERPRET(v_float64x2, double, f64) OPENCV_HAL_IMPL_C_REINTERPRET(v_uint64x2, uint64, u64) OPENCV_HAL_IMPL_C_REINTERPRET(v_int64x2, int64, s64) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_SHIFTL(_Tpvec, _Tp) \ template<int n> inline _Tpvec v_shl(const _Tpvec& a) \ { return a << n; } //! @name Left shift //! @{ //! @brief Shift left OPENCV_HAL_IMPL_C_SHIFTL(v_uint16x8, ushort) OPENCV_HAL_IMPL_C_SHIFTL(v_int16x8, short) OPENCV_HAL_IMPL_C_SHIFTL(v_uint32x4, unsigned) OPENCV_HAL_IMPL_C_SHIFTL(v_int32x4, int) OPENCV_HAL_IMPL_C_SHIFTL(v_uint64x2, uint64) OPENCV_HAL_IMPL_C_SHIFTL(v_int64x2, int64) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_SHIFTR(_Tpvec, _Tp) \ template<int n> inline _Tpvec v_shr(const _Tpvec& a) \ { return a >> n; } //! @name Right shift //! @{ //! @brief Shift right OPENCV_HAL_IMPL_C_SHIFTR(v_uint16x8, ushort) OPENCV_HAL_IMPL_C_SHIFTR(v_int16x8, short) OPENCV_HAL_IMPL_C_SHIFTR(v_uint32x4, unsigned) OPENCV_HAL_IMPL_C_SHIFTR(v_int32x4, int) OPENCV_HAL_IMPL_C_SHIFTR(v_uint64x2, uint64) OPENCV_HAL_IMPL_C_SHIFTR(v_int64x2, int64) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_RSHIFTR(_Tpvec, _Tp) \ template<int n> inline _Tpvec v_rshr(const _Tpvec& a) \ { \ _Tpvec c; \ for( int i = 0; i < _Tpvec::nlanes; i++ ) \ c.s[i] = (_Tp)((a.s[i] + ((_Tp)1 << (n - 1))) >> n); \ return c; \ } //! @name Rounding shift //! @{ //! @brief Rounding shift right OPENCV_HAL_IMPL_C_RSHIFTR(v_uint16x8, ushort) OPENCV_HAL_IMPL_C_RSHIFTR(v_int16x8, short) OPENCV_HAL_IMPL_C_RSHIFTR(v_uint32x4, unsigned) OPENCV_HAL_IMPL_C_RSHIFTR(v_int32x4, int) OPENCV_HAL_IMPL_C_RSHIFTR(v_uint64x2, uint64) OPENCV_HAL_IMPL_C_RSHIFTR(v_int64x2, int64) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_PACK(_Tpvec, _Tpnvec, _Tpn, pack_suffix) \ inline _Tpnvec v_##pack_suffix(const _Tpvec& a, const _Tpvec& b) \ { \ _Tpnvec c; \ for( int i = 0; i < _Tpvec::nlanes; i++ ) \ { \ c.s[i] = saturate_cast<_Tpn>(a.s[i]); \ c.s[i+_Tpvec::nlanes] = saturate_cast<_Tpn>(b.s[i]); \ } \ return c; \ } //! @name Pack //! @{ //! @brief Pack values from two vectors to one //! //! Return vector type have twice more elements than input vector types. Variant with _u_ suffix also //! converts to corresponding unsigned type. //! //! - pack: for 16-, 32- and 64-bit integer input types //! - pack_u: for 16- and 32-bit signed integer input types OPENCV_HAL_IMPL_C_PACK(v_uint16x8, v_uint8x16, uchar, pack) OPENCV_HAL_IMPL_C_PACK(v_int16x8, v_int8x16, schar, pack) OPENCV_HAL_IMPL_C_PACK(v_uint32x4, v_uint16x8, ushort, pack) OPENCV_HAL_IMPL_C_PACK(v_int32x4, v_int16x8, short, pack) OPENCV_HAL_IMPL_C_PACK(v_uint64x2, v_uint32x4, unsigned, pack) OPENCV_HAL_IMPL_C_PACK(v_int64x2, v_int32x4, int, pack) OPENCV_HAL_IMPL_C_PACK(v_int16x8, v_uint8x16, uchar, pack_u) OPENCV_HAL_IMPL_C_PACK(v_int32x4, v_uint16x8, ushort, pack_u) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_RSHR_PACK(_Tpvec, _Tp, _Tpnvec, _Tpn, pack_suffix) \ template<int n> inline _Tpnvec v_rshr_##pack_suffix(const _Tpvec& a, const _Tpvec& b) \ { \ _Tpnvec c; \ for( int i = 0; i < _Tpvec::nlanes; i++ ) \ { \ c.s[i] = saturate_cast<_Tpn>((a.s[i] + ((_Tp)1 << (n - 1))) >> n); \ c.s[i+_Tpvec::nlanes] = saturate_cast<_Tpn>((b.s[i] + ((_Tp)1 << (n - 1))) >> n); \ } \ return c; \ } //! @name Pack with rounding shift //! @{ //! @brief Pack values from two vectors to one with rounding shift //! //! Values from the input vectors will be shifted right by _n_ bits with rounding, converted to narrower //! type and returned in the result vector. Variant with _u_ suffix converts to unsigned type. //! //! - pack: for 16-, 32- and 64-bit integer input types //! - pack_u: for 16- and 32-bit signed integer input types OPENCV_HAL_IMPL_C_RSHR_PACK(v_uint16x8, ushort, v_uint8x16, uchar, pack) OPENCV_HAL_IMPL_C_RSHR_PACK(v_int16x8, short, v_int8x16, schar, pack) OPENCV_HAL_IMPL_C_RSHR_PACK(v_uint32x4, unsigned, v_uint16x8, ushort, pack) OPENCV_HAL_IMPL_C_RSHR_PACK(v_int32x4, int, v_int16x8, short, pack) OPENCV_HAL_IMPL_C_RSHR_PACK(v_uint64x2, uint64, v_uint32x4, unsigned, pack) OPENCV_HAL_IMPL_C_RSHR_PACK(v_int64x2, int64, v_int32x4, int, pack) OPENCV_HAL_IMPL_C_RSHR_PACK(v_int16x8, short, v_uint8x16, uchar, pack_u) OPENCV_HAL_IMPL_C_RSHR_PACK(v_int32x4, int, v_uint16x8, ushort, pack_u) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_PACK_STORE(_Tpvec, _Tp, _Tpnvec, _Tpn, pack_suffix) \ inline void v_##pack_suffix##_store(_Tpn* ptr, const _Tpvec& a) \ { \ for( int i = 0; i < _Tpvec::nlanes; i++ ) \ ptr[i] = saturate_cast<_Tpn>(a.s[i]); \ } //! @name Pack and store //! @{ //! @brief Store values from the input vector into memory with pack //! //! Values will be stored into memory with saturating conversion to narrower type. //! Variant with _u_ suffix converts to corresponding unsigned type. //! //! - pack: for 16-, 32- and 64-bit integer input types //! - pack_u: for 16- and 32-bit signed integer input types OPENCV_HAL_IMPL_C_PACK_STORE(v_uint16x8, ushort, v_uint8x16, uchar, pack) OPENCV_HAL_IMPL_C_PACK_STORE(v_int16x8, short, v_int8x16, schar, pack) OPENCV_HAL_IMPL_C_PACK_STORE(v_uint32x4, unsigned, v_uint16x8, ushort, pack) OPENCV_HAL_IMPL_C_PACK_STORE(v_int32x4, int, v_int16x8, short, pack) OPENCV_HAL_IMPL_C_PACK_STORE(v_uint64x2, uint64, v_uint32x4, unsigned, pack) OPENCV_HAL_IMPL_C_PACK_STORE(v_int64x2, int64, v_int32x4, int, pack) OPENCV_HAL_IMPL_C_PACK_STORE(v_int16x8, short, v_uint8x16, uchar, pack_u) OPENCV_HAL_IMPL_C_PACK_STORE(v_int32x4, int, v_uint16x8, ushort, pack_u) //! @} //! @brief Helper macro //! @ingroup core_hal_intrin_impl #define OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(_Tpvec, _Tp, _Tpnvec, _Tpn, pack_suffix) \ template<int n> inline void v_rshr_##pack_suffix##_store(_Tpn* ptr, const _Tpvec& a) \ { \ for( int i = 0; i < _Tpvec::nlanes; i++ ) \ ptr[i] = saturate_cast<_Tpn>((a.s[i] + ((_Tp)1 << (n - 1))) >> n); \ } //! @name Pack and store with rounding shift //! @{ //! @brief Store values from the input vector into memory with pack //! //! Values will be shifted _n_ bits right with rounding, converted to narrower type and stored into //! memory. Variant with _u_ suffix converts to unsigned type. //! //! - pack: for 16-, 32- and 64-bit integer input types //! - pack_u: for 16- and 32-bit signed integer input types OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_uint16x8, ushort, v_uint8x16, uchar, pack) OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_int16x8, short, v_int8x16, schar, pack) OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_uint32x4, unsigned, v_uint16x8, ushort, pack) OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_int32x4, int, v_int16x8, short, pack) OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_uint64x2, uint64, v_uint32x4, unsigned, pack) OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_int64x2, int64, v_int32x4, int, pack) OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_int16x8, short, v_uint8x16, uchar, pack_u) OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(v_int32x4, int, v_uint16x8, ushort, pack_u) //! @} /** @brief Matrix multiplication Scheme: @code {A0 A1 A2 A3} |V0| {B0 B1 B2 B3} |V1| {C0 C1 C2 C3} |V2| {D0 D1 D2 D3} x |V3| ==================== {R0 R1 R2 R3}, where: R0 = A0V0 + A1V1 + A2V2 + A3V3, R1 = B0V0 + B1V1 + B2V2 + B3V3 ... @endcode */ inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, const v_float32x4& m1, const v_float32x4& m2, const v_float32x4& m3) { return v_float32x4(v.s[0]*m0.s[0] + v.s[1]*m1.s[0] + v.s[2]*m2.s[0] + v.s[3]*m3.s[0], v.s[0]*m0.s[1] + v.s[1]*m1.s[1] + v.s[2]*m2.s[1] + v.s[3]*m3.s[1], v.s[0]*m0.s[2] + v.s[1]*m1.s[2] + v.s[2]*m2.s[2] + v.s[3]*m3.s[2], v.s[0]*m0.s[3] + v.s[1]*m1.s[3] + v.s[2]*m2.s[3] + v.s[3]*m3.s[3]); } //! @} //! @name Check SIMD support //! @{ //! @brief Check CPU capability of SIMD operation static inline bool hasSIMD128() { return false; } //! @} } #endif
[ "hersh.godse@berkeley.edu" ]
hersh.godse@berkeley.edu
ea33dd189bceb0c9657b7811ced87b0551c38f85
a3d9725023c004295c92431739b06365e7880f6f
/src/Commands/TimedIntake.cpp
5049dfa94791bb3ad455a4ac5b1ae44bdbc88c3b
[]
no_license
4329/MOState2015
e95ce680a55a03e17a7a1906b3974206184da27c
22aec6cb9fba9f1fca63b86bfe0859a7ceebf984
refs/heads/master
2016-09-05T11:23:29.662296
2015-04-30T01:29:04
2015-04-30T01:29:04
34,827,342
0
0
null
null
null
null
UTF-8
C++
false
false
1,599
cpp
// RobotBuilder Version: 1.5 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // C++ from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. #include "TimedIntake.h" TimedIntake::TimedIntake() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES Requires(Robot::spinners); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES first = false; TimeToRunSecs = Preferences::GetInstance()->GetDouble("TimedIntake::TimeToRunSecs"); } // Called just before this Command runs the first time void TimedIntake::Initialize() { } // Called repeatedly when this Command is scheduled to run void TimedIntake::Execute() { if (!first) { first = true; myTimer.Start(); } Robot::spinners->Intake(); } // Make this return true when this Command no longer needs to run execute() bool TimedIntake::IsFinished() { return myTimer.HasPeriodPassed(TimeToRunSecs); } // Called once after isFinished returns true void TimedIntake::End() { Robot::spinners->Stop(); myTimer.Stop(); myTimer.Reset(); first = false; } // Called when another command which requires one or more of the same // subsystems is scheduled to run void TimedIntake::Interrupted() { }
[ "mdballard2@charter.net" ]
mdballard2@charter.net
08ef8245be75532fb1e587483bb160700b177932
c0c0af2d8a1c5e3c0a036c6c3b934f3d43c0f5cf
/MFC/Deliver/Deliver.cpp
fa2bbee6b0f88e9ff2ec8f0fe1185a77466c3fec
[]
no_license
feiqiu/repository-of-projects
5f796734e906ccf16b386f7c8f486669e75159cb
a0393d01f57b14d030064cd45d3cd9bb538d4419
refs/heads/master
2021-05-31T10:14:12.565392
2014-02-10T06:04:28
2014-02-10T06:04:28
null
0
0
null
null
null
null
GB18030
C++
false
false
3,605
cpp
// Deliver.cpp : 定义应用程序的类行为。 // #include "stdafx.h" #include "Deliver.h" #include "MainFrm.h" #include "DeliverDoc.h" #include "DeliverView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CDeliverApp BEGIN_MESSAGE_MAP(CDeliverApp, CWinApp) ON_COMMAND(ID_APP_ABOUT, &CDeliverApp::OnAppAbout) // 基于文件的标准文档命令 ON_COMMAND(ID_FILE_NEW, &CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen) END_MESSAGE_MAP() // CDeliverApp 构造 CDeliverApp::CDeliverApp() { // TODO: 在此处添加构造代码, // 将所有重要的初始化放置在 InitInstance 中 } // 唯一的一个 CDeliverApp 对象 CDeliverApp theApp; // CDeliverApp 初始化 BOOL CDeliverApp::InitInstance() { // 如果一个运行在 Windows XP 上的应用程序清单指定要 // 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式, //则需要 InitCommonControlsEx()。否则,将无法创建窗口。 INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // 将它设置为包括所有要在应用程序中使用的 // 公共控件类。 InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); // 初始化 OLE 库 if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // 标准初始化 // 如果未使用这些功能并希望减小 // 最终可执行文件的大小,则应移除下列 // 不需要的特定初始化例程 // 更改用于存储设置的注册表项 // TODO: 应适当修改该字符串, // 例如修改为公司或组织名 SetRegistryKey(_T("应用程序向导生成的本地应用程序")); LoadStdProfileSettings(4); // 加载标准 INI 文件选项(包括 MRU) // 注册应用程序的文档模板。文档模板 // 将用作文档、框架窗口和视图之间的连接 CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CDeliverDoc), RUNTIME_CLASS(CMainFrame), // 主 SDI 框架窗口 RUNTIME_CLASS(CDeliverView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // 分析标准外壳命令、DDE、打开文件操作的命令行 CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // 调度在命令行中指定的命令。如果 // 用 /RegServer、/Register、/Unregserver 或 /Unregister 启动应用程序,则返回 FALSE。 if (!ProcessShellCommand(cmdInfo)) return FALSE; // 唯一的一个窗口已初始化,因此显示它并对其进行更新 m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); // 仅当具有后缀时才调用 DragAcceptFiles // 在 SDI 应用程序中,这应在 ProcessShellCommand 之后发生 return TRUE; } // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialog { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // 用于运行对话框的应用程序命令 void CDeliverApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // CDeliverApp 消息处理程序
[ "Micheal19840929@81659778-87ce-11de-a4f2-b7219ab9ea91" ]
Micheal19840929@81659778-87ce-11de-a4f2-b7219ab9ea91
626c0107a7f55f1badb97b703c327fcffb2aa23f
67ed24f7e68014e3dbe8970ca759301f670dc885
/win10.19042/SysWOW64/winhttpcom.dll.cpp
3c90669402e13b5573aefa93b64297293457c8d9
[]
no_license
nil-ref/dll-exports
d010bd77a00048e52875d2a739ea6a0576c82839
42ccc11589b2eb91b1aa82261455df8ee88fa40c
refs/heads/main
2023-04-20T21:28:05.295797
2021-05-07T14:06:23
2021-05-07T14:06:23
401,055,938
1
0
null
2021-08-29T14:00:50
2021-08-29T14:00:49
null
UTF-8
C++
false
false
216
cpp
#pragma comment(linker, "/export:DllCanUnloadNow=\"C:\\Windows\\SysWOW64\\winhttpcom.DllCanUnloadNow\"") #pragma comment(linker, "/export:DllGetClassObject=\"C:\\Windows\\SysWOW64\\winhttpcom.DllGetClassObject\"")
[ "magnus@stubman.eu" ]
magnus@stubman.eu
9491ec88823a93e973422f5f30bb2cc815938dcc
7435c4218f847c1145f2d8e60468fcb8abca1979
/Vaango/src/Core/Grid/BoundaryConditions/BoundCondBaseP.h
0dd246d37b34b8d2d750f4aaf800a39062f17480
[]
no_license
markguozhiming/ParSim
bb0d7162803279e499daf58dc8404440b50de38d
6afe2608edd85ed25eafff6085adad553e9739bc
refs/heads/master
2020-05-16T19:04:09.700317
2019-02-12T02:30:45
2019-02-12T02:30:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,373
h
/* * The MIT License * * Copyright (c) 2013-2014 Callaghan Innovation, New Zealand * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef __VAANGO_BOUND_COND_BASEP_H__ #define __VAANGO_BOUND_COND_BASEP_H__ #include <memory> namespace Uintah { class BoundCondBase; typedef std::shared_ptr<BoundCondBase> BoundCondBaseP; } #endif
[ "b.banerjee.nz@gmail.com" ]
b.banerjee.nz@gmail.com
3480e789028abf02b0608dc62c6bd53859034442
d6277591f92c4d021bee86f4532d87556922783c
/codes/codeforces/140A.cpp
3bdb57bac30f1961b7f83813612686f99a8a1cde
[]
no_license
masterchef2209/coding-solutions
83a1e8083f7db7f99ca16c9a8a584684f2ad8726
48c7aa127e2f2353cc18cf064fbd5b57875c1efa
refs/heads/master
2021-05-26T06:02:53.579607
2020-04-25T21:23:56
2020-04-25T21:23:56
127,779,581
0
0
null
null
null
null
UTF-8
C++
false
false
1,715
cpp
/*Read the problem carefully before starting to work on it*/ #include <bits/stdc++.h> //#include <boost/multiprecision/cpp_int.hpp> //using namespace boost::multiprecision; //#include <ext/pb_ds/assoc_container.hpp> //#include <ext/pb_ds/tree_policy.hpp> using namespace std; //using namespace __gnu_pbds; typedef long long ll; typedef long double ld; typedef complex<ld> cd; //ll ncr(ll n,ll r){ll ans=1;r=min(r,n-r);for (int i=1;i<=r;i++){ans*=(n-r+i);ans/=i;}return ans;} #define pb push_back #define eb emplace_back #define mp(x,y) make_pair(x,y) #define mod 1000000007 double PI=3.1415926535897932384626; //template<typename T> T power(T x,T y,ll m=mod){T ans=1;while(y>0){if(y&1LL) ans=(ans*x)%m;y>>=1LL;x=(x*x)%m;}return ans%m;} #define bip(n) __builtin_popcount(n)//no of ones bit in binary!! #define bictz(n) __builtin_ctz(n)//no of trailing zeroes in binary!! #define biclz(n) __builtin_clz(n)//no of leading zeroes in binary!! #define bffs(n) __builtin_ffs(n)//index of first one bit!! typedef pair<int, int> ii; typedef tuple<int, int, int> iii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<ld> vd; typedef vector<ll> vl; //#define fi1 ifstream cin("input.txt") //#define of1 ofstream cout("output.txt") //typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> ost; #define fi first #define se second int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); double n,R,r; double ep=10e-10; cin>>n>>R>>r; double temp=(R-r)*sin(PI/n); if(n==1) { if(r<=(R+ep)) { cout<<"YES"; } else { cout<<"NO"; } return 0; } if((r<(temp+ep))) cout<<"YES"; else cout<<"NO"; return 0; }
[ "huk2209@gmail.com" ]
huk2209@gmail.com
b1b4363bfcbd4fdcd84948a1ce3a7f970f04d136
fbb16c652f8db717ef9efbb653fc7b520fb23771
/WS2812_ESP_RMT.cpp
20c52f38f2f28f898bd9fbbf08f6251280077256
[]
no_license
jordan9001/esp32_javascript_lights
a10f7237a33d624562c3b5cab219c596de57770a
a47c91a9cdfb37288ccf2d2e428e8e53d5b1bf2b
refs/heads/master
2020-09-28T10:52:48.033927
2019-12-18T02:53:06
2019-12-18T02:53:06
226,763,342
0
0
null
null
null
null
UTF-8
C++
false
false
3,288
cpp
#include "WS2812_ESP_RMT.h" // The esp32-snippets by nkolban were super helpful here! //I just rewrote it to better understand ESPRMTLED::ESPRMTLED(uint16_t numleds, uint8_t pin, uint16_t rmt_chan) { this->numpixels = numleds; this->numbits = (numleds * 24) + 1; this->channel = (rmt_channel_t)channel; // I need 24 bits per led, plus a terminator this->bits = new rmt_item32_t[this->numbits]; this->colors = new uint32_t[numleds]; this->clear(); pinMode(pin, OUTPUT); /* * typedef struct { * union { * struct { * uint32_t duration0 :15; * uint32_t level0 :1; * uint32_t duration1 :15; * uint32_t level1 :1; * }; * uint32_t val; * }; * } rmt_item32_t; */ // all the timing is done here. // the clk_div is 8, so we are working with 100ns units in duration this->highbit.duration0 = 8; // should be 0.8 us this->highbit.level0 = 1; this->highbit.duration1 = 5; // shouod be .45 us, but we have .15 wiggle room this->highbit.level1 = 0; this->lowbit.duration0 = 4; // should be 0.4 us this->lowbit.level0 = 1; this->lowbit.duration1 = 8; // should be 0.85 us, but we have .15 us wiggle room this->lowbit.level1 = 0; this->termbit.val = 0; rmt_config_t config; config.rmt_mode = RMT_MODE_TX; config.channel = this->channel; config.gpio_num = (gpio_num_t)pin; // number of memory blocks used for now just take as many as we can get config.mem_block_num = 8 - rmt_chan; // range of pulse len generated. Source clock is typically 80Mhz. // So div by 8 means each tick is at 100ns config.clk_div = 8; config.tx_config.loop_en = 0; config.tx_config.carrier_en = 0; config.tx_config.idle_output_en = 1; config.tx_config.idle_level = (rmt_idle_level_t)0; // we disabled the carrier, but fill it out anyway config.tx_config.carrier_freq_hz = 10000; config.tx_config.carrier_level = (rmt_carrier_level_t)1; config.tx_config.carrier_duty_percent = 50; rmt_config(&config); // no rx buf, default flags rmt_driver_install(this->channel, 0, 0); } ESPRMTLED::~ESPRMTLED(void) { delete[] this->colors; delete[] this->bits; } void ESPRMTLED::show() { rmt_item32_t* cur; uint16_t i; int bt; uint32_t c; bool bitset; cur = this->bits; for (i=0; i<this->numpixels; i++) { c = this->colors[i]; // ok we have the color, we need to set up our bits from MSB to LSB in GRB // set up G for (bt = 15; bt >= 8; bt--) { bitset = c & (1 << bt); *cur = (bitset) ? this->highbit : this->lowbit; cur++; } // set up R for (bt = 23; bt >= 16; bt--) { bitset = c & (1 << bt); *cur = (bitset) ? this->highbit : this->lowbit; cur++; } // set up B for (bt = 7; bt >= 0; bt--) { bitset = c & (1 << bt); *cur = (bitset) ? this->highbit : this->lowbit; cur++; } } // set terminator *cur = this->termbit; // tell the rmt to write it out rmt_write_items(this->channel, this->bits, this->numbits, 1); // wait_tx_done } void ESPRMTLED::clear() { uint16_t i; for (i=0; i<this->numpixels; i++) { this->colors[i] = 0; } } void ESPRMTLED::setPixelColor(uint16_t i, uint32_t color) { if (i > this->numpixels) { return; } // Store GRB //this->colors[i] = ((color & 0xff0000) >> 8) | ((color & 0xff00) << 8) | (color & ff); this->colors[i] = color; }
[ "jordan9001@gmail.com" ]
jordan9001@gmail.com
e0fb7a36994e53663cf72e5ebb0fec8fde020273
89416910e56dfe16a75a4a02781585d369cde45b
/ICMP_Win_Client/ArgsManager.cpp
55bc88dcfceda339c600492c2ec2cd2727d65d73
[]
no_license
GabrielReusRodriguez/ICMP_win
8bc54966c2fb31a76fa26d2e473bcf2d77bffa71
26d8a504cd9a3e991105b1f76732ee2f643e0886
refs/heads/master
2020-07-29T08:39:14.935019
2019-10-08T20:10:25
2019-10-08T20:10:25
209,732,689
0
1
null
null
null
null
UTF-8
C++
false
false
2,270
cpp
#include "ArgsManager.h" #include <vector> #include <iostream> #define NO_MIN_ARGS_CHECK -1 ArgsManager::ArgsManager(int _argc, char* _argv[]) throw (ArgsException) { procesa(_argc, _argv, NO_MIN_ARGS_CHECK); } ArgsManager::ArgsManager(int _argc, char* _argv[], int _minArgc) throw (ArgsException) { procesa(_argc, _argv, -_minArgc); } ArgsManager::~ArgsManager() { } void ArgsManager::procesa(int _argc, char* _argv[], int _minArgc) throw (ArgsException){ //http://www.cplusplus.com/articles/DEN36Up4/ if (_minArgc != NO_MIN_ARGS_CHECK && _argc < _minArgc) { muestraUso(_argv[0]); throw ArgsException(1, "Incorrect number of arguments"); } //std::vector <std::string> sources; //std::string destination; for (int i = 1; i < _argc; ++i) { std::string arg = _argv[i]; if ((arg == "-h") || (arg == "--help")) { muestraUso(_argv[0]); return; } /* else if ((arg == "-d") || (arg == "--destination")) { if (i + 1 < argc) { // Make sure we aren't at the end of argv! destination = argv[i++]; // Increment 'i' so we don't get the argument as the next argv[i]. } else { // Uh-oh, there was no argument to the destination option. std::cerr << "--destination option requires one argument." << std::endl; return 1; } } */ else if ((arg == "-p") || (arg == "--payload")) { if (i + 1 < _argc) { // Make sure we aren't at the end of argv! this->payload = _argv[i++]; // Increment 'i' so we don't get the argument as the next argv[i]. } else { // Uh-oh, there was no argument to the destination option. std::cerr << "--payload option requires one argument." << std::endl; throw ArgsException(2, "Payload option requires one argument"); } } else { this->destino = _argv[i]; //sources.push_back(argv[i]); } } } void ArgsManager::muestraUso(std::string name) { std::cerr << "Usage: " << name << " <option(s)> SOURCES" << "Options:\n" << "\t-h,--help\t\tShow this help message\n" //<< "\t-d,--destination\tSpecify the destination HOST\n" << "\t-p,--payload \tSpecify the Payload to send\n" << "\tdestination\n" << std::endl; } std::string ArgsManager::getDestino() { return this->destino; } std::string ArgsManager::getPayload() { return this->payload; }
[ "gabrielin@gmail.com" ]
gabrielin@gmail.com
a75336c354d18f1cc1e144f708e9377792ca8243
28ea54a68b4bd8f4225a33484db0dddabbe91a2c
/source/Classes/Client/UILayer/WaitingLayer.cpp
5e26011518cdf2ff4787a839558ee6e408ac7f22
[]
no_license
cash2one/hellopetclient
fad7374899a1c0bb04581caa517586ae8fb124ab
f87e47cd946858f8fe5bae6ea2bbc13b43d912d4
refs/heads/master
2020-12-24T11:52:38.157993
2015-12-26T17:07:23
2015-12-26T17:07:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,374
cpp
#include "WaitingLayer.h" #include "GameManager.h" #include "SceneLayer.h" #include "UIDefine.h" #include "AspriteManager.h" WaitingLayer::WaitingLayer(): m_pSprite(NULL) ,m_bShow(false) { m_sumHideTimer = 0; m_hidingTimer = 0 ; } WaitingLayer::~WaitingLayer() { } bool WaitingLayer::init() { bool bRet = false; do { CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); m_pSprite = AspriteManager::getInstance()->getOneFrame("UI/ui.bin", "map_ui_FRAME_ICON_LOAD"); m_pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); m_pSprite->setAnchorPoint(ccp(0.5,0.5)); this->addChild(m_pSprite, 0); setTouchEnabled(true); bRet = true; }while (0); return true; } void WaitingLayer::update(float dt) { if (m_hidingTimer >= m_sumHideTimer) { float fDelta = dt * 300; float fRotate = m_pSprite->getRotation(); m_pSprite->setRotation(fRotate + fDelta); m_pSprite->setVisible(true); } else { m_pSprite->setVisible(false); m_hidingTimer += dt; } } void WaitingLayer::ShowWaiting(bool bShowRightNow /* = true */,float sumTimer /* = 0.3 */) { if (!m_bShow) { this->setVisible(true); m_pSprite->setRotation(0); scheduleUpdate(); m_bShow = true; m_hidingTimer = 0; if (bShowRightNow) { m_sumHideTimer = 0; } else { m_sumHideTimer = sumTimer; } } } void WaitingLayer::HideWaiting() { this->setVisible(false); unscheduleUpdate(); m_bShow = false; m_sumHideTimer = 0; m_hidingTimer = 0 ; } bool WaitingLayer::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { if(isVisible()) { return true; } return false; } void WaitingLayer::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) { CCLayer::ccTouchMoved(pTouch,pEvent); } void WaitingLayer::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) { CCLayer::ccTouchEnded(pTouch,pEvent); } void WaitingLayer::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) { CCLayer::ccTouchCancelled(pTouch,pEvent); } void WaitingLayer::registerWithTouchDispatcher() { CCDirector* pDirector = CCDirector::sharedDirector(); pDirector->getTouchDispatcher()->addTargetedDelegate(this, KCCMenuOnMessageBoxPripority, true); }
[ "zhibniu@gmail.com" ]
zhibniu@gmail.com
20be960d080d0c9c0dffcb66d8f4b0780c2b793d
b28305dab0be0e03765c62b97bcd7f49a4f8073d
/chromeos/dbus/update_engine_client.h
7af4496ca667c6464d807e41709781e64931108d
[ "BSD-3-Clause" ]
permissive
svarvel/browser-android-tabs
9e5e27e0a6e302a12fe784ca06123e5ce090ced5
bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f
refs/heads/base-72.0.3626.105
2020-04-24T12:16:31.442851
2019-08-02T19:15:36
2019-08-02T19:15:36
171,950,555
1
2
NOASSERTION
2019-08-02T19:15:37
2019-02-21T21:47:44
null
UTF-8
C++
false
false
7,805
h
// 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. #ifndef CHROMEOS_DBUS_UPDATE_ENGINE_CLIENT_H_ #define CHROMEOS_DBUS_UPDATE_ENGINE_CLIENT_H_ #include <stdint.h> #include <string> #include "base/callback.h" #include "base/macros.h" #include "base/observer_list.h" #include "chromeos/chromeos_export.h" #include "chromeos/dbus/dbus_client.h" #include "chromeos/dbus/dbus_client_implementation_type.h" #include "dbus/message.h" #include "third_party/cros_system_api/dbus/update_engine/dbus-constants.h" namespace chromeos { // UpdateEngineClient is used to communicate with the update engine. class CHROMEOS_EXPORT UpdateEngineClient : public DBusClient { public: // Edges for state machine // IDLE->CHECKING_FOR_UPDATE // CHECKING_FOR_UPDATE->IDLE // CHECKING_FOR_UPDATE->UPDATE_AVAILABLE // CHECKING_FOR_UPDATE->NEED_PERMISSION_TO_UPDATE // ... // FINALIZING->UPDATE_NEED_REBOOT // Any state can transition to REPORTING_ERROR_EVENT and then on to IDLE. enum UpdateStatusOperation { UPDATE_STATUS_ERROR = -1, UPDATE_STATUS_IDLE = 0, UPDATE_STATUS_CHECKING_FOR_UPDATE, UPDATE_STATUS_UPDATE_AVAILABLE, // User permission is needed to download an update on a cellular connection. UPDATE_STATUS_NEED_PERMISSION_TO_UPDATE, UPDATE_STATUS_DOWNLOADING, UPDATE_STATUS_VERIFYING, UPDATE_STATUS_FINALIZING, UPDATE_STATUS_UPDATED_NEED_REBOOT, UPDATE_STATUS_REPORTING_ERROR_EVENT, UPDATE_STATUS_ATTEMPTING_ROLLBACK, }; // The status of the ongoing update attempt. struct Status { UpdateStatusOperation status = UPDATE_STATUS_IDLE; // 0.0 - 1.0 double download_progress = 0.0; // As reported by std::time(). int64_t last_checked_time = 0; std::string new_version; // Valid during DOWNLOADING, in bytes. int64_t new_size = 0; // True if the update is actually a rollback and the device will be wiped // when rebooted. bool is_rollback = false; }; // The result code used for RequestUpdateCheck(). enum UpdateCheckResult { UPDATE_RESULT_SUCCESS, UPDATE_RESULT_FAILED, UPDATE_RESULT_NOTIMPLEMENTED, }; // Interface for observing changes from the update engine. class Observer { public: virtual ~Observer() {} // Called when the status is updated. virtual void UpdateStatusChanged(const Status& status) {} // Called when the user's one time permission on update over cellular // connection has been granted. virtual void OnUpdateOverCellularOneTimePermissionGranted() {} }; ~UpdateEngineClient() override; // Adds and removes the observer. virtual void AddObserver(Observer* observer) = 0; virtual void RemoveObserver(Observer* observer) = 0; // Returns true if this object has the given observer. virtual bool HasObserver(const Observer* observer) const = 0; // Called once RequestUpdateCheck() is complete. Takes one parameter: // - UpdateCheckResult: the result of the update check. using UpdateCheckCallback = base::Callback<void(UpdateCheckResult)>; // Requests an update check and calls |callback| when completed. virtual void RequestUpdateCheck(const UpdateCheckCallback& callback) = 0; // Reboots if update has been performed. virtual void RebootAfterUpdate() = 0; // Starts Rollback. virtual void Rollback() = 0; // Called once CanRollbackCheck() is complete. Takes one parameter: // - bool: the result of the rollback availability check. using RollbackCheckCallback = base::Callback<void(bool can_rollback)>; // Checks if Rollback is available and calls |callback| when completed. virtual void CanRollbackCheck( const RollbackCheckCallback& callback) = 0; // Called once GetChannel() is complete. Takes one parameter; // - string: the channel name like "beta-channel". using GetChannelCallback = base::Callback<void(const std::string& channel_name)>; // Returns the last status the object received from the update engine. // // Ideally, the D-Bus client should be state-less, but there are clients // that need this information. virtual Status GetLastStatus() = 0; // Changes the current channel of the device to the target // channel. If the target channel is a less stable channel than the // current channel, then the channel change happens immediately (at // the next update check). If the target channel is a more stable // channel, then if |is_powerwash_allowed| is set to true, then also // the change happens immediately but with a powerwash if // required. Otherwise, the change takes effect eventually (when the // version on the target channel goes above the version number of // what the device currently has). |target_channel| should look like // "dev-channel", "beta-channel" or "stable-channel". virtual void SetChannel(const std::string& target_channel, bool is_powerwash_allowed) = 0; // If |get_current_channel| is set to true, calls |callback| with // the name of the channel that the device is currently // on. Otherwise, it calls it with the name of the channel the // device is supposed to be (in case of a pending channel // change). On error, calls |callback| with an empty string. virtual void GetChannel(bool get_current_channel, const GetChannelCallback& callback) = 0; // Called once GetEolStatus() is complete. Takes one parameter; // - EndOfLife Status: the end of life status of the device. using GetEolStatusCallback = base::OnceCallback<void(update_engine::EndOfLifeStatus status)>; // Get EndOfLife status of the device and calls |callback| when completed. virtual void GetEolStatus(GetEolStatusCallback callback) = 0; // Either allow or disallow receiving updates over cellular connections. // Synchronous (blocking) method. virtual void SetUpdateOverCellularPermission( bool allowed, const base::Closure& callback) = 0; // Called once SetUpdateOverCellularOneTimePermission() is complete. Takes one // parameter; // - success: indicates whether the permission is set successfully. using UpdateOverCellularOneTimePermissionCallback = base::Callback<void(bool success)>; // Sets a one time permission on a certain update in Update Engine which then // performs downloading of that update after RequestUpdateCheck() is invoked // in the |callback|. // - update_version: the Chrome OS version we want to update to. // - update_size: the size of that Chrome OS version in bytes. // These two parameters are a failsafe to prevent downloading an update that // the user didn't agree to. They should be set using the version and size we // received from update engine when it broadcasts NEED_PERMISSION_TO_UPDATE. // They are used by update engine to double-check with update server in case // there's a new update available or a delta update becomes a full update with // a larger size. virtual void SetUpdateOverCellularOneTimePermission( const std::string& update_version, int64_t update_size, const UpdateOverCellularOneTimePermissionCallback& callback) = 0; // Creates the instance. static UpdateEngineClient* Create(DBusClientImplementationType type); // Returns true if |target_channel| is more stable than |current_channel|. static bool IsTargetChannelMoreStable(const std::string& current_channel, const std::string& target_channel); protected: // Create() should be used instead. UpdateEngineClient(); private: DISALLOW_COPY_AND_ASSIGN(UpdateEngineClient); }; } // namespace chromeos #endif // CHROMEOS_DBUS_UPDATE_ENGINE_CLIENT_H_
[ "artem@brave.com" ]
artem@brave.com
6ac3dcc0ae3e956de69e7898577554e21c42badf
6fd79e415c45f3f5fd3f7e534b3c56959f223545
/Source/Ed_05_TestingGrounds/Ed_05_TestingGroundsGameMode.cpp
960a194cc952bffd7c2687539ba1f8668eb98591
[]
no_license
pobrien11/Ed_05_TestingGrounds
e05ed68ab9d16cb288f6c7d3266ab93506a7b829
819fda7ae4013d12e3791cbbd287cf10816f1409
refs/heads/master
2020-03-28T11:32:38.110532
2018-09-12T22:26:45
2018-09-12T22:26:45
148,223,577
0
0
null
null
null
null
UTF-8
C++
false
false
624
cpp
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #include "Ed_05_TestingGroundsGameMode.h" #include "Ed_05_TestingGroundsHUD.h" #include "Ed_05_TestingGroundsCharacter.h" #include "UObject/ConstructorHelpers.h" AEd_05_TestingGroundsGameMode::AEd_05_TestingGroundsGameMode() : Super() { // set default pawn class to our Blueprinted character static ConstructorHelpers::FClassFinder<APawn> PlayerPawnClassFinder(TEXT("/Game/FirstPersonCPP/Blueprints/FirstPersonCharacter")); DefaultPawnClass = PlayerPawnClassFinder.Class; // use our custom HUD class HUDClass = AEd_05_TestingGroundsHUD::StaticClass(); }
[ "patrick@patrickobrienart.com" ]
patrick@patrickobrienart.com
5f5830263b4530884cbe8193f87206d636469779
a6bb89b2ff6c1fc8c45a4f105ef528416100a360
/contrib/framewave_1.3.1_src/Framewave/domain/fwImage/src/MorphOpenBorder.cpp
8177fcbf6e7062bb097a92563ba8f9bf05ecdfe8
[ "Apache-2.0" ]
permissive
dudochkin-victor/ngxe
2c03717c45431b5a88a7ca4f3a70a2f23695cd63
34687494bcbb4a9ce8cf0a7327a7296bfa95e68a
refs/heads/master
2016-09-06T02:28:20.233312
2013-01-05T19:59:28
2013-01-05T19:59:28
7,311,793
0
1
null
null
null
null
UTF-8
C++
false
false
11,404
cpp
/* Copyright (c) 2006-2009 Advanced Micro Devices, Inc. All Rights Reserved. This software is subject to the Apache v2.0 License. */ #include "fwdev.h" #include "fwImage.h" //#include "algorithm.h" #include "FwSharedCode_SSE2.h" #include "Morphology.h" using namespace OPT_LEVEL; #if BUILD_NUM_AT_LEAST( 9999 ) //Morphology Opening operation: A open B = (A erode B) dilate B //A: source image //B: structure element(SE) or mask or kernel template< class TS, CH chSrc, DispatchType disp > FwStatus My_FW_MorphOpenBorder(const TS *pSrc, int srcStep, TS *pDst, int dstStep, FwiSize roiSize, FwiBorderType border, FwiMorphAdvState *pState) { if (pSrc == 0 || pDst == 0 || pState == 0) return fwStsNullPtrErr; if (roiSize.height < 1 || roiSize.width < 1 || roiSize.width > pState->roiSize.width) return fwStsSizeErr; int x = 0, y = 0, k = 0, channel = ChannelCount(chSrc); if(srcStep < pState->roiSize.width || dstStep < pState->roiSize.width) return fwStsStepErr; if(srcStep %4 != 0 || dstStep %4 != 0) return fwStsNotEvenStepErr; border = fwBorderRepl; if(border != fwBorderRepl) return fwStsBadArgErr; //check if all pMask elements are zero or not. //Check if all mask values are equal to zero. //for(x = 0; x < pState->maskSize.width * pState->maskSize.height; x++) //if(*(pState->pMask+x) != 0) ////Whenever found a nonzero value, set the x out of bound. So they can go out of the loop. //x = pState->maskSize.width * pState->maskSize.height + 1; //if(x != pState->maskSize.width * pState->maskSize.height + 1) //return fwStsZeroMaskValuesErr; //The temporary buffer TS *pDst_T = (TS*) fwMalloc(sizeof(TS) * (roiSize.width * roiSize.height * channel)); TS *pSrcAddr; TS *pDstAddr; //A erode B for(y = 0; y < roiSize.height; y++) { for( x = 0; x < roiSize.width; x++) { for (k=0; k<channel; k++) { //In the four-channel imamge, the alpha channel is not processed. if(k == 3) { pSrcAddr = (TS*)((Fw8u*)pSrc+y*srcStep+x*channel+k); pDstAddr = (TS*)((Fw8u*)pDst_T+y*roiSize.width*channel+x*channel+k); *pDstAddr = *pSrcAddr; } else { pDstAddr = (TS*)((Fw8u*)pDst_T+y*roiSize.width*channel+x*channel+k); *pDstAddr = 255; for(int n = 0; n < pState->maskSize.height; n++) { for(int m = 0; m < pState->maskSize.width; m++) { //if((y+n) < 0 || (x+m) < 0 || (y+n) >= roiSize.height || (x+m) >= roiSize.width) //continue; pSrcAddr = (TS*)((Fw8u*)pSrc+(y+n)*srcStep+(x+m)*channel+k); pDstAddr = (TS*)((Fw8u*)pDst_T+y*roiSize.width*channel+x*channel+k); if((pState->pMask[(n+pState->anchor.y)*(pState->maskSize.width) + (m+pState->anchor.x)]) > 0) { if(*pSrcAddr < *pDstAddr) { *pDstAddr = *pSrcAddr; } } } } } } } } //Because I already initialized and "reflect" the pMask. Now, I do not need to do the "reflect" again. //(A erode B) dilate B for(y = 0; y < roiSize.height; y++) { for( x = 0; x < roiSize.width; x++) { for (k=0; k<channel; k++) { //In the four-channel imamge, the alpha channel is not processed. if(k == 3) { pSrcAddr = (TS*)((Fw8u*)pDst+y*dstStep+x*channel+k); pDstAddr = (TS*)((Fw8u*)pDst_T+y*roiSize.width*channel+x*channel+k); *pSrcAddr = *pDstAddr; } else { pDstAddr = (TS*)((Fw8u*)pDst+y*dstStep+x*channel+k); *pDstAddr = 0; for(int n = 0; n < pState->maskSize.height; n++) { for(int m = 0; m < pState->maskSize.width; m++) { //if((y+n) < 0 || (x+m) < 0 || (y+n) >= roiSize.height || (x+m) >= roiSize.width) //continue; pSrcAddr = (TS*)((Fw8u*)pDst+y*dstStep+x*channel+k); pDstAddr = (TS*)((Fw8u*)pDst_T+(y+n)*roiSize.width*channel+(x+m)*channel+k); if((pState->pMask[(n+pState->anchor.y)*(pState->maskSize.width) + (m+pState->anchor.x)]) > 0) { if(*pDstAddr > *pSrcAddr) { *pSrcAddr = *pDstAddr; } } } } } } } } fwFree(pDst_T); return fwStsNoErr; } //void reverseMask_open(Fw8u* mask, FwiSize maskSize) //{ // for(int i = 0; i < maskSize.width * maskSize.height; i++) // *(mask+i) = 255 - *(mask+i); //} FwStatus PREFIX_OPT(OPT_PREFIX, fwiMorphOpenBorder_8u_C1R)(const Fw8u *pSrc, int srcStep, Fw8u *pDst, int dstStep, FwiSize roiSize, FwiBorderType border, FwiMorphAdvState *pState) { switch( Dispatch::Type<DT_SSE2>()) { case DT_SSE3: case DT_SSE2: { FwiMorphState *pState_T = (FwiMorphState*)fwMalloc(sizeof(FwiMorphState)); pState_T->anchor = pState->anchor; pState_T->isRectangule = pState->isRectangule; pState_T->isSymmetric = pState->isSymmetric; pState_T->maskSize = pState->maskSize; pState_T->pMask = pState->pMask; pState_T->roiWidth = pState->roiSize.width; //reverseMask_open(pState_T->pMask, pState_T->maskSize); Fw8u *pDst_T = (Fw8u*) fwMalloc(sizeof(Fw8u) * (dstStep * roiSize.height * 1)); fwiErodeBorderReplicate_8u_C1R(pSrc, srcStep, pDst_T, dstStep, roiSize, border, pState_T); fwiDilateBorderReplicate_8u_C1R(pDst_T, dstStep, pDst, dstStep, roiSize, border, pState_T); fwFree(pDst_T); return fwStsNoErr; } default: return My_FW_MorphOpenBorder<Fw8u, C1, DT_REFR> (pSrc, srcStep, pDst, dstStep, roiSize, border, pState); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiMorphOpenBorder_8u_C3R)(const Fw8u *pSrc, int srcStep, Fw8u *pDst, int dstStep, FwiSize roiSize, FwiBorderType border, FwiMorphAdvState *pState) { switch( Dispatch::Type<DT_SSE2>()) { case DT_SSE3: case DT_SSE2: { FwiMorphState *pState_T = (FwiMorphState*)fwMalloc(sizeof(FwiMorphState)); pState_T->anchor = pState->anchor; pState_T->isRectangule = pState->isRectangule; pState_T->isSymmetric = pState->isSymmetric; pState_T->maskSize = pState->maskSize; pState_T->pMask = pState->pMask; pState_T->roiWidth = pState->roiSize.width; //reverseMask_open(pState_T->pMask, pState_T->maskSize); Fw8u *pDst_T = (Fw8u*) fwMalloc(sizeof(Fw8u) * (dstStep * roiSize.height * 3)); fwiErodeBorderReplicate_8u_C3R(pSrc, srcStep, pDst_T, dstStep, roiSize,border, pState_T); fwiDilateBorderReplicate_8u_C3R(pDst_T, dstStep, pDst, dstStep, roiSize,border, pState_T); fwFree(pDst_T); return fwStsNoErr; } default: return My_FW_MorphOpenBorder<Fw8u, C3, DT_REFR> (pSrc, srcStep, pDst, dstStep, roiSize, border, pState); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiMorphOpenBorder_8u_C4R)(const Fw8u *pSrc, int srcStep, Fw8u *pDst, int dstStep, FwiSize roiSize, FwiBorderType border, FwiMorphAdvState *pState) { switch( Dispatch::Type<DT_SSE2>()) { case DT_SSE3: case DT_SSE2: { FwiMorphState *pState_T = (FwiMorphState*)fwMalloc(sizeof(FwiMorphState)); pState_T->anchor = pState->anchor; pState_T->isRectangule = pState->isRectangule; pState_T->isSymmetric = pState->isSymmetric; pState_T->maskSize = pState->maskSize; pState_T->pMask = pState->pMask; pState_T->roiWidth = pState->roiSize.width; //reverseMask_open(pState_T->pMask, pState_T->maskSize); Fw8u *pDst_T = (Fw8u*) fwMalloc(sizeof(Fw8u) * (dstStep * roiSize.height * 4)); fwiErodeBorderReplicate_8u_C4R(pSrc, srcStep, pDst_T, dstStep, roiSize,border, pState_T); fwiDilateBorderReplicate_8u_C4R(pDst_T, dstStep, pDst, dstStep, roiSize,border, pState_T); fwFree(pDst_T); return fwStsNoErr; } default: return My_FW_MorphOpenBorder<Fw8u, C4, DT_REFR> (pSrc, srcStep, pDst, dstStep, roiSize, border, pState); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiMorphOpenBorder_32f_C1R)(const Fw32f *pSrc, int srcStep, Fw32f *pDst, int dstStep, FwiSize roiSize, FwiBorderType border, FwiMorphAdvState *pState) { switch( Dispatch::Type<DT_SSE2>()) { case DT_SSE3: case DT_SSE2: { FwiMorphState *pState_T = (FwiMorphState*)fwMalloc(sizeof(FwiMorphState)); pState_T->anchor = pState->anchor; pState_T->isRectangule = pState->isRectangule; pState_T->isSymmetric = pState->isSymmetric; pState_T->maskSize = pState->maskSize; pState_T->pMask = pState->pMask; pState_T->roiWidth = pState->roiSize.width; //reverseMask_open(pState_T->pMask, pState_T->maskSize); Fw32f *pDst_T = (Fw32f*) fwMalloc(sizeof(Fw32f) * (dstStep * roiSize.height * 1)); fwiErodeBorderReplicate_32f_C1R(pSrc, srcStep, pDst_T, dstStep, roiSize,border, pState_T); fwiDilateBorderReplicate_32f_C1R(pDst_T, dstStep, pDst, dstStep, roiSize,border, pState_T); fwFree(pDst_T); return fwStsNoErr; } default: return My_FW_MorphOpenBorder<Fw32f, C1, DT_REFR> (pSrc, srcStep, pDst, dstStep, roiSize, border, pState); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiMorphOpenBorder_32f_C3R)(const Fw32f *pSrc, int srcStep, Fw32f *pDst, int dstStep, FwiSize roiSize, FwiBorderType border, FwiMorphAdvState *pState) { switch( Dispatch::Type<DT_SSE2>()) { case DT_SSE3: case DT_SSE2: { FwiMorphState *pState_T = (FwiMorphState*)fwMalloc(sizeof(FwiMorphState)); pState_T->anchor = pState->anchor; pState_T->isRectangule = pState->isRectangule; pState_T->isSymmetric = pState->isSymmetric; pState_T->maskSize = pState->maskSize; pState_T->pMask = pState->pMask; pState_T->roiWidth = pState->roiSize.width; //reverseMask_open(pState_T->pMask, pState_T->maskSize); Fw32f *pDst_T = (Fw32f*) fwMalloc(sizeof(Fw32f) * (dstStep * roiSize.height * 3)); fwiErodeBorderReplicate_32f_C3R(pSrc, srcStep, pDst_T, dstStep, roiSize,border, pState_T); fwiDilateBorderReplicate_32f_C3R(pDst_T, dstStep, pDst, dstStep, roiSize,border, pState_T); fwFree(pDst_T); return fwStsNoErr; } default: return My_FW_MorphOpenBorder<Fw32f, C3, DT_REFR> (pSrc, srcStep, pDst, dstStep, roiSize, border, pState); } } FwStatus PREFIX_OPT(OPT_PREFIX, fwiMorphOpenBorder_32f_C4R)(const Fw32f *pSrc, int srcStep, Fw32f *pDst, int dstStep, FwiSize roiSize, FwiBorderType border, FwiMorphAdvState *pState) { switch( Dispatch::Type<DT_SSE2>()) { case DT_SSE3: case DT_SSE2: { FwiMorphState *pState_T = (FwiMorphState*)fwMalloc(sizeof(FwiMorphState)); pState_T->anchor = pState->anchor; pState_T->isRectangule = pState->isRectangule; pState_T->isSymmetric = pState->isSymmetric; pState_T->maskSize = pState->maskSize; pState_T->pMask = pState->pMask; pState_T->roiWidth = pState->roiSize.width; //reverseMask_open(pState_T->pMask, pState_T->maskSize); Fw32f *pDst_T = (Fw32f*) fwMalloc(sizeof(Fw32f) * (dstStep * roiSize.height * 4)); fwiErodeBorderReplicate_32f_C4R(pSrc, srcStep, pDst_T, dstStep, roiSize,border, pState_T); fwiDilateBorderReplicate_32f_C4R(pDst_T, dstStep, pDst, dstStep, roiSize,border, pState_T); fwFree(pDst_T); return fwStsNoErr; } default: return My_FW_MorphOpenBorder<Fw32f, C4, DT_REFR> (pSrc, srcStep, pDst, dstStep, roiSize, border, pState); } } #endif //BUILD_NUM_AT_LEAST // Please do NOT remove the above line for CPP files that need to be multipass compiled // OREFR OSSE2
[ "dudochkin.victor@gmail.com" ]
dudochkin.victor@gmail.com
e6af6d9272b40ee4f5e746bc7cbc67ad5fe363e4
403f3b2112f02c2ae1f933346209ee1b3bd96783
/hsmakata/hsmakata_joint_commander/include/joint_commander.h
b08ddf369a3a6e7f5ea78d7953bc2697561ff155
[]
no_license
informatik-mannheim/Serviceroboter
c9b5ed801132f857d1f6bd4b60f89aecdaffabd8
b56ad980330db80c0dafe0aab2cbfebaf1f769ed
refs/heads/master
2021-01-10T09:48:28.328647
2015-12-15T11:59:17
2015-12-15T11:59:17
48,036,550
2
1
null
null
null
null
UTF-8
C++
false
false
2,169
h
/* * UOS-ROS packages - Robot Operating System code by the University of Osnabrück * Copyright (C) 2012 University of Osnabrück * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * joint_commander.h * * Created on: 24.08.2012 * Author: Martin Günther <mguenthe@uos.de> */ #ifndef JOINT_COMMANDER_H_ #define JOINT_COMMANDER_H_ #include <ros/ros.h> #include <math.h> #include <dynamic_reconfigure/server.h> #include <hsmakata_joint_commander/JointCommanderConfig.h> #include <std_msgs/Float64.h> #include <sensor_msgs/JointState.h> #include <dynamixel_msgs/JointState.h> namespace hsmakata_joint_commander { class JointCommander { public: JointCommander(); virtual ~JointCommander(); void update_config(hsmakata_joint_commander::JointCommanderConfig &new_config, uint32_t level = 0); void loop_once(); void set_yaw(const dynamixel_msgs::JointState::ConstPtr &msg); void set_pitch(const dynamixel_msgs::JointState::ConstPtr &msg); private: // ROS ros::NodeHandle nh_; ros::Publisher kinect_pitch_controller_pub_; ros::Publisher kinect_yaw_controller_pub_; ros::Publisher joint_states_pub_; //ros::Subscriber dxl_pitch; //ros::Subscriber dxl_yaw; float old_yaw, old_pitch, curr_yaw, curr_pitch; // Dynamic Reconfigure JointCommanderConfig config_; dynamic_reconfigure::Server<hsmakata_joint_commander::JointCommanderConfig> dynamic_reconfigure_server_; }; } /* namespace kurtana_pole_joint_commander */ #endif /* JOINT_COMMANDER_H_ */
[ "avira@avira.(none)" ]
avira@avira.(none)
bc7973a25e6b8a02c66ce94a5febb03942782f8e
53d7768c6199bea057b3b141cd4ae2ac4bfbc2e1
/literal.h
8f02c4cc40e18c772b34762c25307779af88358a
[]
no_license
zsmith876/Cpp-Recursive-Descent-Parser
b6ba79ea003632a271260c6e39393adb9e2f9954
20f42c61b6acab2dce66a827141b244bf2d35635
refs/heads/master
2022-12-05T07:52:12.353600
2020-08-26T00:27:28
2020-08-26T00:27:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
184
h
class Literal: public Operand { public: Literal(int value) { this->value = value; } int evaluate() { return value; } private: int value; };
[ "zsmith876@gmail.com" ]
zsmith876@gmail.com
ca6122d09513794a97a9d4df4e6701244fbe5c3e
76c5e0e751e41873a871c31ad590d3e93d193982
/HopVaGiaoCuaHaiDaySo1.cpp
61157b0d06a3f124ad5f12da3117d1bd544e376f
[]
no_license
quynhtrangn/CTDL-GT
f25a892523b294c0e419df2e7553436f6be3b6f1
af28b0c45063c45b9d6a401a1127414e00301929
refs/heads/master
2023-07-30T10:56:14.660274
2021-09-13T11:54:55
2021-09-13T11:54:55
405,948,437
0
0
null
null
null
null
UTF-8
C++
false
false
1,069
cpp
//#include <bits/stdc++.h> //#define endl '\n' //using namespace std; // //void solve(){ // int n, m; cin >> n >> m; // vector<int> tick(100005, 0); // for(int i = 0; i<n+m; i++){ // int tmp; cin >> tmp; // tick[tmp]++; // } // for(int i = 0; i<100005; i++){ // if(tick[i]!=0) cout << i << " "; // } // cout << endl; // for(int i = 0; i<100005; i++){ // if(tick[i]>1) cout << i << " "; // } // cout << endl; //} // //void fastIO(){ // ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); //} // //int main(){ // fastIO(); // int t = 1; cin >> t; // while(t--) solve(); // return 0; //} #include<bits/stdc++.h> using namespace std; void handle(){ int n,m; cin>>n>>m; vector<int> c(1000001,0); for(int i=0;i<n+m;i++){ int tmp; cin>>tmp; c[tmp]++; } for(int i=0;i<100001;i++){ if(c[i]!=0) cout<<i<<" "; } cout<<endl; for(int i=0;i<100001;i++){ if(c[i]>1) cout<<i<<" "; } cout<<endl; } int main() { int T=1; cin>>T; while(T--){ handle(); } return 0; }
[ "quynhtrangn25201@gmail.com" ]
quynhtrangn25201@gmail.com
75cd9bc1b7ebdea117fb4d0f7d2d0f12f2aafb96
1832bcd5577ccbfbee53c1fc9e83c64af10c0042
/Graphs/DFS/CAM5.cpp
07e0d7ceec64ee1b74b84975b504df83e911eae4
[]
no_license
sonalisingh18/Algorithms_and_Problems
d46558ce6c70e2d90b5e640044bab1ccd08c1a45
a9661a9732ade0ae88b8ccad54ffae1bc0431404
refs/heads/master
2023-02-15T03:37:15.673069
2021-01-08T12:19:09
2021-01-08T12:19:09
216,610,095
4
5
null
2020-11-01T00:24:25
2019-10-21T16:06:26
C++
UTF-8
C++
false
false
1,056
cpp
/* Sonali Singh Question link: https://www.spoj.com/problems/CAM5/ */ #include<bits/stdc++.h> #define mod 1000000007 #define ll long long int #define pb push_back #define mp make_pair #define pll pair<ll,ll> #define f first #define s second #define fio ios_base::sync_with_stdio(false);cin.tie(NULL) using namespace std; ll vis[1000000]; void addEdge(vector<ll>adj[], ll a, ll b){ adj[a].pb(b); adj[b].pb(a); } void DFS(ll p, vector<ll>adj[]){ vis[p]=1; for(ll i=0;i<adj[p].size();i++){ if(vis[adj[p][i]]==0){ DFS(adj[p][i],adj); } } } int main(){ fio; ll t,n,m,a,b; cin>>t; while(t--){ ll ConnectedComp=0; cin>>n>>m; memset(vis,0,sizeof(vis)); vector<ll> adj[n+1]; for(ll i=0;i<m;i++){ cin>>a>>b; addEdge(adj,a,b); } for(ll i=0;i<n;i++){ if(vis[i]==0){ DFS(i,adj); ConnectedComp++; } } cout<<ConnectedComp<<endl; } return 0; }
[ "sonalisingh2402@gmail.com" ]
sonalisingh2402@gmail.com
2c6ba1618fcb6634eb4576ca45742ce1ead628ca
fc7688d16559b70f94399a1ca05514865384ca84
/lib/seismic/libseispp/Metadata.cc
fc3ca0d2affb295b75d505db98367812f49f28aa
[]
no_license
brtteakins/antelope_contrib
d99c11a75efaf2d1a32ab8e1dfcb851269f89907
066ae3479be81098d5ee39ebfc90b37b07b35d9b
refs/heads/master
2021-01-18T08:25:20.770785
2010-05-03T15:10:09
2010-05-03T15:10:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,884
cc
#include <iostream> #include <sstream> #include "stock.h" #include "pf.h" #include <string> #include "AttributeMap.h" #include "Metadata.h" #include "dbpp.h" using namespace std; namespace SEISPP { /***** Start with Helpers. These have only file scope. */ /* Small helper returns a string that can be used to print the type name of a attribute */ string mdtypename(MDtype mdt) { string result; switch(mdt) { case MDreal: result="REAL"; break; case MDstring: result="STRING"; break; case MDint: result="INT"; break; case MDboolean: result="BOOLEAN"; break; case MDinvalid: result="INVALID"; break; default: result="UNKNOWN"; } return result; } void pf2metadatastring(Pf *pfin, map<string,string>& mdstr) { // Parameter files translate almost directly to the mstring // map. They are keyed arrays linking to strings. // Chose to not use the Pf directly here due to // clash found in memory management in earlier version. // The major complication is dealing with Arr and Tbl // that have to be converted to strings without the keys int i; Tbl *t; t=pfkeys(pfin); string key; char *sk,*sv; int ipftype; string svalue; Pf *pfnested; char *pfstr; for(i=0;i<maxtbl(t);++i) { sk=static_cast<char *>(gettbl(t,i)); key=string(sk); void *pfget_result; ipftype=pfget(pfin,sk,&pfget_result); switch (ipftype) { case PFSTRING: svalue=string(static_cast<char *>(pfget_result)); break; case PFARR: pfnested = static_cast<Pf *>(pfget_result); pfstr=pf2string(pfnested); svalue=string(" &Arr{\n") + string(pfstr)+string("\n}\n"); free(pfstr); break; case PFTBL: pfnested = static_cast<Pf *>(pfget_result); pfstr=pf2string(pfnested); svalue=string(pfstr); free(pfstr); } mdstr[key]=svalue; } freetbl(t,0); } /* Begin member functions */ Metadata::Metadata(const Metadata& mdold) { mreal=mdold.mreal; mint=mdold.mint; mbool=mdold.mbool; mstring=mdold.mstring; } Metadata::Metadata(Pf *pfin) { pf2metadatastring(pfin,mstring); } // Variant that extracts a subset of a pf with the prefix // label: tag &Arr{ Metadata::Metadata(Pf *pfin, string tag) { void *result; int pftype_return; Pf *pfnested; pftype_return = pfget(pfin,(char *)tag.c_str(),&result); if(pftype_return != PFARR) { throw MetadataError(string("Metadata pfsubset constructor: tag =") + tag + string(" &Arr{\nNot found in parameter file")); } // This casting seems necessary pfnested = static_cast<Pf *>(result); pf2metadatastring(pfnested,mstring); } // constructor from an antelope database (possibly view) row driven by // mdlist and am. The list of attributes found in mdlist are extracted // from the database row using dbgetv. am defines how the Antelope // attributes (e.g. wfdisc.time) are translated to an internal namespace. // That is, will attempt to read all attributes in AttributeMap list // and put them in the Metadata object Metadata::Metadata(DatabaseHandle& dbh, MetadataList& mdlist, AttributeMap& am) throw(MetadataError) { const string base_error("Metadata db constructor: "); try { DatascopeHandle& ddbh=dynamic_cast<DatascopeHandle&>(dbh); MetadataList::iterator i; map<string,AttributeProperties>::iterator ape=am.attributes.end(); // We'll just use the Dbptr and use raw Datascope routines. This // was done for two reasons. The main one is I had a working form // of this algorithm before I converted to the generic database handle // concept. If it isn't broken, don't fix it. Second, it should // be slightly faster as it removes the overhead of a second set // of function calls if the object oriented handle is used Dbptr db = ddbh.db; // This is used as a loop test below bool success; // This could, in principle, be done with a for_each loop // but I think this is easier to understand. for(i=mdlist.begin();i!=mdlist.end();++i) { MDtype mdtype; char csval[128]; // ugly to used fixed buffer, but no choice double fpval; long ival; map<string,AttributeProperties>::iterator ap; string dbattributename; string internal_name; internal_name = (*i).tag; /* This contains a list of db names that drive the loop below. When a names is not an alias the list will contain only one entry. When a name is an alias the members are tried in order until success or reaching end of list. If not found anywhere an exception is thrown */ list<string> dbnamelist; list<string>::iterator dbniter; //iterator for dbnamelist if(am.is_alias(internal_name)) { list<string> tablenames=am.aliastables(internal_name); list<string>::iterator tbliter; map<string,AttributeProperties> aliasmap=am.aliases(internal_name); bool ascanfirstpass(true); for(tbliter=tablenames.begin();tbliter!=tablenames.end();++tbliter) { AttributeProperties apalias=aliasmap[*tbliter]; if(ascanfirstpass) { mdtype=apalias.mdt; ascanfirstpass=false; } else { if(mdtype!=apalias.mdt) throw MetadataError(base_error + "Data type mismatch for db attributes" + string(" tagged with key=") + internal_name); } dbattributename=apalias.fully_qualified_name(); dbnamelist.push_back(dbattributename); } } else { mdtype = (*i).mdt; ap = am.attributes.find(internal_name); if(ap==ape) throw MetadataError(base_error + "required attribute " + internal_name +string(" is not in AttributeMap. Check initialization")); // the weird ap->second is a STL oddity for the item // two of a pair <key,type> dbattributename=ap->second.fully_qualified_name(); if((*i).mdt != ap->second.mdt) throw MetadataError(base_error +string("mismatch of type definitions for database attribute ")+(ap->second.fully_qualified_name())); dbnamelist.push_back(dbattributename); } success=false; for(dbniter=dbnamelist.begin();dbniter!=dbnamelist.end();++dbniter) { dbattributename=*dbniter; switch(mdtype) { case MDreal: if(dbgetv(db,0,dbattributename.c_str(), &fpval,0)!=dbINVALID) { put(internal_name,fpval); success=true; } else elog_flush(0,0); break; case MDint: if(dbgetv(db,0, dbattributename.c_str(), &ival,0)!=dbINVALID) { put(internal_name,ival); success=true; } else elog_flush(0,0); break; case MDstring: if(dbgetv(db,0, dbattributename.c_str(), csval,0)!=dbINVALID) { put(internal_name,csval); success=true; } else elog_flush(0,0); break; default: throw MetadataError(base_error + string("requested unsupported metadata type. Check parameter file definitions")); } if(success)break; } if(!success) { string mdnametype=mdtypename(mdtype); throw MetadataGetError(mdnametype,internal_name, string("This attribute or any associated alias was not found in the database") ); } } } catch (...) {throw;}; } // // These functions get and convert values // double Metadata::get_double(string s) throw(MetadataGetError) { map<string,double>::iterator iptr; iptr=mreal.find(s); if(iptr!=mreal.end()) return((*iptr).second); map<string,string>::iterator pfstyle; pfstyle=mstring.find(s); if(pfstyle==mstring.end()) throw MetadataGetError("real",s,""); string valstring=(*pfstyle).second; return ( atof(valstring.c_str()) ); } int Metadata::get_int(string s) throw(MetadataGetError) { try { long lival; lival=this->get_long(s); return(static_cast<int>(lival)); } catch (MetadataGetError& mderr){throw mderr;}; } long Metadata::get_long(string s) throw(MetadataGetError) { map<string,long>::iterator iptr; iptr=mint.find(s); if(iptr!=mint.end()) return((*iptr).second); map<string,string>::iterator pfstyle; pfstyle=mstring.find(s); if(pfstyle==mstring.end()) throw MetadataGetError("int",s,""); string valstring=(*pfstyle).second; return ( atol(valstring.c_str()) ); } string Metadata::get_string(string s) throw(MetadataGetError) { map<string,string>::iterator iptr; iptr=mstring.find(s); if(iptr==mstring.end()) throw MetadataGetError("string",s,""); return((*iptr).second); } bool Metadata::get_bool(string s) { map<string,bool>::iterator iptr; iptr=mbool.find(s); if(iptr!=mbool.end()) return((*iptr).second); map<string,string>::iterator pfstyle; pfstyle=mstring.find(s); if(pfstyle==mstring.end()) return (false); if( ((*pfstyle).second==string("t")) || ((*pfstyle).second==string("true")) || ((*pfstyle).second==string("1")) ) return(true); return(false); } // // Functions to put things into metadata object // void Metadata::put(string name, double val) { mreal[name]=val; } void Metadata::put(string name, long val) { mint[name]=val; } void Metadata::put(string name, int val) { long newval=static_cast<long>(val); mint[name]=val; } void Metadata::put(string name, string val) { mstring[name]=val; } // for C style strings, we should not depend on the compiler void Metadata::put(string name, char *val) { mstring[name]=string(val); } void Metadata::put(string name, bool val) { mbool[name]=val; } void Metadata::append_string(string key, string separator, string appendage) { map<string,string>::iterator sptr; sptr=mstring.find(key); if(sptr==mstring.end()) { // Ignore separator and just add appendage if the key is not // already in the object mstring[key]=appendage; } else { string newval=(*sptr).second+separator+appendage; mstring[key]=newval; } } void Metadata::remove(string name) { // We assume this is an uncommon operation for Metadata // so the approach used here is to search through all the // maps and destroying any entry with the key name map<string,long>::iterator iptr; iptr=mint.find(name); if(iptr!=mint.end()) mint.erase(iptr); map<string,double>::iterator rptr; rptr=mreal.find(name); if(rptr!=mreal.end()) mreal.erase(rptr); map<string,string>::iterator sptr; sptr=mstring.find(name); if(sptr!=mstring.end()) mstring.erase(sptr); map<string,bool>::iterator bptr; bptr=mbool.find(name); if(bptr!=mbool.end()) mbool.erase(bptr); } Metadata::Metadata(string mdin) throw(MetadataParseError) { Pf *pf; pf=pfnew(PFARR); int ierr; ierr = pfcompile(const_cast<char *>(mdin.c_str()),&pf); if(ierr!=0) throw MetadataParseError(ierr,"pfcompile failure in Metadata constructor"); // // The following duplicates code in the Pf constructor. // There may be a tricky way to invoke that code I'm not // aware of, but without making maps public I don't see how to // deal with that // int i; Tbl *t; t=pfkeys(pf); string key; char *sk,*sv; for(i=0;i<maxtbl(t);++i) { sk=static_cast<char *>(gettbl(t,i)); key=string(sk); sv=pfget_string(pf,sk); mstring[key]=string(sv); } freetbl(t,0); pffree(pf); } bool Metadata::is_attribute_set(string key) { map<string,double>::iterator rptr; rptr=mreal.find(key); if(rptr!=mreal.end()) return(true); map<string,long>::iterator iptr; iptr=mint.find(key); if(iptr!=mint.end()) return(true); map<string,string>::iterator sptr; sptr=mstring.find(key); if(sptr!=mstring.end()) return(true); map<string,bool>::iterator bptr; bptr=mbool.find(key); if(bptr!=mbool.end()) return(true); } bool Metadata::is_attribute_set(char *key) { return(this->is_attribute_set(string(key))); } MetadataList Metadata::keys() { MetadataList result; Metadata_typedef member; map<string,string>::iterator sptr; for(sptr=mstring.begin();sptr!=mstring.end();++sptr) { member.tag=(*sptr).first; member.mdt=MDstring; result.push_back(member); } map<string,long>::iterator iptr; for(iptr=mint.begin();iptr!=mint.end();++iptr) { member.tag=(*iptr).first; member.mdt=MDint; result.push_back(member); } map<string,double>::iterator rptr; for(rptr=mreal.begin();rptr!=mreal.end();++rptr) { member.tag=(*rptr).first; member.mdt=MDreal; result.push_back(member); } map<string,bool>::iterator bptr; for(bptr=mbool.begin();bptr!=mbool.end();++bptr) { member.tag=(*bptr).first; member.mdt=MDboolean; result.push_back(member); } return(result); } // //Sometimes we need to not copy all of the metadata from one object //to another. This function allows selective copy driven by a list // void copy_selected_metadata(Metadata& mdin, Metadata& mdout, MetadataList& mdlist) throw(MetadataError) { MetadataList::iterator mdti; int count; for(mdti=mdlist.begin(),count=0;mdti!=mdlist.end();++mdti,++count) { MDtype mdtest; double r; int iv; string s; Tbl *t; Arr *a; bool b; mdtest = mdti->mdt; try { switch(mdtest) { case MDreal: r=mdin.get_double(mdti->tag); mdout.put(mdti->tag,r); break; case MDint: iv=mdin.get_int(mdti->tag); mdout.put(mdti->tag,iv); break; case MDstring: s=mdin.get_string(mdti->tag); mdout.put(mdti->tag,s); break; case MDboolean: b=mdin.get_bool(mdti->tag); mdout.put(mdti->tag,b); break; case MDinvalid: // silently skip values marked as invalid break; default: throw MetadataError(string("copy_selected_metadata: ") + " was passed illegal type definition\n" + string("This indicates a coding error that must be fixed\n") + string("If caller does not exit on this error, expect a less graceful abort")); }; } catch( MetadataError& merr) { cerr << "Error in copy_selected_metadata at item "; cerr << count << " with tag " << mdti->tag <<"\n" ; cerr << "Copy truncated" << endl; merr.log_error(); throw; } } } // output stream operator. Originally was in ignorance made // a named function called print_all_metadata (older versions may // have this as debris. // ostream& operator<<(ostream& os, Metadata& md) { map<string,string>::iterator sptr; for(sptr=md.mstring.begin();sptr!=md.mstring.end();++sptr) { os << (*sptr).first <<" "<<(*sptr).second<<endl; } map<string,long>::iterator iptr; for(iptr=md.mint.begin();iptr!=md.mint.end();++iptr) { os << (*iptr).first <<" "<<(*iptr).second<<endl; } map<string,double>::iterator rptr; for(rptr=md.mreal.begin();rptr!=md.mreal.end();++rptr) { os << (*rptr).first <<" "<<(*rptr).second<<endl; } map<string,bool>::iterator bptr; for(bptr=md.mbool.begin();bptr!=md.mbool.end();++bptr) { os << (*bptr).first; if((*bptr).second) os<<" true"<<endl; else os<<" false"<<endl; } return os; } // // Small function to extract the entire metadata contents to a pf. // Implementation here is very crude being a memory pig and simultaneously // prone to failure with finite buffer to hold content. // Pf *Metadata_to_pf(Metadata& md) { const int BUFSIZE(65536); char buf[BUFSIZE]; ostringstream pfinp(buf); pfinp<< md; Pf *pf; pfcompile(const_cast<char *>(pfinp.str().c_str()),&pf); return(pf); } } // Termination of namespace SEISPP definitions
[ "pavlis@indiana.edu" ]
pavlis@indiana.edu
3e644483f95f9881b7875148e175d1a9b9f2a476
38c10c01007624cd2056884f25e0d6ab85442194
/chrome/browser/supervised_user/legacy/supervised_user_shared_settings_service_unittest.cc
ffa3940b610d887a63fcdd0bf668cd952eea0712
[ "BSD-3-Clause" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
9,773
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/bind.h" #include "base/json/json_writer.h" #include "base/prefs/pref_service.h" #include "chrome/browser/supervised_user/legacy/supervised_user_shared_settings_service.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/testing_profile.h" #include "content/public/test/test_browser_thread_bundle.h" #include "sync/api/fake_sync_change_processor.h" #include "sync/api/sync_change.h" #include "sync/api/sync_change_processor_wrapper_for_test.h" #include "sync/api/sync_error_factory_mock.h" #include "sync/protocol/sync.pb.h" #include "testing/gtest/include/gtest/gtest.h" using base::DictionaryValue; using base::FundamentalValue; using base::StringValue; using base::Value; using sync_pb::ManagedUserSharedSettingSpecifics; using syncer::SUPERVISED_USER_SHARED_SETTINGS; using syncer::SyncChange; using syncer::SyncChangeList; using syncer::SyncChangeProcessor; using syncer::SyncChangeProcessorWrapperForTest; using syncer::SyncData; using syncer::SyncDataList; using syncer::SyncError; using syncer::SyncErrorFactory; using syncer::SyncMergeResult; namespace { class MockSyncErrorFactory : public syncer::SyncErrorFactory { public: explicit MockSyncErrorFactory(syncer::ModelType type); ~MockSyncErrorFactory() override; // SyncErrorFactory implementation: syncer::SyncError CreateAndUploadError( const tracked_objects::Location& location, const std::string& message) override; private: syncer::ModelType type_; DISALLOW_COPY_AND_ASSIGN(MockSyncErrorFactory); }; MockSyncErrorFactory::MockSyncErrorFactory(syncer::ModelType type) : type_(type) {} MockSyncErrorFactory::~MockSyncErrorFactory() {} syncer::SyncError MockSyncErrorFactory::CreateAndUploadError( const tracked_objects::Location& location, const std::string& message) { return syncer::SyncError(location, SyncError::DATATYPE_ERROR, message, type_); } // Convenience method to allow us to use EXPECT_EQ to compare values. std::string ToJson(const Value* value) { if (!value) return std::string(); std::string json_value; base::JSONWriter::Write(*value, &json_value); return json_value; } } // namespace class SupervisedUserSharedSettingsServiceTest : public ::testing::Test { protected: typedef base::CallbackList<void(const std::string&, const std::string&)> CallbackList; SupervisedUserSharedSettingsServiceTest() : settings_service_(profile_.GetPrefs()) {} ~SupervisedUserSharedSettingsServiceTest() override {} void StartSyncing(const syncer::SyncDataList& initial_sync_data) { sync_processor_.reset(new syncer::FakeSyncChangeProcessor); scoped_ptr<syncer::SyncErrorFactory> error_handler( new MockSyncErrorFactory(SUPERVISED_USER_SHARED_SETTINGS)); SyncMergeResult result = settings_service_.MergeDataAndStartSyncing( SUPERVISED_USER_SHARED_SETTINGS, initial_sync_data, scoped_ptr<SyncChangeProcessor>( new SyncChangeProcessorWrapperForTest(sync_processor_.get())), error_handler.Pass()); EXPECT_FALSE(result.error().IsSet()); } const base::DictionaryValue* GetAllSettings() { return profile_.GetPrefs()->GetDictionary( prefs::kSupervisedUserSharedSettings); } void VerifySyncChangesAndClear() { SyncChangeList& changes = sync_processor_->changes(); for (const SyncChange& sync_change : changes) { const sync_pb::ManagedUserSharedSettingSpecifics& setting = sync_change.sync_data().GetSpecifics().managed_user_shared_setting(); EXPECT_EQ( setting.value(), ToJson(settings_service_.GetValue(setting.mu_id(), setting.key()))); } changes.clear(); } // testing::Test overrides: void SetUp() override { subscription_ = settings_service_.Subscribe( base::Bind(&SupervisedUserSharedSettingsServiceTest::OnSettingChanged, base::Unretained(this))); } void TearDown() override { settings_service_.Shutdown(); } void OnSettingChanged(const std::string& su_id, const std::string& key) { const Value* value = settings_service_.GetValue(su_id, key); ASSERT_TRUE(value); changed_settings_.push_back( SupervisedUserSharedSettingsService::CreateSyncDataForSetting( su_id, key, *value, true)); } content::TestBrowserThreadBundle thread_bundle_; TestingProfile profile_; SupervisedUserSharedSettingsService settings_service_; SyncDataList changed_settings_; scoped_ptr<CallbackList::Subscription> subscription_; scoped_ptr<syncer::FakeSyncChangeProcessor> sync_processor_; }; TEST_F(SupervisedUserSharedSettingsServiceTest, Empty) { StartSyncing(SyncDataList()); EXPECT_EQ(0u, sync_processor_->changes().size()); EXPECT_EQ(0u, changed_settings_.size()); EXPECT_EQ( 0u, settings_service_.GetAllSyncData(SUPERVISED_USER_SHARED_SETTINGS).size()); EXPECT_EQ(0u, GetAllSettings()->size()); } TEST_F(SupervisedUserSharedSettingsServiceTest, SetAndGet) { StartSyncing(SyncDataList()); const char kIdA[] = "aaaaaa"; const char kIdB[] = "bbbbbb"; const char kIdC[] = "cccccc"; StringValue name("Jack"); FundamentalValue age(8); StringValue bar("bar"); settings_service_.SetValue(kIdA, "name", name); ASSERT_EQ(1u, sync_processor_->changes().size()); VerifySyncChangesAndClear(); settings_service_.SetValue(kIdA, "age", FundamentalValue(6)); ASSERT_EQ(1u, sync_processor_->changes().size()); VerifySyncChangesAndClear(); settings_service_.SetValue(kIdA, "age", age); ASSERT_EQ(1u, sync_processor_->changes().size()); VerifySyncChangesAndClear(); settings_service_.SetValue(kIdB, "foo", bar); ASSERT_EQ(1u, sync_processor_->changes().size()); VerifySyncChangesAndClear(); EXPECT_EQ( 3u, settings_service_.GetAllSyncData(SUPERVISED_USER_SHARED_SETTINGS).size()); EXPECT_EQ(ToJson(&name), ToJson(settings_service_.GetValue(kIdA, "name"))); EXPECT_EQ(ToJson(&age), ToJson(settings_service_.GetValue(kIdA, "age"))); EXPECT_EQ(ToJson(&bar), ToJson(settings_service_.GetValue(kIdB, "foo"))); EXPECT_FALSE(settings_service_.GetValue(kIdA, "foo")); EXPECT_FALSE(settings_service_.GetValue(kIdB, "name")); EXPECT_FALSE(settings_service_.GetValue(kIdC, "name")); } TEST_F(SupervisedUserSharedSettingsServiceTest, Merge) { // Set initial values, then stop syncing so we can restart. StartSyncing(SyncDataList()); const char kIdA[] = "aaaaaa"; const char kIdB[] = "bbbbbb"; const char kIdC[] = "cccccc"; FundamentalValue age(8); StringValue bar("bar"); settings_service_.SetValue(kIdA, "name", StringValue("Jack")); settings_service_.SetValue(kIdA, "age", age); settings_service_.SetValue(kIdB, "foo", bar); settings_service_.StopSyncing(SUPERVISED_USER_SHARED_SETTINGS); StringValue name("Jill"); StringValue blurp("blurp"); SyncDataList sync_data; sync_data.push_back( SupervisedUserSharedSettingsService::CreateSyncDataForSetting( kIdA, "name", name, true)); sync_data.push_back( SupervisedUserSharedSettingsService::CreateSyncDataForSetting( kIdC, "baz", blurp, true)); StartSyncing(sync_data); EXPECT_EQ(2u, sync_processor_->changes().size()); VerifySyncChangesAndClear(); EXPECT_EQ(2u, changed_settings_.size()); EXPECT_EQ( 4u, settings_service_.GetAllSyncData(SUPERVISED_USER_SHARED_SETTINGS).size()); EXPECT_EQ(ToJson(&name), ToJson(settings_service_.GetValue(kIdA, "name"))); EXPECT_EQ(ToJson(&age), ToJson(settings_service_.GetValue(kIdA, "age"))); EXPECT_EQ(ToJson(&bar), ToJson(settings_service_.GetValue(kIdB, "foo"))); EXPECT_EQ(ToJson(&blurp), ToJson(settings_service_.GetValue(kIdC, "baz"))); EXPECT_FALSE(settings_service_.GetValue(kIdA, "foo")); EXPECT_FALSE(settings_service_.GetValue(kIdB, "name")); EXPECT_FALSE(settings_service_.GetValue(kIdC, "name")); } TEST_F(SupervisedUserSharedSettingsServiceTest, ProcessChanges) { StartSyncing(SyncDataList()); const char kIdA[] = "aaaaaa"; const char kIdB[] = "bbbbbb"; const char kIdC[] = "cccccc"; FundamentalValue age(8); StringValue bar("bar"); settings_service_.SetValue(kIdA, "name", StringValue("Jack")); settings_service_.SetValue(kIdA, "age", age); settings_service_.SetValue(kIdB, "foo", bar); StringValue name("Jill"); StringValue blurp("blurp"); SyncChangeList changes; changes.push_back( SyncChange(FROM_HERE, SyncChange::ACTION_UPDATE, SupervisedUserSharedSettingsService::CreateSyncDataForSetting( kIdA, "name", name, true))); changes.push_back( SyncChange(FROM_HERE, SyncChange::ACTION_ADD, SupervisedUserSharedSettingsService::CreateSyncDataForSetting( kIdC, "baz", blurp, true))); SyncError error = settings_service_.ProcessSyncChanges(FROM_HERE, changes); EXPECT_FALSE(error.IsSet()) << error.ToString(); EXPECT_EQ(2u, changed_settings_.size()); EXPECT_EQ( 4u, settings_service_.GetAllSyncData(SUPERVISED_USER_SHARED_SETTINGS).size()); EXPECT_EQ(ToJson(&name), ToJson(settings_service_.GetValue(kIdA, "name"))); EXPECT_EQ(ToJson(&age), ToJson(settings_service_.GetValue(kIdA, "age"))); EXPECT_EQ(ToJson(&bar), ToJson(settings_service_.GetValue(kIdB, "foo"))); EXPECT_EQ(ToJson(&blurp), ToJson(settings_service_.GetValue(kIdC, "baz"))); EXPECT_FALSE(settings_service_.GetValue(kIdA, "foo")); EXPECT_FALSE(settings_service_.GetValue(kIdB, "name")); EXPECT_FALSE(settings_service_.GetValue(kIdC, "name")); }
[ "zeno.albisser@hemispherian.com" ]
zeno.albisser@hemispherian.com
2a78948fa379f543af48187b7e02cc18951ecebc
ae669239ac5e676f84fcb3ad005e015d14ac2e1f
/DS_PriorityQueue/main.cpp
8bd311319328e467608458b4b47af763321ebac7
[]
no_license
standingbychen/Date-Structure
9700436c51d554e4e1416553499f22a5141cdce2
a7b4cc89f07df582d436291380c67fa7bf3c8d2b
refs/heads/master
2021-09-14T12:06:21.557290
2018-05-13T12:23:02
2018-05-13T12:23:02
null
0
0
null
null
null
null
GB18030
C++
false
false
3,574
cpp
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #define MaxSize 200 using namespace std; /************************************ 需建立文件F:\\task.dat ************************************/ struct process //进程 { int num; //进程任务号 int pri; //进程优先级 }; struct HEAP { process pro[MaxSize]; int n; //堆中数据数 }; //创建一个空堆 void MaxHeap(HEAP &heap) { heap.n=0; } //判断堆是否为空 bool HeapEmpty(HEAP heap) { return (!heap.n); } //判断堆是否为满 bool HeapFull(HEAP heap) { return (heap.n==MaxSize-1); } //插入一个元素 void Insert(HEAP &heap,process p) { int i=0; if(!HeapFull(heap)) //堆不满 { heap.n++; i=heap.n; while((i!=1)&&(p.pri>heap.pro[i/2].pri)) //[i/2]为i的父节点 { heap.pro[i]=heap.pro[i/2]; i=i/2; } heap.pro[i]=p; } else cout<<"插入失败,堆已满!"<<endl; } //删除堆顶元素 process DeleteMax(HEAP &heap) { int parent=1,child=2; process p,tmp; if(!HeapEmpty(heap)) { p=heap.pro[1]; tmp=heap.pro[heap.n--]; //保存堆末元素 while(child<=heap.n) {/*从堆顶开始,将元素逐层向上串*/ if( (child<heap.n)&&(heap.pro[child].pri<heap.pro[child+1].pri) ) //较大子树 child++; if(tmp.pri>heap.pro[child].pri) //若堆末元素较大 则填补节点位置 break; heap.pro[parent]=heap.pro[child]; parent=child; //选择分支 child*=2; //扫描下一层 }//while heap.pro[parent]=tmp; //用堆末元素填补空缺 return p; }//if return heap.pro[0]; } /* void Input(HEAP &heap) { int num,pri,i; process tmp; cout<<"请输入 进程任务号 进程优先级(输入负值停止)"<<endl; while(1) { if(heap.n==MaxSize) break; cin>>num; if(num<0) break; cin>>pri; if(pri<0) break; tmp.num=num; tmp.pri=pri; Insert(heap,tmp); } cout<<"输入完成!"<<endl; for(i=1;i<=heap.n;i++) { cout<<heap.pro[i].num<<' '<<heap.pro[i].pri<<endl; } putchar('\n'); } */ //从文件读入 void FInput(HEAP &heap) { FILE *fp=NULL; if((fp=fopen("F:\\task.dat","r"))==NULL) { cout<<"Failure to open the file!"<<endl; exit(0); } int num,pri; process tmp; while(!feof(fp)) {//读入 if(heap.n==MaxSize) break; fscanf(fp,"%d",&num); cout<<num<<' '; if(num<0) break; fscanf(fp,"%d",&pri); cout<<pri<<' '<<endl; if(pri<0) break; tmp.num=num; tmp.pri=pri; Insert(heap,tmp); } cout<<"输入完成!"<<endl; putchar('\n'); fclose(fp); } //排序依据 bool cmp(process a,process b) { if(a.pri!=b.pri) return a.pri>b.pri; return a.num<b.num; } //整理输出 void Output(HEAP &heap) { int n=heap.n; process *tmp=NULL; tmp=new process[n]; int i; for(i=0;i<n;i++) { tmp[i]=DeleteMax(heap); } sort(tmp,tmp+n,cmp); //对数组按cmp排序 cout<<"输出序列如下:"<<endl; cout<<"任务号 优先级"<<endl; for(i=0;i<n;i++) { cout<<" "<<tmp[i].num<<" "<<tmp[i].pri<<endl; } } int main() { HEAP heap; MaxHeap(heap); FInput(heap); Output(heap); return 0; }
[ "386506287@qq.com" ]
386506287@qq.com
6dfbcce706ec01e5df2a03ca22b3985fc262bc90
b8564eafb6c65fbe0cd7cadbcb299bc9e86ad2eb
/uva/Uva - 357.cpp
18e4322b238a6f9cb4c22666c027351349683c94
[]
no_license
Mohamed-Hossam/Problem-Solving
3051db03cc25d2f76fab6b43b2fd89d2ea373f83
8b6145679cc17481c1f625b1044d006580fdd870
refs/heads/master
2021-09-18T23:42:21.013810
2018-07-21T19:05:23
2018-07-21T19:05:23
90,371,332
0
0
null
null
null
null
UTF-8
C++
false
false
2,050
cpp
//In the name of Allah #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<algorithm> #include<vector> #include<set> #include<map> #include<queue> #include<stack> #include<iterator> #include<cmath> #include<string> #include<sstream> #include<cstring> #include<ctype.h> #include<iomanip> #include<functional> #include<bitset> #include<stdio.h> #include<fstream> #include<stdlib.h> #include<math.h> #include<ctime> #include<string> #include<cstdio> #include<locale> #include<codecvt> using namespace std; #define lop(i,a,n) for(int i=a;i<n;++i) #define loop(i,n,a)for(int i=n-1;i>=a;--i) #define R_(s) freopen(s, "r", stdin) #define W_(s) freopen(s, "w", stdout) #define R_W R_("in.txt"),W_("out.txt") #define ll long long #define ld long double #define ii pair<ll,ll> #define vii vector<ii> #define vi vector<int> #define vll vector<ll> #define vs vector<string> #define vvii vector<vector<ii>> #define vvi vector<vector<int>> #define vvll vector<vector<ll>> #define sz(v) (ll)v.size() #define all(v) v.begin(),v.end() #define sc(n) scanf("%d",&n) #define scl(n) scanf("%lld",&n) #define pr1(n) printf("%d\n",n) #define pr2(n) printf("%d " ,n) #define pr3(n) cout<<fixed<<setprecision(9)<<n<<endl #define endl "\n" #define PI 2*acos(0.0) #define DFS_GRAY -1 #define DFS_WHITE 0 #define DFS_BLACK 1 #define oo 1e9 #define OO 1e18 #define EPS 1e-9 int dr[] = { 1, 0, -1, 0, -1, -1, 1, 1 }; int dc[] = { 0, -1, 0, 1, -1, 1, -1, 1 }; const int MAX = 1e2 + 7; const int MOD = 1073741824; ll c[] = { 1,5,10,25,50 }; ll dp[6][30000 + 7]; int main() { int n; while (cin >> n) { dp[5][0] = 1; loop(i, 5, 0)lop(j, 0, n + 1) { dp[i][j] = dp[i + 1][j]; if (j - c[i] >= 0)dp[i][j] += dp[i][j - c[i]]; } ll out = dp[0][n]; if (out > 1) printf("There are %lld ways to produce %d cents change.\n", out, n); else printf("There is only %lld way to produce %d cents change.\n", out, n); } } }
[ "eng.mohamed.hosaam@gmail.com" ]
eng.mohamed.hosaam@gmail.com
5e81a7b9d0e29adf5cd12550533aa5a565a7aa4e
1a6017fe5873fe86f3a7c1fcf50261120b28444d
/test_src/cpp/hierarchical_parallelism/atomic-float/target__teams__parallel__simd.cpp
4f07de88b69fd3a2a09f54d509cb731f9447f197
[ "MIT" ]
permissive
colleeneb/OvO
3a6400352bf1893090a71dc7ef9cd93bf87ea3eb
08ad05d93ae24d976fc65da8153a1108a52eb679
refs/heads/master
2022-11-30T19:06:02.161563
2020-08-09T23:33:32
2020-08-09T23:33:32
286,334,249
0
0
MIT
2020-08-09T23:32:32
2020-08-09T23:32:32
null
UTF-8
C++
false
false
991
cpp
#include <iostream> #include <cstdlib> #include <cmath> #ifdef _OPENMP #include <omp.h> #else int omp_get_num_teams() {return 1;} int omp_get_num_threads() {return 1;} #endif bool almost_equal(float x, float gold, float tol) { return gold * (1-tol) <= x && x <= gold * (1 + tol); } void test_target__teams__parallel__simd() { const int N0 { 262144 }; const float expected_value { N0 }; float counter_teams{}; #pragma omp target map(tofrom: counter_teams) #pragma omp teams { #pragma omp parallel { #pragma omp simd for (int i0 = 0 ; i0 < N0 ; i0++ ) { #pragma omp atomic update counter_teams = counter_teams + float { float { 1. } / ( omp_get_num_teams() * omp_get_num_threads() ) }; } } } if (!almost_equal(counter_teams, expected_value, 0.1)) { std::cerr << "Expected: " << expected_value << " Got: " << counter_teams << std::endl; std::exit(112); } } int main() { test_target__teams__parallel__simd(); }
[ "tapplencourt@Thomass-MacBook-Pro.local" ]
tapplencourt@Thomass-MacBook-Pro.local
6d700bde16d0f1c67eb023ed6e97fb19450599dd
bed1ee6e2983fea6a760cfdbf88e159171657f16
/header/RoutingSchedule.hpp
dc83f82002d84c61a49c4db0209829dba990fd8f
[]
no_license
Twl09008181/Global-Routing-With-Cell-movement-Advanced
fcbf5966f8597f1b9fc277b6656e52dfe91cefec
33b78846058982a1ce58e9544fdaa10e7c304484
refs/heads/master
2023-09-01T22:49:34.482380
2021-10-29T06:40:13
2021-10-29T06:40:13
369,090,882
1
0
null
null
null
null
UTF-8
C++
false
false
1,972
hpp
#ifndef R_SCHLER #define R_SCHLER #include "graph.hpp" #include"Routing.hpp" #include "analysis.hpp" #include <vector> struct netinfo{ int netId; int hpwl; int wl; }; std::vector<netinfo> getNetlist(Graph*graph);//sort by wl - hpwl void Reject(Graph*graph,std::vector<ReroutInfo>&info,std::vector<int>&AlreadyRipUp); void Accept(Graph*graph,std::vector<ReroutInfo>&info); bool RoutingSchedule(Graph*graph,int netid,std::vector<ReroutInfo>&infos,std::vector<int>&RipId,int defaultLayer=0,ReroutInfo**overflowNet=nullptr,bool recover = true); bool overFlowRouting(Graph*graph,int Netid,std::vector<ReroutInfo>&infos,std::vector<int>&RipId,int defaultLayer=0,ReroutInfo**overflowNet=nullptr); using routing_callback = decltype(RoutingSchedule)*; void BatchRoute(Graph*graph,std::vector<netinfo>&netlist,int start,int _end,routing_callback _callback,int batchsize=1,int default_layer=0); bool RouteAAoR(Graph*graph,std::vector<netinfo>&netlist,CellInst*c = nullptr,bool recover = true);//Route "All" Accept or Reject , can be used as batch route. void Route(Graph*graph,std::vector<netinfo>&netlist);//Route "Single" Accept or Reject //simple example // void OnlyRouting(Graph*graph,int batchSize,bool overflow,float topPercent) // { // float sc = graph->score; // std::vector<netinfo> netlist = getNetlist(graph);//get netList // //-----------------overflow allowed---------------------------- // if(overflow){ // routing(graph,netlist,0,netlist.size()*topPercent,overFlowRouting,batchSize); // } // //------------------------------------------------------------ // routing(graph,netlist,0,netlist.size(),overFlowRouting,batchSize); // } inline bool change_state(float cost1,float cost2,float temperature) { float c = cost1-cost2;//more bigger, more good srand(1); double x = (double) rand() / (RAND_MAX + 1.0); double successProb = 1 /(1+exp(-c/temperature)); return successProb > x; } #endif
[ "twl0985314726@gmail.com" ]
twl0985314726@gmail.com
41d9bd4d4e456b6deecf0725eccc65dd82df5ff9
c56fb29a67e04e6e2c678896427db6050972bca6
/segmentVis/Image.h
ca199695be1845e96d7445dae0070ea71ae8b9e9
[ "MIT" ]
permissive
acvictor/IDD-Viz
64e99201e91cf7a72d8cf0cc1cfb22fe26e8d329
0860c6a933f4d8706a3453ead4fc5db4e2df8c81
refs/heads/master
2020-04-16T07:55:46.557706
2019-01-21T07:32:39
2019-01-21T07:32:39
165,404,331
0
0
null
null
null
null
UTF-8
C++
false
false
429
h
#pragma once #include <bits/stdc++.h> #include <opencv2/core/core.hpp> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include "Segment.h" using namespace std; using namespace cv; class Image { public: vector<Segment> segments; int imgHeight, imgWidth; Image(); void ReadJson(string fName); void PrintSegments(); void ComputeBoundingBox(); void DrawSegments(string fName); };
[ "ankita3victor@yahoo.com" ]
ankita3victor@yahoo.com
2688e8d812e57036cca105080a3026ad80c1694a
2f89b19631984f8fe47f8e1468668865583bfb85
/ABC/■100/11-20/ABC_012/ABC012_A.cpp
c75d906800c31cff018d1902f4f88db51f9c3ef7
[]
no_license
masakinihirota/2019pg
29e6ded7a043d0e061c714feeebf9439d171bbc3
0d7e3fda329bf610de19e6e019ca0ea2954b3155
refs/heads/master
2020-09-22T11:30:05.244365
2020-01-13T01:46:17
2020-01-13T01:46:17
225,169,649
0
0
null
null
null
null
UTF-8
C++
false
false
709
cpp
#include <bits/stdc++.h> #include <ctype.h> using namespace std; #define ll long long #define all(x) (x).begin(), (x).end() const long long INF = 1LL << 60; #define rep(i, n) for (int i = 0; i < (int)(n); i++) //(i, 10) i=0~i=9まで #define repr(i, n) for (int i = n; i >= 0; i--) // (i, 10) i=10~i=0まで #define FOR(i, m, n) for (int i = m; i < n; i++) // (i, 3, 10) i=3~i=9まで // 総数を1000000007で割った余り const long long mod = 1e9 + 7; int main() { // cin.tie(0); // ios::sync_with_stdio(false); // cout << fixed << setprecision(5); // 入力 int a, b; cin >> a >> b; // 処理 // 出力 cout << b << " " << a << endl; return 0; }
[ "masakinihirota@gmail.com" ]
masakinihirota@gmail.com
39d0cd75297cd119bca4b7fc0a7064fd8d0a0abc
b066e4af061f28c739ecf179ae0a8d0ae425b937
/cond.h
31c0bb636b30be64c0acee819e7b3f464ae9d8a7
[]
no_license
lxq2537664558/fluid
185ee4bebaf1f8311ed9ad4eaca18bc72afbcf16
0c06aea6f8e5b36b8512a42cda15261e6ecb3d8c
refs/heads/master
2021-05-13T16:19:01.954681
2016-03-31T04:13:21
2016-03-31T04:13:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
338
h
#ifndef __COND_H__ #define __COND_H__ #include "sys.h" #include "noncopyable.h" #include "mutex.h" namespace fluid { class Cond : private Noncopyable { private: pthread_cond_t cond; public: Cond(); ~Cond(); void broadcast(); void signal(); void wait(Mutex& mutex); }; } #endif
[ "netease@NeteasedeMac-Pro-2.local" ]
netease@NeteasedeMac-Pro-2.local
fffcaf341455877bf4248402de745bf9b196d8c7
69dd4bd4268e1c361d8b8d95f56b5b3f5264cc96
/GPU Pro1/10_Beyond Pixels & Triangles/02_Accelerating Virtual Texturing using CUDA/VtexRelease/src/klLib/shared.h
eb2034f59a02c5a3b3718a3c11374b6deb8d0729
[ "MIT" ]
permissive
AnabaenaQing/Source-Code_ShaderX_GPU-Pro_GPU-Zen
65c16710d1abb9207fd7e1116290336a64ddfc86
f442622273c6c18da36b61906ec9acff3366a790
refs/heads/master
2022-12-15T00:40:42.931271
2020-09-07T16:48:25
2020-09-07T16:48:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,483
h
/** * * This software module was originally developed for research purposes, * by Multimedia Lab at Ghent University (Belgium). * Its performance may not be optimized for specific applications. * * Those intending to use this software module in hardware or software products * are advized that its use may infringe existing patents. The developers of * this software module, their companies, Ghent Universtity, nor Multimedia Lab * have any liability for use of this software module or modifications thereof. * * Ghent University and Multimedia Lab (Belgium) retain full right to modify and * use the code for their own purpose, assign or donate the code to a third * party, and to inhibit third parties from using the code for their products. * * This copyright notice must be included in all copies or derivative works. * * For information on its use, applications and associated permission for use, * please contact Prof. Rik Van de Walle (rik.vandewalle@ugent.be). * * Detailed information on the activities of * Ghent University Multimedia Lab can be found at * http://multimedialab.elis.ugent.be/. * * Copyright (c) Ghent University 2004-2009. * **/ #pragma once #include <vector> #include <string> #include <fstream> #include <sstream> #include <stdio.h> #include <string.h> #include <assert.h> #include "maths.h" #include "vectors.h" #include "matrix.h" /* Php style explode*/ inline std::vector<std::string> explode( const std::string & in, const std::string & delim) { typedef std::string::size_type size_type; const size_type delim_len = delim.length(); std::vector<std::string> result; size_type i = 0; size_type j; while(true) { j = in.find(delim, i); result.push_back(in.substr(i, j-i)) ; if (j == std::string::npos) { // reached end of string... break; } i = j + delim_len; } return result; } /* Puts text in the console buffer (manually add \n if desired) */ void klPrint(const char *buffer); /* Shows the error + exits */ void klFatalError(const char *format,...); /* Shows the error */ void klError(const char *format,...); /* Print to the log (does not need \n in strings) */ void klLog(const char *format,...); /******* FIXME: Put these somewhere else? */ void klCheckGlErrors(void); struct klCachedGlState { int currentTextureUnit; }; extern klCachedGlState glState;
[ "IRONKAGE@gmail.com" ]
IRONKAGE@gmail.com
ad5207a6298abb82e2c57e21794c2cacbf54c5e5
2efd8e38cef72ded4852ae2a0a958915ab94e5ec
/CodeJam/CoinJam/jamcoin.cpp
a23af0d16bea3f1549aa6aa668f0421b18b5206c
[]
no_license
toc007/Fun
42d0663d244f14fbafbc3c8c731ea88b20752429
64a015ac6395eac2cae6d77fc7ccc6b4c3f8350f
refs/heads/master
2021-01-11T19:57:15.269592
2017-12-23T10:27:49
2017-12-23T10:27:49
79,428,434
0
0
null
null
null
null
UTF-8
C++
false
false
93
cpp
#include <iostream> #include <set> #include <vector> using namespace std; int main() { }
[ "toc007@ucsd.edu" ]
toc007@ucsd.edu
be050da7bea0f422b1716a3f74aa9bae380b006d
98f068a08860ca19e6c3d8f1c7802b725c824c1f
/test_cyclone_p3d.cpp
effc1d0de187d677a538aaaa6958bda500a55f1b
[]
no_license
gqian-coder/MGARD-Cyclone
cfbc0e9a288e181c5f7316a3ffb41ce28d56767e
4ff3060c9e3752659090371bc1381fe8bdc4acd4
refs/heads/master
2023-04-02T23:12:19.244556
2021-04-16T19:57:40
2021-04-16T19:57:40
358,706,972
0
0
null
null
null
null
UTF-8
C++
false
false
4,600
cpp
#include <cmath> #include <fstream> #include <iostream> #include <vector> #include <chrono> #include "adios2.h" #include "mgard/mgard_api.h" #define SECONDS(d) std::chrono::duration_cast<std::chrono::seconds>(d).count() #define T_STEP 4 template <typename Type> void FileWriter_bin(const char *filename, Type *data, size_t size) { std::ofstream fout(filename, std::ios::binary); fout.write((const char*)(data), size*sizeof(Type)); fout.close(); } int main(int argc, char **argv) { std::chrono::steady_clock clock; std::chrono::steady_clock::time_point start, stop; std::chrono::steady_clock::duration duration; float tol, result; int out_size; unsigned char *compressed_data = 0; MPI_Init(&argc, &argv); int rank, np_size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &np_size); std::vector<float> rel_tol {1e-4, 1e-4, 1e-4, 1e-4, 1e-4}; adios2::ADIOS ad(MPI_COMM_WORLD); std::string dpath("/gpfs/alpine/proj-shared/csc143/gongq/andes/TC-CaseStudy/mgard-test/stb_layout/"); std::string fname(argv[1]); std::vector<std::string> data_f{"01-01"/*, "01-31", "03-02", "04-01", "05-01", "05-31", "06-30", "07-30", "08-29", "09-28", "10-28", "11-27", "12-27"*/}; std::vector<std::string> var_name {"PSL", "T200", "T500", "UBOT", "VBOT"}; std::vector<std::string> suffx = {"_top.bp", "_bottom.bp", "_side.bp"}; std::vector<std::size_t> compressed_size(var_name.size(),0); for (size_t data_id=0; data_id<data_f.size(); data_id++) { for (size_t suff_id=0; suff_id<suffx.size(); suff_id++) { if (rank==0) std::cout << "readin: " << data_f[data_id] << ": " << suffx[suff_id] << "\n"; adios2::IO reader_io = ad.DeclareIO("Input"+std::to_string(data_id)+std::to_string(suff_id)); adios2::IO writer_io = ad.DeclareIO("Output"+std::to_string(data_id)+std::to_string(suff_id)); adios2::Engine reader = reader_io.Open(dpath+fname+data_f[data_id]+"-21600.tcv5"+suffx[suff_id], adios2::Mode::Read); adios2::Engine writer = writer_io.Open("./3D/1e-4/step4/"+fname+data_f[data_id]+"-21600.tcv5" +suffx[suff_id] + ".mgard", adios2::Mode::Write); for (int ivar=0; ivar<var_name.size(); ivar++) { // MPI ADIOS: decompose the variable size_t r_step = rank*T_STEP; adios2::Variable<float> var_ad2; var_ad2 = reader_io.InquireVariable<float>(var_name[ivar]); std::vector<std::size_t> shape = var_ad2.Shape(); adios2::Variable<float>var_out = writer_io.DefineVariable<float>(var_name[ivar], shape, {0, 0, 0}, shape); const std::array<std::size_t, 3> dims = {4, shape[1], shape[2]}; const mgard::TensorMeshHierarchy<3, float> hierarchy(dims); const size_t ndof = hierarchy.ndof(); while (r_step<shape[0]) { std::vector<float> var_in; var_ad2.SetSelection(adios2::Box<adios2::Dims>({r_step, 0, 0}, {4, shape[1], shape[2]})); reader.Get<float>(var_ad2, var_in, adios2::Mode::Sync); reader.PerformGets(); auto [min_v, max_v] = std::minmax_element(begin(var_in), end(var_in)); tol = rel_tol.at(ivar) * (*max_v- *min_v); // std::cout << "tol: " << tol << "\n"; // std::cout << "rank " << rank << " read " << var_name[ivar] << " in " << suffx[suff_id] << " step " << r_step << "\n"; const mgard::CompressedDataset<3, float> compressed = mgard::compress(hierarchy, var_in.data(), (float)0.0, tol); const mgard::DecompressedDataset<3, float> decompressed = mgard::decompress(compressed); compressed_size[ivar] += compressed.size(); var_out.SetSelection(adios2::Box<adios2::Dims>({r_step, 0, 0}, {4, shape[1], shape[2]})); writer.Put<float>(var_out, decompressed.data(), adios2::Mode::Sync); writer.PerformPuts(); r_step += np_size*T_STEP; } } writer.Close(); reader.Close(); } } std::cout << "processor " << rank << ", " << var_name[0] << ": " << compressed_size[0] << ", " << var_name[1] << ": " << compressed_size[1] << ", " << var_name[2] << ": " << compressed_size[2] << ", " << var_name[3] << ": " << compressed_size[3] << ", " << var_name[4] << ": " << compressed_size[4] << "\n"; MPI_Finalize(); return 0; }
[ "gongq@andes-login3.olcf.ornl.gov" ]
gongq@andes-login3.olcf.ornl.gov
abcd37f474d0b7e1a6cfa0c900ef64105704451e
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/Handle_Extrema_HArray2OfPOnSurfParams.hxx
48ba098a2967ded9e3cbc4fb1aa18ff8e66f04a1
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
814
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _Handle_Extrema_HArray2OfPOnSurfParams_HeaderFile #define _Handle_Extrema_HArray2OfPOnSurfParams_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Handle_MMgt_TShared_HeaderFile #include <Handle_MMgt_TShared.hxx> #endif class Standard_Transient; class Handle(Standard_Type); class Handle(MMgt_TShared); class Extrema_HArray2OfPOnSurfParams; DEFINE_STANDARD_HANDLE(Extrema_HArray2OfPOnSurfParams,MMgt_TShared) #endif
[ "litao1009@gmail.com" ]
litao1009@gmail.com
0bc82c3272c5dea9eccefbe8a73c4073f451d2c3
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE762_Mismatched_Memory_Management_Routines/s05/CWE762_Mismatched_Memory_Management_Routines__new_array_delete_wchar_t_15.cpp
f04163051c883bdaf37be74be1db30ace8c4c608
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
6,011
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__new_array_delete_wchar_t_15.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_array_delete.label.xml Template File: sources-sinks-15.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: Allocate data using new [] * GoodSource: Allocate data using new * Sinks: * GoodSink: Deallocate data using delete [] * BadSink : Deallocate data using delete * Flow Variant: 15 Control flow: switch(6) and switch(7) * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__new_array_delete_wchar_t_15 { #ifndef OMITBAD void bad() { wchar_t * data; /* Initialize data*/ data = NULL; switch(6) { case 6: /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */ data = new wchar_t[100]; break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } switch(7) { case 7: /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may * require a call to delete [] to deallocate the memory */ delete data; break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G1() - use badsource and goodsink by changing the second switch to switch(8) */ static void goodB2G1() { wchar_t * data; /* Initialize data*/ data = NULL; switch(6) { case 6: /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */ data = new wchar_t[100]; break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } switch(8) { case 7: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; default: /* FIX: Deallocate the memory using delete [] */ delete [] data; break; } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second switch */ static void goodB2G2() { wchar_t * data; /* Initialize data*/ data = NULL; switch(6) { case 6: /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */ data = new wchar_t[100]; break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } switch(7) { case 7: /* FIX: Deallocate the memory using delete [] */ delete [] data; break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } } /* goodG2B1() - use goodsource and badsink by changing the first switch to switch(5) */ static void goodG2B1() { wchar_t * data; /* Initialize data*/ data = NULL; switch(5) { case 6: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; default: /* FIX: Allocate memory from the heap using new */ data = new wchar_t; break; } switch(7) { case 7: /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may * require a call to delete [] to deallocate the memory */ delete data; break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the first switch */ static void goodG2B2() { wchar_t * data; /* Initialize data*/ data = NULL; switch(6) { case 6: /* FIX: Allocate memory from the heap using new */ data = new wchar_t; break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } switch(7) { case 7: /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may * require a call to delete [] to deallocate the memory */ delete data; break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } } void good() { goodB2G1(); goodB2G2(); goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__new_array_delete_wchar_t_15; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
04ea16006546ffe1d0f7fccd97405a9c95219aab
0ecd2e862b7f569a48e7507f3e9cc2bebe031d70
/components/subresource_filter/content/renderer/document_subresource_filter.h
d09ac3b13f6d29ef68fc26050c378633c5ddf318
[ "BSD-3-Clause" ]
permissive
ClientSelection/chromium
ef3a646c54f6df0386c2d630a297565c2f642447
bd2d8595a7e3937876b4410dee22ae5ee5d1941b
refs/heads/master
2023-03-06T23:02:56.905715
2017-02-02T21:48:15
2017-02-02T21:48:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,751
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SUBRESOURCE_FILTER_CONTENT_RENDERER_DOCUMENT_SUBRESOURCE_FILTER_H_ #define COMPONENTS_SUBRESOURCE_FILTER_CONTENT_RENDERER_DOCUMENT_SUBRESOURCE_FILTER_H_ #include <stddef.h> #include <vector> #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "components/subresource_filter/content/common/document_load_statistics.h" #include "components/subresource_filter/core/common/activation_level.h" #include "components/subresource_filter/core/common/indexed_ruleset.h" #include "third_party/WebKit/public/platform/WebDocumentSubresourceFilter.h" #include "url/gurl.h" #include "url/origin.h" namespace subresource_filter { class FirstPartyOrigin; class MemoryMappedRuleset; // Performs filtering of subresource loads in the scope of a given document. class DocumentSubresourceFilter : public blink::WebDocumentSubresourceFilter, public base::SupportsWeakPtr<DocumentSubresourceFilter> { public: // Constructs a new filter that will: // -- Operate at the prescribed |activation_level|, which must be either // ActivationLevel::DRYRUN or ActivationLevel::ENABLED. In the former // case filtering will be performed but no loads will be disallowed. // -- Hold a reference to and use |ruleset| for its entire lifetime. // -- Expect |ancestor_document_urls| to be the URLs of documents loaded into // nested frames, starting with the current frame and ending with the main // frame. This provides the context for evaluating domain-specific rules. // -- Invoke |first_disallowed_load_callback|, if it is non-null, on the // first disallowed subresource load. DocumentSubresourceFilter( ActivationLevel activation_level, bool measure_performance, const scoped_refptr<const MemoryMappedRuleset>& ruleset, const std::vector<GURL>& ancestor_document_urls, const base::Closure& first_disallowed_load_callback); ~DocumentSubresourceFilter() override; const DocumentLoadStatistics& statistics() const { return statistics_; } // blink::WebDocumentSubresourceFilter: bool allowLoad(const blink::WebURL& resourceUrl, blink::WebURLRequest::RequestContext) override; private: const ActivationLevel activation_level_; const bool measure_performance_; scoped_refptr<const MemoryMappedRuleset> ruleset_; IndexedRulesetMatcher ruleset_matcher_; // Note: Equals nullptr iff |filtering_disabled_for_document_|. std::unique_ptr<FirstPartyOrigin> document_origin_; base::Closure first_disallowed_load_callback_; // Even when subresource filtering is activated at the page level by the // |activation_level| passed into the constructor, the current document or // ancestors thereof may still match special filtering rules that specifically // disable the application of other types of rules on these documents. See // proto::ActivationType for details. // // Indicates whether the document is subject to a whitelist rule with DOCUMENT // activation type. bool filtering_disabled_for_document_ = false; // Indicates whether the document is subject to a whitelist rule with // GENERICBLOCK activation type. Undefined if // |filtering_disabled_for_document_|. bool generic_blocking_rules_disabled_ = false; DocumentLoadStatistics statistics_; DISALLOW_COPY_AND_ASSIGN(DocumentSubresourceFilter); }; } // namespace subresource_filter #endif // COMPONENTS_SUBRESOURCE_FILTER_CONTENT_RENDERER_DOCUMENT_SUBRESOURCE_FILTER_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
f6134f8016c3864b6d18a78f6592e9f5f5ff34ab
426aaae0110dd221fcee8e91f5a4a35e82c380a6
/src/main.cpp
1d72b8c379a7f9d60c7524fd0778925790d87dd9
[]
no_license
alejandro70/nodemcu-clock-ap
966acb446bd0be3a6998256fba0982a6bf48b469
ccf0ed27d9d8839c75a47121a33985ca6fa0d097
refs/heads/master
2022-07-09T22:57:52.192052
2020-05-17T20:37:51
2020-05-17T20:37:51
264,751,998
0
0
null
null
null
null
UTF-8
C++
false
false
3,523
cpp
/* * Time sync to NTP time source * git remote add origin https://github.com/alejandro70/nodemcu-clock.git */ #include <Arduino.h> #include <DNSServer.h> #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #include <TimeLib.h> #include <WiFiManager.h> //https://github.com/tzapu/WiFiManager #include <WiFiUdp.h> #include <SimpleTimer.h> #include <ArduinoJson.h> #include <Wire.h> #include <Adafruit_Sensor.h> #include <Adafruit_TSL2561_U.h> #include "global.h" #include "display.h" #include "ntp.h" #define BTN_TRIGGER D2 // Activación de Access Point (AP) mode #define ANALOG_PIN A0 // NodeMCU board ADC pin // local variables volatile int timer1Seconds = 0; bool apModeStarted = false; // timers SimpleTimer timer; int timerDisplayTime; int timerMatrixBanner; int timerLightSensor; // functions void configModeCallback(WiFiManager *); void restart(); void ldrRange(); // ISR to Fire when Timer is triggered void ICACHE_RAM_ATTR onTimer1() { timer1Seconds++; if (timer1Seconds == 20) { timer1Seconds = 0; if (WiFi.status() != WL_CONNECTED && !apModeStarted) { ESP.restart(); } } // Re-Arm the timer as using TIM_SINGLE timer1_write(312500); //1 s } void setup() { Serial.begin(115200); pinMode(BTN_TRIGGER, INPUT_PULLUP); { //Initialize NodeMCU Timer1 every 1s timer1_attachInterrupt(onTimer1); // Add ISR Function timer1_enable(TIM_DIV256, TIM_EDGE, TIM_SINGLE); timer1_write(312500); // 312500 / 1 tick per 3.2 us from TIM_DIV256 == 1 s interval } // Max72xxPanel initMatrix(); matrixRender("Hola!", 31); // WiFiManager WiFiManager wifiManager; // Local intialization. wifiManager.setAPCallback(configModeCallback); // AP Configuration wifiManager.setBreakAfterConfig(true); // Exit After Config Instead of connecting //Reset Settings - If Button Pressed if (digitalRead(BTN_TRIGGER) == LOW) { wifiManager.resetSettings(); ESP.restart(); } // Tries to connect to last known settings or else starts an access point. if (!wifiManager.autoConnect("NTP Clock")) { ESP.reset(); } delay(3000); { while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); // Seed Random With vVlues Unique To This Device uint8_t macAddr[6]; WiFi.macAddress(macAddr); uint32_t seed1 = (macAddr[5] << 24) | (macAddr[4] << 16) | (macAddr[3] << 8) | macAddr[2]; randomSeed(seed1 + micros()); localPort = random(1024, 65535); udp.begin(localPort); // NTP config setSyncProvider(getNtpTime); setSyncInterval(5 * 60); } // timers (init disabled) timerDisplayTime = timer.setInterval(1000L, displayTime); timer.disable(timerDisplayTime); timerMatrixBanner = timer.setInterval((long)bannerFrecuency, matrixBannerFrame); timer.disable(timerMatrixBanner); timer.setTimeout(86400000L, restart); timerLightSensor = timer.setInterval(10000L, ldrRange); // IP banner matrixBanner(5000L, String("IP:") + WiFi.localIP().toString().c_str()); } void loop() { timer.run(); } // called when AP mode and config portal is started void configModeCallback(WiFiManager *myWiFiManager) { matrixRender("WiFi?", 31); apModeStarted = true; } void restart() { ESP.restart(); } void ldrRange() { int sensorValue = analogRead(ANALOG_PIN); // ajustar intensidad de display int intensity = map(sensorValue, 0, 1024, 0, 4); matrix.setIntensity(intensity); }
[ "aespitia70@gmail.com" ]
aespitia70@gmail.com
8cbf316006331d32e39bd491e24794b6ac26b16b
29240f76d2e969703ec40c367d479bcd1d6b2f5d
/CPP, C++ Solutions/456. 132 Pattern.cpp
a5f7707512f7e51e446992c6f45d519243efde56
[ "MIT" ]
permissive
jainans/My-Leetcode-Solution-In-CPP
ab54b443db7c0c77f73858f2eaf345153932df2d
ca5bff0733c2082615bcba0594805eb576036360
refs/heads/main
2023-06-11T14:37:43.822614
2021-07-09T08:42:55
2021-07-09T08:42:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
649
cpp
// TC - O(N) class Solution { public: bool find132pattern(vector<int>& nums) { int n = nums.size(); if(n < 3) return false; stack<int> st; int s3 = INT_MIN; for(int i = n-1; i >= 0; i--) { if(nums[i] < s3) return true; else while(!st.empty() && st.top() < nums[i]) { s3 = st.top(); st.pop(); } st.push(nums[i]); } return false; } }; // Solution Explanation Link - https://leetcode.com/problems/132-pattern/discuss/94071/Single-pass-C%2B%2B-O(n)-space-and-time-solution-(8-lines)-with-detailed-explanation.
[ "jainarpitkekri@gmail.com" ]
jainarpitkekri@gmail.com
b9031286175c9ea36c8643c31f7dbf320729a603
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/admin/wmi/wbem/winmgmt/xfiles/a51rep.cpp
80c5c826e49ea3a21ba97efe1a5f2601b1578008
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
159,799
cpp
/*++ Copyright (C) 2000-2001 Microsoft Corporation --*/ #include <windows.h> #include <wbemidl.h> #include <wbemint.h> #include <stdio.h> #include <wbemcomn.h> #include <ql.h> #include <time.h> #include "a51rep.h" #include <md5.h> #include <objpath.h> #include "lock.h" #include <persistcfg.h> #include "a51fib.h" #include "RepositoryPackager.h" //************************************************************************************************** HRESULT STDMETHODCALLTYPE CSession::QueryInterface(REFIID riid, void** ppv) { if(riid == IID_IUnknown || riid == IID_IWmiDbSession || riid == IID_IWmiDbSessionEx) { AddRef(); *ppv = this; return S_OK; } else return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE CSession::Release() { return CUnkBase<IWmiDbSessionEx, &IID_IWmiDbSessionEx>::Release(); } CSession::~CSession() { } HRESULT STDMETHODCALLTYPE CSession::GetObject( IWmiDbHandle *pScope, IWbemPath *pPath, DWORD dwFlags, DWORD dwRequestedHandleType, IWmiDbHandle **ppResult ) { #ifdef A51_SUPER_VERBOSE_LOGGING { DWORD dwLen = 0; HRESULT hres = pPath->GetText(WBEMPATH_GET_ORIGINAL, &dwLen, NULL); if(FAILED(hres) && hres != WBEM_E_BUFFER_TOO_SMALL) return hres; WCHAR* wszBuffer = (WCHAR*)TempAlloc(dwLen * sizeof(WCHAR)); if(wszBuffer == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe tfm(wszBuffer, dwLen * sizeof(WCHAR)); if(FAILED(pPath->GetText(WBEMPATH_GET_ORIGINAL, &dwLen, wszBuffer))) return WBEM_E_FAILED; ERRORTRACE((LOG_REPDRV, "CSession::GetObject - pPath=<%S>\n", wszBuffer)); } #endif try { HRESULT hres; CAutoReadLock lock(&g_readWriteLock); if (!m_bInWriteTransaction) { if (!lock.Lock()) return WBEM_E_FAILED; } if (g_bShuttingDown) { return WBEM_E_SHUTTING_DOWN; } CNamespaceHandle* pNs = (CNamespaceHandle*)pScope; if(FAILED(pNs->GetErrorStatus())) { return pNs->GetErrorStatus(); } hres = pNs->GetObject(pPath, dwFlags, dwRequestedHandleType, ppResult); InternalCommitTransaction(false); return hres; } catch (...) { return WBEM_E_CRITICAL_ERROR; } } HRESULT STDMETHODCALLTYPE CSession::GetObjectDirect( IWmiDbHandle *pScope, IWbemPath *pPath, DWORD dwFlags, REFIID riid, LPVOID *pObj ) { #ifdef A51_SUPER_VERBOSE_LOGGING { DWORD dwLen = 0; HRESULT hres = pPath->GetText(WBEMPATH_GET_ORIGINAL, &dwLen, NULL); if(FAILED(hres) && hres != WBEM_E_BUFFER_TOO_SMALL) return hres; WCHAR* wszBuffer = (WCHAR*)TempAlloc(dwLen * sizeof(WCHAR)); if(wszBuffer == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe tfm(wszBuffer, dwLen * sizeof(WCHAR)); if(FAILED(pPath->GetText(WBEMPATH_GET_ORIGINAL, &dwLen, wszBuffer))) return WBEM_E_FAILED; ERRORTRACE((LOG_REPDRV, "CSession::GetObjectDirect - pPath=<%S>\n", wszBuffer)); } #endif try { HRESULT hres; CAutoReadLock lock(&g_readWriteLock); if (!m_bInWriteTransaction) { if (!lock.Lock()) return WBEM_E_FAILED; } if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; CNamespaceHandle* pNs = (CNamespaceHandle*)pScope; if(FAILED(pNs->GetErrorStatus())) { return pNs->GetErrorStatus(); } hres = pNs->GetObjectDirect(pPath, dwFlags, riid, pObj); InternalCommitTransaction(false); return hres; } catch (...) { return WBEM_E_CRITICAL_ERROR; } } HRESULT STDMETHODCALLTYPE CSession::GetObjectByPath( IWmiDbHandle *pScope, LPCWSTR wszObjectPath, DWORD dwFlags, REFIID riid, LPVOID *pObj ) { #ifdef A51_SUPER_VERBOSE_LOGGING { ERRORTRACE((LOG_REPDRV, "CSession::GetObjectByPath - pPath=<%S>\n", wszObjectPath)); } #endif try { HRESULT hres; CAutoReadLock lock(&g_readWriteLock); if (!m_bInWriteTransaction) { if (!lock.Lock()) return WBEM_E_FAILED; } if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; CNamespaceHandle* pNs = (CNamespaceHandle*)pScope; if(FAILED(pNs->GetErrorStatus())) { return pNs->GetErrorStatus(); } DWORD dwLen = wcslen(wszObjectPath)+1; LPWSTR wszPath = (WCHAR*)TempAlloc(dwLen*sizeof(WCHAR)); if (wszPath == NULL) { return WBEM_E_OUT_OF_MEMORY; } wcscpy(wszPath, wszObjectPath); CTempFreeMe vdm(wszPath, dwLen * sizeof(WCHAR)); hres = pNs->GetObjectByPath(wszPath, dwFlags, riid, pObj); InternalCommitTransaction(false); return hres; } catch (...) { return WBEM_E_CRITICAL_ERROR; } } HRESULT STDMETHODCALLTYPE CSession::PutObject( IWmiDbHandle *pScope, REFIID riid, LPVOID pObj, DWORD dwFlags, DWORD dwRequestedHandleType, IWmiDbHandle **ppResult ) { #ifdef A51_SUPER_VERBOSE_LOGGING { _IWmiObject* pObjEx = NULL; ((IUnknown*)pObj)->QueryInterface(IID__IWmiObject, (void**)&pObjEx); CReleaseMe rm1(pObjEx); BSTR str = NULL; pObjEx->GetObjectText(0, &str); CSysFreeMe sfm( str ); ERRORTRACE((LOG_REPDRV, "CSession::PutObject Flags = <0x%X> - <%S>\n", dwFlags, str)); } #endif try { HRESULT hres; long lRes; CAutoWriteLock lock(&g_readWriteLock); CEventCollector aNonTransactedEvents; CEventCollector *aEvents = &m_aTransactedEvents; if (!m_bInWriteTransaction) { if (!lock.Lock()) return WBEM_E_FAILED; if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; aEvents = &aNonTransactedEvents; hres = InternalBeginTransaction(true); if(hres != ERROR_SUCCESS) return hres; g_Glob.GetForestCache()->BeginTransaction(); } else if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; CNamespaceHandle* pNs = (CNamespaceHandle*)pScope; if(FAILED(pNs->GetErrorStatus())) { if(!m_bInWriteTransaction) { InternalAbortTransaction(true); g_Glob.GetForestCache()->AbortTransaction(); } return pNs->GetErrorStatus(); } hres = pNs->PutObject(riid, pObj, dwFlags, dwRequestedHandleType, ppResult, *aEvents); if(!m_bInWriteTransaction) { if (FAILED(hres)) { InternalAbortTransaction(true); g_Glob.GetForestCache()->AbortTransaction(); } else { hres = InternalCommitTransaction(true); if(hres != ERROR_SUCCESS) { g_Glob.GetForestCache()->AbortTransaction(); } else { g_Glob.GetForestCache()->CommitTransaction(); lock.Unlock(); _IWmiCoreServices * pSvcs = g_Glob.GetCoreSvcs(); CReleaseMe rm(pSvcs); aNonTransactedEvents.SendEvents(pSvcs); } } aNonTransactedEvents.DeleteAllEvents(); } return hres; } catch (...) { return WBEM_E_CRITICAL_ERROR; } } HRESULT STDMETHODCALLTYPE CSession::DeleteObject( IWmiDbHandle *pScope, DWORD dwFlags, REFIID riid, LPVOID pObj ) { #ifdef A51_SUPER_VERBOSE_LOGGING { _IWmiObject* pObjEx = NULL; ((IUnknown*)pObj)->QueryInterface(IID__IWmiObject, (void**)&pObjEx); CReleaseMe rm1(pObjEx); BSTR str = NULL; pObjEx->GetObjectText(0, &str); CSysFreeMe sfm( str ); ERRORTRACE((LOG_REPDRV, "CSession::DeleteObject - <%S>\n", str)); } #endif try { HRESULT hres; long lRes; CAutoWriteLock lock(&g_readWriteLock); CEventCollector aNonTransactedEvents; CEventCollector *aEvents = &m_aTransactedEvents; if (!m_bInWriteTransaction) { if (!lock.Lock()) return WBEM_E_FAILED; if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; aEvents = &aNonTransactedEvents; hres = InternalBeginTransaction(true); if(hres != ERROR_SUCCESS) return hres; } else if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; CNamespaceHandle* pNs = (CNamespaceHandle*)pScope; if(FAILED(pNs->GetErrorStatus())) { if(!m_bInWriteTransaction) { InternalAbortTransaction(true); } return pNs->GetErrorStatus(); } hres = pNs->DeleteObject(dwFlags, riid, pObj, *aEvents); if(!m_bInWriteTransaction) { if (FAILED(hres)) { InternalAbortTransaction(true); } else { hres = InternalCommitTransaction(true); if(hres == ERROR_SUCCESS) { lock.Unlock(); _IWmiCoreServices * pSvcs = g_Glob.GetCoreSvcs(); CReleaseMe rm(pSvcs); aNonTransactedEvents.SendEvents(pSvcs); } } aNonTransactedEvents.DeleteAllEvents(); } return hres; } catch (...) { return WBEM_E_CRITICAL_ERROR; } } HRESULT STDMETHODCALLTYPE CSession::DeleteObjectByPath( IWmiDbHandle *pScope, LPCWSTR wszObjectPath, DWORD dwFlags ) { #ifdef A51_SUPER_VERBOSE_LOGGING { ERRORTRACE((LOG_REPDRV, "CSession::DeleteObjectByPath - <%S>\n", wszObjectPath)); } #endif try { HRESULT hres; long lRes; CAutoWriteLock lock(&g_readWriteLock); CEventCollector aNonTransactedEvents; CEventCollector *aEvents = &m_aTransactedEvents; if (!m_bInWriteTransaction) { if (!lock.Lock()) return WBEM_E_FAILED; if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; aEvents = &aNonTransactedEvents; hres = InternalBeginTransaction(true); if(hres != ERROR_SUCCESS) return hres; } else if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; CNamespaceHandle* pNs = (CNamespaceHandle*)pScope; if(FAILED(pNs->GetErrorStatus())) { if(!m_bInWriteTransaction) { InternalAbortTransaction(true); } return pNs->GetErrorStatus(); } DWORD dwLen = wcslen(wszObjectPath)+1; LPWSTR wszPath = (WCHAR*)TempAlloc(dwLen*sizeof(WCHAR)); if (wszPath == NULL) { if(!m_bInWriteTransaction) { InternalAbortTransaction(true); } return WBEM_E_OUT_OF_MEMORY; } wcscpy(wszPath, wszObjectPath); CTempFreeMe vdm(wszPath, dwLen * sizeof(WCHAR)); hres = pNs->DeleteObjectByPath(dwFlags, wszPath, *aEvents); if(!m_bInWriteTransaction) { if (FAILED(hres)) { InternalAbortTransaction(true); } else { hres = InternalCommitTransaction(true); if(hres == ERROR_SUCCESS) { lock.Unlock(); _IWmiCoreServices * pSvcs = g_Glob.GetCoreSvcs(); CReleaseMe rm(pSvcs); aNonTransactedEvents.SendEvents(pSvcs); } } aNonTransactedEvents.DeleteAllEvents(); } return hres; } catch (...) { return WBEM_E_CRITICAL_ERROR; } } HRESULT STDMETHODCALLTYPE CSession::ExecQuery( IWmiDbHandle *pScope, IWbemQuery *pQuery, DWORD dwFlags, DWORD dwRequestedHandleType, DWORD *dwMessageFlags, IWmiDbIterator **ppQueryResult ) { #ifdef A51_SUPER_VERBOSE_LOGGING { LPWSTR wszQuery = NULL; HRESULT hres = pQuery->GetAnalysis(WMIQ_ANALYSIS_QUERY_TEXT, 0, (void**)&wszQuery); if (FAILED(hres)) return hres; ERRORTRACE((LOG_REPDRV, "CSession::ExecQuery - <%S>\n", wszQuery)); pQuery->FreeMemory(wszQuery); } #endif try { HRESULT hres; CAutoReadLock lock(&g_readWriteLock); if (!m_bInWriteTransaction) { if (!lock.Lock()) return WBEM_E_FAILED; } if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; CNamespaceHandle* pNs = (CNamespaceHandle*)pScope; if(FAILED(pNs->GetErrorStatus())) { return pNs->GetErrorStatus(); } //If we are in a transaction, we have to get a message to the iteratir //on create so it does not mess around with the locks! if (m_bInWriteTransaction) pNs->TellIteratorNotToLock(); hres = pNs->ExecQuery(pQuery, dwFlags, dwRequestedHandleType, dwMessageFlags, ppQueryResult); InternalCommitTransaction(false); return hres; } catch (...) { return WBEM_E_CRITICAL_ERROR; } } HRESULT STDMETHODCALLTYPE CSession::ExecQuerySink( IWmiDbHandle *pScope, IWbemQuery *pQuery, DWORD dwFlags, DWORD dwRequestedHandleType, IWbemObjectSink* pSink, DWORD *dwMessageFlags ) { try { HRESULT hres; CAutoReadLock lock(&g_readWriteLock); if (!m_bInWriteTransaction) { if (!lock.Lock()) return WBEM_E_FAILED; } if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; CNamespaceHandle* pNs = (CNamespaceHandle*)pScope; if(FAILED(pNs->GetErrorStatus())) { return pNs->GetErrorStatus(); } hres = pNs->ExecQuerySink(pQuery, dwFlags, dwRequestedHandleType, pSink, dwMessageFlags); InternalCommitTransaction(false); return hres; } catch (...) { return WBEM_E_CRITICAL_ERROR; } } HRESULT STDMETHODCALLTYPE CSession::RenameObject( IWbemPath *pOldPath, IWbemPath *pNewPath, DWORD dwFlags, DWORD dwRequestedHandleType, IWmiDbHandle **ppResult ) { DebugBreak(); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CSession::Enumerate( IWmiDbHandle *pScope, DWORD dwFlags, DWORD dwRequestedHandleType, IWmiDbIterator **ppQueryResult ) { DebugBreak(); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CSession::AddObject( IWmiDbHandle *pScope, IWbemPath *pPath, DWORD dwFlags, DWORD dwRequestedHandleType, IWmiDbHandle **ppResult ) { DebugBreak(); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CSession::RemoveObject ( IWmiDbHandle *pScope, IWbemPath *pPath, DWORD dwFlags ) { DebugBreak(); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CSession::SetDecoration( LPWSTR lpMachineName, LPWSTR lpNamespacePath ) { // // As the default driver, we really don't care. // return WBEM_S_NO_ERROR; } HRESULT STDMETHODCALLTYPE CSession::BeginWriteTransaction(DWORD dwFlags) { if (CLock::NoError != g_readWriteLock.WriteLock()) return WBEM_E_FAILED; if (g_bShuttingDown) { g_readWriteLock.WriteUnlock(); return WBEM_E_SHUTTING_DOWN; } HRESULT hres = InternalBeginTransaction(true); if(hres != ERROR_SUCCESS) { g_readWriteLock.WriteUnlock(); return hres; } m_bInWriteTransaction = true; return ERROR_SUCCESS; } HRESULT STDMETHODCALLTYPE CSession::BeginReadTransaction(DWORD dwFlags) { if (CLock::NoError != g_readWriteLock.ReadLock()) return WBEM_E_FAILED; if (g_bShuttingDown) { g_readWriteLock.ReadUnlock(); return WBEM_E_SHUTTING_DOWN; } return ERROR_SUCCESS; } HRESULT STDMETHODCALLTYPE CSession::CommitTransaction(DWORD dwFlags) { if (m_bInWriteTransaction) { long lRes = g_Glob.GetFileCache()->CommitTransaction(); if(lRes != ERROR_SUCCESS) { HRESULT hres = A51TranslateErrorCode(lRes); AbortTransaction(0); CRepository::RecoverCheckpoint(); return hres; } else { CRepository::WriteOperationNotification(); } m_bInWriteTransaction = false; //Copy the event list and delete the original. We need to deliver //outside the write lock. CEventCollector aTransactedEvents; aTransactedEvents.TransferEvents(m_aTransactedEvents); g_readWriteLock.WriteUnlock(); _IWmiCoreServices * pSvcs = g_Glob.GetCoreSvcs(); CReleaseMe rm(pSvcs); aTransactedEvents.SendEvents(pSvcs); aTransactedEvents.DeleteAllEvents(); } else { if (m_aTransactedEvents.GetSize()) { _ASSERT(false, L"Read transaction has events to send"); } g_readWriteLock.ReadUnlock(); } return ERROR_SUCCESS; } HRESULT STDMETHODCALLTYPE CSession::AbortTransaction(DWORD dwFlags) { if (m_bInWriteTransaction) { m_bInWriteTransaction = false; g_Glob.GetFileCache()->AbortTransaction(); m_aTransactedEvents.DeleteAllEvents(); g_readWriteLock.WriteUnlock(); } else { if (m_aTransactedEvents.GetSize()) { _ASSERT(false, L"Read transaction has events to send"); } g_readWriteLock.ReadUnlock(); } return ERROR_SUCCESS; } HRESULT CSession::InternalBeginTransaction(bool bWriteOperation) { if (bWriteOperation) { long lRes = g_Glob.GetFileCache()->BeginTransaction(); if (lRes) { //An internal error state may have been triggered, therefore //we should try and recover from that and try again... CRepository::RecoverCheckpoint(); lRes = g_Glob.GetFileCache()->BeginTransaction(); } return A51TranslateErrorCode(lRes); } else return ERROR_SUCCESS; } HRESULT CSession::InternalAbortTransaction(bool bWriteOperation) { if (bWriteOperation) { g_Glob.GetFileCache()->AbortTransaction(); } return ERROR_SUCCESS; } HRESULT CSession::InternalCommitTransaction(bool bWriteOperation) { DWORD dwres = ERROR_SUCCESS; if (bWriteOperation) { long lRes = g_Glob.GetFileCache()->CommitTransaction(); if(lRes != ERROR_SUCCESS) { dwres = A51TranslateErrorCode(lRes); InternalAbortTransaction(bWriteOperation); CRepository::RecoverCheckpoint(); } else { CRepository::WriteOperationNotification(); } } else { CRepository::ReadOperationNotification(); } return dwres; } // // // // /////////////////////////////////////////////////////////////////////// long CNamespaceHandle::s_lActiveRepNs = 0; CNamespaceHandle::CNamespaceHandle(CLifeControl* pControl,CRepository * pRepository) : TUnkBase(pControl), m_pClassCache(NULL), m_pNullClass(NULL), m_bCached(false), m_pRepository(pRepository), m_bUseIteratorLock(true) { m_pRepository->AddRef(); // unrefed pointer to a global m_ForestCache = g_Glob.GetForestCache(); InterlockedIncrement(&s_lActiveRepNs); } CNamespaceHandle::~CNamespaceHandle() { if(m_pClassCache) { // give-up our own reference // m_pClassCache->Release(); // remove from the Forest cache this namespace m_ForestCache->ReleaseNamespaceCache(m_wsNamespace, m_pClassCache); } m_pRepository->Release(); if(m_pNullClass) m_pNullClass->Release(); InterlockedDecrement(&s_lActiveRepNs); } CHR CNamespaceHandle::GetErrorStatus() { // // TEMP CODE: Someone is calling us on an impersonated thread. Let's catch // the, ahem, culprit // HANDLE hToken; BOOL bRes = OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &hToken); if(bRes) { //_ASSERT(false, L"Called with a thread token"); ERRORTRACE((LOG_WBEMCORE, "Repository called with a thread token! " "It shall be removed\n")); CloseHandle(hToken); SetThreadToken(NULL, NULL); } return m_pClassCache->GetError(); } void CNamespaceHandle::SetErrorStatus(HRESULT hres) { m_pClassCache->SetError(hres); } CHR CNamespaceHandle::Initialize(LPCWSTR wszNamespace, LPCWSTR wszScope) { HRESULT hres; m_wsNamespace = wszNamespace; m_wsFullNamespace = L"\\\\.\\"; m_wsFullNamespace += wszNamespace; DWORD dwSize = MAX_COMPUTERNAME_LENGTH+1; GetComputerNameW(m_wszMachineName, &dwSize); if(wszScope) m_wsScope = wszScope; // // Ask the forest for the cache for this namespace // m_pClassCache = g_Glob.GetForestCache()-> GetNamespaceCache(wszNamespace); if(m_pClassCache == NULL) return WBEM_E_OUT_OF_MEMORY; wcscpy(m_wszClassRootDir, g_Glob.GetRootDir()); // // Append namespace-specific prefix // wcscat(m_wszClassRootDir, L"\\NS_"); // // Append hashed namespace name // if (!Hash(wszNamespace, m_wszClassRootDir + wcslen(m_wszClassRootDir))) return WBEM_E_OUT_OF_MEMORY; m_lClassRootDirLen = wcslen(m_wszClassRootDir); // // Constuct the instance root dir // if(wszScope == NULL) { // // Basic namespace --- instances go into the root of the namespace // wcscpy(m_wszInstanceRootDir, m_wszClassRootDir); m_lInstanceRootDirLen = m_lClassRootDirLen; } else { wcscpy(m_wszInstanceRootDir, m_wszClassRootDir); wcscat(m_wszInstanceRootDir, L"\\" A51_SCOPE_DIR_PREFIX); if(!Hash(m_wsScope, m_wszInstanceRootDir + wcslen(m_wszInstanceRootDir))) { return WBEM_E_OUT_OF_MEMORY; } m_lInstanceRootDirLen = wcslen(m_wszInstanceRootDir); } return WBEM_S_NO_ERROR; } CHR CNamespaceHandle::GetObject( IWbemPath *pPath, DWORD dwFlags, DWORD dwRequestedHandleType, IWmiDbHandle **ppResult ) { HRESULT hres; if((dwRequestedHandleType & WMIDB_HANDLE_TYPE_COOKIE) == 0) { DebugBreak(); return E_NOTIMPL; } DWORD dwLen = 0; hres = pPath->GetText(WBEMPATH_GET_ORIGINAL, &dwLen, NULL); if(FAILED(hres) && hres != WBEM_E_BUFFER_TOO_SMALL) return hres; WCHAR* wszBuffer = (WCHAR*)TempAlloc(dwLen * sizeof(WCHAR)); if(wszBuffer == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe tfm(wszBuffer, dwLen * sizeof(WCHAR)); if(FAILED(pPath->GetText(WBEMPATH_GET_ORIGINAL, &dwLen, wszBuffer))) return WBEM_E_FAILED; return GetObjectHandleByPath(wszBuffer, dwFlags, dwRequestedHandleType, ppResult); } CHR CNamespaceHandle::GetObjectHandleByPath( LPWSTR wszBuffer, DWORD dwFlags, DWORD dwRequestedHandleType, IWmiDbHandle **ppResult ) { // // Get the key from path // DWORD dwLen = wcslen(wszBuffer)*sizeof(WCHAR)+2; LPWSTR wszKey = (WCHAR*)TempAlloc(dwLen); if(wszKey == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe tfm(wszKey, dwLen); bool bIsClass; LPWSTR wszClassName = NULL; HRESULT hres = ComputeKeyFromPath(wszBuffer, wszKey, &wszClassName, &bIsClass); if(FAILED(hres)) return hres; CTempFreeMe tfm1(wszClassName, (wcslen(wszClassName)+1) * sizeof(WCHAR*)); // // Check if it exists (except for ROOT --- it's fake) // _IWmiObject* pObj = NULL; if(m_wsNamespace.Length() > 0) { hres = GetInstanceByKey(wszClassName, wszKey, IID__IWmiObject, (void**)&pObj); if(FAILED(hres)) return hres; } CReleaseMe rm1(pObj); CNamespaceHandle* pNewHandle = new CNamespaceHandle(m_pControl,m_pRepository); if (pNewHandle == NULL) return WBEM_E_OUT_OF_MEMORY; pNewHandle->AddRef(); CReleaseMe rm2(pNewHandle); // // Check if this is a namespace or not // if(pObj == NULL || pObj->InheritsFrom(L"__Namespace") == S_OK) { // // It's a namespace. Open a basic handle pointing to it // WString wsName = m_wsNamespace; if(wsName.Length() > 0) wsName += L"\\"; wsName += wszKey; hres = pNewHandle->Initialize(wsName); // // Since our namespace is for real, tell the cache that it is now valid. // The cache might have been invalidated if this namespace was deleted // in the past // if (SUCCEEDED(hres)) pNewHandle->SetErrorStatus(S_OK); } else { // // It's a scope. Construct the new scope name by appending this // object's path to our own scope // VARIANT v; VariantInit(&v); CClearMe cm(&v); hres = pObj->Get(L"__RELPATH", 0, &v, NULL, NULL); if(FAILED(hres)) return hres; if(V_VT(&v) != VT_BSTR) return WBEM_E_INVALID_OBJECT; WString wsScope = m_wsScope; if(wsScope.Length() > 0) wsScope += L":"; wsScope += V_BSTR(&v); hres = pNewHandle->Initialize(m_wsNamespace, wsScope); } if(FAILED(hres)) return hres; return pNewHandle->QueryInterface(IID_IWmiDbHandle, (void**)ppResult); } CHR CNamespaceHandle::ComputeKeyFromPath(LPWSTR wszPath, LPWSTR wszKey, TEMPFREE_ME LPWSTR* pwszClass, bool* pbIsClass, TEMPFREE_ME LPWSTR* pwszNamespace) { HRESULT hres; *pbIsClass = false; // // Get and skip the namespace portion. // if(wszPath[0] == '\\' || wszPath[0] == '/') { // // Find where the server portion ends // WCHAR* pwcNextSlash = wcschr(wszPath+2, wszPath[0]); if(pwcNextSlash == NULL) return WBEM_E_INVALID_OBJECT_PATH; // // Find where the namespace portion ends // WCHAR* pwcColon = wcschr(pwcNextSlash, L':'); if(pwcColon == NULL) return WBEM_E_INVALID_OBJECT_PATH; if(pwszNamespace) { DWORD dwLen = pwcColon - pwcNextSlash; *pwszNamespace = (WCHAR*)TempAlloc(dwLen * sizeof(WCHAR)); if(*pwszNamespace == NULL) return WBEM_E_OUT_OF_MEMORY; *pwcColon = 0; wcscpy(*pwszNamespace, pwcNextSlash+1); } // // Advance wszPath to beyond the namespace portion // wszPath = pwcColon+1; } else if(pwszNamespace) { *pwszNamespace = NULL; } // Get the first key WCHAR* pwcFirstEq = wcschr(wszPath, L'='); if(pwcFirstEq == NULL) { // // It's a class! // *pbIsClass = true; // path to the "class" to distinguish from its instances wszKey[0] = 1; wszKey[1] = 0; *pwszClass = (WCHAR*)TempAlloc((wcslen(wszPath)+1) * sizeof(WCHAR)); if(*pwszClass == NULL) { if(pwszNamespace) TempFree(*pwszNamespace); return WBEM_E_OUT_OF_MEMORY; } wcscpy(*pwszClass, wszPath); return S_OK; } WCHAR* pwcFirstDot = wcschr(wszPath, L'.'); if(pwcFirstDot == NULL || pwcFirstDot > pwcFirstEq) { // No name on the first key *pwcFirstEq = 0; *pwszClass = (WCHAR*)TempAlloc((wcslen(wszPath)+1) * sizeof(WCHAR)); if(*pwszClass == NULL) { if(pwszNamespace) TempFree(*pwszNamespace); return WBEM_E_OUT_OF_MEMORY; } wcscpy(*pwszClass, wszPath); WCHAR* pwcThisKey = NULL; WCHAR* pwcEnd = NULL; hres = ParseKey(pwcFirstEq+1, &pwcThisKey, &pwcEnd); if(FAILED(hres)) { TempFree(*pwszClass); if(pwszNamespace) TempFree(*pwszNamespace); return hres; } if(*pwcEnd != NULL) { TempFree(*pwszClass); if(pwszNamespace) TempFree(*pwszNamespace); return WBEM_E_INVALID_OBJECT_PATH; } wcscpy(wszKey, pwcThisKey); return S_OK; } // // Normal case // // // Get all the key values // struct CKeyStruct { WCHAR* m_pwcValue; WCHAR* m_pwcName; } * aKeys = (CKeyStruct*)TempAlloc(sizeof(CKeyStruct[256])); if (0==aKeys) { if(pwszNamespace) TempFree(*pwszNamespace); return WBEM_E_OUT_OF_MEMORY; } CTempFreeMe release_aKeys(aKeys); DWORD dwNumKeys = 0; *pwcFirstDot = NULL; *pwszClass = (WCHAR*)TempAlloc((wcslen(wszPath)+1) * sizeof(WCHAR)); if(*pwszClass == NULL) { if(pwszNamespace) TempFree(*pwszNamespace); return WBEM_E_OUT_OF_MEMORY; } wcscpy(*pwszClass, wszPath); WCHAR* pwcNextKey = pwcFirstDot+1; do { pwcFirstEq = wcschr(pwcNextKey, L'='); if(pwcFirstEq == NULL) { TempFree(*pwszClass); if(pwszNamespace) TempFree(*pwszNamespace); return WBEM_E_INVALID_OBJECT_PATH; } *pwcFirstEq = 0; aKeys[dwNumKeys].m_pwcName = pwcNextKey; hres = ParseKey(pwcFirstEq+1, &(aKeys[dwNumKeys].m_pwcValue), &pwcNextKey); if(FAILED(hres)) { TempFree(*pwszClass); if(pwszNamespace) TempFree(*pwszNamespace); return hres; } dwNumKeys++; } while(*pwcNextKey); if(*pwcNextKey != 0) { TempFree(*pwszClass); if(pwszNamespace) TempFree(*pwszNamespace); return WBEM_E_INVALID_OBJECT_PATH; } // // We have the array of keys --- sort it // DWORD dwCurrentIndex = 0; while(dwCurrentIndex < dwNumKeys-1) { if(wbem_wcsicmp(aKeys[dwCurrentIndex].m_pwcName, aKeys[dwCurrentIndex+1].m_pwcName) > 0) { CKeyStruct Temp = aKeys[dwCurrentIndex]; aKeys[dwCurrentIndex] = aKeys[dwCurrentIndex+1]; aKeys[dwCurrentIndex+1] = Temp; if(dwCurrentIndex) dwCurrentIndex--; else dwCurrentIndex++; } else dwCurrentIndex++; } // // Now generate the result // WCHAR* pwcKeyEnd = wszKey; for(DWORD i = 0; i < dwNumKeys; i++) { wcscpy(pwcKeyEnd, aKeys[i].m_pwcValue); pwcKeyEnd += wcslen(aKeys[i].m_pwcValue); if(i < dwNumKeys-1) *(pwcKeyEnd++) = -1; } *pwcKeyEnd = 0; return S_OK; } CHR CNamespaceHandle::ParseKey(LPWSTR wszKeyStart, LPWSTR* pwcRealStart, LPWSTR* pwcNextKey) { if(wszKeyStart[0] == L'"' || wszKeyStart[0] == L'\'') { WCHAR wcStart = wszKeyStart[0]; WCHAR* pwcRead = wszKeyStart+1; WCHAR* pwcWrite = wszKeyStart+1; while(*pwcRead && *pwcRead != wcStart) { if((*pwcRead == '\\') && (*(pwcRead+1) != 'x') && (*(pwcRead+1) != 'X')) pwcRead++; *(pwcWrite++) = *(pwcRead++); } if(*pwcRead == 0) return WBEM_E_INVALID_OBJECT_PATH; *pwcWrite = 0; if(pwcRealStart) *pwcRealStart = wszKeyStart+1; // // Check separator // if(pwcRead[1] && pwcRead[1] != L',') return WBEM_E_INVALID_OBJECT_PATH; if(pwcNextKey) { // // If there is a separator, skip it. Don't skip end of string! // if(pwcRead[1]) *pwcNextKey = pwcRead+2; else *pwcNextKey = pwcRead+1; } } else { if(pwcRealStart) *pwcRealStart = wszKeyStart; WCHAR* pwcComma = wcschr(wszKeyStart, L','); if(pwcComma == NULL) { if(pwcNextKey) *pwcNextKey = wszKeyStart + wcslen(wszKeyStart); } else { *pwcComma = 0; if(pwcNextKey) *pwcNextKey = pwcComma+1; } } return S_OK; } CHR CNamespaceHandle::GetObjectDirect( IWbemPath *pPath, DWORD dwFlags, REFIID riid, LPVOID *pObj ) { HRESULT hres; DWORD dwLen = 0; hres = pPath->GetText(WBEMPATH_GET_ORIGINAL, &dwLen, NULL); LPWSTR wszPath = (WCHAR*)TempAlloc(dwLen*sizeof(WCHAR)); if (wszPath == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe vdm(wszPath, dwLen * sizeof(WCHAR)); hres = pPath->GetText(WBEMPATH_GET_ORIGINAL, &dwLen, wszPath); if(FAILED(hres)) return hres; return GetObjectByPath(wszPath, dwFlags, riid, pObj); } CHR CNamespaceHandle::GetObjectByPath( LPWSTR wszPath, DWORD dwFlags, REFIID riid, LPVOID *pObj ) { HRESULT hres; // // Get the key from path // DWORD dwLen = wcslen(wszPath)*sizeof(WCHAR)+2; LPWSTR wszKey = (WCHAR*)TempAlloc(dwLen); if(wszKey == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe tfm(wszKey, dwLen); bool bIsClass; LPWSTR wszClassName = NULL; hres = ComputeKeyFromPath(wszPath, wszKey, &wszClassName, &bIsClass); if(FAILED(hres)) return hres; CTempFreeMe tfm1(wszClassName, (wcslen(wszClassName)+1) * sizeof(WCHAR*)); if(bIsClass) { return GetClassDirect(wszClassName, riid, pObj, true, NULL, NULL, NULL); } else { return GetInstanceByKey(wszClassName, wszKey, riid, pObj); } } CHR CNamespaceHandle::GetInstanceByKey(LPCWSTR wszClassName, LPCWSTR wszKey, REFIID riid, void** ppObj) { HRESULT hres; // // Get the class definition // _IWmiObject* pClass = NULL; hres = GetClassDirect(wszClassName, IID__IWmiObject, (void**)&pClass, false, NULL, NULL, NULL); if(FAILED(hres)) return hres; CReleaseMe rm1(pClass); // // Construct directory path // CFileName wszFilePath; if (wszFilePath == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructKeyRootDirFromClass(wszFilePath, wszClassName); if(FAILED(hres)) return hres; // // Construct the file path // int nLen = wcslen(wszFilePath); wszFilePath[nLen] = L'\\'; hres = ConstructInstanceDefName(wszFilePath+nLen+1, wszKey); if(FAILED(hres)) return hres; // // Get the object from that file // _IWmiObject* pInst; hres = FileToInstance(NULL, wszFilePath, NULL, 0, &pInst); if(FAILED(hres)) return hres; CReleaseMe rm2(pInst); // // Return // return pInst->QueryInterface(riid, (void**)ppObj); } CHR CNamespaceHandle::GetClassByHash(LPCWSTR wszHash, bool bClone, _IWmiObject** ppClass, __int64* pnTime, bool* pbRead, bool *pbSystemClass) { HRESULT hres; // // Check the cache first // *ppClass = m_pClassCache->GetClassDefByHash(wszHash, bClone, pnTime, pbRead, pbSystemClass); if(*ppClass) return S_OK; // // Not found --- construct the file name and read it // if(pbRead) *pbRead = true; CFileName wszFileName; if (wszFileName == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructClassDefFileNameFromHash(wszHash, wszFileName); if(FAILED(hres)) return hres; CFileName wszFilePath; if (wszFilePath == NULL) return WBEM_E_OUT_OF_MEMORY; swprintf(wszFilePath, L"%s\\%s", m_wszClassRootDir, wszFileName); hres = FileToClass(wszFilePath, ppClass, bClone, pnTime, pbSystemClass); if(FAILED(hres)) return hres; return S_OK; } CHR CNamespaceHandle::GetClassDirect(LPCWSTR wszClassName, REFIID riid, void** ppObj, bool bClone, __int64* pnTime, bool* pbRead, bool *pbSystemClass) { HRESULT hres; if(wszClassName == NULL || wcslen(wszClassName) == 0) { if(m_pNullClass == NULL) { hres = CoCreateInstance(CLSID_WbemClassObject, NULL, CLSCTX_INPROC_SERVER, IID__IWmiObject, (void **)&m_pNullClass); if (FAILED(hres)) return hres; } IWbemClassObject* pRawObj; hres = m_pNullClass->Clone(&pRawObj); if (FAILED(hres)) return hres; CReleaseMe rm(pRawObj); if(pnTime) *pnTime = 0; if(pbRead) *pbRead = false; return pRawObj->QueryInterface(riid, ppObj); } _IWmiObject* pClass; // // Check the cache first // pClass = m_pClassCache->GetClassDef(wszClassName, bClone, pnTime, pbRead); if(pClass) { CReleaseMe rm1(pClass); return pClass->QueryInterface(riid, ppObj); } if(pbRead) *pbRead = true; // // Construct the path for the file // CFileName wszFileName; if (wszFileName == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructClassDefFileName(wszClassName, wszFileName); if(FAILED(hres)) return hres; CFileName wszFilePath; if (wszFilePath == NULL) return WBEM_E_OUT_OF_MEMORY; swprintf(wszFilePath, L"%s\\%s", m_wszClassRootDir, wszFileName); // // Read it from the file // hres = FileToClass(wszFilePath, &pClass, bClone, pnTime, pbSystemClass); if(FAILED(hres)) return hres; CReleaseMe rm1(pClass); return pClass->QueryInterface(riid, ppObj); } CHR CNamespaceHandle::FileToInstance(_IWmiObject* pClass, LPCWSTR wszFileName, BYTE *pRetrievedBlob, DWORD dwSize, _IWmiObject** ppInstance, bool bMustBeThere) { HRESULT hres; // // Read the data from the file // BYTE* pBlob = NULL; if (pRetrievedBlob == NULL) { long lRes = g_Glob.GetFileCache()->ReadObject(wszFileName, &dwSize, &pBlob, bMustBeThere); if(lRes != ERROR_SUCCESS) { if(lRes == ERROR_FILE_NOT_FOUND || lRes == ERROR_PATH_NOT_FOUND) return WBEM_E_NOT_FOUND; else return WBEM_E_FAILED; } pRetrievedBlob = pBlob; } CTempFreeMe tfm1(pBlob, dwSize); _ASSERT(dwSize > sizeof(__int64), L"Instance blob too short"); if(dwSize <= sizeof(__int64)) return WBEM_E_OUT_OF_MEMORY; // // Extract the class hash // WCHAR wszClassHash[MAX_HASH_LEN+1]; DWORD dwClassHashLen = MAX_HASH_LEN*sizeof(WCHAR); memcpy(wszClassHash, pRetrievedBlob, MAX_HASH_LEN*sizeof(WCHAR)); wszClassHash[MAX_HASH_LEN] = 0; __int64 nInstanceTime; memcpy(&nInstanceTime, pRetrievedBlob + dwClassHashLen, sizeof(__int64)); __int64 nOldClassTime; memcpy(&nOldClassTime, pRetrievedBlob + dwClassHashLen + sizeof(__int64), sizeof(__int64)); BYTE* pInstancePart = pRetrievedBlob + dwClassHashLen + sizeof(__int64)*2; DWORD dwInstancePartSize = dwSize - dwClassHashLen - sizeof(__int64)*2; // // Get the class def // _IWmiObject* pRetrievedClass = NULL; if (pClass == NULL) { __int64 nClassTime; bool bRead; bool bSystemClass = false; hres = GetClassByHash(wszClassHash, false, &pRetrievedClass, &nClassTime, &bRead, &bSystemClass); if(FAILED(hres)) return hres; pClass = pRetrievedClass; } CReleaseMe rm1(pRetrievedClass); #ifdef A51_CHECK_TIMESTAMPS _ASSERT(nClassTime <= nInstanceTime, L"Instance is older than its class"); _ASSERT(nClassTime == nOldClassTime, L"Instance verified with the wrong " L"class definition"); #endif // // Construct the instance // _IWmiObject* pInst = NULL; hres = pClass->Merge(WMIOBJECT_MERGE_FLAG_INSTANCE, dwInstancePartSize, pInstancePart, &pInst); if(FAILED(hres)) return hres; // // Decorate it // pInst->SetDecoration(m_wszMachineName, m_wsNamespace); A51TRACE(("Read instance from %S in namespace %S\n", wszFileName, (LPCWSTR)m_wsNamespace)); *ppInstance = pInst; return S_OK; } CHR CNamespaceHandle::FileToSystemClass(LPCWSTR wszFileName, _IWmiObject** ppClass, bool bClone, __int64* pnTime) { // // Note: we must always clone the result of the system class retrieval, // since it will be decorated by the caller // return GetClassByHash(wszFileName + (wcslen(wszFileName) - MAX_HASH_LEN), true, ppClass, pnTime, NULL, NULL); } CHR CNamespaceHandle::FileToClass(LPCWSTR wszFileName, _IWmiObject** ppClass, bool bClone, __int64* pnTime, bool *pbSystemClass) { HRESULT hres; // // Read the data from the file // __int64 nTime; DWORD dwSize; BYTE* pBlob; VARIANT vClass; long lRes = g_Glob.GetFileCache()->ReadObject(wszFileName, &dwSize, &pBlob); if(lRes != ERROR_SUCCESS) { //We didn't find it here, so lets try and find it in the default namespace! //If we are not in the __SYSTEMCLASS namespace then we need to call into that... if((lRes == ERROR_FILE_NOT_FOUND || lRes == ERROR_PATH_NOT_FOUND) && g_pSystemClassNamespace && wcscmp(m_wsNamespace, A51_SYSTEMCLASS_NS) != 0) { hres = g_pSystemClassNamespace->FileToSystemClass(wszFileName, ppClass, bClone, &nTime); if (FAILED(hres)) return hres; if (pnTime) *pnTime = nTime; //need to cache this item in the local cache hres = (*ppClass)->Get(L"__CLASS", 0, &vClass, NULL, NULL); if(FAILED(hres) || V_VT(&vClass) != VT_BSTR) return WBEM_E_INVALID_OBJECT; CClearMe cm1(&vClass); A51TRACE(("Read class %S from disk in namespace %S\n", V_BSTR(&vClass), m_wsNamespace)); (*ppClass)->SetDecoration(m_wszMachineName, m_wsNamespace); m_pClassCache->AssertClass((*ppClass), V_BSTR(&vClass), bClone, nTime, true); if (pbSystemClass) *pbSystemClass = true; return hres; } else if (lRes == ERROR_FILE_NOT_FOUND || lRes == ERROR_PATH_NOT_FOUND) return WBEM_E_NOT_FOUND; else return WBEM_E_FAILED; } CTempFreeMe tfm1(pBlob, dwSize); _ASSERT(dwSize > sizeof(__int64), L"Class blob too short"); if(dwSize <= sizeof(__int64)) return WBEM_E_OUT_OF_MEMORY; // // Read off the superclass name // DWORD dwSuperLen; memcpy(&dwSuperLen, pBlob, sizeof(DWORD)); LPWSTR wszSuperClass = (WCHAR*)TempAlloc(dwSuperLen*sizeof(WCHAR)+2); if (wszSuperClass == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe vdm1(wszSuperClass, dwSuperLen*sizeof(WCHAR)+2); wszSuperClass[dwSuperLen] = 0; memcpy(wszSuperClass, pBlob+sizeof(DWORD), dwSuperLen*sizeof(WCHAR)); DWORD dwPrefixLen = sizeof(DWORD) + dwSuperLen*sizeof(WCHAR); memcpy(&nTime, pBlob + dwPrefixLen, sizeof(__int64)); // // Get the superclass // _IWmiObject* pSuperClass; __int64 nSuperTime; bool bRead; hres = GetClassDirect(wszSuperClass, IID__IWmiObject, (void**)&pSuperClass, false, &nSuperTime, &bRead, NULL); if(FAILED(hres)) return WBEM_E_CRITICAL_ERROR; CReleaseMe rm1(pSuperClass); #ifdef A51_CHECK_TIMESTAMPS _ASSERT(nSuperTime <= nTime, L"Parent class is older than child"); #endif DWORD dwClassLen = dwSize - dwPrefixLen - sizeof(__int64); _IWmiObject* pNewObj; hres = pSuperClass->Merge(0, dwClassLen, pBlob + dwPrefixLen + sizeof(__int64), &pNewObj); if(FAILED(hres)) return hres; // // Decorate it // pNewObj->SetDecoration(m_wszMachineName, m_wsNamespace); // // Cache it! // hres = pNewObj->Get(L"__CLASS", 0, &vClass, NULL, NULL); if(FAILED(hres) || V_VT(&vClass) != VT_BSTR) return WBEM_E_INVALID_OBJECT; CClearMe cm1(&vClass); A51TRACE(("Read class %S from disk in namespace %S\n", V_BSTR(&vClass), m_wsNamespace)); m_pClassCache->AssertClass(pNewObj, V_BSTR(&vClass), bClone, nTime, false); *ppClass = pNewObj; if(pnTime) *pnTime = nTime; if (pbSystemClass) *pbSystemClass = false; return S_OK; } CHR CNamespaceHandle::PutObject( REFIID riid, LPVOID pObj, DWORD dwFlags, DWORD dwRequestedHandleType, IWmiDbHandle **ppResult, CEventCollector &aEvents ) { HRESULT hres; _IWmiObject* pObjEx = NULL; ((IUnknown*)pObj)->QueryInterface(IID__IWmiObject, (void**)&pObjEx); CReleaseMe rm1(pObjEx); if(pObjEx->IsObjectInstance() == S_OK) { hres = PutInstance(pObjEx, dwFlags, aEvents); } else { hres = PutClass(pObjEx, dwFlags, aEvents); } if(FAILED(hres)) return hres; if(ppResult) { // // Got to get a handle // VARIANT v; hres = pObjEx->Get(L"__RELPATH", 0, &v, NULL, NULL); if(FAILED(hres) || V_VT(&v) != VT_BSTR) return WBEM_E_INVALID_OBJECT; hres = GetObjectHandleByPath(V_BSTR(&v), 0, WMIDB_HANDLE_TYPE_COOKIE, ppResult); if(FAILED(hres)) return hres; } return S_OK; } CHR CNamespaceHandle::PutInstance(_IWmiObject* pInst, DWORD dwFlags, CEventCollector &aEvents) { HRESULT hres; bool bDisableEvents = ((dwFlags & WMIDB_DISABLE_EVENTS)?true:false); // // Get the class name // VARIANT vClass; hres = pInst->Get(L"__CLASS", 0, &vClass, NULL, NULL); if(FAILED(hres) || V_VT(&vClass) != VT_BSTR) return WBEM_E_INVALID_OBJECT; CClearMe cm1(&vClass); LPCWSTR wszClassName = V_BSTR(&vClass); // // Get the class so we can compare to make sure it is the same class used to // create the instance // _IWmiObject* pClass = NULL; __int64 nClassTime; hres = GetClassDirect(wszClassName, IID__IWmiObject, (void**)&pClass, false, &nClassTime, NULL, NULL); if(FAILED(hres)) return hres; CReleaseMe rm2(pClass); if(wszClassName[0] != L'_') { hres = pInst->IsParentClass(0, pClass); if(FAILED(hres)) return hres; if(hres == WBEM_S_FALSE) return WBEM_E_INVALID_CLASS; } // // Get the path // VARIANT var; VariantInit(&var); hres = pInst->Get(L"__relpath", 0, &var, 0, 0); if (FAILED(hres)) return hres; CClearMe cm2(&var); DWORD dwLen = (wcslen(V_BSTR(&var)) + 1) * sizeof(WCHAR); LPWSTR strKey = (WCHAR*)TempAlloc(dwLen); if(strKey == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe tfm(strKey, dwLen); bool bIsClass; LPWSTR __wszClassName = NULL; hres = ComputeKeyFromPath(V_BSTR(&var), strKey, &__wszClassName, &bIsClass); if(FAILED(hres)) return hres; CTempFreeMe tfm1(__wszClassName); A51TRACE(("Putting instance %S of class %S\n", strKey, wszClassName)); // // Get the old copy // _IWmiObject* pOldInst = NULL; hres = GetInstanceByKey(wszClassName, strKey, IID__IWmiObject, (void**)&pOldInst); if(FAILED(hres) && hres != WBEM_E_NOT_FOUND) return hres; CReleaseMe rm1(pOldInst); if ((dwFlags & WBEM_FLAG_CREATE_ONLY) && (hres != WBEM_E_NOT_FOUND)) return WBEM_E_ALREADY_EXISTS; else if ((dwFlags & WBEM_FLAG_UPDATE_ONLY) && (hres != WBEM_S_NO_ERROR)) return WBEM_E_NOT_FOUND; if(pOldInst) { // // Check that this guy is of the same class as the new one // // // Get the class name // VARIANT vClass2; hres = pOldInst->Get(L"__CLASS", 0, &vClass2, NULL, NULL); if(FAILED(hres)) return hres; if(V_VT(&vClass2) != VT_BSTR) return WBEM_E_INVALID_OBJECT; CClearMe cm3(&vClass2); if(wbem_wcsicmp(V_BSTR(&vClass2), wszClassName)) return WBEM_E_INVALID_CLASS; } // // Construct the hash for the file // CFileName wszInstanceHash; if (wszInstanceHash == NULL) return WBEM_E_OUT_OF_MEMORY; if(!Hash(strKey, wszInstanceHash)) return WBEM_E_OUT_OF_MEMORY; // // Construct the path to the instance file in key root // CFileName wszInstanceFilePath; if (wszInstanceFilePath == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructKeyRootDirFromClass(wszInstanceFilePath, wszClassName); if(FAILED(hres)) return hres; wcscat(wszInstanceFilePath, L"\\" A51_INSTDEF_FILE_PREFIX); wcscat(wszInstanceFilePath, wszInstanceHash); // // Construct the path to the link file under the class // CFileName wszInstanceLinkPath; if (wszInstanceLinkPath == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructLinkDirFromClass(wszInstanceLinkPath, wszClassName); if(FAILED(hres)) return hres; wcscat(wszInstanceLinkPath, L"\\" A51_INSTLINK_FILE_PREFIX); wcscat(wszInstanceLinkPath, wszInstanceHash); // // Clean up what was there, if anything // if(pOldInst) { // // Just delete it, but be careful not to delete the scope! // hres = DeleteInstanceSelf(wszInstanceFilePath, pOldInst, false); if(FAILED(hres) && hres != WBEM_E_NOT_FOUND) return hres; } // // Create the actual instance def under key root // hres = InstanceToFile(pInst, wszClassName, wszInstanceFilePath, wszInstanceLinkPath, nClassTime); if(FAILED(hres)) return hres; // // Write the references // hres = WriteInstanceReferences(pInst, wszClassName, wszInstanceFilePath); if(FAILED(hres)) return hres; if(!bDisableEvents) { // // Fire Event // if(pInst->InheritsFrom(L"__Namespace") == S_OK) { // // Get the namespace name // VARIANT vClass2; VariantInit(&vClass2); CClearMe cm3(&vClass2); hres = pInst->Get(L"Name", 0, &vClass2, NULL, NULL); if(FAILED(hres) || V_VT(&vClass2) != VT_BSTR) return WBEM_E_INVALID_OBJECT; if(pOldInst) { hres = FireEvent(aEvents, WBEM_EVENTTYPE_NamespaceModification, V_BSTR(&vClass2), pInst, pOldInst); } else { hres = FireEvent(aEvents, WBEM_EVENTTYPE_NamespaceCreation, V_BSTR(&vClass2), pInst); } } else { if(pOldInst) { hres = FireEvent(aEvents, WBEM_EVENTTYPE_InstanceModification, wszClassName, pInst, pOldInst); } else { hres = FireEvent(aEvents, WBEM_EVENTTYPE_InstanceCreation, wszClassName, pInst); } } } A51TRACE(("PutInstance for %S of class %S succeeded\n", strKey, wszClassName)); return S_OK; } CHR CNamespaceHandle::GetKeyRoot(LPCWSTR wszClass, TEMPFREE_ME LPWSTR* pwszKeyRootClass) { HRESULT hres; // // Look in the cache first // hres = m_pClassCache->GetKeyRoot(wszClass, pwszKeyRootClass); if(hres == S_OK) return S_OK; else if(hres == WBEM_E_CANNOT_BE_ABSTRACT) return WBEM_E_CANNOT_BE_ABSTRACT; // // Walk up the tree getting classes until you hit an unkeyed one // WString wsThisName = wszClass; WString wsPreviousName; while(1) { _IWmiObject* pClass = NULL; hres = GetClassDirect(wsThisName, IID__IWmiObject, (void**)&pClass, false, NULL, NULL, NULL); if(FAILED(hres)) return hres; CReleaseMe rm1(pClass); // // Check if this class is keyed // unsigned __int64 i64Flags = 0; hres = pClass->QueryObjectFlags(0, WMIOBJECT_GETOBJECT_LOFLAG_KEYED, &i64Flags); if(FAILED(hres)) return hres; if(i64Flags == 0) { // // It is not keyed --- the previous class wins! // if(wsPreviousName.Length() == 0) return WBEM_E_CANNOT_BE_ABSTRACT; DWORD dwLen = (wsPreviousName.Length()+1)*sizeof(WCHAR); *pwszKeyRootClass = (WCHAR*)TempAlloc(dwLen); if (*pwszKeyRootClass == NULL) return WBEM_E_OUT_OF_MEMORY; wcscpy(*pwszKeyRootClass, (LPCWSTR)wsPreviousName); return S_OK; } // // It is keyed --- get the parent and continue; // VARIANT vParent; VariantInit(&vParent); CClearMe cm(&vParent); hres = pClass->Get(L"__SUPERCLASS", 0, &vParent, NULL, NULL); if(FAILED(hres)) return hres; if(V_VT(&vParent) != VT_BSTR) { // // We've reached the top --- return this class // DWORD dwLen = (wsThisName.Length()+1)*sizeof(WCHAR); *pwszKeyRootClass = (WCHAR*)TempAlloc(dwLen); if (*pwszKeyRootClass == NULL) return WBEM_E_OUT_OF_MEMORY; wcscpy(*pwszKeyRootClass, (LPCWSTR)wsThisName); return S_OK; } wsPreviousName = wsThisName; wsThisName = V_BSTR(&vParent); } // Never here DebugBreak(); return WBEM_E_CRITICAL_ERROR; } CHR CNamespaceHandle::GetKeyRootByHash(LPCWSTR wszClassHash, TEMPFREE_ME LPWSTR* pwszKeyRootClass) { // // Look in the cache first // HRESULT hres = m_pClassCache->GetKeyRootByKey(wszClassHash, pwszKeyRootClass); if(hres == S_OK) return S_OK; else if(hres == WBEM_E_CANNOT_BE_ABSTRACT) return WBEM_E_CANNOT_BE_ABSTRACT; // // NOTE: this could be done more efficiently, but it happens once in a // lifetime, so it's not worth the complexity. // // // Get Class definition // _IWmiObject* pClass = NULL; hres = GetClassByHash(wszClassHash, false, &pClass, NULL, NULL, NULL); if(FAILED(hres)) return hres; CReleaseMe rm1(pClass); // // Get the class name // VARIANT vClass; hres = pClass->Get(L"__CLASS", 0, &vClass, NULL, NULL); if(FAILED(hres) || (V_VT(&vClass) != VT_BSTR) || !V_BSTR(&vClass) || !wcslen(V_BSTR(&vClass))) { return WBEM_E_INVALID_OBJECT; } CClearMe cm1(&vClass); LPCWSTR wszClassName = V_BSTR(&vClass); // // Now get it by name // return GetKeyRoot(wszClassName, pwszKeyRootClass); } CHR CNamespaceHandle::ConstructKeyRootDirFromClass(LPWSTR wszDir, LPCWSTR wszClassName) { HRESULT hres; // // NULL class stands for "meta-class" // if(wszClassName == NULL) return ConstructKeyRootDirFromKeyRoot(wszDir, L""); // // Figure out the key root for the class // LPWSTR wszKeyRootClass = NULL; hres = GetKeyRoot(wszClassName, &wszKeyRootClass); if(FAILED(hres)) return hres; if(wszKeyRootClass == NULL) { // Abstract class --- bad error return WBEM_E_INVALID_CLASS; } CTempFreeMe tfm(wszKeyRootClass, (wcslen(wszKeyRootClass)+1)*sizeof(WCHAR)); return ConstructKeyRootDirFromKeyRoot(wszDir, wszKeyRootClass); } CHR CNamespaceHandle::ConstructKeyRootDirFromClassHash(LPWSTR wszDir, LPCWSTR wszClassHash) { HRESULT hres; // // Figure out the key root for the class // LPWSTR wszKeyRootClass = NULL; hres = GetKeyRootByHash(wszClassHash, &wszKeyRootClass); if(FAILED(hres)) return hres; if(wszKeyRootClass == NULL) { // Abstract class --- bad error return WBEM_E_INVALID_CLASS; } CTempFreeMe tfm(wszKeyRootClass, (wcslen(wszKeyRootClass)+1)*sizeof(WCHAR)); return ConstructKeyRootDirFromKeyRoot(wszDir, wszKeyRootClass); } CHR CNamespaceHandle::ConstructKeyRootDirFromKeyRoot(LPWSTR wszDir, LPCWSTR wszKeyRootClass) { wcscpy(wszDir, m_wszInstanceRootDir); wszDir[m_lInstanceRootDirLen] = L'\\'; wcscpy(wszDir+m_lInstanceRootDirLen+1, A51_KEYROOTINST_DIR_PREFIX); if(!Hash(wszKeyRootClass, wszDir+m_lInstanceRootDirLen+wcslen(A51_KEYROOTINST_DIR_PREFIX)+1)) { return WBEM_E_OUT_OF_MEMORY; } return S_OK; } CHR CNamespaceHandle::ConstructLinkDirFromClass(LPWSTR wszDir, LPCWSTR wszClassName) { wcscpy(wszDir, m_wszInstanceRootDir); wszDir[m_lInstanceRootDirLen] = L'\\'; wcscpy(wszDir+m_lInstanceRootDirLen+1, A51_CLASSINST_DIR_PREFIX); if(!Hash(wszClassName, wszDir+m_lInstanceRootDirLen+wcslen(A51_CLASSINST_DIR_PREFIX)+1)) { return WBEM_E_OUT_OF_MEMORY; } return S_OK; } CHR CNamespaceHandle::ConstructLinkDirFromClassHash(LPWSTR wszDir, LPCWSTR wszClassHash) { wcscpy(wszDir, m_wszInstanceRootDir); wszDir[m_lInstanceRootDirLen] = L'\\'; wcscpy(wszDir+m_lInstanceRootDirLen+1, A51_CLASSINST_DIR_PREFIX); wcscat(wszDir, wszClassHash); return S_OK; } CHR CNamespaceHandle::WriteInstanceReferences(_IWmiObject* pInst, LPCWSTR wszClassName, LPCWSTR wszFilePath) { HRESULT hres; hres = pInst->BeginEnumeration(WBEM_FLAG_REFS_ONLY); if(FAILED(hres)) return hres; VARIANT v; BSTR strName; while((hres = pInst->Next(0, &strName, &v, NULL, NULL)) == S_OK) { CSysFreeMe sfm(strName); CClearMe cm(&v); if(V_VT(&v) == VT_BSTR) { hres = WriteInstanceReference(wszFilePath, wszClassName, strName, V_BSTR(&v)); if(FAILED(hres)) return hres; } } if(FAILED(hres)) return hres; pInst->EndEnumeration(); return S_OK; } // NOTE: will clobber wszTargetPath CHR CNamespaceHandle::ConstructReferenceDir(LPWSTR wszTargetPath, LPWSTR wszReferenceDir) { // // Deconstruct the target path name so that we could get a directory // for it // DWORD dwKeySpace = (wcslen(wszTargetPath)+1) * sizeof(WCHAR); LPWSTR wszKey = (LPWSTR)TempAlloc(dwKeySpace); if(wszKey == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe tfm2(wszKey, dwKeySpace); LPWSTR wszClassName = NULL; LPWSTR wszTargetNamespace = NULL; bool bIsClass; HRESULT hres = ComputeKeyFromPath(wszTargetPath, wszKey, &wszClassName, &bIsClass, &wszTargetNamespace); if(FAILED(hres)) return hres; CTempFreeMe tfm1(wszClassName); wszTargetPath = NULL; // invalidated by parsing CTempFreeMe tfm3(wszTargetNamespace); // // Check if the target namespace is the same as ours // CNamespaceHandle* pTargetHandle = NULL; if(wszTargetNamespace && wbem_wcsicmp(wszTargetNamespace, m_wsNamespace)) { // // It's different --- open it! // hres = m_pRepository->GetNamespaceHandle(wszTargetNamespace, &pTargetHandle); if(FAILED(hres)) { ERRORTRACE((LOG_WBEMCORE, "Unable to open target namespace " "'%S' in namespace '%S'\n", wszTargetNamespace, (LPCWSTR)m_wsNamespace)); return hres; } } else { pTargetHandle = this; pTargetHandle->AddRef(); } CReleaseMe rm1(pTargetHandle); if(bIsClass) { return pTargetHandle->ConstructReferenceDirFromKey(NULL, wszClassName, wszReferenceDir); } else { return pTargetHandle->ConstructReferenceDirFromKey(wszClassName, wszKey, wszReferenceDir); } } CHR CNamespaceHandle::ConstructReferenceDirFromKey(LPCWSTR wszClassName, LPCWSTR wszKey, LPWSTR wszReferenceDir) { HRESULT hres; // // Construct the class directory for this instance // hres = ConstructKeyRootDirFromClass(wszReferenceDir, wszClassName); if(FAILED(hres)) return hres; int nLen = wcslen(wszReferenceDir); wcscpy(wszReferenceDir+nLen, L"\\" A51_INSTREF_DIR_PREFIX); nLen += 1 + wcslen(A51_INSTREF_DIR_PREFIX); // // Write instance hash // if(!Hash(wszKey, wszReferenceDir+nLen)) return WBEM_E_OUT_OF_MEMORY; return S_OK; } // NOTE: will clobber wszReference CHR CNamespaceHandle::ConstructReferenceFileName(LPWSTR wszReference, LPCWSTR wszReferringFile, LPWSTR wszReferenceFile) { HRESULT hres = ConstructReferenceDir(wszReference, wszReferenceFile); if(FAILED(hres)) return hres; wszReference = NULL; // invalid // // It is basically // irrelevant, we should use a randomly constructed name. Right now, we // use a hash of the class name of the referrer --- THIS IS A BUG, THE SAME // INSTANCE CAN POINT TO THE SAME ENDPOINT TWICE!! // wcscat(wszReferenceFile, L"\\"A51_REF_FILE_PREFIX); DWORD dwLen = wcslen(wszReferenceFile); if (!Hash(wszReferringFile, wszReferenceFile+dwLen)) return WBEM_E_OUT_OF_MEMORY; return S_OK; } // NOTE: will clobber wszReference CHR CNamespaceHandle::WriteInstanceReference(LPCWSTR wszReferringFile, LPCWSTR wszReferringClass, LPCWSTR wszReferringProp, LPWSTR wszReference) { HRESULT hres; // // Figure out the name of the file for the reference. // CFileName wszReferenceFile; if (wszReferenceFile == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructReferenceFileName(wszReference, wszReferringFile, wszReferenceFile); if(FAILED(hres)) { if(hres == WBEM_E_NOT_FOUND) { // // Oh joy. A reference to an instance of a *class* that does not // exist (not a non-existence instance, those are normal). // Forget it (BUGBUG) // return S_OK; } else return hres; } // // Construct the buffer // DWORD dwTotalLen = 4 * sizeof(DWORD) + (wcslen(wszReferringClass) + wcslen(wszReferringProp) + wcslen(wszReferringFile) - g_Glob.GetRootDirLen() + wcslen(m_wsNamespace) + 4) * sizeof(WCHAR); BYTE* pBuffer = (BYTE*)TempAlloc(dwTotalLen); if (pBuffer == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe vdm(pBuffer, dwTotalLen); BYTE* pCurrent = pBuffer; DWORD dwStringLen; // // Write namespace name // dwStringLen = wcslen(m_wsNamespace); memcpy(pCurrent, &dwStringLen, sizeof(DWORD)); pCurrent += sizeof(DWORD); memcpy(pCurrent, m_wsNamespace, sizeof(WCHAR)*dwStringLen); pCurrent += sizeof(WCHAR)*dwStringLen; // // Write the referring class name // dwStringLen = wcslen(wszReferringClass); memcpy(pCurrent, &dwStringLen, sizeof(DWORD)); pCurrent += sizeof(DWORD); memcpy(pCurrent, wszReferringClass, sizeof(WCHAR)*dwStringLen); pCurrent += sizeof(WCHAR)*dwStringLen; // // Write referring property name // dwStringLen = wcslen(wszReferringProp); memcpy(pCurrent, &dwStringLen, sizeof(DWORD)); pCurrent += sizeof(DWORD); memcpy(pCurrent, wszReferringProp, sizeof(WCHAR)*dwStringLen); pCurrent += sizeof(WCHAR)*dwStringLen; // // Write referring file name minus the database root path. Notice that we // cannot skip the namespace-specific prefix lest we break cross-namespace // associations // dwStringLen = wcslen(wszReferringFile) - g_Glob.GetRootDirLen(); memcpy(pCurrent, &dwStringLen, sizeof(DWORD)); pCurrent += sizeof(DWORD); memcpy(pCurrent, wszReferringFile + g_Glob.GetRootDirLen(), sizeof(WCHAR)*dwStringLen); pCurrent += sizeof(WCHAR)*dwStringLen; // // All done --- create the file // long lRes = g_Glob.GetFileCache()->WriteObject(wszReferenceFile, NULL, dwTotalLen, pBuffer); if(lRes != ERROR_SUCCESS) return WBEM_E_FAILED; return S_OK; } CHR CNamespaceHandle::PutClass(_IWmiObject* pClass, DWORD dwFlags, CEventCollector &aEvents) { HRESULT hres; bool bDisableEvents = ((dwFlags & WMIDB_DISABLE_EVENTS)?true:false); // // Get the class name // VARIANT vClass; hres = pClass->Get(L"__CLASS", 0, &vClass, NULL, NULL); if(FAILED(hres) || (V_VT(&vClass) != VT_BSTR) || !V_BSTR(&vClass) || !wcslen(V_BSTR(&vClass))) { return WBEM_E_INVALID_OBJECT; } CClearMe cm1(&vClass); LPCWSTR wszClassName = V_BSTR(&vClass); // // Check to make sure this class was created from a valid parent class // VARIANT vSuperClass; hres = pClass->Get(L"__SUPERCLASS", 0, &vSuperClass, NULL, NULL); if (FAILED(hres)) return WBEM_E_INVALID_OBJECT; CClearMe cm2(&vSuperClass); _IWmiObject* pSuperClass = NULL; if ((V_VT(&vSuperClass) == VT_BSTR) && V_BSTR(&vSuperClass) && wcslen(V_BSTR(&vSuperClass))) { LPCWSTR wszSuperClassName = V_BSTR(&vSuperClass); // do not clone hres = GetClassDirect(wszSuperClassName, IID__IWmiObject, (void**)&pSuperClass, false, NULL, NULL, NULL); if (hres == WBEM_E_NOT_FOUND) return WBEM_E_INVALID_SUPERCLASS; if (FAILED(hres)) return hres; if(wszClassName[0] != L'_') { hres = pClass->IsParentClass(0, pSuperClass); if(FAILED(hres)) return hres; if(hres == WBEM_S_FALSE) return WBEM_E_INVALID_SUPERCLASS; } } CReleaseMe rm(pSuperClass); // // Retrieve the previous definition, if any // _IWmiObject* pOldClass = NULL; __int64 nOldTime = 0; hres = GetClassDirect(wszClassName, IID__IWmiObject, (void**)&pOldClass, false, &nOldTime, NULL, NULL); // do not clone if(FAILED(hres) && hres != WBEM_E_NOT_FOUND) return hres; CReleaseMe rm1(pOldClass); if ((dwFlags & WBEM_FLAG_CREATE_ONLY) && (hres != WBEM_E_NOT_FOUND)) return WBEM_E_ALREADY_EXISTS; if ((dwFlags & WBEM_FLAG_UPDATE_ONLY) && (FAILED(hres))) return WBEM_E_NOT_FOUND; // // If the class exists, we need to check the update scenarios to make sure // we do not break any // bool bNoClassChangeDetected = false; if (pOldClass) { hres = pClass->CompareDerivedMostClass(0, pOldClass); if ((hres != WBEM_S_FALSE) && (hres != WBEM_S_NO_ERROR)) return hres; else if (hres == WBEM_S_NO_ERROR) bNoClassChangeDetected = true; } A51TRACE(("Putting class %S, dwFlags=0x%X. Old was %p, changed=%d\n", wszClassName, dwFlags, pOldClass, !bNoClassChangeDetected)); if (!bNoClassChangeDetected) { if (pOldClass != NULL) { hres = CanClassBeUpdatedCompatible(dwFlags, wszClassName, pOldClass, pClass); if(FAILED(hres)) { if((dwFlags & WBEM_FLAG_UPDATE_SAFE_MODE) == 0 && (dwFlags & WBEM_FLAG_UPDATE_FORCE_MODE) == 0) { // Can't compatibly, not allowed any other way return hres; } if(hres != WBEM_E_CLASS_HAS_CHILDREN && hres != WBEM_E_CLASS_HAS_INSTANCES) { // some serious failure! return hres; } // // This is a safe mode or force mode update which takes more // than a compatible update to carry out the operation // return UpdateClassSafeForce(pSuperClass, dwFlags, wszClassName, pOldClass, pClass, aEvents); } } // // Either there was no previous copy, or it is compatible with the new // one, so we can perform a compatible update // hres = UpdateClassCompatible(pSuperClass, wszClassName, pClass, pOldClass, nOldTime); if (FAILED(hres)) return hres; } if(!bDisableEvents) { if(pOldClass) { hres = FireEvent(aEvents, WBEM_EVENTTYPE_ClassModification, wszClassName, pClass, pOldClass); } else { hres = FireEvent(aEvents, WBEM_EVENTTYPE_ClassCreation, wszClassName, pClass); } } return S_OK; } CHR CNamespaceHandle::UpdateClassCompatible(_IWmiObject* pSuperClass, LPCWSTR wszClassName, _IWmiObject *pClass, _IWmiObject *pOldClass, __int64 nFakeUpdateTime) { HRESULT hres; // // Construct the path for the file // CFileName wszHash; if (wszHash == NULL) return WBEM_E_OUT_OF_MEMORY; if(!A51Hash(wszClassName, wszHash)) return WBEM_E_OUT_OF_MEMORY; A51TRACE(("Class %S has has %S\n", wszClassName, wszHash)); return UpdateClassCompatibleHash(pSuperClass, wszHash, pClass, pOldClass, nFakeUpdateTime); } CHR CNamespaceHandle::UpdateClassCompatibleHash(_IWmiObject* pSuperClass, LPCWSTR wszClassHash, _IWmiObject *pClass, _IWmiObject *pOldClass, __int64 nFakeUpdateTime) { HRESULT hres; CFileName wszFileName; CFileName wszFilePath; if ((wszFileName == NULL) || (wszFilePath == NULL)) return WBEM_E_OUT_OF_MEMORY; wcscpy(wszFileName, A51_CLASSDEF_FILE_PREFIX); wcscat(wszFileName, wszClassHash); wcscpy(wszFilePath, m_wszClassRootDir); wcscat(wszFilePath, L"\\"); wcscat(wszFilePath, wszFileName); // // Write it into the file // hres = ClassToFile(pSuperClass, pClass, wszFilePath, nFakeUpdateTime); if(FAILED(hres)) return hres; // // Add all needed references --- parent, pointers, etc // if (pOldClass) { VARIANT v; VariantInit(&v); hres = pClass->Get(L"__CLASS", 0, &v, NULL, NULL); CClearMe cm(&v); if(SUCCEEDED(hres)) { hres = EraseClassRelationships(V_BSTR(&v), pOldClass, wszFileName); } if (FAILED(hres)) return hres; } hres = WriteClassRelationships(pClass, wszFileName); return hres; } CHR CNamespaceHandle::UpdateClassSafeForce(_IWmiObject* pSuperClass, DWORD dwFlags, LPCWSTR wszClassName, _IWmiObject *pOldClass, _IWmiObject *pNewClass, CEventCollector &aEvents) { HRESULT hres = UpdateClassAggressively(pSuperClass, dwFlags, wszClassName, pNewClass, pOldClass, aEvents); // // If this is a force mode update and we failed for anything other than // out of memory then we should delete the class and try again. // if (FAILED(hres) && (hres != WBEM_E_OUT_OF_MEMORY) && (hres != WBEM_E_CIRCULAR_REFERENCE) && (hres != WBEM_E_UPDATE_TYPE_MISMATCH) && (dwFlags & WBEM_FLAG_UPDATE_FORCE_MODE)) { // // We need to delete the class and try again. // hres = DeleteClass(wszClassName, aEvents); if(FAILED(hres)) return hres; //Write class as though it did not exist hres = UpdateClassCompatible(pSuperClass, wszClassName, pNewClass, NULL); } return hres; } CHR CNamespaceHandle::UpdateClassAggressively(_IWmiObject* pSuperClass, DWORD dwFlags, LPCWSTR wszClassName, _IWmiObject *pNewClass, _IWmiObject *pOldClass, CEventCollector &aEvents) { HRESULT hres = WBEM_S_NO_ERROR; if ((dwFlags & WBEM_FLAG_UPDATE_FORCE_MODE) == 0) { // // If we have instances we need to quit as we cannot update them. // hres = ClassHasInstances(wszClassName); if(FAILED(hres)) return hres; if (hres == WBEM_S_NO_ERROR) return WBEM_E_CLASS_HAS_INSTANCES; _ASSERT(hres == WBEM_S_FALSE, L"Unknown success code!"); } else if (dwFlags & WBEM_FLAG_UPDATE_FORCE_MODE) { // // We need to delete the instances // hres = DeleteClassInstances(wszClassName, pOldClass, aEvents); if(FAILED(hres)) return hres; } // // Retrieve all child classes and update them // CWStringArray wsChildHashes; hres = GetChildHashes(wszClassName, wsChildHashes); if(FAILED(hres)) return hres; for (int i = 0; i != wsChildHashes.Size(); i++) { hres = UpdateChildClassAggressively(dwFlags, wsChildHashes[i], pNewClass, aEvents); if (FAILED(hres)) return hres; } // // Now we need to write the class back, update class refs etc. // hres = UpdateClassCompatible(pSuperClass, wszClassName, pNewClass, pOldClass); if(FAILED(hres)) return hres; // // Generate the class modification event... // if(!(dwFlags & WMIDB_DISABLE_EVENTS)) { hres = FireEvent(aEvents, WBEM_EVENTTYPE_ClassModification, wszClassName, pNewClass, pOldClass); } return S_OK; } CHR CNamespaceHandle::UpdateChildClassAggressively(DWORD dwFlags, LPCWSTR wszClassHash, _IWmiObject *pNewParentClass, CEventCollector &aEvents) { HRESULT hres = WBEM_S_NO_ERROR; dwFlags &= (WBEM_FLAG_UPDATE_FORCE_MODE | WBEM_FLAG_UPDATE_SAFE_MODE); if ((dwFlags & WBEM_FLAG_UPDATE_FORCE_MODE) == 0) { hres = ClassHasInstancesFromClassHash(wszClassHash); if(FAILED(hres)) return hres; if (hres == WBEM_S_NO_ERROR) return WBEM_E_CLASS_HAS_INSTANCES; _ASSERT(hres == WBEM_S_FALSE, L"Unknown success code!"); } // // Get the old class definition // _IWmiObject *pOldClass = NULL; hres = GetClassByHash(wszClassHash, true, &pOldClass, NULL, NULL, NULL); if(FAILED(hres)) return hres; CReleaseMe rm1(pOldClass); if (dwFlags & WBEM_FLAG_UPDATE_FORCE_MODE) { // // Need to delete all its instances, if any // VARIANT v; VariantInit(&v); hres = pOldClass->Get(L"__CLASS", 0, &v, NULL, NULL); if(FAILED(hres)) return hres; CClearMe cm(&v); hres = DeleteClassInstances(V_BSTR(&v), pOldClass, aEvents); if(FAILED(hres)) return hres; } // // Update the existing class definition to work with the new parent class // _IWmiObject *pNewClass = NULL; hres = pNewParentClass->Update(pOldClass, dwFlags, &pNewClass); if(FAILED(hres)) return hres; CReleaseMe rm2(pNewClass); // // Now we have to recurse through all child classes and do the same // CWStringArray wsChildHashes; hres = GetChildHashesByHash(wszClassHash, wsChildHashes); if(FAILED(hres)) return hres; for (int i = 0; i != wsChildHashes.Size(); i++) { hres = UpdateChildClassAggressively(dwFlags, wsChildHashes[i], pNewClass, aEvents); if (FAILED(hres)) return hres; } // // Now we need to write the class back, update class refs etc // hres = UpdateClassCompatibleHash(pNewParentClass, wszClassHash, pNewClass, pOldClass); if(FAILED(hres)) return hres; return S_OK; } CHR CNamespaceHandle::CanClassBeUpdatedCompatible(DWORD dwFlags, LPCWSTR wszClassName, _IWmiObject *pOldClass, _IWmiObject *pNewClass) { HRESULT hres; HRESULT hresError = WBEM_S_NO_ERROR; // // Do we have subclasses? // hres = ClassHasChildren(wszClassName); if(FAILED(hres)) return hres; if(hres == WBEM_S_NO_ERROR) { hresError = WBEM_E_CLASS_HAS_CHILDREN; } else { _ASSERT(hres == WBEM_S_FALSE, L"Unknown success code"); // // Do we have instances belonging to this class? Don't even need to // worry about sub-classes because we know we have none at this point! // hres = ClassHasInstances(wszClassName); if(FAILED(hres)) return hres; if(hres == WBEM_S_NO_ERROR) { hresError = WBEM_E_CLASS_HAS_INSTANCES; } else { _ASSERT(hres == WBEM_S_FALSE, L"Unknown success code"); // // No nothing! // return WBEM_S_NO_ERROR; } } _ASSERT(hresError != WBEM_S_NO_ERROR, L""); // // We have either subclasses or instances. // Can we reconcile this class safely? // hres = pOldClass->ReconcileWith( WMIOBJECT_RECONCILE_FLAG_TESTRECONCILE, pNewClass); if(hres == WBEM_S_NO_ERROR) { // reconcilable, so OK return WBEM_S_NO_ERROR; } else if(hres == WBEM_E_FAILED) // awful, isn't it { // irreconcilable return hresError; } else { return hres; } } CHR CNamespaceHandle::FireEvent(CEventCollector &aEvents, DWORD dwType, LPCWSTR wszArg1, _IWmiObject* pObj1, _IWmiObject* pObj2) { try { CRepEvent *pEvent = new CRepEvent(dwType, m_wsFullNamespace, wszArg1, pObj1, pObj2); if (pEvent == NULL) return WBEM_E_OUT_OF_MEMORY; if (!aEvents.AddEvent(pEvent)) { delete pEvent; return WBEM_E_OUT_OF_MEMORY; } return WBEM_S_NO_ERROR; } catch (CX_MemoryException) { return WBEM_E_OUT_OF_MEMORY; } } HRESULT CNamespaceHandle::SendEvents(CEventCollector &aEvents) { _IWmiCoreServices * pSvcs = g_Glob.GetCoreSvcs(); CReleaseMe rm(pSvcs); aEvents.SendEvents(pSvcs); // // Ignore ESS return codes --- they do not invalidate the operation // return WBEM_S_NO_ERROR; } CHR CNamespaceHandle::WriteClassRelationships(_IWmiObject* pClass, LPCWSTR wszFileName) { HRESULT hres; // // Get the parent // VARIANT v; VariantInit(&v); hres = pClass->Get(L"__SUPERCLASS", 0, &v, NULL, NULL); CClearMe cm(&v); if(FAILED(hres)) return hres; if(V_VT(&v) == VT_BSTR) hres = WriteParentChildRelationship(wszFileName, V_BSTR(&v)); else hres = WriteParentChildRelationship(wszFileName, L""); if(FAILED(hres)) return hres; // // Write references // hres = pClass->BeginEnumeration(WBEM_FLAG_REFS_ONLY); if(FAILED(hres)) return hres; BSTR strName = NULL; while((hres = pClass->Next(0, &strName, NULL, NULL, NULL)) == S_OK) { CSysFreeMe sfm(strName); hres = WriteClassReference(pClass, wszFileName, strName); if(FAILED(hres)) return hres; } pClass->EndEnumeration(); if(FAILED(hres)) return hres; return S_OK; } CHR CNamespaceHandle::WriteClassReference(_IWmiObject* pReferringClass, LPCWSTR wszReferringFile, LPCWSTR wszReferringProp) { HRESULT hres; // // Figure out the class we are pointing to // DWORD dwSize = 0; DWORD dwFlavor = 0; CIMTYPE ct; hres = pReferringClass->GetPropQual(wszReferringProp, L"CIMTYPE", 0, 0, &ct, &dwFlavor, &dwSize, NULL); if(dwSize == 0) return WBEM_E_OUT_OF_MEMORY; LPWSTR wszQual = (WCHAR*)TempAlloc(dwSize); if(wszQual == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe tfm(wszQual, dwSize); hres = pReferringClass->GetPropQual(wszReferringProp, L"CIMTYPE", 0, dwSize, &ct, &dwFlavor, &dwSize, wszQual); if(FAILED(hres)) return hres; // // Parse out the class name // WCHAR* pwcColon = wcschr(wszQual, L':'); if(pwcColon == NULL) return S_OK; // untyped reference requires no bookkeeping LPCWSTR wszReferredToClass = pwcColon+1; // // Figure out the name of the file for the reference. // CFileName wszReferenceFile; if (wszReferenceFile == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructClassReferenceFileName(wszReferredToClass, wszReferringFile, wszReferringProp, wszReferenceFile); if(FAILED(hres)) return hres; // // Create the empty file // long lRes = g_Glob.GetFileCache()->WriteLink(wszReferenceFile); if(lRes != ERROR_SUCCESS) return WBEM_E_FAILED; return S_OK; } CHR CNamespaceHandle::WriteParentChildRelationship( LPCWSTR wszChildFileName, LPCWSTR wszParentName) { CFileName wszParentChildFileName; if (wszParentChildFileName == NULL) return WBEM_E_OUT_OF_MEMORY; HRESULT hres = ConstructParentChildFileName(wszChildFileName, wszParentName, wszParentChildFileName); // // Create the file // long lRes = g_Glob.GetFileCache()->WriteLink(wszParentChildFileName); if(lRes != ERROR_SUCCESS) return WBEM_E_FAILED; return S_OK; } CHR CNamespaceHandle::ConstructParentChildFileName( LPCWSTR wszChildFileName, LPCWSTR wszParentName, LPWSTR wszParentChildFileName) { // // Construct the name of the directory where the parent class keeps its // children // HRESULT hres = ConstructClassRelationshipsDir(wszParentName, wszParentChildFileName); if(FAILED(hres)) return hres; // // Append the filename of the child, but substituting the child-class prefix // for the class-def prefix // wcscat(wszParentChildFileName, L"\\" A51_CHILDCLASS_FILE_PREFIX); wcscat(wszParentChildFileName, wszChildFileName + wcslen(A51_CLASSDEF_FILE_PREFIX)); return S_OK; } CHR CNamespaceHandle::ConstructClassRelationshipsDir(LPCWSTR wszClassName, LPWSTR wszDirPath) { wcscpy(wszDirPath, m_wszClassRootDir); wcscpy(wszDirPath + m_lClassRootDirLen, L"\\" A51_CLASSRELATION_DIR_PREFIX); if(!Hash(wszClassName, wszDirPath + m_lClassRootDirLen + 1 + wcslen(A51_CLASSRELATION_DIR_PREFIX))) { return WBEM_E_OUT_OF_MEMORY; } return S_OK; } CHR CNamespaceHandle::ConstructClassRelationshipsDirFromHash( LPCWSTR wszHash, LPWSTR wszDirPath) { wcscpy(wszDirPath, m_wszClassRootDir); wcscpy(wszDirPath + m_lClassRootDirLen, L"\\" A51_CLASSRELATION_DIR_PREFIX); wcscpy(wszDirPath + m_lClassRootDirLen + 1 +wcslen(A51_CLASSRELATION_DIR_PREFIX), wszHash); return S_OK; } CHR CNamespaceHandle::ConstructClassReferenceFileName( LPCWSTR wszReferredToClass, LPCWSTR wszReferringFile, LPCWSTR wszReferringProp, LPWSTR wszFileName) { HRESULT hres; hres = ConstructClassRelationshipsDir(wszReferredToClass, wszFileName); if(FAILED(hres)) return hres; // // Extract the portion of the referring file containing the class hash // WCHAR* pwcLastUnderscore = wcsrchr(wszReferringFile, L'_'); if(pwcLastUnderscore == NULL) return WBEM_E_CRITICAL_ERROR; LPCWSTR wszReferringClassHash = pwcLastUnderscore+1; wcscat(wszFileName, L"\\" A51_REF_FILE_PREFIX); wcscat(wszFileName, wszReferringClassHash); return S_OK; } CHR CNamespaceHandle::DeleteObject( DWORD dwFlags, REFIID riid, LPVOID pObj, CEventCollector &aEvents ) { DebugBreak(); return E_NOTIMPL; } CHR CNamespaceHandle::DeleteObjectByPath(DWORD dwFlags, LPWSTR wszPath, CEventCollector &aEvents) { HRESULT hres; // // Get the key from path // DWORD dwLen = wcslen(wszPath)*sizeof(WCHAR)+2; LPWSTR wszKey = (WCHAR*)TempAlloc(dwLen); if(wszKey == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe tfm(wszKey, dwLen); bool bIsClass; LPWSTR wszClassName = NULL; hres = ComputeKeyFromPath(wszPath, wszKey, &wszClassName, &bIsClass); if(FAILED(hres)) return hres; CTempFreeMe tfm1(wszClassName, (wcslen(wszClassName)+1) * sizeof(WCHAR*)); if(bIsClass) { return DeleteClass(wszClassName, aEvents); } else { return DeleteInstance(wszClassName, wszKey, aEvents); } } CHR CNamespaceHandle::DeleteInstance(LPCWSTR wszClassName, LPCWSTR wszKey, CEventCollector &aEvents) { HRESULT hres; // // Get Class definition // _IWmiObject* pClass = NULL; hres = GetClassDirect(wszClassName, IID__IWmiObject, (void**)&pClass, false, NULL, NULL, NULL); if(FAILED(hres)) return hres; CReleaseMe rm1(pClass); // // Create its directory // CFileName wszFilePath; if (wszFilePath == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructKeyRootDirFromClass(wszFilePath, wszClassName); if(FAILED(hres)) return hres; // // Construct the path for the file // CFileName wszFileName; if (wszFileName == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructInstanceDefName(wszFileName, wszKey); if(FAILED(hres)) return hres; wcscat(wszFilePath, L"\\"); wcscat(wszFilePath, wszFileName); _IWmiObject* pInst; hres = FileToInstance(NULL, wszFilePath, NULL, 0, &pInst); if(FAILED(hres)) return hres; CReleaseMe rm2(pInst); if(pInst->InheritsFrom(L"__Namespace") == S_OK) { //Make sure this is not a deletion of the root\default namespace VARIANT vName; VariantInit(&vName); CClearMe cm1(&vName); hres = pInst->Get(L"Name", 0, &vName, NULL, NULL); if(FAILED(hres)) return WBEM_E_INVALID_OBJECT; LPCWSTR wszName = V_BSTR(&vName); if ((_wcsicmp(m_wsFullNamespace, L"\\\\.\\root") == 0) && (_wcsicmp(wszName, L"default") == 0)) return WBEM_E_ACCESS_DENIED; } hres = DeleteInstanceByFile(wszFilePath, pInst, false, aEvents); if(FAILED(hres)) return hres; // // Fire an event // if(pInst->InheritsFrom(L"__Namespace") == S_OK) { // // There is no need to do anything --- deletion of namespaces // automatically fires events in DeleteInstanceByFile (because we need // to accomplish it in the case of deleting a class derived from // __NAMESPACE. // } else { hres = FireEvent(aEvents, WBEM_EVENTTYPE_InstanceDeletion, wszClassName, pInst); } A51TRACE(("DeleteInstance for class %S succeeded\n", wszClassName)); return S_OK; } CHR CNamespaceHandle::DeleteInstanceByFile(LPCWSTR wszFilePath, _IWmiObject* pInst, bool bClassDeletion, CEventCollector &aEvents) { HRESULT hres; hres = DeleteInstanceSelf(wszFilePath, pInst, bClassDeletion); if(FAILED(hres)) return hres; hres = DeleteInstanceAsScope(pInst, aEvents); if(FAILED(hres) && hres != WBEM_E_NOT_FOUND) { return hres; } return S_OK; } CHR CNamespaceHandle::DeleteInstanceSelf(LPCWSTR wszFilePath, _IWmiObject* pInst, bool bClassDeletion) { HRESULT hres; // // Delete the file // long lRes = g_Glob.GetFileCache()->DeleteObject(wszFilePath); if(lRes == ERROR_FILE_NOT_FOUND || lRes == ERROR_PATH_NOT_FOUND) { return WBEM_E_NOT_FOUND; } else if(lRes != ERROR_SUCCESS) return WBEM_E_FAILED; hres = DeleteInstanceLink(pInst, wszFilePath); if(FAILED(hres) && hres != WBEM_E_NOT_FOUND) return hres; hres = DeleteInstanceReferences(pInst, wszFilePath); if(FAILED(hres) && hres != WBEM_E_NOT_FOUND) return hres; if(bClassDeletion) { // // We need to remove all dangling references to this instance, // because they make no sense once the class is deleted --- we don't // know what key structure the new class will even have. In the future, // we'll want to move these references to some class-wide location // hres = DeleteInstanceBackReferences(wszFilePath); if(FAILED(hres) && hres != WBEM_E_NOT_FOUND) return hres; } return S_OK; } CHR CNamespaceHandle::ConstructReferenceDirFromFilePath( LPCWSTR wszFilePath, LPWSTR wszReferenceDir) { // // It's the same, only with INSTDEF_FILE_PREFIX replaced with // INSTREF_DIR_PREFIX // CFileName wszEnding; if (wszEnding == NULL) return WBEM_E_OUT_OF_MEMORY; WCHAR* pwcLastSlash = wcsrchr(wszFilePath, L'\\'); if(pwcLastSlash == NULL) return WBEM_E_FAILED; wcscpy(wszEnding, pwcLastSlash + 1 + wcslen(A51_INSTDEF_FILE_PREFIX)); wcscpy(wszReferenceDir, wszFilePath); wszReferenceDir[(pwcLastSlash+1)-wszFilePath] = 0; wcscat(wszReferenceDir, A51_INSTREF_DIR_PREFIX); wcscat(wszReferenceDir, wszEnding); return S_OK; } CHR CNamespaceHandle::DeleteInstanceBackReferences(LPCWSTR wszFilePath) { HRESULT hres; CFileName wszReferenceDir; if (wszReferenceDir == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructReferenceDirFromFilePath(wszFilePath, wszReferenceDir); if(FAILED(hres)) return hres; wcscat(wszReferenceDir, L"\\"); CFileName wszReferencePrefix; if (wszReferencePrefix == NULL) return WBEM_E_OUT_OF_MEMORY; wcscpy(wszReferencePrefix, wszReferenceDir); wcscat(wszReferencePrefix, A51_REF_FILE_PREFIX); // Prepare a buffer for file path CFileName wszFullFileName; if (wszFullFileName == NULL) return WBEM_E_OUT_OF_MEMORY; wcscpy(wszFullFileName, wszReferenceDir); long lDirLen = wcslen(wszFullFileName); CFileName wszFileName; if (wszFileName == NULL) return WBEM_E_OUT_OF_MEMORY; // Enumerate all files in it void* hSearch; long lRes = g_Glob.GetFileCache()->IndexEnumerationBegin(wszReferencePrefix, &hSearch); if (lRes == ERROR_FILE_NOT_FOUND) return ERROR_SUCCESS; else if (lRes != ERROR_SUCCESS) return A51TranslateErrorCode(lRes); while ((lRes = g_Glob.GetFileCache()->IndexEnumerationNext(hSearch, wszFileName)) == ERROR_SUCCESS) { wcscpy(wszFullFileName+lDirLen, wszFileName); lRes = g_Glob.GetFileCache()->DeleteObject(wszFullFileName); if(lRes != ERROR_SUCCESS) { ERRORTRACE((LOG_WBEMCORE, "Cannot delete reference file '%S' with " "error code %d\n", wszFullFileName, lRes)); lRes = ERROR_INVALID_OPERATION; //trigger the correct error! } } g_Glob.GetFileCache()->IndexEnumerationEnd(hSearch); if(lRes == ERROR_NO_MORE_FILES) { return WBEM_S_NO_ERROR; } else if(lRes != ERROR_SUCCESS) { return WBEM_E_FAILED; } return S_OK; } CHR CNamespaceHandle::DeleteInstanceLink(_IWmiObject* pInst, LPCWSTR wszInstanceDefFilePath) { HRESULT hres; // // Get the class name // VARIANT vClass; VariantInit(&vClass); CClearMe cm1(&vClass); hres = pInst->Get(L"__CLASS", 0, &vClass, NULL, NULL); if(FAILED(hres)) return WBEM_E_INVALID_OBJECT; LPCWSTR wszClassName = V_BSTR(&vClass); // // Construct the link directory for the class // CFileName wszInstanceLinkPath; if (wszInstanceLinkPath == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructLinkDirFromClass(wszInstanceLinkPath, wszClassName); if(FAILED(hres)) return hres; wcscat(wszInstanceLinkPath, L"\\" A51_INSTLINK_FILE_PREFIX); // // It remains to append the instance-specific part of the file name. // Convineintly, it is the same material as was used for the def file path, // so we can steal it. ALERT: RELIES ON ALL PREFIXES ENDING IN '_'!! // WCHAR* pwcLastUnderscore = wcsrchr(wszInstanceDefFilePath, L'_'); if(pwcLastUnderscore == NULL) return WBEM_E_CRITICAL_ERROR; wcscat(wszInstanceLinkPath, pwcLastUnderscore+1); // // Delete the file // long lRes = g_Glob.GetFileCache()->DeleteLink(wszInstanceLinkPath); if(lRes == ERROR_FILE_NOT_FOUND || lRes == ERROR_PATH_NOT_FOUND) return WBEM_E_NOT_FOUND; else if(lRes != ERROR_SUCCESS) return WBEM_E_FAILED; return S_OK; } CHR CNamespaceHandle::DeleteInstanceAsScope(_IWmiObject* pInst, CEventCollector &aEvents) { HRESULT hres; // // For now, just check if it is a namespace // hres = pInst->InheritsFrom(L"__Namespace"); if(FAILED(hres)) return hres; if(hres != S_OK) // not a namespace return S_FALSE; // // It is a namespace --- construct full path // WString wsFullName = m_wsNamespace; wsFullName += L"\\"; VARIANT vName; VariantInit(&vName); CClearMe cm(&vName); hres = pInst->Get(L"Name", 0, &vName, NULL, NULL); if(FAILED(hres)) return hres; if(V_VT(&vName) != VT_BSTR) return WBEM_E_INVALID_OBJECT; wsFullName += V_BSTR(&vName); // // Delete it // CNamespaceHandle* pNewHandle = new CNamespaceHandle(m_pControl, m_pRepository); if(pNewHandle == NULL) return WBEM_E_OUT_OF_MEMORY; pNewHandle->AddRef(); CReleaseMe rm1(pNewHandle); hres = pNewHandle->Initialize(wsFullName); if(FAILED(hres)) return hres; // // Mind to only fire child namespace deletion events from the inside // bool bNamespaceOnly = aEvents.IsNamespaceOnly(); aEvents.SetNamespaceOnly(true); hres = pNewHandle->DeleteSelf(aEvents); if(FAILED(hres)) return hres; aEvents.SetNamespaceOnly(bNamespaceOnly); // // Fire the event // hres = FireEvent(aEvents, WBEM_EVENTTYPE_NamespaceDeletion, V_BSTR(&vName), pInst); return S_OK; } CHR CNamespaceHandle::DeleteSelf(CEventCollector &aEvents) { // // Delete all top-level classes. This will delete all namespaces // (as instances of __Namespace), all classes (as children of top-levels) // and all instances // HRESULT hres = DeleteDerivedClasses(L"", aEvents); if(FAILED(hres)) return hres; // // We do not delete our class root directory --- if we are a namespace, it // is the same as our instance root directory so we are already done; if not // we should not be cleaning up all the classes! // m_pClassCache->SetError(WBEM_E_INVALID_NAMESPACE); return S_OK; } CHR CNamespaceHandle::DeleteInstanceReferences(_IWmiObject* pInst, LPCWSTR wszFilePath) { HRESULT hres; hres = pInst->BeginEnumeration(WBEM_FLAG_REFS_ONLY); if(FAILED(hres)) return hres; VARIANT v; while((hres = pInst->Next(0, NULL, &v, NULL, NULL)) == S_OK) { CClearMe cm(&v); if(V_VT(&v) == VT_BSTR) { hres = DeleteInstanceReference(wszFilePath, V_BSTR(&v)); if(FAILED(hres)) return hres; } } if(FAILED(hres)) return hres; pInst->EndEnumeration(); return S_OK; } // NOTE: will clobber wszReference CHR CNamespaceHandle::DeleteInstanceReference(LPCWSTR wszOurFilePath, LPWSTR wszReference) { HRESULT hres; CFileName wszReferenceFile; if (wszReferenceFile == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructReferenceFileName(wszReference, wszOurFilePath, wszReferenceFile); if(FAILED(hres)) { if(hres == WBEM_E_NOT_FOUND) { // // Oh joy. A reference to an instance of a *class* that does not // exist (not a non-existence instance, those are normal). // Forget it (BUGBUG) // return S_OK; } else return hres; } long lRes = g_Glob.GetFileCache()->DeleteObject(wszReferenceFile); if(lRes != ERROR_SUCCESS) { if(lRes == ERROR_FILE_NOT_FOUND) return WBEM_E_NOT_FOUND; else return WBEM_E_FAILED; } else return WBEM_S_NO_ERROR; } CHR CNamespaceHandle::DeleteClassByHash(LPCWSTR wszHash, CEventCollector &aEvents) { HRESULT hres; // // Get Class definition // _IWmiObject* pClass = NULL; bool bSystemClass = false; hres = GetClassByHash(wszHash, false, &pClass, NULL, NULL, &bSystemClass); CReleaseMe rm1(pClass); if(FAILED(hres)) return hres; // // Get the actual class name // VARIANT v; hres = pClass->Get(L"__CLASS", 0, &v, NULL, NULL); if(FAILED(hres)) return hres; CClearMe cm1(&v); if(V_VT(&v) != VT_BSTR) return WBEM_E_INVALID_CLASS; // // Construct definition file name // CFileName wszFileName; if (wszFileName == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructClassDefFileNameFromHash(wszHash, wszFileName); if(FAILED(hres)) return hres; return DeleteClassInternal(V_BSTR(&v), pClass, wszFileName, aEvents, bSystemClass); } CHR CNamespaceHandle::DeleteClass(LPCWSTR wszClassName, CEventCollector &aEvents) { HRESULT hres; A51TRACE(("Deleting class %S\n", wszClassName)); // // Construct the path for the file // CFileName wszFileName; if (wszFileName == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructClassDefFileName(wszClassName, wszFileName); if(FAILED(hres)) return hres; // // Get Class definition // _IWmiObject* pClass = NULL; bool bSystemClass = false; hres = GetClassDirect(wszClassName, IID__IWmiObject, (void**)&pClass, false, NULL, NULL, &bSystemClass); if(FAILED(hres)) return hres; CReleaseMe rm1(pClass); return DeleteClassInternal(wszClassName, pClass, wszFileName, aEvents, bSystemClass); } CHR CNamespaceHandle::DeleteClassInternal(LPCWSTR wszClassName, _IWmiObject* pClass, LPCWSTR wszFileName, CEventCollector &aEvents, bool bSystemClass) { HRESULT hres; CFileName wszFilePath; if (wszFilePath == NULL) return WBEM_E_OUT_OF_MEMORY; swprintf(wszFilePath, L"%s\\%s", m_wszClassRootDir, wszFileName); // // Delete all derived classes // hres = DeleteDerivedClasses(wszClassName, aEvents); if(FAILED(hres)) return hres; // // Delete all instances. Only fire events if namespaces are deleted // bool bNamespaceOnly = aEvents.IsNamespaceOnly(); aEvents.SetNamespaceOnly(true); hres = DeleteClassInstances(wszClassName, pClass, aEvents); if(FAILED(hres)) return hres; aEvents.SetNamespaceOnly(bNamespaceOnly); if (!bSystemClass) { // // Clean up references // hres = EraseClassRelationships(wszClassName, pClass, wszFileName); if(FAILED(hres)) return hres; // // Delete the file // long lRes = g_Glob.GetFileCache()->DeleteObject(wszFilePath); if(lRes == ERROR_FILE_NOT_FOUND || lRes == ERROR_PATH_NOT_FOUND) return WBEM_E_NOT_FOUND; else if(lRes != ERROR_SUCCESS) return WBEM_E_FAILED; } m_pClassCache->InvalidateClass(wszClassName); // // Fire an event // hres = FireEvent(aEvents, WBEM_EVENTTYPE_ClassDeletion, wszClassName, pClass); return S_OK; } CHR CNamespaceHandle::DeleteDerivedClasses(LPCWSTR wszClassName, CEventCollector &aEvents) { HRESULT hres; CWStringArray wsChildHashes; hres = GetChildHashes(wszClassName, wsChildHashes); if(FAILED(hres)) return hres; for(int i = 0; i < wsChildHashes.Size(); i++) { hres = DeleteClassByHash(wsChildHashes[i], aEvents); if(FAILED(hres) && (hres != WBEM_E_NOT_FOUND)) { return hres; } } return S_OK; } CHR CNamespaceHandle::GetChildDefs(LPCWSTR wszClassName, bool bRecursive, IWbemObjectSink* pSink, bool bClone) { CFileName wszHash; if (wszHash == NULL) return WBEM_E_OUT_OF_MEMORY; if(!A51Hash(wszClassName, wszHash)) return WBEM_E_OUT_OF_MEMORY; return GetChildDefsByHash(wszHash, bRecursive, pSink, bClone); } CHR CNamespaceHandle::GetChildDefsByHash(LPCWSTR wszHash, bool bRecursive, IWbemObjectSink* pSink, bool bClone) { HRESULT hres; long lStartIndex = m_pClassCache->GetLastInvalidationIndex(); // // Get the hashes of the child filenames // CWStringArray wsChildHashes; hres = GetChildHashesByHash(wszHash, wsChildHashes); if(FAILED(hres)) return hres; // // Get their class definitions // for(int i = 0; i < wsChildHashes.Size(); i++) { LPCWSTR wszChildHash = wsChildHashes[i]; _IWmiObject* pClass = NULL; hres = GetClassByHash(wszChildHash, bClone, &pClass, NULL, NULL, NULL); if(FAILED(hres)) return hres; CReleaseMe rm1(pClass); hres = pSink->Indicate(1, (IWbemClassObject**)&pClass); if(FAILED(hres)) return hres; // // Continue recursively if indicated // if(bRecursive) { hres = GetChildDefsByHash(wszChildHash, bRecursive, pSink, bClone); if(FAILED(hres)) return hres; } } // // Mark cache completeness // m_pClassCache->DoneWithChildrenByHash(wszHash, bRecursive, lStartIndex); return S_OK; } CHR CNamespaceHandle::GetChildHashes(LPCWSTR wszClassName, CWStringArray& wsChildHashes) { CFileName wszHash; if (wszHash == NULL) return WBEM_E_OUT_OF_MEMORY; if(!A51Hash(wszClassName, wszHash)) return WBEM_E_OUT_OF_MEMORY; return GetChildHashesByHash(wszHash, wsChildHashes); } CHR CNamespaceHandle::GetChildHashesByHash(LPCWSTR wszHash, CWStringArray& wsChildHashes) { HRESULT hres; long lRes; //Try retrieving the system classes namespace first... if (g_pSystemClassNamespace && (wcscmp(m_wsNamespace, A51_SYSTEMCLASS_NS) != 0)) { hres = g_pSystemClassNamespace->GetChildHashesByHash(wszHash, wsChildHashes); if (FAILED(hres)) return hres; } // // Construct the prefix for the children classes // CFileName wszChildPrefix; if (wszChildPrefix == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructClassRelationshipsDirFromHash(wszHash, wszChildPrefix); if(FAILED(hres)) return hres; wcscat(wszChildPrefix, L"\\" A51_CHILDCLASS_FILE_PREFIX); // // Enumerate all such files in the cache // void* pHandle = NULL; CFileName wszFileName; if (wszFileName == NULL) return WBEM_E_OUT_OF_MEMORY; lRes = g_Glob.GetFileCache()->IndexEnumerationBegin(wszChildPrefix, &pHandle); if (lRes == ERROR_FILE_NOT_FOUND) return ERROR_SUCCESS; else if (lRes != ERROR_SUCCESS) return A51TranslateErrorCode(lRes); while((lRes = g_Glob.GetFileCache()->IndexEnumerationNext(pHandle, wszFileName)) == ERROR_SUCCESS) { wsChildHashes.Add(wszFileName + wcslen(A51_CHILDCLASS_FILE_PREFIX)); } g_Glob.GetFileCache()->IndexEnumerationEnd(pHandle); if(lRes != ERROR_NO_MORE_FILES && lRes != S_OK) return WBEM_E_FAILED; else return S_OK; } CHR CNamespaceHandle::ClassHasChildren(LPCWSTR wszClassName) { CFileName wszHash; if (wszHash == NULL) return WBEM_E_OUT_OF_MEMORY; if(!A51Hash(wszClassName, wszHash)) return WBEM_E_OUT_OF_MEMORY; HRESULT hres; long lRes; //Try retrieving the system classes namespace first... if (g_pSystemClassNamespace && (wcscmp(m_wsNamespace, A51_SYSTEMCLASS_NS) != 0)) { hres = g_pSystemClassNamespace->ClassHasChildren(wszClassName); if (FAILED(hres) || (hres == WBEM_S_NO_ERROR)) return hres; } // // Construct the prefix for the children classes // CFileName wszChildPrefix; if (wszChildPrefix == NULL) return WBEM_E_OUT_OF_MEMORY; CFileName wszFileName; if (wszFileName == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructClassRelationshipsDirFromHash(wszHash, wszChildPrefix); if(FAILED(hres)) return hres; wcscat(wszChildPrefix, L"\\" A51_CHILDCLASS_FILE_PREFIX); void* pHandle = NULL; lRes = g_Glob.GetFileCache()->IndexEnumerationBegin(wszChildPrefix, &pHandle); if (lRes == ERROR_FILE_NOT_FOUND) return WBEM_S_FALSE; if (lRes != ERROR_SUCCESS) return A51TranslateErrorCode(lRes); g_Glob.GetFileCache()->IndexEnumerationEnd(pHandle); return WBEM_S_NO_ERROR; } CHR CNamespaceHandle::ClassHasInstances(LPCWSTR wszClassName) { CFileName wszHash; if (wszHash == NULL) return WBEM_E_OUT_OF_MEMORY; if(!A51Hash(wszClassName, wszHash)) return WBEM_E_OUT_OF_MEMORY; return ClassHasInstancesFromClassHash(wszHash); } CHR CNamespaceHandle::ClassHasInstancesFromClassHash(LPCWSTR wszClassHash) { HRESULT hres; long lRes; // // Check the instances in this namespace first. The instance directory in // default scope is the class directory of the namespace // hres = ClassHasInstancesInScopeFromClassHash(m_wszClassRootDir, wszClassHash); if(hres != WBEM_S_FALSE) return hres; return WBEM_S_FALSE; } CHR CNamespaceHandle::ClassHasInstancesInScopeFromClassHash( LPCWSTR wszInstanceRootDir, LPCWSTR wszClassHash) { CFileName wszFullDirName; if (wszFullDirName == NULL) return WBEM_E_OUT_OF_MEMORY; wcscpy(wszFullDirName, wszInstanceRootDir); wcscat(wszFullDirName, L"\\" A51_CLASSINST_DIR_PREFIX); wcscat(wszFullDirName, wszClassHash); wcscat(wszFullDirName, L"\\" A51_INSTLINK_FILE_PREFIX); void* pHandle = NULL; LONG lRes; lRes = g_Glob.GetFileCache()->IndexEnumerationBegin(wszFullDirName, &pHandle); if (lRes == ERROR_FILE_NOT_FOUND) return WBEM_S_FALSE; if (lRes != ERROR_SUCCESS) { return WBEM_E_FAILED; } if(pHandle) g_Glob.GetFileCache()->IndexEnumerationEnd(pHandle); return WBEM_S_NO_ERROR; } CHR CNamespaceHandle::EraseParentChildRelationship( LPCWSTR wszChildFileName, LPCWSTR wszParentName) { CFileName wszParentChildFileName; if (wszParentChildFileName == NULL) return WBEM_E_OUT_OF_MEMORY; HRESULT hres = ConstructParentChildFileName(wszChildFileName, wszParentName, wszParentChildFileName); // // Delete the file // long lRes = g_Glob.GetFileCache()->DeleteLink(wszParentChildFileName); if(lRes != ERROR_SUCCESS) return WBEM_E_FAILED; return S_OK; } CHR CNamespaceHandle::EraseClassRelationships(LPCWSTR wszClassName, _IWmiObject* pClass, LPCWSTR wszFileName) { HRESULT hres; // // Get the parent // VARIANT v; VariantInit(&v); hres = pClass->Get(L"__SUPERCLASS", 0, &v, NULL, NULL); CClearMe cm(&v); if(FAILED(hres)) return hres; if(V_VT(&v) == VT_BSTR) hres = EraseParentChildRelationship(wszFileName, V_BSTR(&v)); else hres = EraseParentChildRelationship(wszFileName, L""); if(FAILED(hres)) return hres; // // Erase references // hres = pClass->BeginEnumeration(WBEM_FLAG_REFS_ONLY); if(FAILED(hres)) return hres; BSTR strName = NULL; while((hres = pClass->Next(0, &strName, NULL, NULL, NULL)) == S_OK) { CSysFreeMe sfm(strName); hres = EraseClassReference(pClass, wszFileName, strName); if(FAILED(hres) && (hres != WBEM_E_NOT_FOUND)) return hres; } pClass->EndEnumeration(); return S_OK; } CHR CNamespaceHandle::EraseClassReference(_IWmiObject* pReferringClass, LPCWSTR wszReferringFile, LPCWSTR wszReferringProp) { HRESULT hres; // // Figure out the class we are pointing to // DWORD dwSize = 0; DWORD dwFlavor = 0; CIMTYPE ct; hres = pReferringClass->GetPropQual(wszReferringProp, L"CIMTYPE", 0, 0, &ct, &dwFlavor, &dwSize, NULL); if(dwSize == 0) return WBEM_E_OUT_OF_MEMORY; LPWSTR wszQual = (WCHAR*)TempAlloc(dwSize); if(wszQual == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe tfm(wszQual, dwSize); hres = pReferringClass->GetPropQual(wszReferringProp, L"CIMTYPE", 0, dwSize, &ct, &dwFlavor, &dwSize, wszQual); if(FAILED(hres)) return hres; // // Parse out the class name // WCHAR* pwcColon = wcschr(wszQual, L':'); if(pwcColon == NULL) return S_OK; // untyped reference requires no bookkeeping LPCWSTR wszReferredToClass = pwcColon+1; // // Figure out the name of the file for the reference. // CFileName wszReferenceFile; if (wszReferenceFile == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructClassReferenceFileName(wszReferredToClass, wszReferringFile, wszReferringProp, wszReferenceFile); if(FAILED(hres)) return hres; // // Delete the file // long lRes = g_Glob.GetFileCache()->DeleteLink(wszReferenceFile); if (lRes == ERROR_FILE_NOT_FOUND) return WBEM_E_NOT_FOUND; else if(lRes != ERROR_SUCCESS) return WBEM_E_FAILED; return S_OK; } CHR CNamespaceHandle::DeleteClassInstances(LPCWSTR wszClassName, _IWmiObject* pClass, CEventCollector &aEvents) { HRESULT hres; // // Find the link directory for this class // CFileName wszLinkDir; if (wszLinkDir == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructLinkDirFromClass(wszLinkDir, wszClassName); if(FAILED(hres)) return hres; // // Enumerate all links in it // CFileName wszSearchPrefix; if (wszSearchPrefix == NULL) return WBEM_E_OUT_OF_MEMORY; wcscpy(wszSearchPrefix, wszLinkDir); wcscat(wszSearchPrefix, L"\\" A51_INSTLINK_FILE_PREFIX); // // Prepare a buffer for instance definition file path // CFileName wszFullFileName; if (wszFullFileName == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructKeyRootDirFromClass(wszFullFileName, wszClassName); if(FAILED(hres)) { if(hres == WBEM_E_CANNOT_BE_ABSTRACT) return WBEM_S_NO_ERROR; return hres; } long lDirLen = wcslen(wszFullFileName); wszFullFileName[lDirLen] = L'\\'; lDirLen++; CFileName wszFileName; if (wszFullFileName == NULL) return WBEM_E_OUT_OF_MEMORY; void* hSearch; long lRes = g_Glob.GetFileCache()->IndexEnumerationBegin(wszSearchPrefix, &hSearch); if (lRes == ERROR_FILE_NOT_FOUND) return ERROR_SUCCESS; if (lRes != ERROR_SUCCESS) return A51TranslateErrorCode(lRes); while((lRes = g_Glob.GetFileCache()->IndexEnumerationNext(hSearch, wszFileName)) == ERROR_SUCCESS) { hres = ConstructInstDefNameFromLinkName(wszFullFileName+lDirLen, wszFileName); if(FAILED(hres)) break; _IWmiObject* pInst; hres = FileToInstance(NULL, wszFullFileName, NULL, 0, &pInst); if(FAILED(hres)) break; CReleaseMe rm1(pInst); // // Delete the instance, knowing that we are deleting its class. That // has an affect on how we deal with the references // hres = DeleteInstanceByFile(wszFullFileName, pInst, true, aEvents); if(FAILED(hres)) break; } g_Glob.GetFileCache()->IndexEnumerationEnd(hSearch); if (hres != ERROR_SUCCESS) return hres; if(lRes != ERROR_NO_MORE_FILES && lRes != S_OK) { return WBEM_E_FAILED; } return S_OK; } class CExecQueryObject : public CFiberTask { protected: IWbemQuery* m_pQuery; CDbIterator* m_pIter; CNamespaceHandle* m_pNs; DWORD m_lFlags; public: CExecQueryObject(CNamespaceHandle* pNs, IWbemQuery* pQuery, CDbIterator* pIter, DWORD lFlags) : m_pQuery(pQuery), m_pIter(pIter), m_pNs(pNs), m_lFlags(lFlags) { m_pQuery->AddRef(); m_pNs->AddRef(); // // Does not AddRef the iterator --- iterator owns and cleans up the req // } ~CExecQueryObject() { if(m_pQuery) m_pQuery->Release(); if(m_pNs) m_pNs->Release(); } HRESULT Execute() { HRESULT hres = m_pNs->ExecQuerySink(m_pQuery, m_lFlags, 0, m_pIter, NULL); m_pIter->SetStatus(WBEM_STATUS_COMPLETE, hres, NULL, NULL); return hres; } }; CHR CNamespaceHandle::ExecQuery( IWbemQuery *pQuery, DWORD dwFlags, DWORD dwRequestedHandleType, DWORD *dwMessageFlags, IWmiDbIterator **ppQueryResult ) { CDbIterator* pIter = new CDbIterator(m_pControl, m_bUseIteratorLock); m_bUseIteratorLock = true; if (pIter == NULL) return WBEM_E_OUT_OF_MEMORY; pIter->AddRef(); CReleaseMe rm1((IWmiDbIterator*)pIter); // // Create a fiber execution object // CExecQueryObject* pReq = new CExecQueryObject(this, pQuery, pIter, dwFlags); if(pReq == NULL) return WBEM_E_OUT_OF_MEMORY; // // Create a fiber for it // void* pFiber = CreateFiberForTask(pReq); if(pFiber == NULL) { delete pReq; return WBEM_E_OUT_OF_MEMORY; } pIter->SetExecFiber(pFiber, pReq); return pIter->QueryInterface(IID_IWmiDbIterator, (void**)ppQueryResult); } CHR CNamespaceHandle::ExecQuerySink( IWbemQuery *pQuery, DWORD dwFlags, DWORD dwRequestedHandleType, IWbemObjectSink* pSink, DWORD *dwMessageFlags ) { try { if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; HRESULT hres; LPWSTR wszQuery = NULL; hres = pQuery->GetAnalysis(WMIQ_ANALYSIS_QUERY_TEXT, 0, (void**)&wszQuery); if (FAILED(hres)) return hres; DWORD dwLen = ((wcslen(wszQuery) + 1) * sizeof(wchar_t)); LPWSTR strParse = (LPWSTR)TempAlloc(dwLen); if(strParse == NULL) { pQuery->FreeMemory(wszQuery); return WBEM_E_OUT_OF_MEMORY; } CTempFreeMe tfm(strParse, dwLen); wcscpy(strParse, wszQuery); if(!_wcsicmp(wcstok(strParse, L" "), L"references")) { hres = ExecReferencesQuery(wszQuery, pSink); pQuery->FreeMemory(wszQuery); return hres; } QL_LEVEL_1_RPN_EXPRESSION* pExpr = NULL; CTextLexSource Source(wszQuery); QL1_Parser Parser(&Source); int nRet = Parser.Parse(&pExpr); CDeleteMe<QL_LEVEL_1_RPN_EXPRESSION> dm(pExpr); pQuery->FreeMemory(wszQuery); if (nRet == QL1_Parser::OUT_OF_MEMORY) return WBEM_E_OUT_OF_MEMORY; if (nRet != QL1_Parser::SUCCESS) return WBEM_E_FAILED; if(!_wcsicmp(pExpr->bsClassName, L"meta_class")) { return ExecClassQuery(pExpr, pSink, dwFlags); } else { return ExecInstanceQuery(pExpr, pExpr->bsClassName, (dwFlags & WBEM_FLAG_SHALLOW ? false : true), pSink); } } catch (CX_MemoryException) { return WBEM_E_OUT_OF_MEMORY; } } CHR CNamespaceHandle::ExecClassQuery(QL_LEVEL_1_RPN_EXPRESSION* pExpr, IWbemObjectSink* pSink, DWORD dwFlags) { if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; HRESULT hres = ERROR_SUCCESS; // // Optimizations: // LPCWSTR wszClassName = NULL; LPCWSTR wszSuperClass = NULL; LPCWSTR wszAncestor = NULL; bool bDontIncludeAncestorInResultSet = false; if(pExpr->nNumTokens == 1) { QL_LEVEL_1_TOKEN* pToken = pExpr->pArrayOfTokens; if(!_wcsicmp(pToken->PropertyName.GetStringAt(0), L"__SUPERCLASS") && pToken->nOperator == QL1_OPERATOR_EQUALS) { wszSuperClass = V_BSTR(&pToken->vConstValue); } else if(!_wcsicmp(pToken->PropertyName.GetStringAt(0), L"__THIS") && pToken->nOperator == QL1_OPERATOR_ISA) { wszAncestor = V_BSTR(&pToken->vConstValue); } else if(!_wcsicmp(pToken->PropertyName.GetStringAt(0), L"__CLASS") && pToken->nOperator == QL1_OPERATOR_EQUALS) { wszClassName = V_BSTR(&pToken->vConstValue); } } else if (pExpr->nNumTokens == 3) { // // This is a special optimisation used for deep enumeration of classes, // and is expecting a query of: // select * from meta_class where __this isa '<class_name>' // and __class <> '<class_name>' // where the <class_name> is the same class iin both cases. This will // set the wszAncestor to <class_name> and propagate a flag to not // include the actual ancestor in the list. // QL_LEVEL_1_TOKEN* pToken = pExpr->pArrayOfTokens; if ((pToken[0].nTokenType == QL1_OP_EXPRESSION) && (pToken[1].nTokenType == QL1_OP_EXPRESSION) && (pToken[2].nTokenType == QL1_AND) && (pToken[0].nOperator == QL1_OPERATOR_ISA) && (pToken[1].nOperator == QL1_OPERATOR_NOTEQUALS) && (_wcsicmp(pToken[0].PropertyName.GetStringAt(0), L"__THIS") == 0) && (_wcsicmp(pToken[1].PropertyName.GetStringAt(0), L"__CLASS") == 0) && (wcscmp(V_BSTR(&pToken[0].vConstValue), V_BSTR(&pToken[1].vConstValue)) == 0) ) { wszAncestor = V_BSTR(&pToken[0].vConstValue); bDontIncludeAncestorInResultSet = true; } } if(wszClassName) { _IWmiObject* pClass = NULL; hres = GetClassDirect(wszClassName, IID__IWmiObject, (void**)&pClass, true, NULL, NULL, NULL); if(hres == WBEM_E_NOT_FOUND) { // // Class not there --- but that's success for us! // if (dwFlags & WBEM_FLAG_VALIDATE_CLASS_EXISTENCE) return hres; else return S_OK; } else if(FAILED(hres)) { return hres; } else { CReleaseMe rm1(pClass); // // Get the class // hres = pSink->Indicate(1, (IWbemClassObject**)&pClass); if(FAILED(hres)) return hres; return S_OK; } } if (dwFlags & WBEM_FLAG_VALIDATE_CLASS_EXISTENCE) { _IWmiObject* pClass = NULL; if (wszSuperClass) hres = GetClassDirect(wszSuperClass, IID__IWmiObject, (void**)&pClass, false, NULL, NULL, NULL); else if (wszAncestor) hres = GetClassDirect(wszAncestor, IID__IWmiObject, (void**)&pClass, false, NULL, NULL, NULL); if (FAILED(hres)) return hres; if (pClass) pClass->Release(); } hres = EnumerateClasses(pSink, wszSuperClass, wszAncestor, true, bDontIncludeAncestorInResultSet); if(FAILED(hres)) return hres; return S_OK; } CHR CNamespaceHandle::EnumerateClasses(IWbemObjectSink* pSink, LPCWSTR wszSuperClass, LPCWSTR wszAncestor, bool bClone, bool bDontIncludeAncestorInResultSet) { if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; CWStringArray wsClasses; HRESULT hres; // // If superclass is given, check if its record is complete wrt children // if(wszSuperClass) { hres = m_pClassCache->EnumChildren(wszSuperClass, false, wsClasses); if(hres == WBEM_S_FALSE) { // // Not in cache --- get the info from files // return GetChildDefs(wszSuperClass, false, pSink, bClone); } else { if(FAILED(hres)) return hres; return ListToEnum(wsClasses, pSink, bClone); } } else { if(wszAncestor == NULL) wszAncestor = L""; hres = m_pClassCache->EnumChildren(wszAncestor, true, wsClasses); if(hres == WBEM_S_FALSE) { // // Not in cache --- get the info from files // hres = GetChildDefs(wszAncestor, true, pSink, bClone); if(FAILED(hres)) return hres; if(*wszAncestor && !bDontIncludeAncestorInResultSet) { // // The class is derived from itself // _IWmiObject* pClass = NULL; hres = GetClassDirect(wszAncestor, IID__IWmiObject, (void**)&pClass, bClone, NULL, NULL, NULL); if(FAILED(hres)) return hres; CReleaseMe rm1(pClass); hres = pSink->Indicate(1, (IWbemClassObject**)&pClass); if(FAILED(hres)) return hres; } return S_OK; } else { if(FAILED(hres)) return hres; if(*wszAncestor && !bDontIncludeAncestorInResultSet) { wsClasses.Add(wszAncestor); } return ListToEnum(wsClasses, pSink, bClone); } } } CHR CNamespaceHandle::ListToEnum(CWStringArray& wsClasses, IWbemObjectSink* pSink, bool bClone) { HRESULT hres; for(int i = 0; i < wsClasses.Size(); i++) { _IWmiObject* pClass = NULL; if(wsClasses[i] == NULL || wsClasses[i][0] == 0) continue; hres = GetClassDirect(wsClasses[i], IID__IWmiObject, (void**)&pClass, bClone, NULL, NULL, NULL); if(FAILED(hres)) { if(hres == WBEM_E_NOT_FOUND) { // That's OK --- class got removed } else return hres; } else { CReleaseMe rm1(pClass); hres = pSink->Indicate(1, (IWbemClassObject**)&pClass); if(FAILED(hres)) return hres; } } return WBEM_S_NO_ERROR; } CHR CNamespaceHandle::ExecInstanceQuery(QL_LEVEL_1_RPN_EXPRESSION* pQuery, LPCWSTR wszClassName, bool bDeep, IWbemObjectSink* pSink) { if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; HRESULT hres; WCHAR wszHash[MAX_HASH_LEN+1]; if(!Hash(wszClassName, wszHash)) return WBEM_E_OUT_OF_MEMORY; if(bDeep) hres = ExecDeepInstanceQuery(pQuery, wszHash, pSink); else hres = ExecShallowInstanceQuery(pQuery, wszHash, pSink); if(FAILED(hres)) return hres; return S_OK; } CHR CNamespaceHandle::ExecDeepInstanceQuery( QL_LEVEL_1_RPN_EXPRESSION* pQuery, LPCWSTR wszClassHash, IWbemObjectSink* pSink) { if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; HRESULT hres; // // Get all our instances // hres = ExecShallowInstanceQuery(pQuery, wszClassHash, pSink); if(FAILED(hres)) return hres; CWStringArray awsChildHashes; // // Check if the list of child classes is known to the cache // hres = m_pClassCache->EnumChildKeysByKey(wszClassHash, awsChildHashes); if (hres == WBEM_S_FALSE) { // // OK --- get them from the disk // hres = GetChildHashesByHash(wszClassHash, awsChildHashes); } if (FAILED(hres)) { return hres; } // // We have our hashes --- call them recursively // for(int i = 0; i < awsChildHashes.Size(); i++) { LPCWSTR wszChildHash = awsChildHashes[i]; hres = ExecDeepInstanceQuery(pQuery, wszChildHash, pSink); if(FAILED(hres)) return hres; } return S_OK; } CHR CNamespaceHandle::ExecShallowInstanceQuery( QL_LEVEL_1_RPN_EXPRESSION* pQuery, LPCWSTR wszClassHash, IWbemObjectSink* pSink) { if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; HRESULT hres; // // Enumerate all files in the link directory // CFileName wszSearchPrefix; if (wszSearchPrefix == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructLinkDirFromClassHash(wszSearchPrefix, wszClassHash); if(FAILED(hres)) return hres; wcscat(wszSearchPrefix, L"\\" A51_INSTLINK_FILE_PREFIX); // // Get Class definition // _IWmiObject* pClass = NULL; hres = GetClassByHash(wszClassHash, false, &pClass, NULL, NULL, NULL); if(FAILED(hres)) return hres; CReleaseMe rm1(pClass); CFileName fn; if (fn == NULL) return WBEM_E_OUT_OF_MEMORY; void* hSearch; long lRes = g_Glob.GetFileCache()->ObjectEnumerationBegin(wszSearchPrefix, &hSearch); if (lRes == ERROR_FILE_NOT_FOUND) return S_OK; else if (lRes != ERROR_SUCCESS) return A51TranslateErrorCode(lRes); BYTE *pBlob = NULL; DWORD dwSize = 0; while ((hres == ERROR_SUCCESS) && (lRes = g_Glob.GetFileCache()->ObjectEnumerationNext(hSearch, fn, &pBlob, &dwSize) == ERROR_SUCCESS)) { _IWmiObject* pInstance = NULL; hres = FileToInstance(pClass, fn, pBlob, dwSize, &pInstance, true); CReleaseMe rm2(pInstance); if (SUCCEEDED(hres)) hres = pSink->Indicate(1, (IWbemClassObject**)&pInstance); g_Glob.GetFileCache()->ObjectEnumerationFree(hSearch, pBlob); } g_Glob.GetFileCache()->ObjectEnumerationEnd(hSearch); if (lRes == ERROR_NO_MORE_FILES) return S_OK; else if (lRes) return A51TranslateErrorCode(lRes); else return hres; } CHR CNamespaceHandle::ExecReferencesQuery(LPCWSTR wszQuery, IWbemObjectSink* pSink) { if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; HRESULT hres; // // Make a copy for parsing // LPWSTR wszParse = new WCHAR[wcslen(wszQuery)+1]; if (wszParse == NULL) return WBEM_E_OUT_OF_MEMORY; CVectorDeleteMe<WCHAR> vdm(wszParse); wcscpy(wszParse, wszQuery); // // Extract the path of the target object. // // // Find the first brace // WCHAR* pwcStart = wcschr(wszParse, L'{'); if(pwcStart == NULL) return WBEM_E_INVALID_QUERY; // // Find the beginning of the path // while(*pwcStart && iswspace(*pwcStart)) pwcStart++; if(!*pwcStart) return WBEM_E_INVALID_QUERY; pwcStart++; // // Find the ending curly brace // WCHAR* pwc = pwcStart; WCHAR wcCurrentQuote = 0; while(*pwc && (wcCurrentQuote || *pwc != L'}')) { if(wcCurrentQuote) { if(*pwc == L'\\') { pwc++; } else if(*pwc == wcCurrentQuote) wcCurrentQuote = 0; } else if(*pwc == L'\'' || *pwc == L'"') wcCurrentQuote = *pwc; pwc++; } if(*pwc != L'}') return WBEM_E_INVALID_QUERY; // // Find the end of the path // WCHAR* pwcEnd = pwc-1; while(iswspace(*pwcEnd)) pwcEnd--; pwcEnd[1] = 0; LPWSTR wszTargetPath = pwcStart; if(wszTargetPath == NULL) return WBEM_E_INVALID_QUERY; // // Parse the path // DWORD dwLen = (wcslen(wszTargetPath)+1) * sizeof(WCHAR); LPWSTR wszKey = (LPWSTR)TempAlloc(dwLen); if(wszKey == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe tfm(wszKey, dwLen); LPWSTR wszClassName = NULL; bool bIsClass; hres = ComputeKeyFromPath(wszTargetPath, wszKey, &wszClassName, &bIsClass); if(FAILED(hres)) return hres; CTempFreeMe tfm1(wszClassName, (wcslen(wszClassName)+1) * sizeof(WCHAR*)); if(bIsClass) { // // Need to execute an instance reference query to find all instances // pointing to this class // hres = ExecInstanceRefQuery(wszQuery, NULL, wszClassName, pSink); if(FAILED(hres)) return hres; hres = ExecClassRefQuery(wszQuery, wszClassName, pSink); if(FAILED(hres)) return hres; } else { hres = ExecInstanceRefQuery(wszQuery, wszClassName, wszKey, pSink); if(FAILED(hres)) return hres; } return S_OK; } CHR CNamespaceHandle::ExecInstanceRefQuery(LPCWSTR wszQuery, LPCWSTR wszClassName, LPCWSTR wszKey, IWbemObjectSink* pSink) { if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; HRESULT hres; // // Find the instance's ref dir. // CFileName wszReferenceDir; if (wszReferenceDir == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructReferenceDirFromKey(wszClassName, wszKey, wszReferenceDir); if(FAILED(hres)) return hres; CFileName wszReferenceMask; if (wszReferenceMask == NULL) return WBEM_E_OUT_OF_MEMORY; wcscpy(wszReferenceMask, wszReferenceDir); wcscat(wszReferenceMask, L"\\" A51_REF_FILE_PREFIX); // // Prepare a buffer for file path // CFileName wszFullFileName; if (wszFullFileName == NULL) return WBEM_E_OUT_OF_MEMORY; wcscpy(wszFullFileName, wszReferenceDir); wcscat(wszFullFileName, L"\\"); long lDirLen = wcslen(wszFullFileName); HRESULT hresGlobal = WBEM_S_NO_ERROR; CFileName wszReferrerFileName; if (wszReferrerFileName == NULL) return WBEM_E_OUT_OF_MEMORY; wcscpy(wszReferrerFileName, g_Glob.GetRootDir()); CFileName wszFileName; if (wszFileName == NULL) return WBEM_E_OUT_OF_MEMORY; // // Enumerate all files in it // void* hSearch; long lRes = g_Glob.GetFileCache()->IndexEnumerationBegin(wszReferenceMask, &hSearch); if (lRes == ERROR_FILE_NOT_FOUND) return S_OK; else if (lRes != ERROR_SUCCESS) return A51TranslateErrorCode(lRes); while((lRes = g_Glob.GetFileCache()->IndexEnumerationNext(hSearch, wszFileName)) == ERROR_SUCCESS) { wcscpy(wszFullFileName+lDirLen, wszFileName); LPWSTR wszReferrerClass = NULL; LPWSTR wszReferrerProp = NULL; LPWSTR wszReferrerNamespace = NULL; hres = GetReferrerFromFile(wszFullFileName, wszReferrerFileName + g_Glob.GetRootDirLen(), &wszReferrerNamespace, &wszReferrerClass, &wszReferrerProp); if(FAILED(hres)) continue; CVectorDeleteMe<WCHAR> vdm1(wszReferrerClass); CVectorDeleteMe<WCHAR> vdm2(wszReferrerProp); CVectorDeleteMe<WCHAR> vdm3(wszReferrerNamespace); // Check if the namespace of the referring object is the same as ours CNamespaceHandle* pReferrerHandle = NULL; if(wbem_wcsicmp(wszReferrerNamespace, m_wsNamespace)) { // Open the other namespace hres = m_pRepository->GetNamespaceHandle(wszReferrerNamespace, &pReferrerHandle); if(FAILED(hres)) { ERRORTRACE((LOG_WBEMCORE, "Unable to open referring namespace '%S' in namespace '%S'\n", wszReferrerNamespace, (LPCWSTR)m_wsNamespace)); hresGlobal = hres; continue; } } else { pReferrerHandle = this; pReferrerHandle->AddRef(); } CReleaseMe rm1(pReferrerHandle); _IWmiObject* pInstance = NULL; hres = pReferrerHandle->FileToInstance(NULL, wszReferrerFileName, NULL, 0, &pInstance); if(FAILED(hres)) { // Oh well --- continue; hresGlobal = hres; } else { CReleaseMe rm2(pInstance); hres = pSink->Indicate(1, (IWbemClassObject**)&pInstance); if(FAILED(hres)) { hresGlobal = hres; break; } } } g_Glob.GetFileCache()->IndexEnumerationEnd(hSearch); if (hresGlobal != ERROR_SUCCESS) return hresGlobal; if(lRes == ERROR_NO_MORE_FILES) { // // No files in dir --- no problem // return WBEM_S_NO_ERROR; } else if(lRes != ERROR_SUCCESS) { return WBEM_E_FAILED; } return WBEM_S_NO_ERROR; } CHR CNamespaceHandle::GetReferrerFromFile(LPCWSTR wszReferenceFile, LPWSTR wszReferrerRelFile, LPWSTR* pwszReferrerNamespace, LPWSTR* pwszReferrerClass, LPWSTR* pwszReferrerProp) { // // Get the entire buffer from the file // BYTE* pBuffer = NULL; DWORD dwBufferLen = 0; long lRes = g_Glob.GetFileCache()->ReadObject(wszReferenceFile, &dwBufferLen, &pBuffer); if(lRes != ERROR_SUCCESS) return WBEM_E_FAILED; CTempFreeMe tfm(pBuffer, dwBufferLen); if(dwBufferLen == 0) return WBEM_E_OUT_OF_MEMORY; BYTE* pCurrent = pBuffer; DWORD dwStringLen; // // Get the referrer namespace // memcpy(&dwStringLen, pCurrent, sizeof(DWORD)); pCurrent += sizeof(DWORD); *pwszReferrerNamespace = new WCHAR[dwStringLen+1]; if (*pwszReferrerNamespace == NULL) return WBEM_E_OUT_OF_MEMORY; (*pwszReferrerNamespace)[dwStringLen] = 0; memcpy(*pwszReferrerNamespace, pCurrent, dwStringLen*sizeof(WCHAR)); pCurrent += sizeof(WCHAR)*dwStringLen; // // Get the referrer class name // memcpy(&dwStringLen, pCurrent, sizeof(DWORD)); pCurrent += sizeof(DWORD); *pwszReferrerClass = new WCHAR[dwStringLen+1]; if (*pwszReferrerClass == NULL) return WBEM_E_OUT_OF_MEMORY; (*pwszReferrerClass)[dwStringLen] = 0; memcpy(*pwszReferrerClass, pCurrent, dwStringLen*sizeof(WCHAR)); pCurrent += sizeof(WCHAR)*dwStringLen; // // Get the referrer property // memcpy(&dwStringLen, pCurrent, sizeof(DWORD)); pCurrent += sizeof(DWORD); *pwszReferrerProp = new WCHAR[dwStringLen+1]; if (*pwszReferrerProp == NULL) return WBEM_E_OUT_OF_MEMORY; (*pwszReferrerProp)[dwStringLen] = 0; memcpy(*pwszReferrerProp, pCurrent, dwStringLen*sizeof(WCHAR)); pCurrent += sizeof(WCHAR)*dwStringLen; // // Get referrer file path // memcpy(&dwStringLen, pCurrent, sizeof(DWORD)); pCurrent += sizeof(DWORD); wszReferrerRelFile[dwStringLen] = 0; memcpy(wszReferrerRelFile, pCurrent, dwStringLen*sizeof(WCHAR)); pCurrent += sizeof(WCHAR)*dwStringLen; return S_OK; } CHR CNamespaceHandle::ExecClassRefQuery(LPCWSTR wszQuery, LPCWSTR wszClassName, IWbemObjectSink* pSink) { if (g_bShuttingDown) return WBEM_E_SHUTTING_DOWN; HRESULT hres = ERROR_SUCCESS; //Execute against system class namespace first if (g_pSystemClassNamespace && (wcscmp(m_wsNamespace, A51_SYSTEMCLASS_NS) != 0)) { hres = g_pSystemClassNamespace->ExecClassRefQuery(wszQuery, wszClassName, pSink); if (FAILED(hres)) return hres; } // // Find the class's ref dir. // CFileName wszReferenceDir; if (wszReferenceDir == NULL) return WBEM_E_OUT_OF_MEMORY; hres = ConstructClassRelationshipsDir(wszClassName, wszReferenceDir); CFileName wszReferenceMask; if (wszReferenceMask == NULL) return WBEM_E_OUT_OF_MEMORY; wcscpy(wszReferenceMask, wszReferenceDir); wcscat(wszReferenceMask, L"\\" A51_REF_FILE_PREFIX); CFileName wszFileName; if (wszFileName == NULL) return WBEM_E_OUT_OF_MEMORY; // // Enumerate all files in it // void* hSearch; long lRes = g_Glob.GetFileCache()->IndexEnumerationBegin(wszReferenceMask, &hSearch); if (lRes == ERROR_FILE_NOT_FOUND) return S_OK; else if (lRes != ERROR_SUCCESS) return A51TranslateErrorCode(lRes); while ((hres == ERROR_SUCCESS) && ((lRes = g_Glob.GetFileCache()->IndexEnumerationNext(hSearch, wszFileName) == ERROR_SUCCESS))) { // // Extract the class hash from the name of the file // LPCWSTR wszReferrerHash = wszFileName + wcslen(A51_REF_FILE_PREFIX); // // Get the class from that hash // _IWmiObject* pClass = NULL; hres = GetClassByHash(wszReferrerHash, true, &pClass, NULL, NULL, NULL); if(hres == WBEM_E_NOT_FOUND) { hres = ERROR_SUCCESS; continue; } CReleaseMe rm1(pClass); if (hres == ERROR_SUCCESS) hres = pSink->Indicate(1, (IWbemClassObject**)&pClass); } g_Glob.GetFileCache()->IndexEnumerationEnd(hSearch); if (hres != ERROR_SUCCESS) return hres; if(lRes == ERROR_NO_MORE_FILES) { // // No files in dir --- no problem // return WBEM_S_NO_ERROR; } else if(lRes != ERROR_SUCCESS) { return WBEM_E_FAILED; } return S_OK; } bool CNamespaceHandle::Hash(LPCWSTR wszName, LPWSTR wszHash) { return A51Hash(wszName, wszHash); } CHR CNamespaceHandle::InstanceToFile(IWbemClassObject* pInst, LPCWSTR wszClassName, LPCWSTR wszFileName1, LPCWSTR wszFileName2, __int64 nClassTime) { HRESULT hres; // // Allocate enough space for the buffer // _IWmiObject* pInstEx; pInst->QueryInterface(IID__IWmiObject, (void**)&pInstEx); CReleaseMe rm1(pInstEx); DWORD dwInstancePartLen = 0; hres = pInstEx->Unmerge(0, 0, &dwInstancePartLen, NULL); // // Add enough room for the class hash // DWORD dwClassHashLen = MAX_HASH_LEN * sizeof(WCHAR); DWORD dwTotalLen = dwInstancePartLen + dwClassHashLen + sizeof(__int64)*2; BYTE* pBuffer = (BYTE*)TempAlloc(dwTotalLen); if (pBuffer == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe vdm(pBuffer, dwTotalLen); // // Write the class hash // if(!Hash(wszClassName, (LPWSTR)pBuffer)) return WBEM_E_OUT_OF_MEMORY; memcpy(pBuffer + dwClassHashLen, &g_nCurrentTime, sizeof(__int64)); g_nCurrentTime++; memcpy(pBuffer + dwClassHashLen + sizeof(__int64), &nClassTime, sizeof(__int64)); // // Unmerge the instance into a buffer // DWORD dwLen; hres = pInstEx->Unmerge(0, dwInstancePartLen, &dwLen, pBuffer + dwClassHashLen + sizeof(__int64)*2); if(FAILED(hres)) return hres; // // Write to the file only as much as we have actually used! // long lRes = g_Glob.GetFileCache()->WriteObject(wszFileName1, wszFileName2, dwClassHashLen + sizeof(__int64)*2 + dwLen, pBuffer); if(lRes != ERROR_SUCCESS) return WBEM_E_FAILED; return WBEM_S_NO_ERROR; } CHR CNamespaceHandle::ClassToFile(_IWmiObject* pParentClass, _IWmiObject* pClass, LPCWSTR wszFileName, __int64 nFakeUpdateTime) { HRESULT hres; // // Get superclass name // VARIANT vSuper; hres = pClass->Get(L"__SUPERCLASS", 0, &vSuper, NULL, NULL); if(FAILED(hres)) return hres; CClearMe cm1(&vSuper); LPCWSTR wszSuper; if(V_VT(&vSuper) == VT_BSTR) wszSuper = V_BSTR(&vSuper); else wszSuper = L""; VARIANT vClassName; hres = pClass->Get(L"__CLASS", 0, &vClassName, NULL, NULL); if(FAILED(hres)) return hres; CClearMe cm2(&vClassName); LPCWSTR wszClassName; if(V_VT(&vClassName) == VT_BSTR) wszClassName = V_BSTR(&vClassName); else wszClassName = L""; #ifdef A51_SUPER_VALIDATION if (wcscmp(wszSuper, wszClassName) == 0) { OutputDebugString(L"WinMgmt: Repository is trying to put a class that is derived from itself!\n"); DebugBreak(); return WBEM_E_FAILED; } if (pClass->IsObjectInstance() == S_OK) { OutputDebugString(L"WinMgmt: Repository is trying to store an instance in a class blob!\n"); DebugBreak(); return WBEM_E_FAILED; } if (FAILED(pClass->ValidateObject(WMIOBJECT_VALIDATEOBJECT_FLAG_FORCE))) { OutputDebugString(L"WinMgmt: Repository was gived an invalid class to store in the repository!\n"); DebugBreak(); return WBEM_E_FAILED; } #endif // // Get unmerge length // DWORD dwUnmergedLen = 0; hres = pClass->Unmerge(0, 0, &dwUnmergedLen, NULL); // // Add enough space for the parent class name and the timestamp // DWORD dwSuperLen = sizeof(DWORD) + wcslen(wszSuper)*sizeof(WCHAR); DWORD dwLen = dwUnmergedLen + dwSuperLen + sizeof(__int64); BYTE* pBuffer = (BYTE*)TempAlloc(dwLen); if (pBuffer == NULL) return WBEM_E_OUT_OF_MEMORY; CTempFreeMe vdm(pBuffer, dwLen); // // Write superclass name // DWORD dwActualSuperLen = wcslen(wszSuper); memcpy(pBuffer, &dwActualSuperLen, sizeof(DWORD)); memcpy(pBuffer + sizeof(DWORD), wszSuper, wcslen(wszSuper)*sizeof(WCHAR)); // // Write the timestamp // if(nFakeUpdateTime == 0) { nFakeUpdateTime = g_nCurrentTime; g_nCurrentTime++; } memcpy(pBuffer + dwSuperLen, &nFakeUpdateTime, sizeof(__int64)); // // Write the unmerged portion // BYTE* pUnmergedPortion = pBuffer + dwSuperLen + sizeof(__int64); hres = pClass->Unmerge(0, dwUnmergedLen, &dwUnmergedLen, pUnmergedPortion); if(FAILED(hres)) return hres; // // Stash away the real length // DWORD dwFileLen = dwUnmergedLen + dwSuperLen + sizeof(__int64); long lRes = g_Glob.GetFileCache()->WriteObject(wszFileName, NULL, dwFileLen, pBuffer); if(lRes != ERROR_SUCCESS) return WBEM_E_FAILED; // // To properly cache the new class definition, first invalidate it // hres = m_pClassCache->InvalidateClass(wszClassName); if(FAILED(hres)) return hres; // // Now, remerge the unmerged portion back in // if(pParentClass == NULL) { // // Get the empty class // hres = GetClassDirect(NULL, IID__IWmiObject, (void**)&pParentClass, false, NULL, NULL, NULL); if(FAILED(hres)) return hres; } else pParentClass->AddRef(); CReleaseMe rm0(pParentClass); _IWmiObject* pNewObj; hres = pParentClass->Merge(0, dwUnmergedLen, pUnmergedPortion, &pNewObj); if(FAILED(hres)) return hres; CReleaseMe rm1(pNewObj); hres = pNewObj->SetDecoration(m_wszMachineName, m_wsNamespace); if(FAILED(hres)) return hres; hres = m_pClassCache->AssertClass(pNewObj, wszClassName, false, nFakeUpdateTime, false); if(FAILED(hres)) return hres; return WBEM_S_NO_ERROR; } CHR CNamespaceHandle::ConstructInstanceDefName(LPWSTR wszInstanceDefName, LPCWSTR wszKey) { wcscpy(wszInstanceDefName, A51_INSTDEF_FILE_PREFIX); if(!Hash(wszKey, wszInstanceDefName + wcslen(A51_INSTDEF_FILE_PREFIX))) { return WBEM_E_OUT_OF_MEMORY; } return WBEM_S_NO_ERROR; } CHR CNamespaceHandle::ConstructInstDefNameFromLinkName( LPWSTR wszInstanceDefName, LPCWSTR wszInstanceLinkName) { wcscpy(wszInstanceDefName, A51_INSTDEF_FILE_PREFIX); wcscat(wszInstanceDefName, wszInstanceLinkName + wcslen(A51_INSTLINK_FILE_PREFIX)); return WBEM_S_NO_ERROR; } CHR CNamespaceHandle::ConstructClassDefFileName(LPCWSTR wszClassName, LPWSTR wszFileName) { wcscpy(wszFileName, A51_CLASSDEF_FILE_PREFIX); if(!Hash(wszClassName, wszFileName+wcslen(A51_CLASSDEF_FILE_PREFIX))) return WBEM_E_INVALID_OBJECT; return WBEM_S_NO_ERROR; } CHR CNamespaceHandle::ConstructClassDefFileNameFromHash(LPCWSTR wszHash, LPWSTR wszFileName) { wcscpy(wszFileName, A51_CLASSDEF_FILE_PREFIX); wcscat(wszFileName, wszHash); return WBEM_S_NO_ERROR; } //============================================================================= // // CNamespaceHandle::CreateSystemClasses // // We are in a pseudo namespace. We need to determine if we already have // the system classes in this namespace. The system classes that we create // are those that exist in all namespaces, and no others. If they do not exist // we create them. // The whole creation process happens within the confines of a transaction // that we create and own within this method. // //============================================================================= HRESULT CNamespaceHandle::CreateSystemClasses(CFlexArray &aSystemClasses) { HRESULT hRes = WBEM_S_NO_ERROR; //Now we need to determine if the system classes already exist. Lets do this by looking for the __thisnamespace //class! { _IWmiObject *pObj = NULL; hRes = GetClassDirect(L"__thisnamespace", IID__IWmiObject, (void**)&pObj, false, NULL, NULL, NULL); if (SUCCEEDED(hRes)) { //All done! They already exist! pObj->Release(); return WBEM_S_NO_ERROR; } else if (hRes != WBEM_E_NOT_FOUND) { //Something went bad, so we just fail! return hRes; } } //There are no system classes so we need to create them. hRes = A51TranslateErrorCode(g_Glob.GetFileCache()->BeginTransaction()); CEventCollector eventCollector; _IWmiObject *Objects[256]; _IWmiObject **ppObjects = NULL; ULONG uSize = 256; if (SUCCEEDED(hRes) && aSystemClasses.Size()) { //If we have a system-class array we need to use that instead of using the ones retrieved from the core //not doing so will cause a mismatch. We retrieved these as part of the upgrade process... uSize = aSystemClasses.Size(); ppObjects = (_IWmiObject**)&aSystemClasses[0]; } else if (SUCCEEDED(hRes)) { //None retrieved from upgrade process so we must be a clean install. Therefore we should //get the list from the core... _IWmiCoreServices * pSvcs = g_Glob.GetCoreSvcs(); CReleaseMe rm(pSvcs); hRes = pSvcs->GetSystemObjects(GET_SYSTEM_STD_OBJECTS, &uSize, Objects); ppObjects = Objects; } if (SUCCEEDED(hRes)) { for (int i = 0; i < uSize; i++) { IWbemClassObject *pObj; if (SUCCEEDED(hRes)) { hRes = ppObjects[i]->QueryInterface(IID_IWbemClassObject, (LPVOID *) &pObj); if (SUCCEEDED(hRes)) { hRes = PutObject(IID_IWbemClassObject, pObj, WMIDB_DISABLE_EVENTS, 0, 0, eventCollector); pObj->Release(); if (FAILED(hRes)) { ERRORTRACE((LOG_WBEMCORE, "Creation of system class failed during repository creation <0x%X>!\n", hRes)); } } } ppObjects[i]->Release(); } } //Clear out the array that was sent to us. aSystemClasses.Empty(); if (FAILED(hRes)) { g_Glob.GetFileCache()->AbortTransaction(); } else { hRes = A51TranslateErrorCode(g_Glob.GetFileCache()->CommitTransaction()); if (hRes == ERROR_SUCCESS) CRepository::WriteOperationNotification(); else CRepository::RecoverCheckpoint(); } return hRes; } class CSystemClassDeletionSink : public CUnkBase<IWbemObjectSink, &IID_IWbemObjectSink> { CWStringArray &m_aChildNamespaces; public: CSystemClassDeletionSink(CWStringArray &aChildNamespaces) : m_aChildNamespaces(aChildNamespaces) { } ~CSystemClassDeletionSink() { } STDMETHOD(Indicate)(long lNumObjects, IWbemClassObject** apObjects) { HRESULT hRes; for (int i = 0; i != lNumObjects; i++) { if (apObjects[i] != NULL) { _IWmiObject *pInst = NULL; hRes = apObjects[i]->QueryInterface(IID__IWmiObject, (void**)&pInst); if (FAILED(hRes)) return hRes; CReleaseMe rm(pInst); BSTR strKey = NULL; hRes = pInst->GetKeyString(0, &strKey); if(FAILED(hRes)) return hRes; CSysFreeMe sfm(strKey); if (m_aChildNamespaces.Add(strKey) != CWStringArray::no_error) return WBEM_E_OUT_OF_MEMORY; } } return WBEM_S_NO_ERROR; } STDMETHOD(SetStatus)(long lFlags, HRESULT hresResult, BSTR, IWbemClassObject*) { return WBEM_S_NO_ERROR; } }; //============================================================================= //============================================================================= CDbIterator::CDbIterator(CLifeControl* pControl, bool bUseLock) : TUnkBase(pControl), m_lCurrentIndex(0), m_hresStatus(WBEM_S_FALSE), m_pMainFiber(NULL), m_pExecFiber(NULL), m_dwNumRequested(0), m_pExecReq(NULL), m_hresCancellationStatus(WBEM_S_NO_ERROR), m_bExecFiberRunning(false), m_bUseLock(bUseLock) { } CDbIterator::~CDbIterator() { if(m_pExecFiber) Cancel(0, NULL); if(m_pExecReq) delete m_pExecReq; CRepository::ReadOperationNotification(); } void CDbIterator::SetExecFiber(void* pFiber, CFiberTask* pReq) { m_pExecFiber = pFiber; m_pExecReq = pReq; } STDMETHODIMP CDbIterator::Cancel(DWORD dwFlags, void* pFiber) { CInCritSec ics(&m_cs); m_qObjects.Clear(); // // Mark the iterator as cancelled and allow the execution fiber to resume // and complete --- that guarantees that any memory it allocated will be // cleaned up. The exception to this rule is if the fiber has not started // execution yet; in that case, we do not want to switch to it, as it would // have to run until the first Indicate to find out that it's been // cancelled. (In the normal case, the execution fiber is suspended // inside Indicate, so when we switch back we will immediately give it // WBEM_E_CALL_CANCELLED so that it can clean up and return) // m_hresCancellationStatus = WBEM_E_CALL_CANCELLED; if(m_pExecFiber) { if(m_bExecFiberRunning) { _ASSERT(m_pMainFiber == NULL && m_pExecFiber != NULL, L"Fiber trouble"); // // Make sure the calling thread has a fiber // m_pMainFiber = pFiber; if(m_pMainFiber == NULL) return WBEM_E_OUT_OF_MEMORY; { CAutoReadLock lock(&g_readWriteLock); if (m_bUseLock) { if (!lock.Lock()) return WBEM_E_FAILED; } SwitchToFiber(m_pExecFiber); } } // // At this point, the executing fiber is dead. We know, because in the // cancelled state we do not switch to the main fiber in Indicate. // ReturnFiber(m_pExecFiber); m_pExecFiber = NULL; } return S_OK; } STDMETHODIMP CDbIterator::NextBatch( DWORD dwNumRequested, DWORD dwTimeOutSeconds, DWORD dwFlags, DWORD dwRequestedHandleType, REFIID riid, void* pFiber, DWORD *pdwNumReturned, LPVOID *ppObjects ) { CInCritSec ics(&m_cs); // // TEMP CODE: Someone is calling us on an impersonated thread. Let's catch // the, ahem, bastard // HANDLE hToken; BOOL bRes = OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &hToken); if(bRes) { //_ASSERT(false, L"Called with a thread token"); ERRORTRACE((LOG_WBEMCORE, "Repository called with a thread token! " "It shall be removed\n")); CloseHandle(hToken); SetThreadToken(NULL, NULL); } _ASSERT(SUCCEEDED(m_hresCancellationStatus), L"Next called after Cancel"); m_bExecFiberRunning = true; // // Wait until it's over or the right number of objects has been received // if(m_qObjects.GetQueueSize() < dwNumRequested) { _ASSERT(m_pMainFiber == NULL && m_pExecFiber != NULL, L"Fiber trouble"); // // Make sure the calling thread has a fiber // m_pMainFiber = pFiber; if(m_pMainFiber == NULL) return WBEM_E_OUT_OF_MEMORY; m_dwNumRequested = dwNumRequested; // // We need to acquire the read lock for the duration of the continuation // of the retrieval // { CAutoReadLock lock(&g_readWriteLock); if (m_bUseLock) { if (!lock.Lock()) { m_pMainFiber = NULL; return WBEM_E_FAILED; } } if (g_bShuttingDown) { m_pMainFiber = NULL; return WBEM_E_SHUTTING_DOWN; } SwitchToFiber(m_pExecFiber); } m_pMainFiber = NULL; } // // We have as much as we are going to have! // DWORD dwReqIndex = 0; while(dwReqIndex < dwNumRequested) { if(0 == m_qObjects.GetQueueSize()) { // // That's it --- we waited for production, so there are simply no // more objects in the enumeration // *pdwNumReturned = dwReqIndex; return m_hresStatus; } IWbemClassObject* pObj = m_qObjects.Dequeue(); CReleaseMe rm1(pObj); pObj->QueryInterface(riid, ppObjects + dwReqIndex); dwReqIndex++; } // // Got everything // *pdwNumReturned= dwNumRequested; return S_OK; } HRESULT CDbIterator::Indicate(long lNumObjects, IWbemClassObject** apObjects) { if(FAILED(m_hresCancellationStatus)) { // // Screw-up --- the fiber called back with Indicate even after we // cancelled! Oh well. // _ASSERT(false, L"Execution code ignored cancel return code!"); return m_hresCancellationStatus; } // // Add the objects received to the array // for(long i = 0; i < lNumObjects; i++) { m_qObjects.Enqueue(apObjects[i]); } // // Check if we have compiled enough for the current request and should // therefore interrupt the gatherer // if(m_qObjects.GetQueueSize() >= m_dwNumRequested) { // // Switch us back to the original fiber // SwitchToFiber(m_pMainFiber); } return m_hresCancellationStatus; } HRESULT CDbIterator::SetStatus(long lFlags, HRESULT hresResult, BSTR, IWbemClassObject*) { _ASSERT(m_hresStatus == WBEM_S_FALSE, L"SetStatus called twice!"); _ASSERT(lFlags == WBEM_STATUS_COMPLETE, L"SetStatus flags invalid"); m_hresStatus = hresResult; // // Switch us back to the original thread, we are done // m_bExecFiberRunning = false; SwitchToFiber(m_pMainFiber); return WBEM_S_NO_ERROR; } CRepEvent::CRepEvent(DWORD dwType, LPCWSTR wszNamespace, LPCWSTR wszArg1, _IWmiObject* pObj1, _IWmiObject* pObj2) { m_dwType = dwType; m_pObj1 = 0; m_pObj2 = 0; m_wszArg1 = m_wszNamespace = NULL; if (wszArg1) { m_wszArg1 = (WCHAR*)TempAlloc((wcslen(wszArg1)+1)*sizeof(WCHAR)); if (m_wszArg1 == NULL) throw CX_MemoryException(); wcscpy(m_wszArg1, wszArg1); } if (wszNamespace) { m_wszNamespace = (WCHAR*)TempAlloc((wcslen(wszNamespace)+1)*sizeof(WCHAR)); if (m_wszNamespace == NULL) throw CX_MemoryException(); wcscpy(m_wszNamespace, wszNamespace); } if (pObj1) { m_pObj1 = pObj1; pObj1->AddRef(); } if (pObj2) { m_pObj2 = pObj2; pObj2->AddRef(); } } CRepEvent::~CRepEvent() { TempFree(m_wszArg1, (wcslen(m_wszArg1)+1)*sizeof(WCHAR)); TempFree(m_wszNamespace, (wcslen(m_wszNamespace)+1)*sizeof(WCHAR)); if (m_pObj1) m_pObj1->Release(); if (m_pObj2) m_pObj2->Release(); }; HRESULT CEventCollector::SendEvents(_IWmiCoreServices* pCore) { HRESULT hresGlobal = WBEM_S_NO_ERROR; for (int i = 0; i != m_apEvents.GetSize(); i++) { CRepEvent *pEvent = m_apEvents[i]; _IWmiObject* apObjs[2]; apObjs[0] = pEvent->m_pObj1; apObjs[1] = pEvent->m_pObj2; HRESULT hres = pCore->DeliverIntrinsicEvent( pEvent->m_wszNamespace, pEvent->m_dwType, NULL, pEvent->m_wszArg1, NULL, (pEvent->m_pObj2?2:1), apObjs); if(FAILED(hres)) hresGlobal = hres; } return hresGlobal; } bool CEventCollector::AddEvent(CRepEvent* pEvent) { EnterCriticalSection(&m_csLock); if(m_bNamespaceOnly) { if(pEvent->m_dwType != WBEM_EVENTTYPE_NamespaceCreation && pEvent->m_dwType != WBEM_EVENTTYPE_NamespaceDeletion && pEvent->m_dwType != WBEM_EVENTTYPE_NamespaceModification) { delete pEvent; LeaveCriticalSection(&m_csLock); return true; } } bool bRet = (m_apEvents.Add(pEvent) >= 0); LeaveCriticalSection(&m_csLock); return bRet; } void CEventCollector::DeleteAllEvents() { EnterCriticalSection(&m_csLock); m_bNamespaceOnly = false; m_apEvents.RemoveAll(); LeaveCriticalSection(&m_csLock); } void CEventCollector::TransferEvents(CEventCollector &aEventsToTransfer) { m_bNamespaceOnly = aEventsToTransfer.m_bNamespaceOnly; while(aEventsToTransfer.m_apEvents.GetSize()) { CRepEvent *pEvent = 0; aEventsToTransfer.m_apEvents.RemoveAt(0, &pEvent); m_apEvents.Add(pEvent); } }
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
228ccfc9932a7a53f07e92a0443a81895dbdd6cc
cb80a8562d90eb969272a7ff2cf52c1fa7aeb084
/inletTest3/0.112/uniform/cumulativeContErr
041a8ee595dc7e04172f46c62586090005bba446
[]
no_license
mahoep/inletCFD
eb516145fad17408f018f51e32aa0604871eaa95
0df91e3fbfa60d5db9d52739e212ca6d3f0a28b2
refs/heads/main
2023-08-30T22:07:41.314690
2021-10-14T19:23:51
2021-10-14T19:23:51
314,657,843
0
0
null
null
null
null
UTF-8
C++
false
false
958
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v2006 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class uniformDimensionedScalarField; location "0.112/uniform"; object cumulativeContErr; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; value -0.00137856; // ************************************************************************* //
[ "mhoeper3234@gmail.com" ]
mhoeper3234@gmail.com
76f7db48044c0d3c204e20372a3d019049be57d7
fc2d01d1afa08ffc46c23901163c37e679c3beaf
/Renderer2D/R2D_Text.h
0e2b5f6c9588067441cbfb52861b4403fa4249ff
[]
no_license
seblef/ShadowEngine
a9428607b49cdd41eb22dcbd8504555454e26a0c
fba95e910c63269bfe0a05ab639dc78b6c16ab8b
refs/heads/master
2023-02-14T19:08:25.878492
2021-01-08T16:16:44
2021-01-08T16:16:44
113,681,956
1
0
null
null
null
null
UTF-8
C++
false
false
791
h
#ifndef _R2D_TEXT_H_ #define _R2D_TEXT_H_ #include "R2D_Object.h" #include "R2D_Font.h" class R2D_Text : public R2D_Object { protected: R2D_Font* _font; string _text; public: R2D_Text(R2D_Font* font) : R2D_Object(R2D_TEXT), _font(font) {} R2D_Text(R2D_Font* font, const string& txt) : R2D_Object(R2D_TEXT), _font(font), _text(txt) {} R2D_Text(R2D_Font* font, const string& txt, const Vector2& pos, const Vector2& size, const Color& c) : R2D_Object(R2D_TEXT,pos,size,c), _font(font), _text(txt) {} R2D_Font* getFont() const { return _font; } void setText(const string& txt) { _text=txt; } string& getText() { return _text; } const string& getText() const { return _text; } }; #endif
[ "sebast.lefort@gmail.com" ]
sebast.lefort@gmail.com
6adc8e769ee66f9eb0b4c6fffac459754b8e56fb
e1e6314f63c9f2dc6843ec62cab7be827e996b45
/imageManager.cpp
da35b1069b705908b0458ace0ca72aa682352169
[]
no_license
jisan-Park/NewClearThrone
44e78a8ef7b164c7ae49442d27140671407a575b
9cf3604ce6c18912bb6da32e6ce9e8d856595c54
refs/heads/master
2023-02-28T04:59:32.884014
2021-02-08T20:39:09
2021-02-08T20:39:09
335,621,624
0
1
null
null
null
null
UHC
C++
false
false
3,933
cpp
#include "stdafx.h" #include "imageManager.h" imageManager::imageManager() { } imageManager::~imageManager() { } HRESULT imageManager::init() { return S_OK; } void imageManager::release() { deleteAll(); } image* imageManager::addImage(string strKey, int width, int height) { image* img = findImage(strKey); //해당 이미지가 있으면 그 이미지를 반환해라 if (img) return img; //없으면 새로 하나 할당해줘라 img = new image; if (FAILED(img->init(width, height))) { SAFE_DELETE(img); return nullptr; } _mImageList.insert(make_pair(strKey, img)); return img; } image* imageManager::addImage(string strKey, const char * fileName, int width, int height, bool trans, COLORREF transColor) { image* img = findImage(strKey); //해당 이미지가 있으면 그 이미지를 반환해라 if (img) return img; //없으면 새로 하나 할당해줘라 img = new image; if (FAILED(img->init(fileName, width, height, trans, transColor))) { SAFE_DELETE(img); return nullptr; } _mImageList.insert(make_pair(strKey, img)); return img; } image * imageManager::addFrameImage(string strKey, const char * fileName, float x, float y, int width, int height, int frameX, int frameY, BOOL trans, COLORREF transColor) { image* img = findImage(strKey); //해당 이미지가 있으면 그 이미지를 반환해라 if (img) return img; //없으면 새로 하나 할당해줘라 img = new image; if (FAILED(img->init(fileName, x, y, width, height, frameX, frameY, trans, transColor))) { SAFE_DELETE(img); return nullptr; } _mImageList.insert(make_pair(strKey, img)); return img; } image * imageManager::addFrameImage(string strKey, const char * fileName, int width, int height, int frameX, int frameY, BOOL trans, COLORREF transColor) { image* img = findImage(strKey); //해당 이미지가 있으면 그 이미지를 반환해라 if (img) return img; //없으면 새로 하나 할당해줘라 img = new image; if (FAILED(img->init(fileName, width, height, frameX, frameY, trans, transColor))) { SAFE_DELETE(img); return nullptr; } _mImageList.insert(make_pair(strKey, img)); return img; } image* imageManager::findImage(string strKey) { mapImageIter key = _mImageList.find(strKey); //찾았다 if (key != _mImageList.end()) { return key->second; } return nullptr; } BOOL imageManager::deleteImage(string strKey) { mapImageIter key = _mImageList.find(strKey); if (key != _mImageList.end()) { key->second->release(); SAFE_DELETE(key->second); _mImageList.erase(key); return true; } return false; } BOOL imageManager::deleteAll() { mapImageIter iter = _mImageList.begin(); for (; iter != _mImageList.end();) { if (iter->second != NULL) { iter->second->release(); SAFE_DELETE(iter->second); iter = _mImageList.erase(iter); } else ++iter; } _mImageList.clear(); return 0; } void imageManager::render(string strKey, HDC hdc) { image* img = findImage(strKey); if (img) img->render(hdc); } void imageManager::render(string strKey, HDC hdc, int destX, int destY) { image* img = findImage(strKey); if (img) img->render(hdc, destX, destY); } void imageManager::render(string strKey, HDC hdc, int destX, int destY, int sourX, int sourY, int sourWidth, int sourHeight) { image* img = findImage(strKey); if (img) img->render(hdc, destX, destY, sourX, sourY, sourWidth, sourHeight); } void imageManager::loopRender(string strKey, HDC hdc, const LPRECT drawArea, int offSetX, int offSetY) { image* img = findImage(strKey); if (img) img->loopRender(hdc, drawArea, offSetX, offSetY); } void imageManager::stretchRender(string strKey, HDC hdc, int destX, int destY, int destWidth, int destHeight, int sourX, int sourY, int sourWidth, int sourHeight) { image* img = findImage(strKey); if (img) img->stretchRender(hdc,destX,destY,destWidth,destHeight,sourX,sourY,sourWidth,sourHeight); }
[ "jsnpark1221@gmail.com" ]
jsnpark1221@gmail.com
0da03c261112d4dcfb969582daf1028c38ac14ae
76853cbb59da39c3291c0bec3f796a354cf7fe07
/175_desk/window.cpp
a401b12f1b7f711391c8e897340358cc6594026d
[]
no_license
dskabiri/ecs175
3e8f51dddaf96861298d796f26c8c96be8e06cc2
c1dba10b971c84a7d0eb77b93aba8e05d155312c
refs/heads/master
2016-09-02T01:53:19.336072
2014-03-01T08:31:08
2014-03-01T08:31:08
16,710,452
1
3
null
null
null
null
UTF-8
C++
false
false
2,904
cpp
#include "window.h" #include <QtGui> Window::Window(QWidget *parent) : QWidget(parent) { glwidget = new GLWidget(); QLabel* ambient_label = new QLabel("ambient"); QSlider* ambient_slider = new QSlider(); ambient_slider->setOrientation(Qt::Horizontal); ambient_slider->setRange(0, 5); QCheckBox* specular_on = new QCheckBox("specular"); QSlider* specular_slider = new QSlider(); specular_slider->setOrientation(Qt::Horizontal); specular_slider->setRange(0, 5); QLabel* light_label = new QLabel("light intensity"); QSlider* light_slider = new QSlider(); light_slider->setOrientation(Qt::Horizontal); light_slider->setRange(0, 5); light_slider->setSliderPosition(5); QGroupBox* light_group = new QGroupBox("light color"); QRadioButton* red = new QRadioButton("red"); QRadioButton* green = new QRadioButton("green"); QRadioButton* blue = new QRadioButton("blue"); QRadioButton* white = new QRadioButton("white"); white->setChecked(true); QHBoxLayout* hbox = new QHBoxLayout(); hbox->addWidget(red); hbox->addWidget(green); hbox->addWidget(blue); hbox->addWidget(white); light_group->setLayout(hbox); QGroupBox* light_type = new QGroupBox("light type"); QRadioButton* point = new QRadioButton("point light"); QRadioButton* direction = new QRadioButton("directional light"); direction->setChecked(true); QHBoxLayout* hbox2 = new QHBoxLayout(); hbox2->addWidget(point); hbox2->addWidget(direction); light_type->setLayout(hbox2); QVBoxLayout* vbox = new QVBoxLayout(); vbox->addWidget(glwidget); vbox->addWidget(ambient_label); vbox->addWidget(ambient_slider); vbox->addWidget(specular_on); vbox->addWidget(specular_slider); vbox->addWidget(light_label); vbox->addWidget(light_slider); vbox->addWidget(light_group); vbox->addWidget(light_type); connect(ambient_slider, SIGNAL(valueChanged(int)), glwidget, SLOT(ambient(int))); connect(specular_slider, SIGNAL(valueChanged(int)), glwidget, SLOT(specular(int))); connect(light_slider, SIGNAL(valueChanged(int)), glwidget, SLOT(lightIntensity(int))); connect(red, SIGNAL(clicked()), glwidget, SLOT(redLight())); connect(green, SIGNAL(clicked()), glwidget, SLOT(greenLight())); connect(blue, SIGNAL(clicked()), glwidget, SLOT(blueLight())); connect(white, SIGNAL(clicked()), glwidget, SLOT(whiteLight())); connect(point, SIGNAL(clicked()), glwidget, SLOT(pointLight())); connect(direction, SIGNAL(clicked()), glwidget, SLOT(directionalLight())); connect(specular_on, SIGNAL(clicked(bool)), glwidget, SLOT(specularOn(bool))); setLayout(vbox); } void Window::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Escape) close(); else QWidget::keyPressEvent(e); }
[ "nikedaud1@gmail.com" ]
nikedaud1@gmail.com
23c684ad86c29450fe7b271d7f5c6372e685ecd7
2cdf8fede9e76f919c4b74ee53d3080c0b82f3ab
/binary_search_tree.cpp
aceaa495eaca564f5e7c57570f593b381894269f
[]
no_license
beeender/tree_test
e08e95afd4830004f13d15e3ff034b82c641e08c
f44bdf29a9ac9dbaec8107e231604ad8354508f8
refs/heads/master
2020-06-06T08:06:10.582989
2014-08-27T08:01:31
2014-08-27T08:01:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,068
cpp
#include "ascii_tree.h" using namespace std; template<typename _T> class BinarySearchTree { private: struct _Node{ _Node *mLeft; _Node *mRight; _T mValue; _Node(const _T &value, _Node *left = nullptr, _Node *right = nullptr) : mLeft(left), mRight(right), mValue(value) { }; }; public: BinarySearchTree(); ~BinarySearchTree(); bool insert(const _T &v); void remove(const _T &v); _T &find_max(); _T &find_min(); _T &find(_T v); template<typename UnaryFun> void traverse(_Node *node, UnaryFun fun) { if (!node) return; traverse(node->mLeft, fun); fun(node); traverse(node->mRight, fun); }; class VisualTree : public visual_tree { public: VisualTree(BinarySearchTree &bst) : mNode(&(bst.mRoot)){}; ~VisualTree() {}; private: VisualTree(_Node **node) : mNode(node){}; const shared_ptr<visual_tree> visual_left() const { if (!(*mNode)->mLeft) return shared_ptr<visual_tree>(); return shared_ptr<visual_tree>(new VisualTree(&(*mNode)->mLeft)); }; const shared_ptr<visual_tree> visual_right() const { if (!(*mNode)->mRight) return shared_ptr<visual_tree>(); return shared_ptr<visual_tree>(new VisualTree(&(*mNode)->mRight)); } string visual_element() const { return to_string((*mNode)->mValue); } _Node **mNode; }; private: _Node **find_node(const _T v) { _Node **tmp = &mRoot; while (true) { if (!(*tmp)) return nullptr; if (v < (*tmp)->mValue) { tmp = &(*tmp)->mLeft; continue; } if ((*tmp)->mValue < v) { tmp = &(*tmp)->mRight; continue; } return tmp; } return nullptr; }; _Node *mRoot; }; template <typename _T> BinarySearchTree<_T>::BinarySearchTree() : mRoot(nullptr) { } template <typename _T> BinarySearchTree<_T>::~BinarySearchTree() { traverse(mRoot, [](_Node *node) { cout << node->mValue; delete node; }); } template <typename _T> bool BinarySearchTree<_T>::insert(const _T &v) { _Node **tmp = &mRoot; while (true) { if (!(*tmp)) { *tmp = new _Node(v); return true; } if (v < (*tmp)->mValue) { tmp = &((*tmp)->mLeft); continue; } if ((*tmp)->mValue < v) { tmp = &((*tmp)->mRight); continue; } break; } return false; } template <typename _T> void BinarySearchTree<_T>::remove(const _T &v) { _Node **tmp = find_node(v); if (!tmp) return; if (!(*tmp)->mLeft && !(*tmp)->mRight) { delete *tmp; *tmp = nullptr; return; } if (!(*tmp)->mLeft) { _Node *right = (*tmp)->mRight; delete *tmp; *tmp = right; return; } if (!(*tmp)->mRight) { _Node *left = (*tmp)->mLeft; delete *tmp; *tmp = left; return; } _Node **left = &(*tmp)->mRight; while ((*left)->mLeft) { left = &(*left)->mLeft; } (*left)->mLeft = (*tmp)->mLeft; if (*left == (*tmp)->mRight) { (*left)->mRight = nullptr; } else { (*left)->mRight = (*tmp)->mRight; } delete *tmp; *tmp = *left; *left = nullptr; } int main(int, char**) { BinarySearchTree<int> bst; bst.insert(1); shared_ptr<visual_tree> vt(new BinarySearchTree<int>::VisualTree(bst)); ascii_tree(vt).print(); bst.insert(5); ascii_tree(vt).print(); bst.insert(4); ascii_tree(vt).print(); bst.insert(9); ascii_tree(vt).print(); bst.insert(0); ascii_tree(vt).print(); bst.insert(-1); ascii_tree(vt).print(); bst.insert(-9); ascii_tree(vt).print(); bst.remove(1); ascii_tree(vt).print(); }
[ "chenmulong@gmail.com" ]
chenmulong@gmail.com
24716db41a5b9853bd3f484739cec68d8f2e14ce
2f4d478b72a6963ee0f42dd9cb6c1cfa4e31102d
/include/Application.hpp
2f6cf1e2414d28ea8b3a0a04ef0d5a919ac2f7e8
[]
no_license
Edai/TerrainEngine
5edbfd5f268f8b3ba005731571ac8ad060e427d8
0047b42734e405c3998418b19c84eeb8e1b39b5f
refs/heads/master
2020-03-16T18:16:34.239759
2018-05-12T18:27:45
2018-05-12T18:27:45
132,866,597
1
1
null
null
null
null
UTF-8
C++
false
false
867
hpp
// // Created by edai on 19/03/18. // #ifndef ASSIGNMENT_APPLICATION_HPP #define ASSIGNMENT_APPLICATION_HPP #include <GL/glew.h> #include <GL/gl.h> #include <GL/glut.h> #include <GL/freeglut.h> #include <iostream> #include <SOIL/SOIL.h> #include <unistd.h> #include <cstdlib> #include <getopt.h> #include <string> #define DEFAULT_WIDTH 960 #define DEFAULT_HEIGHT 960 #define WINDOWPOS_X 500 #define WINDOWPOS_Y 50 #define WINDOW_TITLE "Valentin KAO - 2017280242" struct Options { std::string window_name; int width; int height; public: Options() { width = DEFAULT_WIDTH; height = DEFAULT_HEIGHT; } }; class Application { public: static bool Parse(Options *, int, char**); static int Start(int, char **); protected: Application(); ~Application(); }; #endif //ASSIGNMENT2_APPLICATION_HPP
[ "valentin.kao@epitech.eu" ]
valentin.kao@epitech.eu
5b0c931a0160a2feae47d0a8970477b72e13493a
549028675a0450e1f95f24bacc4839b928c82327
/world/test/test_bmat_arduino.cpp
a0191d8d5b3acb6301d4acd2c2d0cca6b4e450d8
[ "MIT" ]
permissive
blobrobots/libs
84dcc851f00b57ef9c7f1a8432a2c502fbaa33df
cc11f56bc4e1112033e8b7352e5653f98f1bfc13
refs/heads/master
2020-12-25T17:25:58.727120
2018-05-02T11:01:43
2018-05-02T11:01:43
26,779,741
1
0
null
null
null
null
UTF-8
C++
false
false
368
cpp
/********* blob robotics 2014 ********* * title: test_arduino.cpp * brief: test for comms library (arduino) * author: adrian jimenez-gonzalez * e-mail: blob.robotics@gmail.com /*************************************/ #include "Arduino.h" #include "blob/matrix.h" void setup() { Serial.begin(115200); while (!Serial); } void loop() { delay(5000); }
[ "ajimenez@ixion.es" ]
ajimenez@ixion.es
f694956b8fa5b154360c0e58317712eef2d04574
6e8c1949a3c0189e2792b5a841c736409ef16ca0
/sdhash-src/sdhash.cc
e9636bafa17be2124a702aa12173449c0a9f175a
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
zieckey/sdhash
d8ac12ebdc93b14ba4142fd7ddb49b4a9558f5e6
a9ded3bf9a7d38f7add360ea5031443bf22fa4e4
refs/heads/master
2021-01-01T05:51:33.994080
2013-12-12T08:01:24
2013-12-12T08:01:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,952
cc
/** * sdhash: Command-line interface for file hashing * authors: Vassil Roussev, Candice Quates */ #include "../sdbf/sdbf_class.h" #include "../sdbf/sdbf_defines.h" #include "../sdbf/sdbf_set.h" #include "sdhash_threads.h" #include "sdhash.h" #include "version.h" #include "boost/filesystem.hpp" #include "boost/program_options.hpp" #include "boost/lexical_cast.hpp" #include <fstream> namespace fs = boost::filesystem; namespace po = boost::program_options; std::string read_file(const char* fname) { int length; char * buffer; ifstream is; is.open (fname, ios::binary ); // get length of file: is.seekg (0, ios::end); length = is.tellg(); is.seekg (0, ios::beg); // allocate memory: buffer = new char [length]; // read data as a block: is.read (buffer,length); is.close(); std::string r(buffer,length); delete [] buffer; return r; } double utcsecond() { struct timeval tv; gettimeofday( &tv, NULL ); return (double)(tv.tv_sec) + ((double)(tv.tv_usec))/1000000.0f; } // Global parameter configuration defaults sdbf_parameters_t sdbf_sys = { 1, // threads 64, // entr_win_size 256, // BF size 4*KB, // block_size 64, // pop_win_size 16, // threshold _MAX_ELEM_COUNT, // max_elem 1, // output_threshold FLAG_OFF, // warnings -1, // dd block size 0, // sample size off 0, // verbose mode off 128*MB, // segment size NULL // optional filename }; /** sdhash program main */ int main( int argc, char **argv) { uint32_t i, j, k, file_cnt; int rcf; time_t hash_start; time_t hash_end; string config_file; string listingfile; string input_name; string output_name; string segment_size; string idx_size; string idx_dir; // where to find indexes uint32_t index_size = 16*MB; // default? vector<string> inputlist; po::variables_map vm; po::options_description config("Configuration"); try { // Declare a group of options that will be // allowed both on command line and in // config file config.add_options() ("config-file,C", po::value<string>(&config_file)->default_value("sdhash.cfg"), "name of config file") ("hash-list,f",po::value<std::string>(&listingfile),"generate SDBFs from list of filenames") ("deep,r", "generate SDBFs from directories and files") ("gen-compare,g", "generate SDBFs and compare all pairs") ("compare,c","compare all pairs in SDBF file, or compare two SDBF files to each other") ("benchmark,B","compare two SDBF files to each other, and do a benchmark") ("threshold,t",po::value<int32_t>(&sdbf_sys.output_threshold)->default_value(1),"only show results >=threshold") ("block-size,b",po::value<int32_t>(&sdbf_sys.dd_block_size),"hashes input files in nKB blocks") ("threads,p",po::value<uint32_t>(&sdbf_sys.thread_cnt)->default_value(1),"compute threads to use") ("sample-size,s",po::value<uint32_t>(&sdbf_sys.sample_size)->default_value(0),"sample N filters for comparisons") ("segment-size,z",po::value<std::string>(&segment_size),"break files into segments before hashing") ("name,n",po::value<std::string>(&input_name),"set SDBF name for stdin mode") ("output,o",po::value<std::string>(&output_name),"set output filename") ("heat-map,m", "show a heat map of BF matches") ("validate","parse SDBF file to check if it is valid") ("index","generate indexes while hashing") ("index-dir",po::value<std::string>(&idx_dir),"compare against reference indexes") ("search-all","match at file level, all matching sets") ("search-first","match at file level, first match") ("basename","print set matches with only base filenames") ("warnings,w","turn on warnings") ("verbose","debugging and progress output") ("version","show version info") ("help,h","produce help message") ; // options that do not need to be in help message po::options_description hidden("Hidden"); hidden.add_options() ("input-files", po::value<vector<std::string> >(&inputlist), "input file") ; po::options_description cmdline_options; cmdline_options.add(config).add(hidden); po::options_description config_file_options; config_file_options.add(config); // setup for list of files on command line po::positional_options_description p; p.add("input-files", -1); store(po::command_line_parser(argc, argv). options(cmdline_options).positional(p).run(), vm); notify(vm); ifstream ifs(config_file.c_str()); if (ifs) { store(parse_config_file(ifs, config_file_options), vm); notify(vm); } if (vm.count("help")) { cout << VERSION_INFO << ", rev " << REVISION << endl; cout << "Usage: sdhash <options> <source files>|<hash files>"<< endl; cout << config << endl; return 0; } if (vm.count("version")) { cout << VERSION_INFO << ", rev " << REVISION << endl; cout << " http://sdhash.org, license Apache v2.0" << endl; return 0; } if (vm.count("warnings")) { sdbf_sys.warnings = 1; } if (vm.count("verbose")) { sdbf_sys.warnings = 1; sdbf_sys.verbose = 1; } if (vm.count("segment-size")) { sdbf_sys.segment_size = (boost::lexical_cast<uint64_t>(segment_size)) * MB; } if (vm.count("name")) { sdbf_sys.filename=(char*)input_name.c_str(); } if (vm.count("index") && !vm.count("output")) { cerr << "sdhash: ERROR: indexing requires output base filename " << endl; return -1; } } catch(exception& e) { cout << e.what() << "\n"; return 0; } // Initialization // set up sdbf object with current options sdbf::config = new sdbf_conf(sdbf_sys.thread_cnt, sdbf_sys.warnings, _MAX_ELEM_COUNT, _MAX_ELEM_COUNT_DD); // possible two sets to load for comparisons sdbf_set *set1 = new sdbf_set(); sdbf_set *set2 = new sdbf_set(); // indexing search support std::vector<bloom_filter *> indexlist; std::vector<sdbf_set *> setlist; index_info *info=(index_info*)malloc(sizeof(index_info)); info->index=NULL; info->indexlist=&indexlist; info->setlist=&setlist; info->search_deep=true; if (vm.count("search-first")) { info->search_first=true; info->search_deep=true; } else info->search_first=false; if (vm.count("basename")) info->basename=true; else info->basename=false; if (vm.count("index-dir")) { if (sdbf_sys.verbose) cerr << "loading indexes "; if (fs::is_directory(idx_dir.c_str())) { for (fs::directory_iterator itr(idx_dir.c_str()); itr!=fs::directory_iterator(); ++itr) { if (fs::is_regular_file(itr->status()) && (itr->path().extension().string() == ".idx")) { bloom_filter *indextest=new bloom_filter(itr->path().string()); if (sdbf_sys.verbose && (indexlist.size() % 5 == 0)) cerr<< "." ; indexlist.push_back(indextest); sdbf_set *tmp=new sdbf_set((idx_dir+"/"+itr->path().stem().string()).c_str()); setlist.push_back(tmp); tmp->index=indextest; } } } if (sdbf_sys.verbose) cerr << "done"<< endl; } // Perform all-pairs comparison if (vm.count("compare")) { if (inputlist.size()==1) { std::string resultlist; // load first set try { set1=new sdbf_set(inputlist[0].c_str()); } catch (int e) { cerr << "sdhash: ERROR: Could not load SDBF file "<< inputlist[0] << ". Exiting"<< endl; return -1; } resultlist=set1->compare_all(sdbf_sys.output_threshold); cout << resultlist; } else if (inputlist.size()==2) { try { set1=new sdbf_set(inputlist[0].c_str()); } catch (int e) { cerr << "sdhash: ERROR: Could not load SDBF file "<< inputlist[0] << ". Exiting"<< endl; return -1; } // load second set for comparison try { set2=new sdbf_set(inputlist[1].c_str()); } catch (int e) { cerr << "sdhash: ERROR: Could not load SDBF file "<< inputlist[1] << ". Exiting"<< endl; return -1; } std::string resultlist; resultlist=set1->compare_to(set2,sdbf_sys.output_threshold, sdbf_sys.sample_size); cout << resultlist; } else { cerr << "sdhash: ERROR: Comparison requires 1 or 2 arguments." << endl; delete set1; delete set2; return -1; } int n; if (set1!=NULL) { for (n=0;n< set1->size(); n++) delete set1->at(n); delete set1; } if (set2!=NULL) { for (n=0;n< set2->size(); n++) delete set2->at(n); delete set2; } return 0; } // Perform tow comparison if (vm.count("benchmark")) { if (inputlist.size()==2) { try { set1=new sdbf_set(inputlist[0].c_str()); } catch (int e) { cerr << "sdhash: ERROR: Could not load SDBF file "<< inputlist[0] << ". Exiting"<< endl; return -1; } // load second set for comparison std::string resultlist; std::string against_sdbf_buffer = read_file(inputlist[1].c_str()); double begin = utcsecond(); int loop = 1000; for (int i = 0; i < loop; ++i) { set2=new sdbf_set(against_sdbf_buffer.data(), against_sdbf_buffer.size()); resultlist=set1->compare_to(set2,sdbf_sys.output_threshold, sdbf_sys.sample_size); sdbf_set::destory(set2); } double end = utcsecond(); cout << "cost=" << end - begin << " qps=" << loop/(end-begin) << " loop=" << loop << " result:" << resultlist; //sdbf_set *set2_cmp=new sdbf_set(inputlist[1].c_str()); //resultlist=set1->compare_to(set2_cmp,sdbf_sys.output_threshold, sdbf_sys.sample_size); //cout << "result:" << resultlist; //cout << "new:set2:[" << set2 << "]\n"; //cout << "old:set2:[" << set2_cmp << "]\n"; } else { cerr << "sdhash: ERROR: Comparison requires 1 or 2 arguments." << endl; delete set1; delete set2; return -1; } int n; if (set1!=NULL) { for (n=0;n< set1->size(); n++) delete set1->at(n); delete set1; } if (set2!=NULL) { for (n=0;n< set2->size(); n++) delete set2->at(n); delete set2; } return 0; } // validate hashes if (vm.count("validate")) { for (i=0; i< inputlist.size(); i++) { // load each set and throw it away if (!fs::is_regular_file(inputlist[i])) { cout << "sdhash: ERROR file " << inputlist[i] << " not readable or not found." << endl; continue; } try { set1=new sdbf_set(inputlist[i].c_str()); cout << "sdhash: file " << inputlist[i]; cout << " SDBFs valid, contains " << set1->size() << " hashes." << endl; cout << "contains "<< set1->filter_count() << " bloom filters." << endl; cout << set1->input_size() << " total data size. " << endl; } catch (int e) { cerr << "sdhash: ERROR: Could not load file of SDBFs, "<< inputlist[i] << " is empty or invalid."<< endl; continue; } if (set1!=NULL) { for (int n=0;n< set1->size(); n++) delete set1->at(n); delete set1; } } return 0; } std::vector<string> small; std::vector<string> large; // Otherwise we are hashing. Make sure we have files. if (vm.count("input-files")) { // process stdin -- look for - arg if (inputlist.size()==1 && !inputlist[0].compare("-")) { if (sdbf_sys.segment_size == 0) { sdbf_sys.segment_size = 128*MB; // not currently allowing no segments } if (sdbf_sys.dd_block_size > 0) { set1=sdbf_hash_stdin(info); } else { // block size is always going to be defaulted in this case sdbf_sys.dd_block_size = 16; set1=sdbf_hash_stdin(info); } } else { // input list iterator if (sdbf_sys.verbose) cerr << "sdhash: Building list of files to be hashed" << endl; vector<string>::iterator inp; for (inp=inputlist.begin(); inp < inputlist.end(); inp++) { // if recursive mode, then check directories as well if ( vm.count("deep") ) { try { if (fs::is_directory(*inp)) for ( fs::recursive_directory_iterator end, it(*inp); it!= end; ++it ) if (boost::filesystem::is_regular_file(*it)) { if (sdbf_sys.verbose) cerr << "sdhash: adding file to hashlist "<< it->path().string() << endl; if (fs::file_size(*it) < 16*MB) small.push_back(it->path().string()); else large.push_back(it->path().string()); if ((fs::file_size(it->path()) >= sdbf_sys.segment_size) && sdbf_sys.warnings ) { cerr << "Warning: file " << it->path().string() << " will be segmented in "; cerr << sdbf_sys.segment_size/MB << "MB chunks prior to hashing."<< endl; } } } catch (fs::filesystem_error err) { cerr << "sdhash: ERROR: Filesystem problem in recursive searching " ; cerr << err.what() << endl; continue; } } // always check if regular file. if (fs::is_regular_file(*inp)) { if (sdbf_sys.verbose) cerr << "sdhash: adding file to hashlist "<< *inp << endl; if (fs::file_size(*inp) < 16*MB) small.push_back(*inp); else large.push_back(*inp); if ((fs::file_size(*inp) >= sdbf_sys.segment_size) && sdbf_sys.warnings ) { cerr << "sdhash: Warning: file " << *inp << " will be segmented in "; cerr << sdbf_sys.segment_size/MB << "MB chunks prior to hashing."<< endl; } } } } } else if (vm.count("hash-list")) { // hash from a list in a file struct stat stat_res; if( stat( listingfile.c_str(), &stat_res) != 0) { cerr << "sdhash: ERROR: Could not access input file "<< listingfile<< ". Exiting." << endl; return -1; } processed_file_t *mlist=process_file(listingfile.c_str(), 1, sdbf_sys.warnings); if (!mlist) { cerr << "sdhash: ERROR: Could not access input file "<< listingfile<< ". Exiting." << endl; return -1; } i=0; std::istringstream fromfile((char*)mlist->buffer); std::string fname; while (std::getline(fromfile,fname)) { if (fs::is_regular_file(fname)) { if (fs::file_size(fname) < 16*MB) { small.push_back(fname); } else { large.push_back(fname); } if ((fs::file_size(fname) >= sdbf_sys.segment_size) && sdbf_sys.warnings ) { cerr << "sdhash: Warning: file " << fname << " will be segmented in "; cerr << sdbf_sys.segment_size/MB << "MB chunks prior to hashing."<< endl; } } } } else { cout << VERSION_INFO << ", rev " << REVISION << endl; cout << " http://sdhash.org, license Apache v2.0" << endl; cout << "Usage: sdhash <options> <source files>|<hash files>"<< endl; cout << config << endl; return 0; } // Having built our lists of small/large files, hash them. int smallct=small.size(); int largect=large.size(); // from here, if we are indexing on creation, build things differently. if (vm.count("index")) { delete set1; int status = hash_index_stringlist(small,output_name); int status2 = hash_index_stringlist(large,output_name); return 0; } else { hash_start=time(0); if (smallct > 0) { if (sdbf_sys.verbose) cerr << "sdhash: hashing small files"<< endl; char **smalllist=(char **)alloc_check(ALLOC_ONLY,smallct*sizeof(char*),"main", "filename list", ERROR_EXIT); for (i=0; i < smallct ; i++) { smalllist[i]=(char*)alloc_check(ALLOC_ONLY,small[i].length()+1, "main", "filename", ERROR_EXIT); strncpy(smalllist[i],small[i].c_str(),small[i].length()+1); } if (sdbf_sys.dd_block_size < 1 ) { if (vm.count("gen-compare") || vm.count("output")||vm.count("index-dir")) // if we need to save this set for comparison sdbf_hash_files( smalllist, smallct, sdbf_sys.thread_cnt,set1, info); else sdbf_hash_files( smalllist, smallct, sdbf_sys.thread_cnt,NULL, info); } else { if (vm.count("gen-compare") || vm.count("output")||vm.count("index-dir")) sdbf_hash_files_dd( smalllist, smallct, sdbf_sys.dd_block_size*KB,sdbf_sys.segment_size, set1, info); else sdbf_hash_files_dd( smalllist, smallct, sdbf_sys.dd_block_size*KB,sdbf_sys.segment_size, NULL, info); } } if (largect > 0) { if (sdbf_sys.verbose) cerr << "sdhash: hashing large files"<< endl; char **largelist=(char **)alloc_check(ALLOC_ONLY,largect*sizeof(char*),"main", "filename list", ERROR_EXIT); for (i=0; i < largect ; i++) { largelist[i]=(char*)alloc_check(ALLOC_ONLY,large[i].length()+1, "main", "filename", ERROR_EXIT); strncpy(largelist[i],large[i].c_str(),large[i].length()+1); } if (sdbf_sys.dd_block_size == 0 ) { if (vm.count("gen-compare")) // if we need to save this set for comparison sdbf_hash_files( largelist, largect, sdbf_sys.thread_cnt,set1, info); else sdbf_hash_files( largelist, largect, sdbf_sys.thread_cnt,NULL, info); } else { if (sdbf_sys.dd_block_size == -1) { if (sdbf_sys.warnings || sdbf_sys.verbose) cerr << "sdhash: Warning: files over 16MB are being hashed in block mode. Use -b 0 to disable." << endl; if (vm.count("gen-compare")|| vm.count("output") ||vm.count("index-dir")) // if we need to save this set for comparison sdbf_hash_files_dd( largelist, largect, 16*KB,sdbf_sys.segment_size, set1, info); else sdbf_hash_files_dd( largelist, largect, 16*KB,sdbf_sys.segment_size, NULL, info); } else { if (vm.count("gen-compare")||vm.count("output") ||vm.count("index-dir")) // if we need to save this set for comparison sdbf_hash_files_dd( largelist, largect, sdbf_sys.dd_block_size*KB,sdbf_sys.segment_size, set1, info); else sdbf_hash_files_dd( largelist, largect, sdbf_sys.dd_block_size*KB,sdbf_sys.segment_size, NULL, info); } } } // if large files exist hash_end=time(0); if (sdbf_sys.verbose) cerr << hash_end - hash_start << " seconds hash time" << endl; } // if not indexing // print it out if we've been asked to if (vm.count("gen-compare")) { string resultlist; resultlist=set1->compare_all(sdbf_sys.output_threshold); cout << resultlist; } else { if (vm.count("output")) { if (vm.count("index-dir")) { string output_indexr = output_name + ".idx-result"; std::filebuf fb; fb.open (output_indexr.c_str(),ios::out|ios::binary); if (fb.is_open()) { std::ostream os(&fb); os << set1->index_results(); fb.close(); } else { cerr << "sdhash: ERROR cannot write to file " << output_indexr<< endl; return -1; } } else { // search-index is destructive, so we do not make actual sdhashes in this case output_name= output_name+".sdbf"; std::filebuf fb; fb.open (output_name.c_str(),ios::out|ios::binary); if (fb.is_open()) { std::ostream os(&fb); os << set1; fb.close(); } else { cerr << "sdhash: ERROR cannot write to file " << output_name<< endl; return -1; } } } else { if (vm.count("index-dir")) cerr << set1->index_results(); else cout << set1; } } if (setlist.size() > 0) { for (int n=0;n< setlist.size(); n++) { for (int m=0;m< setlist.at(n)->size(); m++) { delete setlist.at(n)->at(m); } delete setlist.at(n)->index; delete setlist.at(n); } } if (set1!=NULL) { for (int n=0;n< set1->size(); n++) delete set1->at(n); delete set1; } if (set2!=NULL) { for (int n=0;n< set2->size(); n++) delete set2->at(n); delete set2; } if (info) free(info); return 0; }
[ "zieckey@gmail.com" ]
zieckey@gmail.com
1bae5b553cdc096302ded0be25d76c188d3b890c
d3266dc4591e3fb38e7a5eb3c7afc457406a571e
/Master-CRAFT/include/mastercraft/cube/SuperChunk.hpp
88d192abb4ab2c86a06575bf042d78212bba3690
[]
no_license
elisehardy/Kill-mob
9e77c9dc78ce8b6b0eea997a69f691e47636ce1f
390b50b7b6464911d60c77c2fc44fe007f0d5ce8
refs/heads/master
2021-03-26T01:09:59.017629
2020-03-21T09:24:07
2020-03-21T09:24:07
247,661,406
0
0
null
null
null
null
UTF-8
C++
false
false
1,683
hpp
#ifndef MASTERCRAFT_SUPERCHUNK_HPP #define MASTERCRAFT_SUPERCHUNK_HPP #include <glm/glm.hpp> #include <mastercraft/cube/Chunk.hpp> #include <mastercraft/shader/Shader.hpp> #include <mastercraft/util/INonCopyable.hpp> #include <mastercraft/game/ConfigManager.hpp> namespace mastercraft::cube { class SuperChunk : public util::INonCopyable { public: static constexpr GLint CHUNK_X = 2; static constexpr GLint CHUNK_Y = 16; static constexpr GLint CHUNK_Z = 2; static constexpr GLint CHUNK_SIZE = CHUNK_X * CHUNK_Y * CHUNK_Z; static constexpr GLint X = Chunk::X * CHUNK_X; static constexpr GLint Y = Chunk::Y * CHUNK_Y; static constexpr GLint Z = Chunk::Z * CHUNK_Z; static constexpr GLint SIZE = CHUNK_SIZE * Chunk::SIZE; static_assert(game::ConfigManager::GEN_MAX_HEIGHT <= Y); private: Chunk chunks[CHUNK_X][CHUNK_Y][CHUNK_Z]; glm::ivec3 position; GLboolean modified; GLuint count; public: SuperChunk() = default; explicit SuperChunk(glm::ivec3 position); SuperChunk(GLuint x, GLuint y, GLuint z); ~SuperChunk() = default; CubeType get(GLuint x, GLuint y, GLuint z); void set(GLuint x, GLuint y, GLuint z, CubeType type); void touch(); GLuint update(); GLuint render(bool alpha); }; } #endif //MASTERCRAFT_SUPERCHUNK_HPP
[ "elise.hardy-bererd@laposte.net" ]
elise.hardy-bererd@laposte.net
38b685e1d6c7abf9835ccbf3239828c8a81a9323
5d26dd63026c7db87740a073dbac420e2b3588d4
/Game Original/vampire.cc
b87784744b5deb4e21745c054c0dfb0a2b30d346
[]
no_license
DhruvaAlam/LegendOfZeldaCommandLineEdition
8ae3c7730656cca885eddbd1ada0b794a65f9f3b
56642bc183a5362cff35b3540818013619181f90
refs/heads/master
2021-03-19T14:12:17.399847
2016-12-03T06:55:16
2016-12-03T06:55:16
75,457,388
1
0
null
null
null
null
UTF-8
C++
false
false
209
cc
#include "boardobject.h" #include "character.h" #include "enemy.h" #include "vampire.h" #include "tile.h" using namespace std; Vampire::Vampire(Tile* t): Enemy{'V', t, 50, 25, 25} {} Vampire::~Vampire() {}
[ "dhalam@blackberry.com" ]
dhalam@blackberry.com
fa8f945d5983b3cb8925d8c974ffbb519b9022c0
f788bde0757cc50ea7c825e049d9652d6700ba37
/CamMgrDll/NetCamMgr.cpp
f9312f74a6e3d3f34018c924476ed6b6a61c9ac8
[]
no_license
15831944/CCD_Project
235a6c05dfc790f18aa1b66394158b8cbadc7bf2
21fd27a9638d698002c3b0231366337a770aaa25
refs/heads/master
2023-02-27T07:45:16.250515
2021-02-04T09:44:08
2021-02-04T09:44:08
486,609,060
0
1
null
null
null
null
GB18030
C++
false
false
3,603
cpp
// NetCamMgr.cpp : 实现文件 // #include "stdafx.h" #include "NetCamMgr.h" #include "afxdialogex.h" // CNetCamMgr 对话框 IMPLEMENT_DYNAMIC(CNetCamMgr, CTpLayerWnd) CNetCamMgr::CNetCamMgr(CWnd* pParent /*=NULL*/) : CTpLayerWnd(CNetCamMgr::IDD, pParent) , m_nMethod(NET_CAM_CHANGE_BY_INDEX) , m_nMethodBkup(NET_CAM_CHANGE_BY_INDEX) { m_NetCam.nNet = 0; m_NetCam.nCam = 0; } CNetCamMgr::CNetCamMgr(UINT nIDTemplate, CWnd * pParent/* = nullptr*/) : CTpLayerWnd(nIDTemplate, pParent) , m_nMethod(NET_CAM_CHANGE_BY_INDEX) , m_nMethodBkup(NET_CAM_CHANGE_BY_INDEX) { m_NetCam.nNet = 0; m_NetCam.nCam = 0; } CNetCamMgr::~CNetCamMgr() { } void CNetCamMgr::DoDataExchange(CDataExchange* pDX) { CTpLayerWnd::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CNetCamMgr, CTpLayerWnd) END_MESSAGE_MAP() BEGIN_EVENTSINK_MAP(CNetCamMgr, CTpLayerWnd) ON_EVENT(CNetCamMgr, IDC_RD_NET_CAM_INDEX, 1, CNetCamMgr::StatusChangedRdNetCamIndex, VTS_BOOL) ON_EVENT(CNetCamMgr, IDC_RD_NET_CAM_MAC, 1, CNetCamMgr::StatusChangedRdNetCamMac, VTS_BOOL) END_EVENTSINK_MAP() // CNetCamMgr 消息处理程序 BOOL CNetCamMgr::OnInitDialog() { CTpLayerWnd::OnInitDialog(); // TODO: 在此添加额外的初始化 m_NetCamBkup = m_NetCam; _UpdateUi(); LockCtrls(-1); return TRUE; // return TRUE unless you set the focus to a control // 异常: OCX 属性页应返回 FALSE } void CNetCamMgr::OnOK() { m_NetCam.nNet = ((CBL_Edit *)(GetDlgItem(IDC_EDIT_NET_CAM_NET)))->GetIntValue() - 1; m_NetCam.nCam = ((CBL_Edit *)(GetDlgItem(IDC_EDIT_NET_CAM_CAM)))->GetIntValue() - 1; m_NetCam.strMac = ((CBL_Edit *)(GetDlgItem(IDC_EDIT_NET_CAM_MAC)))->GetValueText(); m_NetCam.strMac.MakeUpper(); m_NetCamBkup.strMac.MakeUpper(); if (m_nMethod != m_nMethodBkup || m_NetCam.nNet != m_NetCamBkup.nNet || m_NetCam.nCam != m_NetCamBkup.nCam || m_NetCam.strMac != m_NetCamBkup.strMac) { _FileDirty(TRUE); CTpLayerWnd::OnOK(); } else { OnCancel(); } } void CNetCamMgr::LockCtrls(int nLock) { const BOOL bLocked = _GetLockState(nLock, PSD_LEVEL_TE); const BOOL bEnable = !bLocked; for (int i = 0; i < NET_CAM_CHAGE_METHOD_SUM; i++) { GetDlgItem(IDC_RD_NET_CAM_INDEX + i)->EnableWindow(bEnable); } ((CBL_Edit *)GetDlgItem(IDC_EDIT_NET_CAM_NET))->SetReadOnly(NET_CAM_CHANGE_BY_INDEX != m_nMethod); ((CBL_Edit *)GetDlgItem(IDC_EDIT_NET_CAM_CAM))->SetReadOnly(NET_CAM_CHANGE_BY_INDEX != m_nMethod); ((CBL_Edit *)GetDlgItem(IDC_EDIT_NET_CAM_MAC))->SetReadOnly(NET_CAM_CHANGE_BY_MAC != m_nMethod); m_BtBaseOk.EnableWindow(bEnable); } void CNetCamMgr::_UpdateUi(void) { for (int i = 0; i < NET_CAM_CHAGE_METHOD_SUM; i++) { ((CBL_Radio *)(GetDlgItem(IDC_RD_NET_CAM_INDEX + i)))->SetSelect(i == m_nMethod); } ((CBL_Edit *)(GetDlgItem(IDC_EDIT_NET_CAM_NET)))->SetValue(m_NetCam.nNet + 1); ((CBL_Edit *)(GetDlgItem(IDC_EDIT_NET_CAM_CAM)))->SetValue(m_NetCam.nCam + 1); ((CBL_Edit *)(GetDlgItem(IDC_EDIT_NET_CAM_MAC)))->SetValueText(m_NetCam.strMac); } void CNetCamMgr::StatusChangedRdNetCamIndex(BOOL bNewStatus) { // TODO: 在此处添加消息处理程序代码 m_nMethod = NET_CAM_CHANGE_BY_INDEX; for (int i = 0; i < NET_CAM_CHAGE_METHOD_SUM; i++) { ((CBL_Radio *)(GetDlgItem(IDC_RD_NET_CAM_INDEX + i)))->SetSelect(i == m_nMethod); } LockCtrls(-1); } void CNetCamMgr::StatusChangedRdNetCamMac(BOOL bNewStatus) { // TODO: 在此处添加消息处理程序代码 m_nMethod = NET_CAM_CHANGE_BY_MAC; for (int i = 0; i < NET_CAM_CHAGE_METHOD_SUM; i++) { ((CBL_Radio *)(GetDlgItem(IDC_RD_NET_CAM_INDEX + i)))->SetSelect(i == m_nMethod); } LockCtrls(-1); }
[ "463115211@qq.com" ]
463115211@qq.com
54e20d6a61dcc7a8da6881f965d5bd10e4c7b1dc
f4e17640afef6d1b4d4a85f583a90e37f705dbd5
/B2G/gecko/netwerk/protocol/ftp/nsFtpConnectionThread.cpp
547cb42bc6d8c09133e15eda4cef82adef3253d8
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
wilebeast/FireFox-OS
d370362916f0c5a5408fa08285dbf4779f8b5eb3
43067f28711d78c429a1d6d58c77130f6899135f
refs/heads/master
2016-09-05T22:06:54.838558
2013-09-03T13:49:21
2013-09-03T13:49:21
12,572,236
4
3
null
null
null
null
UTF-8
C++
false
false
75,009
cpp
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* vim:set tw=80 ts=4 sts=4 sw=4 et cin: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <limits.h> #include <ctype.h> #include "prprf.h" #include "prlog.h" #include "prtime.h" #include "nsIOService.h" #include "nsFTPChannel.h" #include "nsFtpConnectionThread.h" #include "nsFtpControlConnection.h" #include "nsFtpProtocolHandler.h" #include "ftpCore.h" #include "netCore.h" #include "nsCRT.h" #include "nsEscape.h" #include "nsMimeTypes.h" #include "nsNetUtil.h" #include "nsThreadUtils.h" #include "nsStreamUtils.h" #include "nsICacheService.h" #include "nsIURL.h" #include "nsISocketTransport.h" #include "nsIStreamListenerTee.h" #include "nsIPrefService.h" #include "nsIPrefBranch.h" #include "nsIStringBundle.h" #include "nsAuthInformationHolder.h" #include "nsICharsetConverterManager.h" #include "nsIProtocolProxyService.h" #include "nsICancelable.h" #if defined(PR_LOGGING) extern PRLogModuleInfo* gFTPLog; #endif #define LOG(args) PR_LOG(gFTPLog, PR_LOG_DEBUG, args) #define LOG_ALWAYS(args) PR_LOG(gFTPLog, PR_LOG_ALWAYS, args) // remove FTP parameters (starting with ";") from the path static void removeParamsFromPath(nsCString& path) { int32_t index = path.FindChar(';'); if (index >= 0) { path.SetLength(index); } } NS_IMPL_ISUPPORTS_INHERITED5(nsFtpState, nsBaseContentStream, nsIInputStreamCallback, nsITransportEventSink, nsICacheListener, nsIRequestObserver, nsIProtocolProxyCallback) nsFtpState::nsFtpState() : nsBaseContentStream(true) , mState(FTP_INIT) , mNextState(FTP_S_USER) , mKeepRunning(true) , mReceivedControlData(false) , mTryingCachedControl(false) , mRETRFailed(false) , mFileSize(UINT64_MAX) , mServerType(FTP_GENERIC_TYPE) , mAction(GET) , mAnonymous(true) , mRetryPass(false) , mStorReplyReceived(false) , mInternalError(NS_OK) , mReconnectAndLoginAgain(false) , mCacheConnection(true) , mPort(21) , mAddressChecked(false) , mServerIsIPv6(false) , mControlStatus(NS_OK) , mDeferredCallbackPending(false) { LOG_ALWAYS(("FTP:(%x) nsFtpState created", this)); // make sure handler stays around NS_ADDREF(gFtpHandler); } nsFtpState::~nsFtpState() { LOG_ALWAYS(("FTP:(%x) nsFtpState destroyed", this)); if (mProxyRequest) mProxyRequest->Cancel(NS_ERROR_FAILURE); // release reference to handler nsFtpProtocolHandler *handler = gFtpHandler; NS_RELEASE(handler); } // nsIInputStreamCallback implementation NS_IMETHODIMP nsFtpState::OnInputStreamReady(nsIAsyncInputStream *aInStream) { LOG(("FTP:(%p) data stream ready\n", this)); // We are receiving a notification from our data stream, so just forward it // on to our stream callback. if (HasPendingCallback()) DispatchCallbackSync(); return NS_OK; } void nsFtpState::OnControlDataAvailable(const char *aData, uint32_t aDataLen) { LOG(("FTP:(%p) control data available [%u]\n", this, aDataLen)); mControlConnection->WaitData(this); // queue up another call if (!mReceivedControlData) { // parameter can be null cause the channel fills them in. OnTransportStatus(nullptr, NS_NET_STATUS_BEGIN_FTP_TRANSACTION, 0, 0); mReceivedControlData = true; } // Sometimes we can get two responses in the same packet, eg from LIST. // So we need to parse the response line by line nsCString buffer = mControlReadCarryOverBuf; // Clear the carryover buf - if we still don't have a line, then it will // be reappended below mControlReadCarryOverBuf.Truncate(); buffer.Append(aData, aDataLen); const char* currLine = buffer.get(); while (*currLine && mKeepRunning) { int32_t eolLength = strcspn(currLine, CRLF); int32_t currLineLength = strlen(currLine); // if currLine is empty or only contains CR or LF, then bail. we can // sometimes get an ODA event with the full response line + CR without // the trailing LF. the trailing LF might come in the next ODA event. // because we are happy enough to process a response line ending only // in CR, we need to take care to discard the extra LF (bug 191220). if (eolLength == 0 && currLineLength <= 1) break; if (eolLength == currLineLength) { mControlReadCarryOverBuf.Assign(currLine); break; } // Append the current segment, including the LF nsAutoCString line; int32_t crlfLength = 0; if ((currLineLength > eolLength) && (currLine[eolLength] == nsCRT::CR) && (currLine[eolLength+1] == nsCRT::LF)) { crlfLength = 2; // CR +LF } else { crlfLength = 1; // + LF or CR } line.Assign(currLine, eolLength + crlfLength); // Does this start with a response code? bool startNum = (line.Length() >= 3 && isdigit(line[0]) && isdigit(line[1]) && isdigit(line[2])); if (mResponseMsg.IsEmpty()) { // If we get here, then we know that we have a complete line, and // that it is the first one NS_ASSERTION(line.Length() > 4 && startNum, "Read buffer doesn't include response code"); mResponseCode = atoi(PromiseFlatCString(Substring(line,0,3)).get()); } mResponseMsg.Append(line); // This is the last line if its 3 numbers followed by a space if (startNum && line[3] == ' ') { // yup. last line, let's move on. if (mState == mNextState) { NS_ERROR("ftp read state mixup"); mInternalError = NS_ERROR_FAILURE; mState = FTP_ERROR; } else { mState = mNextState; } nsCOMPtr<nsIFTPEventSink> ftpSink; mChannel->GetFTPEventSink(ftpSink); if (ftpSink) ftpSink->OnFTPControlLog(true, mResponseMsg.get()); nsresult rv = Process(); mResponseMsg.Truncate(); if (NS_FAILED(rv)) { CloseWithStatus(rv); return; } } currLine = currLine + eolLength + crlfLength; } } void nsFtpState::OnControlError(nsresult status) { NS_ASSERTION(NS_FAILED(status), "expecting error condition"); LOG(("FTP:(%p) CC(%p) error [%x was-cached=%u]\n", this, mControlConnection.get(), status, mTryingCachedControl)); mControlStatus = status; if (mReconnectAndLoginAgain && NS_SUCCEEDED(mInternalError)) { mReconnectAndLoginAgain = false; mAnonymous = false; mControlStatus = NS_OK; Connect(); } else if (mTryingCachedControl && NS_SUCCEEDED(mInternalError)) { mTryingCachedControl = false; Connect(); } else { CloseWithStatus(status); } } nsresult nsFtpState::EstablishControlConnection() { NS_ASSERTION(!mControlConnection, "we already have a control connection"); nsresult rv; LOG(("FTP:(%x) trying cached control\n", this)); // Look to see if we can use a cached control connection: nsFtpControlConnection *connection = nullptr; // Don't use cached control if anonymous (bug #473371) if (!mChannel->HasLoadFlag(nsIRequest::LOAD_ANONYMOUS)) gFtpHandler->RemoveConnection(mChannel->URI(), &connection); if (connection) { mControlConnection.swap(connection); if (mControlConnection->IsAlive()) { // set stream listener of the control connection to be us. mControlConnection->WaitData(this); // read cached variables into us. mServerType = mControlConnection->mServerType; mPassword = mControlConnection->mPassword; mPwd = mControlConnection->mPwd; mTryingCachedControl = true; // we're already connected to this server, skip login. mState = FTP_S_PASV; mResponseCode = 530; // assume the control connection was dropped. mControlStatus = NS_OK; mReceivedControlData = false; // For this request, we have not. // if we succeed, return. Otherwise, we need to create a transport rv = mControlConnection->Connect(mChannel->ProxyInfo(), this); if (NS_SUCCEEDED(rv)) return rv; } LOG(("FTP:(%p) cached CC(%p) is unusable\n", this, mControlConnection.get())); mControlConnection->WaitData(nullptr); mControlConnection = nullptr; } LOG(("FTP:(%p) creating CC\n", this)); mState = FTP_READ_BUF; mNextState = FTP_S_USER; nsAutoCString host; rv = mChannel->URI()->GetAsciiHost(host); if (NS_FAILED(rv)) return rv; mControlConnection = new nsFtpControlConnection(host, mPort); if (!mControlConnection) return NS_ERROR_OUT_OF_MEMORY; rv = mControlConnection->Connect(mChannel->ProxyInfo(), this); if (NS_FAILED(rv)) { LOG(("FTP:(%p) CC(%p) failed to connect [rv=%x]\n", this, mControlConnection.get(), rv)); mControlConnection = nullptr; return rv; } return mControlConnection->WaitData(this); } void nsFtpState::MoveToNextState(FTP_STATE nextState) { if (NS_FAILED(mInternalError)) { mState = FTP_ERROR; LOG(("FTP:(%x) FAILED (%x)\n", this, mInternalError)); } else { mState = FTP_READ_BUF; mNextState = nextState; } } nsresult nsFtpState::Process() { nsresult rv = NS_OK; bool processingRead = true; while (mKeepRunning && processingRead) { switch (mState) { case FTP_COMMAND_CONNECT: KillControlConnection(); LOG(("FTP:(%p) establishing CC", this)); mInternalError = EstablishControlConnection(); // sets mState if (NS_FAILED(mInternalError)) { mState = FTP_ERROR; LOG(("FTP:(%p) FAILED\n", this)); } else { LOG(("FTP:(%p) SUCCEEDED\n", this)); } break; case FTP_READ_BUF: LOG(("FTP:(%p) Waiting for CC(%p)\n", this, mControlConnection.get())); processingRead = false; break; case FTP_ERROR: // xx needs more work to handle dropped control connection cases if ((mTryingCachedControl && mResponseCode == 530 && mInternalError == NS_ERROR_FTP_PASV) || (mResponseCode == 425 && mInternalError == NS_ERROR_FTP_PASV)) { // The user was logged out during an pasv operation // we want to restart this request with a new control // channel. mState = FTP_COMMAND_CONNECT; } else if (mResponseCode == 421 && mInternalError != NS_ERROR_FTP_LOGIN) { // The command channel dropped for some reason. // Fire it back up, unless we were trying to login // in which case the server might just be telling us // that the max number of users has been reached... mState = FTP_COMMAND_CONNECT; } else if (mAnonymous && mInternalError == NS_ERROR_FTP_LOGIN) { // If the login was anonymous, and it failed, try again with a username // Don't reuse old control connection, see #386167 mAnonymous = false; mState = FTP_COMMAND_CONNECT; } else { LOG(("FTP:(%x) FTP_ERROR - calling StopProcessing\n", this)); rv = StopProcessing(); NS_ASSERTION(NS_SUCCEEDED(rv), "StopProcessing failed."); processingRead = false; } break; case FTP_COMPLETE: LOG(("FTP:(%x) COMPLETE\n", this)); rv = StopProcessing(); NS_ASSERTION(NS_SUCCEEDED(rv), "StopProcessing failed."); processingRead = false; break; // USER case FTP_S_USER: rv = S_user(); if (NS_FAILED(rv)) mInternalError = NS_ERROR_FTP_LOGIN; MoveToNextState(FTP_R_USER); break; case FTP_R_USER: mState = R_user(); if (FTP_ERROR == mState) mInternalError = NS_ERROR_FTP_LOGIN; break; // PASS case FTP_S_PASS: rv = S_pass(); if (NS_FAILED(rv)) mInternalError = NS_ERROR_FTP_LOGIN; MoveToNextState(FTP_R_PASS); break; case FTP_R_PASS: mState = R_pass(); if (FTP_ERROR == mState) mInternalError = NS_ERROR_FTP_LOGIN; break; // ACCT case FTP_S_ACCT: rv = S_acct(); if (NS_FAILED(rv)) mInternalError = NS_ERROR_FTP_LOGIN; MoveToNextState(FTP_R_ACCT); break; case FTP_R_ACCT: mState = R_acct(); if (FTP_ERROR == mState) mInternalError = NS_ERROR_FTP_LOGIN; break; // SYST case FTP_S_SYST: rv = S_syst(); if (NS_FAILED(rv)) mInternalError = NS_ERROR_FTP_LOGIN; MoveToNextState(FTP_R_SYST); break; case FTP_R_SYST: mState = R_syst(); if (FTP_ERROR == mState) mInternalError = NS_ERROR_FTP_LOGIN; break; // TYPE case FTP_S_TYPE: rv = S_type(); if (NS_FAILED(rv)) mInternalError = rv; MoveToNextState(FTP_R_TYPE); break; case FTP_R_TYPE: mState = R_type(); if (FTP_ERROR == mState) mInternalError = NS_ERROR_FAILURE; break; // CWD case FTP_S_CWD: rv = S_cwd(); if (NS_FAILED(rv)) mInternalError = NS_ERROR_FTP_CWD; MoveToNextState(FTP_R_CWD); break; case FTP_R_CWD: mState = R_cwd(); if (FTP_ERROR == mState) mInternalError = NS_ERROR_FTP_CWD; break; // LIST case FTP_S_LIST: rv = S_list(); if (rv == NS_ERROR_NOT_RESUMABLE) { mInternalError = rv; } else if (NS_FAILED(rv)) { mInternalError = NS_ERROR_FTP_CWD; } MoveToNextState(FTP_R_LIST); break; case FTP_R_LIST: mState = R_list(); if (FTP_ERROR == mState) mInternalError = NS_ERROR_FAILURE; break; // SIZE case FTP_S_SIZE: rv = S_size(); if (NS_FAILED(rv)) mInternalError = rv; MoveToNextState(FTP_R_SIZE); break; case FTP_R_SIZE: mState = R_size(); if (FTP_ERROR == mState) mInternalError = NS_ERROR_FAILURE; break; // REST case FTP_S_REST: rv = S_rest(); if (NS_FAILED(rv)) mInternalError = rv; MoveToNextState(FTP_R_REST); break; case FTP_R_REST: mState = R_rest(); if (FTP_ERROR == mState) mInternalError = NS_ERROR_FAILURE; break; // MDTM case FTP_S_MDTM: rv = S_mdtm(); if (NS_FAILED(rv)) mInternalError = rv; MoveToNextState(FTP_R_MDTM); break; case FTP_R_MDTM: mState = R_mdtm(); // Don't want to overwrite a more explicit status code if (FTP_ERROR == mState && NS_SUCCEEDED(mInternalError)) mInternalError = NS_ERROR_FAILURE; break; // RETR case FTP_S_RETR: rv = S_retr(); if (NS_FAILED(rv)) mInternalError = rv; MoveToNextState(FTP_R_RETR); break; case FTP_R_RETR: mState = R_retr(); if (FTP_ERROR == mState) mInternalError = NS_ERROR_FAILURE; break; // STOR case FTP_S_STOR: rv = S_stor(); if (NS_FAILED(rv)) mInternalError = rv; MoveToNextState(FTP_R_STOR); break; case FTP_R_STOR: mState = R_stor(); if (FTP_ERROR == mState) mInternalError = NS_ERROR_FAILURE; break; // PASV case FTP_S_PASV: rv = S_pasv(); if (NS_FAILED(rv)) mInternalError = NS_ERROR_FTP_PASV; MoveToNextState(FTP_R_PASV); break; case FTP_R_PASV: mState = R_pasv(); if (FTP_ERROR == mState) mInternalError = NS_ERROR_FTP_PASV; break; // PWD case FTP_S_PWD: rv = S_pwd(); if (NS_FAILED(rv)) mInternalError = NS_ERROR_FTP_PWD; MoveToNextState(FTP_R_PWD); break; case FTP_R_PWD: mState = R_pwd(); if (FTP_ERROR == mState) mInternalError = NS_ERROR_FTP_PWD; break; default: ; } } return rv; } /////////////////////////////////// // STATE METHODS /////////////////////////////////// nsresult nsFtpState::S_user() { // some servers on connect send us a 421 or 521. (84525) (141784) if ((mResponseCode == 421) || (mResponseCode == 521)) return NS_ERROR_FAILURE; nsresult rv; nsAutoCString usernameStr("USER "); mResponseMsg = ""; if (mAnonymous) { mReconnectAndLoginAgain = true; usernameStr.AppendLiteral("anonymous"); } else { mReconnectAndLoginAgain = false; if (mUsername.IsEmpty()) { // No prompt for anonymous requests (bug #473371) if (mChannel->HasLoadFlag(nsIRequest::LOAD_ANONYMOUS)) return NS_ERROR_FAILURE; nsCOMPtr<nsIAuthPrompt2> prompter; NS_QueryAuthPrompt2(static_cast<nsIChannel*>(mChannel), getter_AddRefs(prompter)); if (!prompter) return NS_ERROR_NOT_INITIALIZED; nsRefPtr<nsAuthInformationHolder> info = new nsAuthInformationHolder(nsIAuthInformation::AUTH_HOST, EmptyString(), EmptyCString()); bool retval; rv = prompter->PromptAuth(mChannel, nsIAuthPrompt2::LEVEL_NONE, info, &retval); // if the user canceled or didn't supply a username we want to fail if (NS_FAILED(rv) || !retval || info->User().IsEmpty()) return NS_ERROR_FAILURE; mUsername = info->User(); mPassword = info->Password(); } // XXX Is UTF-8 the best choice? AppendUTF16toUTF8(mUsername, usernameStr); } usernameStr.Append(CRLF); return SendFTPCommand(usernameStr); } FTP_STATE nsFtpState::R_user() { mReconnectAndLoginAgain = false; if (mResponseCode/100 == 3) { // send off the password return FTP_S_PASS; } if (mResponseCode/100 == 2) { // no password required, we're already logged in return FTP_S_SYST; } if (mResponseCode/100 == 5) { // problem logging in. typically this means the server // has reached it's user limit. return FTP_ERROR; } // LOGIN FAILED return FTP_ERROR; } nsresult nsFtpState::S_pass() { nsresult rv; nsAutoCString passwordStr("PASS "); mResponseMsg = ""; if (mAnonymous) { if (!mPassword.IsEmpty()) { // XXX Is UTF-8 the best choice? AppendUTF16toUTF8(mPassword, passwordStr); } else { nsXPIDLCString anonPassword; bool useRealEmail = false; nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID); if (prefs) { rv = prefs->GetBoolPref("advanced.mailftp", &useRealEmail); if (NS_SUCCEEDED(rv) && useRealEmail) { prefs->GetCharPref("network.ftp.anonymous_password", getter_Copies(anonPassword)); } } if (!anonPassword.IsEmpty()) { passwordStr.AppendASCII(anonPassword); } else { // We need to default to a valid email address - bug 101027 // example.com is reserved (rfc2606), so use that passwordStr.AppendLiteral("mozilla@example.com"); } } } else { if (mPassword.IsEmpty() || mRetryPass) { // No prompt for anonymous requests (bug #473371) if (mChannel->HasLoadFlag(nsIRequest::LOAD_ANONYMOUS)) return NS_ERROR_FAILURE; nsCOMPtr<nsIAuthPrompt2> prompter; NS_QueryAuthPrompt2(static_cast<nsIChannel*>(mChannel), getter_AddRefs(prompter)); if (!prompter) return NS_ERROR_NOT_INITIALIZED; nsRefPtr<nsAuthInformationHolder> info = new nsAuthInformationHolder(nsIAuthInformation::AUTH_HOST | nsIAuthInformation::ONLY_PASSWORD, EmptyString(), EmptyCString()); info->SetUserInternal(mUsername); bool retval; rv = prompter->PromptAuth(mChannel, nsIAuthPrompt2::LEVEL_NONE, info, &retval); // we want to fail if the user canceled. Note here that if they want // a blank password, we will pass it along. if (NS_FAILED(rv) || !retval) return NS_ERROR_FAILURE; mPassword = info->Password(); } // XXX Is UTF-8 the best choice? AppendUTF16toUTF8(mPassword, passwordStr); } passwordStr.Append(CRLF); return SendFTPCommand(passwordStr); } FTP_STATE nsFtpState::R_pass() { if (mResponseCode/100 == 3) { // send account info return FTP_S_ACCT; } if (mResponseCode/100 == 2) { // logged in return FTP_S_SYST; } if (mResponseCode == 503) { // start over w/ the user command. // note: the password was successful, and it's stored in mPassword mRetryPass = false; return FTP_S_USER; } if (mResponseCode/100 == 5 || mResponseCode==421) { // There is no difference between a too-many-users error, // a wrong-password error, or any other sort of error if (!mAnonymous) mRetryPass = true; return FTP_ERROR; } // unexpected response code return FTP_ERROR; } nsresult nsFtpState::S_pwd() { return SendFTPCommand(NS_LITERAL_CSTRING("PWD" CRLF)); } FTP_STATE nsFtpState::R_pwd() { // Error response to PWD command isn't fatal, but don't cache the connection // if CWD command is sent since correct mPwd is needed for further requests. if (mResponseCode/100 != 2) return FTP_S_TYPE; nsAutoCString respStr(mResponseMsg); int32_t pos = respStr.FindChar('"'); if (pos > -1) { respStr.Cut(0, pos+1); pos = respStr.FindChar('"'); if (pos > -1) { respStr.Truncate(pos); if (mServerType == FTP_VMS_TYPE) ConvertDirspecFromVMS(respStr); if (respStr.Last() != '/') respStr.Append('/'); mPwd = respStr; } } return FTP_S_TYPE; } nsresult nsFtpState::S_syst() { return SendFTPCommand(NS_LITERAL_CSTRING("SYST" CRLF)); } FTP_STATE nsFtpState::R_syst() { if (mResponseCode/100 == 2) { if (( mResponseMsg.Find("L8") > -1) || ( mResponseMsg.Find("UNIX") > -1) || ( mResponseMsg.Find("BSD") > -1) || ( mResponseMsg.Find("MACOS Peter's Server") > -1) || ( mResponseMsg.Find("MACOS WebSTAR FTP") > -1) || ( mResponseMsg.Find("MVS") > -1) || ( mResponseMsg.Find("OS/390") > -1) || ( mResponseMsg.Find("OS/400") > -1)) { mServerType = FTP_UNIX_TYPE; } else if (( mResponseMsg.Find("WIN32", true) > -1) || ( mResponseMsg.Find("windows", true) > -1)) { mServerType = FTP_NT_TYPE; } else if (mResponseMsg.Find("OS/2", true) > -1) { mServerType = FTP_OS2_TYPE; } else if (mResponseMsg.Find("VMS", true) > -1) { mServerType = FTP_VMS_TYPE; } else { NS_ERROR("Server type list format unrecognized."); // Guessing causes crashes. // (Of course, the parsing code should be more robust...) nsCOMPtr<nsIStringBundleService> bundleService = do_GetService(NS_STRINGBUNDLE_CONTRACTID); if (!bundleService) return FTP_ERROR; nsCOMPtr<nsIStringBundle> bundle; nsresult rv = bundleService->CreateBundle(NECKO_MSGS_URL, getter_AddRefs(bundle)); if (NS_FAILED(rv)) return FTP_ERROR; PRUnichar* ucs2Response = ToNewUnicode(mResponseMsg); const PRUnichar *formatStrings[1] = { ucs2Response }; NS_NAMED_LITERAL_STRING(name, "UnsupportedFTPServer"); nsXPIDLString formattedString; rv = bundle->FormatStringFromName(name.get(), formatStrings, 1, getter_Copies(formattedString)); nsMemory::Free(ucs2Response); if (NS_FAILED(rv)) return FTP_ERROR; // TODO(darin): this code should not be dictating UI like this! nsCOMPtr<nsIPrompt> prompter; mChannel->GetCallback(prompter); if (prompter) prompter->Alert(nullptr, formattedString.get()); // since we just alerted the user, clear mResponseMsg, // which is displayed to the user. mResponseMsg = ""; return FTP_ERROR; } return FTP_S_PWD; } if (mResponseCode/100 == 5) { // server didn't like the SYST command. Probably (500, 501, 502) // No clue. We will just hope it is UNIX type server. mServerType = FTP_UNIX_TYPE; return FTP_S_PWD; } return FTP_ERROR; } nsresult nsFtpState::S_acct() { return SendFTPCommand(NS_LITERAL_CSTRING("ACCT noaccount" CRLF)); } FTP_STATE nsFtpState::R_acct() { if (mResponseCode/100 == 2) return FTP_S_SYST; return FTP_ERROR; } nsresult nsFtpState::S_type() { return SendFTPCommand(NS_LITERAL_CSTRING("TYPE I" CRLF)); } FTP_STATE nsFtpState::R_type() { if (mResponseCode/100 != 2) return FTP_ERROR; return FTP_S_PASV; } nsresult nsFtpState::S_cwd() { // Don't cache the connection if PWD command failed if (mPwd.IsEmpty()) mCacheConnection = false; nsAutoCString cwdStr; if (mAction != PUT) cwdStr = mPath; if (cwdStr.IsEmpty() || cwdStr.First() != '/') cwdStr.Insert(mPwd,0); if (mServerType == FTP_VMS_TYPE) ConvertDirspecToVMS(cwdStr); cwdStr.Insert("CWD ",0); cwdStr.Append(CRLF); return SendFTPCommand(cwdStr); } FTP_STATE nsFtpState::R_cwd() { if (mResponseCode/100 == 2) { if (mAction == PUT) return FTP_S_STOR; return FTP_S_LIST; } return FTP_ERROR; } nsresult nsFtpState::S_size() { nsAutoCString sizeBuf(mPath); if (sizeBuf.IsEmpty() || sizeBuf.First() != '/') sizeBuf.Insert(mPwd,0); if (mServerType == FTP_VMS_TYPE) ConvertFilespecToVMS(sizeBuf); sizeBuf.Insert("SIZE ",0); sizeBuf.Append(CRLF); return SendFTPCommand(sizeBuf); } FTP_STATE nsFtpState::R_size() { if (mResponseCode/100 == 2) { PR_sscanf(mResponseMsg.get() + 4, "%llu", &mFileSize); mChannel->SetContentLength64(mFileSize); } // We may want to be able to resume this return FTP_S_MDTM; } nsresult nsFtpState::S_mdtm() { nsAutoCString mdtmBuf(mPath); if (mdtmBuf.IsEmpty() || mdtmBuf.First() != '/') mdtmBuf.Insert(mPwd,0); if (mServerType == FTP_VMS_TYPE) ConvertFilespecToVMS(mdtmBuf); mdtmBuf.Insert("MDTM ",0); mdtmBuf.Append(CRLF); return SendFTPCommand(mdtmBuf); } FTP_STATE nsFtpState::R_mdtm() { if (mResponseCode == 213) { mResponseMsg.Cut(0,4); mResponseMsg.Trim(" \t\r\n"); // yyyymmddhhmmss if (mResponseMsg.Length() != 14) { NS_ASSERTION(mResponseMsg.Length() == 14, "Unknown MDTM response"); } else { mModTime = mResponseMsg; // Save lastModified time for downloaded files. nsAutoCString timeString; nsresult error; PRExplodedTime exTime; mResponseMsg.Mid(timeString, 0, 4); exTime.tm_year = timeString.ToInteger(&error, 10); mResponseMsg.Mid(timeString, 4, 2); exTime.tm_month = timeString.ToInteger(&error, 10) - 1; //january = 0 mResponseMsg.Mid(timeString, 6, 2); exTime.tm_mday = timeString.ToInteger(&error, 10); mResponseMsg.Mid(timeString, 8, 2); exTime.tm_hour = timeString.ToInteger(&error, 10); mResponseMsg.Mid(timeString, 10, 2); exTime.tm_min = timeString.ToInteger(&error, 10); mResponseMsg.Mid(timeString, 12, 2); exTime.tm_sec = timeString.ToInteger(&error, 10); exTime.tm_usec = 0; exTime.tm_params.tp_gmt_offset = 0; exTime.tm_params.tp_dst_offset = 0; PR_NormalizeTime(&exTime, PR_GMTParameters); exTime.tm_params = PR_LocalTimeParameters(&exTime); PRTime time = PR_ImplodeTime(&exTime); (void)mChannel->SetLastModifiedTime(time); } } nsCString entityID; entityID.Truncate(); entityID.AppendInt(int64_t(mFileSize)); entityID.Append('/'); entityID.Append(mModTime); mChannel->SetEntityID(entityID); // We weren't asked to resume if (!mChannel->ResumeRequested()) return FTP_S_RETR; //if (our entityID == supplied one (if any)) if (mSuppliedEntityID.IsEmpty() || entityID.Equals(mSuppliedEntityID)) return FTP_S_REST; mInternalError = NS_ERROR_ENTITY_CHANGED; mResponseMsg.Truncate(); return FTP_ERROR; } nsresult nsFtpState::SetContentType() { // FTP directory URLs don't always end in a slash. Make sure they do. // This check needs to be here rather than a more obvious place // (e.g. LIST command processing) so that it ensures the terminating // slash is appended for the new request case, as well as the case // where the URL is being loaded from the cache. if (!mPath.IsEmpty() && mPath.Last() != '/') { nsCOMPtr<nsIURL> url = (do_QueryInterface(mChannel->URI())); nsAutoCString filePath; if(NS_SUCCEEDED(url->GetFilePath(filePath))) { filePath.Append('/'); url->SetFilePath(filePath); } } return mChannel->SetContentType( NS_LITERAL_CSTRING(APPLICATION_HTTP_INDEX_FORMAT)); } nsresult nsFtpState::S_list() { nsresult rv = SetContentType(); if (NS_FAILED(rv)) // XXX Invalid cast of FTP_STATE to nsresult -- FTP_ERROR has // value < 0x80000000 and will pass NS_SUCCEEDED() (bug 778109) return (nsresult)FTP_ERROR; rv = mChannel->PushStreamConverter("text/ftp-dir", APPLICATION_HTTP_INDEX_FORMAT); if (NS_FAILED(rv)) { // clear mResponseMsg which is displayed to the user. // TODO: we should probably set this to something meaningful. mResponseMsg = ""; return rv; } if (mCacheEntry) { // save off the server type if we are caching. nsAutoCString serverType; serverType.AppendInt(mServerType); mCacheEntry->SetMetaDataElement("servertype", serverType.get()); // open cache entry for writing, and configure it to receive data. if (NS_FAILED(InstallCacheListener())) { mCacheEntry->AsyncDoom(nullptr); mCacheEntry = nullptr; } } // dir listings aren't resumable NS_ENSURE_TRUE(!mChannel->ResumeRequested(), NS_ERROR_NOT_RESUMABLE); mChannel->SetEntityID(EmptyCString()); const char *listString; if (mServerType == FTP_VMS_TYPE) { listString = "LIST *.*;0" CRLF; } else { listString = "LIST" CRLF; } return SendFTPCommand(nsDependentCString(listString)); } FTP_STATE nsFtpState::R_list() { if (mResponseCode/100 == 1) { // OK, time to start reading from the data connection. if (HasPendingCallback()) mDataStream->AsyncWait(this, 0, 0, CallbackTarget()); return FTP_READ_BUF; } if (mResponseCode/100 == 2) { //(DONE) mNextState = FTP_COMPLETE; mDoomCache = false; return FTP_COMPLETE; } return FTP_ERROR; } nsresult nsFtpState::S_retr() { nsAutoCString retrStr(mPath); if (retrStr.IsEmpty() || retrStr.First() != '/') retrStr.Insert(mPwd,0); if (mServerType == FTP_VMS_TYPE) ConvertFilespecToVMS(retrStr); retrStr.Insert("RETR ",0); retrStr.Append(CRLF); return SendFTPCommand(retrStr); } FTP_STATE nsFtpState::R_retr() { if (mResponseCode/100 == 2) { //(DONE) mNextState = FTP_COMPLETE; return FTP_COMPLETE; } if (mResponseCode/100 == 1) { // We're going to grab a file, not a directory. So we need to clear // any cache entry, otherwise we'll have problems reading it later. // See bug 122548 if (mCacheEntry) { (void)mCacheEntry->AsyncDoom(nullptr); mCacheEntry = nullptr; } if (HasPendingCallback()) mDataStream->AsyncWait(this, 0, 0, CallbackTarget()); return FTP_READ_BUF; } // These error codes are related to problems with the connection. // If we encounter any at this point, do not try CWD and abort. if (mResponseCode == 421 || mResponseCode == 425 || mResponseCode == 426) return FTP_ERROR; if (mResponseCode/100 == 5) { mRETRFailed = true; return FTP_S_PASV; } return FTP_S_CWD; } nsresult nsFtpState::S_rest() { nsAutoCString restString("REST "); // The int64_t cast is needed to avoid ambiguity restString.AppendInt(int64_t(mChannel->StartPos()), 10); restString.Append(CRLF); return SendFTPCommand(restString); } FTP_STATE nsFtpState::R_rest() { if (mResponseCode/100 == 4) { // If REST fails, then we can't resume mChannel->SetEntityID(EmptyCString()); mInternalError = NS_ERROR_NOT_RESUMABLE; mResponseMsg.Truncate(); return FTP_ERROR; } return FTP_S_RETR; } nsresult nsFtpState::S_stor() { NS_ENSURE_STATE(mChannel->UploadStream()); NS_ASSERTION(mAction == PUT, "Wrong state to be here"); nsCOMPtr<nsIURL> url = do_QueryInterface(mChannel->URI()); NS_ASSERTION(url, "I thought you were a nsStandardURL"); nsAutoCString storStr; url->GetFilePath(storStr); NS_ASSERTION(!storStr.IsEmpty(), "What does it mean to store a empty path"); // kill the first slash since we want to be relative to CWD. if (storStr.First() == '/') storStr.Cut(0,1); if (mServerType == FTP_VMS_TYPE) ConvertFilespecToVMS(storStr); NS_UnescapeURL(storStr); storStr.Insert("STOR ",0); storStr.Append(CRLF); return SendFTPCommand(storStr); } FTP_STATE nsFtpState::R_stor() { if (mResponseCode/100 == 2) { //(DONE) mNextState = FTP_COMPLETE; mStorReplyReceived = true; // Call Close() if it was not called in nsFtpState::OnStoprequest() if (!mUploadRequest && !IsClosed()) Close(); return FTP_COMPLETE; } if (mResponseCode/100 == 1) { LOG(("FTP:(%x) writing on DT\n", this)); return FTP_READ_BUF; } mStorReplyReceived = true; return FTP_ERROR; } nsresult nsFtpState::S_pasv() { if (!mAddressChecked) { // Find socket address mAddressChecked = true; PR_InitializeNetAddr(PR_IpAddrAny, 0, &mServerAddress); nsITransport *controlSocket = mControlConnection->Transport(); if (!controlSocket) // XXX Invalid cast of FTP_STATE to nsresult -- FTP_ERROR has // value < 0x80000000 and will pass NS_SUCCEEDED() (bug 778109) return (nsresult)FTP_ERROR; nsCOMPtr<nsISocketTransport> sTrans = do_QueryInterface(controlSocket); if (sTrans) { nsresult rv = sTrans->GetPeerAddr(&mServerAddress); if (NS_SUCCEEDED(rv)) { if (!PR_IsNetAddrType(&mServerAddress, PR_IpAddrAny)) mServerIsIPv6 = mServerAddress.raw.family == PR_AF_INET6 && !PR_IsNetAddrType(&mServerAddress, PR_IpAddrV4Mapped); else { /* * In case of SOCKS5 remote DNS resolution, we do * not know the remote IP address. Still, if it is * an IPV6 host, then the external address of the * socks server should also be IPv6, and this is the * self address of the transport. */ PRNetAddr selfAddress; rv = sTrans->GetSelfAddr(&selfAddress); if (NS_SUCCEEDED(rv)) mServerIsIPv6 = selfAddress.raw.family == PR_AF_INET6 && !PR_IsNetAddrType(&selfAddress, PR_IpAddrV4Mapped); } } } } const char *string; if (mServerIsIPv6) { string = "EPSV" CRLF; } else { string = "PASV" CRLF; } return SendFTPCommand(nsDependentCString(string)); } FTP_STATE nsFtpState::R_pasv() { if (mResponseCode/100 != 2) return FTP_ERROR; nsresult rv; int32_t port; nsAutoCString responseCopy(mResponseMsg); char *response = responseCopy.BeginWriting(); char *ptr = response; // Make sure to ignore the address in the PASV response (bug 370559) if (mServerIsIPv6) { // The returned string is of the form // text (|||ppp|) // Where '|' can be any single character char delim; while (*ptr && *ptr != '(') ptr++; if (*ptr++ != '(') return FTP_ERROR; delim = *ptr++; if (!delim || *ptr++ != delim || *ptr++ != delim || *ptr < '0' || *ptr > '9') return FTP_ERROR; port = 0; do { port = port * 10 + *ptr++ - '0'; } while (*ptr >= '0' && *ptr <= '9'); if (*ptr++ != delim || *ptr != ')') return FTP_ERROR; } else { // The returned address string can be of the form // (xxx,xxx,xxx,xxx,ppp,ppp) or // xxx,xxx,xxx,xxx,ppp,ppp (without parens) int32_t h0, h1, h2, h3, p0, p1; uint32_t fields = 0; // First try with parens while (*ptr && *ptr != '(') ++ptr; if (*ptr) { ++ptr; fields = PR_sscanf(ptr, "%ld,%ld,%ld,%ld,%ld,%ld", &h0, &h1, &h2, &h3, &p0, &p1); } if (!*ptr || fields < 6) { // OK, lets try w/o parens ptr = response; while (*ptr && *ptr != ',') ++ptr; if (*ptr) { // backup to the start of the digits do { ptr--; } while ((ptr >=response) && (*ptr >= '0') && (*ptr <= '9')); ptr++; // get back onto the numbers fields = PR_sscanf(ptr, "%ld,%ld,%ld,%ld,%ld,%ld", &h0, &h1, &h2, &h3, &p0, &p1); } } NS_ASSERTION(fields == 6, "Can't parse PASV response"); if (fields < 6) return FTP_ERROR; port = ((int32_t) (p0<<8)) + p1; } bool newDataConn = true; if (mDataTransport) { // Reuse this connection only if its still alive, and the port // is the same nsCOMPtr<nsISocketTransport> strans = do_QueryInterface(mDataTransport); if (strans) { int32_t oldPort; nsresult rv = strans->GetPort(&oldPort); if (NS_SUCCEEDED(rv)) { if (oldPort == port) { bool isAlive; if (NS_SUCCEEDED(strans->IsAlive(&isAlive)) && isAlive) newDataConn = false; } } } if (newDataConn) { mDataTransport->Close(NS_ERROR_ABORT); mDataTransport = nullptr; mDataStream = nullptr; } } if (newDataConn) { // now we know where to connect our data channel nsCOMPtr<nsISocketTransportService> sts = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID); if (!sts) return FTP_ERROR; nsCOMPtr<nsISocketTransport> strans; nsAutoCString host; if (!PR_IsNetAddrType(&mServerAddress, PR_IpAddrAny)) { char buf[64]; PR_NetAddrToString(&mServerAddress, buf, sizeof(buf)); host.Assign(buf); } else { /* * In case of SOCKS5 remote DNS resolving, the peer address * fetched previously will be invalid (0.0.0.0): it is unknown * to us. But we can pass on the original hostname to the * connect for the data connection. */ rv = mChannel->URI()->GetAsciiHost(host); if (NS_FAILED(rv)) return FTP_ERROR; } rv = sts->CreateTransport(nullptr, 0, host, port, mChannel->ProxyInfo(), getter_AddRefs(strans)); // the data socket if (NS_FAILED(rv)) return FTP_ERROR; mDataTransport = strans; strans->SetQoSBits(gFtpHandler->GetDataQoSBits()); LOG(("FTP:(%x) created DT (%s:%x)\n", this, host.get(), port)); // hook ourself up as a proxy for status notifications rv = mDataTransport->SetEventSink(this, NS_GetCurrentThread()); NS_ENSURE_SUCCESS(rv, FTP_ERROR); if (mAction == PUT) { NS_ASSERTION(!mRETRFailed, "Failed before uploading"); // nsIUploadChannel requires the upload stream to support ReadSegments. // therefore, we can open an unbuffered socket output stream. nsCOMPtr<nsIOutputStream> output; rv = mDataTransport->OpenOutputStream(nsITransport::OPEN_UNBUFFERED, 0, 0, getter_AddRefs(output)); if (NS_FAILED(rv)) return FTP_ERROR; // perform the data copy on the socket transport thread. we do this // because "output" is a socket output stream, so the result is that // all work will be done on the socket transport thread. nsCOMPtr<nsIEventTarget> stEventTarget = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID); if (!stEventTarget) return FTP_ERROR; nsCOMPtr<nsIAsyncStreamCopier> copier; rv = NS_NewAsyncStreamCopier(getter_AddRefs(copier), mChannel->UploadStream(), output, stEventTarget, true, // upload stream is buffered false); // output is NOT buffered if (NS_FAILED(rv)) return FTP_ERROR; rv = copier->AsyncCopy(this, nullptr); if (NS_FAILED(rv)) return FTP_ERROR; // hold a reference to the copier so we can cancel it if necessary. mUploadRequest = copier; // update the current working directory before sending the STOR // command. this is needed since we might be reusing a control // connection. return FTP_S_CWD; } // // else, we are reading from the data connection... // // open a buffered, asynchronous socket input stream nsCOMPtr<nsIInputStream> input; rv = mDataTransport->OpenInputStream(0, nsIOService::gDefaultSegmentSize, nsIOService::gDefaultSegmentCount, getter_AddRefs(input)); NS_ENSURE_SUCCESS(rv, FTP_ERROR); mDataStream = do_QueryInterface(input); } if (mRETRFailed || mPath.IsEmpty() || mPath.Last() == '/') return FTP_S_CWD; return FTP_S_SIZE; } //////////////////////////////////////////////////////////////////////////////// // nsIRequest methods: static inline uint32_t NowInSeconds() { return uint32_t(PR_Now() / PR_USEC_PER_SEC); } uint32_t nsFtpState::mSessionStartTime = NowInSeconds(); /* Is this cache entry valid to use for reading? * Since we make up an expiration time for ftp, use the following rules: * (see bug 103726) * * LOAD_FROM_CACHE : always use cache entry, even if expired * LOAD_BYPASS_CACHE : overwrite cache entry * LOAD_NORMAL|VALIDATE_ALWAYS : overwrite cache entry * LOAD_NORMAL : honor expiration time * LOAD_NORMAL|VALIDATE_ONCE_PER_SESSION : overwrite cache entry if first access * this session, otherwise use cache entry * even if expired. * LOAD_NORMAL|VALIDATE_NEVER : always use cache entry, even if expired * * Note that in theory we could use the mdtm time on the directory * In practice, the lack of a timezone plus the general lack of support for that * on directories means that its not worth it, I suspect. Revisit if we start * caching files - bbaetz */ bool nsFtpState::CanReadCacheEntry() { NS_ASSERTION(mCacheEntry, "must have a cache entry"); nsCacheAccessMode access; nsresult rv = mCacheEntry->GetAccessGranted(&access); if (NS_FAILED(rv)) return false; // If I'm not granted read access, then I can't reuse it... if (!(access & nsICache::ACCESS_READ)) return false; if (mChannel->HasLoadFlag(nsIRequest::LOAD_FROM_CACHE)) return true; if (mChannel->HasLoadFlag(nsIRequest::LOAD_BYPASS_CACHE)) return false; if (mChannel->HasLoadFlag(nsIRequest::VALIDATE_ALWAYS)) return false; uint32_t time; if (mChannel->HasLoadFlag(nsIRequest::VALIDATE_ONCE_PER_SESSION)) { rv = mCacheEntry->GetLastModified(&time); if (NS_FAILED(rv)) return false; return (mSessionStartTime > time); } if (mChannel->HasLoadFlag(nsIRequest::VALIDATE_NEVER)) return true; // OK, now we just check the expiration time as usual rv = mCacheEntry->GetExpirationTime(&time); if (NS_FAILED(rv)) return false; return (NowInSeconds() <= time); } nsresult nsFtpState::InstallCacheListener() { NS_ASSERTION(mCacheEntry, "must have a cache entry"); nsCOMPtr<nsIOutputStream> out; mCacheEntry->OpenOutputStream(0, getter_AddRefs(out)); NS_ENSURE_STATE(out); nsCOMPtr<nsIStreamListenerTee> tee = do_CreateInstance(NS_STREAMLISTENERTEE_CONTRACTID); NS_ENSURE_STATE(tee); nsresult rv = tee->Init(mChannel->StreamListener(), out, nullptr); NS_ENSURE_SUCCESS(rv, rv); mChannel->SetStreamListener(tee); return NS_OK; } nsresult nsFtpState::OpenCacheDataStream() { NS_ASSERTION(mCacheEntry, "must have a cache entry"); // Get a transport to the cached data... nsCOMPtr<nsIInputStream> input; mCacheEntry->OpenInputStream(0, getter_AddRefs(input)); NS_ENSURE_STATE(input); nsCOMPtr<nsIStreamTransportService> sts = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID); NS_ENSURE_STATE(sts); nsCOMPtr<nsITransport> transport; sts->CreateInputTransport(input, -1, -1, true, getter_AddRefs(transport)); NS_ENSURE_STATE(transport); nsresult rv = transport->SetEventSink(this, NS_GetCurrentThread()); NS_ENSURE_SUCCESS(rv, rv); // Open a non-blocking, buffered input stream... nsCOMPtr<nsIInputStream> transportInput; transport->OpenInputStream(0, nsIOService::gDefaultSegmentSize, nsIOService::gDefaultSegmentCount, getter_AddRefs(transportInput)); NS_ENSURE_STATE(transportInput); mDataStream = do_QueryInterface(transportInput); NS_ENSURE_STATE(mDataStream); mDataTransport = transport; return NS_OK; } nsresult nsFtpState::Init(nsFtpChannel *channel) { // parameter validation NS_ASSERTION(channel, "FTP: needs a channel"); mChannel = channel; // a straight ref ptr to the channel mKeepRunning = true; mSuppliedEntityID = channel->EntityID(); if (channel->UploadStream()) mAction = PUT; nsresult rv; nsAutoCString path; nsCOMPtr<nsIURL> url = do_QueryInterface(mChannel->URI()); nsCString host; url->GetAsciiHost(host); if (host.IsEmpty()) { return NS_ERROR_MALFORMED_URI; } if (url) { rv = url->GetFilePath(path); } else { rv = mChannel->URI()->GetPath(path); } if (NS_FAILED(rv)) return rv; removeParamsFromPath(path); // FTP parameters such as type=i are ignored if (url) { url->SetFilePath(path); } else { mChannel->URI()->SetPath(path); } // Skip leading slash char *fwdPtr = path.BeginWriting(); if (!fwdPtr) return NS_ERROR_OUT_OF_MEMORY; if (*fwdPtr == '/') fwdPtr++; if (*fwdPtr != '\0') { // now unescape it... %xx reduced inline to resulting character int32_t len = NS_UnescapeURL(fwdPtr); mPath.Assign(fwdPtr, len); if (IsUTF8(mPath)) { nsAutoCString originCharset; rv = mChannel->URI()->GetOriginCharset(originCharset); if (NS_SUCCEEDED(rv) && !originCharset.EqualsLiteral("UTF-8")) ConvertUTF8PathToCharset(originCharset); } #ifdef DEBUG if (mPath.FindCharInSet(CRLF) >= 0) NS_ERROR("NewURI() should've prevented this!!!"); #endif } // pull any username and/or password out of the uri nsAutoCString uname; rv = mChannel->URI()->GetUsername(uname); if (NS_FAILED(rv)) return rv; if (!uname.IsEmpty() && !uname.EqualsLiteral("anonymous")) { mAnonymous = false; CopyUTF8toUTF16(NS_UnescapeURL(uname), mUsername); // return an error if we find a CR or LF in the username if (uname.FindCharInSet(CRLF) >= 0) return NS_ERROR_MALFORMED_URI; } nsAutoCString password; rv = mChannel->URI()->GetPassword(password); if (NS_FAILED(rv)) return rv; CopyUTF8toUTF16(NS_UnescapeURL(password), mPassword); // return an error if we find a CR or LF in the password if (mPassword.FindCharInSet(CRLF) >= 0) return NS_ERROR_MALFORMED_URI; // setup the connection cache key int32_t port; rv = mChannel->URI()->GetPort(&port); if (NS_FAILED(rv)) return rv; if (port > 0) mPort = port; // Lookup Proxy information asynchronously if it isn't already set // on the channel and if we aren't configured explicitly to go directly nsCOMPtr<nsIProtocolProxyService> pps = do_GetService(NS_PROTOCOLPROXYSERVICE_CONTRACTID); if (pps && !mChannel->ProxyInfo()) { pps->AsyncResolve(mChannel->URI(), 0, this, getter_AddRefs(mProxyRequest)); } return NS_OK; } void nsFtpState::Connect() { mState = FTP_COMMAND_CONNECT; mNextState = FTP_S_USER; nsresult rv = Process(); // check for errors. if (NS_FAILED(rv)) { LOG(("FTP:Process() failed: %x\n", rv)); mInternalError = NS_ERROR_FAILURE; mState = FTP_ERROR; CloseWithStatus(mInternalError); } } void nsFtpState::KillControlConnection() { mControlReadCarryOverBuf.Truncate(0); mAddressChecked = false; mServerIsIPv6 = false; // if everything went okay, save the connection. // FIX: need a better way to determine if we can cache the connections. // there are some errors which do not mean that we need to kill the connection // e.g. fnf. if (!mControlConnection) return; // kill the reference to ourselves in the control connection. mControlConnection->WaitData(nullptr); if (NS_SUCCEEDED(mInternalError) && NS_SUCCEEDED(mControlStatus) && mControlConnection->IsAlive() && mCacheConnection) { LOG_ALWAYS(("FTP:(%p) caching CC(%p)", this, mControlConnection.get())); // Store connection persistent data mControlConnection->mServerType = mServerType; mControlConnection->mPassword = mPassword; mControlConnection->mPwd = mPwd; nsresult rv = NS_OK; // Don't cache controlconnection if anonymous (bug #473371) if (!mChannel->HasLoadFlag(nsIRequest::LOAD_ANONYMOUS)) rv = gFtpHandler->InsertConnection(mChannel->URI(), mControlConnection); // Can't cache it? Kill it then. mControlConnection->Disconnect(rv); } else { mControlConnection->Disconnect(NS_BINDING_ABORTED); } mControlConnection = nullptr; } class nsFtpAsyncAlert : public nsRunnable { public: nsFtpAsyncAlert(nsIPrompt *aPrompter, nsACString& aResponseMsg) : mPrompter(aPrompter) , mResponseMsg(aResponseMsg) { MOZ_COUNT_CTOR(nsFtpAsyncAlert); } virtual ~nsFtpAsyncAlert() { MOZ_COUNT_DTOR(nsFtpAsyncAlert); } NS_IMETHOD Run() { if (mPrompter) { mPrompter->Alert(nullptr, NS_ConvertASCIItoUTF16(mResponseMsg).get()); } return NS_OK; } private: nsCOMPtr<nsIPrompt> mPrompter; nsCString mResponseMsg; }; nsresult nsFtpState::StopProcessing() { // Only do this function once. if (!mKeepRunning) return NS_OK; mKeepRunning = false; LOG_ALWAYS(("FTP:(%x) nsFtpState stopping", this)); #ifdef DEBUG_dougt printf("FTP Stopped: [response code %d] [response msg follows:]\n%s\n", mResponseCode, mResponseMsg.get()); #endif if (NS_FAILED(mInternalError) && !mResponseMsg.IsEmpty()) { // check to see if the control status is bad. // web shell wont throw an alert. we better: // XXX(darin): this code should not be dictating UI like this! nsCOMPtr<nsIPrompt> prompter; mChannel->GetCallback(prompter); if (prompter) { nsCOMPtr<nsIRunnable> alertEvent = new nsFtpAsyncAlert(prompter, mResponseMsg); NS_DispatchToMainThread(alertEvent, NS_DISPATCH_NORMAL); } } nsresult broadcastErrorCode = mControlStatus; if (NS_SUCCEEDED(broadcastErrorCode)) broadcastErrorCode = mInternalError; mInternalError = broadcastErrorCode; KillControlConnection(); // XXX This can fire before we are done loading data. Is that a problem? OnTransportStatus(nullptr, NS_NET_STATUS_END_FTP_TRANSACTION, 0, 0); if (NS_FAILED(broadcastErrorCode)) CloseWithStatus(broadcastErrorCode); return NS_OK; } nsresult nsFtpState::SendFTPCommand(const nsCSubstring& command) { NS_ASSERTION(mControlConnection, "null control connection"); // we don't want to log the password: nsAutoCString logcmd(command); if (StringBeginsWith(command, NS_LITERAL_CSTRING("PASS "))) logcmd = "PASS xxxxx"; LOG(("FTP:(%x) writing \"%s\"\n", this, logcmd.get())); nsCOMPtr<nsIFTPEventSink> ftpSink; mChannel->GetFTPEventSink(ftpSink); if (ftpSink) ftpSink->OnFTPControlLog(false, logcmd.get()); if (mControlConnection) return mControlConnection->Write(command); return NS_ERROR_FAILURE; } // Convert a unix-style filespec to VMS format // /foo/fred/barney/file.txt -> foo:[fred.barney]file.txt // /foo/file.txt -> foo:[000000]file.txt void nsFtpState::ConvertFilespecToVMS(nsCString& fileString) { int ntok=1; char *t, *nextToken; nsAutoCString fileStringCopy; // Get a writeable copy we can strtok with. fileStringCopy = fileString; t = nsCRT::strtok(fileStringCopy.BeginWriting(), "/", &nextToken); if (t) while (nsCRT::strtok(nextToken, "/", &nextToken)) ntok++; // count number of terms (tokens) LOG(("FTP:(%x) ConvertFilespecToVMS ntok: %d\n", this, ntok)); LOG(("FTP:(%x) ConvertFilespecToVMS from: \"%s\"\n", this, fileString.get())); if (fileString.First() == '/') { // absolute filespec // / -> [] // /a -> a (doesn't really make much sense) // /a/b -> a:[000000]b // /a/b/c -> a:[b]c // /a/b/c/d -> a:[b.c]d if (ntok == 1) { if (fileString.Length() == 1) { // Just a slash fileString.Truncate(); fileString.AppendLiteral("[]"); } else { // just copy the name part (drop the leading slash) fileStringCopy = fileString; fileString = Substring(fileStringCopy, 1, fileStringCopy.Length()-1); } } else { // Get another copy since the last one was written to. fileStringCopy = fileString; fileString.Truncate(); fileString.Append(nsCRT::strtok(fileStringCopy.BeginWriting(), "/", &nextToken)); fileString.AppendLiteral(":["); if (ntok > 2) { for (int i=2; i<ntok; i++) { if (i > 2) fileString.Append('.'); fileString.Append(nsCRT::strtok(nextToken, "/", &nextToken)); } } else { fileString.AppendLiteral("000000"); } fileString.Append(']'); fileString.Append(nsCRT::strtok(nextToken, "/", &nextToken)); } } else { // relative filespec // a -> a // a/b -> [.a]b // a/b/c -> [.a.b]c if (ntok == 1) { // no slashes, just use the name as is } else { // Get another copy since the last one was written to. fileStringCopy = fileString; fileString.Truncate(); fileString.AppendLiteral("[."); fileString.Append(nsCRT::strtok(fileStringCopy.BeginWriting(), "/", &nextToken)); if (ntok > 2) { for (int i=2; i<ntok; i++) { fileString.Append('.'); fileString.Append(nsCRT::strtok(nextToken, "/", &nextToken)); } } fileString.Append(']'); fileString.Append(nsCRT::strtok(nextToken, "/", &nextToken)); } } LOG(("FTP:(%x) ConvertFilespecToVMS to: \"%s\"\n", this, fileString.get())); } // Convert a unix-style dirspec to VMS format // /foo/fred/barney/rubble -> foo:[fred.barney.rubble] // /foo/fred -> foo:[fred] // /foo -> foo:[000000] // (null) -> (null) void nsFtpState::ConvertDirspecToVMS(nsCString& dirSpec) { LOG(("FTP:(%x) ConvertDirspecToVMS from: \"%s\"\n", this, dirSpec.get())); if (!dirSpec.IsEmpty()) { if (dirSpec.Last() != '/') dirSpec.Append('/'); // we can use the filespec routine if we make it look like a file name dirSpec.Append('x'); ConvertFilespecToVMS(dirSpec); dirSpec.Truncate(dirSpec.Length()-1); } LOG(("FTP:(%x) ConvertDirspecToVMS to: \"%s\"\n", this, dirSpec.get())); } // Convert an absolute VMS style dirspec to UNIX format void nsFtpState::ConvertDirspecFromVMS(nsCString& dirSpec) { LOG(("FTP:(%x) ConvertDirspecFromVMS from: \"%s\"\n", this, dirSpec.get())); if (dirSpec.IsEmpty()) { dirSpec.Insert('.', 0); } else { dirSpec.Insert('/', 0); dirSpec.ReplaceSubstring(":[", "/"); dirSpec.ReplaceChar('.', '/'); dirSpec.ReplaceChar(']', '/'); } LOG(("FTP:(%x) ConvertDirspecFromVMS to: \"%s\"\n", this, dirSpec.get())); } //----------------------------------------------------------------------------- NS_IMETHODIMP nsFtpState::OnTransportStatus(nsITransport *transport, nsresult status, uint64_t progress, uint64_t progressMax) { // Mix signals from both the control and data connections. // Ignore data transfer events on the control connection. if (mControlConnection && transport == mControlConnection->Transport()) { switch (status) { case NS_NET_STATUS_RESOLVING_HOST: case NS_NET_STATUS_RESOLVED_HOST: case NS_NET_STATUS_CONNECTING_TO: case NS_NET_STATUS_CONNECTED_TO: break; default: return NS_OK; } } // Ignore the progressMax value from the socket. We know the true size of // the file based on the response from our SIZE request. Additionally, only // report the max progress based on where we started/resumed. mChannel->OnTransportStatus(nullptr, status, progress, mFileSize - mChannel->StartPos()); return NS_OK; } //----------------------------------------------------------------------------- NS_IMETHODIMP nsFtpState::OnCacheEntryAvailable(nsICacheEntryDescriptor *entry, nsCacheAccessMode access, nsresult status) { // We may have been closed while we were waiting for this cache entry. if (IsClosed()) return NS_OK; if (NS_SUCCEEDED(status) && entry) { mDoomCache = true; mCacheEntry = entry; if (CanReadCacheEntry() && ReadCacheEntry()) { mState = FTP_READ_CACHE; return NS_OK; } } Connect(); return NS_OK; } //----------------------------------------------------------------------------- NS_IMETHODIMP nsFtpState::OnCacheEntryDoomed(nsresult status) { return NS_ERROR_NOT_IMPLEMENTED; } //----------------------------------------------------------------------------- NS_IMETHODIMP nsFtpState::OnStartRequest(nsIRequest *request, nsISupports *context) { mStorReplyReceived = false; return NS_OK; } NS_IMETHODIMP nsFtpState::OnStopRequest(nsIRequest *request, nsISupports *context, nsresult status) { mUploadRequest = nullptr; // Close() will be called when reply to STOR command is received // see bug #389394 if (!mStorReplyReceived) return NS_OK; // We're done uploading. Let our consumer know that we're done. Close(); return NS_OK; } //----------------------------------------------------------------------------- NS_IMETHODIMP nsFtpState::Available(uint64_t *result) { if (mDataStream) return mDataStream->Available(result); return nsBaseContentStream::Available(result); } NS_IMETHODIMP nsFtpState::ReadSegments(nsWriteSegmentFun writer, void *closure, uint32_t count, uint32_t *result) { // Insert a thunk here so that the input stream passed to the writer is this // input stream instead of mDataStream. if (mDataStream) { nsWriteSegmentThunk thunk = { this, writer, closure }; return mDataStream->ReadSegments(NS_WriteSegmentThunk, &thunk, count, result); } return nsBaseContentStream::ReadSegments(writer, closure, count, result); } NS_IMETHODIMP nsFtpState::CloseWithStatus(nsresult status) { LOG(("FTP:(%p) close [%x]\n", this, status)); // Shutdown the control connection processing if we are being closed with an // error. Note: This method may be called several times. if (!IsClosed() && status != NS_BASE_STREAM_CLOSED && NS_FAILED(status)) { if (NS_SUCCEEDED(mInternalError)) mInternalError = status; StopProcessing(); } if (mUploadRequest) { mUploadRequest->Cancel(NS_ERROR_ABORT); mUploadRequest = nullptr; } if (mDataTransport) { // Shutdown the data transport. mDataTransport->Close(NS_ERROR_ABORT); mDataTransport = nullptr; } mDataStream = nullptr; if (mDoomCache && mCacheEntry) mCacheEntry->AsyncDoom(nullptr); mCacheEntry = nullptr; return nsBaseContentStream::CloseWithStatus(status); } static nsresult CreateHTTPProxiedChannel(nsIURI *uri, nsIProxyInfo *pi, nsIChannel **newChannel) { nsresult rv; nsCOMPtr<nsIIOService> ioService = do_GetIOService(&rv); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIProtocolHandler> handler; rv = ioService->GetProtocolHandler("http", getter_AddRefs(handler)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIProxiedProtocolHandler> pph = do_QueryInterface(handler, &rv); if (NS_FAILED(rv)) return rv; return pph->NewProxiedChannel(uri, pi, 0, nullptr, newChannel); } NS_IMETHODIMP nsFtpState::OnProxyAvailable(nsICancelable *request, nsIURI *uri, nsIProxyInfo *pi, nsresult status) { mProxyRequest = nullptr; // failed status code just implies DIRECT processing if (NS_SUCCEEDED(status)) { nsAutoCString type; if (pi && NS_SUCCEEDED(pi->GetType(type)) && type.EqualsLiteral("http")) { // Proxy the FTP url via HTTP // This would have been easier to just return a HTTP channel directly // from nsIIOService::NewChannelFromURI(), but the proxy type cannot // be reliabliy determined synchronously without jank due to pac, etc.. LOG(("FTP:(%p) Configured to use a HTTP proxy channel\n", this)); nsCOMPtr<nsIChannel> newChannel; if (NS_SUCCEEDED(CreateHTTPProxiedChannel(uri, pi, getter_AddRefs(newChannel))) && NS_SUCCEEDED(mChannel->Redirect(newChannel, nsIChannelEventSink::REDIRECT_INTERNAL, true))) { LOG(("FTP:(%p) Redirected to use a HTTP proxy channel\n", this)); return NS_OK; } } else if (pi) { // Proxy using the FTP protocol routed through a socks proxy LOG(("FTP:(%p) Configured to use a SOCKS proxy channel\n", this)); mChannel->SetProxyInfo(pi); } } if (mDeferredCallbackPending) { mDeferredCallbackPending = false; OnCallbackPending(); } return NS_OK; } void nsFtpState::OnCallbackPending() { // If this is the first call, then see if we could use the cache. If we // aren't going to read from (or write to) the cache, then just proceed to // connect to the server. if (mState == FTP_INIT) { if (mProxyRequest) { mDeferredCallbackPending = true; return; } if (CheckCache()) { mState = FTP_WAIT_CACHE; return; } if (mCacheEntry && CanReadCacheEntry() && ReadCacheEntry()) { mState = FTP_READ_CACHE; return; } Connect(); } else if (mDataStream) { mDataStream->AsyncWait(this, 0, 0, CallbackTarget()); } } bool nsFtpState::ReadCacheEntry() { NS_ASSERTION(mCacheEntry, "should have a cache entry"); // make sure the channel knows wassup SetContentType(); nsXPIDLCString serverType; mCacheEntry->GetMetaDataElement("servertype", getter_Copies(serverType)); nsAutoCString serverNum(serverType.get()); nsresult err; mServerType = serverNum.ToInteger(&err); mChannel->PushStreamConverter("text/ftp-dir", APPLICATION_HTTP_INDEX_FORMAT); mChannel->SetEntityID(EmptyCString()); if (NS_FAILED(OpenCacheDataStream())) return false; if (HasPendingCallback()) mDataStream->AsyncWait(this, 0, 0, CallbackTarget()); mDoomCache = false; return true; } bool nsFtpState::CheckCache() { // This function is responsible for setting mCacheEntry if there is a cache // entry that we can use. It returns true if we end up waiting for access // to the cache. // In some cases, we don't want to use the cache: if (mChannel->UploadStream() || mChannel->ResumeRequested()) return false; nsCOMPtr<nsICacheService> cache = do_GetService(NS_CACHESERVICE_CONTRACTID); if (!cache) return false; bool isPrivate = NS_UsePrivateBrowsing(mChannel); const char* sessionName = isPrivate ? "FTP-private" : "FTP"; nsCacheStoragePolicy policy = isPrivate ? nsICache::STORE_IN_MEMORY : nsICache::STORE_ANYWHERE; nsCOMPtr<nsICacheSession> session; cache->CreateSession(sessionName, policy, nsICache::STREAM_BASED, getter_AddRefs(session)); if (!session) return false; session->SetDoomEntriesIfExpired(false); session->SetIsPrivate(isPrivate); // Set cache access requested: nsCacheAccessMode accessReq; if (NS_IsOffline()) { accessReq = nsICache::ACCESS_READ; // can only read } else if (mChannel->HasLoadFlag(nsIRequest::LOAD_BYPASS_CACHE)) { accessReq = nsICache::ACCESS_WRITE; // replace cache entry } else { accessReq = nsICache::ACCESS_READ_WRITE; // normal browsing } // Check to see if we are not allowed to write to the cache: if (mChannel->HasLoadFlag(nsIRequest::INHIBIT_CACHING)) { accessReq &= ~nsICache::ACCESS_WRITE; if (accessReq == nsICache::ACCESS_NONE) return false; } // Generate cache key (remove trailing #ref if any): nsAutoCString key; mChannel->URI()->GetAsciiSpec(key); int32_t pos = key.RFindChar('#'); if (pos != kNotFound) key.Truncate(pos); NS_ENSURE_FALSE(key.IsEmpty(), false); nsresult rv = session->AsyncOpenCacheEntry(key, accessReq, this, false); return NS_SUCCEEDED(rv); } nsresult nsFtpState::ConvertUTF8PathToCharset(const nsACString &aCharset) { nsresult rv; NS_ASSERTION(IsUTF8(mPath), "mPath isn't UTF8 string!"); NS_ConvertUTF8toUTF16 ucsPath(mPath); nsAutoCString result; nsCOMPtr<nsICharsetConverterManager> charsetMgr( do_GetService("@mozilla.org/charset-converter-manager;1", &rv)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIUnicodeEncoder> encoder; rv = charsetMgr->GetUnicodeEncoder(PromiseFlatCString(aCharset).get(), getter_AddRefs(encoder)); NS_ENSURE_SUCCESS(rv, rv); int32_t len = ucsPath.Length(); int32_t maxlen; rv = encoder->GetMaxLength(ucsPath.get(), len, &maxlen); NS_ENSURE_SUCCESS(rv, rv); char buf[256], *p = buf; if (uint32_t(maxlen) > sizeof(buf) - 1) { p = (char *) malloc(maxlen + 1); if (!p) return NS_ERROR_OUT_OF_MEMORY; } rv = encoder->Convert(ucsPath.get(), &len, p, &maxlen); if (NS_FAILED(rv)) goto end; if (rv == NS_ERROR_UENC_NOMAPPING) { NS_WARNING("unicode conversion failed"); rv = NS_ERROR_UNEXPECTED; goto end; } p[maxlen] = 0; result.Assign(p); len = sizeof(buf) - 1; rv = encoder->Finish(buf, &len); if (NS_FAILED(rv)) goto end; buf[len] = 0; result.Append(buf); mPath = result; end: if (p != buf) free(p); return rv; }
[ "info@hadrons.me" ]
info@hadrons.me
6d92f6ea47ef81a5d159b3271a7f012354462926
2ba94892764a44d9c07f0f549f79f9f9dc272151
/Engine/Plugins/Messaging/UdpMessaging/Source/UdpMessaging/Private/Shared/UdpMessagingSettings.h
d6914ae979150619c7cdd20ab0cc0bb928d9cae1
[ "BSD-2-Clause", "LicenseRef-scancode-proprietary-license" ]
permissive
PopCap/GameIdea
934769eeb91f9637f5bf205d88b13ff1fc9ae8fd
201e1df50b2bc99afc079ce326aa0a44b178a391
refs/heads/master
2021-01-25T00:11:38.709772
2018-09-11T03:38:56
2018-09-11T03:38:56
37,818,708
0
0
BSD-2-Clause
2018-09-11T03:39:05
2015-06-21T17:36:44
null
UTF-8
C++
false
false
1,663
h
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once #include "UdpMessagingSettings.generated.h" UCLASS(config=Engine) class UUdpMessagingSettings : public UObject { GENERATED_UCLASS_BODY() public: /** Whether the UDP transport channel is enabled. */ UPROPERTY(config, EditAnywhere, Category=Transport) bool EnableTransport; /** The IP endpoint to listen to and send packets from. */ UPROPERTY(config, EditAnywhere, Category=Transport) FString UnicastEndpoint; /** The IP endpoint to send multicast packets to. */ UPROPERTY(config, EditAnywhere, Category=Transport) FString MulticastEndpoint; /** The time-to-live (TTL) for sent multicast packets. */ UPROPERTY(config, EditAnywhere, Category=Transport) uint8 MulticastTimeToLive; /** * The IP endpoints of static devices. * * Use this setting to list devices on other subnets, such as mobile phones on a WiFi network. */ UPROPERTY(config, EditAnywhere, Category=Transport, AdvancedDisplay) TArray<FString> StaticEndpoints; public: /** Whether the UDP tunnel is enabled. */ UPROPERTY(config, EditAnywhere, Category=Tunnel) bool EnableTunnel; /** The IP endpoint to listen to and send packets from. */ UPROPERTY(config, EditAnywhere, Category=Tunnel) FString TunnelUnicastEndpoint; /** The IP endpoint to send multicast packets to. */ UPROPERTY(config, EditAnywhere, Category=Tunnel) FString TunnelMulticastEndpoint; /** * The IP endpoints of remote tunnel nodes. * * Use this setting to connect to remote tunnel services. */ UPROPERTY(config, EditAnywhere, Category=Tunnel, AdvancedDisplay) TArray<FString> RemoteTunnelEndpoints; };
[ "dkroell@acm.org" ]
dkroell@acm.org
f4d39bbbb3e966350ff50f96c04fa1e0e494a65b
a64c0c617518345567087dcd3d7398fc1b29e252
/MapleStory/MapleStory/DamageSkin.cpp
a26de2981136cad331e00081633c07cf79893d04
[]
no_license
hanjin1029/API
0b1b05b0f4669f21f8df697b9ca77b33c1b42f17
9bbae73a98df7764de4e93e5f851b156303d3b98
refs/heads/master
2021-01-13T09:43:28.471297
2016-11-11T02:37:28
2016-11-11T02:37:28
72,819,471
0
1
null
null
null
null
UTF-8
C++
false
false
965
cpp
#include "StdAfx.h" #include "DamageSkin.h" CDamageSkin::CDamageSkin(void) : m_dwTime(GetTickCount()) { } CDamageSkin::~CDamageSkin(void) { } void CDamageSkin::Initialize(void) { m_tInfo = INFO(0, 0, 33.f, 38.f, 0, 0); m_strKey = "DamageSkin1"; m_tFrame = FRAME(0,10,0, 100); } int CDamageSkin::Progress(void) { if(m_dwTime + m_tFrame.dwTime < GetTickCount()) { m_dwTime = GetTickCount(); m_tFrame.iStart = m_tInfo.iAttack; } if(m_strKey == "DamageSkin1") { m_tFrame.dwTime = 40; m_tInfo.fY -= 5.f; } return 0; } void CDamageSkin::Render(HDC hdc) { TransparentBlt(hdc, int(m_tInfo.fX - m_tInfo.fCX / 2.f + m_ptScroll.x), int(m_tInfo.fY - m_tInfo.fCY / 2.f + m_ptScroll.y ), int(m_tInfo.fCX), int(m_tInfo.fCY) , (*m_pBitMap)[m_strKey]->GetMemDC(), int(m_tInfo.fCX * m_tFrame.iStart), int(m_tInfo.fCY * m_tFrame.iScene), (int)m_tInfo.fCX, (int)m_tInfo.fCY, RGB(255, 255, 255)); } void CDamageSkin::Release() { }
[ "hanjin1029@naver.com" ]
hanjin1029@naver.com
8ea4c61850b2a6232bac88b7da97d8e88afcd390
be123b1ce2c958f9dad3ce3650b735b224438156
/ecnu_oj/retrial/18_2nd/D/D.cpp
ea7547c1ad57ccc80535c29949df9f4314d5ebdc
[]
no_license
dogePrince/oj
f0ad445de56b7fd587713d2463de532a97dec2ad
524f42a49001a4d43085dc86c4aff5a7d2835447
refs/heads/master
2020-04-16T15:18:22.873463
2019-03-31T14:52:19
2019-03-31T14:52:19
165,697,755
0
0
null
null
null
null
UTF-8
C++
false
false
593
cpp
#include<stdio.h> #include<stdlib.h> #include<math.h> int a[21]; int d_cmp(const void *a, const void *b) { int *p1 = (int*)a; int *p2 = (int*)b; return *p1 - *p2; } int main(int argc, char const *argv[]) { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } qsort(a, n, sizeof(int), d_cmp); int min = int(((unsigned int)(~0))>>1); int temp; for (int i = 0; i < n-1; i++) { temp = abs(a[i] - a[i+1]); if (temp < min) { min = temp; } } printf("%d", min); return 0; }
[ "dave-shun.yao@autodesk.com" ]
dave-shun.yao@autodesk.com
194a23698e83fdcaa5ee64d59e863e53c23543b4
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function13979/function13979_schedule_4/function13979_schedule_4.cpp
82a7b33fbbddd715ac9972de1d4e5fb176f5da61
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
942
cpp
#include <tiramisu/tiramisu.h> using namespace tiramisu; int main(int argc, char **argv){ tiramisu::init("function13979_schedule_4"); constant c0("c0", 524288), c1("c1", 128); var i0("i0", 0, c0), i1("i1", 0, c1), i01("i01"), i02("i02"), i03("i03"), i04("i04"); input input00("input00", {i0}, p_int32); input input01("input01", {i0}, p_int32); computation comp0("comp0", {i0, i1}, input00(i0) + input01(i0)); comp0.tile(i0, i1, 64, 64, i01, i02, i03, i04); comp0.parallelize(i01); buffer buf00("buf00", {524288}, p_int32, a_input); buffer buf01("buf01", {524288}, p_int32, a_input); buffer buf0("buf0", {524288, 128}, p_int32, a_output); input00.store_in(&buf00); input01.store_in(&buf01); comp0.store_in(&buf0); tiramisu::codegen({&buf00, &buf01, &buf0}, "../data/programs/function13979/function13979_schedule_4/function13979_schedule_4.o"); return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
d3fd38e0a36ad6784a4c1f8fb90a952ff9eb821c
4b8acd2e0aef7d304bfa2f57b9be06fab0dd42e0
/src/accumulator.h
7fe66d696ce81e820e58a06d8adfac26dc577939
[]
no_license
metastableB/WITCH_On_A_Board
17ff3aa5a072d35d8bc0e0b5cf65933168f8d995
f83e06c67ad866a1d2f01b660916358fae5da680
refs/heads/master
2020-03-27T22:43:00.696211
2015-08-13T18:00:00
2015-08-13T18:00:00
35,816,818
1
1
null
2015-07-10T12:49:48
2015-05-18T12:32:57
C++
UTF-8
C++
false
false
931
h
/* * accumulator.h * * @author Don Dennis (metastableB) * donkdennis [at] gmail [dot] com * 05-Jun-2015 * */ #ifndef ACCUMULATOR_H #define ACCUMULATOR_H #include "dekatron.h" #include "dekatronstore.h" #include <string> // The accumulator is made up of two stores. This detail is hidden // Outside this class. Other objects index from 0-16. 0 Being sign bit. class Accumulator { DekatronStore accumulatorA; DekatronStore accumulatorB; public: void pulseAccumulator(int arr[]); void pulseAccumulator(int arr[], Dekatron* newState); void setAccumulatorValue(int arr[]); int setAccumulatorValue(std::string value); void setAccumulatorValueIn(int index, int value); void setAccumulatorSign(int sign); std::string getStringStateInStore(); DekatronState getStateIn(int index); int getAccumulatorSign(); // TODO: remove this once the drains are implemented void clearAccumulator(); }; #endif // ACCUMULATOR_H
[ "donkdennis@gmail.com" ]
donkdennis@gmail.com
35567b21e58d06f81d48573e04f5d70a6e2c045d
cb1c6c586d769f919ed982e9364d92cf0aa956fe
/examples/TRTRenderTest/GridRaycaster.h
ba7562de782b98ef96f7fd83d15f8e0df70cc1aa
[]
no_license
jrk/tinyrt
86fd6e274d56346652edbf50f0dfccd2700940a6
760589e368a981f321e5f483f6d7e152d2cf0ea6
refs/heads/master
2016-09-01T18:24:22.129615
2010-01-07T15:19:44
2010-01-07T15:19:44
462,454
3
0
null
null
null
null
UTF-8
C++
false
false
1,606
h
//===================================================================================================================== // // GridRaycaster.h // // Part of the TinyRT Raytracing Library. // Author: Joshua Barczak // // Copyright 2008 Joshua Barczak. All rights reserved. // See Doc/LICENSE.txt for terms and conditions. // //===================================================================================================================== #ifndef _TRT_GRIDRAYCASTER_H_ #define _TRT_GRIDRAYCASTER_H_ #include "TestRaycaster.h" //===================================================================================================================== /// \ingroup TinyRTTest /// \brief //===================================================================================================================== class GridRaycaster : public TestRaycaster { public: GridRaycaster( TestMesh* pMesh ); virtual ~GridRaycaster(); virtual void RaycastFirstHit( TinyRT::Ray& rRay, TinyRT::TriangleRayHit& rHitInfo ) ; virtual float ComputeCost( float fISectCost ) const ; inline const UniformGrid<TestMesh>* GetGrid() const { return m_pGrid; }; private: UniformGrid<TestMesh>* m_pGrid; //typedef NullMailbox MailboxType; typedef DirectMapMailbox<uint32,16> MailboxType; //typedef FifoMailbox<uint32,8> MailboxType; //typedef SimdFifoMailbox<8> MailboxType; //FifoMailbox<uint32,8> m_mb; //DirectMapMailbox<uint32,8> m_mb; //SimdFifoMailbox<8> m_mb; }; #endif // _TRT_GRIDRAYCASTER_H_
[ "jbarcz1@6ce04321-59f9-4392-9e3f-c0843787e809" ]
jbarcz1@6ce04321-59f9-4392-9e3f-c0843787e809
cbc3a390fbef75664b0acbdd0431ba3e35658485
38be6da813f2d230a90d1ac4c7deb81ca6221be0
/math/basic/codeforces/F1345A/Solution.cpp
0ade34fa3d92f6cb6d033ce19095a63264b2ad7c
[ "MIT" ]
permissive
MdAman02/problem_solving
c8c0ce3cd5d6daa458cb0a54ac419c7518bdbe1f
1cb731802a49bbb247b332f2d924d9440b9ec467
refs/heads/dev
2022-09-13T09:40:51.998372
2022-09-04T14:15:17
2022-09-04T14:15:17
256,194,798
0
0
MIT
2020-04-16T19:08:24
2020-04-16T11:27:57
Java
UTF-8
C++
false
false
579
cpp
// problem_name: Puzzle Pieces // problem_link: https://codeforces.com/contest/1345/problem/A // contest_link: https://codeforces.com/contest/1345 // time: (?) // author: reyad // other_tags: game // difficulty_level: easy #include <bits/stdc++.h> using namespace std; int main() { int tc; scanf("%d", &tc); for(int cc=0; cc<tc; cc++) { int n, m; scanf("%d %d", &n, &m); if(n == 1 || m == 1) { printf("YES\n"); } else { if(n <= 2 && m <= 2) { printf("YES\n"); } else { printf("NO\n"); } } } return 0; }
[ "reyadussalahin@gmail.com" ]
reyadussalahin@gmail.com
b614902fc44650dc6b9b2d00c2fa79fef49f3db5
247f9a5cc6e068695d0439e4a6bbaf6c1f5d7032
/FunctionType/WindowsServiceCppLibraryStaticLib/Code/ServiceCreate.cpp
ddba984b6633168e712cb90df5068c6960bd43cb
[ "MIT" ]
permissive
15831944/WindowsServiceCppLibrary
d90e0802b3708027194d88ca92391d35da5cacdf
1d4ff4b96b4808efdbc56615566e3355885361a6
refs/heads/master
2021-06-20T03:38:38.466047
2017-07-23T15:13:41
2017-07-23T15:13:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,683
cpp
#include "stdafx.h" #include "Common.hpp" #include "ServiceCreate.hpp" #include <strsafe.h> #include <process.h> #include <string> #include <vector> #include <stdexcept> static SERVICE_STATUS SvcStatus; static SERVICE_STATUS_HANDLE SvcStatusHandle; struct WinServiceInfo { SVCTHREAD ServiceThread; std::basic_string<TCHAR> ServiceName; WinSvcLib::ServiceState State; WinSvcLib::ServiceControl CurrentControl; } inf; struct CommandLine { CommandLine() = default; CommandLine(DWORD dwArgc, LPTSTR lpszArgv[]) : argc(dwArgc) { if (lpszArgv == NULL) this->argv = std::vector<std::basic_string<TCHAR>>(); else for (DWORD i = 0; i < dwArgc; i++) this->argv.emplace_back(lpszArgv[i]); } DWORD argc; std::vector<std::basic_string<TCHAR>> argv; } cmd; DWORD WINAPI HandlerEx(DWORD dwControl, DWORD, PVOID, PVOID) { inf.CurrentControl = static_cast<WinSvcLib::ServiceControl>(dwControl); switch (dwControl) { case SERVICE_CONTROL_STOP: SvcStatus.dwCurrentState = static_cast<DWORD>(WinSvcLib::ServiceState::Stopped); inf.State = WinSvcLib::ServiceState::Stopped; break; case SERVICE_CONTROL_PAUSE: SvcStatus.dwCurrentState = static_cast<DWORD>(WinSvcLib::ServiceState::Paused); inf.State = WinSvcLib::ServiceState::Paused; break; case SERVICE_CONTROL_CONTINUE: SvcStatus.dwCurrentState = static_cast<DWORD>(WinSvcLib::ServiceState::Running); inf.State = WinSvcLib::ServiceState::Running; break; case SERVICE_CONTROL_SHUTDOWN: SvcStatus.dwCurrentState = static_cast<DWORD>(WinSvcLib::ServiceState::Stopped); inf.State = WinSvcLib::ServiceState::Stopped; break; default: break; } SetServiceStatus(SvcStatusHandle, &SvcStatus); return NO_ERROR; } namespace WinSvcLib { ServiceControl operator | (const ServiceControl A, const ServiceControl B) { return static_cast<ServiceControl>(static_cast<DWORD>(A) | static_cast<DWORD>(B)); } ServiceType operator | (const ServiceType A, const ServiceType B) { return static_cast<ServiceType>(static_cast<DWORD>(A) | static_cast<DWORD>(B)); } ServiceControlsAccepted operator | (const ServiceControlsAccepted A, const ServiceControlsAccepted B) { return static_cast<ServiceControlsAccepted>(static_cast<DWORD>(A) | static_cast<DWORD>(B)); } ServiceAccessType operator | (const ServiceAccessType A, const ServiceAccessType B) { return static_cast<ServiceAccessType>(static_cast<DWORD>(A) | static_cast<DWORD>(B)); } namespace ServiceCreate { void EntryServiceMainToWindows(SVCMAIN ServiceMain) { #ifndef _DEBUG TCHAR buf[256]; #ifdef UNICODE wcscpy_s(buf, inf.ServiceName.c_str()); #else strcpy_s(buf, inf.ServiceName.c_str()); #endif SERVICE_TABLE_ENTRY ServiceTableEntry[] = { { buf, ServiceMain }, { NULL, NULL } }; StartServiceCtrlDispatcher(ServiceTableEntry); #else SvcStatus.dwCurrentState = static_cast<DWORD>(ServiceState::Running); ServiceMain(0, NULL); #endif } void SetDebugCommandLine(LPTSTR lpszArgv[]) { #ifdef _DEBUG cmd = CommandLine(sizeof(lpszArgv) / sizeof(lpszArgv[0]), lpszArgv); #else UNREFERENCED_PARAMETER(lpszArgv); #endif } namespace CallInServiceMain { void WinSvcLibInit(const std::basic_string<TCHAR> ServiceName, SVCTHREAD ServiceThread, DWORD dwArgc, LPTSTR lpszArgv[]) { #ifdef _DEBUG UNREFERENCED_PARAMETER(dwArgc); UNREFERENCED_PARAMETER(lpszArgv); ServiceThread(NULL); #else cmd = CommandLine(dwArgc, lpszArgv); inf.ServiceThread = ServiceThread; SvcStatusHandle = RegisterServiceCtrlHandlerEx(ServiceName.c_str(), HandlerEx, NULL); memset(&SvcStatus, 0, sizeof(SvcStatus)); inf.ServiceName = ServiceName; SvcStatus.dwServiceType = static_cast<DWORD>(ServiceType::Win32OwnProcess); SvcStatus.dwCurrentState = static_cast<DWORD>(ServiceState::Running); SvcStatus.dwControlsAccepted = static_cast<DWORD>(ServiceControlsAccepted::Stop | ServiceControlsAccepted::PauseContinue); SvcStatus.dwWin32ExitCode = NO_ERROR; SvcStatus.dwServiceSpecificExitCode = 0; SvcStatus.dwCheckPoint = 0; SvcStatus.dwWaitHint = 2000; #endif } void WinSvcLibInit(const std::basic_string<TCHAR> ServiceName, SVCTHREAD ServiceThread) { WinSvcLibInit(ServiceName, ServiceThread, 1, NULL); } void SetServiceType(const ServiceType SvcType) { SvcStatus.dwServiceType = static_cast<DWORD>(SvcType); } void SetCurrentState(const ServiceState SvcState) { SvcStatus.dwCurrentState = static_cast<DWORD>(SvcState); } void SetControlsAccepted(const ServiceControlsAccepted SvcControlAccepted) { SvcStatus.dwControlsAccepted = static_cast<DWORD>(SvcControlAccepted); } void SetWin32ExitCode(const DWORD Win32ExitCode) { SvcStatus.dwWin32ExitCode = Win32ExitCode; } void SetServiceSpecificExitCode(const DWORD ServiceSpecificExitCode) { SvcStatus.dwServiceSpecificExitCode = ServiceSpecificExitCode; } void SetCheckPoint(const DWORD CheckPoint) { SvcStatus.dwCheckPoint = CheckPoint; } void SetWaitHint(const DWORD WaitHint) { SvcStatus.dwWaitHint = WaitHint; } void WinSvcLibEnd() { #ifndef _DEBUG UINT uiThreadID; _beginthreadex( NULL, 0, inf.ServiceThread, NULL, 0, &uiThreadID ); SetServiceStatus(SvcStatusHandle, &SvcStatus); #endif } } namespace CallInServiceThread { ServiceControl GetCurrentControl() { return inf.CurrentControl; } ServiceState GetServiceState() { return inf.State; } DWORD GetArgc() { return cmd.argc; } std::basic_string<TCHAR> GetArgv(const size_t Number) { return cmd.argv[Number]; } std::vector<std::basic_string<TCHAR>> GetArgv() { return cmd.argv; } } } }
[ "aimegu2014@gmail.com" ]
aimegu2014@gmail.com
b48365cab572206e0fe84210ad723ca7c57c55c6
b052937681803bd58d410d6e84abfabf9c6c598e
/sw_x/gvm_apps/syncConfigTest/platform_android/project/jni/.svn/text-base/syncconfigtest_jni.cpp.svn-base
1ba814e39759731e6983197cd019a1e4482c64ff
[]
no_license
muyl1/acer_cloud_wifi_copy
a8eff32e7dc02769bd2302914a7d5bd984227365
f7459f5d28056fa3884720cbd891d77e0b00698b
refs/heads/master
2021-05-27T08:52:21.443483
2014-06-17T09:17:17
2014-06-17T09:17:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,041
#include <string> #include <android/log.h> #include "com_igware_sync_config_test_SyncConfigNative.h" int syncConfigTest(int argc, const char ** argv); #define LOG_INFO( info, p1 ) __android_log_print( ANDROID_LOG_WARN, "NATIVE CODE", info, p1 ); JNIEXPORT jint JNICALL Java_com_igware_sync_1config_test_SyncConfigNative_testSyncConfig( JNIEnv *env, jclass, jint jargc, jobjectArray jstringArray) { int argc = (int) jargc; int ret = 0; char* raw_argv[argc]; int argv_length = env->GetArrayLength(jstringArray); for (int i = 0; i < argv_length; i++) { jstring string = (jstring) env->GetObjectArrayElement(jstringArray, i); const char* raw_sting = env->GetStringUTFChars(string, 0); raw_argv[i] = (char*) raw_sting; } ret = syncConfigTest(argc, (const char**) raw_argv); for (int i = 0; i < argv_length; i++) { jstring string = (jstring) env->GetObjectArrayElement(jstringArray, i); env->ReleaseStringUTFChars(string, raw_argv[i]); } return ret; }
[ "jimmyiverson@gmail.com" ]
jimmyiverson@gmail.com
9cc1d66ef0d7919d417546a56bce8452dcd408b2
e6c548bc3af16ad7b175a3c6b32aafdb37087adc
/test/mat-serve-test/main.cpp
d972f08582e51753b113c05423baaece2a5e6fa5
[]
no_license
imalsogreg/simple-tracker
8b7764bb5c8c25418e39ca1014c7f2b6734b139e
6596074b1af23cfe1b9489c7fd4f067a77efd8fd
refs/heads/master
2021-01-13T06:52:10.550926
2015-04-30T00:59:02
2015-04-30T00:59:02
34,761,525
0
0
null
2015-04-28T23:34:53
2015-04-28T23:34:53
null
UTF-8
C++
false
false
1,393
cpp
//****************************************************************************** //* Copyright (c) Jon Newman (jpnewman at mit snail edu) //* All right reserved. //* This file is part of the Simple Tracker project. //* This 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 software 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 source code. If not, see <http://www.gnu.org/licenses/>. //****************************************************************************** #include "MatServeTest.h" int main(int argc, char *argv[]) { if (argc != 3) { std::cout << "Usage: " << argv[0] << " SERVER-NAME TEST-AVI-FILE" << std::endl; std::cout << "cv::Mat data server test" << std::endl; return 1; } MatServeTest server(argv[1]); server.openVideo(argv[2]); while (server.serveMat()) { std::cout << "Sent frame." << std::endl; } // Exit return 0; }
[ "jpnewman@mit.edu" ]
jpnewman@mit.edu
45f4e980a1cd80ce971ee524bfe2100773eee09e
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE78_OS_Command_Injection/s06/CWE78_OS_Command_Injection__wchar_t_console_execl_81a.cpp
342dd88773d459a28800f5ec6b504f254505842a
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
3,283
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__wchar_t_console_execl_81a.cpp Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-81a.tmpl.cpp */ /* * @description * CWE: 78 OS Command Injection * BadSource: console Read input from the console * GoodSource: Fixed string * Sinks: execl * BadSink : execute command with wexecl * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference * * */ #include "std_testcase.h" #include "CWE78_OS_Command_Injection__wchar_t_console_execl_81.h" namespace CWE78_OS_Command_Injection__wchar_t_console_execl_81 { #ifndef OMITBAD void bad() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; { /* Read input from the console */ size_t dataLen = wcslen(data); /* if there is room in data, read into it from the console */ if (100-dataLen > 1) { /* POTENTIAL FLAW: Read data from the console */ if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL) { /* The next few lines remove the carriage return from the string that is * inserted by fgetws() */ dataLen = wcslen(data); if (dataLen > 0 && data[dataLen-1] == L'\n') { data[dataLen-1] = L'\0'; } } else { printLine("fgetws() failed"); /* Restore NUL terminator if fgetws fails */ data[dataLen] = L'\0'; } } } const CWE78_OS_Command_Injection__wchar_t_console_execl_81_base& baseObject = CWE78_OS_Command_Injection__wchar_t_console_execl_81_bad(); baseObject.action(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; /* FIX: Append a fixed string to data (not user / external input) */ wcscat(data, L"*.*"); const CWE78_OS_Command_Injection__wchar_t_console_execl_81_base& baseObject = CWE78_OS_Command_Injection__wchar_t_console_execl_81_goodG2B(); baseObject.action(data); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE78_OS_Command_Injection__wchar_t_console_execl_81; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
74e7c7e5ab95cc6cf96e005c7254620f2711b6eb
feb48d956fd04d0643dbe305b75eaee7523bba71
/Chain.h
e776920b81c7455bf76521091facac003ad87386
[]
no_license
jefryhdz/P3_JefryHernandez_Lab8
0bb3df299121d5a7f710fae3e6bf9eccd21e76f3
2437f07db9fa66f72e1c2004b72dbfb3fb8eb6a3
refs/heads/master
2021-08-24T11:55:27.289707
2017-12-09T06:00:58
2017-12-09T06:00:58
113,621,215
0
0
null
null
null
null
UTF-8
C++
false
false
416
h
#include <iostream> #include <string> #include <vector> #include <sstream> #include "Melee.h" #include "Range.h" using namespace std; #ifndef CHAIN_H #define CHAIN_H class Chain : public Melee{ protected: string color; public: Chain(string,int,double,double,double,double,double,string,string); Chain(); string getColor(); void setColor(string); ~Chain(); int Ataque(Minion*,bool); }; #endif
[ "jefryhdz@gmail.com" ]
jefryhdz@gmail.com
1b1359fab8b4d011fda20d08ebe3f408881ab75b
a81c07a5663d967c432a61d0b4a09de5187be87b
/ui/views/metadata/type_conversion.cc
b165b2867afa77eef847aec4fef5d1713d04be87
[ "BSD-3-Clause" ]
permissive
junxuezheng/chromium
c401dec07f19878501801c9e9205a703e8643031
381ce9d478b684e0df5d149f59350e3bc634dad3
refs/heads/master
2023-02-28T17:07:31.342118
2019-09-03T01:42:42
2019-09-03T01:42:42
205,967,014
2
0
BSD-3-Clause
2019-09-03T01:48:23
2019-09-03T01:48:23
null
UTF-8
C++
false
false
11,874
cc
// 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. #include "ui/views/metadata/type_conversion.h" #include "base/strings/string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "ui/base/ime/text_input_type.h" #include "ui/gfx/geometry/rect.h" namespace views { namespace metadata { const base::string16& GetNullOptStr() { static const base::NoDestructor<base::string16> kNullOptStr( base::ASCIIToUTF16("<Empty>")); return *kNullOptStr; } /***** String Conversions *****/ #define CONVERT_NUMBER_TO_STRING(T) \ base::string16 TypeConverter<T>::ToString(T source_value) { \ return base::NumberToString16(source_value); \ } CONVERT_NUMBER_TO_STRING(int8_t) CONVERT_NUMBER_TO_STRING(int16_t) CONVERT_NUMBER_TO_STRING(int32_t) CONVERT_NUMBER_TO_STRING(int64_t) CONVERT_NUMBER_TO_STRING(uint8_t) CONVERT_NUMBER_TO_STRING(uint16_t) CONVERT_NUMBER_TO_STRING(uint32_t) CONVERT_NUMBER_TO_STRING(uint64_t) CONVERT_NUMBER_TO_STRING(float) CONVERT_NUMBER_TO_STRING(double) base::string16 TypeConverter<bool>::ToString(bool source_value) { return base::ASCIIToUTF16(source_value ? "true" : "false"); } base::string16 TypeConverter<gfx::Size>::ToString( const gfx::Size& source_value) { return base::ASCIIToUTF16(base::StringPrintf("{%i, %i}", source_value.width(), source_value.height())); } base::string16 TypeConverter<base::string16>::ToString( const base::string16& source_value) { return source_value; } base::string16 TypeConverter<const char*>::ToString(const char* source_value) { return base::UTF8ToUTF16(source_value); } base::string16 TypeConverter<gfx::ShadowValues>::ToString( const gfx::ShadowValues& source_value) { base::string16 ret = base::ASCIIToUTF16("["); for (auto shadow_value : source_value) { ret += base::ASCIIToUTF16(" " + shadow_value.ToString() + ";"); } ret[ret.length() - 1] = ' '; ret += base::ASCIIToUTF16("]"); return ret; } base::string16 TypeConverter<gfx::Range>::ToString( const gfx::Range& source_value) { return base::ASCIIToUTF16(base::StringPrintf( "{%i, %i}", source_value.GetMin(), source_value.GetMax())); } base::Optional<int8_t> TypeConverter<int8_t>::FromString( const base::string16& source_value) { int32_t ret = 0; if (base::StringToInt(source_value, &ret) && base::IsValueInRangeForNumericType<int8_t>(ret)) { return static_cast<int8_t>(ret); } return base::nullopt; } base::Optional<int16_t> TypeConverter<int16_t>::FromString( const base::string16& source_value) { int32_t ret = 0; if (base::StringToInt(source_value, &ret) && base::IsValueInRangeForNumericType<int16_t>(ret)) { return static_cast<int16_t>(ret); } return base::nullopt; } base::Optional<int32_t> TypeConverter<int32_t>::FromString( const base::string16& source_value) { int value; return base::StringToInt(source_value, &value) ? base::make_optional(value) : base::nullopt; } base::Optional<int64_t> TypeConverter<int64_t>::FromString( const base::string16& source_value) { int64_t value; return base::StringToInt64(source_value, &value) ? base::make_optional(value) : base::nullopt; } base::Optional<uint8_t> TypeConverter<uint8_t>::FromString( const base::string16& source_value) { uint32_t ret = 0; if (base::StringToUint(source_value, &ret) && base::IsValueInRangeForNumericType<uint8_t>(ret)) { return static_cast<uint8_t>(ret); } return base::nullopt; } base::Optional<uint16_t> TypeConverter<uint16_t>::FromString( const base::string16& source_value) { uint32_t ret = 0; if (base::StringToUint(source_value, &ret) && base::IsValueInRangeForNumericType<uint16_t>(ret)) { return static_cast<uint16_t>(ret); } return base::nullopt; } base::Optional<uint32_t> TypeConverter<uint32_t>::FromString( const base::string16& source_value) { unsigned int value; return base::StringToUint(source_value, &value) ? base::make_optional(value) : base::nullopt; } base::Optional<uint64_t> TypeConverter<uint64_t>::FromString( const base::string16& source_value) { uint64_t value; return base::StringToUint64(source_value, &value) ? base::make_optional(value) : base::nullopt; } base::Optional<float> TypeConverter<float>::FromString( const base::string16& source_value) { if (base::Optional<double> temp = TypeConverter<double>::FromString(source_value)) return static_cast<float>(temp.value()); return base::nullopt; } base::Optional<double> TypeConverter<double>::FromString( const base::string16& source_value) { double value; return base::StringToDouble(base::UTF16ToUTF8(source_value), &value) ? base::make_optional(value) : base::nullopt; } base::Optional<bool> TypeConverter<bool>::FromString( const base::string16& source_value) { const bool is_true = source_value == base::ASCIIToUTF16("true"); if (is_true || source_value == base::ASCIIToUTF16("false")) return is_true; return base::nullopt; } base::Optional<gfx::Size> TypeConverter<gfx::Size>::FromString( const base::string16& source_value) { const auto values = base::SplitStringPiece(source_value, base::ASCIIToUTF16("{,}"), base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); int width, height; if ((values.size() == 2) && base::StringToInt(values[0], &width) && base::StringToInt(values[1], &height)) { return gfx::Size(width, height); } return base::nullopt; } base::Optional<base::string16> TypeConverter<base::string16>::FromString( const base::string16& source_value) { return source_value; } base::Optional<gfx::ShadowValues> TypeConverter<gfx::ShadowValues>::FromString( const base::string16& source_value) { gfx::ShadowValues ret; const auto shadow_value_strings = base::SplitStringPiece(source_value, base::ASCIIToUTF16("[;]"), base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); for (auto v : shadow_value_strings) { base::string16 member_string; base::RemoveChars(v.as_string(), base::ASCIIToUTF16("()rgba"), &member_string); const auto members = base::SplitStringPiece( member_string, base::ASCIIToUTF16(","), base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); int x, y, r, g, b, a; double blur; if ((members.size() == 7) && base::StringToInt(members[0], &x) && base::StringToInt(members[1], &y) && base::StringToDouble(UTF16ToASCII(members[2]), &blur) && base::StringToInt(members[3], &r) && base::StringToInt(members[4], &g) && base::StringToInt(members[5], &b) && base::StringToInt(members[6], &a)) ret.emplace_back(gfx::Vector2d(x, y), blur, SkColorSetARGB(a, r, g, b)); } return ret; } base::Optional<gfx::Range> TypeConverter<gfx::Range>::FromString( const base::string16& source_value) { const auto values = base::SplitStringPiece(source_value, base::ASCIIToUTF16("{,}"), base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); int min, max; if ((values.size() == 2) && base::StringToInt(values[0], &min) && base::StringToInt(values[1], &max)) { return gfx::Range(min, max); } return base::nullopt; } } // namespace metadata } // namespace views DEFINE_ENUM_CONVERTERS(gfx::HorizontalAlignment, {gfx::HorizontalAlignment::ALIGN_LEFT, base::ASCIIToUTF16("ALIGN_LEFT")}, {gfx::HorizontalAlignment::ALIGN_CENTER, base::ASCIIToUTF16("ALIGN_CENTER")}, {gfx::HorizontalAlignment::ALIGN_RIGHT, base::ASCIIToUTF16("ALIGN_RIGHT")}, {gfx::HorizontalAlignment::ALIGN_TO_HEAD, base::ASCIIToUTF16("ALIGN_TO_HEAD")}) DEFINE_ENUM_CONVERTERS( gfx::VerticalAlignment, {gfx::VerticalAlignment::ALIGN_TOP, base::ASCIIToUTF16("ALIGN_TOP")}, {gfx::VerticalAlignment::ALIGN_MIDDLE, base::ASCIIToUTF16("ALIGN_MIDDLE")}, {gfx::VerticalAlignment::ALIGN_BOTTOM, base::ASCIIToUTF16("ALIGN_BOTTOM")}) DEFINE_ENUM_CONVERTERS( gfx::ElideBehavior, {gfx::ElideBehavior::NO_ELIDE, base::ASCIIToUTF16("NO_ELIDE")}, {gfx::ElideBehavior::TRUNCATE, base::ASCIIToUTF16("TRUNCATE")}, {gfx::ElideBehavior::ELIDE_HEAD, base::ASCIIToUTF16("ELIDE_HEAD")}, {gfx::ElideBehavior::ELIDE_MIDDLE, base::ASCIIToUTF16("ELIDE_MIDDLE")}, {gfx::ElideBehavior::ELIDE_TAIL, base::ASCIIToUTF16("ELIDE_TAIL")}, {gfx::ElideBehavior::ELIDE_EMAIL, base::ASCIIToUTF16("ELIDE_EMAIL")}, {gfx::ElideBehavior::FADE_TAIL, base::ASCIIToUTF16("FADE_TAIL")}) DEFINE_ENUM_CONVERTERS(ui::TextInputType, {ui::TextInputType::TEXT_INPUT_TYPE_NONE, base::ASCIIToUTF16("TEXT_INPUT_TYPE_NONE")}, {ui::TextInputType::TEXT_INPUT_TYPE_TEXT, base::ASCIIToUTF16("TEXT_INPUT_TYPE_TEXT")}, {ui::TextInputType::TEXT_INPUT_TYPE_PASSWORD, base::ASCIIToUTF16("TEXT_INPUT_TYPE_PASSWORD")}, {ui::TextInputType::TEXT_INPUT_TYPE_SEARCH, base::ASCIIToUTF16("TEXT_INPUT_TYPE_SEARCH")}, {ui::TextInputType::TEXT_INPUT_TYPE_EMAIL, base::ASCIIToUTF16("EXT_INPUT_TYPE_EMAIL")}, {ui::TextInputType::TEXT_INPUT_TYPE_NUMBER, base::ASCIIToUTF16("TEXT_INPUT_TYPE_NUMBER")}, {ui::TextInputType::TEXT_INPUT_TYPE_TELEPHONE, base::ASCIIToUTF16("TEXT_INPUT_TYPE_TELEPHONE")}, {ui::TextInputType::TEXT_INPUT_TYPE_URL, base::ASCIIToUTF16("TEXT_INPUT_TYPE_URL")}, {ui::TextInputType::TEXT_INPUT_TYPE_DATE, base::ASCIIToUTF16("TEXT_INPUT_TYPE_DATE")}, {ui::TextInputType::TEXT_INPUT_TYPE_DATE_TIME, base::ASCIIToUTF16("TEXT_INPUT_TYPE_DATE_TIME")}, {ui::TextInputType::TEXT_INPUT_TYPE_DATE_TIME_LOCAL, base::ASCIIToUTF16("TEXT_INPUT_TYPE_DATE_TIME_LOCAL")}, {ui::TextInputType::TEXT_INPUT_TYPE_MONTH, base::ASCIIToUTF16("TEXT_INPUT_TYPE_MONTH")}, {ui::TextInputType::TEXT_INPUT_TYPE_TIME, base::ASCIIToUTF16("TEXT_INPUT_TYPE_TIME")}, {ui::TextInputType::TEXT_INPUT_TYPE_WEEK, base::ASCIIToUTF16("TEXT_INPUT_TYPE_WEEK")}, {ui::TextInputType::TEXT_INPUT_TYPE_TEXT_AREA, base::ASCIIToUTF16("TEXT_INPUT_TYPE_TEXT_AREA")}, {ui::TextInputType::TEXT_INPUT_TYPE_CONTENT_EDITABLE, base::ASCIIToUTF16("TEXT_INPUT_TYPE_CONTENT_EDITABLE")}, {ui::TextInputType::TEXT_INPUT_TYPE_DATE_TIME_FIELD, base::ASCIIToUTF16("TEXT_INPUT_TYPE_DATE_TIME_FIELD")}, {ui::TextInputType::TEXT_INPUT_TYPE_MAX, base::ASCIIToUTF16("TEXT_INPUT_TYPE_MAX")})
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
d19b7bbc064e24678585ee7226a3fb3910129103
34111b1448ffa98cee2977c858066fbc38396341
/src/ros/base_fusion_ros.cpp
d6e466161a9b6758dc9b61f1e5c90711bfd8a95c
[]
no_license
tienhoangvan/dynamic_objects_fusion
6bd5cf4fb0e01e9242abafc3658f324572495198
921885375d22325dcee02dc87513e4a74f661da0
refs/heads/master
2022-03-31T06:53:36.753516
2019-12-19T02:48:51
2019-12-19T02:48:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,513
cpp
// // Created by shivesh on 12/16/19. // #include "dynamic_objects_fusion/ros/base_fusion_ros.hpp" namespace dynamic_objects_fusion { BaseFusionROS::BaseFusionROS() { } BaseFusionROS::~BaseFusionROS() { } void BaseFusionROS::initialize(DynamicObjectsFusion* dynamic_objects_fusion, int id) { dynamic_objects_fusion_ = dynamic_objects_fusion; id_ = id; } std::shared_ptr<SensorObject> BaseFusionROS::object_to_sensor_object(const dynamic_objects_fusion::Object object) { std::shared_ptr<SensorObject> sensor_object = std::make_shared<SensorObject>(); sensor_object->id_ = object.id; sensor_object->length_ = object.length; sensor_object->width_ = object.width; // sensor_object->height_ = object.height; tf2::Quaternion q; q.setValue( object.position.pose.orientation.x, object.position.pose.orientation.y, object.position.pose.orientation.z, object.position.pose.orientation.w); tf2::Matrix3x3 m(q); double roll, pitch, yaw; m.getRPY(roll, pitch, yaw); if (isnan(yaw)) { yaw = 0; } sensor_object->orientation_ = yaw; sensor_object->position_[0] = object.position.pose.position.x; sensor_object->position_[1] = object.position.pose.position.y; sensor_object->position_[2] = object.position.pose.position.z; sensor_object->position_covariance_[0] = object.position.covariance[0]; sensor_object->position_covariance_[1] = object.position.covariance[7]; sensor_object->position_covariance_[2] = object.position.covariance[14]; sensor_object->velocity_[0] = object.relative_velocity.twist.linear.x; sensor_object->velocity_[1] = object.relative_velocity.twist.linear.y; sensor_object->velocity_[2] = object.relative_velocity.twist.linear.z; sensor_object->velocity_covariance_[0] = object.relative_velocity.covariance[0]; sensor_object->velocity_covariance_[1] = object.relative_velocity.covariance[7]; sensor_object->velocity_covariance_[2] = object.relative_velocity.covariance[14]; sensor_object->acceleration_[0] = object.relative_acceleration.accel.linear.x; sensor_object->acceleration_[1] = object.relative_acceleration.accel.linear.y; sensor_object->acceleration_[2] = object.relative_acceleration.accel.linear.z; sensor_object->acceleration_covariance_[0] = object.relative_acceleration.covariance[0]; sensor_object->acceleration_covariance_[1] = object.relative_acceleration.covariance[7]; sensor_object->acceleration_covariance_[2] = object.relative_acceleration.covariance[14]; return sensor_object; } }
[ "shiveshkhaitan@gmail.com" ]
shiveshkhaitan@gmail.com
f2c84f982547f83cb09b38b7eb9f01e1397ffd7f
bbb82acb25321dddf5212d89cc007d85b1d1d0c1
/ctriangle.cpp
cc5cc9fc6423e7e6369e1cecc3deb984fc024c7f
[]
no_license
alexmikhalevich/RayTracing
67856bf72d722c0d5aa91b2dd6ff3792a667b008
19de14b32bfd068942763c8933c324a544bba38b
refs/heads/master
2021-06-30T18:25:15.620806
2016-05-28T19:55:30
2016-05-28T19:55:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,347
cpp
#include "ctriangle.h" #include <iostream> bool CTriangle::intersect(const CVector3D& ray_vector, CPoint3D& intersection) { CVector3D n = get_normal(); double scalar_product = CVector3D::dot_product(n, ray_vector); if(fabs(scalar_product) < EPS) return false; double d = -(m_vertices[0].get_x() * n.get_coordinates().get_x() + m_vertices[0].get_y() * n.get_coordinates().get_y() + m_vertices[0].get_z() * n.get_coordinates().get_z()); double coeff = -(n.get_coordinates().get_x() * ray_vector.get_coordinates().get_x() + n.get_coordinates().get_y() * ray_vector.get_coordinates().get_y() + n.get_coordinates().get_z() * ray_vector.get_coordinates().get_z() + d) / scalar_product; if(coeff < EPS) return false; double x = ray_vector.get_begin().get_x() + ray_vector.get_coordinates().get_x() * coeff; double y = ray_vector.get_begin().get_y() + ray_vector.get_coordinates().get_y() * coeff; double z = ray_vector.get_begin().get_z() + ray_vector.get_coordinates().get_z() * coeff; CPoint3D intr(x, y, z); if(CVector3D::same_clock_dir(CVector3D(m_vertices[0], m_vertices[1]), CVector3D(m_vertices[0], intr), n) && CVector3D::same_clock_dir(CVector3D(m_vertices[1], m_vertices[2]), CVector3D(m_vertices[1], intr), n) && CVector3D::same_clock_dir(CVector3D(m_vertices[2], m_vertices[0]), CVector3D(m_vertices[2], intr), n)) { intersection = intr; return true; } else return false; } CColor CTriangle::get_intersection_color(const CPoint3D& intersection) { return m_material.get_color(); //TODO: add support for textures } CVector3D CTriangle::get_normal_vector(const CPoint3D& intersection) { return get_normal(); } CPoint3D CTriangle::get_max_boundary_point() const { return CPoint3D(std::max(m_vertices[0].get_x(), std::max(m_vertices[1].get_x(), m_vertices[2].get_x())), std::max(m_vertices[0].get_y(), std::max(m_vertices[1].get_y(), m_vertices[2].get_y())), std::max(m_vertices[0].get_z(), std::max(m_vertices[1].get_z(), m_vertices[2].get_z()))); } CPoint3D CTriangle::get_min_boundary_point() const { return CPoint3D(std::min(m_vertices[0].get_x(), std::min(m_vertices[1].get_x(), m_vertices[2].get_x())), std::min(m_vertices[0].get_y(), std::min(m_vertices[1].get_y(), m_vertices[2].get_y())), std::min(m_vertices[0].get_z(), std::min(m_vertices[1].get_z(), m_vertices[2].get_z()))); }
[ "alex.mikhalevich@gmail.com" ]
alex.mikhalevich@gmail.com
be86e8e82cb4eac109936ad5be1edc208c7e4293
a67af182c81adf11d4f124504e8bd75adefaf762
/src/main.cpp
9c08564fdbf1e5458da408c2c787c63f90a16761
[]
no_license
zeehjr/esp32-smart-home
deac79ad440e99bd113783b39bf585c343945e09
294cbe5b0764e1445873a5e3e23450eb8b8ed2ce
refs/heads/master
2022-12-07T22:30:04.265532
2020-08-30T21:40:52
2020-08-30T21:40:52
291,556,435
0
0
null
null
null
null
UTF-8
C++
false
false
2,045
cpp
#include <Arduino.h> #include <WiFi.h> #include <HTTPClient.h> struct PORT { int port; uint8_t state; uint8_t desiredState; }; PORT LED1; PORT LED2; PORT LED3; const int DELAY = 2000; const char *ssid = "zezin"; const char *password = "sofiaalice2016"; void setup() { LED1.port = 2; LED2.port = 4; LED3.port = 5; LED1.state = LOW; LED1.desiredState = LOW; LED2.state = LOW; LED3.desiredState = LOW; LED3.state = LOW; LED3.desiredState = LOW; pinMode(LED1.port, OUTPUT); pinMode(LED2.port, OUTPUT); pinMode(LED3.port, OUTPUT); Serial.begin(9600); WiFi.begin(ssid, password); Serial.println(); Serial.print("WiFi: Connecting..."); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.println("WiFi: Connected!"); } void checkPort(PORT *port) { if (port->state != port->desiredState) { Serial.printf("PORT: %d - DESIRED: %d - CURRENT: %d \n", port->port, port->desiredState, port->state); port->state = port->desiredState; digitalWrite(port->port, port->state); } Serial.printf("AFTER :: Desired %d, Current %d \n", port->desiredState, port->state); } void checkPorts() { Serial.println("Will check LED1"); checkPort(&LED1); Serial.println("Will check LED2"); checkPort(&LED2); Serial.println("Will check LED3"); checkPort(&LED3); } void updateLeds() { HTTPClient client; client.begin("http://192.168.0.3:3000/esp/states"); int resCode = client.GET(); if (resCode <= 0) { Serial.println("Cannot fetch states from server! We will wait 5 seconds."); delay(5000); return; } String response = client.getString(); if (response.length() != 3) { Serial.println("The response from server has length different than 3."); return; } LED1.desiredState = response[0] == '1' ? HIGH : LOW; LED2.desiredState = response[1] == '1' ? HIGH : LOW; LED3.desiredState = response[2] == '1' ? HIGH : LOW; checkPorts(); } void loop() { updateLeds(); delay(200); }
[ "zeehtecnologia@gmail.com" ]
zeehtecnologia@gmail.com
479f8d38e6e171de6e7605224ec424f1b79ae55e
828806e0cd8d08a2e5c69ab8137b01c54eec8fad
/Event-Creator/Datastore.cpp
28bfd85c49aef7ff2a125f7b0f5a6d9d61fc4cfa
[]
no_license
cgddrd/Endurance-Race-Tracker
5ea5e68f74552cfce8cfcd6c16cc72bd4474fb8d
4cbad054e937320ee1fd28fd15c7f89349a737b3
refs/heads/master
2021-01-18T14:13:54.252239
2013-03-19T20:05:58
2013-03-19T20:05:58
8,357,731
1
0
null
null
null
null
UTF-8
C++
false
false
3,963
cpp
/* * File: Datastore.cpp * Description: Contains and stores all the persistent data used * by the application to allow data to be accessed by multiple classes. * Author: Connor Luke Goddard (clg11) * Date: March 2013 * Copyright: Aberystwyth University, Aberystwyth */ #include "Datastore.h" using namespace std; /** * Default constructor for Datastore. * Sets the initial value of the 'event' pointer to NULL for * error checking purposes. */ Datastore::Datastore() { event = NULL; } /** * Destructor to be used once object is removed. */ Datastore::~Datastore() { delete event; } /** * Fetches the vector of all the courses created for an event. * @return A vector that contains pointers to all the Course objects created. */ vector<Course*> Datastore::getCourseList(void){ return courseList; } /** * Fetches the vector of all the nodes read in from "nodes.txt". * @return A vector that contains pointers to all the Node objects. */ vector<Node*> Datastore::getNodeList(void) { return nodeList; } /** * Fetches the vector of all the entrants created for an event. * @return A vector that contains pointers to all the Entrant objects created. */ vector<Entrant*> Datastore::getEntrantList(void){ return entrantList; } /** * Fetches the Event object created to define the race event. * @return A a pointer to the created Event object. */ Event* Datastore::getEvent(void) const { return event; } /** * Adds a new Course object to the end of the 'courseList' vector. * @param newCourse Pointer to the new Course object to be added to the vector. */ void Datastore::addNewCourse (Course *newCourse) { courseList.push_back(newCourse); } /** * Adds a new Node object to the end of the 'nodeList' vector. * @param newNode Pointer to the new Node object to be added to the vector. */ void Datastore::addNewNode (Node *newNode) { nodeList.push_back(newNode); } /** * Adds a new Entrant object to the end of the 'courseEntrant' vector. * @param newEntrant Pointer to the new Entrant object to be added to the vector. */ void Datastore::addNewEntrant (Entrant *newEntrant) { entrantList.push_back(newEntrant); } /** * Sets the 'event' pointer to a newly created Event object. * @param newEvent A pointer to the new Event object created. */ void Datastore::setNewEvent(Event *newEvent) { this->event = newEvent; } /** * Determines if a course with the inputted ID exists in the vector of * courses ('courseList') and if so returns the pointer to that Course object. * @param selectedID The course ID inputted by the user. * @return Either the located course or NULL. */ Course* Datastore::getInCourse (char selectedID) { //Loop through the entire vector of courses. for (vector<Course*>::iterator it = courseList.begin(); it != courseList.end(); ++it) { //If the ID of the current course matches the inputted ID... if ((*it)->getCourseID() == selectedID) { //... return the pointer to that Course object. return (*it); } } //Otherwise if no matches are found, return NULL. return NULL; } /** * Determines if a node with the inputted number exists in the vector of * nodes ('nodeList') and if so returns the pointer to that Node object. * @param nodeNo The node number inputted by the user. * @return Either a pointer to the located Node object or NULL. */ Node* Datastore::obtainNode (int nodeNo) { //Loop through the entire vector of courses. for (vector<Node*>::iterator it = nodeList.begin(); it != nodeList.end(); ++it) { //If the number of the current node matches the inputted number... if ((*it)->getNodeNo() == nodeNo) { //... return the pointer to that Node object. return (*it); } } //Otherwise if no matches are found, return NULL. return NULL; }
[ "clg11@aber.ac.uk" ]
clg11@aber.ac.uk
6747ec019b823351b905b3a1bf436f3976157b46
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/chrome/browser/sharing/webrtc/sharing_mojo_service.cc
e8ecaee9d19611addcbe771d4fa2cb2fadaf679d
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
716
cc
// Copyright 2020 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/sharing/webrtc/sharing_mojo_service.h" #include "chrome/browser/service_sandbox_type.h" #include "content/public/browser/service_process_host.h" namespace sharing { mojo::PendingRemote<mojom::Sharing> LaunchSharing() { mojo::PendingRemote<mojom::Sharing> remote; content::ServiceProcessHost::Launch<mojom::Sharing>( remote.InitWithNewPipeAndPassReceiver(), content::ServiceProcessHost::Options() .WithDisplayName("Sharing Service") .Pass()); return remote; } } // namespace sharing
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
131233a1e943a2f8de5aa13b9a0f2108bb1ef669
1168562b8c7e6784a3cfad587dd545b7893b908d
/src/gcs_test/include/uavmessage.pb.h
2cbe6f402b84edef400b8ddf071af2ad8975fe17
[]
no_license
MeMiracle/UAV-Swarm-Control
9d50999515a0155916a239f8784c7a6e0ddc133e
ce55a99fea7292b1dad19d29a0261f554049ffa3
refs/heads/master
2023-01-31T20:08:24.413188
2020-12-19T14:11:53
2020-12-19T14:11:53
284,892,654
4
1
null
null
null
null
UTF-8
C++
false
true
21,287
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: uavmessage.proto #ifndef PROTOBUF_uavmessage_2eproto__INCLUDED #define PROTOBUF_uavmessage_2eproto__INCLUDED #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 3004000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) namespace uavMessage { class Message; class MessageDefaultTypeInternal; extern MessageDefaultTypeInternal _Message_default_instance_; class MsgHead; class MsgHeadDefaultTypeInternal; extern MsgHeadDefaultTypeInternal _MsgHead_default_instance_; } // namespace uavMessage namespace uavMessage { namespace protobuf_uavmessage_2eproto { // Internal implementation detail -- do not call these. struct TableStruct { static const ::google::protobuf::internal::ParseTableField entries[]; static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; static const ::google::protobuf::internal::ParseTable schema[]; static const ::google::protobuf::uint32 offsets[]; static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static void InitDefaultsImpl(); }; void AddDescriptors(); void InitDefaults(); } // namespace protobuf_uavmessage_2eproto // =================================================================== class MsgHead : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:uavMessage.MsgHead) */ { public: MsgHead(); virtual ~MsgHead(); MsgHead(const MsgHead& from); inline MsgHead& operator=(const MsgHead& from) { CopyFrom(from); return *this; } #if LANG_CXX11 MsgHead(MsgHead&& from) noexcept : MsgHead() { *this = ::std::move(from); } inline MsgHead& operator=(MsgHead&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const MsgHead& default_instance(); static inline const MsgHead* internal_default_instance() { return reinterpret_cast<const MsgHead*>( &_MsgHead_default_instance_); } static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = 0; void Swap(MsgHead* other); friend void swap(MsgHead& a, MsgHead& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline MsgHead* New() const PROTOBUF_FINAL { return New(NULL); } MsgHead* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL; void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void CopyFrom(const MsgHead& from); void MergeFrom(const MsgHead& from); void Clear() PROTOBUF_FINAL; bool IsInitialized() const PROTOBUF_FINAL; size_t ByteSizeLong() const PROTOBUF_FINAL; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const PROTOBUF_FINAL; void InternalSwap(MsgHead* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated uint32 tgt_uav_id = 10; int tgt_uav_id_size() const; void clear_tgt_uav_id(); static const int kTgtUavIdFieldNumber = 10; ::google::protobuf::uint32 tgt_uav_id(int index) const; void set_tgt_uav_id(int index, ::google::protobuf::uint32 value); void add_tgt_uav_id(::google::protobuf::uint32 value); const ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >& tgt_uav_id() const; ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >* mutable_tgt_uav_id(); // uint32 stx = 1; void clear_stx(); static const int kStxFieldNumber = 1; ::google::protobuf::uint32 stx() const; void set_stx(::google::protobuf::uint32 value); // uint32 msg_type = 2; void clear_msg_type(); static const int kMsgTypeFieldNumber = 2; ::google::protobuf::uint32 msg_type() const; void set_msg_type(::google::protobuf::uint32 value); // uint32 cluster_id = 3; void clear_cluster_id(); static const int kClusterIdFieldNumber = 3; ::google::protobuf::uint32 cluster_id() const; void set_cluster_id(::google::protobuf::uint32 value); // uint32 src_uav_id = 4; void clear_src_uav_id(); static const int kSrcUavIdFieldNumber = 4; ::google::protobuf::uint32 src_uav_id() const; void set_src_uav_id(::google::protobuf::uint32 value); // uint32 tgt_uav_count = 5; void clear_tgt_uav_count(); static const int kTgtUavCountFieldNumber = 5; ::google::protobuf::uint32 tgt_uav_count() const; void set_tgt_uav_count(::google::protobuf::uint32 value); // uint32 topic_id = 6; void clear_topic_id(); static const int kTopicIdFieldNumber = 6; ::google::protobuf::uint32 topic_id() const; void set_topic_id(::google::protobuf::uint32 value); // uint32 msg_id = 7; void clear_msg_id(); static const int kMsgIdFieldNumber = 7; ::google::protobuf::uint32 msg_id() const; void set_msg_id(::google::protobuf::uint32 value); // uint32 msg_length = 8; void clear_msg_length(); static const int kMsgLengthFieldNumber = 8; ::google::protobuf::uint32 msg_length() const; void set_msg_length(::google::protobuf::uint32 value); // uint32 seq_num = 9; void clear_seq_num(); static const int kSeqNumFieldNumber = 9; ::google::protobuf::uint32 seq_num() const; void set_seq_num(::google::protobuf::uint32 value); // uint32 reserved = 20; void clear_reserved(); static const int kReservedFieldNumber = 20; ::google::protobuf::uint32 reserved() const; void set_reserved(::google::protobuf::uint32 value); // @@protoc_insertion_point(class_scope:uavMessage.MsgHead) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::RepeatedField< ::google::protobuf::uint32 > tgt_uav_id_; mutable int _tgt_uav_id_cached_byte_size_; ::google::protobuf::uint32 stx_; ::google::protobuf::uint32 msg_type_; ::google::protobuf::uint32 cluster_id_; ::google::protobuf::uint32 src_uav_id_; ::google::protobuf::uint32 tgt_uav_count_; ::google::protobuf::uint32 topic_id_; ::google::protobuf::uint32 msg_id_; ::google::protobuf::uint32 msg_length_; ::google::protobuf::uint32 seq_num_; ::google::protobuf::uint32 reserved_; mutable int _cached_size_; friend struct protobuf_uavmessage_2eproto::TableStruct; }; // ------------------------------------------------------------------- class Message : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:uavMessage.Message) */ { public: Message(); virtual ~Message(); Message(const Message& from); inline Message& operator=(const Message& from) { CopyFrom(from); return *this; } #if LANG_CXX11 Message(Message&& from) noexcept : Message() { *this = ::std::move(from); } inline Message& operator=(Message&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const Message& default_instance(); static inline const Message* internal_default_instance() { return reinterpret_cast<const Message*>( &_Message_default_instance_); } static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = 1; void Swap(Message* other); friend void swap(Message& a, Message& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline Message* New() const PROTOBUF_FINAL { return New(NULL); } Message* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL; void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void CopyFrom(const Message& from); void MergeFrom(const Message& from); void Clear() PROTOBUF_FINAL; bool IsInitialized() const PROTOBUF_FINAL; size_t ByteSizeLong() const PROTOBUF_FINAL; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const PROTOBUF_FINAL; void InternalSwap(Message* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // bytes playload = 2; void clear_playload(); static const int kPlayloadFieldNumber = 2; const ::std::string& playload() const; void set_playload(const ::std::string& value); #if LANG_CXX11 void set_playload(::std::string&& value); #endif void set_playload(const char* value); void set_playload(const void* value, size_t size); ::std::string* mutable_playload(); ::std::string* release_playload(); void set_allocated_playload(::std::string* playload); // .uavMessage.MsgHead msghead = 1; bool has_msghead() const; void clear_msghead(); static const int kMsgheadFieldNumber = 1; const ::uavMessage::MsgHead& msghead() const; ::uavMessage::MsgHead* mutable_msghead(); ::uavMessage::MsgHead* release_msghead(); void set_allocated_msghead(::uavMessage::MsgHead* msghead); // @@protoc_insertion_point(class_scope:uavMessage.Message) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr playload_; ::uavMessage::MsgHead* msghead_; mutable int _cached_size_; friend struct protobuf_uavmessage_2eproto::TableStruct; }; // =================================================================== // =================================================================== #if !PROTOBUF_INLINE_NOT_IN_HEADERS #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // MsgHead // uint32 stx = 1; inline void MsgHead::clear_stx() { stx_ = 0u; } inline ::google::protobuf::uint32 MsgHead::stx() const { // @@protoc_insertion_point(field_get:uavMessage.MsgHead.stx) return stx_; } inline void MsgHead::set_stx(::google::protobuf::uint32 value) { stx_ = value; // @@protoc_insertion_point(field_set:uavMessage.MsgHead.stx) } // uint32 msg_type = 2; inline void MsgHead::clear_msg_type() { msg_type_ = 0u; } inline ::google::protobuf::uint32 MsgHead::msg_type() const { // @@protoc_insertion_point(field_get:uavMessage.MsgHead.msg_type) return msg_type_; } inline void MsgHead::set_msg_type(::google::protobuf::uint32 value) { msg_type_ = value; // @@protoc_insertion_point(field_set:uavMessage.MsgHead.msg_type) } // uint32 cluster_id = 3; inline void MsgHead::clear_cluster_id() { cluster_id_ = 0u; } inline ::google::protobuf::uint32 MsgHead::cluster_id() const { // @@protoc_insertion_point(field_get:uavMessage.MsgHead.cluster_id) return cluster_id_; } inline void MsgHead::set_cluster_id(::google::protobuf::uint32 value) { cluster_id_ = value; // @@protoc_insertion_point(field_set:uavMessage.MsgHead.cluster_id) } // uint32 src_uav_id = 4; inline void MsgHead::clear_src_uav_id() { src_uav_id_ = 0u; } inline ::google::protobuf::uint32 MsgHead::src_uav_id() const { // @@protoc_insertion_point(field_get:uavMessage.MsgHead.src_uav_id) return src_uav_id_; } inline void MsgHead::set_src_uav_id(::google::protobuf::uint32 value) { src_uav_id_ = value; // @@protoc_insertion_point(field_set:uavMessage.MsgHead.src_uav_id) } // uint32 tgt_uav_count = 5; inline void MsgHead::clear_tgt_uav_count() { tgt_uav_count_ = 0u; } inline ::google::protobuf::uint32 MsgHead::tgt_uav_count() const { // @@protoc_insertion_point(field_get:uavMessage.MsgHead.tgt_uav_count) return tgt_uav_count_; } inline void MsgHead::set_tgt_uav_count(::google::protobuf::uint32 value) { tgt_uav_count_ = value; // @@protoc_insertion_point(field_set:uavMessage.MsgHead.tgt_uav_count) } // uint32 topic_id = 6; inline void MsgHead::clear_topic_id() { topic_id_ = 0u; } inline ::google::protobuf::uint32 MsgHead::topic_id() const { // @@protoc_insertion_point(field_get:uavMessage.MsgHead.topic_id) return topic_id_; } inline void MsgHead::set_topic_id(::google::protobuf::uint32 value) { topic_id_ = value; // @@protoc_insertion_point(field_set:uavMessage.MsgHead.topic_id) } // uint32 msg_id = 7; inline void MsgHead::clear_msg_id() { msg_id_ = 0u; } inline ::google::protobuf::uint32 MsgHead::msg_id() const { // @@protoc_insertion_point(field_get:uavMessage.MsgHead.msg_id) return msg_id_; } inline void MsgHead::set_msg_id(::google::protobuf::uint32 value) { msg_id_ = value; // @@protoc_insertion_point(field_set:uavMessage.MsgHead.msg_id) } // uint32 msg_length = 8; inline void MsgHead::clear_msg_length() { msg_length_ = 0u; } inline ::google::protobuf::uint32 MsgHead::msg_length() const { // @@protoc_insertion_point(field_get:uavMessage.MsgHead.msg_length) return msg_length_; } inline void MsgHead::set_msg_length(::google::protobuf::uint32 value) { msg_length_ = value; // @@protoc_insertion_point(field_set:uavMessage.MsgHead.msg_length) } // uint32 seq_num = 9; inline void MsgHead::clear_seq_num() { seq_num_ = 0u; } inline ::google::protobuf::uint32 MsgHead::seq_num() const { // @@protoc_insertion_point(field_get:uavMessage.MsgHead.seq_num) return seq_num_; } inline void MsgHead::set_seq_num(::google::protobuf::uint32 value) { seq_num_ = value; // @@protoc_insertion_point(field_set:uavMessage.MsgHead.seq_num) } // repeated uint32 tgt_uav_id = 10; inline int MsgHead::tgt_uav_id_size() const { return tgt_uav_id_.size(); } inline void MsgHead::clear_tgt_uav_id() { tgt_uav_id_.Clear(); } inline ::google::protobuf::uint32 MsgHead::tgt_uav_id(int index) const { // @@protoc_insertion_point(field_get:uavMessage.MsgHead.tgt_uav_id) return tgt_uav_id_.Get(index); } inline void MsgHead::set_tgt_uav_id(int index, ::google::protobuf::uint32 value) { tgt_uav_id_.Set(index, value); // @@protoc_insertion_point(field_set:uavMessage.MsgHead.tgt_uav_id) } inline void MsgHead::add_tgt_uav_id(::google::protobuf::uint32 value) { tgt_uav_id_.Add(value); // @@protoc_insertion_point(field_add:uavMessage.MsgHead.tgt_uav_id) } inline const ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >& MsgHead::tgt_uav_id() const { // @@protoc_insertion_point(field_list:uavMessage.MsgHead.tgt_uav_id) return tgt_uav_id_; } inline ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >* MsgHead::mutable_tgt_uav_id() { // @@protoc_insertion_point(field_mutable_list:uavMessage.MsgHead.tgt_uav_id) return &tgt_uav_id_; } // uint32 reserved = 20; inline void MsgHead::clear_reserved() { reserved_ = 0u; } inline ::google::protobuf::uint32 MsgHead::reserved() const { // @@protoc_insertion_point(field_get:uavMessage.MsgHead.reserved) return reserved_; } inline void MsgHead::set_reserved(::google::protobuf::uint32 value) { reserved_ = value; // @@protoc_insertion_point(field_set:uavMessage.MsgHead.reserved) } // ------------------------------------------------------------------- // Message // .uavMessage.MsgHead msghead = 1; inline bool Message::has_msghead() const { return this != internal_default_instance() && msghead_ != NULL; } inline void Message::clear_msghead() { if (GetArenaNoVirtual() == NULL && msghead_ != NULL) delete msghead_; msghead_ = NULL; } inline const ::uavMessage::MsgHead& Message::msghead() const { const ::uavMessage::MsgHead* p = msghead_; // @@protoc_insertion_point(field_get:uavMessage.Message.msghead) return p != NULL ? *p : *reinterpret_cast<const ::uavMessage::MsgHead*>( &::uavMessage::_MsgHead_default_instance_); } inline ::uavMessage::MsgHead* Message::mutable_msghead() { if (msghead_ == NULL) { msghead_ = new ::uavMessage::MsgHead; } // @@protoc_insertion_point(field_mutable:uavMessage.Message.msghead) return msghead_; } inline ::uavMessage::MsgHead* Message::release_msghead() { // @@protoc_insertion_point(field_release:uavMessage.Message.msghead) ::uavMessage::MsgHead* temp = msghead_; msghead_ = NULL; return temp; } inline void Message::set_allocated_msghead(::uavMessage::MsgHead* msghead) { delete msghead_; msghead_ = msghead; if (msghead) { } else { } // @@protoc_insertion_point(field_set_allocated:uavMessage.Message.msghead) } // bytes playload = 2; inline void Message::clear_playload() { playload_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& Message::playload() const { // @@protoc_insertion_point(field_get:uavMessage.Message.playload) return playload_.GetNoArena(); } inline void Message::set_playload(const ::std::string& value) { playload_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:uavMessage.Message.playload) } #if LANG_CXX11 inline void Message::set_playload(::std::string&& value) { playload_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:uavMessage.Message.playload) } #endif inline void Message::set_playload(const char* value) { GOOGLE_DCHECK(value != NULL); playload_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:uavMessage.Message.playload) } inline void Message::set_playload(const void* value, size_t size) { playload_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:uavMessage.Message.playload) } inline ::std::string* Message::mutable_playload() { // @@protoc_insertion_point(field_mutable:uavMessage.Message.playload) return playload_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* Message::release_playload() { // @@protoc_insertion_point(field_release:uavMessage.Message.playload) return playload_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void Message::set_allocated_playload(::std::string* playload) { if (playload != NULL) { } else { } playload_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), playload); // @@protoc_insertion_point(field_set_allocated:uavMessage.Message.playload) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ #endif // !PROTOBUF_INLINE_NOT_IN_HEADERS // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace uavMessage // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_uavmessage_2eproto__INCLUDED
[ "962448801@qq.com" ]
962448801@qq.com
ced0d8577f036c8d8355554d5d50d94f5206bdf7
9a3b9d80afd88e1fa9a24303877d6e130ce22702
/src/Providers/UNIXProviders/IPHeadersFilter/UNIX_IPHeadersFilter_FREEBSD.hxx
bea681c12cacb5d8c34418517a5dc15012c3e071
[ "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,817
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_FREEBSD #ifndef __UNIX_IPHEADERSFILTER_PRIVATE_H #define __UNIX_IPHEADERSFILTER_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
114fa5cd433305e7cb1e42cfa6e3135359fedb63
86f1b47aac824eb3f1f24d025c8a8d618c952d0d
/uva/914 - Jumping Champion.cpp
71e65cffcc5d4c4651077c84576f79c6a5cfbc3b
[]
no_license
anwar-arif/acm-code
2fe9b2f71c3cc65d2aa680475300acbeab551532
ad9c6f3f2a82bf231f848e9934faf9b5e591e923
refs/heads/master
2023-02-07T16:35:25.368871
2023-01-30T08:38:41
2023-01-30T08:38:41
127,539,902
0
1
null
null
null
null
UTF-8
C++
false
false
4,563
cpp
#include <cassert> #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <sstream> #include <iomanip> #include <string> #include <vector> #include <deque> #include <list> #include <set> #include <map> #include <bitset> #include <stack> #include <queue> #include <algorithm> #include <functional> #include <iterator> #include <numeric> #include <utility> #include <fstream> #include <climits> #include <complex> #include <new> #include <memory> #include <time.h> //#include <bits/stdc++.h> using namespace std; #define pf printf #define sc scanf #define ll long long int #define sc1i(a) sc("%d",&a) #define sc2i(a,b) sc("%d%d",&a,&b) #define sc3i(a,b,c) sc("%d%d%d",&a,&b,&c) #define sc4i(a,b,c,d) sc("%d%d%d%d",&a,&b,&c,&d) #define sc1ll(a) sc("%lld",&a) #define sc2ll(a,b) sc("%lld%lld",&a,&b) #define sc3ll(a,b,c) sc("%lld%lld%lld",&a,&b,&c) #define sc4ll(a,b,c,d) sc("%lld%lld%lld%lld",&a,&b,&c,&d) #define pb push_back #define pi acos(-1.0) #define mem(a,x) memset(a,x,sizeof(a)) #define all(v) v.begin(),v.end() #define SZ(a) (int)a.size() #define MP make_pair #define ppcnt(a) __builtin_popcount(a) #define cnttz(a) __builtin_ctz(a) #define cntlz(a) __builtin_clz(a) #define Read freopen("in.txt","r",stdin) #define Write freopen("out.txt","w",stdout) #define repll(i,x,n) for(ll i = x; i <= n;i++) #define rrepll(i,x,n) for(ll i = x; i >= n;i--) #define repi(i,x,n) for(int i = x; i <= n;i++) #define rrepi(i,x,n) for(int i = x; i >= n;i--) #define ___ ios_base::sync_with_stdio(false);cin.tie(NULL); //int dx[]= {-1,-1,0,0,1,1}; //int dy[]= {-1,0,-1,1,0,1}; //int dx[]= {0,0,1,-1};//4 side move //int dy[]= {-1,1,0,0};//4 side move //int dx[]= {1,1,0,-1,-1,-1,0,1};//8 side move //int dy[]= {0,1,1,1,0,-1,-1,-1};//8 side move //int dx[]={1,1,2,2,-1,-1,-2,-2};//knight move //int dy[]={2,-2,1,-1,2,-2,1,-1};//knight move template<class T> T power(T N,T P){ return (P==0)? 1: N*power(N,P-1);}//N^P template<class T> T gcd(T a,T b){if(b == 0)return a;return gcd(b,a%b);}//gcd(a,b) template<class T1> void deb(T1 e1){cout<<e1<<endl;} template<class T1,class T2> void deb(T1 e1,T2 e2){cout<<e1<<" "<<e2<<endl;} template<class T1,class T2,class T3> void deb(T1 e1,T2 e2,T3 e3){cout<<e1<<" "<<e2<<" "<<e3<<endl;} template<class T1,class T2,class T3,class T4> void deb(T1 e1,T2 e2,T3 e3,T4 e4){cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<endl;} template<class T1,class T2,class T3,class T4,class T5> void deb(T1 e1,T2 e2,T3 e3,T4 e4,T5 e5){cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<" "<<e5<<endl;} template<class T1,class T2,class T3,class T4,class T5,class T6> void deb(T1 e1,T2 e2,T3 e3,T4 e4,T5 e5,T6 e6){cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<" "<<e5<<" "<<e6<<endl;} //ll bigmod(ll B,ll P,ll M){ ll R=1; while(P>0) {if(P%2==1){R=(R*B)%M;}P/=2;B=(B*B)%M;} return R;} /// (B^P)%M //ll gcd(ll a,ll b){if(b == 0)return a;return gcd(b,a%b);} //ll lcm(ll a,ll b){return (a/gcd(a,b))*b;} int on(int n,int pos){return n=n|(1<<pos);} void off(int &n,int pos){ n = n & ~(1<<pos);} bool check(int n,int pos){return (bool)(n&(1<<pos));} //N & (N % 2 ? 0 : ~0) | ( ((N & 2)>>1) ^ (N & 1) )://XOR of 1-n numbers const int M = 1000000; int status[(M/32) + 5] , k , primes[100000]; void cal(){ for(int i = 3; i*i <= M ;i += 2){ if(check(status[i >> 5] , i&31) == 0){ for(int j = i*i ; j <= M; j += (i << 1) ){ status[j >> 5] = on(status[j >> 5] , j&31) ; } } } k = 0 ; primes[++k] = 2; for(int i = 3; i <= M; i+=2){ if(check(status[i >> 5] , i&31) == 0)primes[++k] = i; } } int cnt[500]; int main() { #ifndef ONLINE_JUDGE //Read; //Write; // freopen("C:/Users/anwar_sust/Desktop/input.txt","r",stdin); #endif int n; cal(); int tst , a, b , l , r; sc1i(tst) ; while(tst--){ sc2i(a,b); l = lower_bound(primes+1,primes+1+k,a) - primes; r = lower_bound(primes+1,primes+1+k,b) - primes; if(primes[r] > b)--r; mem(cnt , 0); int ans = 0 , mx = 0; for(int i = l+1;i <= r;i++){ int d = primes[i] - primes[i - 1]; if(++cnt[d] > mx){ mx = cnt[d] ; ans = d; } } int tot = 0 ; for(int i = 1; i < 500; i++){ if(cnt[i] == mx){ ++tot; if(tot > 1)break; } } if(tot > 1 || ans == 0 )pf("No jumping champion\n"); else pf("The jumping champion is %d\n",ans); } return 0; }
[ "anwarhossain221095@gmail.com" ]
anwarhossain221095@gmail.com
1dffb121037b9d1813550f9eb40b45776597a9f2
b6ea73b8f091860f57625e66dd161ec34377adc1
/version/dllmain.cpp
780294a0317c9a35c67d0371bbdd3757890af444
[ "Apache-2.0" ]
permissive
afunny9177/project4
96704a6f1a97651ad2b0f5a3ee37c85bdb877131
8a1b694510dae95baba20ad93a1382cfcc79a7c4
refs/heads/master
2020-12-25T14:32:32.754250
2016-12-07T07:01:13
2016-12-07T07:01:13
66,199,930
0
0
null
null
null
null
GB18030
C++
false
false
788
cpp
// dllmain.cpp : 定义 DLL 应用程序的入口点。 #include "stdafx.h" #include "hijackapi.h" #include "hook_manager.h" std::unique_ptr<HookManager> g_manager; BOOL WINAPI DllMain(HMODULE hModule, DWORD dwReason, PVOID pvReserved) { if (DetourIsHelperProcess()) { return TRUE; } if (dwReason == DLL_PROCESS_ATTACH) { DisableThreadLibraryCalls(hModule); DetourRestoreAfterWith(); LoadOrigin(); if (!g_manager) { g_manager.reset(new HookManager()); g_manager->Init(); } } else if (dwReason == DLL_PROCESS_DETACH) { FreeOrigin(); if (g_manager) { g_manager->Uninit(); g_manager.reset(); } } return TRUE; }
[ "1111111@qq.com" ]
1111111@qq.com
b5d131f97c1b059a327e8bcd68ee49c97b03ab45
90047daeb462598a924d76ddf4288e832e86417c
/chrome/browser/ui/webui/extensions/extension_icon_source.cc
46f69c56a2385f19f9b8432ff5b8a6d3683ce1de
[ "BSD-3-Clause" ]
permissive
massbrowser/android
99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080
a9c4371682c9443d6e1d66005d4db61a24a9617c
refs/heads/master
2022-11-04T21:15:50.656802
2017-06-08T12:31:39
2017-06-08T12:31:39
93,747,579
2
2
BSD-3-Clause
2022-10-31T10:34:25
2017-06-08T12:36:07
null
UTF-8
C++
false
false
11,669
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/webui/extensions/extension_icon_source.h" #include <stddef.h> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted_memory.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/threading/thread.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "chrome/common/url_constants.h" #include "chrome/grit/component_extension_resources_map.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/image_loader.h" #include "extensions/common/extension.h" #include "extensions/common/extension_resource.h" #include "extensions/common/manifest_handlers/icons_handler.h" #include "extensions/grit/extensions_browser_resources.h" #include "skia/ext/image_operations.h" #include "ui/base/layout.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/favicon_size.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/skbitmap_operations.h" #include "url/gurl.h" namespace extensions { namespace { scoped_refptr<base::RefCountedMemory> BitmapToMemory(const SkBitmap* image) { base::RefCountedBytes* image_bytes = new base::RefCountedBytes; gfx::PNGCodec::EncodeBGRASkBitmap(*image, false, &image_bytes->data()); return image_bytes; } SkBitmap DesaturateImage(const SkBitmap* image) { color_utils::HSL shift = {-1, 0, 0.6}; return SkBitmapOperations::CreateHSLShiftedBitmap(*image, shift); } SkBitmap* ToBitmap(const unsigned char* data, size_t size) { SkBitmap* decoded = new SkBitmap(); bool success = gfx::PNGCodec::Decode(data, size, decoded); DCHECK(success); return decoded; } } // namespace ExtensionIconSource::ExtensionIconSource(Profile* profile) : profile_(profile) { } struct ExtensionIconSource::ExtensionIconRequest { content::URLDataSource::GotDataCallback callback; scoped_refptr<const Extension> extension; bool grayscale; int size; ExtensionIconSet::MatchType match; }; // static GURL ExtensionIconSource::GetIconURL(const Extension* extension, int icon_size, ExtensionIconSet::MatchType match, bool grayscale) { GURL icon_url(base::StringPrintf("%s%s/%d/%d%s", chrome::kChromeUIExtensionIconURL, extension->id().c_str(), icon_size, match, grayscale ? "?grayscale=true" : "")); CHECK(icon_url.is_valid()); return icon_url; } // static SkBitmap* ExtensionIconSource::LoadImageByResourceId(int resource_id) { base::StringPiece contents = ResourceBundle::GetSharedInstance().GetRawDataResourceForScale( resource_id, ui::SCALE_FACTOR_100P); // Convert and return it. const unsigned char* data = reinterpret_cast<const unsigned char*>(contents.data()); return ToBitmap(data, contents.length()); } std::string ExtensionIconSource::GetSource() const { return chrome::kChromeUIExtensionIconHost; } std::string ExtensionIconSource::GetMimeType(const std::string&) const { // We need to explicitly return a mime type, otherwise if the user tries to // drag the image they get no extension. return "image/png"; } void ExtensionIconSource::StartDataRequest( const std::string& path, const content::ResourceRequestInfo::WebContentsGetter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { // This is where everything gets started. First, parse the request and make // the request data available for later. static int next_id = 0; if (!ParseData(path, ++next_id, callback)) { // If the request data cannot be parsed, request parameters will not be // added to |request_map_|. // Send back the default application icon (not resized or desaturated) as // the default response. callback.Run(BitmapToMemory(GetDefaultAppImage()).get()); return; } ExtensionIconRequest* request = GetData(next_id); ExtensionResource icon = IconsInfo::GetIconResource( request->extension.get(), request->size, request->match); if (icon.relative_path().empty()) { LoadIconFailed(next_id); } else { LoadExtensionImage(icon, next_id); } } bool ExtensionIconSource::AllowCaching() const { // Should not be cached to reflect the latest contents that may be updated by // Extensions. return false; } ExtensionIconSource::~ExtensionIconSource() { } const SkBitmap* ExtensionIconSource::GetDefaultAppImage() { if (!default_app_data_.get()) default_app_data_.reset(LoadImageByResourceId(IDR_APP_DEFAULT_ICON)); return default_app_data_.get(); } const SkBitmap* ExtensionIconSource::GetDefaultExtensionImage() { if (!default_extension_data_.get()) { default_extension_data_.reset( LoadImageByResourceId(IDR_EXTENSION_DEFAULT_ICON)); } return default_extension_data_.get(); } void ExtensionIconSource::FinalizeImage(const SkBitmap* image, int request_id) { SkBitmap bitmap; ExtensionIconRequest* request = GetData(request_id); if (request->grayscale) bitmap = DesaturateImage(image); else bitmap = *image; request->callback.Run(BitmapToMemory(&bitmap).get()); ClearData(request_id); } void ExtensionIconSource::LoadDefaultImage(int request_id) { ExtensionIconRequest* request = GetData(request_id); const SkBitmap* default_image = NULL; if (request->extension->is_app()) default_image = GetDefaultAppImage(); else default_image = GetDefaultExtensionImage(); SkBitmap resized_image(skia::ImageOperations::Resize( *default_image, skia::ImageOperations::RESIZE_LANCZOS3, request->size, request->size)); // There are cases where Resize returns an empty bitmap, for example if you // ask for an image too large. In this case it is better to return the default // image than returning nothing at all. if (resized_image.empty()) resized_image = *default_image; FinalizeImage(&resized_image, request_id); } void ExtensionIconSource::LoadExtensionImage(const ExtensionResource& icon, int request_id) { ExtensionIconRequest* request = GetData(request_id); ImageLoader::Get(profile_)->LoadImageAsync( request->extension.get(), icon, gfx::Size(request->size, request->size), base::Bind(&ExtensionIconSource::OnImageLoaded, AsWeakPtr(), request_id)); } void ExtensionIconSource::LoadFaviconImage(int request_id) { favicon::FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(profile_, ServiceAccessType::EXPLICIT_ACCESS); // Fall back to the default icons if the service isn't available. if (favicon_service == NULL) { LoadDefaultImage(request_id); return; } GURL favicon_url = AppLaunchInfo::GetFullLaunchURL(GetData(request_id)->extension.get()); favicon_service->GetRawFaviconForPageURL( favicon_url, favicon_base::FAVICON, gfx::kFaviconSize, base::Bind(&ExtensionIconSource::OnFaviconDataAvailable, base::Unretained(this), request_id), &cancelable_task_tracker_); } void ExtensionIconSource::OnFaviconDataAvailable( int request_id, const favicon_base::FaviconRawBitmapResult& bitmap_result) { ExtensionIconRequest* request = GetData(request_id); // Fallback to the default icon if there wasn't a favicon. if (!bitmap_result.is_valid()) { LoadDefaultImage(request_id); return; } if (!request->grayscale) { // If we don't need a grayscale image, then we can bypass FinalizeImage // to avoid unnecessary conversions. request->callback.Run(bitmap_result.bitmap_data.get()); ClearData(request_id); } else { FinalizeImage(ToBitmap(bitmap_result.bitmap_data->front(), bitmap_result.bitmap_data->size()), request_id); } } void ExtensionIconSource::OnImageLoaded(int request_id, const gfx::Image& image) { if (image.IsEmpty()) LoadIconFailed(request_id); else FinalizeImage(image.ToSkBitmap(), request_id); } void ExtensionIconSource::LoadIconFailed(int request_id) { ExtensionIconRequest* request = GetData(request_id); ExtensionResource icon = IconsInfo::GetIconResource( request->extension.get(), request->size, request->match); if (request->size == extension_misc::EXTENSION_ICON_BITTY) LoadFaviconImage(request_id); else LoadDefaultImage(request_id); } bool ExtensionIconSource::ParseData( const std::string& path, int request_id, const content::URLDataSource::GotDataCallback& callback) { // Extract the parameters from the path by lower casing and splitting. std::string path_lower = base::ToLowerASCII(path); std::vector<std::string> path_parts = base::SplitString( path_lower, "/", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); if (path_lower.empty() || path_parts.size() < 3) return false; std::string size_param = path_parts.at(1); std::string match_param = path_parts.at(2); match_param = match_param.substr(0, match_param.find('?')); int size; if (!base::StringToInt(size_param, &size)) return false; if (size <= 0 || size > extension_misc::EXTENSION_ICON_GIGANTOR) return false; ExtensionIconSet::MatchType match_type; int match_num; if (!base::StringToInt(match_param, &match_num)) return false; match_type = static_cast<ExtensionIconSet::MatchType>(match_num); if (!(match_type == ExtensionIconSet::MATCH_EXACTLY || match_type == ExtensionIconSet::MATCH_SMALLER || match_type == ExtensionIconSet::MATCH_BIGGER)) match_type = ExtensionIconSet::MATCH_EXACTLY; std::string extension_id = path_parts.at(0); const Extension* extension = ExtensionSystem::Get(profile_)-> extension_service()->GetInstalledExtension(extension_id); if (!extension) return false; bool grayscale = path_lower.find("grayscale=true") != std::string::npos; SetData(request_id, callback, extension, grayscale, size, match_type); return true; } void ExtensionIconSource::SetData( int request_id, const content::URLDataSource::GotDataCallback& callback, const Extension* extension, bool grayscale, int size, ExtensionIconSet::MatchType match) { std::unique_ptr<ExtensionIconRequest> request = base::MakeUnique<ExtensionIconRequest>(); request->callback = callback; request->extension = extension; request->grayscale = grayscale; request->size = size; request->match = match; request_map_[request_id] = std::move(request); } ExtensionIconSource::ExtensionIconRequest* ExtensionIconSource::GetData( int request_id) { return request_map_[request_id].get(); } void ExtensionIconSource::ClearData(int request_id) { request_map_.erase(request_id); } } // namespace extensions
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
0658c8006ec30d3fa11dad62cbf08058659d021a
4903b3017798c219fc72277fc1c96de63d7c4c09
/jni/CloudBox/CBObserver.h
b81c12ce8bdc31d88e2065e2238715e3a7c9b140
[]
no_license
cloudhsu/CloudBox
aef66b1a1665afa156d5228ff6d55d5518f8cda2
e42f1ff3e667e26f47988b4d2938b8fde18e845f
refs/heads/master
2020-05-25T10:48:33.639881
2014-09-11T02:10:36
2014-09-11T02:10:36
5,096,433
1
0
null
null
null
null
UTF-8
C++
false
false
531
h
/* * CBObserver.h * CloudBox Cross-Platform Framework Project * * Created by Cloud on 2013/03/14. * Copyright 2013 Cloud Hsu. All rights reserved. * */ #ifndef __CBOBSERVER_H__ #define __CBOBSERVER_H__ template<class TSubjectObject> class CBObserver { protected: int m_id; public: CBObserver() {} virtual ~CBObserver() {} inline int getId() const { return m_id; } inline void setId(int val) { m_id = val; } virtual void update(TSubjectObject object) = 0; }; #endif
[ "cloudhsu921@gmail.com" ]
cloudhsu921@gmail.com
adf8cef27c7e2fd34b3a445b5a480f0861b69d00
20b663d571ef748e69ce9b733de8f37e1d3c5abe
/utes_b/fmod.h
63babb7c8bce13fcd6c703e6abe67c668858bb3d
[]
no_license
sudakov/DSS-UTES
68f1408f0b4a70194011ecdc52611ddbe8751fe7
03b27c69ca75faf0bd6c74beb98fbc81100f07a5
refs/heads/master
2021-01-10T03:05:03.088397
2016-11-20T12:44:24
2016-11-20T12:44:24
36,016,507
0
0
null
null
null
null
UTF-8
C++
false
false
579
h
// Machine generated IDispatch wrapper class(es) created with ClassWizard ///////////////////////////////////////////////////////////////////////////// // IFmod wrapper class class IFmod : public COleDispatchDriver { public: IFmod() {} // Calls COleDispatchDriver default constructor IFmod(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} IFmod(const IFmod& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: short SetVisible(short flag); short SetAggr(LPCTSTR name); short GetValue(double* v); };
[ "vsudakov@bk.ru" ]
vsudakov@bk.ru
1030636d3832283ca5fe62925f37b2cb2bc74cd6
ebc815aeba8a74801d7cb79daef836a908b2243c
/StGenFactoryScript/PowerCtrl.cpp
ce665f30e2b4eacfe5c8ebbf9233bcf30c23e2e1
[]
no_license
anryu/StGenFactoryScript
9050c2a3883c04b5b60f919cf70f0cfbd4c9a43b
8016ec47f48c443ab727b5edaf20c3bdfc7c70c4
refs/heads/master
2020-04-05T02:47:28.821834
2018-11-13T10:01:21
2018-11-13T10:01:21
156,490,372
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
12,167
cpp
// PowerCtrl.cpp: CPowerCtrl クラスのインプリメンテーション // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" //#include "StGEFactory.h" #include "PowerCtrl.h" //▼1.3.0.10多言語モード対応 #include "HookMsgBox.h" //▲1.3.0.10多言語モード対応 #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif //▼2007/07/13 v0.47 Beta9 CLC232B対応(電源の最大電流値を400mAから500mAに変更) const double gcdblCurrentMaxValue = 0.5; //▲2007/07/13 v0.47 Beta9 CLC232B対応(電源の最大電流値を400mAから500mAに変更) ////////////////////////////////////////////////////////////////////// // 構築/消滅 ////////////////////////////////////////////////////////////////////// CPowerCtrl::CPowerCtrl() { m_hTMI = -1; m_dwPCAddress = 1; m_dwSystemAddress = 1; m_byteChannelForCamera = 1; //A // m_byteChannelForJigu = 2; //B //▼2007/06/01 v0.46 Beta6 ジッタ検査変更(実行位置、初期値、待機時間) //電源を投入してからの経過時間を記憶 m_dwPowerOnTime = GetTickCount(); //▲2007/06/01 v0.46 Beta6 ジッタ検査変更(実行位置、初期値、待機時間) //▼1.0.0.1060 m_dblCurrentLimit = gcdblCurrentMaxValue; //▲1.0.0.1060 } CPowerCtrl::~CPowerCtrl() { bDisconnect(); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- BOOL CPowerCtrl::bConnect(void) { BOOL bReval = TRUE; CHAR pchrPWASet[256]; INT iReval = 0; //初期化(DLLが存在しない場合エラー) bReval = m_TMI_API_IF.IFInitialize(); if(!bReval) return(bReval); //IF種類、PCアドレス,システムアドレスを指定する文字列 sprintf_s(pchrPWASet,sizeof(pchrPWASet)/sizeof(pchrPWASet[0]),"USB:%u:%u",m_dwPCAddress,m_dwSystemAddress); do{ m_hTMI = m_TMI_API_IF.HandleOpen("PW-A",pchrPWASet); if(m_hTMI < 0) { /* if(IDCANCEL == ::MessageBox( NULL, TEXT("通信可能な電源が見つかりませんでした。\r\n") TEXT("手動の場合:[キャンセル]ボタンをクリック\r\n") TEXT("自動の場合:USBケーブルを挿しなおして数秒経ってから[再試行]ボタンをクリック"), NULL, MB_RETRYCANCEL)) */ //▼1.3.0.10多言語モード対応 //CString szText; //szText.LoadStringW(IDS_NOT_FOUND_POWER_UNIT); //if( IDCANCEL == AfxMessageBoxHooked( szText, MB_RETRYCANCEL) ) if(IDCANCEL == AfxMessageBox( TEXT("通信可能な電源が見つかりませんでした。\r\n") TEXT("手動の場合:[キャンセル]ボタンをクリック\r\n") TEXT("自動の場合:USBケーブルを挿しなおして数秒経ってから[再試行]ボタンをクリック"), MB_RETRYCANCEL)) return(FALSE); //▲1.3.0.10多言語モード対応 } else { break; } }while(1); iReval = m_TMI_API_IF.Preset(m_hTMI,1); //メモリ1 if(iReval < 0) { bDisconnect(); return(FALSE); } iReval = m_TMI_API_IF.Voltage(m_hTMI,m_byteChannelForCamera,1,12.0); //メモリ1 チャンネルA 12.0V if(iReval < 0) { bDisconnect(); return(FALSE); } //▼1.0.0.1060 ////▼2007/07/13 v0.47 Beta9 CLC232B対応(電源の最大電流値を400mAから500mAに変更) ////iReval = m_TMI_API_IF.Current(m_hTMI,m_byteChannelForCamera,1,0.40); //メモリ1 チャンネルA 0.4A //iReval = m_TMI_API_IF.Current(m_hTMI,m_byteChannelForCamera,1, gcdblCurrentMaxValue); //メモリ1 チャンネルA 0.4A ////▲2007/07/13 v0.47 Beta9 CLC232B対応(電源の最大電流値を400mAから500mAに変更) iReval = m_TMI_API_IF.Current(m_hTMI,m_byteChannelForCamera,1, m_dblCurrentLimit); //メモリ1 チャンネルA 0.4A //▲1.0.0.1060 if(iReval < 0) { bDisconnect(); return(FALSE); } return(bReval); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- BOOL CPowerCtrl::bDisconnect(void) { BOOL bReval = TRUE; if(m_hTMI >= 0) { m_TMI_API_IF.RemoteLocal(m_hTMI); m_TMI_API_IF.HandleClose(m_hTMI); m_hTMI = -1; } return(bReval); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- BOOL CPowerCtrl::bGetCurrent(DOUBLE *pdblCurrent) { //▼1.0.0.1018 //BOOL bReval = TRUE; //LONG lReval = 0; //DOUBLE dblVoltage; ////DOUBLE dblPrevCurrent; //CHAR chrCVCC; //if(m_hTMI < 0) return(FALSE); ////現在の電流値を取得 //lReval = m_TMI_API_IF.MoniDataQ(m_hTMI,m_byteChannelForCamera,&dblVoltage,pdblCurrent,&chrCVCC); //if(lReval < 0) // bReval = FALSE; //return(bReval); //▲1.0.0.1018 return bGetCurrent(m_byteChannelForCamera, pdblCurrent); } //▼1.0.0.1018 BOOL CPowerCtrl::bGetCurrent(BYTE byteChannel, DOUBLE *pdblCurrent) { BOOL bReval = TRUE; LONG lReval = 0; DOUBLE dblVoltage; CHAR chrCVCC; if(m_hTMI < 0) return(FALSE); //現在の電流値を取得 lReval = m_TMI_API_IF.MoniDataQ(m_hTMI,byteChannel,&dblVoltage,pdblCurrent,&chrCVCC); if(lReval < 0) bReval = FALSE; return(bReval); } //▲1.0.0.1018 //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- BOOL CPowerCtrl::bPowerOn(void) //▼1.0.0.1018 { return bPowerOn(m_byteChannelForCamera); } BOOL CPowerCtrl::bPowerOn(BYTE byteChannel) //▲1.0.0.1018 { BOOL bReval = TRUE; INT iReval = 0; //▼2007/06/01 v0.46 Beta6 ジッタ検査変更(実行位置、初期値、待機時間) //電源を投入してからの経過時間を記憶 m_dwPowerOnTime = GetTickCount(); //▲2007/06/01 v0.46 Beta6 ジッタ検査変更(実行位置、初期値、待機時間) if(m_hTMI < 0) return(FALSE); // 電流値の設定 //▼1.0.0.1060 ////▼1.0.0.1018 ////iReval = m_TMI_API_IF.Current(m_hTMI,m_byteChannelForCamera,1,400.0); //iReval = m_TMI_API_IF.Current(m_hTMI,byteChannel,1,gcdblCurrentMaxValue); ////▲1.0.0.1018 iReval = m_TMI_API_IF.Current(m_hTMI,byteChannel,1,m_dblCurrentLimit); //▲1.0.0.1060 if(iReval < 0) bReval = FALSE; //▼2008/02/29 v0.54 Beta05 電源ONの順番を「治具->カメラ」、電源OFFの順番を「カメラ->治具」に変更 //メインアウトプットON //▼1.0.0.1018 //iReval = m_TMI_API_IF.MainOutput(m_hTMI,1); //if(iReval < 0) bReval = FALSE; //▲1.0.0.1018 //アウトプットセレクト B ON // iReval = m_TMI_API_IF.OutputSel(m_hTMI,m_byteChannelForJigu,1); // if(iReval < 0) bReval = FALSE; // Sleep(500); //アウトプットセレクト A ON //▼1.0.0.1018 //iReval = m_TMI_API_IF.OutputSel(m_hTMI,m_byteChannelForCamera,1); iReval = m_TMI_API_IF.OutputSel(m_hTMI,byteChannel,1); //▲1.0.0.1018 if(iReval < 0) bReval = FALSE; /* //アウトプットセレクト A ON iReval = m_TMI_API_IF.OutputSel(m_hTMI,m_byteChannelForCamera,1); if(iReval < 0) bReval = FALSE; //アウトプットセレクト B ON iReval = m_TMI_API_IF.OutputSel(m_hTMI,m_byteChannelForJigu,1); if(iReval < 0) bReval = FALSE; //メインアウトプットON iReval = m_TMI_API_IF.MainOutput(m_hTMI,1); if(iReval < 0) bReval = FALSE; */ //▲2008/02/29 v0.54 Beta05 電源ONの順番を「治具->カメラ」、電源OFFの順番を「カメラ->治具」に変更 //Aチャンネルの情報を表示 //▼1.0.0.1018 //iReval = m_TMI_API_IF.Display(m_hTMI,m_byteChannelForCamera); iReval = m_TMI_API_IF.Display(m_hTMI,byteChannel); //▲1.0.0.1018 if(iReval < 0) bReval = FALSE; //電源投入待機 DWORD dwRetry = 10; do{ DOUBLE dblCurrent; bGetCurrent(byteChannel,&dblCurrent); if(dblCurrent > 0.05) break; Sleep(500); }while(dwRetry--); //▼2006/10/11 v0.40 正式版 電源投入後一定時間待機するように変更(E42,43で検査開始時に通信エラーが発生したため) Sleep(1000); //▲2006/10/11 v0.40 正式版 電源投入後一定時間待機するように変更(E42,43で検査開始時に通信エラーが発生したため) return(bReval); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- BOOL CPowerCtrl::bPowerOff(void) //▼1.0.0.1018 { return bPowerOff(m_byteChannelForCamera); } BOOL CPowerCtrl::bPowerOff(BYTE byteChannel) //▲1.0.0.1018 { BOOL bReval = TRUE; INT iReval = 0; if(m_hTMI < 0) return(FALSE); //アウトプットセレクト A ON //▼1.0.0.1018 //iReval = m_TMI_API_IF.OutputSel(m_hTMI,m_byteChannelForCamera,0); iReval = m_TMI_API_IF.OutputSel(m_hTMI,byteChannel,0); //▲1.0.0.1018 if(iReval < 0) bReval = FALSE; //メインアウトプットOFF //▼1.0.0.1018 //iReval = m_TMI_API_IF.MainOutput(m_hTMI,0); //if(iReval < 0) bReval = FALSE; //▲1.0.0.1018 return(bReval); } //----------------------------------------------------------------------------- //12V->24V or 24V->12V //----------------------------------------------------------------------------- BOOL CPowerCtrl::bSetVoltage(double dblVoltage) { BOOL bReval = TRUE; INT iReval = 0; // iReval = m_TMI_API_IF.Voltage(m_hTMI,m_byteChannelForCamera,1,18.0); //メモリ1 チャンネルA 18.0V // Sleep(500); iReval = m_TMI_API_IF.Voltage(m_hTMI,m_byteChannelForCamera,1,dblVoltage); //メモリ1 チャンネルA 24.0V return bReval; } //▼1.3.0.9 //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- BOOL CPowerCtrl::bGetVoltage(double *pdblVoltage) { BOOL bReval = TRUE; LONG lReval = 0; DOUBLE dblCurrent; //DOUBLE dblPrevCurrent; CHAR chrCVCC; if(m_hTMI < 0) return(FALSE); //現在の電流値を取得 lReval = m_TMI_API_IF.MoniDataQ(m_hTMI,m_byteChannelForCamera,pdblVoltage,&dblCurrent,&chrCVCC); if(lReval < 0) bReval = FALSE; return(bReval); } //▲1.3.0.9 //▼1.0.0.1060 //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- BOOL CPowerCtrl::bSetCurrentLimit(double dblCurrentLimit) { BOOL bReval = TRUE; if(m_hTMI >= 0) { LONG lReval = 0; lReval = m_TMI_API_IF.m_TMI_Current(m_hTMI,m_byteChannelForCamera,1,dblCurrentLimit); if(lReval < 0) bReval = FALSE; } if( bReval ) m_dblCurrentLimit = dblCurrentLimit; return(bReval); } BOOL CPowerCtrl::bGetCurrentLimit(double *pdblCurrentLimit) { BOOL bReval = TRUE; if(m_hTMI >= 0) { LONG lReval = 0; lReval = m_TMI_API_IF.m_TMI_CurrentQ(m_hTMI,m_byteChannelForCamera,1,pdblCurrentLimit); if(lReval < 0) bReval = FALSE; } else { *pdblCurrentLimit = m_dblCurrentLimit; } return(bReval); } //▲1.0.0.1060 //▼1.0.0.1018 //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- BOOL CPowerCtrl::bMainPowerOn(void) { BOOL bReval = TRUE; INT iReval = 0; if(m_hTMI < 0) return(FALSE); //電源を投入してからの経過時間を記憶 m_dwPowerOnTime = GetTickCount(); //メインアウトプットON iReval = m_TMI_API_IF.MainOutput(m_hTMI,1); if(iReval < 0) bReval = FALSE; return(bReval); } BOOL CPowerCtrl::bMainPowerOff(void) { BOOL bReval = TRUE; INT iReval = 0; if(m_hTMI < 0) return(FALSE); //メインアウトプットOFF iReval = m_TMI_API_IF.MainOutput(m_hTMI,0); if(iReval < 0) bReval = FALSE; return(bReval); } //▲1.0.0.1018
[ "anryu@sentech.co.jp" ]
anryu@sentech.co.jp
42742345b456f4cb989ea7a8fe87f63b4c9b1ec0
d1055d56eaa134744c9d2283b8ede9165b239654
/RLogin/MainFrm.cpp
d33996199af6fd9797f2fb0b73e34c6618a40874
[ "MIT" ]
permissive
archvile/RLogin
c06821c3ddaf7b3af949882c5ddebca3b8ccb4e0
384fdd23f37a578998e978f3a5b8a543cdf8704d
refs/heads/master
2021-05-06T12:28:47.506623
2017-12-03T23:07:48
2017-12-03T23:07:48
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
101,683
cpp
// MainFrm.cpp : CMainFrame クラスの実装 // #include "stdafx.h" #include "RLogin.h" #include "MainFrm.h" #include "ChildFrm.h" #include "RLoginDoc.h" #include "RLoginView.h" #include "ServerSelect.h" #include "Script.h" #include "ssh2.h" #include "ToolDlg.h" #include "richedit.h" #ifdef _DEBUG #define new DEBUG_NEW #endif ///////////////////////////////////////////////////////////////////////////// // CPaneFrame CPaneFrame::CPaneFrame(class CMainFrame *pMain, HWND hWnd, class CPaneFrame *pOwn) { m_pLeft = NULL; m_pRight = NULL; m_hWnd = hWnd; m_pOwn = pOwn; m_pMain = pMain; m_Style = PANEFRAME_WINDOW; m_BoderSize = 2; m_bActive = FALSE; m_pServerEntry = NULL; m_bReqSize = FALSE; if ( m_pOwn != NULL ) m_Frame = m_pOwn->m_Frame; else m_pMain->GetFrameRect(m_Frame); } CPaneFrame::~CPaneFrame() { if ( m_pServerEntry != NULL ) delete m_pServerEntry; if ( m_NullWnd.m_hWnd != NULL ) m_NullWnd.DestroyWindow(); if ( m_pLeft != NULL ) delete m_pLeft; if ( m_pRight != NULL ) delete m_pRight; } void CPaneFrame::Attach(HWND hWnd) { ASSERT(m_Style == PANEFRAME_WINDOW); m_hWnd = hWnd; m_bActive = FALSE; if ( m_NullWnd.m_hWnd != NULL ) m_NullWnd.DestroyWindow(); } void CPaneFrame::CreatePane(int Style, HWND hWnd) { ASSERT(m_Style == PANEFRAME_WINDOW); ASSERT(m_pLeft == NULL); ASSERT(m_pRight == NULL); m_pLeft = new CPaneFrame(m_pMain, m_hWnd, this); m_pRight = new CPaneFrame(m_pMain, hWnd, this); m_hWnd = NULL; m_Style = Style; if ( m_NullWnd.m_hWnd != NULL ) m_NullWnd.DestroyWindow(); if ( m_bActive ) m_pLeft->m_bActive = TRUE; m_bActive = FALSE; switch(m_Style) { case PANEFRAME_WIDTH: m_pLeft->m_Frame.right = m_pLeft->m_Frame.left + (m_Frame.Width() - m_BoderSize) / 2; m_pRight->m_Frame.left = m_pLeft->m_Frame.right + m_BoderSize; break; case PANEFRAME_HEIGHT: m_pLeft->m_Frame.bottom = m_pLeft->m_Frame.top + (m_Frame.Height() - m_BoderSize) / 2; m_pRight->m_Frame.top = m_pLeft->m_Frame.bottom + m_BoderSize; break; case PANEFRAME_MAXIM: CPaneFrame *pPane = m_pLeft; m_pLeft = m_pRight; m_pRight = pPane; break; } if ( m_pLeft->m_Frame.Width() < PANEMIN_WIDTH || m_pLeft->m_Frame.Height() < PANEMIN_HEIGHT || m_pRight->m_Frame.Width() < PANEMIN_WIDTH || m_pRight->m_Frame.Height() < PANEMIN_HEIGHT ) { m_Style = PANEFRAME_MAXIM; m_pLeft->m_Frame = m_Frame; m_pRight->m_Frame = m_Frame; } m_pLeft->MoveFrame(); m_pRight->MoveFrame(); } CPaneFrame *CPaneFrame::InsertPane() { CPaneFrame *pPane = new CPaneFrame(m_pMain, NULL, m_pOwn); pPane->m_Style = PANEFRAME_MAXIM; pPane->m_Frame = m_Frame; pPane->m_pLeft = this; pPane->m_pRight = new CPaneFrame(m_pMain, NULL, pPane); if ( m_pOwn != NULL ) { if ( m_pOwn->m_pLeft == this ) m_pOwn->m_pLeft = pPane; else if ( m_pOwn->m_pRight == this ) m_pOwn->m_pRight = pPane; } m_pOwn = pPane; return pPane; } class CPaneFrame *CPaneFrame::DeletePane(HWND hWnd) { if ( m_Style == PANEFRAME_WINDOW ) { if ( m_hWnd == hWnd ) { delete this; return NULL; } return this; } ASSERT(m_pLeft != NULL); ASSERT(m_pRight != NULL); if ( (m_pLeft = m_pLeft->DeletePane(hWnd)) == NULL ) { if ( m_pRight->m_Style == PANEFRAME_WINDOW ) { m_hWnd = m_pRight->m_hWnd; m_Style = m_pRight->m_Style; delete m_pRight; m_pRight = NULL; MoveFrame(); } else { CPaneFrame *pPane = m_pRight; m_pLeft = pPane->m_pLeft; pPane->m_pLeft = NULL; m_pRight = pPane->m_pRight; pPane->m_pRight = NULL; m_Style = pPane->m_Style; CRect rect = m_Frame; m_Frame = pPane->m_Frame; m_pLeft->m_pOwn = this; m_pRight->m_pOwn = this; MoveParOwn(rect, PANEFRAME_NOCHNG); delete pPane; } } else if ( (m_pRight = m_pRight->DeletePane(hWnd)) == NULL ) { if ( m_pLeft->m_Style == PANEFRAME_WINDOW ) { m_hWnd = m_pLeft->m_hWnd; m_Style = m_pLeft->m_Style; delete m_pLeft; m_pLeft = NULL; MoveFrame(); } else { CPaneFrame *pPane = m_pLeft; m_pLeft = pPane->m_pLeft; pPane->m_pLeft = NULL; m_pRight = pPane->m_pRight; pPane->m_pRight = NULL; m_Style = pPane->m_Style; CRect rect = m_Frame; m_Frame = pPane->m_Frame; m_pLeft->m_pOwn = this; m_pRight->m_pOwn = this; MoveParOwn(rect, PANEFRAME_NOCHNG); delete pPane; } } return this; } class CPaneFrame *CPaneFrame::GetPane(HWND hWnd) { class CPaneFrame *pPane; if ( m_Style == PANEFRAME_WINDOW && m_hWnd == hWnd ) return this; else if ( m_pLeft != NULL && (pPane = m_pLeft->GetPane(hWnd)) != NULL ) return pPane; else if ( m_pRight != NULL && (pPane = m_pRight->GetPane(hWnd)) != NULL ) return pPane; else return NULL; } class CPaneFrame *CPaneFrame::GetNull() { CPaneFrame *pPane; if ( m_Style == PANEFRAME_WINDOW && m_hWnd == NULL && m_bActive ) return this; else if ( m_pLeft != NULL && (pPane = m_pLeft->GetNull()) != NULL ) return pPane; else if ( m_pRight != NULL && (pPane = m_pRight->GetNull()) != NULL ) return pPane; else return NULL; } class CPaneFrame *CPaneFrame::GetEntry() { CPaneFrame *pPane; if ( m_Style == PANEFRAME_WINDOW && m_hWnd == NULL && m_pServerEntry != NULL ) return this; else if ( m_pLeft != NULL && (pPane = m_pLeft->GetEntry()) != NULL ) return pPane; else if ( m_pRight != NULL && (pPane = m_pRight->GetEntry()) != NULL ) return pPane; else return NULL; } class CPaneFrame *CPaneFrame::GetActive() { CPaneFrame *pPane; CWnd *pTemp = m_pMain->MDIGetActive(NULL); if ( (pPane = GetNull()) != NULL ) return pPane; else if ( pTemp != NULL && (pPane = GetPane(pTemp->m_hWnd)) != NULL ) return pPane; else if ( (pPane = GetPane(NULL)) != NULL ) return pPane; else return this; } int CPaneFrame::SetActive(HWND hWnd) { if ( m_Style == PANEFRAME_WINDOW ) return (m_hWnd == hWnd ? TRUE : FALSE); ASSERT(m_pLeft != NULL && m_pRight != NULL); if ( m_pLeft->SetActive(hWnd) ) return TRUE; else if ( !m_pRight->SetActive(hWnd) ) return FALSE; else if ( m_Style != PANEFRAME_MAXIM ) return TRUE; CPaneFrame *pPane = m_pLeft; m_pLeft = m_pRight; m_pRight = pPane; return TRUE; } int CPaneFrame::IsOverLap(CPaneFrame *pPane) { int n; CRect rect; if ( pPane == NULL || pPane == this ) return (-1); if ( m_Style == PANEFRAME_WINDOW && rect.IntersectRect(m_Frame, pPane->m_Frame) ) return 1; if ( m_pLeft != NULL && (n = m_pLeft->IsOverLap(pPane)) != 0 ) return n; if ( m_pRight != NULL && (n = m_pRight->IsOverLap(pPane)) != 0 ) return n; return 0; } BOOL CPaneFrame::IsTopLevel(CPaneFrame *pPane) { CRect rect; if ( m_Style == PANEFRAME_WINDOW ) { if ( pPane->m_hWnd != NULL && m_hWnd != NULL && pPane->m_hWnd != m_hWnd && rect.IntersectRect(m_Frame, pPane->m_Frame) ) { HWND hWnd = pPane->m_hWnd; while ( (hWnd = ::GetWindow(hWnd, GW_HWNDPREV)) != NULL ) { if ( hWnd == m_hWnd ) return FALSE; } } return TRUE; } else if ( m_pLeft != NULL && !m_pLeft->IsTopLevel(pPane) ) return FALSE; else if ( m_pRight != NULL && !m_pRight->IsTopLevel(pPane) ) return FALSE; else return TRUE; } int CPaneFrame::GetPaneCount(int count) { if ( m_Style == PANEFRAME_WINDOW ) count++; if ( m_pLeft != NULL ) count = m_pLeft->GetPaneCount(count); if ( m_pRight != NULL ) count = m_pRight->GetPaneCount(count); return count; } void CPaneFrame::MoveFrame() { ASSERT(m_Style == PANEFRAME_WINDOW); if ( m_hWnd != NULL ) { if ( m_NullWnd.m_hWnd != NULL ) m_NullWnd.DestroyWindow(); ::SetWindowPos(m_hWnd, NULL, m_Frame.left - 2, m_Frame.top - 2, m_Frame.Width(), m_Frame.Height(), SWP_SHOWWINDOW | SWP_FRAMECHANGED | SWP_NOCOPYBITS | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS | SWP_DEFERERASE); } else { CRect rect = m_Frame; m_pMain->AdjustRect(rect); if ( m_NullWnd.m_hWnd == NULL ) m_NullWnd.Create(NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | (m_bActive ? SS_WHITEFRAME : SS_GRAYFRAME), rect, m_pMain); else { m_NullWnd.ModifyStyle(SS_WHITEFRAME | SS_GRAYFRAME, (m_bActive ? SS_WHITEFRAME : SS_GRAYFRAME), 0); m_NullWnd.SetWindowPos(NULL, rect.left, rect.top, rect.Width(), rect.Height(), SWP_SHOWWINDOW | SWP_FRAMECHANGED | SWP_NOCOPYBITS | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_ASYNCWINDOWPOS); } } } void CPaneFrame::GetNextPane(int mode, class CPaneFrame *pThis, class CPaneFrame **ppPane) { if ( m_Style == PANEFRAME_WINDOW ) { if ( m_hWnd != NULL && m_hWnd != pThis->m_hWnd ) { switch(mode) { case 0: // Up if ( m_Frame.bottom > pThis->m_Frame.top ) break; if ( *ppPane == NULL ) *ppPane = this; else if ( m_Frame.bottom > (*ppPane)->m_Frame.bottom ) *ppPane = this; else if ( m_Frame.bottom == (*ppPane)->m_Frame.bottom && abs(m_Frame.left - pThis->m_Frame.left) < abs((*ppPane)->m_Frame.left - pThis->m_Frame.left) ) *ppPane = this; break; case 1: // Down if ( m_Frame.top < pThis->m_Frame.bottom ) break; if ( *ppPane == NULL ) *ppPane = this; else if ( m_Frame.top < (*ppPane)->m_Frame.top ) *ppPane = this; else if ( m_Frame.top == (*ppPane)->m_Frame.top && abs(m_Frame.left - pThis->m_Frame.left) < abs((*ppPane)->m_Frame.left - pThis->m_Frame.left) ) *ppPane = this; break; case 2: // Right if ( m_Frame.left < pThis->m_Frame.right ) break; if ( *ppPane == NULL ) *ppPane = this; else if ( m_Frame.left < (*ppPane)->m_Frame.left ) *ppPane = this; else if ( m_Frame.left == (*ppPane)->m_Frame.left && abs(m_Frame.top - pThis->m_Frame.top) < abs((*ppPane)->m_Frame.top - pThis->m_Frame.top) ) *ppPane = this; break; case 3: // Left if ( m_Frame.right > pThis->m_Frame.left ) break; if ( *ppPane == NULL ) *ppPane = this; else if ( m_Frame.right > (*ppPane)->m_Frame.right ) *ppPane = this; else if ( m_Frame.right == (*ppPane)->m_Frame.right && abs(m_Frame.top - pThis->m_Frame.top) < abs((*ppPane)->m_Frame.top - pThis->m_Frame.top) ) *ppPane = this; break; } } } else { m_pLeft->GetNextPane(mode, pThis, ppPane); m_pRight->GetNextPane(mode, pThis, ppPane); } } BOOL CPaneFrame::IsReqSize() { if ( m_Style == PANEFRAME_WINDOW ) return m_bReqSize; else if ( m_pLeft->IsReqSize() ) return TRUE; else if ( m_pRight->IsReqSize() ) return TRUE; else return FALSE; } void CPaneFrame::MoveParOwn(CRect &rect, int Style) { int n, l, r; if ( m_Style == PANEFRAME_WINDOW ) { m_pMain->InvalidateRect(m_Frame); m_Frame = rect; MoveFrame(); } else { ASSERT(m_pLeft != NULL && m_pRight != NULL); CRect left = rect; CRect right = rect; switch(Style) { case PANEFRAME_NOCHNG: if ( m_pLeft->IsReqSize() ) { if ( m_Style == PANEFRAME_WIDTH ) { left.right = left.left + rect.Width() - m_pRight->m_Frame.Width() - m_BoderSize; right.left = left.right + m_BoderSize; } else if ( m_Style == PANEFRAME_HEIGHT ) { left.bottom = left.top + rect.Height() - m_pRight->m_Frame.Height() - m_BoderSize; right.top = left.bottom + m_BoderSize; } m_pLeft->m_bReqSize = FALSE; break; } else if ( m_pRight->IsReqSize() ) { if ( m_Style == PANEFRAME_WIDTH ) { left.right = left.left + m_pLeft->m_Frame.Width(); right.left = left.right + m_BoderSize; } else if ( m_Style == PANEFRAME_HEIGHT ) { left.bottom = left.top + m_pLeft->m_Frame.Height(); right.top = left.bottom + m_BoderSize; } break; } RECALC: if ( m_Style == PANEFRAME_WIDTH ) { n = m_pLeft->m_Frame.Width() + m_pRight->m_Frame.Width() + m_BoderSize; if ( m_pLeft->m_Frame.Width() > m_pRight->m_Frame.Width() ) { left.right = left.left + m_pLeft->m_Frame.Width() * rect.Width() / n; right.left = left.right + m_BoderSize; } else { right.left = rect.right - m_pRight->m_Frame.Width() * rect.Width() / n; left.right = right.left - m_BoderSize; } } else if ( m_Style == PANEFRAME_HEIGHT ) { n = m_pLeft->m_Frame.Height() + m_pRight->m_Frame.Height() + m_BoderSize; if ( m_pLeft->m_Frame.Height() > m_pRight->m_Frame.Height() ) { left.bottom = left.top + m_pLeft->m_Frame.Height() * rect.Height() / n; right.top = left.bottom + m_BoderSize; } else { right.top = rect.bottom - m_pRight->m_Frame.Height() * rect.Height() / n; left.bottom = right.top - m_BoderSize; } } break; case PANEFRAME_MAXIM: m_Style = Style; break; case PANEFRAME_WIDTH: if ( m_Style != PANEFRAME_MAXIM ) goto RECALC; m_Style = Style; left.right = left.left + (rect.Width() - m_BoderSize) / 2; right.left = left.right + m_BoderSize; Style = PANEFRAME_NOCHNG; break; case PANEFRAME_HEIGHT: if ( m_Style != PANEFRAME_MAXIM ) goto RECALC; m_Style = Style; left.bottom = left.top + (rect.Height() - m_BoderSize) / 2; right.top = left.bottom + m_BoderSize; Style = PANEFRAME_NOCHNG; break; case PANEFRAME_WSPLIT: m_Style = PANEFRAME_WIDTH; left.right = left.left + (rect.Width() - m_BoderSize) / 2; right.left = left.right + m_BoderSize; Style = PANEFRAME_HSPLIT; break; case PANEFRAME_HSPLIT: m_Style = PANEFRAME_HEIGHT; left.bottom = left.top + (rect.Height() - m_BoderSize) / 2; right.top = left.bottom + m_BoderSize; Style = PANEFRAME_WSPLIT; break; case PANEFRAME_WEVEN: l = m_pLeft->GetPaneCount(0); r = m_pRight->GetPaneCount(0); if ( (l + r) == 0 ) { m_Style = PANEFRAME_MAXIM; break; } m_Style = PANEFRAME_WIDTH; left.right = left.left + rect.Width() * l / (l + r) - m_BoderSize / 2; right.left = left.right + m_BoderSize; break; case PANEFRAME_HEVEN: l = m_pLeft->GetPaneCount(0); r = m_pRight->GetPaneCount(0); if ( (l + r) == 0 ) { m_Style = PANEFRAME_MAXIM; break; } m_Style = PANEFRAME_HEIGHT; left.bottom = left.top + rect.Height() * l / (l + r) - m_BoderSize / 2; right.top = left.bottom + m_BoderSize; break; } if ( left.Width() < PANEMIN_WIDTH || left.Height() < PANEMIN_HEIGHT || right.Width() < PANEMIN_WIDTH || right.Height() < PANEMIN_HEIGHT ) { Style = m_Style = PANEFRAME_MAXIM; left = rect; right = rect; } m_Frame = rect; m_pLeft->MoveParOwn(left, Style); m_pRight->MoveParOwn(right, Style); } } void CPaneFrame::HitActive(CPoint &po) { if ( m_Style == PANEFRAME_WINDOW ) { if ( m_hWnd == NULL ) { BOOL bNew = (m_Frame.PtInRect(po) ? TRUE : FALSE); if ( m_bActive != bNew ) { m_bActive = bNew; MoveFrame(); } } else m_bActive = FALSE; } if ( m_pLeft != NULL ) m_pLeft->HitActive(po); if ( m_pRight != NULL ) m_pRight->HitActive(po); } class CPaneFrame *CPaneFrame::HitTest(CPoint &po) { switch(m_Style) { case PANEFRAME_WINDOW: if ( m_Frame.PtInRect(po) ) return this; break; case PANEFRAME_WIDTH: if ( m_Frame.PtInRect(po) && po.x >= (m_pLeft->m_Frame.right - 2) && po.x <= (m_pRight->m_Frame.left + 2) ) return this; break; case PANEFRAME_HEIGHT: if ( m_Frame.PtInRect(po) && po.y >= (m_pLeft->m_Frame.bottom - 2) && po.y <= (m_pRight->m_Frame.top + 2) ) return this; break; } CPaneFrame *pPane; if ( m_pLeft != NULL && (pPane = m_pLeft->HitTest(po)) != NULL ) return pPane; else if ( m_pRight != NULL && (pPane = m_pRight->HitTest(po)) != NULL ) return pPane; else return NULL; } int CPaneFrame::BoderRect(CRect &rect) { switch(m_Style) { case PANEFRAME_WIDTH: rect = m_Frame; rect.left = m_pLeft->m_Frame.right - 1; rect.right = m_pRight->m_Frame.left + 1; break; case PANEFRAME_HEIGHT: rect = m_Frame; rect.top = m_pLeft->m_Frame.bottom - 1; rect.bottom = m_pRight->m_Frame.top + 1; break; default: return FALSE; } m_pMain->AdjustRect(rect); return TRUE; } void CPaneFrame::SetBuffer(CBuffer *buf, BOOL bEntry) { CStringA tmp; int sz = 0; CServerEntry *pEntry = NULL; if ( m_Style == PANEFRAME_WINDOW ) { tmp.Format("%d\t0\t", m_Style); if ( m_pServerEntry != NULL ) { delete m_pServerEntry; m_pServerEntry = NULL; } if ( bEntry && m_hWnd != NULL ) { CChildFrame *pWnd = (CChildFrame *)(CWnd::FromHandlePermanent(m_hWnd)); if ( pWnd != NULL ) { CRLoginDoc *pDoc = (CRLoginDoc *)(pWnd->GetActiveDocument()); if ( pDoc != NULL ) { // 現在のタイトルを保存 if ( !pDoc->m_TitleName.IsEmpty() ) pDoc->m_TextRam.m_TitleName = pDoc->m_TitleName; pDoc->SetEntryProBuffer(); pEntry = &(pDoc->m_ServerEntry); pEntry->m_DocType = DOCTYPE_MULTIFILE; pDoc->SetModifiedFlag(FALSE); #if _MSC_VER >= _MSC_VER_VS10 pDoc->ClearPathName(); #endif tmp.Format("%d\t0\t1\t", m_Style); } } } buf->PutStr(tmp); if ( pEntry != NULL ) pEntry->SetBuffer(*buf); return; } ASSERT(m_pLeft != NULL && m_pRight != NULL); switch(m_Style) { case PANEFRAME_WIDTH: sz = m_pLeft->m_Frame.right * 1000 / m_Frame.Width(); break; case PANEFRAME_HEIGHT: sz = m_pLeft->m_Frame.bottom * 1000 / m_Frame.Height(); break; case PANEFRAME_MAXIM: sz = 100; break; } tmp.Format("%d\t%d\t", m_Style, sz); buf->PutStr(tmp); m_pLeft->SetBuffer(buf); m_pRight->SetBuffer(buf); } class CPaneFrame *CPaneFrame::GetBuffer(class CMainFrame *pMain, class CPaneFrame *pPane, class CPaneFrame *pOwn, CBuffer *buf) { int Size; CStringA tmp; CStringArrayExt stra; if ( pPane == NULL ) pPane = new CPaneFrame(pMain, NULL, pOwn); if ( buf->GetSize() < 4 ) return pPane; buf->GetStr(tmp); if ( tmp.IsEmpty() ) return pPane; stra.GetString(MbsToTstr(tmp)); if ( stra.GetSize() < 2 ) return pPane; pPane->m_Style = stra.GetVal(0); Size = stra.GetVal(1); if ( pPane->m_Style < PANEFRAME_MAXIM || pPane->m_Style > PANEFRAME_WINDOW ) { delete pPane; return NULL; } if ( pPane->m_Style == PANEFRAME_WINDOW ) { if ( stra.GetSize() > 2 && stra.GetVal(2) == 1 ) { pPane->m_pServerEntry = new CServerEntry; pPane->m_pServerEntry->GetBuffer(*buf); } return pPane; } pPane->m_pLeft = new CPaneFrame(pMain, NULL, pPane); pPane->m_pRight = new CPaneFrame(pMain, NULL, pPane); switch(pPane->m_Style) { case PANEFRAME_WIDTH: pPane->m_pLeft->m_Frame.right = pPane->m_Frame.Width() * Size / 1000; pPane->m_pRight->m_Frame.left = pPane->m_pLeft->m_Frame.right + pPane->m_BoderSize; if ( pPane->m_pLeft->m_Frame.Width() < PANEMIN_WIDTH || pPane->m_pRight->m_Frame.Width() < PANEMIN_WIDTH ) { pPane->m_pLeft->m_Frame = pPane->m_Frame; pPane->m_pRight->m_Frame = pPane->m_Frame; pPane->m_Style = PANEFRAME_MAXIM; } break; case PANEFRAME_HEIGHT: pPane->m_pLeft->m_Frame.bottom = pPane->m_Frame.Height() * Size / 1000; pPane->m_pRight->m_Frame.top = pPane->m_pLeft->m_Frame.bottom + pPane->m_BoderSize; if ( pPane->m_pLeft->m_Frame.Height() < PANEMIN_HEIGHT || pPane->m_pRight->m_Frame.Height() < PANEMIN_HEIGHT ) { pPane->m_pLeft->m_Frame = pPane->m_Frame; pPane->m_pRight->m_Frame = pPane->m_Frame; pPane->m_Style = PANEFRAME_MAXIM; } break; } pPane->m_pLeft = GetBuffer(pMain, pPane->m_pLeft, pPane, buf); pPane->m_pRight = GetBuffer(pMain, pPane->m_pRight, pPane, buf); if ( pPane->m_pLeft == NULL || pPane->m_pRight == NULL ) { delete pPane; return NULL; } return pPane; } #ifdef DEBUG void CPaneFrame::Dump() { static const char *style[] = { "NOCHNG", "MAXIM", "WIDTH", "HEIGHT", "WINDOW" }; TRACE("hWnd=%x ", m_hWnd); TRACE("Style=%s ", style[m_Style]); TRACE("Frame=%d,%d,%d,%d ", m_Frame.left, m_Frame.top, m_Frame.right, m_Frame.bottom); TRACE("\n"); if ( m_pLeft != NULL ) m_pLeft->Dump(); if ( m_pRight != NULL ) m_pRight->Dump(); } #endif ///////////////////////////////////////////////////////////////////////////// // CTimerObject CTimerObject::CTimerObject() { m_Id = 0; m_Mode = 0; m_pObject = NULL; m_pList = NULL; } void CTimerObject::CallObject() { ASSERT(m_pObject != NULL); switch(m_Mode & 007) { case TIMEREVENT_DOC: ((CRLoginDoc *)(m_pObject))->OnDelayReceive((-1)); break; case TIMEREVENT_SOCK: ((CExtSocket *)(m_pObject))->OnTimer(m_Id); break; case TIMEREVENT_SCRIPT: ((CScript *)(m_pObject))->OnTimer(m_Id); break; case TIMEREVENT_TEXTRAM: ((CTextRam *)(m_pObject))->OnTimer(m_Id); break; } } ///////////////////////////////////////////////////////////////////////////// // CMainFrame IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd) ON_WM_CREATE() ON_WM_DESTROY() ON_WM_ENTERIDLE() ON_WM_SYSCOMMAND() ON_WM_TIMER() ON_WM_SETCURSOR() ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_COPYDATA() ON_WM_ENTERMENULOOP() ON_WM_EXITMENULOOP() ON_WM_ACTIVATE() ON_WM_CLOSE() ON_WM_DRAWCLIPBOARD() ON_WM_CHANGECBCHAIN() ON_WM_CLIPBOARDUPDATE() ON_WM_MOVING() ON_WM_GETMINMAXINFO() ON_MESSAGE(WM_SOCKSEL, OnWinSockSelect) ON_MESSAGE(WM_GETHOSTADDR, OnGetHostAddr) ON_MESSAGE(WM_ICONMSG, OnIConMsg) ON_MESSAGE(WM_THREADCMD, OnThreadMsg) ON_MESSAGE(WM_AFTEROPEN, OnAfterOpen) ON_MESSAGE(WM_GETCLIPBOARD, OnGetClipboard) ON_MESSAGE(WM_DPICHANGED, OnDpiChanged) ON_MESSAGE(WM_SETMESSAGESTRING, OnSetMessageString) ON_COMMAND(ID_FILE_ALL_LOAD, OnFileAllLoad) ON_COMMAND(ID_FILE_ALL_SAVE, OnFileAllSave) ON_COMMAND(ID_PANE_WSPLIT, OnPaneWsplit) ON_COMMAND(ID_PANE_HSPLIT, OnPaneHsplit) ON_COMMAND(ID_PANE_DELETE, OnPaneDelete) ON_COMMAND(ID_PANE_SAVE, OnPaneSave) ON_COMMAND(ID_VIEW_MENUBAR, &CMainFrame::OnViewMenubar) ON_UPDATE_COMMAND_UI(ID_VIEW_MENUBAR, &CMainFrame::OnUpdateViewMenubar) ON_COMMAND(ID_VIEW_TABBAR, &CMainFrame::OnViewTabbar) ON_UPDATE_COMMAND_UI(ID_VIEW_TABBAR, &CMainFrame::OnUpdateViewTabbar) ON_COMMAND(ID_VIEW_SCROLLBAR, &CMainFrame::OnViewScrollbar) ON_UPDATE_COMMAND_UI(ID_VIEW_SCROLLBAR, &CMainFrame::OnUpdateViewScrollbar) ON_COMMAND(ID_WINDOW_CASCADE, OnWindowCascade) ON_UPDATE_COMMAND_UI(ID_WINDOW_CASCADE, OnUpdateWindowCascade) ON_COMMAND(ID_WINDOW_TILE_HORZ, OnWindowTileHorz) ON_UPDATE_COMMAND_UI(ID_WINDOW_TILE_HORZ, OnUpdateWindowTileHorz) ON_COMMAND(ID_WINDOW_ROTATION, &CMainFrame::OnWindowRotation) ON_UPDATE_COMMAND_UI(ID_WINDOW_ROTATION, &CMainFrame::OnUpdateWindowRotation) ON_COMMAND(IDM_WINDOW_PREV, &CMainFrame::OnWindowPrev) ON_UPDATE_COMMAND_UI(IDM_WINDOW_PREV, &CMainFrame::OnUpdateWindowPrev) ON_COMMAND(IDM_WINODW_NEXT, &CMainFrame::OnWinodwNext) ON_UPDATE_COMMAND_UI(IDM_WINODW_NEXT, &CMainFrame::OnUpdateWinodwNext) ON_COMMAND_RANGE(AFX_IDM_FIRST_MDICHILD, AFX_IDM_FIRST_MDICHILD + 255, &CMainFrame::OnWinodwSelect) ON_COMMAND_RANGE(IDM_MOVEPANE_UP, IDM_MOVEPANE_LEFT, &CMainFrame::OnActiveMove) ON_UPDATE_COMMAND_UI_RANGE(IDM_MOVEPANE_UP, IDM_MOVEPANE_LEFT, &CMainFrame::OnUpdateActiveMove) ON_UPDATE_COMMAND_UI(ID_INDICATOR_SOCK, OnUpdateIndicatorSock) ON_UPDATE_COMMAND_UI(ID_INDICATOR_STAT, OnUpdateIndicatorStat) ON_UPDATE_COMMAND_UI(ID_INDICATOR_KMOD, OnUpdateIndicatorKmod) ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, OnToolTipText) ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, OnToolTipText) ON_COMMAND(IDM_VERSIONCHECK, &CMainFrame::OnVersioncheck) ON_UPDATE_COMMAND_UI(IDM_VERSIONCHECK, &CMainFrame::OnUpdateVersioncheck) ON_COMMAND(IDM_NEWVERSIONFOUND, &CMainFrame::OnNewVersionFound) ON_COMMAND(IDM_BROADCAST, &CMainFrame::OnBroadcast) ON_UPDATE_COMMAND_UI(IDM_BROADCAST, &CMainFrame::OnUpdateBroadcast) ON_COMMAND(IDM_TOOLCUST, &CMainFrame::OnToolcust) ON_COMMAND(IDM_CLIPCHAIN, &CMainFrame::OnClipchain) ON_UPDATE_COMMAND_UI(IDM_CLIPCHAIN, &CMainFrame::OnUpdateClipchain) ON_COMMAND(IDM_DELOLDENTRYTAB, OnDeleteOldEntry) END_MESSAGE_MAP() static const UINT indicators[] = { ID_SEPARATOR, // ステータス ライン インジケータ ID_INDICATOR_SOCK, ID_INDICATOR_STAT, ID_INDICATOR_KMOD, ID_INDICATOR_CAPS, ID_INDICATOR_NUM, // ID_INDICATOR_SCRL, // ID_INDICATOR_KANA, }; ///////////////////////////////////////////////////////////////////////////// // CMainFrame コンストラクション/デストラクション CMainFrame::CMainFrame() { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); m_hIconActive = AfxGetApp()->LoadIcon(IDI_ACTIVE); m_IconShow = FALSE; m_pTopPane = NULL; m_Frame.SetRectEmpty(); m_pTrackPane = NULL; m_LastPaneFlag = FALSE; m_TimerSeqId = TIMERID_TIMEREVENT; m_pTimerUsedId = NULL; m_pTimerFreeId = NULL; m_SleepStatus = 0; m_SleepTimer = 0; m_TransParValue = 255; m_TransParColor = RGB(0, 0, 0); m_SleepCount = 60; m_hMidiOut = NULL; m_MidiTimer = 0; m_InfoThreadCount = 0; m_SplitType = PANEFRAME_WSPLIT; m_StartMenuHand = NULL; m_bVersionCheck = FALSE; m_hNextClipWnd = NULL; m_bBroadCast = FALSE; m_bTabBarShow = FALSE; m_StatusTimer = 0; m_bAllowClipChain = TRUE; m_bClipEnable = FALSE; m_bClipChain = FALSE; m_ScreenDpiX = m_ScreenDpiY = 96; m_bGlassStyle = FALSE; m_UseBitmapUpdate = FALSE; m_bClipThreadCount = 0; m_ClipTimer = 0; m_IdleTimer = 0; } CMainFrame::~CMainFrame() { if ( m_pTopPane != NULL ) delete m_pTopPane; while ( m_pTimerUsedId != NULL ) DelTimerEvent(m_pTimerUsedId->m_pObject); CTimerObject *tp; while ( (tp = m_pTimerFreeId) != NULL ) { m_pTimerFreeId = tp->m_pList; delete tp; } if ( m_MidiTimer != 0 ) KillTimer(m_MidiTimer); CMidiQue *mp; while ( !m_MidiQue.IsEmpty() && (mp = m_MidiQue.RemoveHead()) != NULL ) delete mp; if ( m_hMidiOut != NULL ) { midiOutReset(m_hMidiOut); midiOutClose(m_hMidiOut); } CMenuBitMap *pMap; for ( int n = 0 ; n < m_MenuMap.GetSize() ; n++ ) { if ( (pMap = (CMenuBitMap *)m_MenuMap[n]) == NULL ) continue; pMap->m_Bitmap.DeleteObject(); delete pMap; } for ( int n = 0 ; m_InfoThreadCount > 0 && n < 10 ; n++ ) Sleep(300); } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { int n; CBitmap BitMap; CBuffer buf; CMenu *pMenu; UINT nID, nSt; if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; // キャラクタービットマップの読み込み #if USE_GOZI == 1 || USE_GOZI == 2 ((CRLoginApp *)::AfxGetApp())->LoadResBitmap(MAKEINTRESOURCE(IDB_BITMAP8), BitMap); m_ImageGozi.Create(32, 32, ILC_COLOR24 | ILC_MASK, 28, 10); m_ImageGozi.Add(&BitMap, RGB(192, 192, 192)); BitMap.DeleteObject(); #elif USE_GOZI == 3 ((CRLoginApp *)::AfxGetApp())->LoadResBitmap(MAKEINTRESOURCE(IDB_BITMAP8), BitMap); m_ImageGozi.Create(16, 16, ILC_COLOR24 | ILC_MASK, 12, 10); m_ImageGozi.Add(&BitMap, RGB(255, 255, 255)); BitMap.DeleteObject(); #elif USE_GOZI == 4 m_ImageGozi.Create(16, 16, ILC_COLOR24 | ILC_MASK, 12 * 13, 12); for ( n = 0 ; n < 13 ; n++ ) { ((CRLoginApp *)::AfxGetApp())->LoadResBitmap(MAKEINTRESOURCE(IDB_BITMAP10 + n), BitMap); m_ImageGozi.Add(&BitMap, RGB(255, 255, 255)); BitMap.DeleteObject(); } #endif // USE_GOZI // メニュー画像を作成 InitMenuBitmap(); // ツール・ステータス・タブ バーの作成 if ( !m_wndToolBar.CreateEx(this, TBSTYLE_FLAT | TBSTYLE_TRANSPARENT, WS_CHILD | WS_VISIBLE | CBRS_TOP | /*CBRS_GRIPPER | */CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || !((CRLoginApp *)::AfxGetApp())->LoadResToolBar(MAKEINTRESOURCE(IDR_MAINFRAME), m_wndToolBar) ) { TRACE0("Failed to create toolbar\n"); return -1; // 作成に失敗 } if ( !m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT)) ) { TRACE0("Failed to create status bar\n"); return -1; // 作成に失敗 } if ( !m_wndTabBar.Create(this, WS_VISIBLE| WS_CHILD|CBRS_TOP|WS_EX_WINDOWEDGE, IDC_MDI_TAB_CTRL_BAR) ) { TRACE("Failed to create tabbar\n"); return -1; // fail to create } m_wndStatusBar.GetPaneInfo(0, nID, nSt, n); m_wndStatusBar.SetPaneInfo(0, nID, nSt, 160); m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); m_wndTabBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); DockControlBar(&m_wndTabBar); // バーの表示設定 if ( (AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("ToolBarStyle"), WS_VISIBLE) & WS_VISIBLE) == 0 ) ShowControlBar(&m_wndToolBar, FALSE, 0); if ( (AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("StatusBarStyle"), WS_VISIBLE) & WS_VISIBLE) == 0 ) ShowControlBar(&m_wndStatusBar, FALSE, 0); m_bTabBarShow = AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("TabBarShow"), FALSE); ShowControlBar(&m_wndTabBar, m_bTabBarShow, 0); // 特殊効果の設定 m_TransParValue = AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("LayeredWindow"), 255); m_TransParColor = AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("LayeredColor"), RGB(0, 0 ,0)); SetTransPar(m_TransParColor, m_TransParValue, LWA_ALPHA | LWA_COLORKEY); if ( (m_SleepCount = AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("WakeUpSleep"), 0)) > 0 ) m_SleepTimer = SetTimer(TIMERID_SLEEPMODE, 5000, NULL); m_ScrollBarFlag = AfxGetApp()->GetProfileInt(_T("ChildFrame"), _T("VScroll"), TRUE); m_bVersionCheck = AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("VersionCheckFlag"), FALSE); m_bGlassStyle = AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("GlassStyle"), FALSE); ExDwmEnableWindow(m_hWnd, m_bGlassStyle); // 画面分割を復帰 try { ((CRLoginApp *)AfxGetApp())->GetProfileBuffer(_T("MainFrame"), _T("Pane"), buf); m_pTopPane = CPaneFrame::GetBuffer(this, NULL, NULL, &buf); } catch(LPCTSTR pMsg) { CString tmp; tmp.Format(_T("Pane Init Error '%s'"), pMsg); ::AfxMessageBox(tmp); } catch(...) { CString tmp; tmp.Format(_T("Pane Init Error #%d"), ::GetLastError()); ::AfxMessageBox(tmp); } // メニューの初期化 if ( (pMenu = GetSystemMenu(FALSE)) != NULL ) { pMenu->InsertMenu(0, MF_BYPOSITION | MF_SEPARATOR); pMenu->InsertMenu(0, MF_BYPOSITION | MF_STRING, ID_VIEW_MENUBAR, CStringLoad(IDS_VIEW_MENUBAR)); } if ( (pMenu = GetMenu()) != NULL ) { m_StartMenuHand = pMenu->GetSafeHmenu(); SetMenuBitmap(pMenu); } // クリップボードチェインの設定 if ( (m_bAllowClipChain = AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("ClipboardChain"), TRUE)) ) { if ( ExAddClipboardFormatListener != NULL && ExRemoveClipboardFormatListener != NULL ) { if ( ExAddClipboardFormatListener(m_hWnd) ) PostMessage(WM_GETCLIPBOARD); } else { m_bClipChain = TRUE; m_hNextClipWnd = SetClipboardViewer(); m_ClipTimer = SetTimer(TIMERID_CLIPUPDATE, 60000, NULL); } } // 標準の設定のキー設定を読み込み・初期化 m_DefKeyTab.Serialize(FALSE); m_DefKeyTab.CmdsInit(); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CMDIFrameWnd::PreCreateWindow(cs) ) return FALSE; int n = GetExecCount(); CString sect; if ( n == 0 ) { cs.x = AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("x"), cs.x); cs.y = AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("y"), cs.y); cs.cx = AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("cx"), cs.cx); cs.cy = AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("cy"), cs.cy); } else { sect.Format(_T("SecondFrame%02d"), n); if ( (n = AfxGetApp()->GetProfileInt(sect, _T("x"), (-1))) != (-1) ) cs.x = n; if ( (n = AfxGetApp()->GetProfileInt(sect, _T("y"), (-1))) != (-1) ) cs.y = n; if ( (n = AfxGetApp()->GetProfileInt(sect, _T("cx"), (-1))) != (-1) ) cs.cx = n; else cs.cx = AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("cx"), cs.cx); if ( (n = AfxGetApp()->GetProfileInt(sect, _T("cy"), (-1))) != (-1) ) cs.cy = n; else cs.cy = AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("cy"), cs.cy); } if ( m_ScreenW > 0 ) cs.cx = m_ScreenW; if ( m_ScreenH > 0 ) cs.cy = m_ScreenH; if ( m_ScreenX > 0 ) cs.x = m_ScreenX - cs.cx / 2; if ( m_ScreenY > 0 ) cs.y = m_ScreenY; // モニターの表示範囲チェック HMONITOR hMonitor; MONITORINFOEX mi; CRect rc(cs.x, cs.y, cs.x + cs.cx, cs.y + cs.cy); hMonitor = MonitorFromRect(&rc, MONITOR_DEFAULTTONEAREST); mi.cbSize = sizeof(MONITORINFOEX); GetMonitorInfo(hMonitor, &mi); #if 1 // モニターを基準に調整 if ( cs.x < mi.rcMonitor.left ) cs.x = mi.rcMonitor.left; if ( cs.y < mi.rcMonitor.top ) cs.y = mi.rcMonitor.top; if ( (cs.x + cs.cx) > mi.rcMonitor.right ) { if ( (cs.x = mi.rcMonitor.right - cs.cx) < mi.rcMonitor.left ) { cs.x = mi.rcMonitor.left; cs.cx = mi.rcMonitor.right - mi.rcMonitor.left; } } if ( (cs.y + cs.cy) > mi.rcMonitor.bottom ) { if ( (cs.y = mi.rcMonitor.bottom - cs.cy) < mi.rcMonitor.top ) { cs.y = mi.rcMonitor.top; cs.cy = mi.rcMonitor.bottom - mi.rcMonitor.top; } } #else // 仮想画面サイズを基準に調整 if ( (cs.x + cs.cx) > mi.rcWork.right ) { if ( (cs.x = mi.rcWork.right - cs.cx) < mi.rcWork.left ) { cs.x = mi.rcWork.left; cs.cx = mi.rcWork.right - mi.rcWork.left; } } if ( (cs.y + cs.cy) > mi.rcWork.bottom ) { if ( (cs.y = mi.rcWork.bottom - cs.cy) < mi.rcWork.top ) { cs.y = mi.rcWork.top; cs.cy = mi.rcWork.bottom - mi.rcWork.top; } } #endif // モニターDPIを取得 if ( ExGetDpiForMonitor != NULL ) ExGetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, &m_ScreenDpiX, &m_ScreenDpiY); // メニューをリソースデータベースに置き換え if ( cs.hMenu != NULL ) { DestroyMenu(cs.hMenu); ((CRLoginApp *)::AfxGetApp())->LoadResMenu(MAKEINTRESOURCE(IDR_MAINFRAME), cs.hMenu); } //TRACE("Main Style "); //if ( (cs.style & WS_BORDER) != NULL ) TRACE("WS_BORDER "); //if ( (cs.style & WS_DLGFRAME) != NULL ) TRACE("WS_DLGFRAME "); //if ( (cs.style & WS_THICKFRAME) != NULL ) TRACE("WS_THICKFRAME "); //if ( (cs.dwExStyle & WS_EX_WINDOWEDGE) != NULL ) TRACE("WS_EX_WINDOWEDGE "); //if ( (cs.dwExStyle & WS_EX_CLIENTEDGE) != NULL ) TRACE("WS_EX_CLIENTEDGE "); //if ( (cs.dwExStyle & WS_EX_DLGMODALFRAME) != NULL ) TRACE("WS_EX_DLGMODALFRAME "); //if ( (cs.dwExStyle & WS_EX_TOOLWINDOW) != NULL ) TRACE("WS_EX_TOOLWINDOW "); //TRACE("\n"); return TRUE; } ///////////////////////////////////////////////////////////////////////////// #define AGENT_COPYDATA_ID 0x804e50ba /* random goop */ #define AGENT_MAX_MSGLEN 8192 BOOL CMainFrame::PageantQuery(CBuffer *pInBuf, CBuffer *pOutBuf) { int len; CWnd *pWnd; CString mapname; HANDLE filemap; BYTE *p; COPYDATASTRUCT cds; CStringA mbs; if ( (pWnd = FindWindow(_T("Pageant"), _T("Pageant"))) == NULL ) return FALSE; mapname.Format(_T("PageantRequest%08x"), (unsigned)GetCurrentThreadId()); filemap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, AGENT_MAX_MSGLEN, mapname); if ( filemap == NULL || filemap == INVALID_HANDLE_VALUE ) return FALSE; if ( (p = (BYTE *)MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0)) == NULL ) { CloseHandle(filemap); return FALSE; } ASSERT(pInBuf->GetSize() < AGENT_MAX_MSGLEN); memcpy(p, pInBuf->GetPtr(), pInBuf->GetSize()); mbs = mapname; cds.dwData = AGENT_COPYDATA_ID; cds.cbData = mbs.GetLength() + 1; cds.lpData = mbs.GetBuffer(); pOutBuf->Clear(); if ( pWnd->SendMessage(WM_COPYDATA, NULL, (LPARAM)&cds) > 0 ) { len = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | (p[3]); if ( len > 0 && (len + 4) < AGENT_MAX_MSGLEN ) pOutBuf->Apend(p + 4, len); } UnmapViewOfFile(p); CloseHandle(filemap); return TRUE; } BOOL CMainFrame::PageantInit() { int n, i; int count = 0; CBuffer in, out; CIdKey key; CBuffer blob; CStringA name; for ( i = 0 ; i < m_IdKeyTab.GetSize() ; i++ ) { if ( m_IdKeyTab[i].m_bPageant ) m_IdKeyTab[i].m_bSecInit = FALSE; } in.Put32Bit(1); in.Put8Bit(SSH_AGENTC_REQUEST_IDENTITIES); if ( !PageantQuery(&in, &out) ) return FALSE; if ( out.GetSize() < 5 || out.Get8Bit() != SSH_AGENT_IDENTITIES_ANSWER ) return FALSE; try { count = out.Get32Bit(); for ( n = 0 ; n < count ; n++ ) { out.GetBuf(&blob); out.GetStr(name); key.m_Name = name; key.m_bPageant = TRUE; key.m_bSecInit = TRUE; if ( !key.GetBlob(&blob) ) continue; for ( i = 0 ; i < m_IdKeyTab.GetSize() ; i++ ) { if ( m_IdKeyTab[i].m_bPageant && m_IdKeyTab[i].ComperePublic(&key) == 0 ) { m_IdKeyTab[i].m_bSecInit = TRUE; break; } } if ( i >= m_IdKeyTab.GetSize() ) m_IdKeyTab.AddEntry(key, FALSE); } #ifdef DEBUG } catch(LPCTSTR msg) { TRACE(_T("PageantInit Error %s '%s'\n"), MbsToTstr(name), msg); return FALSE; #endif } catch(...) { return FALSE; } return (count <= 0 ? FALSE : TRUE); } BOOL CMainFrame::PageantSign(CBuffer *blob, CBuffer *sign, LPBYTE buf, int len) { CBuffer in, out, work; work.Put8Bit(SSH_AGENTC_SIGN_REQUEST); work.PutBuf(blob->GetPtr(), blob->GetSize()); work.PutBuf(buf, len); work.Put32Bit(0); in.PutBuf(work.GetPtr(), work.GetSize()); if ( !PageantQuery(&in, &out) ) return FALSE; if ( out.GetSize() < 5 || out.Get8Bit() != SSH_AGENT_SIGN_RESPONSE ) return FALSE; sign->Clear(); out.GetBuf(sign); return TRUE; } ///////////////////////////////////////////////////////////////////////////// int CMainFrame::SetAsyncSelect(SOCKET fd, CExtSocket *pSock, long lEvent) { ASSERT(pSock->m_Type >= 0 && pSock->m_Type < 10); if ( lEvent != 0 && WSAAsyncSelect(fd, GetSafeHwnd(), WM_SOCKSEL, lEvent) != 0 ) return FALSE; ((CRLoginApp *)AfxGetApp())->AddIdleProc(IDLEPROC_SOCKET, pSock); for ( int n = 0 ; n < m_SocketParam.GetSize() ; n += 2 ) { if ( m_SocketParam[n] == (void *)fd ) { m_SocketParam[n + 1] = (void *)pSock; return TRUE; } } m_SocketParam.Add((void *)fd); m_SocketParam.Add(pSock); return TRUE; } void CMainFrame::DelAsyncSelect(SOCKET fd, CExtSocket *pSock, BOOL useWsa) { if ( useWsa ) WSAAsyncSelect(fd, GetSafeHwnd(), 0, 0); ((CRLoginApp *)AfxGetApp())->DelIdleProc(IDLEPROC_SOCKET, pSock); for ( int n = 0 ; n < m_SocketParam.GetSize() ; n += 2 ) { if ( m_SocketParam[n] == (void *)fd ) { m_SocketParam.RemoveAt(n, 2); break; } } } int CMainFrame::SetAsyncHostAddr(int mode, LPCTSTR pHostName, CExtSocket *pSock) { HANDLE hGetHostAddr; CString *pStr = new CString(pHostName); char *pData = new char[MAXGETHOSTSTRUCT]; memset(pData, 0, MAXGETHOSTSTRUCT); if ( (hGetHostAddr = WSAAsyncGetHostByName(GetSafeHwnd(), WM_GETHOSTADDR, TstrToMbs(pHostName), pData, MAXGETHOSTSTRUCT)) == (HANDLE)0 ) { CString errmsg; errmsg.Format(_T("GetHostByName Error '%s'"), pHostName); AfxMessageBox(errmsg, MB_ICONSTOP); return FALSE; } m_HostAddrParam.Add(hGetHostAddr); m_HostAddrParam.Add(pSock); m_HostAddrParam.Add(pStr); m_HostAddrParam.Add(pData); m_HostAddrParam.Add((void *)(INT_PTR)mode); return TRUE; } typedef struct _addrinfo_param { CMainFrame *pWnd; int mode; CString name; CString port; ADDRINFOT hint; int ret; } addrinfo_param; static UINT AddrInfoThread(LPVOID pParam) { ADDRINFOT *ai; addrinfo_param *ap = (addrinfo_param *)pParam; ap->ret = GetAddrInfo(ap->name, ap->port, &(ap->hint), &ai); if ( ap->pWnd->m_InfoThreadCount-- > 0 && ap->pWnd->m_hWnd != NULL ) ap->pWnd->PostMessage(WM_GETHOSTADDR, (WPARAM)ap, (LPARAM)ai); return 0; } int CMainFrame::SetAsyncAddrInfo(int mode, LPCTSTR pHostName, int PortNum, void *pHint, CExtSocket *pSock) { addrinfo_param *ap; ap = new addrinfo_param; ap->pWnd = this; ap->mode = mode; ap->name = pHostName; ap->port.Format(_T("%d"), PortNum); ap->ret = 1; memcpy(&(ap->hint), pHint, sizeof(ADDRINFOT)); m_InfoThreadCount++; AfxBeginThread(AddrInfoThread, ap, THREAD_PRIORITY_NORMAL); m_HostAddrParam.Add(ap); m_HostAddrParam.Add(pSock); m_HostAddrParam.Add(NULL); m_HostAddrParam.Add(NULL); m_HostAddrParam.Add((void *)(INT_PTR)mode); return TRUE; } int CMainFrame::SetAfterId(void *param) { static int SeqId = 0; m_AfterIdParam.Add((void *)(INT_PTR)(++SeqId)); m_AfterIdParam.Add(param); return SeqId; } int CMainFrame::SetTimerEvent(int msec, int mode, void *pParam) { CTimerObject *tp; DelTimerEvent(pParam); if ( m_pTimerFreeId == NULL ) { for ( int n = 0 ; n < 16 ; n++ ) { tp = new CTimerObject; tp->m_Id = m_TimerSeqId++; tp->m_pList = m_pTimerFreeId; m_pTimerFreeId = tp; } } tp = m_pTimerFreeId; m_pTimerFreeId = tp->m_pList; tp->m_pList = m_pTimerUsedId; m_pTimerUsedId = tp; SetTimer(tp->m_Id, msec, NULL); tp->m_Mode = mode; tp->m_pObject = pParam; return tp->m_Id; } void CMainFrame::DelTimerEvent(void *pParam) { CTimerObject *tp, *bp; for ( tp = bp = m_pTimerUsedId ; tp != NULL ; ) { if ( tp->m_pObject == pParam ) { KillTimer(tp->m_Id); if ( tp == m_pTimerUsedId ) m_pTimerUsedId = tp->m_pList; else bp->m_pList = tp->m_pList; FreeTimerEvent(tp); break; } bp = tp; tp = tp->m_pList; } } void CMainFrame::RemoveTimerEvent(CTimerObject *pObject) { CTimerObject *tp; KillTimer(pObject->m_Id); if ( (tp = m_pTimerUsedId) == pObject ) m_pTimerUsedId = pObject->m_pList; else { while ( tp != NULL ) { if ( tp->m_pList == pObject ) { tp->m_pList = pObject->m_pList; break; } tp = tp->m_pList; } } } void CMainFrame::FreeTimerEvent(CTimerObject *pObject) { pObject->m_Mode = 0; pObject->m_pObject = NULL; pObject->m_pList = m_pTimerFreeId; m_pTimerFreeId = pObject; } void CMainFrame::SetMidiEvent(int msec, DWORD msg) { CMidiQue *qp; if ( m_hMidiOut == NULL && midiOutOpen(&m_hMidiOut, MIDIMAPPER, NULL, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) return; if ( m_MidiQue.IsEmpty() && msec == 0 ) { midiOutShortMsg(m_hMidiOut, msg); return; } qp = new CMidiQue; qp->m_mSec = msec; qp->m_Msg = msg; m_MidiQue.AddTail(qp); qp = m_MidiQue.GetHead(); if ( m_MidiTimer == 0 ) m_MidiTimer = SetTimer(TIMERID_MIDIEVENT, qp->m_mSec, NULL); } void CMainFrame::SetIdleTimer(BOOL bSw) { if ( bSw ) { if ( m_IdleTimer == 0 ) m_IdleTimer = SetTimer(TIMERID_IDLETIMER, 200, NULL); } else if ( m_IdleTimer != 0 ) { KillTimer(m_IdleTimer); m_IdleTimer = 0; } } ///////////////////////////////////////////////////////////////////////////// int CMainFrame::OpenServerEntry(CServerEntry &Entry) { int n; CServerSelect dlg; CWnd *pTemp = MDIGetActive(NULL); CPaneFrame *pPane = NULL; CRLoginApp *pApp = (CRLoginApp *)::AfxGetApp(); dlg.m_pData = &m_ServerEntryTab; dlg.m_EntryNum = (-1); if ( m_LastPaneFlag && pTemp != NULL && m_pTopPane != NULL && (pPane = m_pTopPane->GetPane(pTemp->m_hWnd)) != NULL && pPane->m_pServerEntry != NULL ) { Entry = *(pPane->m_pServerEntry); Entry.m_DocType = DOCTYPE_MULTIFILE; delete pPane->m_pServerEntry; pPane->m_pServerEntry = NULL; if ( m_pTopPane->GetEntry() != NULL ) PostMessage(WM_COMMAND, ID_FILE_NEW, 0); else m_LastPaneFlag = FALSE; return TRUE; } m_LastPaneFlag = FALSE; for ( n = 0 ; n< m_ServerEntryTab.m_Data.GetSize() ; n++ ) { if ( m_ServerEntryTab.m_Data[n].m_CheckFlag ) { dlg.m_EntryNum = n; break; } } if ( dlg.m_EntryNum < 0 ) { if ( pApp->m_pServerEntry != NULL ) { Entry = *(pApp->m_pServerEntry); pApp->m_pServerEntry = NULL; return TRUE; } if ( pApp->m_pCmdInfo != NULL && !pApp->m_pCmdInfo->m_Name.IsEmpty() ) { for ( n = 0 ; n< m_ServerEntryTab.m_Data.GetSize() ; n++ ) { if ( pApp->m_pCmdInfo->m_Name.Compare(m_ServerEntryTab.m_Data[n].m_EntryName) == 0 ) { Entry = m_ServerEntryTab.m_Data[n]; Entry.m_DocType = DOCTYPE_REGISTORY; return TRUE; } } } if ( pApp->m_pCmdInfo != NULL && pApp->m_pCmdInfo->m_Proto != (-1) && !pApp->m_pCmdInfo->m_Port.IsEmpty() ) { if ( Entry.m_EntryName.IsEmpty() ) Entry.m_EntryName.Format(_T("%s:%s"), (pApp->m_pCmdInfo->m_Addr.IsEmpty() ? _T("unkown") : pApp->m_pCmdInfo->m_Addr), pApp->m_pCmdInfo->m_Port); Entry.m_DocType = DOCTYPE_SESSION; return TRUE; } if ( dlg.DoModal() != IDOK || dlg.m_EntryNum < 0 ) return FALSE; } m_ServerEntryTab.m_Data[dlg.m_EntryNum].m_CheckFlag = FALSE; Entry = m_ServerEntryTab.m_Data[dlg.m_EntryNum]; Entry.m_DocType = DOCTYPE_REGISTORY; for ( n = 0 ; n < m_ServerEntryTab.m_Data.GetSize() ; n++ ) { if ( m_ServerEntryTab.m_Data[n].m_CheckFlag ) { PostMessage(WM_COMMAND, ID_FILE_NEW, 0); break; } } return TRUE; } void CMainFrame::SetTransPar(COLORREF rgb, int value, DWORD flag) { if ( (flag & LWA_COLORKEY) != 0 && rgb == 0 ) flag &= ~LWA_COLORKEY; else if ( m_TransParColor != 0 ) { rgb = m_TransParColor; flag |= LWA_COLORKEY; } if ( (flag & LWA_ALPHA) != 0 && value == 255 ) flag &= ~LWA_ALPHA; //rgb = RGB(0, 0, 0); //value = 255; //flag = LWA_COLORKEY; if ( flag == 0 ) ModifyStyleEx(WS_EX_LAYERED, 0); else ModifyStyleEx(0, WS_EX_LAYERED); SetLayeredWindowAttributes(rgb, value, flag); Invalidate(TRUE); } void CMainFrame::SetWakeUpSleep(int sec) { AfxGetApp()->WriteProfileInt(_T("MainFrame"), _T("WakeUpSleep"), sec); if ( sec > 0 && m_SleepTimer == 0 ) m_SleepTimer = SetTimer(TIMERID_SLEEPMODE, 5000, NULL); else if ( sec == 0 && m_SleepTimer != 0 ) { KillTimer(m_SleepTimer); if ( m_SleepStatus >= sec ) SetTransPar(0, m_TransParValue, LWA_ALPHA); m_SleepTimer = 0; } m_SleepStatus = 0; m_SleepCount = sec; } void CMainFrame::WakeUpSleep() { if ( m_SleepStatus == 0 ) return; else if ( m_SleepStatus >= m_SleepCount ) { SetTransPar(0, m_TransParValue, LWA_ALPHA); m_SleepTimer = SetTimer(TIMERID_SLEEPMODE, 5000, NULL); } m_SleepStatus = 0; } void CMainFrame::SetIconStyle() { if ( m_IconShow ) { ShowWindow(SW_RESTORE); Shell_NotifyIcon(NIM_DELETE, &m_IconData); m_IconShow = FALSE; return; } ZeroMemory(&m_IconData, sizeof(NOTIFYICONDATA)); m_IconData.cbSize = sizeof(NOTIFYICONDATA); m_IconData.hWnd = m_hWnd; m_IconData.uID = 1000; m_IconData.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; m_IconData.uCallbackMessage = WM_ICONMSG; m_IconData.hIcon = m_hIcon; _tcscpy(m_IconData.szTip, _T("RLogin")); if ( (m_IconShow = Shell_NotifyIcon(NIM_ADD, &m_IconData)) ) ShowWindow(SW_HIDE); } void CMainFrame::SetIconData(HICON hIcon, LPCTSTR str) { if ( m_IconShow == FALSE ) return; if ( hIcon != NULL ) m_IconData.hIcon = hIcon; if ( str != NULL ) _tcsncpy(m_IconData.szTip, str, sizeof(m_IconData.szTip) / sizeof(TCHAR)); Shell_NotifyIcon(NIM_MODIFY, &m_IconData); } ///////////////////////////////////////////////////////////////////////////// BOOL CMainFrame::IsConnectChild(CPaneFrame *pPane) { CChildFrame *pWnd; CRLoginDoc *pDoc; if ( pPane == NULL ) return FALSE; if ( IsConnectChild(pPane->m_pLeft) ) return TRUE; if ( IsConnectChild(pPane->m_pRight) ) return TRUE; if ( pPane->m_Style != PANEFRAME_WINDOW || pPane->m_hWnd == NULL ) return FALSE; if ( (pWnd = (CChildFrame *)(CWnd::FromHandlePermanent(pPane->m_hWnd))) == NULL ) return FALSE; if ( (pDoc = (CRLoginDoc *)(pWnd->GetActiveDocument())) == NULL ) return FALSE; if ( pDoc->m_pSock != NULL ) return TRUE; return FALSE; } void CMainFrame::AddChild(CWnd *pWnd) { if ( m_wndTabBar.m_TabCtrl.GetItemCount() >= 1 ) ShowControlBar(&m_wndTabBar, TRUE, TRUE); m_wndTabBar.Add(pWnd); CPaneFrame *pPane; if ( m_pTopPane == NULL ) { m_pTopPane = new CPaneFrame(this, pWnd->m_hWnd, NULL); m_pTopPane->MoveFrame(); } else if ( (pPane = m_pTopPane->GetNull()) != NULL ) { pPane->Attach(pWnd->m_hWnd); pPane->MoveFrame(); } else if ( (pPane = m_pTopPane->GetEntry()) != NULL ) { pPane->Attach(pWnd->m_hWnd); pPane->MoveFrame(); } else if ( (pPane = m_pTopPane->GetPane(NULL)) != NULL ) { pPane->Attach(pWnd->m_hWnd); pPane->MoveFrame(); } else { CWnd *pTemp = MDIGetActive(NULL); pPane = m_pTopPane->GetPane(pTemp->m_hWnd); pPane->CreatePane(PANEFRAME_MAXIM, pWnd->m_hWnd); } } void CMainFrame::RemoveChild(CWnd *pWnd, BOOL bDelete) { m_wndTabBar.Remove(pWnd); if ( m_wndTabBar.m_TabCtrl.GetItemCount() <= 1 ) ShowControlBar(&m_wndTabBar, m_bTabBarShow, TRUE); if ( m_pTopPane != NULL ) { CPaneFrame *pPane = m_pTopPane->GetPane(pWnd->m_hWnd); if ( pPane != NULL ) { if ( bDelete || (pPane->m_pOwn != NULL && pPane->m_pOwn->m_Style == PANEFRAME_MAXIM) ) { m_pTopPane = m_pTopPane->DeletePane(pWnd->m_hWnd); } else { pPane->m_hWnd = NULL; pPane->MoveFrame(); } } } } void CMainFrame::ActiveChild(CWnd *pWnd) { if ( m_pTopPane == NULL ) return; m_pTopPane->SetActive(pWnd->m_hWnd); #ifdef DEBUG_XXX m_pTopPane->Dump(); #endif } BOOL CMainFrame::IsWindowPanePoint(CPoint point) { if ( m_pTopPane == NULL ) return FALSE; point.y -= m_Frame.top; CPaneFrame *pPane = m_pTopPane->HitTest(point); if ( pPane == NULL || pPane->m_Style != PANEFRAME_WINDOW ) return FALSE; return TRUE; } void CMainFrame::MoveChild(CWnd *pWnd, CPoint point) { if ( m_pTopPane == NULL ) return; point.y -= m_Frame.top; HWND hLeft, hRight; CPaneFrame *pLeftPane = m_pTopPane->GetPane(pWnd->m_hWnd); CPaneFrame *pRightPane = m_pTopPane->HitTest(point); if ( pLeftPane == NULL || pRightPane == NULL ) return; if ( pLeftPane->m_Style != PANEFRAME_WINDOW || pRightPane->m_Style != PANEFRAME_WINDOW ) return; hLeft = pLeftPane->m_hWnd; hRight = pRightPane->m_hWnd; if ( hLeft == NULL || hLeft == hRight ) return; pLeftPane->m_hWnd = hRight; pRightPane->m_hWnd = hLeft; pLeftPane->MoveFrame(); pRightPane->MoveFrame(); } void CMainFrame::SwapChild(CWnd *pLeft, CWnd *pRight) { if ( m_pTopPane == NULL || pLeft == NULL || pRight == NULL ) return; HWND hLeft, hRight; CPaneFrame *pLeftPane = m_pTopPane->GetPane(pLeft->m_hWnd); CPaneFrame *pRightPane = m_pTopPane->GetPane(pRight->m_hWnd); if ( pLeftPane == NULL || pRightPane == NULL ) return; if ( pLeftPane->m_Style != PANEFRAME_WINDOW || pRightPane->m_Style != PANEFRAME_WINDOW ) return; if ( (hLeft = pLeftPane->m_hWnd) == NULL || (hRight = pRightPane->m_hWnd) == NULL || hLeft == hRight ) return; pLeftPane->m_hWnd = hRight; pRightPane->m_hWnd = hLeft; pLeftPane->MoveFrame(); pRightPane->MoveFrame(); } int CMainFrame::GetTabIndex(CWnd *pWnd) { return m_wndTabBar.GetIndex(pWnd); } void CMainFrame::GetTabTitle(CWnd *pWnd, CString &title) { int idx; if ( (idx = m_wndTabBar.GetIndex(pWnd)) >= 0 ) m_wndTabBar.GetTitle(idx, title); } CWnd *CMainFrame::GetTabWnd(int idx) { return m_wndTabBar.GetAt(idx); } int CMainFrame::GetTabCount() { return m_wndTabBar.GetSize(); } CRLoginDoc *CMainFrame::GetMDIActiveDocument() { CChildFrame *pChild; CRLoginDoc *pDoc = NULL; if ( (pChild = (CChildFrame *)(MDIGetActive())) != NULL ) pDoc = (CRLoginDoc *)(pChild->GetActiveDocument()); return pDoc; } BOOL CMainFrame::IsOverLap(HWND hWnd) { CPaneFrame *pPane; if ( m_pTopPane == NULL || (pPane = m_pTopPane->GetPane(hWnd)) == NULL ) return FALSE; return (m_pTopPane->IsOverLap(pPane) == 1 ? TRUE : FALSE); } BOOL CMainFrame::IsTopLevelDoc(CRLoginDoc *pDoc) { CRLoginView *pView; CChildFrame *pChild; CPaneFrame *pPane; if ( pDoc == NULL || (pView = (CRLoginView *)pDoc->GetAciveView()) == NULL || (pChild = pView->GetFrameWnd()) == NULL ) return FALSE; if ( m_pTopPane == NULL || (pPane = m_pTopPane->GetPane(pChild->m_hWnd)) == NULL ) return TRUE; if ( m_pTopPane->IsTopLevel(pPane) ) return TRUE; return FALSE; } void CMainFrame::GetFrameRect(CRect &frame) { if ( m_Frame.IsRectEmpty() ) RepositionBars(0, 0xffff, AFX_IDW_PANE_FIRST, reposQuery, &m_Frame); frame.SetRect(0, 0, m_Frame.Width(), m_Frame.Height()); } void CMainFrame::AdjustRect(CRect &rect) { if ( m_Frame.IsRectEmpty() ) RepositionBars(0, 0xffff, AFX_IDW_PANE_FIRST, reposQuery, &m_Frame); rect.top += m_Frame.top; rect.bottom += m_Frame.top; } ///////////////////////////////////////////////////////////////////////////// static BOOL CALLBACK RLoginExecCountFunc(HWND hwnd, LPARAM lParam) { CMainFrame *pMain = (CMainFrame *)lParam; if ( pMain->m_hWnd != hwnd && CRLoginApp::IsRLoginWnd(hwnd) ) pMain->m_ExecCount++; return TRUE; } int CMainFrame::GetExecCount() { m_ExecCount = 0; ::EnumWindows(RLoginExecCountFunc, (LPARAM)this); return m_ExecCount; } void CMainFrame::SetActivePoint(CPoint point) { CPaneFrame *pPane; ScreenToClient(&point); point.y -= m_Frame.top; if ( m_pTrackPane != NULL || m_pTopPane == NULL ) return; if ( (pPane = m_pTopPane->HitTest(point)) == NULL ) return; if ( pPane->m_Style == PANEFRAME_WINDOW ) { m_pTopPane->HitActive(point); if ( pPane->m_hWnd != NULL ) { CChildFrame *pWnd = (CChildFrame *)CWnd::FromHandle(pPane->m_hWnd); pWnd->MDIActivate(); } } } void CMainFrame::SetStatusText(LPCTSTR message) { if ( m_StatusTimer != 0 ) KillTimer(m_StatusTimer); SetMessageText(message); m_StatusTimer = SetTimer(TIMERID_STATUSCLR, 30000, NULL); } ///////////////////////////////////////////////////////////////////////////// void CMainFrame::ClipBoradStr(LPCWSTR str, CString &tmp) { int n, i; tmp.Empty(); for ( n = 0 ; n < 50 && *str != L'\0' ; n++, str++ ) { if ( *str == L'\n' ) n--; else if ( *str == L'\r' ) tmp += _T("↓"); else if ( *str == L'\x7F' || *str < L' ' || *str == L'&' || *str == L'\\' ) tmp += _T('.'); else if ( *str >= 256 ) { n++; tmp += *str; } else tmp += *str; if ( n >= 40 && (i = (int)wcslen(str)) > 10 ) { tmp += _T(" ... "); str += (i - 11); } } } void CMainFrame::SetClipBoardComboBox(CComboBox *pCombo) { int index = 1; POSITION pos; CString str, tmp; for ( pos = m_ClipBoard.GetHeadPosition() ; pos != NULL ; ) { ClipBoradStr((LPCWSTR)m_ClipBoard.GetNext(pos), str); tmp.Format(_T("%d %s"), (index++) % 10, str); pCombo->AddString(tmp); } } void CMainFrame::SetClipBoardMenu(UINT nId, CMenu *pMenu) { int n; int index = 1; POSITION pos; CString str, tmp; for ( n = 0 ; n < 10 ; n++ ) pMenu->DeleteMenu(nId + n, MF_BYCOMMAND); for ( pos = m_ClipBoard.GetHeadPosition() ; pos != NULL ; ) { ClipBoradStr((LPCWSTR)m_ClipBoard.GetNext(pos), str); tmp.Format(_T("&%d %s"), (index++) % 10, str); pMenu->AppendMenu(MF_STRING, nId++, tmp); } } BOOL CMainFrame::CopyClipboardData(CString &str) { int len, max = 0; HGLOBAL hData; WCHAR *pData = NULL; BOOL ret = FALSE; // 10msロック出来るまで待つ if ( !m_OpenClipboardLock.Lock(10) ) return FALSE; if ( !IsClipboardFormatAvailable(CF_UNICODETEXT) ) goto UNLOCKRET; if ( !OpenClipboard() ) goto UNLOCKRET; if ( (hData = GetClipboardData(CF_UNICODETEXT)) == NULL ) goto CLOSERET; if ( (pData = (WCHAR *)GlobalLock(hData)) == NULL ) goto CLOSERET; str.Empty(); max = (int)GlobalSize(hData) / sizeof(WCHAR); for ( len = 0 ; len < max && len < (256 * 1024) && *pData != L'\0' && *pData != L'\x1A' ; len++ ) str += *(pData++); GlobalUnlock(hData); ret = TRUE; CLOSERET: CloseClipboard(); UNLOCKRET: m_OpenClipboardLock.Unlock(); return ret; } static UINT CopyClipboardThead(LPVOID pParam) { int n; CString *pStr = new CString; CMainFrame *pWnd = (CMainFrame *)pParam; for ( n = 0 ; ; n++ ) { if ( pWnd->CopyClipboardData(*pStr) ) { pWnd->PostMessage(WM_GETCLIPBOARD, NULL, (LPARAM)pStr); break; } if ( n >= 10 ) { delete pStr; break; } Sleep(100); } pWnd->m_bClipThreadCount--; return 0; } BOOL CMainFrame::SetClipboardText(LPCTSTR str, LPCSTR rtf) { HGLOBAL hData; LPTSTR pData; // 500msロック出来るまで待つ if ( !m_OpenClipboardLock.Lock(500) ) { MessageBox(_T("Clipboard Busy...")); return FALSE; } if ( (hData = GlobalAlloc(GMEM_MOVEABLE, (_tcslen(str) + 1) * sizeof(TCHAR))) == NULL ) { m_OpenClipboardLock.Unlock(); MessageBox(_T("Global Alloc Error")); return FALSE; } if ( (pData = (TCHAR *)GlobalLock(hData)) == NULL ) { GlobalFree(hData); m_OpenClipboardLock.Unlock(); MessageBox(_T("Global Lock Error")); return FALSE; } _tcscpy(pData, str); GlobalUnlock(pData); // クリップボードチェインのチェックの為の処理 m_bClipEnable = FALSE; for ( int n = 0 ; !OpenClipboard() ; n++ ) { if ( n >= 10 ) { GlobalFree(hData); m_OpenClipboardLock.Unlock(); MessageBox(_T("Clipboard Open Error")); return FALSE; } Sleep(100); } if ( !EmptyClipboard() ) { GlobalFree(hData); CloseClipboard(); m_OpenClipboardLock.Unlock(); MessageBox(_T("Clipboard Empty Error")); return FALSE; } #ifdef _UNICODE if ( SetClipboardData(CF_UNICODETEXT, hData) == NULL ) { #else if ( SetClipboardData(CF_TEXT, hData) == NULL ) { #endif GlobalFree(hData); CloseClipboard(); m_OpenClipboardLock.Unlock(); MessageBox(_T("Clipboard Set Data Error")); return FALSE; } if ( rtf != NULL ) { if ( (hData = GlobalAlloc(GMEM_MOVEABLE, (strlen(rtf) + 1))) == NULL ) { m_OpenClipboardLock.Unlock(); MessageBox(_T("Global Alloc Error")); return FALSE; } if ( (pData = (TCHAR *)GlobalLock(hData)) == NULL ) { GlobalFree(hData); m_OpenClipboardLock.Unlock(); MessageBox(_T("Global Lock Error")); return FALSE; } strcpy((LPSTR)pData, rtf); GlobalUnlock(pData); if ( SetClipboardData(RegisterClipboardFormat(CF_RTF), hData) == NULL ) { GlobalFree(hData); CloseClipboard(); m_OpenClipboardLock.Unlock(); MessageBox(_T("Clipboard Set Data Error")); return FALSE; } } CloseClipboard(); m_OpenClipboardLock.Unlock(); return TRUE; } BOOL CMainFrame::GetClipboardText(CString &str) { // クリップボードチェインが動かない場合 if ( !m_bClipEnable ) SendMessage(WM_GETCLIPBOARD); if ( m_ClipBoard.IsEmpty() ) return FALSE; str = m_ClipBoard.GetHead(); return TRUE; } ///////////////////////////////////////////////////////////////////////////// static UINT VersionCheckThead(LPVOID pParam) { CMainFrame *pWnd = (CMainFrame *)pParam; pWnd->VersionCheckProc(); return 0; } void CMainFrame::VersionCheckProc() { CBuffer buf; CHttpSession http; CHAR *p, *e; CString str; CStringArray pam; CStringLoad version; ((CRLoginApp *)AfxGetApp())->GetVersion(version); str = AfxGetApp()->GetProfileString(_T("MainFrame"), _T("VersionNumber"), _T("")); if ( version.CompareDigit(str) < 0 ) version = str; if ( !http.GetRequest(CStringLoad(IDS_VERSIONCHECKURL), buf) ) return; p = (CHAR *)buf.GetPtr(); e = p + buf.GetSize(); while ( p < e ) { str.Empty(); pam.RemoveAll(); for ( ; ; ) { if ( p >= e ) { pam.Add(str); break; } else if ( *p == '\n' ) { pam.Add(str); p++; break; } else if ( *p == '\r' ) { p++; } else if ( *p == '\t' || *p == ' ' ) { while ( *p == '\t' || *p == ' ' ) p++; pam.Add(str); str.Empty(); } else { str += *(p++); } } // 0 1 2 3 // RLogin 2.18.4 2015/05/20 http://nanno.dip.jp/softlib/ if ( pam.GetSize() >= 4 && pam[0].CompareNoCase(_T("RLogin")) == 0 && version.CompareDigit(pam[1]) < 0 ) { AfxGetApp()->WriteProfileString(_T("MainFrame"), _T("VersionNumber"), pam[1]); m_VersionMessage.Format(CStringLoad(IDS_NEWVERSIONCHECK), pam[1]); m_VersionPageUrl = pam[3]; PostMessage(WM_COMMAND, IDM_NEWVERSIONFOUND); break; } } } void CMainFrame::VersionCheck() { time_t now; int today, last; if ( !m_bVersionCheck ) return; time(&now); today = (int)(now / (24 * 60 * 60)); last = AfxGetApp()->GetProfileInt(_T("MainFrame"), _T("VersionCheck"), 0); if ( (last + 7) > today ) return; AfxGetApp()->WriteProfileInt(_T("MainFrame"), _T("VersionCheck"), today); AfxBeginThread(VersionCheckThead, this, THREAD_PRIORITY_LOWEST); } ///////////////////////////////////////////////////////////////////////////// // CMainFrame 診断 #ifdef _DEBUG void CMainFrame::AssertValid() const { CMDIFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CMDIFrameWnd::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CMainFrame メッセージ ハンドラ LRESULT CMainFrame::OnWinSockSelect(WPARAM wParam, LPARAM lParam) { int fs = WSAGETSELECTEVENT(lParam); CExtSocket *pSock = NULL; for ( int n = 0 ; n < m_SocketParam.GetSize() ; n += 2 ) { if ( m_SocketParam[n] == (void *)wParam ) { pSock = (CExtSocket *)(m_SocketParam[n + 1]); break; } } if ( pSock == NULL ) return TRUE; ASSERT(pSock->m_Type >= 0 && pSock->m_Type < 10 ); if ( (fs & FD_CLOSE) == 0 && WSAGETSELECTERROR(lParam) != 0 ) { pSock->OnError(WSAGETSELECTERROR(lParam)); return TRUE; } if ( (fs & FD_CONNECT) != 0 ) pSock->OnPreConnect(); if ( (fs & FD_ACCEPT) != 0 ) pSock->OnAccept((SOCKET)wParam); if ( (fs & FD_READ) != 0 ) pSock->OnReceive(0, TRUE); if ( (fs & FD_OOB) != 0 ) pSock->OnReceive(MSG_OOB, TRUE); if ( (fs & FD_WRITE) != 0 ) pSock->OnSend(); if ( (fs & FD_CLOSE) != 0 ) pSock->OnPreClose(); if ( (fs & FD_RECVEMPTY) != 0 ) pSock->OnRecvEmpty(); return TRUE; } LRESULT CMainFrame::OnGetHostAddr(WPARAM wParam, LPARAM lParam) { int n; CExtSocket *pSock; CString *pStr; struct hostent *hp; int mode; struct sockaddr_in in; int errcode = WSAGETASYNCERROR(lParam); int buflen = WSAGETASYNCBUFLEN(lParam); for ( n = 0 ; n < m_HostAddrParam.GetSize() ; n += 5 ) { mode = (int)(INT_PTR)(m_HostAddrParam[n + 4]); if ( (mode & 030) == 0 && m_HostAddrParam[n] == (void *)wParam ) { pSock = (CExtSocket *)m_HostAddrParam[n + 1]; pStr = (CString *)m_HostAddrParam[n + 2]; hp = (struct hostent *)m_HostAddrParam[n + 3]; if ( errcode == 0 ) { memset(&in, 0, sizeof(in)); in.sin_family = hp->h_addrtype; memcpy(&(in.sin_addr), hp->h_addr, (hp->h_length < sizeof(in.sin_addr) ? hp->h_length : sizeof(in.sin_addr))); pSock->GetHostName((struct sockaddr *)&in, sizeof(in), *pStr); } pSock->OnAsyncHostByName(mode, *pStr); m_HostAddrParam.RemoveAt(n, 5); delete pStr; delete hp; break; } else if ( (mode & 030) == 010 && m_HostAddrParam[n] == (void *)wParam ) { addrinfo_param *ap = (addrinfo_param *)wParam; ADDRINFOT *info = (ADDRINFOT *)lParam; pSock = (CExtSocket *)m_HostAddrParam[n + 1]; if ( ap->ret == 0 ) pSock->OnAsyncHostByName(mode, (LPCTSTR)info); else pSock->OnAsyncHostByName(mode & 003, ap->name); m_HostAddrParam.RemoveAt(n, 5); delete ap; break; } } return TRUE; } LRESULT CMainFrame::OnIConMsg(WPARAM wParam, LPARAM lParam) { switch(lParam) { case WM_LBUTTONDBLCLK: ShowWindow(SW_RESTORE); Shell_NotifyIcon(NIM_DELETE, &m_IconData); m_IconShow = FALSE; break; } return FALSE; } LRESULT CMainFrame::OnThreadMsg(WPARAM wParam, LPARAM lParam) { CSyncSock *pSp = (CSyncSock *)lParam; pSp->ThreadCommand((int)wParam); return TRUE; } LRESULT CMainFrame::OnAfterOpen(WPARAM wParam, LPARAM lParam) { int n; for ( n = 0 ; n < m_AfterIdParam.GetSize() ; n += 2 ) { if ( (INT_PTR)(m_AfterIdParam[n]) == (INT_PTR)(wParam) ) { CRLoginDoc *pDoc = (CRLoginDoc *)m_AfterIdParam[n + 1]; m_AfterIdParam.RemoveAt(n, 2); if ( !((CRLoginApp *)AfxGetApp())->CheckDocument(pDoc) ) break; if ( (int)lParam != 0 ) { pDoc->OnSocketError((int)lParam); } else { pDoc->SocketOpen(); CRLoginView *pView = (CRLoginView *)pDoc->GetAciveView(); if ( pView != NULL ) MDIActivate(pView->GetFrameWnd()); } break; } } return TRUE; } LRESULT CMainFrame::OnGetClipboard(WPARAM wParam, LPARAM lParam) { CString *pStr, tmp; if ( lParam != NULL ) pStr = (CString *)lParam; else if ( CopyClipboardData(tmp) ) pStr = &tmp; else return TRUE; POSITION pos = m_ClipBoard.GetHeadPosition(); while ( pos != NULL ) { if ( m_ClipBoard.GetAt(pos).Compare(TstrToUni(*pStr)) == 0 ) { m_ClipBoard.RemoveAt(pos); break; } m_ClipBoard.GetNext(pos); } m_ClipBoard.AddHead(*pStr); while ( m_ClipBoard.GetSize() > 10 ) m_ClipBoard.RemoveTail(); if ( lParam != NULL ) delete pStr; return TRUE; } LRESULT CMainFrame::OnDpiChanged(WPARAM wParam, LPARAM lParam) { // wParam // The HIWORD of the wParam contains the Y-axis value of the new dpi of the window. // The LOWORD of the wParam contains the X-axis value of the new DPI of the window. // // lParam // A pointer to a RECT structure that provides a suggested size and position of the // current window scaled for the new DPI. The expectation is that apps will reposition // and resize windows based on the suggestions provided by lParam when handling this message. m_ScreenDpiX = LOWORD(wParam); m_ScreenDpiY = HIWORD(wParam); TabBarFontCheck(); MoveWindow((RECT *)lParam, TRUE); return TRUE; } void CMainFrame::OnClose() { int count = 0; CWinApp *pApp = AfxGetApp(); POSITION pos = pApp->GetFirstDocTemplatePosition(); while ( pos != NULL ) { CDocTemplate *pDocTemp = pApp->GetNextDocTemplate(pos); POSITION dpos = pDocTemp->GetFirstDocPosition(); while ( dpos != NULL ) { CRLoginDoc *pDoc = (CRLoginDoc *)pDocTemp->GetNextDoc(dpos); if ( pDoc != NULL && pDoc->m_pSock != NULL && pDoc->m_pSock->m_bConnect ) count++; } } if ( count > 0 && AfxMessageBox(CStringLoad(IDS_FILECLOSEQES), MB_ICONQUESTION | MB_YESNO) != IDYES ) return; CMDIFrameWnd::OnClose(); } void CMainFrame::OnDestroy() { AfxGetApp()->WriteProfileInt(_T("MainFrame"), _T("ToolBarStyle"), m_wndToolBar.GetStyle()); AfxGetApp()->WriteProfileInt(_T("MainFrame"), _T("StatusBarStyle"), m_wndStatusBar.GetStyle()); //AfxGetApp()->WriteProfileInt(_T("MainFrame"), _T("TabBarShow"), m_bTabBarShow); //AfxGetApp()->WriteProfileInt(_T("MainFrame"), _T("LayeredWindow"), m_TransParValue); //AfxGetApp()->WriteProfileInt(_T("MainFrame"), _T("LayeredColor"), m_TransParColor); //AfxGetApp()->WriteProfileInt(_T("ChildFrame"), _T("VScroll"), m_ScrollBarFlag); //AfxGetApp()->WriteProfileInt(_T("MainFrame"), _T("VersionCheckFlag"), m_bVersionCheck); if ( !IsIconic() && !IsZoomed() ) { int n = GetExecCount(); CString sect; CRect rect; GetWindowRect(&rect); if ( n == 0 ) sect = _T("MainFrame"); else sect.Format(_T("SecondFrame%02d"), n); AfxGetApp()->WriteProfileInt(sect, _T("x"), rect.left); AfxGetApp()->WriteProfileInt(sect, _T("y"), rect.top); AfxGetApp()->WriteProfileInt(sect, _T("cx"), rect.Width()); AfxGetApp()->WriteProfileInt(sect, _T("cy"), rect.Height()); } if ( m_bClipChain ) { m_bClipChain = FALSE; ChangeClipboardChain(m_hNextClipWnd); } else if ( ExRemoveClipboardFormatListener != NULL ) ExRemoveClipboardFormatListener(m_hWnd); if ( m_TempPath.GetSize() > 0 ) { int n, er; CString msg; do { msg.Format(CStringLoad(IDS_TEMPFILEDELETEMSG), m_TempPath.GetSize()); for ( er = n = 0 ; n < m_TempPath.GetSize() ; n++ ) { if ( DeleteFile(m_TempPath[n]) ) { m_TempPath.RemoveAt(n); n--; } else if ( ++er < 3 ) { msg += _T("\n"); msg += m_TempPath[n]; } } } while ( er > 0 && MessageBox(msg, _T("Question"), MB_ICONQUESTION | MB_YESNO) == IDYES ); } CMDIFrameWnd::OnDestroy(); } void CMainFrame::OnEnterIdle(UINT nWhy, CWnd* pWho) { CMDIFrameWnd::OnEnterIdle(nWhy, pWho); //if ( nWhy == MSGF_MENU ) // ((CRLoginApp *)AfxGetApp())->OnIdle(-1); } void CMainFrame::OnTimer(UINT_PTR nIDEvent) { CTimerObject *tp; CMidiQue *mp; if ( nIDEvent == m_SleepTimer ) { if ( m_SleepStatus < m_SleepCount ) { m_SleepStatus += 5; } else if ( m_SleepStatus == m_SleepCount ) { m_SleepStatus++; m_SleepTimer = SetTimer(TIMERID_SLEEPMODE, 100, NULL); } else if ( m_SleepStatus < (m_SleepCount + 18) ) { m_SleepStatus++; SetTransPar(0, m_TransParValue * (m_SleepCount + 20 - m_SleepStatus) / 20, LWA_ALPHA); } else if ( m_SleepStatus == (m_SleepCount + 18) ) { m_SleepStatus++; KillTimer(nIDEvent); m_SleepTimer = 0; } } else if ( nIDEvent == m_MidiTimer ) { KillTimer(nIDEvent); m_MidiTimer = 0; if ( !m_MidiQue.IsEmpty() && (mp = m_MidiQue.RemoveHead()) != NULL ) { if ( m_hMidiOut != NULL ) midiOutShortMsg(m_hMidiOut, mp->m_Msg); delete mp; } while ( !m_MidiQue.IsEmpty() && (mp = m_MidiQue.GetHead()) != NULL && mp->m_mSec == 0 ) { if ( m_hMidiOut != NULL ) midiOutShortMsg(m_hMidiOut, mp->m_Msg); m_MidiQue.RemoveHead(); delete mp; } if ( !m_MidiQue.IsEmpty() && (mp = m_MidiQue.GetHead()) != NULL ) m_MidiTimer = SetTimer(TIMERID_MIDIEVENT, mp->m_mSec, NULL); } else if ( nIDEvent == m_StatusTimer ) { KillTimer(m_StatusTimer); m_StatusTimer = 0; SetMessageText(AFX_IDS_IDLEMESSAGE); } else if ( nIDEvent == TIMERID_CLIPUPDATE ) { if ( m_bClipChain ) { ChangeClipboardChain(m_hNextClipWnd); m_hNextClipWnd = SetClipboardViewer(); } else { KillTimer(nIDEvent); m_ClipTimer = 0; } } else if ( nIDEvent == TIMERID_IDLETIMER ) { // 最大20回、200ms以下に制限 int n; clock_t st = clock() + 180; for ( n = 0 ; n < 20 && st > clock() ; n++ ) { if ( !((CRLoginApp *)AfxGetApp())->OnIdle((LONG)(-1)) ) break; } //TRACE("TimerIdle %d(%d)\n", n, clock() - st + 180); } else { for ( tp = m_pTimerUsedId ; tp != NULL ; tp = tp->m_pList ) { if ( tp->m_Id == (int)nIDEvent ) { if ( (tp->m_Mode & 030) == 000 ) { RemoveTimerEvent(tp); tp->CallObject(); FreeTimerEvent(tp); } else tp->CallObject(); break; } } if ( tp == NULL ) KillTimer(nIDEvent); } CMDIFrameWnd::OnTimer(nIDEvent); } void CMainFrame::RecalcLayout(BOOL bNotify) { CMDIFrameWnd::RecalcLayout(bNotify); RepositionBars(0, 0xffff, AFX_IDW_PANE_FIRST, reposQuery, &m_Frame); if ( m_pTopPane == NULL ) return; CRect rect; GetFrameRect(rect); m_pTopPane->MoveParOwn(rect, PANEFRAME_NOCHNG); } void CMainFrame::SplitWidthPane() { if ( m_pTopPane == NULL ) m_pTopPane = new CPaneFrame(this, NULL, NULL); CPaneFrame *pPane = m_pTopPane->GetActive(); if ( pPane->m_pOwn == NULL || pPane->m_pOwn->m_Style != PANEFRAME_MAXIM ) pPane->CreatePane(PANEFRAME_WIDTH, NULL); else { while ( pPane->m_pOwn != NULL && pPane->m_pOwn->m_Style == PANEFRAME_MAXIM ) pPane = pPane->m_pOwn; pPane = pPane->InsertPane(); if ( pPane->m_pOwn == NULL ) m_pTopPane = pPane; pPane->MoveParOwn(pPane->m_Frame, PANEFRAME_WIDTH); } } void CMainFrame::SplitHeightPane() { if ( m_pTopPane == NULL ) m_pTopPane = new CPaneFrame(this, NULL, NULL); CPaneFrame *pPane = m_pTopPane->GetActive(); if ( pPane->m_pOwn == NULL || pPane->m_pOwn->m_Style != PANEFRAME_MAXIM ) pPane->CreatePane(PANEFRAME_HEIGHT, NULL); else { while ( pPane->m_pOwn != NULL && pPane->m_pOwn->m_Style == PANEFRAME_MAXIM ) pPane = pPane->m_pOwn; pPane = pPane->InsertPane(); if ( pPane->m_pOwn == NULL ) m_pTopPane = pPane; pPane->MoveParOwn(pPane->m_Frame, PANEFRAME_HEIGHT); } } CPaneFrame *CMainFrame::GetPaneFromChild(HWND hWnd) { if ( m_pTopPane == NULL ) return NULL; return m_pTopPane->GetPane(hWnd); } void CMainFrame::OnPaneWsplit() { if ( m_pTopPane == NULL ) m_pTopPane = new CPaneFrame(this, NULL, NULL); CPaneFrame *pPane = m_pTopPane->GetActive(); if ( pPane->m_pOwn == NULL || pPane->m_pOwn->m_Style != PANEFRAME_MAXIM ) pPane->CreatePane(PANEFRAME_WIDTH, NULL); else { while ( pPane->m_pOwn != NULL && pPane->m_pOwn->m_Style == PANEFRAME_MAXIM ) pPane = pPane->m_pOwn; pPane->MoveParOwn(pPane->m_Frame, PANEFRAME_WIDTH); } } void CMainFrame::OnPaneHsplit() { if ( m_pTopPane == NULL ) m_pTopPane = new CPaneFrame(this, NULL, NULL); CPaneFrame *pPane = m_pTopPane->GetActive(); if ( pPane->m_pOwn == NULL || pPane->m_pOwn->m_Style != PANEFRAME_MAXIM ) pPane->CreatePane(PANEFRAME_HEIGHT, NULL); else { while ( pPane->m_pOwn != NULL && pPane->m_pOwn->m_Style == PANEFRAME_MAXIM ) pPane = pPane->m_pOwn; pPane->MoveParOwn(pPane->m_Frame, PANEFRAME_HEIGHT); } } void CMainFrame::OnPaneDelete() { if ( m_pTopPane == NULL ) return; CPaneFrame *pPane, *pOwner; if ( (pPane = m_pTopPane->GetActive()) == NULL ) return; if ( pPane->m_Style == PANEFRAME_WINDOW && pPane->m_hWnd == NULL && (pOwner = pPane->m_pOwn) != NULL ) { pPane->m_pLeft = pPane->m_pRight = NULL; delete pPane; pPane = (pOwner->m_pLeft == pPane ? pOwner->m_pRight : pOwner->m_pLeft); pOwner->m_Style = pPane->m_Style; pOwner->m_pLeft = pPane->m_pLeft; pOwner->m_pRight = pPane->m_pRight; pOwner->m_hWnd = pPane->m_hWnd; if ( pOwner->m_pServerEntry != NULL ) delete pOwner->m_pServerEntry; pOwner->m_pServerEntry = pPane->m_pServerEntry; pPane->m_pServerEntry = NULL; if ( pOwner->m_pLeft != NULL ) pOwner->m_pLeft->m_pOwn = pOwner; if ( pOwner->m_pRight != NULL ) pOwner->m_pRight->m_pOwn = pOwner; pPane->m_pLeft = pPane->m_pRight = NULL; delete pPane; pOwner->MoveParOwn(pOwner->m_Frame, PANEFRAME_NOCHNG); return; } for ( pOwner = pPane->m_pOwn ; pOwner != NULL ; pOwner = pOwner->m_pOwn ) { if ( pOwner->m_pLeft != NULL && pOwner->m_pLeft->m_hWnd == NULL && pOwner->m_pLeft->m_pLeft == NULL ) pOwner->DeletePane(NULL); if ( pOwner->m_pRight != NULL && pOwner->m_pRight->m_hWnd == NULL && pOwner->m_pRight->m_pLeft == NULL ) pOwner->DeletePane(NULL); if ( pOwner->m_Style != PANEFRAME_MAXIM ) { pOwner->MoveParOwn(pOwner->m_Frame, PANEFRAME_MAXIM); break; } } } void CMainFrame::OnPaneSave() { if ( m_pTopPane == NULL ) return; CBuffer buf; m_pTopPane->SetBuffer(&buf, FALSE); ((CRLoginApp *)AfxGetApp())->WriteProfileBinary(_T("MainFrame"), _T("Pane"), buf.GetPtr(), buf.GetSize()); } void CMainFrame::OnWindowCascade() { while ( m_pTopPane != NULL && m_pTopPane->GetPane(NULL) != NULL ) m_pTopPane = m_pTopPane->DeletePane(NULL); if ( m_pTopPane == NULL ) return; CRect rect; GetFrameRect(rect); m_pTopPane->MoveParOwn(rect, PANEFRAME_MAXIM); } void CMainFrame::OnWindowTileHorz() { while ( m_pTopPane != NULL && m_pTopPane->GetPane(NULL) != NULL ) m_pTopPane = m_pTopPane->DeletePane(NULL); if ( m_pTopPane == NULL ) return; CRect rect; GetFrameRect(rect); m_pTopPane->MoveParOwn(rect, m_SplitType); switch(m_SplitType) { case PANEFRAME_WSPLIT: m_SplitType = PANEFRAME_HSPLIT; break; case PANEFRAME_HSPLIT: m_SplitType = PANEFRAME_WEVEN; break; case PANEFRAME_WEVEN: m_SplitType = PANEFRAME_HEVEN; break; case PANEFRAME_HEVEN: m_SplitType = PANEFRAME_WSPLIT; break; } } void CMainFrame::OnWindowRotation() { int n, idx; HWND hWnd; CWnd *pWnd; CPaneFrame *pPane, *pNext; CRLoginDoc *pDoc; if ( m_pTopPane == NULL ) return; if ( (pWnd = MDIGetActive()) == NULL ) return; if ( (idx = m_wndTabBar.GetIndex(pWnd)) < 0 ) return; if ( (pPane = m_pTopPane->GetPane(pWnd->GetSafeHwnd())) == NULL ) return; for ( n = 1 ; n < m_wndTabBar.GetSize() ; n++ ) { if ( ++idx >= m_wndTabBar.GetSize() ) idx = 0; if ( (pWnd = m_wndTabBar.GetAt(idx)) == NULL ) break; if ( (pNext = m_pTopPane->GetPane(pWnd->GetSafeHwnd())) == NULL ) break; hWnd = pPane->m_hWnd; pPane->m_hWnd = pNext->m_hWnd; pNext->m_hWnd = hWnd; pPane->MoveFrame(); pPane = pNext; } pPane->MoveFrame(); if ( (pDoc = GetMDIActiveDocument()) != NULL && pDoc->m_TextRam.IsOptEnable(TO_RLPAINWTAB) ) m_wndTabBar.NextActive(); PostMessage(WM_COMMAND, IDM_DISPWINIDX); } void CMainFrame::OnUpdateWindowCascade(CCmdUI* pCmdUI) { pCmdUI->Enable(m_pTopPane != NULL && m_pTopPane->m_Style != PANEFRAME_WINDOW ? TRUE : FALSE); } void CMainFrame::OnUpdateWindowTileHorz(CCmdUI* pCmdUI) { pCmdUI->Enable(m_pTopPane != NULL && m_pTopPane->m_Style != PANEFRAME_WINDOW ? TRUE : FALSE); } void CMainFrame::OnUpdateWindowRotation(CCmdUI *pCmdUI) { pCmdUI->Enable(m_pTopPane != NULL && m_pTopPane->m_Style != PANEFRAME_WINDOW ? TRUE : FALSE); } BOOL CMainFrame::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { CPoint point; CPaneFrame *pPane; GetCursorPos(&point); ScreenToClient(&point); point.y -= m_Frame.top; if ( m_pTopPane != NULL && (pPane = m_pTopPane->HitTest(point)) != NULL && pPane->m_Style != PANEFRAME_WINDOW ) { LPCTSTR id = (pPane->m_Style == PANEFRAME_HEIGHT ? ATL_MAKEINTRESOURCE(AFX_IDC_VSPLITBAR) : ATL_MAKEINTRESOURCE(AFX_IDC_HSPLITBAR)); HINSTANCE hInst = AfxFindResourceHandle(id, ATL_RT_GROUP_CURSOR); HCURSOR hCursor = NULL; if ( hInst != NULL ) hCursor = ::LoadCursorW(hInst, id); if ( hCursor == NULL ) hCursor = AfxGetApp()->LoadStandardCursor(pPane->m_Style == PANEFRAME_HEIGHT ? IDC_SIZENS : IDC_SIZEWE); if ( hCursor != NULL ) ::SetCursor(hCursor); return TRUE; } return CMDIFrameWnd::OnSetCursor(pWnd, nHitTest, message); } BOOL CMainFrame::PreTranslateMessage(MSG* pMsg) { if ( pMsg->message == WM_LBUTTONDOWN ) { CPoint point(LOWORD(pMsg->lParam), HIWORD(pMsg->lParam)); ::ClientToScreen(pMsg->hwnd, &point); ScreenToClient(&point); if ( PreLButtonDown((UINT)pMsg->wParam, point) ) return TRUE; } else if ( (pMsg->message == WM_KEYDOWN || pMsg->message == WM_SYSKEYDOWN) ) { if ( MDIGetActive() == NULL ) { int id, st = 0; CBuffer tmp; if ( (GetKeyState(VK_SHIFT) & 0x80) != 0 ) st |= MASK_SHIFT; if ( (GetKeyState(VK_CONTROL) & 0x80) != 0 ) st |= MASK_CTRL; if ( (GetKeyState(VK_MENU) & 0x80) != 0 ) st |= MASK_ALT; if ( m_DefKeyTab.FindMaps((int)pMsg->wParam, st, &tmp) && (id = CKeyNodeTab::GetCmdsKey((LPCWSTR)tmp)) > 0 ) { PostMessage(WM_COMMAND, (WPARAM)id); return TRUE; } } if ( (pMsg->wParam == VK_TAB || pMsg->wParam == VK_F6) && (GetKeyState(VK_CONTROL) & 0x80) != 0 ) return TRUE; } return CMDIFrameWnd::PreTranslateMessage(pMsg); } void CMainFrame::OffsetTrack(CPoint point) { CRect rect = m_pTrackPane->m_Frame; AdjustRect(rect); point.y -= m_Frame.top; if ( m_pTrackPane->m_Style == PANEFRAME_WIDTH ) { m_TrackRect += CPoint(point.x - m_TrackPoint.x, 0); int w = m_TrackRect.Width(); if ( m_TrackRect.left < (rect.left + PANEMIN_WIDTH) ) { m_TrackRect.left = rect.left + PANEMIN_WIDTH; m_TrackRect.right = m_TrackRect.left + w; } else if ( m_TrackRect.right > (rect.right - PANEMIN_WIDTH) ) { m_TrackRect.right = rect.right - PANEMIN_WIDTH; m_TrackRect.left = m_TrackRect.right - w; } } else { m_TrackRect += CPoint(0, point.y - m_TrackPoint.y); int h = m_TrackRect.Height(); if ( m_TrackRect.top < (rect.top + PANEMIN_HEIGHT) ) { m_TrackRect.top = rect.top + PANEMIN_HEIGHT; m_TrackRect.bottom = m_TrackRect.top + h; } else if ( m_TrackRect.bottom > (rect.bottom - PANEMIN_HEIGHT) ) { m_TrackRect.bottom = rect.bottom - PANEMIN_HEIGHT; m_TrackRect.top = m_TrackRect.bottom - h; } } m_TrackPoint = point; } void CMainFrame::InvertTracker(CRect &rect) { CDC* pDC = GetDC(); CBrush* pBrush = CDC::GetHalftoneBrush(); HBRUSH hOldBrush = NULL; if (pBrush != NULL) hOldBrush = (HBRUSH)SelectObject(pDC->m_hDC, pBrush->m_hObject); pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT); if (hOldBrush != NULL) SelectObject(pDC->m_hDC, hOldBrush); ReleaseDC(pDC); } int CMainFrame::PreLButtonDown(UINT nFlags, CPoint point) { CPaneFrame *pPane; point.y -= m_Frame.top; if ( m_pTrackPane != NULL || m_pTopPane == NULL ) return FALSE; if ( (pPane = m_pTopPane->HitTest(point)) == NULL ) return FALSE; if ( pPane->m_Style == PANEFRAME_WINDOW ) { m_pTopPane->HitActive(point); return FALSE; } SetCapture(); m_pTrackPane = pPane; m_pTrackPane->BoderRect(m_TrackRect); InvertTracker(m_TrackRect); m_TrackPoint = point; return TRUE; } void CMainFrame::OnLButtonUp(UINT nFlags, CPoint point) { CMDIFrameWnd::OnLButtonUp(nFlags, point); if ( m_pTrackPane == NULL ) return; InvertTracker(m_TrackRect); OffsetTrack(point); ReleaseCapture(); m_TrackRect.top -= m_Frame.top; m_TrackRect.bottom -= m_Frame.top; if ( m_pTrackPane->m_Style == PANEFRAME_WIDTH ) { m_pTrackPane->m_pLeft->m_Frame.right = m_TrackRect.left + 1; m_pTrackPane->m_pRight->m_Frame.left = m_TrackRect.right - 1; } else { m_pTrackPane->m_pLeft->m_Frame.bottom = m_TrackRect.top + 1; m_pTrackPane->m_pRight->m_Frame.top = m_TrackRect.bottom - 1; } m_pTrackPane->MoveParOwn(m_pTrackPane->m_Frame, PANEFRAME_NOCHNG); m_pTrackPane = NULL; } void CMainFrame::OnMouseMove(UINT nFlags, CPoint point) { CMDIFrameWnd::OnMouseMove(nFlags, point); if ( m_pTrackPane == NULL ) return; InvertTracker(m_TrackRect); OffsetTrack(point); InvertTracker(m_TrackRect); } void CMainFrame::OnUpdateIndicatorSock(CCmdUI* pCmdUI) { int n = 6; CRLoginDoc *pDoc; static LPCTSTR ProtoName[] = { _T("TCP"), _T("Login"), _T("Telnet"), _T("SSH"), _T("COM"), _T("PIPE"), _T("") }; if ( (pDoc = GetMDIActiveDocument()) != NULL && pDoc->m_pSock != NULL ) n = pDoc->m_pSock->m_Type; pCmdUI->SetText(ProtoName[n]); // m_wndStatusBar.GetStatusBarCtrl().SetIcon(pCmdUI->m_nIndex, AfxGetApp()->LoadIcon(IDI_LOCKICON)); } void CMainFrame::OnUpdateIndicatorStat(CCmdUI* pCmdUI) { LPCTSTR str = _T(""); CRLoginDoc *pDoc; if ( (pDoc = GetMDIActiveDocument()) != NULL && pDoc->m_pSock != NULL ) str = pDoc->m_SockStatus; pCmdUI->SetText(str); } void CMainFrame::OnUpdateIndicatorKmod(CCmdUI* pCmdUI) { CRLoginDoc *pDoc; CString str; if ( (pDoc = GetMDIActiveDocument()) != NULL && pDoc->m_pSock != NULL ) { str += ( pDoc->m_TextRam.IsOptEnable(TO_RLPNAM) ? _T('A') : _T(' ')); str += ( pDoc->m_TextRam.IsOptEnable(TO_DECCKM) ? _T('C') : _T(' ')); str += (!pDoc->m_TextRam.IsOptEnable(TO_DECANM) ? _T('V') : _T(' ')); } pCmdUI->SetText(str); } void CMainFrame::OnFileAllSave() { if ( m_pTopPane == NULL || MDIGetActive(NULL) == NULL ) return; CFile file; CBuffer buf; CFileDialog dlg(FALSE, _T("rlg"), m_AllFilePath, OFN_OVERWRITEPROMPT, CStringLoad(IDS_FILEDLGRLOGIN), this); if ( dlg.DoModal() != IDOK ) return; m_pTopPane->SetBuffer(&buf); if ( !file.Open(dlg.GetPathName(), CFile::modeCreate | CFile::modeWrite) ) return; file.Write("RLM100\n", 7); file.Write(buf.GetPtr(), buf.GetSize()); file.Close(); } void CMainFrame::OnFileAllLoad() { CPaneFrame *pPane; if ( IsConnectChild(m_pTopPane) ) { if ( MessageBox(CStringLoad(IDE_ALLCLOSEREQ), _T("Warning"), MB_ICONQUESTION | MB_OKCANCEL) != IDOK ) return; } try { if ( (pPane = CPaneFrame::GetBuffer(this, NULL, NULL, &m_AllFileBuf)) == NULL ) return; } catch(...) { ::AfxMessageBox(_T("File All Load Error")); return; } AfxGetApp()->CloseAllDocuments(FALSE); if ( m_pTopPane != NULL ) delete m_pTopPane; m_pTopPane = pPane; if ( m_pTopPane->GetEntry() != NULL ) { m_LastPaneFlag = TRUE; AfxGetApp()->AddToRecentFileList(m_AllFilePath); PostMessage(WM_COMMAND, ID_FILE_NEW, 0); } } BOOL CMainFrame::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct) { if ( pCopyDataStruct->dwData == 0x524c4f31 ) { return ((CRLoginApp *)::AfxGetApp())->OnInUseCheck(pCopyDataStruct); } else if ( pCopyDataStruct->dwData == 0x524c4f32 ) { return ((CRLoginApp *)::AfxGetApp())->OnIsOnlineEntry(pCopyDataStruct); #ifdef USE_KEYMACGLOBAL } else if ( pCopyDataStruct->dwData == 0x524c4f33 ) { ((CRLoginApp *)::AfxGetApp())->OnUpdateKeyMac(pCopyDataStruct); return TRUE; #endif } else if ( pCopyDataStruct->dwData == 0x524c4f34 ) { if ( m_bBroadCast ) ((CRLoginApp *)::AfxGetApp())->OnSendBroadCast(pCopyDataStruct); return TRUE; } else if ( pCopyDataStruct->dwData == 0x524c4f35 ) { ((CRLoginApp *)::AfxGetApp())->OnSendBroadCastMouseWheel(pCopyDataStruct); return TRUE; } else if ( pCopyDataStruct->dwData == 0x524c4f36 ) { if ( m_bBroadCast ) ((CRLoginApp *)::AfxGetApp())->OnSendGroupCast(pCopyDataStruct); return TRUE; } else if ( pCopyDataStruct->dwData == 0x524c4f37 ) { return ((CRLoginApp *)::AfxGetApp())->OnEntryData(pCopyDataStruct); } else if ( pCopyDataStruct->dwData == 0x524c4f38 ) { return ((CRLoginApp *)::AfxGetApp())->OnIsOpenRLogin(pCopyDataStruct); } return CMDIFrameWnd::OnCopyData(pWnd, pCopyDataStruct); } void CMainFrame::InitMenuBitmap() { int n, cx, cy; CDC dc[2]; CBitmap BitMap; CBitmap *pOld[2]; CBitmap *pBitmap; BITMAP mapinfo; CMenuBitMap *pMap; // リソースデータベースからメニューイメージを作成 cx = GetSystemMetrics(SM_CXMENUCHECK); cy = GetSystemMetrics(SM_CYMENUCHECK); dc[0].CreateCompatibleDC(NULL); dc[1].CreateCompatibleDC(NULL); CResDataBase *pResData = &(((CRLoginApp *)::AfxGetApp())->m_ResDataBase); // Add Menu Image From Bitmap Resource for ( n = 0 ; n < 3 ; n++ ) pResData->AddBitmap(MAKEINTRESOURCE(IDB_MENUMAP1 + n)); // MenuMap RemoveAll for ( int n = 0 ; n < m_MenuMap.GetSize() ; n++ ) { if ( (pMap = (CMenuBitMap *)m_MenuMap[n]) == NULL ) continue; pMap->m_Bitmap.DeleteObject(); delete pMap; } m_MenuMap.RemoveAll(); for ( n = 0 ; n < pResData->m_Bitmap.GetSize() ; n++ ) { if ( pResData->m_Bitmap[n].m_hBitmap == NULL ) continue; pBitmap = CBitmap::FromHandle(pResData->m_Bitmap[n].m_hBitmap); if ( pBitmap == NULL || !pBitmap->GetBitmap(&mapinfo) ) continue; if ( (pMap = new CMenuBitMap) == NULL ) continue; pMap->m_Id = pResData->m_Bitmap[n].m_ResId; pMap->m_Bitmap.CreateBitmap(cx, cy, dc[1].GetDeviceCaps(PLANES), dc[1].GetDeviceCaps(BITSPIXEL), NULL); m_MenuMap.Add(pMap); pOld[0] = dc[0].SelectObject(pBitmap); pOld[1] = dc[1].SelectObject(&(pMap->m_Bitmap)); dc[1].FillSolidRect(0, 0, cx, cy, GetSysColor(COLOR_MENU)); dc[1].TransparentBlt(0, 0, cx, cy, &(dc[0]), 0, 0, (mapinfo.bmWidth <= mapinfo.bmHeight ? mapinfo.bmWidth : mapinfo.bmHeight), mapinfo.bmHeight, RGB(192, 192, 192)); dc[0].SelectObject(pOld[0]); dc[1].SelectObject(pOld[1]); } dc[0].DeleteDC(); dc[1].DeleteDC(); } void CMainFrame::SetMenuBitmap(CMenu *pMenu) { int n; CMenuBitMap *pMap; for ( n = 0 ; n < m_MenuMap.GetSize() ; n++ ) { if ( (pMap = (CMenuBitMap *)m_MenuMap[n]) != NULL ) pMenu->SetMenuItemBitmaps(pMap->m_Id, MF_BYCOMMAND, &(pMap->m_Bitmap), NULL); } } CBitmap *CMainFrame::GetMenuBitmap(UINT nId) { int n; CMenuBitMap *pMap; for ( n = 0 ; n < m_MenuMap.GetSize() ; n++ ) { if ( (pMap = (CMenuBitMap *)m_MenuMap[n]) != NULL && pMap->m_Id == nId ) return &(pMap->m_Bitmap); } return NULL; } void CMainFrame::OnEnterMenuLoop(BOOL bIsTrackPopupMenu) { int n, a; CMenu *pMenu, *pSubMenu; CRLoginDoc *pDoc; CString str; SetIdleTimer(TRUE); if ( (pMenu = GetMenu()) == NULL ) return; if ( (pDoc = GetMDIActiveDocument()) != NULL ) pDoc->SetMenu(pMenu); else { m_DefKeyTab.CmdsInit(); for ( n = 0 ; n < m_DefKeyTab.m_Cmds.GetSize() ; n++ ) { if ( pMenu->GetMenuString(m_DefKeyTab.m_Cmds[n].m_Id, str, MF_BYCOMMAND) <= 0 ) continue; if ( (a = str.Find(_T('\t'))) >= 0 ) str.Truncate(a); m_DefKeyTab.m_Cmds[n].m_Text = str; m_DefKeyTab.m_Cmds[n].SetMenu(pMenu); } } // Add Old ServerEntryTab Delete Menu if ( (pSubMenu = CMenuLoad::GetItemSubMenu(IDM_PASSWORDLOCK, pMenu)) != NULL ) { pSubMenu->DeleteMenu(IDM_DELOLDENTRYTAB, MF_BYCOMMAND); if ( ((CRLoginApp *)AfxGetApp())->AliveProfileKeys(_T("ServerEntryTab")) ) pSubMenu->AppendMenu(MF_STRING, IDM_DELOLDENTRYTAB, CStringLoad(IDS_DELOLDENTRYMENU)); } SetMenuBitmap(pMenu); } void CMainFrame::OnExitMenuLoop(BOOL bIsTrackPopupMenu) { SetIdleTimer(FALSE); } void CMainFrame::OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized) { CMDIFrameWnd::OnActivate(nState, pWndOther, bMinimized); if ( nState == WA_INACTIVE ) m_wndTabBar.SetGhostWnd(FALSE); } void CMainFrame::OnViewScrollbar() { CWinApp *pApp; if ( (pApp = AfxGetApp()) == NULL ) return; m_ScrollBarFlag = (m_ScrollBarFlag ? FALSE : TRUE); POSITION pos = pApp->GetFirstDocTemplatePosition(); while ( pos != NULL ) { CDocTemplate *pDocTemp = pApp->GetNextDocTemplate(pos); POSITION dpos = pDocTemp->GetFirstDocPosition(); while ( dpos != NULL ) { CRLoginDoc *pDoc = (CRLoginDoc *)pDocTemp->GetNextDoc(dpos); POSITION vpos = pDoc->GetFirstViewPosition(); while ( vpos != NULL ) { CRLoginView *pView = (CRLoginView *)pDoc->GetNextView(vpos); if ( pView != NULL ) { CChildFrame *pChild = pView->GetFrameWnd(); if ( pChild != NULL ) pChild->SetScrollBar(m_ScrollBarFlag); } } } } pApp->WriteProfileInt(_T("ChildFrame"), _T("VScroll"), m_ScrollBarFlag); } void CMainFrame::OnUpdateViewScrollbar(CCmdUI *pCmdUI) { pCmdUI->SetCheck(m_ScrollBarFlag); } void CMainFrame::OnViewMenubar() { CWinApp *pApp; BOOL bMenu; CChildFrame *pChild = (CChildFrame *)MDIGetActive(); if ( (pApp = AfxGetApp()) == NULL ) return; bMenu = (pApp->GetProfileInt(_T("ChildFrame"), _T("VMenu"), TRUE) ? FALSE : TRUE); pApp->WriteProfileInt(_T("ChildFrame"), _T("VMenu"), bMenu); if ( pChild != NULL ) { if ( bMenu ) { pChild->OnUpdateFrameMenu(TRUE, pChild, NULL); SetMenu(GetMenu()); } else SetMenu(NULL); } } void CMainFrame::OnUpdateViewMenubar(CCmdUI *pCmdUI) { pCmdUI->SetCheck(GetMenu() != NULL ? TRUE : FALSE); } void CMainFrame::OnSysCommand(UINT nID, LPARAM lParam) { switch(nID) { case ID_VIEW_MENUBAR: OnViewMenubar(); break; default: CMDIFrameWnd::OnSysCommand(nID, lParam); break; } } void CMainFrame::OnViewTabbar() { CWinApp *pApp = AfxGetApp(); m_bTabBarShow = (m_bTabBarShow? FALSE : TRUE); pApp->WriteProfileInt(_T("MainFrame"), _T("TabBarShow"), m_bTabBarShow); if ( m_bTabBarShow ) ShowControlBar(&m_wndTabBar, m_bTabBarShow, 0); else if ( m_wndTabBar.m_TabCtrl.GetItemCount() <= 1 ) ShowControlBar(&m_wndTabBar, m_bTabBarShow, 0); } void CMainFrame::OnUpdateViewTabbar(CCmdUI *pCmdUI) { pCmdUI->SetCheck(m_bTabBarShow); } void CMainFrame::OnNewVersionFound() { if ( MessageBox(m_VersionMessage, _T("New Version"), MB_ICONQUESTION | MB_YESNO) == IDYES ) ShellExecute(m_hWnd, NULL, m_VersionPageUrl, NULL, NULL, SW_NORMAL); } void CMainFrame::OnVersioncheck() { m_bVersionCheck = (m_bVersionCheck ? FALSE : TRUE); AfxGetApp()->WriteProfileInt(_T("MainFrame"), _T("VersionCheckFlag"), m_bVersionCheck); AfxGetApp()->WriteProfileString(_T("MainFrame"), _T("VersionNumber"), _T("")); if ( m_bVersionCheck ) VersionCheckProc(); } void CMainFrame::OnUpdateVersioncheck(CCmdUI *pCmdUI) { pCmdUI->SetCheck(m_bVersionCheck); } void CMainFrame::OnWinodwNext() { if ( m_wndTabBar.GetSize() <= 1 ) return; m_wndTabBar.NextActive(); } void CMainFrame::OnUpdateWinodwNext(CCmdUI *pCmdUI) { pCmdUI->Enable(m_wndTabBar.GetSize() > 1 ? TRUE : FALSE); } void CMainFrame::OnWindowPrev() { if ( m_wndTabBar.GetSize() <= 1 ) return; m_wndTabBar.PrevActive(); } void CMainFrame::OnUpdateWindowPrev(CCmdUI *pCmdUI) { pCmdUI->Enable(m_wndTabBar.GetSize() > 1 ? TRUE : FALSE); } void CMainFrame::OnWinodwSelect(UINT nID) { m_wndTabBar.SelectActive(nID - AFX_IDM_FIRST_MDICHILD); } void CMainFrame::OnActiveMove(UINT nID) { CWnd *pTemp; CPaneFrame *pActive; CChildFrame *pWnd; CPaneFrame *pPane = NULL; if ( m_pTopPane == NULL || (pTemp = MDIGetActive(NULL)) == NULL || (pActive = m_pTopPane->GetPane(pTemp->m_hWnd)) == NULL ) return; m_pTopPane->GetNextPane(nID - IDM_MOVEPANE_UP, pActive, &pPane); if ( pPane != NULL && (pWnd = (CChildFrame *)CWnd::FromHandle(pPane->m_hWnd)) != NULL ) pWnd->MDIActivate(); } void CMainFrame::OnUpdateActiveMove(CCmdUI *pCmdUI) { CWnd *pTemp; CPaneFrame *pActive; CPaneFrame *pPane = NULL; if ( m_pTopPane == NULL || m_wndTabBar.GetSize() <= 1 || (pTemp = MDIGetActive(NULL)) == NULL || (pActive = m_pTopPane->GetPane(pTemp->m_hWnd)) == NULL ) pCmdUI->Enable(FALSE); else { m_pTopPane->GetNextPane(pCmdUI->m_nID - IDM_MOVEPANE_UP, pActive, &pPane); pCmdUI->Enable(pPane != NULL ? TRUE : FALSE); } } void CMainFrame::OnBroadcast() { m_bBroadCast = (m_bBroadCast ? FALSE : TRUE); } void CMainFrame::OnUpdateBroadcast(CCmdUI *pCmdUI) { pCmdUI->SetCheck(m_bBroadCast); } void CMainFrame::OnDrawClipboard() { CMDIFrameWnd::OnDrawClipboard(); if ( m_hNextClipWnd && m_hNextClipWnd != m_hWnd ) ::SendMessage(m_hNextClipWnd, WM_DRAWCLIPBOARD, NULL, NULL); m_bClipEnable = TRUE; // クリップボードチェインが有効? if ( m_bClipThreadCount < CLIPOPENTHREADMAX ) { m_bClipThreadCount++; AfxBeginThread(CopyClipboardThead, this, THREAD_PRIORITY_NORMAL); } } void CMainFrame::OnChangeCbChain(HWND hWndRemove, HWND hWndAfter) { CMDIFrameWnd::OnChangeCbChain(hWndRemove, hWndAfter); if ( hWndRemove == m_hNextClipWnd ) m_hNextClipWnd = hWndAfter; else if ( m_hNextClipWnd && m_hNextClipWnd != m_hWnd ) ::SendMessage(m_hNextClipWnd, WM_CHANGECBCHAIN, (WPARAM)hWndRemove, (LPARAM)hWndAfter); } void CMainFrame::OnClipboardUpdate() { m_bClipEnable = TRUE; // クリップボードチェインが有効? // 本来ならここでOpenClipboardなどのクリップボードにアクセスすれば良いと思うのだが // リモートディスクトップをRLogin上のポートフォワードで実行するとGetClipboardDataで // デッドロックが起こってしまう。 // その対応で別スレッドでクリップボードのアクセスを行っているがExcel2010などでクリ // ップボードのコピーを多数行った場合などにこのOnClipboardUpdateがかなりの頻度で送 // られるようになりスレッドが重複して起動する // OpenClipboardでは、同じウィンドウでのオープンをブロックしないようで妙な動作が確 // 認できた(Open->Open->Close->Closeで先のCloseで解放され、後のCloseは無視される) // GlobalLockしているメモリハンドルがUnlock前に解放される症状が出た // メインウィンドウでのアクセスはCMutexLockをOpenClipbardの前に行うよう // にした。別スレッドのクリップボードアクセスは、問題が多いと思う // かなりややこしい動作なのでここにメモを残す if ( m_bClipThreadCount < CLIPOPENTHREADMAX ) { m_bClipThreadCount++; AfxBeginThread(CopyClipboardThead, this, THREAD_PRIORITY_NORMAL); } } void CMainFrame::OnToolcust() { CToolDlg dlg; if ( dlg.DoModal() != IDOK ) return; ((CRLoginApp *)::AfxGetApp())->LoadResToolBar(MAKEINTRESOURCE(IDR_MAINFRAME), m_wndToolBar); // ツールバーの再表示 RecalcLayout(FALSE); } void CMainFrame::OnClipchain() { if ( m_bAllowClipChain ) { // Do Disable m_bAllowClipChain = FALSE; if ( m_bClipChain == FALSE ) { if ( ExRemoveClipboardFormatListener != NULL ) ExRemoveClipboardFormatListener(m_hWnd); } else { if ( m_ClipTimer != 0 ) { KillTimer(m_ClipTimer); m_ClipTimer = 0; } ChangeClipboardChain(m_hNextClipWnd); } } else { // Do Enable m_bAllowClipChain = TRUE; if ( ExAddClipboardFormatListener != NULL && ExRemoveClipboardFormatListener != NULL ) { if ( ExAddClipboardFormatListener(m_hWnd) ) PostMessage(WM_GETCLIPBOARD); m_bClipChain = FALSE; } else { m_hNextClipWnd = SetClipboardViewer(); m_ClipTimer = SetTimer(TIMERID_CLIPUPDATE, 60000, NULL); m_bClipChain = TRUE; } } AfxGetApp()->WriteProfileInt(_T("MainFrame"), _T("ClipboardChain"), m_bAllowClipChain); } void CMainFrame::OnUpdateClipchain(CCmdUI *pCmdUI) { pCmdUI->SetCheck(m_bAllowClipChain); } void CMainFrame::OnMoving(UINT fwSide, LPRECT pRect) { CMDIFrameWnd::OnMoving(fwSide, pRect); if ( !ExDwmEnable && m_bGlassStyle ) Invalidate(FALSE); if ( m_UseBitmapUpdate ) { m_UseBitmapUpdate = FALSE; CWinApp *pApp = AfxGetApp(); POSITION pos = pApp->GetFirstDocTemplatePosition(); while ( pos != NULL ) { CDocTemplate *pDocTemp = pApp->GetNextDocTemplate(pos); POSITION dpos = pDocTemp->GetFirstDocPosition(); while ( dpos != NULL ) { CRLoginDoc *pDoc = (CRLoginDoc *)pDocTemp->GetNextDoc(dpos); if ( pDoc != NULL && pDoc->m_TextRam.m_BitMapStyle == MAPING_DESKTOP ) pDoc->UpdateAllViews(NULL, UPDATE_INITPARA, NULL); } } } } void CMainFrame::OnGetMinMaxInfo(MINMAXINFO* lpMMI) { CRect rect; int cx = 200, cy = 200; if ( m_hWnd != NULL ) { GetWindowRect(rect); if ( !m_Frame.IsRectEmpty() && !rect.IsRectEmpty() ) { cx = rect.Width() - m_Frame.Width() + PANEMIN_WIDTH * 4; cy = rect.Height() - m_Frame.Height() + PANEMIN_HEIGHT * 2; } } lpMMI->ptMinTrackSize.x = cx; lpMMI->ptMinTrackSize.y = cy; CMDIFrameWnd::OnGetMinMaxInfo(lpMMI); } void CMainFrame::OnDeleteOldEntry() { if ( ::AfxMessageBox(IDS_DELOLDENTRYMSG, MB_ICONQUESTION | MB_YESNO) == IDYES ) ((CRLoginApp *)AfxGetApp())->DelProfileSection(_T("ServerEntryTab")); } LRESULT CMainFrame::OnSetMessageString(WPARAM wParam, LPARAM lParam) { if ( wParam == 0 ) return CMDIFrameWnd::OnSetMessageString(wParam, lParam); int n; CStringLoad msg((UINT)wParam); if ( (n = msg.Find(_T("\n"))) >= 0 ) msg.Truncate(n); return CMDIFrameWnd::OnSetMessageString(0, (LPARAM)(LPCTSTR)msg); } #define _AfxGetDlgCtrlID(hWnd) ((UINT)(WORD)::GetDlgCtrlID(hWnd)) BOOL CMainFrame::OnToolTipText(UINT nId, NMHDR* pNMHDR, LRESULT* pResult) { // return CMDIFrameWnd::OnToolTipText(nId, pNMHDR, pResult); ENSURE_ARG(pNMHDR != NULL); ENSURE_ARG(pResult != NULL); ASSERT(pNMHDR->code == TTN_NEEDTEXTA || pNMHDR->code == TTN_NEEDTEXTW); // need to handle both ANSI and UNICODE versions of the message TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR; TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR; // TCHAR szFullText[256]; CStringLoad szFullText; CString strTipText; UINT_PTR nID = pNMHDR->idFrom; if (pNMHDR->code == TTN_NEEDTEXTA && (pTTTA->uFlags & TTF_IDISHWND) || pNMHDR->code == TTN_NEEDTEXTW && (pTTTW->uFlags & TTF_IDISHWND)) { // idFrom is actually the HWND of the tool nID = _AfxGetDlgCtrlID((HWND)nID); } if (nID != 0) // will be zero on a separator { // don't handle the message if no string resource found // if (AfxLoadString((UINT)nID, szFullText) == 0) if (szFullText.LoadString((UINT)nID) == 0) return FALSE; // this is the command id, not the button index AfxExtractSubString(strTipText, szFullText, 1, '\n'); } #ifndef _UNICODE if (pNMHDR->code == TTN_NEEDTEXTA) Checked::strncpy_s(pTTTA->szText, _countof(pTTTA->szText), strTipText, _TRUNCATE); else _mbstowcsz(pTTTW->szText, strTipText, _countof(pTTTW->szText)); #else if (pNMHDR->code == TTN_NEEDTEXTA) _wcstombsz(pTTTA->szText, strTipText, _countof(pTTTA->szText)); else Checked::wcsncpy_s(pTTTW->szText, _countof(pTTTW->szText), strTipText, _TRUNCATE); #endif *pResult = 0; // bring the tooltip window above other popup windows ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOMOVE|SWP_NOOWNERZORDER); return TRUE; // message was handled }
[ "kmiya@gem.or.jp" ]
kmiya@gem.or.jp
af31e0fe3b2012020131596b05a0ef2ed73ff12c
2ed2a2c7d417b57ba203fa4ac2bd6baaa8c5d193
/1.05/App/ioPinot1.05-Debian7/Linux-ia32/include/pinot/filters/Filter.h
85f2fdc61c052db37ec93de5bcecbbf0c51f2cba
[]
no_license
mutek/pinot
843fd881fe5f97520fa3491e4d6c87ff7d67e049
e02eaf12eedbbe7ab9a3d48621c33540675b5ca2
refs/heads/master
2021-01-13T01:57:52.841469
2013-04-05T15:47:33
2013-04-05T15:47:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,401
h
/* * Copyright 2007-2009 Fabrice Colin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef _DIJON_FILTER_H #define _DIJON_FILTER_H #include <string> #include <set> #include <map> #ifndef DIJON_FILTER_EXPORT #if defined __GNUC__ && (__GNUC__ >= 4) #define DIJON_FILTER_EXPORT __attribute__ ((visibility("default"))) #define DIJON_FILTER_INITIALIZE __attribute__((constructor)) #define DIJON_FILTER_SHUTDOWN __attribute__((destructor)) #else #define DIJON_FILTER_EXPORT #define DIJON_FILTER_INITIALIZE #define DIJON_FILTER_SHUTDOWN #endif #endif #include "Memory.h" namespace Dijon { class Filter; /** Provides the list of MIME types supported by the filter(s). * The character string is allocated with new[]. * This function is exported by dynamically loaded filter libraries. */ typedef bool (get_filter_types_func)(std::set<std::string> &); /** Returns what data should be passed to the filter(s). * Output is cast from Filter::DataInput to int for convenience. * This function is exported by dynamically loaded filter libraries. * The aim is to let the client application know before-hand whether * it should load documents or not. */ typedef bool (check_filter_data_input_func)(int); /** Returns a Filter that handles the given MIME type. * The Filter object is allocated with new. * This function is exported by dynamically loaded filter libraries * and serves as a factory for Filter objects, so that the client * application doesn't have to know which Filter sub-types handle * which MIME types. */ typedef Filter *(get_filter_func)(const std::string &); /** Converts text to UTF-8. */ typedef std::string (convert_to_utf8_func)(const char *, unsigned int, const std::string &); /// Filter interface. class DIJON_FILTER_EXPORT Filter { public: /// Builds an empty filter. Filter(const std::string &mime_type); /// Destroys the filter. virtual ~Filter(); // Enumerations. /** What data a filter supports as input. * It can be either the whole document data, its file name, or its URI. */ typedef enum { DOCUMENT_DATA = 0, DOCUMENT_STRING, DOCUMENT_FILE_NAME, DOCUMENT_URI } DataInput; /** Input properties supported by the filter. * - PREFERRED_CHARSET is the charset preferred by the client application. * The filter will convert document's content to this charset if possible. * - OPERATING_MODE can be set to either view or index. * - MAXIMUM_NESTED_SIZE is the maximum size in bytes of nested documents. */ typedef enum { PREFERRED_CHARSET = 0, OPERATING_MODE, MAXIMUM_NESTED_SIZE } Properties; // Information. /// Returns the MIME type handled by the filter. std::string get_mime_type(void) const; /// Returns what data the filter requires as input. virtual bool is_data_input_ok(DataInput input) const = 0; // Initialization. /** Sets a property, prior to calling set_document_XXX(). * Returns false if the property is not supported. */ virtual bool set_property(Properties prop_name, const std::string &prop_value) = 0; /** (Re)initializes the filter with the given data. * Caller should ensure the given pointer is valid until the * Filter object is destroyed, as some filters may not need to * do a deep copy of the data. * Call next_document() to position the filter onto the first document. * Returns false if this input is not supported or an error occured. */ virtual bool set_document_data(const char *data_ptr, unsigned int data_length) = 0; /** (Re)initializes the filter with the given data. * Call next_document() to position the filter onto the first document. * Returns false if this input is not supported or an error occured. */ virtual bool set_document_string(const std::string &data_str) = 0; /** (Re)initializes the filter with the given file. * Call next_document() to position the filter onto the first document. * Returns false if this input is not supported or an error occured. */ virtual bool set_document_file(const std::string &file_path, bool unlink_when_done = false); /** (Re)initializes the filter with the given URI. * Call next_document() to position the filter onto the first document. * Returns false if this input is not supported or an error occured. */ virtual bool set_document_uri(const std::string &uri) = 0; // Going from one nested document to the next. /** Returns true if there are nested documents left to extract. * Returns false if the end of the parent document was reached * or an error occured. */ virtual bool has_documents(void) const = 0; /** Moves to the next nested document. * Returns false if there are none left. */ virtual bool next_document(void) = 0; /** Skips to the nested document with the given ipath. * Returns false if no such document exists. */ virtual bool skip_to_document(const std::string &ipath) = 0; // Accessing documents' contents. /// Returns the message for the most recent error that has occured. virtual std::string get_error(void) const = 0; /** Returns a dictionary of metadata extracted from the current document. * Metadata fields may include one or more of the following : * title, ipath, mimetype, language, charset, author, creator, * publisher, modificationdate, creationdate, size * Special considerations apply : * - ipath is an internal path to the nested document that can be * later passed to skip_to_document(). It may be empty if the parent * document's type doesn't allow embedding, in which case the filter * should only return one document. * - mimetype should be text/plain if the document could be handled * internally, empty if unknown. If any other value, it is expected * that the client application can pass the nested document's content * to another filter that supports this particular type. */ const std::map<std::string, std::string> &get_meta_data(void) const; /// Returns content. const dstring &get_content(void) const; protected: /// The MIME type handled by the filter. std::string m_mimeType; /// Metadata dictionary. std::map<std::string, std::string> m_metaData; /// Content. dstring m_content; /// The name of the input file, if any. std::string m_filePath; /// Rewinds the filter. virtual void rewind(void); private: /// Whether the input file should be deleted when done. bool m_deleteInputFile; /// Filter objects cannot be copied. Filter(const Filter &other); /// Filter objects cannot be copied. Filter& operator=(const Filter& other); /// Deletes the input file. void deleteInputFile(void); }; } #endif // _DIJON_FILTER_H
[ "mutek@riseup.net" ]
mutek@riseup.net
b15291fa8299c94073db4274d25cadefe3f4ce09
a5fb319c0a08787cb3efe2f5de77136887d5f55d
/55M.cpp
17a44444705a4d75796131f23b8cf62faac6c82f
[]
no_license
rachitjain123/leetcode-submissions
1c64a652e67862d17261188a85bb0e843372ed20
bb50f1c232ca81ffab52b7dc31c6a03c4f5955fb
refs/heads/master
2022-11-08T14:38:52.424740
2020-06-27T07:37:58
2020-06-27T07:37:58
225,630,669
0
0
null
null
null
null
UTF-8
C++
false
false
284
cpp
class Solution { public: bool canJump(vector<int>& nums) { int maxi=0; for(int i=0;i<nums.size();i++) { if(i<=maxi) maxi=max(maxi,i+nums[i]); else return false; } return true; } };
[ "jainrachit100@gmail.com" ]
jainrachit100@gmail.com
9e844c3d093761a73c3f3256570aacbb316ec6ef
504fd67b9fe8a7d2c4fadf69e9e48afc7395ea98
/PapuEngine/Button.h
41f3e9d0c91b13809ca5ef4150fa0479330df9c5
[]
no_license
lvaldivia/Fundamentos201902
1267df787d8ecb453198362cba19316c3ed174e8
3bc6faebe34c16ca9f4e8d05736e648de94b0d54
refs/heads/master
2020-09-02T07:59:12.670356
2019-12-23T04:03:08
2019-12-23T04:03:08
219,173,284
0
0
null
null
null
null
UTF-8
C++
false
false
407
h
#pragma once #include "SpriteBacth.h" #include <glm\glm.hpp> #include "GLTexture.h" #include <string> class Button { private: std::string texture; int textureID; glm::vec2 position; public: void draw(SpriteBacth& spriteBatch); Button(std::string texture); bool clicked(glm::vec2 position); void setPosition(glm::vec2 position); glm::vec2 getPosition() const { return position; } ~Button(); };
[ "wmorales83@gmail.com" ]
wmorales83@gmail.com
c3f7ce1c43ea66bcf2a1cdd8cd73101367981c04
de7e771699065ec21a340ada1060a3cf0bec3091
/analysis/common/src/java/org/apache/lucene/analysis/fa/PersianNormalizationFilterFactory.h
52d7e49ad8db357878b302035955acf88a80f4b8
[]
no_license
sraihan73/Lucene-
0d7290bacba05c33b8d5762e0a2a30c1ec8cf110
1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3
refs/heads/master
2020-03-31T07:23:46.505891
2018-12-08T14:57:54
2018-12-08T14:57:54
152,020,180
7
0
null
null
null
null
UTF-8
C++
false
false
3,069
h
#pragma once #include "../util/MultiTermAwareComponent.h" #include "../util/TokenFilterFactory.h" #include "stringhelper.h" #include <memory> #include <stdexcept> #include <string> #include <unordered_map> // C++ NOTE: Forward class declarations: #include "core/src/java/org/apache/lucene/analysis/fa/PersianNormalizationFilter.h" #include "core/src/java/org/apache/lucene/analysis/TokenStream.h" #include "core/src/java/org/apache/lucene/analysis/util/AbstractAnalysisFactory.h" /* * Licensed to the Syed Mamun Raihan (sraihan.com) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * sraihan.com licenses this file to You under GPLv3 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 * * https://www.gnu.org/licenses/gpl-3.0.en.html * * 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. */ namespace org::apache::lucene::analysis::fa { using PersianNormalizationFilter = org::apache::lucene::analysis::fa::PersianNormalizationFilter; using TokenStream = org::apache::lucene::analysis::TokenStream; using AbstractAnalysisFactory = org::apache::lucene::analysis::util::AbstractAnalysisFactory; using MultiTermAwareComponent = org::apache::lucene::analysis::util::MultiTermAwareComponent; using TokenFilterFactory = org::apache::lucene::analysis::util::TokenFilterFactory; /** * Factory for {@link PersianNormalizationFilter}. * <pre class="prettyprint"> * &lt;fieldType name="text_fanormal" class="solr.TextField" * positionIncrementGap="100"&gt; &lt;analyzer&gt; &lt;charFilter * class="solr.PersianCharFilterFactory"/&gt; &lt;tokenizer * class="solr.StandardTokenizerFactory"/&gt; &lt;filter * class="solr.PersianNormalizationFilterFactory"/&gt; &lt;/analyzer&gt; * &lt;/fieldType&gt;</pre> */ class PersianNormalizationFilterFactory : public TokenFilterFactory, public MultiTermAwareComponent { GET_CLASS_NAME(PersianNormalizationFilterFactory) /** Creates a new PersianNormalizationFilterFactory */ public: PersianNormalizationFilterFactory( std::unordered_map<std::wstring, std::wstring> &args); std::shared_ptr<PersianNormalizationFilter> create(std::shared_ptr<TokenStream> input) override; std::shared_ptr<AbstractAnalysisFactory> getMultiTermComponent() override; protected: std::shared_ptr<PersianNormalizationFilterFactory> shared_from_this() { return std::static_pointer_cast<PersianNormalizationFilterFactory>( org.apache.lucene.analysis.util.TokenFilterFactory::shared_from_this()); } }; } // #include "core/src/java/org/apache/lucene/analysis/fa/
[ "smamunr@fedora.localdomain" ]
smamunr@fedora.localdomain
06cec2b23fd1629f29b0253fe94e241c0439e09c
98157b3124db71ca0ffe4e77060f25503aa7617f
/fbhc/2019_2/bitstrings_as_a_service.cpp
97a9e3b8d5028e54546a30541a07be0273d6cbd4
[]
no_license
wiwitrifai/competitive-programming
c4130004cd32ae857a7a1e8d670484e236073741
f4b0044182f1d9280841c01e7eca4ad882875bca
refs/heads/master
2022-10-24T05:31:46.176752
2022-09-02T07:08:05
2022-09-02T07:08:35
59,357,984
37
4
null
null
null
null
UTF-8
C++
false
false
2,258
cpp
#include <bits/stdc++.h> using namespace std; const int M = 1e4 + 4, N = 4004, inf = 1e9 + 7; int p[N]; int find(int x) { return p[x] < 0 ? x : p[x] = find(p[x]); } void merge(int u, int v) { u = find(u); v = find(v); if (u == v) return; if (-p[u] > -p[v]) swap(u, v); p[v] += p[u]; p[u] = v; } int n, m; int x[M], y[M], col[N]; int dp[N][N]; void read_input() { scanf("%d %d", &n, &m); for (int i = 0; i < m; ++i) { scanf("%d %d", x+i, y+i); --x[i], --y[i]; } } void solve() { fill(p, p+n, -1); for (int i = 0; i < m; ++i) { int l = x[i], r = y[i]; while (l < r) { merge(l, r); ++l; --r; } } vector<pair<int, int>> ids; int tot = 0; for (int i = 0; i < n; ++i) if (p[i] < 0) { ids.emplace_back(-p[i], i); tot += -p[i]; } assert(tot == n); for (int i = 0; i <= (int)ids.size(); ++i) for (int j = 0; j <= n; ++j) dp[i][j] = -1; dp[0][0] = 0; for (int i = 0; i < (int)ids.size(); ++i) { int now = ids[i].first; for (int j = 0; j <= n; ++j) { if (dp[i][j] == -1) continue; dp[i+1][j] = 0; if (j + now <= n) { dp[i+1][j+now] = 1; } } } int best = -1; int sz = ids.size(); for (int i = 0; i <= n; ++i) { if (dp[sz][i] == -1) continue; if (best == -1 || abs(n-2*best) > abs(n-2*i)) best = i; } assert(best != -1); int res = abs(n - 2 * best); for (int i = sz; i > 0; --i) { int v = ids[i-1].second, w = ids[i-1].first; col[v] = dp[i][best]; if (dp[i][best]) best -= w; } assert(best == 0); int sum = 0; for (int i = 0; i < n; ++i) { printf("%d", col[find(i)]); sum += col[find(i)]; } assert(abs(n-2*sum) == res); printf("\n"); } int main(int argc, char * argv[]) { clock_t starttime = clock(); int seed = time(0); if (argc >= 2) { seed = atoi(argv[1]); } cerr << "random seed\t= " << seed << endl; srand(seed); int tt; scanf("%d", &tt); for (int tc = 1; tc <= tt; ++tc) { printf("Case #%d: ", tc); read_input(); solve(); fflush(stdout); cerr << "~ TC#" << tc << " done! execution time : " << (double)(clock() - starttime) / CLOCKS_PER_SEC << " s " << endl; } return 0; }
[ "wiwitrifai@gmail.com" ]
wiwitrifai@gmail.com
81f8c4b27b5c34e22705d6452b7cd83b59f5ae8d
0ca5bc1f0d8781bcb7f813eefd46445df6e9f453
/tinyrexxParser.h
d8657b1b46d4f6eecf98d08d822df222e627ad4d
[]
no_license
AkaiSara/Tinyrexx
d9ef10a912915d8097346eb6372ed50d18f7d5c9
d26ea94a038302d0c38bbc2a2c5aa99b1a00c89b
refs/heads/master
2020-05-31T02:00:57.021640
2019-06-03T18:17:39
2019-06-03T18:17:39
190,058,053
0
0
null
null
null
null
UTF-8
C++
false
false
11,001
h
// Generated from tinyrexx.g4 by ANTLR 4.7.1 #pragma once #include "antlr4-runtime.h" class tinyrexxParser : public antlr4::Parser { public: enum { T__0 = 1, T__1 = 2, T__2 = 3, T__3 = 4, T__4 = 5, T__5 = 6, T__6 = 7, T__7 = 8, T__8 = 9, T__9 = 10, OPENP = 11, CLOSEP = 12, MINUS = 13, PLUS = 14, MUL = 15, DIV = 16, EQUAL = 17, LT = 18, LEQ = 19, GT = 20, GEQ = 21, TRUE = 22, FALSE = 23, ID = 24, NUMBER = 25, WS = 26, AND = 27, OR = 28, NOT = 29, ErrorChar = 30 }; enum { RuleProgram = 0, RuleStatement = 1, RuleAssign = 2, RulePrint = 3, RuleInput = 4, RuleI_t_e = 5, RuleE = 6, RuleW_loop = 7, RuleF_loop = 8, RuleGuard = 9, RuleTest = 10, RuleCtest = 11, RuleA_expr = 12, RuleA_op = 13, RuleR_op = 14, RuleL_op = 15 }; tinyrexxParser(antlr4::TokenStream *input); ~tinyrexxParser(); virtual std::string getGrammarFileName() const override; virtual const antlr4::atn::ATN& getATN() const override { return _atn; }; virtual const std::vector<std::string>& getTokenNames() const override { return _tokenNames; }; // deprecated: use vocabulary instead. virtual const std::vector<std::string>& getRuleNames() const override; virtual antlr4::dfa::Vocabulary& getVocabulary() const override; class ProgramContext; class StatementContext; class AssignContext; class PrintContext; class InputContext; class I_t_eContext; class EContext; class W_loopContext; class F_loopContext; class GuardContext; class TestContext; class CtestContext; class A_exprContext; class A_opContext; class R_opContext; class L_opContext; class ProgramContext : public antlr4::ParserRuleContext { public: ProgramContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; antlr4::tree::TerminalNode *EOF(); std::vector<StatementContext *> statement(); StatementContext* statement(size_t i); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; ProgramContext* program(); class StatementContext : public antlr4::ParserRuleContext { public: StatementContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; AssignContext *assign(); PrintContext *print(); InputContext *input(); W_loopContext *w_loop(); F_loopContext *f_loop(); I_t_eContext *i_t_e(); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; StatementContext* statement(); class AssignContext : public antlr4::ParserRuleContext { public: AssignContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; antlr4::tree::TerminalNode *ID(); A_exprContext *a_expr(); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; AssignContext* assign(); class PrintContext : public antlr4::ParserRuleContext { public: PrintContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; A_exprContext *a_expr(); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; PrintContext* print(); class InputContext : public antlr4::ParserRuleContext { public: InputContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; antlr4::tree::TerminalNode *ID(); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; InputContext* input(); class I_t_eContext : public antlr4::ParserRuleContext { public: I_t_eContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; GuardContext *guard(); EContext *e(); std::vector<StatementContext *> statement(); StatementContext* statement(size_t i); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; I_t_eContext* i_t_e(); class EContext : public antlr4::ParserRuleContext { public: EContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; std::vector<StatementContext *> statement(); StatementContext* statement(size_t i); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; EContext* e(); class W_loopContext : public antlr4::ParserRuleContext { public: W_loopContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; GuardContext *guard(); std::vector<StatementContext *> statement(); StatementContext* statement(size_t i); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; W_loopContext* w_loop(); class F_loopContext : public antlr4::ParserRuleContext { public: F_loopContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; antlr4::tree::TerminalNode *ID(); std::vector<antlr4::tree::TerminalNode *> NUMBER(); antlr4::tree::TerminalNode* NUMBER(size_t i); std::vector<StatementContext *> statement(); StatementContext* statement(size_t i); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; F_loopContext* f_loop(); class GuardContext : public antlr4::ParserRuleContext { public: GuardContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; antlr4::tree::TerminalNode *OPENP(); CtestContext *ctest(); antlr4::tree::TerminalNode *CLOSEP(); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; GuardContext* guard(); class TestContext : public antlr4::ParserRuleContext { public: TestContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; std::vector<A_exprContext *> a_expr(); A_exprContext* a_expr(size_t i); R_opContext *r_op(); TestContext *test(); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; TestContext* test(); class CtestContext : public antlr4::ParserRuleContext { public: CtestContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; TestContext *test(); antlr4::tree::TerminalNode *NOT(); std::vector<CtestContext *> ctest(); CtestContext* ctest(size_t i); antlr4::tree::TerminalNode *OPENP(); antlr4::tree::TerminalNode *CLOSEP(); A_exprContext *a_expr(); antlr4::tree::TerminalNode *TRUE(); antlr4::tree::TerminalNode *FALSE(); L_opContext *l_op(); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; CtestContext* ctest(); CtestContext* ctest(int precedence); class A_exprContext : public antlr4::ParserRuleContext { public: A_exprContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; antlr4::tree::TerminalNode *ID(); antlr4::tree::TerminalNode *NUMBER(); std::vector<A_exprContext *> a_expr(); A_exprContext* a_expr(size_t i); antlr4::tree::TerminalNode *MINUS(); A_opContext *a_op(); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; A_exprContext* a_expr(); A_exprContext* a_expr(int precedence); class A_opContext : public antlr4::ParserRuleContext { public: A_opContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; antlr4::tree::TerminalNode *MINUS(); antlr4::tree::TerminalNode *PLUS(); antlr4::tree::TerminalNode *MUL(); antlr4::tree::TerminalNode *DIV(); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; A_opContext* a_op(); class R_opContext : public antlr4::ParserRuleContext { public: R_opContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; antlr4::tree::TerminalNode *EQUAL(); antlr4::tree::TerminalNode *LT(); antlr4::tree::TerminalNode *LEQ(); antlr4::tree::TerminalNode *GT(); antlr4::tree::TerminalNode *GEQ(); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; R_opContext* r_op(); class L_opContext : public antlr4::ParserRuleContext { public: L_opContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; antlr4::tree::TerminalNode *AND(); antlr4::tree::TerminalNode *OR(); virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override; virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override; }; L_opContext* l_op(); virtual bool sempred(antlr4::RuleContext *_localctx, size_t ruleIndex, size_t predicateIndex) override; bool ctestSempred(CtestContext *_localctx, size_t predicateIndex); bool a_exprSempred(A_exprContext *_localctx, size_t predicateIndex); private: static std::vector<antlr4::dfa::DFA> _decisionToDFA; static antlr4::atn::PredictionContextCache _sharedContextCache; static std::vector<std::string> _ruleNames; static std::vector<std::string> _tokenNames; static std::vector<std::string> _literalNames; static std::vector<std::string> _symbolicNames; static antlr4::dfa::Vocabulary _vocabulary; static antlr4::atn::ATN _atn; static std::vector<uint16_t> _serializedATN; struct Initializer { Initializer(); }; static Initializer _init; };
[ "sara.righetto@gmail.com" ]
sara.righetto@gmail.com
f6a4c7b8a03ab3f96179f96ca48bfc41679e7aea
224ea4ce18411b2c6d1da5b953bb10c010a8ab4c
/Source/GEE_UE2/WorldManager.cpp
5ca1affec75301ce29aefc406cc65445b9ef628c
[ "Unlicense" ]
permissive
bernhardrieder/UE4-Procedural-Level-Streaming
78d6e398e1bb6a3a89745d084671ef071eedb6cf
9fb96704720182d652ca2367fec0328cec15c93f
refs/heads/master
2020-03-18T14:54:41.555901
2018-05-25T15:37:16
2018-05-25T15:37:16
134,874,640
0
1
null
null
null
null
UTF-8
C++
false
false
6,982
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "GEE_UE2.h" #include "WorldManager.h" #include "Kismet/GameplayStatics.h" #include "LevelGenerator.h" #include <string> #include "EngineUtils.h" #include "LevelUtils.h" #include <functional> AWorldManager::AWorldManager() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = false; } void AWorldManager::BeginPlay() { Super::BeginPlay(); initalizeLevelSegmentListsAndDictionaries(); m_generatedLevel = LevelGenerator->GenerateLevel(); loadWorldRootSegment(m_generatedLevel[0]); } //https://forums.unrealengine.com/showthread.php?3851-(39)-Rama-s-Extra-Blueprint-Nodes-for-You-as-a-Plugin-No-C-Required!&p=387524&viewfull=1#post387524 //https://github.com/EverNewJoy/VictoryPlugin/blob/master/Source/VictoryBPLibrary/Private/VictoryBPFunctionLibrary.cpp ULevelStreaming* AWorldManager::loadLevelInstance(UObject* WorldContextObject, FString MapFolderOffOfContent, FString LevelName, int32 InstanceNumber, FVector Location, FRotator Rotation, bool& Success) const { Success = false; if (!WorldContextObject) return nullptr; UWorld* const World = GEngine->GetWorldFromContextObject(WorldContextObject); if (!World) return nullptr; //~~~~~~~~~~~ //Full Name FString FullName = "/Game/" + MapFolderOffOfContent + "/" + LevelName; FName LevelFName = FName(*FullName); FString PackageFileName = FullName; ULevelStreamingKismet* StreamingLevel = NewObject<ULevelStreamingKismet>(World, ULevelStreamingKismet::StaticClass(), NAME_None, RF_Transient, NULL); if (!StreamingLevel) { return nullptr; } //Long Package Name FString LongLevelPackageName = FPackageName::FilenameToLongPackageName(PackageFileName); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Here is where a unique name is chosen for the new level asset // Ensure unique names to gain ability to have multiple instances of same level! // <3 Rama //Create Unique Name based on BP-supplied instance value FString UniqueLevelPackageName = LongLevelPackageName; UniqueLevelPackageName += FString::FromInt(InstanceNumber); //Set! StreamingLevel->SetWorldAssetByPackageName(FName(*UniqueLevelPackageName)); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (World->IsPlayInEditor()) { FWorldContext WorldContext = GEngine->GetWorldContextFromWorldChecked(World); StreamingLevel->RenameForPIE(WorldContext.PIEInstance); } StreamingLevel->LevelColor = FColor::MakeRandomColor(); StreamingLevel->bShouldBeLoaded = true; StreamingLevel->bShouldBeVisible = true; StreamingLevel->bShouldBlockOnLoad = false; StreamingLevel->bInitiallyLoaded = true; StreamingLevel->bInitiallyVisible = true; //Transform StreamingLevel->LevelTransform = FTransform(Rotation, Location); StreamingLevel->PackageNameToLoad = LevelFName; if (!FPackageName::DoesPackageExist(StreamingLevel->PackageNameToLoad.ToString(), NULL, &PackageFileName)) { return nullptr; } //~~~ //Actual map package to load StreamingLevel->PackageNameToLoad = FName(*LongLevelPackageName); //~~~ // Add the new level to world. World->StreamingLevels.Add(StreamingLevel); Success = true; return StreamingLevel; } void AWorldManager::initalizeLevelSegmentListsAndDictionaries() { for (FLevelSegmentMapping mapping : LevelSegmentMapping) { m_levelSegmentMapping.Add(mapping.Type, mapping.MapName); m_levelSegmentTypeCounter.Add(mapping.Type, 0); } } void AWorldManager::loadWorldRootSegment(const LevelSegmentProperties& properties) { LoadLevelSegments(nullptr, properties.NeighbourIndexes); LoadLevelSegment(properties); } void AWorldManager::LoadLevelSegment(const LevelSegmentProperties& properties) { if(isLocationInUse(properties.Location)) { m_loadedLevelSegments[findUsedLocationIndex(properties.Location)]->IsNeeded(true); return; } bool success = false; ULevelStreaming* levelInstance = nullptr; do { if (levelInstance != nullptr) levelInstance->bIsRequestingUnloadAndRemoval = true; levelInstance = loadLevelInstance(this, MapFolderName, m_levelSegmentMapping[properties.Type], m_levelSegmentTypeCounter[properties.Type]++, properties.Location, properties.Rotation, success); } while (!success); m_newLoadedLevels.Add(TPairInitializer<ULevelStreaming*, LevelSegmentProperties>(levelInstance, properties)); levelInstance->OnLevelShown.AddDynamic(this, &AWorldManager::setActiveLevelSegments); } void AWorldManager::LoadLevelSegments(ALevelSegment* root, const TArray<int>& neighbourIndexes) { for (ALevelSegment* segment : m_loadedLevelSegments) segment->IsNeeded(false); if (root != nullptr) root->IsNeeded(true); for (int index : neighbourIndexes) LoadLevelSegment(m_generatedLevel[index]); } void AWorldManager::unloadUnneededMaps() { TArray<ALevelSegment*> unloadSegments; for (ALevelSegment* segment : m_loadedLevelSegments) { if (segment->IsNeeded()) continue; unloadSegments.Add(segment); } for (ALevelSegment* segment : unloadSegments) { removeUsedLocation(segment->GetActorLocation()); m_loadedLevelSegments.Remove(segment); //https://answers.unrealengine.com/questions/205702/unloading-instanced-levels.html !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ULevelStreaming* level = FLevelUtils::FindStreamingLevel(segment->GetLevel()); level->bIsRequestingUnloadAndRemoval = true; } } bool AWorldManager::isLocationInUse(const FVector& location) { for (FVector used_location : m_usedLocations) { if (used_location.Equals(location)) return true; } return false; } int AWorldManager::findUsedLocationIndex(const FVector& location) { for(int i = 0; i < m_usedLocations.Num(); ++i) { if (m_usedLocations[i].Equals(location)) return i; } return m_usedLocations.Num(); } void AWorldManager::removeUsedLocation(const FVector& location) { for(auto a : m_usedLocations) { if(a.Equals(location)) { m_usedLocations.Remove(a); return; } } } void AWorldManager::setActiveLevelSegments() { if (m_newLoadedLevels.Num() == 0) return; for (int i = 0; i < m_newLoadedLevels.Num(); ++i) { auto pair = m_newLoadedLevels[i]; ULevelStreaming* level = pair.Key; if (level && level->IsLevelVisible()) { for (auto a : level->GetLoadedLevel()->Actors) { ALevelSegment* segment = Cast<ALevelSegment>(a); if (segment) { segment->SetActorLocation(pair.Value.Location); segment->SetActorRotation(pair.Value.Rotation); segment->IsNeeded(true); segment->NeighbourIndexes = pair.Value.NeighbourIndexes; segment->WorldManager = this; segment->SetActorHiddenInGame(false); m_usedLocations.Add(segment->GetActorLocation()); m_loadedLevelSegments.Add(segment); m_newLoadedLevels.RemoveAt(i,1,false); break; } } } } m_newLoadedLevels.Shrink(); if(m_newLoadedLevels.Num() == 0) unloadUnneededMaps(); }
[ "bernhard.rieder@live.at" ]
bernhard.rieder@live.at
68f7e5008a4296360a50b5716b5dca21a1f3f2d2
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/xnnpack/src/bench/square.cc
998cefc95afc8f6e48e5cbd147ee18974651b5f1
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
6,940
cc
// Copyright 2021 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <algorithm> #include <array> #include <cmath> #include <functional> #include <limits> #include <random> #include <vector> #include <xnnpack.h> #include <benchmark/benchmark.h> #include "bench/utils.h" #ifdef BENCHMARK_TENSORFLOW_LITE #include "flatbuffers/include/flatbuffers/flatbuffers.h" #include "tensorflow/lite/interpreter.h" #include "tensorflow/lite/kernels/register.h" #include "tensorflow/lite/model.h" #include "tensorflow/lite/schema/schema_generated.h" #include "tensorflow/lite/version.h" #endif // BENCHMARK_TENSORFLOW_LITE static void xnnpack_square_f32(benchmark::State& state) { const size_t batch_size = state.range(0); std::random_device random_device; auto rng = std::mt19937(random_device()); auto f32rng = std::bind(std::uniform_real_distribution<float>(-10.0f, 10.0f), std::ref(rng)); std::vector<float> input(batch_size + XNN_EXTRA_BYTES / sizeof(float)); std::vector<float> output(batch_size); std::generate(input.begin(), input.end(), std::ref(f32rng)); std::fill(output.begin(), output.end(), std::nanf("")); xnn_status status = xnn_initialize(nullptr /* allocator */); if (status != xnn_status_success) { state.SkipWithError("failed to initialize XNNPACK"); return; } xnn_operator_t square_op = nullptr; status = xnn_create_square_nc_f32( 1 /* channels */, 1 /* input stride */, 1 /* output stride */, 0 /* flags */, &square_op); if (status != xnn_status_success || square_op == nullptr) { state.SkipWithError("failed to create Square operator"); return; } status = xnn_setup_square_nc_f32( square_op, batch_size, input.data(), output.data(), nullptr /* thread pool */); if (status != xnn_status_success) { state.SkipWithError("failed to setup Square operator"); return; } for (auto _ : state) { status = xnn_run_operator(square_op, nullptr /* thread pool */); if (status != xnn_status_success) { state.SkipWithError("failed to run Square operator"); return; } } status = xnn_delete_operator(square_op); if (status != xnn_status_success) { state.SkipWithError("failed to delete Square operator"); return; } const uint64_t cpu_frequency = benchmark::utils::GetCurrentCpuFrequency(); if (cpu_frequency != 0) { state.counters["cpufreq"] = cpu_frequency; } state.counters["elements"] = benchmark::Counter(uint64_t(state.iterations()) * batch_size, benchmark::Counter::kIsRate); const size_t bytes_per_iteration = 2 * batch_size * sizeof(float); state.counters["bytes"] = benchmark::Counter(uint64_t(state.iterations()) * bytes_per_iteration, benchmark::Counter::kIsRate); } #ifdef BENCHMARK_TENSORFLOW_LITE static void tflite_square_f32(benchmark::State& state) { const size_t batch_size = state.range(0); std::random_device random_device; auto rng = std::mt19937(random_device()); auto f32rng = std::bind(std::uniform_real_distribution<float>(-10.0f, 10.0f), std::ref(rng)); flatbuffers::FlatBufferBuilder builder; const flatbuffers::Offset<tflite::OperatorCode> operator_code = CreateOperatorCode(builder, tflite::BuiltinOperator_SQUARE); const std::array<flatbuffers::Offset<tflite::Buffer>, 1> buffers{{ tflite::CreateBuffer(builder, builder.CreateVector({})), }}; const std::array<int32_t, 1> shape{{ static_cast<int32_t>(batch_size) }}; const std::array<flatbuffers::Offset<tflite::Tensor>, 2> tensors{{ tflite::CreateTensor(builder, builder.CreateVector<int32_t>(shape.data(), shape.size()), tflite::TensorType_FLOAT32), tflite::CreateTensor(builder, builder.CreateVector<int32_t>(shape.data(), shape.size()), tflite::TensorType_FLOAT32), }}; const std::array<int32_t, 1> op_inputs{{ 0 }}; const std::array<int32_t, 1> op_outputs{{ 1 }}; flatbuffers::Offset<tflite::Operator> op = tflite::CreateOperator( builder, 0 /* opcode_index */, builder.CreateVector<int32_t>(op_inputs.data(), op_inputs.size()), builder.CreateVector<int32_t>(op_outputs.data(), op_outputs.size())); const std::array<int32_t, 1> graph_inputs{{ 0 }}; const std::array<int32_t, 1> graph_outputs{{ 1 }}; const flatbuffers::Offset<tflite::SubGraph> subgraph = tflite::CreateSubGraph( builder, builder.CreateVector(tensors.data(), tensors.size()), builder.CreateVector<int32_t>(graph_inputs.data(), graph_inputs.size()), builder.CreateVector<int32_t>(graph_outputs.data(), graph_outputs.size()), builder.CreateVector(&op, 1)); const flatbuffers::Offset<tflite::Model> model_buffer = tflite::CreateModel(builder, TFLITE_SCHEMA_VERSION, builder.CreateVector(&operator_code, 1), builder.CreateVector(&subgraph, 1), builder.CreateString("Square model"), builder.CreateVector(buffers.data(), buffers.size())); builder.Finish(model_buffer); const tflite::Model* model = tflite::GetModel(builder.GetBufferPointer()); tflite::ops::builtin::BuiltinOpResolverWithoutDefaultDelegates resolver; tflite::InterpreterBuilder interpreterBuilder(model, resolver); std::unique_ptr<tflite::Interpreter> interpreter; if (interpreterBuilder(&interpreter) != kTfLiteOk || interpreter == nullptr) { state.SkipWithError("failed to create TFLite interpreter"); return; } interpreter->SetNumThreads(1); if (interpreter->AllocateTensors() != kTfLiteOk) { state.SkipWithError("failed to allocate tensors"); return; } std::generate( interpreter->typed_tensor<float>(0), interpreter->typed_tensor<float>(0) + batch_size, std::ref(f32rng)); for (auto _ : state) { if (interpreter->Invoke() != kTfLiteOk) { state.SkipWithError("failed to invoke TFLite interpreter"); return; } } const uint64_t cpu_frequency = benchmark::utils::GetCurrentCpuFrequency(); if (cpu_frequency != 0) { state.counters["cpufreq"] = cpu_frequency; } state.counters["elements"] = benchmark::Counter(uint64_t(state.iterations()) * batch_size, benchmark::Counter::kIsRate); const size_t bytes_per_iteration = 2 * batch_size * sizeof(float); state.counters["bytes"] = benchmark::Counter(uint64_t(state.iterations()) * bytes_per_iteration, benchmark::Counter::kIsRate); interpreter.reset(); } #endif // BENCHMARK_TENSORFLOW_LITE BENCHMARK(xnnpack_square_f32) ->Apply(benchmark::utils::UnaryElementwiseParameters<float, float>) ->UseRealTime(); #ifdef BENCHMARK_TENSORFLOW_LITE BENCHMARK(tflite_square_f32) ->Apply(benchmark::utils::UnaryElementwiseParameters<float, float>) ->UseRealTime(); #endif // BENCHMARK_TENSORFLOW_LITE #ifndef XNNPACK_BENCHMARK_NO_MAIN BENCHMARK_MAIN(); #endif
[ "jengelh@inai.de" ]
jengelh@inai.de