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
79c4c435e81f2f90e4c361e0ce2ca591c9065de5
7ec327e08a35fa7ba13e64db417475eed8b258fb
/controllers/ros_custom/include/webots_ros/skin_get_bone_orientationRequest.h
8cc96b0cbd8665f84715f447f226b6dab4d6985d
[]
no_license
Federico-Ciuffardi/webots_benchmark
accb69213098b534011c6ddfcd466a8ca1d466b5
0c2c2e464cfdc1b0a021e79b7f338884f68903b6
refs/heads/master
2023-04-20T01:30:39.314603
2021-05-13T19:25:21
2021-05-13T19:25:21
360,763,711
0
0
null
null
null
null
UTF-8
C++
false
false
6,243
h
/* * Copyright 1996-2020 Cyberbotics 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 WEBOTS_ROS_MESSAGE_SKIN_GET_BONE_ORIENTATIONREQUEST_H #define WEBOTS_ROS_MESSAGE_SKIN_GET_BONE_ORIENTATIONREQUEST_H #include <string> #include <vector> #include <map> #include "ros/types.h" #include "ros/serialization.h" #include "ros/builtin_message_traits.h" #include "ros/message_operations.h" namespace webots_ros { template <class ContainerAllocator> struct skin_get_bone_orientationRequest_ { typedef skin_get_bone_orientationRequest_<ContainerAllocator> Type; skin_get_bone_orientationRequest_() : index(0) , absolute(false) { } skin_get_bone_orientationRequest_(const ContainerAllocator& _alloc) : index(0) , absolute(false) { } typedef int32_t _index_type; _index_type index; typedef uint8_t _absolute_type; _absolute_type absolute; typedef boost::shared_ptr< ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> const> ConstPtr; boost::shared_ptr<std::map<std::string, std::string> > __connection_header; }; typedef ::webots_ros::skin_get_bone_orientationRequest_<std::allocator<void> > skin_get_bone_orientationRequest; typedef boost::shared_ptr< ::webots_ros::skin_get_bone_orientationRequest > skin_get_bone_orientationRequestPtr; typedef boost::shared_ptr< ::webots_ros::skin_get_bone_orientationRequest const> skin_get_bone_orientationRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace webots_ros namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'std_msgs': ['/opt/ros/groovy/share/std_msgs/msg'], 'webots_ros // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> > { static const char* value() { return "f5889bc85962c2ea0f40d74e77b00b8b"; } static const char* value(const ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xf9df5232b65af94fULL; static const uint64_t static_value2 = 0x73f79fe6d84301bbULL; }; template<class ContainerAllocator> struct DataType< ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> > { static const char* value() { return "webots_ros/skin_get_bone_orientationRequest"; } static const char* value(const ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> > { static const char* value() { return "int32 index\n\ bool absolute\n\\n\ \n\ "; } static const char* value(const ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.index); stream.next(m.absolute); } ROS_DECLARE_ALLINONE_SERIALIZER; }; } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::webots_ros::skin_get_bone_orientationRequest_<ContainerAllocator>& v) { s << indent << "index: "; Printer<int32_t>::stream(s, indent + " ", v.index); s << indent << "absolute: "; Printer<uint8_t>::stream(s, indent + " ", v.absolute); } }; } // namespace message_operations } // namespace ros #endif // WEBOTS_ROS_MESSAGE_SKIN_GET_BONE_ORIENTATIONREQUEST_H
[ "federico.ciuffardi@outlook.com" ]
federico.ciuffardi@outlook.com
2d70fe03a138d9fafccc4ba112e23787e0cf8257
f7e646329e39ccc57b0b75595283b1579eb509b4
/Labo1/MultipleAPI_AvecBridge/formes/rectangle.cpp
9d93ec7dabc67c66a1a065eebffae6b906583053
[]
no_license
Blondwolf/Design-pattern
4c0f6038c13a95cebb8e78c8c04bb30c12730862
34183284889391fa6b454d957bfb0a31ec2a75b7
refs/heads/master
2016-09-06T08:41:11.525495
2015-06-04T20:09:52
2015-06-04T20:09:52
31,897,031
0
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
#include "rectangle.h" Rectangle::Rectangle(APIs_implementor &api) : Shape(api) { h = 0; w = 0; a = 0; } Rectangle::~Rectangle() { //dtor } void Rectangle::draw() { drawRectangle(getX(),getY(),h,w,a); } int Rectangle::getA() const { return a; } int Rectangle::getW() const { return w; } int Rectangle::getH() const { return h; } void Rectangle::setA(int a) { this->a = a; } void Rectangle::setW(int w) { this->w = w; } void Rectangle::setH(int h) { this->h = h; }
[ "arkeine@Mjolnir" ]
arkeine@Mjolnir
5dbd606fb55a24ffecc13d6172d873c27df8bca1
4cc7c74b4bb7b818562bedffd026a86f9ec78f41
/services/device/device_service.cc
f82738401edd350fddbbd680003a9d3261257a67
[ "BSD-3-Clause" ]
permissive
jennyb2911/chromium
1e03c9e5a63af1cf82832e0e99e0028e255872bd
62b48b4fdb3984762f4d2fd3690f02f167920f52
refs/heads/master
2023-01-10T01:08:34.961976
2018-09-28T03:36:36
2018-09-28T03:36:36
150,682,761
1
0
NOASSERTION
2018-09-28T03:49:28
2018-09-28T03:49:27
null
UTF-8
C++
false
false
13,749
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/device/device_service.h" #include <utility> #include "base/bind.h" #include "base/memory/weak_ptr.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "mojo/public/cpp/system/message_pipe.h" #include "services/device/bluetooth/bluetooth_system_factory.h" #include "services/device/fingerprint/fingerprint.h" #include "services/device/generic_sensor/sensor_provider_impl.h" #include "services/device/geolocation/geolocation_config.h" #include "services/device/geolocation/geolocation_context.h" #include "services/device/geolocation/public_ip_address_geolocator.h" #include "services/device/geolocation/public_ip_address_location_notifier.h" #include "services/device/power_monitor/power_monitor_message_broadcaster.h" #include "services/device/public/mojom/battery_monitor.mojom.h" #include "services/device/serial/serial_device_enumerator_impl.h" #include "services/device/serial/serial_io_handler_impl.h" #include "services/device/time_zone_monitor/time_zone_monitor.h" #include "services/device/wake_lock/wake_lock_provider.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "ui/gfx/native_widget_types.h" #if defined(OS_ANDROID) #include "base/android/jni_android.h" #include "jni/InterfaceRegistrar_jni.h" #include "services/device/screen_orientation/screen_orientation_listener_android.h" #else #include "services/device/battery/battery_monitor_impl.h" #include "services/device/battery/battery_status_service.h" #include "services/device/hid/hid_manager_impl.h" #include "services/device/vibration/vibration_manager_impl.h" #endif #if defined(OS_LINUX) && defined(USE_UDEV) #include "services/device/hid/input_service_linux.h" #endif namespace device { #if defined(OS_ANDROID) std::unique_ptr<service_manager::Service> CreateDeviceService( scoped_refptr<base::SingleThreadTaskRunner> file_task_runner, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const std::string& geolocation_api_key, bool use_gms_core_location_provider, const WakeLockContextCallback& wake_lock_context_callback, const CustomLocationProviderCallback& custom_location_provider_callback, const base::android::JavaRef<jobject>& java_nfc_delegate) { GeolocationProviderImpl::SetGeolocationConfiguration( url_loader_factory, geolocation_api_key, custom_location_provider_callback, use_gms_core_location_provider); return std::make_unique<DeviceService>( std::move(file_task_runner), std::move(io_task_runner), std::move(url_loader_factory), geolocation_api_key, wake_lock_context_callback, java_nfc_delegate); } #else std::unique_ptr<service_manager::Service> CreateDeviceService( scoped_refptr<base::SingleThreadTaskRunner> file_task_runner, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const std::string& geolocation_api_key, const CustomLocationProviderCallback& custom_location_provider_callback) { GeolocationProviderImpl::SetGeolocationConfiguration( url_loader_factory, geolocation_api_key, custom_location_provider_callback); return std::make_unique<DeviceService>( std::move(file_task_runner), std::move(io_task_runner), std::move(url_loader_factory), geolocation_api_key); } #endif #if defined(OS_ANDROID) DeviceService::DeviceService( scoped_refptr<base::SingleThreadTaskRunner> file_task_runner, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const std::string& geolocation_api_key, const WakeLockContextCallback& wake_lock_context_callback, const base::android::JavaRef<jobject>& java_nfc_delegate) : file_task_runner_(std::move(file_task_runner)), io_task_runner_(std::move(io_task_runner)), url_loader_factory_(std::move(url_loader_factory)), geolocation_api_key_(geolocation_api_key), wake_lock_context_callback_(wake_lock_context_callback), java_interface_provider_initialized_(false) { java_nfc_delegate_.Reset(java_nfc_delegate); } #else DeviceService::DeviceService( scoped_refptr<base::SingleThreadTaskRunner> file_task_runner, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const std::string& geolocation_api_key) : file_task_runner_(std::move(file_task_runner)), io_task_runner_(std::move(io_task_runner)), url_loader_factory_(std::move(url_loader_factory)), geolocation_api_key_(geolocation_api_key) {} #endif DeviceService::~DeviceService() { #if !defined(OS_ANDROID) device::BatteryStatusService::GetInstance()->Shutdown(); #endif } void DeviceService::OnStart() { registry_.AddInterface<mojom::Fingerprint>(base::Bind( &DeviceService::BindFingerprintRequest, base::Unretained(this))); registry_.AddInterface<mojom::GeolocationConfig>(base::BindRepeating( &DeviceService::BindGeolocationConfigRequest, base::Unretained(this))); registry_.AddInterface<mojom::GeolocationContext>(base::Bind( &DeviceService::BindGeolocationContextRequest, base::Unretained(this))); registry_.AddInterface<mojom::GeolocationControl>(base::Bind( &DeviceService::BindGeolocationControlRequest, base::Unretained(this))); registry_.AddInterface<mojom::PowerMonitor>(base::Bind( &DeviceService::BindPowerMonitorRequest, base::Unretained(this))); registry_.AddInterface<mojom::PublicIpAddressGeolocationProvider>( base::Bind(&DeviceService::BindPublicIpAddressGeolocationProviderRequest, base::Unretained(this))); registry_.AddInterface<mojom::ScreenOrientationListener>( base::Bind(&DeviceService::BindScreenOrientationListenerRequest, base::Unretained(this))); registry_.AddInterface<mojom::SensorProvider>(base::Bind( &DeviceService::BindSensorProviderRequest, base::Unretained(this))); registry_.AddInterface<mojom::TimeZoneMonitor>(base::Bind( &DeviceService::BindTimeZoneMonitorRequest, base::Unretained(this))); registry_.AddInterface<mojom::WakeLockProvider>(base::Bind( &DeviceService::BindWakeLockProviderRequest, base::Unretained(this))); registry_.AddInterface<mojom::SerialDeviceEnumerator>( base::Bind(&DeviceService::BindSerialDeviceEnumeratorRequest, base::Unretained(this))); registry_.AddInterface<mojom::SerialIoHandler>(base::Bind( &DeviceService::BindSerialIoHandlerRequest, base::Unretained(this))); #if defined(OS_ANDROID) registry_.AddInterface(GetJavaInterfaceProvider() ->CreateInterfaceFactory<mojom::BatteryMonitor>()); registry_.AddInterface( GetJavaInterfaceProvider()->CreateInterfaceFactory<mojom::NFCProvider>()); registry_.AddInterface( GetJavaInterfaceProvider() ->CreateInterfaceFactory<mojom::VibrationManager>()); #else registry_.AddInterface<mojom::BatteryMonitor>(base::Bind( &DeviceService::BindBatteryMonitorRequest, base::Unretained(this))); registry_.AddInterface<mojom::HidManager>(base::Bind( &DeviceService::BindHidManagerRequest, base::Unretained(this))); registry_.AddInterface<mojom::NFCProvider>(base::Bind( &DeviceService::BindNFCProviderRequest, base::Unretained(this))); registry_.AddInterface<mojom::VibrationManager>(base::Bind( &DeviceService::BindVibrationManagerRequest, base::Unretained(this))); #endif #if defined(OS_CHROMEOS) registry_.AddInterface<mojom::BluetoothSystemFactory>( base::BindRepeating(&DeviceService::BindBluetoothSystemFactoryRequest, base::Unretained(this))); registry_.AddInterface<mojom::MtpManager>(base::BindRepeating( &DeviceService::BindMtpManagerRequest, base::Unretained(this))); #endif #if defined(OS_LINUX) && defined(USE_UDEV) registry_.AddInterface<mojom::InputDeviceManager>(base::Bind( &DeviceService::BindInputDeviceManagerRequest, base::Unretained(this))); #endif } void DeviceService::OnBindInterface( const service_manager::BindSourceInfo& source_info, const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe) { registry_.BindInterface(interface_name, std::move(interface_pipe)); } #if !defined(OS_ANDROID) void DeviceService::BindBatteryMonitorRequest( mojom::BatteryMonitorRequest request) { BatteryMonitorImpl::Create(std::move(request)); } void DeviceService::BindHidManagerRequest(mojom::HidManagerRequest request) { if (!hid_manager_) hid_manager_ = std::make_unique<HidManagerImpl>(); hid_manager_->AddBinding(std::move(request)); } void DeviceService::BindNFCProviderRequest(mojom::NFCProviderRequest request) { LOG(ERROR) << "NFC is only supported on Android"; NOTREACHED(); } void DeviceService::BindVibrationManagerRequest( mojom::VibrationManagerRequest request) { VibrationManagerImpl::Create(std::move(request)); } #endif #if defined(OS_CHROMEOS) void DeviceService::BindBluetoothSystemFactoryRequest( mojom::BluetoothSystemFactoryRequest request) { BluetoothSystemFactory::CreateFactory(std::move(request)); } void DeviceService::BindMtpManagerRequest(mojom::MtpManagerRequest request) { if (!mtp_device_manager_) mtp_device_manager_ = MtpDeviceManager::Initialize(); mtp_device_manager_->AddBinding(std::move(request)); } #endif #if defined(OS_LINUX) && defined(USE_UDEV) void DeviceService::BindInputDeviceManagerRequest( mojom::InputDeviceManagerRequest request) { file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&InputServiceLinux::BindRequest, std::move(request))); } #endif void DeviceService::BindFingerprintRequest(mojom::FingerprintRequest request) { Fingerprint::Create(std::move(request)); } void DeviceService::BindGeolocationConfigRequest( mojom::GeolocationConfigRequest request) { GeolocationConfig::Create(std::move(request)); } void DeviceService::BindGeolocationContextRequest( mojom::GeolocationContextRequest request) { GeolocationContext::Create(std::move(request)); } void DeviceService::BindGeolocationControlRequest( mojom::GeolocationControlRequest request) { GeolocationProviderImpl::GetInstance()->BindGeolocationControlRequest( std::move(request)); } void DeviceService::BindPowerMonitorRequest( mojom::PowerMonitorRequest request) { if (!power_monitor_message_broadcaster_) { power_monitor_message_broadcaster_ = std::make_unique<PowerMonitorMessageBroadcaster>(); } power_monitor_message_broadcaster_->Bind(std::move(request)); } void DeviceService::BindPublicIpAddressGeolocationProviderRequest( mojom::PublicIpAddressGeolocationProviderRequest request) { if (!public_ip_address_geolocation_provider_) { public_ip_address_geolocation_provider_ = std::make_unique<PublicIpAddressGeolocationProvider>( url_loader_factory_, geolocation_api_key_); } public_ip_address_geolocation_provider_->Bind(std::move(request)); } void DeviceService::BindScreenOrientationListenerRequest( mojom::ScreenOrientationListenerRequest request) { #if defined(OS_ANDROID) if (io_task_runner_) { io_task_runner_->PostTask( FROM_HERE, base::Bind(&ScreenOrientationListenerAndroid::Create, base::Passed(&request))); } #endif } void DeviceService::BindSensorProviderRequest( mojom::SensorProviderRequest request) { if (io_task_runner_) { io_task_runner_->PostTask( FROM_HERE, base::Bind(&device::SensorProviderImpl::Create, file_task_runner_, base::Passed(&request))); } } void DeviceService::BindTimeZoneMonitorRequest( mojom::TimeZoneMonitorRequest request) { if (!time_zone_monitor_) time_zone_monitor_ = TimeZoneMonitor::Create(file_task_runner_); time_zone_monitor_->Bind(std::move(request)); } void DeviceService::BindWakeLockProviderRequest( mojom::WakeLockProviderRequest request) { WakeLockProvider::Create(std::move(request), file_task_runner_, wake_lock_context_callback_); } void DeviceService::BindSerialDeviceEnumeratorRequest( mojom::SerialDeviceEnumeratorRequest request) { #if (defined(OS_LINUX) && defined(USE_UDEV)) || defined(OS_WIN) || \ defined(OS_MACOSX) SerialDeviceEnumeratorImpl::Create(std::move(request)); #endif } void DeviceService::BindSerialIoHandlerRequest( mojom::SerialIoHandlerRequest request) { #if (defined(OS_LINUX) && defined(USE_UDEV)) || defined(OS_WIN) || \ defined(OS_MACOSX) if (io_task_runner_) { io_task_runner_->PostTask( FROM_HERE, base::Bind(&SerialIoHandlerImpl::Create, base::Passed(&request), base::ThreadTaskRunnerHandle::Get())); } #endif } #if defined(OS_ANDROID) service_manager::InterfaceProvider* DeviceService::GetJavaInterfaceProvider() { if (!java_interface_provider_initialized_) { service_manager::mojom::InterfaceProviderPtr provider; JNIEnv* env = base::android::AttachCurrentThread(); Java_InterfaceRegistrar_createInterfaceRegistryForContext( env, mojo::MakeRequest(&provider).PassMessagePipe().release().value(), java_nfc_delegate_); java_interface_provider_.Bind(std::move(provider)); java_interface_provider_initialized_ = true; } return &java_interface_provider_; } #endif } // namespace device
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
000e133f2bee0744ed04fbeb271be493e0ffad3f
bcb9cdda3f3d449be90846e6c4e81a9b9f5f0e99
/solutions/jenya_paulovets/2/sources/2_6/2_3.cpp
f53eb5bdf66a0658176374d4ec63c72b5abe4bd9
[]
no_license
marozau/cpp_craft_0314
4b264c6956f303e7b89cd86cc712c13e1654eb89
4c2e312bf8c4d75d675c889e2b23bb6cace7aadb
refs/heads/master
2021-01-20T05:04:51.826658
2014-06-12T13:49:52
2014-06-12T13:49:52
17,398,797
2
1
null
2014-07-09T06:51:42
2014-03-04T10:44:28
C++
UTF-8
C++
false
false
3,408
cpp
#include <iostream> #include <fstream> #include <boost/cstdint.hpp> #include <boost/date_time/gregorian/gregorian.hpp> typedef boost::uint32_t uint_32; typedef boost::gregorian::date date; struct Sdata { char stock_name[9]; char date_time[9]; double price; double vwap; uint_32 volume; double f1; double t1; double f2; double f3; double f4; Sdata() : price(0), vwap(0), volume(0), f1(0), t1(0), f2(0), f3(0), f4(0) {} bool readData(std::fstream &fileIn, const uint_32 sizeStr); bool writeData(std::fstream &fileOut, uint_32 days, const uint_32 sizeStr) const; }; bool Sdata::readData(std::fstream &fileIn, const uint_32 sizeStr) { fileIn.read(reinterpret_cast<char*>(stock_name), (sizeStr - 1) * sizeof(char)); stock_name[sizeStr - 1] = '\0'; fileIn.read(reinterpret_cast<char*>(date_time), (sizeStr - 1) * sizeof(char)); date_time[sizeStr - 1] = '\0'; fileIn.read(reinterpret_cast<char*>(&price), sizeof(double)); fileIn.read(reinterpret_cast<char*>(&vwap), sizeof(double)); fileIn.read(reinterpret_cast<char*>(&volume), sizeof(uint_32)); fileIn.read(reinterpret_cast<char*>(&f1), sizeof(double)); fileIn.read(reinterpret_cast<char*>(&t1), sizeof(double)); fileIn.read(reinterpret_cast<char*>(&f2), sizeof(double)); fileIn.read(reinterpret_cast<char*>(&f3), sizeof(double)); fileIn.read(reinterpret_cast<char*>(&f4), sizeof(double)); if(!fileIn)return false; return true; } bool Sdata::writeData(std::fstream &fileOut, uint_32 days, const uint_32 sizeStr) const { fileOut.write(reinterpret_cast<const char*>(stock_name), sizeStr * sizeof(char)); fileOut.write(reinterpret_cast<const char*>(&days), sizeof(uint_32)); fileOut.write(reinterpret_cast<const char*>(&vwap), sizeof(double)); fileOut.write(reinterpret_cast<const char*>(&volume), sizeof(uint_32)); fileOut.write(reinterpret_cast<const char*>(&f2), sizeof(double)); if(!fileOut)return false; return true; } //Parsed request to get necessary information void parseInputData(std::fstream &fileIn, std::fstream &fileOut, const uint_32 sizeStr) { Sdata *request = new Sdata(); if(!request->readData(fileIn, sizeStr)) { std::cout << "There is no data in input file" << std::endl; fileIn.close(); fileOut.close(); exit(1); } const uint_32 daysOfYear = 372; const uint_32 daysOfMonth = 31; uint_32 days = 0; date *dateShell = NULL; do { dateShell = new date(boost::gregorian::from_undelimited_string(request->date_time)); days = dateShell->year() * daysOfYear + (dateShell->month()-1) * daysOfMonth + dateShell->day(); if(!request->writeData(fileOut, days, sizeStr)) { std::cout << "Write error" << std::endl; fileIn.close(); fileOut.close(); exit(1); } delete request; request = new Sdata(); delete dateShell; } while (request->readData(fileIn, sizeStr)); delete request; } int main(int argc, char **argv) { std::fstream fileIn; fileIn.open( BINARY_DIR "/input.txt", std::ios::binary | std::ios::in); if (!fileIn) { std::cout << "Error path for input.txt" << std::endl; fileIn.close(); exit(1); } std::fstream fileOut; fileOut.open( BINARY_DIR "/output.txt", std::ios::binary | std::ios::out); if (!fileOut) { std::cout << "Error path for output.txt" << std::endl; fileIn.close(); fileOut.close(); exit(1); } const uint_32 sizeStr = 9; parseInputData(fileIn, fileOut, sizeStr); fileIn.close(); fileOut.close(); return 0; }
[ "jenya.paulovets@gmail.com" ]
jenya.paulovets@gmail.com
08cff91c868a86835fc4eb4c8b0b0889af9deacd
c6fa53212eb03017f9e72fad36dbf705b27cc797
/DataFormats/EcalDigi/interface/EKSrFlag.h
38ff967e773e490006026d309af355f328d4a846
[]
no_license
gem-sw/cmssw
a31fc4ef2233b2157e1e7cbe9a0d9e6c2795b608
5893ef29c12b2718b3c1385e821170f91afb5446
refs/heads/CMSSW_6_2_X_SLHC
2022-04-29T04:43:51.786496
2015-12-16T16:09:31
2015-12-16T16:09:31
12,892,177
2
4
null
2018-11-22T13:40:31
2013-09-17T10:10:26
C++
UTF-8
C++
false
false
1,344
h
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 8; -*- //$Id: EKSrFlag.h,v 1.2 2014/04/02 09:55:00 shervin Exp $ #ifndef EKSRFLAG_H #define EKSRFLAG_H #include "DataFormats/EcalDetId/interface/EcalScDetId.h" #include "DataFormats/EcalDigi/interface/EcalSrFlag.h" #include "FWCore/Utilities/interface/Exception.h" /** This class holds a Selective Readout Flag (SRF) associated to an * ECAL Shashlik supercrystal. */ class EKSrFlag: public EcalSrFlag { public: public: typedef EcalScDetId key_type; //key for edm::SortedCollection public: /** Default constructor. */ EKSrFlag() {}; /** Constructor * @param sc supercrystal det id * @param flag the srp flag, an integer in [0,7]. See constants SRF_xxx in EcalSrFlags class. */ EKSrFlag(const EcalScDetId& sc, const int& flag): scId_(sc){ //SRP flag is coded on 3 bits: if(flag<0 || flag>0x7) throw cms::Exception("InvalidValue", "srp flag greater than 0x7 or negative."); flag_ = (unsigned char) flag; } /** For edm::SortedCollection. * @return det id of the trigger tower the flag is assigned to. */ const EcalScDetId& id() const { return scId_;} private: /** trigger tower id */ EcalScDetId scId_; }; std::ostream& operator<<(std::ostream& s, const EKSrFlag& digi); #endif //EKSRFLAG_H not defined
[ "shervin@cern.ch" ]
shervin@cern.ch
9819e888a4a6ca48a59236c21847a3709af89d7e
479809c083921bda768e61eb5a635859c6d4a540
/Wwise Tetris/GeneratedSoundBanks/Wwise_IDs.h
688cf9821085a7f7888b327fa2f40732ba95e74a
[ "MIT" ]
permissive
Berklee-Game-Audio/Unity-Wwise-Tetris
bd166fe0f4305c5e116b3dfd6baa31626c9daa66
8c346e9b18b3d1a19cbf6f04ab6358d2a990f378
refs/heads/master
2023-06-08T12:06:52.879933
2021-11-29T00:33:43
2021-11-29T00:33:43
170,428,965
1
0
null
null
null
null
UTF-8
C++
false
false
4,301
h
///////////////////////////////////////////////////////////////////////////////////////////////////// // // Audiokinetic Wwise generated include file. Do not edit. // ///////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __WWISE_IDS_H__ #define __WWISE_IDS_H__ #include <AK/SoundEngine/Common/AkTypes.h> namespace AK { namespace EVENTS { static const AkUniqueID CLEAR_ROW = 1870373793U; static const AkUniqueID FLIP_SHAPE = 2497998238U; static const AkUniqueID GAME_LOADED = 2238459845U; static const AkUniqueID GAME_START = 733168346U; static const AkUniqueID LAND_SHAPE = 3742617664U; static const AkUniqueID MAIN_MENU = 2005704188U; static const AkUniqueID MOVE_SHAPE_LEFT = 1146992660U; static const AkUniqueID MOVE_SHAPE_RIGHT = 898688307U; static const AkUniqueID PAUSE_GAME = 528278262U; static const AkUniqueID PAUSE_RELEASE = 1119896719U; static const AkUniqueID ROUND_LOSE = 3411202357U; static const AkUniqueID ROUND_WIN = 361697008U; static const AkUniqueID STAGE_COMPLETE = 3435819489U; } // namespace EVENTS namespace STATES { namespace GAMEPLAY_STATE { static const AkUniqueID GROUP = 762757699U; namespace STATE { static const AkUniqueID GAMEPLAY = 89505537U; static const AkUniqueID MENU = 2607556080U; static const AkUniqueID NONE = 748895195U; } // namespace STATE } // namespace GAMEPLAY_STATE } // namespace STATES namespace SWITCHES { namespace LEVEL { static const AkUniqueID GROUP = 2782712965U; namespace SWITCH { static const AkUniqueID LEVEL_1 = 1290008369U; static const AkUniqueID LEVEL_2 = 1290008370U; static const AkUniqueID LEVEL_3 = 1290008371U; static const AkUniqueID LEVEL_4 = 1290008372U; static const AkUniqueID LEVEL_5 = 1290008373U; static const AkUniqueID LEVEL_6 = 1290008374U; static const AkUniqueID LEVEL_7 = 1290008375U; static const AkUniqueID LEVEL_8 = 1290008376U; static const AkUniqueID LEVEL_9 = 1290008377U; static const AkUniqueID LEVEL_10 = 1004413459U; } // namespace SWITCH } // namespace LEVEL namespace STAGES { static const AkUniqueID GROUP = 936729656U; namespace SWITCH { static const AkUniqueID STAGE_01 = 344719509U; static const AkUniqueID STAGE_02 = 344719510U; static const AkUniqueID STAGE_03 = 344719511U; } // namespace SWITCH } // namespace STAGES } // namespace SWITCHES namespace GAME_PARAMETERS { static const AkUniqueID LEVEL_NUMBER = 4014985419U; static const AkUniqueID MAX_HEIGHT = 3817197105U; static const AkUniqueID NOTE = 849560917U; static const AkUniqueID SCORE = 2398231425U; static const AkUniqueID STAGE_NUMBER = 14811615U; } // namespace GAME_PARAMETERS namespace TRIGGERS { static const AkUniqueID CLEAR_ROW_TRIGGER = 3249509688U; static const AkUniqueID FLIP_SHAPE_TRIGGER = 750315547U; static const AkUniqueID LAND_SHAPE_TRIGGER = 2925865545U; static const AkUniqueID MOVE_SHAPE_LEFT_TRIGGER = 1337504389U; static const AkUniqueID MOVE_SHAPE_RIGHT_TRIGGER = 2830854102U; } // namespace TRIGGERS namespace BANKS { static const AkUniqueID INIT = 1355168291U; static const AkUniqueID TETRIS_SOUNDBANK = 3052682920U; } // namespace BANKS namespace BUSSES { static const AkUniqueID MASTER_AUDIO_BUS = 3803692087U; } // namespace BUSSES namespace AUDIO_DEVICES { static const AkUniqueID NO_OUTPUT = 2317455096U; static const AkUniqueID SYSTEM = 3859886410U; } // namespace AUDIO_DEVICES }// namespace AK #endif // __WWISE_IDS_H__
[ "msweet37@gmail.com" ]
msweet37@gmail.com
ed0ec3ce3a9c6eea3a3feaf53428dfe555f4e972
e62b72f6fcdfe40575997e237d8b5bd05b00236f
/bullet2.cpp
cd1800f48a7b5a0f9908e516a9c20b68c0735548
[]
no_license
COP3503Checkers/GameBox
8614849f0f897f15779a7c7e667594b3737d60ce
9ef792b81c6e6670fd4a1ec524e789ed7bf74450
refs/heads/master
2021-06-06T17:28:01.440221
2016-04-20T08:39:08
2016-04-20T08:39:08
54,787,583
1
0
null
null
null
null
UTF-8
C++
false
false
1,672
cpp
#include "bullet2.h" #include "enemy.h" #include "enemy2.h" #include "galaga.h" #include <QTimer> #include <QGraphicsScene> #include <QList> #include <typeinfo> //we can access global object Galaga extern Galaga * galaga; BulletTwo::BulletTwo(QGraphicsItem * parent):QObject(), QGraphicsPixmapItem(parent) { //making bullet setPixmap(QPixmap(":/images/bullet2.png")); //connecting timer(signal) to slot QTimer * timer = new QTimer(); connect(timer,SIGNAL(timeout()),this,SLOT(move())); //every 50 ms the bullet will move timer->start(50); } void BulletTwo::move() { //checking to see if it collides with enemy QList<QGraphicsItem*> colliding = collidingItems(); for(int i = 0; i<colliding.size(); i++){ if(typeid(*(colliding[i])) == typeid(Enemy)){ //increases the score galaga->score->increaseScore(); //remove both scene()->removeItem(colliding[i]); scene()->removeItem(this); //delete both delete colliding[i]; delete this; return; } if(typeid(*(colliding[i])) == typeid(EnemyTwo)){ //increases the score galaga->score->increaseScore(); //remove both scene()->removeItem(colliding[i]); scene()->removeItem(this); //delete both delete colliding[i]; delete this; return; } } //move bullet up setPos(x(),y()-20); if (pos().y() < 0){ scene()->removeItem(this); delete this; } }
[ "cristo.silva@yahoo.com" ]
cristo.silva@yahoo.com
46283e886c729602b2db674ee6b79674f383ca7c
0893cd08598d6829d27e2c0a15012eb7e0ecbbd5
/librapid/cxxblas/level2extensions/her.tcc
86972ab2c9c94dcbad8e3d74507e374953d4be31
[ "MIT", "BSD-3-Clause", "BSD-2-Clause" ]
permissive
LibRapid/librapid
813b8cf89b2fb15618a017bd1b7dccf0dac9b794
4f60eeef8b2d834315d1a9ca6ddd57cd7c093794
refs/heads/master
2023-09-01T22:02:48.706683
2023-08-04T00:48:23
2023-08-04T00:48:23
370,833,810
137
9
MIT
2023-09-11T10:40:54
2021-05-25T21:36:23
C++
UTF-8
C++
false
false
2,262
tcc
/* * Copyright (c) 2009, Michael Lehn * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3) Neither the name of the FLENS development group nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER 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. */ #ifndef CXXBLAS_LEVEL2EXTENSIONS_HER_TCC #define CXXBLAS_LEVEL2EXTENSIONS_HER_TCC 1 #include <complex> #include "cxxblas/cxxblas.h" namespace cxxblas { template<typename IndexType, typename ALPHA, typename VX, typename MA> void her(StorageOrder order, StorageUpLo upLo, Transpose conjugateA, IndexType n, const ALPHA &alpha, const VX *x, IndexType incX, MA *A, IndexType ldA) { CXXBLAS_DEBUG_OUT("her_generic (extension)"); if (incX < 0) { x -= incX * (n - 1); } her_generic(order, upLo, conjugateA, n, alpha, x, incX, A, ldA); } } // namespace cxxblas #endif // CXXBLAS_LEVEL2EXTENSIONS_HER_TCC
[ "pencilcaseman@gmail.com" ]
pencilcaseman@gmail.com
ee6f89ae191e29ad854916e955e1d8cd2663b0cf
d647aceb4672ba8f5135237082fdd828ba4024f6
/BackpackMega_EepromGpsGprs/src/mygprs.cpp
6013be9a8386f0607a4bedba0cea2823dcf84bc9
[]
no_license
alextrof94/PIO_Arduino
645aac728e96f93699be496d5fc200c97de93a01
2d4b9f12b36d4111afe06160826cec037430f0db
refs/heads/master
2021-11-27T01:34:38.402226
2021-09-08T07:18:32
2021-09-08T07:18:32
228,223,751
0
0
null
null
null
null
UTF-8
C++
false
false
21
cpp
void mygprsWork(){ }
[ "alextrof94@gmail.com" ]
alextrof94@gmail.com
98cc5c938b946f2a81ddbb7059bf312f16a6f745
4f6175ab4c768c7632482e4082916b69a0811db7
/lnetlib/lnetlib/encryption.cpp
11459bb2f1016b911dd1f10421bf07ef8eddb2c0
[ "MIT" ]
permissive
cpp11nullptr/lnetlib
47e82fe451da2d04c556206872d7476c8c2d4615
cf29b7a6f209e1d174e16992188d25e589c5e181
refs/heads/master
2016-08-11T14:58:04.112376
2016-02-16T15:09:07
2016-02-16T15:09:07
44,202,602
40
9
null
null
null
null
UTF-8
C++
false
false
3,365
cpp
/* The MIT License (MIT) Copyright (c) 2015 Ievgen Polyvanyi 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 "encryption.h" namespace lnetlib { encryption::encryption() : _enabled(false), _method(encryption_method::tlsv11), _verify_mode(ssl_verify_none), _context(static_cast<ssl_context::method>(_method)) { } encryption::~encryption() { } void encryption::init(encryption_method method) { _last_error.clear(); _method = method; _ca_filename.clear(); _cert_filename.clear(); _private_key_filename.clear(); _verify_mode = ssl_verify_none; _verify_callback = verify_callback(); _context = std::move(ssl_context(static_cast<ssl_context::method>(_method))); } bool encryption::is_enabled() const { return _enabled; } void encryption::set_enabled(bool enabled) { _enabled = enabled; } std::string encryption::ca_filename() const { return _ca_filename; } void encryption::set_ca_filename(const std::string& filename) { _last_error.clear(); if (!filename.empty()) { auto file = helper::read_binary_file(filename); if (file.second > 0) { _context.add_certificate_authority(const_buffer(file.first.get(), file.second)); } else { _last_error = "Can't read CA file"; } } } std::string encryption::cert_filename() const { return _cert_filename; } void encryption::set_cert_filename(const std::string& filename) { _cert_filename = filename; _context.use_certificate_file(filename, ssl_context::pem); } std::string encryption::private_key_filename() const { return _private_key_filename; } void encryption::set_private_key_filename(const std::string& filename) { _private_key_filename = filename; _context.use_private_key_file(filename, ssl_context::pem); } int encryption::verify_mode() const { return _verify_mode; } void encryption::set_verify_mode(int mode) { _verify_mode = mode; } void encryption::set_verify_callback(verify_callback callback) { _verify_callback = callback; } bool encryption::verify_certificate(bool preverified, verify_context& context) { if (_verify_callback) { return _verify_callback(preverified, context.native_handle()); } return preverified; } std::string encryption::last_error() const { return _last_error; } encryption::ssl_context& encryption::context() { return _context; } }
[ "cpp11nullptr@gmail.com" ]
cpp11nullptr@gmail.com
ff28f2055f9fbac430b23bbeb9a8038aa4cb6684
5f854aa5e72c69132c85e8d74909c89ac043f188
/1.euler/欧拉前50题/027/27.cpp
9d68c114149839aa598e6932634578e5a881e385
[]
no_license
ldc0111/shuatiku
02f92bc38eb50d3af7a1f35fa34046d22100f84d
8e7ec6e7c1311dcef0fac8fd824206bfa0cc4254
refs/heads/master
2020-03-25T23:27:41.574572
2019-02-24T07:00:41
2019-02-24T07:00:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,280
cpp
/************************************************************************* > File Name: 27.cpp > Author: > Mail: > Created Time: 2018年08月06日 星期一 10时23分01秒 ************************************************************************/ #include <stdio.h> #include <limits.h> #include <inttypes.h> #include <time.h> #include <stdlib.h> #define MAX_N 1000 #define MAX_M 2500 #define R_M_TEST_ROUND 30 int32_t prime[MAX_M + 5] = {0}; int32_t gcd(int32_t a, int32_t b) { if (!b) return a; return gcd(b, a % b); } bool R_M_TEST(int32_t x) {//测试发 if (x <= 1) return false;//如果小于等于1不用测试 int64_t a, m, ans; for (int32_t i = 0; i < R_M_TEST_ROUND; i++) {//测试轮数 a = (rand() % (x - 1)) + 1;//生成随机数 ans = 1;//初始化值 m = x - 1;//初始化值 while (m) {//a^(x - 1)mod x == 1 if (m % 2) ans = (ans * a) % x;//快速幂 a = (a * a) % x; m /= 2; } if (ans != 1) return false;//如果不等于1返回0 } return true;//等于返回失败 } int32_t HowManyPrime(int32_t a, int32_t b) { int32_t i = 0; while (R_M_TEST(i * i + a * i + b)) ++i;//统计从0开始素数的个数 return i;//开始 } int32_t main() { srand(time(0)); prime[1] = INT_MAX; for (int32_t i = 2; i <= MAX_M; i++) if (!prime[i]) for (int32_t j = i; j <= MAX_M; j += i) if (!prime[j]) prime[j] = i;//素数筛 int32_t maxNum = 40, tempNum, result = 0; for (int32_t a = 1 - MAX_N; a < MAX_N; a++) for (int32_t b = (a < 0 ? -a + 1 : 2); b < MAX_N; b++) {//b的遍历范围 //剪枝剪枝开始 if (prime[b] != b) continue;//根据结论,不是素数返回 if (prime[b + a + 1] != b + a + 1) continue;//不是素数返回 if (a > 0 && b > 0 && prime[gcd(a, b)] <= maxNum) continue;//结论3 //剪枝结束 tempNum = HowManyPrime(a, b);//返回生成的最大素数的个数 if (tempNum > maxNum) {//如果大于就交换 result = a * b;//计算积 maxNum = tempNum; } } printf("%d\n", result); return 0; }
[ "913361300@qq.com" ]
913361300@qq.com
3eaee53e94e9a8c39c30c622ccba640e3b3a5768
30178ea25af7b8c6c28ce5d03a1cf3c2fc8a37d7
/gfx/skia/skia/src/core/SkTime.cpp
841ea331146337a29d8a9c03c42a96588744e08d
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
weilonge/gecko-dev
8bde51f637b0481008ab04682e46188ef9dc4ce2
046e8897a90570889fec893493a4759aadfac554
refs/heads/master
2021-01-21T03:41:32.816543
2016-03-15T00:55:56
2016-03-15T00:55:56
33,717,822
0
0
NOASSERTION
2019-11-10T05:38:23
2015-04-10T08:37:13
null
UTF-8
C++
false
false
3,676
cpp
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkOncePtr.h" #include "SkString.h" #include "SkTime.h" #include "SkTypes.h" void SkTime::DateTime::toISO8601(SkString* dst) const { if (dst) { int timeZoneMinutes = SkToInt(fTimeZoneMinutes); char timezoneSign = timeZoneMinutes >= 0 ? '+' : '-'; int timeZoneHours = SkTAbs(timeZoneMinutes) / 60; timeZoneMinutes = SkTAbs(timeZoneMinutes) % 60; dst->printf("%04u-%02u-%02uT%02u:%02u:%02u%c%02d:%02d", static_cast<unsigned>(fYear), static_cast<unsigned>(fMonth), static_cast<unsigned>(fDay), static_cast<unsigned>(fHour), static_cast<unsigned>(fMinute), static_cast<unsigned>(fSecond), timezoneSign, timeZoneHours, timeZoneMinutes); } } #ifdef SK_BUILD_FOR_WIN32 #include "Windows.h" void SkTime::GetDateTime(DateTime* dt) { if (dt) { SYSTEMTIME st; GetSystemTime(&st); dt->fTimeZoneMinutes = 0; dt->fYear = st.wYear; dt->fMonth = SkToU8(st.wMonth); dt->fDayOfWeek = SkToU8(st.wDayOfWeek); dt->fDay = SkToU8(st.wDay); dt->fHour = SkToU8(st.wHour); dt->fMinute = SkToU8(st.wMinute); dt->fSecond = SkToU8(st.wSecond); } } #else // SK_BUILD_FOR_WIN32 #include <time.h> void SkTime::GetDateTime(DateTime* dt) { if (dt) { time_t m_time; time(&m_time); struct tm* tstruct; tstruct = gmtime(&m_time); dt->fTimeZoneMinutes = 0; dt->fYear = tstruct->tm_year + 1900; dt->fMonth = SkToU8(tstruct->tm_mon + 1); dt->fDayOfWeek = SkToU8(tstruct->tm_wday); dt->fDay = SkToU8(tstruct->tm_mday); dt->fHour = SkToU8(tstruct->tm_hour); dt->fMinute = SkToU8(tstruct->tm_min); dt->fSecond = SkToU8(tstruct->tm_sec); } } #endif // SK_BUILD_FOR_WIN32 #if defined(_MSC_VER) // TODO: try std::chrono again with MSVC 2015? #include <intrin.h> SK_DECLARE_STATIC_ONCE_PTR(double, ns_per_tick); double SkTime::GetNSecs() { uint64_t ticks = __rdtsc(); return ticks * *ns_per_tick.get([]{ LARGE_INTEGER khz; // The docs say this returns Hz, but it returns KHz. QueryPerformanceFrequency(&khz); return new double(1e6 / khz.QuadPart); }); } #elif defined(__MACH__) // TODO: fold into std::chrono when available? #include <mach/mach_time.h> SK_DECLARE_STATIC_ONCE_PTR(double, ns_per_tick); double SkTime::GetNSecs() { uint64_t ticks = mach_absolute_time(); return ticks * *ns_per_tick.get([]{ mach_timebase_info_data_t timebase; (void)mach_timebase_info(&timebase); return new double(timebase.numer * 1.0 / timebase.denom); }); } #elif defined(SK_BUILD_FOR_UNIX) || defined(SK_BUILD_FOR_ANDROID) #include <time.h> double SkTime::GetNSecs() { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) { return 0.0; } return ts.tv_sec * 1e9 + ts.tv_nsec; } #else // This std::chrono code looks great on Linux and Android, // but MSVC 2013 returned mostly garbage (0ns times, etc). #include <chrono> double SkTime::GetNSecs() { auto now = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::nano> ns = now.time_since_epoch(); return ns.count(); } #endif
[ "lsalzman@mozilla.com" ]
lsalzman@mozilla.com
4f01157c895968f2ceee8eadbd5dba8be2425451
1bfd698b2c1f5760734dc42632fe54c65a286086
/IfcPlusPlus/src/ifcpp/IFC4/include/IfcMotorConnectionTypeEnum.h
9a78ffbc52efef531fb2367cf88478240ebe3426
[]
no_license
wartburgritter0/old_IfcPlusPlus
c0bd0b784396c100d0d96fc7af6146a0325a9e1b
d0f9d81462b295990d3eb83c9c406d520840330e
refs/heads/master
2021-05-27T21:54:14.456425
2014-06-03T21:23:14
2014-06-03T21:23:14
19,681,159
1
0
null
null
null
null
UTF-8
C++
false
false
1,623
h
/* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library 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 * OpenSceneGraph Public License for more details. */ #pragma once #include <vector> #include <map> #include <sstream> #include <string> #include "ifcpp/model/shared_ptr.h" #include "ifcpp/model/IfcPPObject.h" // TYPE IfcMotorConnectionTypeEnum = ENUMERATION OF (BELTDRIVE ,COUPLING ,DIRECTDRIVE ,USERDEFINED ,NOTDEFINED); class IfcMotorConnectionTypeEnum : virtual public IfcPPObject { public: enum IfcMotorConnectionTypeEnumEnum { ENUM_BELTDRIVE, ENUM_COUPLING, ENUM_DIRECTDRIVE, ENUM_USERDEFINED, ENUM_NOTDEFINED }; IfcMotorConnectionTypeEnum(); IfcMotorConnectionTypeEnum( IfcMotorConnectionTypeEnumEnum e ) { m_enum = e; } ~IfcMotorConnectionTypeEnum(); virtual const char* classname() const { return "IfcMotorConnectionTypeEnum"; } virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const; static shared_ptr<IfcMotorConnectionTypeEnum> createObjectFromStepData( const std::string& arg ); IfcMotorConnectionTypeEnumEnum m_enum; };
[ "fabian.gerold@gmail.com@06f6d6f3-f2e0-f239-6e86-ba6a5d17d3a5" ]
fabian.gerold@gmail.com@06f6d6f3-f2e0-f239-6e86-ba6a5d17d3a5
88e1cdebec2dfd11c22e3540e81dad409eb1cd97
c5825e4bce4b7dc06690b46aed6e8b4738904d9d
/BaseCode/hook/inline/HookInternal.h
634c96d514201a213420cdb45f4a7e01a59305b9
[]
no_license
deathmemory/reportTest
73e95b77bb6f993a8678f30ec5c27f822f9e9464
e4ef7d97d15c279081775fc7f938bae4890bd028
refs/heads/master
2020-06-05T13:18:23.365897
2013-05-28T16:57:34
2013-05-28T16:57:34
10,100,185
0
1
null
null
null
null
GB18030
C++
false
false
4,932
h
#pragma once #define _HOOK_INTERNAL #pragma pack(1) #include <windows.h> #include <shlwapi.h> #include "../../VM_MACRO/VMP.H" //#include "../../common/commondef.h" #include "../../dasm/disassemble.h" #include "../../system/System.hpp" #include "../../String/STRING_EX.h" using namespace STRING_EX; #pragma comment(lib,"shlwapi") #pragma warning(disable:4312) #pragma warning(disable:4099) #pragma warning(disable:4311) #pragma warning(disable:4102) #define NAKED_ALLOC(size) __asm SUB ESP,size #define NAKED_FREE(size) __asm ADD ESP,size #define LEAVE_EX(argCount) __asm LEAVE \ __asm RET argCount*4 #define LEAVE_WITH_ADDR(argCount,retAddr)__asm LEAVE \ __asm PUSH retAddr \ __asm POP DWORD PTR[ESP] \ __asm RET argCount*4 #define FUNCTION_HEAD __asm MOV EDI, EDI __asm PUSH EBP __asm MOV EBP, ESP #define FUNCTION_ENTRY(argCount) __asm SUB ESP,argCount*4+4 __asm MOV EDI, EDI __asm PUSH EBP __asm MOV EBP, ESP #define GET_RET_ADDR(DEST)__asm PUSH DWORD PTR [EBP+4] \ __asm LEA EAX,DEST \ __asm POP DWORD PTR [EAX] #define JMP_MAKE_CALL_ADDR(entry,BackEIP)__asm MOV EAX,BackEIP \ __asm MOV [EBP+4],EAX \ __asm MOV EAX,entry \ __asm JMP EAX #define JMP_MAKE_CALL_PTR(entry,BackEIP)__asm MOV EAX,BackEIP \ __asm MOV [EBP+4],EAX \ __asm LEA EAX,entry \ __asm JMP EAX #define PUSHALL __asm pushad __asm pushfd #define POPALL __asm popfd __asm popad typedef struct tagRESTORE_CODE { int size; DWORD RestoreCode[10]; DWORD JmpBack[10]; void SaveRestoreCode(DWORD hookAddr,BYTE *RestoreBuff,BOOL brunRestore); }RESTORE_CODE; enum SEARCH_PAGE_TYPE { SEARCH_PAGE_RW, SEARCH_PAGE_EXEC }; typedef BOOL (CALLBACK *_HBCallBack)( PEXCEPTION_POINTERS ExceptionInfo ); typedef LONG (CALLBACK *_VirtualVectoredHandler)( PEXCEPTION_POINTERS ExceptionInfo ); typedef struct tagHOOK_INTERNAL { static DWORD SearchAndPlace(BYTE *imageBase,BYTE *dSearch,BYTE *dReplace,DWORD ReplaceLen,BOOL replaceAll); static DWORD SearchKeyCode(DWORD Pid,DWORD searchFrom,char *KeyCode,DWORD searchSize=0); static DWORD SearchKeyCode(DWORD Pid,char *KeyCode,SEARCH_PAGE_TYPE stype); static DWORD SearchKeyCode(DWORD Pid,char *KeyCode,VOID* searchFrom,DWORD rang); static ULONG ConvertHexToDec(CHAR* szHex, BYTE nHexLen); static DWORD SearchKeyStr(HANDLE hp,BYTE* pbegin,CHAR *fcode,ULONG lenCode,ULONG searchLen,SEARCH_PAGE_TYPE stype); _HBCallBack m_HBCallBack; _VirtualVectoredHandler m_virtual_function; DWORD OldRet; DWORD *pHookAddr; //hook地址 RESTORE_CODE RestoreCodeMem;//保存原指令 RESTORE_CODE RestoreCodeFromFile;//原指令 DWORD *pHookBack; //返回地址 DWORD *pCallBack; //回调函数 DWORD OffsetByte; DWORD *GetFunRealAddr(DWORD *funaddr); BYTE pHookAddrCode[512]; HANDLE hProcess; BOOL bRunRestoreCode; HINSTANCE ModuleBase; tagHOOK_INTERNAL(); void UnhookAddressCurrentProcess(BOOL fromFile=FALSE); void HookAddressCurrentProcess(); void UnhookAddress(BOOL fromFile=FALSE); void HookAddress(); void InitSoftBP(DWORD* addr,DWORD* newFun); DWORD UnhookCurrentProcessHB(); DWORD InitHookCurrentProcessHB(VOID *HookBaseAddr,_HBCallBack HBCallBack); DWORD InitHookCurrentProcess(DWORD offsetbyte,VOID *HookBaseAddr,VOID *newFun,BOOL runRestoreCode); DWORD InitHookCurrentProcess(DWORD offsetbyte,TCHAR *module,CHAR *funname,VOID *newFun,BOOL runRestoreCode); void InitHook(HANDLE _hProcess,DWORD offsetbyte,TCHAR *module,char *funname,void *newFun,BOOL runRestoreCode); void InitHook(HANDLE _hProcess,DWORD offsetbyte,TCHAR *module,char *funname,DWORD funOffset,void *newFun,BYTE *restorCode,int len,BOOL runRestoreCode); void InitHook(HANDLE _hProcess,DWORD offsetbyte,TCHAR *module,void *HookBaseAddr,void *newFun,BOOL runRestoreCode); BOOL InitHookKeyCode(HANDLE _hProcess,DWORD offsetbyte,TCHAR *module,DWORD *newFunc,char* findCode,BOOL runRestoreCode); void ReadRestoreCodeFromFile(TCHAR *module); VOID InitRestore(); typedef HANDLE (WINAPI *_CreateEventA)(LPSECURITY_ATTRIBUTES lpEventAttributes,BOOL bManualReset,BOOL bInitialState,LPCSTR lpName); typedef BOOL (WINAPI *_SetEvent)(HANDLE hEvent); typedef BOOL (WINAPI *_ResetEvent)(HANDLE hEvent); typedef DWORD (WINAPI *_WaitForSingleObject)(HANDLE hHandle,DWORD dwMilliseconds); _CreateEventA m_CreateEvent; #define IT_SetEvent(tmpfun,_this,h) __asm nop /*tmpfun = (*_this)->m_SetEvent;\ __asm PUSH h \ __asm CALL tmpfun*/ _SetEvent m_SetEvent; #define IT_ResetEvent(tmpfun,_this,h) __asm nop /*tmpfun = (*_this)->m_ResetEvent;\ __asm PUSH h \ __asm CALL tmpfun*/ _ResetEvent m_ResetEvent; #define IT_WaitForSingleObject(tmpfun,_this,h,t) __asm nop /*tmpfun = (*_this)->m_WaitForSingleObject;\ __asm PUSH t \ __asm PUSH h \ __asm CALL tmpfun*/ _WaitForSingleObject m_WaitForSingleObject; HANDLE m_hEvent; }HOOK_INTERNAL; /* void __declspec(naked)RetBack() { __asm PUSH pHookAddr __asm RET } void __declspec(naked)JmpBack() { __asm MOV EAX,pHookAddr __asm JMP EAX } */ #pragma pack()
[ "DeathMemory@163.com" ]
DeathMemory@163.com
a297a2d6eb5b9ad5d9eb737c474007d1216d00b8
b179ee1c603139301b86fa44ccbbd315a148c47b
/engine/effects/include/MappingEffect.hpp
d680454e456e6cf086e77aee65f441cb68fcfd54
[ "MIT", "Zlib" ]
permissive
prolog/shadow-of-the-wyrm
06de691e94c2cb979756cee13d424a994257b544
cd419efe4394803ff3d0553acf890f33ae1e4278
refs/heads/master
2023-08-31T06:08:23.046409
2023-07-08T14:45:27
2023-07-08T14:45:27
203,472,742
71
9
MIT
2023-07-08T14:45:29
2019-08-21T00:01:37
C++
UTF-8
C++
false
false
953
hpp
#pragma once #include "Effect.hpp" enum struct MappingType { MAPPING_TYPE_FORGET = 0, MAPPING_TYPE_MAP = 1, MAPPING_TYPE_MAP_ALL = 2 }; class MappingEffect : public Effect { public: virtual std::string get_effect_identification_message(std::shared_ptr<Creature> creature) const override; virtual Effect* clone() override; protected: virtual void map(MapPtr map, const MappingType mt); virtual bool effect_blessed(std::shared_ptr<Creature> creature, ActionManager * const am, const Coordinate& affected_coordinate, TilePtr affected_tile) override; virtual bool effect_uncursed(std::shared_ptr<Creature> creature, ActionManager * const am, const Coordinate& affected_coordinate, TilePtr affected_tile) override; virtual bool effect_cursed(std::shared_ptr<Creature> creature, ActionManager * const am, const Coordinate& affected_coordinate, TilePtr affected_tile) override; std::string mapping_msg; };
[ "jcd748@mail.usask.ca" ]
jcd748@mail.usask.ca
d450b7d5a7b5506a437fc1addb2c1bf382a92acf
6171256bfc049ab44d0f4fcab0edc87757cac520
/Semester 2/Bank_Management_System Repo/AdminHome.cpp
7970bca2e361e365b95c317e571e6be710ad4150
[]
no_license
HaiderSultanArc/AcademicProjects
39ef3cd8ccf30957d67424ef0c5c84c02ee439c9
bb631d7abb2a184e8b69c45d211455b4e19041ba
refs/heads/master
2023-04-10T08:41:41.726899
2021-04-24T19:03:35
2021-04-24T19:03:35
320,339,440
7
1
null
null
null
null
UTF-8
C++
false
false
1,381
cpp
#include "AdminHome.h" using namespace SigninForm; bool AdminHome::isValidName(String^ name) { string strName = marshal_as<string>(name); for (int ch = 0; ch < strName.length(); ch++) { if (!isalpha(strName[ch]) && strName[ch] != 32) { return false; } } return true; } bool AdminHome::isValidEmail(String^ email) { email = email->ToLower(); if (email->Contains("@")) { if (email->EndsWith(".com")) { return true; } else { return false; } } else { return false; } } bool AdminHome::isValidAccType(String^ accType) { accType = accType->ToLower(); if (accType->Equals("loan")) { return true; } else if (accType->Equals("saving")) { return true; } else { return false; } } bool AdminHome::isValidPhone(String^ phone) { if (phone->Length == 13) { if (phone->StartsWith("+92")) { string strPhone = marshal_as<string>(phone); for (int ch = 1; ch < strPhone.length(); ch++) { if (!isdigit(strPhone[ch])) { return false; } } return true; } else { return false; } } else { return false; } } bool AdminHome::isValidAmmount(String^ ammount) { if (ammount->Length <= 9) { string strAccNum = marshal_as<string>(ammount); for (int digit = 0; digit < strAccNum.length(); digit++) { if (!isdigit(strAccNum[digit])) { return false; } } return true; } else { return false; } }
[ "haidersultanarc@gmail.com" ]
haidersultanarc@gmail.com
ee597f3bbbbf19b47f60e159c5a29c362cb5740a
72f9b35aedec21866d0896694039e33b0b47331e
/blocks/statements/rela_pressions/factor.hpp
b980f2e62905b87c3bf36f075be99168c920be16
[]
no_license
HelmetBro/custom_compiler
a32d6888501eb0e168430d2b6eef79faaffcce37
8502750952c1203e79705e20ca89eedae35df710
refs/heads/master
2022-12-18T22:38:48.829733
2020-09-19T08:21:42
2020-09-19T08:21:42
165,970,554
0
0
null
null
null
null
UTF-8
C++
false
false
461
hpp
// // Created by EricP on 1/22/2019. // #ifndef FACTOR_H_ #define FACTOR_H_ #include "designator.hpp" #include "expression.hpp" #include "../../../lex_analyzer.hpp" #include "../function_call.hpp" class designator; class function_call; class factor{ public: //only one may be assigned designator * des = nullptr; int number; expression * exp = nullptr; function_call * func_call = nullptr; factor(); void print(); }; #endif
[ "ericparsons@live.com" ]
ericparsons@live.com
56a46640c8a975e74024e02d24b0be5b03e4b59a
72f13ab1fd09e22c464e452e27508392854a46d8
/src/Components/Svg.re
ca172d792628af8797dc2dc956de6b153d76e71e
[]
no_license
chattyzilla-labs/reason-chat-widget
a3ae0766af4e6c57235f1d2ea111787b34836077
987f2b73b42f00014be9691480314342f57607ac
refs/heads/master
2023-01-28T05:29:04.167451
2020-01-21T01:59:34
2020-01-21T01:59:34
234,832,446
1
0
null
2023-01-06T01:28:50
2020-01-19T03:09:06
C++
UTF-8
C++
false
false
2,895
re
open Styles.Icons; let sendIcon = <svg version="1.1" className={icon} xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="37.393px" height="37.393px" viewBox="0 0 37.393 37.393" enableBackground="new 0 0 37.393 37.393"> <g id="Layer_2"> <path d="M36.511,17.594L2.371,2.932c-0.374-0.161-0.81-0.079-1.1,0.21C0.982,3.43,0.896,3.865,1.055,4.241l5.613,13.263 L2.082,32.295c-0.115,0.372-0.004,0.777,0.285,1.038c0.188,0.169,0.427,0.258,0.67,0.258c0.132,0,0.266-0.026,0.392-0.08 l33.079-14.078c0.368-0.157,0.607-0.519,0.608-0.919S36.879,17.752,36.511,17.594z M4.632,30.825L8.469,18.45h8.061 c0.552,0,1-0.448,1-1s-0.448-1-1-1H8.395L3.866,5.751l29.706,12.757L4.632,30.825z" /> </g> </svg>; let emojiIcon = <svg className={emojiIcon} version="1.1" id="Layer_2" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="37.393px" height="37.393px" viewBox="0 0 37.393 37.393" enableBackground="new 0 0 37.393 37.393" > <g> <path d="M18.696,37.393C8.387,37.393,0,29.006,0,18.696C0,8.387,8.387,0,18.696,0c10.31,0,18.696,8.387,18.696,18.696 C37.393,29.006,29.006,37.393,18.696,37.393z M18.696,2C9.49,2,2,9.49,2,18.696c0,9.206,7.49,16.696,16.696,16.696 c9.206,0,16.696-7.49,16.696-16.696C35.393,9.49,27.902,2,18.696,2z" /> </g> <g> <circle cx="12.379" cy="14.359" r="1.938" /> </g> <g> <circle cx="24.371" cy="14.414" r="1.992" /> </g> <g> <path d="M18.035,27.453c-5.748,0-8.342-4.18-8.449-4.357c-0.286-0.473-0.135-1.087,0.338-1.373 c0.471-0.286,1.084-0.136,1.372,0.335c0.094,0.151,2.161,3.396,6.74,3.396c4.713,0,7.518-3.462,7.545-3.497 c0.343-0.432,0.973-0.504,1.405-0.161c0.433,0.344,0.505,0.973,0.161,1.405C27.009,23.374,23.703,27.453,18.035,27.453z" /> </g> </svg>; let fileIcon = <svg version="1.1" xmlns="http://www.w3.org/2000/svg" className={icon} x="0px" y="0px" width="24px" height="24px" viewBox="0 0 37.393 37.393" enableBackground="new 0 0 37.393 37.393" > <path d="M20.807 10.22l-2.030-2.029-10.15 10.148c-1.682 1.681-1.682 4.408 0 6.089s4.408 1.681 6.090 0l12.18-12.178c2.804-2.802 2.804-7.346 0-10.148-2.802-2.803-7.347-2.803-10.149 0l-12.788 12.787c-0.009 0.009-0.019 0.018-0.027 0.026-3.909 3.909-3.909 10.245 0 14.153 3.908 3.908 10.246 3.908 14.156 0 0.009-0.009 0.016-0.018 0.026-0.027l0.001 0.001 8.729-8.728-2.031-2.029-8.729 8.727c-0.009 0.008-0.018 0.018-0.026 0.026-2.784 2.783-7.312 2.783-10.096 0-2.783-2.783-2.783-7.31 0-10.093 0.010-0.009 0.019-0.018 0.028-0.026l-0.001-0.002 12.79-12.786c1.678-1.679 4.411-1.679 6.090 0s1.678 4.411 0 6.089l-12.18 12.178c-0.56 0.56-1.47 0.56-2.030 0-0.559-0.559-0.559-1.47 0-2.029l10.15-10.149z"></path> </svg>
[ "narjune131@gmail.com" ]
narjune131@gmail.com
2dbe90d3e94a8897c6be99954f031ba4169e4378
1d04a98d3b6f6273a08d25a20f85b310f87921a3
/include/kshortestpaths/2heap.h
f5bbb3d734815c074e5727ea57ce51da8fa8b598
[]
no_license
gyankos/kShortestPaths
eb3578f023ebad13b9da1c2c759de84c17e07112
657c513a04340902def5ead51729a15410c13297
refs/heads/main
2023-05-13T02:52:28.925125
2021-06-10T13:38:10
2021-06-10T13:38:10
375,612,701
1
1
null
null
null
null
UTF-8
C++
false
false
3,894
h
// Implemented by Jon Graehl <jongraehl@earthling.net> // binary max heap with elements packed in [heapStart, heapEnd) // heapEnd - heapStart = number of elements #ifndef kShortestPaths_2heap #define kShortestPaths_2heap template <class T> int heapSize ( T *s, T *e ) { return e - s; } template <class T> void heapAdd ( T *heapStart, T *heapEnd, const T& elt ) // caller is responsbile for ensuring that *heapEnd is allocated and // safe to store the element in (and keeping track of increased size) { T *heap = heapStart - 1; int i = heapEnd - heap; int last = i; while ( (i /= 2) && heap[i] < elt ) { heap[last] = heap[i]; last = i; } heap[last] = elt; } template <class T> static void heapify ( T *heap, int heapSize, int i) // internal routine { T temp = heap[i]; int parent = i, child = 2*i; while ( child < heapSize ) { if ( heap[child] < heap[child+1] ) ++child; if ( !(temp < heap[child] ) ) break; heap[parent] = heap[child]; parent = child; child *= 2; } if ( child == heapSize && temp < heap[child]) { heap[parent] = heap[child]; parent = child; } heap[parent] = temp; } template <class T> void heapPop (T *heapStart, T *heapEnd) { T *heap = heapStart - 1; // to start numbering of array at 1 int heapSize = heapEnd - heapStart; heap[1] = heap[heapSize--]; heapify(heap, heapSize, 1); } template <class T> void heapSort (T *heapStart, T *heapEnd) { heapBuild(heapStart, heapEnd); T *heap = heapStart - 1; // to start numbering of array at 1 T temp; int heapSize = heapEnd - heapStart; for ( int i = heapSize ; i != 1 ; --i ) { temp = heap[1]; heap[1] = heap[i]; heap[i] = temp; heapify(heap, i-1, 1); } } template <class T> void heapAdjustUp ( T *heapStart, T *element) { T *heap = heapStart - 1; int parent, current = element - heap; T temp = heap[current]; while ( current > 1 ) { parent = current / 2; if ( !(heap[parent] < temp) ) break; heap[current] = heap[parent]; current = parent; } heap[current] = temp; } template <class T> void heapBuild ( T *heapStart, T *heapEnd ) { T *heap = heapStart - 1; int size = heapEnd - heapStart; for ( int i = size/2 ; i ; --i ) heapify(heap, size, i); } // shared heap - adding creates copies of any changed nodes template <class T> void treeHeapAdd(T *&heapRoot, T *node) { T *oldRoot = heapRoot; if ( !oldRoot ) { heapRoot = node; node->left = node->right = NULL; node->nDescend = 0; return; } ++oldRoot->nDescend; int goLeft = !oldRoot->left || (oldRoot->right && oldRoot->right->nDescend > oldRoot->left->nDescend); if ( *oldRoot < *node ) { node->left = oldRoot->left; node->right = oldRoot->right; node->nDescend = oldRoot->nDescend; heapRoot = node; if ( goLeft ) treeHeapAdd(node->left, oldRoot); else treeHeapAdd(node->right, oldRoot); } else { if (goLeft) treeHeapAdd(oldRoot->left, node); else treeHeapAdd(oldRoot->right, node); } } template <class T> T *newTreeHeapAdd(T *heapRoot, T *node) { if ( !heapRoot ) { node->left = node->right = NULL; node->nDescend = 0; return node; } T *newRoot = new T(*heapRoot); ++newRoot->nDescend; int goLeft = !newRoot->left || (newRoot->right && newRoot->right->nDescend > newRoot->left->nDescend); if ( *newRoot < *node ) { node->left = newRoot->left; node->right = newRoot->right; node->nDescend = newRoot->nDescend; if ( goLeft ) node->left = newTreeHeapAdd(node->left, newRoot); else node->right = newTreeHeapAdd(node->right, newRoot); return node; } else { if (goLeft) newRoot->left = newTreeHeapAdd(newRoot->left, node); else newRoot->right = newTreeHeapAdd(newRoot->right, node); return newRoot; } } #endif
[ "bergamigiacomo@gmail.com" ]
bergamigiacomo@gmail.com
3dd29b07e0e10b759859f44ec953620a6c51918f
1cacc0d3bfa02a41ca1426e2a25aaa305fd81bd8
/OpenGL_SDL Base Project/Collider.h
a8583b424a0ce6fd98cc5f4a62dbb88f96438647
[]
no_license
Its-Aaron/CPPEngine
5b32125693e7b7050877310d387b463ae156bfb6
8bd19517fbc151a9e39ce5f64bd34daef1582a61
refs/heads/master
2020-04-11T00:43:44.714006
2018-12-13T17:49:43
2018-12-13T17:49:43
161,393,176
0
0
null
null
null
null
UTF-8
C++
false
false
609
h
#ifndef _COLLIDER_H #define _COLLIDER_H #include "Component.h" #include "RigidBody.h" class Collider : public Component { public: Collider(); virtual ~Collider(); bool visible; virtual void Update(float deltaTime); void Init(); COLLIDERTYPE GetType() { return colliderType; } void SetCollided(bool _collided, GameObject* other = nullptr); bool GetCollided() { return collided; } virtual void CalculateBounds() {} bool toBeDestroyed; bool isTrigger; Vector3D offset; bool debug = false; Bounds bounds; protected: COLLIDERTYPE colliderType; //Transform* transform; bool collided; }; #endif
[ "aj.green91@hotmail.co.uk" ]
aj.green91@hotmail.co.uk
72e9b1f9128cfd9810d5ce37a6e8018f2dafda82
6f9b4ede52e886ba8af79cfcae1c56c8d90ac39d
/app/rtkpost_qt/postopt.cpp
2eee1c64849961c16dc56e75cd03de6b77cee047
[]
no_license
szp35/rtklib-n8ur
ad3d8b8aed0068545f3368a80f86962549d8be42
7b519e0f7801ed157b3e2d6e306189d12c3fe6d3
refs/heads/master
2022-03-01T11:42:00.738779
2019-11-19T20:34:01
2019-11-19T20:35:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
47,685
cpp
//--------------------------------------------------------------------------- #include "postmain.h" #include "postopt.h" #include "keydlg.h" #include "viewer.h" #include "refdlg.h" #include "extopt.h" #include "maskoptdlg.h" #include <QShowEvent> #include <QFileDialog> #include <QFileSystemModel> #include <QCompleter> extern MainForm *mainForm; //--------------------------------------------------------------------------- OptDialog::OptDialog(QWidget *parent) : QDialog(parent) { setupUi(this); widget->setVisible(false); int nglo = MAXPRNGLO, ngal = MAXPRNGAL, nqzs = MAXPRNQZS, ncmp = MAXPRNCMP; int nirn = MAXPRNIRN; #if 0 QString label, s; Freq->Items->Clear(); for (int i = 0; i < NFREQ; i++) { label = label + (i > 0 ? "+" : "L") + s.sprintf("%d", freq[i]); Freq->Items->Add(label); } #endif QCompleter *fileCompleter = new QCompleter(this); QFileSystemModel *fileModel = new QFileSystemModel(fileCompleter); fileModel->setRootPath(""); fileCompleter->setModel(fileModel); StaPosFile->setCompleter(fileCompleter); AntPcvFile->setCompleter(fileCompleter); SatPcvFile->setCompleter(fileCompleter); DCBFile->setCompleter(fileCompleter); GeoidDataFile->setCompleter(fileCompleter); EOPFile->setCompleter(fileCompleter); BLQFile->setCompleter(fileCompleter); IonoFile->setCompleter(fileCompleter); connect(BtnOk, SIGNAL(clicked(bool)), this, SLOT(BtnOkClick())); connect(RovAntPcv, SIGNAL(clicked(bool)), this, SLOT(RovAntPcvClick())); connect(RefAntPcv, SIGNAL(clicked(bool)), this, SLOT(RovAntPcvClick())); connect(BtnAntPcvFile, SIGNAL(clicked(bool)), this, SLOT(BtnAntPcvFileClick())); connect(BtnIonoFile, SIGNAL(clicked(bool)), this, SLOT(BtnIonoFileClick())); connect(BtnAntPcvView, SIGNAL(clicked(bool)), this, SLOT(BtnAntPcvViewClick())); connect(PosMode, SIGNAL(currentIndexChanged(int)), this, SLOT(PosModeChange())); connect(SolFormat, SIGNAL(currentIndexChanged(int)), this, SLOT(SolFormatChange())); connect(AmbRes, SIGNAL(currentIndexChanged(int)), this, SLOT(AmbResChange())); connect(BtnLoad, SIGNAL(clicked(bool)), this, SLOT(BtnLoadClick())); connect(BtnCancel, SIGNAL(clicked(bool)), this, SLOT(reject())); connect(BtnSave, SIGNAL(clicked(bool)), this, SLOT(BtnSaveClick())); connect(Freq, SIGNAL(currentIndexChanged(int)), this, SLOT(FreqChange())); connect(BtnRefPos, SIGNAL(clicked(bool)), this, SLOT(BtnRefPosClick())); connect(BtnRovPos, SIGNAL(clicked(bool)), this, SLOT(BtnRovPosClick())); connect(BtnStaPosView, SIGNAL(clicked(bool)), this, SLOT(BtnStaPosViewClick())); connect(BtnStaPosFile, SIGNAL(clicked(bool)), this, SLOT(BtnStaPosFileClick())); connect(OutputHeight, SIGNAL(currentIndexChanged(int)), this, SLOT(OutputHeightClick())); connect(RefPosType, SIGNAL(currentIndexChanged(int)), this, SLOT(RefPosTypeChange())); connect(RovPosType, SIGNAL(currentIndexChanged(int)), this, SLOT(RovPosTypeChange())); connect(BtnSatPcvFile, SIGNAL(clicked(bool)), this, SLOT(BtnSatPcvFileClick())); connect(BtnSatPcvView, SIGNAL(clicked(bool)), this, SLOT(BtnSatPcvViewClick())); connect(SatEphem, SIGNAL(currentIndexChanged(int)), this, SLOT(SatEphemChange())); connect(BtnGeoidDataFile, SIGNAL(clicked(bool)), this, SLOT(BtnGeoidDataFileClick())); connect(BaselineConst, SIGNAL(clicked(bool)), this, SLOT(BaselineConstClick())); connect(NavSys1, SIGNAL(clicked(bool)), this, SLOT(NavSys2Click())); connect(NavSys2, SIGNAL(clicked(bool)), this, SLOT(NavSys2Click())); connect(NavSys3, SIGNAL(clicked(bool)), this, SLOT(NavSys2Click())); connect(NavSys4, SIGNAL(clicked(bool)), this, SLOT(NavSys2Click())); connect(NavSys5, SIGNAL(clicked(bool)), this, SLOT(NavSys2Click())); connect(NavSys6, SIGNAL(clicked(bool)), this, SLOT(NavSys2Click())); connect(IonoOpt, SIGNAL(currentIndexChanged(int)), this, SLOT(IonoOptChange())); connect(TropOpt, SIGNAL(currentIndexChanged(int)), this, SLOT(TropOptChange())); connect(DynamicModel, SIGNAL(currentIndexChanged(int)), this, SLOT(DynamicModelChange())); connect(SatEphem, SIGNAL(currentIndexChanged(int)), this, SLOT(SatEphemChange())); connect(RovAnt, SIGNAL(currentIndexChanged(int)), this, SLOT(RovAntClick())); connect(RefAnt, SIGNAL(currentIndexChanged(int)), this, SLOT(RefAntClick())); connect(BtnDCBFile, SIGNAL(clicked(bool)), this, SLOT(BtnDCBFileClick())); connect(BtnDCBView, SIGNAL(clicked(bool)), this, SLOT(BtnDCBViewClick())); connect(BtnHelp, SIGNAL(clicked(bool)), this, SLOT(BtnHelpClick())); connect(BtnBLQFile, SIGNAL(clicked(bool)), this, SLOT(BtnBLQFileClick())); connect(BtnBLQFileView, SIGNAL(clicked(bool)), this, SLOT(BtnBLQFileViewClick())); connect(BtnEOPFile, SIGNAL(clicked(bool)), this, SLOT(BtnEOPFileClick())); connect(BtnEOPView, SIGNAL(clicked(bool)), this, SLOT(BtnEOPViewClick())); connect(BtnExtOpt, SIGNAL(clicked(bool)), this, SLOT(BtnExtOptClick())); connect(BtnMask, SIGNAL(clicked(bool)), this, SLOT(BtnMaskClick())); if (nglo <= 0) NavSys2->setEnabled(false); if (ngal <= 0) NavSys3->setEnabled(false); if (nqzs <= 0) NavSys4->setEnabled(false); if (ncmp <= 0) NavSys6->setEnabled(false); if (nirn <= 0) NavSys7->setEnabled(false); UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::showEvent(QShowEvent *event) { if (event->spontaneous()) return; GetOpt(); } //--------------------------------------------------------------------------- void OptDialog::BtnOkClick() { SetOpt(); accept(); } //--------------------------------------------------------------------------- void OptDialog::BtnLoadClick() { LoadOpt(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Load Options"), QString(), tr("Options File (*.conf);;All (*.*)")))); } //--------------------------------------------------------------------------- void OptDialog::BtnSaveClick() { QString file; file = QDir::toNativeSeparators(QFileDialog::getSaveFileName(this, tr("Save Options"), QString(), tr("Options File (*.conf);;All (*.*)"))); QFileInfo f(file); if (f.suffix() == "") file = file + ".conf"; SaveOpt(file); } //--------------------------------------------------------------------------- void OptDialog::BtnStaPosViewClick() { if (StaPosFile->text() == "") return; TextViewer *viewer = new TextViewer(this); viewer->show(); viewer->Read(StaPosFile->text()); } //--------------------------------------------------------------------------- void OptDialog::BtnStaPosFileClick() { StaPosFile->setText(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Station Position File"), QString(), tr("Position File (*.pos);;All (*.*)")))); } //--------------------------------------------------------------------------- void OptDialog::RovPosTypeChange() { QLineEdit *edit[] = { RovPos1, RovPos2, RovPos3 }; double pos[3]; GetPos(RovPosTypeP, edit, pos); SetPos(RovPosType->currentIndex(), edit, pos); RovPosTypeP = RovPosType->currentIndex(); UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::RefPosTypeChange() { QLineEdit *edit[] = { RefPos1, RefPos2, RefPos3 }; double pos[3]; GetPos(RefPosTypeP, edit, pos); SetPos(RefPosType->currentIndex(), edit, pos); RefPosTypeP = RefPosType->currentIndex(); UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::BtnRovPosClick() { QLineEdit *edit[] = { RovPos1, RovPos2, RovPos3 }; double p[3], pos[3]; GetPos(RovPosType->currentIndex(), edit, p); ecef2pos(p, pos); RefDialog *refDialog = new RefDialog(this); refDialog->RovPos[0] = pos[0] * R2D; refDialog->RovPos[1] = pos[1] * R2D; refDialog->Pos[2] = pos[2]; refDialog->StaPosFile = StaPosFile->text(); refDialog->move(this->pos().x() + width() / 2 - refDialog->width() / 2, this->pos().y() + height() / 2 - refDialog->height() / 2); refDialog->exec(); if (refDialog->result() != QDialog::Accepted) return; pos[0] = refDialog->Pos[0] * D2R; pos[1] = refDialog->Pos[1] * D2R; pos[2] = refDialog->Pos[2]; pos2ecef(pos, p); SetPos(RovPosType->currentIndex(), edit, p); delete refDialog; } //--------------------------------------------------------------------------- void OptDialog::BtnRefPosClick() { QLineEdit *edit[] = { RefPos1, RefPos2, RefPos3 }; double p[3], pos[3]; GetPos(RefPosType->currentIndex(), edit, p); ecef2pos(p, pos); RefDialog *refDialog = new RefDialog(this); refDialog->RovPos[0] = pos[0] * R2D; refDialog->RovPos[1] = pos[1] * R2D; refDialog->RovPos[2] = pos[2]; refDialog->StaPosFile = StaPosFile->text(); refDialog->move(this->pos().x() + width() / 2 - refDialog->width() / 2, this->pos().y() + height() / 2 - refDialog->height() / 2); refDialog->exec(); if (refDialog->result() != QDialog::Accepted) return; pos[0] = refDialog->Pos[0] * D2R; pos[1] = refDialog->Pos[1] * D2R; pos[2] = refDialog->Pos[2]; pos2ecef(pos, p); SetPos(RefPosType->currentIndex(), edit, p); delete refDialog; } //--------------------------------------------------------------------------- void OptDialog::BtnSatPcvViewClick() { if (SatPcvFile->text() == "") return; TextViewer *viewer = new TextViewer(this); viewer->show(); viewer->Read(SatPcvFile->text()); } //--------------------------------------------------------------------------- void OptDialog::BtnSatPcvFileClick() { SatPcvFile->setText(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Satellite Antenna PCV File"), QString(), tr("PCV File (*.pcv *.atx);;All (*.*)")))); } //--------------------------------------------------------------------------- void OptDialog::BtnAntPcvViewClick() { if (AntPcvFile->text() == "") return; TextViewer *viewer = new TextViewer(this); viewer->show(); viewer->Read(AntPcvFile->text()); } //--------------------------------------------------------------------------- void OptDialog::BtnAntPcvFileClick() { AntPcvFile->setText(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Receiver Antenna PCV File"), QString(), tr("APCV File (*.pcv *.atx);;All (*.*)")))); ReadAntList(); } //--------------------------------------------------------------------------- void OptDialog::BtnGeoidDataFileClick() { GeoidDataFile->setText(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Geoid Data File"), QString(), tr("All (*.*)")))); } //--------------------------------------------------------------------------- void OptDialog::BtnDCBFileClick() { DCBFile->setText(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("DCB Data File"), QString(), tr("DCB Data File (*.dcb *.DCB);;All (*.*)")))); } //--------------------------------------------------------------------------- void OptDialog::BtnDCBViewClick() { QString DCBFile_Text = DCBFile->text(); if (DCBFile->text() == "") return; TextViewer *viewer = new TextViewer(this); viewer->show(); viewer->Read(DCBFile_Text); } //--------------------------------------------------------------------------- void OptDialog::BtnEOPFileClick() { EOPFile->setText(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("EOP Date File"), QString(), tr("EOP Data File (*.eop *.erp);;All (*.*)")))); } //--------------------------------------------------------------------------- void OptDialog::BtnEOPViewClick() { QString EOPFile_Text = EOPFile->text(); if (EOPFile->text() == "") return; TextViewer *viewer = new TextViewer(this); viewer->show(); viewer->Read(EOPFile_Text); } //--------------------------------------------------------------------------- void OptDialog::BtnBLQFileClick() { BLQFile->setText(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Ocean Tide Loading BLQ File"), QString(), tr("OTL BLQ File (*.blq);;All (*.*)")))); } //--------------------------------------------------------------------------- void OptDialog::BtnBLQFileViewClick() { QString BLQFile_Text = BLQFile->text(); if (BLQFile->text() == "") return; TextViewer *viewer = new TextViewer(this); viewer->show(); viewer->Read(BLQFile_Text); } //--------------------------------------------------------------------------- void OptDialog::BtnIonoFileClick() { IonoFile->setText(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Ionosphere DataFile"), QString(), tr("Ionosphere Data File (*.*i,*stec);;All (*.*)")))); } //--------------------------------------------------------------------------- void OptDialog::FreqChange() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::IonoOptChange() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::TropOptChange() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::DynamicModelChange() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::SatEphemChange() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::SolFormatChange() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::PosModeChange() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::SatEphemClick() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::NavSys2Click() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::AmbResChange() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::RovAntPcvClick() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::NetRSCorrClick() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::SatClkCorrClick() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::RovPosClick() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::RefPosClick() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::SbasCorrClick() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::OutputHeightClick() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::BaselineConstClick() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::RovAntClick() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::RefAntClick() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::GetOpt(void) { QLineEdit *editu[] = { RovPos1, RovPos2, RovPos3 }; QLineEdit *editr[] = { RefPos1, RefPos2, RefPos3 }; PosMode->setCurrentIndex(mainForm->PosMode); Freq->setCurrentIndex(mainForm->Freq); Solution->setCurrentIndex(mainForm->Solution); ElMask->setCurrentText(QString::number(mainForm->ElMask, 'f', 0)); SnrMask = mainForm->SnrMask; DynamicModel->setCurrentIndex(mainForm->DynamicModel); TideCorr->setCurrentIndex(mainForm->TideCorr); IonoOpt->setCurrentIndex(mainForm->IonoOpt); TropOpt->setCurrentIndex(mainForm->TropOpt); SatEphem->setCurrentIndex(mainForm->SatEphem); ExSats->setText(mainForm->ExSats); NavSys1->setChecked(mainForm->NavSys & SYS_GPS); NavSys2->setChecked(mainForm->NavSys & SYS_GLO); NavSys3->setChecked(mainForm->NavSys & SYS_GAL); NavSys4->setChecked(mainForm->NavSys & SYS_QZS); NavSys5->setChecked(mainForm->NavSys & SYS_SBS); NavSys6->setChecked(mainForm->NavSys & SYS_CMP); NavSys7->setChecked(mainForm->NavSys & SYS_IRN); PosOpt1->setChecked(mainForm->PosOpt[0]); PosOpt2->setChecked(mainForm->PosOpt[1]); PosOpt3->setChecked(mainForm->PosOpt[2]); PosOpt4->setChecked(mainForm->PosOpt[3]); PosOpt5->setChecked(mainForm->PosOpt[4]); PosOpt6->setChecked(mainForm->PosOpt[5]); // MapFunc->setCurrentIndex(mainForm->MapFunc); AmbRes->setCurrentIndex(mainForm->AmbRes); GloAmbRes->setCurrentIndex(mainForm->GloAmbRes); BdsAmbRes->setCurrentIndex(mainForm->BdsAmbRes); ValidThresAR->setValue(mainForm->ValidThresAR); ThresAR2->setValue(mainForm->ThresAR2); ThresAR3->setValue(mainForm->ThresAR3); OutCntResetAmb->setValue(mainForm->OutCntResetAmb); FixCntHoldAmb->setValue(mainForm->FixCntHoldAmb); LockCntFixAmb->setValue(mainForm->LockCntFixAmb); ElMaskAR->setValue(mainForm->ElMaskAR); ElMaskHold->setValue(mainForm->ElMaskHold); MaxAgeDiff->setValue(mainForm->MaxAgeDiff); RejectGdop->setValue(mainForm->RejectGdop); RejectThres->setValue(mainForm->RejectThres); SlipThres->setValue(mainForm->SlipThres); ARIter->setValue(mainForm->ARIter); NumIter->setValue(mainForm->NumIter); BaselineLen->setValue(mainForm->BaseLine[0]); BaselineSig->setValue(mainForm->BaseLine[1]); BaselineConst->setChecked(mainForm->BaseLineConst); SolFormat->setCurrentIndex(mainForm->SolFormat); TimeFormat->setCurrentIndex(mainForm->TimeFormat); TimeDecimal->setValue(mainForm->TimeDecimal); LatLonFormat->setCurrentIndex(mainForm->LatLonFormat); FieldSep->setText(mainForm->FieldSep); OutputHead->setCurrentIndex(mainForm->OutputHead); OutputOpt->setCurrentIndex(mainForm->OutputOpt); OutputSingle->setCurrentIndex(mainForm->OutputSingle); MaxSolStd->setValue(mainForm->MaxSolStd); OutputDatum->setCurrentIndex(mainForm->OutputDatum); OutputHeight->setCurrentIndex(mainForm->OutputHeight); OutputGeoid->setCurrentIndex(mainForm->OutputGeoid); SolStatic->setCurrentIndex(mainForm->SolStatic); DebugTrace->setCurrentIndex(mainForm->DebugTrace); DebugStatus->setCurrentIndex(mainForm->DebugStatus); MeasErrR1->setValue(mainForm->MeasErrR1); MeasErrR2->setValue(mainForm->MeasErrR2); MeasErr2->setValue(mainForm->MeasErr2); MeasErr3->setValue(mainForm->MeasErr3); MeasErr4->setValue(mainForm->MeasErr4); MeasErr5->setValue(mainForm->MeasErr5); SatClkStab->setText(QString::number(mainForm->SatClkStab, 'E', 2)); PrNoise1->setText(QString::number(mainForm->PrNoise1, 'E', 2)); PrNoise2->setText(QString::number(mainForm->PrNoise2, 'E', 2)); PrNoise3->setText(QString::number(mainForm->PrNoise3, 'E', 2)); PrNoise4->setText(QString::number(mainForm->PrNoise4, 'E', 2)); PrNoise5->setText(QString::number(mainForm->PrNoise5, 'E', 2)); RovAntPcv->setChecked(mainForm->RovAntPcv); RefAntPcv->setChecked(mainForm->RefAntPcv); RovAntE->setValue(mainForm->RovAntE); RovAntN->setValue(mainForm->RovAntN); RovAntU->setValue(mainForm->RovAntU); RefAntE->setValue(mainForm->RefAntE); RefAntN->setValue(mainForm->RefAntN); RefAntU->setValue(mainForm->RefAntU); AntPcvFile->setText(mainForm->AntPcvFile); RnxOpts1->setText(mainForm->RnxOpts1); RnxOpts2->setText(mainForm->RnxOpts2); PPPOpts->setText(mainForm->PPPOpts); IntpRefObs->setCurrentIndex(mainForm->IntpRefObs); SbasSat->setText(QString::number(mainForm->SbasSat)); SatPcvFile->setText(mainForm->SatPcvFile); StaPosFile->setText(mainForm->StaPosFile); GeoidDataFile->setText(mainForm->GeoidDataFile); EOPFile->setText(mainForm->EOPFile); DCBFile->setText(mainForm->DCBFile); BLQFile->setText(mainForm->BLQFile); IonoFile->setText(mainForm->IonoFile); RovPosType->setCurrentIndex(mainForm->RovPosType); RefPosType->setCurrentIndex(mainForm->RefPosType); RovPosTypeP = RovPosType->currentIndex(); RefPosTypeP = RefPosType->currentIndex(); SetPos(RovPosType->currentIndex(), editu, mainForm->RovPos); SetPos(RefPosType->currentIndex(), editr, mainForm->RefPos); ReadAntList(); RovAnt->setCurrentText(mainForm->RovAnt); RefAnt->setCurrentText(mainForm->RefAnt); RovList->setPlainText(mainForm->RovList); BaseList->setPlainText(mainForm->BaseList); ExtErr = mainForm->ExtErr; UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::SetOpt(void) { QLineEdit *editu[] = { RovPos1, RovPos2, RovPos3 }; QLineEdit *editr[] = { RefPos1, RefPos2, RefPos3 }; mainForm->PosMode = PosMode->currentIndex(); mainForm->Freq = Freq->currentIndex(); mainForm->Solution = Solution->currentIndex(); mainForm->ElMask = ElMask->currentText().toDouble(); mainForm->SnrMask = SnrMask; mainForm->DynamicModel = DynamicModel->currentIndex(); mainForm->TideCorr = TideCorr->currentIndex(); mainForm->IonoOpt = IonoOpt->currentIndex(); mainForm->TropOpt = TropOpt->currentIndex(); mainForm->SatEphem = SatEphem->currentIndex(); mainForm->ExSats = ExSats->text(); mainForm->NavSys = 0; if (NavSys1->isChecked()) mainForm->NavSys |= SYS_GPS; if (NavSys2->isChecked()) mainForm->NavSys |= SYS_GLO; if (NavSys3->isChecked()) mainForm->NavSys |= SYS_GAL; if (NavSys4->isChecked()) mainForm->NavSys |= SYS_QZS; if (NavSys5->isChecked()) mainForm->NavSys |= SYS_SBS; if (NavSys6->isChecked()) mainForm->NavSys |= SYS_CMP; if (NavSys7->isChecked()) mainForm->NavSys |= SYS_IRN; mainForm->PosOpt[0] = PosOpt1->isChecked(); mainForm->PosOpt[1] = PosOpt2->isChecked(); mainForm->PosOpt[2] = PosOpt3->isChecked(); mainForm->PosOpt[3] = PosOpt4->isChecked(); mainForm->PosOpt[4] = PosOpt5->isChecked(); mainForm->PosOpt[5] = PosOpt6->isChecked(); // mainForm->MapFunc=MapFunc->currentIndex(); mainForm->AmbRes = AmbRes->currentIndex(); mainForm->GloAmbRes = GloAmbRes->currentIndex(); mainForm->BdsAmbRes = BdsAmbRes->currentIndex(); mainForm->ValidThresAR = ValidThresAR->value(); mainForm->ThresAR2 = ThresAR2->value(); mainForm->ThresAR3 = ThresAR3->value(); mainForm->OutCntResetAmb = OutCntResetAmb->value(); mainForm->FixCntHoldAmb = FixCntHoldAmb->value(); mainForm->OutCntResetAmb = OutCntResetAmb->value(); mainForm->LockCntFixAmb = LockCntFixAmb->value(); mainForm->ElMaskAR = ElMaskAR->value(); mainForm->ElMaskHold = ElMaskHold->value(); mainForm->MaxAgeDiff = MaxAgeDiff->value(); mainForm->RejectGdop = RejectGdop->value(); mainForm->RejectThres = RejectThres->value(); mainForm->SlipThres = SlipThres->value(); mainForm->ARIter = ARIter->value(); mainForm->NumIter = NumIter->value(); mainForm->BaseLine[0] = BaselineLen->value(); mainForm->BaseLine[1] = BaselineSig->value(); mainForm->BaseLineConst = BaselineConst->isChecked(); mainForm->SolFormat = SolFormat->currentIndex(); mainForm->TimeFormat = TimeFormat->currentIndex(); mainForm->TimeDecimal = TimeDecimal->value(); mainForm->LatLonFormat = LatLonFormat->currentIndex(); mainForm->FieldSep = FieldSep->text(); mainForm->OutputHead = OutputHead->currentIndex(); mainForm->OutputOpt = OutputOpt->currentIndex(); mainForm->OutputSingle = OutputSingle->currentIndex(); mainForm->MaxSolStd = MaxSolStd->value(); mainForm->OutputDatum = OutputDatum->currentIndex(); mainForm->OutputHeight = OutputHeight->currentIndex(); mainForm->OutputGeoid = OutputGeoid->currentIndex(); mainForm->SolStatic = SolStatic->currentIndex(); mainForm->DebugTrace = DebugTrace->currentIndex(); mainForm->DebugStatus = DebugStatus->currentIndex(); mainForm->MeasErrR1 = MeasErrR1->value(); mainForm->MeasErrR2 = MeasErrR2->value(); mainForm->MeasErr2 = MeasErr2->value(); mainForm->MeasErr3 = MeasErr3->value(); mainForm->MeasErr4 = MeasErr4->value(); mainForm->MeasErr5 = MeasErr5->value(); mainForm->SatClkStab = SatClkStab->text().toDouble(); mainForm->PrNoise1 = PrNoise1->text().toDouble(); mainForm->PrNoise2 = PrNoise2->text().toDouble(); mainForm->PrNoise3 = PrNoise3->text().toDouble(); mainForm->PrNoise4 = PrNoise4->text().toDouble(); mainForm->PrNoise5 = PrNoise5->text().toDouble(); mainForm->RovAntPcv = RovAntPcv->isChecked(); mainForm->RefAntPcv = RefAntPcv->isChecked(); mainForm->RovAnt = RovAnt->currentText(); mainForm->RefAnt = RefAnt->currentText(); mainForm->RovAntE = RovAntE->value(); mainForm->RovAntN = RovAntN->value(); mainForm->RovAntU = RovAntU->value(); mainForm->RefAntE = RefAntE->value(); mainForm->RefAntN = RefAntN->value(); mainForm->RefAntU = RefAntU->value(); mainForm->RnxOpts1 = RnxOpts1->text(); mainForm->RnxOpts2 = RnxOpts2->text(); mainForm->PPPOpts = PPPOpts->text(); mainForm->IntpRefObs = IntpRefObs->currentIndex(); mainForm->SbasSat = SbasSat->text().toInt(); mainForm->AntPcvFile = AntPcvFile->text(); mainForm->SatPcvFile = SatPcvFile->text(); mainForm->StaPosFile = StaPosFile->text(); mainForm->GeoidDataFile = GeoidDataFile->text(); mainForm->EOPFile = EOPFile->text(); mainForm->DCBFile = DCBFile->text(); mainForm->BLQFile = BLQFile->text(); mainForm->IonoFile = IonoFile->text(); mainForm->RovPosType = RovPosType->currentIndex(); mainForm->RefPosType = RefPosType->currentIndex(); GetPos(RovPosType->currentIndex(), editu, mainForm->RovPos); GetPos(RefPosType->currentIndex(), editr, mainForm->RefPos); mainForm->RovList = RovList->toPlainText(); mainForm->BaseList = BaseList->toPlainText(); mainForm->ExtErr = ExtErr; UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::LoadOpt(const QString &file) { QLineEdit *editu[] = { RovPos1, RovPos2, RovPos3 }; QLineEdit *editr[] = { RefPos1, RefPos2, RefPos3 }; QString buff; char id[32]; int sat; prcopt_t prcopt = prcopt_default; solopt_t solopt = solopt_default; filopt_t filopt; memset(&filopt, 0, sizeof(filopt_t)); resetsysopts(); if (!loadopts(qPrintable(file), sysopts)) return; getsysopts(&prcopt, &solopt, &filopt); PosMode->setCurrentIndex(prcopt.mode); Freq->setCurrentIndex(prcopt.nf > NFREQ - 1 ? NFREQ - 1 : prcopt.nf - 1); Solution->setCurrentIndex(prcopt.soltype); ElMask->setCurrentText(QString::number(prcopt.elmin * R2D, 'f', 0)); SnrMask = prcopt.snrmask; DynamicModel->setCurrentIndex(prcopt.dynamics); TideCorr->setCurrentIndex(prcopt.tidecorr); IonoOpt->setCurrentIndex(prcopt.ionoopt); TropOpt->setCurrentIndex(prcopt.tropopt); SatEphem->setCurrentIndex(prcopt.sateph); ExSats->setText(""); for (sat = 1; sat <= MAXSAT; sat++) { if (!prcopt.exsats[sat - 1]) continue; satno2id(sat, id); buff += QString("%1%2%3").arg(buff.isEmpty() ? "" : " ").arg(prcopt.exsats[sat - 1] == 2 ? "+" : "").arg(id); } ExSats->setText(buff); NavSys1->setChecked(prcopt.navsys & SYS_GPS); NavSys2->setChecked(prcopt.navsys & SYS_GLO); NavSys3->setChecked(prcopt.navsys & SYS_GAL); NavSys4->setChecked(prcopt.navsys & SYS_QZS); NavSys5->setChecked(prcopt.navsys & SYS_SBS); NavSys6->setChecked(prcopt.navsys & SYS_CMP); PosOpt1->setChecked(prcopt.posopt[0]); PosOpt2->setChecked(prcopt.posopt[1]); PosOpt3->setChecked(prcopt.posopt[2]); PosOpt4->setChecked(prcopt.posopt[3]); PosOpt5->setChecked(prcopt.posopt[4]); PosOpt6->setChecked(prcopt.posopt[5]); // MapFunc->setCurrentIndex(prcopt.mapfunc); AmbRes->setCurrentIndex(prcopt.modear); GloAmbRes->setCurrentIndex(prcopt.glomodear); BdsAmbRes->setCurrentIndex(prcopt.bdsmodear); ValidThresAR->setValue(prcopt.thresar[0]); ThresAR2->setValue(prcopt.thresar[1]); ThresAR3->setValue(prcopt.thresar[2]); OutCntResetAmb->setValue(prcopt.maxout); FixCntHoldAmb->setValue(prcopt.minfix); LockCntFixAmb->setValue(prcopt.minlock); ElMaskAR->setValue(prcopt.elmaskar * R2D); ElMaskHold->setValue(prcopt.elmaskhold * R2D); MaxAgeDiff->setValue(prcopt.maxtdiff); RejectGdop->setValue(prcopt.maxgdop); RejectThres->setValue(prcopt.maxinno); SlipThres->setValue(prcopt.thresslip); ARIter->setValue(prcopt.armaxiter); NumIter->setValue(prcopt.niter); BaselineLen->setValue(prcopt.baseline[0]); BaselineSig->setValue(prcopt.baseline[1]); BaselineConst->setChecked(prcopt.baseline[0] > 0.0); SolFormat->setCurrentIndex(solopt.posf); TimeFormat->setCurrentIndex(solopt.timef == 0 ? 0 : solopt.times + 1); TimeDecimal->setValue(solopt.timeu); LatLonFormat->setCurrentIndex(solopt.degf); FieldSep->setText(solopt.sep); OutputHead->setCurrentIndex(solopt.outhead); OutputOpt->setCurrentIndex(solopt.outopt); OutputSingle->setCurrentIndex(prcopt.outsingle); MaxSolStd->setValue(solopt.maxsolstd); OutputDatum->setCurrentIndex(solopt.datum); OutputHeight->setCurrentIndex(solopt.height); OutputGeoid->setCurrentIndex(solopt.geoid); SolStatic->setCurrentIndex(solopt.solstatic); NmeaIntv1->setValue(solopt.nmeaintv[0]); NmeaIntv2->setValue(solopt.nmeaintv[1]); DebugTrace->setCurrentIndex(solopt.trace); DebugStatus->setCurrentIndex(solopt.sstat); MeasErrR1->setValue(prcopt.eratio[0]); MeasErrR2->setValue(prcopt.eratio[1]); MeasErr2->setValue(prcopt.err[1]); MeasErr3->setValue(prcopt.err[2]); MeasErr4->setValue(prcopt.err[3]); MeasErr5->setValue(prcopt.err[4]); SatClkStab->setText(QString::number(prcopt.sclkstab, 'E', 2)); PrNoise1->setText(QString::number(prcopt.prn[0], 'E', 2)); PrNoise2->setText(QString::number(prcopt.prn[1], 'E', 2)); PrNoise3->setText(QString::number(prcopt.prn[2], 'E', 2)); PrNoise4->setText(QString::number(prcopt.prn[3], 'E', 2)); PrNoise5->setText(QString::number(prcopt.prn[4], 'E', 2)); RovAntPcv->setChecked(*prcopt.anttype[0]); RefAntPcv->setChecked(*prcopt.anttype[1]); RovAnt->setCurrentText(prcopt.anttype[0]); RefAnt->setCurrentText(prcopt.anttype[1]); RovAntE->setValue(prcopt.antdel[0][0]); RovAntN->setValue(prcopt.antdel[0][1]); RovAntU->setValue(prcopt.antdel[0][2]); RefAntE->setValue(prcopt.antdel[1][0]); RefAntN->setValue(prcopt.antdel[1][1]); RefAntU->setValue(prcopt.antdel[1][2]); RnxOpts1->setText(prcopt.rnxopt[0]); RnxOpts2->setText(prcopt.rnxopt[1]); PPPOpts->setText(prcopt.pppopt); IntpRefObs->setCurrentIndex(prcopt.intpref); SbasSat->setText(QString::number(prcopt.sbassatsel)); RovPosType->setCurrentIndex(prcopt.rovpos == 0 ? 0 : prcopt.rovpos + 2); RefPosType->setCurrentIndex(prcopt.refpos == 0 ? 0 : prcopt.refpos + 2); RovPosTypeP = RovPosType->currentIndex(); RefPosTypeP = RefPosType->currentIndex(); SetPos(RovPosType->currentIndex(), editu, prcopt.ru); SetPos(RefPosType->currentIndex(), editr, prcopt.rb); SatPcvFile->setText(filopt.satantp); AntPcvFile->setText(filopt.rcvantp); StaPosFile->setText(filopt.stapos); GeoidDataFile->setText(filopt.geoid); EOPFile->setText(filopt.eop); DCBFile->setText(filopt.dcb); BLQFile->setText(filopt.blq); IonoFile->setText(filopt.iono); ReadAntList(); UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::SaveOpt(const QString &file) { QString ExSats_Text = ExSats->text(), FieldSep_Text = FieldSep->text(); QString RovAnt_Text = RovAnt->currentText(), RefAnt_Text = RefAnt->currentText(); QString SatPcvFile_Text = SatPcvFile->text(); QString AntPcvFile_Text = AntPcvFile->text(); QString StaPosFile_Text = StaPosFile->text(); QString GeoidDataFile_Text = GeoidDataFile->text(); QString EOPFile_Text = EOPFile->text(); QString DCBFile_Text = DCBFile->text(); QString BLQFile_Text = BLQFile->text(); QString IonoFile_Text = IonoFile->text(); QString RnxOpts1_Text = RnxOpts1->text(); QString RnxOpts2_Text = RnxOpts2->text(); QString PPPOpts_Text = PPPOpts->text(); QLineEdit *editu[] = { RovPos1, RovPos2, RovPos3 }; QLineEdit *editr[] = { RefPos1, RefPos2, RefPos3 }; char buff[1024], *p, comment[256], s[64]; int sat, ex; prcopt_t prcopt = prcopt_default; solopt_t solopt = solopt_default; filopt_t filopt; memset(&filopt, 0, sizeof(filopt_t)); prcopt.mode = PosMode->currentIndex(); prcopt.nf = Freq->currentIndex() + 1; prcopt.soltype = Solution->currentIndex(); prcopt.elmin = ElMask->currentText().toDouble() * D2R; prcopt.snrmask = SnrMask; prcopt.dynamics = DynamicModel->currentIndex(); prcopt.tidecorr = TideCorr->currentIndex(); prcopt.ionoopt = IonoOpt->currentIndex(); prcopt.tropopt = TropOpt->currentIndex(); prcopt.sateph = SatEphem->currentIndex(); if (ExSats->text() != "") { strcpy(buff, qPrintable(ExSats_Text)); for (p = strtok(buff, " "); p; p = strtok(NULL, " ")) { if (*p == '+') { ex = 2; p++; } else { ex = 1; } if (!(sat = satid2no(p))) continue; prcopt.exsats[sat - 1] = ex; } } prcopt.navsys = (NavSys1->isChecked() ? SYS_GPS : 0) | (NavSys2->isChecked() ? SYS_GLO : 0) | (NavSys3->isChecked() ? SYS_GAL : 0) | (NavSys4->isChecked() ? SYS_QZS : 0) | (NavSys5->isChecked() ? SYS_SBS : 0) | (NavSys6->isChecked() ? SYS_CMP : 0); prcopt.posopt[0] = PosOpt1->isChecked(); prcopt.posopt[1] = PosOpt2->isChecked(); prcopt.posopt[2] = PosOpt3->isChecked(); prcopt.posopt[3] = PosOpt4->isChecked(); prcopt.posopt[4] = PosOpt5->isChecked(); prcopt.posopt[5] = PosOpt6->isChecked(); // prcopt.mapfunc=MapFunc->currentIndex(); prcopt.modear = AmbRes->currentIndex(); prcopt.glomodear = GloAmbRes->currentIndex(); prcopt.bdsmodear = BdsAmbRes->currentIndex(); prcopt.thresar[0] = ValidThresAR->value(); prcopt.thresar[1] = ThresAR2->value(); prcopt.thresar[2] = ThresAR3->value(); prcopt.maxout = OutCntResetAmb->value(); prcopt.minfix = FixCntHoldAmb->value(); prcopt.minlock = LockCntFixAmb->value(); prcopt.elmaskar = ElMaskAR->value() * D2R; prcopt.elmaskhold = ElMaskHold->value() * D2R; prcopt.maxtdiff = MaxAgeDiff->value(); prcopt.maxgdop = RejectGdop->value(); prcopt.maxinno = RejectThres->value(); prcopt.thresslip = SlipThres->value(); prcopt.armaxiter = ARIter->value(); prcopt.niter = NumIter->value(); if (prcopt.mode == PMODE_MOVEB && BaselineConst->isChecked()) { prcopt.baseline[0] = BaselineLen->value(); prcopt.baseline[1] = BaselineSig->value(); } solopt.posf = SolFormat->currentIndex(); solopt.timef = TimeFormat->currentIndex() == 0 ? 0 : 1; solopt.times = TimeFormat->currentIndex() == 0 ? 0 : TimeFormat->currentIndex() - 1; solopt.timeu = TimeDecimal->value(); solopt.degf = LatLonFormat->currentIndex(); strcpy(solopt.sep, qPrintable(FieldSep_Text)); solopt.outhead = OutputHead->currentIndex(); solopt.outopt = OutputOpt->currentIndex(); prcopt.outsingle = OutputSingle->currentIndex(); solopt.maxsolstd = MaxSolStd->value(); solopt.datum = OutputDatum->currentIndex(); solopt.height = OutputHeight->currentIndex(); solopt.geoid = OutputGeoid->currentIndex(); solopt.solstatic = SolStatic->currentIndex(); solopt.nmeaintv[0] = NmeaIntv1->value(); solopt.nmeaintv[1] = NmeaIntv2->value(); solopt.trace = DebugTrace->currentIndex(); solopt.sstat = DebugStatus->currentIndex(); prcopt.eratio[0] = MeasErrR1->value(); prcopt.eratio[1] = MeasErrR2->value(); prcopt.err[1] = MeasErr2->value(); prcopt.err[2] = MeasErr3->value(); prcopt.err[3] = MeasErr4->value(); prcopt.err[4] = MeasErr5->value(); prcopt.sclkstab = SatClkStab->text().toDouble(); prcopt.prn[0] = PrNoise1->text().toDouble(); prcopt.prn[1] = PrNoise2->text().toDouble(); prcopt.prn[2] = PrNoise3->text().toDouble(); prcopt.prn[3] = PrNoise4->text().toDouble(); prcopt.prn[4] = PrNoise5->text().toDouble(); if (RovAntPcv->isChecked()) strcpy(prcopt.anttype[0], qPrintable(RovAnt_Text)); if (RefAntPcv->isChecked()) strcpy(prcopt.anttype[1], qPrintable(RefAnt_Text)); prcopt.antdel[0][0] = RovAntE->value(); prcopt.antdel[0][1] = RovAntN->value(); prcopt.antdel[0][2] = RovAntU->value(); prcopt.antdel[1][0] = RefAntE->value(); prcopt.antdel[1][1] = RefAntN->value(); prcopt.antdel[1][2] = RefAntU->value(); prcopt.intpref = IntpRefObs->currentIndex(); prcopt.sbassatsel = SbasSat->text().toInt(); prcopt.rovpos = RovPosType->currentIndex() < 3 ? 0 : RovPosType->currentIndex() - 2; prcopt.refpos = RefPosType->currentIndex() < 3 ? 0 : RefPosType->currentIndex() - 2; if (prcopt.rovpos == 0) GetPos(RovPosType->currentIndex(), editu, prcopt.ru); if (prcopt.refpos == 0) GetPos(RefPosType->currentIndex(), editr, prcopt.rb); strcpy(prcopt.rnxopt[0], qPrintable(RnxOpts1_Text)); strcpy(prcopt.rnxopt[1], qPrintable(RnxOpts2_Text)); strcpy(prcopt.pppopt, qPrintable(PPPOpts_Text)); strcpy(filopt.satantp, qPrintable(SatPcvFile_Text)); strcpy(filopt.rcvantp, qPrintable(AntPcvFile_Text)); strcpy(filopt.stapos, qPrintable(StaPosFile_Text)); strcpy(filopt.geoid, qPrintable(GeoidDataFile_Text)); strcpy(filopt.eop, qPrintable(EOPFile_Text)); strcpy(filopt.dcb, qPrintable(DCBFile_Text)); strcpy(filopt.blq, qPrintable(BLQFile_Text)); strcpy(filopt.iono, qPrintable(IonoFile_Text)); time2str(utc2gpst(timeget()), s, 0); sprintf(comment, "rtkpost_qt options (%s, v.%s %s)", s, VER_RTKLIB, PATCH_LEVEL); setsysopts(&prcopt, &solopt, &filopt); if (!saveopts(qPrintable(file), "w", comment, sysopts)) return; } //--------------------------------------------------------------------------- void OptDialog::UpdateEnable(void) { bool rel = PMODE_DGPS <= PosMode->currentIndex() && PosMode->currentIndex() <= PMODE_FIXED; bool rtk = PMODE_KINEMA <= PosMode->currentIndex() && PosMode->currentIndex() <= PMODE_FIXED; bool ppp = PosMode->currentIndex() >= PMODE_PPP_KINEMA; bool ar = rtk || ppp; Freq->setEnabled(rel || ppp); Solution->setEnabled(rel || ppp); DynamicModel->setEnabled(rel); TideCorr->setEnabled(rel || ppp); //IonoOpt->setEnabled(!ppp); PosOpt1->setEnabled(ppp); PosOpt2->setEnabled(ppp); PosOpt3->setEnabled(ppp); PosOpt4->setEnabled(ppp); PosOpt6->setEnabled(ppp); AmbRes->setEnabled(ar); GloAmbRes->setEnabled(ar && AmbRes->currentIndex() > 0 && NavSys2->isChecked()); BdsAmbRes->setEnabled(ar && AmbRes->currentIndex() > 0 && NavSys6->isChecked()); ValidThresAR->setEnabled(ar && AmbRes->currentIndex() >= 1 && AmbRes->currentIndex() < 4); ThresAR2->setEnabled(ar && AmbRes->currentIndex() >= 4); ThresAR3->setEnabled(ar && AmbRes->currentIndex() >= 4); LockCntFixAmb->setEnabled(ar && AmbRes->currentIndex() >= 1); ElMaskAR->setEnabled(ar && AmbRes->currentIndex() >= 1); OutCntResetAmb->setEnabled(ar || ppp); FixCntHoldAmb->setEnabled(ar && AmbRes->currentIndex() == 3); ElMaskHold->setEnabled(ar && AmbRes->currentIndex() == 3); SlipThres->setEnabled(rtk || ppp); MaxAgeDiff->setEnabled(rel); RejectThres->setEnabled(rel || ppp); ARIter->setEnabled(ppp); NumIter->setEnabled(rel || ppp); BaselineConst->setEnabled(PosMode->currentIndex() == PMODE_MOVEB); BaselineLen->setEnabled(BaselineConst->isChecked() && PosMode->currentIndex() == PMODE_MOVEB); BaselineSig->setEnabled(BaselineConst->isChecked() && PosMode->currentIndex() == PMODE_MOVEB); OutputHead->setEnabled(SolFormat->currentIndex() < 3); OutputOpt->setEnabled(SolFormat->currentIndex() < 3); TimeFormat->setEnabled(SolFormat->currentIndex() < 3); TimeDecimal->setEnabled(SolFormat->currentIndex() < 3); LatLonFormat->setEnabled(SolFormat->currentIndex() == 0); FieldSep->setEnabled(SolFormat->currentIndex() < 3); OutputSingle->setEnabled(PosMode->currentIndex() != 0); OutputDatum->setEnabled(SolFormat->currentIndex() == 0); OutputHeight->setEnabled(SolFormat->currentIndex() == 0); OutputGeoid->setEnabled(SolFormat->currentIndex() == 0 && OutputHeight->currentIndex() == 1); SolStatic->setEnabled(PosMode->currentIndex() == PMODE_STATIC || PosMode->currentIndex() == PMODE_PPP_STATIC); RovAntPcv->setEnabled(rel || ppp); RovAnt->setEnabled((rel || ppp) && RovAntPcv->isChecked()); RovAntE->setEnabled((rel || ppp) && RovAntPcv->isChecked()); RovAntN->setEnabled((rel || ppp) && RovAntPcv->isChecked()); RovAntU->setEnabled((rel || ppp) && RovAntPcv->isChecked()); LabelRovAntD->setEnabled((rel || ppp) && RovAntPcv->isChecked()); RefAntPcv->setEnabled(rel); RefAnt->setEnabled(rel && RefAntPcv->isChecked()); RefAntE->setEnabled(rel && RefAntPcv->isChecked()); RefAntN->setEnabled(rel && RefAntPcv->isChecked()); RefAntU->setEnabled(rel && RefAntPcv->isChecked()); LabelRefAntD->setEnabled(rel && RefAntPcv->isChecked()); RovPosType->setEnabled(PosMode->currentIndex() == PMODE_FIXED || PosMode->currentIndex() == PMODE_PPP_FIXED); RovPos1->setEnabled(RovPosType->isEnabled() && RovPosType->currentIndex() <= 2); RovPos2->setEnabled(RovPosType->isEnabled() && RovPosType->currentIndex() <= 2); RovPos3->setEnabled(RovPosType->isEnabled() && RovPosType->currentIndex() <= 2); BtnRovPos->setEnabled(RovPosType->isEnabled() && RovPosType->currentIndex() <= 2); RefPosType->setEnabled(rel && PosMode->currentIndex() != PMODE_MOVEB); RefPos1->setEnabled(RefPosType->isEnabled() && RefPosType->currentIndex() <= 2); RefPos2->setEnabled(RefPosType->isEnabled() && RefPosType->currentIndex() <= 2); RefPos3->setEnabled(RefPosType->isEnabled() && RefPosType->currentIndex() <= 2); BtnRefPos->setEnabled(RefPosType->isEnabled() && RefPosType->currentIndex() <= 2); } //--------------------------------------------------------------------------- void OptDialog::GetPos(int type, QLineEdit **edit, double *pos) { QString edit0_Text = edit[0]->text(); QString edit1_Text = edit[1]->text(); double p[3] = { 0 }, dms1[3] = { 0 }, dms2[3] = { 0 }; if (type == 1) { /* lat/lon/height dms/m */ QStringList tokens = edit0_Text.split(' '); if (tokens.size() == 3) for (int i = 0; i < 3; i++) dms1[i] = tokens.at(i).toDouble(); tokens = edit1_Text.split(' '); if (tokens.size() == 3) for (int i = 0; i < 3; i++) dms2[i] = tokens.at(i).toDouble(); p[0] = (dms1[0] < 0 ? -1 : 1) * (fabs(dms1[0]) + dms1[1] / 60 + dms1[2] / 3600) * D2R; p[1] = (dms2[0] < 0 ? -1 : 1) * (fabs(dms2[0]) + dms2[1] / 60 + dms2[2] / 3600) * D2R; p[2] = edit[2]->text().toDouble(); pos2ecef(p, pos); } else if (type == 2) { /* x/y/z-ecef */ pos[0] = edit[0]->text().toDouble(); pos[1] = edit[1]->text().toDouble(); pos[2] = edit[2]->text().toDouble(); } else { p[0] = edit[0]->text().toDouble() * D2R; p[1] = edit[1]->text().toDouble() * D2R; p[2] = edit[2]->text().toDouble(); pos2ecef(p, pos); } } //--------------------------------------------------------------------------- void OptDialog::SetPos(int type, QLineEdit **edit, double *pos) { double p[3], dms1[3], dms2[3], s1, s2; if (type == 1) { /* lat/lon/height dms/m */ ecef2pos(pos, p); s1 = p[0] < 0 ? -1 : 1; s2 = p[1] < 0 ? -1 : 1; p[0] = fabs(p[0]) * R2D + 1E-12; p[1] = fabs(p[1]) * R2D + 1E-12; dms1[0] = floor(p[0]); p[0] = (p[0] - dms1[0]) * 60.0; dms1[1] = floor(p[0]); dms1[2] = (p[0] - dms1[1]) * 60.0; dms2[0] = floor(p[1]); p[1] = (p[1] - dms2[0]) * 60.0; dms2[1] = floor(p[1]); dms2[2] = (p[1] - dms2[1]) * 60.0; edit[0]->setText(QString("%1 %2 %3").arg(s1 * dms1[0], 0, 'f', 0).arg(dms1[1], 2, 'f', 0).arg(dms1[2], 9, 'f', 6)); edit[1]->setText(QString("%1 %2 %3").arg(s2 * dms2[0], 0, 'f', 0).arg(dms2[1], 2, 'f', 0).arg(dms2[2], 9, 'f', 6)); edit[2]->setText(QString("%1").arg(p[2], 0, 'f', 4)); } else if (type == 2) { /* x/y/z-ecef */ edit[0]->setText(QString::number(pos[0], 'f', 4)); edit[1]->setText(QString::number(pos[1], 'f', 4)); edit[2]->setText(QString::number(pos[2], 'f', 4)); } else { ecef2pos(pos, p); edit[0]->setText(QString::number(p[0] * R2D, 'f', 9)); edit[1]->setText(QString::number(p[1] * R2D, 'f', 9)); edit[2]->setText(QString::number(p[2], 'f', 4)); } } //--------------------------------------------------------------------------- void OptDialog::ReadAntList(void) { QString AntPcvFile_Text = AntPcvFile->text(); pcvs_t pcvs = { 0, 0, 0 }; char *p; if (!readpcv(qPrintable(AntPcvFile_Text), &pcvs)) return; RovAnt->clear(); RefAnt->clear(); RovAnt->addItem(""); RefAnt->addItem(""); RovAnt->addItem("*"); RefAnt->addItem("*"); for (int i = 0; i < pcvs.n; i++) { if (pcvs.pcv[i].sat) continue; if ((p = strchr(pcvs.pcv[i].type, ' '))) *p = '\0'; if (i > 0 && !strcmp(pcvs.pcv[i].type, pcvs.pcv[i - 1].type)) continue; RovAnt->addItem(pcvs.pcv[i].type); RefAnt->addItem(pcvs.pcv[i].type); } free(pcvs.pcv); } //--------------------------------------------------------------------------- void OptDialog::BtnHelpClick() { KeyDialog *keyDialog = new KeyDialog(this); keyDialog->Flag = 2; keyDialog->exec(); delete keyDialog; } //--------------------------------------------------------------------------- void OptDialog::ExtEna0Click() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::ExtEna1Click() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::ExtEna2Click() { UpdateEnable(); } //--------------------------------------------------------------------------- void OptDialog::BtnExtOptClick() { ExtOptDialog *extOptDialog = new ExtOptDialog(this); extOptDialog->exec(); delete extOptDialog; } //--------------------------------------------------------------------------- void OptDialog::BtnMaskClick() { MaskOptDialog *maskOptDialog = new MaskOptDialog(this); maskOptDialog->Mask = SnrMask; maskOptDialog->exec(); if (maskOptDialog->result() != QDialog::Accepted) return; SnrMask = maskOptDialog->Mask; delete maskOptDialog; } //--------------------------------------------------------------------------- void OptDialog::NavSys6Click() { UpdateEnable(); } //---------------------------------------------------------------------------
[ "jra@febo.com" ]
jra@febo.com
88af7e5e06f49fd06f64391b05f3a812726c2417
f3e813535f75fb461e2306f1ad18596ac233e758
/odb_api_bundle-0.17.6-Source/eckit/src/eckit/option/FactoryOption.cc
ef9ce347263b70e39e382367b51fd853e6999084
[ "Apache-2.0" ]
permissive
vyesubabu/metview
47f9de3eb5f1bf418e513ed306aa2279635b79c7
74c2b9bc28673001fd02e00194e92c53a897fb62
refs/heads/master
2021-05-17T16:42:41.697859
2018-04-09T15:08:19
2018-04-09T15:08:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,513
cc
/* * (C) Copyright 1996-2017 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ /// @author Baudouin Raoult /// @author Tiago Quintino /// @date Apr 2015 #include <iostream> #include "eckit/config/Configured.h" #include "eckit/config/Configuration.h" #include "eckit/exception/Exceptions.h" #include "eckit/option/FactoryOption.h" #include "eckit/utils/Translator.h" namespace eckit { namespace option { template<class T> FactoryOption<T>::FactoryOption(const std::string &name, const std::string &description): Option(name, description) { } template<class T> FactoryOption<T>::~FactoryOption() { } template<class T> void FactoryOption<T>::set(const std::string &value, Configured &parametrisation) const { parametrisation.set(name_, value); } template<class T> void FactoryOption<T>::copy(const Configuration &from, Configured &to) const { std::string v; if(from.get(name_, v)) { to.set(name_, v); } } template<class T> void FactoryOption<T>::print(std::ostream &out) const { out << " --" << name_ << "=name" << " (" << description_ << ")"; out << std::endl << " Values are: "; T::list(out); } } // namespace option } // namespace eckit
[ "Xin.L.Zhang@noaa.gov" ]
Xin.L.Zhang@noaa.gov
f605d5f7d19954fc39ef90225b99eafbe786904e
3b31bbc1074ba61c115209156413ffdf419cf9f8
/newnnfw/tools/nnapi_quickcheck/tests/fully_connected_quan_1.cpp
1cb75fea05dae40afe9209e58dc0244431fc8cc3
[ "MIT", "Apache-2.0" ]
permissive
mojunsang26/Tizen-NN-Runtime
caa35a5aa8137fc8dfc376805c92ac333be9c06b
ff50aa626ef101483d03550533ac7110ddca5afc
refs/heads/master
2020-04-09T07:19:22.780932
2019-10-30T02:31:03
2019-10-30T02:31:03
160,150,527
0
0
Apache-2.0
2018-12-03T07:34:44
2018-12-03T07:34:44
null
UTF-8
C++
false
false
5,821
cpp
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gtest/gtest.h" #include "support/tflite/kernels/register.h" #include "tensorflow/contrib/lite/model.h" #include "tensorflow/contrib/lite/builtin_op_data.h" #include "env.h" #include "util/environment.h" #include "support/tflite/Diff.h" #include "support/tflite/Quantization.h" #include "support/tflite/interp/FunctionBuilder.h" #include <iostream> #include <cassert> #include <chrono> #include <random> using namespace tflite; using namespace tflite::ops::builtin; template <typename T> T *make_malloc(void) { return reinterpret_cast<T *>(malloc(sizeof(T))); } TEST(NNAPI_Quickcheck_fully_connected_1, simple_test) { int verbose = 0; int tolerance = 1; nnfw::util::env::IntAccessor("VERBOSE").access(verbose); nnfw::util::env::IntAccessor("TOLERANCE").access(tolerance); // Set random seed int SEED = std::chrono::system_clock::now().time_since_epoch().count(); nnfw::util::env::IntAccessor("SEED").access(SEED); #define INT_VALUE(NAME, VALUE) IntVar NAME##_Value(#NAME, VALUE); #include "fully_connected_quan_1.lst" #undef INT_VALUE const int32_t IFM_C = IFM_C_Value(); const int32_t IFM_H = IFM_H_Value(); const int32_t IFM_W = IFM_W_Value(); const int32_t KER_H = KER_H_Value(); const int32_t KER_W = IFM_C_Value() * IFM_H_Value() * IFM_W_Value(); const int32_t OUT_LEN = KER_H; // Initialize random number generator std::minstd_rand random(SEED); std::cout << "Configurations:" << std::endl; #define PRINT_NEWLINE() \ { \ std::cout << std::endl; \ } #define PRINT_VALUE(value) \ { \ std::cout << " " << #value << ": " << (value) << std::endl; \ } PRINT_VALUE(SEED); PRINT_NEWLINE(); PRINT_VALUE(IFM_C); PRINT_VALUE(IFM_H); PRINT_VALUE(IFM_W); PRINT_NEWLINE(); PRINT_VALUE(KER_H); PRINT_VALUE(KER_W); PRINT_NEWLINE(); PRINT_VALUE(OUT_LEN); #undef PRINT_VALUE #undef PRINT_NEWLINE // Configure Kernel Data const uint32_t kernel_size = KER_H * KER_W; float kernel_data[kernel_size] = { 0.0f, }; // Fill kernel data with random data { std::normal_distribution<float> kernel_dist(-1.0f, +1.0f); for (uint32_t off = 0; off < kernel_size; ++off) { kernel_data[off++] = kernel_dist(random); } } // Configure Bias Data const auto bias_size = KER_H; int32_t bias_data[bias_size] = { 0, }; // Fill bias data with random data { std::normal_distribution<float> bias_dist(-1.0f, +1.0f); for (uint32_t off = 0; off < bias_size; ++off) { bias_data[off] = static_cast<int32_t>(bias_dist(random)); } } auto setup = [&](Interpreter &interp) { // Comment from 'context.h' // // Parameters for asymmetric quantization. Quantized values can be converted // back to float using: // real_value = scale * (quantized_value - zero_point); // // Q: Is this necessary? TfLiteQuantizationParams quantization = make_default_quantization(); quantization.scale = FLOAT_NEAREST_TO_1; quantization.zero_point = 0; // On AddTensors(N) call, T/F Lite interpreter creates N tensors whose index is [0 ~ N) interp.AddTensors(4); // Configure OFM interp.SetTensorParametersReadWrite(0, kTfLiteUInt8 /* type */, "output" /* name */, {1 /*N*/, KER_H} /* dims */, quantization); // Configure IFM interp.SetTensorParametersReadWrite(1, kTfLiteUInt8 /* type */, "input" /* name */, {1 /*N*/, IFM_H, IFM_W, IFM_C} /* dims */, quantization); // NOTE kernel_data & bias_data should live longer than interpreter! interp.SetTensorParametersReadOnly( 2, kTfLiteUInt8 /* type */, "filter" /* name */, {KER_H, KER_W} /* dims */, quantization, reinterpret_cast<const char *>(kernel_data), kernel_size * sizeof(uint8_t)); interp.SetTensorParametersReadOnly( 3, kTfLiteInt32 /* type */, "bias" /* name */, {bias_size} /* dims */, quantization, reinterpret_cast<const char *>(bias_data), bias_size * sizeof(int32_t)); // Add Fully Connected Node // // NOTE AddNodeWithParameters take the ownership of param, and deallocate it with free // So, param should be allocated with malloc auto param = make_malloc<TfLiteFullyConnectedParams>(); param->activation = kTfLiteActRelu; // Run Convolution and store its result into Tensor #0 // - Read IFM from Tensor #1 // - Read Filter from Tensor #2, // - Read Bias from Tensor #3 interp.AddNodeWithParameters({1, 2, 3}, {0}, nullptr, 0, reinterpret_cast<void *>(param), BuiltinOpResolver().FindOp(BuiltinOperator_FULLY_CONNECTED, 1)); // Set Tensor #1 as Input #0, and Tensor #0 as Output #0 interp.SetInputs({1}); interp.SetOutputs({0}); }; const nnfw::support::tflite::interp::FunctionBuilder builder(setup); RandomTestParam param; param.verbose = verbose; param.tolerance = tolerance; int res = RandomTestRunner{SEED, param}.run(builder); EXPECT_EQ(res, 0); }
[ "lazineer@gmail.com" ]
lazineer@gmail.com
d1e14144dcc35462e8b832a72c4bdd9712688944
29aacef65cecf10cfa6fc2046cc5a36aac90eabf
/openfst-1.5.0/src/script/compose.cc
032a7fe244f38d3ee4faf663c39acc769777771f
[ "Apache-2.0" ]
permissive
jeremieroche/VisualOpenFstiOS
a54d4d7b1718100050de5967bf3bcdf43fe6a1a1
01f98805716183fe85a8799a807921e251cec25a
refs/heads/master
2020-09-23T07:33:48.736428
2016-09-07T13:56:22
2016-09-07T13:56:22
67,538,795
0
0
null
null
null
null
UTF-8
C++
false
false
1,872
cc
// 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. // // Copyright 2005-2010 Google, Inc. // Author: jpr@google.com (Jake Ratkiewicz) #include "fst/script/fst-class.h" #include "fst/script/script-impl.h" #include "fst/script/compose.h" namespace fst { namespace script { void Compose(const FstClass &ifst1, const FstClass &ifst2, MutableFstClass *ofst, ComposeFilter compose_filter) { if (!ArcTypesMatch(ifst1, ifst2, "Compose") || !ArcTypesMatch(*ofst, ifst1, "Compose")) return; ComposeArgs1 args(ifst1, ifst2, ofst, compose_filter); Apply<Operation<ComposeArgs1> >("Compose", ifst1.ArcType(), &args); } void Compose(const FstClass &ifst1, const FstClass &ifst2, MutableFstClass *ofst, const ComposeOptions &copts) { if (!ArcTypesMatch(ifst1, ifst2, "Compose") || !ArcTypesMatch(*ofst, ifst1, "Compose")) return; ComposeArgs2 args(ifst1, ifst2, ofst, copts); Apply<Operation<ComposeArgs2> >("Compose", ifst1.ArcType(), &args); } REGISTER_FST_OPERATION(Compose, StdArc, ComposeArgs1); REGISTER_FST_OPERATION(Compose, LogArc, ComposeArgs1); REGISTER_FST_OPERATION(Compose, Log64Arc, ComposeArgs1); REGISTER_FST_OPERATION(Compose, StdArc, ComposeArgs2); REGISTER_FST_OPERATION(Compose, LogArc, ComposeArgs2); REGISTER_FST_OPERATION(Compose, Log64Arc, ComposeArgs2); } // namespace script } // namespace fst
[ "jeremieroche@gmail.com" ]
jeremieroche@gmail.com
4e9846a0e0face5ce53909c7ad6887f9b1931c01
520b75c144414d2af5a655e592fa65787ee89aaa
/yukicoder/0047.cpp
9e3689783f0c34ee2a18d4671f5dad53c08bb815
[]
no_license
arrows-1011/CPro
4ac069683c672ba685534444412aa2e28026879d
2e1a9242b2433851f495468e455ee854a8c4dac7
refs/heads/master
2020-04-12T09:36:40.846130
2017-06-10T08:02:10
2017-06-10T08:02:10
46,426,455
1
1
null
null
null
null
UTF-8
C++
false
false
241
cpp
#include <iostream> using namespace std; int main() { int N; cin >> N; for (int i = 0; i <= 30; i++) { if (N <= (1 << i)) { cout << i << endl; break; } } return 0; }
[ "s1210207@gmail.com" ]
s1210207@gmail.com
ed125e2759cab00a7df214fcdceb6043ae871b64
a35b30a7c345a988e15d376a4ff5c389a6e8b23a
/boost/fusion/container/map/detail/cpp03/preprocessed/map20.hpp
c4e662ecf9c7e44cf2fc083cbad0217d57420a44
[]
no_license
huahang/thirdparty
55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b
07a5d64111a55dda631b7e8d34878ca5e5de05ab
refs/heads/master
2021-01-15T14:29:26.968553
2014-02-06T07:35:22
2014-02-06T07:35:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
98
hpp
#include "thirdparty/boost_1_55_0/boost/fusion/container/map/detail/cpp03/preprocessed/map20.hpp"
[ "liuhuahang@xiaomi.com" ]
liuhuahang@xiaomi.com
237709a9ffa7693ddd155985607131993be9f446
857bac188d3baa16255ea0a751267227fab28315
/Libraries/xcdriver/Headers/xcdriver/VersionAction.h
fd61df020a37d07292c92178e2c72aad952532b0
[ "BSD-3-Clause", "LicenseRef-scancode-philippe-de-muyter", "NCSA", "Zlib", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
modocache/xcbuild
1305e1f92a5cd27f4c1253b9e20efce904e70137
60b8598501b7c16c6aee5e3b998676eac6ef1576
refs/heads/master
2020-04-05T22:50:26.109831
2016-06-16T18:57:36
2016-06-18T20:23:43
61,489,213
0
0
null
2016-06-19T16:25:27
2016-06-19T16:25:26
null
UTF-8
C++
false
false
691
h
/** Copyright (c) 2015-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. */ #ifndef __xcdriver_VersionAction_h #define __xcdriver_VersionAction_h #include <xcdriver/Base.h> namespace libutil { class Filesystem; } namespace xcdriver { class Options; class VersionAction { private: VersionAction(); ~VersionAction(); public: static int Run(libutil::Filesystem const *filesystem, Options const &options); }; } #endif // !__xcdriver_VersionAction_h
[ "git@grantpaul.com" ]
git@grantpaul.com
9edb4d9bc23894807df8aca29d9d52e2d1d6f9df
2518f165b24387516961f8699bd1c9ba41d550c7
/simulation/dynamics/_GeneralModuleFiles/dynamicObject.h
ba63f913d69a60c12cd987c97d0bb7d039b52ed1
[]
no_license
willflowers95/src
e0be563f0bf9394e27375a108bebf3602246fac2
3737c62a71cfe70c62d8855b19439c8579f3d264
refs/heads/master
2020-04-18T16:28:02.499720
2019-01-26T01:00:48
2019-01-26T01:00:48
167,634,524
0
1
null
null
null
null
UTF-8
C++
false
false
2,358
h
/* ISC License Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef DYNAMICOBJECT_H #define DYNAMICOBJECT_H #include <vector> #include <stdint.h> #include "dynParamManager.h" #include "stateEffector.h" #include "dynamicEffector.h" #include "stateVecIntegrator.h" #include "_GeneralModuleFiles/sys_model.h" /*! @brief Object that is to be used by an integrator. This holds the equations of motion, integrate state, energy and momentum calculations. dynamicObject is what puts all of the pieces together for your system */ class DynamicObject : public SysModel { public: DynParamManager dynManager; //!< -- Dynamics parameter manager for all effectors StateVecIntegrator *integrator; //!< -- Integrator used to propagate state forward public: DynamicObject(); //!< -- Constructor virtual ~DynamicObject(); //!< -- Destructor virtual void initializeDynamics(); //!< -- Initializes the dynamics and variables virtual void computeEnergyMomentum(double t); //!< -- Method to compute energy and momentum of the system virtual void UpdateState(uint64_t callTime) = 0; //!< -- This hooks the dyn-object into Basilisk architecture virtual void equationsOfMotion(double t) = 0; //!< -- This is computing F = Xdot(X,t) virtual void integrateState(double t) = 0; //!< -- This method steps the state forward in time void setIntegrator(StateVecIntegrator *newIntegrator); //!< -- Sets a new integrator }; #endif /* DYNAMICOBJECT_H */
[ "will.flowers.95@gmail.com" ]
will.flowers.95@gmail.com
90b70f1f05e3b5e5fd47b77caef289db29558c78
a69042cde9531714459b2e2608f2e1a7ef809039
/cd5/정보올림피아드관련/정보올림피아드관련/KOI4U NET KOI 96~01/eunjae85.new21.org/LECTURE2/CKOI98M1.CPP
6a82a35c9dee00c2ec4b6184191c715ac25a7f31
[]
no_license
almoreir/algorithm
7ebb8b79cfd92208df6db4425f5cb49ee06a50be
af74200d33cf89b038016311efd3487c58132bb3
refs/heads/master
2020-09-03T07:13:53.305987
2016-11-02T10:09:45
2016-11-02T10:09:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,119
cpp
#include <fstream.h> #include <stdlib.h> int n; int e[100][100]; int g[100]; int gc = 0; void output2 () { ofstream out ("output.txt"); out << 0 << endl; out.close (); exit (0); } void input () { ifstream in ("input.txt"); in >> n; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { in >> e[i][j]; if ((i > j) && (e[i][j] != e[j][i])) output2 (); } in.close (); } void process () { int flag; for (int i = 0; i < n; i++) { flag = 0; for (int j = 0; j < gc; j++) { for (int k = 0; k < i; k++) if ((g[k] == j) && e[i][k]) flag = 1; if (flag == 0) { g[i] = j; flag = 1; break; } flag = 0; } if (flag == 0) { g[i] = gc; gc++; } } int count; for (i = 0; i < gc; i++) { count = 0; for (int j = 0; j < n; j++) if (g[j] == i) count++; if (count < 2) output2 (); } } void output () { ofstream out ("output.txt"); out << gc << endl; for (int i = 0; i < gc; i++) { for (int j = 0; j < n; j++) if (g[j] == i) out << j + 1 << ' '; out << endl; } out.close (); } void main() { input (); process (); output (); }
[ "pooh0216@gmail.com" ]
pooh0216@gmail.com
e377974779eec75d5ee876da8312d07e85388af8
4d1fad3c0b901d4a1dcefaa433ca0e52920ff23c
/Basic.Data.Structures/LinkedList/LinkedList/LinkedList.h
69e348dace8de952243ea7e8c813c64a938236c0
[ "MIT" ]
permissive
pipecaniza/Data.Structures
350b32dac5977e9ca524fbe587e23ef292b2f987
5857cfbc7088f22ffd3496b95a5cea925c552da3
refs/heads/master
2020-05-17T06:39:18.404001
2015-08-04T06:39:19
2015-08-04T06:39:19
40,167,697
1
0
null
null
null
null
UTF-8
C++
false
false
1,685
h
#pragma once template<typename T> struct Node { T Value; Node<T>* Next; Node(const T& value) { Value = value; Next = nullptr; } ~Node(){} }; template<typename T> class LinkedList { private: Node<T>* First; Node<T>* Last; int size; public: LinkedList() { this->First = nullptr; this->Last = nullptr; this->size = 0; } ~LinkedList() { Node<T>* current = this->First; while (current != nullptr) { Node<T>* next = current->Next; delete current; current = next; } } void push_back(const T& elem) { if (this->First == nullptr) { this->First = new Node<T>(elem); this->Last = this->First; this->size++; } else{ this->Last->Next = new Node<T>(elem); this->Last = Last->Next; this->size++; } } void remove(const int& at) { if (at == 0){ Node<T>* ptr_aux = this->First->Next; delete this->First; this->First = ptr_aux; this->size--; return; } Node<T>* previous = nullptr; Node<T>* current = this->First; // size_t -> unsigned int for (size_t i = 0; i < at && i < this->size; i++) { previous = current; current = current->Next; } delete previous->Next; previous->Next = current; this->size--; } int find(const T& obj) { Node<T>* current = this->First; // size_t -> unsigned int for (size_t i = 0; i < this->size; i++) { if (current->Value == obj) return i; current = current->Next; } return -1; } // O(n) Node<T>& operator [](const int& target) { if (target > this->size) return *(this->Last); Node<T>* current = this->First; for (size_t i = 0; i < target; i++) { current = current->Next; } return *current; } };
[ "pipecaniza@outlook.com" ]
pipecaniza@outlook.com
459b804b73bd7fe7fc3781cfeb3e13d6f5e7839d
a0b0eb383ecfeaeed3d2b0271657a0c32472bf8e
/leetcode/1001-2000/1080-insufficient-nodes-in-root-to-leaf-paths.cpp
93ff073d28a4692b04ab22afdcdc1dcadf44be4e
[ "Apache-2.0" ]
permissive
tangjz/acm-icpc
45764d717611d545976309f10bebf79c81182b57
f1f3f15f7ed12c0ece39ad0dd044bfe35df9136d
refs/heads/master
2023-04-07T10:23:07.075717
2022-12-24T15:30:19
2022-12-26T06:22:53
13,367,317
53
20
Apache-2.0
2022-12-26T06:22:54
2013-10-06T18:57:09
C++
UTF-8
C++
false
false
1,084
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { TreeNode *dfs(TreeNode *rt, int lim, int cur, int &ret) { if(rt == nullptr) return nullptr; if(rt -> left == nullptr && rt -> right == nullptr) { ret = rt -> val; return cur + ret >= lim ? rt : nullptr; } for(TreeNode **ptr: {&(rt -> left), &(rt -> right)}) { int tmp = INT_MIN; *ptr = dfs(*ptr, lim, cur + (rt -> val), tmp); if(tmp > INT_MIN) ret = max(ret, rt -> val + tmp); } return cur + ret >= lim ? rt : nullptr; } public: TreeNode* sufficientSubset(TreeNode* root, int limit) { int upp = INT_MIN; return dfs(root, limit, 0, upp); } };
[ "t251346744@gmail.com" ]
t251346744@gmail.com
698b956dbcc7cd7622d3607d4aba9b8b938834a4
02ae3c40379fdedd39979f71ea89a231b1670f31
/HawkEye/MediaArchieve/MediaCQ_ErrorDetectMedhods/0x00000001_EdgeBlockiness_src/DetectEdgeBlockiness.h
ef5eacc3b05f20a17c0633232978962c9361bf5d
[]
no_license
mmhasan023/VED-200
6e78f9dfd05a9861ab04cca6d6a4ff8fee575ed8
c1b1e808570b12fc86b3bb7143b30c8acfeebb2f
refs/heads/master
2020-03-19T07:56:58.848301
2018-06-06T06:04:03
2018-06-06T06:04:03
136,163,025
0
0
null
null
null
null
UTF-8
C++
false
false
1,832
h
//DetecEdgeBlockiness.h //Detection Edge Blockiness //By kiok ahn //2012.02.06 #ifndef _CEDGE_BLOCKINESS_H_INCLUDE_ #define _CEDGE_BLOCKINESS_H_INCLUDE_ #include "stdafx.h" #include "TTypeDefine.h" #include "CommonDataApi.h" class C1DImpulseEdgeDetectionRT; class CImpulseDetectByMedian; class CDetectionEdgeBlockiness { public: CDetectionEdgeBlockiness(void); ~CDetectionEdgeBlockiness(void); public: HRESULT CheckStream ( LPAVDATA lpAVData ); void SetCallback ( LPFN_AVRESULT lpCallback, LPVOID lpUserData ); HRESULT FinishedStream( void ); HRESULT SetOption ( LPSTR_MAP lpmapOption ); protected: void LoadCommonDLL ( void ); HRESULT SendErrorFrame( LPAVDATA lpAVData, const int& nTargetFrame ); HRESULT ImpulseNoiseEnhance(LPAVDATA lpAVData); HRESULT CheckStreamSobel60Hypotenuse(LPAVDATA lpAVData); HRESULT CheckStreamSobel16Hypotenuse(LPAVDATA lpAVData); private: AVRESULT m_AVResult ; CVIDEOAPI m_VideoApi ; LPFN_AVRESULT m_lpCallback ; LPVOID m_lpUserData ; HINSTANCE m_hCommonDLL ; DWORD m_dwDetecedFlag ; BOOL m_bInitialize ; protected: int m_nWindowSize ; INT m_nWidth ; INT m_nHeight ; INT m_nSize ; DWORD m_dwTotalFrames ; BYTE* m_pGrayPhase ; long* m_pHistogramPhase ; C1DImpulseEdgeDetectionRT** m_ppErrorDector; CImpulseDetectByMedian** m_ppEDByMedian; protected: time_t m_tAlramSystemStartTime ; time_t m_tAlramSystemEndTime ; DWORD m_dwNoneDetectEndFrame ; DWORD m_dwNoneDetectStartFrame; BYTE m_ucNoneDetectStartRatio; BYTE m_ucNoneDetectEndRatio ; }; #endif//_CEDGE_BLOCKINESS_H_INCLUDE_
[ "36214486+mmhasan023@users.noreply.github.com" ]
36214486+mmhasan023@users.noreply.github.com
11de1c6c88bbaf64b73bfbf5ea896561562afe6a
bf514223b63f968c29292149c79545922623c3ff
/120406.cpp
a47c5eda882522fd4fc872eb8a2dab3bc93cde19
[]
no_license
wxlARG/leetcode
f76a1ad986b5f8d45e837673ca3d17de10c9e6d3
ac72bdccb72f98b43f7236159246cda2253222ef
refs/heads/master
2021-01-01T05:47:15.667603
2018-06-03T12:43:07
2018-06-03T12:43:07
39,574,886
1
0
null
null
null
null
UTF-8
C++
false
false
1,237
cpp
#include<iostream> #include<vector> #include<deque> #include<string> #include<iterator> #include<algorithm> #include<cstring> #include<climits> using namespace std; bool searchMatrix(vector<vector<int> > &matrix, int target) { int start = 0; int end = matrix.size()-1; int row; while(start <= end) { int mid = start+(end-start)/2; if(matrix[mid][0] > target) end = mid-1; else if(matrix[mid][0] < target) { if(mid<matrix.size()-1 && matrix[mid+1][0]>target) { row = mid; break; } else start = mid+1; } else return true; } if(end < 0) return false; if(start > matrix.size()-1) row = matrix.size()-1; start = 0; end = matrix[row].size()-1; while(start <= end) { int mid = start+(end-start)/2; if(matrix[row][mid] > target) end = mid-1; else if(matrix[row][mid] < target) start = mid+1; else return true; } return false; } int main() { int arr[][4] = { {1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 50} }; vector<vector<int> > matrix; for(int i=0; i<3; ++i) { vector<int> tmp; for(int j=0; j<4; ++j) tmp.push_back(arr[i][j]); matrix.push_back(tmp); } bool result = searchMatrix(matrix,8); cout << result << endl; return 0; }
[ "wxl890206@126.com" ]
wxl890206@126.com
c0db86760d8c573b94c5fc4fb47c13cd8647e6d5
1073f60829eb29bb4ba4f8436046936eb7344212
/MPI-2-C++/contrib/test_suite/sendrecv_rep.cc
dcc85b135c97f45fa3f614680f86664d167d66f9
[ "LicenseRef-scancode-notre-dame", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
matthiasdiener/mpich
c6f369b5e1cd45ab51e8ee2d7b7319f049e6897f
8c5903e77ee847b4f22cde6f9313ad5f46e68d64
refs/heads/master
2021-05-12T04:32:41.235171
2018-01-11T23:22:17
2018-01-11T23:22:17
117,158,857
0
0
null
null
null
null
UTF-8
C++
false
false
5,843
cc
// Copyright 1997-2000, University of Notre Dame. // Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and // Andrew Lumsdaine // // This file is part of the Notre Dame C++ bindings for MPI. // // You should have received a copy of the License Agreement for the Notre // Dame C++ bindings for MPI along with the software; see the file // LICENSE. If not, contact Office of Research, University of Notre // Dame, Notre Dame, IN 46556. // // Permission to modify the code and to distribute modified code is // granted, provided the text of this NOTICE is retained, a notice that // the code was modified is included with the above COPYRIGHT NOTICE and // with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE // file is distributed with the modified code. // // LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. // By way of example, but not limitation, Licensor MAKES NO // REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY // PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS // OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS // OR OTHER RIGHTS. // // Additional copyrights may follow. /**************************************************************************** MESSAGE PASSING INTERFACE TEST CASE SUITE Copyright IBM Corp. 1995 IBM Corp. hereby grants a non-exclusive license to use, copy, modify, and distribute this software for any purpose and without fee provided that the above copyright notice and the following paragraphs appear in all copies. IBM Corp. makes no representation that the test cases comprising this suite are correct or are an accurate representation of any standard. In no event shall IBM be liable to any party for direct, indirect, special incidental, or consequential damage arising out of the use of this software even if IBM Corp. has been advised of the possibility of such damage. IBM CORP. SPECIFICALLY DISCLAIMS ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS AND IBM CORP. HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. **************************************************************************** These test cases reflect an interpretation of the MPI Standard. They are are, in most cases, unit tests of specific MPI behaviors. If a user of any test case from this set believes that the MPI Standard requires behavior different than that implied by the test case we would appreciate feedback. Comments may be sent to: Richard Treumann treumann@kgn.ibm.com **************************************************************************** */ #include "mpi2c++_test.h" void sendrecv_rep() { char msg[150]; int buf[1000]; int dest; int i; int recvtag; int sendtag; int src; MPI::Status status; Testing("Sendrecv_rep w/ Status"); if(my_rank < 2) { src = dest = 1 - my_rank; sendtag = my_rank; recvtag = src; for(i = 0; i < 100; i++) buf[i] = my_rank; MPI::COMM_WORLD.Sendrecv_replace(buf, 100, MPI::INT, dest, sendtag, src, recvtag, status); for(i = 0; i < 100; i++) if(buf[i] != src) { sprintf(msg, "NODE %d - 1) ERROR in MPI::Sendrecv_rep, buf[%d] = %d, should be %d", my_rank, i, buf[i], src); Fail(msg); } if(status.Get_source() != src) { sprintf(msg, "NODE %d - 2) ERROR IN MPI::Sendrecv_rep, source = %d, should be %d", my_rank, status.Get_source(), src); Fail(msg); } if(status.Get_tag() != recvtag) { sprintf(msg, "NODE %d - 3) ERROR in MPI::Sendrecv_rep, tag = %d, should be %d", my_rank, status.Get_tag(), recvtag); Fail(msg); } } src = (my_rank == 0) ? comm_size - 1 : my_rank - 1; dest = (my_rank == comm_size - 1) ? 0 : my_rank + 1; sendtag = my_rank; recvtag = src; for(i = 0; i < 100; i++) buf[i] = my_rank; MPI::COMM_WORLD.Sendrecv_replace(buf, 100, MPI::INT, dest, sendtag, src, recvtag, status); for(i = 0; i < 100; i++) if(buf[i] != src) { sprintf(msg, "NODE %d - 4) ERROR in MPI::Sendrecv_rep, buf[%d] = %d, should be %d", my_rank, i, buf[i], src); Fail(msg); } if(status.Get_source() != src) { sprintf(msg, "NODE %d - 5) ERROR IN MPI::Sendrecv_rep, source = %d, should be %d", my_rank, status.Get_source(), src); Fail(msg); } if(status.Get_tag() != recvtag) { sprintf(msg, "NODE %d - 6) ERROR in MPI::Sendrecv_rep, tag = %d, should be %d", my_rank, status.Get_tag(), recvtag); Fail(msg); } Pass(); // Sendrecv_rep w/ Status MPI::COMM_WORLD.Barrier(); Testing("Sendrecv_rep w/o Status"); if(my_rank < 2) { src = dest = 1 - my_rank; sendtag = my_rank; recvtag = src; for(i = 0; i < 100; i++) buf[i] = my_rank; MPI::COMM_WORLD.Sendrecv_replace(buf, 100, MPI::INT, dest, sendtag, src, recvtag); for(i = 0; i < 100; i++) if(buf[i] != src) { sprintf(msg, "NODE %d - 7) ERROR in MPI::Sendrecv_rep, buf[%d] = %d, should be %d", my_rank, i, buf[i], src); Fail(msg); } } src = (my_rank == 0) ? comm_size - 1 : my_rank - 1; dest = (my_rank == comm_size - 1) ? 0 : my_rank + 1; sendtag = my_rank; recvtag = src; for(i = 0; i < 100; i++) buf[i] = my_rank; MPI::COMM_WORLD.Sendrecv_replace(buf, 100, MPI::INT, dest, sendtag, src, recvtag, status); for(i = 0; i < 100; i++) if(buf[i] != src) { sprintf(msg, "NODE %d - 8) ERROR in MPI::Sendrecv_rep, buf[%d] = %d, should be %d", my_rank, i, buf[i], src); Fail(msg); } Pass(); // Sendrecv_rep w/o Status MPI::COMM_WORLD.Barrier(); }
[ "mdiener@illinois.edu" ]
mdiener@illinois.edu
8f43daf824893522f51b5069f1c43caa943bdc3d
de8eab8f6844a07379033e6efea010e14622c3c2
/Deianeira/exe/Deianeira/Deianeira/FileRenameForm.h
75b76f6181b39fa461740d9e43e882f8c767e8b4
[]
no_license
renecn/openlibs
62b51bdb1e05673cfadabcabcad83ec039dbe3c9
24b9aea915ed7ea9b56f4aadbcaa0aa2738f2f69
refs/heads/master
2020-05-14T14:30:02.704419
2016-01-01T16:14:07
2016-01-01T16:14:07
null
0
0
null
null
null
null
GB18030
C++
false
false
4,592
h
#pragma once namespace Deianeira { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace Microsoft::VisualBasic::FileIO; /// <summary> /// FileRenameForm 摘要 /// </summary> public ref class FileRenameForm : public System::Windows::Forms::Form { public: FileRenameForm(ListViewItem^ item_) { InitializeComponent(); // //TODO: 在此处添加构造函数代码 // this->item_ = item_; } FileRenameForm(TreeNode^ tn_) { InitializeComponent(); // //TODO: 在此处添加构造函数代码 // this->tn_ = tn_; } protected: /// <summary> /// 清理所有正在使用的资源。 /// </summary> ~FileRenameForm() { if (components) { delete components; } } private: System::Windows::Forms::TextBox^ txtName; protected: private: System::Windows::Forms::Button^ btnOK; private: System::Windows::Forms::Button^ btnQuit; protected: private: /// <summary> /// 必需的设计器变量。 /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> void InitializeComponent(void) { this->txtName = (gcnew System::Windows::Forms::TextBox()); this->btnOK = (gcnew System::Windows::Forms::Button()); this->btnQuit = (gcnew System::Windows::Forms::Button()); this->SuspendLayout(); // // txtName // this->txtName->Location = System::Drawing::Point(12, 12); this->txtName->Name = L"txtName"; this->txtName->Size = System::Drawing::Size(272, 21); this->txtName->TabIndex = 0; // // btnOK // this->btnOK->Location = System::Drawing::Point(128, 39); this->btnOK->Name = L"btnOK"; this->btnOK->Size = System::Drawing::Size(75, 23); this->btnOK->TabIndex = 1; this->btnOK->Text = L"确定"; this->btnOK->UseVisualStyleBackColor = true; this->btnOK->Click += gcnew System::EventHandler(this, &FileRenameForm::btnOK_Click); // // btnQuit // this->btnQuit->Location = System::Drawing::Point(209, 39); this->btnQuit->Name = L"btnQuit"; this->btnQuit->Size = System::Drawing::Size(75, 23); this->btnQuit->TabIndex = 2; this->btnQuit->Text = L"取消"; this->btnQuit->UseVisualStyleBackColor = true; this->btnQuit->Click += gcnew System::EventHandler(this, &FileRenameForm::btnQuit_Click); // // FileRenameForm // this->AutoScaleDimensions = System::Drawing::SizeF(6, 12); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(297, 70); this->Controls->Add(this->btnQuit); this->Controls->Add(this->btnOK); this->Controls->Add(this->txtName); this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedDialog; this->MaximizeBox = false; this->Name = L"FileRenameForm"; this->ShowInTaskbar = false; this->StartPosition = System::Windows::Forms::FormStartPosition::CenterParent; this->Text = L"重命名"; this->Load += gcnew System::EventHandler(this, &FileRenameForm::FileRenameForm_Load); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion ListViewItem^ item_; TreeNode^ tn_; //窗体加载事件 private: System::Void FileRenameForm_Load(System::Object^ sender, System::EventArgs^ e) { if (item_!=nullptr) { this->txtName->Text = item_->SubItems[0]->Text; txtName->SelectAll(); } else { this->txtName->Text = tn_->Text; txtName->SelectAll(); } } //确定 private: System::Void btnOK_Click(System::Object^ sender, System::EventArgs^ e) { try { if (item_!=nullptr) { if (item_->SubItems[2]->Text == "文件夹") { FileSystem::RenameDirectory(item_->Tag->ToString(),txtName->Text); } else { FileSystem::RenameFile(item_->Tag->ToString(),txtName->Text); } item_->SubItems[0]->Text = txtName->Text; } else { FileSystem::RenameDirectory(tn_->Tag->ToString(),txtName->Text); tn_->Text = txtName->Text; } this->Close(); } catch (Exception^ ex) { MessageBox::Show(ex->Message); } } //取消 private: System::Void btnQuit_Click(System::Object^ sender, System::EventArgs^ e) { this->Close(); } }; }
[ "gerronjo@gmail.com" ]
gerronjo@gmail.com
6e18ff24a774ac6895949c89b927e00b80de2eb8
f88d8da07e0b3f15d53deb673c552ac0588b67fc
/codelite/WarriorInputComponent.h
fc8836dc04e02ee40ccc5057048e35103799e160
[]
no_license
StevenJHulshof/sdl_sdk
cf285608c74471d2aa484b4116465816fee7e43c
5eb8c2c24ad314f9b62bc1e5f99058f015481f20
refs/heads/master
2021-08-30T11:05:09.973950
2017-12-13T22:14:29
2017-12-13T22:14:29
107,877,339
0
0
null
null
null
null
UTF-8
C++
false
false
562
h
#pragma once #include "UnitInputComponent.h" template <class obj_t> class WarriorInputComponent: public UnitInputComponent<obj_t> { public: WarriorInputComponent(); virtual ~WarriorInputComponent(); virtual void update(); }; template <class obj_t> WarriorInputComponent<obj_t>::WarriorInputComponent(): UnitInputComponent<obj_t>() { } template <class obj_t> WarriorInputComponent<obj_t>::~WarriorInputComponent() { } template <class obj_t> void WarriorInputComponent<obj_t>::update() { InputComponent<obj_t>::update(); }
[ "steven.j.hulshof@gmail.com" ]
steven.j.hulshof@gmail.com
63df2a4bd80f1d64eb5faa8c1e2199743d213740
f31a6906f589ceedba8350fdaf1389aafcad1611
/CvGameCoreDLL/RiseFall.cpp
b077b99dde986ed5084be1280796531bbd9ef6d3
[]
no_license
f1rpo/AdvCiv
8ff751901b88473105a06768b7ce343028c77a7d
56c03ce198957509be42b2dadda05fc321d8f383
refs/heads/master
2023-08-10T22:30:54.460007
2023-06-10T17:32:22
2023-06-10T17:32:22
88,413,773
20
11
null
2022-01-24T18:46:35
2017-04-16T13:06:59
C++
UTF-8
C++
false
false
51,225
cpp
#include "CvGameCoreDLL.h" #include "RiseFall.h" #include "CvInfo_GameOption.h" #include "CoreAI.h" #include "CvCityAI.h" #include "CvSelectionGroup.h" #include "CvDeal.h" #include "UWAIAgent.h" // advc.104 #include "CvTalkingHeadMessage.h" #include "CvPopupInfo.h" #include "CvReplayInfo.h" #include "CvPlot.h" using std::wstringstream; using std::vector; using std::wstring; using std::pair; using std::make_pair; using namespace fmath; // Single-player only, so this is fine. // advc: namespace { __inline PlayerTypes getActivePlayer() { return GC.getGame().getActivePlayer(); } } RiseFall::RiseFall() { originalName = NULL; reset(); } RiseFall::~RiseFall() { reset(); } void RiseFall::reset() { interludeLength = interludeCountdown = -1; selectingCiv = retryingCivSelection = false; SAFE_DELETE(originalName); for(size_t i = 0; i < chapters.size(); i++) SAFE_DELETE(chapters[i]); chapters.clear(); offLimits.clear(); clearDiploStrings(); riseScore.reset(); } void RiseFall::init() { // Caller can't tell whether initialization already done if(!chapters.empty()) return; CvGame& g = GC.getGame(); if(g.isGameMultiPlayer()) { shutOff(gDLL->getText("TXT_KEY_RF_SINGLEPL_ONLY")); return; } for(int i = 0; i < MAX_TEAMS; i++) { CvTeam const& t = GET_TEAM((TeamTypes)i); if(t.getNumMembers() > 1) { shutOff(gDLL->getText("TXT_KEY_RF_NO_TEAMS")); return; } } vector<GameOptionTypes> incompatible; incompatible.push_back(GAMEOPTION_SPAH); incompatible.push_back(GAMEOPTION_PERMANENT_ALLIANCES); incompatible.push_back(GAMEOPTION_ONE_CITY_CHALLENGE); for(size_t i = 0; i < incompatible.size(); i++) { if(g.isOption(incompatible[i])) { shutOff(gDLL->getText("TXT_KEY_RF_INVALID_OPTION", GC.getInfo(incompatible[i]).getTextKeyWide())); return; } } int maxChapters = GC.getDefineINT("RF_CHAPTERS_BASE"); CvGameSpeedInfo& speed = GC.getInfo(g.getGameSpeedType()); double chapterModifier = (speed.getGoldenAgePercent() + 100) / 200.0; int startTurn = g.getStartTurn(); int endTurn = g.getEstimateEndTurn(); int totalTurns = endTurn - startTurn; chapterModifier *= totalTurns / (double)endTurn; int civs = g.countCivPlayersAlive(); { // If few civs, stick to unmodified maxChapters. int maxChaptersModified = ::round(maxChapters * chapterModifier); if(maxChaptersModified > maxChapters) { int bound = std::max(::round(civs / 1.51), maxChapters); maxChapters = std::min(bound, maxChaptersModified); } else maxChapters = maxChaptersModified; } maxChapters = std::min(civs, maxChapters); if(maxChapters < 1) { shutOff(gDLL->getText("TXT_KEY_RF_INVALID_CHAPTERS", maxChapters)); return; } interludeLength = GC.getDefineINT("RF_INTERLUDE_LENGTH_BASE"); interludeLength = ::range(::round((interludeLength * speed.getTrainPercent()) / 100.0), std::min(interludeLength, 5), std::max(interludeLength, 10)); int playLength = totalTurns - (maxChapters - 1) * interludeLength; int partialLength = 0; for(int i = 0; i < maxChapters - 1; i++) { chapters.push_back(new RFChapter(i, maxChapters, playLength)); partialLength += chapters[i]->getLength(); } int finalChLen = playLength - partialLength; bool timeLimit = (g.getMaxTurns() > 0); if(!timeLimit) finalChLen = -1; chapters.push_back(new RFChapter(maxChapters - 1, maxChapters, playLength, finalChLen)); FAssert(chapters.size() == maxChapters); if(!chapters.empty() && !timeLimit) chapters[chapters.size() - 1]->setEndless(true); for(size_t i = 0; i < chapters.size(); i++) { int len = chapters[i]->getLength(); if(len < 10 && !chapters[i]->isEndless()) { shutOff(gDLL->getText("TXT_KEY_RF_CHAPTER_TOO_SHORT", (int)i, len)); return; } } double delayFirst = GC.getDefineINT("RF_SCORING_DELAY_FIRST") / 100.0; double delayPenult = GC.getDefineINT("RF_SCORING_DELAY_PENULTIMATE") / 100.0; int chapterStart = startTurn; for(size_t i = 0; i < chapters.size(); i++) { int nextChapterLength = (i >= chapters.size() - 1 ? 0 : chapters[i + 1]->getLength()); if(nextChapterLength <= 0) chapters[i]->setDelay(-10000); // For a negative scoreTurn else { double delayMultiplier = delayPenult; if(maxChapters != 2) { delayMultiplier = delayFirst + i * (delayPenult - delayFirst) / (maxChapters - 2); } chapters[i]->setDelay(interludeLength + ::range((int)( // Round down // Avoid very long delays when chapters are long std::min(speed.getGoldenAgePercent(), nextChapterLength) * delayMultiplier) + 1, 5, nextChapterLength - 5)); } chapters[i]->setStartTurn(chapterStart); chapterStart += chapters[i]->getLength() + interludeLength; } FAssert(chapterStart - interludeLength == endTurn || !timeLimit); chapters[0]->setCiv(getActivePlayer()); chapters[0]->start(); originalName = new CvWString(GC.getInitCore().getLeaderName(chapters[0]->getCiv())); setPlayerName(); /* When the EXE calls CvGameTextMgr::getTurnTimerText on turn 0, RiseFall isn't initialized yet. Refresh the timer now that initialization is through. */ gDLL->UI().setDirty(TurnTimer_DIRTY_BIT, true); /* Initial auto-save. Normally happens already in CvGame::update, but RiseFall isn't yet initialized then. */ g.autoSave(true); g.showDawnOfMan(); } // Needs to happen earlier than init, hence a separate public function. void RiseFall::setPlayerHandicap(PlayerTypes civId, bool bHuman, bool bIncrease) { HandicapTypes const eGameHandicap = GC.getGame().getHandicapType(); int iAdjust = (!bIncrease ? 0 : range(GC.getDefineINT(CvGlobals::RF_PLAYER_HANDICAP_ADJUSTMENT), -eGameHandicap, GC.getNumHandicapInfos() - eGameHandicap - 1)); GC.getInitCore().setHandicap(civId, (HandicapTypes)(bHuman ? eGameHandicap + iAdjust : GC.getGame().getAIHandicap() + iAdjust)); /* (Caller will have to call CvGame::updateAIHandicap if several AI player handicaps are changed, i.e. if the avg. handicap may have changed.) */ CvPlayerAI& kCiv = GET_PLAYER(civId); kCiv.updateMaintenance(); kCiv.AI_makeAssignWorkDirty(); // (Further updates might be warranted) } void RiseFall::write(FDataStreamBase* pStream) { int savegameVersion = 1; // For later changes that may break compatibility pStream->Write(savegameVersion); bool origNameGiven = (originalName != NULL); pStream->Write(origNameGiven); if(origNameGiven) pStream->WriteString(originalName->c_str()); pStream->Write(interludeLength); pStream->Write(interludeCountdown); pStream->Write((int)offLimits.size()); for(std::set<TeamTypes>::const_iterator it = offLimits.begin(); it != offLimits.end(); ++it) pStream->Write(*it); pStream->Write((int)chapters.size()); for(size_t i = 0; i < chapters.size(); i++) chapters[i]->write(pStream); riseScore.write(pStream); } void RiseFall::read(FDataStreamBase* pStream) { reset(); int savegameVersion = -1; pStream->Read(&savegameVersion); if(savegameVersion >= 1) { // else leave it as NULL bool origNameGiven = false; pStream->Read(&origNameGiven); if(origNameGiven) { wchar* tmp = pStream->ReadWideString(); originalName = new CvWString(tmp); delete tmp; } } pStream->Read(&interludeLength); pStream->Read(&interludeCountdown); int sz = -1; pStream->Read(&sz); for(int i = 0; i < sz; i++) { int tId = -1; pStream->Read(&tId); offLimits.insert((TeamTypes)tId); } pStream->Read(&sz); for(int i = 0; i < sz; i++) { chapters.push_back(new RFChapter()); chapters[i]->read(pStream); } // E.g. CvPlot::m_bAllFog not saved FAssertMsg(interludeCountdown < 0, "Mustn't load into interlude"); riseScore.read(pStream); } int RiseFall::getInterludeCountdown() const { return interludeCountdown; } void RiseFall::reportElimination(PlayerTypes civId) { int pos = getCurrentChapter(); if(pos < 0) return; if(pos > 0 && chapters[pos - 1]->getCiv() == civId) chapters[pos - 1]->score(); if(chapters[pos]->getCiv() == civId) { chapters[pos]->score(); setPlayerControl(civId, false); CvPlayer& nextAlive = GET_PLAYER(nextCivAlive(BARBARIAN_PLAYER)); if(pos < (int)(chapters.size() - 1)) { GC.getGame().setActivePlayer(nextAlive.getID()); nextAlive.setIsHuman(true); nextAlive.setNetID(0); CvPopupInfo* popup = new CvPopupInfo(BUTTONPOPUP_RF_DEFEAT); // So that launchDefeatPopup knows which chapter we've just scored (ended) popup->setData1(pos); nextAlive.addPopup(popup, true); } else { setPlayerControl(nextAlive.getID(), true); if(originalName != NULL) GC.getInitCore().setLeaderName(nextAlive.getID(), *originalName); FAssert(GC.getGame().countHumanPlayersAlive() > 0); // End the game directly when defeated in the final chapter GC.getGame().setGameState(GAMESTATE_OVER); } } } void RiseFall::retire() { int pos = getCurrentChapter(); if(pos < 0) return; int t = getRetireTurns(); if(t <= 0) return; CvGame& g = GC.getGame(); if(chapters[pos]->getRetireTurn() < 0) // Don't store multiple timestamps chapters[pos]->setRetireTurn(g.getGameTurn()); g.setAIAutoPlay(t); /* Don't do this. CvPlayer not yet loaded. No need either - plans already abandoned at start of retirement. */ //abandonPlans(chapters[pos]->getCiv()); } int RiseFall::getRetireTurns() const { int pos = getCurrentChapter(); if(pos < 0) return 0; return chapters[pos]->getEndTurn() - GC.getGame().getGameTurn() + 1; } bool RiseFall::hasRetired() const { int pos = getCurrentChapter(); if(pos < 0) return false; int t = chapters[pos]->getRetireTurn(); return t >= 0 && t <= GC.getGame().getGameTurn(); } int RiseFall::getAutoPlayCountdown() const { if(isSelectingCiv()) /* Not sure if needed; be sure we're not showing a countdown while the popup is open. */ return 0; PlayerTypes activePl = getActivePlayer(); if(activePl == NO_PLAYER) { FAssert(activePl != NO_PLAYER); return -1; } CvPlayer const& pl = GET_PLAYER(activePl); if(pl.isHuman() && !pl.isHumanDisabled()) // Normal play return 0; if(hasRetired() && pl.isHumanDisabled()) { int r = GC.getGame().getAIAutoPlay(); if(interludeCountdown < 0) // Anticipate interlude r += interludeLength; else r += interludeCountdown; return r + 1; // +1 for the turn of retirement } // +1 for the turn on which the chapter is ended return std::max(0, interludeCountdown + 1); } void RiseFall::atTurnEnd(PlayerTypes civId) { /* Would rather get a call right before the turn of a civ begins, but can't find this in the DLL code; only for civ 0 (atActiveTurnStart). */ CvGame& g = GC.getGame(); if(g.getGameState() == GAMESTATE_EXTENDED) return; int gameTurn = g.getGameTurn(); // The chapter of civ 0 needs to be started at the end of the previous game turn if(civId == BARBARIAN_PLAYER) gameTurn++; /* Conduct scoring exactly as scheduled at the end of a turn of the civ being scored; show the score popup at the start of the next active player turn. */ for(size_t i = 0; i < chapters.size(); i++) { if(chapters[i]->getCiv() == civId && chapters[i]->getScoreTurn() == gameTurn) chapters[i]->score(); } int currentChPos = getCurrentChapter(); if(currentChPos < 0 || currentChPos >= (int)chapters.size()) { FAssertMsg(currentChPos < 0 || interludeCountdown < 0, "Interlude past final chapter"); return; } RFChapter& currentCh = *chapters[currentChPos]; PlayerTypes nextCivId = nextCivAlive(civId); if(nextCivId == currentCh.getCiv()) { if(nextCivId != getActivePlayer()) { if(GET_PLAYER(nextCivId).isAlive()) { setPlayerControl(nextCivId, true); interludeCountdown = -1; /* Don't start a chapter across a game turn (i.e. during the barbs' turn). Switching to civ 0 is handled by atGameTurnStart. */ if(nextCivId != (PlayerTypes)0) currentCh.start(); } else if(!currentCh.isScored()) { /* If scored, then defeat happened after starting the chapter, and normal civ selection is coming up. Otherwise, nextCiv has died in between selection and chapter start. */ retryingCivSelection = true; haltForCivSelection(nextCivAlive(nextCivId)); } } } if(gameTurn == currentCh.getEndTurn() && civId == currentCh.getCiv()) { currentCh.setScoreAtEnd(currentCh.computeScore()); // Even if interludeLength is 0, parts of a round need to be skipped interludeCountdown = interludeLength; g.setAIAutoPlay(0); // In case that the player has retired setPlayerControl(currentCh.getCiv(), false); abandonPlans(currentCh.getCiv()); CvWString replayText = gDLL->getText("TXT_KEY_RF_INTERLUDE_STARTED"); g.addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, getActivePlayer(), replayText, GC.getColorType("HIGHLIGHT_TEXT")); } } void RiseFall::atGameTurnStart() { CvGame const& g = GC.getGame(); int currentChPos = getCurrentChapter(); if(currentChPos < 0 || interludeCountdown > 0) { interludeCountdown--; /* I'd like to keep the camera in one place during interlude, but this only turns into a tug of war when the player moves the camera. */ //centerCamera(getActivePlayer()); return; } int gameTurn = g.getGameTurn(); RFChapter& currentCh = *chapters[currentChPos]; if(currentCh.getStartTurn() >= gameTurn) { FAssert(currentCh.getStartTurn() == gameTurn); if(currentCh.getCiv() == NO_PLAYER) haltForCivSelection(nextCivAlive(BARBARIAN_PLAYER)); } } void RiseFall::atActiveTurnStart() { int pos = getCurrentChapter(); if(pos < 0) return; // Happens on turn 0 b/c not yet initialized CvGame& g = GC.getGame(); int gameTurn = g.getGameTurn(); PlayerTypes activeId = getActivePlayer(); if(activeId == NO_PLAYER) return; CvPlayerAI& active = GET_PLAYER(activeId); RFChapter& currentCh = *chapters[pos]; if(currentCh.getCiv() != activeId) return; if(gameTurn == currentCh.getStartTurn() && pos > 0) welcomeToNextChapter(pos); g.autoSave(); if(active.isHumanDisabled()) // Only popups from here return; updateOffLimits(); /* Any civ that is a vassal of ActiveTeam at some point becomes ineligible for the next chapter */ for(size_t i = 0; i < chapters.size(); i++) { if(chapters[i]->isScored() && !chapters[i]->isScoreShown()) { CvPopupInfo* popup = new CvPopupInfo(BUTTONPOPUP_TEXT); CvWString text; wchar const* civDescr = GET_PLAYER(chapters[i]->getCiv()). getCivilizationShortDescription(); if(GET_PLAYER(chapters[i]->getCiv()).isAlive()) text = gDLL->getText("TXT_KEY_RF_POPUP_SCORE", i + 1, civDescr); else text = gDLL->getText("TXT_KEY_RF_POPUP_SCORE_EARLY", i + 1, civDescr); text.append(L":\n\n" + *chapters[i]->computeScoreBreakdown().getString()); popup->setText(text); gDLL->UI().addPopup(popup, activeId); chapters[i]->setScoreShown(true); } } if(pos < ((int)chapters.size()) - 1 && gameTurn == currentCh.getEndTurn() && GC.getDefineINT("RF_ENABLE_FINAL_TURN_POPUP") > 0) { CvPopupInfo* popup = new CvPopupInfo(BUTTONPOPUP_TEXT); CvWString text = gDLL->getText("TXT_KEY_RF_POPUP_FINAL_TURN", pos + 1); if(interludeLength > 0) text.append(gDLL->getText("TXT_KEY_RF_POPUP_AUTO_PLAY", pos + 2, interludeLength)); popup->setText(text); gDLL->UI().addPopup(popup, activeId); } vector<PlayerTypes> eligible; computeEligibleCivs(eligible, false); // Recommend retirement when top rank reached and not near victory if(pos > 0 && pos < ((int)chapters.size()) - 2 && !chapters[pos]->wasRetireRecommended() && !(((int)eligible.size()) > 1) && g.getPlayerRank(activeId) == 0 && !active.AI_atVictoryStage3()) { RFChapterScore const& sc = chapters[pos]->computeScoreBreakdown(); if(sc.getScore() >= 50 && sc.getScoreFromRemainingTime() >= 10 && sc.getInitialRank() >= 3) { CvPopupInfo* popup = new CvPopupInfo(BUTTONPOPUP_TEXT); CvWString text = gDLL->getText("TXT_KEY_RF_POPUP_RECOMMEND_RETIRE", active.getCivilizationShortDescription()); popup->setText(text); gDLL->UI().addPopup(popup, activeId); chapters[pos]->setRetireWasRecommended(true); } } } void RiseFall::setPlayerControl(PlayerTypes civId, bool b) { CvGame& g = GC.getGame(); PlayerTypes formerHumanCiv = getActivePlayer(); if(formerHumanCiv != NO_PLAYER && !GET_PLAYER(formerHumanCiv).isHuman()) formerHumanCiv = NO_PLAYER; CvPlayer& civ = GET_PLAYER(civId); if(!b || !civ.isHuman()) // Unless human control continues gDLL->UI().clearQueuedPopups(); setPlayerHandicap(civId, b, /* increase only human handicap here */ b); if(b) g.changeHumanPlayer(civId); else { civ.setNetID(-1); civ.setIsHuman(false, true); GC.getInitCore().setLeaderName(civId, GC.getInfo(civ.getLeaderType()).getDescription()); gDLL->UI().flushTalkingHeadMessages(); gDLL->UI().clearEventMessages(); gDLL->UI().clearSelectedCities(); gDLL->UI().clearSelectionList(); } // (Un)fog the map if(b || !g.isDebugMode()) { CvPlot::setAllFog(!b); if(!b) g.updateActiveVisibility(); setUIHidden(!b); } if (b) // (Otherwise CvPlayer::setIsHuman has already updated the full attitude cache) { for(int i = 0; i < MAX_CIV_PLAYERS; i++) { CvPlayerAI& other = GET_PLAYER((PlayerTypes)i); if(!other.isAlive() || other.isMinorCiv()) continue; if(other.getID() != civId && GET_TEAM(civId).isHasMet(other.getTeam())) other.AI_updateAttitude(civId); if(formerHumanCiv != NO_PLAYER && civId != formerHumanCiv && other.getID() != formerHumanCiv && GET_TEAM(formerHumanCiv). isHasMet(other.getTeam())) other.AI_updateAttitude(formerHumanCiv); } } if(b) { // Updates to apply human modifiers civ.updateWarWearinessPercentAnger(); FOR_EACH_CITY_VAR(c, civ) c->updateMaintenance(); } } void RiseFall::setUIHidden(bool b) { if(gDLL->UI().isBareMapMode() != b) gDLL->UI().toggleBareMapMode(); /* toggleScoresVisible(): Isn't actually hidden b/c CvMainInterface.py doesn't update itself during interlude. toggleTurnLog(): Can't check if it's open. */ gDLL->UI().setDiplomacyLocked(b); } void RiseFall::setPlayerName() { PlayerTypes activeCiv = getActivePlayer(); CvWString newName = GC.getInfo(GET_PLAYER(activeCiv).getLeaderType()).getDescription(); /* Must only use characters that are allowed in file names; otherwise, no replay file gets created for the HoF. */ newName += L"'"; GC.getInitCore().setLeaderName(activeCiv, newName); int pos = getCurrentChapter(); if(pos >= 0) { CvWString replayText = gDLL->getText("TXT_KEY_RF_REPLAY_NEXT_CHAPTER", pos + 1, GET_PLAYER(activeCiv).getReplayName()); GC.getGame().addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, activeCiv, replayText, GC.getColorType("HIGHLIGHT_TEXT")); } } void RiseFall::welcomeToNextChapter(int pos) { FAssert(pos > 0); /* Message about revolution from the turn before human takeover lingers for some reason (and perhaps other messages too). Player will have to check the Event Log anyway, so let's just clear the screen. */ gDLL->UI().clearEventMessages(); RFChapter& ch = *chapters[pos]; setPlayerName(); CvPlayer& p = GET_PLAYER(ch.getCiv()); /* Wrong net ids can, apparently, mess with the diplo screen, making it impossible to add certain items to the table. It's probably sufficient to set the proper ids here, but I try to keep them up to date at all times. Would be nice to let CvPlayer::setIsHuman handle that, but that may not work in multiplayer modes and would break the net id update in CvGame::setActivePlayer. */ FOR_EACH_ENUM(Player) GET_PLAYER(eLoopPlayer).setNetID(-1); p.setNetID(0); p.verifyCivics(); resetProductionDecay(p.getID()); // Doing this in setUIHidden has no effect GC.getGame().setGlobeView(false); centerCamera(p.getID()); abandonPlans(p.getID()); // Also tries to move the camera GC.getGame().showDawnOfMan(); showDoW(); showQuests(); offLimits.clear(); updateOffLimits(); } void RiseFall::resetProductionDecay(PlayerTypes civId) { /* Production decay affects only humans, so the AI ignores it. Don't want human to suffer for that after assuming control. Well, mainly, I don't want humans to be distracted by (BULL) decay warnings. I'm setting the accumulated production to 0 iff decay has already started. Either way, the decay timer gets reset to 0. */ int iBuildingThresh = GC.getDefineINT(CvGlobals::BUILDING_PRODUCTION_DECAY_TIME) * GC.getInfo(GC.getGame().getGameSpeedType()).getConstructPercent(); int iUnitThresh = GC.getDefineINT(CvGlobals::UNIT_PRODUCTION_DECAY_TIME) * GC.getInfo(GC.getGame().getGameSpeedType()).getTrainPercent(); FOR_EACH_CITY_VAR(pCity, GET_PLAYER(civId)) { FOR_EACH_ENUM(Building) { if (pCity->getBuildingProduction(eLoopBuilding) <= 0) continue; if (pCity->getBuildingProductionTime(eLoopBuilding) * 100 > iBuildingThresh) pCity->setBuildingProduction(eLoopBuilding, 0); pCity->setBuildingProductionTime(eLoopBuilding, 0); } FOR_EACH_ENUM(Unit) { if (pCity->getUnitProduction(eLoopUnit) <= 0) continue; if (pCity->getUnitProductionTime(eLoopUnit) * 100 > iUnitThresh) pCity->setUnitProduction(eLoopUnit, 0); pCity->setUnitProductionTime(eLoopUnit, 0); } } } void RiseFall::centerCamera(PlayerTypes civId) { if(GET_PLAYER(civId).hasCapital()) { /* Apparently, this has no effect, at least not at the time that I call this function. Misplaced camera is also an issue when regenerating the map or using Civ Changer (Alt+Z); perhaps can't be fixed. */ gDLL->UI().lookAt(GET_PLAYER(civId).getCapital()->getPlot().getPoint(), CAMERALOOKAT_NORMAL); // This doesn't seem to help either: /*NiPoint3 p3 = capitalPlot->getPoint(); gDLL->getEngineIFace()->ClampToWorldCoords(&p3);*/ } } void RiseFall::showDoW() { CvTeamAI& activeTeam = GET_TEAM(GC.getGame().getActiveTeam()); /* Would be nicer to show e.g. "Alexander has declared war on you in 1923", but would have to track additional info for this, or piece it together from past messages. Both too much work. */ for(int i = 0; i < MAX_CIV_PLAYERS; i++) { CvPlayer& enemy = GET_PLAYER((PlayerTypes)i); if(!enemy.isAlive() || enemy.isMinorCiv() || !activeTeam.isAtWar(enemy.getTeam())) continue; gDLL->UI().addMessage(getActivePlayer(), true, -1, gDLL->getText("TXT_KEY_YOU_AT_WAR", enemy.getName()), NULL, MESSAGE_TYPE_INFO, NULL, GC.getColorType("WARNING_TEXT"), // advc.127b: enemy.getCapitalX(activeTeam.getID(), true), enemy.getCapitalY(activeTeam.getID(), true)); } } void RiseFall::showQuests() { CvPlayer& p = GET_PLAYER(getActivePlayer()); CvMessageQueue const& archive = p.getGameMessages(); for(std::list<CvTalkingHeadMessage>::const_iterator it = archive.begin(); it != archive.end(); ++it) { // CvPlayer::expireEvent should ensure that only ongoing quests are listed if(it->getMessageType() == MESSAGE_TYPE_QUEST) { gDLL->UI().addMessage(p.getID(), true, -1, gDLL->getText("TXT_KEY_GOT_QUESTS"), NULL, MESSAGE_TYPE_INFO, NULL); return; } } } void RiseFall::abandonPlans(PlayerTypes civId) { CvPlayerAI& civ = GET_PLAYER(civId); bool active = (civId == getActivePlayer() && civ.isHuman()); FOR_EACH_GROUP_VAR(gr, civ) gr->splitGroup(1); CvCity* capital = civ.getCapital(); bool unitSelected = false; FOR_EACH_GROUP_VAR(gr, civ) { if(gr->getHeadUnit() == NULL) continue; gr->setAutomateType(NO_AUTOMATE); // Remove all but the current mission while(gr->headMissionQueueNode() != NULL && gr->nextMissionQueueNode(gr->headMissionQueueNode()) != NULL) gr->deleteMissionQueueNode(gr->nextMissionQueueNode(gr->headMissionQueueNode())); /* If it's not a BUILD mission, remove the current mission too. Also remove MISSION_ROUTE_TO b/c it's not really just a single mission. */ if(gr->getActivityType() != ACTIVITY_MISSION || gr->getMissionType(0) != MISSION_BUILD) { gr->setActivityType(ACTIVITY_AWAKE); gr->clearMissionQueue(); if(!active) continue; } // Not really the job of this function, but while we're at it: if(!unitSelected && capital != NULL && gr->atPlot(capital->plot())) { gDLL->UI().selectGroup(gr->getHeadUnit(), false, false, false); unitSelected = true; gDLL->UI().lookAtSelectionPlot(); } // Without this, units outside owner's borders don't appear on the main interface. if(gr->plot()->getOwner() != civId) gr->plot()->updateCenterUnit(); /* ^Perhaps no longer needed due to a change in CvPlot::updateVisibility (advc.061). Should test this some time. */ } // Set research slider to a balanced-budget position int incr = GC.getDefineINT("COMMERCE_PERCENT_CHANGE_INCREMENTS"); civ.setCommercePercent(COMMERCE_RESEARCH, 100); while(civ.calculateGoldRate() < 0 && civ.getCommercePercent(COMMERCE_RESEARCH) > 9) civ.setCommercePercent(COMMERCE_RESEARCH, civ.getCommercePercent(COMMERCE_RESEARCH) - incr); // 0 espionage weight for(int i = 0; i < MAX_CIV_TEAMS; i++) civ.setEspionageSpendingWeightAgainstTeam((TeamTypes)i, 0); // Clear research queue TechTypes currentTech = civ.getCurrentResearch(); if(currentTech == NO_TECH) civ.clearResearchQueue(); else civ.pushResearch(currentTech, true); FOR_EACH_CITYAI_VAR(c, civ) { // Turn off production emphasis. AvoidGrowth is also a type of emphasis. for(int i = 0; i < GC.getNumEmphasizeInfos(); i++) c->AI_setEmphasize((EmphasizeTypes)i, false); // Clear production queue c->setProductionAutomated(false, true); c->setCitizensAutomated(true); } } int RiseFall::getMaxChapters() const { return chapters.size(); } RFChapter& RiseFall::getChapter(int i) const { FAssert(i >= 0 && i < (int)chapters.size()); return *chapters[i]; } wstring* RiseFall::chapterScoreBreakdown() { int pos = getCurrentChapter(); if(pos < 0) return NULL; return chapters[pos]->computeScoreBreakdown().getString(); } wstring* RiseFall::riseScoreBreakdown() { riseScore.update(chapters); return riseScore.getString(); } int RiseFall::getCurrentChapter() const { for(size_t i = 0; i < chapters.size(); i++) if(chapters[i]->isOngoing()) return i; return -1; } pair<int,int> RiseFall::getChapterCountdown() const { int chIndex = getCurrentChapter(); int r1 = -1, r2 = -1; if(chIndex >= 0) { RFChapter const& ch = *chapters[chIndex]; // Start at 1 r1 = GC.getGame().getGameTurn() - ch.getStartTurn() + 1; r2 = ch.getLength(); } return make_pair(r1, r2); } bool RiseFall::isBlockPopups() const { int pos = getCurrentChapter(); if(pos < 1) return false; /* Since the AI chooses the production of all cities before the player gets to take over, there shouldn't be a reason to show a choose- production popup during the initial turn of a chapter. Conceivable exception: The player conquers a city on the initial turn, and there is no disorder because the city was formerly owned. I guess in this case, the player won't be prompted to choose production, which is bad, but rare and won't crash the game. I'm now also using this function for tech-choice popups, contact by the AI and Civ4lerts. */ return chapters[pos]->getStartTurn() == GC.getGame().getGameTurn(); } bool RiseFall::isDeliverMessages(PlayerTypes civId) const { // False if civId not human and human takeover of civId impossible if(civId == NO_PLAYER || civId == BARBARIAN_PLAYER || GET_PLAYER(civId).isMinorCiv()) return false; // Don't accommodate civs getting played more than once for(size_t i = 0; i < chapters.size(); i++) if(chapters[i]->hasEnded() && chapters[i]->getCiv() == civId) return false; // First player civ not in slot 0; initialization not yet done. if(chapters.empty()) return true; // Can't switch after the final chapter int pos = getCurrentChapter(); if(pos == chapters.size() - 1) return chapters[pos]->getCiv() == civId; return true; } bool RiseFall::isCooperationRestricted(PlayerTypes aiCiv) const { PlayerTypes masterId = GET_TEAM(GET_PLAYER(aiCiv).getMasterTeam()).getLeaderID(); if(masterId != aiCiv) return isCooperationRestricted(masterId); PlayerTypes human = getActivePlayer(); if(aiCiv == human) return false; int currentChPos = getCurrentChapter(); if(currentChPos < 0) return false; RFChapter const& currentCh = *chapters[currentChPos]; if(currentCh.isFinalChapter()) { if(currentCh.isEndless()) // Game already ended return false; // Only civ still to be scored: the one from the previous chapter PlayerTypes prevChCiv = NO_PLAYER; if(currentChPos > 0) prevChCiv = chapters[currentChPos - 1]->getCiv(); return prevChCiv == aiCiv; } for(int i = 0; i <= currentChPos; i++) if(chapters[i]->getCiv() == aiCiv) return !chapters[i]->isScored(); CvGame const& g = GC.getGame(); int aiVictStage = victoryStage(aiCiv); /*if(aiVictStage >= 4) return true; */ int humanVictStage = victoryStage(human); if(aiVictStage < 3) aiVictStage = 0; if(humanVictStage < 3) humanVictStage = 0; if(aiVictStage != humanVictStage) return (aiVictStage < humanVictStage); return (g.getPlayerRank(aiCiv) > g.getPlayerRank(human)); } // currently unused RFChapter* RiseFall::mostRecentlyFinished() const { for(size_t i = chapters.size() - 1; i >= 0; i--) { if(chapters[i]->hasEnded()) return chapters[i]; } return NULL; } void RiseFall::computeEligibleCivs(vector<PlayerTypes>& r, bool allowRepeat) const { for(int i = 0; i < MAX_CIV_PLAYERS; i++) { PlayerTypes civId = (PlayerTypes)i; if(isEligible(civId, allowRepeat)) r.push_back(civId); } } bool RiseFall::isEligible(PlayerTypes civId, bool allowRepeat) const { CvPlayer const& civ = GET_PLAYER(civId); if(!civ.isAlive() || civ.isMinorCiv() || offLimits.count(civ.getTeam()) > 0) return false; for(size_t i = 0; i < chapters.size(); i++) { if(chapters[i]->getCiv() != civId) continue; if(chapters[i]->hasEnded()) { if(allowRepeat) return chapters[i]->isScored(); return false; } } return true; } void RiseFall::updateOffLimits() { for(int i = 0; i < MAX_CIV_TEAMS; i++) { CvTeam& t = GET_TEAM((TeamTypes)i); if(t.isAlive() && t.isVassal(GC.getGame().getActiveTeam())) offLimits.insert(t.getID()); } } void RiseFall::haltForCivSelection(PlayerTypes haltCiv) { CvGame& g = GC.getGame(); /* Set to active human for a moment, just to get the civ selection popup through. Reset to AI-control in handleCivSelection. */ CvPlayer& h = GET_PLAYER(haltCiv); GET_PLAYER(getActivePlayer()).setNetID(-1); /* (bForceHotSeat would take care of the net id, but would also show a "you now control such-and-such" popup.) */ g.setActivePlayer(haltCiv); GET_PLAYER(haltCiv).setNetID(0); h.setIsHuman(true); CvPopupInfo* popup = new CvPopupInfo(BUTTONPOPUP_RF_CHOOSECIV); h.addPopup(popup, true); selectingCiv = true; } PlayerTypes RiseFall::nextCivAlive(PlayerTypes startExcluded) const { int r = (startExcluded + 1) % MAX_PLAYERS; while(!GET_PLAYER((PlayerTypes)r).isAlive() && r != startExcluded) r = (r + 1) % MAX_PLAYERS; if(r == startExcluded) return NO_PLAYER; FAssert(startExcluded == BARBARIAN_PLAYER || startExcluded < r || r == BARBARIAN_PLAYER); return (PlayerTypes)r; } void RiseFall::prepareForExtendedGame() { CvGame& g = GC.getGame(); int pos = getCurrentChapter(); if(pos < 0) { /* Score the latest chapter to avoid confusion about whether it is covered by the points from "unscored finished" */ for(size_t i = chapters.size() - 1; i >= 0; i--) { if(chapters[i]->hasStarted()) { chapters[i]->score(); break; } } riseScore.freezeTotal(chapters); /* Show the latest started chapter as endless, but will actually remain in between chapters indefinitely. */ for(size_t i = chapters.size() - 1; i >= 0; i--) { if(chapters[i]->hasStarted()) { chapters[i]->setEndless(true); break; } } TeamTypes winnerId = g.getWinner(); if(winnerId == NO_TEAM) // Can this be? winnerId = (TeamTypes)0; // Try to avoid giving the player control of the winner b/c it's confusing PlayerTypes haltId = nextCivAlive(GET_TEAM(winnerId).getLeaderID()); if(haltId == NO_PLAYER) haltId = GET_TEAM(winnerId).getLeaderID(); setPlayerControl(haltId, true); interludeCountdown = -1; /* Don't want the player to be addressed by the name of an arbitray civ on the Dan Quayle screen; restore the original player name. */ if(originalName != NULL) GC.getInitCore().setLeaderName(haltId, *originalName); } else if(interludeCountdown < 0) { // Score the current chapter b/c it's not counted under finished unscored if(g.getWinner() != TEAMID(chapters[pos]->getCiv())) chapters[pos]->score(); riseScore.freezeTotal(chapters); chapters[pos]->setEndless(true); /* So that the game end turn gets shown as the score turn. The popup that switches to extended game appears one turn after victory. */ chapters[pos]->setScored(GC.getGame().getGameTurn() - 1); if(g.getAIAutoPlay()) { abandonPlans(chapters[pos]->getCiv()); g.setAIAutoPlay(0); } } else { PlayerTypes civId = chapters[pos]->getCiv(); if(civId == NO_PLAYER) civId = nextCivAlive(civId); // Come back from retirement riseScore.freezeTotal(chapters); setPlayerControl(civId, true); interludeCountdown = -1; } // Player needs to be in control for the game end sequence FAssert(interludeCountdown < 0); FAssert(GET_PLAYER(getActivePlayer()).isHuman()); FAssert(!GET_PLAYER(getActivePlayer()).isHumanDisabled()); } int RiseFall::getFinalRiseScore() const { return riseScore.getScore(); } int RiseFall::getNormalizedFinalScore() const { return riseScore.getNormalizedScore(); } bool RiseFall::launchDefeatPopup(CvPopup* popup, CvPopupInfo& info) { int startTurn = 0; int pos = info.getData1(); if(pos >= 0 && pos < (int)(chapters.size() - 1)) startTurn = chapters[pos + 1]->getStartTurn(); else FAssert(false); CvWString text = gDLL->getText("TXT_KEY_MISC_DEFEAT") + L"\n\n"; text += gDLL->getText("TXT_KEY_RF_DEFEAT", startTurn, startTurn - GC.getGame().getGameTurn()); gDLL->UI().popupSetBodyString(popup, text); gDLL->UI().popupAddGenericButton(popup, gDLL->getText("TXT_KEY_POPUP_EXIT_TO_MAIN_MENU"), NULL, 1, WIDGET_GENERAL); gDLL->UI().popupLaunch(popup); return true; } void RiseFall::handleDefeatPopup(int buttonClicked, int pos) { if(buttonClicked == 1) { setUIHidden(false); CvPlot::setAllFog(false); GC.getGame().exitToMenu(); return; } if(pos < 0 || pos >= (int)(chapters.size() - 1)) { FAssert(false); pos = -1; } // -1: Current turn already passed interludeCountdown = chapters[pos + 1]->getStartTurn() - GC.getGame().getGameTurn() - 1; FAssert(interludeCountdown >= 0); CvPlayer& h = GET_PLAYER(getActivePlayer()); h.setNetID(-1); h.setIsHuman(false); } bool RiseFall::launchCivSelectionPopup(CvPopup* popup, CvPopupInfo& info) { vector<PlayerTypes> eligible; eligibleByRecommendation(eligible); int pos = getCurrentChapter(); // Don't show the popup again when loading the auto-save created at chapter start if(pos >= 0 && chapters[pos]->getCiv() != NO_PLAYER) return false; if(eligible.empty()) { CvWString text = gDLL->getText("TXT_KEY_RF_CIV_SELECTION_EMPTY", pos + 1); /* The handler for this "skip chapter" button isn't properly implemented See comment in afterCivSelection. */ /*text += L" " + gDLL->getText("TXT_KEY_RF_CIV_SELECTION_EMPTY2"); if(pos >= 0 && !chapters[pos]->isScored()) text += L" " + gDLL->getText("TXT_KEY_RF_CIV_SELECTION_UNSCORED", pos); gDLL->UI().popupSetBodyString(popup, text); gDLL->UI().popupAddGenericButton(popup, gDLL->getText("TXT_KEY_RF_SKIP_CHAPTER", pos + 1, chapters[pos]->getLength() + interludeLength), NULL, 1, WIDGET_GENERAL);*/ gDLL->UI().popupAddGenericButton(popup, gDLL->getText("TXT_KEY_RF_RETIRE_ALL"), NULL, 2, WIDGET_GENERAL); gDLL->UI().popupLaunch(popup, false, POPUPSTATE_IMMEDIATE); return true; } CvWString text = gDLL->getText("TXT_KEY_RF_CIV_SELECTION", pos + 1); if(retryingCivSelection) { text += L"\n" + gDLL->getText("TXT_KEY_RF_CIV_SELECTION_RETRY"); retryingCivSelection = false; } gDLL->UI().popupSetBodyString(popup, text); for(size_t i = 0; i < eligible.size(); i++) { wstringstream wss; wss << (eligible.size() - i) << ". " << knownName(eligible[i], false); gDLL->UI().popupAddGenericButton(popup, wss.str(), NULL, 0, WIDGET_RF_CIV_CHOICE, eligible[i]); } gDLL->UI().popupLaunch(popup, false, POPUPSTATE_IMMEDIATE); return true; } void RiseFall::assignCivSelectionHelp(CvWStringBuffer& szBuffer, PlayerTypes selectedCiv) { CvGame& g = GC.getGame(); wstringstream wss; wss << knownName(selectedCiv, false) << L"\n"; int victStage = victoryStage(selectedCiv); if(victStage > 0) { wss << gDLL->getText("TXT_KEY_RF_CIV_SELECTION_VICTSTAGE") << L": " << victStage << L"/4\n"; } wss << gDLL->getText("TXT_KEY_RF_CIV_SELECTION_SCORE", g.getPlayerScore(selectedCiv)); CvTeam& t = GET_TEAM(selectedCiv); if(t.isAVassal()) { wss << L"\n"; PlayerTypes masterLeader = GET_TEAM(t.getMasterTeam()).getLeaderID(); if(t.isCapitulated()) wss << gDLL->getText("TXT_KEY_RF_CIV_SELECTION_CAPVASSAL") << L" " << knownName(masterLeader, true); else wss << gDLL->getText("TXT_KEY_RF_CIV_SELECTION_VOLVASSAL") << L" " << knownName(masterLeader, true); } if(t.getNumWars() > 0) { wss << L"\n" << gDLL->getText("TXT_KEY_RF_CIV_SELECTION_WAR") << L": "; vector<PlayerTypes> warEnemies; // To get the commas right for(int i = 0; i < MAX_CIV_PLAYERS; i++) { CvPlayer& enemy = GET_PLAYER((PlayerTypes)i); if(enemy.isAlive() && !enemy.isMinorCiv() && t.isAtWar(enemy.getTeam())) warEnemies.push_back(enemy.getID()); } for(size_t i = 0; i < warEnemies.size(); i++) { wss << knownName(warEnemies[i], true); if(i < warEnemies.size() - 1) wss << L", "; } } int repeatCh = getCivChapter(selectedCiv); int currentCh = getCurrentChapter(); if(repeatCh >= 0 && repeatCh <= currentCh) // 2nd condition important when loading wss << L"\n" << gDLL->getText("TXT_KEY_RF_CIV_SELECTION_REPEAT", repeatCh + 1, currentCh + 1); szBuffer.assign(wss.str()); } CvWString RiseFall::knownName(PlayerTypes civId, bool nameNumber) const { bool hasMet = false; for(size_t i = 0; i < chapters.size(); i++) { if(!chapters[i]->hasEnded()) break; if(GET_TEAM(chapters[i]->getCiv()).isHasMet(TEAMID(civId))) { hasMet = true; break; } } if(hasMet) { CvPlayer const& civ = GET_PLAYER(civId); bool unique = true; for(int i = 0; i < MAX_CIV_PLAYERS; i++) { CvPlayer const& other = GET_PLAYER((PlayerTypes)i); if(other.isEverAlive() && other.getID() != civId && other.getCivilizationType() == civ.getCivilizationType()) { unique = false; break; } } wchar const* civDescr = civ.getCivilizationShortDescription(); /* Nicer to show civ names, but if one civ is in the game multiple times, will have to show the leader name. */ if(unique) return civDescr; return CvWString(GC.getInfo(civ.getLeaderType()).getDescription()) + L"'s " + civDescr; } if(!nameNumber) return gDLL->getText("TXT_KEY_TOPCIVS_UNKNOWN"); // Order has to be consistent with the numbering in launchCivSelectionPopup vector<PlayerTypes> eligible; eligibleByRecommendation(eligible); size_t index = 0; for(; index < eligible.size(); index++) if(eligible[index] == civId) break; if(index >= eligible.size()) return gDLL->getText("TXT_KEY_TOPCIVS_UNKNOWN"); return gDLL->getText("TXT_KEY_RF_CIV_SELECTION_NUMBER", eligible.size() - index); } void RiseFall::eligibleByRecommendation(vector<PlayerTypes>& r) const { vector<PlayerTypes> noRepeat; computeEligibleCivs(noRepeat, false); std::sort(noRepeat.begin(), noRepeat.end(), byRecommendation); r.insert(r.begin(), noRepeat.begin(), noRepeat.end()); vector<PlayerTypes> all; computeEligibleCivs(all, true); /* Sort those in 'all' minus 'noRepeat' separately and append the result to 'r'. (Would be nicer to let byRecommendation handle this, but that's difficult w/o accessing non-static functions, and I don't want to turn byRecommendation into a functor.) */ vector<PlayerTypes> repeat; for(size_t i = 0; i < all.size(); i++) { bool found = false; for(size_t j = 0; j < noRepeat.size(); j++) { if(noRepeat[j] == all[i]) { found = true; break; } } if(!found) repeat.push_back(all[i]); } std::sort(repeat.begin(), repeat.end(), byRecommendation); r.insert(r.end(), repeat.begin(), repeat.end()); } bool RiseFall::byRecommendation(PlayerTypes one, PlayerTypes two) { CvPlayer const& p1 = GET_PLAYER(one); CvPlayer const& p2 = GET_PLAYER(two); CvTeam const& t1 = GET_TEAM(one); CvTeam const& t2 = GET_TEAM(two); if(t1.isCapitulated() && !t2.isCapitulated()) return false; if(t2.isCapitulated() && !t1.isCapitulated()) return true; if(p1.isAVassal() && !p2.isAVassal()) return false; if(p2.isAVassal() && !p1.isAVassal()) return true; int vs1 = victoryStage(one); int vs2 = victoryStage(two); if(vs1 > vs2) return false; if(vs2 > vs1) return false; CvGame const& g = GC.getGame(); int sc1 = g.getPlayerScore(one); int sc2 = g.getPlayerScore(two); if(sc1 > sc2) return false; if(sc2 > sc1) return true; return g.getPlayerRank(one) > g.getPlayerRank(two); } int RiseFall::victoryStage(PlayerTypes civId) { if(civId == NO_PLAYER) { FAssert(false); return 0; } CvPlayerAI const& civ = GET_PLAYER(civId); if(!civ.isAlive()) return -1; int r = 0; // Stages 1 and 2 aren't meaningful enough if(civ.AI_atVictoryStage3()) r = 3; if(civ.AI_atVictoryStage4()) r = 4; /* Culture4 is normally quite a bit farther away from victory than the other stage-4 strategies. Need to recompute the culture victory stage with a lowered countdownThresh. */ if(r == 4 && civ.AI_atVictoryStage(AI_VICTORY_CULTURE4 & ~AI_VICTORY_DIPLOMACY4 & ~AI_VICTORY_CONQUEST4 & ~AI_VICTORY_DOMINATION4 & ~AI_VICTORY_SPACE4)) r = std::max(3, civ.AI_calculateCultureVictoryStage(167)); return r; } CvWString RiseFall::retireConfirmMsg() const { CvWString r = gDLL->getText("TXT_KEY_RF_CONFIRM_RETIRE", getRetireTurns()); if(interludeLength > 0 && getCurrentChapter() < (int)(chapters.size() - 1)) r.append(L" (" + gDLL->getText("TXT_KEY_RF_CONFIRM_RETIRE_INTERLUDE", interludeLength) + L")"); r.append(NEWLINE); r.append(NEWLINE); r.append(gDLL->getText("TXT_KEY_RF_RETIRE_FOR_GOOD")); return r; } bool RiseFall::launchRetirePopup(CvPopup* popup, CvPopupInfo& info) { int pos = getCurrentChapter(); FAssert(pos >= 0); bool bEndless = (pos >= 0 && chapters[pos]->isEndless()); CvDLLInterfaceIFaceBase& base = *gDLL->getInterfaceIFace(); base.popupSetBodyString(popup, bEndless ? gDLL->getText("TXT_KEY_POPUP_ARE_YOU_SURE") : retireConfirmMsg()); // The popupAddGenericButton calls are copied from CvDLLButtonPopup::launchConfirmMenu if(!bEndless) { base.popupAddGenericButton(popup, gDLL->getText("TXT_KEY_POPUP_RETIRE"), NULL, 0, WIDGET_GENERAL); } base.popupAddGenericButton(popup, gDLL->getText("TXT_KEY_POPUP_CANCEL"), NULL, 1, WIDGET_GENERAL); base.popupAddGenericButton(popup, gDLL->getText("TXT_KEY_RF_END_GAME"), NULL, 2, WIDGET_GENERAL); base.popupLaunch(popup, false, POPUPSTATE_IMMEDIATE); return true; } void RiseFall::handleRetirePopup(int buttonClicked) { if(buttonClicked == 2) GC.getGame().retire(); else if(buttonClicked == 0) retire(); } int RiseFall::getCivChapter(PlayerTypes civId) const { int r = -1; for(size_t i = 0; i < chapters.size(); i++) { if(chapters[i]->getCiv() == civId) r = i; } return r; } bool RiseFall::isSelectingCiv() const { return selectingCiv; } void RiseFall::afterCivSelection(int buttonClicked) { CvGame& g = GC.getGame(); CvPlayer& h = GET_PLAYER(getActivePlayer()); int pos = getCurrentChapter(); if(buttonClicked == 1) { FAssert(false); /* Tbd.: Not working at all, at least not when the game ends during the upcoming chapter. Probably doesn't work otherwise either. */ /*setPlayerControl(h.getID(), true); int t = chapters[pos + 1]->getStartTurn(); if(pos >= (int)(chapters.size() - 1)) t = chapters[pos]->getEndTurn() + 1 + interludeLength; t -= (g.getGameTurn() + 1); g.setAIAutoPlay(t);*/ selectingCiv = false; return; } else if(buttonClicked == 2) { PlayerTypes nextCiv = NO_PLAYER; if(pos > 0) nextCiv = chapters[pos - 1]->getCiv(); else nextCiv = nextCivAlive(BARBARIAN_PLAYER); chapters[pos]->setCiv(nextCiv); setPlayerControl(nextCiv, true); interludeCountdown = -1; chapters[pos]->start(); g.setGameState(GAMESTATE_OVER); } // (buttonClicked==0 handled by handleCivSelection) selectingCiv = false; if(pos > 0) { // Relevant when loading a savegame CvPlayer& prev = GET_PLAYER(chapters[pos - 1]->getCiv()); prev.setNetID(-1); prev.setIsHuman(false); } if(pos >= 0 && chapters[pos]->getCiv() == h.getID()) { // Start of human turn was missed; need to fill in some steps. setPlayerControl(h.getID(), true); interludeCountdown = -1; chapters[pos]->start(); // Save before firing popups g.autoSave(); welcomeToNextChapter(pos); return; } h.setNetID(-1); h.setIsHuman(false); } void RiseFall::handleCivSelection(PlayerTypes selectedCiv) { int pos = getCurrentChapter(); if(pos < 0) { FAssert(pos >= 0); return; } if(getCivChapter(selectedCiv) >= 0) chapters[pos]->setRepeat(true); chapters[pos]->setCiv(selectedCiv); } bool RiseFall::isSquareDeal(CLinkList<TradeData> const& humanReceives, CLinkList<TradeData> const& aiReceives, PlayerTypes aiCiv) const { PlayerTypes human = getActivePlayer(); /* Actually no problem if the human receives sth. non-dual, e.g. gold for peace. */ if(//allSquare(humanReceives, aiCiv, human) && allSquare(aiReceives, human, aiCiv)) return true; return false; } bool RiseFall::isNeededWarTrade(CLinkList<TradeData> const& humanReceives) const { CvPlayerAI const& human = GET_PLAYER(getActivePlayer()); FOR_EACH_TRADE_ITEM(humanReceives) { if(pItem->m_eItemType == TRADE_WAR) { TeamTypes targetId = (TeamTypes)pItem->m_iData; if(targetId == NO_TEAM) { FAssert(targetId != NO_TEAM); return false; } if(/*GET_TEAM(targetId).AI_getWarSuccess(human.getTeam()) > GC.getWAR_SUCCESS_CITY_CAPTURING() &&*/ GET_TEAM(human.getTeam()).AI_getEnemyPowerPercent() > 100) return true; } } return false; } bool RiseFall::allSquare(CLinkList<TradeData> const& list, PlayerTypes from, PlayerTypes to) const { bool allVassal = true; bool allDual = true; bool allLiberation = true; FOR_EACH_TRADE_ITEM(list) { TradeableItems item = pItem->m_eItemType; if(!CvDeal::isDual(item)) allDual = false; if(item != TRADE_SURRENDER && item != TRADE_VASSAL) allVassal = false; if(item == TRADE_CITIES) { CvCity const* c = GET_PLAYER(from).getCity(pItem->m_iData); if(c == NULL || c->getLiberationPlayer() != to) allLiberation = false; } else allLiberation = false; } return allDual || allVassal || allLiberation; } int RiseFall::pessimisticDealVal(PlayerTypes aiCivId, int dealVal, CLinkList<TradeData> const& humanReceives) const { int r = dealVal; PlayerTypes humanCivId = getActivePlayer(); TeamTypes humanTeamId = TEAMID(humanCivId); if(humanTeamId == NO_TEAM || humanCivId == NO_PLAYER) { FAssert(false); return r; } TeamTypes aiTeamId = TEAMID(aiCivId); CvTeamAI const& aiTeam = GET_TEAM(aiTeamId); CvTeamAI const& humanTeam = GET_TEAM(humanTeamId); CvPlayerAI const& humanCiv = GET_PLAYER(humanCivId); // Loop based on CvPlayerAI::AI_dealVal FOR_EACH_TRADE_ITEM(humanReceives) { int itemVal = 0; /* What the AI thinks that the item should be worth to the human civ. In most cases, there is no code for this, and then replVal has to be set based on itemVal (what the AI normally demands for the item). */ int replVal = -1; int data = pItem->m_iData; switch(pItem->m_eItemType) { case TRADE_PEACE: itemVal = humanTeam.AI_makePeaceTradeVal((TeamTypes)data, aiTeamId); break; case TRADE_WAR: itemVal = humanTeam.AI_declareWarTradeVal((TeamTypes)data, aiTeamId); if(getUWAI().isEnabled()) // advc.104 replVal = GET_TEAM(humanTeamId).uwai().tradeValJointWar( (TeamTypes)data, aiTeam.getID()); break; case TRADE_EMBARGO: itemVal = humanCiv.AI_stopTradingTradeVal((TeamTypes)data, aiCivId); break; case TRADE_CIVIC: itemVal = humanCiv.AI_civicTradeVal((CivicTypes)data, aiCivId); break; case TRADE_RELIGION: itemVal = humanCiv.AI_religionTradeVal((ReligionTypes)data, aiCivId); break; } /* Don't hinder low-value trades (e.g. a little payment for switching to a religion that is already the majority religion) */ if(itemVal <= (GC.AI_getGame().AI_getCurrEraFactor() + 1) * 100) continue; if(replVal < 0) replVal = ::round(itemVal / 1.5); r = r - itemVal + replVal; } return std::max(r, 0); } double RiseFall::dealThresh(bool annual) const { if(annual) // Resource trades (and peace treaties) are less problematic return 0.35; return 0.65; } void RiseFall::substituteDiploText(bool gift) { if(!gift) /* Possibly still to be implemented: Response along the lines of */ return;/* "you're too generous" to a rejected trade offer. */ CvDiplomacyResponse* resp = findThanks(); if(resp == NULL || resp->getNumDiplomacyText() <= 0) return; /* Conversion from wstring: breaks if multi-byte chars are involved (i.e. non-ASCII). */ CvString replacement(gDLL->getText("TXT_KEY_RF_NO_THANKS")); clearDiploStrings(); for(int j = 0; j < resp->getNumDiplomacyText(); j++) { originalThanks.push_back(new CvString(resp->getDiplomacyText(j))); resp->setDiplomacyText(j, replacement); } } void RiseFall::restoreDiploText() { if(originalThanks.empty()) return; CvDiplomacyResponse* resp = findThanks(); if(resp == NULL) return; FAssert(resp->getNumDiplomacyText() == originalThanks.size()); for(int j = 0; j < resp->getNumDiplomacyText(); j++) resp->setDiplomacyText(j, *originalThanks[j]); clearDiploStrings(); } wchar const* RiseFall::fillWS(int n, bool addPlus) { addPlus = (addPlus && n >= 0); n = (int)std::abs(n); if(n >= 1000) // Spell out the literals in order to avoid dynamic memory return (addPlus ? L"+" : L""); if(n >= 100) return (addPlus ? L" +" : L" "); if(n >= 10) return (addPlus ? L" +" : L" "); return (addPlus ? L" +" : L" "); } CvDiplomacyResponse* RiseFall::findThanks() { CvDiplomacyInfo* thanks = NULL; for(int i = 0; i < GC.getNumDiplomacyInfos(); i++) { if(_tcscmp(GC.getDiplomacyInfo(i).getType(), TEXT("AI_DIPLOCOMMENT_THANKS")) == 0) thanks = &GC.getDiplomacyInfo(i); } if(thanks == NULL) return NULL; for(int i = 0; i < thanks->getNumResponses(); i++) { return &thanks->getResponse_(i); } return NULL; } void RiseFall::clearDiploStrings() { for(size_t i = 0; i < originalThanks.size(); i++) SAFE_DELETE(originalThanks[i]); originalThanks.clear(); } void RiseFall::shutOff(CvWString errorMsg) { showError(gDLL->getText("TXT_KEY_RF_SHUT_OFF")); showError(errorMsg); GC.getGame().setOption(GAMEOPTION_RISE_FALL, false); reset(); } void RiseFall::showError(CvWString errorMsg) { gDLL->UI().addMessage(getActivePlayer(), true, 1, errorMsg, NULL, MESSAGE_TYPE_MAJOR_EVENT, NULL, GC.getColorType("RED")); }
[ "no.m@il.specified" ]
no.m@il.specified
dda6bffa8b553f7665df1a3920131e2ce46737e6
65f3e6b0c62bd22e08a5ef447bef6a6c86e6cd06
/ouzel/graphics/RenderResource.hpp
c82dc73d25915ba5b2015c45e2632c25fded5c16
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
whztt07/ouzel
f2dfb9f3e6d12d54edf3b5a724ebfb8a04f0b555
f9a7d6dedd640ca4db429c6c62a72aec5332661c
refs/heads/master
2020-03-24T22:37:44.426088
2018-07-25T08:37:29
2018-07-25T08:37:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
604
hpp
// Copyright 2015-2018 Elviss Strazdins. All rights reserved. #pragma once namespace ouzel { namespace graphics { class RenderResource { public: RenderResource() {} virtual ~RenderResource() {} RenderResource(const RenderResource&) = delete; RenderResource& operator=(const RenderResource&) = delete; RenderResource(RenderResource&&) = delete; RenderResource& operator=(RenderResource&&) = delete; virtual void reload() {} }; } // namespace graphics } // namespace ouzel
[ "elviss@elviss.lv" ]
elviss@elviss.lv
997223f23dba8fa88f37d2fa9614d747b7d7f6a9
2464d368a1dc6b9b3567e15575d55a9402c2fee0
/lightoj-1258 - Making Huge Palindromes.cpp
19c86d63da009870cb35fbed2954690a6ccaeaa6
[]
no_license
Emon46/Lightoj
01fbf2551a149cd3a849db2af47d937638f93241
25a6ab5582295c20693347f4c1662ffacc01ec87
refs/heads/master
2021-09-13T10:57:35.253273
2018-04-28T20:45:23
2018-04-28T20:45:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,154
cpp
/* ID: hremon32 PROG: LANG: C++11 */ #include<iostream> #include<stdio.h> #include<stdlib.h> #include<math.h> #include<cstring> #include<algorithm> #include<vector> #include<stack> #include<queue> #include<map> #include<set> using namespace std; #define mod 1000000007 #define ll long long #define llu unsigned long long #define pii pair<int,int> #define PI acos(-1.00) #define pb push_back #define ppb pop_back string pattern,text; int a[1000010]; int kmp() { string text=pattern; reverse(pattern.begin(),pattern.end()); int now=0,cnt=0,mx=0; a[0]=0; for(int i=1; i<pattern.size(); i++) { while(now!=0&&pattern[now]!=pattern[i])now=a[now-1]; if(pattern[now]==pattern[i])a[i]=++now; else a[i]=now; } now=0; for(int i=0; i<text.size(); i++) { while(now!=0&&pattern[now]!=text[i])now=a[now-1]; if(text[i]==pattern[now])now++; } return (2*text.size()-now); } int main() { ios::sync_with_stdio(false); int tst,t=1; cin>>tst; while(tst--) { cin>>pattern; cout<<"Case "<<t++<<": "; cout<<kmp()<<endl; } return 0; }
[ "hremon331046@gmail.com" ]
hremon331046@gmail.com
d8d25d872e1502334feee579378c47e77c0c9bfc
0067b6b5a69ca4b540400a55bd50c8d642ebd09d
/cMain.cpp
c4ec299e794d1b973f630de216c4bcdbeee47bec
[ "MIT" ]
permissive
stewkk/sa
b22531c47787652aeccc115e6daa34d8ab008333
595374c1139475315ac8fca7cc6d57f7b6723b77
refs/heads/main
2022-12-28T00:11:06.809400
2020-10-09T12:54:02
2020-10-09T12:54:02
302,629,305
0
0
null
null
null
null
UTF-8
C++
false
false
32,262
cpp
#include "cMain.h" wxDEFINE_EVENT(MY_EVENT_TYPE, wxCommandEvent); wxBEGIN_EVENT_TABLE(cMain, wxFrame) EVT_TEXT(ID_ENTRY_ANIME_NAME, onAnimeEntryChange) EVT_BUTTON(ID_BUTTON_SEARCH_ANIME, onButtonSearchAnime) EVT_TEXT_ENTER(ID_ENTRY_ANIME_NAME, onButtonSearchAnime) EVT_LISTBOX_DCLICK(ID_CHOOSE_ANIME, onButtonSelectTitle) EVT_CHECKLISTBOX(ID_CHOOSE_EPISODES_TO_DOWNLOAD, onCheckListChecked) EVT_MENU(ID_TOP_MENU_INFO, onTopMenuInfo) EVT_MENU(ID_TOP_MENU_LOGOUT, onlogoutSA) EVT_LISTBOX(ID_CHOOSE_EPISODE, onEpisodeChoosen) EVT_LIST_ITEM_SELECTED(ID_TRANSLATES_LIST, onTranslationChoosen) EVT_BUTTON(ID_BUTTON_DOWNLOAD_ANIME, onButtonDownloadAnime) EVT_LIST_ITEM_RIGHT_CLICK(ID_DOWNLOADS_LIST, OnDownloadsListRightClick) EVT_COMMAND(ID_WXPANEL_MAIN, MY_EVENT_TYPE, OnEnableMainPanel) EVT_COMMAND(ID_CLEAR_GUI_FOR_SEARCH, MY_EVENT_TYPE, OnClearGuiForSearch) EVT_COMMAND(ID_CHOOSE_ANIME, MY_EVENT_TYPE, OnAppendToAnimesList) EVT_COMMAND(ID_CLEAR_GUI_FOR_CHOOSED_ANIME, MY_EVENT_TYPE, OnClearGuiForChoosedAnime) EVT_COMMAND(ID_CHOOSE_EPISODES_TO_DOWNLOAD, MY_EVENT_TYPE, OnChooseEpisodesToDownloadAppend) EVT_COMMAND(ID_TRANSLATES_LIST, MY_EVENT_TYPE, OnClearTranslatesList) EVT_COMMAND(ID_TRANSLATES_LIST_INSERT, MY_EVENT_TYPE, OnInsertToTranslatesList) EVT_COMMAND(ID_TRANSLATES_LIST_STATUS, MY_EVENT_TYPE, onSetDownloadStasus) EVT_COMMAND(ID_TRANSLATES_LIST_PARAMS, MY_EVENT_TYPE, onSetDownloadParams) EVT_COMMAND(ID_TRANSLATES_LIST_PARAMS_PROGRESS, MY_EVENT_TYPE, onSetDownloadParamsProgress) EVT_COMMAND(ID_DOWNLOADS_LIST_INSERT, MY_EVENT_TYPE, onDownloadsListInsert) wxEND_EVENT_TABLE() cMain::cMain() : wxFrame(nullptr, wxID_ANY, "Anime", wxPoint(0, 0), wxSize(800, 900), (wxDEFAULT_FRAME_STYLE & ~(wxRESIZE_BORDER | wxMAXIMIZE_BOX))) { execCURL(); this->SetIcon(wxIcon(icon)); Centre(); do_logout = false; saLoginDialog = new wxTextEntryDialog(this, "Email", "smotret-anime.online auth", "", (wxOK | wxCENTRE | wxWS_EX_VALIDATE_RECURSIVELY)); saPasswordDialog = new wxPasswordEntryDialog(this, "Password", "smotret-anime.online auth", "", (wxOK | wxCENTRE | wxWS_EX_VALIDATE_RECURSIVELY)); main_panel = new MyPanel(this); main_panel->SetId(ID_WXPANEL_MAIN); button_search_anime = new wxButton(main_panel, ID_BUTTON_SEARCH_ANIME, "Search", wxPoint(325, 243), wxSize(90, 35)); #ifdef _DEBUG entry_anime_name = new wxTextCtrl(main_panel, ID_ENTRY_ANIME_NAME, "Yesterday wo Utatte", wxPoint(50, 250), wxSize(265, 20), wxTE_PROCESS_ENTER); #else entry_anime_name = new wxTextCtrl(main_panel, ID_ENTRY_ANIME_NAME, "", wxPoint(50, 250), wxSize(265, 20), wxTE_PROCESS_ENTER); #endif choose_anime = new wxListBox(main_panel, ID_CHOOSE_ANIME, wxPoint(25, 25), wxSize(400, 200)); choose_episodes_to_download = new wxCheckListBox(main_panel, ID_CHOOSE_EPISODES_TO_DOWNLOAD, wxPoint(470, 25), wxSize(250, 200)); top_menu = new wxMenu(); top_menu->Append(ID_TOP_MENU_INFO, "Info"); top_menu->Append(ID_TOP_MENU_LOGOUT, "Logout"); top_menu_bar = new wxMenuBar(); top_menu_bar->Append(top_menu, "Menu"); SetMenuBar(top_menu_bar); CreateStatusBar(3); SetStatusText(wxT("Ready"), 0); // SetStatusText(wxT("stewkk"), 1); choose_episode = new wxListBox(main_panel, ID_CHOOSE_EPISODE, wxPoint(25, 300), wxSize(250, 200)); wxString choice_settings_names[2] = { "By size" }; choice_default_transl = new wxChoice(main_panel, ID_CHOICE_DEFAULT_TRANSL, wxPoint(470, 250), wxSize(100, 25), 1, choice_settings_names); choice_default_transl->SetSelection(0); choice_default_transl->Disable(); translates_list = new wxListCtrl(main_panel, ID_TRANSLATES_LIST, wxPoint(300, 300), wxSize(450, 200), wxLC_REPORT | wxLC_SINGLE_SEL); translates_list->AppendColumn("Author", wxLIST_FORMAT_LEFT, 190); translates_list->AppendColumn("Size", wxLIST_FORMAT_LEFT, 80); translates_list->AppendColumn("Quality", wxLIST_FORMAT_LEFT, 80); translates_list->AppendColumn("Duration", wxLIST_FORMAT_LEFT, 80); button_download_anime = new wxButton(main_panel, ID_BUTTON_DOWNLOAD_ANIME, "Download", wxPoint(600, 243), wxSize(90, 35)); downloads_list = new wxListCtrl(main_panel, ID_DOWNLOADS_LIST, wxPoint(25, 525), wxSize(725, 250), wxLC_REPORT | wxLC_SINGLE_SEL); downloads_list->AppendColumn("Name", wxLIST_FORMAT_LEFT, 190); downloads_list->AppendColumn("Size", wxLIST_FORMAT_LEFT, 80); downloads_list->AppendColumn("Progress", wxLIST_FORMAT_LEFT, 80); downloads_list->AppendColumn("Status", wxLIST_FORMAT_LEFT, 80); downloads_list->AppendColumn("Speed", wxLIST_FORMAT_LEFT, 80); downloads_list->AppendColumn("Time passed", wxLIST_FORMAT_LEFT, 80); downloads_list->AppendColumn("Time left", wxLIST_FORMAT_LEFT, 80); download_only_subs_checkbox = new wxCheckBox(main_panel, ID_DOWNLOAD_ONLY_SUBS_CHECKBOX, "Subs only", wxPoint(470, 275), wxSize(100, 25)); if (!checkSaAuth()) { execSaAuth(); } } cMain::~cMain() { saLoginDialog->Destroy(); saPasswordDialog->Destroy(); curl_easy_cleanup(curl_handle); curl_easy_cleanup(curl_handle_cookies); curl_multi_cleanup(curl_multi_handle); if (do_logout) { std::remove("cookies"); } } static size_t WriteCallbackToString(void* contents, size_t size, size_t nmemb, void* userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } static size_t DontWriteCallback(void* contents, size_t size, size_t nmemb, void* userp) { return size * nmemb; } bool get(CURL* curl, const char url[]) { curl_easy_setopt(curl, CURLOPT_URL, url); CURLcode res = curl_easy_perform(curl); long response_code; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); return res == CURLE_OK && response_code == 200; } bool requestSAapi(CURL* curl_handle, std::string& request_url, std::string& readBuffer) { if (curl_handle) { curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, &readBuffer); return get(curl_handle, request_url.c_str()); } return false; } void encodeStringToURL(CURL* curl_handle, std::string& str) { char* output = curl_easy_escape(curl_handle, str.c_str(), str.size()); str = output; curl_free(output); } void parseAnimes(cMain* cMain, std::string& readBuffer) { json j = json::parse(readBuffer); j = j["data"]; wxCommandEvent* event_clear = new wxCommandEvent(MY_EVENT_TYPE, cMain->ID_CLEAR_GUI_FOR_SEARCH); wxQueueEvent(cMain, event_clear); cMain->epIDs.clear(); cMain->animeIDs.clear(); cMain->animeNames.clear(); cMain->epNames.clear(); for (auto& anime : j) { json temp_json = anime["id"]; if (temp_json.is_number()) { long long id = temp_json.get<long long>(); std::string title; temp_json = anime["titles"]["romaji"]; std::string romanji_title = temp_json.get<std::string>(); temp_json = anime["titles"]["ru"]; if (temp_json.is_string()) { title = temp_json.get<std::string>(); } else { title = romanji_title; } cMain->animeNames.push_back(romanji_title); cMain->animeIDs.push_back(id); wxCommandEvent* event_append = new wxCommandEvent(MY_EVENT_TYPE, cMain->ID_CHOOSE_ANIME); event_append->SetString(title); std::string* temp = new std::string; *temp = title; event_append->SetClientData(temp); wxQueueEvent(cMain, event_append); } } } void findAnimeSA(cMain* cMain, CURL* curl_handle, std::string animename) { encodeStringToURL(curl_handle, animename); std::string readBuffer; #ifdef _DEBUG std::string request_url = "https://smotret-anime.online/api/series/?pretty=1&query=" + animename; #else std::string request_url = "https://smotret-anime.online/api/series/?query=" + animename; #endif if (requestSAapi(curl_handle, request_url, readBuffer) && !readBuffer.empty()) { parseAnimes(cMain, readBuffer); } enableMainPanel(cMain); } void parseTranslations(cMain* cMain, CURL* curl_handle, std::string& readBuffer, size_t index) { json j = json::parse(readBuffer); j = j["data"]["translations"]; for (auto& tr : j) { if (tr["type"].get<std::string>() == "subRu" && tr["isActive"].get<long long>()) { std::string authorsSummary = tr["authorsSummary"].get<std::string>(); std::string qualityType = tr["qualityType"].get<std::string>(); long long trID = tr["id"].get<long long>(); long long duration = stod(tr["duration"].get<std::string>()); if (authorsSummary.empty()) { authorsSummary = "unknown"; } long long epID = cMain->epIDs[index]; transl ep; ep.tr_links = getDirectDownloadLinks(cMain, curl_handle, trID); if (!ep.tr_links.videoLink.empty()) { ep.size = getTranslSize(ep.tr_links.videoLink); if (ep.size) { ep.translName = authorsSummary; ep.quality = ep.tr_links.quality; ep.duration = duration; ep.id = trID; cMain->epTransl[index].push_back(ep); } } sort(cMain->epTransl[index].rbegin(), cMain->epTransl[index].rend(), trCmp); } } } bool trCmp(const transl& a, const transl& b) { return a.size < b.size; } curl_off_t getTranslSize(std::string& url) { CURL* curl_handle = curl_easy_init(); std::string readBuffer; curl_off_t size = 0; if (curl_handle) { curl_easy_setopt(curl_handle, CURLOPT_NOBODY, 1L); requestSAapi(curl_handle, url, readBuffer); CURLcode res = curl_easy_getinfo(curl_handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &size); long response_code; curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &response_code); curl_easy_cleanup(curl_handle); if (response_code != 200) { return 0; } } return size; } std::string parseLinkToVideo(const std::string& page) { std::string ans = ""; size_t i = page.find("&quot;urls&quot;:[&quot;"); if (i != std::string::npos) { i += 24; size_t j = page.find("&quot;", i); ans = page.substr(i, j - i); ans.erase(ans.find("amp;"), 4); i = ans.find('\\'); while (i != std::string::npos) { ans.erase(i, 1); i = ans.find('\\'); } } return ans; } std::string parseLinkToSubs(const std::string& page) { size_t i = page.find("data-subtitles=\""); i += 16; size_t j = page.find('"', i); std::string ans = page.substr(i, j - i); return ans; } links parseDirectDownloadLink(std::string& readBuffer) { std::string linkToVideo = parseLinkToVideo(readBuffer); std::string linkToSubs = parseLinkToSubs(readBuffer); return { linkToVideo, linkToSubs }; } bool requestSAWithCookies(CURL* curl_handle_cookies, std::string& request_url, std::string& readBuffer) { if (curl_handle_cookies) { curl_easy_setopt(curl_handle_cookies, CURLOPT_WRITEDATA, &readBuffer); return get(curl_handle_cookies, request_url.c_str()); } return false; } links getDirectDownloadLinks(cMain* cMain, CURL* curl_handle, long long epID) { links directDownloadLinks; std::string request_url = "https://smotret-anime.online/translations/embed/" + std::to_string(epID); std::string readBuffer; if (requestSAWithCookies(cMain->curl_handle_cookies, request_url, readBuffer) && !readBuffer.empty()) { links res = parseDirectDownloadLink(readBuffer); std::string quality = parseVideoQuality(readBuffer); res.quality = quality; directDownloadLinks = res; } return directDownloadLinks; } std::string parseVideoQuality(std::string& page) { std::string ans = ""; size_t i = page.find("&quot;height&quot;:"); if (i != std::string::npos) { i += 19; size_t j = page.find(",&quot;", i); ans = page.substr(i, j - i); } return ans; } static int xferinfo(void* p, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { struct myprogress* myp = (struct myprogress*)p; CURL* curl = myp->curl; TIMETYPE curtime = 0; curl_easy_getinfo(curl, TIMEOPT, &curtime); if ((curtime - myp->lastruntime) >= MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL) { std::string* params = new std::string[3]; params[0] = std::to_string((long long)(((dlnow - myp->lastdownloaded) / 1024.0 / 1024.0) / (((double)curtime - myp->lastruntime) / 1000000.0))) + "MB/s"; params[1] = std::to_string((long long)((dltotal - dlnow) / (dlnow / (curtime / 1000000.0)))); params[2] = std::to_string(curtime / 1000000); wxCommandEvent* event_insert = new wxCommandEvent(MY_EVENT_TYPE, myp->cMain->ID_TRANSLATES_LIST_PARAMS); event_insert->SetInt(myp->index); event_insert->SetClientData(params); wxQueueEvent(myp->cMain, event_insert); //myp->cMain->downloads_list->SetItem(myp->index, 4, std::to_string(long long(((dlnow - myp->lastdownloaded) / 1024.0 / 1024.0) // / (((double)curtime - myp->lastruntime) / 1000000.0))) + "MB/s"); // current download speed //myp->cMain->downloads_list->SetItem(myp->index, 6, std::to_string(long long((dltotal - dlnow) / (dlnow / (curtime / 1000000.0))))); // time left //myp->cMain->downloads_list->SetItem(myp->index, 5, std::to_string(curtime / 1000000)); // current time myp->lastruntime = curtime; myp->lastdownloaded = dlnow; } wxCommandEvent* event_insert = new wxCommandEvent(MY_EVENT_TYPE, myp->cMain->ID_TRANSLATES_LIST_PARAMS_PROGRESS); event_insert->SetInt(myp->index); event_insert->SetString(std::to_string((int)((float)dlnow / dltotal * 100)) + "%"); //myp->cMain->downloads_list->SetItem(myp->index, 2, std::to_string((int)((float)dlnow / dltotal * 100)) + "%"); // progress wxQueueEvent(myp->cMain, event_insert); return 0; } void addHandle(cMain* cMain, const std::string& url, FILE* f, long long index) { CURL* easy_handle = curl_easy_init(); myprogress* prog = new myprogress; prog->lastruntime = 0; prog->curl = easy_handle; prog->cMain = cMain; prog->index = index; if (index != -1) { curl_easy_setopt(easy_handle, CURLOPT_NOPROGRESS, 0L); curl_easy_setopt(easy_handle, CURLOPT_XFERINFOFUNCTION, xferinfo); curl_easy_setopt(easy_handle, CURLOPT_XFERINFODATA, prog); } curl_easy_setopt(easy_handle, CURLOPT_URL, url.c_str()); curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, f); curl_easy_setopt(easy_handle, CURLOPT_PRIVATE, prog); curl_multi_add_handle(cMain->curl_multi_handle, easy_handle); } void multiDownload(cMain* cMain) { int still_running = 0; do { CURLMcode mc; int numfds; mc = curl_multi_perform(cMain->curl_multi_handle, &still_running); CURLMsg* m; do { int msgq = 0; m = curl_multi_info_read(cMain->curl_multi_handle, &msgq); if (m && (m->msg == CURLMSG_DONE)) { CURL* e = m->easy_handle; myprogress* prog = nullptr; curl_easy_getinfo(e, CURLINFO_PRIVATE, &prog); if (prog->index != -1) { wxCommandEvent* event_status = new wxCommandEvent(MY_EVENT_TYPE, cMain->ID_TRANSLATES_LIST_STATUS); event_status->SetInt(prog->index); if (m->data.result == CURLE_OK) { event_status->SetString("Done"); } else { event_status->SetString("Error"); } wxQueueEvent(cMain, event_status); } delete prog; curl_multi_remove_handle(cMain->curl_multi_handle, e); curl_easy_cleanup(e); } } while (m); if (mc == CURLM_OK) { /* wait for activity or timeout */ mc = curl_multi_poll(cMain->curl_multi_handle, NULL, 0, 1000, &numfds); } if (mc != CURLM_OK) { //fprintf(stderr, "curl_multi , code %d.\n", mc); break; } } while (still_running); } void dowloadAnimeSA(cMain* cMain, CURL* curl_handle, size_t n, wxArrayInt checkedEps, size_t index, bool is_download_only_subs) { if (!checkedEps.IsEmpty()) { std::vector <FILE*> files; #ifdef _LINUX mkdir(cMain->choosedTitleName.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); #else _mkdir(cMain->choosedTitleName.c_str()); #endif for (size_t i = 0; i < n; ++i) { size_t epInd = checkedEps.Item(i); if (epInd != 0) { epInd--; if (cMain->selTranslIDs[epInd] == -1) { getEpInfo(cMain, curl_handle, epInd); } if (cMain->selTranslIDs[epInd] != -1) { transl tr = cMain->epTransl[epInd][cMain->selTranslIDs[epInd]]; std::string epString = std::to_string(epInd + 1); for (int it = epString.size(); it < 3; ++it) { epString = "0" + epString; } FILE* f; if (!is_download_only_subs) { #ifdef _LINUX f = fopen((cMain->choosedTitleName + "/[Anime365] " + cMain->choosedTitleName + " - " + epString + ".mp4").c_str(), "wb"); #else f = fopen((cMain->choosedTitleName + "\\[Anime365] " + cMain->choosedTitleName + " - " + epString + ".mp4").c_str(), "wb"); #endif files.push_back(f); addHandle(cMain, tr.tr_links.videoLink, f, index); std::string* params = new std::string[2]; params[0] = cMain->epNames[epInd] + ".mp4"; params[1] = std::to_string(tr.size / 1024 / 1024); wxCommandEvent* event_insert = new wxCommandEvent(MY_EVENT_TYPE, cMain->ID_DOWNLOADS_LIST_INSERT); event_insert->SetInt(index); event_insert->SetClientData(params); wxQueueEvent(cMain, event_insert); index++; } /*cMain->downloads_list->InsertItem(index, cMain->epNames[epInd] + ".mp4"); cMain->downloads_list->SetItem(index, 1, std::to_string(tr.size / 1024 / 1024)); cMain->downloads_list->SetItem(index, 2, "0%"); cMain->downloads_list->SetItem(index, 3, "downloading"); cMain->downloads_list->SetItem(index, 4, "0"); cMain->downloads_list->SetItem(index, 5, "0"); cMain->downloads_list->SetItem(index, 6, "0");*/ if (!tr.tr_links.subsLink.empty()) { #ifdef _LINUX f = fopen((cMain->choosedTitleName + "/[Anime365] " + cMain->choosedTitleName + " - " + epString + ".ass").c_str(), "wb"); #else f = fopen((cMain->choosedTitleName + "\\[Anime365] " + cMain->choosedTitleName + " - " + epString + ".ass").c_str(), "wb"); #endif files.push_back(f); addHandle(cMain, tr.tr_links.subsLink, f, -1); } } } } multiDownload(cMain); for (auto& file : files) { fclose(file); } } enableMainPanel(cMain); } inline bool fileExistsTest(const std::string& name) { if (FILE* file = fopen(name.c_str(), "r")) { fclose(file); return true; } else { return false; } } bool checkSaAuth() { return fileExistsTest("cookies"); } std::string readAllFileContents(const std::string& filename) { std::ifstream t(filename); std::string page((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); t.close(); return page; } void saAuth(const std::string& email, const std::string& password) { CURL* curl = curl_easy_init(); CURLcode res; std::string url = "https://smotret-anime.online/users/login"; FILE* cookies_file = fopen("cookies", "w"); if (curl && cookies_file) { fclose(cookies_file); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, DontWriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, nullptr); struct curl_slist* list = NULL; list = curl_slist_append(list, "authority: smotret-anime.online"); list = curl_slist_append(list, "dnt: 1"); list = curl_slist_append(list, "accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"); list = curl_slist_append(list, "upgrade-insecure-requests: 1"); list = curl_slist_append(list, "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"); list = curl_slist_append(list, "sec-fetch-site: none"); list = curl_slist_append(list, "sec-fetch-mode: navigate"); list = curl_slist_append(list, "sec-fetch-user: ?1"); list = curl_slist_append(list, "sec-fetch-dest: document"); list = curl_slist_append(list, "accept-language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7"); curl_easy_setopt(curl, CURLOPT_COOKIESESSION, 1L); curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies"); curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list); res = curl_easy_perform(curl); curl_easy_setopt(curl, CURLOPT_URL, "https://smotret-anime-365.ru/users/syncCookies"); res = curl_easy_perform(curl); curl_easy_setopt(curl, CURLOPT_URL, "https://smotret-anime.online/users/login"); curl_easy_setopt(curl, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL); curl_slist_free_all(list); list = NULL; list = curl_slist_append(list, "authority: smotret-anime.online"); list = curl_slist_append(list, "dnt: 1"); list = curl_slist_append(list, "accept: text/html, */*; q=0.01"); list = curl_slist_append(list, "x-requested-with: XMLHttpRequest"); list = curl_slist_append(list, "content-type: application/x-www-form-urlencoded; charset=UTF-8"); list = curl_slist_append(list, "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"); list = curl_slist_append(list, "origin: https://smotret-anime.online"); list = curl_slist_append(list, "sec-fetch-site: same-origin"); list = curl_slist_append(list, "sec-fetch-mode: cors"); list = curl_slist_append(list, "sec-fetch-dest: empty"); list = curl_slist_append(list, "referer: https://smotret-anime.online/users/login"); list = curl_slist_append(list, "accept-language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list); curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_COOKIELIST, "FLUSH"); std::string cookf = readAllFileContents("cookies"); size_t i = cookf.find("csrf"); i += 5; std::string csrf = cookf.substr(i, 92); std::string postfield = "csrf=" + csrf + "&LoginForm%5Busername%5D=" + email + "&LoginForm%5Bpassword%5D=" + password + "&yt0=&dynpage=1"; const char* data = postfield.c_str(); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, postfield.size()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); res = curl_easy_perform(curl); curl_slist_free_all(list); } curl_easy_cleanup(curl); } void parseEpisodes(cMain* cMain, std::string& readBuffer) { json j = json::parse(readBuffer); j = j["data"]["episodes"]; cMain->epIDs.clear(); cMain->epNames.clear(); wxCommandEvent* event_clear = new wxCommandEvent(MY_EVENT_TYPE, cMain->ID_CLEAR_GUI_FOR_CHOOSED_ANIME); wxQueueEvent(cMain, event_clear); for (auto& ep : j) { long long id = ep["id"].get<long long>(); std::string episodeFull = ep["episodeFull"].get<std::string>(); cMain->epIDs.push_back(id); wxCommandEvent* event_append = new wxCommandEvent(MY_EVENT_TYPE, cMain->ID_CHOOSE_EPISODES_TO_DOWNLOAD); std::string* temp = new std::string; *temp = episodeFull; event_append->SetClientData(temp); wxQueueEvent(cMain, event_append); cMain->epNames.push_back(episodeFull); } cMain->epTransl.clear(); cMain->epTransl.resize(cMain->epIDs.size()); cMain->selTranslIDs.assign(cMain->epIDs.size(), -1); } void findEpisodesSA(cMain* cMain, CURL* curl_handle, size_t ind) { long long id = cMain->animeIDs[ind]; std::string readBuffer; #ifdef _DEBUG std::string request_url = "https://smotret-anime.online/api/series/" + std::to_string(id) + "?pretty=1"; #else std::string request_url = "https://smotret-anime.online/api/series/" + std::to_string(id); #endif if (requestSAapi(curl_handle, request_url, readBuffer) && !readBuffer.empty()) { parseEpisodes(cMain, readBuffer); } enableMainPanel(cMain); } void cMain::execSaAuth() { saLoginDialog->ShowModal(); std::string email = (std::string)saLoginDialog->GetValue(); saPasswordDialog->ShowModal(); std::string password = (std::string)saPasswordDialog->GetValue(); if (!email.empty() && !password.empty()) { std::thread auther(saAuth, email, password); auther.detach(); } } void cMain::execCURL() { curl_handle = curl_easy_init(); curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 0L); curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, USER_AGENT); curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteCallbackToString); curl_handle_cookies = curl_easy_init(); curl_easy_setopt(curl_handle_cookies, CURLOPT_VERBOSE, 0L); curl_easy_setopt(curl_handle_cookies, CURLOPT_COOKIEJAR, "cookies"); curl_easy_setopt(curl_handle_cookies, CURLOPT_COOKIEFILE, "cookies"); curl_easy_setopt(curl_handle_cookies, CURLOPT_WRITEFUNCTION, WriteCallbackToString); curl_multi_handle = curl_multi_init(); } void findEpTranslations(cMain* cMain, CURL* curl_handle, size_t index, wxArrayInt checkedEps) { if (checkedEps.Item(0) == 0) { index++; } size_t epInd = checkedEps.Item(index); epInd--; if (cMain->selTranslIDs[epInd] == -1) { getEpInfo(cMain, curl_handle, epInd); } cMain->cur_ep_index = epInd; refreshTranslatesList(cMain, cMain->epTransl[epInd]); enableMainPanel(cMain); } void getEpInfo(cMain* cMain, CURL* curl_handle, size_t index) { std::string epIDstr = std::to_string(cMain->epIDs[index]); #ifdef _DEBUG std::string request_url = "https://smotret-anime.online/api/episodes/" + epIDstr + "?pretty=1"; #else std::string request_url = "https://smotret-anime.online/api/episodes/" + epIDstr; #endif std::string readBuffer; if (requestSAapi(curl_handle, request_url, readBuffer) && !readBuffer.empty()) { parseTranslations(cMain, curl_handle, readBuffer, index); } if (cMain->epTransl[index].size()) { cMain->selTranslIDs[index] = 0; } } void refreshTranslatesList(cMain* cMain, std::vector<transl>& info) { wxCommandEvent* event_remove = new wxCommandEvent(MY_EVENT_TYPE, cMain->ID_TRANSLATES_LIST); wxQueueEvent(cMain, event_remove); for (size_t i = 0; i < info.size(); ++i) { wxCommandEvent* event_insert = new wxCommandEvent(MY_EVENT_TYPE, cMain->ID_TRANSLATES_LIST_INSERT); event_insert->SetInt(i); std::string* params = new std::string[4]; params[0] = info[i].translName; params[1] = std::to_string(info[i].size / 1024 / 1024) + " MB"; params[2] = info[i].quality + "p"; std::string duration_fixed = std::to_string((long long)info[i].duration / 60) + "m " + std::to_string((long long)info[i].duration % 60) + "s"; params[3] = duration_fixed; event_insert->SetClientData(params); wxQueueEvent(cMain, event_insert); } } void enableMainPanel(cMain* cMain) { wxCommandEvent* event = new wxCommandEvent(MY_EVENT_TYPE, cMain->ID_WXPANEL_MAIN); wxQueueEvent(cMain, event); } void disableMainPanel(cMain* cMain, wxString status = "Working") { cMain->main_panel->Disable(); cMain->SetStatusText(status, 0); } void cMain::onButtonSearchAnime(wxCommandEvent& evt) { if (button_search_anime->IsEnabled()) { disableMainPanel(this, "Searching"); std::string animename = (std::string)entry_anime_name->GetValue().ToUTF8(); std::thread searcher(findAnimeSA, this, curl_handle, animename); searcher.detach(); } evt.Skip(); } void cMain::onButtonDownloadAnime(wxCommandEvent& evt) { disableMainPanel(this, "Downloading"); wxArrayInt checkedEps; size_t n = choose_episodes_to_download->GetCheckedItems(checkedEps); size_t index = downloads_list->GetItemCount(); bool is_download_only_subs = download_only_subs_checkbox->IsChecked(); std::thread downloader(dowloadAnimeSA, this, curl_handle, n, checkedEps, index, is_download_only_subs); downloader.detach(); evt.Skip(); } void cMain::onButtonSelectTitle(wxCommandEvent& evt) { disableMainPanel(this); size_t ind = choose_anime->GetSelection(); choosedTitleName = animeNames[ind]; std::thread downloader(findEpisodesSA, this, curl_handle, ind); downloader.detach(); evt.Skip(); } void cMain::onAnimeEntryChange(wxCommandEvent& evt) { if (entry_anime_name->GetValue().empty()) { button_search_anime->Disable(); } else { button_search_anime->Enable(); } evt.Skip(); } void cMain::onCheckListChecked(wxCommandEvent& evt) { if (evt.GetInt() == 0) { if (choose_episodes_to_download->IsChecked(0)) { for (size_t i = 1; i < choose_episodes_to_download->GetCount(); ++i) { choose_episodes_to_download->Check(i); } } else { for (size_t i = 1; i < choose_episodes_to_download->GetCount(); ++i) { choose_episodes_to_download->Check(i, false); } } } choose_episode->Clear(); wxArrayInt checkedEps; size_t n = choose_episodes_to_download->GetCheckedItems(checkedEps); for (size_t i = 0; i < n; ++i) { if (checkedEps.Item(i) != 0) { choose_episode->Append(wxString::FromUTF8(epNames[checkedEps.Item(i) - 1].c_str())); } } evt.Skip(); } void cMain::onTopMenuInfo(wxCommandEvent& evt) { wxAboutDialogInfo info; info.SetName("SA"); info.SetVersion("1.0"); info.SetDescription("Program to download anime from smotret-anime.online"); info.SetCopyright(wxT("(C) 2020 Alexandr Starovoytov <stewk6@gmail.com>")); wxAboutBox(info); evt.Skip(); } void cMain::onEpisodeChoosen(wxCommandEvent& evt) { disableMainPanel(this); size_t index = evt.GetInt(); wxArrayInt checkedEps; choose_episodes_to_download->GetCheckedItems(checkedEps); std::thread downloader(findEpTranslations, this, curl_handle, index, checkedEps); downloader.detach(); evt.Skip(); } void cMain::onTranslationChoosen(wxListEvent& evt) { size_t trIndex = evt.GetIndex(); selTranslIDs[cur_ep_index] = trIndex; evt.Skip(); } void cMain::onlogoutSA(wxCommandEvent& evt) { do_logout = true; evt.Skip(); Close(); } void cMain::OnDownloadsListRightClick(wxListEvent& evt) { void* data = reinterpret_cast<void*>(evt.GetItem().GetData()); wxMenu mnu; #define ID_SOMETHING 2001 #define ID_SOMETHING_ELSE 2002 mnu.SetClientData(data); mnu.Append(ID_SOMETHING, "Do something"); mnu.Append(ID_SOMETHING_ELSE, "Do something else"); mnu.Connect(wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(cMain::OnPopupClick), NULL, this); PopupMenu(&mnu); } void cMain::OnPopupClick(wxCommandEvent& evt) { void* data = static_cast<wxMenu*>(evt.GetEventObject())->GetClientData(); switch (evt.GetId()) { case ID_SOMETHING: break; case ID_SOMETHING_ELSE: break; } } void cMain::OnEnableMainPanel(wxCommandEvent& evt) { main_panel->Enable(); SetStatusText(wxT("Ready"), 0); evt.Skip(); } void cMain::OnClearGuiForSearch(wxCommandEvent& evt) { choose_episode->Clear(); choose_anime->Clear(); choose_episodes_to_download->Clear(); translates_list->DeleteAllItems(); evt.Skip(); } void cMain::OnAppendToAnimesList(wxCommandEvent& evt) { std::string* temp = (std::string *)evt.GetClientData(); choose_anime->Append(wxString::FromUTF8(temp->c_str())); delete temp; evt.Skip(); } void cMain::OnClearGuiForChoosedAnime(wxCommandEvent& evt) { choose_episodes_to_download->Clear(); choose_episode->Clear(); choose_episodes_to_download->Append(wxString::FromUTF8("Выделить все")); translates_list->DeleteAllItems(); evt.Skip(); } void cMain::OnChooseEpisodesToDownloadAppend(wxCommandEvent& evt) { std::string* temp = (std::string*)evt.GetClientData(); choose_episodes_to_download->Append(wxString::FromUTF8(temp->c_str())); delete temp; evt.Skip(); } void cMain::OnClearTranslatesList(wxCommandEvent& evt) { translates_list->DeleteAllItems(); evt.Skip(); } void cMain::OnInsertToTranslatesList(wxCommandEvent& evt) { size_t i = evt.GetInt(); std::string* params = (std::string*)evt.GetClientData(); translates_list->InsertItem(i, wxString::FromUTF8(params[0].c_str())); translates_list->SetItem(i, 1, params[1]); translates_list->SetItem(i, 2, params[2]); translates_list->SetItem(i, 3, params[3]); delete[] params; evt.Skip(); } void cMain::onSetDownloadStasus(wxCommandEvent& evt) { long long index = evt.GetInt(); wxString status = evt.GetString(); downloads_list->SetItem(index, 3, status); downloads_list->SetItem(index, 6, "0"); evt.Skip(); } void cMain::onSetDownloadParams(wxCommandEvent& evt) { long long i = evt.GetInt(); std::string* params = (std::string*)evt.GetClientData(); downloads_list->SetItem(i, 4, params[0]); downloads_list->SetItem(i, 6, params[1]); downloads_list->SetItem(i, 5, params[2]); delete[] params; evt.Skip(); } void cMain::onSetDownloadParamsProgress(wxCommandEvent& evt) { long long index = evt.GetInt(); wxString str = evt.GetString(); downloads_list->SetItem(index, 2, str); evt.Skip(); } void cMain::onDownloadsListInsert(wxCommandEvent& evt) { long long i = evt.GetInt(); std::string* params = (std::string*)evt.GetClientData(); downloads_list->InsertItem(i, wxString::FromUTF8(params[0].c_str())); downloads_list->SetItem(i, 1, params[1]); downloads_list->SetItem(i, 2, "0%"); downloads_list->SetItem(i, 3, "downloading"); downloads_list->SetItem(i, 4, "0"); downloads_list->SetItem(i, 5, "0"); downloads_list->SetItem(i, 6, "0"); delete[] params; evt.Skip(); }
[ "saniy200311@gmail.com" ]
saniy200311@gmail.com
ed115d11de77fe5d2c13bd7726915cb527742deb
ef3cd329865eb1c50fc639af7db7168079bd9b37
/src/walletdb.cpp
132bacb62aaa8eb4801294609778575da6cc267d
[ "MIT" ]
permissive
flandersdev/flanders-source
0d76b91ea73560a6ac87001b7b3a86b339d078d9
92284c52ce1a81b96ea531fddc3a21e9942821ed
refs/heads/master
2020-03-12T11:00:09.438907
2018-04-22T16:28:38
2018-04-22T16:28:38
130,585,832
0
0
null
null
null
null
UTF-8
C++
false
false
23,828
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletdb.h" #include "wallet.h" #include <boost/version.hpp> #include <boost/filesystem.hpp> using namespace std; using namespace boost; static uint64_t nAccountingEntryNumber = 0; extern bool fWalletUnlockStakingOnly; // // CWalletDB // bool CWalletDB::WriteName(const string& strAddress, const string& strName) { nWalletDBUpdated++; return Write(make_pair(string("name"), strAddress), strName); } bool CWalletDB::EraseName(const string& strAddress) { // This should only be used for sending addresses, never for receiving addresses, // receiving addresses must always have an address book entry if they're not change return. nWalletDBUpdated++; return Erase(make_pair(string("name"), strAddress)); } bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account) { account.SetNull(); return Read(make_pair(string("acc"), strAccount), account); } bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account) { return Write(make_pair(string("acc"), strAccount), account); } bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry) { return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry); } bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry) { return WriteAccountingEntry(++nAccountingEntryNumber, acentry); } int64_t CWalletDB::GetAccountCreditDebit(const string& strAccount) { list<CAccountingEntry> entries; ListAccountCreditDebit(strAccount, entries); int64_t nCreditDebit = 0; BOOST_FOREACH (const CAccountingEntry& entry, entries) nCreditDebit += entry.nCreditDebit; return nCreditDebit; } void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries) { bool fAllAccounts = (strAccount == "*"); Dbc* pcursor = GetCursor(); if (!pcursor) throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64_t(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; if (ret == DB_NOTFOUND) break; else if (ret != 0) { pcursor->close(); throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB"); } // Unserialize string strType; ssKey >> strType; if (strType != "acentry") break; CAccountingEntry acentry; ssKey >> acentry.strAccount; if (!fAllAccounts && acentry.strAccount != strAccount) break; ssValue >> acentry; ssKey >> acentry.nEntryNo; entries.push_back(acentry); } pcursor->close(); } DBErrors CWalletDB::ReorderTransactions(CWallet* pwallet) { LOCK(pwallet->cs_wallet); // Old wallets didn't have any defined order for transactions // Probably a bad idea to change the output of this // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap. typedef pair<CWalletTx*, CAccountingEntry*> TxPair; typedef multimap<int64_t, TxPair > TxItems; TxItems txByTime; for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0))); } list<CAccountingEntry> acentries; ListAccountCreditDebit("", acentries); BOOST_FOREACH(CAccountingEntry& entry, acentries) { txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry))); } int64_t& nOrderPosNext = pwallet->nOrderPosNext; nOrderPosNext = 0; std::vector<int64_t> nOrderPosOffsets; for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it) { CWalletTx *const pwtx = (*it).second.first; CAccountingEntry *const pacentry = (*it).second.second; int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos; if (nOrderPos == -1) { nOrderPos = nOrderPosNext++; nOrderPosOffsets.push_back(nOrderPos); if (pacentry) // Have to write accounting regardless, since we don't keep it in memory if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) return DB_LOAD_FAIL; } else { int64_t nOrderPosOff = 0; BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets) { if (nOrderPos >= nOffsetStart) ++nOrderPosOff; } nOrderPos += nOrderPosOff; nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1); if (!nOrderPosOff) continue; // Since we're changing the order, write it back if (pwtx) { if (!WriteTx(pwtx->GetHash(), *pwtx)) return DB_LOAD_FAIL; } else if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) return DB_LOAD_FAIL; } } return DB_LOAD_OK; } class CWalletScanState { public: unsigned int nKeys; unsigned int nCKeys; unsigned int nKeyMeta; bool fIsEncrypted; bool fAnyUnordered; int nFileVersion; vector<uint256> vWalletUpgrade; CWalletScanState() { nKeys = nCKeys = nKeyMeta = 0; fIsEncrypted = false; fAnyUnordered = false; nFileVersion = 0; } }; bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, CWalletScanState &wss, string& strType, string& strErr) { try { // Unserialize // Taking advantage of the fact that pair serialization // is just the two items serialized one after the other ssKey >> strType; if (strType == "name") { string strAddress; ssKey >> strAddress; ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()]; } else if (strType == "tx") { uint256 hash; ssKey >> hash; CWalletTx& wtx = pwallet->mapWallet[hash]; ssValue >> wtx; if (wtx.CheckTransaction() && (wtx.GetHash() == hash)) wtx.BindWallet(pwallet); else { pwallet->mapWallet.erase(hash); return false; } // Undo serialize changes in 31600 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703) { if (!ssValue.empty()) { char fTmp; char fUnused; ssValue >> fTmp >> fUnused >> wtx.strFromAccount; strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str()); wtx.fTimeReceivedIsTxTime = fTmp; } else { strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str()); wtx.fTimeReceivedIsTxTime = 0; } wss.vWalletUpgrade.push_back(hash); } if (wtx.nOrderPos == -1) wss.fAnyUnordered = true; //// debug print //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str()); //printf(" %12"PRId64" %s %s %s\n", // wtx.vout[0].nValue, // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(), // wtx.hashBlock.ToString().substr(0,20).c_str(), // wtx.mapValue["message"].c_str()); } else if (strType == "acentry") { string strAccount; ssKey >> strAccount; uint64_t nNumber; ssKey >> nNumber; if (nNumber > nAccountingEntryNumber) nAccountingEntryNumber = nNumber; if (!wss.fAnyUnordered) { CAccountingEntry acentry; ssValue >> acentry; if (acentry.nOrderPos == -1) wss.fAnyUnordered = true; } } else if (strType == "key" || strType == "wkey") { vector<unsigned char> vchPubKey; ssKey >> vchPubKey; CKey key; if (strType == "key") { wss.nKeys++; CPrivKey pkey; ssValue >> pkey; key.SetPubKey(vchPubKey); if (!key.SetPrivKey(pkey)) { strErr = "Error reading wallet database: CPrivKey corrupt"; return false; } if (key.GetPubKey() != vchPubKey) { strErr = "Error reading wallet database: CPrivKey pubkey inconsistency"; return false; } if (!key.IsValid()) { strErr = "Error reading wallet database: invalid CPrivKey"; return false; } } else { CWalletKey wkey; ssValue >> wkey; key.SetPubKey(vchPubKey); if (!key.SetPrivKey(wkey.vchPrivKey)) { strErr = "Error reading wallet database: CPrivKey corrupt"; return false; } if (key.GetPubKey() != vchPubKey) { strErr = "Error reading wallet database: CWalletKey pubkey inconsistency"; return false; } if (!key.IsValid()) { strErr = "Error reading wallet database: invalid CWalletKey"; return false; } } if (!pwallet->LoadKey(key)) { strErr = "Error reading wallet database: LoadKey failed"; return false; } } else if (strType == "mkey") { unsigned int nID; ssKey >> nID; CMasterKey kMasterKey; ssValue >> kMasterKey; if(pwallet->mapMasterKeys.count(nID) != 0) { strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID); return false; } pwallet->mapMasterKeys[nID] = kMasterKey; if (pwallet->nMasterKeyMaxID < nID) pwallet->nMasterKeyMaxID = nID; } else if (strType == "ckey") { wss.nCKeys++; vector<unsigned char> vchPubKey; ssKey >> vchPubKey; vector<unsigned char> vchPrivKey; ssValue >> vchPrivKey; if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey)) { strErr = "Error reading wallet database: LoadCryptedKey failed"; return false; } wss.fIsEncrypted = true; } else if (strType == "keymeta") { CPubKey vchPubKey; ssKey >> vchPubKey; CKeyMetadata keyMeta; ssValue >> keyMeta; wss.nKeyMeta++; pwallet->LoadKeyMetadata(vchPubKey, keyMeta); // find earliest key creation time, as wallet birthday if (!pwallet->nTimeFirstKey || (keyMeta.nCreateTime < pwallet->nTimeFirstKey)) pwallet->nTimeFirstKey = keyMeta.nCreateTime; } else if (strType == "defaultkey") { ssValue >> pwallet->vchDefaultKey; } else if (strType == "pool") { int64_t nIndex; ssKey >> nIndex; CKeyPool keypool; ssValue >> keypool; pwallet->setKeyPool.insert(nIndex); // If no metadata exists yet, create a default with the pool key's // creation time. Note that this may be overwritten by actually // stored metadata for that key later, which is fine. CKeyID keyid = keypool.vchPubKey.GetID(); if (pwallet->mapKeyMetadata.count(keyid) == 0) pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime); } else if (strType == "version") { ssValue >> wss.nFileVersion; if (wss.nFileVersion == 10300) wss.nFileVersion = 300; } else if (strType == "cscript") { uint160 hash; ssKey >> hash; CScript script; ssValue >> script; if (!pwallet->LoadCScript(script)) { strErr = "Error reading wallet database: LoadCScript failed"; return false; } } else if (strType == "orderposnext") { ssValue >> pwallet->nOrderPosNext; } } catch (...) { return false; } return true; } static bool IsKeyType(string strType) { return (strType== "key" || strType == "wkey" || strType == "mkey" || strType == "ckey"); } DBErrors CWalletDB::LoadWallet(CWallet* pwallet) { pwallet->vchDefaultKey = CPubKey(); CWalletScanState wss; bool fNoncriticalErrors = false; DBErrors result = DB_LOAD_OK; try { LOCK(pwallet->cs_wallet); int nMinVersion = 0; if (Read((string)"minversion", nMinVersion)) { if (nMinVersion > CLIENT_VERSION) return DB_TOO_NEW; pwallet->LoadMinVersion(nMinVersion); } // Get cursor Dbc* pcursor = GetCursor(); if (!pcursor) { printf("Error getting wallet database cursor\n"); return DB_CORRUPT; } while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue); if (ret == DB_NOTFOUND) break; else if (ret != 0) { printf("Error reading next record from wallet database\n"); return DB_CORRUPT; } // Try to be tolerant of single corrupt records: string strType, strErr; if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr)) { // losing keys is considered a catastrophic error, anything else // we assume the user can live with: if (IsKeyType(strType)) result = DB_CORRUPT; else { // Leave other errors alone, if we try to fix them we might make things worse. fNoncriticalErrors = true; // ... but do warn the user there is something wrong. if (strType == "tx") // Rescan if there is a bad transaction record: SoftSetBoolArg("-rescan", true); } } if (!strErr.empty()) printf("%s\n", strErr.c_str()); } pcursor->close(); } catch (...) { result = DB_CORRUPT; } if (fNoncriticalErrors && result == DB_LOAD_OK) result = DB_NONCRITICAL_ERROR; // Any wallet corruption at all: skip any rewriting or // upgrading, we don't want to make it worse. if (result != DB_LOAD_OK) return result; printf("nFileVersion = %d\n", wss.nFileVersion); printf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n", wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys); // nTimeFirstKey is only reliable if all keys have metadata if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta) pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value' BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade) WriteTx(hash, pwallet->mapWallet[hash]); // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc: if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000)) return DB_NEED_REWRITE; if (wss.nFileVersion < CLIENT_VERSION) // Update WriteVersion(CLIENT_VERSION); if (wss.fAnyUnordered) result = ReorderTransactions(pwallet); return result; } void ThreadFlushWalletDB(void* parg) { // Make this thread recognisable as the wallet flushing thread RenameThread("flanders-wallet"); const string& strFile = ((const string*)parg)[0]; static bool fOneThread; if (fOneThread) return; fOneThread = true; if (!GetBoolArg("-flushwallet", true)) return; unsigned int nLastSeen = nWalletDBUpdated; unsigned int nLastFlushed = nWalletDBUpdated; int64_t nLastWalletUpdate = GetTime(); while (!fShutdown) { MilliSleep(500); if (nLastSeen != nWalletDBUpdated) { nLastSeen = nWalletDBUpdated; nLastWalletUpdate = GetTime(); } if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2) { TRY_LOCK(bitdb.cs_db,lockDb); if (lockDb) { // Don't do this if any databases are in use int nRefCount = 0; map<string, int>::iterator mi = bitdb.mapFileUseCount.begin(); while (mi != bitdb.mapFileUseCount.end()) { nRefCount += (*mi).second; mi++; } if (nRefCount == 0 && !fShutdown) { map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile); if (mi != bitdb.mapFileUseCount.end()) { printf("Flushing wallet.dat\n"); nLastFlushed = nWalletDBUpdated; int64_t nStart = GetTimeMillis(); // Flush wallet.dat so it's self contained bitdb.CloseDb(strFile); bitdb.CheckpointLSN(strFile); bitdb.mapFileUseCount.erase(mi++); printf("Flushed wallet.dat %"PRId64"ms\n", GetTimeMillis() - nStart); } } } } } } bool BackupWallet(const CWallet& wallet, const string& strDest) { if (!wallet.fFileBacked) return false; while (!fShutdown) { { LOCK(bitdb.cs_db); if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0) { // Flush log data to the dat file bitdb.CloseDb(wallet.strWalletFile); bitdb.CheckpointLSN(wallet.strWalletFile); bitdb.mapFileUseCount.erase(wallet.strWalletFile); // Copy wallet.dat filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile; filesystem::path pathDest(strDest); if (filesystem::is_directory(pathDest)) pathDest /= wallet.strWalletFile; try { #if BOOST_VERSION >= 104000 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists); #else filesystem::copy_file(pathSrc, pathDest); #endif printf("copied wallet.dat to %s\n", pathDest.string().c_str()); return true; } catch(const filesystem::filesystem_error &e) { printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what()); return false; } } } MilliSleep(100); } return false; } // // Try to (very carefully!) recover wallet.dat if there is a problem. // bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys) { // Recovery procedure: // move wallet.dat to wallet.timestamp.bak // Call Salvage with fAggressive=true to // get as much data as possible. // Rewrite salvaged data to wallet.dat // Set -rescan so any missing transactions will be // found. int64_t now = GetTime(); std::string newFilename = strprintf("wallet.%"PRId64".bak", now); int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL, newFilename.c_str(), DB_AUTO_COMMIT); if (result == 0) printf("Renamed %s to %s\n", filename.c_str(), newFilename.c_str()); else { printf("Failed to rename %s to %s\n", filename.c_str(), newFilename.c_str()); return false; } std::vector<CDBEnv::KeyValPair> salvagedData; bool allOK = dbenv.Salvage(newFilename, true, salvagedData); if (salvagedData.empty()) { printf("Salvage(aggressive) found no records in %s.\n", newFilename.c_str()); return false; } printf("Salvage(aggressive) found %"PRIszu" records\n", salvagedData.size()); bool fSuccess = allOK; Db* pdbCopy = new Db(&dbenv.dbenv, 0); int ret = pdbCopy->open(NULL, // Txn pointer filename.c_str(), // Filename "main", // Logical db name DB_BTREE, // Database type DB_CREATE, // Flags 0); if (ret > 0) { printf("Cannot create database file %s\n", filename.c_str()); return false; } CWallet dummyWallet; CWalletScanState wss; DbTxn* ptxn = dbenv.TxnBegin(); BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData) { if (fOnlyKeys) { CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION); CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION); string strType, strErr; bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue, wss, strType, strErr); if (!IsKeyType(strType)) continue; if (!fReadOK) { printf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType.c_str(), strErr.c_str()); continue; } } Dbt datKey(&row.first[0], row.first.size()); Dbt datValue(&row.second[0], row.second.size()); int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE); if (ret2 > 0) fSuccess = false; } ptxn->commit(0); pdbCopy->close(0); delete pdbCopy; return fSuccess; } bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename) { return CWalletDB::Recover(dbenv, filename, false); }
[ "laatmaar19@hotmail.com" ]
laatmaar19@hotmail.com
dc15a806a5759c9a45c836a09ef0a9df0202d2cb
1027d84f3e867e16b6bd7022d0e2d4a2ae79c927
/export/windows/cpp/obj/src/haxe/zip/FlushMode.cpp
fd31baae3026ea4969606a07cd0862cc2536fad1
[]
no_license
ninjamuffin99/PixelDayPCGame
d5c252c51a2502cc3f4d15c07e82933a7c63155e
ebebd59c642aa4ce306d2ef0b74ed16c247dfd83
refs/heads/master
2021-05-12T16:21:38.981304
2018-01-29T01:09:24
2018-01-29T01:09:24
117,009,635
0
0
null
null
null
null
UTF-8
C++
false
true
4,174
cpp
// Generated by Haxe 3.4.4 #include <hxcpp.h> #ifndef INCLUDED_haxe_zip_FlushMode #include <haxe/zip/FlushMode.h> #endif namespace haxe{ namespace zip{ ::haxe::zip::FlushMode FlushMode_obj::BLOCK; ::haxe::zip::FlushMode FlushMode_obj::FINISH; ::haxe::zip::FlushMode FlushMode_obj::FULL; ::haxe::zip::FlushMode FlushMode_obj::_hx_NO; ::haxe::zip::FlushMode FlushMode_obj::SYNC; bool FlushMode_obj::__GetStatic(const ::String &inName, ::Dynamic &outValue, hx::PropertyAccess inCallProp) { if (inName==HX_("BLOCK",2d,ad,ea,32)) { outValue = FlushMode_obj::BLOCK; return true; } if (inName==HX_("FINISH",53,ec,01,39)) { outValue = FlushMode_obj::FINISH; return true; } if (inName==HX_("FULL",8f,b1,85,2e)) { outValue = FlushMode_obj::FULL; return true; } if (inName==HX_("NO",41,44,00,00)) { outValue = FlushMode_obj::_hx_NO; return true; } if (inName==HX_("SYNC",5b,82,20,37)) { outValue = FlushMode_obj::SYNC; return true; } return super::__GetStatic(inName, outValue, inCallProp); } HX_DEFINE_CREATE_ENUM(FlushMode_obj) int FlushMode_obj::__FindIndex(::String inName) { if (inName==HX_("BLOCK",2d,ad,ea,32)) return 4; if (inName==HX_("FINISH",53,ec,01,39)) return 3; if (inName==HX_("FULL",8f,b1,85,2e)) return 2; if (inName==HX_("NO",41,44,00,00)) return 0; if (inName==HX_("SYNC",5b,82,20,37)) return 1; return super::__FindIndex(inName); } int FlushMode_obj::__FindArgCount(::String inName) { if (inName==HX_("BLOCK",2d,ad,ea,32)) return 0; if (inName==HX_("FINISH",53,ec,01,39)) return 0; if (inName==HX_("FULL",8f,b1,85,2e)) return 0; if (inName==HX_("NO",41,44,00,00)) return 0; if (inName==HX_("SYNC",5b,82,20,37)) return 0; return super::__FindArgCount(inName); } hx::Val FlushMode_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { if (inName==HX_("BLOCK",2d,ad,ea,32)) return BLOCK; if (inName==HX_("FINISH",53,ec,01,39)) return FINISH; if (inName==HX_("FULL",8f,b1,85,2e)) return FULL; if (inName==HX_("NO",41,44,00,00)) return _hx_NO; if (inName==HX_("SYNC",5b,82,20,37)) return SYNC; return super::__Field(inName,inCallProp); } static ::String FlushMode_obj_sStaticFields[] = { HX_("NO",41,44,00,00), HX_("SYNC",5b,82,20,37), HX_("FULL",8f,b1,85,2e), HX_("FINISH",53,ec,01,39), HX_("BLOCK",2d,ad,ea,32), ::String(null()) }; static void FlushMode_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(FlushMode_obj::BLOCK,"BLOCK"); HX_MARK_MEMBER_NAME(FlushMode_obj::FINISH,"FINISH"); HX_MARK_MEMBER_NAME(FlushMode_obj::FULL,"FULL"); HX_MARK_MEMBER_NAME(FlushMode_obj::_hx_NO,"_hx_NO"); HX_MARK_MEMBER_NAME(FlushMode_obj::SYNC,"SYNC"); }; #ifdef HXCPP_VISIT_ALLOCS static void FlushMode_obj_sVisitStatic(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(FlushMode_obj::__mClass,"__mClass"); HX_VISIT_MEMBER_NAME(FlushMode_obj::BLOCK,"BLOCK"); HX_VISIT_MEMBER_NAME(FlushMode_obj::FINISH,"FINISH"); HX_VISIT_MEMBER_NAME(FlushMode_obj::FULL,"FULL"); HX_VISIT_MEMBER_NAME(FlushMode_obj::_hx_NO,"_hx_NO"); HX_VISIT_MEMBER_NAME(FlushMode_obj::SYNC,"SYNC"); }; #endif hx::Class FlushMode_obj::__mClass; Dynamic __Create_FlushMode_obj() { return new FlushMode_obj; } void FlushMode_obj::__register() { hx::Static(__mClass) = hx::_hx_RegisterClass(HX_HCSTRING("haxe.zip.FlushMode","\x12","\x16","\x75","\x3c"), hx::TCanCast< FlushMode_obj >,FlushMode_obj_sStaticFields,0, &__Create_FlushMode_obj, &__Create, &super::__SGetClass(), &CreateFlushMode_obj, FlushMode_obj_sMarkStatics #ifdef HXCPP_VISIT_ALLOCS , FlushMode_obj_sVisitStatic #endif #ifdef HXCPP_SCRIPTABLE , 0 #endif ); __mClass->mGetStaticField = &FlushMode_obj::__GetStatic; } void FlushMode_obj::__boot() { BLOCK = hx::CreateEnum< FlushMode_obj >(HX_HCSTRING("BLOCK","\x2d","\xad","\xea","\x32"),4,0); FINISH = hx::CreateEnum< FlushMode_obj >(HX_HCSTRING("FINISH","\x53","\xec","\x01","\x39"),3,0); FULL = hx::CreateEnum< FlushMode_obj >(HX_HCSTRING("FULL","\x8f","\xb1","\x85","\x2e"),2,0); _hx_NO = hx::CreateEnum< FlushMode_obj >(HX_HCSTRING("NO","\x41","\x44","\x00","\x00"),0,0); SYNC = hx::CreateEnum< FlushMode_obj >(HX_HCSTRING("SYNC","\x5b","\x82","\x20","\x37"),1,0); } } // end namespace haxe } // end namespace zip
[ "cameron.taylor.ninja@gmail.com" ]
cameron.taylor.ninja@gmail.com
fe9f1da6357d3bf9865f04c73e731c6d6f8afb8e
fcdea24e6466d4ec8d7798555358a9af8acf9b35
/Tests/common/GameEntityManager.cpp
72141dc1ca6949d302de39e8bcc579c82ebb50f1
[]
no_license
yingzhang536/mrayy-Game-Engine
6634afecefcb79c2117cecf3e4e635d3089c9590
6b6fcbab8674a6169e26f0f20356d0708620b828
refs/heads/master
2021-01-17T07:59:30.135446
2014-11-30T16:10:54
2014-11-30T16:10:54
27,630,181
2
0
null
null
null
null
UTF-8
C++
false
false
706
cpp
#include "GameEntity.h" #include "GameEntityManager.h" namespace mray{ GameEntityManager::GameEntityManager(){ } GameEntityManager::~GameEntityManager(){ clear(); } void GameEntityManager::addEntity(GCPtr<GameEntity> e){ m_entities.push_back(e); } void GameEntityManager::removeEntity(GCPtr<GameEntity> e){ EntityList::iterator it=m_entities.begin(); for(;it!=m_entities.end();++it){ if(e==*it){ m_entities.erase(it); return; } } } void GameEntityManager::clear(){ m_entities.clear(); } void GameEntityManager::update(float dt){ EntityList::iterator it=m_entities.begin(); for(;it!=m_entities.end();++it){ (*it)->update(dt); } } }
[ "mrayyamen@gmail.com" ]
mrayyamen@gmail.com
e6c88a3738dcb13ef8b5b3f495056b7583fd0c99
4953e6d48e7f5c62a5c6eb6535300fe8d40d1590
/pcsx2/MemoryCard.cpp
0b67d68730e203306bddb8654d966421f8fc694a
[]
no_license
0xZERO3/PCSX2-rr-lua
14d32c4f907bb57d7a880d61d8196df9e69876a3
01d886fba27afce0cc13ea1198dcc9e4213ab6d0
refs/heads/master
2021-01-18T02:08:17.168784
2013-12-30T06:35:08
2013-12-30T06:35:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,166
cpp
/* Pcsx2 - Pc Ps2 Emulator * Copyright (C) 2002-2008 Pcsx2 Team * * 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 */ #include "PrecompiledHeader.h" #include "Misc.h" #include "MemoryCard.h" #include "Paths.h" #ifdef WIN32 extern void NTFS_CompressFile( const char* file, bool compressMode ); #endif FILE* MemoryCard::cardfile[2] = { NULL, NULL }; // Ensures memory card files are created/initialized. void MemoryCard::Init() { for( int i=0; i<2; i++ ) { if( Config.Mcd[i].Enabled && cardfile[i] == NULL ) cardfile[i] = Load(i); } } void MemoryCard::Shutdown() { for( int i=0; i<2; i++ ) Unload( i ); } void MemoryCard::Unload( uint mcd ) { jASSUME( mcd < 2 ); if(cardfile[mcd] == NULL) return; fclose( cardfile[mcd] ); cardfile[mcd] = NULL; } bool MemoryCard::IsPresent( uint mcd ) { jASSUME( mcd < 2 ); return cardfile[mcd] != NULL; } FILE *MemoryCard::Load( uint mcd ) { FILE *f; jASSUME( mcd < 2 ); string str( Config.Mcd[mcd].Filename ); if( str.empty() ) Path::Combine( str, MEMCARDS_DIR, fmt_string( "Mcd00%d.ps2", mcd ) ); if( !Path::Exists(str) ) Create( str.c_str() ); #ifdef WIN32 NTFS_CompressFile( str.c_str(), Config.McdEnableNTFS ); #endif f = fopen( str.c_str(), "r+b" ); if (f == NULL) { Msgbox::Alert("Failed loading MemoryCard from file: %hs", params &str); return NULL; } return f; } void MemoryCard::Seek( FILE *f, u32 adr ) { u32 size; fseek(f, 0, SEEK_END); size = ftell(f); if (size == MCD_SIZE + 64) fseek(f, adr + 64, SEEK_SET); else if (size == MCD_SIZE + 3904) fseek(f, adr + 3904, SEEK_SET); else fseek(f, adr, SEEK_SET); } void MemoryCard::Read( uint mcd, u8 *data, u32 adr, int size ) { jASSUME( mcd < 2 ); FILE* const mcfp = cardfile[mcd]; if( mcfp == NULL ) { Console::Error( "MemoryCard > Ignoring attempted read from disabled card." ); memset(data, 0, size); return; } Seek(mcfp, adr); fread(data, 1, size, mcfp); } void MemoryCard::Save( uint mcd, const u8 *data, u32 adr, int size ) { jASSUME( mcd < 2 ); FILE* const mcfp = cardfile[mcd]; if( mcfp == NULL ) { Console::Error( "MemoryCard > Ignoring attempted save/write to disabled card." ); return; } Seek(mcfp, adr); u8 *currentdata = (u8 *)malloc(size); fread(currentdata, 1, size, mcfp); for (int i=0; i<size; i++) { if ((currentdata[i] & data[i]) != data[i]) Console::Notice("MemoryCard : writing odd data"); currentdata[i] &= data[i]; } Seek(mcfp, adr); fwrite(currentdata, 1, size, mcfp); free(currentdata); } void MemoryCard::Erase( uint mcd, u32 adr ) { u8 data[528*16]; memset8_obj<0xff>(data); // clears to -1's jASSUME( mcd < 2 ); FILE* const mcfp = cardfile[mcd]; if( mcfp == NULL ) { DevCon::Notice( "MemoryCard > Ignoring seek for disabled card." ); return; } Seek(mcfp, adr); fwrite(data, 1, 528*16, mcfp); } void MemoryCard::Create( const char *mcdFile ) { //int enc[16] = {0x77,0x7f,0x7f,0x77,0x7f,0x7f,0x77,0x7f,0x7f,0x77,0x7f,0x7f,0,0,0,0}; FILE* fp = fopen( mcdFile, "wb" ); if( fp == NULL ) return; for( uint i=0; i<16384; i++ ) { for( uint j=0; j<528; j++ ) fputc( 0xFF,fp ); // for(j=0; j<16; j++) fputc(enc[j],fp); } fclose( fp ); } u64 MemoryCard::GetCRC( uint mcd ) { jASSUME( mcd < 2 ); FILE* const mcfp = cardfile[mcd]; if( mcfp == NULL ) return 0; Seek( mcfp, 0 ); u64 retval = 0; for( uint i=MC2_SIZE/sizeof(u64); i; --i ) { u64 temp; fread( &temp, sizeof(temp), 1, mcfp ); retval ^= temp; } return retval; }
[ "taba" ]
taba
b8107c4155e5f679cae5491ee505b1e589b40555
2250d0f835699eb29e0d87c32cbf0d1d187b9735
/Source/TLCG/Public/TLCGPlayerController.h
680daa8230bb57e8c911e988552b837bb5944efd
[]
no_license
romaktion/TLCG
c3f4f20e030abe4b7d100afe321ec2ce969d58e4
ff35e73d1376e3944fb396224069a5b15bf9a64a
refs/heads/master
2020-08-13T03:16:27.741429
2020-04-22T13:31:37
2020-04-22T13:31:37
214,895,917
2
0
null
null
null
null
UTF-8
C++
false
false
851
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/PlayerController.h" #include "TLCGGameState.h" #include "TLCGPlayerController.generated.h" /** * */ UCLASS() class TLCG_API ATLCGPlayerController : public APlayerController { GENERATED_UCLASS_BODY() UFUNCTION(NetMulticast, Reliable) void MulticastGoToMainMenu(bool Win, const TArray<FLeaderBoard>& InLeaderBoard); UFUNCTION(BlueprintCallable, Category = "UserInterface") void PerformClientTravel(const FString& Path); UFUNCTION(BlueprintCallable, Server, Reliable, WithValidation, Category = "TLCGPlayerController", DisplayName = "SpawnPawn") void ServerSpawnPawn(const FString& ClassPath); UFUNCTION(Server, Reliable, WithValidation) void ServerAllowStartRound(); AActor* StartSpot; };
[ "romaktion@gmail.com" ]
romaktion@gmail.com
63efb13938a01af3534e6f39fb3626190f0dfd03
81f1acfbd4c9a32aabcc47bbbba54fcdfd9d73e1
/vitrina/contenedor.h
8254efdcc41fcb4dae13d19fda225af4daf7449d
[]
no_license
rodety/optical
121ffc4819b312ca1fa1edd8722f52d3b379dc7d
f8e41a00252a19d948de6e8b71f99d095917e111
refs/heads/master
2021-01-19T18:58:13.948491
2013-03-12T22:42:41
2013-03-12T22:42:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
911
h
#ifndef CONTENEDOR_H #define CONTENEDOR_H #include "objetopersistente.h" class contenedor:public ObjetoPersistente { private: QString idContenedor; QString idAndamio; QString nombre; QString descripcion; QString pos_fila; QString pos_columna; QString capacidad; public: contenedor(); contenedor(QString,QString,QString,QString,QString,QString,QString); QString getIdContenedor(); QString getIdAndamio(); QString getNombre(); QString getDescripcion(); QString getPosFila(); QString getPosColumna(); QString getCapacidad(); void setIdContenedor(QString); void setIdAndamio(QString); void setNombre(QString); void setDescripcion(QString); void setPosFila(QString); void setPosColumna(QString); void setCapacidad(QString); bool agregar(); bool actualizar(); bool eliminar(); }; #endif // CONTENEDOR_H
[ "leonard@leonard-PC.(none)" ]
leonard@leonard-PC.(none)
ce4112d45f256509c225d33e890e3f7878cbe2c6
fc214bfc7caf6050eec8ec5201e7f7eb568e3a17
/Windows/Qt/Qt5.9-msvc2017_64/5.9/msvc2017_64/include/QtCore/qresultstore.h
811238344ada88ea3468ed0dec99cd1d7b3e75a1
[]
no_license
MediaArea/MediaArea-Utils-Binaries
44402a1dacb43e19ef6857da46a48289b106137d
5cde31480dba6092e195dfae96478c261018bf32
refs/heads/master
2023-09-01T04:54:34.216269
2023-04-11T08:44:15
2023-04-11T08:44:15
57,366,211
4
1
null
2023-04-11T08:44:16
2016-04-29T07:51:36
C++
UTF-8
C++
false
false
7,165
h
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QTCORE_RESULTSTORE_H #define QTCORE_RESULTSTORE_H #include <QtCore/qglobal.h> #ifndef QT_NO_QFUTURE #include <QtCore/qmap.h> #include <QtCore/qdebug.h> QT_BEGIN_NAMESPACE /* ResultStore stores indexed results. Results can be added and retrieved either individually batched in a QVector. Retriveing results and checking which indexes are in the store can be done either by iterating or by random accees. In addition results kan be removed from the front of the store, either individually or in batches. */ #ifndef Q_QDOC namespace QtPrivate { class ResultItem { public: ResultItem(const void *_result, int _count) : m_count(_count), result(_result) { } // contruct with vector of results ResultItem(const void *_result) : m_count(0), result(_result) { } // construct with result ResultItem() : m_count(0), result(Q_NULLPTR) { } bool isValid() const { return result != Q_NULLPTR; } bool isVector() const { return m_count != 0; } int count() const { return (m_count == 0) ? 1 : m_count; } int m_count; // result is either a pointer to a result or to a vector of results, const void *result; // if count is 0 it's a result, otherwise it's a vector. }; class Q_CORE_EXPORT ResultIteratorBase { public: ResultIteratorBase(); ResultIteratorBase(QMap<int, ResultItem>::const_iterator _mapIterator, int _vectorIndex = 0); int vectorIndex() const; int resultIndex() const; ResultIteratorBase operator++(); int batchSize() const; void batchedAdvance(); bool operator==(const ResultIteratorBase &other) const; bool operator!=(const ResultIteratorBase &other) const; bool isVector() const; bool canIncrementVectorIndex() const; protected: QMap<int, ResultItem>::const_iterator mapIterator; int m_vectorIndex; public: template <typename T> const T &value() const { return *pointer<T>(); } template <typename T> const T *pointer() const { if (mapIterator.value().isVector()) return &(reinterpret_cast<const QVector<T> *>(mapIterator.value().result)->at(m_vectorIndex)); else return reinterpret_cast<const T *>(mapIterator.value().result); } }; class Q_CORE_EXPORT ResultStoreBase { public: ResultStoreBase(); void setFilterMode(bool enable); bool filterMode() const; int addResult(int index, const void *result); int addResults(int index, const void *results, int vectorSize, int logicalCount); ResultIteratorBase begin() const; ResultIteratorBase end() const; bool hasNextResult() const; ResultIteratorBase resultAt(int index) const; bool contains(int index) const; int count() const; virtual ~ResultStoreBase(); protected: int insertResultItem(int index, ResultItem &resultItem); void insertResultItemIfValid(int index, ResultItem &resultItem); void syncPendingResults(); void syncResultCount(); int updateInsertIndex(int index, int _count); QMap<int, ResultItem> m_results; int insertIndex; // The index where the next results(s) will be inserted. int resultCount; // The number of consecutive results stored, starting at index 0. bool m_filterMode; QMap<int, ResultItem> pendingResults; int filteredResults; public: template <typename T> int addResult(int index, const T *result) { if (result == 0) return addResult(index, static_cast<void *>(nullptr)); else return addResult(index, static_cast<void *>(new T(*result))); } template <typename T> int addResults(int index, const QVector<T> *results) { return addResults(index, new QVector<T>(*results), results->count(), results->count()); } template <typename T> int addResults(int index, const QVector<T> *results, int totalCount) { if (m_filterMode == true && results->count() != totalCount && 0 == results->count()) return addResults(index, 0, 0, totalCount); else return addResults(index, new QVector<T>(*results), results->count(), totalCount); } int addCanceledResult(int index) { return addResult(index, static_cast<void *>(nullptr)); } template <typename T> int addCanceledResults(int index, int _count) { QVector<T> empty; return addResults(index, &empty, _count); } template <typename T> void clear() { QMap<int, ResultItem>::const_iterator mapIterator = m_results.constBegin(); while (mapIterator != m_results.constEnd()) { if (mapIterator.value().isVector()) delete reinterpret_cast<const QVector<T> *>(mapIterator.value().result); else delete reinterpret_cast<const T *>(mapIterator.value().result); ++mapIterator; } resultCount = 0; m_results.clear(); } }; } // namespace QtPrivate #endif //Q_QDOC QT_END_NAMESPACE #endif // QT_NO_QFUTURE #endif
[ "you@example.com" ]
you@example.com
fc3d97776024678da0091d6fce1bf6296f79c120
ef6f391d7c7699d976c54c659258e7a63264a228
/vectorOfVectors1.cpp
9028afa4ea660894b63843d6876ba41557dd6bda
[]
no_license
MPaluszynski/Sem-III-Jezyki-Programowania-Obiektowego_ZADANIE_2
833d715e095982299ed880e9e232adb5dca8f5e6
0eadaf2342403692bc04e208389f300a53e257a8
refs/heads/master
2023-01-20T08:20:34.288581
2020-11-15T17:57:13
2020-11-15T17:57:13
313,090,282
0
0
null
null
null
null
UTF-8
C++
false
false
1,061
cpp
#include <iostream> #include "vectorNd.h" #include "vectorOfVectors1.h" #include "vectorOfVectors2.h" using namespace std; /*KONSTRUKTORY I DESTRUKTOR KLASY VectorOfVectors1*/ VectorOfVectors1::VectorOfVectors1(){ cout << " Wywolano konstruktor PUSTY VectorOfVectors1 -> utworzono: "<< this <<endl<<endl; size = 3; } VectorOfVectors1::VectorOfVectors1(const VektorNd _vektory[], int _size){ cout << " Wywolano konstruktor ZWYKLY VectorOfVectors1 -> utworzono: "<< this <<endl<<endl; size = _size; for(int i=0;i<size;i++) vektory[i] = _vektory[i]; } VectorOfVectors1::VectorOfVectors1(const VectorOfVectors1& oryginal){ cout << " Wywolano konstruktor KOPIUJACY VectorOfVectors1 -> utworzono: " <<endl<<endl; size = oryginal.size; for(int i=0;i<size;i++) vektory[i] = oryginal.vektory[i]; } VectorOfVectors1::~VectorOfVectors1(){ cout << " Wywolano destruktor VectorOfVectors1 -> zwalniam pamiec: " << this <<endl<<endl; cout << " Destruktor VectorOfVectors1 -> ZAKONCZONO" <<endl<<endl; }
[ "macpalus@gmail.com" ]
macpalus@gmail.com
7df887bb50d8b49fbd97da1542a50479fc513317
68fb4455432da95e830a4efb6940a71916882843
/Source - Alex Denford & Michael Green/Solitaire/game.h
d9ed1597f2f4358b46d427b4837647fe0c23efdc
[]
no_license
pantherNZ/Solitaire
9a6bb2e5f1593e136366193b95157e081536c777
b697b57de2728f0a7844acd6104b1af9207c9ea6
refs/heads/master
2020-03-23T04:27:16.481436
2020-03-19T00:10:29
2020-03-19T00:10:29
141,084,506
0
0
null
null
null
null
UTF-8
C++
false
false
1,230
h
#pragma once #ifndef __GAME_H__ #define __GAME_H__ #include <windows.h> #include "clock.h" #include "level.h" #define VALIDATE(a) if (!a) return(false) class CLevel; class CBackBuffer; class CGame { // Class functions public: virtual ~CGame(); virtual bool Initialise(HINSTANCE _hInstance, HWND _hWnd, int _iWidth, int _iHeight); virtual void Draw(); virtual void Process(float _fDeltaTick); void ExecuteOneFrame(); //(bool& _bGameActive); CBackBuffer* GetBackBuffer() const; CLevel* GetLevel() const; HINSTANCE GetAppInstance() const; HWND GetWindow() const; CClock* GetTimer() const; // Singleton Methods static CGame& GetInstance(); static void DestroyInstance(); void ResetGame(); protected: private: CGame(); CGame(const CGame& _kr); CGame& operator= (const CGame& _kr); // class variables public: protected: // sub classes used in the game CClock* m_pClock; CLevel* m_pLevel; CBackBuffer* m_pBackBuffer; //bool m_bGameActive; //Application data HINSTANCE m_hApplicationInstance; HWND m_hMainWindow; // Singleton Instance static CGame* s_pGame; private: }; #endif // __GAME_H__
[ "pantherNZ@users.noreply.github.com" ]
pantherNZ@users.noreply.github.com
6dee126559fbd99579d345883db8bd3ff63594e4
8ef75ec298e38373a3b9b212eac2762f6c452a25
/SDL2_mixer/external/libmodplug-0.8.9.0/src/load_med.cpp
745e2c65d7e89376bfefa4cee7664f7dec57f3e6
[ "LicenseRef-scancode-public-domain", "Zlib", "GPL-1.0-or-later", "MIT" ]
permissive
mozeal/SDL_gui
dc0d529ba300df41ed0fcb26ec3e176a49cfb316
31bcfbf9c9a5803dc0ffb022b7e7abd76e5c3cfd
refs/heads/master
2022-05-05T06:18:51.640215
2022-04-01T11:23:12
2022-04-01T11:23:12
48,752,765
321
67
MIT
2021-04-21T14:38:23
2015-12-29T15:06:32
C
UTF-8
C++
false
false
29,221
cpp
/* * This source code is public domain. * * Authors: Olivier Lapicque <olivierl@jps.net>, * Adam Goode <adam@evdebs.org> (endian and char fixes for PPC) */ #include "stdafx.h" #include "sndfile.h" //#define MED_LOG #ifdef MED_LOG extern void Log(LPCSTR s, ...); #endif ////////////////////////////////////////////////////////// // OctaMed MED file support (import only) // // Lookup table for bpm values. static const BYTE bpmvals[10] = { 179,164,152,141,131,123,116,110,104,99 }; // flags #define MMD_FLAG_FILTERON 0x1 #define MMD_FLAG_JUMPINGON 0x2 #define MMD_FLAG_JUMP8TH 0x4 #define MMD_FLAG_INSTRSATT 0x8 // instruments are attached (this is a module) #define MMD_FLAG_VOLHEX 0x10 #define MMD_FLAG_STSLIDE 0x20 // SoundTracker mode for slides #define MMD_FLAG_8CHANNEL 0x40 // OctaMED 8 channel song #define MMD_FLAG_SLOWHQ 0x80 // HQ slows playing speed (V2-V4 compatibility) // flags2 #define MMD_FLAG2_BMASK 0x1F #define MMD_FLAG2_BPM 0x20 #define MMD_FLAG2_MIX 0x80 // uses Mixing (V7+) // flags3: #define MMD_FLAG3_STEREO 0x1 // mixing in Stereo mode #define MMD_FLAG3_FREEPAN 0x2 // free panning #define MMD_FLAG3_GM 0x4 // module designed for GM/XG compatibility // generic MMD tags #define MMDTAG_END 0 #define MMDTAG_PTR 0x80000000 // data needs relocation #define MMDTAG_MUSTKNOW 0x40000000 // loader must fail if this isn't recognized #define MMDTAG_MUSTWARN 0x20000000 // loader must warn if this isn't recognized // ExpData tags // # of effect groups, including the global group (will // override settings in MMDSong struct), default = 1 #define MMDTAG_EXP_NUMFXGROUPS 1 #define MMDTAG_TRK_NAME (MMDTAG_PTR|1) // trackinfo tags #define MMDTAG_TRK_NAMELEN 2 // namelen includes zero term. #define MMDTAG_TRK_FXGROUP 3 // effectinfo tags #define MMDTAG_FX_ECHOTYPE 1 #define MMDTAG_FX_ECHOLEN 2 #define MMDTAG_FX_ECHODEPTH 3 #define MMDTAG_FX_STEREOSEP 4 #define MMDTAG_FX_GROUPNAME (MMDTAG_PTR|5) // the Global Effects group shouldn't have name saved! #define MMDTAG_FX_GRPNAMELEN 6 // namelen includes zero term. #pragma pack(1) typedef struct tagMEDMODULEHEADER { DWORD id; // MMD1-MMD3 DWORD modlen; // Size of file DWORD song; // Position in file for this song WORD psecnum; WORD pseq; DWORD blockarr; // Position in file for blocks DWORD mmdflags; DWORD smplarr; // Position in file for samples DWORD reserved; DWORD expdata; // Absolute offset in file for ExpData (0 if not present) DWORD reserved2; WORD pstate; WORD pblock; WORD pline; WORD pseqnum; WORD actplayline; BYTE counter; BYTE extra_songs; // # of songs - 1 } MEDMODULEHEADER; typedef struct tagMMD0SAMPLE { WORD rep, replen; BYTE midich; BYTE midipreset; BYTE svol; signed char strans; } MMD0SAMPLE; // Sample header is immediately followed by sample data... typedef struct tagMMDSAMPLEHEADER { DWORD length; // length of *one* *unpacked* channel in *bytes* WORD type; // if non-negative // bits 0-3 reserved for multi-octave instruments, not supported on the PC // 0x10: 16 bit (otherwise 8 bit) // 0x20: Stereo (otherwise mono) // 0x40: Uses DeltaCode // 0x80: Packed data // -1: Synth // -2: Hybrid // if type indicates packed data, these fields follow, otherwise we go right to the data WORD packtype; // Only 1 = ADPCM is supported WORD subtype; // Packing subtype // ADPCM subtype // 1: g723_40 // 2: g721 // 3: g723_24 BYTE commonflags; // flags common to all packtypes (none defined so far) BYTE packerflags; // flags for the specific packtype ULONG leftchlen; // packed length of left channel in bytes ULONG rightchlen; // packed length of right channel in bytes (ONLY PRESENT IN STEREO SAMPLES) BYTE SampleData[1]; // Sample Data } MMDSAMPLEHEADER; // MMD0/MMD1 song header typedef struct tagMMD0SONGHEADER { MMD0SAMPLE sample[63]; WORD numblocks; // # of blocks WORD songlen; // # of entries used in playseq BYTE playseq[256]; // Play sequence WORD deftempo; // BPM tempo signed char playtransp; // Play transpose BYTE flags; // 0x10: Hex Volumes | 0x20: ST/NT/PT Slides | 0x40: 8 Channels song BYTE flags2; // [b4-b0]+1: Tempo LPB, 0x20: tempo mode, 0x80: mix_conv=on BYTE tempo2; // tempo TPL BYTE trkvol[16]; // track volumes BYTE mastervol; // master volume BYTE numsamples; // # of samples (max=63) } MMD0SONGHEADER; // MMD2/MMD3 song header typedef struct tagMMD2SONGHEADER { MMD0SAMPLE sample[63]; WORD numblocks; // # of blocks WORD numsections; // # of sections DWORD playseqtable; // filepos of play sequence DWORD sectiontable; // filepos of sections table (WORD array) DWORD trackvols; // filepos of tracks volume (BYTE array) WORD numtracks; // # of tracks (max 64) WORD numpseqs; // # of play sequences DWORD trackpans; // filepos of tracks pan values (BYTE array) LONG flags3; // 0x1:stereo_mix, 0x2:free_panning, 0x4:GM/XG compatibility WORD voladj; // vol_adjust (set to 100 if 0) WORD channels; // # of channels (4 if =0) BYTE mix_echotype; // 1:normal,2:xecho BYTE mix_echodepth; // 1..6 WORD mix_echolen; // > 0 signed char mix_stereosep; // -4..4 BYTE pad0[223]; WORD deftempo; // BPM tempo signed char playtransp; // play transpose BYTE flags; // 0x1:filteron, 0x2:jumpingon, 0x4:jump8th, 0x8:instr_attached, 0x10:hex_vol, 0x20:PT_slides, 0x40:8ch_conv,0x80:hq slows playing speed BYTE flags2; // 0x80:mix_conv=on, [b4-b0]+1:tempo LPB, 0x20:tempo_mode BYTE tempo2; // tempo TPL BYTE pad1[16]; BYTE mastervol; // master volume BYTE numsamples; // # of samples (max 63) } MMD2SONGHEADER; // For MMD0 the note information is held in 3 bytes, byte0, byte1, byte2. For reference we // number the bits in each byte 0..7, where 0 is the low bit. // The note is held as bits 5..0 of byte0 // The instrument is encoded in 6 bits, bits 7 and 6 of byte0 and bits 7,6,5,4 of byte1 // The command number is bits 3,2,1,0 of byte1, command data is in byte2: // For command 0, byte2 represents the second data byte, otherwise byte2 // represents the first data byte. typedef struct tagMMD0BLOCK { BYTE numtracks; BYTE lines; // File value is 1 less than actual, so 0 -> 1 line } MMD0BLOCK; // BYTE data[lines+1][tracks][3]; // For MMD1,MMD2,MMD3 the note information is carried in 4 bytes, byte0, byte1, // byte2 and byte3 // The note is held as byte0 (values above 0x84 are ignored) // The instrument is held as byte1 // The command number is held as byte2, command data is in byte3 // For commands 0 and 0x19 byte3 represents the second data byte, // otherwise byte2 represents the first data byte. typedef struct tagMMD1BLOCK { WORD numtracks; // Number of tracks, may be > 64, but then that data is skipped. WORD lines; // Stored value is 1 less than actual, so 0 -> 1 line DWORD info; // Offset of BlockInfo (if 0, no block_info is present) } MMD1BLOCK; typedef struct tagMMD1BLOCKINFO { DWORD hlmask; // Unimplemented - ignore DWORD blockname; // file offset of block name DWORD blocknamelen; // length of block name (including term. 0) DWORD pagetable; // file offset of command page table DWORD cmdexttable; // file offset of command extension table DWORD reserved[4]; // future expansion } MMD1BLOCKINFO; // A set of play sequences is stored as an array of ULONG files offsets // Each offset points to the play sequence itself. typedef struct tagMMD2PLAYSEQ { CHAR name[32]; DWORD command_offs; // filepos of command table DWORD reserved; WORD length; WORD seq[512]; // skip if > 0x8000 } MMD2PLAYSEQ; // A command table contains commands that effect a particular play sequence // entry. The only commands read in are STOP or POSJUMP, all others are ignored // POSJUMP is presumed to have extra bytes containing a WORD for the position typedef struct tagMMDCOMMAND { WORD offset; // Offset within current sequence entry BYTE cmdnumber; // STOP (537) or POSJUMP (538) (others skipped) BYTE extra_count; BYTE extra_bytes[4];// [extra_count]; } MMDCOMMAND; // Last entry has offset == 0xFFFF, cmd_number == 0 and 0 extrabytes typedef struct tagMMD0EXP { DWORD nextmod; // File offset of next Hdr DWORD exp_smp; // Pointer to extra instrument data WORD s_ext_entries; // Number of extra instrument entries WORD s_ext_entrsz; // Size of extra instrument data DWORD annotxt; DWORD annolen; DWORD iinfo; // Instrument names WORD i_ext_entries; WORD i_ext_entrsz; DWORD jumpmask; DWORD rgbtable; BYTE channelsplit[4]; // Only used if 8ch_conv (extra channel for every nonzero entry) DWORD n_info; DWORD songname; // Song name DWORD songnamelen; DWORD dumps; DWORD mmdinfo; DWORD mmdrexx; DWORD mmdcmd3x; DWORD trackinfo_ofs; // ptr to song->numtracks ptrs to tag lists DWORD effectinfo_ofs; // ptr to group ptrs DWORD tag_end; } MMD0EXP; #pragma pack() static void MedConvert(MODCOMMAND *p, const MMD0SONGHEADER *pmsh) //--------------------------------------------------------------- { UINT command = p->command; UINT param = p->param; switch(command) { case 0x00: if (param) command = CMD_ARPEGGIO; else command = 0; break; case 0x01: command = CMD_PORTAMENTOUP; break; case 0x02: command = CMD_PORTAMENTODOWN; break; case 0x03: command = CMD_TONEPORTAMENTO; break; case 0x04: command = CMD_VIBRATO; break; case 0x05: command = CMD_TONEPORTAVOL; break; case 0x06: command = CMD_VIBRATOVOL; break; case 0x07: command = CMD_TREMOLO; break; case 0x0A: if (param & 0xF0) param &= 0xF0; command = CMD_VOLUMESLIDE; if (!param) command = 0; break; case 0x0B: command = CMD_POSITIONJUMP; break; case 0x0C: command = CMD_VOLUME; if (pmsh->flags & MMD_FLAG_VOLHEX) { if (param < 0x80) { param = (param+1) / 2; } else command = 0; } else { if (param <= 0x99) { param = (param >> 4)*10+((param & 0x0F) % 10); if (param > 64) param = 64; } else command = 0; } break; case 0x09: command = (param < 0x20) ? CMD_SPEED : CMD_TEMPO; break; case 0x0D: if (param & 0xF0) param &= 0xF0; command = CMD_VOLUMESLIDE; if (!param) command = 0; break; case 0x0F: // Set Tempo / Special // F.00 = Pattern Break if (!param) command = CMD_PATTERNBREAK; else // F.01 - F.F0: Set tempo/speed if (param <= 0xF0) { if (pmsh->flags & MMD_FLAG_8CHANNEL) { param = (param > 10) ? 99 : bpmvals[param-1]; } else // F.01 - F.0A: Set Speed if (param <= 0x0A) { command = CMD_SPEED; } else // Old tempo if (!(pmsh->flags2 & MMD_FLAG2_BPM)) { param = _muldiv(param, 5*715909, 2*474326); } // F.0B - F.F0: Set Tempo (assumes LPB=4) if (param > 0x0A) { command = CMD_TEMPO; if (param < 0x21) param = 0x21; if (param > 240) param = 240; } } else switch(param) { // F.F1: Retrig 2x case 0xF1: command = CMD_MODCMDEX; param = 0x93; break; // F.F2: Note Delay 2x case 0xF2: command = CMD_MODCMDEX; param = 0xD3; break; // F.F3: Retrig 3x case 0xF3: command = CMD_MODCMDEX; param = 0x92; break; // F.F4: Note Delay 1/3 case 0xF4: command = CMD_MODCMDEX; param = 0xD2; break; // F.F5: Note Delay 2/3 case 0xF5: command = CMD_MODCMDEX; param = 0xD4; break; // F.F8: Filter Off case 0xF8: command = CMD_MODCMDEX; param = 0x00; break; // F.F9: Filter On case 0xF9: command = CMD_MODCMDEX; param = 0x01; break; // F.FD: Very fast tone-portamento case 0xFD: command = CMD_TONEPORTAMENTO; param = 0xFF; break; // F.FE: End Song case 0xFE: command = CMD_SPEED; param = 0; break; // F.FF: Note Cut case 0xFF: command = CMD_MODCMDEX; param = 0xC0; break; default: #ifdef MED_LOG Log("Unknown Fxx command: cmd=0x%02X param=0x%02X\n", command, param); #endif param = command = 0; } break; // 11.0x: Fine Slide Up case 0x11: command = CMD_MODCMDEX; if (param > 0x0F) param = 0x0F; param |= 0x10; break; // 12.0x: Fine Slide Down case 0x12: command = CMD_MODCMDEX; if (param > 0x0F) param = 0x0F; param |= 0x20; break; // 14.xx: Vibrato case 0x14: command = CMD_VIBRATO; break; // 15.xx: FineTune case 0x15: command = CMD_MODCMDEX; param &= 0x0F; param |= 0x50; break; // 16.xx: Pattern Loop case 0x16: command = CMD_MODCMDEX; if (param > 0x0F) param = 0x0F; param |= 0x60; break; // 18.xx: Note Cut case 0x18: command = CMD_MODCMDEX; if (param > 0x0F) param = 0x0F; param |= 0xC0; break; // 19.xx: Sample Offset case 0x19: command = CMD_OFFSET; break; // 1A.0x: Fine Volume Up case 0x1A: command = CMD_MODCMDEX; if (param > 0x0F) param = 0x0F; param |= 0xA0; break; // 1B.0x: Fine Volume Down case 0x1B: command = CMD_MODCMDEX; if (param > 0x0F) param = 0x0F; param |= 0xB0; break; // 1D.xx: Pattern Break case 0x1D: command = CMD_PATTERNBREAK; break; // 1E.0x: Pattern Delay case 0x1E: command = CMD_MODCMDEX; if (param > 0x0F) param = 0x0F; param |= 0xE0; break; // 1F.xy: Retrig case 0x1F: command = CMD_RETRIG; param &= 0x0F; break; // 2E.xx: set panning case 0x2E: command = CMD_MODCMDEX; param = ((param + 0x10) & 0xFF) >> 1; if (param > 0x0F) param = 0x0F; param |= 0x80; break; default: #ifdef MED_LOG // 0x2E ? Log("Unknown command: cmd=0x%02X param=0x%02X\n", command, param); #endif command = param = 0; } p->command = command; p->param = param; } BOOL CSoundFile::ReadMed(const BYTE *lpStream, DWORD dwMemLength) //--------------------------------------------------------------- { const MEDMODULEHEADER *pmmh; const MMD0SONGHEADER *pmsh; const MMD2SONGHEADER *pmsh2; const MMD0EXP *pmex; DWORD dwBlockArr, dwSmplArr, dwExpData, wNumBlocks; LPDWORD pdwTable; CHAR version; UINT deftempo; int playtransp = 0; if ((!lpStream) || (dwMemLength < 0x200)) return FALSE; pmmh = (MEDMODULEHEADER *)lpStream; if (((pmmh->id & 0x00FFFFFF) != 0x444D4D) || (!pmmh->song)) return FALSE; // Check for 'MMDx' DWORD dwSong = bswapBE32(pmmh->song); if ((dwSong >= dwMemLength) || (dwSong + sizeof(MMD0SONGHEADER) >= dwMemLength)) return FALSE; version = (signed char)((pmmh->id >> 24) & 0xFF); if ((version < '0') || (version > '3')) return FALSE; #ifdef MED_LOG Log("\nLoading MMD%c module (flags=0x%02X)...\n", version, bswapBE32(pmmh->mmdflags)); Log(" modlen = %d\n", bswapBE32(pmmh->modlen)); Log(" song = 0x%08X\n", bswapBE32(pmmh->song)); Log(" psecnum = %d\n", bswapBE16(pmmh->psecnum)); Log(" pseq = %d\n", bswapBE16(pmmh->pseq)); Log(" blockarr = 0x%08X\n", bswapBE32(pmmh->blockarr)); Log(" mmdflags = 0x%08X\n", bswapBE32(pmmh->mmdflags)); Log(" smplarr = 0x%08X\n", bswapBE32(pmmh->smplarr)); Log(" reserved = 0x%08X\n", bswapBE32(pmmh->reserved)); Log(" expdata = 0x%08X\n", bswapBE32(pmmh->expdata)); Log(" reserved2= 0x%08X\n", bswapBE32(pmmh->reserved2)); Log(" pstate = %d\n", bswapBE16(pmmh->pstate)); Log(" pblock = %d\n", bswapBE16(pmmh->pblock)); Log(" pline = %d\n", bswapBE16(pmmh->pline)); Log(" pseqnum = %d\n", bswapBE16(pmmh->pseqnum)); Log(" actplayline=%d\n", bswapBE16(pmmh->actplayline)); Log(" counter = %d\n", pmmh->counter); Log(" extra_songs = %d\n", pmmh->extra_songs); Log("\n"); #endif m_nType = MOD_TYPE_MED; m_nSongPreAmp = 0x20; dwBlockArr = bswapBE32(pmmh->blockarr); dwSmplArr = bswapBE32(pmmh->smplarr); dwExpData = bswapBE32(pmmh->expdata); if ((dwExpData) && (dwExpData < dwMemLength - sizeof(MMD0EXP))) pmex = (MMD0EXP *)(lpStream+dwExpData); else pmex = NULL; pmsh = (MMD0SONGHEADER *)(lpStream + dwSong); pmsh2 = (MMD2SONGHEADER *)pmsh; #ifdef MED_LOG if (version < '2') { Log("MMD0 Header:\n"); Log(" numblocks = %d\n", bswapBE16(pmsh->numblocks)); Log(" songlen = %d\n", bswapBE16(pmsh->songlen)); Log(" playseq = "); for (UINT idbg1=0; idbg1<16; idbg1++) Log("%2d, ", pmsh->playseq[idbg1]); Log("...\n"); Log(" deftempo = 0x%04X\n", bswapBE16(pmsh->deftempo)); Log(" playtransp = %d\n", (signed char)pmsh->playtransp); Log(" flags(1,2) = 0x%02X, 0x%02X\n", pmsh->flags, pmsh->flags2); Log(" tempo2 = %d\n", pmsh->tempo2); Log(" trkvol = "); for (UINT idbg2=0; idbg2<16; idbg2++) Log("0x%02X, ", pmsh->trkvol[idbg2]); Log("...\n"); Log(" mastervol = 0x%02X\n", pmsh->mastervol); Log(" numsamples = %d\n", pmsh->numsamples); } else { Log("MMD2 Header:\n"); Log(" numblocks = %d\n", bswapBE16(pmsh2->numblocks)); Log(" numsections= %d\n", bswapBE16(pmsh2->numsections)); Log(" playseqptr = 0x%04X\n", bswapBE32(pmsh2->playseqtable)); Log(" sectionptr = 0x%04X\n", bswapBE32(pmsh2->sectiontable)); Log(" trackvols = 0x%04X\n", bswapBE32(pmsh2->trackvols)); Log(" numtracks = %d\n", bswapBE16(pmsh2->numtracks)); Log(" numpseqs = %d\n", bswapBE16(pmsh2->numpseqs)); Log(" trackpans = 0x%04X\n", bswapBE32(pmsh2->trackpans)); Log(" flags3 = 0x%08X\n", bswapBE32(pmsh2->flags3)); Log(" voladj = %d\n", bswapBE16(pmsh2->voladj)); Log(" channels = %d\n", bswapBE16(pmsh2->channels)); Log(" echotype = %d\n", pmsh2->mix_echotype); Log(" echodepth = %d\n", pmsh2->mix_echodepth); Log(" echolen = %d\n", bswapBE16(pmsh2->mix_echolen)); Log(" stereosep = %d\n", (signed char)pmsh2->mix_stereosep); Log(" deftempo = 0x%04X\n", bswapBE16(pmsh2->deftempo)); Log(" playtransp = %d\n", (signed char)pmsh2->playtransp); Log(" flags(1,2) = 0x%02X, 0x%02X\n", pmsh2->flags, pmsh2->flags2); Log(" tempo2 = %d\n", pmsh2->tempo2); Log(" mastervol = 0x%02X\n", pmsh2->mastervol); Log(" numsamples = %d\n", pmsh->numsamples); } Log("\n"); #endif wNumBlocks = bswapBE16(pmsh->numblocks); m_nChannels = 4; m_nSamples = pmsh->numsamples; if (m_nSamples > 63) m_nSamples = 63; // Tempo m_nDefaultTempo = 125; deftempo = bswapBE16(pmsh->deftempo); if (!deftempo) deftempo = 125; if (pmsh->flags2 & MMD_FLAG2_BPM) { UINT tempo_tpl = (pmsh->flags2 & MMD_FLAG2_BMASK) + 1; if (!tempo_tpl) tempo_tpl = 4; deftempo *= tempo_tpl; deftempo /= 4; #ifdef MED_LOG Log("newtempo: %3d bpm (bpm=%3d lpb=%2d)\n", deftempo, bswapBE16(pmsh->deftempo), (pmsh->flags2 & MMD_FLAG2_BMASK)+1); #endif } else { if (pmsh->flags & MMD_FLAG_8CHANNEL && deftempo > 0 && deftempo <= 10) { deftempo = bpmvals[deftempo-1]; } else { deftempo = _muldiv(deftempo, 5*715909, 2*474326); } #ifdef MED_LOG Log("oldtempo: %3d bpm (bpm=%3d)\n", deftempo, bswapBE16(pmsh->deftempo)); #endif } // Speed m_nDefaultSpeed = pmsh->tempo2; if (!m_nDefaultSpeed) m_nDefaultSpeed = 6; if (deftempo < 0x21) deftempo = 0x21; if (deftempo > 255) { while ((m_nDefaultSpeed > 3) && (deftempo > 260)) { deftempo = (deftempo * (m_nDefaultSpeed - 1)) / m_nDefaultSpeed; m_nDefaultSpeed--; } if (deftempo > 255) deftempo = 255; } m_nDefaultTempo = deftempo; // Reading Samples for (UINT iSHdr=0; iSHdr<m_nSamples; iSHdr++) { MODINSTRUMENT *pins = &Ins[iSHdr+1]; pins->nLoopStart = bswapBE16(pmsh->sample[iSHdr].rep) << 1; pins->nLoopEnd = pins->nLoopStart + (bswapBE16(pmsh->sample[iSHdr].replen) << 1); pins->nVolume = (pmsh->sample[iSHdr].svol << 2); pins->nGlobalVol = 64; if (pins->nVolume > 256) pins->nVolume = 256; pins->RelativeTone = -12 * pmsh->sample[iSHdr].strans; pins->nPan = 128; if (pins->nLoopEnd) pins->uFlags |= CHN_LOOP; } // Common Flags if (!(pmsh->flags & 0x20)) m_dwSongFlags |= SONG_FASTVOLSLIDES; // Reading play sequence if (version < '2') { UINT nbo = pmsh->songlen >> 8; if (nbo >= MAX_ORDERS) nbo = MAX_ORDERS-1; if (!nbo) nbo = 1; memcpy(Order, pmsh->playseq, nbo); playtransp = pmsh->playtransp; } else { UINT nOrders, nSections; UINT nTrks = bswapBE16(pmsh2->numtracks); if ((nTrks >= 4) && (nTrks <= 32)) m_nChannels = nTrks; DWORD playseqtable = bswapBE32(pmsh2->playseqtable); UINT numplayseqs = bswapBE16(pmsh2->numpseqs); if (!numplayseqs) numplayseqs = 1; nOrders = 0; nSections = bswapBE16(pmsh2->numsections); DWORD sectiontable = bswapBE32(pmsh2->sectiontable); if ((!nSections) || (!sectiontable) || (sectiontable >= dwMemLength-2)) nSections = 1; nOrders = 0; for (UINT iSection=0; iSection<nSections; iSection++) { UINT nplayseq = 0; if ((sectiontable) && (sectiontable < dwMemLength-2)) { nplayseq = lpStream[sectiontable+1]; sectiontable += 2; // WORDs } else { nSections = 0; } UINT pseq = 0; if ((playseqtable) && (playseqtable < dwMemLength) && (nplayseq*4 < dwMemLength - playseqtable)) { pseq = bswapBE32(((LPDWORD)(lpStream+playseqtable))[nplayseq]); } if ((pseq) && dwMemLength > sizeof(MMD2PLAYSEQ) && (pseq < dwMemLength - sizeof(MMD2PLAYSEQ))) { const MMD2PLAYSEQ *pmps = (MMD2PLAYSEQ *)(lpStream + pseq); if (!m_szNames[0][0]) memcpy(m_szNames[0], pmps->name, 31); UINT n = bswapBE16(pmps->length); if (n < (dwMemLength - (pseq + sizeof(*pmps)) + sizeof(pmps->seq)) / sizeof(pmps->seq[0])) { for (UINT i=0; i<n; i++) { UINT seqval = pmps->seq[i] >> 8; if ((seqval < wNumBlocks) && (nOrders < MAX_ORDERS-1)) { Order[nOrders++] = seqval; } } } } } playtransp = pmsh2->playtransp; while (nOrders < MAX_ORDERS) Order[nOrders++] = 0xFF; } // Reading Expansion structure if (pmex) { // Channel Split if ((m_nChannels == 4) && (pmsh->flags & MMD_FLAG_8CHANNEL)) { for (UINT i8ch=0; i8ch<4; i8ch++) { if (pmex->channelsplit[i8ch]) m_nChannels++; } } // Song Comments uint32_t annotxt = bswapBE32(pmex->annotxt); uint32_t annolen = bswapBE32(pmex->annolen); if ((annotxt) && (annolen) && (annotxt + annolen > annotxt) // overflow checks. && (annotxt+annolen <= dwMemLength)) { m_lpszSongComments = new char[annolen+1]; memcpy(m_lpszSongComments, lpStream+annotxt, annolen); m_lpszSongComments[annolen] = 0; } // Song Name uint32_t songname = bswapBE32(pmex->songname); uint32_t songnamelen = bswapBE32(pmex->songnamelen); if ((songname) && (songnamelen) && (songname+songnamelen > songname) && (songname+songnamelen <= dwMemLength)) { if (songnamelen > 31) songnamelen = 31; memcpy(m_szNames[0], lpStream+songname, songnamelen); m_szNames[0][31] = '\0'; } // Sample Names DWORD smpinfoex = bswapBE32(pmex->iinfo); if (smpinfoex) { DWORD iinfoptr = bswapBE32(pmex->iinfo); UINT ientries = bswapBE16(pmex->i_ext_entries); UINT ientrysz = bswapBE16(pmex->i_ext_entrsz); if ((iinfoptr) && (ientrysz < 256) && (ientries*ientrysz < dwMemLength) && (iinfoptr < dwMemLength - (ientries*ientrysz))) { LPCSTR psznames = (LPCSTR)(lpStream + iinfoptr); UINT maxnamelen = ientrysz; // copy a max of 32 bytes. if (maxnamelen > 32) maxnamelen = 32; for (UINT i=0; i<ientries; i++) if (i < m_nSamples) { lstrcpyn(m_szNames[i+1], psznames + i*ientrysz, maxnamelen); m_szNames[i+1][31] = '\0'; } } } // Track Names DWORD trackinfo_ofs = bswapBE32(pmex->trackinfo_ofs); if ((trackinfo_ofs) && (trackinfo_ofs < dwMemLength) && (m_nChannels * 4 < dwMemLength - trackinfo_ofs)) { DWORD *ptrktags = (DWORD *)(lpStream + trackinfo_ofs); for (UINT i=0; i<m_nChannels; i++) { DWORD trknameofs = 0, trknamelen = 0; DWORD trktagofs = bswapBE32(ptrktags[i]); if (trktagofs) { while (trktagofs < dwMemLength - 8) { DWORD ntag = bswapBE32(*(DWORD *)(lpStream + trktagofs)); if (ntag == MMDTAG_END) break; DWORD tagdata = bswapBE32(*(DWORD *)(lpStream + trktagofs + 4)); switch(ntag) { case MMDTAG_TRK_NAMELEN: trknamelen = tagdata; break; case MMDTAG_TRK_NAME: trknameofs = tagdata; break; } trktagofs += 8; } if (trknamelen > MAX_CHANNELNAME) trknamelen = MAX_CHANNELNAME; if ((trknameofs) && (trknamelen < dwMemLength) && (trknameofs < dwMemLength - trknamelen)) { lstrcpyn(ChnSettings[i].szName, (LPCSTR)(lpStream+trknameofs), MAX_CHANNELNAME); ChnSettings[i].szName[MAX_CHANNELNAME-1] = '\0'; } } } } } // Reading samples if (dwSmplArr > dwMemLength - 4*m_nSamples) return TRUE; pdwTable = (LPDWORD)(lpStream + dwSmplArr); for (UINT iSmp=0; iSmp<m_nSamples; iSmp++) if (pdwTable[iSmp]) { UINT dwPos = bswapBE32(pdwTable[iSmp]); if ((dwPos >= dwMemLength) || (dwPos + sizeof(MMDSAMPLEHEADER) >= dwMemLength)) continue; MMDSAMPLEHEADER *psdh = (MMDSAMPLEHEADER *)(lpStream + dwPos); UINT len = bswapBE32(psdh->length); #ifdef MED_LOG Log("SampleData %d: stype=0x%02X len=%d\n", iSmp, bswapBE16(psdh->type), len); #endif if ((len > MAX_SAMPLE_LENGTH) || (dwPos + len + 6 > dwMemLength)) len = 0; UINT flags = RS_PCM8S, stype = bswapBE16(psdh->type); LPSTR psdata = (LPSTR)(lpStream + dwPos + 6); if (stype & 0x80) { psdata += (stype & 0x20) ? 14 : 6; } else { if (stype & 0x10) { Ins[iSmp+1].uFlags |= CHN_16BIT; len /= 2; flags = (stype & 0x20) ? RS_STPCM16M : RS_PCM16M; } else { flags = (stype & 0x20) ? RS_STPCM8S : RS_PCM8S; } if (stype & 0x20) len /= 2; } Ins[iSmp+1].nLength = len; ReadSample(&Ins[iSmp+1], flags, psdata, dwMemLength - dwPos - 6); } // Reading patterns (blocks) if (wNumBlocks > MAX_PATTERNS) wNumBlocks = MAX_PATTERNS; if ((!dwBlockArr) || (dwMemLength < 4*wNumBlocks) || (dwBlockArr > dwMemLength - 4*wNumBlocks)) return TRUE; pdwTable = (LPDWORD)(lpStream + dwBlockArr); playtransp += (version == '3') ? 24 : 48; for (UINT iBlk=0; iBlk<wNumBlocks; iBlk++) { UINT dwPos = bswapBE32(pdwTable[iBlk]); if ((!dwPos) || (dwPos >= dwMemLength) || (dwPos >= dwMemLength - 8)) continue; UINT lines = 64, tracks = 4; if (version == '0') { const MMD0BLOCK *pmb = (const MMD0BLOCK *)(lpStream + dwPos); lines = pmb->lines + 1; tracks = pmb->numtracks; if (!tracks) tracks = m_nChannels; if ((Patterns[iBlk] = AllocatePattern(lines, m_nChannels)) == NULL) continue; PatternSize[iBlk] = lines; MODCOMMAND *p = Patterns[iBlk]; LPBYTE s = (LPBYTE)(lpStream + dwPos + 2); UINT maxlen = tracks*lines*3; if (maxlen + dwPos > dwMemLength - 2) break; for (UINT y=0; y<lines; y++) { for (UINT x=0; x<tracks; x++, s+=3) if (x < m_nChannels) { BYTE note = s[0] & 0x3F; BYTE instr = s[1] >> 4; if (s[0] & 0x80) instr |= 0x10; if (s[0] & 0x40) instr |= 0x20; if ((note) && (note <= 132)) p->note = note + playtransp; p->instr = instr; p->command = s[1] & 0x0F; p->param = s[2]; // if (!iBlk) Log("%02X.%02X.%02X | ", s[0], s[1], s[2]); MedConvert(p, pmsh); p++; } //if (!iBlk) Log("\n"); } } else { const MMD1BLOCK *pmb = (MMD1BLOCK *)(lpStream + dwPos); #ifdef MED_LOG Log("MMD1BLOCK: lines=%2d, tracks=%2d, offset=0x%04X\n", bswapBE16(pmb->lines), bswapBE16(pmb->numtracks), bswapBE32(pmb->info)); #endif const MMD1BLOCKINFO *pbi = NULL; BYTE *pcmdext = NULL; lines = (pmb->lines >> 8) + 1; tracks = pmb->numtracks >> 8; if (!tracks) tracks = m_nChannels; if ((Patterns[iBlk] = AllocatePattern(lines, m_nChannels)) == NULL) continue; PatternSize[iBlk] = (WORD)lines; DWORD dwBlockInfo = bswapBE32(pmb->info); if ((dwBlockInfo) && (dwBlockInfo < dwMemLength - sizeof(MMD1BLOCKINFO))) { pbi = (MMD1BLOCKINFO *)(lpStream + dwBlockInfo); #ifdef MED_LOG Log(" BLOCKINFO: blockname=0x%04X namelen=%d pagetable=0x%04X &cmdexttable=0x%04X\n", bswapBE32(pbi->blockname), bswapBE32(pbi->blocknamelen), bswapBE32(pbi->pagetable), bswapBE32(pbi->cmdexttable)); #endif if ((pbi->blockname) && (pbi->blocknamelen)) { DWORD nameofs = bswapBE32(pbi->blockname); UINT namelen = bswapBE32(pbi->blocknamelen); if ((nameofs < dwMemLength) && (namelen < dwMemLength + nameofs)) { SetPatternName(iBlk, (LPCSTR)(lpStream+nameofs)); } } if (pbi->cmdexttable) { DWORD cmdexttable = bswapBE32(pbi->cmdexttable); if (cmdexttable < dwMemLength - 4) { cmdexttable = bswapBE32(*(DWORD *)(lpStream + cmdexttable)); if ((cmdexttable) && (cmdexttable <= dwMemLength - lines*tracks)) { pcmdext = (BYTE *)(lpStream + cmdexttable); } } } } MODCOMMAND *p = Patterns[iBlk]; LPBYTE s = (LPBYTE)(lpStream + dwPos + 8); UINT maxlen = tracks*lines*4; if (maxlen + dwPos > dwMemLength - 8) break; for (UINT y=0; y<lines; y++) { for (UINT x=0; x<tracks; x++, s+=4) if (x < m_nChannels) { BYTE note = s[0]; if ((note) && (note <= 132)) { int rnote = note + playtransp; if (rnote < 1) rnote = 1; if (rnote > NOTE_MAX) rnote = NOTE_MAX; p->note = (BYTE)rnote; } p->instr = s[1]; p->command = s[2]; p->param = s[3]; if (pcmdext) p->vol = pcmdext[x]; MedConvert(p, pmsh); p++; } if (pcmdext) pcmdext += tracks; } } } // Setup channel pan positions for (UINT iCh=0; iCh<m_nChannels; iCh++) { ChnSettings[iCh].nPan = (((iCh&3) == 1) || ((iCh&3) == 2)) ? 0xC0 : 0x40; ChnSettings[iCh].nVolume = 64; } return TRUE; }
[ "mozeal@gmail.com" ]
mozeal@gmail.com
c76998a159a346f65e66c6121624b8428974dd32
45a3a80e5cdd62d3743d8ff0b126ed7caffbb318
/DS Assignments/DS assignment 1/Queue/Queue.cpp
a6dcd06c4a76e2f20b9b4532f60a23d624bea063
[]
no_license
aditya4389/ncrwork
97ca69b6c199361c97c205c46ecaf60ff1c35b39
6b955dbfda726a0464e54995322cd98abdec408a
refs/heads/master
2020-04-20T06:19:11.167159
2019-03-18T04:50:15
2019-03-18T04:50:15
168,679,683
0
0
null
null
null
null
UTF-8
C++
false
false
1,415
cpp
// Queue.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; class Queue { int data[50], n; int rear, front; public: Queue() { cout << "Enter Size: "; cin >> n; for (int i = 0; i < n; i++) data[i] = 0; rear = -1; front = -1; } void Enque(); void Deque(); void display(); }; void Queue::Enque() { try { if (front == n - 1) throw front; else { cout << "Enter Data: " << endl; int d; cin >> d; data[++front] = d; rear = 0; } } catch (int a) { cout << "Queue OverFlow\n"; } } void Queue::Deque() { try { if ((rear == -1 && front == -1) || (rear - 1 == front)) throw rear; else { cout << "Dequed Data is: " << data[rear] << "\n"; rear++; } } catch (int a) { cout << "Queue UnderFlow\n"; } } void Queue::display() { try { if ((rear == -1 && front == -1) || rear - 1 == front) throw rear; else { for (int i = front; i != rear; i--) cout << data[i] << " "; cout << "\n"; } } catch (int a) { cout << "Queue Empty\n"; } } int main() { Queue q; int flag = 0; while (flag != 1) { cout << "1-Enque 2-Deque 3-display 4-exit\n"; int c; cin >> c; switch (c) { case 1: q.Enque(); break; case 2: q.Deque(); break; case 3: q.display(); break; case 4: flag = 1; break; } } system("pause"); }
[ "37670392+aditya4389@users.noreply.github.com" ]
37670392+aditya4389@users.noreply.github.com
5c752947746ecf115be06893c917a18fa8919e8b
e95adb59feacfe95904c3a8e90a4159860b6c26a
/build/Android/Preview/outsideTheBox/app/src/main/include/Android.android.view.ActionModeDLRCallback.h
467491b501fa5e83c8114583d648286f325079d7
[]
no_license
deliloka/bethebox
837dff20c1ff55db631db1e0f6cb51d935497e91
f9bc71b8593dd54b8aaf86bc0a654d233432c362
refs/heads/master
2021-01-21T08:20:42.970891
2016-02-19T10:00:37
2016-02-19T10:00:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,962
h
// This file was generated based on '/usr/local/share/uno/Packages/Android/0.23.1/Android/android/view/$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Android.Base.Wrappers.IJWrapper.h> #include <Uno.Object.h> namespace g{namespace Android{namespace android{namespace view{struct ActionMode;}}}} namespace g{ namespace Android{ namespace android{ namespace view{ // public abstract extern interface ActionModeDLRCallback :26624 // { uInterfaceType* ActionModeDLRCallback_typeof(); struct ActionModeDLRCallback { void(*fp_onActionItemClicked)(uObject*, ::g::Android::android::view::ActionMode*, uObject*, bool*); void(*fp_onCreateActionMode)(uObject*, ::g::Android::android::view::ActionMode*, uObject*, bool*); void(*fp_onDestroyActionMode)(uObject*, ::g::Android::android::view::ActionMode*); void(*fp_onPrepareActionMode)(uObject*, ::g::Android::android::view::ActionMode*, uObject*, bool*); static bool onActionItemClicked(const uInterface& __this, ::g::Android::android::view::ActionMode* arg0, uObject* arg1) { bool __retval; return __this.VTable<ActionModeDLRCallback>()->fp_onActionItemClicked(__this, arg0, arg1, &__retval), __retval; } static bool onCreateActionMode(const uInterface& __this, ::g::Android::android::view::ActionMode* arg0, uObject* arg1) { bool __retval; return __this.VTable<ActionModeDLRCallback>()->fp_onCreateActionMode(__this, arg0, arg1, &__retval), __retval; } static void onDestroyActionMode(const uInterface& __this, ::g::Android::android::view::ActionMode* arg0) { __this.VTable<ActionModeDLRCallback>()->fp_onDestroyActionMode(__this, arg0); } static bool onPrepareActionMode(const uInterface& __this, ::g::Android::android::view::ActionMode* arg0, uObject* arg1) { bool __retval; return __this.VTable<ActionModeDLRCallback>()->fp_onPrepareActionMode(__this, arg0, arg1, &__retval), __retval; } }; // } }}}} // ::g::Android::android::view
[ "Havard.Halse@nrk.no" ]
Havard.Halse@nrk.no
6e56799a571be4baebb5e611831c457ca6a8f0dd
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/drivers/smartcrd/gempc430/smartcard.h
845500361f14bd31d3469af906d442a65fda9376
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
5,643
h
//------------------------------------------------------------------- // This is abstract class for generic device // Specific devices should use it as a parent device // Author: Sergey Ivanov // Log: // 08/11/99 - implemented //------------------------------------------------------------------- #ifndef __SMART_CARD__ #define __SMART_CARD__ #include "generic.h" #include "kernel.h" // // - IOCTL_SMARTCARD_VENDOR_IFD_EXCHANGE defines a specific IOCTL for the Gemplus // Reader to exchange data with the reader without control of the driver. // - IOCTL_SMARTCARD_VENDOR_GET_ATTRIBUTE defines a specific IOCTL for the Gemplus // Reader to gets vendor attributes. // - IOCTL_SMARTCARD_VENDOR_SET_ATTRIBUTE defines a specific IOCTL for the Gemplus // Reader to sets vendor attributes. // #define IOCTL_SMARTCARD_VENDOR_IFD_EXCHANGE CTL_CODE(FILE_DEVICE_SMARTCARD,2048,0,0) #define IOCTL_SMARTCARD_VENDOR_GET_ATTRIBUTE CTL_CODE(FILE_DEVICE_SMARTCARD,2049,0,0) #define IOCTL_SMARTCARD_VENDOR_SET_ATTRIBUTE CTL_CODE(FILE_DEVICE_SMARTCARD,2050,0,0) // 2051 is reserved for Gcr420 keyboard reader. #define IOCTL_SMARTCARD_VENDOR_SWITCH_SPEED CTL_CODE(FILE_DEVICE_SMARTCARD,2052,0,0) // // - SCARD_CLASS is a macro to know the class of a Tag. // #define SCARD_CLASS(Value) (ULONG) (((ULONG)(Value)) >> 16) // // - SCARD_ATTR_SPEC_BAUD_RATE is the Tag to acces at the value of the baud rate (PC/IFD). // - SCARD_ATTR_SPEC_CMD_TIMEOUT is the Tag to access at the value of the Cmd Timeout. // - SCARD_ATTR_SPEC_POWER_TIMEOUT is the Tag to access at the value of the Power // Timeout. // - SCARD_ATTR_SPEC_APDU_TIMEOUT is the Tag to access at the value of the APDU // Timeout. // #define SCARD_ATTR_SPEC_BAUD_RATE SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_DEFINED,0x0180) #define SCARD_ATTR_SPEC_CMD_TIMEOUT SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_DEFINED,0x0181) #define SCARD_ATTR_SPEC_POWER_TIMEOUT SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_DEFINED,0x0182) #define SCARD_ATTR_SPEC_APDU_TIMEOUT SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_DEFINED,0x0183) // // To give possibility for recognition of driver // #define SCARD_ATTR_MANUFACTURER_NAME SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_DEFINED,0x0190) #define SCARD_ATTR_ORIGINAL_FILENAME SCARD_ATTR_VALUE(SCARD_CLASS_VENDOR_DEFINED,0x0191) #define GBCLASS_OPEN_SESSION 0x3001 #define GBCLASS_CLOSE_SESSION 0x3002 #define GBCLASS_DRIVER_SCNAME 0x3003 #define GBCLASS_CONNECTION_TYPE 0x3004 #define IOCTL_OPEN_SESSION CTL_CODE(FILE_DEVICE_BUS_EXTENDER,GBCLASS_OPEN_SESSION,METHOD_BUFFERED,FILE_ANY_ACCESS) #define IOCTL_CLOSE_SESSION CTL_CODE(FILE_DEVICE_BUS_EXTENDER,GBCLASS_CLOSE_SESSION,METHOD_BUFFERED,FILE_ANY_ACCESS) #define IOCTL_DRIVER_SCNAME CTL_CODE(FILE_DEVICE_BUS_EXTENDER,GBCLASS_DRIVER_SCNAME,METHOD_BUFFERED,FILE_ANY_ACCESS) #define IOCTL_GET_CONNECTION_TYPE CTL_CODE(FILE_DEVICE_BUS_EXTENDER,GBCLASS_CONNECTION_TYPE,METHOD_BUFFERED,FILE_ANY_ACCESS) #define ATTR_MANUFACTURER_NAME "Gemplus" #define ATTR_ORIGINAL_FILENAME "GrClass.sys" #define ATTR_LENGTH 32 #define SC_IFD_DEFAULT_CLK_FREQUENCY 4000 #define SC_IFD_MAXIMUM_CLK_FREQUENCY 4000 #define SC_IFD_DEFAULT_DATA_RATE 10753 #define SC_IFD_MAXIMUM_DATA_RATE 125000 #define SC_IFD_MAXIMUM_IFSD 253// To correct problem with SMCLIB! #define SC_IFD_T0_MAXIMUM_LEX 256 #define SC_IFD_T0_MAXIMUM_LC 255 // PTS mode parameters #define PROTOCOL_MODE_DEFAULT 0 #define PROTOCOL_MODE_MANUALLY 1 static ULONG dataRatesSupported[] = { 10753, 14337, 15625, 17204, 20833, 21505, 28674, 31250, 34409, 41667, 43011, 57348, 62500, 83333, 86022, 114695, 125000 }; #define GRCLASS_DRIVER_NAME "GRClass" #define GRCLASS_VENDOR_NAME "Gemplus" #define GRCLASS_READER_TYPE "GemPC430" #define REQUEST_TO_NOTIFY_INSERTION 1 #define REQUEST_TO_NOTIFY_REMOVAL 2 #pragma LOCKEDCODE // Declare Smclib system callbacks... #ifdef __cplusplus extern "C"{ #endif NTSTATUS smartCard_Transmit(PSMARTCARD_EXTENSION SmartcardExtension); NTSTATUS smartCard_CancelTracking(IN PDEVICE_OBJECT DeviceObject,IN PIRP Irp); NTSTATUS smartCard_Tracking(PSMARTCARD_EXTENSION SmartcardExtension); NTSTATUS smartCard_VendorIoctl(PSMARTCARD_EXTENSION SmartcardExtension); NTSTATUS smartCard_Power(PSMARTCARD_EXTENSION SmartcardExtension); NTSTATUS smartCard_SetProtocol(PSMARTCARD_EXTENSION SmartcardExtension); #ifdef __cplusplus } #endif #pragma PAGEDCODE class CUSBReader;//TO CHANGE LATER... class CSmartCard { public: NTSTATUS m_Status; SAFE_DESTRUCTORS(); virtual VOID dispose(){self_delete();}; private: CUSBReader* reader; CDebug* debug; CMemory* memory; CLock* lock; CSystem* system; CIrp* irp; KEVENT evCanceled;// set when tracking is canceled... PIRP poolingIrp; UNICODE_STRING DosDeviceName;//Used only at Win9x public: KSPIN_LOCK CardLock; protected: virtual ~CSmartCard(); public: CSmartCard(); virtual CUSBReader* getReader() {return reader;};//TO CHANGE LATER... virtual BOOL smartCardConnect(CUSBReader* reader); virtual VOID smartCardDisconnect(); virtual BOOL smartCardStart(); virtual PKSPIN_LOCK getCardLock(){return &CardLock;}; virtual VOID completeCardTracking(); virtual VOID setPoolingIrp(PIRP Irp){poolingIrp = Irp;}; virtual PIRP getPoolingIrp(){return poolingIrp;}; virtual BOOLEAN CheckSpecificMode(BYTE* ATR, DWORD ATRLength); }; #endif
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
7ff0b3bd03fdb8b236f2317d56f83cee4cc1fcf4
ef80a4616a15ab64cceb64e7bfe8886e695c52b8
/third_party/blink/renderer/modules/xr/xr_webgl_layer.h
50fb226a7e6df9f5b4c3626157daa6bf8f81c18a
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
bobsmile/chromium
646377745bff0224df61d63dbeb9aa7b84fd380e
563ebbe80c8993978cee672c5da9c6ab4fca451b
refs/heads/master
2023-02-21T00:45:34.337364
2020-02-10T10:29:43
2020-02-10T10:29:43
239,488,818
1
0
BSD-3-Clause
2020-02-10T10:50:05
2020-02-10T10:50:04
null
UTF-8
C++
false
false
3,167
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_XR_XR_WEBGL_LAYER_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_XR_XR_WEBGL_LAYER_H_ #include "third_party/blink/renderer/bindings/modules/v8/v8_xr_webgl_layer_init.h" #include "third_party/blink/renderer/bindings/modules/v8/webgl_rendering_context_or_webgl2_rendering_context.h" #include "third_party/blink/renderer/modules/webgl/webgl2_rendering_context.h" #include "third_party/blink/renderer/modules/webgl/webgl_rendering_context.h" #include "third_party/blink/renderer/modules/xr/xr_view.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/graphics/gpu/xr_webgl_drawing_buffer.h" #include "third_party/blink/renderer/platform/wtf/ref_counted.h" namespace viz { class SingleReleaseCallback; } namespace blink { class ExceptionState; class HTMLCanvasElement; class WebGLFramebuffer; class WebGLRenderingContextBase; class XRSession; class XRViewport; class XRWebGLLayer final : public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: XRWebGLLayer(XRSession*, WebGLRenderingContextBase*, scoped_refptr<XRWebGLDrawingBuffer>, WebGLFramebuffer*, double framebuffer_scale, bool ignore_depth_values); ~XRWebGLLayer() override; static XRWebGLLayer* Create( XRSession*, const WebGLRenderingContextOrWebGL2RenderingContext&, const XRWebGLLayerInit*, ExceptionState&); XRSession* session() const { return session_; } WebGLRenderingContextBase* context() const { return webgl_context_; } WebGLFramebuffer* framebuffer() const { return framebuffer_; } uint32_t framebufferWidth() const; uint32_t framebufferHeight() const; bool antialias() const; bool ignoreDepthValues() const { return ignore_depth_values_; } XRViewport* getViewport(XRView*); static double getNativeFramebufferScaleFactor(XRSession* session); XRViewport* GetViewportForEye(XRView::XREye); void UpdateViewports(); HTMLCanvasElement* output_canvas() const; void OnFrameStart(const base::Optional<gpu::MailboxHolder>&); void OnFrameEnd(); void OnResize(); // Called from XRSession::OnFrame handler. Params are background texture // mailbox holder and its size respectively. void HandleBackgroundImage(const gpu::MailboxHolder&, const IntSize&) {} scoped_refptr<StaticBitmapImage> TransferToStaticBitmapImage(); void Trace(blink::Visitor*) override; private: const Member<XRSession> session_; Member<XRViewport> left_viewport_; Member<XRViewport> right_viewport_; Member<WebGLRenderingContextBase> webgl_context_; scoped_refptr<XRWebGLDrawingBuffer> drawing_buffer_; Member<WebGLFramebuffer> framebuffer_; double framebuffer_scale_ = 1.0; bool viewports_dirty_ = true; bool is_direct_draw_frame = false; bool ignore_depth_values_ = false; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_XR_XR_WEBGL_LAYER_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
3324063d3b36f64834021e5fee4dcb3ab087aea9
43aa2e04ab3e8d7aff6feba43a080285eb48ab26
/program7/Search_tree.h
3586958ab856f68b6144171dc1e747bad21920f8
[]
no_license
anfleene/362
1c84a6cc49ec42dd967002a31ec9ed640dec7af5
3e76aa73d64b053543e437c6377588c932be4ae8
refs/heads/master
2020-05-17T21:15:54.390908
2009-12-14T23:17:12
2009-12-14T23:17:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,372
h
/* *Name: Andrew Fleener *Date: 10/21/09 *Description: This is a search binary tree class, the only implimentation preformed was max_value */ #include "Binary_tree.h" //Search_tree class interface template <class Entry> class Search_tree: public Binary_tree<Entry> { public: Search_tree(); //constructor //postcondition: empty tree has been created Error_code insert(const Entry &new_data); /* Post:: If a an entry with a key matching that of new_data already belongs to the Search_tree, a code of duplicate_error is returned. Otherwise, the entry new_data is inserted into the tree in such a way that the properties of a binary search tree are preserved. and a code of success is returned. Uses: recursive function search_and_insert */ Error_code remove(const Entry &old_data); /* Post: If a Entry with a key matching that of target belongs to the Search_tree, a code of success is returned and the corresponding node is removed from the tree. Otherwise, a code of not_present is returned. Uses: recursive function search_and_destroy */ Error_code tree_search(Entry &target) const; /* Post: If there is an entry in the tree whose key matches that in target, the parameter target is replaced by the corresponding Entry from the tree and a code of success is returned. Otherwise a code of not_present is returned. Uses: recursive function search_for_node */ Entry Max_value() const; //Post: the maximum value stored in the BST has been returned //Uses function recursive_max protected: Error_code remove_root(Binary_node<Entry> *&sub_root); /* Pre: sub_root is either NULL or points to a subtree of the Search_tree. Post: If sub_root is NULL, a code of not_present is returned. Otherwise, the root of the subtree is removed in such a way that the properties of a binary search tree are preserved. The parameter sub_root is reset as the root of the modified subtree, and success is returned. */ private: //auxiliary function prototypes Error_code search_and_insert( Binary_node<Entry> *&sub_root, const Entry &new_data); /* Pre: sub_root is either NULL or points to a subtree of a Search_tree Post: If the key of target is not in the subtree, it is inserted in the proper spot and a value of success is returned. Otherwise the key is already in the tree and a value of duplicate_error is returned. */ Error_code search_and_destroy( Binary_node<Entry>* &sub_root, const Entry &target); /* Pre: sub_root is either NULL or points to a subtree of the Search_tree. Post: If the key of target is not in the subtree, a code of not_present is returned. Otherwise, a code of success is returned and the subtree node containing target has been removed in such a way that the properties of a binary search tree have been preserved. Uses: Functions search_and_destroy recursively and remove_root */ Binary_node<Entry>* search_for_node( Binary_node<Entry>* sub_root, const Entry &target) const; /* Pre: sub_root is either NULL or points to a subtree of a Search_tree Post: If the key of target is not in the subtree, a result of NULL is returned. Otherwise, a pointer to the subtree node containing the target is returned. */ Entry recursive_max(Binary_node<Entry>* sub_root) const; //Pre: sub_root is NULL or points to a subtree //Post: returns the maximum valued node in the subtree }; template <class Entry> Search_tree<Entry>::Search_tree():Binary_tree<Entry>(){} //Bits and pieces of useful code for Search trees template <class Entry> Binary_node<Entry> *Search_tree<Entry>::search_for_node( Binary_node<Entry>* sub_root, const Entry &target) const { if (sub_root == NULL || sub_root->data == target) return sub_root; else if (sub_root->data < target) return search_for_node(sub_root->right, target); else return search_for_node(sub_root->left, target); } template <class Entry> Error_code Search_tree<Entry>::tree_search(Entry &target) const /* Post: If there is an entry in the tree whose key matches that in target, the parameter target is replaced by the corresponding entry from the tree and a code of success is returned. Otherwise a code of not_present is returned. Uses: function search_for_node */ { Error_code result = success; Binary_node<Entry> *found = search_for_node(this->root, target); if (found == NULL) result = not_present; else target = found->data; return result; } template <class Entry> Error_code Search_tree<Entry>::insert(const Entry &new_data) { return search_and_insert(this->root, new_data); } template <class Entry> Error_code Search_tree<Entry>::search_and_insert( Binary_node<Entry> *&sub_root, const Entry &new_data) { if (sub_root == NULL) { sub_root = new Binary_node<Entry>(new_data); return success; } else if (new_data < sub_root->data) return search_and_insert(sub_root->left, new_data); else if (new_data > sub_root->data) return search_and_insert(sub_root->right, new_data); else return duplicate_error; } template <class Entry> Error_code Search_tree<Entry>::remove_root(Binary_node<Entry> *&sub_root) /* Pre: sub_root is either NULL or points to a subtree of the Search_tree. Post: If sub_root is NULL, a code of not_present is returned. Otherwise, the root of the subtree is removed in such a way that the properties of a binary search tree are preserved. The parameter sub_root is reset as the root of the modified subtree, and success is returned. */ { if (sub_root == NULL) return not_present; Binary_node<Entry> *to_delete = sub_root; // Remember node to delete at end. if (sub_root->right == NULL) sub_root = sub_root->left; else if (sub_root->left == NULL) sub_root = sub_root->right; else { // Neither subtree is empty. to_delete = sub_root->left; // Move left to find predecessor. Binary_node<Entry> *parent = sub_root; // parent of to_delete while (to_delete->right != NULL) { // to_delete is not the predecessor. parent = to_delete; to_delete = to_delete->right; } sub_root->data = to_delete->data; // Move from to_delete to root. if (parent == sub_root) sub_root->left = to_delete->left; else parent->right = to_delete->left; } delete to_delete; // Remove to_delete from tree. return success; } template <class Entry> Error_code Search_tree<Entry>::remove(const Entry &target) /* Post: If a Entry with a key matching that of target belongs to the Search_tree, a code of success is returned and the corresponding node is removed from the tree. Otherwise, a code of not_present is returned. Uses: Function search_and_destroy */ { return search_and_destroy(this->root, target); } template <class Entry> Error_code Search_tree<Entry>::search_and_destroy( Binary_node<Entry>* &sub_root, const Entry &target) /* Pre: sub_root is either NULL or points to a subtree of the Search_tree. Post: If the key of target is not in the subtree, a code of not_present is returned. Otherwise, a code of success is returned and the subtree node containing target has been removed in such a way that the properties of a binary search tree have been preserved. Uses: Functions search_and_destroy recursively and remove_root */ { if (sub_root == NULL || sub_root->data == target) return remove_root(sub_root); else if (target < sub_root->data) return search_and_destroy(sub_root->left, target); else return search_and_destroy(sub_root->right, target); } //This method returns the max value in the search tree by calling recursive max template <class Entry> Entry Search_tree<Entry>::Max_value() const{ return recursive_max(this->root); } //this method traverses the tree to the farthest right node and returns that value template <class Entry> Entry Search_tree<Entry>::recursive_max(Binary_node<Entry>* sub_root) const{ if(sub_root->right == NULL){ return sub_root->data; }else{ recursive_max(sub_root->right); } }
[ "anfleene@iupui.edu" ]
anfleene@iupui.edu
5ae59c3b9e74acf0bf75eaaa69dc29a91549169c
d737fa49e2a7af29bdbe5a892bce2bc7807a567c
/firmware/robot/DisplayWrapper.cpp
0d75873dde0eb0347ab20dece82f8c0d7e7dd1e2
[ "MIT" ]
permissive
TG-Techie/CASPER
ec47dfbfd6c3a668739ff4d707572e0b853518b4
2575d3d35e7dbbd7f78110864e659e582c6f3c2e
refs/heads/master
2020-12-19T12:43:53.825964
2020-01-23T17:24:04
2020-01-23T17:24:04
235,736,872
0
1
MIT
2020-01-23T17:09:19
2020-01-23T06:29:10
Python
UTF-8
C++
false
false
806
cpp
#include "Arduino.h" //Standard arduino library #include "DisplayWrapper.h" //The header file for this class DisplayWrapper::DisplayWrapper(){} void DisplayWrapper::initialize(){} String DisplayWrapper::clearErrors(){return "Not implemented yet";} String DisplayWrapper::getLastError(){return "Not implemented yet";} String DisplayWrapper::getErrorCount(){return "Not implemented yet";} String DisplayWrapper::clear(){return "Not implemented yet";} String DisplayWrapper::turnOn(){return "Not implemented yet";} String DisplayWrapper::turnOff(){return "Not implemented yet";} String DisplayWrapper::getState(){return "Not implemented yet";}; String DisplayWrapper::getText(int line){return "Not implemented yet";} String DisplayWrapper::setText(int lint, String text){return "Not implemented yet";}
[ "jparadie@gmail.com" ]
jparadie@gmail.com
076fceba1bfd20169025027b8ef53e1f2b011d7d
3a0af4633b004defc3d86537a02ada5ad632b3a4
/hello.cpp
ccbc8afb62e486d6810f6d7969790500e4bc315f
[ "MIT" ]
permissive
dpkbaranwal/testcpprepository
9e0fa4319fbc8e76a6f3d98a3bb9030a18739d1c
0881c08dda3b0b48ce55b0d693b1bed253699e46
refs/heads/master
2020-04-05T17:47:54.604355
2018-11-11T12:22:35
2018-11-11T12:22:35
157,076,038
0
0
null
null
null
null
UTF-8
C++
false
false
97
cpp
#include <iostream> int main() { std::cout << "Hello World" << std:: endl; return 0; }
[ "dpk_baranwal@ymail.com" ]
dpk_baranwal@ymail.com
79a76be18f1c85ff206df4156d4abff55940fbb6
64eef6eac297ff7c47b93980b8f3fa1eef77a2ab
/XDU C语言实验课/实验2/实验题目5.cpp
9effb513fce8349f9fe52a36309905a98881b30e
[]
no_license
BBBBchan/C_CPP_ACM
51bf78825285a0a9700a929c97e2a0cb3ba506a8
d23b6688067dd8f1ad7504072bffd439a985c6b0
refs/heads/master
2021-06-02T19:26:04.765720
2020-08-04T06:55:04
2020-08-04T06:55:04
112,023,061
2
0
null
null
null
null
UTF-8
C++
false
false
200
cpp
#include <stdio.h> int main() { int m,n,p,q,t,times; scanf("%d %d",&m,&n); p = m; q = n; while(n != 0){ t = n; n = m % n; m = t; } times = p*q/m; printf("%d %d",m,times); return 0; }
[ "sbysbysby123@gmail.com" ]
sbysbysby123@gmail.com
d8ab84eddf0626ecc9eeae5c3ad36ba80c298ae7
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14142/function14142_schedule_5/function14142_schedule_5_wrapper.cpp
265431f49025f5bd8a3620ad8a396af0b1cf9199
[]
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
852
cpp
#include "Halide.h" #include "function14142_schedule_5_wrapper.h" #include "tiramisu/utils.h" #include <cstdlib> #include <iostream> #include <time.h> #include <fstream> #include <chrono> #define MAX_RAND 200 int main(int, char **){Halide::Buffer<int32_t> buf0(16384, 4096); init_buffer(buf0, (int32_t)0); auto t1 = std::chrono::high_resolution_clock::now(); function14142_schedule_5(buf0.raw_buffer()); auto t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = t2 - t1; std::ofstream exec_times_file; exec_times_file.open("../data/programs/function14142/function14142_schedule_5/exec_times.txt", std::ios_base::app); if (exec_times_file.is_open()){ exec_times_file << diff.count() * 1000000 << "us" <<std::endl; exec_times_file.close(); } return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
09988ebd755f5b0e65ae1ac496b454d6ab372e67
b7f2c737686d1feb87a819def55c1df9729bd3f7
/Codeforces/1104C.cpp
2dc287aa1eb37a3542ac6b4aca8a828d7189ca09
[]
no_license
frontseat-astronaut/Competitive-Programming
e052c887497c5da9b82c701eacc765b7f839049f
eb49d9112cfe35cd0ef8cf1b690b607a8beede7d
refs/heads/master
2020-03-21T03:15:41.561248
2019-01-27T15:59:19
2019-01-27T15:59:19
138,044,632
0
0
null
null
null
null
UTF-8
C++
false
false
1,945
cpp
#include<bits/stdc++.h> using namespace std; int main() { string s; cin>>s; bool g[4][4]={}; for(auto x:s) { if(x=='1') { for(int i=0; i<4; ++i) { int cnt=0; int j; for(j=0; j<3; ++j) { if(!g[i][j] && !g[i][j+1]) break; } if(j<3) { cout<<i+1<<" "<<j+1<<endl; g[i][j]=1; g[i][j+1]=1; break; } } for(int i=0; i<4; ++i) { bool all=1; int j; for(j=0; j<4; ++j) { if(!g[i][j]) { all=0; break; } } if(all) { for(int j=0; j<4; ++j) g[i][j]=0; } } } else { for(int i=0; i<4; ++i) { int cnt=0; int j; for(j=0; j<3; ++j) { if(!g[j][i] && !g[j+1][i]) break; } if(j<3) { cout<<j+1<<" "<<i+1<<endl; g[j][i]=1; g[j+1][i]=1; break; } } for(int i=0; i<4; ++i) { bool all=1; for(int j=0; j<4; ++j) { if(!g[j][i]) { all=0; break; } } if(all) { for(int j=0; j<4; ++j) g[j][i]=0; } } } } }
[ "32930066+frontseat-astronaut@users.noreply.github.com" ]
32930066+frontseat-astronaut@users.noreply.github.com
cd9fffe832f10cb0b1a8b69925c859ccf000cee5
8dc84558f0058d90dfc4955e905dab1b22d12c08
/net/third_party/http2/hpack/decoder/hpack_block_collector.h
1195b7482c5b99c559a519769599df529e65c25c
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
5,463
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 NET_THIRD_PARTY_HTTP2_HPACK_DECODER_HPACK_BLOCK_COLLECTOR_H_ #define NET_THIRD_PARTY_HTTP2_HPACK_DECODER_HPACK_BLOCK_COLLECTOR_H_ // HpackBlockCollector implements HpackEntryDecoderListener in order to record // the calls using HpackEntryCollector instances (one per HPACK entry). This // supports testing of HpackBlockDecoder, which decodes entire HPACK blocks. // // In addition to implementing the callback methods, HpackBlockCollector also // supports comparing two HpackBlockCollector instances (i.e. an expected and // an actual), or a sole HPACK entry against an expected value. #include <stddef.h> #include <vector> #include "net/third_party/http2/hpack/decoder/hpack_entry_collector.h" #include "net/third_party/http2/hpack/decoder/hpack_entry_decoder_listener.h" #include "net/third_party/http2/hpack/http2_hpack_constants.h" #include "net/third_party/http2/hpack/tools/hpack_block_builder.h" #include "net/third_party/http2/platform/api/http2_string.h" #include "net/third_party/http2/platform/api/http2_string_piece.h" namespace http2 { namespace test { class RandomBase; class HpackBlockCollector : public HpackEntryDecoderListener { public: // Implementations of HpackEntryDecoderListener, forwarding to pending_entry_, // an HpackEntryCollector for the "in-progress" HPACK entry. OnIndexedHeader // and OnDynamicTableSizeUpdate are pending only for that one call, while // OnStartLiteralHeader is followed by many calls, ending with OnValueEnd. // Once all the calls for one HPACK entry have been received, PushPendingEntry // is used to append the pending_entry_ entry to the collected entries_. HpackBlockCollector(); HpackBlockCollector(const HpackBlockCollector& other); ~HpackBlockCollector() override; void OnIndexedHeader(size_t index) override; void OnDynamicTableSizeUpdate(size_t size) override; void OnStartLiteralHeader(HpackEntryType header_type, size_t maybe_name_index) override; void OnNameStart(bool huffman_encoded, size_t len) override; void OnNameData(const char* data, size_t len) override; void OnNameEnd() override; void OnValueStart(bool huffman_encoded, size_t len) override; void OnValueData(const char* data, size_t len) override; void OnValueEnd() override; // Methods for creating a set of expectations (i.e. HPACK entries to compare // against those collected by another instance of HpackBlockCollector). // Add an HPACK entry for an indexed header. void ExpectIndexedHeader(size_t index); // Add an HPACK entry for a dynamic table size update. void ExpectDynamicTableSizeUpdate(size_t size); // Add an HPACK entry for a header entry with an index for the name, and a // literal value. void ExpectNameIndexAndLiteralValue(HpackEntryType type, size_t index, bool value_huffman, const Http2String& value); // Add an HPACK entry for a header entry with a literal name and value. void ExpectLiteralNameAndValue(HpackEntryType type, bool name_huffman, const Http2String& name, bool value_huffman, const Http2String& value); // Shuffle the entries, in support of generating an HPACK block of entries // in some random order. void ShuffleEntries(RandomBase* rng); // Serialize entries_ to the HpackBlockBuilder. void AppendToHpackBlockBuilder(HpackBlockBuilder* hbb) const; // Return AssertionSuccess if there is just one entry, and it is an // Indexed Header with the specified index. ::testing::AssertionResult ValidateSoleIndexedHeader(size_t ndx) const; // Return AssertionSuccess if there is just one entry, and it is a // Dynamic Table Size Update with the specified size. ::testing::AssertionResult ValidateSoleDynamicTableSizeUpdate( size_t size) const; // Return AssertionSuccess if there is just one entry, and it is a Header // entry with an index for the name and a literal value. ::testing::AssertionResult ValidateSoleLiteralValueHeader( HpackEntryType expected_type, size_t expected_index, bool expected_value_huffman, Http2StringPiece expected_value) const; // Return AssertionSuccess if there is just one entry, and it is a Header // with a literal name and literal value. ::testing::AssertionResult ValidateSoleLiteralNameValueHeader( HpackEntryType expected_type, bool expected_name_huffman, Http2StringPiece expected_name, bool expected_value_huffman, Http2StringPiece expected_value) const; bool IsNotPending() const { return pending_entry_.IsClear(); } bool IsClear() const { return IsNotPending() && entries_.empty(); } void Clear(); ::testing::AssertionResult VerifyEq(const HpackBlockCollector& that) const; private: // Push the value of pending_entry_ onto entries_, and clear pending_entry_. // The pending_entry_ must be complete. void PushPendingEntry(); HpackEntryCollector pending_entry_; std::vector<HpackEntryCollector> entries_; }; } // namespace test } // namespace http2 #endif // NET_THIRD_PARTY_HTTP2_HPACK_DECODER_HPACK_BLOCK_COLLECTOR_H_
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
d3800a0b8abb908a760344c69e9fa5e1a7fb83cc
fa4163e2697a66aec3b038de22ed32d02a823413
/treeplot/TreePlot.cpp
d4914ef720d2c1af835a694f86638db4dac9038e
[]
no_license
spatel78745/experiments
71cabb73e1f55f881ef97c74e719316a37b3d757
3951d2e97404f2a2ab28aef8f18c2a85d6f934c6
refs/heads/master
2021-01-10T03:38:39.662237
2016-01-31T01:40:48
2016-01-31T01:40:48
46,378,220
0
0
null
null
null
null
UTF-8
C++
false
false
649
cpp
/* * TreePlot.cpp * * Created on: Nov 26, 2015 * Author: spatel78745 */ #include <iostream> #include "TreePlot.h" #include "MyException.h" using namespace std; void TreePlot::drawNode(int row, int col, const string& key) const { cerr << "drawNode " << row << " " << col << " " << key << endl; } void TreePlot::drawLeftLeg(int row1, int col1, int row2, int col2) const { cerr << "drawLeftLeg " << row1 << " " << col1 << " " << row2 << " " << col2 << endl; } void TreePlot::drawRightLeg(int row1, int col1, int row2, int col2) const { cerr << "drawRightLeg " << row1 << " " << col1 << " " << row2 << " " << col2 << endl; }
[ "spatel78745@gmail.com" ]
spatel78745@gmail.com
7e14baf409935a7a059399cb1e8d47b63161e4ce
faa9035860d374b3d925257a36a5e323b3cfe89b
/CPPPrimer/ch2/two_lines.cpp
50207da7d745b3cd79a7a55e7a2c46ba86b2ce92
[]
no_license
nguaki/CPP
a739a056f42fe41bcf4c76bb8ea1dc300b629ad3
df296dea0c0493b5f2b4137e11d5d160446d95a5
refs/heads/master
2020-03-22T13:36:50.899751
2018-09-27T06:28:52
2018-09-27T06:28:52
140,119,629
0
0
null
null
null
null
UTF-8
C++
false
false
216
cpp
#include <iostream> // //a really really really 2 lines // using namespace std; int main() { int catch_22; cout << "a really really really " << " 2 lines " << endl; return 0; }
[ "jamesche0409@gmail.com" ]
jamesche0409@gmail.com
1c887dc3505486ffd351b7416dabbb0e426893e1
30874a1295d700427f7775d89a74ff5c4836dbe9
/libraries/SerialSRAM/examples/SPIFRAM_Test/SPIFRAM_Test.ino
0e9f7d7ba2c0b15e86fc3bb69244efbbcd028b25
[]
no_license
una1veritas/Arduino-public
f9b445bffe493e1c5b72f6587946b3fa3c5335ac
381cbd5193961534b910f1cfeb3a83bc273889a0
refs/heads/master
2021-01-19T15:20:21.300335
2020-10-15T12:08:24
2020-10-15T12:08:24
100,960,464
0
0
null
null
null
null
UTF-8
C++
false
false
1,252
ino
/* * SerialRAM_Test.cpp * * Created on: 2013/05/14 * Author: sin */ #include <string.h> #include <SPI.h> #include <SPIFRAM.h> SPIFRAM fram(10, SPIFRAM::BUSWIDTH_FM25V10); static const char text[][64] = { "The mailman passes by and I just wonder why", "He never stops to ring my front door bell", "There's not a single line from that dear old love of mine", "No, not a word since I last heard \"farewell\"." }; char buff[128]; void setup() { Serial.begin(9600); Serial.println("Hello."); delay(200); randomSeed(millis()); Serial.println("random seed by millis()."); SPI.begin(); fram.begin(); Serial.print("read status: "); Serial.println((int)fram.status(), HEX); Serial.println(); uint32_t addr; int length; for(int i = 0; i < 3; i++) { addr = random(0, 1L<<SPIFRAM::BUSWIDTH_FM25V10); Serial.print(addr, HEX); Serial.print(": "); memset(buff,0,64); strcpy(buff, text[millis()%4]); length = strlen(buff); fram.write(addr, (byte*) buff, length+1); Serial.println((int)fram.status(), HEX); memset(buff,0,64); fram.read(addr, (byte*) buff, length+1); Serial.println(buff); Serial.println(); delay(100); } } void loop() { }
[ "una.veritas@me.com" ]
una.veritas@me.com
c3553d3256c508bdc4783dca246a2c8dfd0b0ac8
d7c957a87e0e4d55ed4c8185f029555c033877d1
/tools/fconv/include/convMxN.h
d3fb3671f9d29e565b1176685cdafa4491886fc0
[ "BSD-2-Clause" ]
permissive
kenoogl/CDMlib
eb597908e483ec745fcd05313590c032fd39fdd6
60fd081c6b2f8fc35be915e32b7313fbac32c730
refs/heads/master
2020-12-13T14:42:38.836288
2014-08-23T07:59:34
2014-08-23T07:59:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
856
h
#ifndef _CONVMXN_H_ #define _CONVMXN_H_ /* * fconv (File Converter) * * CDMlib - Cartesian Data Management library * * Copyright (c) 2013-2014 Advanced Institute for Computational Science, RIKEN. * All rights reserved. * */ #include "conv.h" #include "convOutput.h" /** * @file convMxN.h * @brief convMxN Class Header * @author aics * @date 2013/11/14 */ class convMxN : public CONV { public: int m_Gvoxel[3]; int m_Gdiv[3]; int m_Head[3]; int m_Tail[3]; vector<cio_DFI *>m_out_dfi; //出力DFIのポインタ public: /** コンストラクタ */ convMxN(); /** デストラクタ */ ~convMxN(); public: /** * @brief 領域分割と出力DFIのインスタンス */ void VoxelInit(); /** * @brief MxNの実行 * @return エラーコード */ bool exec(); }; #endif // _CONVEXEC_H_
[ "keno@riken.jp" ]
keno@riken.jp
999c0793798f35b6d227a23ef75f9fc0270db2a0
413df0c83cdd3021f58d8abf01fd81f8290d2c28
/libraries/StepperDriver-master/examples/BasicStepperDriver/BasicStepperDriver.ino
44f5a6fed3509daa2f63d1fa196a74320e920f85
[ "MIT" ]
permissive
RimantasSmitas/Arduino
6d7328633b0fb7f9e0c83fa8c15924e67830854b
1c9da217471d7426207780ca1fb1e139f69f4016
refs/heads/master
2020-03-11T23:40:36.056105
2019-06-24T07:34:00
2019-06-24T07:34:00
130,327,780
0
0
null
null
null
null
UTF-8
C++
false
false
1,818
ino
/* * Simple demo, should work with any driver board * * Connect STEP, DIR as indicated * * Copyright (C)2015-2017 Laurentiu Badea * * This file may be redistributed under the terms of the MIT license. * A copy of this license has been included with this distribution in the file LICENSE. */ #include <Arduino.h> #include "BasicStepperDriver.h" // Motor steps per revolution. Most steppers are 200 steps or 1.8 degrees/step #define MOTOR_STEPS 200 #define RPM 100 // Since microstepping is set externally, make sure this matches the selected mode // If it doesn't, the motor will move at a different RPM than chosen // 1=full step, 2=half step etc. #define MICROSTEPS 128 // All the wires needed for full functionality #define DIR 8 #define STEP 9 //Uncomment line to use enable/disable functionality //#define SLEEP 13 // 2-wire basic config, microstepping is hardwired on the driver BasicStepperDriver stepper(MOTOR_STEPS, DIR, STEP); //Uncomment line to use enable/disable functionality //BasicStepperDriver stepper(MOTOR_STEPS, DIR, STEP, SLEEP); void setup() { stepper.begin(RPM, MICROSTEPS); // if using enable/disable on ENABLE pin (active LOW) instead of SLEEP uncomment next line // stepper.setEnableActiveState(LOW); } void loop() { // energize coils - the motor will hold position // stepper.enable(); /* * Moving motor one full revolution using the degree notation */ stepper.rotate(0.1); // stepper.rotate(5.65); // stepper.rotate(5.65); // stepper.rotate(5.65); delay(1000); // stepper.rotate(5.65); /* * Moving motor to original position using steps */ // stepper.move(-MOTOR_STEPS*MICROSTEPS); // pause and allow the motor to be moved by hand // stepper.disable(); // delay(100); }
[ "rimantas.smitas@gmail.com" ]
rimantas.smitas@gmail.com
ca03552f378eafc6b23cb3c9d500f3da4f2bd839
c3ca81bcc87ea5b3a01038ddc6312a7dbef12d00
/md/tremolo/src/CallbackCompilationUnit.cc
c4c901070e987dd8f62f0c18a0f1eaef10e8d81a
[ "BSD-2-Clause" ]
permissive
kraused/maci-code
08dc21efcd934df1ff3d907a7be73cc7dfc15593
9fb999ff8f2899a88617f1e980cae0924b64e691
refs/heads/master
2020-04-27T04:55:23.137733
2013-06-14T09:19:55
2013-06-14T09:19:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
742
cc
#include "Callback.hh" void (*RattleIntegrator_CorrectAfterKickDriftCB)(RattleIntegrator* self) = 0; void (*RattleIntegrator_CorrectAfterKickCB)(RattleIntegrator* self) = 0; void (*TimeIntegrator_ApplyDamperCB)(TimeIntegrator* self) = 0; void (*TimeIntegrator_plugins_setupCB)(TimeIntegrator* self) = 0; void (*TimeIntegrator_plugins_pre_integrationCB)(TimeIntegrator* self) = 0; void (*TimeIntegrator_plugins_post_integrationCB)(TimeIntegrator* self) = 0; void (*TimeIntegrator_plugins_pre_forceCB)(TimeIntegrator* self) = 0; void (*TimeIntegrator_plugins_post_forceCB)(TimeIntegrator* self) = 0; void (*TimeIntegrator_plugins_pre_stepCB)(TimeIntegrator* self) = 0; void (*TimeIntegrator_plugins_post_stepCB)(TimeIntegrator* self) = 0;
[ "dorian@91df63fb.com" ]
dorian@91df63fb.com
f3fcf302c78bbe4d612801c11f468897008d6ebd
c3bfd0eb01cf69b4f35c3309de43ef9820e5f8d6
/DataStructure/disjoint_set.cpp
43bd44c4e6d5ef9fba48dd2e160e0a3264d1bffd
[ "MIT" ]
permissive
kmyk/rsk0315-library
deae1609691e7651bafc5c9bb393a00ff552dd19
344f8f8c6c8c8951637154d6cb87cfb3dbc50376
refs/heads/master
2023-02-26T17:24:31.796182
2021-02-01T14:50:34
2021-02-01T14:50:34
292,615,801
0
0
null
null
null
null
UTF-8
C++
false
false
1,084
cpp
#ifndef H_disjoint_set #define H_disjoint_set /** * @brief 素集合データ構造 * @author えびちゃん */ #include <cstddef> #include <cstdint> #include <utility> #include <vector> class disjoint_set { public: using size_type = size_t; private: mutable std::vector<intmax_t> M_c; public: disjoint_set() = default; explicit disjoint_set(size_type n): M_c(n, -1) {} void reset() { M_c.assign(M_c.size(), -1); } size_type representative(size_type v) const { if (M_c[v] < 0) return v; return (M_c[v] = representative(M_c[v])); } bool unite(size_type u, size_type v) { u = representative(u); v = representative(v); if (u == v) return false; if (-M_c[u] > -M_c[v]) std::swap(u, v); M_c[v] += M_c[u]; M_c[u] = v; return true; } bool equivalent(size_type u, size_type v) const { return (representative(u) == representative(v)); } size_type size() const noexcept { return M_c.size(); } size_type count(size_type v) const { return -M_c[representative(v)]; } }; #endif /* !defined(H_disjoint_set) */
[ "rsk0315@icloud.com" ]
rsk0315@icloud.com
7dac481d433a10bd3ec5e0c38e94272eb8610ab5
f691a46cb8fc317083dc61622f7229130148ba53
/vector/object/Circle.cpp
03e9ffe11c125d877b45c088ae5f4203d97dda57
[]
no_license
caofang/c_cpp_snippet
3a16de127d6d7acab8ae8dd26e4574e7cbf4ae71
5c337e8f343e65a15b614ad11d0e231c45b3b9eb
refs/heads/master
2021-05-03T10:14:56.595547
2020-02-26T20:11:21
2020-02-26T20:11:21
120,532,107
0
0
null
null
null
null
UTF-8
C++
false
false
292
cpp
// practice of class class #include "Circle.h" Circle::Circle() { } void Circle::setRadius(double r) { radius = r; } double Circle::getRadius() { return radius; } double Circle::Area() { return 3.14 * radius * radius; } double Circle::Circumference() { return 2 * 3.14 * radius; }
[ "fc63@njit.edu" ]
fc63@njit.edu
28883149ebebb7834a48b1d0f00e341dc89c1969
ce00f011cde87891fd01c0101ab432b28269073a
/C++/IteratorHeap/IteratorHeap/Source.cpp
9d7e8fa34f20fc2081b729e662c2f7e91e72efd9
[]
no_license
stevenRush/furry-ninja
2562370ba8ef3fdf24558b7135e13577abc94152
3347d9420bcf178115cead2f3d14c1e49c907f43
refs/heads/master
2020-05-31T16:50:34.202262
2014-12-09T19:08:34
2014-12-09T19:08:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
457
cpp
#include "Heap.h" #include <deque> #include <iostream> int main() { freopen("C:\\in.txt", "r", stdin); std::deque<size_t> d; Heap h; int M; int s; int max; std::cin >> M; for(size_t i = 0; i < M-1; ++i) { std::cin >> s; d.push_back(h.Add(s)); } std::cin >> s; do { d.push_back(h.Add(s)); std::cout << h.GetMax() << std::endl; h.Delete(d.front()); d.pop_front(); std::cin >> s; } while(s != -1); fclose(stdin); return 0; }
[ "evgeny.eltishev@phystech.edu" ]
evgeny.eltishev@phystech.edu
844002a184210ea9688fad020b8e18f59ba0eb19
ab1c643f224197ca8c44ebd562953f0984df321e
/cys/mys/manageyourserver.hpp
06d2ff3bec051082e918a6da69dc7476987f1a60
[]
no_license
KernelPanic-OpenSource/Win2K3_NT_admin
e162e0452fb2067f0675745f2273d5c569798709
d36e522f16bd866384bec440517f954a1a5c4a4d
refs/heads/master
2023-04-12T13:25:45.807158
2021-04-13T16:33:59
2021-04-13T16:33:59
357,613,696
0
1
null
null
null
null
UTF-8
C++
false
false
6,200
hpp
// Copyright (C) 2002 Microsoft Corporation // // class ManageYourServer, which implements IManageYourServer // // 21 January 2002 sburns #ifndef MANAGEYOURSERVER_HPP_INCLUDED #define MANAGEYOURSERVER_HPP_INCLUDED #include <cys.h> enum HardenedLevel { NO_HARDENING, USERS_HARDENED, ADMINS_HARDENED, ALL_HARDENED }; class ManageYourServer : public IManageYourServer /* , public ISupportErrorInfo */ // CODEWORK: add support for ErrorInfo { // this is the only entity with access to the ctor of this class friend class ClassFactory<ManageYourServer>; public: // IUnknown methods virtual HRESULT __stdcall QueryInterface(const IID& riid, void **ppv); virtual ULONG __stdcall AddRef(); virtual ULONG __stdcall Release(); // IDispatch methods virtual HRESULT __stdcall GetTypeInfoCount(UINT *pcti); virtual HRESULT __stdcall GetTypeInfo(UINT cti, LCID, ITypeInfo **ppti); virtual HRESULT __stdcall GetIDsOfNames( REFIID riid, OLECHAR **prgpsz, UINT cNames, LCID lcid, DISPID *prgids); virtual HRESULT __stdcall Invoke( DISPID id, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *params, VARIANT *pVarResult, EXCEPINFO *pei, UINT *puArgErr); // // ISupportErrorInfo methods // // virtual // HRESULT __stdcall // InterfaceSupportsErrorInfo(const IID& iid); // // IManageYourServer methods // virtual HRESULT __stdcall GetConfiguredRoleMarkup( /* [retval][out] */ BSTR *result); virtual HRESULT __stdcall HasRoleStatusChanged( /* [retval][out] */ BOOL *result); virtual HRESULT __stdcall IsClusterNode( /* [retval][out] */ BOOL *result); virtual HRESULT __stdcall IsCurrentUserAnAdministrator( /* [out, retval] */ BOOL* result); virtual HRESULT __stdcall IsSupportedSku( /* [out, retval] */ BOOL* result); virtual HRESULT __stdcall IsStartupFlagSet( /* [out, retval] */ BOOL* result); virtual HRESULT __stdcall SetRunAtLogon( /* [in] */ BOOL newState); // NTRAID#NTBUG9-530202-29-Mar-2002-jrowlett // support needed to check if link is valid virtual HRESULT __stdcall IsServerManagementConsolePresent( /* [out, retval] */ BOOL* result ); // NTRAID#NTBUG9-602954-29-Apr-2002-jrowlett // support hiding the startup checkbox when policy is enabled. virtual HRESULT __stdcall IsShowAtStartupPolicyEnabled( /* [out, retval] */ BOOL* result ); // NTRAID#NTBUG9-627875-2002/05/22-artm // support hiding startup checkbox when running on datacenter server virtual HRESULT __stdcall IsDatacenterServer( /* [out, retval] */ BOOL* result ); // NTRAID#NTBUG9-648428-2002/06/25-artm // support hiding web application server console link if on IA64 virtual HRESULT __stdcall IsWebServerConsolePresent( /* [out, retval] */ BOOL* result ); // NTRAID#NTBUG9-632113-2002/07/01-artm // support saving collapsed/expanded state of role nodes virtual HRESULT __stdcall CollapseRole( /* [in] */ BSTR roleId, /* [in] */ BOOL collapse ); // NTRAID#NTBUG9-632113-2002/07/01-artm // support checking collapsed state of role nodes virtual HRESULT __stdcall IsRoleCollapsed( /* [in] */ BSTR roleId, /* [out, retval] */ BOOL* result); // NTRAID#NTBUG9-680200-2002/08/01-artm // Support retrieving working area of the display. // // Area info is returned as a comma separated string b/c JScript does not // support getting back SAFEARRAY's. // // e.g. "0,0,800,600" --> working area is 800 wide, 600 high, and starts at // screen position (0,0) virtual HRESULT __stdcall GetWorkingAreaInfo( /* [out, retval] */ BSTR* info); private: // only our friend class factory can instantiate us. ManageYourServer(); // only Release can cause us to be deleted virtual ~ManageYourServer(); // not implemented: no copying allowed ManageYourServer(const ManageYourServer&); const ManageYourServer& operator=(const ManageYourServer&); struct RoleStatus { ServerRole role; // The enum used to identify a role InstallationStatus status; // The enum used for the role's state // we sort by role bool operator<(const RoleStatus& rhs) const { if (this == &rhs) { return false; } return this->role < rhs.role; } bool operator==(const RoleStatus& rhs) const { if (this == &rhs) { // identity is equality return true; } return (this->role == rhs.role) && (this->status == rhs.status); } }; typedef std::vector<RoleStatus, Burnslib::Heap::Allocator<RoleStatus> > RoleStatusVector; typedef void (*ParamSubFunc)(String& target); typedef std::map< ServerRole, std::pair<String, ParamSubFunc>, std::less<ServerRole>, Burnslib::Heap::Allocator<std::pair<String, ParamSubFunc> > > RoleToFragmentNameMap; static void AppendXmlFragment( String& s, const String& fragName, ParamSubFunc subFunc); static void BuildFragMap(); static void GetRoleStatus(RoleStatusVector& stat); // NTRAID#NTBUG9-698722-2002/09/03-artm static void InitDCPromoStatusCheck(); static bool isDCCheckInitialized; static RoleToFragmentNameMap fragMap; static bool fragMapBuilt; RoleStatusVector roleStatus; ComServerReference dllref; long refcount; ITypeInfo** m_ppTypeInfo; bool foundTLS; // Found terminal licensing server? HardenedLevel ieSecurity; // Level of IE security (hardening patch) }; #endif // MANAGEYOURSERVER_HPP_INCLUDED
[ "polarisdp@gmail.com" ]
polarisdp@gmail.com
bb60c637c28331b18306390850b108173d00091a
5c1ad4f9babc7e0fc2ca427cef72f79c8c1229b9
/Examples/BasicFightStick/BasicFightStick.ino
ca078b0d78a2ce121a2ffae497a2fe1a0cf1ceb5
[]
no_license
JasonElting/controller
f87f224b95292d7eae072d86035aa8ba48f6b175
5105f6991287695f3da62245d8feac339ac13f10
refs/heads/master
2021-01-23T14:04:51.189528
2014-09-30T19:47:41
2014-09-30T19:47:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,700
ino
#include "UnoJoy.h" // Define our pins int TrianglePin = 4; int SquarePin = 5; int CrossPin = 3; int CirclePin = 2; int LeftPin = 8; int UpPin = 9; int RightPin = 10; int DownPin = 11; int StartPin = 12; void setup(){ setupPins(); setupUnoJoy(); } void loop(){ // Always be getting fresh data dataForController_t controllerData = getControllerData(); setControllerData(controllerData); } void setupPins(void){ // Set all the digital pins as inputs // with the pull-up enabled, except for the // two serial line pins for (int i = 2; i <= 12; i++){ pinMode(i, INPUT_PULLUP); digitalWrite(i, LOW); } } dataForController_t getControllerData(void){ // Set up a place for our controller data // Use the getBlankDataForController() function, since // just declaring a fresh dataForController_t tends // to get you one filled with junk from other, random // values that were in those memory locations before dataForController_t controllerData = getBlankDataForController(); // Since our buttons are all held high and // pulled low when pressed, we use the "!" // operator to invert the readings from the pins controllerData.triangleOn = !digitalRead(TrianglePin); controllerData.circleOn = !digitalRead(CirclePin); controllerData.squareOn = !digitalRead(SquarePin); controllerData.crossOn = !digitalRead(CrossPin); controllerData.dpadUpOn = !digitalRead(UpPin); controllerData.dpadDownOn = !digitalRead(DownPin); controllerData.dpadLeftOn = !digitalRead(LeftPin); controllerData.dpadRightOn = !digitalRead(RightPin); controllerData.startOn = !digitalRead(StartPin); // And return the data! return controllerData; }
[ "jason.elting@gmail.com" ]
jason.elting@gmail.com
adb8fe4e70c52b51fc2ef46fe6d334ba536d5d2e
5f02484319bf6448068410a9e8bc6c0b4446258d
/Hangman/src/Functionality.cpp
c79d148ed2ce2efcb89ccc318c7786972e265f0e
[]
no_license
amirul123akmal/Hangman
0418cd9a685f7556c1f32f9cf919512bd34fb604
8b46b7989088c711573a9c614bcf03943ee9892f
refs/heads/master
2023-08-29T14:53:12.108337
2021-10-01T08:50:19
2021-10-01T08:50:19
412,180,276
0
0
null
null
null
null
UTF-8
C++
false
false
1,256
cpp
#include "Functionality.h" namespace basic { void clear() { system("cls"); } int random(int min, int max) { std::random_device random; std::mt19937 mt(random()); std::uniform_real_distribution<float> dist(min, max); return (int)dist(mt) ; } bool ifExsit(std::string word, char ch) { for (int i = 0 ; i < word.size() ; i++) { if (word[i] == ch) { return true; } } return false; } std::vector<char> replace(std::string word, std::vector<char> list, char ch) { for (int i = 0; i < list.size() - 1 ;i++) { if (word[i] == ch) { list[i] = ch; } } return list; } bool comparison(std::vector<char> a1) { for (int i = 0; i< a1.size() - 1;i++) { if (a1[i] == '*') { return false; } } return true; } void printColored(std::string sentence, int color, bool nextline) { switch (color) { case 1: printf("\033[0;31m"); break; case 2: printf("\033[0;34m"); break; case 3: printf("\033[0;32m"); break; default: break; } printf("%s", sentence.c_str()); if (nextline) { printf("\n"); } printf("\033[0;37m"); } void printIt(std::vector<char> name) { for(int i = 0;i < name.size() - 1 ;i++) { std::cout << name[i]; } } }
[ "amirul.akmal.putrajaya2003@gmail.com" ]
amirul.akmal.putrajaya2003@gmail.com
b2cb514ba589fb95f8fc5eac8840604abef33bcc
9d107a4d6451b6d352ed434fc3fa1bdec3c5791c
/bchis/w3c.cpp
c2f5b876570db708cdc1f46bb9973a392ad6a0cb
[]
no_license
HarrtTong/Bitcoin-History
d50c7476452fe4f1fa6c6634eb37b10c5f7db67a
ef06995188b4ccb3126d56710ada272c278169f8
refs/heads/master
2020-05-23T01:08:02.873643
2014-05-15T00:57:17
2014-05-15T00:57:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
39,373
cpp
#include "w3c.h" #include <cstring> using namespace std; #define __HTTP_VERB_GET "GET" #define __HTTP_VERB_POST "POST" #define __HTTP_ACCEPT_TYPE "*/*" #define __HTTP_ACCEPT "Accept: */*\r\n" #define __DEFAULT_BUF_SIZE 1024 void __w3cexcept(const char *szaddress, long nport, W3Client::w3t t, const char *szmsg){ #ifdef _DEBUG string sztmp; sztmp+="[ "; switch(t) { case W3Client::w3http: sztmp+="http://"; break; case W3Client::w3https: sztmp+="https://"; break; case W3Client::w3ftp: sztmp+="ftp://"; break; } sztmp+=szaddress; sztmp+=":"; char szp[10]="\0"; sprintf(szp, "%d", nport); sztmp+=szp; sztmp+=" ] "; sztmp+=szmsg; ::OutputDebugString(sztmp.c_str()); DWORD err=::GetLastError(); LPVOID lpMsgBuffer; DWORD dwRet=FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE, GetModuleHandle("wininet.dll"), err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPTSTR>(&lpMsgBuffer), 0, NULL); char szmsg2[1024]="\0"; sprintf(szmsg2, "[%d, 0x%08x] %s", err, err, reinterpret_cast<LPTSTR>(lpMsgBuffer)); OutputDebugString(szmsg2); ::LocalFree(lpMsgBuffer); #endif } void __w3cexcept(const char *szaddress, long nport, W3Client::w3t t, const char *szuri, const char *szmsg){ #ifdef _DEBUG string sztmp; sztmp+="[ "; switch(t) { case W3Client::w3http: sztmp+="http://"; break; case W3Client::w3https: sztmp+="https://"; break; case W3Client::w3ftp: sztmp+="ftp://"; break; } sztmp+=szaddress; sztmp+=":"; char szp[10]="\0"; sprintf(szp, "%d", nport); sztmp+=szp; sztmp+=szuri; sztmp+=" ] "; sztmp+=szmsg; ::OutputDebugString(sztmp.c_str()); LPVOID lpMsgBuffer; DWORD err=::GetLastError(); DWORD dwRet=FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE, GetModuleHandle("wininet.dll"), err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPTSTR>(&lpMsgBuffer), 0, NULL); char szmsg2[1024]="\0"; sprintf(szmsg2, "[%d, 0x%08x] %s", err, err, reinterpret_cast<LPTSTR>(lpMsgBuffer)); OutputDebugString(szmsg2); ::LocalFree(lpMsgBuffer); #endif } // W3Client : synchronized www client bool W3Client::Connect(const char *szaddress, const char *szuser /*=NULL*/, const char *szpassword /*=NULL*/, const char *szagent /*=__W3_DEFAULT_AGENT*/){ char szp[__DEFAULT_BUF_SIZE]="\0", szus[__DEFAULT_BUF_SIZE]="\0", szpw[__DEFAULT_BUF_SIZE]="\0"; char sza[__DEFAULT_BUF_SIZE]="\0", szuri[__DEFAULT_BUF_SIZE]="\0"; unsigned long port=0; __w3curlparse(szaddress, szp, szus, szpw, sza, port, szuri); w3t wt; if(!strncmp(szp, "https", 5)) wt=w3https; else if(!strncmp(szp, "http", 4)) wt=w3http; else if(!strncmp(szp, "ftp", 3)) wt=w3ftp; _szuri=szuri; return Connect(sza, port, ((szuser || (!szuser && strlen(szus)==0))? szuser : szus), ((szpassword || (!szpassword && strlen(szpw)==0))? szpassword : szpw), wt, szagent); } bool W3Client::Connect( const char *szaddress, long nport, const char *szuser /*=NULL*/, const char *szpassword /*=NULL*/, w3t t /*=w3http*/, const char *szagent /*=__W3_DEFAULT_AGENT*/){ bool r=true; try{ _hOpen=::InternetOpen( szagent, // agent INTERNET_OPEN_TYPE_PRECONFIG, // access type NULL, // proxy NULL, // proxy by pass 0); // flags if(!_hOpen || _hOpen==INVALID_HANDLE_VALUE) throw "open internet failed..."; switch(t) { case w3ftp: _hConnection=::InternetConnect( _hOpen, szaddress, (nport? nport: INTERNET_DEFAULT_FTP_PORT), szuser, szpassword, INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, NULL); break; case w3http: _hConnection=::InternetConnect( _hOpen, szaddress, (nport? nport: INTERNET_DEFAULT_HTTP_PORT), szuser, szpassword, INTERNET_SERVICE_HTTP, 0, NULL); break; case w3https: _hConnection=::InternetConnect( _hOpen, szaddress, (nport? nport: INTERNET_DEFAULT_HTTPS_PORT), szuser, szpassword, INTERNET_SERVICE_HTTP, 0, NULL); break; } if(!_hConnection || _hConnection==INVALID_HANDLE_VALUE) throw "connect failed..."; if(::InternetAttemptConnect(NULL)!=ERROR_SUCCESS) throw "connect failed..."; _szaddress=szaddress; if(!nport){ switch(t) { case w3ftp: _nport=INTERNET_DEFAULT_FTP_PORT; break; case w3http: _nport=INTERNET_DEFAULT_HTTP_PORT; break; case w3https: _nport=INTERNET_DEFAULT_HTTPS_PORT; break; } }else _nport=nport; _t=t; if(szuser) _szuser=szuser; if(szpassword) _szpassword=szpassword; InitializeCookies(); InitializePostArguments(); }catch(const char *szm){ r=false; if(_hOpen || _hOpen!=INVALID_HANDLE_VALUE) ::InternetCloseHandle(_hOpen); if(_hConnection || _hConnection!=INVALID_HANDLE_VALUE) ::CloseHandle(_hConnection); __w3cexcept(szaddress, nport, t, szm); }catch(...){ r=false; if(_hOpen || _hOpen!=INVALID_HANDLE_VALUE) ::InternetCloseHandle(_hOpen); if(_hConnection || _hConnection!=INVALID_HANDLE_VALUE) ::CloseHandle(_hConnection); __w3cexcept(szaddress, nport, t, "unknown exception..."); } return r; } void W3Client::Close(){ if(_hRequest) ::InternetCloseHandle(_hRequest); if(_hConnection) ::InternetCloseHandle(_hConnection); if(_hOpen) ::InternetCloseHandle(_hOpen); return; } bool W3Client::Request(const char *szuri, w3m m, const char *szref /*=NULL*/){ bool bflag=false; try{ switch(m) { case reqPost: bflag=RequestPost(szuri, szref); break; case reqPostMultipartsFormdata: bflag=RequestPost2(szuri, szref); break; case reqGet: bflag=RequestGet(szuri, szref); break; } if(bflag){ _szuri=szuri; }else{ ::InternetCloseHandle(_hRequest); _hRequest=NULL; } }catch(const char *szm){ ::InternetCloseHandle(_hRequest); _hRequest=NULL; __w3cexcept(_szaddress.c_str(), _nport, _t, szuri, szm); }catch(...){ ::InternetCloseHandle(_hRequest); _hRequest=NULL; __w3cexcept(_szaddress.c_str(), _nport, _t, szuri, "unknown exception..."); } return bflag; } bool W3Client::RequestGet(const char *szuri, const char *szref /*=NULL*/){ static LPCTSTR szAcceptType=TEXT(__HTTP_ACCEPT_TYPE); if(!_hConnection || _hConnection==INVALID_HANDLE_VALUE) throw "handle not opened..."; _hRequest=::HttpOpenRequest( _hConnection, __HTTP_VERB_GET, // HTTP Verb szuri, // Object Name HTTP_VERSION, // Version szref, // Reference &szAcceptType, // Accept Type INTERNET_FLAG_NO_CACHE_WRITE | (_t==w3https? INTERNET_FLAG_SECURE:0), NULL); // context call-back point if(!_hRequest || _hRequest==INVALID_HANDLE_VALUE) throw "request failed..."; // REPLACE HEADER if(!::HttpAddRequestHeaders( _hRequest, __HTTP_ACCEPT, strlen(__HTTP_ACCEPT), HTTP_ADDREQ_FLAG_REPLACE)) throw "additional header failed..."; // COOKIE ADD if(_listcookies.size()>0){ string szurl; switch(_t) { case w3http: szurl="http://"; break; case w3https: szurl="https://"; break; } szurl+=_szaddress.c_str(); if(!((_t==w3http && _nport==INTERNET_DEFAULT_HTTP_PORT) || (_t==w3https && _nport==INTERNET_DEFAULT_HTTPS_PORT))){ char tmp[10]="\0"; sprintf(tmp, ":%d", _nport); szurl+=tmp; } szurl+=szuri; for(list<HTTP_COOKIE*>::iterator it=_listcookies.begin(); it!=_listcookies.end(); it++){ HTTP_COOKIE *pc=reinterpret_cast<HTTP_COOKIE*>(*it); if(!::InternetSetCookie(szurl.c_str(), pc->name.c_str(), pc->value.c_str())) throw "add cookie failed..."; } } // SEND REQUEST if(!::HttpSendRequest( _hRequest, // handle by returned HttpOpenRequest NULL, // additional HTTP header 0, // additional HTTP header length NULL, // additional data in HTTP Post or HTTP Put 0) // additional data length ) throw "request failed..."; return true; } void W3Client::InitializePostArguments(){ if(_listargs.size()>0){ for(list<HTTP_ARG*>::iterator it=_listargs.begin(); it!=_listargs.end(); it++){ HTTP_ARG *p=reinterpret_cast<HTTP_ARG*>(*it); delete p; } _listargs.clear(); } return; } void W3Client::AddPostArgument(const char *szname, const int nvalue){ HTTP_ARG *pa=new HTTP_ARG(szname, nvalue); _listargs.push_back(pa); return; } void W3Client::AddPostArgument(const char *szname, const long nvalue){ HTTP_ARG *pa=new HTTP_ARG(szname, nvalue); _listargs.push_back(pa); return; } void W3Client::AddPostArgument(const char *szname, const float nvalue){ HTTP_ARG *pa=new HTTP_ARG(szname, nvalue); _listargs.push_back(pa); return; } void W3Client::AddPostArgument(const char *szname, const double nvalue){ HTTP_ARG *pa=new HTTP_ARG(szname, nvalue); _listargs.push_back(pa); return; } void W3Client::AddPostArgument(const char *szname, const char *szvalue, bool bfile /*=false*/){ HTTP_ARG *pa=new HTTP_ARG(szname, szvalue, bfile); _listargs.push_back(pa); return; } void W3Client::InitializeCookies(){ if(_listcookies.size()>0){ for(list<HTTP_COOKIE*>::iterator it=_listcookies.begin(); it!=_listcookies.end(); it++){ HTTP_COOKIE *p=reinterpret_cast<HTTP_COOKIE*>(*it); delete p; } _listcookies.clear(); } return; } void W3Client::AddCookie(const char *szname, const char *szvalue){ HTTP_COOKIE *pc=new HTTP_COOKIE(szname, szvalue); _listcookies.push_back(pc); return; } void W3Client::AddCookie(const char *szname, const int value){ HTTP_COOKIE *pc=new HTTP_COOKIE(szname, value); _listcookies.push_back(pc); return; } void W3Client::AddCookie(const char *szname, const long value){ HTTP_COOKIE *pc=new HTTP_COOKIE(szname, value); _listcookies.push_back(pc); return; } void W3Client::AddCookie(const char *szname, const float value){ HTTP_COOKIE *pc=new HTTP_COOKIE(szname, value); _listcookies.push_back(pc); return; } void W3Client::AddCookie(const char *szname, const double value){ HTTP_COOKIE *pc=new HTTP_COOKIE(szname, value); _listcookies.push_back(pc); return; } unsigned long W3Client::GetPostArgumentsLength(){ unsigned long len=0; if(_listargs.size()>0){ for(list<HTTP_ARG*>::iterator it=_listargs.begin(); it!=_listargs.end(); it++){ HTTP_ARG *p=reinterpret_cast<HTTP_ARG*>(*it); len+=p->length()+1; } } return len? len-1: 0; } unsigned long W3Client::GetPostData(unsigned char *buf, unsigned long len){ unsigned long l=0; if(len>GetPostArgumentsLength() && _listargs.size()>0){ for(list<HTTP_ARG*>::iterator it=_listargs.begin(); it!=_listargs.end(); it++){ HTTP_ARG *p=reinterpret_cast<HTTP_ARG*>(*it); p->dump(buf+l, p->length()); buf[l+p->length()]='&'; l+=p->length()+1; } buf[l-1]='\0'; } return l? l-1: 0; } bool W3Client::RequestPost(const char *szuri, const char *szref /*=NULL*/){ static LPCTSTR szAcceptType=__HTTP_ACCEPT_TYPE; static LPCTSTR szContentType="Content-Type: application/x-www-form-urlencoded\r\n"; unsigned char *buf=NULL; unsigned long len=0; if(!_hConnection || _hConnection==INVALID_HANDLE_VALUE) throw "handle not opened..."; _hRequest=::HttpOpenRequest( _hConnection, __HTTP_VERB_POST, // HTTP Verb szuri, // Object Name HTTP_VERSION, // Version szref, // Reference &szAcceptType, // Accept Type INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_FORMS_SUBMIT | (_t==w3https? INTERNET_FLAG_SECURE:0), NULL); // context call-back point if(!_hRequest || _hRequest==INVALID_HANDLE_VALUE) throw "request failed..."; // REPLACE HEADER if(!::HttpAddRequestHeaders( _hRequest, __HTTP_ACCEPT, strlen(__HTTP_ACCEPT), HTTP_ADDREQ_FLAG_REPLACE)) throw "additional header failed..."; // COOKIE ADD if(_listcookies.size()>0){ string szurl; switch(_t) { case w3http: szurl="http://"; break; case w3https: szurl="https://"; break; } szurl+=_szaddress.c_str(); if(!((_t==w3http && _nport==INTERNET_DEFAULT_HTTP_PORT) || (_t==w3https && _nport==INTERNET_DEFAULT_HTTPS_PORT))){ char tmp[10]="\0"; sprintf(tmp, ":%d", _nport); szurl+=tmp; } szurl+=szuri; for(list<HTTP_COOKIE*>::iterator it=_listcookies.begin(); it!=_listcookies.end(); it++){ HTTP_COOKIE *pc=reinterpret_cast<HTTP_COOKIE*>(*it); if(!::InternetSetCookie(szurl.c_str(), pc->name.c_str(), pc->value.c_str())) throw "add cookie failed..."; } } // GET POST ARGUMENTS buf=reinterpret_cast<unsigned char*>(::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, GetPostArgumentsLength()+1)); len=GetPostData(buf, GetPostArgumentsLength()+1); // SEND REQUEST WITH POST ARGUEMENTS if(!::HttpSendRequest( _hRequest, // handle by returned HttpOpenRequest szContentType, // additional HTTP header strlen(szContentType), // additional HTTP header length reinterpret_cast<LPVOID>(buf), // additional data in HTTP Post or HTTP Put len) // additional data length && ::GetLastError()!=12168){ ::HeapFree(::GetProcessHeap(), 0, buf); throw "request failed..."; } ::HeapFree(::GetProcessHeap(), 0, buf); return true; } unsigned long W3Client::GetMultiPartsFormDataLength(){ unsigned long len=0; if(_listargs.size()>0){ for(list<HTTP_ARG*>::iterator it=_listargs.begin(); it!=_listargs.end(); it++){ HTTP_ARG *p=reinterpret_cast<HTTP_ARG*>(*it); len+=p->length2(); } } return len; } unsigned long W3Client::AllocMultiPartsFormData(unsigned char *&buf, const char *szboundry){ unsigned long len=0; unsigned long ns=GetMultiPartsFormDataLength()+1; if(buf) return 0; buf=reinterpret_cast<unsigned char*>(::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, ns)); if(_listargs.size()>0){ for(list<HTTP_ARG*>::iterator it=_listargs.begin(); it!=_listargs.end(); it++){ HTTP_ARG *pa=reinterpret_cast<HTTP_ARG*>(*it); len+=pa->dump2(buf+len, ns-len, szboundry); } } memcpy(buf+len, "--", 2); memcpy(buf+len+2, szboundry, strlen(szboundry)); memcpy(buf+len+2+strlen(szboundry), "--\r\n", 4); len+=2+strlen(szboundry)+4; return len; } void W3Client::FreeMultiPartsFormData(unsigned char *buf){ ::HeapFree(::GetProcessHeap(), 0, buf); return; } bool W3Client::RequestPost2(const char *szuri, const char *szref /*=NULL*/){ static LPCTSTR szAcceptType=__HTTP_ACCEPT_TYPE; static LPCTSTR szContentType="Content-Type: multipart/form-data; boundary=--MULTI-PARTS-FORM-DATA-BOUNDARY\r\n"; unsigned char *buf=NULL; unsigned long len=0; if(!_hConnection || _hConnection==INVALID_HANDLE_VALUE) throw "handle not opened..."; _hRequest=::HttpOpenRequest( _hConnection, __HTTP_VERB_POST, // HTTP Verb szuri, // Object Name HTTP_VERSION, // Version szref, // Reference &szAcceptType, // Accept Type INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_FORMS_SUBMIT | (_t==w3https? INTERNET_FLAG_SECURE:0), NULL); // context call-back point if(!_hRequest || _hRequest==INVALID_HANDLE_VALUE) throw "request failed..."; // REPLACE HEADER if(!::HttpAddRequestHeaders( _hRequest, __HTTP_ACCEPT, strlen(__HTTP_ACCEPT), HTTP_ADDREQ_FLAG_REPLACE)) throw "additional header failed..."; if(!::HttpAddRequestHeaders( _hRequest, szContentType, strlen(szContentType), HTTP_ADDREQ_FLAG_ADD_IF_NEW)) throw "additional header failed..."; // COOKIE ADD if(_listcookies.size()>0){ string szurl; switch(_t) { case w3http: szurl="http://"; break; case w3https: szurl="https://"; break; } szurl+=_szaddress.c_str(); if(!( (_t==w3http && _nport==INTERNET_DEFAULT_HTTP_PORT) || (_t==w3https && _nport==INTERNET_DEFAULT_HTTPS_PORT) )){ char tmp[10]="\0"; sprintf(tmp, ":%d", _nport); szurl+=tmp; } szurl+=szuri; for(list<HTTP_COOKIE*>::iterator it=_listcookies.begin(); it!=_listcookies.end(); it++){ HTTP_COOKIE *pc=reinterpret_cast<HTTP_COOKIE*>(*it); if(!::InternetSetCookie(szurl.c_str(), pc->name.c_str(), pc->value.c_str())) throw "add cookie failed..."; } } // build multi-parts/form-data len=AllocMultiPartsFormData(buf, "--MULTI-PARTS-FORM-DATA-BOUNDARY"); // ADD HEADER CONTENT LENGTH char szcl[__DEFAULT_BUF_SIZE]="\0"; sprintf(szcl, "Content-Length: %d\r\n", len); if(!::HttpAddRequestHeaders( _hRequest, szcl, strlen(szcl), HTTP_ADDREQ_FLAG_ADD_IF_NEW)) throw "additional header failed..."; // SEND REQUEST WITH HttpSendRequestEx and InternetWriteFile static INTERNET_BUFFERS InternetBufferIn={0}; InternetBufferIn.dwStructSize=sizeof(INTERNET_BUFFERS); InternetBufferIn.Next=NULL; if(!::HttpSendRequestEx(_hRequest, &InternetBufferIn, NULL, HSR_INITIATE, 0)){ // free FreeMultiPartsFormData(buf); throw "request failed"; } unsigned long nout=0; DWORD dwOutPostBufferLength=0; if(!::InternetWriteFile(_hRequest, buf, len, &nout)){ // free FreeMultiPartsFormData(buf); throw "request failed"; } if(!::HttpEndRequest(_hRequest, NULL, HSR_INITIATE, 0)){ // free FreeMultiPartsFormData(buf); throw "request failed"; } // free multi-parts/form-data FreeMultiPartsFormData(buf); return true; } unsigned long W3Client::QueryCookie(unsigned char *buf, unsigned long len, unsigned long idx /*=0*/){ if(!::HttpQueryInfo(_hRequest, HTTP_QUERY_SET_COOKIE, buf, &len, &idx)){ __w3cexcept(_szaddress.c_str(), _nport, _t, _szuri.c_str(), "query cookie failed..."); return 0; } return len; } unsigned long W3Client::QueryContentLength(){ char szt[__DEFAULT_BUF_SIZE]="\0"; unsigned long nread=__DEFAULT_BUF_SIZE; memset(szt, 0x00, __DEFAULT_BUF_SIZE); if(!::HttpQueryInfo(_hRequest, HTTP_QUERY_CONTENT_LENGTH , szt, reinterpret_cast<unsigned long*>(&nread), NULL)){ __w3cexcept(_szaddress.c_str(), _nport, _t, _szuri.c_str(), "query content-length failed..."); return 0; } return atol(szt); } const char * W3Client::QueryContentType(){ static char szt[__DEFAULT_BUF_SIZE]="\0"; unsigned long nread=__DEFAULT_BUF_SIZE; memset(szt, 0x00, __DEFAULT_BUF_SIZE); if(!::HttpQueryInfo(_hRequest, HTTP_QUERY_CONTENT_TYPE , szt, reinterpret_cast<unsigned long*>(&nread), NULL)){ __w3cexcept(_szaddress.c_str(), _nport, _t, _szuri.c_str(), "query content-type failed..."); return NULL; } return const_cast<char*>(szt); } unsigned int W3Client::QueryResult() { char szt[__DEFAULT_BUF_SIZE]="\0"; unsigned long nread=__DEFAULT_BUF_SIZE; memset(szt, 0x00, __DEFAULT_BUF_SIZE); if(!::HttpQueryInfo(_hRequest, HTTP_QUERY_STATUS_CODE , szt, reinterpret_cast<unsigned long*>(&nread), NULL)){ __w3cexcept(_szaddress.c_str(), _nport, _t, _szuri.c_str(), "query status code failed..."); return 404; } return atoi(szt); } unsigned long W3Client::QueryRawHeader(unsigned char *buf, unsigned long len){ if(!::HttpQueryInfo(_hRequest, HTTP_QUERY_RAW_HEADERS_CRLF, buf, &len, NULL)){ __w3cexcept(_szaddress.c_str(), _nport, _t, _szuri.c_str(), "query cookie failed..."); return 0; } return len; } unsigned long W3Client::Response(unsigned char *buf, unsigned long len){ unsigned long nread=0; try{ if(!_hRequest) throw "connection failed..."; if(!::InternetReadFile(_hRequest, buf, len, &nread)) throw "response failed..."; }catch(const char *szm){ ::InternetCloseHandle(_hRequest); _hRequest=NULL; __w3cexcept(_szaddress.c_str(), _nport, _t, _szuri.c_str(), szm); }catch(...){ ::InternetCloseHandle(_hRequest); _hRequest=NULL; __w3cexcept(_szaddress.c_str(), _nport, _t, _szuri.c_str(), "unknown exception..."); } return nread; } bool W3Client::GetFile(const char *szuri, const char *szfile, bool ascii /*=false*/){ bool r=true; try{ if(!_hOpen || !_hConnection) throw "connection failed"; _hRequest=::FtpOpenFile(_hConnection, szuri, GENERIC_READ, (ascii? INTERNET_FLAG_TRANSFER_ASCII : INTERNET_FLAG_TRANSFER_BINARY), NULL); if(!_hRequest || _hRequest==INVALID_HANDLE_VALUE) throw "request failed..."; HANDLE f=::CreateFile(szfile, GENERIC_WRITE, FILE_SHARE_WRITE, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); unsigned char buf[__DEFAULT_BUF_SIZE]="\0"; unsigned long nread=0; if(f){ while(::InternetReadFile(_hRequest, buf, __DEFAULT_BUF_SIZE, &nread) && nread>0) ::WriteFile(f, buf, nread, &nread, NULL); ::CloseHandle(f); } }catch(const char *szm){ r=false; __w3cexcept(_szaddress.c_str(), _nport, _t, szuri, szm); }catch(...){ r=false; __w3cexcept(_szaddress.c_str(), _nport, _t, szuri, "unknown exception..."); } ::InternetCloseHandle(_hRequest); _hRequest=NULL; return r; } unsigned long W3Client::GetFile(const char *szuri, unsigned char *buf, unsigned long len, bool ascii /*=false*/){ unsigned long nread=0; try{ if(!_hOpen || !_hConnection) throw "connection failed"; if(!_hRequest) _hRequest=::FtpOpenFile(_hConnection, szuri, GENERIC_READ, (ascii? INTERNET_FLAG_TRANSFER_ASCII : INTERNET_FLAG_TRANSFER_BINARY), NULL); if(!_hRequest || _hRequest==INVALID_HANDLE_VALUE) throw "request failed..."; if(!::InternetReadFile(_hRequest, buf, len, &nread) || nread<=0){ ::InternetCloseHandle(_hRequest); _hRequest=NULL; } }catch(const char *szm){ nread=0; __w3cexcept(_szaddress.c_str(), _nport, _t, szuri, szm); }catch(...){ nread=0; __w3cexcept(_szaddress.c_str(), _nport, _t, szuri, "unknown exception..."); } return nread; } bool W3Client::PutFile(const char *szuri, const char *szfile, bool ascii /*=false*/){ bool r=true; try{ if(!_hOpen || !_hConnection) throw "connection failed"; _hRequest=::FtpOpenFile(_hConnection, szuri, GENERIC_WRITE, (ascii? INTERNET_FLAG_TRANSFER_ASCII : INTERNET_FLAG_TRANSFER_BINARY), NULL); if(!_hRequest || _hRequest==INVALID_HANDLE_VALUE) throw "request failed..."; HANDLE f=::CreateFile(szfile, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); unsigned char buf[__DEFAULT_BUF_SIZE]="\0"; unsigned long nread=0; if(f){ while(::ReadFile(f, buf, __DEFAULT_BUF_SIZE, &nread, 0) && nread>0) ::InternetWriteFile(_hRequest, buf, nread, &nread); ::CloseHandle(f); } }catch(const char *szm){ r=false; __w3cexcept(_szaddress.c_str(), _nport, _t, szuri, szm); }catch(...){ r=false; __w3cexcept(_szaddress.c_str(), _nport, _t, szuri, "unknown exception..."); } ::InternetCloseHandle(_hRequest); _hRequest=NULL; return r; } unsigned long W3Client::PutFile(const char *szuri, unsigned char *buf, unsigned long len, bool ascii){ unsigned long nread=0; try{ if(!_hOpen || !_hConnection) throw "connection failed"; if(!_hRequest) _hRequest=::FtpOpenFile(_hConnection, szuri, GENERIC_WRITE, (ascii? INTERNET_FLAG_TRANSFER_ASCII : INTERNET_FLAG_TRANSFER_BINARY), NULL); if(!_hRequest || _hRequest==INVALID_HANDLE_VALUE) throw "request failed..."; if(!::InternetWriteFile(_hRequest, buf, nread, &nread) || nread<=0){ ::InternetCloseHandle(_hRequest); _hRequest=NULL; } }catch(const char *szm){ nread=0; __w3cexcept(_szaddress.c_str(), _nport, _t, szuri, szm); }catch(...){ nread=0; __w3cexcept(_szaddress.c_str(), _nport, _t, szuri, "unknown exception..."); } return nread; } void __w3curlparse(const char *szurl, char *szprotocol, char *szuser, char *szpassword, char *szaddress, unsigned long &nport, char *szuri){ char szport[1024]="\0"; unsigned long npos=0; bool bflag=false; while(strlen(szurl)>0 && npos<strlen(szurl) && strncmp((szurl+npos), ":", 1)) ++npos; if(!strncmp((szurl+npos+1), "/", 1)){ // is protocol if(szprotocol){ strncpy(szprotocol, szurl, npos); szprotocol[npos]=0; } bflag=true; }else{ // is host if(szprotocol){ strncpy(szprotocol, "http", 4); szprotocol[5]='\0'; } } unsigned long nsp=0, usp=0; if(bflag){ usp=nsp=npos+=3; }else{ usp=nsp=npos=0; } while(strlen(szurl)>0 && usp<strlen(szurl) && strncmp((szurl+usp), "@", 1)) ++usp; if(usp<strlen(szurl)){ // find username and find password unsigned long ssp=nsp; while(strlen(szurl)>0 && npos<strlen(szurl) && strncmp((szurl+ssp), ":", 1)) ++ssp; if(ssp<usp){// find strncpy(szuser, szurl+nsp, ssp-nsp); szuser[ssp-nsp+1]='\0'; strncpy(szpassword, szurl+ssp+1, usp-ssp-1); szpassword[usp-ssp]='\0'; } nsp=npos=usp+1; } bflag=false; while(strlen(szurl)>0 && npos<strlen(szurl) && strncmp((szurl+npos), "/", 1)) ++npos; unsigned long nf=nsp; for(;nf<=npos;nf++){ if(!strncmp((szurl+nf), ":", 1)){ // find PORT bflag=true; break; } } if(bflag){ char sztmp[1024]="\0"; strncpy(sztmp, (szurl+nf+1), npos-nf); nport=atol(sztmp); strncpy(szaddress, (szurl+nsp), nf-nsp); }else if(!strcmp(szprotocol,"https")){ nport=INTERNET_DEFAULT_HTTPS_PORT; strncpy(szaddress, (szurl+nsp), npos-nsp); }else if(!strcmp(szprotocol, "ftp")){ nport=INTERNET_DEFAULT_FTP_PORT; strncpy(szaddress, (szurl+nsp), npos-nsp); }else { nport=INTERNET_DEFAULT_HTTP_PORT; strncpy(szaddress, (szurl+nsp), npos-nsp); } if(npos<strlen(szurl)){ // find URI strncpy(szuri, (szurl+npos), strlen(szurl)-npos); }else{ szuri[0]='/'; szuri[1]='\0'; } return; } // Asynchronized www client bool AsyncW3Client::Connect(const char *szaddress, INTERNET_STATUS_CALLBACK lpfn, const char *szuser /*=NULL*/, const char *szpassword /*=NULL*/, const char *szagent /*=__W3_DEFAULT_AGENT*/){ char szp[__DEFAULT_BUF_SIZE]="\0", szus[__DEFAULT_BUF_SIZE]="\0", szpw[__DEFAULT_BUF_SIZE]="\0"; char sza[__DEFAULT_BUF_SIZE]="\0", szuri[__DEFAULT_BUF_SIZE]="\0"; unsigned long port=0; __w3curlparse(szaddress, szp, szus, szpw, sza, port, szuri); w3t wt; if(!strncmp(szp, "https", 5)) wt=w3https; else if(!strncmp(szp, "http", 4)) wt=w3http; else if(!strncmp(szp, "ftp", 3)) wt=w3ftp; _szuri=szuri; return Connect(sza, port, lpfn, ((szuser || (!szuser && strlen(szus)==0))? szuser : szus), ((szpassword || (!szpassword && strlen(szpw)==0))? szpassword : szpw), wt, szagent); } bool AsyncW3Client::Connect( const char *szaddress, long nport, INTERNET_STATUS_CALLBACK lpfn, const char *szuser /*=NULL*/, const char *szpassword /*=NULL*/, w3t t /*=w3http*/, const char *szagent /*=__W3_DEFAULT_AGENT*/){ bool r=true; try{ _hOpen=::InternetOpen( szagent, // agent INTERNET_OPEN_TYPE_PRECONFIG, // access type NULL, // proxy NULL, // proxy by pass INTERNET_FLAG_ASYNC); // flags if(!_hOpen || _hOpen==INVALID_HANDLE_VALUE) throw "open internet failed..."; INTERNET_STATUS_CALLBACK pc=::InternetSetStatusCallback(_hOpen, lpfn); //if(!pc || pc==INTERNET_INVALID_STATUS_CALLBACK ) // throw "set status call-back functino failed..."; switch(t) { case w3ftp: _hConnection=::InternetConnect( _hOpen, szaddress, (nport? nport: INTERNET_DEFAULT_FTP_PORT), szuser, szpassword, INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, reinterpret_cast<unsigned long>(this)); break; case w3http: _hConnection=::InternetConnect( _hOpen, szaddress, (nport? nport: INTERNET_DEFAULT_HTTP_PORT), szuser, szpassword, INTERNET_SERVICE_HTTP, 0, reinterpret_cast<unsigned long>(this)); break; case w3https: _hConnection=::InternetConnect( _hOpen, szaddress, (nport? nport: INTERNET_DEFAULT_HTTPS_PORT), szuser, szpassword, INTERNET_SERVICE_HTTP, 0, reinterpret_cast<unsigned long>(this)); break; } if(!_hConnection || _hConnection==INVALID_HANDLE_VALUE) throw "connect failed..."; if(::InternetAttemptConnect(NULL)!=ERROR_SUCCESS) throw "connect failed..."; _szaddress=szaddress; if(!nport){ switch(t) { case w3ftp: _nport=INTERNET_DEFAULT_FTP_PORT; break; case w3http: _nport=INTERNET_DEFAULT_HTTP_PORT; break; case w3https: _nport=INTERNET_DEFAULT_HTTPS_PORT; break; } }else _nport=nport; _t=t; if(szuser) _szuser=szuser; if(szpassword) _szpassword=szpassword; InitializeCookies(); InitializePostArguments(); }catch(const char *szm){ r=false; if(_hOpen || _hOpen!=INVALID_HANDLE_VALUE) ::InternetCloseHandle(_hOpen); if(_hConnection || _hConnection!=INVALID_HANDLE_VALUE) ::InternetCloseHandle(_hConnection); __w3cexcept(szaddress, nport, t, szm); }catch(...){ r=false; if(_hOpen || _hOpen!=INVALID_HANDLE_VALUE) ::CloseHandle(_hOpen); if(_hConnection || _hConnection!=INVALID_HANDLE_VALUE) ::CloseHandle(_hConnection); __w3cexcept(szaddress, nport, t, "unknown exception..."); } return r; } bool AsyncW3Client::RequestGet(const char *szuri, const char *szref /*=NULL*/){ static LPCTSTR szAcceptType=TEXT(__HTTP_ACCEPT_TYPE); if(!_hConnection || _hConnection==INVALID_HANDLE_VALUE) throw "handle not opened..."; _hRequest=::HttpOpenRequest( _hConnection, __HTTP_VERB_GET, // HTTP Verb szuri, // Object Name HTTP_VERSION, // Version szref, // Reference &szAcceptType, // Accept Type INTERNET_FLAG_NO_CACHE_WRITE | (_t==w3https? INTERNET_FLAG_SECURE:0), reinterpret_cast<unsigned long>(this)); // context call-back point if(!_hRequest || _hRequest==INVALID_HANDLE_VALUE) throw "request failed..."; // REPLACE HEADER if(!::HttpAddRequestHeaders( _hRequest, __HTTP_ACCEPT, strlen(__HTTP_ACCEPT), HTTP_ADDREQ_FLAG_REPLACE)) throw "additional header failed..."; // COOKIE ADD if(_listcookies.size()>0){ string szurl; switch(_t) { case w3http: szurl="http://"; break; case w3https: szurl="https://"; break; } szurl+=_szaddress.c_str(); if(!((_t==w3http && _nport==INTERNET_DEFAULT_HTTP_PORT) || (_t==w3https && _nport==INTERNET_DEFAULT_HTTPS_PORT))){ char tmp[10]="\0"; sprintf(tmp, ":%d", _nport); szurl+=tmp; } szurl+=szuri; for(list<HTTP_COOKIE*>::iterator it=_listcookies.begin(); it!=_listcookies.end(); it++){ HTTP_COOKIE *pc=reinterpret_cast<HTTP_COOKIE*>(*it); if(!::InternetSetCookie(szurl.c_str(), pc->name.c_str(), pc->value.c_str())) throw "add cookie failed..."; } } // SEND REQUEST if(!::HttpSendRequest( _hRequest, // handle by returned HttpOpenRequest NULL, // additional HTTP header 0, // additional HTTP header length NULL, // additional data in HTTP Post or HTTP Put 0)// additional data length && ::GetLastError()!=ERROR_IO_PENDING ){ throw "asynchronized request failed..."; } return true; } bool AsyncW3Client::RequestPost(const char *szuri, const char *szref /*=NULL*/){ static LPCTSTR szAcceptType=__HTTP_ACCEPT_TYPE; static LPCTSTR szContentType="Content-Type: application/x-www-form-urlencoded\r\n"; unsigned char *buf=NULL; unsigned long len=0; if(!_hConnection || _hConnection==INVALID_HANDLE_VALUE) throw "handle not opened..."; _hRequest=::HttpOpenRequest( _hConnection, __HTTP_VERB_POST, // HTTP Verb szuri, // Object Name HTTP_VERSION, // Version szref, // Reference &szAcceptType, // Accept Type INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_FORMS_SUBMIT | (_t==w3https? INTERNET_FLAG_SECURE:0), reinterpret_cast<unsigned long>(this)); // context call-back point if(!_hRequest || _hRequest==INVALID_HANDLE_VALUE) throw "request failed..."; // REPLACE HEADER if(!::HttpAddRequestHeaders( _hRequest, __HTTP_ACCEPT, strlen(__HTTP_ACCEPT), HTTP_ADDREQ_FLAG_REPLACE)) throw "additional header failed..."; // COOKIE ADD if(_listcookies.size()>0){ string szurl; switch(_t) { case w3http: szurl="http://"; break; case w3https: szurl="https://"; break; } szurl+=_szaddress.c_str(); if(!((_t==w3http && _nport==INTERNET_DEFAULT_HTTP_PORT) || (_t==w3https && _nport==INTERNET_DEFAULT_HTTPS_PORT))){ char tmp[10]="\0"; sprintf(tmp, ":%d", _nport); szurl+=tmp; } szurl+=szuri; for(list<HTTP_COOKIE*>::iterator it=_listcookies.begin(); it!=_listcookies.end(); it++){ HTTP_COOKIE *pc=reinterpret_cast<HTTP_COOKIE*>(*it); if(!::InternetSetCookie(szurl.c_str(), pc->name.c_str(), pc->value.c_str())) throw "add cookie failed..."; } } // GET POST ARGUMENTS buf=reinterpret_cast<unsigned char*>(::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, GetPostArgumentsLength()+1)); len=GetPostData(buf, GetPostArgumentsLength()+1); // SEND REQUEST WITH HttpSendRequestEx and InternetWriteFile static INTERNET_BUFFERS InternetBufferIn={0}; InternetBufferIn.dwStructSize=sizeof(INTERNET_BUFFERS); InternetBufferIn.Next=NULL; InternetBufferIn.lpcszHeader=szContentType; InternetBufferIn.dwHeadersLength=strlen(szContentType); InternetBufferIn.lpvBuffer=buf; InternetBufferIn.dwBufferLength=len; if(!::HttpSendRequestEx(_hRequest, &InternetBufferIn, NULL, HSR_INITIATE, reinterpret_cast<unsigned long>(this)) && ::GetLastError()!=ERROR_IO_PENDING ){ // free ::HeapFree(::GetProcessHeap(), 0, buf); throw "request failed"; } WaitCompleteRequest(); if(!::HttpEndRequest(_hRequest, NULL, HSR_ASYNC | HSR_INITIATE, reinterpret_cast<unsigned long>(this)) && ::GetLastError()!=ERROR_IO_PENDING ){ // free ::HeapFree(::GetProcessHeap(), 0, buf); throw "request failed"; } ::HeapFree(::GetProcessHeap(), 0, buf); return true; } bool AsyncW3Client::RequestPost2(const char *szuri, const char *szref /*=NULL*/){ static LPCTSTR szAcceptType=__HTTP_ACCEPT_TYPE; static LPCTSTR szContentType="Content-Type: multipart/form-data; boundary=--MULTI-PARTS-FORM-DATA-BOUNDARY\r\n"; unsigned char *buf=NULL; unsigned long len=0; if(!_hConnection || _hConnection==INVALID_HANDLE_VALUE) throw "handle not opened..."; _hRequest=::HttpOpenRequest( _hConnection, __HTTP_VERB_POST, // HTTP Verb szuri, // Object Name HTTP_VERSION, // Version szref, // Reference &szAcceptType, // Accept Type INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_FORMS_SUBMIT | (_t==w3https? INTERNET_FLAG_SECURE:0), reinterpret_cast<unsigned long>(this)); // context call-back point if(!_hRequest || _hRequest==INVALID_HANDLE_VALUE) throw "request failed..."; // REPLACE HEADER if(!::HttpAddRequestHeaders( _hRequest, __HTTP_ACCEPT, strlen(__HTTP_ACCEPT), HTTP_ADDREQ_FLAG_REPLACE)) throw "additional header failed..."; if(!::HttpAddRequestHeaders( _hRequest, szContentType, strlen(szContentType), HTTP_ADDREQ_FLAG_ADD_IF_NEW)) throw "additional header failed..."; // COOKIE ADD if(_listcookies.size()>0){ string szurl; switch(_t) { case w3http: szurl="http://"; break; case w3https: szurl="https://"; break; } szurl+=_szaddress.c_str(); if(!( (_t==w3http && _nport==INTERNET_DEFAULT_HTTP_PORT) || (_t==w3https && _nport==INTERNET_DEFAULT_HTTPS_PORT) )){ char tmp[10]="\0"; sprintf(tmp, ":%d", _nport); szurl+=tmp; } szurl+=szuri; for(list<HTTP_COOKIE*>::iterator it=_listcookies.begin(); it!=_listcookies.end(); it++){ HTTP_COOKIE *pc=reinterpret_cast<HTTP_COOKIE*>(*it); if(!::InternetSetCookie(szurl.c_str(), pc->name.c_str(), pc->value.c_str())) throw "add cookie failed..."; } } // build multi-parts/form-data len=AllocMultiPartsFormData(buf, "--MULTI-PARTS-FORM-DATA-BOUNDARY"); // ADD HEADER CONTENT LENGTH char szcl[__DEFAULT_BUF_SIZE]="\0"; sprintf(szcl, "Content-Length: %d\r\n", len); if(!::HttpAddRequestHeaders( _hRequest, szcl, strlen(szcl), HTTP_ADDREQ_FLAG_ADD_IF_NEW)) throw "additional header failed..."; // SEND REQUEST WITH HttpSendRequestEx and InternetWriteFile static INTERNET_BUFFERS InternetBufferIn={0}; InternetBufferIn.dwStructSize=sizeof(INTERNET_BUFFERS); InternetBufferIn.Next=NULL; InternetBufferIn.lpvBuffer=buf; InternetBufferIn.dwBufferLength=len; if(!::HttpSendRequestEx(_hRequest, &InternetBufferIn, NULL, HSR_INITIATE, reinterpret_cast<unsigned long>(this)) && ::GetLastError()!=ERROR_IO_PENDING ){ // free FreeMultiPartsFormData(buf); throw "request failed"; } WaitCompleteRequest(); if(!::HttpEndRequest(_hRequest, NULL, HSR_ASYNC | HSR_INITIATE, reinterpret_cast<unsigned long>(this)) && ::GetLastError()!=ERROR_IO_PENDING ){ // free FreeMultiPartsFormData(buf); throw "request failed"; } // free multi-parts/form-data FreeMultiPartsFormData(buf); return true; } void AsyncW3Client::SetCompleteRequest(){ ::SetEvent(_hCompleteRequestEvent); } bool AsyncW3Client::WaitCompleteRequest(unsigned long ntime /*=INFINITE*/ ){ if(!_hCompleteRequestEvent || _hCompleteRequestEvent==INVALID_HANDLE_VALUE) false; return ::WaitForSingleObject(_hCompleteRequestEvent, ntime)==WAIT_OBJECT_0? true:false; }
[ "shenjian74@gmail.com" ]
shenjian74@gmail.com
eb0575170104bb080593ee48e49671160f42b767
3a0f470565353553294a43143ef10af11f85f0b2
/libsdca/src/matlab/mex_gd.cpp
d3c4ee73d30a8b31dbc3bc003d67366ba93f189f
[]
no_license
djchu/topkmsvm
ad2c146c0e2371ebc276f7abef1a0b0522107b4f
8d17418309f9a8d96dbb3d95f9d417c28cc1fd14
refs/heads/master
2021-04-26T22:23:11.363676
2018-04-27T08:19:52
2018-04-27T08:19:52
124,082,466
4
0
null
null
null
null
UTF-8
C++
false
false
13,978
cpp
/** * This is a simple batch gradient descent with * the Armijo line search; it is not a part of libsdca. **/ #include <iostream> #include "mex_util.h" #include "solve/solvedef.h" #include "util/util.h" #ifndef MEX_GD #define MEX_GD "mex_gd" #endif #ifndef LIBSDCA_VERSION #define LIBSDCA_VERSION "0.0.0" #endif using namespace sdca; inline void printUsage() { mexPrintf("Usage: model = %s(X,Y,opts);\n", MEX_GD); } template <typename Data> double grad_topk_softmax_nonconvex( const size_type num_dimensions, const size_type num_examples, const size_type num_classes, const Data* X, const std::vector<size_type>& Y, const double C, const size_type k, const Data* W, Data* grad, std::vector<Data>& scores, std::vector<Data>& scratch, std::vector<size_type>& idx ) { typedef typename std::vector<size_type>::difference_type diff_t; auto ifirst = idx.begin() + 1; // ground truth at 0, start at 1 auto ikth = idx.begin() + static_cast<diff_t>(k); // first + k - 1 auto ilast = idx.end(); auto kth = scores.begin() + static_cast<diff_t>(k); auto last = scores.end(); const blas_int D = static_cast<blas_int>(num_dimensions); const blas_int T = static_cast<blas_int>(num_classes); double objective(0); sdca_blas_copy(D * T, W, grad); for (size_type i = 0; i < num_examples; ++i) { const Data* x_i = X + num_dimensions * i; const size_type label = Y[i]; std::iota(idx.begin(), idx.end(), 0); // Compute scores sdca_blas_gemv(D, T, W, x_i, &scratch[0], CblasTrans); std::swap(idx[0], idx[label]); // Find k largest elements (re-order indexes) std::nth_element(ifirst, ikth, ilast, [&scratch](size_type i1, size_type i2) { return scratch[i1] > scratch[i2]; }); // Compute the re-ordered scores, starting with the kth largest one scores[0] = scratch[label]; for (size_type ix = k; ix < num_classes; ++ix) { scores[ix] = scratch[idx[ix]]; } // Pre-compute exp(score_j - M), where M is the kth largest score Data M(*kth); // kth is the maximum in [kth, last) std::for_each(kth + 1, last, [=](Data &x){ x = std::exp(x - M); }); // Compute the log(1 + sum exp) loss and the intermediate terms double s = std::accumulate(kth + 1, last, 0.0); double a = static_cast<double>(M) - static_cast<double>(scores[0]); double b = std::exp(-a); objective += a + std::log1p(b + s); // Coefficients for the gradient std::for_each(ifirst, ikth, [&](size_type ix){ scratch[ix] = 0; }); double coeff = 1 / (1 + s + b); scratch[idx[k]] = static_cast<Data>(coeff); // exp(kth - gt) / (1 + Z) scratch[label] = static_cast<Data>(- (1 + s) * coeff); // - Z / (1 + Z) for (size_type ix = k + 1; ix < num_classes; ++ix) { scratch[idx[ix]] = scores[ix] * static_cast<Data>(coeff); } // Rank-1 update of the gradient sdca_blas_ger(D, T, static_cast<Data>(C), x_i, &scratch[0], grad); } objective *= C; objective += 0.5 * static_cast<double>(sdca_blas_dot(D * T, W, W)); return objective; } template <typename Data> inline double eval_topk_softmax_nonconvex( const size_type num_dimensions, const size_type num_examples, const size_type num_classes, const Data* X, const std::vector<size_type>& Y, const double C, const size_type k, const Data* W, std::vector<Data>& scores ) { typedef typename std::vector<size_type>::difference_type diff_t; auto first = scores.begin() + 1; // ground truth at 0, start at 1 auto kth = scores.begin() + static_cast<diff_t>(k); // first + k - 1 auto last = scores.end(); const blas_int D = static_cast<blas_int>(num_dimensions); const blas_int T = static_cast<blas_int>(num_classes); double objective(0); for (size_type i = 0; i < num_examples; ++i) { const Data* x_i = X + num_dimensions * i; const size_type label = Y[i]; // Compute scores sdca_blas_gemv(D, T, W, x_i, &scores[0], CblasTrans); std::swap(scores[0], scores[label]); // Find k largest elements std::nth_element(first, kth, last, std::greater<Data>()); // Subtract the ground truth score for the T-k remaining tasks Data gt(scores[0]); std::for_each(kth, last, [=](Data &x){ x -= gt; }); // Compute the log(1 + sum exp) loss objective += log_1_sum_exp(kth, last); } objective *= C; objective += 0.5 * static_cast<double>(sdca_blas_dot(D * T, W, W)); return objective; } inline void log_info_status( const std::string message, const size_type epoch, const double objective, const double optimality, const double wall_time, const double cpu_time ) { LOG_INFO << message << std::endl << "epoch: " << std::setw(3) << epoch << std::setw(0) << ", " "objective: " << objective << ", " "optimality: " << optimality << ", " "wall_time: " << wall_time << ", " "cpu_time: " << cpu_time << std::endl; } inline void log_verbose_progress( const size_type epoch, const size_type fun_evals, const double step_size, const double objective, const double optimality, const double wall_time, const double cpu_time ) { LOG_VERBOSE << " " "epoch: " << std::setw(3) << epoch << std::setw(0) << ", " "fun_evals: " << std::setw(3) << fun_evals << std::setw(0) << ", " "step_size: " << step_size << ", " "objective: " << objective << ", " "optimality: " << optimality << ", " "wall_time: " << wall_time << ", " "cpu_time: " << cpu_time << std::endl; } template <typename Data> inline bool check_stopping_conditions( const solver_context<Data>& context, const size_type epoch, const size_type fun_evals, const double step_size, const double primal, const double optimality, stopwatch_wall& wall, stopwatch_cpu& cpu ) { wall.stop(); cpu.stop(); log_verbose_progress(epoch, fun_evals, step_size, primal, optimality, wall.elapsed, cpu.elapsed); // Check stopping criteria if (optimality <= context.criteria.epsilon) { log_info_status("First order optimality condition is met.", epoch, primal, optimality, wall.elapsed, cpu.elapsed); return true; } else if (epoch >= context.criteria.max_epoch) { log_info_status("Maximum number of epochs exceeded.", epoch, primal, optimality, wall.elapsed, cpu.elapsed); return true; } else if (context.criteria.max_cpu_time > 0 && cpu.elapsed >= context.criteria.max_cpu_time) { log_info_status("Maximum CPU time exceeded.", epoch, primal, optimality, wall.elapsed, cpu.elapsed); return true; } else if (context.criteria.max_wall_time > 0 && wall.elapsed >= context.criteria.max_wall_time) { log_info_status("Maximum wall clock time exceeded.", epoch, primal, optimality, wall.elapsed, cpu.elapsed); return true; } wall.resume(); cpu.resume(); return false; } /** * Optimize * F(W) = C * \sum_i f_i(W, x_i, y_i) + 0.5 * ||W||_F^2, * where * f_i(W,x,y) = \log(1 + \sum_{j = k, [j] \neq y}^T \exp(a_{[j]})), * a_j = w_j^T x - w_y^T x, * a_{[1]} \geq ... \geq a_{[T]}. * I.e. the inner sum goes over all tasks, except the ground truth * and the ones with the k-1 largest scores (these are ignored in the loss). **/ template <typename Data> inline void min_topk_softmax_nonconvex( const solver_context<Data>& context, const double C, const size_type k, Data* grad, Data* W_tmp, double& primal, double& optimality ) { // Input data dataset<Data> trn_data = context.datasets.front(); const size_type num_dimensions = trn_data.num_dimensions; const size_type num_examples = trn_data.num_examples; const size_type num_classes = trn_data.num_classes; const Data* X = trn_data.data; const std::vector<size_type>& Y = trn_data.labels; const blas_int DT = static_cast<blas_int>(num_dimensions * num_classes); Data* W = context.primal_variables; // Temporary memory std::vector<Data> scores(num_classes); std::vector<Data> scratch(num_classes); std::vector<size_type> idx(num_classes); // Optimization variables size_type epoch(0), fun_evals(0); double step_size(0), min_step(1e-9), suff_decrease(1e-5), primal_tmp(0); stopwatch_wall wall; stopwatch_cpu cpu; wall.start(); cpu.start(); // Evaluate initial point primal = grad_topk_softmax_nonconvex( num_dimensions, num_examples, num_classes, X, Y, C, k, W, grad, scores, scratch, idx); ++fun_evals; optimality = sdca_blas_nrm2(DT, grad); if (check_stopping_conditions(context, epoch, fun_evals, step_size, primal, optimality, wall, cpu)) return; double step_size_before(0); step_size = std::max(min_step, std::min(1.0, 1 / optimality)); for (;;) { ++epoch; if (step_size == step_size_before) { step_size *= 2.0; } step_size_before = step_size; // Armijo line search double coeff = suff_decrease * optimality; // * optimality; for (;;) { sdca_blas_copy(DT, W, W_tmp); sdca_blas_axpy(DT, static_cast<Data>(-step_size), grad, W_tmp); primal_tmp = eval_topk_softmax_nonconvex( num_dimensions, num_examples, num_classes, X, Y, C, k, W_tmp, scores); ++fun_evals; if (primal_tmp <= primal - step_size * coeff) { break; } step_size *= 0.5; if (step_size < min_step) { log_info_status("Line search failed.", epoch, primal, optimality, wall.elapsed_now(), cpu.elapsed_now()); return; } } // Compute the objective value and the gradient at a new point sdca_blas_copy(DT, W_tmp, W); primal = grad_topk_softmax_nonconvex( num_dimensions, num_examples, num_classes, X, Y, C, k, W, grad, scores, scratch, idx); ++fun_evals; optimality = sdca_blas_nrm2(DT, grad); if (check_stopping_conditions(context, epoch, fun_evals, step_size, primal, optimality, wall, cpu)) return; } } template <typename Data> inline void mex_main( const mxArray* data, const mxArray* labels, const mxArray* opts, mxArray* plhs[] ) { model_info<mxArray*> info; solver_context<Data> context; context.is_dual = false; // dual version (i.e. Gram matrix) is not supported set_datasets(data, labels, context); set_stopping_criteria(opts, context); auto trn_data = context.datasets.front(); mxArray *mxW = mxDuplicateOrCreateMatrixField(opts, "W", trn_data.num_dimensions, trn_data.num_classes, mex_class<Data>::id()); mxCheckCreated(mxW, "W"); context.primal_variables = static_cast<Data*>(mxGetData(mxW)); info.add("W", mxW); mxArray* mxGrad = mxCreateNumericMatrix(trn_data.num_dimensions, trn_data.num_classes, mex_class<Data>::id(), mxREAL); mxCheckCreated(mxGrad, "gradient"); info.add("grad", mxGrad); mxArray* mxWTmp = mxCreateNumericMatrix(trn_data.num_dimensions, trn_data.num_classes, mex_class<Data>::id(), mxREAL); mxCheckCreated(mxWTmp, "W_tmp"); info.add("is_dual", mxCreateScalar(context.is_dual)); info.add("num_dimensions", mxCreateScalar(trn_data.num_dimensions)); info.add("num_examples", mxCreateScalar(trn_data.num_examples)); info.add("num_classes", mxCreateScalar(trn_data.num_classes)); std::string objective = mxGetFieldValueOrDefault( opts, "objective", std::string("l2_topk_softmax_nonconvex")); info.add("objective", mxCreateString(objective.c_str())); double c = mxGetFieldValueOrDefault<double>(opts, "c", 1); mxCheck<double>(std::greater<double>(), c, 0, "c"); double num_examples(static_cast<double>(trn_data.num_examples)); double C = mxGetFieldValueOrDefault<double>(opts, "C", c / num_examples); mxCheck<double>(std::greater<double>(), C, 0, "C"); c = (C != c / num_examples) ? C * num_examples : c; info.add("c", mxCreateScalar(c)); info.add("C", mxCreateScalar(C)); size_type k = mxGetFieldValueOrDefault<size_type>(opts, "k", 1); mxCheckRange<size_type>(k, 1, trn_data.num_classes - 1, "k"); info.add("k", mxCreateScalar(k)); double primal(0), optimality(0); if (objective == "l2_topk_softmax_nonconvex") { min_topk_softmax_nonconvex(context, C, k, static_cast<Data*>(mxGetData(mxGrad)), static_cast<Data*>(mxGetData(mxWTmp)), primal, optimality); } else { mexErrMsgIdAndTxt( err_id[err_objective], err_msg[err_objective], objective.c_str()); } info.add("primal", mxCreateScalar(primal)); info.add("optimality", mxCreateScalar(optimality)); info.add("max_epoch", mxCreateScalar(context.criteria.max_epoch)); info.add("max_cpu_time", mxCreateScalar(context.criteria.max_cpu_time)); info.add("max_wall_time", mxCreateScalar(context.criteria.max_wall_time)); info.add("epsilon", mxCreateScalar(context.criteria.epsilon)); info.add("log_level", mxCreateString(logging::get_level_name())); info.add("log_format", mxCreateString(logging::get_format_name())); info.add("precision", mxCreateString(type_traits<double>::name())); info.add("data_precision", mxCreateString(type_traits<Data>::name())); plhs[0] = mxCreateStruct(info.fields, "model");; } void mexFunction( const int nlhs, mxArray* plhs[], const int nrhs, const mxArray* prhs[] ) { mxCheckArgNum(nrhs, 3, 3, printUsage); mxCheckArgNum(nlhs, 0, 1, printUsage); const mxArray* data = prhs[0]; const mxArray* labels = prhs[1]; const mxArray* opts = prhs[2]; mxCheckStruct(opts, "opts"); logging::format_push(); mat_cout_hijack mat_cout; set_logging_options(opts); if (mxIsDouble(data) || (mxIsCell(data) && !mxIsEmpty(data) && mxIsDouble(mxGetCell(data, 0)))) { mex_main<double>(data, labels, opts, plhs); } else if (mxIsSingle(data) || (mxIsCell(data) && !mxIsEmpty(data) && mxIsSingle(mxGetCell(data, 0)))) { mex_main<float>(data, labels, opts, plhs); } else { mexErrMsgIdAndTxt(err_id[err_arg], err_msg[err_arg]); } mat_cout.release(); logging::format_pop(); }
[ "fangbo@Dejun-3.local" ]
fangbo@Dejun-3.local
d99d1dca77c6f2ce1a17d88bd55520cb09c94b39
cc47fb906cbdcd12edb349cf0978034150466493
/RandomAI/RandomAI.cpp
393139da2d5658a9b5420cc79a0455d0d5b825b4
[]
no_license
james7780/PacmanAI
c16b652c54e9823606e7cdbe41170651b880bf8f
295a75ce915dd451fabded5fe0862d57907eba18
refs/heads/master
2021-01-19T11:05:15.406543
2014-05-09T14:30:21
2014-05-09T14:30:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,187
cpp
/// Random Pacman AI for compo #include "stdafx.h" #include "RandomAI.h" #include <string.h> /// @param buffer Board state buffer to read/write to CRandomAI::CRandomAI(char *buffer, char playerChar) { // Copy board to local buffer memcpy(m_board, buffer, BOARD_WIDTH * BOARD_HEIGHT); // Make sure we have a terminator so we can use str functions m_board[BOARD_WIDTH * BOARD_HEIGHT] = 0; // Find player position m_playerChar = playerChar; char *pc = strchr(m_board, (int)m_playerChar); m_playerPosX = (pc - m_board) % BOARD_WIDTH; m_playerPosY = (pc - m_board) / BOARD_WIDTH; } CRandomAI::~CRandomAI(void) { } // Calculate the next move (updates the board) void CRandomAI::CalculateMove() { // Rules: // 1. Calculate which directions are valid moves // 2. Choose a direction randomly // Erase old pacman m_board[m_playerPosX + BOARD_WIDTH * m_playerPosY] = ' '; // Write new pacman m_playerPosX--; m_board[m_playerPosX + BOARD_WIDTH * m_playerPosY] = m_playerChar; } // Get the results /// @param buffer Destination buffer for the results of AI processing void CRandomAI::GetBoard(char *buffer) { memcpy(buffer, m_board, BOARD_WIDTH * BOARD_HEIGHT); }
[ "james7780@yahoo.com" ]
james7780@yahoo.com
9042749be7567a9205917ff7408dd78746d7451c
7e62f0928681aaaecae7daf360bdd9166299b000
/external/DirectXShaderCompiler/lib/IR/Core.cpp
4d5370442fc3f46ee2137cf381d3f1af8f718d3f
[ "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yuri410/rpg
949b001bd0aec47e2a046421da0ff2a1db62ce34
266282ed8cfc7cd82e8c853f6f01706903c24628
refs/heads/master
2020-08-03T09:39:42.253100
2020-06-16T15:38:03
2020-06-16T15:38:03
211,698,323
0
0
null
null
null
null
UTF-8
C++
false
false
104,901
cpp
//===-- Core.cpp ----------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the common infrastructure (including the C bindings) // for libLLVMCore.a, which implements the LLVM intermediate representation. // //===----------------------------------------------------------------------===// #include "llvm-c/Core.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/CallSite.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/GlobalAlias.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Threading.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <cstdlib> #include <cstring> #include <system_error> using namespace llvm; #define DEBUG_TYPE "ir" void llvm::initializeCore(PassRegistry &Registry) { initializeDominatorTreeWrapperPassPass(Registry); initializePrintModulePassWrapperPass(Registry); initializePrintFunctionPassWrapperPass(Registry); initializePrintBasicBlockPassPass(Registry); initializeVerifierLegacyPassPass(Registry); } void LLVMInitializeCore(LLVMPassRegistryRef R) { initializeCore(*unwrap(R)); } void LLVMShutdown() { llvm_shutdown(); } // HLSL Change: use ISO _strdup rather than strdup, which compiled but fails to link #ifdef _MSC_VER #define strdup _strdup #endif /*===-- Error handling ----------------------------------------------------===*/ char *LLVMCreateMessage(const char *Message) { return strdup(Message); } void LLVMDisposeMessage(char *Message) { free(Message); } /*===-- Operations on contexts --------------------------------------------===*/ LLVMContextRef LLVMContextCreate() { return wrap(new LLVMContext()); } LLVMContextRef LLVMGetGlobalContext() { return wrap(&getGlobalContext()); } void LLVMContextSetDiagnosticHandler(LLVMContextRef C, LLVMDiagnosticHandler Handler, void *DiagnosticContext) { unwrap(C)->setDiagnosticHandler( LLVM_EXTENSION reinterpret_cast<LLVMContext::DiagnosticHandlerTy>(Handler), DiagnosticContext); } void LLVMContextSetYieldCallback(LLVMContextRef C, LLVMYieldCallback Callback, void *OpaqueHandle) { auto YieldCallback = LLVM_EXTENSION reinterpret_cast<LLVMContext::YieldCallbackTy>(Callback); unwrap(C)->setYieldCallback(YieldCallback, OpaqueHandle); } void LLVMContextDispose(LLVMContextRef C) { delete unwrap(C); } unsigned LLVMGetMDKindIDInContext(LLVMContextRef C, const char* Name, unsigned SLen) { return unwrap(C)->getMDKindID(StringRef(Name, SLen)); } unsigned LLVMGetMDKindID(const char* Name, unsigned SLen) { return LLVMGetMDKindIDInContext(LLVMGetGlobalContext(), Name, SLen); } char *LLVMGetDiagInfoDescription(LLVMDiagnosticInfoRef DI) { std::string MsgStorage; raw_string_ostream Stream(MsgStorage); DiagnosticPrinterRawOStream DP(Stream); unwrap(DI)->print(DP); Stream.flush(); return LLVMCreateMessage(MsgStorage.c_str()); } LLVMDiagnosticSeverity LLVMGetDiagInfoSeverity(LLVMDiagnosticInfoRef DI){ LLVMDiagnosticSeverity severity; switch(unwrap(DI)->getSeverity()) { default: severity = LLVMDSError; break; case DS_Warning: severity = LLVMDSWarning; break; case DS_Remark: severity = LLVMDSRemark; break; case DS_Note: severity = LLVMDSNote; break; } return severity; } /*===-- Operations on modules ---------------------------------------------===*/ LLVMModuleRef LLVMModuleCreateWithName(const char *ModuleID) { return wrap(new Module(ModuleID, getGlobalContext())); } LLVMModuleRef LLVMModuleCreateWithNameInContext(const char *ModuleID, LLVMContextRef C) { return wrap(new Module(ModuleID, *unwrap(C))); } void LLVMDisposeModule(LLVMModuleRef M) { delete unwrap(M); } /*--.. Data layout .........................................................--*/ const char * LLVMGetDataLayout(LLVMModuleRef M) { return unwrap(M)->getDataLayoutStr().c_str(); } void LLVMSetDataLayout(LLVMModuleRef M, const char *Triple) { unwrap(M)->setDataLayout(Triple); } /*--.. Target triple .......................................................--*/ const char * LLVMGetTarget(LLVMModuleRef M) { return unwrap(M)->getTargetTriple().c_str(); } void LLVMSetTarget(LLVMModuleRef M, const char *Triple) { unwrap(M)->setTargetTriple(Triple); } void LLVMDumpModule(LLVMModuleRef M) { unwrap(M)->dump(); } LLVMBool LLVMPrintModuleToFile(LLVMModuleRef M, const char *Filename, char **ErrorMessage) { std::error_code EC; raw_fd_ostream dest(Filename, EC, sys::fs::F_Text); if (EC) { *ErrorMessage = strdup(EC.message().c_str()); return true; } unwrap(M)->print(dest, nullptr); dest.close(); if (dest.has_error()) { *ErrorMessage = strdup("Error printing to file"); return true; } return false; } char *LLVMPrintModuleToString(LLVMModuleRef M) { std::string buf; raw_string_ostream os(buf); unwrap(M)->print(os, nullptr); os.flush(); return strdup(buf.c_str()); } /*--.. Operations on inline assembler ......................................--*/ void LLVMSetModuleInlineAsm(LLVMModuleRef M, const char *Asm) { unwrap(M)->setModuleInlineAsm(StringRef(Asm)); } /*--.. Operations on module contexts ......................................--*/ LLVMContextRef LLVMGetModuleContext(LLVMModuleRef M) { return wrap(&unwrap(M)->getContext()); } /*===-- Operations on types -----------------------------------------------===*/ /*--.. Operations on all types (mostly) ....................................--*/ LLVMTypeKind LLVMGetTypeKind(LLVMTypeRef Ty) { switch (unwrap(Ty)->getTypeID()) { case Type::VoidTyID: return LLVMVoidTypeKind; case Type::HalfTyID: return LLVMHalfTypeKind; case Type::FloatTyID: return LLVMFloatTypeKind; case Type::DoubleTyID: return LLVMDoubleTypeKind; case Type::X86_FP80TyID: return LLVMX86_FP80TypeKind; case Type::FP128TyID: return LLVMFP128TypeKind; case Type::PPC_FP128TyID: return LLVMPPC_FP128TypeKind; case Type::LabelTyID: return LLVMLabelTypeKind; case Type::MetadataTyID: return LLVMMetadataTypeKind; case Type::IntegerTyID: return LLVMIntegerTypeKind; case Type::FunctionTyID: return LLVMFunctionTypeKind; case Type::StructTyID: return LLVMStructTypeKind; case Type::ArrayTyID: return LLVMArrayTypeKind; case Type::PointerTyID: return LLVMPointerTypeKind; case Type::VectorTyID: return LLVMVectorTypeKind; case Type::X86_MMXTyID: return LLVMX86_MMXTypeKind; } llvm_unreachable("Unhandled TypeID."); } LLVMBool LLVMTypeIsSized(LLVMTypeRef Ty) { return unwrap(Ty)->isSized(); } LLVMContextRef LLVMGetTypeContext(LLVMTypeRef Ty) { return wrap(&unwrap(Ty)->getContext()); } void LLVMDumpType(LLVMTypeRef Ty) { return unwrap(Ty)->dump(); } char *LLVMPrintTypeToString(LLVMTypeRef Ty) { std::string buf; raw_string_ostream os(buf); if (unwrap(Ty)) unwrap(Ty)->print(os); else os << "Printing <null> Type"; os.flush(); return strdup(buf.c_str()); } /*--.. Operations on integer types .........................................--*/ LLVMTypeRef LLVMInt1TypeInContext(LLVMContextRef C) { return (LLVMTypeRef) Type::getInt1Ty(*unwrap(C)); } LLVMTypeRef LLVMInt8TypeInContext(LLVMContextRef C) { return (LLVMTypeRef) Type::getInt8Ty(*unwrap(C)); } LLVMTypeRef LLVMInt16TypeInContext(LLVMContextRef C) { return (LLVMTypeRef) Type::getInt16Ty(*unwrap(C)); } LLVMTypeRef LLVMInt32TypeInContext(LLVMContextRef C) { return (LLVMTypeRef) Type::getInt32Ty(*unwrap(C)); } LLVMTypeRef LLVMInt64TypeInContext(LLVMContextRef C) { return (LLVMTypeRef) Type::getInt64Ty(*unwrap(C)); } LLVMTypeRef LLVMInt128TypeInContext(LLVMContextRef C) { return (LLVMTypeRef) Type::getInt128Ty(*unwrap(C)); } LLVMTypeRef LLVMIntTypeInContext(LLVMContextRef C, unsigned NumBits) { return wrap(IntegerType::get(*unwrap(C), NumBits)); } LLVMTypeRef LLVMInt1Type(void) { return LLVMInt1TypeInContext(LLVMGetGlobalContext()); } LLVMTypeRef LLVMInt8Type(void) { return LLVMInt8TypeInContext(LLVMGetGlobalContext()); } LLVMTypeRef LLVMInt16Type(void) { return LLVMInt16TypeInContext(LLVMGetGlobalContext()); } LLVMTypeRef LLVMInt32Type(void) { return LLVMInt32TypeInContext(LLVMGetGlobalContext()); } LLVMTypeRef LLVMInt64Type(void) { return LLVMInt64TypeInContext(LLVMGetGlobalContext()); } LLVMTypeRef LLVMInt128Type(void) { return LLVMInt128TypeInContext(LLVMGetGlobalContext()); } LLVMTypeRef LLVMIntType(unsigned NumBits) { return LLVMIntTypeInContext(LLVMGetGlobalContext(), NumBits); } unsigned LLVMGetIntTypeWidth(LLVMTypeRef IntegerTy) { return unwrap<IntegerType>(IntegerTy)->getBitWidth(); } /*--.. Operations on real types ............................................--*/ LLVMTypeRef LLVMHalfTypeInContext(LLVMContextRef C) { return (LLVMTypeRef) Type::getHalfTy(*unwrap(C)); } LLVMTypeRef LLVMFloatTypeInContext(LLVMContextRef C) { return (LLVMTypeRef) Type::getFloatTy(*unwrap(C)); } LLVMTypeRef LLVMDoubleTypeInContext(LLVMContextRef C) { return (LLVMTypeRef) Type::getDoubleTy(*unwrap(C)); } LLVMTypeRef LLVMX86FP80TypeInContext(LLVMContextRef C) { return (LLVMTypeRef) Type::getX86_FP80Ty(*unwrap(C)); } LLVMTypeRef LLVMFP128TypeInContext(LLVMContextRef C) { return (LLVMTypeRef) Type::getFP128Ty(*unwrap(C)); } LLVMTypeRef LLVMPPCFP128TypeInContext(LLVMContextRef C) { return (LLVMTypeRef) Type::getPPC_FP128Ty(*unwrap(C)); } LLVMTypeRef LLVMX86MMXTypeInContext(LLVMContextRef C) { return (LLVMTypeRef) Type::getX86_MMXTy(*unwrap(C)); } LLVMTypeRef LLVMHalfType(void) { return LLVMHalfTypeInContext(LLVMGetGlobalContext()); } LLVMTypeRef LLVMFloatType(void) { return LLVMFloatTypeInContext(LLVMGetGlobalContext()); } LLVMTypeRef LLVMDoubleType(void) { return LLVMDoubleTypeInContext(LLVMGetGlobalContext()); } LLVMTypeRef LLVMX86FP80Type(void) { return LLVMX86FP80TypeInContext(LLVMGetGlobalContext()); } LLVMTypeRef LLVMFP128Type(void) { return LLVMFP128TypeInContext(LLVMGetGlobalContext()); } LLVMTypeRef LLVMPPCFP128Type(void) { return LLVMPPCFP128TypeInContext(LLVMGetGlobalContext()); } LLVMTypeRef LLVMX86MMXType(void) { return LLVMX86MMXTypeInContext(LLVMGetGlobalContext()); } /*--.. Operations on function types ........................................--*/ LLVMTypeRef LLVMFunctionType(LLVMTypeRef ReturnType, LLVMTypeRef *ParamTypes, unsigned ParamCount, LLVMBool IsVarArg) { ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount); return wrap(FunctionType::get(unwrap(ReturnType), Tys, IsVarArg != 0)); } LLVMBool LLVMIsFunctionVarArg(LLVMTypeRef FunctionTy) { return unwrap<FunctionType>(FunctionTy)->isVarArg(); } LLVMTypeRef LLVMGetReturnType(LLVMTypeRef FunctionTy) { return wrap(unwrap<FunctionType>(FunctionTy)->getReturnType()); } unsigned LLVMCountParamTypes(LLVMTypeRef FunctionTy) { return unwrap<FunctionType>(FunctionTy)->getNumParams(); } void LLVMGetParamTypes(LLVMTypeRef FunctionTy, LLVMTypeRef *Dest) { FunctionType *Ty = unwrap<FunctionType>(FunctionTy); for (FunctionType::param_iterator I = Ty->param_begin(), E = Ty->param_end(); I != E; ++I) *Dest++ = wrap(*I); } /*--.. Operations on struct types ..........................................--*/ LLVMTypeRef LLVMStructTypeInContext(LLVMContextRef C, LLVMTypeRef *ElementTypes, unsigned ElementCount, LLVMBool Packed) { ArrayRef<Type*> Tys(unwrap(ElementTypes), ElementCount); return wrap(StructType::get(*unwrap(C), Tys, Packed != 0)); } LLVMTypeRef LLVMStructType(LLVMTypeRef *ElementTypes, unsigned ElementCount, LLVMBool Packed) { return LLVMStructTypeInContext(LLVMGetGlobalContext(), ElementTypes, ElementCount, Packed); } LLVMTypeRef LLVMStructCreateNamed(LLVMContextRef C, const char *Name) { return wrap(StructType::create(*unwrap(C), Name)); } const char *LLVMGetStructName(LLVMTypeRef Ty) { StructType *Type = unwrap<StructType>(Ty); if (!Type->hasName()) return nullptr; return Type->getName().data(); } void LLVMStructSetBody(LLVMTypeRef StructTy, LLVMTypeRef *ElementTypes, unsigned ElementCount, LLVMBool Packed) { ArrayRef<Type*> Tys(unwrap(ElementTypes), ElementCount); unwrap<StructType>(StructTy)->setBody(Tys, Packed != 0); } unsigned LLVMCountStructElementTypes(LLVMTypeRef StructTy) { return unwrap<StructType>(StructTy)->getNumElements(); } void LLVMGetStructElementTypes(LLVMTypeRef StructTy, LLVMTypeRef *Dest) { StructType *Ty = unwrap<StructType>(StructTy); for (StructType::element_iterator I = Ty->element_begin(), E = Ty->element_end(); I != E; ++I) *Dest++ = wrap(*I); } LLVMTypeRef LLVMStructGetTypeAtIndex(LLVMTypeRef StructTy, unsigned i) { StructType *Ty = unwrap<StructType>(StructTy); return wrap(Ty->getTypeAtIndex(i)); } LLVMBool LLVMIsPackedStruct(LLVMTypeRef StructTy) { return unwrap<StructType>(StructTy)->isPacked(); } LLVMBool LLVMIsOpaqueStruct(LLVMTypeRef StructTy) { return unwrap<StructType>(StructTy)->isOpaque(); } LLVMTypeRef LLVMGetTypeByName(LLVMModuleRef M, const char *Name) { return wrap(unwrap(M)->getTypeByName(Name)); } /*--.. Operations on array, pointer, and vector types (sequence types) .....--*/ LLVMTypeRef LLVMArrayType(LLVMTypeRef ElementType, unsigned ElementCount) { return wrap(ArrayType::get(unwrap(ElementType), ElementCount)); } LLVMTypeRef LLVMPointerType(LLVMTypeRef ElementType, unsigned AddressSpace) { return wrap(PointerType::get(unwrap(ElementType), AddressSpace)); } LLVMTypeRef LLVMVectorType(LLVMTypeRef ElementType, unsigned ElementCount) { return wrap(VectorType::get(unwrap(ElementType), ElementCount)); } LLVMTypeRef LLVMGetElementType(LLVMTypeRef Ty) { return wrap(unwrap<SequentialType>(Ty)->getElementType()); } unsigned LLVMGetArrayLength(LLVMTypeRef ArrayTy) { return unwrap<ArrayType>(ArrayTy)->getNumElements(); } unsigned LLVMGetPointerAddressSpace(LLVMTypeRef PointerTy) { return unwrap<PointerType>(PointerTy)->getAddressSpace(); } unsigned LLVMGetVectorSize(LLVMTypeRef VectorTy) { return unwrap<VectorType>(VectorTy)->getNumElements(); } /*--.. Operations on other types ...........................................--*/ LLVMTypeRef LLVMVoidTypeInContext(LLVMContextRef C) { return wrap(Type::getVoidTy(*unwrap(C))); } LLVMTypeRef LLVMLabelTypeInContext(LLVMContextRef C) { return wrap(Type::getLabelTy(*unwrap(C))); } LLVMTypeRef LLVMVoidType(void) { return LLVMVoidTypeInContext(LLVMGetGlobalContext()); } LLVMTypeRef LLVMLabelType(void) { return LLVMLabelTypeInContext(LLVMGetGlobalContext()); } /*===-- Operations on values ----------------------------------------------===*/ /*--.. Operations on all values ............................................--*/ LLVMTypeRef LLVMTypeOf(LLVMValueRef Val) { return wrap(unwrap(Val)->getType()); } const char *LLVMGetValueName(LLVMValueRef Val) { return unwrap(Val)->getName().data(); } void LLVMSetValueName(LLVMValueRef Val, const char *Name) { unwrap(Val)->setName(Name); } void LLVMDumpValue(LLVMValueRef Val) { unwrap(Val)->dump(); } char* LLVMPrintValueToString(LLVMValueRef Val) { std::string buf; raw_string_ostream os(buf); if (unwrap(Val)) unwrap(Val)->print(os); else os << "Printing <null> Value"; os.flush(); return strdup(buf.c_str()); } void LLVMReplaceAllUsesWith(LLVMValueRef OldVal, LLVMValueRef NewVal) { unwrap(OldVal)->replaceAllUsesWith(unwrap(NewVal)); } int LLVMHasMetadata(LLVMValueRef Inst) { return unwrap<Instruction>(Inst)->hasMetadata(); } LLVMValueRef LLVMGetMetadata(LLVMValueRef Inst, unsigned KindID) { auto *I = unwrap<Instruction>(Inst); assert(I && "Expected instruction"); if (auto *MD = I->getMetadata(KindID)) return wrap(MetadataAsValue::get(I->getContext(), MD)); return nullptr; } // MetadataAsValue uses a canonical format which strips the actual MDNode for // MDNode with just a single constant value, storing just a ConstantAsMetadata // This undoes this canonicalization, reconstructing the MDNode. static MDNode *extractMDNode(MetadataAsValue *MAV) { Metadata *MD = MAV->getMetadata(); assert((isa<MDNode>(MD) || isa<ConstantAsMetadata>(MD)) && "Expected a metadata node or a canonicalized constant"); if (MDNode *N = dyn_cast<MDNode>(MD)) return N; return MDNode::get(MAV->getContext(), MD); } void LLVMSetMetadata(LLVMValueRef Inst, unsigned KindID, LLVMValueRef Val) { MDNode *N = Val ? extractMDNode(unwrap<MetadataAsValue>(Val)) : nullptr; unwrap<Instruction>(Inst)->setMetadata(KindID, N); } /*--.. Conversion functions ................................................--*/ #define LLVM_DEFINE_VALUE_CAST(name) \ LLVMValueRef LLVMIsA##name(LLVMValueRef Val) { \ return wrap(static_cast<Value*>(dyn_cast_or_null<name>(unwrap(Val)))); \ } LLVM_FOR_EACH_VALUE_SUBCLASS(LLVM_DEFINE_VALUE_CAST) LLVMValueRef LLVMIsAMDNode(LLVMValueRef Val) { if (auto *MD = dyn_cast_or_null<MetadataAsValue>(unwrap(Val))) if (isa<MDNode>(MD->getMetadata()) || isa<ValueAsMetadata>(MD->getMetadata())) return Val; return nullptr; } LLVMValueRef LLVMIsAMDString(LLVMValueRef Val) { if (auto *MD = dyn_cast_or_null<MetadataAsValue>(unwrap(Val))) if (isa<MDString>(MD->getMetadata())) return Val; return nullptr; } /*--.. Operations on Uses ..................................................--*/ LLVMUseRef LLVMGetFirstUse(LLVMValueRef Val) { Value *V = unwrap(Val); Value::use_iterator I = V->use_begin(); if (I == V->use_end()) return nullptr; return wrap(&*I); } LLVMUseRef LLVMGetNextUse(LLVMUseRef U) { Use *Next = unwrap(U)->getNext(); if (Next) return wrap(Next); return nullptr; } LLVMValueRef LLVMGetUser(LLVMUseRef U) { return wrap(unwrap(U)->getUser()); } LLVMValueRef LLVMGetUsedValue(LLVMUseRef U) { return wrap(unwrap(U)->get()); } /*--.. Operations on Users .................................................--*/ static LLVMValueRef getMDNodeOperandImpl(LLVMContext &Context, const MDNode *N, unsigned Index) { Metadata *Op = N->getOperand(Index); if (!Op) return nullptr; if (auto *C = dyn_cast<ConstantAsMetadata>(Op)) return wrap(C->getValue()); return wrap(MetadataAsValue::get(Context, Op)); } LLVMValueRef LLVMGetOperand(LLVMValueRef Val, unsigned Index) { Value *V = unwrap(Val); if (auto *MD = dyn_cast<MetadataAsValue>(V)) { if (auto *L = dyn_cast<ValueAsMetadata>(MD->getMetadata())) { assert(Index == 0 && "Function-local metadata can only have one operand"); return wrap(L->getValue()); } return getMDNodeOperandImpl(V->getContext(), cast<MDNode>(MD->getMetadata()), Index); } return wrap(cast<User>(V)->getOperand(Index)); } LLVMUseRef LLVMGetOperandUse(LLVMValueRef Val, unsigned Index) { Value *V = unwrap(Val); return wrap(&cast<User>(V)->getOperandUse(Index)); } void LLVMSetOperand(LLVMValueRef Val, unsigned Index, LLVMValueRef Op) { unwrap<User>(Val)->setOperand(Index, unwrap(Op)); } int LLVMGetNumOperands(LLVMValueRef Val) { Value *V = unwrap(Val); if (isa<MetadataAsValue>(V)) return LLVMGetMDNodeNumOperands(Val); return cast<User>(V)->getNumOperands(); } /*--.. Operations on constants of any type .................................--*/ LLVMValueRef LLVMConstNull(LLVMTypeRef Ty) { return wrap(Constant::getNullValue(unwrap(Ty))); } LLVMValueRef LLVMConstAllOnes(LLVMTypeRef Ty) { return wrap(Constant::getAllOnesValue(unwrap(Ty))); } LLVMValueRef LLVMGetUndef(LLVMTypeRef Ty) { return wrap(UndefValue::get(unwrap(Ty))); } LLVMBool LLVMIsConstant(LLVMValueRef Ty) { return isa<Constant>(unwrap(Ty)); } LLVMBool LLVMIsNull(LLVMValueRef Val) { if (Constant *C = dyn_cast<Constant>(unwrap(Val))) return C->isNullValue(); return false; } LLVMBool LLVMIsUndef(LLVMValueRef Val) { return isa<UndefValue>(unwrap(Val)); } LLVMValueRef LLVMConstPointerNull(LLVMTypeRef Ty) { return wrap(ConstantPointerNull::get(unwrap<PointerType>(Ty))); } /*--.. Operations on metadata nodes ........................................--*/ LLVMValueRef LLVMMDStringInContext(LLVMContextRef C, const char *Str, unsigned SLen) { LLVMContext &Context = *unwrap(C); return wrap(MetadataAsValue::get( Context, MDString::get(Context, StringRef(Str, SLen)))); } LLVMValueRef LLVMMDString(const char *Str, unsigned SLen) { return LLVMMDStringInContext(LLVMGetGlobalContext(), Str, SLen); } LLVMValueRef LLVMMDNodeInContext(LLVMContextRef C, LLVMValueRef *Vals, unsigned Count) { LLVMContext &Context = *unwrap(C); SmallVector<Metadata *, 8> MDs; for (auto *OV : makeArrayRef(Vals, Count)) { Value *V = unwrap(OV); Metadata *MD; if (!V) MD = nullptr; else if (auto *C = dyn_cast<Constant>(V)) MD = ConstantAsMetadata::get(C); else if (auto *MDV = dyn_cast<MetadataAsValue>(V)) { MD = MDV->getMetadata(); assert(!isa<LocalAsMetadata>(MD) && "Unexpected function-local metadata " "outside of direct argument to call"); } else { // This is function-local metadata. Pretend to make an MDNode. assert(Count == 1 && "Expected only one operand to function-local metadata"); return wrap(MetadataAsValue::get(Context, LocalAsMetadata::get(V))); } MDs.push_back(MD); } return wrap(MetadataAsValue::get(Context, MDNode::get(Context, MDs))); } LLVMValueRef LLVMMDNode(LLVMValueRef *Vals, unsigned Count) { return LLVMMDNodeInContext(LLVMGetGlobalContext(), Vals, Count); } const char *LLVMGetMDString(LLVMValueRef V, unsigned* Len) { if (const auto *MD = dyn_cast<MetadataAsValue>(unwrap(V))) if (const MDString *S = dyn_cast<MDString>(MD->getMetadata())) { *Len = S->getString().size(); return S->getString().data(); } *Len = 0; return nullptr; } unsigned LLVMGetMDNodeNumOperands(LLVMValueRef V) { auto *MD = cast<MetadataAsValue>(unwrap(V)); if (isa<ValueAsMetadata>(MD->getMetadata())) return 1; return cast<MDNode>(MD->getMetadata())->getNumOperands(); } void LLVMGetMDNodeOperands(LLVMValueRef V, LLVMValueRef *Dest) { auto *MD = cast<MetadataAsValue>(unwrap(V)); if (auto *MDV = dyn_cast<ValueAsMetadata>(MD->getMetadata())) { *Dest = wrap(MDV->getValue()); return; } const auto *N = cast<MDNode>(MD->getMetadata()); const unsigned numOperands = N->getNumOperands(); LLVMContext &Context = unwrap(V)->getContext(); for (unsigned i = 0; i < numOperands; i++) Dest[i] = getMDNodeOperandImpl(Context, N, i); } unsigned LLVMGetNamedMetadataNumOperands(LLVMModuleRef M, const char* name) { if (NamedMDNode *N = unwrap(M)->getNamedMetadata(name)) { return N->getNumOperands(); } return 0; } void LLVMGetNamedMetadataOperands(LLVMModuleRef M, const char* name, LLVMValueRef *Dest) { NamedMDNode *N = unwrap(M)->getNamedMetadata(name); if (!N) return; LLVMContext &Context = unwrap(M)->getContext(); for (unsigned i=0;i<N->getNumOperands();i++) Dest[i] = wrap(MetadataAsValue::get(Context, N->getOperand(i))); } void LLVMAddNamedMetadataOperand(LLVMModuleRef M, const char* name, LLVMValueRef Val) { NamedMDNode *N = unwrap(M)->getOrInsertNamedMetadata(name); if (!N) return; if (!Val) return; N->addOperand(extractMDNode(unwrap<MetadataAsValue>(Val))); } /*--.. Operations on scalar constants ......................................--*/ LLVMValueRef LLVMConstInt(LLVMTypeRef IntTy, unsigned long long N, LLVMBool SignExtend) { return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), N, SignExtend != 0)); } LLVMValueRef LLVMConstIntOfArbitraryPrecision(LLVMTypeRef IntTy, unsigned NumWords, const uint64_t Words[]) { IntegerType *Ty = unwrap<IntegerType>(IntTy); return wrap(ConstantInt::get(Ty->getContext(), APInt(Ty->getBitWidth(), makeArrayRef(Words, NumWords)))); } LLVMValueRef LLVMConstIntOfString(LLVMTypeRef IntTy, const char Str[], uint8_t Radix) { return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), StringRef(Str), Radix)); } LLVMValueRef LLVMConstIntOfStringAndSize(LLVMTypeRef IntTy, const char Str[], unsigned SLen, uint8_t Radix) { return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), StringRef(Str, SLen), Radix)); } LLVMValueRef LLVMConstReal(LLVMTypeRef RealTy, double N) { return wrap(ConstantFP::get(unwrap(RealTy), N)); } LLVMValueRef LLVMConstRealOfString(LLVMTypeRef RealTy, const char *Text) { return wrap(ConstantFP::get(unwrap(RealTy), StringRef(Text))); } LLVMValueRef LLVMConstRealOfStringAndSize(LLVMTypeRef RealTy, const char Str[], unsigned SLen) { return wrap(ConstantFP::get(unwrap(RealTy), StringRef(Str, SLen))); } unsigned long long LLVMConstIntGetZExtValue(LLVMValueRef ConstantVal) { return unwrap<ConstantInt>(ConstantVal)->getZExtValue(); } long long LLVMConstIntGetSExtValue(LLVMValueRef ConstantVal) { return unwrap<ConstantInt>(ConstantVal)->getSExtValue(); } double LLVMConstRealGetDouble(LLVMValueRef ConstantVal, LLVMBool *LosesInfo) { ConstantFP *cFP = unwrap<ConstantFP>(ConstantVal) ; Type *Ty = cFP->getType(); if (Ty->isFloatTy()) { *LosesInfo = false; return cFP->getValueAPF().convertToFloat(); } if (Ty->isDoubleTy()) { *LosesInfo = false; return cFP->getValueAPF().convertToDouble(); } bool APFLosesInfo; APFloat APF = cFP->getValueAPF(); APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &APFLosesInfo); *LosesInfo = APFLosesInfo; return APF.convertToDouble(); } /*--.. Operations on composite constants ...................................--*/ LLVMValueRef LLVMConstStringInContext(LLVMContextRef C, const char *Str, unsigned Length, LLVMBool DontNullTerminate) { /* Inverted the sense of AddNull because ', 0)' is a better mnemonic for null termination than ', 1)'. */ return wrap(ConstantDataArray::getString(*unwrap(C), StringRef(Str, Length), DontNullTerminate == 0)); } LLVMValueRef LLVMConstStructInContext(LLVMContextRef C, LLVMValueRef *ConstantVals, unsigned Count, LLVMBool Packed) { Constant **Elements = unwrap<Constant>(ConstantVals, Count); return wrap(ConstantStruct::getAnon(*unwrap(C), makeArrayRef(Elements, Count), Packed != 0)); } LLVMValueRef LLVMConstString(const char *Str, unsigned Length, LLVMBool DontNullTerminate) { return LLVMConstStringInContext(LLVMGetGlobalContext(), Str, Length, DontNullTerminate); } LLVMValueRef LLVMGetElementAsConstant(LLVMValueRef c, unsigned idx) { return wrap(static_cast<ConstantDataSequential*>(unwrap(c))->getElementAsConstant(idx)); } LLVMBool LLVMIsConstantString(LLVMValueRef c) { return static_cast<ConstantDataSequential*>(unwrap(c))->isString(); } const char *LLVMGetAsString(LLVMValueRef c, size_t* Length) { StringRef str = static_cast<ConstantDataSequential*>(unwrap(c))->getAsString(); *Length = str.size(); return str.data(); } LLVMValueRef LLVMConstArray(LLVMTypeRef ElementTy, LLVMValueRef *ConstantVals, unsigned Length) { ArrayRef<Constant*> V(unwrap<Constant>(ConstantVals, Length), Length); return wrap(ConstantArray::get(ArrayType::get(unwrap(ElementTy), Length), V)); } LLVMValueRef LLVMConstStruct(LLVMValueRef *ConstantVals, unsigned Count, LLVMBool Packed) { return LLVMConstStructInContext(LLVMGetGlobalContext(), ConstantVals, Count, Packed); } LLVMValueRef LLVMConstNamedStruct(LLVMTypeRef StructTy, LLVMValueRef *ConstantVals, unsigned Count) { Constant **Elements = unwrap<Constant>(ConstantVals, Count); StructType *Ty = cast<StructType>(unwrap(StructTy)); return wrap(ConstantStruct::get(Ty, makeArrayRef(Elements, Count))); } LLVMValueRef LLVMConstVector(LLVMValueRef *ScalarConstantVals, unsigned Size) { return wrap(ConstantVector::get(makeArrayRef( unwrap<Constant>(ScalarConstantVals, Size), Size))); } /*-- Opcode mapping */ static LLVMOpcode map_to_llvmopcode(int opcode) { switch (opcode) { default: llvm_unreachable("Unhandled Opcode."); #define HANDLE_INST(num, opc, clas) case num: return LLVM##opc; #include "llvm/IR/Instruction.def" #undef HANDLE_INST } } static int map_from_llvmopcode(LLVMOpcode code) { switch (code) { #define HANDLE_INST(num, opc, clas) case LLVM##opc: return num; #include "llvm/IR/Instruction.def" #undef HANDLE_INST } llvm_unreachable("Unhandled Opcode."); } /*--.. Constant expressions ................................................--*/ LLVMOpcode LLVMGetConstOpcode(LLVMValueRef ConstantVal) { return map_to_llvmopcode(unwrap<ConstantExpr>(ConstantVal)->getOpcode()); } LLVMValueRef LLVMAlignOf(LLVMTypeRef Ty) { return wrap(ConstantExpr::getAlignOf(unwrap(Ty))); } LLVMValueRef LLVMSizeOf(LLVMTypeRef Ty) { return wrap(ConstantExpr::getSizeOf(unwrap(Ty))); } LLVMValueRef LLVMConstNeg(LLVMValueRef ConstantVal) { return wrap(ConstantExpr::getNeg(unwrap<Constant>(ConstantVal))); } LLVMValueRef LLVMConstNSWNeg(LLVMValueRef ConstantVal) { return wrap(ConstantExpr::getNSWNeg(unwrap<Constant>(ConstantVal))); } LLVMValueRef LLVMConstNUWNeg(LLVMValueRef ConstantVal) { return wrap(ConstantExpr::getNUWNeg(unwrap<Constant>(ConstantVal))); } LLVMValueRef LLVMConstFNeg(LLVMValueRef ConstantVal) { return wrap(ConstantExpr::getFNeg(unwrap<Constant>(ConstantVal))); } LLVMValueRef LLVMConstNot(LLVMValueRef ConstantVal) { return wrap(ConstantExpr::getNot(unwrap<Constant>(ConstantVal))); } LLVMValueRef LLVMConstAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getAdd(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstNSWAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getNSWAdd(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstNUWAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getNUWAdd(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstFAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getFAdd(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getSub(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstNSWSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getNSWSub(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstNUWSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getNUWSub(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstFSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getFSub(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getMul(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstNSWMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getNSWMul(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstNUWMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getNUWMul(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstFMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getFMul(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstUDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getUDiv(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstSDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getSDiv(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstExactSDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getExactSDiv(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstFDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getFDiv(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstURem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getURem(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstSRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getSRem(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstFRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getFRem(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstAnd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getAnd(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstOr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getOr(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstXor(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getXor(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstICmp(LLVMIntPredicate Predicate, LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getICmp(Predicate, unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstFCmp(LLVMRealPredicate Predicate, LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getFCmp(Predicate, unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstShl(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getShl(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstLShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getLShr(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstAShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) { return wrap(ConstantExpr::getAShr(unwrap<Constant>(LHSConstant), unwrap<Constant>(RHSConstant))); } LLVMValueRef LLVMConstGEP(LLVMValueRef ConstantVal, LLVMValueRef *ConstantIndices, unsigned NumIndices) { ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices), NumIndices); return wrap(ConstantExpr::getGetElementPtr( nullptr, unwrap<Constant>(ConstantVal), IdxList)); } LLVMValueRef LLVMConstInBoundsGEP(LLVMValueRef ConstantVal, LLVMValueRef *ConstantIndices, unsigned NumIndices) { Constant* Val = unwrap<Constant>(ConstantVal); ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices), NumIndices); return wrap(ConstantExpr::getInBoundsGetElementPtr(nullptr, Val, IdxList)); } LLVMValueRef LLVMConstTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getTrunc(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstSExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getSExt(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstZExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getZExt(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstFPTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getFPTrunc(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstFPExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getFPExtend(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstUIToFP(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getUIToFP(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstSIToFP(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getSIToFP(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstFPToUI(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getFPToUI(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstFPToSI(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getFPToSI(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstPtrToInt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getPtrToInt(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstIntToPtr(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getIntToPtr(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstBitCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getBitCast(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstAddrSpaceCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getAddrSpaceCast(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstZExtOrBitCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getZExtOrBitCast(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstSExtOrBitCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getSExtOrBitCast(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstTruncOrBitCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getTruncOrBitCast(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstPointerCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getPointerCast(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstIntCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType, LLVMBool isSigned) { return wrap(ConstantExpr::getIntegerCast(unwrap<Constant>(ConstantVal), unwrap(ToType), isSigned)); } LLVMValueRef LLVMConstFPCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) { return wrap(ConstantExpr::getFPCast(unwrap<Constant>(ConstantVal), unwrap(ToType))); } LLVMValueRef LLVMConstSelect(LLVMValueRef ConstantCondition, LLVMValueRef ConstantIfTrue, LLVMValueRef ConstantIfFalse) { return wrap(ConstantExpr::getSelect(unwrap<Constant>(ConstantCondition), unwrap<Constant>(ConstantIfTrue), unwrap<Constant>(ConstantIfFalse))); } LLVMValueRef LLVMConstExtractElement(LLVMValueRef VectorConstant, LLVMValueRef IndexConstant) { return wrap(ConstantExpr::getExtractElement(unwrap<Constant>(VectorConstant), unwrap<Constant>(IndexConstant))); } LLVMValueRef LLVMConstInsertElement(LLVMValueRef VectorConstant, LLVMValueRef ElementValueConstant, LLVMValueRef IndexConstant) { return wrap(ConstantExpr::getInsertElement(unwrap<Constant>(VectorConstant), unwrap<Constant>(ElementValueConstant), unwrap<Constant>(IndexConstant))); } LLVMValueRef LLVMConstShuffleVector(LLVMValueRef VectorAConstant, LLVMValueRef VectorBConstant, LLVMValueRef MaskConstant) { return wrap(ConstantExpr::getShuffleVector(unwrap<Constant>(VectorAConstant), unwrap<Constant>(VectorBConstant), unwrap<Constant>(MaskConstant))); } LLVMValueRef LLVMConstExtractValue(LLVMValueRef AggConstant, unsigned *IdxList, unsigned NumIdx) { return wrap(ConstantExpr::getExtractValue(unwrap<Constant>(AggConstant), makeArrayRef(IdxList, NumIdx))); } LLVMValueRef LLVMConstInsertValue(LLVMValueRef AggConstant, LLVMValueRef ElementValueConstant, unsigned *IdxList, unsigned NumIdx) { return wrap(ConstantExpr::getInsertValue(unwrap<Constant>(AggConstant), unwrap<Constant>(ElementValueConstant), makeArrayRef(IdxList, NumIdx))); } LLVMValueRef LLVMConstInlineAsm(LLVMTypeRef Ty, const char *AsmString, const char *Constraints, LLVMBool HasSideEffects, LLVMBool IsAlignStack) { return wrap(InlineAsm::get(dyn_cast<FunctionType>(unwrap(Ty)), AsmString, Constraints, HasSideEffects, IsAlignStack)); } LLVMValueRef LLVMBlockAddress(LLVMValueRef F, LLVMBasicBlockRef BB) { return wrap(BlockAddress::get(unwrap<Function>(F), unwrap(BB))); } /*--.. Operations on global variables, functions, and aliases (globals) ....--*/ LLVMModuleRef LLVMGetGlobalParent(LLVMValueRef Global) { return wrap(unwrap<GlobalValue>(Global)->getParent()); } LLVMBool LLVMIsDeclaration(LLVMValueRef Global) { return unwrap<GlobalValue>(Global)->isDeclaration(); } LLVMLinkage LLVMGetLinkage(LLVMValueRef Global) { switch (unwrap<GlobalValue>(Global)->getLinkage()) { case GlobalValue::ExternalLinkage: return LLVMExternalLinkage; case GlobalValue::AvailableExternallyLinkage: return LLVMAvailableExternallyLinkage; case GlobalValue::LinkOnceAnyLinkage: return LLVMLinkOnceAnyLinkage; case GlobalValue::LinkOnceODRLinkage: return LLVMLinkOnceODRLinkage; case GlobalValue::WeakAnyLinkage: return LLVMWeakAnyLinkage; case GlobalValue::WeakODRLinkage: return LLVMWeakODRLinkage; case GlobalValue::AppendingLinkage: return LLVMAppendingLinkage; case GlobalValue::InternalLinkage: return LLVMInternalLinkage; case GlobalValue::PrivateLinkage: return LLVMPrivateLinkage; case GlobalValue::ExternalWeakLinkage: return LLVMExternalWeakLinkage; case GlobalValue::CommonLinkage: return LLVMCommonLinkage; } llvm_unreachable("Invalid GlobalValue linkage!"); } void LLVMSetLinkage(LLVMValueRef Global, LLVMLinkage Linkage) { GlobalValue *GV = unwrap<GlobalValue>(Global); switch (Linkage) { case LLVMExternalLinkage: GV->setLinkage(GlobalValue::ExternalLinkage); break; case LLVMAvailableExternallyLinkage: GV->setLinkage(GlobalValue::AvailableExternallyLinkage); break; case LLVMLinkOnceAnyLinkage: GV->setLinkage(GlobalValue::LinkOnceAnyLinkage); break; case LLVMLinkOnceODRLinkage: GV->setLinkage(GlobalValue::LinkOnceODRLinkage); break; case LLVMLinkOnceODRAutoHideLinkage: DEBUG(errs() << "LLVMSetLinkage(): LLVMLinkOnceODRAutoHideLinkage is no " "longer supported."); break; case LLVMWeakAnyLinkage: GV->setLinkage(GlobalValue::WeakAnyLinkage); break; case LLVMWeakODRLinkage: GV->setLinkage(GlobalValue::WeakODRLinkage); break; case LLVMAppendingLinkage: GV->setLinkage(GlobalValue::AppendingLinkage); break; case LLVMInternalLinkage: GV->setLinkage(GlobalValue::InternalLinkage); break; case LLVMPrivateLinkage: GV->setLinkage(GlobalValue::PrivateLinkage); break; case LLVMLinkerPrivateLinkage: GV->setLinkage(GlobalValue::PrivateLinkage); break; case LLVMLinkerPrivateWeakLinkage: GV->setLinkage(GlobalValue::PrivateLinkage); break; case LLVMDLLImportLinkage: DEBUG(errs() << "LLVMSetLinkage(): LLVMDLLImportLinkage is no longer supported."); break; case LLVMDLLExportLinkage: DEBUG(errs() << "LLVMSetLinkage(): LLVMDLLExportLinkage is no longer supported."); break; case LLVMExternalWeakLinkage: GV->setLinkage(GlobalValue::ExternalWeakLinkage); break; case LLVMGhostLinkage: DEBUG(errs() << "LLVMSetLinkage(): LLVMGhostLinkage is no longer supported."); break; case LLVMCommonLinkage: GV->setLinkage(GlobalValue::CommonLinkage); break; } } const char *LLVMGetSection(LLVMValueRef Global) { return unwrap<GlobalValue>(Global)->getSection(); } void LLVMSetSection(LLVMValueRef Global, const char *Section) { unwrap<GlobalObject>(Global)->setSection(Section); } LLVMVisibility LLVMGetVisibility(LLVMValueRef Global) { return static_cast<LLVMVisibility>( unwrap<GlobalValue>(Global)->getVisibility()); } void LLVMSetVisibility(LLVMValueRef Global, LLVMVisibility Viz) { unwrap<GlobalValue>(Global) ->setVisibility(static_cast<GlobalValue::VisibilityTypes>(Viz)); } LLVMDLLStorageClass LLVMGetDLLStorageClass(LLVMValueRef Global) { return static_cast<LLVMDLLStorageClass>( unwrap<GlobalValue>(Global)->getDLLStorageClass()); } void LLVMSetDLLStorageClass(LLVMValueRef Global, LLVMDLLStorageClass Class) { unwrap<GlobalValue>(Global)->setDLLStorageClass( static_cast<GlobalValue::DLLStorageClassTypes>(Class)); } LLVMBool LLVMHasUnnamedAddr(LLVMValueRef Global) { return unwrap<GlobalValue>(Global)->hasUnnamedAddr(); } void LLVMSetUnnamedAddr(LLVMValueRef Global, LLVMBool HasUnnamedAddr) { unwrap<GlobalValue>(Global)->setUnnamedAddr(HasUnnamedAddr); } /*--.. Operations on global variables, load and store instructions .........--*/ unsigned LLVMGetAlignment(LLVMValueRef V) { Value *P = unwrap<Value>(V); if (GlobalValue *GV = dyn_cast<GlobalValue>(P)) return GV->getAlignment(); if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) return AI->getAlignment(); if (LoadInst *LI = dyn_cast<LoadInst>(P)) return LI->getAlignment(); if (StoreInst *SI = dyn_cast<StoreInst>(P)) return SI->getAlignment(); llvm_unreachable( "only GlobalValue, AllocaInst, LoadInst and StoreInst have alignment"); } void LLVMSetAlignment(LLVMValueRef V, unsigned Bytes) { Value *P = unwrap<Value>(V); if (GlobalObject *GV = dyn_cast<GlobalObject>(P)) GV->setAlignment(Bytes); else if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) AI->setAlignment(Bytes); else if (LoadInst *LI = dyn_cast<LoadInst>(P)) LI->setAlignment(Bytes); else if (StoreInst *SI = dyn_cast<StoreInst>(P)) SI->setAlignment(Bytes); else llvm_unreachable( "only GlobalValue, AllocaInst, LoadInst and StoreInst have alignment"); } /*--.. Operations on global variables ......................................--*/ LLVMValueRef LLVMAddGlobal(LLVMModuleRef M, LLVMTypeRef Ty, const char *Name) { return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false, GlobalValue::ExternalLinkage, nullptr, Name)); } LLVMValueRef LLVMAddGlobalInAddressSpace(LLVMModuleRef M, LLVMTypeRef Ty, const char *Name, unsigned AddressSpace) { return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr, GlobalVariable::NotThreadLocal, AddressSpace)); } LLVMValueRef LLVMGetNamedGlobal(LLVMModuleRef M, const char *Name) { return wrap(unwrap(M)->getNamedGlobal(Name)); } LLVMValueRef LLVMGetFirstGlobal(LLVMModuleRef M) { Module *Mod = unwrap(M); Module::global_iterator I = Mod->global_begin(); if (I == Mod->global_end()) return nullptr; return wrap(I); } LLVMValueRef LLVMGetLastGlobal(LLVMModuleRef M) { Module *Mod = unwrap(M); Module::global_iterator I = Mod->global_end(); if (I == Mod->global_begin()) return nullptr; return wrap(--I); } LLVMValueRef LLVMGetNextGlobal(LLVMValueRef GlobalVar) { GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar); Module::global_iterator I = GV; if (++I == GV->getParent()->global_end()) return nullptr; return wrap(I); } LLVMValueRef LLVMGetPreviousGlobal(LLVMValueRef GlobalVar) { GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar); Module::global_iterator I = GV; if (I == GV->getParent()->global_begin()) return nullptr; return wrap(--I); } void LLVMDeleteGlobal(LLVMValueRef GlobalVar) { unwrap<GlobalVariable>(GlobalVar)->eraseFromParent(); } LLVMValueRef LLVMGetInitializer(LLVMValueRef GlobalVar) { GlobalVariable* GV = unwrap<GlobalVariable>(GlobalVar); if ( !GV->hasInitializer() ) return nullptr; return wrap(GV->getInitializer()); } void LLVMSetInitializer(LLVMValueRef GlobalVar, LLVMValueRef ConstantVal) { unwrap<GlobalVariable>(GlobalVar) ->setInitializer(unwrap<Constant>(ConstantVal)); } LLVMBool LLVMIsThreadLocal(LLVMValueRef GlobalVar) { return unwrap<GlobalVariable>(GlobalVar)->isThreadLocal(); } void LLVMSetThreadLocal(LLVMValueRef GlobalVar, LLVMBool IsThreadLocal) { unwrap<GlobalVariable>(GlobalVar)->setThreadLocal(IsThreadLocal != 0); } LLVMBool LLVMIsGlobalConstant(LLVMValueRef GlobalVar) { return unwrap<GlobalVariable>(GlobalVar)->isConstant(); } void LLVMSetGlobalConstant(LLVMValueRef GlobalVar, LLVMBool IsConstant) { unwrap<GlobalVariable>(GlobalVar)->setConstant(IsConstant != 0); } LLVMThreadLocalMode LLVMGetThreadLocalMode(LLVMValueRef GlobalVar) { switch (unwrap<GlobalVariable>(GlobalVar)->getThreadLocalMode()) { case GlobalVariable::NotThreadLocal: return LLVMNotThreadLocal; case GlobalVariable::GeneralDynamicTLSModel: return LLVMGeneralDynamicTLSModel; case GlobalVariable::LocalDynamicTLSModel: return LLVMLocalDynamicTLSModel; case GlobalVariable::InitialExecTLSModel: return LLVMInitialExecTLSModel; case GlobalVariable::LocalExecTLSModel: return LLVMLocalExecTLSModel; } llvm_unreachable("Invalid GlobalVariable thread local mode"); } void LLVMSetThreadLocalMode(LLVMValueRef GlobalVar, LLVMThreadLocalMode Mode) { GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar); switch (Mode) { case LLVMNotThreadLocal: GV->setThreadLocalMode(GlobalVariable::NotThreadLocal); break; case LLVMGeneralDynamicTLSModel: GV->setThreadLocalMode(GlobalVariable::GeneralDynamicTLSModel); break; case LLVMLocalDynamicTLSModel: GV->setThreadLocalMode(GlobalVariable::LocalDynamicTLSModel); break; case LLVMInitialExecTLSModel: GV->setThreadLocalMode(GlobalVariable::InitialExecTLSModel); break; case LLVMLocalExecTLSModel: GV->setThreadLocalMode(GlobalVariable::LocalExecTLSModel); break; } } LLVMBool LLVMIsExternallyInitialized(LLVMValueRef GlobalVar) { return unwrap<GlobalVariable>(GlobalVar)->isExternallyInitialized(); } void LLVMSetExternallyInitialized(LLVMValueRef GlobalVar, LLVMBool IsExtInit) { unwrap<GlobalVariable>(GlobalVar)->setExternallyInitialized(IsExtInit); } /*--.. Operations on aliases ......................................--*/ LLVMValueRef LLVMAddAlias(LLVMModuleRef M, LLVMTypeRef Ty, LLVMValueRef Aliasee, const char *Name) { auto *PTy = cast<PointerType>(unwrap(Ty)); return wrap(GlobalAlias::create(PTy, GlobalValue::ExternalLinkage, Name, unwrap<Constant>(Aliasee), unwrap(M))); } /*--.. Operations on functions .............................................--*/ LLVMValueRef LLVMAddFunction(LLVMModuleRef M, const char *Name, LLVMTypeRef FunctionTy) { return wrap(Function::Create(unwrap<FunctionType>(FunctionTy), GlobalValue::ExternalLinkage, Name, unwrap(M))); } LLVMValueRef LLVMGetNamedFunction(LLVMModuleRef M, const char *Name) { return wrap(unwrap(M)->getFunction(Name)); } LLVMValueRef LLVMGetFirstFunction(LLVMModuleRef M) { Module *Mod = unwrap(M); Module::iterator I = Mod->begin(); if (I == Mod->end()) return nullptr; return wrap(I); } LLVMValueRef LLVMGetLastFunction(LLVMModuleRef M) { Module *Mod = unwrap(M); Module::iterator I = Mod->end(); if (I == Mod->begin()) return nullptr; return wrap(--I); } LLVMValueRef LLVMGetNextFunction(LLVMValueRef Fn) { Function *Func = unwrap<Function>(Fn); Module::iterator I = Func; if (++I == Func->getParent()->end()) return nullptr; return wrap(I); } LLVMValueRef LLVMGetPreviousFunction(LLVMValueRef Fn) { Function *Func = unwrap<Function>(Fn); Module::iterator I = Func; if (I == Func->getParent()->begin()) return nullptr; return wrap(--I); } void LLVMDeleteFunction(LLVMValueRef Fn) { unwrap<Function>(Fn)->eraseFromParent(); } LLVMValueRef LLVMGetPersonalityFn(LLVMValueRef Fn) { return wrap(unwrap<Function>(Fn)->getPersonalityFn()); } void LLVMSetPersonalityFn(LLVMValueRef Fn, LLVMValueRef PersonalityFn) { unwrap<Function>(Fn)->setPersonalityFn(unwrap<Constant>(PersonalityFn)); } unsigned LLVMGetIntrinsicID(LLVMValueRef Fn) { if (Function *F = dyn_cast<Function>(unwrap(Fn))) return F->getIntrinsicID(); return 0; } unsigned LLVMGetFunctionCallConv(LLVMValueRef Fn) { return unwrap<Function>(Fn)->getCallingConv(); } void LLVMSetFunctionCallConv(LLVMValueRef Fn, unsigned CC) { return unwrap<Function>(Fn)->setCallingConv( static_cast<CallingConv::ID>(CC)); } const char *LLVMGetGC(LLVMValueRef Fn) { Function *F = unwrap<Function>(Fn); return F->hasGC()? F->getGC() : nullptr; } void LLVMSetGC(LLVMValueRef Fn, const char *GC) { Function *F = unwrap<Function>(Fn); if (GC) F->setGC(GC); else F->clearGC(); } void LLVMAddFunctionAttr(LLVMValueRef Fn, LLVMAttribute PA) { Function *Func = unwrap<Function>(Fn); const AttributeSet PAL = Func->getAttributes(); AttrBuilder B(PA); const AttributeSet PALnew = PAL.addAttributes(Func->getContext(), AttributeSet::FunctionIndex, AttributeSet::get(Func->getContext(), AttributeSet::FunctionIndex, B)); Func->setAttributes(PALnew); } void LLVMAddTargetDependentFunctionAttr(LLVMValueRef Fn, const char *A, const char *V) { Function *Func = unwrap<Function>(Fn); AttributeSet::AttrIndex Idx = AttributeSet::AttrIndex(AttributeSet::FunctionIndex); AttrBuilder B; B.addAttribute(A, V); AttributeSet Set = AttributeSet::get(Func->getContext(), Idx, B); Func->addAttributes(Idx, Set); } void LLVMRemoveFunctionAttr(LLVMValueRef Fn, LLVMAttribute PA) { Function *Func = unwrap<Function>(Fn); const AttributeSet PAL = Func->getAttributes(); AttrBuilder B(PA); const AttributeSet PALnew = PAL.removeAttributes(Func->getContext(), AttributeSet::FunctionIndex, AttributeSet::get(Func->getContext(), AttributeSet::FunctionIndex, B)); Func->setAttributes(PALnew); } LLVMAttribute LLVMGetFunctionAttr(LLVMValueRef Fn) { Function *Func = unwrap<Function>(Fn); const AttributeSet PAL = Func->getAttributes(); return (LLVMAttribute)PAL.Raw(AttributeSet::FunctionIndex); } /*--.. Operations on parameters ............................................--*/ unsigned LLVMCountParams(LLVMValueRef FnRef) { // This function is strictly redundant to // LLVMCountParamTypes(LLVMGetElementType(LLVMTypeOf(FnRef))) return unwrap<Function>(FnRef)->arg_size(); } void LLVMGetParams(LLVMValueRef FnRef, LLVMValueRef *ParamRefs) { Function *Fn = unwrap<Function>(FnRef); for (Function::arg_iterator I = Fn->arg_begin(), E = Fn->arg_end(); I != E; I++) *ParamRefs++ = wrap(I); } LLVMValueRef LLVMGetParam(LLVMValueRef FnRef, unsigned index) { Function::arg_iterator AI = unwrap<Function>(FnRef)->arg_begin(); while (index --> 0) AI++; return wrap(AI); } LLVMValueRef LLVMGetParamParent(LLVMValueRef V) { return wrap(unwrap<Argument>(V)->getParent()); } LLVMValueRef LLVMGetFirstParam(LLVMValueRef Fn) { Function *Func = unwrap<Function>(Fn); Function::arg_iterator I = Func->arg_begin(); if (I == Func->arg_end()) return nullptr; return wrap(I); } LLVMValueRef LLVMGetLastParam(LLVMValueRef Fn) { Function *Func = unwrap<Function>(Fn); Function::arg_iterator I = Func->arg_end(); if (I == Func->arg_begin()) return nullptr; return wrap(--I); } LLVMValueRef LLVMGetNextParam(LLVMValueRef Arg) { Argument *A = unwrap<Argument>(Arg); Function::arg_iterator I = A; if (++I == A->getParent()->arg_end()) return nullptr; return wrap(I); } LLVMValueRef LLVMGetPreviousParam(LLVMValueRef Arg) { Argument *A = unwrap<Argument>(Arg); Function::arg_iterator I = A; if (I == A->getParent()->arg_begin()) return nullptr; return wrap(--I); } void LLVMAddAttribute(LLVMValueRef Arg, LLVMAttribute PA) { Argument *A = unwrap<Argument>(Arg); AttrBuilder B(PA); A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B)); } void LLVMRemoveAttribute(LLVMValueRef Arg, LLVMAttribute PA) { Argument *A = unwrap<Argument>(Arg); AttrBuilder B(PA); A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B)); } LLVMAttribute LLVMGetAttribute(LLVMValueRef Arg) { Argument *A = unwrap<Argument>(Arg); return (LLVMAttribute)A->getParent()->getAttributes(). Raw(A->getArgNo()+1); } void LLVMSetParamAlignment(LLVMValueRef Arg, unsigned align) { Argument *A = unwrap<Argument>(Arg); AttrBuilder B; B.addAlignmentAttr(align); A->addAttr(AttributeSet::get(A->getContext(),A->getArgNo() + 1, B)); } /*--.. Operations on basic blocks ..........................................--*/ LLVMValueRef LLVMBasicBlockAsValue(LLVMBasicBlockRef BB) { return wrap(static_cast<Value*>(unwrap(BB))); } LLVMBool LLVMValueIsBasicBlock(LLVMValueRef Val) { return isa<BasicBlock>(unwrap(Val)); } LLVMBasicBlockRef LLVMValueAsBasicBlock(LLVMValueRef Val) { return wrap(unwrap<BasicBlock>(Val)); } LLVMValueRef LLVMGetBasicBlockParent(LLVMBasicBlockRef BB) { return wrap(unwrap(BB)->getParent()); } LLVMValueRef LLVMGetBasicBlockTerminator(LLVMBasicBlockRef BB) { return wrap(unwrap(BB)->getTerminator()); } unsigned LLVMCountBasicBlocks(LLVMValueRef FnRef) { return unwrap<Function>(FnRef)->size(); } void LLVMGetBasicBlocks(LLVMValueRef FnRef, LLVMBasicBlockRef *BasicBlocksRefs){ Function *Fn = unwrap<Function>(FnRef); for (Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) *BasicBlocksRefs++ = wrap(I); } LLVMBasicBlockRef LLVMGetEntryBasicBlock(LLVMValueRef Fn) { return wrap(&unwrap<Function>(Fn)->getEntryBlock()); } LLVMBasicBlockRef LLVMGetFirstBasicBlock(LLVMValueRef Fn) { Function *Func = unwrap<Function>(Fn); Function::iterator I = Func->begin(); if (I == Func->end()) return nullptr; return wrap(I); } LLVMBasicBlockRef LLVMGetLastBasicBlock(LLVMValueRef Fn) { Function *Func = unwrap<Function>(Fn); Function::iterator I = Func->end(); if (I == Func->begin()) return nullptr; return wrap(--I); } LLVMBasicBlockRef LLVMGetNextBasicBlock(LLVMBasicBlockRef BB) { BasicBlock *Block = unwrap(BB); Function::iterator I = Block; if (++I == Block->getParent()->end()) return nullptr; return wrap(I); } LLVMBasicBlockRef LLVMGetPreviousBasicBlock(LLVMBasicBlockRef BB) { BasicBlock *Block = unwrap(BB); Function::iterator I = Block; if (I == Block->getParent()->begin()) return nullptr; return wrap(--I); } LLVMBasicBlockRef LLVMAppendBasicBlockInContext(LLVMContextRef C, LLVMValueRef FnRef, const char *Name) { return wrap(BasicBlock::Create(*unwrap(C), Name, unwrap<Function>(FnRef))); } LLVMBasicBlockRef LLVMAppendBasicBlock(LLVMValueRef FnRef, const char *Name) { return LLVMAppendBasicBlockInContext(LLVMGetGlobalContext(), FnRef, Name); } LLVMBasicBlockRef LLVMInsertBasicBlockInContext(LLVMContextRef C, LLVMBasicBlockRef BBRef, const char *Name) { BasicBlock *BB = unwrap(BBRef); return wrap(BasicBlock::Create(*unwrap(C), Name, BB->getParent(), BB)); } LLVMBasicBlockRef LLVMInsertBasicBlock(LLVMBasicBlockRef BBRef, const char *Name) { return LLVMInsertBasicBlockInContext(LLVMGetGlobalContext(), BBRef, Name); } void LLVMDeleteBasicBlock(LLVMBasicBlockRef BBRef) { unwrap(BBRef)->eraseFromParent(); } void LLVMRemoveBasicBlockFromParent(LLVMBasicBlockRef BBRef) { unwrap(BBRef)->removeFromParent(); } void LLVMMoveBasicBlockBefore(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos) { unwrap(BB)->moveBefore(unwrap(MovePos)); } void LLVMMoveBasicBlockAfter(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos) { unwrap(BB)->moveAfter(unwrap(MovePos)); } /*--.. Operations on instructions ..........................................--*/ LLVMBasicBlockRef LLVMGetInstructionParent(LLVMValueRef Inst) { return wrap(unwrap<Instruction>(Inst)->getParent()); } LLVMValueRef LLVMGetFirstInstruction(LLVMBasicBlockRef BB) { BasicBlock *Block = unwrap(BB); BasicBlock::iterator I = Block->begin(); if (I == Block->end()) return nullptr; return wrap(I); } LLVMValueRef LLVMGetLastInstruction(LLVMBasicBlockRef BB) { BasicBlock *Block = unwrap(BB); BasicBlock::iterator I = Block->end(); if (I == Block->begin()) return nullptr; return wrap(--I); } LLVMValueRef LLVMGetNextInstruction(LLVMValueRef Inst) { Instruction *Instr = unwrap<Instruction>(Inst); BasicBlock::iterator I = Instr; if (++I == Instr->getParent()->end()) return nullptr; return wrap(I); } LLVMValueRef LLVMGetPreviousInstruction(LLVMValueRef Inst) { Instruction *Instr = unwrap<Instruction>(Inst); BasicBlock::iterator I = Instr; if (I == Instr->getParent()->begin()) return nullptr; return wrap(--I); } void LLVMInstructionEraseFromParent(LLVMValueRef Inst) { unwrap<Instruction>(Inst)->eraseFromParent(); } LLVMIntPredicate LLVMGetICmpPredicate(LLVMValueRef Inst) { if (ICmpInst *I = dyn_cast<ICmpInst>(unwrap(Inst))) return (LLVMIntPredicate)I->getPredicate(); if (ConstantExpr *CE = dyn_cast<ConstantExpr>(unwrap(Inst))) if (CE->getOpcode() == Instruction::ICmp) return (LLVMIntPredicate)CE->getPredicate(); return (LLVMIntPredicate)0; } LLVMRealPredicate LLVMGetFCmpPredicate(LLVMValueRef Inst) { if (FCmpInst *I = dyn_cast<FCmpInst>(unwrap(Inst))) return (LLVMRealPredicate)I->getPredicate(); if (ConstantExpr *CE = dyn_cast<ConstantExpr>(unwrap(Inst))) if (CE->getOpcode() == Instruction::FCmp) return (LLVMRealPredicate)CE->getPredicate(); return (LLVMRealPredicate)0; } LLVMOpcode LLVMGetInstructionOpcode(LLVMValueRef Inst) { if (Instruction *C = dyn_cast<Instruction>(unwrap(Inst))) return map_to_llvmopcode(C->getOpcode()); return (LLVMOpcode)0; } LLVMValueRef LLVMInstructionClone(LLVMValueRef Inst) { if (Instruction *C = dyn_cast<Instruction>(unwrap(Inst))) return wrap(C->clone()); return nullptr; } /*--.. Call and invoke instructions ........................................--*/ unsigned LLVMGetInstructionCallConv(LLVMValueRef Instr) { Value *V = unwrap(Instr); if (CallInst *CI = dyn_cast<CallInst>(V)) return CI->getCallingConv(); if (InvokeInst *II = dyn_cast<InvokeInst>(V)) return II->getCallingConv(); llvm_unreachable("LLVMGetInstructionCallConv applies only to call and invoke!"); } void LLVMSetInstructionCallConv(LLVMValueRef Instr, unsigned CC) { Value *V = unwrap(Instr); if (CallInst *CI = dyn_cast<CallInst>(V)) return CI->setCallingConv(static_cast<CallingConv::ID>(CC)); else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) return II->setCallingConv(static_cast<CallingConv::ID>(CC)); llvm_unreachable("LLVMSetInstructionCallConv applies only to call and invoke!"); } void LLVMAddInstrAttribute(LLVMValueRef Instr, unsigned index, LLVMAttribute PA) { CallSite Call = CallSite(unwrap<Instruction>(Instr)); AttrBuilder B(PA); Call.setAttributes( Call.getAttributes().addAttributes(Call->getContext(), index, AttributeSet::get(Call->getContext(), index, B))); } void LLVMRemoveInstrAttribute(LLVMValueRef Instr, unsigned index, LLVMAttribute PA) { CallSite Call = CallSite(unwrap<Instruction>(Instr)); AttrBuilder B(PA); Call.setAttributes(Call.getAttributes() .removeAttributes(Call->getContext(), index, AttributeSet::get(Call->getContext(), index, B))); } void LLVMSetInstrParamAlignment(LLVMValueRef Instr, unsigned index, unsigned align) { CallSite Call = CallSite(unwrap<Instruction>(Instr)); AttrBuilder B; B.addAlignmentAttr(align); Call.setAttributes(Call.getAttributes() .addAttributes(Call->getContext(), index, AttributeSet::get(Call->getContext(), index, B))); } /*--.. Operations on call instructions (only) ..............................--*/ LLVMBool LLVMIsTailCall(LLVMValueRef Call) { return unwrap<CallInst>(Call)->isTailCall(); } void LLVMSetTailCall(LLVMValueRef Call, LLVMBool isTailCall) { unwrap<CallInst>(Call)->setTailCall(isTailCall); } /*--.. Operations on terminators ...........................................--*/ unsigned LLVMGetNumSuccessors(LLVMValueRef Term) { return unwrap<TerminatorInst>(Term)->getNumSuccessors(); } LLVMBasicBlockRef LLVMGetSuccessor(LLVMValueRef Term, unsigned i) { return wrap(unwrap<TerminatorInst>(Term)->getSuccessor(i)); } void LLVMSetSuccessor(LLVMValueRef Term, unsigned i, LLVMBasicBlockRef block) { return unwrap<TerminatorInst>(Term)->setSuccessor(i,unwrap(block)); } /*--.. Operations on branch instructions (only) ............................--*/ LLVMBool LLVMIsConditional(LLVMValueRef Branch) { return unwrap<BranchInst>(Branch)->isConditional(); } LLVMValueRef LLVMGetCondition(LLVMValueRef Branch) { return wrap(unwrap<BranchInst>(Branch)->getCondition()); } void LLVMSetCondition(LLVMValueRef Branch, LLVMValueRef Cond) { return unwrap<BranchInst>(Branch)->setCondition(unwrap(Cond)); } /*--.. Operations on switch instructions (only) ............................--*/ LLVMBasicBlockRef LLVMGetSwitchDefaultDest(LLVMValueRef Switch) { return wrap(unwrap<SwitchInst>(Switch)->getDefaultDest()); } /*--.. Operations on phi nodes .............................................--*/ void LLVMAddIncoming(LLVMValueRef PhiNode, LLVMValueRef *IncomingValues, LLVMBasicBlockRef *IncomingBlocks, unsigned Count) { PHINode *PhiVal = unwrap<PHINode>(PhiNode); for (unsigned I = 0; I != Count; ++I) PhiVal->addIncoming(unwrap(IncomingValues[I]), unwrap(IncomingBlocks[I])); } unsigned LLVMCountIncoming(LLVMValueRef PhiNode) { return unwrap<PHINode>(PhiNode)->getNumIncomingValues(); } LLVMValueRef LLVMGetIncomingValue(LLVMValueRef PhiNode, unsigned Index) { return wrap(unwrap<PHINode>(PhiNode)->getIncomingValue(Index)); } LLVMBasicBlockRef LLVMGetIncomingBlock(LLVMValueRef PhiNode, unsigned Index) { return wrap(unwrap<PHINode>(PhiNode)->getIncomingBlock(Index)); } /*===-- Instruction builders ----------------------------------------------===*/ LLVMBuilderRef LLVMCreateBuilderInContext(LLVMContextRef C) { return wrap(new IRBuilder<>(*unwrap(C))); } LLVMBuilderRef LLVMCreateBuilder(void) { return LLVMCreateBuilderInContext(LLVMGetGlobalContext()); } void LLVMPositionBuilder(LLVMBuilderRef Builder, LLVMBasicBlockRef Block, LLVMValueRef Instr) { BasicBlock *BB = unwrap(Block); Instruction *I = Instr? unwrap<Instruction>(Instr) : (Instruction*) BB->end(); unwrap(Builder)->SetInsertPoint(BB, I); } void LLVMPositionBuilderBefore(LLVMBuilderRef Builder, LLVMValueRef Instr) { Instruction *I = unwrap<Instruction>(Instr); unwrap(Builder)->SetInsertPoint(I->getParent(), I); } void LLVMPositionBuilderAtEnd(LLVMBuilderRef Builder, LLVMBasicBlockRef Block) { BasicBlock *BB = unwrap(Block); unwrap(Builder)->SetInsertPoint(BB); } LLVMBasicBlockRef LLVMGetInsertBlock(LLVMBuilderRef Builder) { return wrap(unwrap(Builder)->GetInsertBlock()); } void LLVMClearInsertionPosition(LLVMBuilderRef Builder) { unwrap(Builder)->ClearInsertionPoint(); } void LLVMInsertIntoBuilder(LLVMBuilderRef Builder, LLVMValueRef Instr) { unwrap(Builder)->Insert(unwrap<Instruction>(Instr)); } void LLVMInsertIntoBuilderWithName(LLVMBuilderRef Builder, LLVMValueRef Instr, const char *Name) { unwrap(Builder)->Insert(unwrap<Instruction>(Instr), Name); } void LLVMDisposeBuilder(LLVMBuilderRef Builder) { delete unwrap(Builder); } /*--.. Metadata builders ...................................................--*/ void LLVMSetCurrentDebugLocation(LLVMBuilderRef Builder, LLVMValueRef L) { MDNode *Loc = L ? cast<MDNode>(unwrap<MetadataAsValue>(L)->getMetadata()) : nullptr; unwrap(Builder)->SetCurrentDebugLocation(DebugLoc(Loc)); } LLVMValueRef LLVMGetCurrentDebugLocation(LLVMBuilderRef Builder) { LLVMContext &Context = unwrap(Builder)->getContext(); return wrap(MetadataAsValue::get( Context, unwrap(Builder)->getCurrentDebugLocation().getAsMDNode())); } void LLVMSetInstDebugLocation(LLVMBuilderRef Builder, LLVMValueRef Inst) { unwrap(Builder)->SetInstDebugLocation(unwrap<Instruction>(Inst)); } /*--.. Instruction builders ................................................--*/ LLVMValueRef LLVMBuildRetVoid(LLVMBuilderRef B) { return wrap(unwrap(B)->CreateRetVoid()); } LLVMValueRef LLVMBuildRet(LLVMBuilderRef B, LLVMValueRef V) { return wrap(unwrap(B)->CreateRet(unwrap(V))); } LLVMValueRef LLVMBuildAggregateRet(LLVMBuilderRef B, LLVMValueRef *RetVals, unsigned N) { return wrap(unwrap(B)->CreateAggregateRet(unwrap(RetVals), N)); } LLVMValueRef LLVMBuildBr(LLVMBuilderRef B, LLVMBasicBlockRef Dest) { return wrap(unwrap(B)->CreateBr(unwrap(Dest))); } LLVMValueRef LLVMBuildCondBr(LLVMBuilderRef B, LLVMValueRef If, LLVMBasicBlockRef Then, LLVMBasicBlockRef Else) { return wrap(unwrap(B)->CreateCondBr(unwrap(If), unwrap(Then), unwrap(Else))); } LLVMValueRef LLVMBuildSwitch(LLVMBuilderRef B, LLVMValueRef V, LLVMBasicBlockRef Else, unsigned NumCases) { return wrap(unwrap(B)->CreateSwitch(unwrap(V), unwrap(Else), NumCases)); } LLVMValueRef LLVMBuildIndirectBr(LLVMBuilderRef B, LLVMValueRef Addr, unsigned NumDests) { return wrap(unwrap(B)->CreateIndirectBr(unwrap(Addr), NumDests)); } LLVMValueRef LLVMBuildInvoke(LLVMBuilderRef B, LLVMValueRef Fn, LLVMValueRef *Args, unsigned NumArgs, LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch, const char *Name) { return wrap(unwrap(B)->CreateInvoke(unwrap(Fn), unwrap(Then), unwrap(Catch), makeArrayRef(unwrap(Args), NumArgs), Name)); } LLVMValueRef LLVMBuildLandingPad(LLVMBuilderRef B, LLVMTypeRef Ty, unsigned NumClauses, const char *Name) { return wrap(unwrap(B)->CreateLandingPad(unwrap(Ty), NumClauses, Name)); } LLVMValueRef LLVMBuildResume(LLVMBuilderRef B, LLVMValueRef Exn) { return wrap(unwrap(B)->CreateResume(unwrap(Exn))); } LLVMValueRef LLVMBuildUnreachable(LLVMBuilderRef B) { return wrap(unwrap(B)->CreateUnreachable()); } void LLVMAddCase(LLVMValueRef Switch, LLVMValueRef OnVal, LLVMBasicBlockRef Dest) { unwrap<SwitchInst>(Switch)->addCase(unwrap<ConstantInt>(OnVal), unwrap(Dest)); } void LLVMAddDestination(LLVMValueRef IndirectBr, LLVMBasicBlockRef Dest) { unwrap<IndirectBrInst>(IndirectBr)->addDestination(unwrap(Dest)); } void LLVMAddClause(LLVMValueRef LandingPad, LLVMValueRef ClauseVal) { unwrap<LandingPadInst>(LandingPad)-> addClause(cast<Constant>(unwrap(ClauseVal))); } void LLVMSetCleanup(LLVMValueRef LandingPad, LLVMBool Val) { unwrap<LandingPadInst>(LandingPad)->setCleanup(Val); } /*--.. Arithmetic ..........................................................--*/ LLVMValueRef LLVMBuildAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateAdd(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildNSWAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateNSWAdd(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildNUWAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateNUWAdd(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildFAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateFAdd(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateSub(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildNSWSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateNSWSub(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildNUWSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateNUWSub(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildFSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateFSub(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateMul(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildNSWMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateNSWMul(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildNUWMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateNUWMul(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildFMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateFMul(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildUDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateUDiv(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildSDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateSDiv(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildExactSDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateExactSDiv(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildFDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateFDiv(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildURem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateURem(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildSRem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateSRem(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildFRem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateFRem(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildShl(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateShl(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildLShr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateLShr(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildAShr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateAShr(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildAnd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateAnd(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildOr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateOr(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildXor(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateXor(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildBinOp(LLVMBuilderRef B, LLVMOpcode Op, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateBinOp(Instruction::BinaryOps(map_from_llvmopcode(Op)), unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildNeg(LLVMBuilderRef B, LLVMValueRef V, const char *Name) { return wrap(unwrap(B)->CreateNeg(unwrap(V), Name)); } LLVMValueRef LLVMBuildNSWNeg(LLVMBuilderRef B, LLVMValueRef V, const char *Name) { return wrap(unwrap(B)->CreateNSWNeg(unwrap(V), Name)); } LLVMValueRef LLVMBuildNUWNeg(LLVMBuilderRef B, LLVMValueRef V, const char *Name) { return wrap(unwrap(B)->CreateNUWNeg(unwrap(V), Name)); } LLVMValueRef LLVMBuildFNeg(LLVMBuilderRef B, LLVMValueRef V, const char *Name) { return wrap(unwrap(B)->CreateFNeg(unwrap(V), Name)); } LLVMValueRef LLVMBuildNot(LLVMBuilderRef B, LLVMValueRef V, const char *Name) { return wrap(unwrap(B)->CreateNot(unwrap(V), Name)); } /*--.. Memory ..............................................................--*/ LLVMValueRef LLVMBuildMalloc(LLVMBuilderRef B, LLVMTypeRef Ty, const char *Name) { Type* ITy = Type::getInt32Ty(unwrap(B)->GetInsertBlock()->getContext()); Constant* AllocSize = ConstantExpr::getSizeOf(unwrap(Ty)); AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, ITy); Instruction* Malloc = CallInst::CreateMalloc(unwrap(B)->GetInsertBlock(), ITy, unwrap(Ty), AllocSize, nullptr, nullptr, ""); return wrap(unwrap(B)->Insert(Malloc, Twine(Name))); } LLVMValueRef LLVMBuildArrayMalloc(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Val, const char *Name) { Type* ITy = Type::getInt32Ty(unwrap(B)->GetInsertBlock()->getContext()); Constant* AllocSize = ConstantExpr::getSizeOf(unwrap(Ty)); AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, ITy); Instruction* Malloc = CallInst::CreateMalloc(unwrap(B)->GetInsertBlock(), ITy, unwrap(Ty), AllocSize, unwrap(Val), nullptr, ""); return wrap(unwrap(B)->Insert(Malloc, Twine(Name))); } LLVMValueRef LLVMBuildAlloca(LLVMBuilderRef B, LLVMTypeRef Ty, const char *Name) { return wrap(unwrap(B)->CreateAlloca(unwrap(Ty), nullptr, Name)); } LLVMValueRef LLVMBuildArrayAlloca(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Val, const char *Name) { return wrap(unwrap(B)->CreateAlloca(unwrap(Ty), unwrap(Val), Name)); } LLVMValueRef LLVMBuildFree(LLVMBuilderRef B, LLVMValueRef PointerVal) { return wrap(unwrap(B)->Insert( CallInst::CreateFree(unwrap(PointerVal), unwrap(B)->GetInsertBlock()))); } LLVMValueRef LLVMBuildLoad(LLVMBuilderRef B, LLVMValueRef PointerVal, const char *Name) { return wrap(unwrap(B)->CreateLoad(unwrap(PointerVal), Name)); } LLVMValueRef LLVMBuildStore(LLVMBuilderRef B, LLVMValueRef Val, LLVMValueRef PointerVal) { return wrap(unwrap(B)->CreateStore(unwrap(Val), unwrap(PointerVal))); } static AtomicOrdering mapFromLLVMOrdering(LLVMAtomicOrdering Ordering) { switch (Ordering) { case LLVMAtomicOrderingNotAtomic: return NotAtomic; case LLVMAtomicOrderingUnordered: return Unordered; case LLVMAtomicOrderingMonotonic: return Monotonic; case LLVMAtomicOrderingAcquire: return Acquire; case LLVMAtomicOrderingRelease: return Release; case LLVMAtomicOrderingAcquireRelease: return AcquireRelease; case LLVMAtomicOrderingSequentiallyConsistent: return SequentiallyConsistent; } llvm_unreachable("Invalid LLVMAtomicOrdering value!"); } LLVMValueRef LLVMBuildFence(LLVMBuilderRef B, LLVMAtomicOrdering Ordering, LLVMBool isSingleThread, const char *Name) { return wrap( unwrap(B)->CreateFence(mapFromLLVMOrdering(Ordering), isSingleThread ? SingleThread : CrossThread, Name)); } LLVMValueRef LLVMBuildGEP(LLVMBuilderRef B, LLVMValueRef Pointer, LLVMValueRef *Indices, unsigned NumIndices, const char *Name) { ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices); return wrap(unwrap(B)->CreateGEP(nullptr, unwrap(Pointer), IdxList, Name)); } LLVMValueRef LLVMBuildInBoundsGEP(LLVMBuilderRef B, LLVMValueRef Pointer, LLVMValueRef *Indices, unsigned NumIndices, const char *Name) { ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices); return wrap( unwrap(B)->CreateInBoundsGEP(nullptr, unwrap(Pointer), IdxList, Name)); } LLVMValueRef LLVMBuildStructGEP(LLVMBuilderRef B, LLVMValueRef Pointer, unsigned Idx, const char *Name) { return wrap(unwrap(B)->CreateStructGEP(nullptr, unwrap(Pointer), Idx, Name)); } LLVMValueRef LLVMBuildGlobalString(LLVMBuilderRef B, const char *Str, const char *Name) { return wrap(unwrap(B)->CreateGlobalString(Str, Name)); } LLVMValueRef LLVMBuildGlobalStringPtr(LLVMBuilderRef B, const char *Str, const char *Name) { return wrap(unwrap(B)->CreateGlobalStringPtr(Str, Name)); } LLVMBool LLVMGetVolatile(LLVMValueRef MemAccessInst) { Value *P = unwrap<Value>(MemAccessInst); if (LoadInst *LI = dyn_cast<LoadInst>(P)) return LI->isVolatile(); return cast<StoreInst>(P)->isVolatile(); } void LLVMSetVolatile(LLVMValueRef MemAccessInst, LLVMBool isVolatile) { Value *P = unwrap<Value>(MemAccessInst); if (LoadInst *LI = dyn_cast<LoadInst>(P)) return LI->setVolatile(isVolatile); return cast<StoreInst>(P)->setVolatile(isVolatile); } /*--.. Casts ...............................................................--*/ LLVMValueRef LLVMBuildTrunc(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateTrunc(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildZExt(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateZExt(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildSExt(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateSExt(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildFPToUI(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateFPToUI(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildFPToSI(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateFPToSI(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildUIToFP(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateUIToFP(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildSIToFP(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateSIToFP(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildFPTrunc(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateFPTrunc(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildFPExt(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateFPExt(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildPtrToInt(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreatePtrToInt(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildIntToPtr(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateIntToPtr(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildBitCast(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateBitCast(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildAddrSpaceCast(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateAddrSpaceCast(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildZExtOrBitCast(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateZExtOrBitCast(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildSExtOrBitCast(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateSExtOrBitCast(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildTruncOrBitCast(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateTruncOrBitCast(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildCast(LLVMBuilderRef B, LLVMOpcode Op, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateCast(Instruction::CastOps(map_from_llvmopcode(Op)), unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildPointerCast(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreatePointerCast(unwrap(Val), unwrap(DestTy), Name)); } LLVMValueRef LLVMBuildIntCast(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy), /*isSigned*/true, Name)); } LLVMValueRef LLVMBuildFPCast(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, const char *Name) { return wrap(unwrap(B)->CreateFPCast(unwrap(Val), unwrap(DestTy), Name)); } /*--.. Comparisons .........................................................--*/ LLVMValueRef LLVMBuildICmp(LLVMBuilderRef B, LLVMIntPredicate Op, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateICmp(static_cast<ICmpInst::Predicate>(Op), unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildFCmp(LLVMBuilderRef B, LLVMRealPredicate Op, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreateFCmp(static_cast<FCmpInst::Predicate>(Op), unwrap(LHS), unwrap(RHS), Name)); } /*--.. Miscellaneous instructions ..........................................--*/ LLVMValueRef LLVMBuildPhi(LLVMBuilderRef B, LLVMTypeRef Ty, const char *Name) { return wrap(unwrap(B)->CreatePHI(unwrap(Ty), 0, Name)); } LLVMValueRef LLVMBuildCall(LLVMBuilderRef B, LLVMValueRef Fn, LLVMValueRef *Args, unsigned NumArgs, const char *Name) { return wrap(unwrap(B)->CreateCall(unwrap(Fn), makeArrayRef(unwrap(Args), NumArgs), Name)); } LLVMValueRef LLVMBuildSelect(LLVMBuilderRef B, LLVMValueRef If, LLVMValueRef Then, LLVMValueRef Else, const char *Name) { return wrap(unwrap(B)->CreateSelect(unwrap(If), unwrap(Then), unwrap(Else), Name)); } LLVMValueRef LLVMBuildVAArg(LLVMBuilderRef B, LLVMValueRef List, LLVMTypeRef Ty, const char *Name) { return wrap(unwrap(B)->CreateVAArg(unwrap(List), unwrap(Ty), Name)); } LLVMValueRef LLVMBuildExtractElement(LLVMBuilderRef B, LLVMValueRef VecVal, LLVMValueRef Index, const char *Name) { return wrap(unwrap(B)->CreateExtractElement(unwrap(VecVal), unwrap(Index), Name)); } LLVMValueRef LLVMBuildInsertElement(LLVMBuilderRef B, LLVMValueRef VecVal, LLVMValueRef EltVal, LLVMValueRef Index, const char *Name) { return wrap(unwrap(B)->CreateInsertElement(unwrap(VecVal), unwrap(EltVal), unwrap(Index), Name)); } LLVMValueRef LLVMBuildShuffleVector(LLVMBuilderRef B, LLVMValueRef V1, LLVMValueRef V2, LLVMValueRef Mask, const char *Name) { return wrap(unwrap(B)->CreateShuffleVector(unwrap(V1), unwrap(V2), unwrap(Mask), Name)); } LLVMValueRef LLVMBuildExtractValue(LLVMBuilderRef B, LLVMValueRef AggVal, unsigned Index, const char *Name) { return wrap(unwrap(B)->CreateExtractValue(unwrap(AggVal), Index, Name)); } LLVMValueRef LLVMBuildInsertValue(LLVMBuilderRef B, LLVMValueRef AggVal, LLVMValueRef EltVal, unsigned Index, const char *Name) { return wrap(unwrap(B)->CreateInsertValue(unwrap(AggVal), unwrap(EltVal), Index, Name)); } LLVMValueRef LLVMBuildIsNull(LLVMBuilderRef B, LLVMValueRef Val, const char *Name) { return wrap(unwrap(B)->CreateIsNull(unwrap(Val), Name)); } LLVMValueRef LLVMBuildIsNotNull(LLVMBuilderRef B, LLVMValueRef Val, const char *Name) { return wrap(unwrap(B)->CreateIsNotNull(unwrap(Val), Name)); } LLVMValueRef LLVMBuildPtrDiff(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name) { return wrap(unwrap(B)->CreatePtrDiff(unwrap(LHS), unwrap(RHS), Name)); } LLVMValueRef LLVMBuildAtomicRMW(LLVMBuilderRef B,LLVMAtomicRMWBinOp op, LLVMValueRef PTR, LLVMValueRef Val, LLVMAtomicOrdering ordering, LLVMBool singleThread) { AtomicRMWInst::BinOp intop; switch (op) { case LLVMAtomicRMWBinOpXchg: intop = AtomicRMWInst::Xchg; break; case LLVMAtomicRMWBinOpAdd: intop = AtomicRMWInst::Add; break; case LLVMAtomicRMWBinOpSub: intop = AtomicRMWInst::Sub; break; case LLVMAtomicRMWBinOpAnd: intop = AtomicRMWInst::And; break; case LLVMAtomicRMWBinOpNand: intop = AtomicRMWInst::Nand; break; case LLVMAtomicRMWBinOpOr: intop = AtomicRMWInst::Or; break; case LLVMAtomicRMWBinOpXor: intop = AtomicRMWInst::Xor; break; case LLVMAtomicRMWBinOpMax: intop = AtomicRMWInst::Max; break; case LLVMAtomicRMWBinOpMin: intop = AtomicRMWInst::Min; break; case LLVMAtomicRMWBinOpUMax: intop = AtomicRMWInst::UMax; break; case LLVMAtomicRMWBinOpUMin: intop = AtomicRMWInst::UMin; break; } return wrap(unwrap(B)->CreateAtomicRMW(intop, unwrap(PTR), unwrap(Val), mapFromLLVMOrdering(ordering), singleThread ? SingleThread : CrossThread)); } /*===-- Module providers --------------------------------------------------===*/ LLVMModuleProviderRef LLVMCreateModuleProviderForExistingModule(LLVMModuleRef M) { return reinterpret_cast<LLVMModuleProviderRef>(M); } void LLVMDisposeModuleProvider(LLVMModuleProviderRef MP) { delete unwrap(MP); } /*===-- Memory buffers ----------------------------------------------------===*/ LLVMBool LLVMCreateMemoryBufferWithContentsOfFile( const char *Path, LLVMMemoryBufferRef *OutMemBuf, char **OutMessage) { ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(Path); if (std::error_code EC = MBOrErr.getError()) { *OutMessage = strdup(EC.message().c_str()); return 1; } *OutMemBuf = wrap(MBOrErr.get().release()); return 0; } LLVMBool LLVMCreateMemoryBufferWithSTDIN(LLVMMemoryBufferRef *OutMemBuf, char **OutMessage) { ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getSTDIN(); if (std::error_code EC = MBOrErr.getError()) { *OutMessage = strdup(EC.message().c_str()); return 1; } *OutMemBuf = wrap(MBOrErr.get().release()); return 0; } LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRange( const char *InputData, size_t InputDataLength, const char *BufferName, LLVMBool RequiresNullTerminator) { return wrap(MemoryBuffer::getMemBuffer(StringRef(InputData, InputDataLength), StringRef(BufferName), RequiresNullTerminator).release()); } LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRangeCopy( const char *InputData, size_t InputDataLength, const char *BufferName) { return wrap( MemoryBuffer::getMemBufferCopy(StringRef(InputData, InputDataLength), StringRef(BufferName)).release()); } const char *LLVMGetBufferStart(LLVMMemoryBufferRef MemBuf) { return unwrap(MemBuf)->getBufferStart(); } size_t LLVMGetBufferSize(LLVMMemoryBufferRef MemBuf) { return unwrap(MemBuf)->getBufferSize(); } void LLVMDisposeMemoryBuffer(LLVMMemoryBufferRef MemBuf) { delete unwrap(MemBuf); } /*===-- Pass Registry -----------------------------------------------------===*/ LLVMPassRegistryRef LLVMGetGlobalPassRegistry(void) { return wrap(PassRegistry::getPassRegistry()); } /*===-- Pass Manager ------------------------------------------------------===*/ LLVMPassManagerRef LLVMCreatePassManager() { return wrap(new legacy::PassManager()); } LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M) { return wrap(new legacy::FunctionPassManager(unwrap(M))); } LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) { return LLVMCreateFunctionPassManagerForModule( reinterpret_cast<LLVMModuleRef>(P)); } LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) { return unwrap<legacy::PassManager>(PM)->run(*unwrap(M)); } LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) { return unwrap<legacy::FunctionPassManager>(FPM)->doInitialization(); } LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) { return unwrap<legacy::FunctionPassManager>(FPM)->run(*unwrap<Function>(F)); } LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) { return unwrap<legacy::FunctionPassManager>(FPM)->doFinalization(); } void LLVMDisposePassManager(LLVMPassManagerRef PM) { delete unwrap(PM); } /*===-- Threading ------------------------------------------------------===*/ LLVMBool LLVMStartMultithreaded() { return LLVMIsMultithreaded(); } void LLVMStopMultithreaded() { } LLVMBool LLVMIsMultithreaded() { return llvm_is_multithreaded(); }
[ "yuri410@users.noreply.github.com" ]
yuri410@users.noreply.github.com
beee2cad5e2eb48c582291cbc11d688a82b4453a
913a2afce0fe97bd62687d0cbe320f97ad42e571
/ZeeDHistManager/src/ZeeDHistManagerPrint.cxx
6a2745098618896341481018d568a91581f5559c
[]
no_license
kgasniko/ZeeD2p76
028f5d4be09f0928c71c4972a877ef90be6af80a
0bafb5767078bce5bfca31409d77d5491012417a
refs/heads/master
2020-04-06T03:31:55.595961
2017-11-22T10:16:35
2017-11-22T10:16:35
61,799,124
0
0
null
null
null
null
UTF-8
C++
false
false
3,963
cxx
#include "ZeeDHistManager/ZeeDHistManagerPrint.h" // Analysis includes #include "ZeeDEvent/ZeeDEvent.h" #include "ZeeDEvent/ZeeDElectron.h" #include "ZeeDEvent/ZeeDBosonZ.h" #include "ZeeDCuts/ZeeDCutHistManager.h" #include "ZeeDTools/ZeeDCutBit.h" #include "ZeeDMisc/ZeeDMisc.h" #include "ZeeDTools/ZeeDBags.h" #define DEBUG_ON 0 #include <TArrayF.h> #include <iostream> //------------------------------------------------------ ZeeDHistManagerPrint::ZeeDHistManagerPrint(TString name) : ZeeDHistManager(name) { // Constructor Bfile = new TFile(name + ".root", "RECREATE"); treeOut = new TTree("T", "Test treeOut"); e1 = new TLorentzVector; e2 = new TLorentzVector; e1Cl = new TLorentzVector; e2Cl = new TLorentzVector; mZ = new TLorentzVector; ISEM[0] = 0; ISEM[1] = 0; Author[0] = 0; Author[1] = 0; OQMaps[0] = 0; OQMaps[1] = 0; Charge[0] = 0; Charge[1] = 0; Run = 0; LB = 0; Evt = 0; treeOut->Branch("e1", "TLorentzVector", &e1, 16000, 1); treeOut->Branch("e2", "TLorentzVector", &e2, 16000, 1); treeOut->Branch("e1Cl", "TLorentzVector", &e1, 16000, 1); treeOut->Branch("e2Cl", "TLorentzVector", &e2, 16000, 1); treeOut->Branch("Z", "TLorentzVector", &mZ, 16000, 1); treeOut->Branch("ISEM", &ISEM, "ISEM[2]/S"); treeOut->Branch("Author", &Author, "Author[2]/S"); treeOut->Branch("OQMaps", &OQMaps, "OQMaps[2]/S"); treeOut->Branch("Charge", &Charge, "Charge[2]/S"); treeOut->Branch("Run", &Run, "Run/I"); treeOut->Branch("LB", &LB, "LB/I"); treeOut->Branch("Evt", &Evt, "Evt/I"); } //------------------------------------------------------ void ZeeDHistManagerPrint::BookHistos() { DEBUG_MES_START; // Books histograms DEBUG_MES_END; } //------------------------------------------------------ ZeeDHistManagerPrint::~ZeeDHistManagerPrint() { } //------------------------------------------------------ void ZeeDHistManagerPrint::Fill() { // Get event const ZeeDEvent* Event = GetEvent(); const ZeeDBosonZ* ZBos = Event->GetCurrentBoson(); const ZeeDElectron* el1 = (ZeeDElectron*)ZBos->GetFirstLep(); const ZeeDElectron* el2 = (ZeeDElectron*)ZBos->GetSecondLep(); if ( (ZBos == NULL) || (el1 == NULL) || (el2 == NULL)) { return; } TLorentzVector V1 = el1->GetFourVector(); TLorentzVector V2 = el2->GetFourVector(); TLorentzVector V1Cl = el1->Cluster().Get().fourVector; TLorentzVector V2Cl = el1->Cluster().Get().fourVector; TLorentzVector Z = ZBos->GetFourVector(); if ( Event->RunNumber().IsSet() ) { Run = Event->RunNumber().Get(); LB = Event->LB().Get(); Evt = Event->EventNumber().Get(); } if ( el1->IsEM().IsSet() ) { ISEM[0] = el1->IsEM().Get().ZeeDLeptonBags::IsEM::isMedium; } if ( el2->IsEM().IsSet() ) { ISEM[1] = el2->IsEM().Get().ZeeDLeptonBags::IsEM::isMedium; } if(el1->Author().IsSet()) { Author[0] = el1->Author().Get().isElectron; } if(el2->Author().IsSet()) { Author[1] = el2->Author().Get().isElectron; } Charge[0] = el1->getCharge(); Charge[1] = el2->getCharge(); e1->SetPxPyPzE(V1.Px(), V1.Py(), V1.Pz(), V1.E()); e2->SetPxPyPzE(V2.Px(), V2.Py(), V2.Pz(), V2.E()); if (el1->Cluster().IsSet()) { e1Cl->SetPxPyPzE(V1Cl.Px(), V1Cl.Py(), V1Cl.Pz(), V1Cl.E()); } else { e1Cl->SetPxPyPzE(0, 0, 0, 0); } if (el2->Cluster().IsSet()) { e2Cl->SetPxPyPzE(V2Cl.Px(), V2Cl.Py(), V2Cl.Pz(), V2Cl.E()); } else { e2Cl->SetPxPyPzE(0, 0, 0, 0); } mZ->SetPxPyPzE(Z.Px(), Z.Py(), Z.Pz(), Z.E()); treeOut->Fill(); } //------------------------------------------------------ void ZeeDHistManagerPrint::Finalize() { Info("ZeeDHistManagerPrint::Finalize", " Close TTree "); Bfile->Write(); Bfile->Close(); }
[ "ksugasnikova@gmail.com" ]
ksugasnikova@gmail.com
4329a31cbbcdd4f6f9e6710db692bc12af79428a
2799b97a02901d14c2c2e54d0178c2f2a1df5c1b
/Source/FuckYoFriends/FuckYoFriendsGameMode.h
5d050bbad7a8f49e41a67e884f6357f525f69bc1
[]
no_license
RCHoward92/FuckYoFriends
56554ef76207a522e9a569fb7249877b6f23cf29
740eb7e0129891dce7ea27dd9d5a267c36811056
refs/heads/master
2020-03-24T13:06:35.905831
2018-07-29T16:06:52
2018-07-29T16:06:52
142,735,291
0
0
null
null
null
null
UTF-8
C++
false
false
613
h
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "GameFramework/GameModeBase.h" #include "FuckYoFriendsGameMode.generated.h" /** * The GameMode defines the game being played. It governs the game rules, scoring, what actors * are allowed to exist in this game type, and who may enter the game. * * This game mode just sets the default pawn to be the MyCharacter asset, which is a subclass of FuckYoFriendsCharacter */ UCLASS(minimalapi) class AFuckYoFriendsGameMode : public AGameModeBase { GENERATED_BODY() public: AFuckYoFriendsGameMode(); };
[ "robert.c.howard92@gmail.com" ]
robert.c.howard92@gmail.com
a516f7dfcbb92b0a16562f51c57977a6c1ac34df
a2eecdd8b2524d53d9f965ab46abfb1b788b2de8
/include/singleton.hpp
a3d984098df93757b2796a0208464fee735ab6c2
[]
no_license
Johnmper/cpp_utilities
a2437465254cb5922b90dd33615dcad4432ec045
9bb75d8e41e9080993a39bfb44ee95d3074cef37
refs/heads/master
2020-04-09T19:48:50.073916
2019-03-31T00:20:23
2019-03-31T00:20:23
160,554,157
0
0
null
null
null
null
UTF-8
C++
false
false
575
hpp
#ifndef __UL_SINGLETON_HPP #define __UL_SINGLETON_HPP namespace ul{ template<typename T> class Singleton{ static_assert(std::is_default_constructible<T>::value, "T must have default constructor"); private: Singleton(); public: Singleton(const Singleton&) = delete; Singleton(Singleton&&) = delete; Singleton& operator=(const Singleton&) = delete; Singleton& operator=(Singleton&&) = delete; static T& instance(){ static T singleton; return singleton; } }; }; #endif
[ "pereira.john94@gmail.com" ]
pereira.john94@gmail.com
56630d91b74e918e9989ef516dbed8292f196d7b
474056398ceb9b31d48fcfd8979d42ba099dc785
/src/water.cpp
1244e4dde6c296dbd8ac5c3411910ae6b8a4cec9
[ "MIT" ]
permissive
sghoshjr/Virtual-City-Explorer
2e5ccff22cafffa72b14b03c63a3deb53232009a
f1391f76fc9d2dc097740ae89771c42abd7e9e96
refs/heads/master
2020-04-27T11:57:49.758452
2019-07-09T16:43:20
2019-07-09T16:43:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,795
cpp
#include "water.h" extern glm::mat4 proj, view; extern glm::vec3 PlayerPos, PlayerDir; extern int screenWidth, screenHeight; extern double mouseX, mouseY; float timer = 0; water::water() { programID = 0; TexID = 0; } void water::load(const char *modelFileName, const char *textureFileName, GLuint shader_ID) { Object::load(modelFileName); TexID = loadImage_A(textureFileName); programID = shader_ID; //Get all Uniforms uni_MVP = glGetUniformLocation(programID, "MVP"); uni_TexSampler = glGetUniformLocation(programID, "waterTex"); uni_alpha = glGetUniformLocation(programID, "alpha"); } void water::drawWater() { timer++; if (timer > 1000000) { timer = 0; } glm::mat t1 = glm::translate(glm::mat4(1.0f), glm::vec3(10.0f, 1.0f, 5.5f)); glm::mat s1 = glm::scale(glm::mat4(1.0f), glm::vec3(4.0f, 4.0f, 1.0f)); glm::mat r1 = glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(-1.0f, 0.0f, 0.0f)); model = t1*r1*s1; mvp = proj * view * model; // Brightness float alpha = 1.0f - (glm::dot(-PlayerDir, glm::vec3(0.0f, 1.0f, 0.0f)))*0.8f; alpha *= 0.5f; glEnable(GL_BLEND); glUseProgram(programID); glUniform1f(uni_alpha, alpha); glUniform1f(glGetUniformLocation(programID, "time"), (float)timer); glBindVertexArray(VertexArrayID[this->VAO_index_obj]); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glUniformMatrix4fv(uni_MVP, 1, GL_FALSE, &mvp[0][0]); glUniformMatrix4fv(glGetUniformLocation(programID, "M"),1, GL_FALSE, &model[0][0]); glUniform3fv(glGetUniformLocation(programID, "viewPos"), 1, &PlayerPos[0]); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, TexID); glUniform1i(uni_TexSampler, 0); glDrawArrays(GL_TRIANGLES, 0, this->vertex.size()); glDisable(GL_BLEND); } water::~water() { glDeleteTextures(1, &TexID); }
[ "sghoshjr@gmail.com" ]
sghoshjr@gmail.com
4de971e4a2f1bef79fe60922249319a32709c12e
7152d68ea99435ec6dfd8c6a7392d453aec43144
/Project5/Project5/AdvancedCharacter.cpp
7971c1af1e27890b191659553f6dba7100116374
[]
no_license
LadyStormcrow/SimpleCombatGame
56f390cf725349f9311a7811f517662c93c0b9f8
69e08067abf22c7a14fdfffadc743222eba39b82
refs/heads/master
2021-03-19T08:27:04.699755
2017-10-19T10:35:26
2017-10-19T10:35:26
105,593,375
0
0
null
null
null
null
UTF-8
C++
false
false
516
cpp
#include "AdvancedCharacter.h"; #include <string>; AdvancedCharacter::AdvancedCharacter() { name = ""; attack = 0; defence = 0; health = 0; special = 0; } AdvancedCharacter::AdvancedCharacter(std::string _name, int _attack, int _defence, int _health, int _special) { name = _name; attack = _attack; defence = _defence; health = _health; special = _special; } int AdvancedCharacter::getSpecial() { return special; } void AdvancedCharacter::setSpecial(int &_special) { special = _special; }
[ "nthouliss@gmail.com" ]
nthouliss@gmail.com
2d40ebc05bb8ddf125c197b268ab9cb121b70862
7b519e2d99601d91579b287db8a1fef9a19f7160
/Server/PVPGameServer/PVPPlayer.cpp
09bc99f8ac7f3f0a4846090a69a9cc49088e5a60
[]
no_license
Dekryptor/PVPServer
d9c890b2aa6d3ab570e168f3ea27ff3c445ba7ed
71e1764524147f1755e4cd0a484dfff930d4a65d
refs/heads/master
2021-01-01T04:13:28.065445
2016-10-29T15:36:36
2016-10-29T15:36:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
126
cpp
#include "PVPGameServer.h" CPVPPlayer::CPVPPlayer(CPVPGameServer *s) : CPlayer(s) { } CPVPPlayer::~CPVPPlayer(void) { }
[ "liangyue1981816@hotmail.com" ]
liangyue1981816@hotmail.com
7d82de19a6451972651baace4839334c631c5a4e
6e1c8559c12ebe8e0c8308e6f5019f4e74607739
/蓝桥杯练习试题/2基础练习/回文数/回文数.cpp
b59728538d1639646dfe90f2368f4e85d803a1b5
[ "MIT" ]
permissive
OctopusLian/lanqiao
15b5d67981062882c4be57b83e53109984697912
666b30ba8d38becd24ed06a3d1e8b950aa310e7b
refs/heads/master
2022-04-08T14:02:46.757276
2020-03-07T09:55:33
2020-03-07T09:55:33
164,676,348
0
0
null
null
null
null
UTF-8
C++
false
false
259
cpp
#include<stdio.h> int main() { for(int i1=1;i1<10;i1++) { for(int i2=0;i2<10;i2++) { for(int i3=0;i3<10;i3++) { for(int i4=0;i4<10;i4++) { if(i1==i4 && i2==i3) printf("%d%d%d%d\n",i1,i2,i3,i4); } } } } return 0; }
[ "zoctopus@qq.com" ]
zoctopus@qq.com
83368d5689d85302a0faa337c00012c3d5cbe52a
1cc631c61d85076c192a6946acb35d804f0620e4
/Source/third_party/boost_1_58_0/libs/asio/test/is_read_buffered.cpp
4d4d20d40eebed469c54fb217becf300495fcf1d
[ "BSL-1.0" ]
permissive
reven86/dreamfarmgdk
f9746e1c0e701f243c7dd2f14394970cc47346d9
4d5c26701bf05e89eef56ddd4553814aa6b0e770
refs/heads/master
2021-01-19T00:58:04.259208
2016-10-04T21:29:28
2016-10-04T21:33:10
906,953
2
5
null
null
null
null
UTF-8
C++
false
false
3,330
cpp
// // is_read_buffered.cpp // ~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Disable autolinking for unit tests. #if !defined(BOOST_ALL_NO_LIB) #define BOOST_ALL_NO_LIB 1 #endif // !defined(BOOST_ALL_NO_LIB) // Test that header file is self-contained. #include <boost/asio/is_read_buffered.hpp> #include <boost/asio/buffered_read_stream.hpp> #include <boost/asio/buffered_write_stream.hpp> #include <boost/asio/io_service.hpp> #include <boost/asio/ip/tcp.hpp> #include "unit_test.hpp" using namespace std; // For memcmp, memcpy and memset. class test_stream { public: typedef boost::asio::io_service io_service_type; typedef test_stream lowest_layer_type; test_stream(boost::asio::io_service& io_service) : io_service_(io_service) { } io_service_type& io_service() { return io_service_; } lowest_layer_type& lowest_layer() { return *this; } template <typename Const_Buffers> size_t write(const Const_Buffers&) { return 0; } template <typename Const_Buffers> size_t write(const Const_Buffers&, boost::system::error_code& ec) { ec = boost::system::error_code(); return 0; } template <typename Const_Buffers, typename Handler> void async_write(const Const_Buffers&, Handler handler) { boost::system::error_code error; io_service_.post(boost::asio::detail::bind_handler(handler, error, 0)); } template <typename Mutable_Buffers> size_t read(const Mutable_Buffers&) { return 0; } template <typename Mutable_Buffers> size_t read(const Mutable_Buffers&, boost::system::error_code& ec) { ec = boost::system::error_code(); return 0; } template <typename Mutable_Buffers, typename Handler> void async_read(const Mutable_Buffers&, Handler handler) { boost::system::error_code error; io_service_.post(boost::asio::detail::bind_handler(handler, error, 0)); } private: io_service_type& io_service_; }; void is_read_buffered_test() { BOOST_ASIO_CHECK(!boost::asio::is_read_buffered< boost::asio::ip::tcp::socket>::value); BOOST_ASIO_CHECK(!!boost::asio::is_read_buffered< boost::asio::buffered_read_stream< boost::asio::ip::tcp::socket> >::value); BOOST_ASIO_CHECK(!boost::asio::is_read_buffered< boost::asio::buffered_write_stream< boost::asio::ip::tcp::socket> >::value); BOOST_ASIO_CHECK(!!boost::asio::is_read_buffered< boost::asio::buffered_stream<boost::asio::ip::tcp::socket> >::value); BOOST_ASIO_CHECK(!boost::asio::is_read_buffered<test_stream>::value); BOOST_ASIO_CHECK(!!boost::asio::is_read_buffered< boost::asio::buffered_read_stream<test_stream> >::value); BOOST_ASIO_CHECK(!boost::asio::is_read_buffered< boost::asio::buffered_write_stream<test_stream> >::value); BOOST_ASIO_CHECK(!!boost::asio::is_read_buffered< boost::asio::buffered_stream<test_stream> >::value); } BOOST_ASIO_TEST_SUITE ( "is_read_buffered", BOOST_ASIO_TEST_CASE(is_read_buffered_test) )
[ "reven86@gmail.com" ]
reven86@gmail.com
cf28463907ca911ba4a29b5056cb0dffc0b77e51
2336d94ed08becd1e680491fed2757964b41645e
/src/features/RunBrowserFeatureClass.h
091a68851468323a7d0e30bf0cf548ae437f2848
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
adjustive/triumph4php
1360e6110dd717717bc10a5bb09b4ca14a8c525f
5eda79f0a9bf9bd6b5752bb66e9015cabb23f5cf
refs/heads/master
2021-01-17T21:47:13.337615
2015-07-22T00:43:18
2015-07-22T00:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,236
h
/** * @copyright 2009-2011 Roberto Perpuly * @license http://www.opensource.org/licenses/mit-license.php The MIT License * * This software is released under the terms of the MIT 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. */ #ifndef SRC_FEATURES_RUNBROWSERFEATURECLASS_H_ #define SRC_FEATURES_RUNBROWSERFEATURECLASS_H_ #include <wx/string.h> #include <memory> #include <vector> #include "actions/ActionClass.h" #include "features/FeatureClass.h" #include "language_php/UrlTagClass.h" #include "widgets/GaugeDialogClass.h" namespace t4p { class RunBrowserFeatureClass : public FeatureClass { public: /** * The most recent URLs that have been run. New URLs are added after the * user picks one from the "Search For URLs..." button, and they are deleted * only after the list has reached a certain size limit * These urls have a Project scope; when a project is opened any previous * URLs are cleared. */ std::vector<UrlTagClass> RecentUrls; RunBrowserFeatureClass(t4p::AppClass& app); void ExternalBrowser(const wxString& browserName, const wxURI& url); private: }; } // namespace t4p #endif // SRC_FEATURES_RUNBROWSERFEATURECLASS_H_
[ "robertop2004@gmail.com" ]
robertop2004@gmail.com
154e649f9c9fe76acc2a25add4d7d2de71829989
d3e9da02bd64fffaf0fdf06beff5af8b13d8a8f8
/Fall_2013/ADS/C Driver/assign01/Grader01.cpp
5321163b384c4b79361ff3415100968d00b1b7bd
[]
no_license
piushs/Sem1
bbd26f193bd4aea2a39a27645674f860661f7b45
c7529dcce0d3d2771938369e21c1d29f9f2e2475
refs/heads/master
2021-01-19T05:39:01.920792
2015-02-19T03:53:48
2015-02-19T03:53:48
31,000,047
0
0
null
null
null
null
UTF-8
C++
false
false
21,580
cpp
#include <string> #include <cstring> #include <vector> #include <stack> #include <iostream> #include <algorithm> #include "TestCase.h" #include "Stopwatch.h" #include "Interfaces01.h" #include "Grader01.h" void Grader01::createOriginalSequence(int len, std::vector<int>& ret){ for(int i = 0; i < len; ++i){ ret.push_back(i); } } void Grader01::createReverseSequence(int len, std::vector<int>& ret){ for(int i = len - 1; i >= 0; --i){ ret.push_back(i); } } void Grader01::createReverse(std::vector<int>& original, std::vector<int>& ret){ for(int i = original.size() - 1; i >= 0; --i){ ret.push_back(original[i]); } } void Grader01::createRandomSequence(int len, std::vector<int>& ret){ m_random.randomVector(len, ret); } void Grader01::createOrderSort2(std::vector<int>& original, std::vector<int>& ret){ for(int i = 0; i < original.size() - 1; i += 2){ int entry1 = original[i]; int entry2 = original[i+1]; ret.push_back(entry2); ret.push_back(entry1); } } void Grader01::createOrderSort3(std::vector<int>& original, std::vector<int>& ret){ for(int i = 0; i < original.size() - 2 || i < original.size() - 1; i += 3){ int entry1 = original[i]; int entry2 = original[i+1]; if(i + 2 < original.size()){ int entry3 = original[i+2]; ret.push_back(entry3); } ret.push_back(entry2); ret.push_back(entry1); } } void Grader01::createSequenceOrderSort(std::vector<int>& original, std::vector<int>& ret){ int step_size = 2; for(int i = 0; i < original.size(); ){ std::stack<int> stk; for(int j = 0; j < step_size && i + j < original.size(); ++j){ stk.push(original[i+j]); } while(stk.size() > 0){ int entry = stk.top(); stk.pop(); ret.push_back(entry); } i += step_size; ++step_size; } } TestCase * Grader01::singleOrderSort2(int len){ std::vector<int> org_seq; std::vector<int> order_seq; createOriginalSequence(len, org_seq); createOrderSort2(org_seq, order_seq); Stopwatch watch; watch.start(); std::map<ISingleNode *, int> pointers; ISingleList * single_list = (ISingleList *) createObject("ISingleList"); if(single_list == NULL){ return nullObject("ISingleList"); } for(int i = org_seq.size() - 1; i >= 0; --i){ int value = org_seq[i]; single_list->addHead(value); ISingleNode * head = single_list->getHead(); watch.pause(); pointers[head] = value; if(head->getValue() != value){ return failed("problem with addHead"); } watch.unpause(); } single_list->orderSort2(); watch.stop(); ISingleNode * curr = single_list->getHead(); for(int i = 0; i < order_seq.size(); ++i){ if(curr == NULL){ return failed("list terminated abruptly"); } int curr_value = curr->getValue(); if(curr_value != order_seq[i]){ return failed("order incorrect: [index: "+toString(i)+", given: "+toString(curr_value)+", gold: "+toString(order_seq[i])+"]"); } if(pointers[curr] != curr_value){ return failed("pointer mismatch"); } curr = curr->getNext(); } return passed(watch.getTime()); } TestCase * Grader01::singleOrderSort3(int len){ std::vector<int> org_seq; std::vector<int> order_seq; createOriginalSequence(len, org_seq); createOrderSort3(org_seq, order_seq); Stopwatch watch; watch.start(); std::map<ISingleNode *, int> pointers; ISingleList * single_list = (ISingleList *) createObject("ISingleList"); if(single_list == NULL){ return nullObject("ISingleList"); } for(int i = org_seq.size() - 1; i >= 0; --i){ int value = org_seq[i]; single_list->addHead(value); ISingleNode * head = single_list->getHead(); watch.pause(); pointers[head] = value; if(head->getValue() != value){ return failed("problem with addHead"); } watch.unpause(); } single_list->orderSort3(); watch.stop(); ISingleNode * curr = single_list->getHead(); for(int i = 0; i < order_seq.size(); ++i){ if(curr == NULL){ return failed("list terminated abruptly"); } int curr_value = curr->getValue(); if(curr_value != order_seq[i]){ return failed("order incorrect: [index: "+toString(i)+", given: "+toString(curr_value)+", gold: "+toString(order_seq[i])+"]"); } if(pointers[curr] != curr_value){ return failed("pointer mismatch"); } curr = curr->getNext(); } return passed(watch.getTime()); } TestCase * Grader01::singleSequenceOrderSort(int len){ std::vector<int> org_seq; std::vector<int> order_seq; createOriginalSequence(len, org_seq); createSequenceOrderSort(org_seq, order_seq); Stopwatch watch; watch.start(); std::map<ISingleNode *, int> pointers; ISingleList * single_list = (ISingleList *) createObject("ISingleList"); if(single_list == NULL){ return nullObject("ISingleList"); } for(int i = org_seq.size() - 1; i >= 0; --i){ int value = org_seq[i]; single_list->addHead(value); ISingleNode * head = single_list->getHead(); watch.pause(); pointers[head] = value; if(head->getValue() != value){ return failed("problem with addHead"); } watch.unpause(); } single_list->sequenceOrderSort(); watch.stop(); ISingleNode * curr = single_list->getHead(); for(int i = 0; i < order_seq.size(); ++i){ if(curr == NULL){ return failed("list terminated abruptly"); } int curr_value = curr->getValue(); if(curr_value != order_seq[i]){ return failed("order incorrect: [index: "+toString(i)+", given: "+toString(curr_value)+", gold: "+toString(order_seq[i])+"]"); } if(pointers[curr] != curr_value){ return failed("pointer mismatch"); } curr = curr->getNext(); } return passed(watch.getTime()); } TestCase * Grader01::singleReverse(int len){ std::vector<int> org_seq; std::vector<int> order_seq; createOriginalSequence(len, org_seq); createReverseSequence(len, order_seq); Stopwatch watch; watch.start(); std::map<ISingleNode *, int> pointers; ISingleList * single_list = (ISingleList *) createObject("ISingleList"); if(single_list == NULL){ return nullObject("ISingleList"); } for(int i = org_seq.size() - 1; i >= 0; --i){ int value = org_seq[i]; single_list->addHead(value); ISingleNode * head = single_list->getHead(); watch.pause(); pointers[head] = value; if(head->getValue() != value){ return failed("problem with addHead"); } watch.unpause(); } single_list->reverse(); watch.stop(); ISingleNode * curr = single_list->getHead(); for(int i = 0; i < order_seq.size(); ++i){ if(curr == NULL){ return failed("list terminated abruptly"); } int curr_value = curr->getValue(); if(curr_value != order_seq[i]){ return failed("order incorrect: [index: "+toString(i)+", given: "+toString(curr_value)+", gold: "+toString(order_seq[i])+"]"); } if(pointers[curr] != curr_value){ return failed("pointer mismatch"); } curr = curr->getNext(); } return passed(watch.getTime()); } TestCase * Grader01::doubleOrderSort2(int len){ std::vector<int> org_seq; std::vector<int> random_seq; std::vector<int> order_seq; createRandomSequence(len, random_seq); org_seq = random_seq; std::sort(org_seq.begin(), org_seq.end()); createOrderSort2(org_seq, order_seq); Stopwatch watch; watch.start(); IDoubleList * double_list = (IDoubleList *) createObject("IDoubleList"); if(double_list == NULL){ return nullObject("IDoubleList"); } for(int i = 0; i < random_seq.size(); ++i){ int value = random_seq[i]; double_list->addSorted(value); } IDoubleNode * curr = double_list->getHead(); while (curr !=NULL) { std :: cout << "\n Node " << curr->getValue(); curr=curr->getNext(); } getchar(); watch.pause(); std::map<IDoubleNode *, int> pointers; std::vector<IDoubleNode *> order; while(curr != NULL){ pointers[curr] = curr->getValue(); order.push_back(curr); curr = curr->getNext(); } if(order.size() != len){ return failed("forward traversal size incorrect"); } watch.unpause(); curr = double_list->getTail(); watch.pause(); std::vector<IDoubleNode *> rorder; while(curr != NULL){ rorder.push_back(curr); curr = curr->getPrev(); } if(rorder.size() != len){ return failed("reverse traversal size incorrect"); } for(int i = 0; i < org_seq.size(); ++i){ int lhs = org_seq[i]; int rhs = order[i]->getValue(); if(lhs != rhs){ return failed("forward traversal is not sorted"); } } for(int i = 0; i < org_seq.size(); ++i){ int lhs = org_seq[org_seq.size() - 1 - i]; int rhs = rorder[i]->getValue(); if(lhs != rhs){ return failed("reverse traversal is not sorted"); } } order.clear(); rorder.clear(); watch.unpause(); double_list->orderSort2(); IDoubleNode * head = double_list->getHead(); IDoubleNode * tail = double_list->getTail(); watch.pause(); curr = head; while(curr != NULL){ if(pointers[curr] != curr->getValue()){ return failed("pointer mismatch"); } order.push_back(curr); curr = curr->getNext(); } if(order.size() != len){ return failed("forward traversal size incorrect #2"); } for(int i = 0; i < order_seq.size(); ++i){ int lhs = order_seq[i]; int rhs = order[i]->getValue(); if(lhs != rhs){ return failed("forward traversal is out of final order"); } } curr = tail; while(curr != NULL){ if(pointers[curr] != curr->getValue()){ return failed("pointer mismatch"); } rorder.push_back(curr); curr = curr->getPrev(); } for(int i = 0; i < order_seq.size(); ++i){ int lhs = order_seq[order_seq.size() - 1 - i]; int rhs = rorder[i]->getValue(); if(lhs != rhs){ return failed("reverse traversal is out of final order"); } } return passed(watch.getTime()); } TestCase * Grader01::doubleOrderSort3(int len){ std::vector<int> org_seq; std::vector<int> random_seq; std::vector<int> order_seq; createRandomSequence(len, random_seq); org_seq = random_seq; std::sort(org_seq.begin(), org_seq.end()); createOrderSort3(org_seq, order_seq); Stopwatch watch; watch.start(); IDoubleList * double_list = (IDoubleList *) createObject("IDoubleList"); if(double_list == NULL){ return nullObject("IDoubleList"); } for(int i = 0; i < random_seq.size(); ++i){ int value = random_seq[i]; double_list->addSorted(value); } IDoubleNode * curr = double_list->getHead(); watch.pause(); std::map<IDoubleNode *, int> pointers; std::vector<IDoubleNode *> order; while(curr != NULL){ pointers[curr] = curr->getValue(); order.push_back(curr); curr = curr->getNext(); } if(order.size() != len){ return failed("forward traversal size incorrect"); } watch.unpause(); curr = double_list->getTail(); watch.pause(); std::vector<IDoubleNode *> rorder; while(curr != NULL){ rorder.push_back(curr); curr = curr->getPrev(); } if(rorder.size() != len){ return failed("reverse traversal size incorrect"); } for(int i = 0; i < org_seq.size(); ++i){ int lhs = org_seq[i]; int rhs = order[i]->getValue(); if(lhs != rhs){ return failed("forward traversal is not sorted"); } } for(int i = 0; i < org_seq.size(); ++i){ int lhs = org_seq[org_seq.size() - 1 - i]; int rhs = rorder[i]->getValue(); if(lhs != rhs){ return failed("reverse traversal is not sorted"); } } order.clear(); rorder.clear(); watch.unpause(); double_list->orderSort3(); IDoubleNode * head = double_list->getHead(); IDoubleNode * tail = double_list->getTail(); watch.pause(); curr = head; while(curr != NULL){ if(pointers[curr] != curr->getValue()){ return failed("pointer mismatch"); } order.push_back(curr); curr = curr->getNext(); } if(order.size() != len){ return failed("forward traversal size incorrect #2"); } for(int i = 0; i < order_seq.size(); ++i){ int lhs = order_seq[i]; int rhs = order[i]->getValue(); if(lhs != rhs){ return failed("forward traversal is out of final order"); } } curr = tail; while(curr != NULL){ if(pointers[curr] != curr->getValue()){ return failed("pointer mismatch"); } rorder.push_back(curr); curr = curr->getPrev(); } for(int i = 0; i < order_seq.size(); ++i){ int lhs = order_seq[order_seq.size() - 1 - i]; int rhs = rorder[i]->getValue(); if(lhs != rhs){ std::cout << "index: " << i << std::endl; std::cout << "lhs: " << lhs << std::endl; std::cout << "rhs: " << rhs << std::endl; for(int j = 0; j < order_seq.size(); ++j){ std::cout << "order_seq[" << j << "]: " << order_seq[j] << std::endl; } return failed("reverse traversal is out of final order"); } } return passed(watch.getTime()); } TestCase * Grader01::doubleSequenceOrderSort(int len){ std::vector<int> org_seq; std::vector<int> random_seq; std::vector<int> order_seq; createRandomSequence(len, random_seq); org_seq = random_seq; std::sort(org_seq.begin(), org_seq.end()); createSequenceOrderSort(org_seq, order_seq); Stopwatch watch; watch.start(); IDoubleList * double_list = (IDoubleList *) createObject("IDoubleList"); if(double_list == NULL){ return nullObject("IDoubleList"); } for(int i = 0; i < random_seq.size(); ++i){ int value = random_seq[i]; double_list->addSorted(value); } IDoubleNode * curr = double_list->getHead(); watch.pause(); std::map<IDoubleNode *, int> pointers; std::vector<IDoubleNode *> order; while(curr != NULL){ pointers[curr] = curr->getValue(); order.push_back(curr); curr = curr->getNext(); } if(order.size() != len){ return failed("forward traversal size incorrect"); } watch.unpause(); curr = double_list->getTail(); watch.pause(); std::vector<IDoubleNode *> rorder; while(curr != NULL){ rorder.push_back(curr); curr = curr->getPrev(); } if(rorder.size() != len){ return failed("reverse traversal size incorrect"); } for(int i = 0; i < org_seq.size(); ++i){ int lhs = org_seq[i]; int rhs = order[i]->getValue(); if(lhs != rhs){ return failed("forward traversal is not sorted"); } } for(int i = 0; i < org_seq.size(); ++i){ int lhs = org_seq[org_seq.size() - 1 - i]; int rhs = rorder[i]->getValue(); if(lhs != rhs){ return failed("reverse traversal is not sorted"); } } order.clear(); rorder.clear(); watch.unpause(); double_list->sequenceOrderSort(); IDoubleNode * head = double_list->getHead(); IDoubleNode * tail = double_list->getTail(); watch.pause(); curr = head; while(curr != NULL){ if(pointers[curr] != curr->getValue()){ return failed("pointer mismatch"); } order.push_back(curr); curr = curr->getNext(); } if(order.size() != len){ return failed("forward traversal size incorrect #2"); } for(int i = 0; i < order_seq.size(); ++i){ int lhs = order_seq[i]; int rhs = order[i]->getValue(); if(lhs != rhs){ return failed("forward traversal is out of final order"); } } curr = tail; while(curr != NULL){ if(pointers[curr] != curr->getValue()){ return failed("pointer mismatch"); } rorder.push_back(curr); curr = curr->getPrev(); } for(int i = 0; i < order_seq.size(); ++i){ int lhs = order_seq[order_seq.size() - 1 - i]; int rhs = rorder[i]->getValue(); if(lhs != rhs){ return failed("reverse traversal is out of final order"); } } return passed(watch.getTime()); } TestCase * Grader01::doubleReverse(int len){ std::vector<int> org_seq; std::vector<int> random_seq; std::vector<int> order_seq; createRandomSequence(len, random_seq); org_seq = random_seq; std::sort(org_seq.begin(), org_seq.end()); createReverse(org_seq, order_seq); Stopwatch watch; watch.start(); IDoubleList * double_list = (IDoubleList *) createObject("IDoubleList"); if(double_list == NULL){ return nullObject("IDoubleList"); } for(int i = 0; i < random_seq.size(); ++i){ int value = random_seq[i]; double_list->addSorted(value); } IDoubleNode * curr = double_list->getHead(); watch.pause(); std::map<IDoubleNode *, int> pointers; std::vector<IDoubleNode *> order; while(curr != NULL){ pointers[curr] = curr->getValue(); order.push_back(curr); curr = curr->getNext(); } if(order.size() != len){ return failed("forward traversal size incorrect"); } watch.unpause(); curr = double_list->getTail(); watch.pause(); std::vector<IDoubleNode *> rorder; while(curr != NULL){ rorder.push_back(curr); curr = curr->getPrev(); } if(rorder.size() != len){ return failed("reverse traversal size incorrect"); } for(int i = 0; i < org_seq.size(); ++i){ int lhs = org_seq[i]; int rhs = order[i]->getValue(); if(lhs != rhs){ return failed("forward traversal is not sorted"); } } for(int i = 0; i < org_seq.size(); ++i){ int lhs = org_seq[org_seq.size() - 1 - i]; int rhs = rorder[i]->getValue(); if(lhs != rhs){ return failed("reverse traversal is not sorted"); } } order.clear(); rorder.clear(); watch.unpause(); double_list->reverse(); IDoubleNode * head = double_list->getHead(); IDoubleNode * tail = double_list->getTail(); watch.pause(); curr = head; while(curr != NULL){ if(pointers[curr] != curr->getValue()){ return failed("pointer mismatch"); } order.push_back(curr); curr = curr->getNext(); } if(order.size() != len){ return failed("forward traversal size incorrect #2"); } for(int i = 0; i < order_seq.size(); ++i){ int lhs = order_seq[i]; int rhs = order[i]->getValue(); if(lhs != rhs){ return failed("forward traversal is out of final order"); } } curr = tail; while(curr != NULL){ if(pointers[curr] != curr->getValue()){ return failed("pointer mismatch"); } rorder.push_back(curr); curr = curr->getPrev(); } for(int i = 0; i < order_seq.size(); ++i){ int lhs = order_seq[order_seq.size() - 1 - i]; int rhs = rorder[i]->getValue(); if(lhs != rhs){ return failed("reverse traversal is out of final order"); } } return passed(watch.getTime()); } int Grader01::size(){ return 20; } std::string Grader01::getDescription(int test_case) { switch(test_case){ case 0: return "single order sort2 small"; case 1: return "single order sort2 large"; case 2: return "single order sort3 small"; case 3: return "single order sort3 small odd"; case 4: return "single order sort3 large"; case 5: return "single sequence order sort small"; case 6: return "single sequence order sort odd"; case 7: return "single sequence order sort large"; case 8: return "single reverse small"; case 9: return "single reverse large"; case 10: return "double order sort2 small"; case 11: return "double order sort2 large"; case 12: return "double order sort3 small"; case 13: return "double order sort3 odd"; case 14: return "double order sort3 large"; case 15: return "double sequence order sort small"; case 16: return "double sequence order sort odd"; case 17: return "double sequence order sort large"; case 18: return "double reverse small"; case 19: return "double reverse large"; } return ""; } int Grader01::getPoints(int test_case) { switch(test_case){ case 0: return 5; case 1: return 5; case 2: return 5; case 3: return 5; case 4: return 5; case 5: return 5; case 6: return 5; case 7: return 5; case 8: return 5; case 9: return 5; case 10: return 5; case 11: return 5; case 12: return 5; case 13: return 5; case 14: return 5; case 15: return 5; case 16: return 5; case 17: return 5; case 18: return 5; case 19: return 5; } return 0; } Date Grader01::getDueDate() { return Date(9, 12, 2013); } TestCase * Grader01::grade(int index){ int single_len2 = 8388607; int single_len3 = 14348907; int single_len_sequence = 4501499; int single_len_reverse = 8388607; int double_len2 = 65536; int double_len3 = 59049; int double_len_sequence = 60030; int double_len_reverse = 65536; switch(index){ case 0: return singleOrderSort2(8); case 1: return singleOrderSort2(single_len2); case 2: return singleOrderSort3(12); case 3: return singleOrderSort3(11); case 4: return singleOrderSort3(single_len3); case 5: return singleSequenceOrderSort(14); case 6: return singleSequenceOrderSort(13); case 7: return singleSequenceOrderSort(single_len_sequence); case 8: return singleReverse(10); case 9: return singleReverse(single_len_reverse); case 10: return doubleOrderSort2(8); case 11: return doubleOrderSort2(double_len2); case 12: return doubleOrderSort3(12); case 13: return doubleOrderSort3(11); case 14: return doubleOrderSort3(double_len3); case 15: return doubleSequenceOrderSort(14); case 16: return doubleSequenceOrderSort(13); case 17: return doubleSequenceOrderSort(double_len_sequence); case 18: return doubleReverse(10); case 19: return doubleReverse(double_len_reverse); default: return NULL; } }
[ "pasrivas@syr.edu" ]
pasrivas@syr.edu
38d3f6d508ef11a30d7631a74ce751713cac8678
6730d04ec84d3968bd261c5d1ef6bd7d4a21f15f
/attic/p42/SysCore/Kernel/exception.cpp
89c84ab2fd13dad0166748cd8b266a3e2de9a23e
[ "LicenseRef-scancode-public-domain", "Unlicense" ]
permissive
mooseman/plan_42
13776200695d7fc56acba8decbc1bac769731ddf
0b726f06088c6940aa7050b5cef9f93a3cdcc788
refs/heads/master
2021-01-23T11:47:48.070287
2016-01-08T02:02:06
2016-01-08T02:02:06
207,514
10
2
null
null
null
null
UTF-8
C++
false
false
4,147
cpp
#include "exception.h" #include <hal.h> #include <stdint.h> extern void _cdecl kernel_panic (const char* fmt, ...); #define intstart() \ _asm cli \ _asm sub ebp, 4 #pragma warning (disable:4100) //! divide by 0 fault void _cdecl divide_by_zero_fault (uint32_t eflags,uint32_t cs,uint32_t eip, uint32_t other) { _asm { cli add esp, 12 pushad } kernel_panic ("Divide by 0 at physical address [0x%x:0x%x] EFLAGS [0x%x] other: 0x%x",cs,eip, eflags, other); for (;;); } //! single step void interrupt _cdecl single_step_trap (unsigned int cs, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("Single step"); for (;;); } //! non maskable interrupt trap void interrupt _cdecl nmi_trap (unsigned int cs, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("NMI trap"); for (;;); } //! breakpoint hit void interrupt _cdecl breakpoint_trap (unsigned int cs,unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("Breakpoint trap"); for (;;); } //! overflow void interrupt _cdecl overflow_trap (unsigned int cs, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("Overflow trap"); for (;;); } //! bounds check void interrupt _cdecl bounds_check_fault (unsigned int cs, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("Bounds check fault"); for (;;); } //! invalid opcode / instruction void interrupt _cdecl invalid_opcode_fault (unsigned int cs, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("Invalid opcode"); for (;;); } //! device not available void interrupt _cdecl no_device_fault (unsigned int cs, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("Device not found"); for (;;); } //! double fault void interrupt _cdecl double_fault_abort (unsigned int cs, unsigned int err, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("Double fault"); for (;;); } //! invalid Task State Segment (TSS) void interrupt _cdecl invalid_tss_fault (unsigned int cs,unsigned int err, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("Invalid TSS"); for (;;); } //! segment not present void interrupt _cdecl no_segment_fault (unsigned int cs,unsigned int err, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("Invalid segment"); for (;;); } //! stack fault void interrupt _cdecl stack_fault ( unsigned int cs,unsigned int err, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("Stack fault"); for (;;); } //! general protection fault void interrupt _cdecl general_protection_fault (unsigned int cs,unsigned int err, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("General Protection Fault"); for (;;); } //! page fault void _cdecl page_fault (uint32_t err,uint32_t eflags,uint32_t cs,uint32_t eip) { _asm cli _asm sub ebp, 4 // int faultAddr=0; // _asm { // mov eax, cr2 // mov [faultAddr], eax // } // kernel_panic ("Page Fault at 0x%x:0x%x refrenced memory at 0x%x", // cs, eip, faultAddr); // kernel_panic ("Page Fault"); for (;;); _asm popad _asm sti _asm iretd } //! Floating Point Unit (FPU) error void interrupt _cdecl fpu_fault (unsigned int cs, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("FPU Fault"); for (;;); } //! alignment check void interrupt _cdecl alignment_check_fault (unsigned int cs,unsigned int err, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("Alignment Check"); for (;;); } //! machine check void interrupt _cdecl machine_check_abort (unsigned int cs, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("Machine Check"); for (;;); } //! Floating Point Unit (FPU) Single Instruction Multiple Data (SIMD) error void interrupt _cdecl simd_fpu_fault (unsigned int cs, unsigned int eip, unsigned int eflags) { intstart (); kernel_panic ("FPU SIMD fault"); for (;;); }
[ "andy.elvey@paradise.net.nz" ]
andy.elvey@paradise.net.nz
88512cadab1f7dc2733cf43fd8d8425765ef4f20
e5c453b57fe861ee62489781f88d8c922784f791
/Program/piramide.cpp
c9c8afbc1f60aaa2d139408612c3fca50dce8e82
[]
no_license
Bulcs/geometryLab2
39a2de6377734fe4d77a8ddd2c7ff6c6eb92507d
99899173fbe9226f2a154ea8b82be56a5fcd5174
refs/heads/master
2020-03-12T06:49:42.900277
2018-04-22T19:58:09
2018-04-22T19:58:09
130,493,996
0
0
null
null
null
null
UTF-8
C++
false
false
2,026
cpp
/** * @file main.cpp * @brief Programa para calcular as Área e Volume da Pirâmide * @author Vinícius Ribeiro Bulcão * @since 18/04/2018 * @date 20/04/2018 */ #include <iostream> #include "piramide.h" #include <cmath> using namespace std; /** @brief chamada do Método getPiramide da classe Piramide @param 'area_base' Representará a área da base da figura geométrica @param 'area_lateral' Representará o área lateral da figura geométrica @param 'altura' Representará a altura da figura geométrica @param 'area' Representará o área total da figura geométrica @param 'volume' Representará o volume da figura geométrica */ int Piramide::getPiramide(float area_base, float area_lateral, float altura, float area, float volume){ /** @brief Criação dos floats para representar o area_base, area_lateral, altura, volume, area @param 'arb' Representa a area_base a ser implementada @param 'arl' Representa a area_lateral a ser implementada @param 'a' Representa a altura a ser implementada @param 'ar' Representa a area implementado @param 'v' Representa o volume implementado */ float arb, arl, a, ar, v; cout << "\nPiramide\n"; cout << "Digite a area da base: \n"; /** @brief Cin para leitura da área da base 'arb' */ cin >> arb; /** @brief 'area_base' recebe 'arb' */ area_base = arb; cout << "\nDigite a area lateral: \n"; /** @brief Cin para leitura da área lateral 'arl' */ cin >> arl; /** @brief 'area_lateral' recebe 'arl' */ area_lateral = arl; /** @brief Atribuição da fórmula da área */ ar = arb + arl; /** @brief 'area' recebe 'ar' */ area = ar; cout << "\nDigite a altura da Piramide: \n"; /** @brief Cin para leitura da altura 'arb' */ cin >> a; /** @brief 'altura' recebe 'a' */ altura = a; /** @brief Atribuição da fórmula do volume */ v = (arb*a)/3; /** @brief 'volume' recebe 'v' */ volume = v; /** @brief Impressão dos valores da área e volume */ cout << "\nÁrea: " << area; cout << "\nVolume: " << volume << endl; return 0; }
[ "vrbulcao@hotmail.com" ]
vrbulcao@hotmail.com
643b283ac07b09a09433ad73040407a6d1b0f21a
876a5840149b4ba1350ff5f6816144a9c51ed110
/p2p/base/relayserver.cc
87aaf65ebfb54046be53bb408be89bcb894f26a0
[]
no_license
zhangyongfei/testjingle
6165e7e57369397ae675db23cba2ca9d80433e3b
15420097c65c2f1bac5df380603f6f71572fa4f2
refs/heads/master
2016-09-10T02:02:19.700814
2014-06-19T08:51:18
2014-06-19T08:51:18
20,157,419
0
1
null
null
null
null
UTF-8
C++
false
false
26,550
cc
/* * libjingle * Copyright 2004--2005, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "p2p/base/relayserver.h" #ifdef POSIX #include <errno.h> #endif // POSIX #include <algorithm> #include "base/asynctcpsocket.h" #include "base/helpers.h" #include "base/logging.h" #include "base/socketadapters.h" namespace cricket { // By default, we require a ping every 90 seconds. const int MAX_LIFETIME = 15 * 60 * 1000; // The number of bytes in each of the usernames we use. const uint32 USERNAME_LENGTH = 16; static const uint32 kMessageAcceptConnection = 1; // Calls SendTo on the given socket and logs any bad results. void Send(talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size, const talk_base::SocketAddress& addr) { talk_base::PacketOptions options; int result = socket->SendTo(bytes, size, addr, options); if (result < static_cast<int>(size)) { LOG(LS_ERROR) << "SendTo wrote only " << result << " of " << size << " bytes"; } else if (result < 0) { LOG_ERR(LS_ERROR) << "SendTo"; } } // Sends the given STUN message on the given socket. void SendStun(const StunMessage& msg, talk_base::AsyncPacketSocket* socket, const talk_base::SocketAddress& addr) { talk_base::ByteBuffer buf; msg.Write(&buf); Send(socket, buf.Data(), buf.Length(), addr); } // Constructs a STUN error response and sends it on the given socket. void SendStunError(const StunMessage& msg, talk_base::AsyncPacketSocket* socket, const talk_base::SocketAddress& remote_addr, int error_code, const char* error_desc, const std::string& magic_cookie) { RelayMessage err_msg; err_msg.SetType(GetStunErrorResponseType(msg.type())); err_msg.SetTransactionID(msg.transaction_id()); StunByteStringAttribute* magic_cookie_attr = StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE); if (magic_cookie.size() == 0) { magic_cookie_attr->CopyBytes(cricket::TURN_MAGIC_COOKIE_VALUE, sizeof(cricket::TURN_MAGIC_COOKIE_VALUE)); } else { magic_cookie_attr->CopyBytes(magic_cookie.c_str(), magic_cookie.size()); } err_msg.AddAttribute(magic_cookie_attr); StunErrorCodeAttribute* err_code = StunAttribute::CreateErrorCode(); err_code->SetClass(error_code / 100); err_code->SetNumber(error_code % 100); err_code->SetReason(error_desc); err_msg.AddAttribute(err_code); SendStun(err_msg, socket, remote_addr); } RelayServer::RelayServer(talk_base::Thread* thread) : thread_(thread), log_bindings_(true) { } RelayServer::~RelayServer() { // Deleting the binding will cause it to be removed from the map. while (!bindings_.empty()) delete bindings_.begin()->second; for (size_t i = 0; i < internal_sockets_.size(); ++i) delete internal_sockets_[i]; for (size_t i = 0; i < external_sockets_.size(); ++i) delete external_sockets_[i]; for (size_t i = 0; i < removed_sockets_.size(); ++i) delete removed_sockets_[i]; while (!server_sockets_.empty()) { talk_base::AsyncSocket* socket = server_sockets_.begin()->first; server_sockets_.erase(server_sockets_.begin()->first); delete socket; } } void RelayServer::AddInternalSocket(talk_base::AsyncPacketSocket* socket) { ASSERT(internal_sockets_.end() == std::find(internal_sockets_.begin(), internal_sockets_.end(), socket)); internal_sockets_.push_back(socket); socket->SignalReadPacket.connect(this, &RelayServer::OnInternalPacket); } void RelayServer::RemoveInternalSocket(talk_base::AsyncPacketSocket* socket) { SocketList::iterator iter = std::find(internal_sockets_.begin(), internal_sockets_.end(), socket); ASSERT(iter != internal_sockets_.end()); internal_sockets_.erase(iter); removed_sockets_.push_back(socket); socket->SignalReadPacket.disconnect(this); } void RelayServer::AddExternalSocket(talk_base::AsyncPacketSocket* socket) { ASSERT(external_sockets_.end() == std::find(external_sockets_.begin(), external_sockets_.end(), socket)); external_sockets_.push_back(socket); socket->SignalReadPacket.connect(this, &RelayServer::OnExternalPacket); } void RelayServer::RemoveExternalSocket(talk_base::AsyncPacketSocket* socket) { SocketList::iterator iter = std::find(external_sockets_.begin(), external_sockets_.end(), socket); ASSERT(iter != external_sockets_.end()); external_sockets_.erase(iter); removed_sockets_.push_back(socket); socket->SignalReadPacket.disconnect(this); } void RelayServer::AddInternalServerSocket(talk_base::AsyncSocket* socket, cricket::ProtocolType proto) { ASSERT(server_sockets_.end() == server_sockets_.find(socket)); server_sockets_[socket] = proto; socket->SignalReadEvent.connect(this, &RelayServer::OnReadEvent); } void RelayServer::RemoveInternalServerSocket( talk_base::AsyncSocket* socket) { ServerSocketMap::iterator iter = server_sockets_.find(socket); ASSERT(iter != server_sockets_.end()); server_sockets_.erase(iter); socket->SignalReadEvent.disconnect(this); } int RelayServer::GetConnectionCount() const { return static_cast<int>(connections_.size()); } talk_base::SocketAddressPair RelayServer::GetConnection(int connection) const { int i = 0; for (ConnectionMap::const_iterator it = connections_.begin(); it != connections_.end(); ++it) { if (i == connection) { return it->second->addr_pair(); } ++i; } return talk_base::SocketAddressPair(); } bool RelayServer::HasConnection(const talk_base::SocketAddress& address) const { for (ConnectionMap::const_iterator it = connections_.begin(); it != connections_.end(); ++it) { if (it->second->addr_pair().destination() == address) { return true; } } return false; } void RelayServer::OnReadEvent(talk_base::AsyncSocket* socket) { ASSERT(server_sockets_.find(socket) != server_sockets_.end()); AcceptConnection(socket); } void RelayServer::OnInternalPacket( talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size, const talk_base::SocketAddress& remote_addr, const talk_base::PacketTime& packet_time) { // Get the address of the connection we just received on. talk_base::SocketAddressPair ap(remote_addr, socket->GetLocalAddress()); ASSERT(!ap.destination().IsNil()); // If this did not come from an existing connection, it should be a STUN // allocate request. ConnectionMap::iterator piter = connections_.find(ap); if (piter == connections_.end()) { HandleStunAllocate(bytes, size, ap, socket); return; } RelayServerConnection* int_conn = piter->second; // Handle STUN requests to the server itself. if (int_conn->binding()->HasMagicCookie(bytes, size)) { HandleStun(int_conn, bytes, size); return; } // Otherwise, this is a non-wrapped packet that we are to forward. Make sure // that this connection has been locked. (Otherwise, we would not know what // address to forward to.) if (!int_conn->locked()) { LOG(LS_WARNING) << "Dropping packet: connection not locked"; return; } // Forward this to the destination address into the connection. RelayServerConnection* ext_conn = int_conn->binding()->GetExternalConnection( int_conn->default_destination()); if (ext_conn && ext_conn->locked()) { // TODO: Check the HMAC. ext_conn->Send(bytes, size); } else { // This happens very often and is not an error. LOG(LS_INFO) << "Dropping packet: no external connection"; } } void RelayServer::OnExternalPacket( talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size, const talk_base::SocketAddress& remote_addr, const talk_base::PacketTime& packet_time) { // Get the address of the connection we just received on. talk_base::SocketAddressPair ap(remote_addr, socket->GetLocalAddress()); ASSERT(!ap.destination().IsNil()); // If this connection already exists, then forward the traffic. ConnectionMap::iterator piter = connections_.find(ap); if (piter != connections_.end()) { // TODO: Check the HMAC. RelayServerConnection* ext_conn = piter->second; RelayServerConnection* int_conn = ext_conn->binding()->GetInternalConnection( ext_conn->addr_pair().source()); ASSERT(int_conn != NULL); int_conn->Send(bytes, size, ext_conn->addr_pair().source()); ext_conn->Lock(); // allow outgoing packets return; } // The first packet should always be a STUN / TURN packet. If it isn't, then // we should just ignore this packet. RelayMessage msg; talk_base::ByteBuffer buf(bytes, size); if (!msg.Read(&buf)) { LOG(LS_WARNING) << "Dropping packet: first packet not STUN"; return; } // The initial packet should have a username (which identifies the binding). const StunByteStringAttribute* username_attr = msg.GetByteString(STUN_ATTR_USERNAME); if (!username_attr) { LOG(LS_WARNING) << "Dropping packet: no username"; return; } uint32 length = talk_base::_min(static_cast<uint32>(username_attr->length()), USERNAME_LENGTH); std::string username(username_attr->bytes(), length); // TODO: Check the HMAC. // The binding should already be present. BindingMap::iterator biter = bindings_.find(username); if (biter == bindings_.end()) { LOG(LS_WARNING) << "Dropping packet: no binding with username"; return; } // Add this authenticted connection to the binding. RelayServerConnection* ext_conn = new RelayServerConnection(biter->second, ap, socket); ext_conn->binding()->AddExternalConnection(ext_conn); AddConnection(ext_conn); // We always know where external packets should be forwarded, so we can lock // them from the beginning. ext_conn->Lock(); // Send this message on the appropriate internal connection. RelayServerConnection* int_conn = ext_conn->binding()->GetInternalConnection( ext_conn->addr_pair().source()); ASSERT(int_conn != NULL); int_conn->Send(bytes, size, ext_conn->addr_pair().source()); } bool RelayServer::HandleStun( const char* bytes, size_t size, const talk_base::SocketAddress& remote_addr, talk_base::AsyncPacketSocket* socket, std::string* username, StunMessage* msg) { // Parse this into a stun message. Eat the message if this fails. talk_base::ByteBuffer buf(bytes, size); if (!msg->Read(&buf)) { return false; } // The initial packet should have a username (which identifies the binding). const StunByteStringAttribute* username_attr = msg->GetByteString(STUN_ATTR_USERNAME); if (!username_attr) { SendStunError(*msg, socket, remote_addr, 432, "Missing Username", ""); return false; } // Record the username if requested. if (username) username->append(username_attr->bytes(), username_attr->length()); // TODO: Check for unknown attributes (<= 0x7fff) return true; } void RelayServer::HandleStunAllocate( const char* bytes, size_t size, const talk_base::SocketAddressPair& ap, talk_base::AsyncPacketSocket* socket) { // Make sure this is a valid STUN request. RelayMessage request; std::string username; if (!HandleStun(bytes, size, ap.source(), socket, &username, &request)) return; // Make sure this is a an allocate request. if (request.type() != STUN_ALLOCATE_REQUEST) { SendStunError(request, socket, ap.source(), 600, "Operation Not Supported", ""); return; } // TODO: Check the HMAC. // Find or create the binding for this username. RelayServerBinding* binding; BindingMap::iterator biter = bindings_.find(username); if (biter != bindings_.end()) { binding = biter->second; } else { // NOTE: In the future, bindings will be created by the bot only. This // else-branch will then disappear. // Compute the appropriate lifetime for this binding. uint32 lifetime = MAX_LIFETIME; const StunUInt32Attribute* lifetime_attr = request.GetUInt32(STUN_ATTR_LIFETIME); if (lifetime_attr) lifetime = talk_base::_min(lifetime, lifetime_attr->value() * 1000); binding = new RelayServerBinding(this, username, "0", lifetime); binding->SignalTimeout.connect(this, &RelayServer::OnTimeout); bindings_[username] = binding; if (log_bindings_) { LOG(LS_INFO) << "Added new binding " << username << ", " << bindings_.size() << " total"; } } // Add this connection to the binding. It starts out unlocked. RelayServerConnection* int_conn = new RelayServerConnection(binding, ap, socket); binding->AddInternalConnection(int_conn); AddConnection(int_conn); // Now that we have a connection, this other method takes over. HandleStunAllocate(int_conn, request); } void RelayServer::HandleStun( RelayServerConnection* int_conn, const char* bytes, size_t size) { // Make sure this is a valid STUN request. RelayMessage request; std::string username; if (!HandleStun(bytes, size, int_conn->addr_pair().source(), int_conn->socket(), &username, &request)) return; // Make sure the username is the one were were expecting. if (username != int_conn->binding()->username()) { int_conn->SendStunError(request, 430, "Stale Credentials"); return; } // TODO: Check the HMAC. // Send this request to the appropriate handler. if (request.type() == STUN_SEND_REQUEST) HandleStunSend(int_conn, request); else if (request.type() == STUN_ALLOCATE_REQUEST) HandleStunAllocate(int_conn, request); else int_conn->SendStunError(request, 600, "Operation Not Supported"); } void RelayServer::HandleStunAllocate( RelayServerConnection* int_conn, const StunMessage& request) { // Create a response message that includes an address with which external // clients can communicate. RelayMessage response; response.SetType(STUN_ALLOCATE_RESPONSE); response.SetTransactionID(request.transaction_id()); StunByteStringAttribute* magic_cookie_attr = StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE); magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(), int_conn->binding()->magic_cookie().size()); response.AddAttribute(magic_cookie_attr); size_t index = rand() % external_sockets_.size(); talk_base::SocketAddress ext_addr = external_sockets_[index]->GetLocalAddress(); StunAddressAttribute* addr_attr = StunAttribute::CreateAddress(STUN_ATTR_MAPPED_ADDRESS); addr_attr->SetIP(ext_addr.ipaddr()); addr_attr->SetPort(ext_addr.port()); response.AddAttribute(addr_attr); StunUInt32Attribute* res_lifetime_attr = StunAttribute::CreateUInt32(STUN_ATTR_LIFETIME); res_lifetime_attr->SetValue(int_conn->binding()->lifetime() / 1000); response.AddAttribute(res_lifetime_attr); // TODO: Support transport-prefs (preallocate RTCP port). // TODO: Support bandwidth restrictions. // TODO: Add message integrity check. // Send a response to the caller. int_conn->SendStun(response); } void RelayServer::HandleStunSend( RelayServerConnection* int_conn, const StunMessage& request) { const StunAddressAttribute* addr_attr = request.GetAddress(STUN_ATTR_DESTINATION_ADDRESS); if (!addr_attr) { int_conn->SendStunError(request, 400, "Bad Request"); return; } const StunByteStringAttribute* data_attr = request.GetByteString(STUN_ATTR_DATA); if (!data_attr) { int_conn->SendStunError(request, 400, "Bad Request"); return; } talk_base::SocketAddress ext_addr(addr_attr->ipaddr(), addr_attr->port()); RelayServerConnection* ext_conn = int_conn->binding()->GetExternalConnection(ext_addr); if (!ext_conn) { // Create a new connection to establish the relationship with this binding. ASSERT(external_sockets_.size() == 1); talk_base::AsyncPacketSocket* socket = external_sockets_[0]; talk_base::SocketAddressPair ap(ext_addr, socket->GetLocalAddress()); ext_conn = new RelayServerConnection(int_conn->binding(), ap, socket); ext_conn->binding()->AddExternalConnection(ext_conn); AddConnection(ext_conn); } // If this connection has pinged us, then allow outgoing traffic. if (ext_conn->locked()) ext_conn->Send(data_attr->bytes(), data_attr->length()); const StunUInt32Attribute* options_attr = request.GetUInt32(STUN_ATTR_OPTIONS); if (options_attr && (options_attr->value() & 0x01)) { int_conn->set_default_destination(ext_addr); int_conn->Lock(); RelayMessage response; response.SetType(STUN_SEND_RESPONSE); response.SetTransactionID(request.transaction_id()); StunByteStringAttribute* magic_cookie_attr = StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE); magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(), int_conn->binding()->magic_cookie().size()); response.AddAttribute(magic_cookie_attr); StunUInt32Attribute* options2_attr = StunAttribute::CreateUInt32(cricket::STUN_ATTR_OPTIONS); options2_attr->SetValue(0x01); response.AddAttribute(options2_attr); int_conn->SendStun(response); } } void RelayServer::AddConnection(RelayServerConnection* conn) { ASSERT(connections_.find(conn->addr_pair()) == connections_.end()); connections_[conn->addr_pair()] = conn; } void RelayServer::RemoveConnection(RelayServerConnection* conn) { ConnectionMap::iterator iter = connections_.find(conn->addr_pair()); ASSERT(iter != connections_.end()); connections_.erase(iter); } void RelayServer::RemoveBinding(RelayServerBinding* binding) { BindingMap::iterator iter = bindings_.find(binding->username()); ASSERT(iter != bindings_.end()); bindings_.erase(iter); if (log_bindings_) { LOG(LS_INFO) << "Removed binding " << binding->username() << ", " << bindings_.size() << " remaining"; } } void RelayServer::OnMessage(talk_base::Message *pmsg) { ASSERT(pmsg->message_id == kMessageAcceptConnection); talk_base::MessageData* data = pmsg->pdata; talk_base::AsyncSocket* socket = static_cast <talk_base::TypedMessageData<talk_base::AsyncSocket*>*> (data)->data(); AcceptConnection(socket); delete data; } void RelayServer::OnTimeout(RelayServerBinding* binding) { // This call will result in all of the necessary clean-up. We can't call // delete here, because you can't delete an object that is signaling you. thread_->Dispose(binding); } void RelayServer::AcceptConnection(talk_base::AsyncSocket* server_socket) { // Check if someone is trying to connect to us. talk_base::SocketAddress accept_addr; talk_base::AsyncSocket* accepted_socket = server_socket->Accept(&accept_addr); if (accepted_socket != NULL) { // We had someone trying to connect, now check which protocol to // use and create a packet socket. ASSERT(server_sockets_[server_socket] == cricket::PROTO_TCP || server_sockets_[server_socket] == cricket::PROTO_SSLTCP); if (server_sockets_[server_socket] == cricket::PROTO_SSLTCP) { accepted_socket = new talk_base::AsyncSSLServerSocket(accepted_socket); } talk_base::AsyncTCPSocket* tcp_socket = new talk_base::AsyncTCPSocket(accepted_socket, false); // Finally add the socket so it can start communicating with the client. AddInternalSocket(tcp_socket); } } RelayServerConnection::RelayServerConnection( RelayServerBinding* binding, const talk_base::SocketAddressPair& addrs, talk_base::AsyncPacketSocket* socket) : binding_(binding), addr_pair_(addrs), socket_(socket), locked_(false) { // The creation of a new connection constitutes a use of the binding. binding_->NoteUsed(); } RelayServerConnection::~RelayServerConnection() { // Remove this connection from the server's map (if it exists there). binding_->server()->RemoveConnection(this); } void RelayServerConnection::Send(const char* data, size_t size) { // Note that the binding has been used again. binding_->NoteUsed(); cricket::Send(socket_, data, size, addr_pair_.source()); } void RelayServerConnection::Send( const char* data, size_t size, const talk_base::SocketAddress& from_addr) { // If the from address is known to the client, we don't need to send it. if (locked() && (from_addr == default_dest_)) { Send(data, size); return; } // Wrap the given data in a data-indication packet. RelayMessage msg; msg.SetType(STUN_DATA_INDICATION); StunByteStringAttribute* magic_cookie_attr = StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE); magic_cookie_attr->CopyBytes(binding_->magic_cookie().c_str(), binding_->magic_cookie().size()); msg.AddAttribute(magic_cookie_attr); StunAddressAttribute* addr_attr = StunAttribute::CreateAddress(STUN_ATTR_SOURCE_ADDRESS2); addr_attr->SetIP(from_addr.ipaddr()); addr_attr->SetPort(from_addr.port()); msg.AddAttribute(addr_attr); StunByteStringAttribute* data_attr = StunAttribute::CreateByteString(STUN_ATTR_DATA); ASSERT(size <= 65536); data_attr->CopyBytes(data, uint16(size)); msg.AddAttribute(data_attr); SendStun(msg); } void RelayServerConnection::SendStun(const StunMessage& msg) { // Note that the binding has been used again. binding_->NoteUsed(); cricket::SendStun(msg, socket_, addr_pair_.source()); } void RelayServerConnection::SendStunError( const StunMessage& request, int error_code, const char* error_desc) { // An error does not indicate use. If no legitimate use off the binding // occurs, we want it to be cleaned up even if errors are still occuring. cricket::SendStunError( request, socket_, addr_pair_.source(), error_code, error_desc, binding_->magic_cookie()); } void RelayServerConnection::Lock() { locked_ = true; } void RelayServerConnection::Unlock() { locked_ = false; } // IDs used for posted messages: const uint32 MSG_LIFETIME_TIMER = 1; RelayServerBinding::RelayServerBinding( RelayServer* server, const std::string& username, const std::string& password, uint32 lifetime) : server_(server), username_(username), password_(password), lifetime_(lifetime) { // For now, every connection uses the standard magic cookie value. magic_cookie_.append( reinterpret_cast<const char*>(TURN_MAGIC_COOKIE_VALUE), sizeof(TURN_MAGIC_COOKIE_VALUE)); // Initialize the last-used time to now. NoteUsed(); // Set the first timeout check. server_->thread()->PostDelayed(lifetime_, this, MSG_LIFETIME_TIMER); } RelayServerBinding::~RelayServerBinding() { // Clear the outstanding timeout check. server_->thread()->Clear(this); // Clean up all of the connections. for (size_t i = 0; i < internal_connections_.size(); ++i) delete internal_connections_[i]; for (size_t i = 0; i < external_connections_.size(); ++i) delete external_connections_[i]; // Remove this binding from the server's map. server_->RemoveBinding(this); } void RelayServerBinding::AddInternalConnection(RelayServerConnection* conn) { internal_connections_.push_back(conn); } void RelayServerBinding::AddExternalConnection(RelayServerConnection* conn) { external_connections_.push_back(conn); } void RelayServerBinding::NoteUsed() { last_used_ = talk_base::Time(); } bool RelayServerBinding::HasMagicCookie(const char* bytes, size_t size) const { if (size < 24 + magic_cookie_.size()) { return false; } else { return memcmp(bytes + 24, magic_cookie_.c_str(), magic_cookie_.size()) == 0; } } RelayServerConnection* RelayServerBinding::GetInternalConnection( const talk_base::SocketAddress& ext_addr) { // Look for an internal connection that is locked to this address. for (size_t i = 0; i < internal_connections_.size(); ++i) { if (internal_connections_[i]->locked() && (ext_addr == internal_connections_[i]->default_destination())) return internal_connections_[i]; } // If one was not found, we send to the first connection. ASSERT(internal_connections_.size() > 0); return internal_connections_[0]; } RelayServerConnection* RelayServerBinding::GetExternalConnection( const talk_base::SocketAddress& ext_addr) { for (size_t i = 0; i < external_connections_.size(); ++i) { if (ext_addr == external_connections_[i]->addr_pair().source()) return external_connections_[i]; } return 0; } void RelayServerBinding::OnMessage(talk_base::Message *pmsg) { if (pmsg->message_id == MSG_LIFETIME_TIMER) { ASSERT(!pmsg->pdata); // If the lifetime timeout has been exceeded, then send a signal. // Otherwise, just keep waiting. if (talk_base::Time() >= last_used_ + lifetime_) { LOG(LS_INFO) << "Expiring binding " << username_; SignalTimeout(this); } else { server_->thread()->PostDelayed(lifetime_, this, MSG_LIFETIME_TIMER); } } else { ASSERT(false); } } } // namespace cricket
[ "zhang13730865557@163.com" ]
zhang13730865557@163.com
e04c74cb91a70bd9fe5ab31ce16c4e9dd4ca3fac
fa476614d54468bcdd9204c646bb832b4e64df93
/CDF/321DIV2/B.cpp
149bbdd4c7052a0f69242156638e37ffa6cd134d
[]
no_license
LuisAlbertoVasquezVargas/CP
300b0ed91425cd7fea54237a61a4008c5f1ed2b7
2901a603a00822b008fae3ac65b7020dcddcb491
refs/heads/master
2021-01-22T06:23:14.143646
2017-02-16T17:52:59
2017-02-16T17:52:59
81,754,145
0
0
null
null
null
null
UTF-8
C++
false
false
1,045
cpp
#include <bits/stdc++.h> using namespace std; #define sc( x ) scanf( "%d" , &x ) #define REP( i , n ) for( int i = 0 ; i < n ; i++ ) #define clr( t , val ) memset( t , val , sizeof(t) ) #define all(v) v.begin() , v.end() #define pb push_back #define SZ( v ) ((int)(v).size()) #define mp make_pair #define fi first #define se second #define test() cerr << "hola que hace ?" << endl; #define DEBUG( x ) cerr << #x << "=" << x << endl; #define DEBUG2( x , y ) cerr << #x << "=" << x << " " << #y << "=" << y << endl; typedef long long ll; typedef pair< int , int > pii; typedef vector< pii > vpii; typedef vector< int > vi; int main(){ int n , d; while( sc( n ) == 1 ){ sc( d ); vpii v; REP( i , n ){ int x , y; sc( x ) , sc( y ); v.pb( mp( x , y ) ); } sort( all( v ) ); ll ans = 0 , cur = 0; for( int i = 0 , j = -1 ; i < n ; ++i ){ while( j + 1 < n && v[ j + 1 ].fi - v[ i ].fi < d ){ cur += v[ j + 1 ].se; j ++; } ans = max( ans , cur ); cur -= v[ i ].se; } cout << ans << '\n'; } }
[ "luisv0909@gmail.com" ]
luisv0909@gmail.com
6a0e78b137406e34e8456e2ba1dc62337abb146f
b24c5c71797a780f8710dd750ccf2b5f1b749c98
/Classes/Main/ChildLayer/MajorQuestLayer.cpp
c54def8df64c62bbe9b40bca232d0a224d28b73c
[]
no_license
ume3003/Koumechan
088066ba8dc95a2c820f20a41ca77545dd88f413
4d8e597515d0e1d03510ca92b73f3735caa27f7f
refs/heads/master
2021-05-27T22:06:05.407570
2014-08-18T01:53:57
2014-08-18T01:53:57
22,201,565
0
0
null
null
null
null
UTF-8
C++
false
false
2,295
cpp
// // MajorQuestLayer.cpp // koumeChan // // Created by 上野 彰三 on 2014/03/19. // // #include "MajorQuestLayer.h" #include "KoumeChan.h" #include "MainScene.h" #include "KCDef.h" #include "JsonKeyString.h" #include "KcListCell.h" #include "DirectionQuest.h" #include "MajorQuest.h" using namespace cocos2d; using namespace std; using namespace cocos2d::extension; MajorQuestLayer::MajorQuestLayer() { } MajorQuestLayer::~MajorQuestLayer() { } bool MajorQuestLayer::init() { if(KcListLayer::init()){ return true; } return false; }; void MajorQuestLayer::onEnter() { KcListLayer::onEnter(); } std::string MajorQuestLayer::getHeaderString() { DirectionQuest* direction = KoumeChan::getInstance()->getDirectionMaster(); if(direction){ return direction->getName().asString(); } return string("メインクエスト"); }; bool MajorQuestLayer::enable(long index) { return true; }; long MajorQuestLayer::numberOfCellsInTableView(cocos2d::extension::TableView* table) { DirectionQuest* direction = KoumeChan::getInstance()->getDirectionMaster(); if(direction){ vector<long > v =direction->getMajorQuestNos(); return v.size(); } return 0L; }; bool MajorQuestLayer::isSameCell(cocos2d::extension::TableViewCell* preCell,long index) { DirectionQuest* direction = KoumeChan::getInstance()->getDirectionMaster(); if(direction){ vector<long > v =direction->getMajorQuestNos(); KcListCell* preListCell = (KcListCell*)preCell; return preListCell->getId() == v.at(index); } return false; }; cocos2d::extension::TableViewCell* MajorQuestLayer::getNewCell(long index) { DirectionQuest* direction = KoumeChan::getInstance()->getDirectionMaster(); if(direction){ vector<long > v =direction->getMajorQuestNos(); long majorQuestNo = v.at(index); MajorQuest* major = KoumeChan::getInstance()->getMajorQuestMaster(majorQuestNo); return KcListCell::create(major->getMasterNo(),major->getName(),Value(""),Size(getCellWidth(),getCellHeight())); } KcListCell* cell = KcListCell::create(index, Value(StringUtils::format("No %ld",index)), Value(""), Size(getCellWidth(),getCellHeight())); return cell; }; void MajorQuestLayer::onTouchCell(long id) { KoumeChan::getInstance()->changeMajorQuest(id); ((MainScene*)getParent())->showMinorQuestLayer(); }
[ "shozo.ueno@smikiegames.com" ]
shozo.ueno@smikiegames.com
628ec8f1c2e93b1bcce54812cb2953a7968388b7
64fda67d42a44deab0a57834fc2e04ce0e655425
/tempest_source/Engine/AudioTool/AudioSystem.h
38e8a2313c89c7b91465b140e658c142b4024495
[]
no_license
charlesboudousquie/Workbench
6984575e2fddc7c1eaa59ab9ad6861cb51aa884c
724021fa76a33cdb0182f53392918f4560960f9b
refs/heads/master
2020-08-17T16:33:44.040296
2019-11-24T03:45:33
2019-11-24T03:45:33
215,687,374
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,147
h
/*!*************************************************************************************** \file AudioSystem.h \author Morgen Hyde \date 7/31/18 \copyright All content © 2018-2019 DigiPen (USA) Corporation, all rights reserved. \par Project: Boomerang \brief *****************************************************************************************/ #pragma once #include "SystemBase.h" #include "AudioEngine.hpp" #include "UIEventTypes.h" class AudioSystem : public SystemBase { public: AudioSystem(); ~AudioSystem(); bool onInitialize() override; void onUpdate() override; void onShutdown() override; void sendAudioEvent(Audio::EventBase* audioEvent) { engine->postEvent(audioEvent); } Audio::BusInterface* getBusInterface() const; const std::string& getSystemName() const override { return systemName; } void playHandler(Audio::PlayEvent* pEvent); void stopHandler(Audio::StopEvent* sEvent); void pauseHandler(Audio::PauseEvent* pEvent); void IOSwapHandler(Audio::IOTargetSwapEvent* iEvent); private: Audio::AudioEngine* engine; std::string systemName; };
[ "charlesboudousquie@gmail.com" ]
charlesboudousquie@gmail.com
21f1af2238cdab5a9201a0bcfb0ed82de2740ce8
8e5d955bb99dbac495e14bf93642eff324c43db4
/segundo curso/primer cuatrimestre/programacion avanzada/Proyecto 18-10-18 - copia - copia/Base/Base/cilindro.cpp
04918bc0433ec89b46d678e7168e40961eb042a0
[]
no_license
Ivan-Sanandres/universidad
af7038ac7c5f8e1879d24e2f90a1de2c5f08afc7
7a34ae5b0e680c941ddea7756c9c396c616730aa
refs/heads/master
2021-10-12T02:59:13.834881
2019-01-31T20:16:41
2019-01-31T20:16:41
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
701
cpp
#include "cilindro.h" Cilindro::Cilindro(float rad1, float rad2) { quadratic = gluNewQuadric(); rad1 = rad; rad2 = rad; } void Cilindro::render() { glPushMatrix(); //Push y Pop se usan para que las transformaciones anteriores no afecten glTranslatef(this->getPos().getX(), this->getPos().getY(), this->getPos().getZ());//también lo puedo poner como this->pos.x o (*this).pos.x //glRotatef(t / 30, 1.0, 0.0, 0.0); glColor3f(this->getCol().getX(), this->getCol().getY(), this->getCol().getZ()); gluCylinder(quadratic, rad, rad, he, 15, 15); //pinta un cubo glPopMatrix(); //Al no poner el pop aquí, se anida con las transformaciones siguientes permitiendo efectos como órbitas }
[ "rrevolverr09@gmail.com" ]
rrevolverr09@gmail.com
0bcecde3bd314b0b24e198f6c95f3c055b43371e
9e665e26ce5f312a11d5923f029a5d96079dbf99
/线性表-单链表/线性表-单链表2.cpp
10825312a3d4a203192d4a84880e6b88b5debd3a
[]
no_license
Mercury-Duo/List-ListNode
ffe313d99d16ef2dba9c5c3b9272701d33e77359
f8d232b206d53943c9a223ef19a611b3f9ba5cbb
refs/heads/master
2023-04-03T21:38:55.547197
2021-04-13T12:05:20
2021-04-13T12:05:20
357,535,986
0
0
null
null
null
null
GB18030
C++
false
false
3,304
cpp
#include <stdio.h> #include <stdlib.h> typedef struct Link { int elem; struct Link* next; }link; link* initLink(); //链表插入的函数,p是链表,elem是插入的结点的数据域,add是插入的位置 link* insertElem(link* p, int elem, int add); //删除结点的函数,p代表操作链表,add代表删除节点的位置 link* delElem(link* p, int add); //查找结点的函数,elem为目标结点的数据域的值 int selectElem(link* p, int elem); //更新结点的函数,newElem为新的数据域的值 link* amendElem(link* p, int add, int newElem); void display(link* p); int main() { //初始化链表(1,2,3,4) printf("初始化链表为:\n"); link* p = initLink(); display(p); printf("在第4的位置插入元素5:\n"); p = insertElem(p, 5, 4); display(p); printf("删除元素3:\n"); p = delElem(p, 3); display(p); printf("查找元素2的位置为:\n"); int address = selectElem(p, 2); if (address == -1) { printf("没有该元素"); } else { printf("元素2的位置为:%d\n", address); } printf("更改第3的位置的数据为7:\n"); p = amendElem(p, 3, 7); display(p); return 0; } link* initLink() { link* p = (link*)malloc(sizeof(link));//创建一个头结点 link* temp = p;//声明一个指针指向头结点,用于遍历链表 //生成链表 for (int i = 1; i < 5; i++) { link* a = (link*)malloc(sizeof(link)); a->elem = i; a->next = NULL; temp->next = a; temp = temp->next; } return p; } link* insertElem(link* p, int elem, int add) { link* temp = p;//创建临时结点temp //首先找到要插入位置的上一个结点 for (int i = 1; i < add; i++) { if (temp == NULL) { printf("插入位置无效\n"); return p; } temp = temp->next; } //创建插入结点c link* c = (link*)malloc(sizeof(link)); c->elem = elem; //向链表中插入结点 c->next = temp->next; temp->next = c; return p; } link* delElem(link* p, int add) { link* temp = p; //遍历到被删除结点的上一个结点 for (int i = 1; i < add; i++) { temp = temp->next; } link* del = temp->next;//单独设置一个指针指向被删除结点,以防丢失 temp->next = temp->next->next;//删除某个结点的方法就是更改前一个结点的指针域 free(del);//手动释放该结点,防止内存泄漏 return p; } int selectElem(link* p, int elem) { link* t = p; int i = 1; while (t->next) { t = t->next; if (t->elem == elem) { return i; } i++; } return -1; } link* amendElem(link* p, int add, int newElem) { link* temp = p; temp = temp->next;//tamp指向首元结点 //temp指向被删除结点 for (int i = 1; i < add; i++) { temp = temp->next; } temp->elem = newElem; return p; } void display(link* p) { link* temp = p;//将temp指针重新指向头结点 //只要temp指针指向的结点的next不是Null,就执行输出语句。 while (temp->next) { temp = temp->next; printf("%d", temp->elem); } printf("\n"); }
[ "铎@DESKTOP-733MSEH" ]
铎@DESKTOP-733MSEH
0707b66c777f45903931cfd1b5236ace7ccd9cf8
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/enduser/windows.com/wuv3/wuv3is/autoupd.cpp
8dacd54cf627a18ea92e7fa75264168358568a4c
[]
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
19,890
cpp
//======================================================================= // // Copyright (c) 1999 Microsoft Corporation. All Rights Reserved. // // File: autoupd.cpp // // Owner: YanL // // Description: // // AutoApdateSupport // //======================================================================= #include "stdafx.h" #include "WUV3IS.h" #include <stdio.h> #include <initguid.h> #include <inseng.h> #include <shlwapi.h> #include <wininet.h> #define USEWUV3INCLUDES #include <wuv3.h> #undef USEWUV3INCLUDES #include <winspool.h> #include <cstate.h> #include <wustl.h> #include <osdet.h> #include "CV3.h" #include "detect.h" #include "callback.h" #include "locstr.h" #include "safearr.h" #include "install.h" #include "log.h" #include "filecrc.h" #include "newtrust.h" #define REGKEY_WUV3TEST _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\wuv3test") extern CState g_v3state; //defined in CV3.CPP extern void ProcessInstallList(Varray<DEPENDPUID>& vFinalList, int& cFinalList); static void Cleanup(PINVENTORY_ITEM pItem); // find auto-update catalog and get all puids in dependency order STDMETHODIMP CCV3::BuildCatalog(BOOL fGoOnline, DWORD dwType, BSTR bstrServerUrl) { LOG_block("CCV3::BuildCatalog"); if (fGoOnline) { LOG_out("fGoOnline = true"); } else { LOG_out("fGoOnline = false"); } try { // we don't want to check the launch server from this interface m_bLaunchServChecked = TRUE; // Configure download CWUDownload::s_fOffline = ! fGoOnline; PUID puidCatalog = 0; #ifdef _WUV3TEST // catalog spoofing auto_hkey hkey; if (NO_ERROR == RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGKEY_WUV3TEST, 0, KEY_READ, &hkey)) { DWORD dwPuidCatalog = 0; DWORD dwSize = sizeof(dwPuidCatalog); if (NO_ERROR == RegQueryValueEx(hkey, _T("AutoUpdateCatalog"), 0, 0, (LPBYTE)&dwPuidCatalog, &dwSize)) { LOG_out("Test override to catalog %d", dwPuidCatalog); puidCatalog = dwPuidCatalog; } } // only then do normal if (0 == puidCatalog) { #endif CCatalog* pCatalogList = ProcessCatalog(0, bstrServerUrl, 0, 0, WU_ALL_ITEMS, 0); if (NULL == pCatalogList) { LOG_error("Cannot open catalog list"); return E_FAIL; } for(int nCatalog = 0; nCatalog < pCatalogList->GetHeader()->totalItems; nCatalog ++) { PINVENTORY_ITEM pItem = pCatalogList->GetItem(nCatalog); if (NULL == pItem) { continue; } if (pItem->ps->state != WU_ITEM_STATE_PRUNED && (pItem->pf->d.flags & dwType)) { puidCatalog = pItem->pf->d.puid; LOG_out("Found AutoUpdate catalog %d", puidCatalog); break; } } #ifdef _WUV3TEST } #endif if (0 == puidCatalog) { LOG_error("Can't find AU catalog puid"); return E_FAIL; } m_pCatalogAU = ProcessCatalog(puidCatalog, bstrServerUrl, 0, 0, WU_ALL_ITEMS, 0); if (NULL == m_pCatalogAU) { LOG_error("Cannot open catalog"); return E_FAIL; } ReadHiddenPuids(); // download common images and other files if (fGoOnline) { TCHAR szRtfDir[MAX_PATH]; GetWindowsUpdateDirectory(szRtfDir); PathAppend(szRtfDir, _T("RTF")); V3_CreateDirectory(szRtfDir); (void)DownloadCommonRTFFiles(FALSE, NULL); } } catch(HRESULT hr) { LOG_error("error %08X", hr); return hr; } return S_OK; } // find auto-update catalog and get all puids in dependency order STDMETHODIMP CCV3::GetPuidsList(LONG* pcnPuids, PUID** ppPuids) { LOG_block("CCV3::GetPuidsList"); HRESULT hrRet = S_OK; try { // Builds correct dependency array Varray<DEPENDPUID> vFinalList; int cFinalList = 0; ProcessInstallList(vFinalList, cFinalList); if (0 == cFinalList) return E_INVALIDARG; //output it m_apuids.resize(cFinalList); PUID* pPuids = m_apuids; for (int nPuid = 0; nPuid < cFinalList; nPuid++) pPuids[nPuid] = vFinalList[nPuid].puid; *pcnPuids = m_apuids.size(); *ppPuids = m_apuids; } catch(HRESULT hr) { LOG_error("error %08X", hr); hrRet = hr; } return hrRet; } static void UrlAppend(LPTSTR pszURL, LPCTSTR pszPath) { if (_T('/') != pszURL[lstrlen(pszURL) - 1]) lstrcat(pszURL, _T("/")); lstrcat(pszURL, pszPath); } STDMETHODIMP CCV3::QueryDownloadFiles(long puid, void* pCallbackParam, PFN_QueryDownloadFilesCallback pCallback) { LOG_block("CCV3::QueryDownloadFiles"); LOG_out("puid %d", puid); try { USES_CONVERSION; PINVENTORY_ITEM pItem; if (!g_v3state.GetCatalogAndItem(puid, &pItem, NULL)) return E_INVALIDARG; // Buffers that we will use TCHAR szURL[INTERNET_MAX_URL_LENGTH]; TCHAR szLocalFile[MAX_PATH]; // CIF if (pItem->recordType == WU_TYPE_ACTIVE_SETUP_RECORD) { PWU_VARIABLE_FIELD pvCif = pItem->pd->pv->Find(WU_DESC_CIF_CRC); if (NULL == pvCif) return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND); TCHAR szCifBaseName[16]; wsprintf(szCifBaseName, _T("%d.cif"), puid); TCHAR szCifCRCName[64]; HRESULT hr = MakeCRCName(szCifBaseName, (WUCRC_HASH*)pvCif->pData, szCifCRCName, sizeof(szCifCRCName)); if (FAILED(hr)) return hr; GetWindowsUpdateDirectory(szLocalFile); PathAppend(szLocalFile, szCifBaseName); lstrcpy(szURL, g_v3state.GetRootServer()); UrlAppend(szURL, _T("CRCCif")); UrlAppend(szURL, szCifCRCName); pCallback(pCallbackParam, puid, T2W(szURL), T2W(szLocalFile)); } // read this first pages PWU_VARIABLE_FIELD pvRTFCRC = pItem->pd->pv->Find(WU_DESC_RTF_CRC_ARRAY); if (pvRTFCRC != NULL) { PWU_VARIABLE_FIELD pvRTFImages = pItem->pd->pv->Find(WU_DESC_RTF_IMAGES); // build a multisz string of file names BYTE mszFileNames[512]; int iLen = sprintf((char*)mszFileNames, "%d.htm", pItem->GetPuid()); mszFileNames[++iLen] = '\0'; if (pvRTFImages != NULL) { // we have images memcpy(mszFileNames + iLen, pvRTFImages->pData, pvRTFImages->len - 4); } // local directory TCHAR szLocalDir[MAX_PATH]; GetWindowsUpdateDirectory(szLocalDir); wsprintf(szLocalFile, _T("RTF\\%d"), pItem->GetPuid()); // reuse szLocalFile as a temp buffer PathAppend(szLocalDir, szLocalFile); for(int iFileNo = 0; true; iFileNo++) { TCHAR szLocalName[128]; TCHAR szServerName[128]; if (FAILED(GetCRCNameFromList(iFileNo, mszFileNames, pvRTFCRC->pData, szServerName, sizeof(szServerName), szLocalName))) { // end of the list break; } // build full paths lstrcpy(szLocalFile, szLocalDir); PathAppend(szLocalFile, szLocalName); lstrcpy(szURL, g_v3state.GetRootServer()); UrlAppend(szURL, _T("CRCRtf")); UrlAppend(szURL, szServerName); LOG_out("%s - %s", szURL, szLocalFile); pCallback(pCallbackParam, puid, T2W(szURL), T2W(szLocalFile)); } // for } // Cabs TCHAR szLocalDir[MAX_PATH]; GetWindowsUpdateDirectory(szLocalDir); wsprintf(szLocalFile, _T("Cabs\\%d"), puid); // reuse szLocalFile as a temp buffer PathAppend(szLocalDir, szLocalFile); //See if the package has a server override defined. PWU_VARIABLE_FIELD pvServer = pItem->pd->pv->Find(WU_DESCRIPTION_SERVERROOT); LPCTSTR pszCabPoolServer = pvServer ? A2T((LPSTR)(pvServer->pData)) : g_v3state.GetCabPoolServer(); PWU_VARIABLE_FIELD pvCabs = pItem->pd->pv->Find(WU_DESCRIPTION_CABFILENAME); PWU_VARIABLE_FIELD pvCRCs = pItem->pd->pv->Find(WU_DESC_CRC_ARRAY); if (NULL == pvCabs || NULL == pvCRCs) { // Active setup items can have no cabs if( pItem->recordType != WU_TYPE_ACTIVE_SETUP_RECORD) return HRESULT_FROM_WIN32(ERROR_NOT_FOUND); } else { for(int iCabNo = 0; true; iCabNo++) { TCHAR szLocalCab[128]; TCHAR szServerCab[128]; if (FAILED(GetCRCNameFromList(iCabNo, pvCabs->pData, pvCRCs->pData, szServerCab, sizeof(szServerCab) , szLocalCab))) break; PathCombine(szLocalFile, szLocalDir, szLocalCab); lstrcpy(szURL, pszCabPoolServer); UrlAppend(szURL, _T("CabPool")); UrlAppend(szURL, szServerCab); LOG_out("%s - %s", szURL, szLocalFile); pCallback(pCallbackParam, puid, T2W(szURL), T2W(szLocalFile)); } } } catch (HRESULT hr) { LOG_error("error %08X", hr); return hr; } return S_OK; } STDMETHODIMP CCV3::GetCatalogArray(VARIANT *pCatalogArray) { LOG_block("CCV3::GetCatalogArray"); try { return MakeReturnCatalogArray(m_pCatalogAU, WU_UPDATE_ITEMS, 0, pCatalogArray); } catch (HRESULT hr) { LOG_error("error %08X", hr); return hr; } return S_OK; } STDMETHODIMP CCV3::SelectAllPuids() { LOG_block("CCV3::SelectAllPuids"); try { for(int nItem = 0; nItem < m_pCatalogAU->GetHeader()->totalItems; nItem ++) { PINVENTORY_ITEM pItem = m_pCatalogAU->GetItem(nItem); if (NULL == pItem) { continue; } if (! pItem->ps->bHidden && ( WU_TYPE_ACTIVE_SETUP_RECORD == pItem->recordType || WU_TYPE_CDM_RECORD == pItem->recordType || WU_TYPE_RECORD_TYPE_PRINTER == pItem->recordType ) && ( WU_ITEM_STATE_INSTALL == pItem->ps->state || WU_ITEM_STATE_UPDATE == pItem->ps->state )) { PUID puid = (WU_TYPE_ACTIVE_SETUP_RECORD == pItem->recordType) ? pItem->pf->a.puid : pItem->pf->d.puid; if (!IsPuidHidden(puid)) g_v3state.m_selectedItems.Select(puid, TRUE); } } } catch (HRESULT hr) { LOG_error("error %08X", hr); return hr; } return S_OK; } STDMETHODIMP CCV3::UnselectAllPuids() { LOG_block("CCV3::UnselectAllPuids"); try { g_v3state.m_selectedItems.Clear(); } catch (HRESULT hr) { LOG_error("error %08X", hr); return hr; } return S_OK; } STDMETHODIMP CCV3::SelectPuid(long puid) { LOG_block("CCV3::SelectPuid"); try { if (IsPuidHidden(puid)) throw E_INVALIDARG; g_v3state.m_selectedItems.Select(puid, TRUE); } catch (HRESULT hr) { LOG_error("error %08X", hr); return hr; } return S_OK; } STDMETHODIMP CCV3::UnselectPuid(long puid) { LOG_block("CCV3::UnselectPuid"); try { if (IsPuidHidden(puid)) throw E_INVALIDARG; g_v3state.m_selectedItems.Unselect(puid); } catch (HRESULT hr) { LOG_error("error %08X", hr); return hr; } return S_OK; } static void RemoveFiles(long puid, bool fCif) { TCHAR szBaseName[16]; TCHAR szLocalFile[MAX_PATH]; if (fCif) { wsprintf(szBaseName, _T("%d.cif"), puid); GetWindowsUpdateDirectory(szLocalFile); PathAppend(szLocalFile, szBaseName); DeleteFile(szLocalFile); } wsprintf(szBaseName, _T("Cabs\\%d"), puid); GetWindowsUpdateDirectory(szLocalFile); PathAppend(szLocalFile, szBaseName); DeleteNode(szLocalFile); wsprintf(szBaseName, _T("RTF\\%d"), puid); GetWindowsUpdateDirectory(szLocalFile); PathAppend(szLocalFile, szBaseName); DeleteNode(szLocalFile); } STDMETHODIMP CCV3::HidePuid(long puid) { LOG_block("CCV3::HidePuid"); try { PINVENTORY_ITEM pItem; if (!g_v3state.GetCatalogAndItem(puid, &pItem, NULL)) return E_INVALIDARG; // Hide it in catalog pItem->ps->bHidden = TRUE; pItem->ps->dwReason = WU_STATE_REASON_BACKEND; // Unselect it g_v3state.m_selectedItems.Unselect(puid); HidePuidAndSave(puid); RemoveFiles(puid, pItem->recordType == WU_TYPE_ACTIVE_SETUP_RECORD); } catch (HRESULT hr) { LOG_error("error %08X", hr); return hr; } return S_OK; } STDMETHODIMP CCV3::InstallSelectedPuids(void* pCallbackParam, PFN_InstallCallback pCallback) { LOG_block("CCV3::InstallSelectedPuids"); try { // Builds correct dependency array Varray<DEPENDPUID> vFinalList; int cFinalList = 0; ProcessInstallList(vFinalList, cFinalList); //output it for (int nPuid = 0; nPuid < cFinalList; nPuid++) { PINVENTORY_ITEM pItem; if (!g_v3state.GetCatalogAndItem(vFinalList[nPuid].puid, &pItem, NULL)) throw E_FAIL; SELECTITEMINFO info; info.bInstall = TRUE; info.puid = vFinalList[nPuid].puid; info.iStatus = ITEM_STATUS_SUCCESS; info.hrError = S_OK; InstallItemAU(pItem, &info); LOG_out("%d status %d error %d(%08X)\n", info.puid, info.iStatus, info.hrError, info.hrError); pCallback(pCallbackParam, info.puid, info.iStatus, info.hrError); } } catch(HRESULT hr) { LOG_error("error %08X", hr); return hr; } return S_OK; } STDMETHODIMP CCV3::CleanupCabsAndReadThis(void) { LOG_block("CCV3::CleanupCabsAndReadThis"); TCHAR szCabDir[MAX_PATH]; GetWindowsUpdateDirectory(szCabDir); PathAppend(szCabDir, _T("Cabs")); DeleteNode(szCabDir); CleanupReadThis(); return S_OK; } STDMETHODIMP CCV3::UnhideAllPuids(void) { LOG_block("CCV3::CleanupCabsAndReadThis"); RegDeleteKey(HKEY_LOCAL_MACHINE, REGISTRYHIDING_KEY); return S_OK; } STDMETHODIMP CCV3::StatusReport(long puid, LPCSTR pszStatus) { LOG_block("CCV3::StatusReport"); try { PINVENTORY_ITEM pItem; if (!g_v3state.GetCatalogAndItem(puid, &pItem, NULL)) { LOG_error("invalid arg"); return E_INVALIDARG; } CWUDownload dl(g_v3state.GetIdentServer(), 8192); // build the URL with parameters TCHAR szURL[INTERNET_MAX_PATH_LENGTH]; wsprintf(szURL, _T("wutrack.bin?PUID=%d&PLAT=%d&LOCALE=%s&STATUS=%s&RID=%4.4x%4.4x"), pItem->GetPuid(), m_pCatalogAU->GetPlatform(), m_pCatalogAU->GetMachineLocaleSZ(), pszStatus, rand(), rand()); // ping the URL and receive the response in memory PVOID pMemBuf; ULONG ulMemSize; if (dl.QCopy(szURL, &pMemBuf, &ulMemSize)) { // we don't care about the response so we just free it LOG_error("%s", szURL); V3_free(pMemBuf); } else { LOG_out("%s", szURL); } } catch (HRESULT hr) { LOG_error("error %08X", hr); } return S_OK; } STDMETHODIMP CCV3::DownloadReadThisPage(long puid) { LOG_block("CCV3::DownloadReadThisPage"); LOG_out("puid = %d", puid); try { PINVENTORY_ITEM pItem; if (!g_v3state.GetCatalogAndItem(puid, &pItem, NULL)) { LOG_error("no item"); return E_INVALIDARG; } return DownloadReadThis(pItem); } catch (HRESULT hr) { LOG_error("error %08X", hr); return hr; } return S_OK; } void CCV3::InstallItemAU(PINVENTORY_ITEM pItem, PSELECTITEMINFO pinfo) { LOG_block("CCV3::InstallItemAU"); try { GetCurTime(&(pinfo->stDateTime)); CDiamond diamond; // local directory TCHAR szLocalDir[MAX_PATH]; GetWindowsUpdateDirectory(szLocalDir); TCHAR szTmp[40]; wsprintf(szTmp, _T("Cabs\\%d"), pinfo->puid); PathAppend(szLocalDir, szTmp); // Decompress cab files PWU_VARIABLE_FIELD pvCabs = pItem->pd->pv->Find(WU_DESCRIPTION_CABFILENAME); PWU_VARIABLE_FIELD pvCRCs = pItem->pd->pv->Find(WU_DESC_CRC_ARRAY); if (NULL != pvCabs && NULL != pvCRCs) { for(int iCabNo = 0; true; iCabNo++) { TCHAR szLocalCab[128]; TCHAR szLocalFile[MAX_PATH]; // we don't care about server file name if (FAILED(GetCRCNameFromList(iCabNo, pvCabs->pData, pvCRCs->pData, szLocalFile, sizeof(szLocalFile), szLocalCab))) break; PathCombine(szLocalFile, szLocalDir, szLocalCab); // check signature of the download CAB file // Don't show MS cert. // use the VerifyFile function (see WU bug # 12251) HRESULT hr = VerifyFile(szLocalFile, FALSE); if (FAILED(hr)) throw hr; if( pItem->recordType != WU_TYPE_ACTIVE_SETUP_RECORD && diamond.IsValidCAB(szLocalFile)) diamond.Decompress(szLocalFile, _T("*")); } } switch (pItem->recordType) { case WU_TYPE_ACTIVE_SETUP_RECORD: { TCHAR szCIFFile[MAX_PATH]; TCHAR szCifBaseName[16]; wsprintf(szCifBaseName, _T("%d.cif"), pItem->GetPuid()); GetWindowsUpdateDirectory(szCIFFile); PathAppend(szCIFFile, szCifBaseName); // Decompress if we need to if (diamond.IsValidCAB(szCIFFile)) { TCHAR szTmpCif[MAX_PATH]; lstrcpy(szTmpCif, szCIFFile); lstrcpy(szTmpCif, _T(".cab")); MoveFile(szCIFFile, szTmpCif); diamond.Decompress(szTmpCif, szCIFFile); DeleteFile(szTmpCif); } LOG_out("calling InstallActiveSetupItem(szLocalDir=%s, szCIFFile=%s) for puid %d", szLocalDir, szCIFFile, pinfo->puid); InstallActiveSetupItem(szLocalDir, szCIFFile, pinfo, NULL); } break; case WU_TYPE_CDM_RECORD: LOG_out("calling InstallDriverItem(szLocalDir=%s) for puid %d", szLocalDir, pinfo->puid); InstallDriverItem(szLocalDir, IsWindowsNT(), _T(""), pItem, pinfo); break; case WU_TYPE_RECORD_TYPE_PRINTER: { PWU_VARIABLE_FIELD pvDriverName = pItem->pv->Find(WU_CDM_DRIVER_NAME); PWU_VARIABLE_FIELD pvArchitecture = pItem->pv->Find(WU_CDM_PRINTER_DRIVER_ARCH); if (NULL == pvDriverName || NULL == pvArchitecture) throw E_UNEXPECTED; // should never happen LOG_out("calling InstallPrinterItem(szDriverName=%s, szLocalDir=%s) for puid %d", (LPCTSTR)pvDriverName->pData, szLocalDir, pinfo->puid); InstallPrinterItem((LPCTSTR)pvDriverName->pData, szLocalDir, (LPCTSTR)pvArchitecture->pData); } break; case WU_TYPE_CDM_RECORD_PLACE_HOLDER: case WU_TYPE_SECTION_RECORD: case WU_TYPE_SUBSECTION_RECORD: case WU_TYPE_SUBSUBSECTION_RECORD: default: LOG_error(" cannot install recordtype %d for puid %d", pItem->recordType, pinfo->puid); throw E_UNEXPECTED; } } catch(HRESULT hr) { pinfo->iStatus = ITEM_STATUS_FAILED; pinfo->hrError = hr; } // Cleanup RemoveFiles(pItem->GetPuid(), pItem->recordType == WU_TYPE_ACTIVE_SETUP_RECORD); UpdateInstallHistory(pinfo, 1); } void CCV3::ReadHiddenPuids() { auto_hkey hKey; if (NO_ERROR == RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGISTRYHIDING_KEY, 0, KEY_READ, &hKey)) { DWORD dwSize; if ( NO_ERROR == RegQueryValueEx(hKey, _T("AutoUpdateItems"), NULL, NULL, NULL, &dwSize) && dwSize > 0 ) { m_abHiddenPuids.resize(dwSize); if (NO_ERROR != RegQueryValueEx(hKey, _T("AutoUpdateItems"), NULL, NULL, m_abHiddenPuids, &dwSize)) m_abHiddenPuids.resize(0); } } PUID* ppuidHidden =(PUID*)(LPBYTE)m_abHiddenPuids; for(int nOffset = 0; nOffset < m_abHiddenPuids.size(); nOffset += sizeof(PUID)) { PINVENTORY_ITEM pItem; if (g_v3state.GetCatalogAndItem(*ppuidHidden, &pItem, NULL)) { // Hide it in catalog pItem->ps->bHidden = TRUE; pItem->ps->dwReason = WU_STATE_REASON_BACKEND; } ppuidHidden ++; } } bool CCV3::IsPuidHidden(PUID puid) { PUID* ppuidHidden =(PUID*)(LPBYTE)m_abHiddenPuids; for(int nOffset = 0; nOffset < m_abHiddenPuids.size(); nOffset += sizeof(PUID)) { if (*ppuidHidden == puid) return true; ppuidHidden ++; } return false; } void CCV3::HidePuidAndSave(PUID puid) { // Bug 378289 // The following block of reading the registry value and putting it into m_abHiddenPuids has been added. // This is because, in the earlier case the m_abHiddenPuids would be read the first time from the registry // and would hold on to the registry values. // Due to this it would not reflect the new changes made by the user (eg. Clear History), and would write back the old values in m_abHiddenPuids back onto the registry // By making the following change m_abHiddenPuids contains the updated registry values. m_abHiddenPuids.resize(0); auto_hkey hKey; if (NO_ERROR == RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGISTRYHIDING_KEY, 0, KEY_READ, &hKey)) { DWORD dwSize; if ( NO_ERROR == RegQueryValueEx(hKey, _T("AutoUpdateItems"), NULL, NULL, NULL, &dwSize) && dwSize > 0 ) { m_abHiddenPuids.resize(dwSize); if (NO_ERROR != RegQueryValueEx(hKey, _T("AutoUpdateItems"), NULL, NULL, m_abHiddenPuids, &dwSize)) m_abHiddenPuids.resize(0); } } if (IsPuidHidden(puid)) return; int cbSize = m_abHiddenPuids.size(); m_abHiddenPuids.resize(cbSize + sizeof(PUID)); *(PUID*)((LPBYTE)m_abHiddenPuids + cbSize) = puid; DWORD dwDisposition; if (NO_ERROR == RegCreateKeyEx(HKEY_LOCAL_MACHINE, REGISTRYHIDING_KEY, 0, _T(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &dwDisposition)) { if (0 == m_abHiddenPuids.size()) { RegDeleteValue(hKey, _T("AutoUpdateItems")); } else { RegSetValueEx(hKey, _T("AutoUpdateItems"), 0, REG_BINARY, m_abHiddenPuids, m_abHiddenPuids.size()); } } }
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
9446c2578530e1591a1f1c85ccb432b3fd5dc05b
dca653bb975528bd1b8ab2547f6ef4f48e15b7b7
/tags/wxPy-2.9.0.1/src/common/imagpng.cpp
3305f30b04104eb50f2227bc759b74217177d644
[]
no_license
czxxjtu/wxPython-1
51ca2f62ff6c01722e50742d1813f4be378c0517
6a7473c258ea4105f44e31d140ea5c0ae6bc46d8
refs/heads/master
2021-01-15T12:09:59.328778
2015-01-05T20:55:10
2015-01-05T20:55:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,266
cpp
///////////////////////////////////////////////////////////////////////////// // Name: src/common/imagpng.cpp // Purpose: wxImage PNG handler // Author: Robert Roebling // RCS-ID: $Id$ // Copyright: (c) Robert Roebling // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_IMAGE && wxUSE_LIBPNG #include "wx/imagpng.h" #ifndef WX_PRECOMP #include "wx/log.h" #include "wx/intl.h" #include "wx/palette.h" #include "wx/stream.h" #endif #include "png.h" // For memcpy #include <string.h> // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // image can not have any transparent pixels at all, have only 100% opaque // and/or 100% transparent pixels in which case a simple mask is enough to // store this information in wxImage or have a real alpha channel in which case // we need to have it in wxImage as well enum Transparency { Transparency_None, Transparency_Mask, Transparency_Alpha }; // ---------------------------------------------------------------------------- // local functions // ---------------------------------------------------------------------------- // return the kind of transparency needed for this image assuming that it does // have transparent pixels, i.e. either Transparency_Alpha or Transparency_Mask static Transparency CheckTransparency(unsigned char **lines, png_uint_32 x, png_uint_32 y, png_uint_32 w, png_uint_32 h, size_t numColBytes); // init the alpha channel for the image and fill it with 1s up to (x, y) static unsigned char *InitAlpha(wxImage *image, png_uint_32 x, png_uint_32 y); // find a free colour for the mask in the PNG data array static void FindMaskColour(unsigned char **lines, png_uint_32 width, png_uint_32 height, unsigned char& rMask, unsigned char& gMask, unsigned char& bMask); // is the pixel with this value of alpha a fully opaque one? static inline bool IsOpaque(unsigned char a) { return a == 0xff; } // is the pixel with this value of alpha a fully transparent one? static inline bool IsTransparent(unsigned char a) { return !a; } // ============================================================================ // wxPNGHandler implementation // ============================================================================ IMPLEMENT_DYNAMIC_CLASS(wxPNGHandler,wxImageHandler) #if wxUSE_STREAMS #ifndef PNGLINKAGEMODE #ifdef PNGAPI #define PNGLINKAGEMODE PNGAPI #elif defined(__WATCOMC__) // we need an explicit cdecl for Watcom, at least according to // // http://sf.net/tracker/index.php?func=detail&aid=651492&group_id=9863&atid=109863 // // more testing is needed for this however, please remove this comment // if you can confirm that my fix works with Watcom 11 #define PNGLINKAGEMODE cdecl #else #define PNGLINKAGEMODE LINKAGEMODE #endif #endif // VS: wxPNGInfoStruct declared below is a hack that needs some explanation. // First, let me describe what's the problem: libpng uses jmp_buf in // its png_struct structure. Unfortunately, this structure is // compiler-specific and may vary in size, so if you use libpng compiled // as DLL with another compiler than the main executable, it may not work // (this is for example the case with wxMGL port and SciTech MGL library // that provides custom runtime-loadable libpng implementation with jmpbuf // disabled altogether). Luckily, it is still possible to use setjmp() & // longjmp() as long as the structure is not part of png_struct. // // Sadly, there's no clean way to attach user-defined data to png_struct. // There is only one customizable place, png_struct.io_ptr, which is meant // only for I/O routines and is set with png_set_read_fn or // png_set_write_fn. The hacky part is that we use io_ptr to store // a pointer to wxPNGInfoStruct that holds I/O structures _and_ jmp_buf. struct wxPNGInfoStruct { jmp_buf jmpbuf; bool verbose; union { wxInputStream *in; wxOutputStream *out; } stream; }; #define WX_PNG_INFO(png_ptr) ((wxPNGInfoStruct*)png_get_io_ptr(png_ptr)) // ---------------------------------------------------------------------------- // helper functions // ---------------------------------------------------------------------------- extern "C" { static void PNGLINKAGEMODE wx_PNG_stream_reader( png_structp png_ptr, png_bytep data, png_size_t length ) { WX_PNG_INFO(png_ptr)->stream.in->Read(data, length); } static void PNGLINKAGEMODE wx_PNG_stream_writer( png_structp png_ptr, png_bytep data, png_size_t length ) { WX_PNG_INFO(png_ptr)->stream.out->Write(data, length); } static void PNGLINKAGEMODE wx_png_warning(png_structp png_ptr, png_const_charp message) { wxPNGInfoStruct *info = png_ptr ? WX_PNG_INFO(png_ptr) : NULL; if ( !info || info->verbose ) wxLogWarning( wxString::FromAscii(message) ); } // from pngerror.c // so that the libpng doesn't send anything on stderr static void PNGLINKAGEMODE wx_png_error(png_structp png_ptr, png_const_charp message) { wx_png_warning(NULL, message); // we're not using libpng built-in jump buffer (see comment before // wxPNGInfoStruct above) so we have to return ourselves, otherwise libpng // would just abort longjmp(WX_PNG_INFO(png_ptr)->jmpbuf, 1); } } // extern "C" // ---------------------------------------------------------------------------- // LoadFile() helpers // ---------------------------------------------------------------------------- // determine the kind of transparency we need for this image: if the only alpha // values it has are 0 (transparent) and 0xff (opaque) then we can simply // create a mask for it, we should be ok with a simple mask but otherwise we // need a full blown alpha channel in wxImage // // parameters: // lines raw PNG data // x, y starting position // w, h size of the image // numColBytes number of colour bytes (1 for grey scale, 3 for RGB) // (NB: alpha always follows the colour bytes) Transparency CheckTransparency(unsigned char **lines, png_uint_32 x, png_uint_32 y, png_uint_32 w, png_uint_32 h, size_t numColBytes) { // suppose that a mask will suffice and check all the remaining alpha // values to see if it does for ( ; y < h; y++ ) { // each pixel is numColBytes+1 bytes, offset into the current line by // the current x position unsigned const char *ptr = lines[y] + (x * (numColBytes + 1)); for ( png_uint_32 x2 = x; x2 < w; x2++ ) { // skip the grey or colour byte(s) ptr += numColBytes; unsigned char a2 = *ptr++; if ( !IsTransparent(a2) && !IsOpaque(a2) ) { // not fully opaque nor fully transparent, hence need alpha return Transparency_Alpha; } } // during the next loop iteration check all the pixels in the row x = 0; } // mask will be enough return Transparency_Mask; } unsigned char *InitAlpha(wxImage *image, png_uint_32 x, png_uint_32 y) { // create alpha channel image->SetAlpha(); unsigned char *alpha = image->GetAlpha(); // set alpha for the pixels we had so far png_uint_32 end = y * image->GetWidth() + x; for ( png_uint_32 i = 0; i < end; i++ ) { // all the previous pixels were opaque *alpha++ = 0xff; } return alpha; } void FindMaskColour(unsigned char **lines, png_uint_32 width, png_uint_32 height, unsigned char& rMask, unsigned char& gMask, unsigned char& bMask) { // choosing the colour for the mask is more // difficult: we need to iterate over the entire // image for this in order to choose an unused // colour (this is not very efficient but what else // can we do?) wxImageHistogram h; unsigned nentries = 0; unsigned char r2, g2, b2; for ( png_uint_32 y2 = 0; y2 < height; y2++ ) { const unsigned char *p = lines[y2]; for ( png_uint_32 x2 = 0; x2 < width; x2++ ) { r2 = *p++; g2 = *p++; b2 = *p++; ++p; // jump over alpha wxImageHistogramEntry& entry = h[wxImageHistogram:: MakeKey(r2, g2, b2)]; if ( entry.value++ == 0 ) entry.index = nentries++; } } if ( !h.FindFirstUnusedColour(&rMask, &gMask, &bMask) ) { wxLogWarning(_("Too many colours in PNG, the image may be slightly blurred.")); // use a fixed mask colour and we'll fudge // the real pixels with this colour (see // below) rMask = 0xfe; gMask = 0; bMask = 0xff; } } // ---------------------------------------------------------------------------- // reading PNGs // ---------------------------------------------------------------------------- bool wxPNGHandler::DoCanRead( wxInputStream& stream ) { unsigned char hdr[4]; if ( !stream.Read(hdr, WXSIZEOF(hdr)) ) return false; return memcmp(hdr, "\211PNG", WXSIZEOF(hdr)) == 0; } // convert data from RGB to wxImage format static void CopyDataFromPNG(wxImage *image, unsigned char **lines, png_uint_32 width, png_uint_32 height, int color_type) { Transparency transparency = Transparency_None; // only non NULL if transparency == Transparency_Alpha unsigned char *alpha = NULL; // RGB of the mask colour if transparency == Transparency_Mask // (but init them anyhow to avoid compiler warnings) unsigned char rMask = 0, gMask = 0, bMask = 0; unsigned char *ptrDst = image->GetData(); if ( !(color_type & PNG_COLOR_MASK_COLOR) ) { // grey image: GAGAGA... where G == grey component and A == alpha for ( png_uint_32 y = 0; y < height; y++ ) { const unsigned char *ptrSrc = lines[y]; for ( png_uint_32 x = 0; x < width; x++ ) { unsigned char g = *ptrSrc++; unsigned char a = *ptrSrc++; // the first time we encounter a transparent pixel we must // decide about what to do about them if ( !IsOpaque(a) && transparency == Transparency_None ) { // we'll need at least the mask for this image and // maybe even full alpha channel info: the former is // only enough if we have alpha values of 0 and 0xff // only, otherwisewe need the latter transparency = CheckTransparency ( lines, x, y, width, height, 1 ); if ( transparency == Transparency_Mask ) { // let's choose this colour for the mask: this is // not a problem here as all the other pixels are // grey, i.e. R == G == B which is not the case for // this one so no confusion is possible rMask = 0xff; gMask = 0; bMask = 0xff; } else // transparency == Transparency_Alpha { alpha = InitAlpha(image, x, y); } } switch ( transparency ) { case Transparency_Mask: if ( IsTransparent(a) ) { *ptrDst++ = rMask; *ptrDst++ = gMask; *ptrDst++ = bMask; break; } // else: !transparent // must be opaque then as otherwise we shouldn't be // using the mask at all wxASSERT_MSG( IsOpaque(a), _T("logic error") ); // fall through case Transparency_Alpha: if ( alpha ) *alpha++ = a; // fall through case Transparency_None: *ptrDst++ = g; *ptrDst++ = g; *ptrDst++ = g; break; } } } } else // colour image: RGBRGB... { for ( png_uint_32 y = 0; y < height; y++ ) { const unsigned char *ptrSrc = lines[y]; for ( png_uint_32 x = 0; x < width; x++ ) { unsigned char r = *ptrSrc++; unsigned char g = *ptrSrc++; unsigned char b = *ptrSrc++; unsigned char a = *ptrSrc++; // the logic here is the same as for the grey case except // where noted if ( !IsOpaque(a) && transparency == Transparency_None ) { transparency = CheckTransparency ( lines, x, y, width, height, 3 ); if ( transparency == Transparency_Mask ) { FindMaskColour(lines, width, height, rMask, gMask, bMask); } else // transparency == Transparency_Alpha { alpha = InitAlpha(image, x, y); } } switch ( transparency ) { case Transparency_Mask: if ( IsTransparent(a) ) { *ptrDst++ = rMask; *ptrDst++ = gMask; *ptrDst++ = bMask; break; } else // !transparent { // must be opaque then as otherwise we shouldn't be // using the mask at all wxASSERT_MSG( IsOpaque(a), _T("logic error") ); // if we couldn't find a unique colour for the // mask, we can have real pixels with the same // value as the mask and it's better to slightly // change their colour than to make them // transparent if ( r == rMask && g == gMask && b == bMask ) { r++; } } // fall through case Transparency_Alpha: if ( alpha ) *alpha++ = a; // fall through case Transparency_None: *ptrDst++ = r; *ptrDst++ = g; *ptrDst++ = b; break; } } } } if ( transparency == Transparency_Mask ) { image->SetMaskColour(rMask, gMask, bMask); } } // temporarily disable the warning C4611 (interaction between '_setjmp' and // C++ object destruction is non-portable) - I don't see any dtors here #ifdef __VISUALC__ #pragma warning(disable:4611) #endif /* VC++ */ bool wxPNGHandler::LoadFile(wxImage *image, wxInputStream& stream, bool verbose, int WXUNUSED(index)) { // VZ: as this function uses setjmp() the only fool-proof error handling // method is to use goto (setjmp is not really C++ dtors friendly...) unsigned char **lines = NULL; png_infop info_ptr = (png_infop) NULL; wxPNGInfoStruct wxinfo; png_uint_32 i, width, height = 0; int bit_depth, color_type, interlace_type; wxinfo.verbose = verbose; wxinfo.stream.in = &stream; image->Destroy(); png_structp png_ptr = png_create_read_struct ( PNG_LIBPNG_VER_STRING, (voidp) NULL, wx_png_error, wx_png_warning ); if (!png_ptr) goto error; // NB: please see the comment near wxPNGInfoStruct declaration for // explanation why this line is mandatory png_set_read_fn( png_ptr, &wxinfo, wx_PNG_stream_reader); info_ptr = png_create_info_struct( png_ptr ); if (!info_ptr) goto error; if (setjmp(wxinfo.jmpbuf)) goto error; png_read_info( png_ptr, info_ptr ); png_get_IHDR( png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL ); if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_expand( png_ptr ); // Fix for Bug [ 439207 ] Monochrome PNG images come up black if (bit_depth < 8) png_set_expand( png_ptr ); png_set_strip_16( png_ptr ); png_set_packing( png_ptr ); if (png_get_valid( png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_expand( png_ptr ); png_set_filler( png_ptr, 0xff, PNG_FILLER_AFTER ); image->Create((int)width, (int)height, (bool) false /* no need to init pixels */); if (!image->Ok()) goto error; // initialize all line pointers to NULL to ensure that they can be safely // free()d if an error occurs before all of them could be allocated lines = (unsigned char **)calloc(height, sizeof(unsigned char *)); if ( !lines ) goto error; for (i = 0; i < height; i++) { if ((lines[i] = (unsigned char *)malloc( (size_t)(width * (sizeof(unsigned char) * 4)))) == NULL) goto error; } png_read_image( png_ptr, lines ); png_read_end( png_ptr, info_ptr ); #if wxUSE_PALETTE if (color_type == PNG_COLOR_TYPE_PALETTE) { const size_t ncolors = info_ptr->num_palette; unsigned char* r = new unsigned char[ncolors]; unsigned char* g = new unsigned char[ncolors]; unsigned char* b = new unsigned char[ncolors]; for (size_t j = 0; j < ncolors; j++) { r[j] = info_ptr->palette[j].red; g[j] = info_ptr->palette[j].green; b[j] = info_ptr->palette[j].blue; } image->SetPalette(wxPalette(ncolors, r, g, b)); delete[] r; delete[] g; delete[] b; } #endif // wxUSE_PALETTE png_destroy_read_struct( &png_ptr, &info_ptr, (png_infopp) NULL ); // loaded successfully, now init wxImage with this data CopyDataFromPNG(image, lines, width, height, color_type); for ( i = 0; i < height; i++ ) free( lines[i] ); free( lines ); return true; error: if (verbose) wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory.")); if ( image->Ok() ) { image->Destroy(); } if ( lines ) { for ( unsigned int n = 0; n < height; n++ ) free( lines[n] ); free( lines ); } if ( png_ptr ) { if ( info_ptr ) { png_destroy_read_struct( &png_ptr, &info_ptr, (png_infopp) NULL ); free(info_ptr); } else png_destroy_read_struct( &png_ptr, (png_infopp) NULL, (png_infopp) NULL ); } return false; } // ---------------------------------------------------------------------------- // writing PNGs // ---------------------------------------------------------------------------- bool wxPNGHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose ) { wxPNGInfoStruct wxinfo; wxinfo.verbose = verbose; wxinfo.stream.out = &stream; png_structp png_ptr = png_create_write_struct ( PNG_LIBPNG_VER_STRING, NULL, wx_png_error, wx_png_warning ); if (!png_ptr) { if (verbose) wxLogError(_("Couldn't save PNG image.")); return false; } png_infop info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { png_destroy_write_struct( &png_ptr, (png_infopp)NULL ); if (verbose) wxLogError(_("Couldn't save PNG image.")); return false; } if (setjmp(wxinfo.jmpbuf)) { png_destroy_write_struct( &png_ptr, (png_infopp)NULL ); if (verbose) wxLogError(_("Couldn't save PNG image.")); return false; } // NB: please see the comment near wxPNGInfoStruct declaration for // explanation why this line is mandatory png_set_write_fn( png_ptr, &wxinfo, wx_PNG_stream_writer, NULL); const int iColorType = image->HasOption(wxIMAGE_OPTION_PNG_FORMAT) ? image->GetOptionInt(wxIMAGE_OPTION_PNG_FORMAT) : wxPNG_TYPE_COLOUR; const int iBitDepth = image->HasOption(wxIMAGE_OPTION_PNG_BITDEPTH) ? image->GetOptionInt(wxIMAGE_OPTION_PNG_BITDEPTH) : 8; wxASSERT_MSG( iBitDepth == 8 || iBitDepth == 16, _T("PNG bit depth must be 8 or 16") ); bool bHasAlpha = image->HasAlpha(); bool bHasMask = image->HasMask(); bool bUseAlpha = bHasAlpha || bHasMask; int iPngColorType; if ( iColorType==wxPNG_TYPE_COLOUR ) { iPngColorType = bUseAlpha ? PNG_COLOR_TYPE_RGB_ALPHA : PNG_COLOR_TYPE_RGB; } else { iPngColorType = bUseAlpha ? PNG_COLOR_TYPE_GRAY_ALPHA : PNG_COLOR_TYPE_GRAY; } if (image->HasOption(wxIMAGE_OPTION_PNG_FILTER)) png_set_filter( png_ptr, PNG_FILTER_TYPE_BASE, image->GetOptionInt(wxIMAGE_OPTION_PNG_FILTER) ); if (image->HasOption(wxIMAGE_OPTION_PNG_COMPRESSION_LEVEL)) png_set_compression_level( png_ptr, image->GetOptionInt(wxIMAGE_OPTION_PNG_COMPRESSION_LEVEL) ); if (image->HasOption(wxIMAGE_OPTION_PNG_COMPRESSION_MEM_LEVEL)) png_set_compression_mem_level( png_ptr, image->GetOptionInt(wxIMAGE_OPTION_PNG_COMPRESSION_MEM_LEVEL) ); if (image->HasOption(wxIMAGE_OPTION_PNG_COMPRESSION_STRATEGY)) png_set_compression_strategy( png_ptr, image->GetOptionInt(wxIMAGE_OPTION_PNG_COMPRESSION_STRATEGY) ); if (image->HasOption(wxIMAGE_OPTION_PNG_COMPRESSION_BUFFER_SIZE)) png_set_compression_buffer_size( png_ptr, image->GetOptionInt(wxIMAGE_OPTION_PNG_COMPRESSION_BUFFER_SIZE) ); png_set_IHDR( png_ptr, info_ptr, image->GetWidth(), image->GetHeight(), iBitDepth, iPngColorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); int iElements; png_color_8 sig_bit; if ( iPngColorType & PNG_COLOR_MASK_COLOR ) { sig_bit.red = sig_bit.green = sig_bit.blue = (png_byte)iBitDepth; iElements = 3; } else // grey { sig_bit.gray = (png_byte)iBitDepth; iElements = 1; } if ( iPngColorType & PNG_COLOR_MASK_ALPHA ) { sig_bit.alpha = (png_byte)iBitDepth; iElements++; } if ( iBitDepth == 16 ) iElements *= 2; // save the image resolution if we have it int resX, resY; switch ( GetResolutionFromOptions(*image, &resX, &resY) ) { case wxIMAGE_RESOLUTION_INCHES: { const double INCHES_IN_METER = 10000.0 / 254; resX = int(resX * INCHES_IN_METER); resY = int(resY * INCHES_IN_METER); } break; case wxIMAGE_RESOLUTION_CM: resX *= 100; resY *= 100; break; case wxIMAGE_RESOLUTION_NONE: break; default: wxFAIL_MSG( _T("unsupported image resolution units") ); } if ( resX && resY ) png_set_pHYs( png_ptr, info_ptr, resX, resY, PNG_RESOLUTION_METER ); png_set_sBIT( png_ptr, info_ptr, &sig_bit ); png_write_info( png_ptr, info_ptr ); png_set_shift( png_ptr, &sig_bit ); png_set_packing( png_ptr ); unsigned char * data = (unsigned char *)malloc( image->GetWidth() * iElements ); if ( !data ) { png_destroy_write_struct( &png_ptr, (png_infopp)NULL ); return false; } unsigned char * pAlpha = (unsigned char *)(bHasAlpha ? image->GetAlpha() : NULL); int iHeight = image->GetHeight(); int iWidth = image->GetWidth(); unsigned char uchMaskRed = 0, uchMaskGreen = 0, uchMaskBlue = 0; if ( bHasMask ) { uchMaskRed = image->GetMaskRed(); uchMaskGreen = image->GetMaskGreen(); uchMaskBlue = image->GetMaskBlue(); } unsigned char *pColors = image->GetData(); for (int y = 0; y != iHeight; ++y) { unsigned char *pData = data; for (int x = 0; x != iWidth; x++) { unsigned char uchRed = *pColors++; unsigned char uchGreen = *pColors++; unsigned char uchBlue = *pColors++; switch ( iColorType ) { default: wxFAIL_MSG( _T("unknown wxPNG_TYPE_XXX") ); // fall through case wxPNG_TYPE_COLOUR: *pData++ = uchRed; if ( iBitDepth == 16 ) *pData++ = 0; *pData++ = uchGreen; if ( iBitDepth == 16 ) *pData++ = 0; *pData++ = uchBlue; if ( iBitDepth == 16 ) *pData++ = 0; break; case wxPNG_TYPE_GREY: { // where do these coefficients come from? maybe we // should have image options for them as well? unsigned uiColor = (unsigned) (76.544*(unsigned)uchRed + 150.272*(unsigned)uchGreen + 36.864*(unsigned)uchBlue); *pData++ = (unsigned char)((uiColor >> 8) & 0xFF); if ( iBitDepth == 16 ) *pData++ = (unsigned char)(uiColor & 0xFF); } break; case wxPNG_TYPE_GREY_RED: *pData++ = uchRed; if ( iBitDepth == 16 ) *pData++ = 0; break; } if ( bUseAlpha ) { unsigned char uchAlpha = 255; if ( bHasAlpha ) uchAlpha = *pAlpha++; if ( bHasMask ) { if ( (uchRed == uchMaskRed) && (uchGreen == uchMaskGreen) && (uchBlue == uchMaskBlue) ) uchAlpha = 0; } *pData++ = uchAlpha; if ( iBitDepth == 16 ) *pData++ = 0; } } png_bytep row_ptr = data; png_write_rows( png_ptr, &row_ptr, 1 ); } free(data); png_write_end( png_ptr, info_ptr ); png_destroy_write_struct( &png_ptr, (png_infopp)&info_ptr ); return true; } #ifdef __VISUALC__ #pragma warning(default:4611) #endif /* VC++ */ #endif // wxUSE_STREAMS #endif // wxUSE_LIBPNG
[ "RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775" ]
RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775
96aac45deeaf5e451727f51541e198be50bc2a77
ca0ac1fc171512e59598dd5c4aaae28fefd43ed7
/URI/Paradigms/Motoboy.cpp
01b7533a942a6cbe0919746a3a1e6144b1877bce
[]
no_license
MAAF72/Competitive-Programming
ed81a83df0032d83ade8800912044cff402334b4
3323d904fb2c607673f3c681b76305777f6ba29b
refs/heads/master
2020-05-20T18:51:03.772126
2019-09-07T01:52:29
2019-09-07T01:52:29
185,714,723
0
0
null
null
null
null
UTF-8
C++
false
false
1,219
cpp
#include <iostream> #include <algorithm> #define endl "\n" using namespace std; struct Pizza { int Time, Count; }; bool compare(Pizza P1, Pizza P2) { return (P1.Count < P2.Count); } int P, N; Pizza Order[20]; int Best; int BruteForce(int Deep, int SumTime, int SumCount) { if(Deep < N) { if((SumCount+Order[Deep].Count) <= P) { int Choosed = BruteForce(Deep+1, SumTime + Order[Deep].Time, SumCount + Order[Deep].Count); int NotChoosed = BruteForce(Deep+1, SumTime, SumCount); //cout << "Deep : " << Deep << " Choosed : " << Choosed << " NotChoosed : " << NotChoosed << " SumCount : " << SumCount << endl; return max(Choosed, NotChoosed); } else { //cout << "Deep : " << Deep << " SumTime : " << SumTime << " SumCount : " << SumCount << endl; return SumTime; } } else { //cout << "Deep : " << Deep << " SumTime : " << SumTime << " SumCount : " << SumCount << endl; return SumTime; } } int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); while(cin >> N && N != 0) { cin >> P; for(int i = 0; i < N; i++) { cin >> Order[i].Time >> Order[i].Count; } sort(Order, Order+N, compare); Best = BruteForce(0, 0, 0); cout << Best << " min." << endl; } return 0; }
[ "abdurrahmanalfatih72@gmail.com" ]
abdurrahmanalfatih72@gmail.com
65dcc75c043f41cdd087b472d4d9f54ebeeeb29f
755a473dce548a3d498fedfdc1d318db2a8e18de
/database/src/staff.h
658771bbf89819059b73a79954fb084091901a7c
[]
no_license
NCCA/cpp_workshops_complete
e56942c576348a6de61cb8e799d59bc8a4a21a6b
f838dbd1da9cba8aaba0b6308c102175b349b229
refs/heads/master
2020-04-04T02:04:02.584407
2018-11-01T08:56:27
2018-11-01T08:56:27
155,687,900
0
0
null
null
null
null
UTF-8
C++
false
false
966
h
#ifndef STAFF_H #define STAFF_H // The base class of Staff #include "entity.h" // Needed for date storage #include <boost/date_time/gregorian/gregorian.hpp> class Staff : public Entity { public: /// An enumerated type for the different types of roles available typedef enum { ROLE_UNDEFINED, ROLE_ADMIN, ROLE_PRODUCTION, ROLE_RESEARCH } RoleType; /// Constructor Staff(const std::string _firstname, const std::string _lastname, const boost::gregorian::date _dob, RoleType _role = ROLE_UNDEFINED); /// Destructor virtual ~Staff(); /// Pure virtual print function virtual void print(); protected: /// Some standard goodies to store with this class std::string m_firstname; std::string m_lastname; boost::gregorian::date m_dob; /// A local typedef to identify the type of role of this staff member RoleType m_role; }; #endif // STAFF_H
[ "rsouthern@bournemouth.ac.uk" ]
rsouthern@bournemouth.ac.uk
9ced7be2b028ef7ce62d76708c149f267c721b41
d6eb6c4f340d343ea368507b1c7e7671d45a5767
/src/lib/v8/src/store-buffer.cc
0f1fed0286e32246d4ad02ce4cf226807bfe7fd9
[ "BSD-3-Clause", "bzip2-1.0.6" ]
permissive
brn/mocha
8242888c18081cb844a2c2bd0c222162cd46e4cf
9ff68d6e2c753acf6ce57cdb3188f162549d2045
refs/heads/master
2021-06-06T06:43:06.230281
2021-05-07T16:04:12
2021-05-07T16:04:12
2,707,603
19
0
null
null
null
null
UTF-8
C++
false
false
25,174
cc
// Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "store-buffer.h" #include "store-buffer-inl.h" #include "v8-counters.h" namespace v8 { namespace internal { StoreBuffer::StoreBuffer(Heap* heap) : heap_(heap), start_(NULL), limit_(NULL), old_start_(NULL), old_limit_(NULL), old_top_(NULL), old_reserved_limit_(NULL), old_buffer_is_sorted_(false), old_buffer_is_filtered_(false), during_gc_(false), store_buffer_rebuilding_enabled_(false), callback_(NULL), may_move_store_buffer_entries_(true), virtual_memory_(NULL), hash_set_1_(NULL), hash_set_2_(NULL), hash_sets_are_empty_(true) { } void StoreBuffer::Setup() { virtual_memory_ = new VirtualMemory(kStoreBufferSize * 3); uintptr_t start_as_int = reinterpret_cast<uintptr_t>(virtual_memory_->address()); start_ = reinterpret_cast<Address*>(RoundUp(start_as_int, kStoreBufferSize * 2)); limit_ = start_ + (kStoreBufferSize / kPointerSize); old_virtual_memory_ = new VirtualMemory(kOldStoreBufferLength * kPointerSize); old_top_ = old_start_ = reinterpret_cast<Address*>(old_virtual_memory_->address()); // Don't know the alignment requirements of the OS, but it is certainly not // less than 0xfff. ASSERT((reinterpret_cast<uintptr_t>(old_start_) & 0xfff) == 0); int initial_length = static_cast<int>(OS::CommitPageSize() / kPointerSize); ASSERT(initial_length > 0); ASSERT(initial_length <= kOldStoreBufferLength); old_limit_ = old_start_ + initial_length; old_reserved_limit_ = old_start_ + kOldStoreBufferLength; CHECK(old_virtual_memory_->Commit( reinterpret_cast<void*>(old_start_), (old_limit_ - old_start_) * kPointerSize, false)); ASSERT(reinterpret_cast<Address>(start_) >= virtual_memory_->address()); ASSERT(reinterpret_cast<Address>(limit_) >= virtual_memory_->address()); Address* vm_limit = reinterpret_cast<Address*>( reinterpret_cast<char*>(virtual_memory_->address()) + virtual_memory_->size()); ASSERT(start_ <= vm_limit); ASSERT(limit_ <= vm_limit); USE(vm_limit); ASSERT((reinterpret_cast<uintptr_t>(limit_) & kStoreBufferOverflowBit) != 0); ASSERT((reinterpret_cast<uintptr_t>(limit_ - 1) & kStoreBufferOverflowBit) == 0); CHECK(virtual_memory_->Commit(reinterpret_cast<Address>(start_), kStoreBufferSize, false)); // Not executable. heap_->public_set_store_buffer_top(start_); hash_set_1_ = new uintptr_t[kHashSetLength]; hash_set_2_ = new uintptr_t[kHashSetLength]; hash_sets_are_empty_ = false; ClearFilteringHashSets(); } void StoreBuffer::TearDown() { delete virtual_memory_; delete old_virtual_memory_; delete[] hash_set_1_; delete[] hash_set_2_; old_start_ = old_top_ = old_limit_ = old_reserved_limit_ = NULL; start_ = limit_ = NULL; heap_->public_set_store_buffer_top(start_); } void StoreBuffer::StoreBufferOverflow(Isolate* isolate) { isolate->heap()->store_buffer()->Compact(); } #if V8_TARGET_ARCH_X64 static int CompareAddresses(const void* void_a, const void* void_b) { intptr_t a = reinterpret_cast<intptr_t>(*reinterpret_cast<const Address*>(void_a)); intptr_t b = reinterpret_cast<intptr_t>(*reinterpret_cast<const Address*>(void_b)); // Unfortunately if int is smaller than intptr_t there is no branch-free // way to return a number with the same sign as the difference between the // pointers. if (a == b) return 0; if (a < b) return -1; ASSERT(a > b); return 1; } #else static int CompareAddresses(const void* void_a, const void* void_b) { intptr_t a = reinterpret_cast<intptr_t>(*reinterpret_cast<const Address*>(void_a)); intptr_t b = reinterpret_cast<intptr_t>(*reinterpret_cast<const Address*>(void_b)); ASSERT(sizeof(1) == sizeof(a)); // Shift down to avoid wraparound. return (a >> kPointerSizeLog2) - (b >> kPointerSizeLog2); } #endif void StoreBuffer::Uniq() { // Remove adjacent duplicates and cells that do not point at new space. Address previous = NULL; Address* write = old_start_; ASSERT(may_move_store_buffer_entries_); for (Address* read = old_start_; read < old_top_; read++) { Address current = *read; if (current != previous) { if (heap_->InNewSpace(*reinterpret_cast<Object**>(current))) { *write++ = current; } } previous = current; } old_top_ = write; } void StoreBuffer::EnsureSpace(intptr_t space_needed) { while (old_limit_ - old_top_ < space_needed && old_limit_ < old_reserved_limit_) { size_t grow = old_limit_ - old_start_; // Double size. CHECK(old_virtual_memory_->Commit(reinterpret_cast<void*>(old_limit_), grow * kPointerSize, false)); old_limit_ += grow; } if (old_limit_ - old_top_ >= space_needed) return; if (old_buffer_is_filtered_) return; ASSERT(may_move_store_buffer_entries_); Compact(); old_buffer_is_filtered_ = true; bool page_has_scan_on_scavenge_flag = false; PointerChunkIterator it(heap_); MemoryChunk* chunk; while ((chunk = it.next()) != NULL) { if (chunk->scan_on_scavenge()) page_has_scan_on_scavenge_flag = true; } if (page_has_scan_on_scavenge_flag) { Filter(MemoryChunk::SCAN_ON_SCAVENGE); } // If filtering out the entries from scan_on_scavenge pages got us down to // less than half full, then we are satisfied with that. if (old_limit_ - old_top_ > old_top_ - old_start_) return; // Sample 1 entry in 97 and filter out the pages where we estimate that more // than 1 in 8 pointers are to new space. static const int kSampleFinenesses = 5; static const struct Samples { int prime_sample_step; int threshold; } samples[kSampleFinenesses] = { { 97, ((Page::kPageSize / kPointerSize) / 97) / 8 }, { 23, ((Page::kPageSize / kPointerSize) / 23) / 16 }, { 7, ((Page::kPageSize / kPointerSize) / 7) / 32 }, { 3, ((Page::kPageSize / kPointerSize) / 3) / 256 }, { 1, 0} }; for (int i = kSampleFinenesses - 1; i >= 0; i--) { ExemptPopularPages(samples[i].prime_sample_step, samples[i].threshold); // As a last resort we mark all pages as being exempt from the store buffer. ASSERT(i != 0 || old_top_ == old_start_); if (old_limit_ - old_top_ > old_top_ - old_start_) return; } UNREACHABLE(); } // Sample the store buffer to see if some pages are taking up a lot of space // in the store buffer. void StoreBuffer::ExemptPopularPages(int prime_sample_step, int threshold) { PointerChunkIterator it(heap_); MemoryChunk* chunk; while ((chunk = it.next()) != NULL) { chunk->set_store_buffer_counter(0); } bool created_new_scan_on_scavenge_pages = false; MemoryChunk* previous_chunk = NULL; for (Address* p = old_start_; p < old_top_; p += prime_sample_step) { Address addr = *p; MemoryChunk* containing_chunk = NULL; if (previous_chunk != NULL && previous_chunk->Contains(addr)) { containing_chunk = previous_chunk; } else { containing_chunk = MemoryChunk::FromAnyPointerAddress(addr); } int old_counter = containing_chunk->store_buffer_counter(); if (old_counter == threshold) { containing_chunk->set_scan_on_scavenge(true); created_new_scan_on_scavenge_pages = true; } containing_chunk->set_store_buffer_counter(old_counter + 1); previous_chunk = containing_chunk; } if (created_new_scan_on_scavenge_pages) { Filter(MemoryChunk::SCAN_ON_SCAVENGE); } old_buffer_is_filtered_ = true; } void StoreBuffer::Filter(int flag) { Address* new_top = old_start_; MemoryChunk* previous_chunk = NULL; for (Address* p = old_start_; p < old_top_; p++) { Address addr = *p; MemoryChunk* containing_chunk = NULL; if (previous_chunk != NULL && previous_chunk->Contains(addr)) { containing_chunk = previous_chunk; } else { containing_chunk = MemoryChunk::FromAnyPointerAddress(addr); previous_chunk = containing_chunk; } if (!containing_chunk->IsFlagSet(flag)) { *new_top++ = addr; } } old_top_ = new_top; // Filtering hash sets are inconsistent with the store buffer after this // operation. ClearFilteringHashSets(); } void StoreBuffer::SortUniq() { Compact(); if (old_buffer_is_sorted_) return; qsort(reinterpret_cast<void*>(old_start_), old_top_ - old_start_, sizeof(*old_top_), &CompareAddresses); Uniq(); old_buffer_is_sorted_ = true; // Filtering hash sets are inconsistent with the store buffer after this // operation. ClearFilteringHashSets(); } bool StoreBuffer::PrepareForIteration() { Compact(); PointerChunkIterator it(heap_); MemoryChunk* chunk; bool page_has_scan_on_scavenge_flag = false; while ((chunk = it.next()) != NULL) { if (chunk->scan_on_scavenge()) page_has_scan_on_scavenge_flag = true; } if (page_has_scan_on_scavenge_flag) { Filter(MemoryChunk::SCAN_ON_SCAVENGE); } // Filtering hash sets are inconsistent with the store buffer after // iteration. ClearFilteringHashSets(); return page_has_scan_on_scavenge_flag; } #ifdef DEBUG void StoreBuffer::Clean() { ClearFilteringHashSets(); Uniq(); // Also removes things that no longer point to new space. CheckForFullBuffer(); } static Address* in_store_buffer_1_element_cache = NULL; bool StoreBuffer::CellIsInStoreBuffer(Address cell_address) { if (!FLAG_enable_slow_asserts) return true; if (in_store_buffer_1_element_cache != NULL && *in_store_buffer_1_element_cache == cell_address) { return true; } Address* top = reinterpret_cast<Address*>(heap_->store_buffer_top()); for (Address* current = top - 1; current >= start_; current--) { if (*current == cell_address) { in_store_buffer_1_element_cache = current; return true; } } for (Address* current = old_top_ - 1; current >= old_start_; current--) { if (*current == cell_address) { in_store_buffer_1_element_cache = current; return true; } } return false; } #endif void StoreBuffer::ClearFilteringHashSets() { if (!hash_sets_are_empty_) { memset(reinterpret_cast<void*>(hash_set_1_), 0, sizeof(uintptr_t) * kHashSetLength); memset(reinterpret_cast<void*>(hash_set_2_), 0, sizeof(uintptr_t) * kHashSetLength); hash_sets_are_empty_ = true; } } void StoreBuffer::GCPrologue() { ClearFilteringHashSets(); during_gc_ = true; } #ifdef DEBUG static void DummyScavengePointer(HeapObject** p, HeapObject* o) { // Do nothing. } void StoreBuffer::VerifyPointers(PagedSpace* space, RegionCallback region_callback) { PageIterator it(space); while (it.has_next()) { Page* page = it.next(); FindPointersToNewSpaceOnPage( reinterpret_cast<PagedSpace*>(page->owner()), page, region_callback, &DummyScavengePointer); } } void StoreBuffer::VerifyPointers(LargeObjectSpace* space) { LargeObjectIterator it(space); for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) { if (object->IsFixedArray()) { Address slot_address = object->address(); Address end = object->address() + object->Size(); while (slot_address < end) { HeapObject** slot = reinterpret_cast<HeapObject**>(slot_address); // When we are not in GC the Heap::InNewSpace() predicate // checks that pointers which satisfy predicate point into // the active semispace. heap_->InNewSpace(*slot); slot_address += kPointerSize; } } } } #endif void StoreBuffer::Verify() { #ifdef DEBUG VerifyPointers(heap_->old_pointer_space(), &StoreBuffer::FindPointersToNewSpaceInRegion); VerifyPointers(heap_->map_space(), &StoreBuffer::FindPointersToNewSpaceInMapsRegion); VerifyPointers(heap_->lo_space()); #endif } void StoreBuffer::GCEpilogue() { during_gc_ = false; if (FLAG_verify_heap) { Verify(); } } void StoreBuffer::FindPointersToNewSpaceInRegion( Address start, Address end, ObjectSlotCallback slot_callback) { for (Address slot_address = start; slot_address < end; slot_address += kPointerSize) { Object** slot = reinterpret_cast<Object**>(slot_address); if (heap_->InNewSpace(*slot)) { HeapObject* object = reinterpret_cast<HeapObject*>(*slot); ASSERT(object->IsHeapObject()); slot_callback(reinterpret_cast<HeapObject**>(slot), object); if (heap_->InNewSpace(*slot)) { EnterDirectlyIntoStoreBuffer(slot_address); } } } } // Compute start address of the first map following given addr. static inline Address MapStartAlign(Address addr) { Address page = Page::FromAddress(addr)->ObjectAreaStart(); return page + (((addr - page) + (Map::kSize - 1)) / Map::kSize * Map::kSize); } // Compute end address of the first map preceding given addr. static inline Address MapEndAlign(Address addr) { Address page = Page::FromAllocationTop(addr)->ObjectAreaStart(); return page + ((addr - page) / Map::kSize * Map::kSize); } void StoreBuffer::FindPointersToNewSpaceInMaps( Address start, Address end, ObjectSlotCallback slot_callback) { ASSERT(MapStartAlign(start) == start); ASSERT(MapEndAlign(end) == end); Address map_address = start; while (map_address < end) { ASSERT(!heap_->InNewSpace(Memory::Object_at(map_address))); ASSERT(Memory::Object_at(map_address)->IsMap()); Address pointer_fields_start = map_address + Map::kPointerFieldsBeginOffset; Address pointer_fields_end = map_address + Map::kPointerFieldsEndOffset; FindPointersToNewSpaceInRegion(pointer_fields_start, pointer_fields_end, slot_callback); map_address += Map::kSize; } } void StoreBuffer::FindPointersToNewSpaceInMapsRegion( Address start, Address end, ObjectSlotCallback slot_callback) { Address map_aligned_start = MapStartAlign(start); Address map_aligned_end = MapEndAlign(end); ASSERT(map_aligned_start == start); ASSERT(map_aligned_end == end); FindPointersToNewSpaceInMaps(map_aligned_start, map_aligned_end, slot_callback); } // This function iterates over all the pointers in a paged space in the heap, // looking for pointers into new space. Within the pages there may be dead // objects that have not been overwritten by free spaces or fillers because of // lazy sweeping. These dead objects may not contain pointers to new space. // The garbage areas that have been swept properly (these will normally be the // large ones) will be marked with free space and filler map words. In // addition any area that has never been used at all for object allocation must // be marked with a free space or filler. Because the free space and filler // maps do not move we can always recognize these even after a compaction. // Normal objects like FixedArrays and JSObjects should not contain references // to these maps. The special garbage section (see comment in spaces.h) is // skipped since it can contain absolutely anything. Any objects that are // allocated during iteration may or may not be visited by the iteration, but // they will not be partially visited. void StoreBuffer::FindPointersToNewSpaceOnPage( PagedSpace* space, Page* page, RegionCallback region_callback, ObjectSlotCallback slot_callback) { Address visitable_start = page->ObjectAreaStart(); Address end_of_page = page->ObjectAreaEnd(); Address visitable_end = visitable_start; Object* free_space_map = heap_->free_space_map(); Object* two_pointer_filler_map = heap_->two_pointer_filler_map(); while (visitable_end < end_of_page) { Object* o = *reinterpret_cast<Object**>(visitable_end); // Skip fillers but not things that look like fillers in the special // garbage section which can contain anything. if (o == free_space_map || o == two_pointer_filler_map || (visitable_end == space->top() && visitable_end != space->limit())) { if (visitable_start != visitable_end) { // After calling this the special garbage section may have moved. (this->*region_callback)(visitable_start, visitable_end, slot_callback); if (visitable_end >= space->top() && visitable_end < space->limit()) { visitable_end = space->limit(); visitable_start = visitable_end; continue; } } if (visitable_end == space->top() && visitable_end != space->limit()) { visitable_start = visitable_end = space->limit(); } else { // At this point we are either at the start of a filler or we are at // the point where the space->top() used to be before the // visit_pointer_region call above. Either way we can skip the // object at the current spot: We don't promise to visit objects // allocated during heap traversal, and if space->top() moved then it // must be because an object was allocated at this point. visitable_start = visitable_end + HeapObject::FromAddress(visitable_end)->Size(); visitable_end = visitable_start; } } else { ASSERT(o != free_space_map); ASSERT(o != two_pointer_filler_map); ASSERT(visitable_end < space->top() || visitable_end >= space->limit()); visitable_end += kPointerSize; } } ASSERT(visitable_end == end_of_page); if (visitable_start != visitable_end) { (this->*region_callback)(visitable_start, visitable_end, slot_callback); } } void StoreBuffer::IteratePointersInStoreBuffer( ObjectSlotCallback slot_callback) { Address* limit = old_top_; old_top_ = old_start_; { DontMoveStoreBufferEntriesScope scope(this); for (Address* current = old_start_; current < limit; current++) { #ifdef DEBUG Address* saved_top = old_top_; #endif Object** slot = reinterpret_cast<Object**>(*current); Object* object = *slot; if (heap_->InFromSpace(object)) { HeapObject* heap_object = reinterpret_cast<HeapObject*>(object); slot_callback(reinterpret_cast<HeapObject**>(slot), heap_object); if (heap_->InNewSpace(*slot)) { EnterDirectlyIntoStoreBuffer(reinterpret_cast<Address>(slot)); } } ASSERT(old_top_ == saved_top + 1 || old_top_ == saved_top); } } } void StoreBuffer::IteratePointersToNewSpace(ObjectSlotCallback slot_callback) { // We do not sort or remove duplicated entries from the store buffer because // we expect that callback will rebuild the store buffer thus removing // all duplicates and pointers to old space. bool some_pages_to_scan = PrepareForIteration(); // TODO(gc): we want to skip slots on evacuation candidates // but we can't simply figure that out from slot address // because slot can belong to a large object. IteratePointersInStoreBuffer(slot_callback); // We are done scanning all the pointers that were in the store buffer, but // there may be some pages marked scan_on_scavenge that have pointers to new // space that are not in the store buffer. We must scan them now. As we // scan, the surviving pointers to new space will be added to the store // buffer. If there are still a lot of pointers to new space then we will // keep the scan_on_scavenge flag on the page and discard the pointers that // were added to the store buffer. If there are not many pointers to new // space left on the page we will keep the pointers in the store buffer and // remove the flag from the page. if (some_pages_to_scan) { if (callback_ != NULL) { (*callback_)(heap_, NULL, kStoreBufferStartScanningPagesEvent); } PointerChunkIterator it(heap_); MemoryChunk* chunk; while ((chunk = it.next()) != NULL) { if (chunk->scan_on_scavenge()) { chunk->set_scan_on_scavenge(false); if (callback_ != NULL) { (*callback_)(heap_, chunk, kStoreBufferScanningPageEvent); } if (chunk->owner() == heap_->lo_space()) { LargePage* large_page = reinterpret_cast<LargePage*>(chunk); HeapObject* array = large_page->GetObject(); ASSERT(array->IsFixedArray()); Address start = array->address(); Address end = start + array->Size(); FindPointersToNewSpaceInRegion(start, end, slot_callback); } else { Page* page = reinterpret_cast<Page*>(chunk); PagedSpace* owner = reinterpret_cast<PagedSpace*>(page->owner()); FindPointersToNewSpaceOnPage( owner, page, (owner == heap_->map_space() ? &StoreBuffer::FindPointersToNewSpaceInMapsRegion : &StoreBuffer::FindPointersToNewSpaceInRegion), slot_callback); } } } if (callback_ != NULL) { (*callback_)(heap_, NULL, kStoreBufferScanningPageEvent); } } } void StoreBuffer::Compact() { Address* top = reinterpret_cast<Address*>(heap_->store_buffer_top()); if (top == start_) return; // There's no check of the limit in the loop below so we check here for // the worst case (compaction doesn't eliminate any pointers). ASSERT(top <= limit_); heap_->public_set_store_buffer_top(start_); EnsureSpace(top - start_); ASSERT(may_move_store_buffer_entries_); // Goes through the addresses in the store buffer attempting to remove // duplicates. In the interest of speed this is a lossy operation. Some // duplicates will remain. We have two hash sets with different hash // functions to reduce the number of unnecessary clashes. hash_sets_are_empty_ = false; // Hash sets are in use. for (Address* current = start_; current < top; current++) { ASSERT(!heap_->cell_space()->Contains(*current)); ASSERT(!heap_->code_space()->Contains(*current)); ASSERT(!heap_->old_data_space()->Contains(*current)); uintptr_t int_addr = reinterpret_cast<uintptr_t>(*current); // Shift out the last bits including any tags. int_addr >>= kPointerSizeLog2; int hash1 = ((int_addr ^ (int_addr >> kHashSetLengthLog2)) & (kHashSetLength - 1)); if (hash_set_1_[hash1] == int_addr) continue; uintptr_t hash2 = (int_addr - (int_addr >> kHashSetLengthLog2)); hash2 ^= hash2 >> (kHashSetLengthLog2 * 2); hash2 &= (kHashSetLength - 1); if (hash_set_2_[hash2] == int_addr) continue; if (hash_set_1_[hash1] == 0) { hash_set_1_[hash1] = int_addr; } else if (hash_set_2_[hash2] == 0) { hash_set_2_[hash2] = int_addr; } else { // Rather than slowing down we just throw away some entries. This will // cause some duplicates to remain undetected. hash_set_1_[hash1] = int_addr; hash_set_2_[hash2] = 0; } old_buffer_is_sorted_ = false; old_buffer_is_filtered_ = false; *old_top_++ = reinterpret_cast<Address>(int_addr << kPointerSizeLog2); ASSERT(old_top_ <= old_limit_); } heap_->isolate()->counters()->store_buffer_compactions()->Increment(); CheckForFullBuffer(); } void StoreBuffer::CheckForFullBuffer() { EnsureSpace(kStoreBufferSize * 2); } } } // namespace v8::internal
[ "dobaw20@gmail.com" ]
dobaw20@gmail.com