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
897726b5d65caa45ade9a9fd92b571823a882408
1fec016178991e2e9fcc8722843adb960a211c17
/services/service_manager/public/cpp/binder_registry.h
44eab787a9c51b2e858f1caa04b71aa7a0f76e7a
[ "BSD-3-Clause" ]
permissive
youngbeezee/chromium
7504dd95c1529c6b25a383cfad095b7681ab7686
7938b191e4a1bae161445ab33dd664a1afa799b7
refs/heads/master
2022-12-11T01:53:02.566554
2017-05-01T16:14:22
2017-05-01T16:14:22
89,991,004
1
0
null
2017-05-02T04:17:34
2017-05-02T04:17:34
null
UTF-8
C++
false
false
3,345
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 SERVICES_SERVICE_MANAGER_PUBLIC_CPP_BINDER_REGISTRY_H_ #define SERVICES_SERVICE_MANAGER_PUBLIC_CPP_BINDER_REGISTRY_H_ #include <map> #include <memory> #include <string> #include "base/callback.h" #include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "mojo/public/cpp/system/message_pipe.h" #include "services/service_manager/public/cpp/interface_factory.h" #include "services/service_manager/public/cpp/lib/callback_binder.h" #include "services/service_manager/public/cpp/lib/interface_factory_binder.h" namespace service_manager { class Identity; class InterfaceBinder; class BinderRegistry { public: using Binder = base::Callback<void(const std::string&, mojo::ScopedMessagePipeHandle)>; BinderRegistry(); ~BinderRegistry(); // Provide a factory to be called when a request to bind |Interface| is // received by this registry. template <typename Interface> void AddInterface(InterfaceFactory<Interface>* factory) { SetInterfaceBinder( Interface::Name_, base::MakeUnique<internal::InterfaceFactoryBinder<Interface>>(factory)); } // Provide a callback to be run when a request to bind |Interface| is received // by this registry. template <typename Interface> void AddInterface( const base::Callback<void(mojo::InterfaceRequest<Interface>)>& callback, const scoped_refptr<base::SingleThreadTaskRunner>& task_runner = nullptr) { SetInterfaceBinder( Interface::Name_, base::MakeUnique<internal::CallbackBinder<Interface>>(callback, task_runner)); } void AddInterface( const std::string& interface_name, const base::Callback<void(mojo::ScopedMessagePipeHandle)>& callback, const scoped_refptr<base::SingleThreadTaskRunner>& task_runner = nullptr); // Removes the specified interface from the registry. This has no effect on // bindings already completed. template <typename Interface> void RemoveInterface() { RemoveInterface(Interface::Name_); } void RemoveInterface(const std::string& interface_name); // Returns true if an InterfaceBinder is registered for |interface_name|. bool CanBindInterface(const std::string& interface_name) const; // Completes binding the request for |interface_name| on |interface_pipe|, by // invoking the corresponding InterfaceBinder. void BindInterface(const Identity& remote_identity, const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe); base::WeakPtr<BinderRegistry> GetWeakPtr(); private: using InterfaceNameToBinderMap = std::map<std::string, std::unique_ptr<InterfaceBinder>>; // Adds |binder| to the internal map. void SetInterfaceBinder(const std::string& interface_name, std::unique_ptr<InterfaceBinder> binder); InterfaceNameToBinderMap binders_; base::WeakPtrFactory<BinderRegistry> weak_factory_; DISALLOW_COPY_AND_ASSIGN(BinderRegistry); }; } // namespace service_manager #endif // SERVICES_SERVICE_MANAGER_PUBLIC_CPP_BINDER_REGISTRY_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
974d4591b6fb4c113391ec445b36ec5919d9922f
5a2349399fa9d57c6e8cc6e0f7226d683391a362
/src/qt/qtwebkit/Source/WebKit2/Shared/Network/CustomProtocols/CustomProtocolManager.h
b0fe3c3b97f938e39b272da5b72ffd18f43d8f23
[ "BSD-3-Clause" ]
permissive
aharthcock/phantomjs
e70f3c379dcada720ec8abde3f7c09a24808154c
7d7f2c862347fbc7215c849e790290b2e07bab7c
refs/heads/master
2023-03-18T04:58:32.428562
2023-03-14T05:52:52
2023-03-14T05:52:52
24,828,890
0
0
BSD-3-Clause
2023-03-14T05:52:53
2014-10-05T23:38:56
C++
UTF-8
C++
false
false
4,184
h
/* * Copyright (C) 2012, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 CustomProtocolManager_h #define CustomProtocolManager_h #if ENABLE(CUSTOM_PROTOCOLS) #include "Connection.h" #include "NetworkProcessSupplement.h" #include "WebProcessSupplement.h" #include "WorkQueue.h" #include <wtf/HashSet.h> #include <wtf/Threading.h> #include <wtf/text/WTFString.h> #if PLATFORM(MAC) #include <wtf/HashMap.h> #include <wtf/RetainPtr.h> OBJC_CLASS WKCustomProtocol; #endif namespace CoreIPC { class DataReference; } // namespace CoreIPC namespace WebCore { class ResourceError; class ResourceResponse; } // namespace WebCore namespace WebKit { class ChildProcess; struct NetworkProcessCreationParameters; class CustomProtocolManager : public WebProcessSupplement, public NetworkProcessSupplement, public CoreIPC::Connection::WorkQueueMessageReceiver { WTF_MAKE_NONCOPYABLE(CustomProtocolManager); public: explicit CustomProtocolManager(ChildProcess*); static const char* supplementName(); ChildProcess* childProcess() const { return m_childProcess; } void registerScheme(const String&); void unregisterScheme(const String&); bool supportsScheme(const String&); #if PLATFORM(MAC) void addCustomProtocol(WKCustomProtocol *); void removeCustomProtocol(WKCustomProtocol *); #endif private: // ChildProcessSupplement void initializeConnection(CoreIPC::Connection*) OVERRIDE; // WebProcessSupplement void initialize(const WebProcessCreationParameters&) OVERRIDE; #if ENABLE(NETWORK_PROCESS) // NetworkProcessSupplement void initialize(const NetworkProcessCreationParameters&) OVERRIDE; #endif // CoreIPC::MessageReceiver virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; void didFailWithError(uint64_t customProtocolID, const WebCore::ResourceError&); void didLoadData(uint64_t customProtocolID, const CoreIPC::DataReference&); void didReceiveResponse(uint64_t customProtocolID, const WebCore::ResourceResponse&, uint32_t cacheStoragePolicy); void didFinishLoading(uint64_t customProtocolID); HashSet<String> m_registeredSchemes; Mutex m_registeredSchemesMutex; ChildProcess* m_childProcess; RefPtr<WorkQueue> m_messageQueue; #if PLATFORM(MAC) typedef HashMap<uint64_t, RetainPtr<WKCustomProtocol> > CustomProtocolMap; CustomProtocolMap m_customProtocolMap; Mutex m_customProtocolMapMutex; // WKCustomProtocol objects can be removed from the m_customProtocolMap from multiple threads. // We return a RetainPtr here because it is unsafe to return a raw pointer since the object might immediately be destroyed from a different thread. RetainPtr<WKCustomProtocol> protocolForID(uint64_t customProtocolID); #endif }; } // namespace WebKit #endif // ENABLE(CUSTOM_PROTOCOLS) #endif // CustomProtocolManager_h
[ "ariya.hidayat@gmail.com" ]
ariya.hidayat@gmail.com
7b352ebc3862fe7457c4d6c3c99ea9907dedf000
36763d8887ee063a80196b0258021625389873cc
/pmacApp/src/Hashtable.h
fc6bdff4c602b80ba65df9c3fd8a87dcb97e5cd0
[]
no_license
arvinderpalaha/pmac
93eb6d622a10cbb13a8676e8afa4c12bfc22a1e3
df4b1b7ace731f33d07064c0e12fe781d68f907c
refs/heads/master
2020-06-15T10:08:08.686560
2016-12-01T15:10:06
2016-12-01T15:10:06
75,302,970
0
0
null
2016-12-01T15:00:05
2016-12-01T15:00:05
null
UTF-8
C++
false
false
2,398
h
/* * Hashtable.h * * Created on: 9 Feb 2016 * Author: gnx91527 */ #ifndef PMACAPP_SRC_HASHTABLE_H_ #define PMACAPP_SRC_HASHTABLE_H_ #include <stdlib.h> // Hashes are long integers, 64-bits on the right architecture. typedef long unsigned int hash_t; struct table_entry { hash_t hash; void *key; // Null if absent void *value; }; class Hashtable { public: Hashtable(); virtual ~Hashtable(); // Look up key in hash table, return NULL if not found. void *lookup(const void *key); // Inserts (key,value) pair in hash table. If value is already present its old // value is returned before being overwritten with the new value, otherwise NULL // is returned. void *insert(const void *key, void *value); // Deletes key from hash table, returning the old value if present, otherwise NULL. void *remove(const void *key); // Returns the number of entries in the table. size_t count(); // Resizes hash table to have at least the given number of slots. Can also be // used after deleting entries to compress table. void resize(size_t min_size); table_entry *internal_begin(); bool internal_hasNext(); table_entry *internal_next(); void keys(void **keys); // Sanity checking of hash table consistency, raises assert fail if any error is // found. Should only fail in presence of hash table bug, memory overwrite, or // key lifetime mismanagement. void validate(struct hash_table *table); protected: virtual void *copy_key(const void *key) = 0; virtual bool compare_key(const void *key1, const void *key2) = 0; virtual void release_key(void *key) = 0; bool empty_entry(struct table_entry *entry); struct table_entry *lookup(const void *key, hash_t hash, bool *found); hash_t hash_string(const void *key); private: static size_t INITIAL_SIZE; // initial size of data store constant static hash_t EMPTY_HASH; // constant to represent an empty hash static hash_t DELETED_HASH; // constant to represent a deleted hash size_t entries; // Number of entries in table size_t deleted; // Number of deleted entries in table size_t size_mask; // True size is power of 2, mask selects modulo size size_t walk_index; // Used for keeping track of next and has next struct table_entry *table; // Actual data storage pointer }; #endif /* PMACAPP_SRC_HASHTABLE_H_ */
[ "alan.greer@diamond.ac.uk" ]
alan.greer@diamond.ac.uk
908d71def03a9b5068cde6385a1ceeeaaa9b1252
e19f96a07d297057710fb5383dff12a906d2b770
/src/config.cpp
396bd2dfc3cdec334d5c5abec83587c1c3f47859
[ "MIT" ]
permissive
slcoolj/tuxdump
da961722534ad4cd5e030013a4f929408c274162
bf7f7c59a5e39f2233b1f6476947e6890074cb4a
refs/heads/master
2020-03-29T10:17:42.483715
2018-09-21T17:49:21
2018-09-21T17:49:21
149,797,760
0
0
MIT
2018-09-21T17:43:20
2018-09-21T17:43:20
null
UTF-8
C++
false
false
2,851
cpp
#include "config.h" bool TConfig::ReadFile(const char* file) { try { m_cfg.readFile(file); return true; } catch (const libconfig::FileIOException& fioex) { fprintf(stderr, "%s: I/O error while reading file '%s'\n", fioex.what(), file); } catch (const libconfig::ParseException& pex) { fprintf(stderr, "%s: Parse error at %s:%i - %s\n", pex.what(), pex.getFile(), pex.getLine(), pex.getError()); } return false; } bool TConfig::ReadFile(const std::string& file) { return ReadFile(file.c_str()); } std::string TConfig::GetName() { const libconfig::Setting& root = m_cfg.getRoot(); std::string result = "Unknown"; if (root.exists("name")) { root.lookupValue("name", result); } return result; } std::string TConfig::GetVersion() { const libconfig::Setting& root = m_cfg.getRoot(); std::string result = "Unknown"; if (root.exists("version")) { root.lookupValue("version", result); } return result; } std::string TConfig::GetProcessName() { const libconfig::Setting& root = m_cfg.getRoot(); std::string result; if (root.exists("process")) { root.lookupValue("process", result); } return result; } signatures_t TConfig::GetSignatures() { const libconfig::Setting& root = m_cfg.getRoot(); signatures_t result; try { const libconfig::Setting& sigRoot = root["signatures"]; for (auto&& def : sigRoot) { if (!def.exists("module")) { fprintf(stderr, "WARN: '%s' missing module entry. Skipping.", def.getName()); continue; } if (!def.exists("pattern")) { fprintf(stderr, "WARN: '%s' missing pattern entry. Skipping.", def.getName()); continue; } SignatureDefinition_t sig; sig.name = def.getName(); def.lookupValue("module", sig.module); def.lookupValue("pattern", sig.pattern); if (def.exists("offset")) { for (auto&& offset : def["offset"]) { sig.offset.push_back(offset); } } if (def.exists("extra")) { def.lookupValue("extra", sig.extra); } if (def.exists("relative")) { def.lookupValue("relative", sig.relative); } if (def.exists("comment")) { def.lookupValue("comment", sig.comment); } else { sig.comment = "N/A"; } result.push_back(std::move(sig)); } } catch (const libconfig::SettingNotFoundException& e) { fprintf(stderr, "%s: Missing 'signatures' group in config file.\n", e.what()); } return result; }
[ "jkinnaird1991@gmail.com" ]
jkinnaird1991@gmail.com
d40c906c66173060d66324591599e6b83fa85012
226b1a89354f05670f4329bd6a8741720e15e804
/ScrollableLists/1_bulk/src/ListItem.cpp
ee255a2bcf210382a1e59ed16048548629abc7cd
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
Hmaied/Cascades-Samples
cc116e82093636d6c8ca4d9d72a7bfdb6b16c01d
f34ffe088b07f848847a6279fe1a93f9476aa8a2
refs/heads/master
2021-01-22T20:34:49.140535
2014-04-29T17:30:57
2014-04-29T17:30:57
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
5,304
cpp
/* Copyright (c) 2012 Research In Motion Limited. * * 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 "ListItem.hpp" #include <bb/cascades/Container> #include <bb/cascades/DockLayout> #include <bb/cascades/DockLayoutProperties> #include <bb/cascades/Textstyle> #include <bb/cascades/Systemdefaults> #include <bb/cascades/ImageView> #include <bb/cascades/Label> #include <bb/cascades/StackLayout> #include <bb/cascades/StackLayoutProperties> using namespace bb::cascades; /** * This Class implements its counterpart described by "common/ListItem.qml" * e.g.: demonstrate how to implement a custom List Item by C++. */ /** * Constructor * * Construct the UI of the list item */ ListItem::ListItem(Container* parent) : CustomControl(parent) { // Dock layout with margins inside. Container* itemContainer = new Container(); DockLayout* itemLayout = new DockLayout(); itemContainer->setLayout(itemLayout); itemContainer->setPreferredWidth(250.0f); // A background Container that will hold a background image and an item content Container. Container* backgroundContainer = new Container(); DockLayout* backgroundLayout = new DockLayout(); backgroundContainer->setLayout(backgroundLayout); backgroundContainer->setLayoutProperties( DockLayoutProperties::create().horizontal(HorizontalAlignment::Center).vertical(VerticalAlignment::Center)); // A Colored Container will be used to show if an item is highlighted. m_highlighContainer = new Container(); m_highlighContainer->setBackground(Color::fromARGB(0xff75b5d3)); m_highlighContainer->setLayoutProperties(DockLayoutProperties::create().horizontal(HorizontalAlignment::Center).vertical(VerticalAlignment::Center)); m_highlighContainer->setOpacity(0.0); m_highlighContainer->setPreferredWidth(242.0f); m_highlighContainer->setPreferredHeight(168.0f); // Content Container, Image + text with padding to get alignment on background image. Container* contentContainer = new Container(); DockLayout* contentLayout = new DockLayout(); contentContainer->setLayout(contentLayout); contentContainer->setLayoutProperties(DockLayoutProperties::create().horizontal(HorizontalAlignment::Center).vertical(VerticalAlignment::Center)); // The list item image, docked to the top, the actual image is set in updateItem. m_itemImage = ImageView::create("asset:///images/white_photo.png").preferredSize(238.0f, 160.0f).layoutProperties( DockLayoutProperties::create().vertical(VerticalAlignment::Center).horizontal(HorizontalAlignment::Center)); // A list item label, docked to the center, the text is set in updateItem. m_itemLabel = Label::create().text(" ").layoutProperties( DockLayoutProperties::create().vertical(VerticalAlignment::Center).horizontal(HorizontalAlignment::Center)); m_itemLabel->textStyle()->setBase(SystemDefaults::TextStyles::titleText()); m_itemLabel->textStyle()->setColor(Color::Black); // Add the Label to the content. contentContainer->add(m_itemLabel); // Add the background image and the content to the background item container. backgroundContainer->add(m_itemImage); backgroundContainer->add(m_highlighContainer); backgroundContainer->add(contentContainer); // Finally add the background Container to the item Container. itemContainer->add(backgroundContainer); setRoot(itemContainer); } /** * void ListItem::updateItem(const QString text, const QString imagePath) * * Update the background image and the text for this item */ void ListItem::updateItem(const QString text, const QString imagePath) { // Update image and text for the current item. m_itemImage->setImage(Image(imagePath)); m_itemLabel->setText(text); } /** * void ListItem::select(bool select) * * Change the look and feel of this item depending the selection state */ void ListItem::select(bool select) { // When an item is selected show the colored highlight Container-´, if (select) { m_highlighContainer->setOpacity(0.9f); } else { m_highlighContainer->setOpacity(0.0f); } } /** * void ListItem::reset(bool selected, bool activated) * * Reset the item to the given state */ void ListItem::reset(bool selected, bool activated) { Q_UNUSED(activated); // Since items are recycled the reset function is where we have // to make sure that item state, defined by the arguments, is correct. select(selected); } /** * void ListItem::activate(bool activate) * * set the item to the given activated state */ void ListItem::activate(bool activate) { // There is no special activate state, select and activated looks the same. select(activate); }
[ "pelegri@calterra.com" ]
pelegri@calterra.com
e6b032e280023d161a48cf18c6eaf2e2d6683619
6c24e3321627fb00725e94da61b989b8a75ed9f8
/devel/include/rosserial_mbed/TestResponse.h
f811b2e4480ba0fb81a973333673114752810556
[]
no_license
isabellahuang/robotfinger
0838858d16dff239810438781c5c568cf929a1ea
02eea2510acbeb9ac01736df6b21e9939b133fce
refs/heads/master
2020-03-21T08:33:06.786541
2019-04-11T18:58:57
2019-04-11T18:58:57
138,350,265
1
0
null
null
null
null
UTF-8
C++
false
false
5,139
h
// Generated by gencpp from file rosserial_mbed/TestResponse.msg // DO NOT EDIT! #ifndef ROSSERIAL_MBED_MESSAGE_TESTRESPONSE_H #define ROSSERIAL_MBED_MESSAGE_TESTRESPONSE_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 rosserial_mbed { template <class ContainerAllocator> struct TestResponse_ { typedef TestResponse_<ContainerAllocator> Type; TestResponse_() : output() { } TestResponse_(const ContainerAllocator& _alloc) : output(_alloc) { (void)_alloc; } typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _output_type; _output_type output; typedef boost::shared_ptr< ::rosserial_mbed::TestResponse_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::rosserial_mbed::TestResponse_<ContainerAllocator> const> ConstPtr; }; // struct TestResponse_ typedef ::rosserial_mbed::TestResponse_<std::allocator<void> > TestResponse; typedef boost::shared_ptr< ::rosserial_mbed::TestResponse > TestResponsePtr; typedef boost::shared_ptr< ::rosserial_mbed::TestResponse const> TestResponseConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::rosserial_mbed::TestResponse_<ContainerAllocator> & v) { ros::message_operations::Printer< ::rosserial_mbed::TestResponse_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace rosserial_mbed namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'rosserial_mbed': ['/home/isabella/catkin_ws/src/rosserial/rosserial_mbed/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::rosserial_mbed::TestResponse_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::rosserial_mbed::TestResponse_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::rosserial_mbed::TestResponse_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::rosserial_mbed::TestResponse_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::rosserial_mbed::TestResponse_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::rosserial_mbed::TestResponse_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::rosserial_mbed::TestResponse_<ContainerAllocator> > { static const char* value() { return "0825d95fdfa2c8f4bbb4e9c74bccd3fd"; } static const char* value(const ::rosserial_mbed::TestResponse_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x0825d95fdfa2c8f4ULL; static const uint64_t static_value2 = 0xbbb4e9c74bccd3fdULL; }; template<class ContainerAllocator> struct DataType< ::rosserial_mbed::TestResponse_<ContainerAllocator> > { static const char* value() { return "rosserial_mbed/TestResponse"; } static const char* value(const ::rosserial_mbed::TestResponse_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::rosserial_mbed::TestResponse_<ContainerAllocator> > { static const char* value() { return "string output\n\ \n\ "; } static const char* value(const ::rosserial_mbed::TestResponse_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::rosserial_mbed::TestResponse_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.output); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct TestResponse_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::rosserial_mbed::TestResponse_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::rosserial_mbed::TestResponse_<ContainerAllocator>& v) { s << indent << "output: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.output); } }; } // namespace message_operations } // namespace ros #endif // ROSSERIAL_MBED_MESSAGE_TESTRESPONSE_H
[ "isabellahuang7@gmail.com" ]
isabellahuang7@gmail.com
e7c310b31b5d49ce3a705cb10e6a1778c762c677
54781ed7607a3a7e483795f61a072b2345d1be5d
/FourConnect/include/TGUI/Widgets/Grid.hpp
c6c1bab8538dbadc825725c5a34511e7954d2aac
[]
no_license
WaldiDev/FourConnect
e5e8d5c3145f50b5ca994365241a036a285ab7cd
f550820672ff89bfc686bc8f9d4497f9fd623cbb
refs/heads/master
2021-01-10T14:32:59.388709
2016-01-28T16:59:35
2016-01-28T16:59:35
50,231,765
0
0
null
null
null
null
UTF-8
C++
false
false
13,754
hpp
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // TGUI - Texus's Graphical User Interface // Copyright (C) 2012-2015 Bruno Van de Velde (vdv_b@tgui.eu) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef TGUI_GRID_HPP #define TGUI_GRID_HPP #include <TGUI/Container.hpp> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace tgui { ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class TGUI_API Grid : public Container { public: typedef std::shared_ptr<Grid> Ptr; ///< Shared widget pointer typedef std::shared_ptr<const Grid> ConstPtr; ///< Shared constant widget pointer ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief The alignment of the widget in its cell. /// /// Where in the cell is the widget located? /// The widget is centered by default. /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// enum class Alignment { UpperLeft, ///< Draw the widget in the upper left corner of the cell Up, ///< Draw the widget at the upper side of the cell (horizontally centered) UpperRight, ///< Draw the widget in the upper right corner of the cell Right, ///< Draw the widget at the right side of the cell (vertically centered) BottomRight, ///< Draw the widget in the bottom right corner of the cell Bottom, ///< Draw the widget at the bottom of the cell (horizontally centered) BottomLeft, ///< Draw the widget in the bottom left corner of the cell Left, ///< Draw the widget at the left side of the cell (vertically centered) Center ///< Center the widget in the cell }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Default constructor ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Grid(); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Copy constructor /// /// @param copy Instance to copy /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Grid(const Grid& copy); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Overload of assignment operator /// /// @param right Instance to assign /// /// @return Reference to itself /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Grid& operator= (const Grid& right); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Makes a copy of another grid /// /// @param grid The other grid /// /// @return The new grid /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static Grid::Ptr copy(Grid::ConstPtr grid); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Changes the size of the grid. /// /// @param size New size of the grid /// /// Widgets in the grid will be repositionned to fill in the best way the available space of the grid. /// If the size is too small to have all Widgets correctly placed, the size will be ignored and the grid auto-sized until /// some Widgets are removed of the grid and the size was become valid again. /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// virtual void setSize(const Layout2d& size) override; using Transformable::setSize; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Returns the size of the grid. /// /// @return Size of the grid /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// virtual sf::Vector2f getSize() const override { return m_realSize; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Removes a single widget that was added to the container. /// /// @param widget Pointer to the widget to remove /// /// @see remove(sf::String) /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// virtual bool remove(const Widget::Ptr& widget) override; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Removes all widgets that were added to the container. /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// virtual void removeAllWidgets() override; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Add a widget to the grid. /// /// @param widget Pointer to a fully created widget that will be added to the grid /// @param row The row in which the widget should be placed /// @param column The column in which the widget should be placed /// @param borders Distance from the grid square to the widget (left, top, right, bottom) /// @param alignment Where the widget is located in the square /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void addWidget(const Widget::Ptr& widget, unsigned int row, unsigned int column, const Borders& borders = Borders(0, 0, 0, 0), Alignment alignment = Alignment::Center); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Returns the widget in a specific square of the grid. /// /// @param row The row that the widget is in /// @param column The column that the widget is in /// /// @return The widget inside the given square, or nullptr when the square doesn't contain a widget /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Widget::Ptr getWidget(unsigned int row, unsigned int column); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Updates the position and size of the widget. /// /// You should no longer have to call this function manually as widgets are supposed to call this function themselves /// when their position or size is changed. /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void updateWidgets(); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Changes borders of a given widget. /// /// @param widget The widget to which borders should be added /// @param borders The new borders around the widget /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void changeWidgetBorders(const Widget::Ptr& widget, const Borders& borders = Borders(0, 0, 0, 0)); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Changes the alignment of a given widget in its cell. /// /// @param widget The widget for which the alignment should be changed /// @param alignment The new alignment /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void changeWidgetAlignment(const Widget::Ptr& widget, Alignment alignment = Alignment::Center); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @internal ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// virtual bool mouseOnWidget(float x, float y) const override; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// protected: ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Returns the minimum size required by the grid to display correctly all widgets. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// sf::Vector2f getMinSize(); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Reposition all the widgets. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void updatePositionsOfAllWidgets(); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Makes a copy of the widget ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// virtual Widget::Ptr clone() const override { return std::make_shared<Grid>(*this); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Draws the widget on the render target. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const override; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// protected: std::vector<std::vector<Widget::Ptr>> m_gridWidgets; std::vector<std::vector<Borders>> m_objBorders; std::vector<std::vector<Alignment>> m_objAlignment; std::vector<float> m_rowHeight; std::vector<float> m_columnWidth; std::map<Widget::Ptr, unsigned int> m_connectedCallbacks; sf::Vector2f m_realSize; // Actual size of the grid, while m_size contains the intended size ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif // TGUI_GRID_HPP
[ "marcus.waldhuetter@wikifolio.com" ]
marcus.waldhuetter@wikifolio.com
2b7a335fc2afaeaa391eb5857ed099b2d2e94f1e
eb7696001a46050ed32582f32e605775d5479938
/hbqt/qtmultimediawidgets/hbqt_init.cpp
3e31ee69547e519b3540beb3098b896ee3b39b0c
[]
no_license
lautaromoreira/qtcontribs
d3f23d1fe241cc700a62dcf1e9892b31555f0e1d
0a6d650d5bdb71949462c1689e5ad9d5c0879292
refs/heads/master
2022-12-26T03:52:30.455364
2020-09-23T13:07:37
2020-09-23T13:07:37
297,971,708
0
0
null
null
null
null
UTF-8
C++
false
false
3,377
cpp
/* * $Id$ */ /* * Harbour Project source code: * QT wrapper main header * * Copyright 2009-14 Pritpal Bedi (bedipritpal@hotmail.com) * Copyright 2010 Viktor Szakats (harbour syenar.net) * www - http://harbour-project.org * * 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, 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 software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA (or visit the web site http://www.gnu.org/). * * As a special exception, the Harbour Project gives permission for * additional uses of the text contained in its release of Harbour. * * The exception is that, if you link the Harbour libraries with other * files to produce an executable, this does not by itself cause the * resulting executable to be covered by the GNU General Public License. * Your use of that executable is in no way restricted on account of * linking the Harbour library code into it. * * This exception does not however invalidate any other reasons why * the executable file might be covered by the GNU General Public License. * * This exception applies only to the code released by the Harbour * Project under the name Harbour. If you copy code from other * Harbour Project or Free Software Foundation releases into a copy of * Harbour, as the General Public License permits, the exception does * not apply to the code that you add in this way. To avoid misleading * anyone as to the status of such modified files, you must delete * this exception notice from them. * * If you write modifications of your own for Harbour, it is your choice * whether to permit this exception to apply to your modifications. * If you do not wish that, delete this exception notice. * */ /*----------------------------------------------------------------------*/ #include "hbgtinfo.ch" #include "hbqt.h" #include "hbqtinit.h" #include "hbapierr.h" #include "hbapiitm.h" #include "hbvm.h" #include "hbinit.h" #if QT_VERSION >= 0x040500 /*----------------------------------------------------------------------*/ static void hbqt_registerCallbacks( void ) { } /*----------------------------------------------------------------------*/ HB_FUNC( __HBQTMULTIMEDIAWIDGETS ) {;} static void hbqt_lib_init( void * cargo ) { HB_SYMBOL_UNUSED( cargo ); hbqt_registerCallbacks(); } static void hbqt_lib_exit( void * cargo ) { HB_SYMBOL_UNUSED( cargo ); } HB_CALL_ON_STARTUP_BEGIN( _hbqtmultimediawidgets_init_ ) hb_vmAtInit( hbqt_lib_init, NULL ); hb_vmAtExit( hbqt_lib_exit, NULL ); HB_CALL_ON_STARTUP_END( _hbqtmultimediawidgets_init_ ) #if defined( HB_PRAGMA_STARTUP ) #pragma startup _hbqtmultimediawidgets_init_ #elif defined( HB_DATASEG_STARTUP ) #define HB_DATASEG_BODY HB_DATASEG_FUNC( _hbqtmultimediawidgets_init_ ) #include "hbiniseg.h" #endif #endif
[ "bedipritpal@d9dd3404-ddb2-4ebf-8b6a-858f5af37adf" ]
bedipritpal@d9dd3404-ddb2-4ebf-8b6a-858f5af37adf
64fc413970a587dbd1a146b6ed46bb6cc1d12c93
b64cf2e7e790924ed2f11a5aff5b63adb68b825d
/PlayerInput.cpp
c1831e5075a516d82e449d53f89caccede61a2a7
[]
no_license
ritabazak/capturetheflag
83b872607055ed0c0a22207261410fffb624c038
40107346f00a181846ea8c2a7ba2bec568954a83
refs/heads/master
2021-07-24T18:44:34.816338
2017-11-03T16:21:13
2017-11-03T16:21:13
109,403,142
0
0
null
null
null
null
UTF-8
C++
false
false
706
cpp
#include "PlayerInput.h" Direction PlayerInput::isOwnMove(char ch) const { for (int i = 0; i < _moveKeys.length(); i++) { if (_moveKeys[i] == ch) { switch (i) { case 0: return Direction::UP; case 1: return Direction::DOWN; case 2: return Direction::LEFT; case 3: return Direction::RIGHT; } } } return Direction::STOPPED; } int PlayerInput::isOwnPawn(char ch) const { for (int i = 0; i < _pawnKeys.length(); i++) { if (_pawnKeys[i] == ch) { return i; } } return -1; }
[ "amit@payobin.com" ]
amit@payobin.com
48c1197b58a2dab23506e39258452591188f4c02
17e7f2f8b786ee8361b9b755740e816411751b76
/NexusNative/nrender_d3d9/ssao.cpp
7e5e0efd38d3dcaa85282c4803b5836b01263b4e
[]
no_license
windless1015/My3DEngine2008
880945bd9d9f5e9a2ed30fe869ee53ec5b4fe2da
6fffdd1b158ba9c63ffd564788fddd5706e08ac0
refs/heads/master
2022-11-13T17:41:46.620000
2020-07-02T13:31:19
2020-07-02T13:31:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,370
cpp
#include "StdAfx.h" #include "ssao.h" #include "nrenderer_d3d9.h" #include "global_shader_lib.h" #include "d3d_device_manager.h" #include "scene_render_targets.h" namespace nexus { ssao::ssao( EQuality quality ):m_quality(quality) ,m_occlustion_radius(20) ,m_occlustion_power(3.5) ,m_blocker_power(1.5f) { scene_render_targets* scene_rt = scene_render_targets::instance(); D3DSURFACE_DESC desc = scene_rt->get_back_surface_desc(); UINT factor = 0; if (m_quality == low) { factor = 4; } else if (m_quality == medium) { factor = 2; } else if (m_quality == high) { factor = 1; } m_items[0] = scene_render_targets::create_item(desc.Width/factor, desc.Height/factor, desc.Format); m_items[1] = scene_render_targets::create_item(desc.Width/factor, desc.Height/factor, desc.Format); } ssao::~ssao(void) { m_items[0].release(); m_items[1].release(); } #define sampler_count 32 struct random_normal { vector<vector4> verts; random_normal() { verts.reserve(sampler_count); for (int i = 0; i < sampler_count; i ++) { vector4 vertex( (float)rand()/RAND_MAX*2 - 1, (float)rand()/RAND_MAX*2 - 1, (float)rand()/RAND_MAX*2 - 1, 1 ); vertex = vec_normalize(vertex); vertex*= (float)rand()/RAND_MAX; verts.push_back(vertex); } } }; random_normal sampler_point; static d3d_texture_ptr get_radom_rot() { static d3d_texture_ptr m_rot_texture; if (!m_rot_texture) { IDirect3DDevice9* device = d3d_device_manager::instance()->get_device(); LPDIRECT3DTEXTURE9 rot_texture = NULL; HRESULT hr = D3DXCreateTextureFromFile(device,_T("../nexus_game/engine_data/resource_default/rotrandomCM.dds"),&rot_texture); m_rot_texture.reset(rot_texture); } return m_rot_texture; } static d3d_volume_texture_ptr get_Jitter() { static d3d_volume_texture_ptr m_jitter_texture; if (!m_jitter_texture) { IDirect3DDevice9* device = d3d_device_manager::instance()->get_device(); LPDIRECT3DVOLUMETEXTURE9 JitterTexture = NULL; HRESULT hr = D3DXCreateVolumeTextureFromFile(device,_T("../nexus_game/engine_data/resource_default/Jitter.dds"),&JitterTexture); m_jitter_texture.reset(JitterTexture); } return m_jitter_texture; } void ssao::render() const { IDirect3DDevice9* device = d3d_device_manager::instance()->get_device(); nrenderer_d3d9* render = nrenderer_d3d9::instance(); scene_render_targets* scene_rt = scene_render_targets::instance(); d3d_effect_ptr effect = global_shader_lib::instance()->find_shader( _T("ssao.fx")); assert(effect); device->SetRenderTarget(0, m_items[0].surf.get()); device->Clear(0, NULL, D3DCLEAR_TARGET, 0xffffff, 1, 0); effect->SetTechnique("techDefault"); const rt_item& scene_depth = scene_rt->get_render_target(ERT_SceneNormalDepth); effect->SetTexture("SceneNormalAndDepth",scene_depth.tex.get()); matrix44 screen_to_view = render->get_view_info()->mat_project; matrix44 inv_project = mat_inverse(render->get_view_info()->mat_project); screen_to_view.m[0][0] = 1; screen_to_view.m[1][1] = 1; screen_to_view = screen_to_view*inv_project; matrix44 screen_to_world = render->get_view_info()->mat_project; matrix44 inv_view_project = mat_inverse(render->get_view_info()->mat_view_project); screen_to_world.m[0][0] = 1; screen_to_world.m[1][1] = 1; screen_to_world = screen_to_world*inv_view_project; effect->SetMatrix("ScreenToView",(D3DXMATRIX*)&(screen_to_view) ); effect->SetMatrix("ScreenToWorld",(D3DXMATRIX*)&(screen_to_world) ); effect->SetMatrix("ProjMatrix",(D3DXMATRIX*)&(render->get_view_info()->mat_project) ); effect->SetMatrix("ViewMatrix",(D3DXMATRIX*)& (render->get_view_info()->mat_view)); effect->SetVector("ViewPos",(D3DXVECTOR4*)&render->get_view_info()->eye_pos); effect->SetVector("ScreenScaleBias",(D3DXVECTOR4*)&scene_rt->calc_screen_scale_bias()); IDirect3DSurface9* surf; D3DSURFACE_DESC desc; device->GetRenderTarget(0,&surf); surf->GetDesc(&desc); surf->Release(); vector2 random_uv_cale((float)desc.Width/64,(float)desc.Height/64); effect->SetVector("RandomUVScale",(D3DXVECTOR4*)&random_uv_cale); effect->SetVectorArray("SamplerPoints",(D3DXVECTOR4*)&sampler_point.verts[0],sampler_count); effect->SetTexture("RandomRot",get_radom_rot().get()); effect->SetFloat("OcclustionRadius",m_occlustion_radius); effect->SetFloat("OcclustionPower",m_occlustion_power); effect->SetFloat("BlockerPower",m_blocker_power); scene_rt->draw_screen_quad(effect.get()); // Configure the sampling offsets and their weights float HBloomWeights[9]; float HBloomOffsets[9]; static float g_GaussMultiplier = 0.3f; // Default multiplier static float g_GaussMean = 0.0f; // Default mean for gaussian distribution static float g_GaussStdDev = 0.83f; // Default standard deviation for gaussian distribution for( int i = 0; i < 9; i++ ) { // Compute the offsets. We take 9 samples - 4 either side and one in the middle: // i = 0, 1, 2, 3, 4, 5, 6, 7, 8 //Offset = -4, -3, -2, -1, 0, +1, +2, +3, +4 HBloomOffsets[i] = (static_cast< float >( i ) - 4.0f) * ( 1.0f / static_cast< float >( desc.Width ) ); // 'x' is just a simple alias to map the [0,8] range down to a [-1,+1] float x = (static_cast< float >( i ) - 4.0f) / 4.0f; // Use a gaussian distribution. Changing the standard-deviation // (second parameter) as well as the amplitude (multiplier) gives // distinctly different results. HBloomWeights[i] = g_GaussMultiplier * ComputeGaussianValue( x, g_GaussMean, g_GaussStdDev ); } // Commit both arrays to the device: device->SetRenderTarget(0, m_items[1].surf.get()); if ( m_quality == high) { effect->SetTechnique("techHorizontalBlurFliter"); } else { effect->SetTechnique("techHorizontalBlur"); } effect->SetTexture("g_tex", m_items[0] .tex.get()); effect->SetTexture("SceneNormalAndDepth", scene_rt->get_render_target(ERT_SceneNormalDepth) .tex.get()); effect->SetFloatArray("HBloomWeights", HBloomWeights, 9 ); effect->SetFloatArray("HBloomOffsets", HBloomOffsets, 9 ); scene_rt->draw_screen_quad(effect.get()); // [ 3 ] BLUR VERTICALLY //---------------------- device->SetRenderTarget(0, m_items[0].surf.get()); effect->SetTexture("g_tex", m_items[1] .tex.get()); effect->SetTexture("SceneNormalAndDepth", scene_rt->get_render_target(ERT_SceneNormalDepth) .tex.get()); if ( m_quality == high) { effect->SetTechnique("techVerticalBlurFliter"); } else { effect->SetTechnique("techVerticalBlur"); } device->GetRenderTarget(0,&surf); surf->GetDesc(&desc); surf->Release(); float VBloomWeights[9]; float VBloomOffsets[9]; for( int i = 0; i < 9; i++ ) { // Compute the offsets. We take 9 samples - 4 either side and one in the middle: // i = 0, 1, 2, 3, 4, 5, 6, 7, 8 //Offset = -4, -3, -2, -1, 0, +1, +2, +3, +4 VBloomOffsets[i] = (static_cast< float >( i ) - 4.0f) * ( 1.0f / static_cast< float >( desc.Height ) ); // 'x' is just a simple alias to map the [0,8] range down to a [-1,+1] float x = (static_cast< float >( i ) - 4.0f) / 4.0f; // Use a gaussian distribution. Changing the standard-deviation // (second parameter) as well as the amplitude (multiplier) gives // distinctly different results. VBloomWeights[i] = g_GaussMultiplier * ComputeGaussianValue( x, g_GaussMean, g_GaussStdDev ); } // Commit both arrays to the device: effect->SetFloatArray("VBloomWeights", VBloomWeights, 9 ); effect->SetFloatArray("VBloomOffsets", VBloomOffsets, 9 ); effect->SetTexture("SceneNormalAndDepth", scene_rt->get_render_target(ERT_SceneNormalDepth) .tex.get()); scene_rt->draw_screen_quad(effect.get()); scene_render_targets::instance()->begin_scene_color(); effect->SetTechnique("techBlend"); effect->SetTexture("g_tex", m_items[0] .tex.get()); scene_rt->draw_screen_quad(effect.get()); scene_render_targets::instance()->end_scene_color(); } }
[ "neil3d@126.com" ]
neil3d@126.com
2313b205b8be260bfab2a3b8c4e691b8019abb0f
2426ae6b2205cceaee961e53685c74e01e9e8a2a
/Advanced_C++_Programming/stub-exam/include/gdwg/graph.hpp
7c3864e3eeb2a10d378ff3d09f308687945ccbf8
[ "Apache-2.0" ]
permissive
HeSixiang/UNSW
937e54eab653a3efdeaf4686f4089c2a25acd800
6f63ebed517eac29f303ca364ee764d55a9581f4
refs/heads/master
2023-03-06T04:26:48.035280
2021-02-16T06:04:56
2021-02-16T06:04:56
245,617,469
0
0
null
null
null
null
UTF-8
C++
false
false
546
hpp
#ifndef GDWG_GRAPH_HPP #define GDWG_GRAPH_HPP #include <concepts/concepts.hpp> #include <initializer_list> #include <ostream> #include <range/v3/iterator.hpp> #include <range/v3/utility.hpp> namespace gdwg { template<concepts::regular N, concepts::regular E> requires concepts::totally_ordered<N> // and concepts::totally_ordered<E> // class graph { public: class iterator; struct value_type { N from; N to; E weight; }; // Your member functions go here private: }; } // namespace gdwg #endif // GDWG_GRAPH_HPP
[ "z5280561@unsw.edu.au" ]
z5280561@unsw.edu.au
401f6d74d4eeec1217fa0534d6c8cef81274e66f
cfec910d55e239f2f5fd29bd830dc32ad383c717
/EngineLayer/SFProtobufPacket.h
5f737eb6b7939273a497c94e60b2d13c5e32734d
[]
no_license
pdpdds/cgsf2019
a7aef9ac29fde63125e80ef433f7b75b5f9c3841
9156cb79386e1d261b107b75339ce02e834daf55
refs/heads/master
2022-07-08T22:03:30.220719
2022-06-30T10:02:27
2022-06-30T10:02:27
214,360,553
8
0
null
2022-06-30T10:02:53
2019-10-11T06:30:39
C++
UTF-8
C++
false
false
558
h
#pragma once #include "SFProtobufPacketImpl.h" template<class T> class SFProtobufPacket : public SFProtobufPacketImpl { public: SFProtobufPacket(int serviceId) : SFProtobufPacketImpl(serviceId, &m_Packet) { } virtual ~SFProtobufPacket(void){} T& GetData() { return m_Packet; } virtual BasePacket* Clone() { SFProtobufPacket* pClone = new SFProtobufPacket<T>(getServiceId()); pClone->CopyBaseHeader(this); pClone->m_Packet = m_Packet; return pClone; } protected: private: T m_Packet; };
[ "juhang3@daum.net" ]
juhang3@daum.net
0617a76f3a74d2b4b87a61571628b92dcde9a62b
2e1f8763e5ef94a1927adf77ffa15afafc8f5615
/src/main.cpp
12ddca0e07b862fb473d602eac190ee25c6935f1
[]
no_license
dz0ny/prusa-wifi
575651374dd0ef00113522bb3482d0477f96f709
fb54d0f6a78f4595293e57767410a207bd51b1c5
refs/heads/master
2022-11-10T06:58:11.530470
2020-06-21T19:43:39
2020-06-21T19:47:06
273,972,613
1
1
null
null
null
null
UTF-8
C++
false
false
3,024
cpp
#include "AsyncJson.h" #include "SD_MMC.h" #include <AsyncWebDAV.h> #include <DNSServer.h> #include <ESPAsyncWebServer.h> #include <ESPAsyncWiFiManager.h> #include <ESPmDNS.h> #include <OctoPrintAPI.h> #include <WiFi.h> #define VERSION "1.3.10" #define SKETCH_VERSION "2.x-localbuild" AsyncWebServer server(80); AsyncEventSource events("/events"); DNSServer dns; const char *hostName = "PrusaWIFI"; void mDNSInit() { if (!MDNS.begin(hostName)) return; // OctoPrint API // Unfortunately, Slic3r doesn't seem to recognize it MDNS.addService("octoprint", "tcp", 80); MDNS.addServiceTxt("octoprint", "tcp", "path", "/"); MDNS.addServiceTxt("octoprint", "tcp", "api", VERSION); MDNS.addServiceTxt("octoprint", "tcp", "version", VERSION); MDNS.addServiceTxt("octoprint", "tcp", "model", "ESP32"); MDNS.addServiceTxt("octoprint", "tcp", "vendor", hostName); MDNS.addServiceTxt("octoprint", "tcp", "mac", WiFi.macAddress()); MDNS.addService("http", "tcp", 80); MDNS.addServiceTxt("http", "tcp", "path", "/"); MDNS.addServiceTxt("http", "tcp", "api", VERSION); MDNS.addServiceTxt("http", "tcp", "version", SKETCH_VERSION); MDNS.addServiceTxt("http", "tcp", "model", "ESP32"); MDNS.addServiceTxt("http", "tcp", "vendor", hostName); MDNS.addServiceTxt("http", "tcp", "mac", WiFi.macAddress()); } void onWiFiEvent(WiFiEvent_t event) { switch (event) { case SYSTEM_EVENT_STA_START: Serial.println("WIFI: Connecting..."); break; case SYSTEM_EVENT_STA_CONNECTED: Serial.println("WIFI: Connected! Waiting for IP..."); break; case SYSTEM_EVENT_STA_LOST_IP: Serial.println("WIFI: Lost IP address..."); break; case SYSTEM_EVENT_STA_GOT_IP: Serial.println("WIFI: Got IP!"); Serial.print("WIFI: IP Address: "); Serial.println(WiFi.localIP()); mDNSInit(); break; default: break; } } void setup() { Serial.begin(115200); WiFi.setHostname(hostName); WiFi.onEvent(onWiFiEvent); if (!SD_MMC.begin("/sdcard", true)) { Serial.println("Card Mount Failed"); return; } uint8_t cardType = SD_MMC.cardType(); if (cardType == CARD_NONE) { Serial.println("No SD card attached"); return; } server.addHandler(new AsyncWebDAV("/drive", SD_MMC)); server.addHandler(new OctoPrintAPI(SD_MMC)); server.serveStatic("/", SD_MMC, "/ui/") .setDefaultFile("index.html") .setCacheControl("max-age=600"); events.onConnect([](AsyncEventSourceClient *client) { client->send("hello!", NULL, millis(), 1000); }); server.addHandler(&events); server.on("/heap", HTTP_GET, [](AsyncWebServerRequest *request) { request->send(200, "text/plain", String(ESP.getFreeHeap())); }); AsyncWiFiManager wifiManager(&server, &dns); // wifiManager.resetSettings(); // Uncomment this to reset the settings on wifiManager.setDebugOutput(false); wifiManager.autoConnect("AutoConnectAP"); DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*"); server.begin(); } void loop() {}
[ "dz0ny@ubuntu.si" ]
dz0ny@ubuntu.si
fc37eb211c1830f991fa21dec48986356be78146
1f9cc0e6e07830f668e8333935536ee063769258
/src/main.cpp
3c2cc0d9bf09f8497bf6c1f0093ab9a15a6e54e8
[ "MIT" ]
permissive
gdchenahu/MQSim
4d23b991de143e523b57e90d18fb18377dca0c3e
784bbe466c576dbfbcda4d93c38fb220f0efe8ab
refs/heads/master
2020-03-18T06:03:59.948524
2018-05-19T01:55:09
2018-05-19T01:55:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,444
cpp
#include <iostream> #include <fstream> #include <ctime> #include <string> #include <cstring> #include "ssd/SSD_Defs.h" #include "exec/Execution_Parameter_Set.h" #include "exec/SSD_Device.h" #include "exec/Host_System.h" #include "utils/rapidxml/rapidxml.hpp" #include "utils/DistributionTypes.h" using namespace std; void command_line_args(char* argv[], string& input_file_path, string& workload_file_path) { for (int arg_cntr = 1; arg_cntr < 5; arg_cntr++) { string arg = argv[arg_cntr]; char file_path_switch[] = "-i"; if (arg.compare(0, strlen(file_path_switch), file_path_switch) == 0) { input_file_path.assign(argv[++arg_cntr]); //cout << input_file_path << endl; continue; } char workload_path_switch[] = "-w"; if (arg.compare(0, strlen(workload_path_switch), workload_path_switch) == 0) { workload_file_path.assign(argv[++arg_cntr]); //cout << workload_file_path << endl; continue; } } } void read_configuration_parameters(const string ssd_config_file_path, Execution_Parameter_Set* exec_params) { ifstream ssd_config_file; ssd_config_file.open(ssd_config_file_path.c_str()); if (!ssd_config_file) { PRINT_MESSAGE("The specified SSD configuration file does not exist.") PRINT_MESSAGE("Using MQSim's default configuration.") PRINT_MESSAGE("Writing the default configuration parameters to the expected configuration file.") Utils::XmlWriter xmlwriter; string tmp; xmlwriter.Open(ssd_config_file_path.c_str()); exec_params->XML_serialize(xmlwriter); xmlwriter.Close(); PRINT_MESSAGE("[====================] Done!\n") } else { //Read input workload parameters string line((std::istreambuf_iterator<char>(ssd_config_file)), std::istreambuf_iterator<char>()); ssd_config_file >> line; if (line.compare("USE_INTERNAL_PARAMS") != 0) { rapidxml::xml_document<> doc; // character type defaults to char char* temp_string = new char[line.length() + 1]; strcpy(temp_string, line.c_str()); doc.parse<0>(temp_string); rapidxml::xml_node<> *mqsim_config = doc.first_node("Execution_Parameter_Set"); if (mqsim_config != NULL) { exec_params = new Execution_Parameter_Set; exec_params->XML_deserialize(mqsim_config); } else { PRINT_MESSAGE("Error in the SSD configuration file!") PRINT_MESSAGE("Using MQSim's default configuration.") } } else { PRINT_MESSAGE("Using MQSim's default configuration."); PRINT_MESSAGE("Writing the default configuration parameters to the expected configuration file."); Utils::XmlWriter xmlwriter; string tmp; xmlwriter.Open(ssd_config_file_path.c_str()); exec_params->XML_serialize(xmlwriter); xmlwriter.Close(); PRINT_MESSAGE("[====================] Done!\n") } } ssd_config_file.close(); } std::vector<std::vector<IO_Flow_Parameter_Set*>*>* read_workload_definitions(const string workload_defs_file_path) { std::vector<std::vector<IO_Flow_Parameter_Set*>*>* io_scenarios = new std::vector<std::vector<IO_Flow_Parameter_Set*>*>; ifstream workload_defs_file; workload_defs_file.open(workload_defs_file_path.c_str()); bool use_default_workloads = true; if (!workload_defs_file) { PRINT_MESSAGE("The specified workload definition file does not exist!"); PRINT_MESSAGE("Using MQSim's default workload definitions."); PRINT_MESSAGE("Writing the default workload definitions to the expected workload definition file."); PRINT_MESSAGE("[====================] Done!\n"); } else { string line((std::istreambuf_iterator<char>(workload_defs_file)), std::istreambuf_iterator<char>()); if (line.compare("USE_INTERNAL_PARAMS") != 0) { rapidxml::xml_document<> doc; // character type defaults to char char* temp_string = new char[line.length() + 1]; strcpy(temp_string, line.c_str()); doc.parse<0>(temp_string); rapidxml::xml_node<> *mqsim_io_scenarios = doc.first_node("MQSim_IO_Scenarios"); if (mqsim_io_scenarios != NULL) { for (auto xml_io_scenario = mqsim_io_scenarios->first_node("IO_Scenario"); xml_io_scenario; xml_io_scenario = xml_io_scenario->next_sibling("IO_Scenario")) { std::vector<IO_Flow_Parameter_Set*>* scenario_definition = new std::vector<IO_Flow_Parameter_Set*>; for (auto flow_def = xml_io_scenario->first_node(); flow_def; flow_def = flow_def->next_sibling()) { IO_Flow_Parameter_Set* flow; if (strcmp(flow_def->name(), "IO_Flow_Parameter_Set_Synthetic") == 0) { flow = new IO_Flow_Parameter_Set_Synthetic; ((IO_Flow_Parameter_Set_Synthetic*)flow)->XML_deserialize(flow_def); } else if (strcmp(flow_def->name(), "IO_Flow_Parameter_Set_Trace_Based") == 0) { flow = new IO_Flow_Parameter_Set_Trace_Based; ((IO_Flow_Parameter_Set_Trace_Based*)flow)->XML_deserialize(flow_def); } scenario_definition->push_back(flow); } io_scenarios->push_back(scenario_definition); use_default_workloads = false; } } else { PRINT_MESSAGE("Error in the workload definition file!"); PRINT_MESSAGE("Using MQSim's default workload definitions."); PRINT_MESSAGE("Writing the default workload definitions to the expected workload definition file."); PRINT_MESSAGE("[====================] Done!\n"); } } } if (use_default_workloads) { std::vector<IO_Flow_Parameter_Set*>* scenario_definition = new std::vector<IO_Flow_Parameter_Set*>; IO_Flow_Parameter_Set_Synthetic* io_flow_1 = new IO_Flow_Parameter_Set_Synthetic; io_flow_1->Device_Level_Data_Caching_Mode = SSD_Components::Caching_Mode::WRITE_CACHE; io_flow_1->Type = Flow_Type::SYNTHETIC; io_flow_1->Priority_Class = IO_Flow_Priority_Class::HIGH; io_flow_1->Channel_No = 8; io_flow_1->Channel_IDs = new flash_channel_ID_type[8]; io_flow_1->Channel_IDs[0] = 0; io_flow_1->Channel_IDs[1] = 1; io_flow_1->Channel_IDs[2] = 2; io_flow_1->Channel_IDs[3] = 3; io_flow_1->Channel_IDs[4] = 4; io_flow_1->Channel_IDs[5] = 5; io_flow_1->Channel_IDs[6] = 6; io_flow_1->Channel_IDs[7] = 7; io_flow_1->Chip_No = 4; io_flow_1->Chip_IDs = new flash_chip_ID_type[4]; io_flow_1->Chip_IDs[0] = 0; io_flow_1->Chip_IDs[1] = 1; io_flow_1->Chip_IDs[2] = 2; io_flow_1->Chip_IDs[3] = 3; io_flow_1->Die_No = 2; io_flow_1->Die_IDs = new flash_die_ID_type[2]; io_flow_1->Die_IDs[0] = 0; io_flow_1->Die_IDs[1] = 1; io_flow_1->Plane_No = 2; io_flow_1->Plane_IDs = new flash_plane_ID_type[2]; io_flow_1->Plane_IDs[0] = 0; io_flow_1->Plane_IDs[1] = 1; io_flow_1->Initial_Occupancy_Percentage = 50; io_flow_1->Working_Set_Percentage = 85; io_flow_1->Synthetic_Generator_Type = Utils::Request_Generator_Type::QUEUE_DEPTH; io_flow_1->Read_Percentage = 100; io_flow_1->Address_Distribution = Utils::Address_Distribution_Type::UNIFORM_RANDOM; io_flow_1->Percentage_of_Hot_Region = 0; io_flow_1->Generated_Aligned_Addresses = true; io_flow_1->Address_Alignment_Unit = 16; io_flow_1->Request_Size_Distribution = Utils::Request_Size_Distribution_Type::FIXED; io_flow_1->Average_Request_Size = 8; io_flow_1->Variance_Request_Size = 0; io_flow_1->Seed = 12344; io_flow_1->Average_No_of_Reqs_in_Queue = 2; io_flow_1->Bandwidth = 262144; io_flow_1->Stop_Time = 1000000000; io_flow_1->Total_Requests_To_Generate = 0; scenario_definition->push_back(io_flow_1); IO_Flow_Parameter_Set_Synthetic* io_flow_2 = new IO_Flow_Parameter_Set_Synthetic; io_flow_2->Device_Level_Data_Caching_Mode = SSD_Components::Caching_Mode::WRITE_CACHE; io_flow_2->Type = Flow_Type::SYNTHETIC; io_flow_2->Priority_Class = IO_Flow_Priority_Class::HIGH; io_flow_2->Channel_No = 8; io_flow_2->Channel_IDs = new flash_channel_ID_type[8]; io_flow_2->Channel_IDs[0] = 0; io_flow_2->Channel_IDs[1] = 1; io_flow_2->Channel_IDs[2] = 2; io_flow_2->Channel_IDs[3] = 3; io_flow_2->Channel_IDs[4] = 4; io_flow_2->Channel_IDs[5] = 5; io_flow_2->Channel_IDs[6] = 6; io_flow_2->Channel_IDs[7] = 7; io_flow_2->Chip_No = 4; io_flow_2->Chip_IDs = new flash_chip_ID_type[4]; io_flow_2->Chip_IDs[0] = 0; io_flow_2->Chip_IDs[1] = 1; io_flow_2->Chip_IDs[2] = 2; io_flow_2->Chip_IDs[3] = 3; io_flow_2->Die_No = 2; io_flow_2->Die_IDs = new flash_die_ID_type[2]; io_flow_2->Die_IDs[0] = 0; io_flow_2->Die_IDs[1] = 1; io_flow_2->Plane_No = 2; io_flow_2->Plane_IDs = new flash_plane_ID_type[2]; io_flow_2->Plane_IDs[0] = 0; io_flow_2->Plane_IDs[1] = 1; io_flow_2->Initial_Occupancy_Percentage = 50; io_flow_2->Working_Set_Percentage = 85; io_flow_2->Synthetic_Generator_Type = Utils::Request_Generator_Type::QUEUE_DEPTH; io_flow_2->Read_Percentage = 100; io_flow_2->Address_Distribution = Utils::Address_Distribution_Type::UNIFORM_RANDOM; io_flow_2->Percentage_of_Hot_Region = 0; io_flow_2->Generated_Aligned_Addresses = true; io_flow_2->Address_Alignment_Unit = 16; io_flow_2->Request_Size_Distribution = Utils::Request_Size_Distribution_Type::FIXED; io_flow_2->Average_Request_Size = 8; io_flow_2->Variance_Request_Size = 0; io_flow_2->Seed = 6533; io_flow_2->Average_No_of_Reqs_in_Queue = 2; io_flow_2->Bandwidth = 131072; io_flow_2->Stop_Time = 1000000000; io_flow_2->Total_Requests_To_Generate = 0; scenario_definition->push_back(io_flow_2); io_scenarios->push_back(scenario_definition); PRINT_MESSAGE("Writing default workload parameters to the expected input file.") Utils::XmlWriter xmlwriter; string tmp; xmlwriter.Open(workload_defs_file_path.c_str()); tmp = "MQSim_IO_Scenarios"; xmlwriter.Write_open_tag(tmp); tmp = "IO_Scenario"; xmlwriter.Write_open_tag(tmp); io_flow_1->XML_serialize(xmlwriter); io_flow_2->XML_serialize(xmlwriter); xmlwriter.Write_close_tag(); xmlwriter.Write_close_tag(); xmlwriter.Close(); } workload_defs_file.close(); return io_scenarios; } void collect_results(SSD_Device& ssd, Host_System& host, const char* output_file_path) { Utils::XmlWriter xmlwriter; xmlwriter.Open(output_file_path); std::string tmp("MQSim_Results"); xmlwriter.Write_open_tag(tmp); host.Report_results_in_XML("", xmlwriter); ssd.Report_results_in_XML("", xmlwriter); xmlwriter.Write_close_tag(); std::vector<Host_Components::IO_Flow_Base*> IO_flows = host.Get_io_flows(); for (unsigned int stream_id = 0; stream_id < IO_flows.size(); stream_id++) { cout << "Flow " << IO_flows[stream_id]->ID() << " - total requests generated: " << IO_flows[stream_id]->Get_generated_request_count() << " total requests serviced:" << IO_flows[stream_id]->Get_serviced_request_count() << endl; cout << " - device response time: " << IO_flows[stream_id]->Get_device_response_time() << " (us)" << " end-to-end request delay:" << IO_flows[stream_id]->Get_end_to_end_request_delay() << " (us)" << endl; } //cin.get(); } void print_help() { cout << "MQSim - A simulator for modern NVMe and SATA SSDs developed at SAFARI group in ETH Zurich" << endl << "Standalone Usage:" << endl << "./MQSim [-i path/to/config/file] [-w path/to/workload/file]" << endl; } int main(int argc, char* argv[]) { string ssd_config_file_path, workload_defs_file_path; if (argc != 5) { // MQSim expects 2 arguments: 1) the path to the SSD configuration definition file, and 2) the path to the workload definition file print_help(); return 1; } command_line_args(argv, ssd_config_file_path, workload_defs_file_path); Execution_Parameter_Set* exec_params = new Execution_Parameter_Set; read_configuration_parameters(ssd_config_file_path, exec_params); std::vector<std::vector<IO_Flow_Parameter_Set*>*>* io_scenarios = read_workload_definitions(workload_defs_file_path); int cntr = 1; for (auto io_scen = io_scenarios->begin(); io_scen != io_scenarios->end(); io_scen++, cntr++) { time_t start_time = time(0); char* dt = ctime(&start_time); PRINT_MESSAGE("MQSim started at " << dt) PRINT_MESSAGE("******************************") PRINT_MESSAGE("Executing scenario " << cntr << " out of " << io_scenarios->size() << " .......") //The simulator should always be reset, before starting the actual simulation Simulator->Reset(); exec_params->Host_Configuration.IO_Flow_Definitions.clear(); for (auto io_flow_def = (*io_scen)->begin(); io_flow_def != (*io_scen)->end(); io_flow_def++) exec_params->Host_Configuration.IO_Flow_Definitions.push_back(*io_flow_def); SSD_Device ssd(&exec_params->SSD_Device_Configuration, &exec_params->Host_Configuration.IO_Flow_Definitions);//Create SSD_Device based on the specified parameters exec_params->Host_Configuration.Input_file_path = workload_defs_file_path.substr(0, workload_defs_file_path.find_last_of("."));//Create Host_System based on the specified parameters Host_System host(&exec_params->Host_Configuration, exec_params->SSD_Device_Configuration.Enabled_Preconditioning, ssd.Host_interface); host.Attach_ssd_device(&ssd); Simulator->Start_simulation(); time_t end_time = time(0); dt = ctime(&end_time); PRINT_MESSAGE("MQSim finished at " << dt) uint64_t duration = (uint64_t)difftime(end_time, start_time); PRINT_MESSAGE("Total simulation time: " << duration / 3600 << ":" << (duration % 3600) / 60 << ":" << ((duration % 3600) % 60)) PRINT_MESSAGE(""); PRINT_MESSAGE("Writing results to output file ......."); collect_results(ssd, host, (workload_defs_file_path.substr(0, workload_defs_file_path.find_last_of(".")) + "_scenario_" + std::to_string(cntr) + ".xml").c_str()); } cin.get(); return 0; }
[ "arash.tavakkol@inf.ethz.ch" ]
arash.tavakkol@inf.ethz.ch
fda02ff5101f29a0bf8cdfc2b7816d1a506b70e5
17e8b775ec28c774857919b8df957145adf2e606
/codechef/Beautiful-Array.cpp
9bf141509163e0122ad7f75e58f72773c5898e2e
[]
no_license
chamow97/Competitive-Coding
30b5acc77d51207c55eca91b8da161d80a3fbfab
8f2d8a1ca6881dbde9c75735240d4e4f681e0138
refs/heads/master
2021-04-28T21:40:05.294842
2019-09-15T13:25:59
2019-09-15T13:25:59
77,766,905
5
0
null
null
null
null
UTF-8
C++
false
false
1,509
cpp
//template by chamow #include<bits/stdc++.h> /*-------------------------------------------------------- */ using namespace std; /*-------------------------------------------------------- */ #define rep(i,val,n) for(ll i=val;i<n;i++) #define per(j,val,n) for(ll j=val;j>=n;j--) #define pb push_back #define pi 3.14157 #define mp make_pair #define MODULO 1000000007 #define INF 1000000000000000 #define fastread ios_base::sync_with_stdio(false); cin.tie(NULL); #define vecit vector<ll> :: iterator #define vecpit vector< pair<ll, ll> > :: iterator #define f first #define s second /*-------------------------------------------------------- */ typedef long long ll; typedef vector<bool> boolean; typedef vector<ll> vec; typedef vector< pair<ll, ll> > vecpair; /*-------------------------------------------------------- */ ll gcd(ll a, ll b) { if(b == 0) { return a; } return gcd(b, a%b); } ll lcm(ll a, ll b) { return ((a*b)/gcd(a,b)); } /*-------------------------------------------------------- */ void solve() { vec mod(5, 0); ll n; cin >> n; ll sum = 0; rep(i,0,n) { ll val; cin >> val; sum += val; val %= 4; mod[val]++; } if(sum % 4 != 0) { cout << -1; } else { ll ans = 0; ans += (min(mod[1], mod[3])); mod[1] -= ans; mod[3] -= ans; ll extra = max(mod[3], mod[1]); extra /= 2; mod[2] += extra; ans += extra; ans += mod[2]/2; cout << ans; } } int main() { fastread; ll t; cin >> t; while(t--) { solve(); cout << '\n'; } return 0; }
[ "jchandramowli15039@it.ssn.edu.in" ]
jchandramowli15039@it.ssn.edu.in
6c1a19fe5fff4a22070edd55bbdcaa182256f61f
d2ab7d271e93a0b8b3e3f3a149f62af64aabec18
/backup/locationsystem/include/locationsystem/SURF.h
9af353ea96c83ee4c0dee55d6ad700d9b33e22c6
[ "BSD-2-Clause" ]
permissive
dolmong/LocationSystem
d98ef4e27bf2a45ea9cd6fc8350d079ee37ebe38
a7fe025cd25db8c58c832bbaa108b2c53119356d
refs/heads/master
2021-01-15T19:28:20.849629
2013-09-12T06:22:09
2013-09-12T06:22:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,906
h
#ifndef LOCATIONSYSTEM_PROJECT_SURF_H #define LOCATIONSYSTEM_PROJECT_SURF_H #include <malloc.h> #include <vector> #include <math.h> #include <float.h> #include <algorithm> #include "ros/ros.h" #include "sensor_msgs/Image.h" //#include "locationsystem/Matrix.h" #define Octave_Num 5 #define Layer_Num 4 #define TINY 1.0e-20 #define NR_END 1 #define FREE_ARG char* class CSURF { public: // Fucntion CSURF(void); ~CSURF(void); private: // Structure typedef struct _ResponseLayer { int _width; int _height; int _interval; int _filter; float *_ptrace; // size = _width*_height float *_pdetH; // size = _width*_height } Responselayer; typedef struct _InterestPoint { float _x; float _y; float _scale; int _Lap; float _majordiretion; float _IpDescriptor[64]; float _dx; float _dy; int _filter; int _chkOverlap; float _height; float _vx; float _vy; float _dis; } Interestpoint; private: // Variable float *m_pIntegralImage; int m_nwidth; int m_nheight; Responselayer m_layer[Octave_Num][Layer_Num]; int des_index; float m_fthreshold; std::vector<Interestpoint> m_vInterestpoint; private: // Inline Function inline int fRound( float flt ); inline float haarX(int row, int column, int size); inline float haarY(int row, int column, int size); inline float gaussian(int x, int y, float sig); inline float gaussian(float x, float y, float sig); private: // Function void SettingIniFact( int width, int height ); void CalculateIntgral( sensor_msgs::Image image ); void ConstructScaleSpace(); void LocaliseInterestPoint( float threshold=0.f ); void GetInterestPoint( std::vector<Interestpoint> &vItpoint ); void getDescriptors( std::vector<Interestpoint> &vItpoint ); void getOrientation( std::vector<Interestpoint> &vItpoint ); void getDescriptor( std::vector<Interestpoint> &vItpoint ); float getAngle(float X, float Y); void nrerror( char error_text[] ); float **matrix_allocate( long nrl, long nrh, long ncl, long nch ); int *ivector( long nl, long nh ); float *vector_allocate( long nl, long nh ); void free_matrix( float **m, long nrl, long nrh, long ncl, long nch ); void free_ivector( int *v, long nl, long nh ); void free_vector( float *v, long nl, long nh ); void ludcmp( float **a, int n, int *indx, float *d ); void lubksb( float **a, int n, int *indx, float *b ); float CalculateRectangularSum( int y, int x, int cy, int cx ); void CalulateFastHessian( int octave, int layer ); bool ApplyNonMaximalSuppression( int octave, int layer, int y, int x ); void InterpolateInterestpoint( int octave, int layer, int x, int y ); public: // Variable std::vector<Interestpoint> ipSurf; public: // Function void Surf( sensor_msgs::Image image, std::vector<Interestpoint> &itpointTmp ); }; #endif
[ "pi@raspberrypi.(none)" ]
pi@raspberrypi.(none)
c59abf872c610b534e02c075e6391c5a703758c5
ea92cb09d832e11ea8b1e74d35326091fb6bbaa6
/demos/d/src/TriangleMesh.h
aa4342ba7c4e6817d56526c79878c2de27fff540
[ "MIT" ]
permissive
DesignEngrLab/StabilityStudy
3929b704b7365b839a64c34b6273ee1f5e637fba
8ed7685621c76dc74816855a6cf370317fe401fb
refs/heads/master
2021-01-16T23:03:25.276541
2016-10-06T23:59:23
2016-10-06T23:59:23
70,174,035
1
0
null
null
null
null
UTF-8
C++
false
false
1,172
h
#pragma once #include "TriangleIndexVertexArray.h" namespace BulletSharp { public ref class TriangleMesh : TriangleIndexVertexArray { internal: TriangleMesh(btTriangleMesh* native); public: TriangleMesh(bool use32BitIndices, bool use4ComponentVertices); TriangleMesh(bool use32BitIndices); TriangleMesh(); #ifndef DISABLE_INTERNAL void AddIndex(int index); #endif void AddTriangleRef(Vector3% vertex0, Vector3% vertex1, Vector3% vertex2, bool removeDuplicateVertices); void AddTriangle(Vector3 vertex0, Vector3 vertex1, Vector3 vertex2, bool removeDuplicateVertices); void AddTriangleRef(Vector3% vertex0, Vector3% vertex1, Vector3% vertex2); void AddTriangle(Vector3 vertex0, Vector3 vertex1, Vector3 vertex2); void AddTriangleIndices(int index1, int index2, int index3); #ifndef DISABLE_INTERNAL int FindOrAddVertex(Vector3 vertex, bool removeDuplicateVertices); #endif property int NumTriangles { int get(); } property bool Use32BitIndices { bool get(); } property bool Use4ComponentVertices { bool get(); } property btScalar WeldingThreshold { btScalar get(); void set(btScalar value); } }; };
[ "huangwe@oregonstate.edu" ]
huangwe@oregonstate.edu
cc1011b45a94cfab2ec0cc0d34186e82fc84214b
cf1f43771249bf7faf32dd8d3bedce73ea33b756
/source/ui/nvenc_shared.hpp
577ed59146ec1336daec83a311138630452d7d3d
[ "MIT" ]
permissive
kryztoval/obs-ffmpeg-encoder
f8772d29ce8d51eb3f1a77699ce402794f7cc0c9
18024aaf12b919d0b3380faf1c555182858b05c1
refs/heads/master
2020-09-06T20:22:10.631092
2019-10-31T05:36:14
2019-10-31T07:13:42
220,524,736
0
0
MIT
2019-11-08T18:23:42
2019-11-08T18:23:41
null
UTF-8
C++
false
false
2,942
hpp
// FFMPEG Video Encoder Integration for OBS Studio // Copyright (c) 2019 Michael Fabian Dirks <info@xaymar.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <map> #include "utility.hpp" extern "C" { #include <obs-properties.h> #pragma warning(push) #pragma warning(disable : 4244) #include <libavcodec/avcodec.h> #pragma warning(pop) } namespace obsffmpeg { namespace nvenc { enum class preset : int64_t { DEFAULT, SLOW, MEDIUM, FAST, HIGH_PERFORMANCE, HIGH_QUALITY, BLURAYDISC, LOW_LATENCY, LOW_LATENCY_HIGH_PERFORMANCE, LOW_LATENCY_HIGH_QUALITY, LOSSLESS, LOSSLESS_HIGH_PERFORMANCE, }; enum class ratecontrolmode : int64_t { CQP, VBR, VBR_HQ, CBR, CBR_HQ, CBR_LD_HQ, }; enum class b_ref_mode : int64_t { DISABLED, EACH, MIDDLE, }; extern std::map<preset, std::string> presets; extern std::map<preset, std::string> preset_to_opt; extern std::map<ratecontrolmode, std::string> ratecontrolmodes; extern std::map<ratecontrolmode, std::string> ratecontrolmode_to_opt; extern std::map<b_ref_mode, std::string> b_ref_modes; extern std::map<b_ref_mode, std::string> b_ref_mode_to_opt; void override_lag_in_frames(size_t& lag, obs_data_t* settings, const AVCodec* codec, AVCodecContext* context); void get_defaults(obs_data_t* settings, const AVCodec* codec, AVCodecContext* context); void get_properties_pre(obs_properties_t* props, const AVCodec* codec); void get_properties_post(obs_properties_t* props, const AVCodec* codec); void get_runtime_properties(obs_properties_t* props, const AVCodec* codec, AVCodecContext* context); void update(obs_data_t* settings, const AVCodec* codec, AVCodecContext* context); void log_options(obs_data_t* settings, const AVCodec* codec, AVCodecContext* context); } // namespace nvenc } // namespace obsffmpeg
[ "info@xaymar.com" ]
info@xaymar.com
be338d8edadc01e93497c5ecbcdcfbe606e8c67e
6a100dd6f378bac2cecfd47fab5ca262a4d45ee5
/Projekt_po_2018/SQL/BazaDanych.h
7a03088573b736bad026215fe4d14a5b30b9484a
[ "MIT" ]
permissive
GrzybuPL/Projekt_po_2018
c07eb440b0a6b7d8f5e0863e61cee1e65e02e6b8
5ce78ed1b8439bed1844ab77419d7908bded291b
refs/heads/master
2021-05-12T02:47:59.678305
2018-02-02T21:26:32
2018-02-02T21:26:32
117,597,015
0
0
MIT
2018-01-15T22:43:24
2018-01-15T21:25:42
C++
UTF-8
C++
false
false
467
h
#pragma once using namespace std; class BazaDanych { public: virtual void odczyt(sqlite3 *db) = 0; //wyswietla wszystkie znaczace dane w odpowiedni sposob + trzeba pamietac o filtrze virtual void zapisAdd(sqlite3 *db) = 0; //jezeli bool edycja jest true zapisuje edtyowane dane do bazy virtual void dodaj(sqlite3 *db) = 0; //edycja danych z natychmiastowym zapisem do bazy virtual void zapisNew(sqlite3 *db) = 0; //zapisuje do tablicy jako nowe dane };
[ "Grzybu@DESKTOP-EPN1FT2" ]
Grzybu@DESKTOP-EPN1FT2
054f68e0468b37258067511a69ffd3ba9a984ead
c6e1059e5e0b3b616f8b9095e17f56669f394666
/src/hash.h
303499a2d2308f3b945e568015ba7d7c8970770b
[ "MIT" ]
permissive
ZalemCoin/ZalemCoin
10d72ecfdde25346d261ee9e501bba1816da2ba6
736939aa1995bdaac8d87196cb851753730aafa7
refs/heads/master
2020-05-03T17:11:05.215229
2019-04-06T09:32:50
2019-04-06T09:32:50
178,739,863
0
0
null
null
null
null
UTF-8
C++
false
false
5,484
h
// 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. #ifndef BITCOIN_HASH_H #define BITCOIN_HASH_H #include "uint256.h" #include "serialize.h" #include <openssl/sha.h> #include <openssl/ripemd.h> #include "crypto/common/ripemd160.h" #include "crypto/common/sha256.h" #include <vector> /** A hasher class for Zalem-Coin's 256-bit hash (double SHA-256). */ class CHash256 { private: CSHA256 sha; public: static const size_t OUTPUT_SIZE = CSHA256::OUTPUT_SIZE; void Finalize(unsigned char hash[OUTPUT_SIZE]) { unsigned char buf[sha.OUTPUT_SIZE]; sha.Finalize(buf); sha.Reset().Write(buf, sha.OUTPUT_SIZE).Finalize(hash); } CHash256& Write(const unsigned char *data, size_t len) { sha.Write(data, len); return *this; } CHash256& Reset() { sha.Reset(); return *this; } }; /** A hasher class for Zalem-Coin's 160-bit hash (SHA-256 + RIPEMD-160). */ class CHash160 { private: CSHA256 sha; public: static const size_t OUTPUT_SIZE = CRIPEMD160::OUTPUT_SIZE; void Finalize(unsigned char hash[OUTPUT_SIZE]) { unsigned char buf[sha.OUTPUT_SIZE]; sha.Finalize(buf); CRIPEMD160().Write(buf, sha.OUTPUT_SIZE).Finalize(hash); } CHash160& Write(const unsigned char *data, size_t len) { sha.Write(data, len); return *this; } CHash160& Reset() { sha.Reset(); return *this; } }; template<typename T1> inline uint256 Hash(const T1 pbegin, const T1 pend) { static unsigned char pblank[1]; uint256 hash1; SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1); uint256 hash2; SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2); return hash2; } class CHashWriter { private: SHA256_CTX ctx; public: int nType; int nVersion; void Init() { SHA256_Init(&ctx); } CHashWriter(int nTypeIn, int nVersionIn) : nType(nTypeIn), nVersion(nVersionIn) { Init(); } CHashWriter& write(const char *pch, size_t size) { SHA256_Update(&ctx, pch, size); return (*this); } // invalidates the object uint256 GetHash() { uint256 hash1; SHA256_Final((unsigned char*)&hash1, &ctx); uint256 hash2; SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2); return hash2; } template<typename T> CHashWriter& operator<<(const T& obj) { // Serialize to this stream ::Serialize(*this, obj, nType, nVersion); return (*this); } }; template<typename T1, typename T2> inline uint256 Hash(const T1 p1begin, const T1 p1end, const T2 p2begin, const T2 p2end) { static unsigned char pblank[1]; uint256 hash1; SHA256_CTX ctx; SHA256_Init(&ctx); SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0])); SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0])); SHA256_Final((unsigned char*)&hash1, &ctx); uint256 hash2; SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2); return hash2; } template<typename T1, typename T2, typename T3> inline uint256 Hash(const T1 p1begin, const T1 p1end, const T2 p2begin, const T2 p2end, const T3 p3begin, const T3 p3end) { static unsigned char pblank[1]; uint256 hash1; SHA256_CTX ctx; SHA256_Init(&ctx); SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0])); SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0])); SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0])); SHA256_Final((unsigned char*)&hash1, &ctx); uint256 hash2; SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2); return hash2; } template<typename T> uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION) { CHashWriter ss(nType, nVersion); ss << obj; return ss.GetHash(); } template<typename T1> inline uint160 Hash160(const T1 pbegin, const T1 pend) { static unsigned char pblank[1]; uint256 hash1; SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1); uint160 hash2; RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2); return hash2; } inline uint160 Hash160(const std::vector<unsigned char>& vch) { return Hash160(vch.begin(), vch.end()); } typedef struct { SHA512_CTX ctxInner; SHA512_CTX ctxOuter; } HMAC_SHA512_CTX; int HMAC_SHA512_Init(HMAC_SHA512_CTX *pctx, const void *pkey, size_t len); int HMAC_SHA512_Update(HMAC_SHA512_CTX *pctx, const void *pdata, size_t len); int HMAC_SHA512_Final(unsigned char *pmd, HMAC_SHA512_CTX *pctx); void BIP32Hash(const unsigned char chainCode[32], unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]); #endif
[ "zalemcoin@gmail.com" ]
zalemcoin@gmail.com
3544913d2173b562e4fcb21595647bff91689070
0121fa6992c92bea9dc60b51ccde12cfe57f601c
/functions.cpp
0c71faa4bc4e410e027c886ec779d7c574d606ca
[]
no_license
NimbusSkye/tictactoe
fa21e9987185bd516260dea9bc3a94ed14288e69
50672848f189f7b43dbe3241e1150d39e060937f
refs/heads/master
2020-12-26T14:30:12.669510
2020-02-24T03:02:28
2020-02-24T03:02:28
237,538,060
0
0
null
null
null
null
UTF-8
C++
false
false
8,172
cpp
#include "functions.h" using namespace std; bool checkIfLegal (int cellNbre, char board[]) { return (cellNbre > 0 && cellNbre < 28 && board[cellNbre-1]!='X' && board[cellNbre-1]!='O'); } void displaySpaces (int a, int b, char board[]) { //Display X or O, otherwise cell number for (int i = a; i <= b; i++) { switch (board[i - 1]) { case 'X': cout << 'X'; break; case 'O': cout << 'O'; break; default: cout << i; } if (i==b) break; cout << " | "; } } char checkRow (char board[]) { //Check rows like 1-2-3 for (int i = 0; i <=24; i+=3) { int player = 0; int cpu = 0; for (int j=i; j<i+3; j++) { switch (board[j]) { case 'X': player++; break; case 'O': cpu++; } } if (player==3) return 'p'; if (cpu==3) return 'c'; } return 'n'; } char checkColumn (char board[]) { //Check columns like 1-4-7 for (int i=0; i<=18; i+=9) { for (int j = i; j < i + 3; j++) { int player = 0; int cpu = 0; for (int k=j; k<=j+6; k+=3) { switch (board[k]) { case 'X': player++; break; case 'O': cpu++; } } if (player == 3) return 'p'; if (cpu == 3) return 'c'; } } return 'n'; } char checkDiagonal (char board[]) { //Check rightward diagonals, e.g. 1-5-9 for (int i = 0; i <= 18; i += 9) { int player = 0; int cpu = 0; for (int j = i; j <= i + 8; j += 4) { switch (board[j]) { case 'X': player++; break; case 'O': cpu++; } } if (player == 3) return 'p'; if (cpu == 3) return 'c'; } //Check leftward diagonals, e.g. 3-5-7 for (int i=2; i<=20; i+=9) { int player = 0; int cpu = 0; for (int j = i; j <= i + 4; j += 2) { switch (board[j]) { case 'X': player++; break; case 'O': cpu++; } } if (player == 3) return 'p'; if (cpu == 3) return 'c'; } return 'n'; } char checkAdjacent (char board[]) { //Check for patterns like 1-9-19 (same cell on each board) for (int i = 0; i < 9; i++) { int player = 0; int cpu = 0; for (int j = i; j <= i + 18; j += 9) { switch (board[j]) { case 'X': player++; break; case 'O': cpu++; } } if (player == 3) return 'p'; if (cpu == 3) return 'c'; } return 'n'; } char checkSkewLines (char board[]) { //Check for patterns like 1-11-21 (row across all 3 boards) for (int i=0; i<=6; i+=3) { int player=0; int cpu=0; for (int j=i; j<=i+20; j+=10) { switch (board[j]) { case 'X': player++; break; case 'O': cpu++; } } if (player==3) return 'p'; if (cpu==3) return 'c'; } //Check for patterns like 1-13-25 (column across all 3 boards) for (int i=0; i<3; i++) { int player=0; int cpu=0; for (int j=i; j<=i+24; j+=12) { switch (board[j]) { case 'X': player++; break; case 'O': cpu++; } } if (player==3) return 'p'; if (cpu==3) return 'c'; } //Check for patterns 1-14-27 and 3-14-25 if (board[0]=='X' && board[13]=='X' && board[26]=='X') return 'p'; if (board[0]=='O' && board[13]=='O' && board[26]=='O') return 'c'; if (board[2]=='X' && board[13]=='X' && board[24]=='X') return 'p'; if (board[2]=='O' && board[13]=='O' && board[24]=='O') return 'c'; return 'n'; } bool checkWinner (char board[]) { //Check each row switch (checkRow(board)) { case 'p': return true; case 'c': return true; } //Check each column switch (checkColumn(board)) { case 'p': return true; case 'c': return true; } //Check each diagonal switch (checkDiagonal(board)) { case 'p': return true; case 'c': return true; } //Check each adjacent pattern e.g. 1-10-19 switch (checkAdjacent(board)) { case 'p': return true; case 'c': return true; } //Check each skew line e.g. 1-11-21, 1-13-25, 1-14-27, 3-14-25 switch (checkSkewLines(board)) { case 'p': return true; case 'c': return true; } return false; } void playerMove(char board[]) { int m=1; while(true) { cout << "Type a cell number: "; cin >> m; if (checkIfLegal(m, board)) break; cout << "Illegal move." << endl; } board[m - 1] = 'X'; } void displayBoard (char board[]) { displaySpaces(1, 3, board); cout << " "; displaySpaces(10, 12, board); cout << " "; displaySpaces(19, 21, board); cout << endl << "---------------------------------------" << endl; displaySpaces(4, 6, board); cout << " "; displaySpaces(13, 15, board); cout << " "; displaySpaces(22, 24, board); cout << " "; cout << endl << "---------------------------------------" << endl; displaySpaces(7, 9, board); cout << " "; displaySpaces(16, 18, board); cout << " "; displaySpaces(25, 27, board); cout << " "; } void greetAndInstruct() { cout << "Hello and welcome to the Tic-Tac-Toe challenge: Player against Computer." << endl; cout << "The board is numbered from 1 to 27 as per the following:" << endl; cout << "1 | 2 | 3 10 | 11 | 12 19 | 20 | 21" << endl; cout << "--------- ------------ ------------" << endl; cout << "4 | 5 | 6 13 | 14 | 15 22 | 23 | 24" << endl; cout << "--------- ------------ ------------" << endl; cout << "7 | 8 | 9 16 | 17 | 19 25 | 26 | 27" << endl; cout << "Player starts first. Simply input the number of the cell you want to occupy. Player’s move is marked with X. Computer’s move is marked with O." << endl; cout << "Start? (y/n):"; char ans; cin >> ans; char board[27]; if (ans == 'y') displayBoard(board); else exit(0); } void computerMove(char board[]) { char test[27]; for (int i = 0; i < 27; i++) { //Protect original board by copying it into another array copy(board, board+27, test); //Check if each move is legal using the test array, then commit if that cell is a win condition if (checkIfLegal(i+1, test)) { //Check for computer's win condition test[i]='O'; if (checkWinner(test)) { board[i] = 'O'; return; } //Check for player's win condition test[i]='X'; if (checkWinner(test)) { board[i]='O'; return; } } } //If no cell is a win condition, make a random move for (int i=0; i<27; i++) { if (checkIfLegal(i+1, board)) { board[i] = 'O'; return; } } }
[ "alexwang6671@gmail.com" ]
alexwang6671@gmail.com
1e43c5892df8fd7b948096c0d3651504c41a6a6d
d41db842dcb78daff50cb277c02ee1bd08ebbca9
/include/pybind11_generics/list.h
cf89e0e1620dcc95807212521c56992610b70215
[ "Apache-2.0" ]
permissive
bluecheetah/pybind11_generics
f6a181814ca36d297df14a4bee1d8bab085aafc4
a4294f555c79f8f4b4a871e2b4eda71102a33a0f
refs/heads/master
2021-08-05T16:54:11.676029
2021-07-21T17:24:41
2021-07-21T17:24:41
220,520,944
0
1
Apache-2.0
2019-11-08T17:58:34
2019-11-08T17:58:34
null
UTF-8
C++
false
false
2,686
h
/* Copyright 2018 Eric Chang 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 PYBIND11_GENERICS_LIST_H #define PYBIND11_GENERICS_LIST_H #include <type_traits> #include <pybind11_generics/cast_input_iterator.h> #include <pybind11_generics/type_name.h> namespace py = pybind11; namespace pybind11_generics { using list_base = py::list; template <typename T> class List : public list_base { public: using value_type = std::remove_reference_t<T>; using const_reference = const value_type &; using base_iter_type = py::detail::list_iterator; using const_iterator = cast_input_iterator<value_type, base_iter_type>; template <typename V> using IsT = std::enable_if_t<std::is_same_v<value_type, std::remove_cv_t<std::remove_reference_t<V>>>, int>; // inherit check_ so we can check if a python object matches this generic using list_base::check_; using list_base::list_base; value_type operator[](size_t index) const { PyObject *result = PyList_GetItem(ptr(), static_cast<Py_ssize_t>(index)); if (!result) { throw py::error_already_set(); } return cast_from_handle<value_type>(py::handle(result)); } const_iterator begin() const { return const_iterator(list_base::begin(), list_base::end()); } const_iterator end() const { return const_iterator(list_base::end(), list_base::end()); } template <class V, IsT<V> = 0> void append(V &&val) const { list_base::append(std::forward<V>(val)); } template <class V, IsT<V> = 0> void push_back(V &&val) { list_base::append(std::forward<V>(val)); } template <class... Args> void emplace_back(Args &&...args) { push_back(value_type(std::forward<Args>(args)...)); } // empty method for compatibility reason void reserve(std::size_t size) {} }; } // namespace pybind11_generics namespace pybind11 { namespace detail { template <typename T> struct handle_type_name<pybind11_generics::List<T>> { static constexpr auto name = _("List[") + py::detail::make_caster<T>::name + _("]"); }; } // namespace detail } // namespace pybind11 #endif
[ "pkerichang@gmail.com" ]
pkerichang@gmail.com
fd8a4215a63153417120a52c504c077c01d9b05a
b3c42c5a3fb73a48793795f6089fa80888c81d88
/src/utils/Geometry.hpp
8d2ec2fd56bbdef3ebacb17dc03e72f929e15e28
[]
no_license
Tandaradei/conrast
cdd247d089f7725a8f1e1f2eefc32fe7ec1029b2
a8e4a2e0f0885020e9ab80d33c00cf684f8addbc
refs/heads/master
2020-05-09T23:34:39.774926
2019-07-08T17:42:37
2019-07-08T17:42:37
181,505,858
0
0
null
null
null
null
UTF-8
C++
false
false
400
hpp
#ifndef GEOMETRY_HPP #define GEOMETRY_HPP #include "utils/Vec.hpp" namespace conrast { namespace utils { namespace geometry { // 2D float calc2DTriangleArea(Vec2f a, Vec2f b, Vec2f c); Vec3f calc2DBarycentric(Vec2f a, Vec2f b, Vec2f c, Vec2f p); // 3D float calc3DTriangleArea(Vec3f a, Vec3f b, Vec3f c); Vec3f calc3DBarycentric(Vec3f a, Vec3f b, Vec3f c, Vec3f p); } } } #endif // GEOMETRY_HPP
[ "thevolut@gmail.com" ]
thevolut@gmail.com
4eaa8ab28105545e31f6fc67a58213a8f9745826
e84e19c5d52f511ae280bb02d2febb8e0650a116
/code1491.cpp
76e71dc7824cdcbf91c700bb1ba2da6e96416254
[]
no_license
AlJamilSuvo/LeetCode
2e3afe0c588d003aa15ea3eb08a8d2ca381c35dd
9ad26f2974ad4a41a9654a5564fe1ad27ae2463c
refs/heads/master
2022-03-15T15:43:21.826485
2022-03-04T20:40:50
2022-03-04T20:40:50
174,458,244
1
0
null
null
null
null
UTF-8
C++
false
false
464
cpp
#include <bits/stdc++.h> using namespace std; class Solution { public: double average(vector<int> &salary) { int mx = INT_MIN; int mn = INT_MAX; double sum; int cnt = salary.size() - 2; for (int i = 0; i < salary.size(); i++) { mx = max(mx, salary[i]); mn = min(mn, salary[i]); sum += salary[i]; } sum = sum - (mx + mn); return sum / cnt; } };
[ "aljamilsuvo@gmail.com" ]
aljamilsuvo@gmail.com
fa4f6c340065ef57ca57cc0fdcc0bd28dbed2bb8
7c81b38038be712d102b98eb6c4842d9db8b768d
/BOJ/14918.cpp
2658bd2019cdf8b3fe0a2d2e4d8dc392035310f0
[]
no_license
joonas-yoon/PS
13d1e2ce2e4d105080793a37e7b4fb8632e6af36
4d03278ade4665f34d6dfe089234df69450d4edc
refs/heads/master
2020-12-02T22:17:52.108600
2020-04-05T02:30:24
2020-04-05T02:30:24
96,108,163
1
0
null
2019-08-19T23:59:13
2017-07-03T12:24:49
C++
UTF-8
C++
false
false
111
cpp
#include <cstdio> int main(){ int a, b; scanf("%d %d", &a, &b); printf("%d", a+b); return 0; }
[ "joonas.yoon@gmail.com" ]
joonas.yoon@gmail.com
9d9c45c2505341eb0a5b014ff869f605a7eddbb6
71d75eb27f92355f3726dcdc82404058a49037cf
/Baekjoon/2775.cpp
2b2b0ca6f29f85abaa597af3bc1bdcaf6815e198
[]
no_license
JunsikKong/PS
7f9c1a5ba0acf01b67958cb8ca2ed525262d6451
87c5bd3e9e06fbf84fa679b7505f1e17ee58ff3c
refs/heads/master
2023-07-09T04:25:37.728024
2021-08-17T17:23:21
2021-08-17T17:23:21
314,890,832
0
0
null
null
null
null
UTF-8
C++
false
false
425
cpp
#include <iostream> using namespace std; int sumMan(int a, int b); int main(void) { cin.tie(NULL); ios::sync_with_stdio(false); int t, k, n; cin >> t; for (int i = 0; i < t; i++) { cin >> k >> n; cout << sumMan(k, n) << '\n'; } return 0; } int sumMan(int a, int b) { int sum = 0; for (int i = 1; i <= b; i++) { if (a == 1) { sum += i; } else { sum += sumMan(a - 1, i); } } return sum; }
[ "workjs1124@gmail.com" ]
workjs1124@gmail.com
252b7be953e8587cef8db4bfbfed4187e77a9b47
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
/chrome/browser/ui/autofill/autofill_popup_controller.h
8d7612a4d0ad4148ef41fe17ec39981756ba84d5
[ "BSD-3-Clause" ]
permissive
massnetwork/mass-browser
7de0dfc541cbac00ffa7308541394bac1e945b76
67526da9358734698c067b7775be491423884339
refs/heads/master
2022-12-07T09:01:31.027715
2017-01-19T14:29:18
2017-01-19T14:29:18
73,799,690
4
4
BSD-3-Clause
2022-11-26T11:53:23
2016-11-15T09:49:29
null
UTF-8
C++
false
false
2,571
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_AUTOFILL_AUTOFILL_POPUP_CONTROLLER_H_ #define CHROME_BROWSER_UI_AUTOFILL_AUTOFILL_POPUP_CONTROLLER_H_ #include <stddef.h> #include <vector> #include "base/compiler_specific.h" #include "base/strings/string16.h" #include "build/build_config.h" #include "chrome/browser/ui/autofill/autofill_popup_view_delegate.h" #include "third_party/skia/include/core/SkColor.h" namespace autofill { class AutofillPopupLayoutModel; struct Suggestion; // This interface provides data to an AutofillPopupView. class AutofillPopupController : public AutofillPopupViewDelegate { public: // Recalculates the height and width of the popup and triggers a redraw. virtual void UpdateBoundsAndRedrawPopup() = 0; // Accepts the suggestion at |index|. virtual void AcceptSuggestion(size_t index) = 0; // Returns true if the given index refers to an element that is a warning // rather than an Autofill suggestion. virtual bool IsWarning(size_t index) const = 0; // Returns the number of lines of data that there are. virtual size_t GetLineCount() const = 0; // Returns the suggestion or pre-elided string at the given row index. virtual const autofill::Suggestion& GetSuggestionAt(size_t row) const = 0; virtual const base::string16& GetElidedValueAt(size_t row) const = 0; virtual const base::string16& GetElidedLabelAt(size_t row) const = 0; // Returns whether the item at |list_index| can be removed. If so, fills // out |title| and |body| (when non-null) with relevant user-facing text. virtual bool GetRemovalConfirmationText(int index, base::string16* title, base::string16* body) = 0; // Removes the suggestion at the given index. virtual bool RemoveSuggestion(int index) = 0; // Returns the background color of the row item according to its |index|, or // transparent if the default popup background should be used. virtual SkColor GetBackgroundColorForRow(int index) const = 0; // Returns the index of the selected line. A line is "selected" when it is // hovered or has keyboard focus. virtual int selected_line() const = 0; virtual const AutofillPopupLayoutModel& layout_model() const = 0; protected: ~AutofillPopupController() override {} }; } // namespace autofill #endif // CHROME_BROWSER_UI_AUTOFILL_AUTOFILL_POPUP_CONTROLLER_H_
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
1ecce9e56257f4631b8ee6b925d9e860815167dc
948d555823c2d123601ff6c149869be377521282
/SDK/SoT_BP_FishingFish_Plentifin_05_Colour_05_Watery_classes.hpp
7a21964d80b3bf808483ea0bca8b7f3f0fdc7cf2
[]
no_license
besimbicer89/SoT-SDK
2acf79303c65edab01107ab4511e9b9af8ab9743
3a4c6f3b77c1045b7ef0cddd064350056ef7d252
refs/heads/master
2022-04-24T01:03:37.163407
2020-04-27T12:45:47
2020-04-27T12:45:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
820
hpp
#pragma once // SeaOfThieves (1.6.4) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_FishingFish_Plentifin_05_Colour_05_Watery.BP_FishingFish_Plentifin_05_Colour_05_Watery_C // 0x0000 (0x0900 - 0x0900) class ABP_FishingFish_Plentifin_05_Colour_05_Watery_C : public ABP_FishingFish_Plentifin_05_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_FishingFish_Plentifin_05_Colour_05_Watery.BP_FishingFish_Plentifin_05_Colour_05_Watery_C"); return ptr; } void UserConstructionScript(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "getpeyton@gmail.com" ]
getpeyton@gmail.com
f96827fa46f0d1184364eed542b3965174971f46
cf3f075bd3504e6b8e3d2b3227cc242f0508a74a
/qmlpagelayoutdemo/third-part/qxpack/indcom/_depre/geometry/qxpack_ic_point.hxx
2d8aa1122068853d6ab2d2cf218f213ca68983e2
[]
no_license
liuzitong/demos
91e27a52186014788f47883c1205c50a6a137487
9afea1317cb88377752470ba7815f16cd6da23f8
refs/heads/master
2022-08-23T14:59:34.692652
2020-05-20T03:25:47
2020-05-21T05:51:42
265,776,097
0
0
null
null
null
null
UTF-8
C++
false
false
6,027
hxx
// ///////////////////////////////////////////////////////////////////// /*! @file qxpack_ic_Point @author night wing @date 2018/11 @brief Point object, describe a 2D Point @version 0.1.0 */ // ///////////////////////////////////////////////////////////////////// #ifndef QXPACK_IC_Point_HXX #define QXPACK_IC_Point_HXX /*! @addtogroup QxPack @{ */ /*! @addtogroup indcom @{ */ /*! @addtogroup gemotry_Exported_Classes @{ */ #include <qxpack/indcom/common/qxpack_ic_def.h> #include <qxpack/indcom/common/qxpack_ic_global.hxx> #include <cassert> namespace QxPack { // //////////////////////////////////////////////////////// /*! * @brief integer object */ // //////////////////////////////////////////////////////// class QXPACK_IC_API IcPoint { public: IcPoint( ) { m_x = m_y = 0; } IcPoint( const IcPoint &p ) { m_x = p.m_x; m_y = p.m_y; } IcPoint( int x, int y ) { m_x = x; m_y = y; } IcPoint& operator=( const IcPoint &p ) { m_x = p.m_x; m_y = p.m_y; return *this; } ~IcPoint( ) { } inline bool isNull() const { return ( m_x == 0 && m_y == 0 ); } inline int x() const { return m_x; } inline int y() const { return m_y; } inline int & rx() { return m_x; } inline int & ry() { return m_y; } inline void setX( int x ) { m_x = x; } inline void setY( int y ) { m_y = y; } inline IcPoint& operator+=( const IcPoint &p ) { m_x += p.m_x; m_y += p.m_y; return *this; } inline IcPoint& operator-=( const IcPoint &p ) { m_x -= p.m_x; m_y -= p.m_y; return *this; } inline IcPoint& operator*=( int c ) { m_x *= c; m_y *= c; return *this; } inline IcPoint& operator*=( double c ) { m_x = QxPack::round( m_x * c ); m_y = QxPack::round( m_y * c ); return *this; } inline IcPoint& operator/=( int c ) { m_x /= c; m_y /= c; return *this; } inline IcPoint& operator/=( double c ) { m_x = QxPack::round( m_x / c ); m_y = QxPack::round( m_y / c ); return *this; } friend inline bool operator==( const IcPoint &p1, const IcPoint &p2 ) { return ( p1.m_x == p2.m_x && p1.m_y == p2.m_y ); } friend inline bool operator!=( const IcPoint &p1, const IcPoint &p2 ) { return ( p1.m_x != p2.m_x || p1.m_y != p2.m_y ); } friend inline const IcPoint operator+( const IcPoint &p1, const IcPoint &p2 ) { return IcPoint( p1.m_x + p2.m_x, p1.m_y + p2.m_y ); } friend inline const IcPoint operator-( const IcPoint &p1, const IcPoint &p2 ) { return IcPoint( p1.m_x - p2.m_x, p1.m_y - p2.m_y ); } friend inline const IcPoint operator*( const IcPoint &p1, double m ) { return IcPoint( QxPack::round( p1.m_x * m ), QxPack::round( p1.m_y * m )); } friend inline const IcPoint operator*( double m, const IcPoint &p1 ) { return IcPoint( QxPack::round( p1.m_x * m ), QxPack::round( p1.m_y * m )); } friend inline const IcPoint operator*( const IcPoint &p1, int m ) { return IcPoint( p1.m_x * m, p1.m_y * m ); } friend inline const IcPoint operator*( int m, const IcPoint &p1 ) { return IcPoint( p1.m_x * m, p1.m_y * m ); } friend inline const IcPoint operator+( const IcPoint &p ) { return p; } friend inline const IcPoint operator-( const IcPoint &p ) { return IcPoint( - p.m_x, - p.m_y ); } friend inline const IcPoint operator/( const IcPoint &p, int d ) { return IcPoint( p.m_x / d, p.m_y / d ); } friend inline const IcPoint operator/( const IcPoint &p, double d ) { return IcPoint( QxPack::round( p.m_x / d ), QxPack::round( p.m_y / d ) ); } private: int m_x, m_y; }; // ///////////////////////////////////////////////////////////// /*! * @brief IcPoint 2D float */ // ///////////////////////////////////////////////////////////// class QXPACK_IC_API IcPointF { public: IcPointF( ) { m_x = m_y = 0; } IcPointF( const IcPointF &p ) { m_x = p.m_x; m_y = p.m_y; } IcPointF( float x, float y ) { m_x = x; m_y = y; } IcPointF& operator=( const IcPointF &p ) { m_x = p.m_x; m_y = p.m_y; return *this; } ~IcPointF( ) { } inline bool isNull( ) const { return QxPack::isNull( m_x ) && QxPack::isNull( m_y ); } inline float x() const { return m_x; } inline float y() const { return m_y; } inline float& rx() { return m_x; } inline float& ry() { return m_y; } inline void setX( float x ) { m_x = x; } inline void setY( float y ) { m_y = y; } inline IcPointF& operator+=( const IcPointF &p ) { m_x += p.m_x; m_y += p.m_y; return *this; } inline IcPointF& operator-=( const IcPointF &p ) { m_x -= p.m_x; m_y -= p.m_y; return *this; } inline IcPointF& operator*=( float c ) { m_x *= c; m_y *= c; return *this; } inline IcPointF& operator/=( float c ) { m_x /= c; m_y /= c; return *this; } friend inline bool operator==( const IcPointF &p1, const IcPointF &p2 ) { return QxPack::fuzzyCompare( p1.m_x, p2.m_x ) && QxPack::fuzzyCompare( p1.m_y, p2.m_y ); } friend inline bool operator!=( const IcPointF &p1, const IcPointF &p2 ) { return !QxPack::fuzzyCompare( p1.m_x, p2.m_x ) || !QxPack::fuzzyCompare( p1.m_y, p2.m_y ); } friend inline const IcPointF operator+( const IcPointF &p1, const IcPointF &p2 ) { return IcPointF( p1.m_x + p2.m_x, p1.m_y + p2.m_y ); } friend inline const IcPointF operator-( const IcPointF &p1, const IcPointF &p2 ) { return IcPointF( p1.m_x - p2.m_x, p1.m_y - p2.m_y ); } friend inline const IcPointF operator*( const IcPointF &p1, float m ) { return IcPointF( p1.m_x * m, p1.m_y * m ); } friend inline const IcPointF operator*( float m, const IcPointF &p1 ) { return IcPointF( p1.m_x * m, p1.m_y * m ); } friend inline const IcPointF operator+( const IcPointF &p ) { return p; } friend inline const IcPointF operator-( const IcPointF &p ) { return IcPointF( - p.m_x, - p.m_y ); } friend inline const IcPointF operator/( const IcPointF &p, float d ) { return IcPointF( p.m_x / d, p.m_y / d ); } private: float m_x, m_y; }; } /*! @} */ /*! @} */ /*! @} */ #endif
[ "liu.zi.tong@hotmail.com" ]
liu.zi.tong@hotmail.com
6585d800f05c7ddbfdb434e2e6325cd173e5be3e
fec64eb2ac4b13f1031db830360fde1588368a48
/example/dsdana/source/DSDdatabase.hpp
2fff372535e2ba5aa24649506dee57dce98ed581
[ "MIT" ]
permissive
goroyabu/anlpy
2ff81164395ddb8fd02814ea3c598172bd9b551b
2d5d65b898d31d69f990e973cbfdbabd8cb0a15c
refs/heads/master
2021-12-06T21:13:33.180610
2021-11-19T09:49:41
2021-11-19T09:49:41
245,841,843
0
0
null
null
null
null
UTF-8
C++
false
false
6,885
hpp
/** @file DSDdatabase.hpp @date 2020/04/11 @author @detail Automatically generated by make_anlpy_project.sh 1.0.0 **/ #ifndef DSDdatabase_hpp #define DSDdatabase_hpp #include <VANL_Module.hpp> #include <vector> #include <algorithm> #include <cmath> class DSDdatabase : public anl::VANL_Module { public: DSDdatabase(); ~DSDdatabase(); int mod_bgnrun() override; int mod_ana() override; int mod_endrun() override; class data_element { public: data_element() : asicid(0), asicch(0), detid(0), stripid(0), material(-1), posx(0), posy(0), posz(0), widthx(0), widthy(0), widthz(0), badch(0), ethre(0), is_xside(false), is_badch(false) {} data_element(const data_element& org) : asicid(org.asicid), asicch(org.asicch), detid(org.detid), stripid(org.stripid), material(org.material), posx(org.posx), posy(org.posy), posz(org.posz), widthx(org.widthx), widthy(org.widthy), widthz(org.widthz), badch(org.badch), ethre(org.ethre), is_xside(org.is_xside), is_badch(org.is_badch) { for(auto p : org.calparam) calparam.emplace_back(p); } data_element &operator=(const data_element &org) { asicid = org.asicid; asicch = org.asicch; detid = org.detid; stripid = org.stripid; material = org.material; posx = org.posx; posy = org.posy; posz = org.posz; widthx = org.widthx; widthy = org.widthy; widthz = org.widthz; badch = org.badch; ethre = org.ethre; is_xside = org.is_xside; is_badch = org.is_badch; for(auto p : org.calparam) calparam.emplace_back(p); return *this; } ~data_element() {} int print(); data_element* setx(const float pos, const float width) { posx = pos; widthx = width; return this; } data_element* sety(const float pos, const float width) { posy = pos; widthy = width; return this; } data_element* setz(const float pos, const float width) { posz = pos; widthz = width; return this; } data_element* set_status (const int badch, const float ethre, const bool is_xside) { this->badch = badch; this->ethre = ethre; this->is_xside = is_xside; if ( badch == 0 ) this->is_badch = false; else this->is_badch = true; return this; } data_element* set_material(const int mate) { this->material = mate; return this; } inline double epi(const float pha) { double value = 0.0; int nparam = (int)this->calparam.size(); for(int i=0; i<nparam; ++i) value += calparam[i]*std::pow(pha, i); return value; } int asicid, asicch, detid, stripid, material; float posx, posy, posz; float widthx, widthy, widthz; int badch; float ethre; bool is_xside, is_badch; std::vector<float> calparam; }; protected: std::vector<data_element*> database; data_element maxinfo; data_element mininfo; std::map< std::pair<int, int>, std::pair<int, int> > strip_map; std::map< std::pair<int, int>, int> detid_stripid_to_index_map; std::map<int, int> stripid_to_index_map; std::vector<int> list_of_asicid; std::vector<int> list_of_detid; std::vector<int> list_of_stripid; template<typename T> bool exist(const std::vector<T>& vec, const T& elem) { auto itr = std::find(vec.begin(), vec.end(), elem); return itr != vec.end(); } public: std::vector<int> GetListOfAsicids(); int GetNasics(); bool ExistAsicid(const int asicid); std::vector<int> GetListOfDetids(); int GetNdetectors(); bool ExistDetid(const int detid); std::vector<int> GetListOfStrips(); int GetNstrips(); bool ExistStrip(int stripid); inline int GetNallch() { return GetNstrips(); } int GetNxside(); inline int GetNyside() { return GetNstrips() - GetNxside(); } std::pair<int, int> FindStrip(int asicid, int asicch); int GetStripid(int asicid, int asicch) { return FindStrip(asicid, asicch).second; } /** @func GetIndex @return Index in the list of strips correponding to the 'stripid'. @return -1 if 'stripid' is not found. **/ int GetIndex(const int stripid); int GetIndex(const std::pair<int,int>& detid_stripid); data_element* GetDataElement(const int index); // { // return database[ index ]; // } int GetAsicid(const int stripid); int GetAsicch(const int stripid); int GetDetid(const int stripid); int GetMaterial(const int stripid); float GetPosx(const int stripid); float GetPosy(const int stripid); float GetPosz(const int stripid); float GetWidthx(const int stripid); float GetWidthy(const int stripid); float GetWidthz(const int stripid); float GetEthre(const int stripid); bool IsBadch(const int stripid); bool IsXside(const int stripid); virtual float GetEPI(const int stripid, const float pha); int GetAsicid(const std::pair<int,int>& detid_stripid); int GetAsicch(const std::pair<int,int>& detid_stripid); int GetDetid(const std::pair<int,int>& detid_stripid); int GetMaterial(const std::pair<int,int>& detid_stripid); float GetPosx(const std::pair<int,int>& detid_stripid); float GetPosy(const std::pair<int,int>& detid_stripid); float GetPosz(const std::pair<int,int>& detid_stripid); float GetWidthx(const std::pair<int,int>& detid_stripid); float GetWidthy(const std::pair<int,int>& detid_stripid); float GetWidthz(const std::pair<int,int>& detid_stripid); float GetEthre(const std::pair<int,int>& detid_stripid); bool IsBadch(const std::pair<int,int>& detid_stripid); bool IsXside(const std::pair<int,int>& detid_stripid); virtual float GetEPI(const std::pair<int,int>& detid_stripid, const float pha); int GetDetectorPosz(const int detid); int GetDetectorWidthz(const int detid); int GetAsicidMax() const { return maxinfo.asicid; } int GetDetidMax() const { return maxinfo.detid; } int GetStripidMax() const { return maxinfo.stripid; } int GetPosxMax() const { return maxinfo.posx; } int GetPosyMax() const { return maxinfo.posy; } int GetPoszMax() const { return maxinfo.posz; } int GetAsicidMin() const { return mininfo.asicid; } int GetDetidMin() const { return mininfo.detid; } int GetStripidMin() const { return mininfo.stripid; } int GetPosxMin() const { return mininfo.posx; } int GetPosyMin() const { return mininfo.posy; } int GetPoszMin() const { return mininfo.posz; } }; #endif
[ "goro.yabu@ipmu.jp" ]
goro.yabu@ipmu.jp
eabedb598f05b7e34bc8f2d27e18f29aeea6746a
9ba9f37abc13771bc3cdceeb54d1dad5e36ed857
/imageProcessor/imageProcessor.h
ec2ad9771adae0dfda549ee4ba55014134d66a82
[]
no_license
hywwqq/Android
9874b4da3fcbeddcd4bb42368b3a0a4124709ae8
13b7b6ee25fcf9907dcafacd3f49693f7c41de22
refs/heads/master
2016-09-06T06:19:00.127017
2014-11-14T13:20:56
2014-11-14T13:20:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,023
h
#ifndef IMAGEPROCESSOR_H #define IMAGEPROCESSOR_H #include <QObject> #include <QString> class ImageProcessorPrivate; class ImageProcessor : public QObject { Q_OBJECT Q_ENUMS(ImageAlgorithm) Q_PROPERTY(QString sourceFile READ sourceFile) Q_PROPERTY(ImageAlgorithm algorithm READ algorithm) public: ImageProcessor(QObject *parent = 0); ~ImageProcessor(); //算法的声明 enum ImageAlgorithm{ Gray = 0, Binarize, Negative, Emboss, Sharpen, Soften, H_Shades, S_Shades, AlgorithmCount }; QString sourceFile() const; ImageAlgorithm algorithm() const; void setTempPath(QString tempPath); //信号量通信 signals: void finished(QString newFile); void progress(int value); public slots: void process(QString file, ImageAlgorithm algorithm); void abort(QString file, ImageAlgorithm algorithm); void abortAll(); private: ImageProcessorPrivate *m_d; }; #endif // IMAGEPROCESSOR_H
[ "hywwqq@163.com" ]
hywwqq@163.com
99418f105317370e7820fe5ab8ea9d986c7f4d27
4b3818f2e48813a300cee36b2f1e87fc47816857
/condition_parser.h
7fe8cdb64c640eae87727d24a3bff0c9b704e39f
[]
no_license
C0DEn1s/DB_of_events
0cff7f82e5152a151772f7d6f5324bb6ec3799f6
6ac341b0fd9cf02412da74d2e14b30798b0cb452
refs/heads/main
2023-02-09T11:16:00.661440
2020-12-19T16:52:48
2020-12-19T16:52:48
322,895,787
0
0
null
null
null
null
UTF-8
C++
false
false
359
h
// // Created by denis on 12.08.2020. // #ifndef FINAL_CONDITION_PARSER_H #define FINAL_CONDITION_PARSER_H #include "node.h" #include "token.h" #include "date.h" #include "test_runner.h" #include <memory> #include <iostream> using namespace std; shared_ptr<Node> ParseCondition(istream& is); void TestParseCondition(); #endif //FINAL_CONDITION_PARSER_H
[ "denis.poroshin98@gmail.com" ]
denis.poroshin98@gmail.com
4c6d37cc65449dd6d39bec1c8df5e06e713f6109
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14289/function14289_schedule_2/function14289_schedule_2.cpp
69c0ae8fc4ca66ece0162388c15532df0f04bfa0
[]
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
998
cpp
#include <tiramisu/tiramisu.h> using namespace tiramisu; int main(int argc, char **argv){ tiramisu::init("function14289_schedule_2"); constant c0("c0", 128), c1("c1", 512), c2("c2", 512); var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i100("i100", 1, c0 - 1), i101("i101", 1, c1 - 1), i102("i102", 1, c2 - 1), i01("i01"), i02("i02"), i03("i03"), i04("i04"); input input0("input0", {i0, i1, i2}, p_int32); computation comp0("comp0", {i100, i101, i102}, (input0(i100, i101, i102) + input0(i100 + 1, i101, i102) + input0(i100 - 1, i101, i102))); comp0.tile(i100, i101, 32, 64, i01, i02, i03, i04); comp0.parallelize(i01); buffer buf00("buf00", {128, 512, 512}, p_int32, a_input); buffer buf0("buf0", {128, 512, 512}, p_int32, a_output); input0.store_in(&buf00); comp0.store_in(&buf0); tiramisu::codegen({&buf00, &buf0}, "../data/programs/function14289/function14289_schedule_2/function14289_schedule_2.o"); return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
5f10545b0f28554db98eac31d421283a0f41a7f6
b199573508893b3c88cc82ac1c870a4753b5c13f
/ConcurrentConsoleApp/dataprocessor.cpp
929efed9ca947221b5d317005ece4f4db65c7ab4
[]
no_license
intprog/ConcurrencyLearningApp
1ac4474c0b7c9f627f44a83d64c98d9c88f68ec4
e611b2249d1f33c14ea8a29369e41d618372fe0d
refs/heads/main
2023-01-24T07:52:21.960953
2020-12-06T20:15:33
2020-12-06T20:15:33
319,115,149
0
0
null
null
null
null
UTF-8
C++
false
false
336
cpp
#include "dataprocessor.h" using namespace std; DataProcessor::DataProcessor(std::promise<std::string> processorPromis): _processorPromise(std::move(processorPromis)) { } void DataProcessor::process(string command) { command += " was processed."; //TODO: add some random waiting _processorPromise.set_value(command); }
[ "pkvl@ukr.net" ]
pkvl@ukr.net
8d6562b2ae81afb5dc3d3a8a5da162bf74b10191
dc5576c815a49fd310e6c599f87eac64d3f99e7d
/src/mbgl/shader/line_vertex.hpp
086100810ea39bf73a25176d7bcc09ab4dee6b97
[ "BSD-3-Clause", "IJG", "LicenseRef-scancode-warranty-disclaimer", "Zlib", "curl", "NCSA", "LicenseRef-scancode-openssl", "OpenSSL", "LicenseRef-scancode-ssleay-windows", "JSON", "ISC", "MIT", "BSL-1.0", "Apache-2.0", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "b...
permissive
sridvijay/mapbox-gl-native
b335d0e4bf045855dff9488b271fcd40103858bb
a4c82b8a3b5e48f3bbccf32be80d45ca78d51515
refs/heads/master
2021-01-12T12:06:35.189058
2016-10-28T21:55:07
2016-10-29T00:10:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,723
hpp
#pragma once #include <mbgl/gl/attribute.hpp> #include <array> #include <cstdint> #include <cmath> namespace mbgl { class LineVertex { public: /* * @param {number} x vertex position * @param {number} y vertex position * @param {number} ex extrude normal * @param {number} ey extrude normal * @param {number} tx texture normal * @param {number} ty texture normal * @param {number} dir direction of the line cap (-1/0/1) */ LineVertex(int16_t x, int16_t y, float ex, float ey, bool tx, bool ty, int8_t dir, int32_t linesofar = 0) : a_pos { static_cast<int16_t>((x * 2) | tx), static_cast<int16_t>((y * 2) | ty) }, a_data { // add 128 to store an byte in an unsigned byte static_cast<uint8_t>(::round(extrudeScale * ex) + 128), static_cast<uint8_t>(::round(extrudeScale * ey) + 128), // Encode the -1/0/1 direction value into the first two bits of .z of a_data. // Combine it with the lower 6 bits of `linesofar` (shifted by 2 bites to make // room for the direction value). The upper 8 bits of `linesofar` are placed in // the `w` component. `linesofar` is scaled down by `LINE_DISTANCE_SCALE` so that // we can store longer distances while sacrificing precision. // Encode the -1/0/1 direction value into .zw coordinates of a_data, which is normally covered // by linesofar, so we need to merge them. // The z component's first bit, as well as the sign bit is reserved for the direction, // so we need to shift the linesofar. static_cast<uint8_t>(((dir == 0 ? 0 : (dir < 0 ? -1 : 1 )) + 1) | ((linesofar & 0x3F) << 2)), static_cast<uint8_t>(linesofar >> 6) } {} const int16_t a_pos[2]; const uint8_t a_data[4]; /* * Scale the extrusion vector so that the normal length is this value. * Contains the "texture" normals (-1..1). This is distinct from the extrude * normals for line joins, because the x-value remains 0 for the texture * normal array, while the extrude normal actually moves the vertex to create * the acute/bevelled line join. */ static const int8_t extrudeScale = 63; }; namespace gl { template <class Shader> struct AttributeBindings<Shader, LineVertex> { std::array<AttributeBinding, 2> operator()(const Shader& shader) { return {{ MBGL_MAKE_ATTRIBUTE_BINDING(LineVertex, shader, a_pos), MBGL_MAKE_ATTRIBUTE_BINDING(LineVertex, shader, a_data) }}; }; }; } // namespace gl } // namespace mbgl
[ "john.firebaugh@gmail.com" ]
john.firebaugh@gmail.com
b14a31ca3da506ab8da6bf4405114a16d26c4c04
924bbbc157f7c93eaf6e9d4507df12f4b2765706
/src/game_engine/agent.cpp
ef4a914c8b2141ae85abf40de726e0d0e744b5c9
[]
no_license
Yeyoxando/NetworkGame
e748cb6428d4804ad7c6cafa601f5a80e915d9e7
141a90aaf836a74611a6905e54123835b81d3ae1
refs/heads/main
2023-06-01T10:11:25.354028
2021-06-14T18:52:45
2021-06-14T18:52:45
348,315,089
0
0
null
null
null
null
UTF-8
C++
false
false
24,379
cpp
/* * Author: Diego Ochando Torres * Date: 2020 * e-mail: c0022981@my.shu.ac.uk | yeyoxando@gmail.com */ // ------------------------------------------------------------------------- // #include "agent.h" #include "network_game.h" #include "game_script/units.h" #include <glm.hpp> // ------------------------------------------------------------------------- // Agent::Agent(){ direction_ = glm::vec2(0.0f, 0.0f); desired_direction_ = glm::vec2(0.0f, 0.0f); acceleration_ = 0.0f; max_acceleration_ = 5.0f; target_ = glm::vec2(0.0f, 0.0f); reached_target_ = false; movement_mode_ = kMovementMode_NONE; agent_size_ = kAgentSize_NONE; is_aproacching_target_ = false; brake_force_ = 0.3f; started_movement_ = false; current_pattern_ = 0; current_path_ = nullptr; refresh_time_ = 3.0f; accum_time_ = refresh_time_; fsm_state_ = kFSMState_Working; is_transitioning_ = false; client_owner_id_ = 0; unit_id_ = 0; hit_points_ = UnitManager::kUnitHitPoints; } // ------------------------------------------------------------------------- // Agent::~Agent(){ delete current_path_; } // ------------------------------------------------------------------------- // void Agent::update(uint32_t time_step){ GameObject::update(time_step); /*if(current_path_ != nullptr) current_path_->calculateTransformedPoints();*/ //current_box_.calculateTransformedPoints(); if (accum_time_ >= refresh_time_) { updateMind(time_step); accum_time_ = 0.0f; } updateBody(time_step); accum_time_ += time_step * 0.001f; } // ------------------------------------------------------------------------- // void Agent::draw(){ GameObject::draw(); if (NetworkGame::instance().game_menus_->debug_mode_) { switch (movement_mode_){ case Agent::kMovementMode_Deterministic: { if (current_path_ != nullptr) current_path_->drawDebug(); break; } case Agent::kMovementMode_Random: { if (current_path_ != nullptr) current_path_->drawDebug(); current_box_.drawDebug(glm::vec4(0, 0, 255, 255)); break; } case Agent::kMovementMode_Tracking: { //current_box_.drawDebug(Vector4(255, 0, 0, 255)); break; } case Agent::kMovementMode_Pattern: { if (current_path_ != nullptr) current_path_->drawDebug(); break; } case Agent::kMovementMode_NONE: { break; } default: { assert(false); break; } } } } // ------------------------------------------------------------------------- // void Agent::updateMind(uint32_t time_step){ // REMOVE: Prevent warnings until its used time_step; // FSM Application switch (fsm_state_){ case Agent::kFSMState_Working: { FSM_Working(); break; } case Agent::kFSMState_Chasing: { FSM_Chasing(); break; } case Agent::kFSMState_Fleeing: { FSM_Fleeing(); break; } case Agent::kFSMState_Resting: { FSM_Resting(); break; } case Agent::kFSMState_End: { FSM_End(); break; } case Agent::kFSMState_NONE: { assert(false); break; } default: { assert(false); break; } } } // ------------------------------------------------------------------------- // void Agent::updateBody(uint32_t time_step){ switch (movement_mode_) { case Agent::kMovementMode_Deterministic: { MOV_Deterministic(time_step); break; } case Agent::kMovementMode_Random: { MOV_Random(time_step); break; } case Agent::kMovementMode_Tracking: { MOV_Tracking(time_step); break; } case Agent::kMovementMode_Pattern: { MOV_Pattern(time_step); break; } case Agent::kMovementMode_NONE: { break; } default: { assert(false); break; } } } // ------------------------------------------------------------------------- // /* void Agent::editor(){ Entity::editor(); ImGui::Text("AGENT PARAMS"); ImGui::Spacing(); ImGui::Text("Target"); ImGui::Indent(); ImGui::Text("X: %.2f, Y: %.2f", target_.x, target_.y); ImGui::Unindent(); ImGui::Spacing(); ImGui::PushID(2); ImGui::Text("Max acceleration (m/s)"); ImGui::SliderFloat("", &max_acceleration_, 3.5f, 60.0f); ImGui::Indent(); ImGui::Text("Current acceleration: %2.3f m/s", acceleration_); ImGui::Unindent(); ImGui::PopID(); ImGui::Spacing(); ImGui::Text("Brake Force"); ImGui::PushID(3); ImGui::SliderFloat("", &brake_force_, 0.0f, 0.8f); ImGui::PopID(); ImGui::Spacing(); ImGui::Text("FSM PARAMS"); ImGui::Spacing(); switch (fsm_state_) { case Agent::kFSMState_Working: { ImGui::Indent(); ImGui::Text("Current state: WORKING"); ImGui::Unindent(); switch (agent_size_) { case Agent::kAgentSize_Huge: { ImGui::Indent(); ImGui::Text("Movement mode: Deterministic"); ImGui::Unindent(); break; } case Agent::kAgentSize_Normal: { ImGui::Indent(); ImGui::Text("Movement mode: Random"); ImGui::Unindent(); break; } case Agent::kAgentSize_Small: { ImGui::Indent(); ImGui::Text("Movement mode: Pattern"); ImGui::Unindent(); break; } case Agent::kAgentSize_NONE: { assert(false); break; } default: { assert(false); break; } } break; } case Agent::kFSMState_Chasing: { ImGui::Indent(); ImGui::Text("Current state: CHASING"); ImGui::Unindent(); ImGui::Indent(); ImGui::Text("Chasing '%s'", objective_->name()); ImGui::Unindent(); break; } case Agent::kFSMState_Fleeing: { ImGui::Indent(); ImGui::Text("Current state: FLEEING"); ImGui::Unindent(); ImGui::Indent(); ImGui::Text("Fleeing from '%s'", objective_->name()); ImGui::Unindent(); break; } case Agent::kFSMState_Resting: { ImGui::Indent(); ImGui::Text("Current state: RESTING"); ImGui::Unindent(); ImGui::Indent(); ImGui::Text("Rest time: %f", (float)(rest_time_ / 1000)); ImGui::Unindent(); ImGui::Indent(); ImGui::Text("Current rest time: %f", (float)(current_rest_time_ / 1000)); ImGui::Unindent(); break; } case Agent::kFSMState_End: { break; } case Agent::kFSMState_NONE: { assert(false); break; } default: { assert(false); break; } } ImGui::Spacing(); switch (agent_size_) { case Agent::kAgentSize_Huge: { ImGui::Indent(); ImGui::Text("Agent size: HUGE"); ImGui::Unindent(); break; } case Agent::kAgentSize_Normal: { ImGui::Indent(); ImGui::Text("Agent size: NORMAL"); ImGui::Unindent(); break; } case Agent::kAgentSize_Small: { ImGui::Indent(); ImGui::Text("Agent size: SMALL"); ImGui::Unindent(); break; } case Agent::kAgentSize_NONE: { assert(false); break; } default: { assert(false); break; } } } */ // ------------------------------------------------------------------------- // void Agent::set_brake_force(float brake_force) { brake_force_ = glm::clamp(brake_force, 0.1f, 0.8f); } // ------------------------------------------------------------------------- // void Agent::set_max_acceleration(float acceleration){ max_acceleration_ = acceleration; } // ------------------------------------------------------------------------- // void Agent::set_movement_mode(MovementMode movement_mode){ movement_mode_ = movement_mode; } // ------------------------------------------------------------------------- // void Agent::set_target(glm::vec2 target){ target_ = target; } // ------------------------------------------------------------------------- // void Agent::set_agent_size(AgentSize agent_size){ agent_size_ = agent_size; switch (agent_size_) { case kAgentSize_Small: { transform_.scale_ = glm::vec3(0.75f, 0.75f, 0.75f); set_max_acceleration(kAgentDefaultSpeed * 1.25f); //Pattern movement set_movement_mode(Agent::kMovementMode_Pattern); set_brake_force(0.6f); set_mind_refresh_time(1.0f); break; } case kAgentSize_Normal: { transform_.scale_ = glm::vec3(1.0f, 1.0f, 1.0f); set_max_acceleration(kAgentDefaultSpeed * 1.0f); //Random movement set_movement_mode(Agent::kMovementMode_Random); set_brake_force(0.5f); set_mind_refresh_time(1.0f); break; } case kAgentSize_Huge: { transform_.scale_ = glm::vec3(1.25f, 1.25f, 1.25f); set_max_acceleration(kAgentDefaultSpeed * 0.75f); //Deterministic movement set_movement_mode(Agent::kMovementMode_Deterministic); set_brake_force(0.4f); set_mind_refresh_time(1.0f); break; } case kAgentSize_NONE: { assert(false); break; } default: { assert(false); break; } } } // ------------------------------------------------------------------------- // void Agent::set_deterministic_path(Path* absolute_path) { if (absolute_path != nullptr) { current_path_ = new Path(*absolute_path); } } // ------------------------------------------------------------------------- // void Agent::set_random_area(Box new_area){ current_box_ = new_area; } // ------------------------------------------------------------------------- // void Agent::set_tracking_objective(GameObject* objective){ if (nullptr != objective) { objective_ = objective; } } // ------------------------------------------------------------------------- // void Agent::set_tracking_area(Box new_area){ current_box_ = new_area; } // ------------------------------------------------------------------------- // void Agent::set_tracking(bool seek){ seeking_ = seek; } // ------------------------------------------------------------------------- // void Agent::addPattern(Pattern new_pattern){ possible_patterns_.push_back(new_pattern); } // ------------------------------------------------------------------------- // void Agent::set_mind_refresh_time(float time_in_seconds){ refresh_time_ = time_in_seconds; accum_time_ = refresh_time_; } // ------------------------------------------------------------------------- // glm::vec2 Agent::direction() const { return direction_; } // ------------------------------------------------------------------------- // float Agent::acceleration() const { return acceleration_; } // ------------------------------------------------------------------------- // Agent::MovementMode Agent::movement_mode() const { return movement_mode_; } // ------------------------------------------------------------------------- // glm::vec2 Agent::target() const { return target_; } // ------------------------------------------------------------------------- // void Agent::MOV_Deterministic(uint32_t time_step) { if (current_path_ == nullptr) return; if (client_owner_id_ != NetworkGame::instance().client_id_) return; if (!NetworkGame::instance().game_started_ || !active_) return; // Init movement if (!started_movement_) { target_ = current_path_->next_target(); started_movement_ = true; } if (hit_points_ <= 0) { if (client_owner_id_ == 2) { NetworkGame::instance().unit_manager_->active_p2_units--; } else { NetworkGame::instance().unit_manager_->active_p1_units--; } transform_.position_ = glm::vec3(current_path_->first_point(), 0); target_ = current_path_->at_point(1); current_path_->current_index_ = 0; active_ = false; } glm::vec2 pos = glm::vec2(transform_.position_.x, transform_.position_.y); //Send command UnitData* unit_data = CreateUnitData(client_owner_id_, pos, unit_id_, hit_points_, active_); NetworkGame::instance().unit_manager_->updateUnit(true, *unit_data); if (hit_points_ <= 0) { NetworkGame::instance().unit_manager_->checkUnitsDisabled(true, client_owner_id_); } // Calculate movement if (!current_path_->is_ready()) { printf("\nError: agent deterministic path not set as ready"); return; } if (glm::distance(pos, target_) < kDistanceToApproach) { // Reduce speed is_aproacching_target_ = true; } if (glm::distance(pos, target_) < kDistanceToReach) { is_aproacching_target_ = false; target_ = current_path_->next_target(); // Check if has finished its path reached_target_ = current_path_->reached_target(target_); if (reached_target_) { reached_target_ = false; transform_.position_ = glm::vec3(current_path_->first_point(), 0); target_ = current_path_->at_point(1); active_ = false; // Send unit disactivate command UnitData* unit_data = CreateUnitData(client_owner_id_, pos, unit_id_, 0, false); NetworkGame::instance().unit_manager_->updateUnit(true, *unit_data); // Subtract to the active units count if (client_owner_id_ == 2) { NetworkGame::instance().unit_manager_->active_p2_units -= 1; // Update enemy castle life int new_castle_life = NetworkGame::instance().castle_life_p1_ - 1; NetworkGame::instance().updateCastleLife(true, 1, new_castle_life); printf("\nPlayer 2 hit."); } else { NetworkGame::instance().unit_manager_->active_p1_units -= 1; // Update enemy castle life int new_castle_life = NetworkGame::instance().castle_life_p2_ - 1; NetworkGame::instance().updateCastleLife(true, 2, new_castle_life); printf("\nPlayer 1 hit."); } // Check if units count is 0 then send the turn finished package NetworkGame::instance().unit_manager_->checkUnitsDisabled(true, client_owner_id_); } } desired_direction_ = target_ - pos; desired_direction_ = glm::normalize(desired_direction_); move(time_step); } // ------------------------------------------------------------------------- // void Agent::MOV_Random(uint32_t time_step) { // Init movement if (!started_movement_) { current_box_.set_position(transform_.position_); current_box_.updatePoints(); current_path_->clear(); current_path_->addPoint(transform_.position_); glm::vec2 box_size = current_box_.size(); for (uint32_t i = 0; i < 39; ++i) { // Rand with area glm::vec2 new_point = glm::vec2((float)(rand() % ((uint32_t)box_size.x)), (float)(rand() % ((uint32_t)box_size.y))); new_point -= glm::vec2(box_size.x / 2, box_size.y / 2); new_point += current_box_.position(); current_path_->addPoint(new_point); } current_path_->set_direction(Path::kDirection_Forward); current_path_->set_action(Path::kAction_Straight); current_path_->set_ready(); target_ = current_path_->first_point(); started_movement_ = true; } // Calculate movement if (!current_path_->is_ready()) { printf("\nError: agent pattern not marked as ready"); return; } glm::vec2 pos = glm::vec2(transform_.position_.x, transform_.position_.y); if (glm::distance(pos, target_) < kDistanceToApproach) { // Reduce speed is_aproacching_target_ = true; } if (glm::distance(pos, target_) < kDistanceToReach) { is_aproacching_target_ = false; // Check if has finished its path if (current_path_->reached_target(target_)) { started_movement_ = false; return; } target_ = current_path_->next_target(); } desired_direction_ = target_ - pos; desired_direction_ = glm::normalize(desired_direction_); move(time_step); } // ------------------------------------------------------------------------- // void Agent::MOV_Tracking(uint32_t time_step) { // Set chase objective and look for if its inside its box range // If is inside set as target and chase him if (objective_ != nullptr) { //if (current_box_.isPositionInside(objective_->position())) { target_ = objective_->transform_.position_; reached_target_ = false; //} //else { // target_ = position_; //} } // Move vision area //current_box_.set_position(position_); //current_box_.updatePoints(); glm::vec2 pos = glm::vec2(transform_.position_.x, transform_.position_.y); if (glm::distance(pos, target_) < kDistanceToReach) { //seeking_ = false; reached_target_ = true; } //if (glm::distance(pos, target_) > 300.0f && !seeking_) { // seeking_ = true; // reached_target_ = true; //} desired_direction_ = target_ - pos; desired_direction_ = glm::normalize(desired_direction_); if (!seeking_) desired_direction_ *= -1.0f; move(time_step); } // ------------------------------------------------------------------------- // void Agent::MOV_Pattern(uint32_t time_step) { // Init movement if (!started_movement_) { if (current_pattern_ >= possible_patterns_.size()) current_pattern_ = 0; current_path_->clear(); if (possible_patterns_[current_pattern_].is_ready()) { current_path_->convertPatternToPath(transform_.position_, possible_patterns_[current_pattern_]); } current_path_->set_direction(Path::kDirection_Forward); current_path_->set_action(Path::kAction_Straight); current_path_->set_ready(); target_ = current_path_->first_point(); reached_target_ = false; is_aproacching_target_ = false; started_movement_ = true; } // Calculate movement if (!current_path_->is_ready()) { printf("\nError: agent pattern not marked as ready"); return; } glm::vec2 pos = glm::vec2(transform_.position_.x, transform_.position_.y); if (glm::distance(pos, target_) < kDistanceToApproach) { // Reduce speed is_aproacching_target_ = true; } if (glm::distance(pos, target_) < kDistanceToReach) { is_aproacching_target_ = false; if (current_path_->reached_target(target_)) { current_pattern_++; reached_target_ = true; started_movement_ = false; } target_ = current_path_->next_target(); } desired_direction_ = target_ - pos; desired_direction_ = glm::normalize(desired_direction_); move(time_step); } // ------------------------------------------------------------------------- // void Agent::FSM_Working(){ //Do only first time after transition if (is_transitioning_) { // Reset movements to default depending on its size switch (agent_size_) { case kAgentSize_Small: { set_movement_mode(Agent::kMovementMode_Pattern); break; } case kAgentSize_Normal: { set_movement_mode(Agent::kMovementMode_Random); break; } case kAgentSize_Huge: { set_movement_mode(Agent::kMovementMode_Deterministic); break; } case kAgentSize_NONE: { assert(false); break; } default: { assert(false); break; } } is_transitioning_ = false; } //Transitions /* if (BaseApp::Instance().current_scene()->quit_game_) { //Change to end fsm_state_ = kFSMState_End; is_transitioning_ = true; } std::vector<ref_ptr<Entity>> entities = BaseApp::Instance().current_scene()->entities_; //For each entity on scene for (uint32_t i = 0; i < entities.size(); ++i) { //Check if its an agent Agent* agent = dynamic_cast<Agent*>(entities[i].get()); if (agent == nullptr) continue; //Check if its himself if (agent == this) continue; //Get distance to other agent float d = glm::vec2::Distance(position_, agent->position_); //Check if is bigger than other and d < d1 if (agent_size_ > agent->agent_size_ && d < kDistanceOne) { //Change to chase fsm_state_ = kFSMState_Chasing; objective_ = agent; is_transitioning_ = true; } //Check if is smaller than other and d < d2 if (agent_size_ < agent->agent_size_ && d < kDistanceTwo) { //Change to fleeing fsm_state_ = kFSMState_Fleeing; objective_ = agent; is_transitioning_ = true; } }*/ } // ------------------------------------------------------------------------- // void Agent::FSM_Chasing(){ //Do only first time after transition if (is_transitioning_) { // Set tracking movement movement_mode_ = kMovementMode_Tracking; seeking_ = true; is_aproacching_target_ = false; is_transitioning_ = false; } //Transitions /*if (BaseApp::Instance().current_scene()->quit_game_) { //Change to end fsm_state_ = kFSMState_End; is_transitioning_ = true; } //Get distance to other agent float d = glm::vec2::Distance(position_, objective_->position()); // Check for distance > d3 if (d > kDistanceThree) { fsm_state_ = kFSMState_Resting; objective_ = nullptr; is_transitioning_ = true; }*/ } // ------------------------------------------------------------------------- // void Agent::FSM_Fleeing(){ //Do only first time after transition if (is_transitioning_) { // Set inverse tracking movement (run away) movement_mode_ = kMovementMode_Tracking; seeking_ = false; is_aproacching_target_ = false; is_transitioning_ = false; } //Transitions /*if (BaseApp::Instance().current_scene()->quit_game_) { //Change to end fsm_state_ = kFSMState_End; is_transitioning_ = true; } //Get distance to other agent float d = glm::vec2::Distance(position_, objective_->position()); // Check for distance > d3 if (d > kDistanceThree) { fsm_state_ = kFSMState_Resting; objective_ = nullptr; is_transitioning_ = true; }*/ } // ------------------------------------------------------------------------- // void Agent::FSM_Resting(){ //Do only first time after transition if (is_transitioning_) { // Set to movement mode none movement_mode_ = kMovementMode_NONE; //3 - 6 rest interval rest_time_ = 3000 + (rand() % 3000); current_rest_time_ = 0; is_transitioning_ = false; } /* //Update state current_rest_time_ += (uint32_t)refresh_time_ * 1000; //Transitions if (BaseApp::Instance().current_scene()->quit_game_) { //Change to end fsm_state_ = kFSMState_End; is_transitioning_ = true; } //Time if (current_rest_time_ > rest_time_) { fsm_state_ = kFSMState_Working; is_transitioning_ = true; started_movement_ = false; } //Only fleeing while resting std::vector<ref_ptr<Entity>> entities = BaseApp::Instance().current_scene()->entities_; //For each entity on scene for (uint32_t i = 0; i < entities.size(); ++i) { //Check if its an agent Agent* agent = dynamic_cast<Agent*>(entities[i].get()); if (agent == nullptr) continue; //Check if its himself if (agent == this) continue; //Get distance to other agent float d = glm::vec2::Distance(position_, agent->position_); //Check if is smaller than other and d < d2 if (agent_size_ < agent->agent_size_ && d < kDistanceTwo) { //Change to fleeing fsm_state_ = kFSMState_Fleeing; objective_ = agent; is_transitioning_ = true; } }*/ } // ------------------------------------------------------------------------- // void Agent::FSM_End(){ //Do nothing, but FSM design requires an end state //if (is_transitioning_) { //} } // ------------------------------------------------------------------------- // void Agent::move(uint32_t time_step){ float delta_time = time_step * 0.001f; // Slow speed when approaching target if (is_aproacching_target_) { float decceleration = max_acceleration_ * (1.0f - brake_force_); acceleration_ += (0.95f * (decceleration - acceleration_)) * delta_time; //direction_.x += (0.99f * (desired_direction_.x - direction_.x)) * delta_time; //direction_.y += (0.99f * (desired_direction_.y - direction_.y)) * delta_time; direction_ = desired_direction_; } // Increase speed going to next target if (!reached_target_ && !is_aproacching_target_) { acceleration_ += (0.85f * (max_acceleration_ - acceleration_)) * delta_time; //direction_.x += (0.99f * (desired_direction_.x - direction_.x)) * delta_time; //direction_.y += (0.99f * (desired_direction_.y - direction_.y)) * delta_time; direction_ = desired_direction_; } // Brake when target is reached if (reached_target_) { acceleration_ += (0.95f * (0.0f - acceleration_)) * delta_time; } transform_.position_.x += acceleration_ * direction_.x * delta_time; transform_.position_.y += acceleration_ * direction_.y * delta_time; //transform_.rotation_ = glm::degrees(atan2(direction_.x, direction_.y)); } // ------------------------------------------------------------------------- //
[ "yeyoxando@gmail.com" ]
yeyoxando@gmail.com
0676f21caa5adfbbb7675c67c8884eecdd13c14c
e82ff0cf1e4590082aaf0337336fb191595377e0
/src/libzerocoin/Coin.h
48755d5c623975149663516727f38ff068acb0b4
[ "MIT" ]
permissive
yoda-x-com/blockchain
f2d5969081cbdd1bfcfa4466304e4ccf773fc294
5f4d83bc9f7dfb17cd6997e61ca5a5c764fc4772
refs/heads/master
2022-07-30T11:49:43.534316
2020-05-08T08:46:41
2020-05-08T08:46:41
262,270,941
1
1
null
null
null
null
UTF-8
C++
false
false
6,422
h
/** * @file Coin.h * * @brief PublicCoin and PrivateCoin classes for the Zerocoin library. * * @author Ian Miers, Christina Garman and Matthew Green * @date June 2013 * * @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green * @license This project is released under the MIT license. **/ // Copyright (c) 2017-2019 The YODA developers #ifndef COIN_H_ #define COIN_H_ #include "Denominations.h" #include "Params.h" #include "amount.h" #include "bignum.h" #include "util.h" #include "key.h" namespace libzerocoin { class InvalidSerialException : public std::exception { public: std::string message; InvalidSerialException(const std::string &message) : message(message) {} }; int ExtractVersionFromSerial(const CBigNum& bnSerial); bool IsValidSerial(const ZerocoinParams* params, const CBigNum& bnSerial); bool IsValidCommitmentToCoinRange(const ZerocoinParams* params, const CBigNum& bnCommitment); CBigNum GetAdjustedSerial(const CBigNum& bnSerial); CBigNum ExtractSerialFromPubKey(const CPubKey pubkey); bool GenerateKeyPair(const CBigNum& bnGroupOrder, const uint256& nPrivkey, CKey& key, CBigNum& bnSerial); /** A Public coin is the part of a coin that * is published to the network and what is handled * by other clients. It contains only the value * of commitment to a serial number and the * denomination of the coin. */ class PublicCoin { public: template <typename Stream> PublicCoin(const ZerocoinParams* p, Stream& strm) : params(p) { strm >> *this; } PublicCoin(const ZerocoinParams* p); /**Generates a public coin * * @param p cryptographic paramters * @param coin the value of the commitment. * @param denomination The denomination of the coin. */ PublicCoin(const ZerocoinParams* p, const CBigNum& coin, const CoinDenomination d); const CBigNum& getValue() const { return this->value; } CoinDenomination getDenomination() const { return this->denomination; } bool operator==(const PublicCoin& rhs) const { return ((this->value == rhs.value) && (this->params == rhs.params) && (this->denomination == rhs.denomination)); } bool operator!=(const PublicCoin& rhs) const { return !(*this == rhs); } /** Checks that coin is prime and in the appropriate range given the parameters * @return true if valid */ bool validate() const; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(value); READWRITE(denomination); } private: const ZerocoinParams* params; CBigNum value; CoinDenomination denomination; }; /** * A private coin. As the name implies, the content * of this should stay private except PublicCoin. * * Contains a coin's serial number, a commitment to it, * and opening randomness for the commitment. * * @warning Failure to keep this secret(or safe), * @warning will result in the theft of your coins * @warning and a TOTAL loss of anonymity. */ class PrivateCoin { public: static int const PUBKEY_VERSION = 2; static int const CURRENT_VERSION = 2; static int const V2_BITSHIFT = 4; template <typename Stream> PrivateCoin(const ZerocoinParams* p, Stream& strm) : params(p), publicCoin(p) { strm >> *this; } PrivateCoin(const ZerocoinParams* p, const CoinDenomination denomination, bool fMintNew = true); PrivateCoin(const ZerocoinParams* p, const CoinDenomination denomination, const CBigNum& bnSerial, const CBigNum& bnRandomness); const PublicCoin& getPublicCoin() const { return this->publicCoin; } // @return the coins serial number const CBigNum& getSerialNumber() const { return this->serialNumber; } const CBigNum& getRandomness() const { return this->randomness; } const CPrivKey& getPrivKey() const { return this->privkey; } const CPubKey getPubKey() const; const uint8_t& getVersion() const { return this->version; } void setPublicCoin(PublicCoin p) { publicCoin = p; } void setRandomness(CBigNum n) { randomness = n; } void setSerialNumber(CBigNum n) { serialNumber = n; } void setVersion(uint8_t nVersion) { this->version = nVersion; } void setPrivKey(const CPrivKey& privkey) { this->privkey = privkey; } bool sign(const uint256& hash, std::vector<unsigned char>& vchSig) const; bool IsValid(); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(publicCoin); READWRITE(randomness); READWRITE(serialNumber); version = (uint8_t )ExtractVersionFromSerial(serialNumber); if (version == 2) { READWRITE(version); READWRITE(privkey); } } private: const ZerocoinParams* params; PublicCoin publicCoin; CBigNum randomness; CBigNum serialNumber; uint8_t version = 1; CPrivKey privkey; /** * @brief Mint a new coin. * @param denomination the denomination of the coin to mint * @throws ZerocoinException if the process takes too long * * Generates a new Zerocoin by (a) selecting a random serial * number, (b) committing to this serial number and repeating until * the resulting commitment is prime. Stores the * resulting commitment (coin) and randomness (trapdoor). **/ void mintCoin(const CoinDenomination denomination); /** * @brief Mint a new coin using a faster process. * @param denomination the denomination of the coin to mint * @throws ZerocoinException if the process takes too long * * Generates a new Zerocoin by (a) selecting a random serial * number, (b) committing to this serial number and repeating until * the resulting commitment is prime. Stores the * resulting commitment (coin) and randomness (trapdoor). * This routine is substantially faster than the * mintCoin() routine, but could be more vulnerable * to timing attacks. Don't use it if you think someone * could be timing your coin minting. **/ void mintCoinFast(const CoinDenomination denomination); }; } /* namespace libzerocoin */ #endif /* COIN_H_ */
[ "support@yoda-x.com" ]
support@yoda-x.com
102f3225770fb3a2b5d52f13e3c2f436f1e0f44e
71d4ed7ee9a120411139be755dfa9c4c67e1ba5b
/libintrinsic3d/src/refinement/volumetric_regularizer.cpp
e17bb73c4d2e144caaeb6de80d0a49adf98b4f4b
[ "CC-BY-4.0", "BSD-3-Clause" ]
permissive
NVlabs/intrinsic3d
eaabcacc49cd070ed1f82c0a39a64850003189fa
05312e564d4bf6986bb11fe8c4b3f921ec9be6e3
refs/heads/master
2023-08-29T05:11:39.084080
2022-07-04T09:35:58
2022-07-04T09:35:58
164,033,138
444
77
BSD-3-Clause
2020-02-10T19:47:50
2019-01-03T23:22:14
C++
UTF-8
C++
false
false
3,158
cpp
/** * This file is part of Intrinsic3D. * * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. * Copyright (c) 2019, Technical University of Munich. 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 NVIDIA CORPORATION 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 "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 <nv/refinement/volumetric_regularizer.h> #include <iostream> #include <nv/sdf/algorithms.h> namespace nv { VolumetricRegularizer::VolumetricRegularizer() { } VolumetricRegularizer::~VolumetricRegularizer() { } VoxelResidual VolumetricRegularizer::create(SparseVoxelGrid<VoxelSBR>* grid, const Vec3i& v_pos) { VoxelResidual r; // collect 1-ring neighborhood voxels std::vector<Vec3i> v_pos_neighbors = SDFAlgorithms::collectRingNeighborhood(v_pos); // use only voxels with valid 1-ring-neighborhood if (!SDFAlgorithms::checkVoxelsValid(grid, v_pos_neighbors)) return r; // reduce weight if sdf differences are too large double w = 1.0; // volumetric regularizer cost Er VolumetricRegularizer* vr_cost = new VolumetricRegularizer(); r.cost = new ceres::AutoDiffCostFunction<VolumetricRegularizer, 1, 1, 1, 1, 1, 1, 1, 1>(vr_cost); r.weight = w; r.params.push_back(&(grid->voxel(v_pos).sdf_refined)); r.params.push_back(&(grid->voxel(v_pos_neighbors[0]).sdf_refined)); r.params.push_back(&(grid->voxel(v_pos_neighbors[1]).sdf_refined)); r.params.push_back(&(grid->voxel(v_pos_neighbors[2]).sdf_refined)); r.params.push_back(&(grid->voxel(v_pos_neighbors[3]).sdf_refined)); r.params.push_back(&(grid->voxel(v_pos_neighbors[4]).sdf_refined)); r.params.push_back(&(grid->voxel(v_pos_neighbors[5]).sdf_refined)); return r; } } // namespace nv
[ "robert.maier@tum.de" ]
robert.maier@tum.de
c1ba62a5eb5665c555ed3526bfc9edb7ab403625
0c2075ff3ef6a0dde625c9879c3bd4ee7bfd8217
/Watery/ThirdParty/ASIO/asio/ssl/detail/password_callback.hpp
a8896a2a485ca91c487754858db5a7c206a63681
[]
no_license
Mike-Leo-Smith/Watery
27349ee581faac107bd6b886cab996270da9518b
ec13ef5e0384522daabb46c08a93bfd6c8ca7c8e
refs/heads/master
2021-01-19T20:24:34.680776
2017-06-23T15:54:33
2017-06-23T15:54:33
88,504,257
6
6
null
2017-06-01T15:10:30
2017-04-17T12:03:40
C++
UTF-8
C++
false
false
1,714
hpp
// // ssl/detail/password_callback.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2016 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) // #ifndef ASIO_SSL_DETAIL_PASSWORD_CALLBACK_HPP #define ASIO_SSL_DETAIL_PASSWORD_CALLBACK_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if !defined(ASIO_ENABLE_OLD_SSL) # include <cstddef> # include <string> # include "asio/ssl/context_base.hpp" #endif // !defined(ASIO_ENABLE_OLD_SSL) #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { namespace detail { #if !defined(ASIO_ENABLE_OLD_SSL) class password_callback_base { public: virtual ~password_callback_base() { } virtual std::string call(std::size_t size, context_base::password_purpose purpose) = 0; }; template<typename PasswordCallback> class password_callback : public password_callback_base { public: explicit password_callback(PasswordCallback callback) : callback_(callback) { } virtual std::string call(std::size_t size, context_base::password_purpose purpose) { return callback_(size, purpose); } private: PasswordCallback callback_; }; #endif // !defined(ASIO_ENABLE_OLD_SSL) } // namespace detail } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_DETAIL_PASSWORD_CALLBACK_HPP
[ "mango@live.cn" ]
mango@live.cn
565299b7d2f7ed4015e48eb828f9eb29508353e2
c8958958e5802f3e04ce88bd4064eacb98ce2f97
/排序矩阵查找.cpp
7c9564dbb8e5ff01e9178615e4cc8072df166467
[]
no_license
Kiids/OJ_Practice
08e5ea99066421bfaf5b71e59eea24e282e39a24
e7d36ddb1664635d27db3c37bec952970b77dcb0
refs/heads/master
2023-09-01T11:38:28.834187
2023-06-30T17:12:18
2023-06-30T17:12:18
217,068,695
0
0
null
null
null
null
GB18030
C++
false
false
1,024
cpp
/* 给定M×N矩阵,每一行、每一列都按升序排列,请编写代码找出某元素。 示例: 现有矩阵 matrix 如下: [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] 给定 target = 5,返回 true。 给定 target = 20,返回 false。 */ class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.empty()) return false; // 右上角 int row = 0; int col = matrix.at(0).size() - 1; // 左下角 int end_row = matrix.size() - 1; int end_col = 0; while (row <= end_row && col >= end_col) { if (matrix.at(row).at(col) == target) return true; else if(target < matrix.at(row).at(col)) // 左边部分找 col--; else if (target > matrix.at(row).at(col)) // 下边部分找 row++; } return false; } };
[ "1980774293@qq.com" ]
1980774293@qq.com
63e59ed1eedbca55bac9e44d6963f49fcf45d5ba
18307e86c085a64e64fe0671edc1ab00ab9aa1be
/Engine/Plugins/UnrealCS/Source/MonoPlugin/Private/GeneratedScriptLibraries/MovieSceneEnumTrack_script.h
d9087495169885bdc9f40aed14f4213fa8638c42
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
rob-ack/UnrealCS
b6e9fe433ba1d04094a6baa3f75a365d0dcc749c
16d6f4989ef2f8622363009ebc6509b67c35a57e
refs/heads/master
2021-08-04T13:50:00.090129
2017-09-06T20:58:36
2017-09-06T20:58:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
312
h
//GENERATED: C++ Code #pragma once class UMovieSceneEnumTrack_ { static UClass* _StaticClassForProxy(){return UMovieSceneEnumTrack::StaticClass();} public: static void BindFunctions() { mono_add_internal_call("UnrealEngine.UMovieSceneEnumTrack::StaticClass",(const void*)_StaticClassForProxy); } } ;
[ "robert.acksel@googlemail.com" ]
robert.acksel@googlemail.com
dd361b6fcfffd01f7cc71d4e8ecb651bf6102f27
13794000c71a63a86e755d95caf1996775dbcfbf
/test_sort.cpp
58695c5809ef9515a4f5646541ec5a261a0defa7
[]
no_license
moh4med/Algorithm
a509fe0d512136ea6a843e8ed4a72c10f66089b2
a55df94440bd2eb1d6b90a7a9a43f3709b4bd178
refs/heads/master
2021-01-17T17:36:54.558198
2017-01-06T07:31:56
2017-01-06T07:31:56
61,139,154
0
0
null
null
null
null
UTF-8
C++
false
false
1,593
cpp
#include<bits/stdc++.h> #include<time.h> #include"Headers/Quick_sort.h" #include"Headers/merge_modified_sort.h" #include"Headers/insertion_sort.h" #include"Headers/Counting_sort.h" #include"Headers/Radix_sort.h" using namespace std; int test() { //freopen("in", "r", stdin); freopen("out", "w", stdout); cout << setw(15) << left << "numbers" << setw(15) << "merge_sort" << setw(15) << "merge time" << setw(15) << "quick_sort" << setw(15) << "quick_time" << setw(15) << "insertion_sort" << setw(15) << "insertion_time" << setw(15) << "Counting_sort" << setw(15) << "Counting_time" << setw(15) << "Radix_sort" << setw(15) << "Radix_time" << endl; srand(time(NULL)); for (int i = 1; i < 100000; i += 50) { int a[i], b[i], c[i], d[i], e[i]; for (int j = 0; j < i; ++j) { a[j] = rand(); b[j] = a[j]; c[j] = a[j]; d[j] = a[j]; e[j] = a[j]; } double x = clock(); merge_sort_modified(a, i); cout << setw(15) << left << i << setw(15) << mergemodisteps() << setw(15) << clock() - x; x = clock(); Quick_sort(b, i); cout << left << setw(15) << quicksteps() << setw(15) << clock() - x; x = clock(); insertion_sort(c, i); cout << left << setw(15) << insertionsteps() << setw(15) << clock() - x; x = clock(); int k = *max_element(a, a + i); Counting_sort(d, i, k); cout << left << setw(15) << Countingsteps() << setw(15) << clock() - x; x = clock(); Radix_sort(e, i); cout << left << setw(15) << Radixsteps() << setw(15) << clock() - x << endl; x = clock(); } return 0; }
[ "moh4med.ahmed@gmail.com" ]
moh4med.ahmed@gmail.com
d1074f0eca0f6667893a3c251dd56f3e4f2825de
8167cb3dc06c33729d948de81a7e693585fe4aa9
/src/activemasternode.cpp
91f78def8f88294f7c85962379aa92af3a4826b1
[ "MIT", "OpenSSL" ]
permissive
Tripperpay-Project/Tripperpay
cd4d46cd0ebb4eec1b5376879825b44c29ec15c0
bb8781ed74d900d372e61dd587d63891faaa8900
refs/heads/master
2020-03-29T07:28:06.216819
2018-09-20T20:23:51
2018-09-20T20:23:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,597
cpp
// Copyright (c) 2009-2012 The Darkcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "protocol.h" #include "activemasternode.h" #include "masternodeman.h" #include <boost/lexical_cast.hpp> #include "clientversion.h" // // Bootup the masternode, look for a 5000 TRP input and register on the network // void CActiveMasternode::ManageStatus() { std::string errorMessage; if (fDebug) LogPrintf("CActiveMasternode::ManageStatus() - Begin\n"); if(!fMasterNode) return; //need correct adjusted time to send ping bool fIsInitialDownload = IsInitialBlockDownload(); if(fIsInitialDownload) { status = MASTERNODE_SYNC_IN_PROCESS; LogPrintf("CActiveMasternode::ManageStatus() - Sync in progress. Must wait until sync is complete to start masternode.\n"); return; } if(status == MASTERNODE_INPUT_TOO_NEW || status == MASTERNODE_NOT_CAPABLE || status == MASTERNODE_SYNC_IN_PROCESS){ status = MASTERNODE_NOT_PROCESSED; } if(status == MASTERNODE_NOT_PROCESSED) { if(strMasterNodeAddr.empty()) { if(!GetLocal(service)) { notCapableReason = "Can't detect external address. Please use the masternodeaddr configuration option."; status = MASTERNODE_NOT_CAPABLE; LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason.c_str()); return; } } else { service = CService(strMasterNodeAddr, true); } LogPrintf("CActiveMasternode::ManageStatus() - Checking inbound connection to '%s'\n", service.ToString().c_str()); if(!ConnectNode((CAddress)service, service.ToString().c_str())){ notCapableReason = "Could not connect to " + service.ToString(); status = MASTERNODE_NOT_CAPABLE; LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason.c_str()); return; } if(pwalletMain->IsLocked()){ notCapableReason = "Wallet is locked."; status = MASTERNODE_NOT_CAPABLE; LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason.c_str()); return; } // Set defaults status = MASTERNODE_NOT_CAPABLE; notCapableReason = "Unknown. Check debug.log for more information.\n"; // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; if(GetMasterNodeVin(vin, pubKeyCollateralAddress, keyCollateralAddress)) { if(GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS){ notCapableReason = "Input must have least " + boost::lexical_cast<string>(MASTERNODE_MIN_CONFIRMATIONS) + " confirmations - " + boost::lexical_cast<string>(GetInputAge(vin)) + " confirmations"; LogPrintf("CActiveMasternode::ManageStatus() - %s\n", notCapableReason.c_str()); status = MASTERNODE_INPUT_TOO_NEW; return; } LogPrintf("CActiveMasternode::ManageStatus() - Is capable master node!\n"); status = MASTERNODE_IS_CAPABLE; notCapableReason = ""; pwalletMain->LockCoin(vin.prevout); // send to all nodes CPubKey pubKeyMasternode; CKey keyMasternode; if(!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrintf("ActiveMasternode::Dseep() - Error upon calling SetKey: %s\n", errorMessage.c_str()); return; } /* donations are not supported in tripperpay.conf */ CScript donationAddress = CScript(); int donationPercentage = 0; if(!Register(vin, service, keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, donationAddress, donationPercentage, errorMessage)) { LogPrintf("CActiveMasternode::ManageStatus() - Error on Register: %s\n", errorMessage.c_str()); } return; } else { notCapableReason = "Could not find suitable coins!"; LogPrintf("CActiveMasternode::ManageStatus() - Could not find suitable coins!\n"); } } //send to all peers if(!Dseep(errorMessage)) { LogPrintf("CActiveMasternode::ManageStatus() - Error on Ping: %s\n", errorMessage.c_str()); } } // Send stop dseep to network for remote masternode bool CActiveMasternode::StopMasterNode(std::string strService, std::string strKeyMasternode, std::string& errorMessage) { CTxIn vin; CKey keyMasternode; CPubKey pubKeyMasternode; if(!darkSendSigner.SetKey(strKeyMasternode, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrintf("CActiveMasternode::StopMasterNode() - Error: %s\n", errorMessage.c_str()); return false; } return StopMasterNode(vin, CService(strService, true), keyMasternode, pubKeyMasternode, errorMessage); } // Send stop dseep to network for main masternode bool CActiveMasternode::StopMasterNode(std::string& errorMessage) { if(status != MASTERNODE_IS_CAPABLE && status != MASTERNODE_REMOTELY_ENABLED) { errorMessage = "masternode is not in a running status"; LogPrintf("CActiveMasternode::StopMasterNode() - Error: %s\n", errorMessage.c_str()); return false; } status = MASTERNODE_STOPPED; CPubKey pubKeyMasternode; CKey keyMasternode; if(!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrintf("Register::ManageStatus() - Error upon calling SetKey: %s\n", errorMessage.c_str()); return false; } return StopMasterNode(vin, service, keyMasternode, pubKeyMasternode, errorMessage); } // Send stop dseep to network for any masternode bool CActiveMasternode::StopMasterNode(CTxIn vin, CService service, CKey keyMasternode, CPubKey pubKeyMasternode, std::string& errorMessage) { pwalletMain->UnlockCoin(vin.prevout); return Dseep(vin, service, keyMasternode, pubKeyMasternode, errorMessage, true); } bool CActiveMasternode::Dseep(std::string& errorMessage) { if(status != MASTERNODE_IS_CAPABLE && status != MASTERNODE_REMOTELY_ENABLED) { errorMessage = "masternode is not in a running status"; LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", errorMessage.c_str()); return false; } CPubKey pubKeyMasternode; CKey keyMasternode; if(!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrintf("CActiveMasternode::Dseep() - Error upon calling SetKey: %s\n", errorMessage.c_str()); return false; } return Dseep(vin, service, keyMasternode, pubKeyMasternode, errorMessage, false); } bool CActiveMasternode::Dseep(CTxIn vin, CService service, CKey keyMasternode, CPubKey pubKeyMasternode, std::string &retErrorMessage, bool stop) { std::string errorMessage; std::vector<unsigned char> vchMasterNodeSignature; std::string strMasterNodeSignMessage; int64_t masterNodeSignatureTime = GetAdjustedTime(); std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(masterNodeSignatureTime) + boost::lexical_cast<std::string>(stop); if(!darkSendSigner.SignMessage(strMessage, errorMessage, vchMasterNodeSignature, keyMasternode)) { retErrorMessage = "sign message failed: " + errorMessage; LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", retErrorMessage.c_str()); return false; } if(!darkSendSigner.VerifyMessage(pubKeyMasternode, vchMasterNodeSignature, strMessage, errorMessage)) { retErrorMessage = "Verify message failed: " + errorMessage; LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", retErrorMessage.c_str()); return false; } // Update Last Seen timestamp in masternode list CMasternode* pmn = mnodeman.Find(vin); if(pmn != NULL) { if(stop) mnodeman.Remove(pmn->vin); else pmn->UpdateLastSeen(); } else { // Seems like we are trying to send a ping while the masternode is not registered in the network retErrorMessage = "Darksend Masternode List doesn't include our masternode, Shutting down masternode pinging service! " + vin.ToString(); LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", retErrorMessage.c_str()); status = MASTERNODE_NOT_CAPABLE; notCapableReason = retErrorMessage; return false; } //send to all peers LogPrintf("CActiveMasternode::Dseep() - RelayMasternodeEntryPing vin = %s\n", vin.ToString().c_str()); mnodeman.RelayMasternodeEntryPing(vin, vchMasterNodeSignature, masterNodeSignatureTime, stop); return true; } bool CActiveMasternode::Register(std::string strService, std::string strKeyMasternode, std::string txHash, std::string strOutputIndex, std::string strDonationAddress, std::string strDonationPercentage, std::string& errorMessage) { CTxIn vin; CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; CPubKey pubKeyMasternode; CKey keyMasternode; CScript donationAddress = CScript(); int donationPercentage = 0; if(!darkSendSigner.SetKey(strKeyMasternode, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrintf("CActiveMasternode::Register() - Error upon calling SetKey: %s\n", errorMessage.c_str()); return false; } if(!GetMasterNodeVin(vin, pubKeyCollateralAddress, keyCollateralAddress, txHash, strOutputIndex)) { errorMessage = "could not allocate vin"; LogPrintf("CActiveMasternode::Register() - Error: %s\n", errorMessage.c_str()); return false; } CTripperpayAddress address; if (strDonationAddress != "") { if(!address.SetString(strDonationAddress)) { LogPrintf("ActiveMasternode::Register - Invalid Donation Address\n"); return false; } donationAddress.SetDestination(address.Get()); try { donationPercentage = boost::lexical_cast<int>( strDonationPercentage ); } catch( boost::bad_lexical_cast const& ) { LogPrintf("ActiveMasternode::Register - Invalid Donation Percentage (Couldn't cast)\n"); return false; } if(donationPercentage < 0 || donationPercentage > 100) { LogPrintf("ActiveMasternode::Register - Donation Percentage Out Of Range\n"); return false; } } return Register(vin, CService(strService, true), keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, donationAddress, donationPercentage, errorMessage); } bool CActiveMasternode::Register(CTxIn vin, CService service, CKey keyCollateralAddress, CPubKey pubKeyCollateralAddress, CKey keyMasternode, CPubKey pubKeyMasternode, CScript donationAddress, int donationPercentage, std::string &retErrorMessage) { std::string errorMessage; std::vector<unsigned char> vchMasterNodeSignature; std::string strMasterNodeSignMessage; int64_t masterNodeSignatureTime = GetAdjustedTime(); std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end()); std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end()); std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(masterNodeSignatureTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(PROTOCOL_VERSION) + donationAddress.ToString() + boost::lexical_cast<std::string>(donationPercentage); if(!darkSendSigner.SignMessage(strMessage, errorMessage, vchMasterNodeSignature, keyCollateralAddress)) { retErrorMessage = "sign message failed: " + errorMessage; LogPrintf("CActiveMasternode::Register() - Error: %s\n", retErrorMessage.c_str()); return false; } if(!darkSendSigner.VerifyMessage(pubKeyCollateralAddress, vchMasterNodeSignature, strMessage, errorMessage)) { retErrorMessage = "Verify message failed: " + errorMessage; LogPrintf("CActiveMasternode::Register() - Error: %s\n", retErrorMessage.c_str()); return false; } CMasternode* pmn = mnodeman.Find(vin); if(pmn == NULL) { LogPrintf("CActiveMasternode::Register() - Adding to masternode list service: %s - vin: %s\n", service.ToString().c_str(), vin.ToString().c_str()); CMasternode mn(service, vin, pubKeyCollateralAddress, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyMasternode, PROTOCOL_VERSION, donationAddress, donationPercentage); mn.UpdateLastSeen(masterNodeSignatureTime); mnodeman.Add(mn); } //send to all peers LogPrintf("CActiveMasternode::Register() - RelayElectionEntry vin = %s\n", vin.ToString().c_str()); mnodeman.RelayMasternodeEntry(vin, service, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyCollateralAddress, pubKeyMasternode, -1, -1, masterNodeSignatureTime, PROTOCOL_VERSION, donationAddress, donationPercentage); return true; } bool CActiveMasternode::GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey) { return GetMasterNodeVin(vin, pubkey, secretKey, "", ""); } bool CActiveMasternode::GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex) { CScript pubScript; // Find possible candidates vector<COutput> possibleCoins = SelectCoinsMasternode(); COutput *selectedOutput; // Find the vin if(!strTxHash.empty()) { // Let's find it uint256 txHash(strTxHash); int outputIndex = boost::lexical_cast<int>(strOutputIndex); bool found = false; BOOST_FOREACH(COutput& out, possibleCoins) { if(out.tx->GetHash() == txHash && out.i == outputIndex) { selectedOutput = &out; found = true; break; } } if(!found) { LogPrintf("CActiveMasternode::GetMasterNodeVin - Could not locate valid vin\n"); return false; } } else { // No output specified, Select the first one if(possibleCoins.size() > 0) { selectedOutput = &possibleCoins[0]; } else { LogPrintf("CActiveMasternode::GetMasterNodeVin - Could not locate specified vin from possible list\n"); return false; } } // At this point we have a selected output, retrieve the associated info return GetVinFromOutput(*selectedOutput, vin, pubkey, secretKey); } bool CActiveMasternode::GetMasterNodeVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey) { return GetMasterNodeVinForPubKey(collateralAddress, vin, pubkey, secretKey, "", ""); } bool CActiveMasternode::GetMasterNodeVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex) { CScript pubScript; // Find possible candidates vector<COutput> possibleCoins = SelectCoinsMasternodeForPubKey(collateralAddress); COutput *selectedOutput; // Find the vin if(!strTxHash.empty()) { // Let's find it uint256 txHash(strTxHash); int outputIndex = boost::lexical_cast<int>(strOutputIndex); bool found = false; BOOST_FOREACH(COutput& out, possibleCoins) { if(out.tx->GetHash() == txHash && out.i == outputIndex) { selectedOutput = &out; found = true; break; } } if(!found) { LogPrintf("CActiveMasternode::GetMasterNodeVinForPubKey - Could not locate valid vin\n"); return false; } } else { // No output specified, Select the first one if(possibleCoins.size() > 0) { selectedOutput = &possibleCoins[0]; } else { LogPrintf("CActiveMasternode::GetMasterNodeVinForPubKey - Could not locate specified vin from possible list\n"); return false; } } // At this point we have a selected output, retrieve the associated info return GetVinFromOutput(*selectedOutput, vin, pubkey, secretKey); } // Extract masternode vin information from output bool CActiveMasternode::GetVinFromOutput(COutput out, CTxIn& vin, CPubKey& pubkey, CKey& secretKey) { CScript pubScript; vin = CTxIn(out.tx->GetHash(),out.i); pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey CTxDestination address1; ExtractDestination(pubScript, address1); CTripperpayAddress address2(address1); CKeyID keyID; if (!address2.GetKeyID(keyID)) { LogPrintf("CActiveMasternode::GetMasterNodeVin - Address does not refer to a key\n"); return false; } if (!pwalletMain->GetKey(keyID, secretKey)) { LogPrintf ("CActiveMasternode::GetMasterNodeVin - Private key for address is not known\n"); return false; } pubkey = secretKey.GetPubKey(); return true; } // get all possible outputs for running masternode vector<COutput> CActiveMasternode::SelectCoinsMasternode() { vector<COutput> vCoins; vector<COutput> filteredCoins; // Retrieve all possible outputs pwalletMain->AvailableCoinsMN(vCoins); // Filter BOOST_FOREACH(const COutput& out, vCoins) { if(out.tx->vout[out.i].nValue == GetMNCollateral(pindexBest->nHeight)*COIN) { //exactly filteredCoins.push_back(out); } } return filteredCoins; } // get all possible outputs for running masternode for a specific pubkey vector<COutput> CActiveMasternode::SelectCoinsMasternodeForPubKey(std::string collateralAddress) { CTripperpayAddress address(collateralAddress); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); vector<COutput> vCoins; vector<COutput> filteredCoins; // Retrieve all possible outputs pwalletMain->AvailableCoins(vCoins); // Filter BOOST_FOREACH(const COutput& out, vCoins) { if(out.tx->vout[out.i].scriptPubKey == scriptPubKey && out.tx->vout[out.i].nValue == GetMNCollateral(pindexBest->nHeight)*COIN) { //exactly filteredCoins.push_back(out); } } return filteredCoins; } // when starting a masternode, this can enable to run as a hot wallet with no funds bool CActiveMasternode::EnableHotColdMasterNode(CTxIn& newVin, CService& newService) { if(!fMasterNode) return false; status = MASTERNODE_REMOTELY_ENABLED; notCapableReason = "Masternode started remotely"; //The values below are needed for signing dseep messages going forward this->vin = newVin; this->service = newService; LogPrintf("CActiveMasternode::EnableHotColdMasterNode() - Enabled! You may shut down the cold daemon.\n"); return true; }
[ "tripperpay@gmail.com" ]
tripperpay@gmail.com
28f9386d52cb4222648ace44d4bfc7c149fedcea
39c56722d9330a472e4930db3eed20f30670ce8d
/apps/Test/RichLaser/RichLaser.cpp
4115940a0328112a6460e75e1c15918edcd10e40
[]
no_license
Ingener74/Jupiter
645941763caad040c895215da90e6678532c0dc8
8e437e772bbf330ea2e3e59f2dc322460f9532cb
refs/heads/master
2021-01-15T15:45:45.072800
2016-09-09T12:47:08
2016-09-09T12:47:08
21,035,866
4
2
null
2014-12-18T19:17:02
2014-06-20T11:36:58
C++
UTF-8
C++
false
false
791
cpp
/* * RichLaser.cpp * * Created on: Nov 19, 2015 * Author: pavel */ #include <iostream> #include <vector> using namespace std; class OutputBuffer: public streambuf { public: OutputBuffer() : _buffer(1 << 8) { setp(_buffer.data(), _buffer.data() + _buffer.size()); } virtual ~OutputBuffer() { } virtual int sync() { printf("%s", _buffer.data()); // output for(auto& i: _buffer) i = 0; // clean setp(_buffer.data(), _buffer.data() + _buffer.size()); // reset return 0; } private: vector<char> _buffer; }; OutputBuffer outbuf; ostream out { &outbuf }; int main(int argc, char **argv) { cout << "RichLaser" << endl; out << "foo " << 42 << endl; out << "quz "; out << "bar" << endl; }
[ "shnaiderpasha@gmail.com" ]
shnaiderpasha@gmail.com
7fbd8c0c3785628c166d4091da102818f8e2fe23
63c490b2dd2b9c3bf3f6f2cda60392ee16edfe9a
/UVa/acm_484.cc
23172183b4b72a00ad7d0f5ee45f0974a3dfa61a
[]
no_license
Meng-Gen/UVa
d84811bfe607bbd6f329683e7f8c3ca9c67eb6f6
06f7c7bda732e04c11c6eb904164c23b2a546c21
refs/heads/master
2020-03-31T09:04:26.933464
2018-08-06T15:37:15
2018-08-06T15:37:15
9,917,565
1
0
null
2018-08-06T15:37:16
2013-05-07T17:32:26
C++
UTF-8
C++
false
false
686
cc
#include <iostream> #include <map> #include <vector> #include <stdio.h> int main(int argc, char* argv[]) { std::map<int, int> number_occurences; std::vector<int> number_debut_list; int curr_num; while (std::cin >> curr_num) { if (number_occurences.find(curr_num) == number_occurences.end()) { number_debut_list.push_back(curr_num); number_occurences[curr_num] = 0; } number_occurences[curr_num]++; } for (unsigned int i = 0; i < number_debut_list.size(); i++) { int num = number_debut_list[i]; std::cout << num << " " << number_occurences[num] << std::endl; } return 0; }
[ "plover@gmail.com" ]
plover@gmail.com
ed681390439e6897f78599e98037da2fab4ef9a3
e296782a95361aba4e0608707a9b289d31a0ef32
/BinaryTreeNode.cpp
2ec6333e23c6f4323fe1d12e6d10faa57563c245
[]
no_license
mma1377/Huffman
f5698f604a3895a99b4d84c2711acc14e3d000bb
0316efc274e42cd8e06bef61e2302ecddc320cf0
refs/heads/main
2023-03-19T22:11:05.965797
2021-03-12T10:54:16
2021-03-12T10:54:16
335,253,673
0
0
null
null
null
null
UTF-8
C++
false
false
711
cpp
#include "BinaryTreeNode.h" namespace BinaryTree { Node::Node(Node* left, Node* right) { _leftChild = left; _rightChild = right; _leftChild->_parent = this; _rightChild->_parent = this; _parent = nullptr; _rank = _leftChild->Rank() + _rightChild->Rank(); } Node::Node() { _leftChild = nullptr; _rightChild = nullptr; _parent = nullptr; _rank = 0; } bool Node::IsRoot() { return _parent == nullptr; } int Node::Rank() { return _rank; } void Node::IncrementRank() { _rank++; } std::string Node::CreateCode() { if (this->IsRoot()) return ""; if (this == _parent->_leftChild) return _parent->CreateCode() + "0"; return _parent->CreateCode() + "1"; } }
[ "35420218+mma1377@users.noreply.github.com" ]
35420218+mma1377@users.noreply.github.com
e6704db56be0def97ffcaa30f0080ce122886f75
add16900a969741c9e7570d3b7b47b76e22ccd04
/torch/csrc/distributed/rpc/tensorpipe_utils.h
346e420957c64c8f30a4b85e45e25e5d3f14fb30
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0", "BSD-2-Clause" ]
permissive
talemache/pytorch
55143c60b927a73f6392f7dde1f4fc8ef7ee76e6
a4da326621418dcccba50d2e827e6644e7f03ed1
refs/heads/master
2023-05-09T06:02:30.990411
2021-05-30T04:37:41
2021-05-30T04:37:41
318,314,852
2
0
NOASSERTION
2021-05-30T04:37:41
2020-12-03T20:43:29
null
UTF-8
C++
false
false
2,687
h
#pragma once #ifdef USE_TENSORPIPE #include <torch/csrc/distributed/rpc/macros.h> #include <torch/csrc/distributed/rpc/utils.h> #ifdef USE_CUDA_NOT_ROCM #include <c10/cuda/CUDAStream.h> #endif namespace tensorpipe { class Message; class Allocation; class Descriptor; } // namespace tensorpipe namespace torch { namespace distributed { namespace rpc { // A struct that holds pointers that keep alive all the memory that will be // accessed by TensorPipe during a write operation. struct TensorpipeWriteBuffers { // Allocate on heap so pointers stay valid as we move the holder. std::unique_ptr<MessageType> type; std::unique_ptr<int64_t> id; std::vector<char> payload; std::vector<char> pickle; // This contains the original tensors and the clones of the sparse tensors. std::vector<torch::Tensor> tensors; // This contains the copies of the data of the tensors that didn't own their // memory, e.g., the ones created from torch::from_blob() with no deleter. std::vector<std::vector<char>> copiedTensors; }; // A struct that holds pointers that keep alive all the memory that will be // accessed by TensorPipe during a read operation. struct TensorpipeReadBuffers { // Allocate on heap so pointers stay valid as we move the holder. std::unique_ptr<MessageType> type; std::unique_ptr<int64_t> id; std::vector<char> payload; std::vector<char> pickle; std::vector<c10::DataPtr> tensors; }; // Convert an RPC message into a TensorPipe message, plus a holder to all the // data that must be kept alive while the write is performed asynchronously. TORCH_API std::tuple<tensorpipe::Message, TensorpipeWriteBuffers> tensorpipeSerialize( Message&& rpcMessage, std::vector<c10::Device> devices, const std::shared_ptr<LazyStreamContext>& ctx); // Allocate the buffers that will hold the incoming data. They will be managed // by the returned holder, which must be kept alive until the asynchronous read // has finished. Pointers to these buffers will be stored in the returned // tensorpipe::Allocation struct. TORCH_API std::pair<tensorpipe::Allocation, TensorpipeReadBuffers> tensorpipeAllocate( const tensorpipe::Descriptor& tpDescriptor, const std::shared_ptr<LazyStreamContext>& ctx); // Convert a TensorPipe message back into an RPC message. This requires the data // to be available and can thus only be performed once the asynchronous read has // completed. The holder can be destroyed once this function returns. TORCH_API Message tensorpipeDeserialize( tensorpipe::Descriptor&& tpDescriptor, TensorpipeReadBuffers&& holder); } // namespace rpc } // namespace distributed } // namespace torch #endif // USE_TENSORPIPE
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
8ec6c9936515807b033585292daeb10848167bd4
9ccb18b8e68dd1bdb6e9055400332dfcfc89b75c
/algorithms/OPQ/searcher_tester.cpp
1df56a533a4c258a51196d07dc82203b67125733
[]
no_license
wenli1206/nns_benchmark
661c8076d7f612ef45baa50e26cfb2728557e923
d4e225a66befbd521756f62f3c09cb3d840567a5
refs/heads/master
2021-01-16T22:14:54.041054
2016-05-20T01:16:19
2016-05-20T01:16:19
59,187,897
0
0
null
2016-05-19T08:24:46
2016-05-19T08:24:46
null
UTF-8
C++
false
false
7,236
cpp
// Copyright 2012 Yandex Artem Babenko #include <iostream> #include <boost/program_options.hpp> #include <sys/time.h> #include <mkl.h> #include "searcher.h" #include "indexer.h" using namespace boost::program_options; using std::endl; using std::ofstream; /** * Number of threads for indexing */ Dimensions SPACE_DIMENSION; /** * File with vocabularies for multiindex structure */ string coarse_vocabs_file; /** * File with vocabularies for reranking */ string fine_vocabs_file; /** * Reranking approach, should be USE_RESIDUALS or USE_INIT_POINTS */ RerankMode mode; /** * Common prefix of all multiindex files */ string index_files_prefix; /** * File with queries (.bvec or .fvec) */ string queries_file; /** * Type, should be BVEC or FVEC */ PointType query_point_type; /** * File with groundtruth (.ivec) */ string groundtruth_file; /** * Number of queries to search */ int queries_count; /** * Should we rerank? */ bool do_rerank; /** * Number of neighbours to look over */ int neighbours_count; /** * File to write report in */ string report_file; /** * Number of nearest centroids for each group of dimensions to handle */ int subspaces_centroids_count; string data_file; int data_count; int use_originaldata; int k; int SetOptions(int argc, char** argv) { options_description description("Options"); description.add_options() ("index_files_prefix,i", value<string>()) ("queries_file,q", value<string>()) ("queries_count,n", value<int>()) ("neighbours_count,k", value<int>()) ("groundtruth_file,g", value<string>()) ("data_file,a", value<string>()) ("data_count,m", value<int>()) ("coarse_vocabs_file,c", value<string>()) ("fine_vocabs_file,f", value<string>()) ("query_point_type,t", value<string>()) ("use_residuals,r", value<int>()) ("do_rerank,l", value<int>()) ("report_file,o", value<string>()) ("space_dim,D", value<int>()) ("dim,d", value<int>()) ("use_originaldata,u", value<int>()) ("subspaces_centroids_count,s", value<int>()) ("k_neighbors,K", value<int>()); variables_map name_to_value; try { store(command_line_parser(argc, argv).options(description).run(), name_to_value); } catch (const invalid_command_line_syntax &inv_syntax) { switch (inv_syntax.kind()) { case invalid_syntax::missing_parameter : cout << "Missing argument for option '" << inv_syntax.tokens() << "'.\n"; break; default: cout << "Syntax error, kind " << int(inv_syntax.kind()) << "\n"; break; }; return 1; } catch (const unknown_option &unkn_opt) { cout << "Unknown option '" << unkn_opt.get_option_name() << "'\n"; return 1; } if (name_to_value.count("help")) { cout << description << "\n"; return 1; } coarse_vocabs_file = name_to_value["coarse_vocabs_file"].as<string>(); fine_vocabs_file = name_to_value["fine_vocabs_file"].as<string>(); SPACE_DIMENSION = name_to_value["dim"].as<int>(); index_files_prefix = name_to_value["index_files_prefix"].as<string>(); queries_file = name_to_value["queries_file"].as<string>(); report_file = name_to_value["report_file"].as<string>(); groundtruth_file = name_to_value["groundtruth_file"].as<string>(); queries_count = name_to_value["queries_count"].as<int>(); neighbours_count = name_to_value["neighbours_count"].as<int>(); subspaces_centroids_count = name_to_value["subspaces_centroids_count"].as<int>(); data_file= name_to_value["data_file"].as<string>(); data_count = name_to_value["data_count"].as<int>(); use_originaldata = name_to_value["use_originaldata"].as<int>(); k = name_to_value["k_neighbors"].as<int>(); do_rerank = (name_to_value["do_rerank"].as<int>() == 0) ? true : false; //cout<< "rerank:"<<do_rerank<<endl; mode = (name_to_value["use_residuals"].as<int>() == 0) ? USE_RESIDUALS : USE_INIT_POINTS; if (name_to_value["query_point_type"].as<string>() == "FVEC") { query_point_type = FVEC; } else if(name_to_value["query_point_type"].as<string>() == "BVEC") { query_point_type = BVEC; } return 0; } float diff_timeval(timeval t1, timeval t2) { return (float) (t1.tv_sec - t2.tv_sec) + (t1.tv_usec - t2.tv_usec) * 1e-6; } template<class TSearcher> void TestSearcher(TSearcher& searcher, const Points& queries, const vector<vector<PointId> >& groundtruth,const Points& dataset) { searcher.Init(index_files_prefix, coarse_vocabs_file, fine_vocabs_file, mode, subspaces_centroids_count, do_rerank,use_originaldata); //,use_originaldata //* int neig_counts[17]={100,200,500,1000,2000,3000,5000,7000,10000,15000,17000,20000,25000,30000,40000,50000,60000}; std::ofstream out(report_file.c_str(),ios::app); for(int j = 0; j<17;j++) { cout<<j<<endl; vector< vector< DistanceToPoint> > result; result.resize(queries_count); timeval start; timeval end; float time=0; gettimeofday(&start, NULL); for(int i = 0; i < queries_count; ++i) //queries_count { searcher.GetNearestNeighbours(queries[i],neig_counts[j], &result[i],dataset); } gettimeofday(&end, NULL); time += diff_timeval(end, start); float recall = 0.0; float rde = 0.0; float map =0.0; for(int i = 0; i < queries_count; ++i) //queries_count { recall += GetRecall(k,groundtruth[i],result[i]); rde += compute_relative_distance_error(k,dataset,queries[i],groundtruth[i],result[i]); map +=compute_mean_average_precision(k,groundtruth[i],result[i]); } recall = recall/queries_count; rde = rde/ queries_count ; time= time/queries_count ; map = map/queries_count ; out.setf(ios::fixed); out << recall<<" "<< rde << " " << time<<" #N_"<<neig_counts[j]<<" "<<map<<" "<<endl; if(recall==1.0) { break; } }//*/ } int main(int argc, char** argv) { SetOptions(argc, argv); cout << "Options are set ...\n"; Points queries; if(query_point_type == BVEC) { ReadPoints<unsigned char, Coord>(queries_file, &queries, queries_count); } else if (query_point_type == FVEC) { ReadPoints<float, Coord>(queries_file, &queries, queries_count); } //dataset Points dataset; ReadPoints<float, Coord>(data_file, &dataset, data_count); cout << "Queries are read ...\n"; vector<vector<PointId> > groundtruth; ReadPoints<int, PointId>(groundtruth_file, &groundtruth, queries_count); MKL_Set_Num_Threads(1); cout << "Groundtruth is read ...\n"; vector<Centroids> fine_vocabs; ReadFineVocabs<float>(fine_vocabs_file, &fine_vocabs); if(fine_vocabs.size() == 8) { MultiSearcher<RerankADC8, PointId> searcher; TestSearcher<MultiSearcher<RerankADC8, PointId> > (searcher, queries, groundtruth,dataset); } else if(fine_vocabs.size() == 16) { MultiSearcher<RerankADC16, PointId> searcher; TestSearcher<MultiSearcher<RerankADC16, PointId> > (searcher, queries, groundtruth,dataset); } return 0; }
[ "yifang.bill.sun@gmail.com" ]
yifang.bill.sun@gmail.com
d8bed7d65f7f981333737de31736476ee5d6360f
d312d534036de17b5dad24a26bf710c9fbf102f5
/src/modules/collection/dummy.cpp
edea1475c34d30b03306da6d10c86c84c7dbf793
[]
no_license
wshmaple/engine
e9f3964e7210125b71fa0294c33df35494abb9e2
f4ae34f9600ba0004af953a7d2447fd835ad85c4
refs/heads/master
2021-05-04T12:27:11.545596
2018-01-30T17:01:05
2018-01-30T18:44:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
27
cpp
#include "ConcurrentMap.h"
[ "martin.gerhardy@gmail.com" ]
martin.gerhardy@gmail.com
5f61e44d96264ee3e38ce0af5989e48d9a926185
cffc460605febc80e8bb7c417266bde1bd1988eb
/before2020/UVa_ACM/102 - Volume CII/UVa 10209.cpp
6aeaf6bda072f954e1698c469992c678056f256d
[]
no_license
m80126colin/Judge
f79b2077f2bf67a3b176d073fcdf68a8583d5a2c
56258ea977733e992b11f9e0cb74d630799ba274
refs/heads/master
2021-06-11T04:25:27.786735
2020-05-21T08:55:03
2020-05-21T08:55:03
19,424,030
7
4
null
null
null
null
UTF-8
C++
false
false
349
cpp
#include <iostream> #include <math.h> #include <iomanip> using namespace std; int main() { double a,x,y,z; cout<<showpoint<<fixed; while (cin>>a) { x=(1.0+2.0*acos(0.0)/3-pow(3,0.5))*a*a; y=(-4.0+2.0*acos(0.0)/3+pow(3,0.5)*2)*a*a; z=(4.0-4.0*acos(0.0)/3-pow(3,0.5))*a*a; cout<<setprecision(3)<<x<<" "<<y<<" "<<z<<endl; } }
[ "m80126colin@gmail.com" ]
m80126colin@gmail.com
851b5e21f9d2e2480da9ace40e479081c5888e44
e7704f7fe5b8d90fee5ce666313f25e1a1c72f3c
/include/scenes/test_particles_scene.h
f42a06bd81e43478c0e1d362064d1c157a6acf83
[]
no_license
BrandonColbert/Geon
f5fc0ae0a150ace65252df27a32a2fccea93a050
41e695551248a9b6878ef1eed854e1fc00a59449
refs/heads/master
2023-04-10T14:19:42.822019
2020-12-12T00:10:52
2020-12-12T00:10:52
304,966,890
0
0
null
null
null
null
UTF-8
C++
false
false
123
h
#pragma once #include "scenes/scene.h" class TestParticlesScene : public Scene { protected: void create() override; };
[ "brandoncolbertos@gmail.com" ]
brandoncolbertos@gmail.com
ebe9364002797579ee2455239531912df32a3160
0ffc74454f804f8b317dea202961c2bef5193085
/src/zlra/accumulatorcheckpoints.cpp
09b61c2d583f0c52269068aa534b75507156eb01
[ "MIT" ]
permissive
cryptobot123/learnium
1bc1b2e69215dab59ed9fee63a8bd9da2ed06121
2ce4867c5b80acd4fe1be9cd29b9cddfab9dea0a
refs/heads/main
2023-01-03T19:50:44.217685
2020-10-30T21:08:32
2020-10-30T21:08:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,670
cpp
// Copyright (c) 2018-2019 The PIVX developers // Copyright (c) 2020 The Learnium developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "accumulatorcheckpoints.h" #include "accumulatorcheckpoints.json.h" namespace AccumulatorCheckpoints { std::map<int, Checkpoint> mapCheckpoints; UniValue read_json(const std::string& jsondata) { UniValue v; if (!v.read(jsondata) || !v.isArray()) { return UniValue(UniValue::VARR); } return v.get_array(); } bool LoadCheckpoints(const std::string& strNetwork) { UniValue v; if (strNetwork == "main") v = read_json(GetMainCheckpoints()); else if (strNetwork == "test") v = read_json(GetTestCheckpoints()); else if (strNetwork == "regtest") v = read_json(GetRegTestCheckpoints()); else return false; if (v.empty()) return false; for (unsigned int idx = 0; idx < v.size(); idx++) { const UniValue &val = v[idx]; const UniValue &o = val.get_obj(); const UniValue &vHeight = find_value(o, "height"); if (!vHeight.isNum()) return false; int nHeight = vHeight.get_int(); if (nHeight < 0) return false; Checkpoint checkpoint; for (auto denom : libzerocoin::zerocoinDenomList) { const UniValue& vDenomValue = find_value(o, std::to_string(denom)); if (!vDenomValue.isStr()) { return false; } CBigNum bn = 0; bn.SetHex(vDenomValue.get_str()); checkpoint.insert(std::make_pair(denom, bn)); } mapCheckpoints.insert(std::make_pair(nHeight, checkpoint)); } return true; } Checkpoint GetClosestCheckpoint(const int& nHeight, int& nHeightCheckpoint) { nHeightCheckpoint = -1; for (auto it : mapCheckpoints) { //only checkpoints that are less than the height requested (unless height is less than the first checkpoint) if (it.first < nHeight) { if (nHeightCheckpoint == -1) nHeightCheckpoint = it.first; if (nHeight - it.first < nHeightCheckpoint) nHeightCheckpoint = it.first; } } if (nHeightCheckpoint != -1) return mapCheckpoints.at(nHeightCheckpoint); return Checkpoint(); } }
[ "72593731+learniumcoin@users.noreply.github.com" ]
72593731+learniumcoin@users.noreply.github.com
f031e5638bb65c2e2642c8f6c510ba71f2e10e3a
0c958692bb3abf99ecbd03bd75a605b202d4da5a
/NtupleTools/plugins/PATIsolationFiller.h
b63b3ed56152c3e9413ba649c1a140dccb631502
[]
no_license
tmrhombus/UWAnalysis
a9ed18a7ba8726522c8d98fbdc018c77d80c5cc5
eb9e0794e1b847f36c660a55d3631176a39148e2
refs/heads/master
2021-01-23T20:46:41.578341
2017-05-01T08:26:57
2017-05-01T08:26:57
10,620,824
0
0
null
2014-10-21T11:21:16
2013-06-11T12:19:43
Python
UTF-8
C++
false
false
2,467
h
// system include files #include <memory> // user include files #include "CommonTools/Utils/interface/StringObjectFunction.h" #include "DataFormats/PatCandidates/interface/LookupTableRecord.h" #include <TTree.h> #include "UWAnalysis/NtupleTools/interface/NtupleFillerBase.h" // // class decleration // template<typename T> class PATIsolationFiller : public NtupleFillerBase { public: PATIsolationFiller(){ } PATIsolationFiller(const edm::ParameterSet& iConfig, TTree* t): NtupleFillerBase(iConfig,t), src_(iConfig.getParameter<edm::InputTag>("src")), cone_(iConfig.getParameter<double>("cone")), type_(iConfig.getParameter<std::string>("type")), leg_(iConfig.getParameter<int>("leg")), veto_(iConfig.getParameter<double>("innerVeto")), multiplicity_(iConfig.getParameter<bool>("multiplicity")), tag_(iConfig.getParameter<std::string>("tag")), leadingOnly_(iConfig.getUntrackedParameter<bool>("leadingOnly",true)) { singleValue=0.; value = new std::vector<double>(); if(!leadingOnly_) vbranch = t->Branch(tag_.c_str(),"std::vector<double>",&value); else vbranch = t->Branch(tag_.c_str(),&singleValue,(tag_+"/F").c_str()); } ~PATIsolationFiller() { } void fill(const edm::Event& iEvent, const edm::EventSetup& iSetup) { edm::Handle<std::vector<T> > handle; singleValue=-1; if(value->size()>0) value->clear(); if(iEvent.getByLabel(src_,handle)) { if(leadingOnly_) { if(handle->size()>0) singleValue = (*function)(handle->at(0)); } else for(unsigned int i=0;i<handle->size();++i) { value->push_back((*function)(handle->at(i))); } } // else // { // printf("Obj not found \n"); // } // vbranch->Fill(); } protected: std::pair<double,int> getIsoDeposit(const T& obj,int leg,std::string type) { edm::Ptr<T> ptr = } edm::InputTag src_; std::string var_; std::string tag_; bool multiplicity_; bool leadingOnly_; double cone_; std::string type_; double veto_; int leg_; float singlevalue; TBranch *vbranch; std::vector<double>* value; }; #include "UWAnalysis/DataFormats/interface/CompositePtrCandidateT1T2MEt.h" #include "UWAnalysis/DataFormats/interface/CompositePtrCandidateTMEt.h" typedef PATIsolationFiller<PATMuPair> PATMuPairIsolationFiller; typedef PATIsolationFiller<pat::Muon> PATMuonFiller;
[ "tomperry7@gmail.com" ]
tomperry7@gmail.com
9ce56ceb9b48cd88959db7682eee3134634621a3
e24898f0a11f837bbdf0dba8e9b155a28166fa9b
/enhance_alg1.h
63df4ff26af24c647120bbff1b3e6286dca3a999
[]
no_license
love1cat/EvenSim
0bdbe2d7efc1dd91a7b756d3e127a0c834a76f08
cf6b7640a3e0dfd945984b1367345d5c5118b6b5
refs/heads/master
2021-01-10T20:54:51.329217
2014-11-18T01:14:27
2014-11-18T01:14:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
483
h
// // enhance_alg1.h // EvenSim // // Created by Yuan on 9/28/14. // Copyright (c) 2014 Yuan. All rights reserved. // #ifndef __EvenSim__enhance_alg1__ #define __EvenSim__enhance_alg1__ #include "enhance_algbase.h" namespace even_energy{ class EnhanceAlg1 : public EnhanceAlgBase { public: virtual void enhance(GreedyAlgBase * grd_alg) const; private: int GetLowestTarget(std::vector<TargetPtr> &tvec) const; }; } #endif /* defined(__EvenSim__enhance_alg1__) */
[ "yuan.uconn@gmail.com" ]
yuan.uconn@gmail.com
449eb0299969c3e93b000bcc630ceb9421a96f96
0e08d948f73152fbafabee185a457ff076a63080
/virtools/CKRenderManager.cpp
17e1b2ff6b029ace047f73fe2d250d7e6c94516f
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
Gamepiaynmo/BallanceModLoader
a492f6e14e4d07b9a7cb1790258216a93be57706
852651edde57475379c653e1959977c5911c0708
refs/heads/master
2023-05-12T23:47:20.120249
2023-05-09T08:34:52
2023-05-09T08:34:52
252,963,888
58
8
MIT
2023-08-23T02:08:36
2020-04-04T10:09:40
C++
UTF-8
C++
false
false
5,224
cpp
#include "CKRenderManager.h" NAKED int CKRenderManager::GetRenderDriverCount() { JUMPV(0x78); } NAKED VxDriverDesc* CKRenderManager::GetRenderDriverDescription(int Driver) { JUMPV(0x7c); } NAKED void CKRenderManager::GetDesiredTexturesVideoFormat(VxImageDescEx& VideoFormat) { JUMPV(0x80); } NAKED void CKRenderManager::SetDesiredTexturesVideoFormat(VxImageDescEx& VideoFormat) { JUMPV(0x84); } NAKED CKRenderContext* CKRenderManager::GetRenderContext(int pos) { JUMPV(0x88); } NAKED CKRenderContext* CKRenderManager::GetRenderContextFromPoint(CKPOINT& pt) { JUMPV(0x8c); } NAKED int CKRenderManager::GetRenderContextCount() { JUMPV(0x90); } NAKED void CKRenderManager::Process() { JUMPV(0x94); } NAKED void CKRenderManager::FlushTextures() { JUMPV(0x98); } NAKED CKRenderContext* CKRenderManager::CreateRenderContext(void* Window, int Driver, CKRECT* rect, CKBOOL Fullscreen, int Bpp, int Zbpp, int StencilBpp, int RefreshRate) { JUMPV(0x9c); } NAKED CKERROR CKRenderManager::DestroyRenderContext(CKRenderContext* context) { JUMPV(0xa0); } NAKED void CKRenderManager::RemoveRenderContext(CKRenderContext* context) { JUMPV(0xa4); } NAKED CKVertexBuffer* CKRenderManager::CreateVertexBuffer() { JUMPV(0xa8); } NAKED void CKRenderManager::DestroyVertexBuffer(CKVertexBuffer* VB) { JUMPV(0xac); } NAKED void CKRenderManager::SetRenderOptions(CKSTRING RenderOptionString, DWORD Value) { JUMPV(0xb0); } NAKED const VxEffectDescription& CKRenderManager::GetEffectDescription(int EffectIndex) { JUMPV(0xb4); } NAKED int CKRenderManager::GetEffectCount() { JUMPV(0xb8); } NAKED int CKRenderManager::AddEffect(const VxEffectDescription& NewEffect) { JUMPV(0xbc); } NAKED void CKRenderManager::DrawAABB(CKRenderContext* iRC, const VxBbox& iBox, const CKDWORD iColor, const VxMatrix* iTransform) { JUMPV(0xc0); } NAKED void CKRenderManager::DrawNormal(CKRenderContext* iRC, const VxRay& iRay, const CKDWORD iColor, const VxMatrix* iTransform) { JUMPV(0xc4); } NAKED void CKRenderManager::DrawPoint(CKRenderContext* iRC, const VxVector& iPoint, const CKDWORD iColor, const VxMatrix* iTransform) { JUMPV(0xc8); } NAKED void CKRenderManager::DrawPlane(CKRenderContext* iRC, const VxPlane& iPlane, const VxVector& iPoint, const CKDWORD iColor, const VxMatrix* iTransform) { JUMPV(0xcc); } NAKED void CKRenderManager::DrawFrustum(CKRenderContext* iRC, const VxFrustum& iFrustum, const CKDWORD iColor, const VxMatrix* iTransform) { JUMPV(0xd0); } NAKED void CKRenderManager::DrawSphere(CKRenderContext* iRC, const VxSphere& iSphere, const CKDWORD iColor, const VxMatrix* iTransform, const int iSubdivisions) { JUMPV(0xd4); } NAKED void CKRenderManager::DrawParabolic(CKRenderContext* iRC, const VxVector& iStartPos, const VxVector& iSpeed, const VxVector& iAcceleration, float iDrawingTime, const int iSubdivisions, const CKDWORD iColor, const VxMatrix* iTransform) { JUMPV(0xd8); } NAKED void CKRenderManager::DrawPoint2D(CKRenderContext* iRC, const Vx2DVector& iPoint, const CKDWORD iColor) { JUMPV(0xdc); } NAKED void CKRenderManager::DrawRectangle(CKRenderContext* iRC, const VxRect& iRect, const CKDWORD iColor) { JUMPV(0xe0); } NAKED void CKRenderManager::DrawFillRectangle(CKRenderContext* iRC, const VxRect& iRect, const CKDWORD iColor) { JUMPV(0xe4); } NAKED void CKRenderManager::DrawText(CKRenderContext* iRC, const Vx2DVector& iPoint, const char* iText, const CKDWORD iColor) { JUMPV(0xe8); } NAKED void CKRenderManager::RegisterAABB(const VxBbox& iBox, const CKDWORD iColor, float iRemainingTime, const VxMatrix* iTransform) { JUMPV(0xec); } NAKED void CKRenderManager::RegisterNormal(const VxRay& iRay, const CKDWORD iColor, float iRemainingTime, const VxMatrix* iTransform) { JUMPV(0xf0); } NAKED void CKRenderManager::RegisterPoint(const VxVector& iPoint, const CKDWORD iColor, float iRemainingTime, const VxMatrix* iTransform) { JUMPV(0xf4); } NAKED void CKRenderManager::RegisterPlane(const VxPlane& iPlane, const VxVector& iPoint, const CKDWORD iColor, float iRemainingTime, const VxMatrix* iTransform) { JUMPV(0xf8); } NAKED void CKRenderManager::RegisterFrustum(const VxFrustum& iFrustum, const CKDWORD iColor, float iRemainingTime, const VxMatrix* iTransform) { JUMPV(0xfc); } NAKED void CKRenderManager::RegisterSphere(const VxSphere& iSphere, const CKDWORD iColor, float iRemainingTime, const VxMatrix* iTransform, const int iSubdivisions) { JUMPV(0x100); } NAKED void CKRenderManager::RegisterParabolic(const VxVector& iStartPos, const VxVector& iSpeed, const VxVector& iAcceleration, float iDrawingTime, const int iSubdivisions, const CKDWORD iColor, float iRemainingTime, const VxMatrix* iTransform) { JUMPV(0x104); } NAKED void CKRenderManager::RegisterPoint2D(const Vx2DVector& iPoint, const CKDWORD iColor, float iRemainingTime) { JUMPV(0x108); } NAKED void CKRenderManager::RegisterRectangle(const VxRect& iRect, const CKDWORD iColor, float iRemainingTime) { JUMPV(0x10c); } NAKED void CKRenderManager::RegisterFillRectangle(const VxRect& iRect, const CKDWORD iColor, float iRemainingTime) { JUMPV(0x110); } NAKED void CKRenderManager::RegisterText(const char* iText, const CKDWORD iColor, float iRemainingTime) { JUMPV(0x114); }
[ "gamepiaynmo@gmail.com" ]
gamepiaynmo@gmail.com
d20bb1df572a87630bd59e0fbbf659bf3f89d278
6bcdb9e8836cd60e972be865beb50fbfefdfa650
/libs/core/include/fcppt/cast/int_to_float_fun.hpp
e3e6b74894897dc39b0ca5e706e017041874f11b
[ "BSL-1.0" ]
permissive
pmiddend/fcppt
4dbba03f7386c1e0d35c21aa0e88e96ed824957f
9f437acbb10258e6df6982a550213a05815eb2be
refs/heads/master
2020-09-22T08:54:49.438518
2019-11-30T14:14:04
2019-11-30T14:14:04
225,129,546
0
0
BSL-1.0
2019-12-01T08:31:12
2019-12-01T08:31:11
null
UTF-8
C++
false
false
719
hpp
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_CAST_INT_TO_FLOAT_FUN_HPP_INCLUDED #define FCPPT_CAST_INT_TO_FLOAT_FUN_HPP_INCLUDED #include <fcppt/cast/int_to_float.hpp> namespace fcppt { namespace cast { /** \brief Function object of fcppt::cast::int_to_float \ingroup fcpptcasts */ struct int_to_float_fun { template< typename Dest, typename Source > static constexpr Dest execute( Source const &_source ) noexcept { return fcppt::cast::int_to_float< Dest >( _source ); } }; } } #endif
[ "carlphilippreh@gmail.com" ]
carlphilippreh@gmail.com
b13506f086dcaaa464903dabdfffc64bc06a2b89
42197a436b880b3175dc5d6333866087cf6a7dbc
/kadas/app/milx/kadasmilxitem.h
13317a2cc3168f298bcb9ba52db4ce672926bc27
[]
no_license
mhugent/kadas-albireo2
2a4dce3cc15592c2271bc7efc89088e8d168a0b8
8744ef1e1cbc772a51a02a6654556d9dc660824d
refs/heads/master
2020-08-27T07:47:00.298743
2019-10-23T19:29:16
2019-10-23T20:21:24
217,289,123
0
0
null
2019-10-24T12:04:29
2019-10-24T12:04:29
null
UTF-8
C++
false
false
6,993
h
/*************************************************************************** kdasmilxitem.h -------------- copyright : (C) 2019 by Sandro Mani email : smani at sourcepole dot ch ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KADASMILXITEM_H #define KADASMILXITEM_H #include <kadas/gui/mapitems/kadasmapitem.h> #include <kadas/app/milx/kadasmilxclient.h> // MilX items always in EPSG:4326 class KadasMilxItem : public KadasMapItem { Q_OBJECT Q_PROPERTY( QString mssString READ mssString WRITE setMssString ) Q_PROPERTY( QString militaryName READ militaryName WRITE setMilitaryName ) Q_PROPERTY( int minNPoints READ minNPoints WRITE setMinNPoints ) Q_PROPERTY( bool hasVariablePoints READ hasVariablePoints WRITE setHasVariablePoints ) public: KadasMilxItem( QObject *parent = nullptr ); void setSymbol( const KadasMilxClient::SymbolDesc &symbolDesc ); const QString &mssString() const { return mMssString; } void setMssString( const QString &mssString ); const QString &militaryName() const { return mMilitaryName; } void setMilitaryName( const QString &militaryName ); int minNPoints() const { return mMinNPoints; } void setMinNPoints( int minNPoints ); bool hasVariablePoints() const { return mHasVariablePoints; } void setHasVariablePoints( bool hasVariablePoints ); QString itemName() const override { return mMilitaryName; } KadasItemRect boundingBox() const override; Margin margin() const override; QList<KadasMapItem::Node> nodes( const QgsMapSettings &settings ) const override; bool intersects( const KadasMapRect &rect, const QgsMapSettings &settings ) const override; void render( QgsRenderContext &context ) const override; QString asKml( const QgsRenderContext &context, QuaZip *kmzZip = nullptr ) const override; // State interface struct State : KadasMapItem::State { QList<KadasItemPos> points; QMap<KadasMilxClient::AttributeType, double> attributes; QMap<KadasMilxClient::AttributeType, KadasItemPos> attributePoints; QList<int> controlPoints; QPoint userOffset; int pressedPoints = 0; void assign( const KadasMapItem::State *other ) override { *this = *static_cast<const State *>( other ); } State *clone() const override SIP_FACTORY { return new State( *this ); } QJsonObject serialize() const override; bool deserialize( const QJsonObject &json ) override; }; const State *constState() const { return static_cast<State *>( mState ); } // Draw interface (all points in item crs) bool startPart( const KadasMapPos &firstPoint, const QgsMapSettings &mapSettings ) override; bool startPart( const AttribValues &values, const QgsMapSettings &mapSettings ) override; void setCurrentPoint( const KadasMapPos &p, const QgsMapSettings &mapSettings ) override; void setCurrentAttributes( const AttribValues &values, const QgsMapSettings &mapSettings ) override; bool continuePart( const QgsMapSettings &mapSettings ) override; void endPart() override; AttribDefs drawAttribs() const override; AttribValues drawAttribsFromPosition( const KadasMapPos &pos, const QgsMapSettings &mapSettings ) const override; KadasMapPos positionFromDrawAttribs( const AttribValues &values, const QgsMapSettings &mapSettings ) const override; // Edit interface (all points in item crs) EditContext getEditContext( const KadasMapPos &pos, const QgsMapSettings &mapSettings ) const override; void edit( const EditContext &context, const KadasMapPos &newPoint, const QgsMapSettings &mapSettings ) override; void edit( const EditContext &context, const AttribValues &values, const QgsMapSettings &mapSettings ) override; void populateContextMenu( QMenu *menu, const EditContext &context, const KadasMapPos &clickPos, const QgsMapSettings &mapSettings ) override; AttribValues editAttribsFromPosition( const EditContext &context, const KadasMapPos &pos, const QgsMapSettings &mapSettings ) const override; KadasMapPos positionFromEditAttribs( const EditContext &context, const AttribValues &values, const QgsMapSettings &mapSettings ) const override; KadasItemPos position() const override; void setPosition( const KadasItemPos &pos ) override; QList<QPoint> computeScreenPoints( const QgsMapToPixel &mapToPixel, const QgsCoordinateTransform &mapCrst ) const; QList< QPair<int, double> > computeScreenAttributes( const QgsMapToPixel &mapToPixel, const QgsCoordinateTransform &mapCrst ) const; bool isMultiPoint() const; KadasMilxClient::NPointSymbol toSymbol( const QgsMapToPixel &mapToPixel, const QgsCoordinateReferenceSystem &mapCrs, bool colored = true ) const; void writeMilx( QDomDocument &doc, QDomElement &itemElement ) const; static KadasMilxItem *fromMilx( const QDomElement &itemElement, const QgsCoordinateTransform &crst, int symbolSize ); static QRect computeScreenExtent( const QgsRectangle &mapExtent, const QgsMapToPixel &mapToPixel ); private: enum AttribIds { AttrX = -2, AttrY = -1, AttrW = KadasMilxClient::AttributeWidth, AttrL = KadasMilxClient::AttributeLength, AttrR = KadasMilxClient::AttributeRadius, AttrA = KadasMilxClient::AttributeAttitude }; QString mMssString; QString mMilitaryName; int mMinNPoints = -1; bool mHasVariablePoints = false; // Symbol cache mutable QImage mCachedGraphic; mutable QPoint mCachedGraphicOffset; mutable QgsRectangle mCachedExtent; Margin mMargin; State *state() { return static_cast<State *>( mState ); } State *createEmptyState() const override { return new State(); } SIP_FACTORY KadasMapItem *_clone() const override { return new KadasMilxItem(); } SIP_FACTORY double metersToPixels( const QgsPointXY &refPoint, const QgsMapToPixel &mapToPixel, const QgsCoordinateTransform &mapCrst ) const; void updateSymbol( const QgsMapSettings &mapSettings, const KadasMilxClient::NPointSymbolGraphic &result ); static void posPointNodeRenderer( QPainter *painter, const QPointF &screenPoint, int nodeSize ); static void ctrlPointNodeRenderer( QPainter *painter, const QPointF &screenPoint, int nodeSize ); }; #endif // KADASMILXITEM_H
[ "manisandro@gmail.com" ]
manisandro@gmail.com
0af43722880b774246eeb600f8c7972feada1598
db04ecf258aef8a187823b8e47f4a1ae908e5897
/Cplus/MinimumNumberofRemovalstoMakeMountainArray.cpp
362f4c85c1227add34530a47ef4de502a9889ea7
[ "MIT" ]
permissive
JumHorn/leetcode
9612a26e531ceae7f25e2a749600632da6882075
abf145686dcfac860b0f6b26a04e3edd133b238c
refs/heads/master
2023-08-03T21:12:13.945602
2023-07-30T07:00:50
2023-07-30T07:00:50
74,735,489
0
0
null
null
null
null
UTF-8
C++
false
false
739
cpp
#include <vector> using namespace std; /* LIS longest increasing and longest decreasing array */ class Solution { public: int minimumMountainRemovals(vector<int> &nums) { int N = nums.size(); vector<int> prefix(N), suffix(N); for (int i = 0; i < N; ++i) { for (int j = 0; j < i; ++j) { if (nums[i] > nums[j]) prefix[i] = max(prefix[j], prefix[i]); } ++prefix[i]; } for (int i = N - 1; i >= 0; --i) { for (int j = N - 1; j > i; --j) { if (nums[i] > nums[j]) suffix[i] = max(suffix[j], suffix[i]); } ++suffix[i]; } int res = 0; for (int i = 0; i < N; ++i) { if (prefix[i] >= 2 && suffix[i] >= 2) res = max(res, prefix[i] + suffix[i] - 1); } return N - res; } };
[ "JumHorn@gmail.com" ]
JumHorn@gmail.com
2161dc201c0aa892a6acdcb0a706924fe5344655
7a5bae16524ea2f59aab249dbae4d9788ce49e97
/2178_미로탐색2.cpp
23d07afde9dff9f99767561e755bd64952216b22
[]
no_license
tuktik/backjoon
25ec144661cd90e004b833890c9e7192e8a838aa
1bd2cd2573cdc66240c755708bf58a1a26710f57
refs/heads/master
2021-01-21T13:04:04.872267
2016-04-14T11:45:51
2016-04-14T11:45:51
48,376,274
0
0
null
null
null
null
UTF-8
C++
false
false
910
cpp
#include <iostream> using namespace std; int mazzArr[105][105]; int visited[105][105]; int n, m; int min(int a, int b, int c, int d) { int minVal = a<b?a:b; minVal = minVal<c ? minVal : c; minVal = minVal<d ? minVal : d; return minVal; } int dfs(int x, int y,int cnt) { if (x >= m || x < 0) return 999999; if (y >= n || y < 0) return 999999; if (mazzArr[y][x] == 0) return 999999; if (x == m - 1 && y == n - 1) return 1; if (visited[y][x]>cnt || visited[y][x]==0) { visited[y][x] = cnt++; int a = dfs(x + 1, y, cnt); int b = dfs(x - 1, y, cnt); int c = dfs(x, y + 1, cnt); int d = dfs(x, y - 1, cnt); return 1 + min(a, b, c, d); } return 99999999; } int main() { cin >> n; cin >> m; char tmp; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> tmp; mazzArr[i][j] = (int)tmp - 48; } } cout << dfs(0, 0,0) << endl; return 0; }
[ "saya7485@naver.com" ]
saya7485@naver.com
a5a0b6fb4875fd0598b7c8ffecc03eb313898304
95d3d5116abe526316b3a01c413679ce82088943
/ERGO Gen 5 Test1/GPS_UBLOX.cpp
17cac4b11b5ba69966e3a91eaec48c215dbb75ed
[]
no_license
simonfrfr/ERGO_GEN_5
b56c3dad5964c44e73d691c1d6f212ff4226292f
a30153d626552f0dc045b9607a8fa91c91d32f40
refs/heads/master
2021-01-20T10:11:03.012597
2014-06-05T20:46:34
2014-06-05T20:46:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,942
cpp
/* GPS_UBLOX.cpp - Ublox GPS library for CCS This code works with boards based on Ti's C6000 Series Written by Simon Tsaoussis This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. GPS configuration : Ublox protocol Baud rate : 38400 Active messages : NAV-POSLLH Geodetic Position Solution, PAGE 66 of datasheet NAV-VELNED Velocity Solution in NED, PAGE 71 of datasheet NAV-STATUS Receiver Navigation Status or NAV-SOL Navigation Solution Information Methods: Init() : GPS Initialization Read() : Call this funcion as often as you want to ensure you read the incomming gps data Properties: Lattitude : Lattitude * 10000000 (long value) Longitude : Longitude * 10000000 (long value) Altitude : Altitude * 100 (meters) (long value) Ground_speed : Speed (m/s) * 100 (long value) Ground_course : Course (degrees) * 100 (long value) NewData : 1 when a new data is received. You need to write a 0 to NewData when you read the data Fix : 1: GPS FIX, 0: No Fix (normal logic) ch: 0 or 1 flags count wnR wnF towMsR towMsF towSubMsF accEst */ #include <GPS_UBLOX.h> #include "GPS_UBLOX.h" #include <stdlib.h> #include <string.h> #include "inc/hw_memmap.h" #include "inc/hw_sysctl.h" #include "inc/hw_types.h" #include "driverlib/flash.h" #include "driverlib/gpio.h" #include "driverlib/interrupt.h" #include "driverlib/sysctl.h" #include "driverlib/systick.h" #include "grlib/grlib.h" #include "grlib/widget.h" #include "grlib/canvas.h" #include "grlib/listbox.h" #include "grlib/pushbutton.h" #include "utils/cmdline.h" #include "utils/locator.h" #include "utils/lwiplib.h" #include "utils/swupdate.h" #include "utils/uartstdio.h" #include "utils/ustdlib.h" #include "fatfs/src/ff.h" #include "fatfs/src/diskio.h" #include "drivers/formike240x320x16_ili9320.h" #include "drivers/touch.h" #include "utils/uartstdio.h" //#define __cplusplus #ifdef __cplusplus extern "C" { #endif // Standard "C" code here int getdataz(void) { return UARTgetc(); } // Send a byte array of UBX protocol to the GPS void sendUBX(int *MSG, int len) { int i=0; while (i<len) { i++; UARTprintf("%h", MSG[i]); // Serial.print(MSG[i], HEX); } UARTprintf("\n"); } // Calculate expected UBX ACK packet and parse UBX response from GPS int getUBX_ACK(int *MSG) { int b; int millis = 0; int ackByteID = 0; int ackPacket[10]; //unsigned long startTime = millis(); //Serial.print(" * Reading ACK response: "); // Construct the expected ACK packet ackPacket[0] = 0xB5; // header ackPacket[1] = 0x62; // header ackPacket[2] = 0x05; // class ackPacket[3] = 0x01; // id ackPacket[4] = 0x02; // length ackPacket[5] = 0x00; ackPacket[6] = MSG[2]; // ACK class ackPacket[7] = MSG[3]; // ACK id ackPacket[8] = 0; // CK_A ackPacket[9] = 0; // CK_B // Calculate the checksums int i=2; while ( i<8){ i++; ackPacket[8] = ackPacket[8] + ackPacket[i]; ackPacket[9] = ackPacket[9] + ackPacket[8]; } while (1) { millis++; // Test for success if (ackByteID > 9) { // All packets in order! UARTprintf(" (SUCCESS!)"); return true; } // Timeout if no valid response in 3 seconds if (millis > 3000) { UARTprintf(" (FAILED!)"); return false; } // Make sure data is available to read if (getdataz()/getdataz() > 0) { b = getdataz(); // Check that bytes arrive in sequence as per expected ACK packet if (b == ackPacket[ackByteID]) { ackByteID++; UARTprintf("%h", b); } else { ackByteID = 0; // Reset and look again, invalid order } } } } char* URLEncode(const char* msg) { const char *hex = "0123456789abcdef"; char* encodedMsg = ""; while (*msg!='\0'){ if( ('a' <= *msg && *msg <= 'z') || ('A' <= *msg && *msg <= 'Z') || ('0' <= *msg && *msg <= '9') ) { encodedMsg += *msg; } else { encodedMsg += '%'; encodedMsg += hex[*msg >> 4]; encodedMsg += hex[*msg & 15]; } msg++; } return encodedMsg; } char *itoa(int num, char *str, int radix) { char sign = 0; char temp[17]; //an int can only be 16 bits long //at radix 2 (binary) the string //is at most 16 + 1 null long. int temp_loc = 0; int digit; int str_loc = 0; //save sign for radix 10 conversion if (radix == 10 && num < 0) { sign = 1; num = -num; } //construct a backward string of the number. do { digit = (unsigned int)num % radix; if (digit < 10) temp[temp_loc++] = digit + '0'; else temp[temp_loc++] = digit - 10 + 'A'; ((unsigned int)num) = num/radix; } while ((unsigned int)num > 0); //now add the sign for radix 10 if (radix == 10 && sign) { temp[temp_loc] = '-'; } else { temp_loc--; } //now reverse the string. while ( temp_loc >=0 ) {// while there are still chars str[str_loc++] = temp[temp_loc--]; } str[str_loc] = 0; // add null termination. return str; } unsigned long millis() { return 0; } #ifdef __cplusplus #include <GPS_UBLOX.h> // Constructors //////////////////////////////////////////////////////////////// GPS_UBLOX_Class :: GPS_UBLOX_Class() { } // Public Methods ////////////////////////////////////////////////////////////// void GPS_UBLOX_Class :: Initi(void) { PosData = 0; ck_a=0; ck_b=0; UBX_step=0; NewData=0; Fix=0; PrintErrors=0; long Year, Month, Day; long Mjd; long GpsCycle = 0; long GpsWeek, GpsSeconds; char* unitid = "01111"; long Altitude = Altitude/1000; long Latitude = Lattitude; long Longitude = Longitude; long Nanoseconds = towSubMsR; char* time; char* date; GPS_timer=millis(); //Restarting timer... // Initialize serial port // Serial.begin(38400); //UARTStdioInitExpClk(1, 38400); } /**************************************************************** * ****************************************************************/ // Join 4 bytes into a long long GPS_UBLOX_Class :: join_4_bytes(unsigned char Buffer[]) { union long_union { int32_t dword; uint8_t byte[4]; } longUnion; longUnion.byte[0] = *Buffer; longUnion.byte[1] = *(Buffer+1); longUnion.byte[2] = *(Buffer+2); longUnion.byte[3] = *(Buffer+3); return(longUnion.dword); } long GPS_UBLOX_Class :: join_2_bytes(unsigned char Buffer[]) { union long_union { int32_t dword; uint8_t byte[2]; } longUnion; longUnion.byte[0] = *Buffer; longUnion.byte[1] = *(Buffer+1); return(longUnion.dword); } void GPS_UBLOX_Class :: translate_tow(long ms, long week_number, long nanis) { } long GPS_UBLOX_Class :: one_byte(unsigned char Buffer[]) { union long_union { int32_t dword; uint8_t byte[1]; } longUnion; longUnion.byte[0] = *Buffer; return(longUnion.dword); } char* GPS_UBLOX_Class :: bytes_to_decimal(char Buffer[]) { int number = 0; return(itoa(number, Buffer, 10)); } /**************************************************************** * ****************************************************************/ // Ublox checksum algorithm void GPS_UBLOX_Class :: ubx_checksum(uint8_t ubx_data) { ck_a+=ubx_data; ck_b+=ck_a; } /**************************************************************** * ****************************************************************/ // Private Methods ////////////////////////////////////////////////////////////// void GPS_UBLOX_Class :: parse_ubx_gps(void) { int j; switch(UBX_class){ case 0x01: switch(UBX_id)//Checking the UBX ID { case 0x02: //ID NAV-POSLLH j=0; Time = join_4_bytes(&UBX_buffer[j]); // ms Time of week j+=4; Longitude = join_4_bytes(&UBX_buffer[j]); // lon*10000000 j+=4; Lattitude = join_4_bytes(&UBX_buffer[j]); // lat*10000000 j+=4; Altitude = join_4_bytes(&UBX_buffer[j]); // elipsoid heigth mm j+=4; //Altitude = (float)join_4_bytes(&UBX_buffer[j]); // MSL heigth mm NewData=1; break; case 0x03://ID NAV-STATUS //if(UBX_buffer[4] >= 0x03) if((UBX_buffer[4] >= 0x03)&&(UBX_buffer[5]&0x01)) Fix=1; //valid position else Fix=0; //invalid position break; case 0x06://ID NAV-SOL if((UBX_buffer[10] >= 0x03)&&(UBX_buffer[11]&0x01)) Fix=1; //valid position else Fix=0; //invalid position UBX_ecefVZ=join_4_bytes(&UBX_buffer[36]); //Vertical Speed in cm/s NumSats=UBX_buffer[47]; //Number of sats... break; case 0x12:// ID NAV-VELNED j=16; Speed_3d = join_4_bytes(&UBX_buffer[j]); // cm/s j+=4; Ground_Speed = join_4_bytes(&UBX_buffer[j]); // Ground speed 2D cm/s j+=4; Ground_Course = join_4_bytes(&UBX_buffer[j]); // Heading 2D deg*100000 Ground_Course /= 1000; // Rescale heading to deg * 100 j+=4; break; } // UBX_class = 0x0D; PosData = 1; break; //Serial.println(UBX_class); case 0x0D: //UBX_id = 0x03; switch(UBX_id)//Checking the UBX ID { case 0x03: //ID TIM-TM2 ch = one_byte(&UBX_buffer[0]); flags = one_byte(&UBX_buffer[1]); count = join_2_bytes(&UBX_buffer[2]); wnR = join_2_bytes(&UBX_buffer[4]); wnF = join_2_bytes(&UBX_buffer[6]); towMsR = join_4_bytes(&UBX_buffer[8]); towSubMsR = join_4_bytes(&UBX_buffer[12]); towMsF = join_4_bytes(&UBX_buffer[16]); towSubMsF = join_4_bytes(&UBX_buffer[20]); accEst = join_4_bytes(&UBX_buffer[24]); checksum = join_2_bytes(&UBX_buffer[28]); break; } NewData=1; break; } } void GPS_UBLOX_Class :: Read(void) { static unsigned long GPS_timer=0; uint8_t data; int numc; numc = ((getdataz())/(getdataz())); if (numc > 0) for (int i=0;i<numc;i++) // Process bytes received { getdataz(); data = getdataz(); switch(UBX_step) { case 0: if(data==0xB5) UBX_step++; break; case 1: if(data==0x62) UBX_step++; else UBX_step=0; break; case 2: UBX_class=data; ubx_checksum(UBX_class); UBX_step++; break; case 3: UBX_id=data; ubx_checksum(UBX_id); UBX_step++; break; case 4: UBX_length_hi=data; ubx_checksum(UBX_length_hi); UBX_step++; if (UBX_length_hi>=UBX_MAX_SIZE) { if (PrintErrors) UARTprintf("ERR:GPS_BAD_PAYLOAD_LENGTH!!"); UBX_step=0; ck_a=0; ck_b=0; } break; case 5: UBX_length_lo=data; ubx_checksum(UBX_length_lo); UBX_step++; UBX_counter=0; break; case 6: if (UBX_counter < UBX_length_hi) { UBX_buffer[UBX_counter] = data; ubx_checksum(data); UBX_counter++; if (UBX_counter==UBX_length_hi) UBX_step++; } break; case 7: UBX_ck_a=data; // Serial.println(UBX_ck_a); UBX_step++; break; case 8: UBX_ck_b=data; // Serial.println(UBX_ck_b); if((ck_a==UBX_ck_a)&&(ck_b==UBX_ck_b)) parse_ubx_gps(); else { if (PrintErrors) UARTprintf("ERR:GPS_CHK!!"); } UBX_step=0; ck_a=0; ck_b=0; GPS_timer=millis(); break; } } if ((millis() - GPS_timer)>2000) { Fix = 0; if (PrintErrors) UARTprintf("ERR:GPS_TIMEOUT!!"); } } GPS_UBLOX_Class GPS; } #endif //}
[ "newtonlabs@bellsouth.net" ]
newtonlabs@bellsouth.net
de1ea392bd22280f71b64e245b9343fcb9ecea0c
61a59e886d56e22299f93c62669b216a81cfe9d9
/model_converter/Source/iruna/Include/iruna_model_data.h
db605ac71a705c07d6c26ab856d21bfc65c91163
[]
no_license
s-tachikawa/SubmitWork
c3b0b6bb174a040dfe4918e449508c07b22f5a39
ff89fa420e99a22ee1b09f369d714d94445b197f
refs/heads/master
2020-12-25T08:42:01.537402
2016-07-31T06:29:43
2016-07-31T06:29:43
62,947,659
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,013
h
//--------------------------------------------------------- // // iruna_model_common.h // 独自モデルデータ定義 // 作成日 10月21日 // 製作者 立川 翔野 // //--------------------------------------------------------- /*----多重インクルード防止-------------------------------------------------*/ #ifndef IRUNA_MODEL_DATA_H #define IRUNA_MODEL_DATA_H /*----インクルード-------------------------------------------------*/ #include "../Include/iruna_utility.h" #include "../Include/iruna_bone.h" #include "../Include/iruna_math.h" #include "../Include/iruna_material.h" #include "../Include/iruna_vertex_buffer.h" #include "../Include/iruna_index_buffer.h" /*----データ型 宣言------------------------------------------------*/ namespace iruna { namespace graphics { // ジオメトリーカウント struct GeometryData { int vertexCount; // 頂点数 int porygonCount; // ポリゴン数 int indexCount; // インデックス数 int materialCount; // マテリアル数 }; struct BoneIndex { unsigned char indexOne; unsigned char indexTwo; unsigned char indexThree; unsigned char indexFour; }; // 頂点データ struct VertexData { math::Vector3 pos; // 頂点座標 math::Vector3 normal; // 法線 math::Vector2 uv; // UV座標 }; // 頂点ブレンディング struct VertexBlending { float weight[ 4 ]; // 頂点ブレンディング int boneIndex[ 4 ]; // 影響ボーンインデックス }; // マテリアルデータ struct MaterialData { Material material; // マテリアル float power; // 透過度 }; // バッファデータ struct BufferData { VertexBuffer* vertexBuffer; IndexBuffer* indexBuffer; }; // メッシュデータ struct MeshData { int meshId; // メッシュID int parentId; // 親メッシュのID GeometryData countData; // ジオメトリーのカウントデータ std::vector< int > childId; // 子メッシュID VertexData* vertex; // 頂点データ VertexBlending* blending; // 頂点ブレンディング int* index; // 頂点インデックス MaterialData* material; // マテリアル std::vector< math::Matrix > tran; // アニメーション平行移動行列(階層アニメーション) VertexBuffer* vertexBuffer; // 頂点バッファ IndexBuffer* indexBuffer; // インデックスバッファ Bone* bone; // ボーン構造体 int boneCount; // ボーン数 }; struct ModelData { int meshCount; // メッシュ数 std::vector< MeshData* > mesh; // メッシュデータ int animeCount; // アニメーション数 }; } // graphics end } // iruna end /* メモ モデルデータのスマートポインタに使用か検討中 期限が短いので、今はModelLoader側がモデルデータの削除をしている。 コンバーター自体はそこまでポインタコピーが起きないので。 */ #endif // IRUNA_MODEL_DATA_H end
[ "syoya.tachi@gmail.com" ]
syoya.tachi@gmail.com
ee565a691e562138f82934b750dad518a062cec6
c811e5aa2762e3a3b23091a6ac172fe609e5ac57
/Linked_list/SLL/Linked List Insertion_1.cpp
a0c65c1a413c402b1172d36bb9666d2537471c9e
[]
no_license
kunal164107/GfG
9f7f2ed64ef9022d3fa11e1645356af488345122
f8286c24357367ee3cadd04c16c88d7d6fa3eeb5
refs/heads/master
2020-03-23T08:04:24.357531
2018-10-02T19:23:35
2018-10-02T19:23:35
141,300,852
0
0
null
null
null
null
UTF-8
C++
false
false
2,926
cpp
#include<iostream> using namespace std; class node{ public: int data; node* next; }; // node* getnewnode(int data1){ // node* newnode = new node(); // newnode->data = data1; // newnode->next = NULL; // return newnode; // } // node* insert(node* head, int data1){ // if(head == NULL){ // head = getnewnode(data1); // return head; // } // cout<<"chk2\n"; // node* temp = head; // while(temp->next != NULL){ // temp = temp->next; // } // temp->next = getnewnode(data1); // return head; // } void insertAtBegining(struct node** headRef, int newData) { // Code here if(*headRef == NULL){ // cout<<"chk1\n"; node* newnode = new node(); newnode->data = newData; newnode->next = NULL; *headRef = newnode; return; } //cout<<"chk2\n"; node* newnode = new node(); newnode->data = newData; // cout<<(*headRef)->data<<endl; newnode->next = *headRef; // cout<<newnode->next->data<<endl; // cout<<(*headRef)->data<<endl; *headRef = newnode; // cout<<(*headRef)->data<<endl; } // function appends the data at the end of the list void insertAtEnd(struct node** headRef, int newData) { // Code here node* temp = *headRef; if(*headRef == NULL){ node* newnode = new node(); newnode->data = newData; newnode->next = NULL; *headRef = newnode; return; } while(temp->next != NULL){ temp = temp->next; } node* newnode = new node(); newnode->data = newData; newnode->next = NULL; temp->next = newnode; } void insertAtPosition(node** headRef,int pos,int newData){ node* temp = *headRef; node* newnode = new node(); newnode->data = newData; newnode->next = NULL; if(*headRef == NULL){ *headRef = newnode; return; } if(pos == 1){ newnode->next = *headRef; *headRef = newnode; } else{ for(int i=1;i<pos-1;i++){ temp = temp->next; } newnode->next = temp->next; temp->next = newnode; } } void traverse(node* head){ if(head == NULL){ cout<<"No element in the list \n"; return; } node* temp = head; cout<<" List --> "; while(temp->next != NULL){ cout<<temp->data<<" "; temp = temp->next; } cout<<temp->data<<endl; } int main(){ node* head = NULL; insertAtBegining(&head,5); traverse(head); insertAtBegining(&head,7); traverse(head); insertAtBegining(&head,9); traverse(head); insertAtBegining(&head,4); traverse(head); insertAtBegining(&head,8); traverse(head); insertAtEnd(&head,1); traverse(head); insertAtEnd(&head,2); traverse(head); insertAtEnd(&head,3); traverse(head); insertAtEnd(&head,6); traverse(head); insertAtEnd(&head,10); traverse(head); insertAtPosition(&head,1,70); traverse(head); insertAtPosition(&head,4,80); traverse(head); insertAtPosition(&head,7,90); traverse(head); insertAtPosition(&head,10,100); traverse(head); }
[ "kunal164107@gmail.com" ]
kunal164107@gmail.com
648a180979e7fb99c343ba6fe8d35c4a0ac3940f
ddced7d67aa3d66aae82922fa11e565a4ee17ab0
/Source/Core/OpenGL/TextureRectangle.h
31739ae5f708d53f40de8d8cc5af52e266b0a227
[ "BSD-3-Clause" ]
permissive
gitter-badger/KVS
4f4a0732031c7079ca3c751d696265ed631881d2
7bc6e0eed3f35d7fe70a1ced3eb71a1c9f229162
refs/heads/develop
2020-02-26T16:10:20.229728
2016-04-05T07:11:01
2016-04-05T07:11:01
55,874,074
0
0
null
2016-04-10T00:50:54
2016-04-10T00:50:54
null
UTF-8
C++
false
false
1,953
h
/****************************************************************************/ /** * @file TextureRectangle.h * @author Naohisa Sakamoto */ /*---------------------------------------------------------------------------- * * Copyright (c) Visualization Laboratory, Kyoto University. * All rights reserved. * See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details. * * $Id: TextureRectangle.h 1551 2013-04-20 01:40:09Z naohisa.sakamoto@gmail.com $ */ /****************************************************************************/ #ifndef KVS__TEXTURE_RECTANGLE_H_INCLUDE #define KVS__TEXTURE_RECTANGLE_H_INCLUDE #include <kvs/Texture> #include <kvs/Deprecated> namespace kvs { /*==========================================================================*/ /** * Texture rectangle class. */ /*==========================================================================*/ class TextureRectangle : public kvs::Texture { public: typedef kvs::Texture BaseClass; private: bool m_is_loaded; ///< if true, the texture is loaded public: static void Unbind(); public: TextureRectangle(); virtual ~TextureRectangle(); bool isLoaded() const; void create( const size_t width, const size_t height, const void* data = NULL ); void release(); void load( const size_t width, const size_t height, const void* data, const size_t xoffset = 0, const size_t yoffset = 0 ); public: KVS_DEPRECATED( bool isDownload() const ) { return this->isLoaded(); } KVS_DEPRECATED( void download( const size_t width, const size_t height, const void* data, const size_t xoffset = 0, const size_t yoffset = 0 ) ) { this->load( width, height, data, xoffset, yoffset ); } }; } // end of namespace kvs #endif // KVS__TEXTURE_RECTANGLE_H_INCLUDE
[ "naohisa.sakamoto@gmail.com" ]
naohisa.sakamoto@gmail.com
24a27bbf3984395ef8583fdd03446f7cf92cf482
88ae8695987ada722184307301e221e1ba3cc2fa
/chromeos/services/network_config/public/cpp/fake_cros_network_config.cc
f093dd098ae52dc88b34616c555ec4e937a9b284
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
6,334
cc
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/services/network_config/public/cpp/fake_cros_network_config.h" #include <memory> #include "base/run_loop.h" namespace chromeos::network_config { FakeCrosNetworkConfig::FakeCrosNetworkConfig() = default; FakeCrosNetworkConfig::~FakeCrosNetworkConfig() = default; void FakeCrosNetworkConfig::AddObserver( mojo::PendingRemote<mojom::CrosNetworkConfigObserver> observer) { observers_.Add(std::move(observer)); } void FakeCrosNetworkConfig::GetNetworkStateList( mojom::NetworkFilterPtr filter, GetNetworkStateListCallback callback) { std::move(callback).Run( GetFilteredNetworkList(filter->network_type, filter->filter)); } void FakeCrosNetworkConfig::GetDeviceStateList( GetDeviceStateListCallback callback) { std::move(callback).Run(mojo::Clone(device_properties_)); } void FakeCrosNetworkConfig::GetManagedProperties( const std::string& guid, GetManagedPropertiesCallback callback) { auto it = guid_to_managed_properties_.find(guid); if (it != guid_to_managed_properties_.end()) { std::move(callback).Run(it->second.Clone()); return; } std::move(callback).Run(nullptr); } void FakeCrosNetworkConfig::RequestNetworkScan(mojom::NetworkType type) { scan_count_[type]++; } void FakeCrosNetworkConfig::GetGlobalPolicy(GetGlobalPolicyCallback callback) { if (!global_policy_) { global_policy_ = mojom::GlobalPolicy::New(); } std::move(callback).Run(global_policy_.Clone()); base::RunLoop().RunUntilIdle(); } void FakeCrosNetworkConfig::GetVpnProviders(GetVpnProvidersCallback callback) { std::vector<mojom::VpnProviderPtr> providers; std::move(callback).Run(std::move(providers)); } void FakeCrosNetworkConfig::CreateCustomApn(const std::string& network_guid, mojom::ApnPropertiesPtr apn) { custom_apns_.push_back(std::move(apn)); } void FakeCrosNetworkConfig::SetDeviceProperties( mojom::DeviceStatePropertiesPtr device_properties) { AddOrReplaceDevice(std::move(device_properties)); for (auto& observer : observers_) { observer->OnDeviceStateListChanged(); } base::RunLoop().RunUntilIdle(); } void FakeCrosNetworkConfig::SetGlobalPolicy( bool allow_only_policy_cellular_networks) { global_policy_ = mojom::GlobalPolicy::New(); global_policy_->allow_only_policy_cellular_networks = allow_only_policy_cellular_networks; for (auto& observer : observers_) { observer->OnPoliciesApplied(/*userhash=*/std::string()); } base::RunLoop().RunUntilIdle(); } void FakeCrosNetworkConfig::SetNetworkState( const std::string& guid, mojom::ConnectionStateType connection_state_type) { for (auto& network : visible_networks_) { if (network->guid == guid) { network->connection_state = connection_state_type; break; } } for (auto& observer : observers_) { observer->OnActiveNetworksChanged(GetFilteredNetworkList( mojom::NetworkType::kAll, mojom::FilterType::kActive)); } base::RunLoop().RunUntilIdle(); } void FakeCrosNetworkConfig::AddNetworkAndDevice( mojom::NetworkStatePropertiesPtr network) { auto device_properties = mojom::DeviceStateProperties::New(); device_properties->type = network->type; device_properties->device_state = mojom::DeviceStateType::kEnabled; visible_networks_.push_back(std::move(network)); AddOrReplaceDevice(std::move(device_properties)); for (auto& observer : observers_) { observer->OnDeviceStateListChanged(); observer->OnActiveNetworksChanged(GetFilteredNetworkList( mojom::NetworkType::kAll, mojom::FilterType::kActive)); } base::RunLoop().RunUntilIdle(); } void FakeCrosNetworkConfig::UpdateNetworkProperties( mojom::NetworkStatePropertiesPtr network) { bool is_found = false; for (unsigned int i = 0; i < visible_networks_.size(); i++) { if (visible_networks_[i]->guid == network->guid) { visible_networks_[i] = mojo::Clone(network); is_found = true; break; } } if (!is_found) { return; } for (auto& observer : observers_) { observer->OnActiveNetworksChanged(GetFilteredNetworkList( mojom::NetworkType::kAll, mojom::FilterType::kActive)); } base::RunLoop().RunUntilIdle(); } void FakeCrosNetworkConfig::AddManagedProperties( const std::string& guid, mojom::ManagedPropertiesPtr managed_properties) { guid_to_managed_properties_[guid] = std::move(managed_properties); } void FakeCrosNetworkConfig::ClearNetworksAndDevices() { visible_networks_.clear(); device_properties_.clear(); for (auto& observer : observers_) { observer->OnDeviceStateListChanged(); observer->OnActiveNetworksChanged({}); } base::RunLoop().RunUntilIdle(); } int FakeCrosNetworkConfig::GetScanCount(mojom::NetworkType type) { return scan_count_[type]; } mojo::PendingRemote<mojom::CrosNetworkConfig> FakeCrosNetworkConfig::GetPendingRemote() { return receiver_.BindNewPipeAndPassRemote(); } void FakeCrosNetworkConfig::AddOrReplaceDevice( mojom::DeviceStatePropertiesPtr device_properties) { auto it = std::find_if( device_properties_.begin(), device_properties_.end(), [&device_properties](const mojom::DeviceStatePropertiesPtr& p) { return p->type == device_properties->type; }); if (it != device_properties_.end()) { (*it).Swap(&device_properties); } else { device_properties_.insert(device_properties_.begin(), std::move(device_properties)); } } std::vector<mojom::NetworkStatePropertiesPtr> FakeCrosNetworkConfig::GetFilteredNetworkList(mojom::NetworkType network_type, mojom::FilterType filter_type) { std::vector<mojom::NetworkStatePropertiesPtr> result; for (const auto& network : visible_networks_) { if (network_type != mojom::NetworkType::kAll && network_type != network->type) { continue; } if (filter_type == mojom::FilterType::kActive && network->connection_state == mojom::ConnectionStateType::kNotConnected) { continue; } result.push_back(network.Clone()); } return result; } } // namespace chromeos::network_config
[ "jengelh@inai.de" ]
jengelh@inai.de
006a48e18e5305f071279236003d03f59a507d15
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
/ui/events/ipc/latency_info_param_traits.cc
a5489afbdc93fb88bd629d1f984952b4b3b7a9c2
[ "BSD-3-Clause" ]
permissive
massnetwork/mass-browser
7de0dfc541cbac00ffa7308541394bac1e945b76
67526da9358734698c067b7775be491423884339
refs/heads/master
2022-12-07T09:01:31.027715
2017-01-19T14:29:18
2017-01-19T14:29:18
73,799,690
4
4
BSD-3-Clause
2022-11-26T11:53:23
2016-11-15T09:49:29
null
UTF-8
C++
false
false
3,634
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/events/ipc/latency_info_param_traits_macros.h" #include "ui/gfx/ipc/geometry/gfx_param_traits.h" // Generate param traits size methods. #include "ipc/param_traits_size_macros.h" namespace IPC { #undef UI_EVENTS_IPC_LATENCY_INFO_PARAM_TRAITS_MACROS_H_ #include "ui/events/ipc/latency_info_param_traits_macros.h" } // Generate param traits write methods. #include "ipc/param_traits_write_macros.h" namespace IPC { #undef UI_EVENTS_IPC_LATENCY_INFO_PARAM_TRAITS_MACROS_H_ #include "ui/events/ipc/latency_info_param_traits_macros.h" } // namespace IPC // Generate param traits read methods. #include "ipc/param_traits_read_macros.h" namespace IPC { #undef UI_EVENTS_IPC_LATENCY_INFO_PARAM_TRAITS_MACROS_H_ #include "ui/events/ipc/latency_info_param_traits_macros.h" } // namespace IPC // Generate param traits log methods. #include "ipc/param_traits_log_macros.h" namespace IPC { #undef UI_EVENTS_IPC_LATENCY_INFO_PARAM_TRAITS_MACROS_H_ #include "ui/events/ipc/latency_info_param_traits_macros.h" } // namespace IPC // Implemetation for ParamTraits<ui::LatencyInfo>. #include "ui/events/ipc/latency_info_param_traits.h" namespace IPC { void ParamTraits<ui::LatencyInfo>::GetSize(base::PickleSizer* s, const param_type& p) { GetParamSize(s, p.trace_name_); GetParamSize(s, p.latency_components_); GetParamSize(s, p.input_coordinates_size_); for (size_t i = 0; i < p.input_coordinates_size_; i++) { GetParamSize(s, p.input_coordinates_[i]); } GetParamSize(s, p.trace_id_); GetParamSize(s, p.terminated_); GetParamSize(s, p.source_event_type_); } void ParamTraits<ui::LatencyInfo>::Write(base::Pickle* m, const param_type& p) { WriteParam(m, p.trace_name_); WriteParam(m, p.latency_components_); WriteParam(m, p.input_coordinates_size_); for (size_t i = 0; i < p.input_coordinates_size_; i++) { WriteParam(m, p.input_coordinates_[i]); } WriteParam(m, p.trace_id_); WriteParam(m, p.terminated_); WriteParam(m, p.source_event_type_); } bool ParamTraits<ui::LatencyInfo>::Read(const base::Pickle* m, base::PickleIterator* iter, param_type* p) { if (!ReadParam(m, iter, &p->trace_name_)) return false; if (!ReadParam(m, iter, &p->latency_components_)) return false; gfx::PointF input_coordinates; uint32_t input_coordinates_size; if (!ReadParam(m, iter, &input_coordinates_size)) return false; for (size_t i = 0; i < input_coordinates_size; i++) { if (!ReadParam(m, iter, &input_coordinates)) return false; if (!p->AddInputCoordinate(input_coordinates)) return false; } if (!ReadParam(m, iter, &p->trace_id_)) return false; if (!ReadParam(m, iter, &p->terminated_)) return false; if (!ReadParam(m, iter, &p->source_event_type_)) return false; return true; } void ParamTraits<ui::LatencyInfo>::Log(const param_type& p, std::string* l) { LogParam(p.trace_name_, l); l->append(" "); LogParam(p.latency_components_, l); l->append(" "); LogParam(p.input_coordinates_size_, l); l->append(" "); for (size_t i = 0; i < p.input_coordinates_size_; i++) { LogParam(p.input_coordinates_[i], l); l->append(" "); } LogParam(p.trace_id_, l); l->append(" "); LogParam(p.terminated_, l); l->append(" "); LogParam(p.source_event_type_, l); } } // namespace IPC
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
8ac5957b069487324f0b72bc5fcab930b49b0b7d
eefb836e9ec761c2b1f102b4007ed7ab6380c7a2
/code/delta/core/modules/shle/libSceSystemService/libSceSystemServiceSuspend.cpp
dbeeb5053f29cae5e88081eeb214d61c1ae310cd
[]
no_license
RyuDanuer/ps4delta
be6ee054ca3ae59159ecbcc59addb77c6f60c85f
e3ee468357fa0fbbd428d52034fc84e76b851c4c
refs/heads/master
2020-09-25T05:18:15.631545
2019-12-02T20:13:54
2019-12-02T20:13:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
374
cpp
// Copyright (C) 2019 Force67 // This file was generated on Sat Sep 7 22:01:28 2019 #include "../../ModuleLinker.h" int sceSystemServiceDeclareReadyForSuspend() { UNIMPLEMENTED_FUNC; return 0; } int sceSystemServiceDisableSuspendNotification() { UNIMPLEMENTED_FUNC; return 0; } int sceSystemServiceEnableSuspendNotification() { UNIMPLEMENTED_FUNC; return 0; }
[ "prelink835@gmail.com" ]
prelink835@gmail.com
9983d3c8df930f8231231b12c33d787588b5885e
d176f0a70b5473267bcb118100556acac77a76d0
/src/examples/clxx/mem1.cpp
27d88a29f4db166e92e29ea243240f68309a7041
[ "MIT" ]
permissive
ptomulik/clxx
866c0c7d9db812231e1bcd32ad2d2d08ff5cc571
9edfb0c39e6ab2f2d86afde0ac42c5e3f21e7ac8
refs/heads/master
2021-01-13T14:19:03.385928
2015-07-27T10:54:24
2015-07-27T10:54:24
21,634,627
1
0
null
null
null
null
UTF-8
C++
false
false
1,566
cpp
// @COPYRIGHT@ // Licensed under MIT license (LICENSE.txt) /** // doc: clxx/mem1.cpp {{{ * \file clxx/mem1.cpp * \brief Usage example for \ref clxx::mem class */ // }}} /** // doc: mem1.cpp {{{ * \example clxx/mem1.cpp * \brief Usage example for \ref clxx::mem class */ // }}} // [Program] #include <clxx/cl/platforms.hpp> #include <clxx/cl/mem.hpp> #include <clxx/cl/context.hpp> #include <clxx/io/types.hpp> #include <iostream> /// Size of array #define ARRAY_SIZE 16 /// Main function int main() { clxx::platforms platforms(clxx::get_platforms()); clxx::context context(clxx::make_context_properties(platforms[0]), clxx::device_type_t::all); float array[ARRAY_SIZE]; clxx::mem buffer(context, clxx::mem_flags_t::read_write, sizeof(array), array); std::cout << "buffer.get_type(): " << buffer.get_type() << std::endl; std::cout << "buffer.get_flags(): " << buffer.get_flags() << std::endl; std::cout << "buffer.get_size(): " << buffer.get_size() << std::endl; std::cout << "buffer.get_map_count(): " << buffer.get_map_count() << std::endl; std::cout << "buffer.get_reference_count(): " << buffer.get_reference_count() << std::endl; return 0; } // [Program] /* [Output] buffer.get_type(): buffer buffer.get_flags(): read_write buffer.get_size(): 64 buffer.get_map_count(): 0 buffer.get_reference_count(): 1 [Output] */ // vim: set expandtab tabstop=2 shiftwidth=2: // vim: set foldmethod=marker foldcolumn=4:
[ "ptomulik@meil.pw.edu.pl" ]
ptomulik@meil.pw.edu.pl
59aa3c72a47cf6d778c88629b76662a2ce349df7
36b2b53ae8bf27388f9bd096e85025d8581d290c
/include/GainCorrect.h
77b681a42ca07a150df41cb18691f4318430079d
[]
no_license
apingault/Trivent4HEP
65112a522e2f7d84ad3b1347ff6481c59bf29cc9
effc2af7511005641668124eb12c7cbc8188b593
refs/heads/master
2016-08-12T04:24:00.293513
2015-06-01T08:05:27
2015-06-01T08:06:10
36,565,522
0
0
null
null
null
null
UTF-8
C++
false
false
952
h
#include <EVENT/LCCollection.h> #include <IMPL/LCCollectionVec.h> #include <IMPL/LCEventImpl.h> #include <EVENT/MCParticle.h> #include <EVENT/CalorimeterHit.h> #include <IMPL/CalorimeterHitImpl.h> #include <EVENT/RawCalorimeterHit.h> #include <iostream> #include <cmath> #include "Mapping.h" #include <TH1.h> #include <TH2.h> using namespace std; struct GainHist{ TH1F *noise_on_dif; TH1F *gain_chan; }; class GainCorrect{ public: GainCorrect(); ~GainCorrect(); // methods uint getCellDif_id(int cell_id); uint getCellAsic_id(int cell_id); uint getCellChan_id(int cell_id); void gainCorrectionInit(std::map<int, LayerID > _mapping); void gainCorrectionParser(EVENT::LCCollection* col); void gainCorrector(const string gain_file); protected: std::map<int, LayerID > _mapping; std::map<int, GainHist > _h_gain ; TH1F *noise_dist; TH1F *gain_chan; TH1F *mean_hit_dif; TH1F *time_hit_dif; };
[ "antoine.pingault@ugent.be" ]
antoine.pingault@ugent.be
641a0641d19adeed9cbb61ec8d54842e058dd210
1005f450818900b923e345b73d77628f20d1875e
/thirdparty/asio/asio/execution/bulk_guarantee.hpp
6482218357dc3b4fb115ef8c869e6a8bfdb1dd25
[ "MIT" ]
permissive
qicosmos/rest_rpc
c7ad37547a9dcb616832b32bc110a237977b8c74
93088a7e0f0ddb3786de40ed7b6311852644edbf
refs/heads/master
2023-08-23T06:56:42.464323
2023-07-04T02:57:13
2023-07-04T02:57:13
162,215,656
1,504
354
MIT
2023-07-05T03:37:24
2018-12-18T02:01:52
C++
UTF-8
C++
false
false
35,956
hpp
// // execution/bulk_guarantee.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2021 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) // #ifndef ASIO_EXECUTION_BULK_GUARANTEE_HPP #define ASIO_EXECUTION_BULK_GUARANTEE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/type_traits.hpp" #include "asio/execution/executor.hpp" #include "asio/execution/scheduler.hpp" #include "asio/execution/sender.hpp" #include "asio/is_applicable_property.hpp" #include "asio/query.hpp" #include "asio/traits/query_free.hpp" #include "asio/traits/query_member.hpp" #include "asio/traits/query_static_constexpr_member.hpp" #include "asio/traits/static_query.hpp" #include "asio/traits/static_require.hpp" #include "asio/detail/push_options.hpp" namespace asio { #if defined(GENERATING_DOCUMENTATION) namespace execution { /// A property to communicate the forward progress and ordering guarantees of /// execution agents associated with the bulk execution. struct bulk_guarantee_t { /// The bulk_guarantee_t property applies to executors, senders, and /// schedulers. template <typename T> static constexpr bool is_applicable_property_v = is_executor_v<T> || is_sender_v<T> || is_scheduler_v<T>; /// The top-level bulk_guarantee_t property cannot be required. static constexpr bool is_requirable = false; /// The top-level bulk_guarantee_t property cannot be preferred. static constexpr bool is_preferable = false; /// The type returned by queries against an @c any_executor. typedef bulk_guarantee_t polymorphic_query_result_type; /// A sub-property that indicates that execution agents within the same bulk /// execution may be parallelised and vectorised. struct unsequenced_t { /// The bulk_guarantee_t::unsequenced_t property applies to executors, /// senders, and schedulers. template <typename T> static constexpr bool is_applicable_property_v = is_executor_v<T> || is_sender_v<T> || is_scheduler_v<T>; /// The bulk_guarantee_t::unsequenced_t property can be required. static constexpr bool is_requirable = true; /// The bulk_guarantee_t::unsequenced_t property can be preferred. static constexpr bool is_preferable = true; /// The type returned by queries against an @c any_executor. typedef bulk_guarantee_t polymorphic_query_result_type; /// Default constructor. constexpr unsequenced_t(); /// Get the value associated with a property object. /** * @returns unsequenced_t(); */ static constexpr bulk_guarantee_t value(); }; /// A sub-property that indicates that execution agents within the same bulk /// execution may not be parallelised and vectorised. struct sequenced_t { /// The bulk_guarantee_t::sequenced_t property applies to executors, /// senders, and schedulers. template <typename T> static constexpr bool is_applicable_property_v = is_executor_v<T> || is_sender_v<T> || is_scheduler_v<T>; /// The bulk_guarantee_t::sequenced_t property can be required. static constexpr bool is_requirable = true; /// The bulk_guarantee_t::sequenced_t property can be preferred. static constexpr bool is_preferable = true; /// The type returned by queries against an @c any_executor. typedef bulk_guarantee_t polymorphic_query_result_type; /// Default constructor. constexpr sequenced_t(); /// Get the value associated with a property object. /** * @returns sequenced_t(); */ static constexpr bulk_guarantee_t value(); }; /// A sub-property that indicates that execution agents within the same bulk /// execution may be parallelised. struct parallel_t { /// The bulk_guarantee_t::parallel_t property applies to executors, /// senders, and schedulers. template <typename T> static constexpr bool is_applicable_property_v = is_executor_v<T> || is_sender_v<T> || is_scheduler_v<T>; /// The bulk_guarantee_t::parallel_t property can be required. static constexpr bool is_requirable = true; /// The bulk_guarantee_t::parallel_t property can be preferred. static constexpr bool is_preferable = true; /// The type returned by queries against an @c any_executor. typedef bulk_guarantee_t polymorphic_query_result_type; /// Default constructor. constexpr parallel_t(); /// Get the value associated with a property object. /** * @returns parallel_t(); */ static constexpr bulk_guarantee_t value(); }; /// A special value used for accessing the bulk_guarantee_t::unsequenced_t /// property. static constexpr unsequenced_t unsequenced; /// A special value used for accessing the bulk_guarantee_t::sequenced_t /// property. static constexpr sequenced_t sequenced; /// A special value used for accessing the bulk_guarantee_t::parallel_t /// property. static constexpr parallel_t parallel; /// Default constructor. constexpr bulk_guarantee_t(); /// Construct from a sub-property value. constexpr bulk_guarantee_t(unsequenced_t); /// Construct from a sub-property value. constexpr bulk_guarantee_t(sequenced_t); /// Construct from a sub-property value. constexpr bulk_guarantee_t(parallel_t); /// Compare property values for equality. friend constexpr bool operator==( const bulk_guarantee_t& a, const bulk_guarantee_t& b) noexcept; /// Compare property values for inequality. friend constexpr bool operator!=( const bulk_guarantee_t& a, const bulk_guarantee_t& b) noexcept; }; /// A special value used for accessing the bulk_guarantee_t property. constexpr bulk_guarantee_t bulk_guarantee; } // namespace execution #else // defined(GENERATING_DOCUMENTATION) namespace execution { namespace detail { namespace bulk_guarantee { template <int I> struct unsequenced_t; template <int I> struct sequenced_t; template <int I> struct parallel_t; } // namespace bulk_guarantee template <int I = 0> struct bulk_guarantee_t { #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T> ASIO_STATIC_CONSTEXPR(bool, is_applicable_property_v = ( is_executor<T>::value || conditional< is_executor<T>::value, false_type, is_sender<T> >::type::value || conditional< is_executor<T>::value, false_type, is_scheduler<T> >::type::value)); #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) ASIO_STATIC_CONSTEXPR(bool, is_requirable = false); ASIO_STATIC_CONSTEXPR(bool, is_preferable = false); typedef bulk_guarantee_t polymorphic_query_result_type; typedef detail::bulk_guarantee::unsequenced_t<I> unsequenced_t; typedef detail::bulk_guarantee::sequenced_t<I> sequenced_t; typedef detail::bulk_guarantee::parallel_t<I> parallel_t; ASIO_CONSTEXPR bulk_guarantee_t() : value_(-1) { } ASIO_CONSTEXPR bulk_guarantee_t(unsequenced_t) : value_(0) { } ASIO_CONSTEXPR bulk_guarantee_t(sequenced_t) : value_(1) { } ASIO_CONSTEXPR bulk_guarantee_t(parallel_t) : value_(2) { } template <typename T> struct proxy { #if defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) struct type { template <typename P> auto query(ASIO_MOVE_ARG(P) p) const noexcept( noexcept( declval<typename conditional<true, T, P>::type>().query( ASIO_MOVE_CAST(P)(p)) ) ) -> decltype( declval<typename conditional<true, T, P>::type>().query( ASIO_MOVE_CAST(P)(p)) ); }; #else // defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) typedef T type; #endif // defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) }; template <typename T> struct static_proxy { #if defined(ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT) struct type { template <typename P> static constexpr auto query(ASIO_MOVE_ARG(P) p) noexcept( noexcept( conditional<true, T, P>::type::query(ASIO_MOVE_CAST(P)(p)) ) ) -> decltype( conditional<true, T, P>::type::query(ASIO_MOVE_CAST(P)(p)) ) { return T::query(ASIO_MOVE_CAST(P)(p)); } }; #else // defined(ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT) typedef T type; #endif // defined(ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT) }; template <typename T> struct query_member : traits::query_member<typename proxy<T>::type, bulk_guarantee_t> {}; template <typename T> struct query_static_constexpr_member : traits::query_static_constexpr_member< typename static_proxy<T>::type, bulk_guarantee_t> {}; #if defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) \ && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) template <typename T> static ASIO_CONSTEXPR typename query_static_constexpr_member<T>::result_type static_query() ASIO_NOEXCEPT_IF(( query_static_constexpr_member<T>::is_noexcept)) { return query_static_constexpr_member<T>::value(); } template <typename T> static ASIO_CONSTEXPR typename traits::static_query<T, unsequenced_t>::result_type static_query( typename enable_if< !query_static_constexpr_member<T>::is_valid >::type* = 0, typename enable_if< !query_member<T>::is_valid >::type* = 0, typename enable_if< traits::static_query<T, unsequenced_t>::is_valid >::type* = 0) ASIO_NOEXCEPT { return traits::static_query<T, unsequenced_t>::value(); } template <typename T> static ASIO_CONSTEXPR typename traits::static_query<T, sequenced_t>::result_type static_query( typename enable_if< !query_static_constexpr_member<T>::is_valid >::type* = 0, typename enable_if< !query_member<T>::is_valid >::type* = 0, typename enable_if< !traits::static_query<T, unsequenced_t>::is_valid >::type* = 0, typename enable_if< traits::static_query<T, sequenced_t>::is_valid >::type* = 0) ASIO_NOEXCEPT { return traits::static_query<T, sequenced_t>::value(); } template <typename T> static ASIO_CONSTEXPR typename traits::static_query<T, parallel_t>::result_type static_query( typename enable_if< !query_static_constexpr_member<T>::is_valid >::type* = 0, typename enable_if< !query_member<T>::is_valid >::type* = 0, typename enable_if< !traits::static_query<T, unsequenced_t>::is_valid >::type* = 0, typename enable_if< !traits::static_query<T, sequenced_t>::is_valid >::type* = 0, typename enable_if< traits::static_query<T, parallel_t>::is_valid >::type* = 0) ASIO_NOEXCEPT { return traits::static_query<T, parallel_t>::value(); } template <typename E, typename T = decltype(bulk_guarantee_t::static_query<E>())> static ASIO_CONSTEXPR const T static_query_v = bulk_guarantee_t::static_query<E>(); #endif // defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) // && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) friend ASIO_CONSTEXPR bool operator==( const bulk_guarantee_t& a, const bulk_guarantee_t& b) { return a.value_ == b.value_; } friend ASIO_CONSTEXPR bool operator!=( const bulk_guarantee_t& a, const bulk_guarantee_t& b) { return a.value_ != b.value_; } struct convertible_from_bulk_guarantee_t { ASIO_CONSTEXPR convertible_from_bulk_guarantee_t(bulk_guarantee_t) {} }; template <typename Executor> friend ASIO_CONSTEXPR bulk_guarantee_t query( const Executor& ex, convertible_from_bulk_guarantee_t, typename enable_if< can_query<const Executor&, unsequenced_t>::value >::type* = 0) #if !defined(__clang__) // Clang crashes if noexcept is used here. #if defined(ASIO_MSVC) // Visual C++ wants the type to be qualified. ASIO_NOEXCEPT_IF(( is_nothrow_query<const Executor&, bulk_guarantee_t<>::unsequenced_t>::value)) #else // defined(ASIO_MSVC) ASIO_NOEXCEPT_IF(( is_nothrow_query<const Executor&, unsequenced_t>::value)) #endif // defined(ASIO_MSVC) #endif // !defined(__clang__) { return asio::query(ex, unsequenced_t()); } template <typename Executor> friend ASIO_CONSTEXPR bulk_guarantee_t query( const Executor& ex, convertible_from_bulk_guarantee_t, typename enable_if< !can_query<const Executor&, unsequenced_t>::value >::type* = 0, typename enable_if< can_query<const Executor&, sequenced_t>::value >::type* = 0) #if !defined(__clang__) // Clang crashes if noexcept is used here. #if defined(ASIO_MSVC) // Visual C++ wants the type to be qualified. ASIO_NOEXCEPT_IF(( is_nothrow_query<const Executor&, bulk_guarantee_t<>::sequenced_t>::value)) #else // defined(ASIO_MSVC) ASIO_NOEXCEPT_IF(( is_nothrow_query<const Executor&, sequenced_t>::value)) #endif // defined(ASIO_MSVC) #endif // !defined(__clang__) { return asio::query(ex, sequenced_t()); } template <typename Executor> friend ASIO_CONSTEXPR bulk_guarantee_t query( const Executor& ex, convertible_from_bulk_guarantee_t, typename enable_if< !can_query<const Executor&, unsequenced_t>::value >::type* = 0, typename enable_if< !can_query<const Executor&, sequenced_t>::value >::type* = 0, typename enable_if< can_query<const Executor&, parallel_t>::value >::type* = 0) #if !defined(__clang__) // Clang crashes if noexcept is used here. #if defined(ASIO_MSVC) // Visual C++ wants the type to be qualified. ASIO_NOEXCEPT_IF(( is_nothrow_query<const Executor&, bulk_guarantee_t<>::parallel_t>::value)) #else // defined(ASIO_MSVC) ASIO_NOEXCEPT_IF(( is_nothrow_query<const Executor&, parallel_t>::value)) #endif // defined(ASIO_MSVC) #endif // !defined(__clang__) { return asio::query(ex, parallel_t()); } ASIO_STATIC_CONSTEXPR_DEFAULT_INIT(unsequenced_t, unsequenced); ASIO_STATIC_CONSTEXPR_DEFAULT_INIT(sequenced_t, sequenced); ASIO_STATIC_CONSTEXPR_DEFAULT_INIT(parallel_t, parallel); #if !defined(ASIO_HAS_CONSTEXPR) static const bulk_guarantee_t instance; #endif // !defined(ASIO_HAS_CONSTEXPR) private: int value_; }; #if defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) \ && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) template <int I> template <typename E, typename T> const T bulk_guarantee_t<I>::static_query_v; #endif // defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) // && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) #if !defined(ASIO_HAS_CONSTEXPR) template <int I> const bulk_guarantee_t<I> bulk_guarantee_t<I>::instance; #endif template <int I> const typename bulk_guarantee_t<I>::unsequenced_t bulk_guarantee_t<I>::unsequenced; template <int I> const typename bulk_guarantee_t<I>::sequenced_t bulk_guarantee_t<I>::sequenced; template <int I> const typename bulk_guarantee_t<I>::parallel_t bulk_guarantee_t<I>::parallel; namespace bulk_guarantee { template <int I = 0> struct unsequenced_t { #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T> ASIO_STATIC_CONSTEXPR(bool, is_applicable_property_v = ( is_executor<T>::value || conditional< is_executor<T>::value, false_type, is_sender<T> >::type::value || conditional< is_executor<T>::value, false_type, is_scheduler<T> >::type::value)); #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) ASIO_STATIC_CONSTEXPR(bool, is_requirable = true); ASIO_STATIC_CONSTEXPR(bool, is_preferable = true); typedef bulk_guarantee_t<I> polymorphic_query_result_type; ASIO_CONSTEXPR unsequenced_t() { } template <typename T> struct query_member : traits::query_member< typename bulk_guarantee_t<I>::template proxy<T>::type, unsequenced_t> {}; template <typename T> struct query_static_constexpr_member : traits::query_static_constexpr_member< typename bulk_guarantee_t<I>::template static_proxy<T>::type, unsequenced_t> {}; #if defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) \ && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) template <typename T> static ASIO_CONSTEXPR typename query_static_constexpr_member<T>::result_type static_query() ASIO_NOEXCEPT_IF(( query_static_constexpr_member<T>::is_noexcept)) { return query_static_constexpr_member<T>::value(); } template <typename T> static ASIO_CONSTEXPR unsequenced_t static_query( typename enable_if< !query_static_constexpr_member<T>::is_valid >::type* = 0, typename enable_if< !query_member<T>::is_valid >::type* = 0, typename enable_if< !traits::query_free<T, unsequenced_t>::is_valid >::type* = 0, typename enable_if< !can_query<T, sequenced_t<I> >::value >::type* = 0, typename enable_if< !can_query<T, parallel_t<I> >::value >::type* = 0) ASIO_NOEXCEPT { return unsequenced_t(); } template <typename E, typename T = decltype(unsequenced_t::static_query<E>())> static ASIO_CONSTEXPR const T static_query_v = unsequenced_t::static_query<E>(); #endif // defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) // && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) static ASIO_CONSTEXPR bulk_guarantee_t<I> value() { return unsequenced_t(); } friend ASIO_CONSTEXPR bool operator==( const unsequenced_t&, const unsequenced_t&) { return true; } friend ASIO_CONSTEXPR bool operator!=( const unsequenced_t&, const unsequenced_t&) { return false; } friend ASIO_CONSTEXPR bool operator==( const unsequenced_t&, const sequenced_t<I>&) { return false; } friend ASIO_CONSTEXPR bool operator!=( const unsequenced_t&, const sequenced_t<I>&) { return true; } friend ASIO_CONSTEXPR bool operator==( const unsequenced_t&, const parallel_t<I>&) { return false; } friend ASIO_CONSTEXPR bool operator!=( const unsequenced_t&, const parallel_t<I>&) { return true; } }; #if defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) \ && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) template <int I> template <typename E, typename T> const T unsequenced_t<I>::static_query_v; #endif // defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) // && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) template <int I = 0> struct sequenced_t { #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T> ASIO_STATIC_CONSTEXPR(bool, is_applicable_property_v = ( is_executor<T>::value || conditional< is_executor<T>::value, false_type, is_sender<T> >::type::value || conditional< is_executor<T>::value, false_type, is_scheduler<T> >::type::value)); #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) ASIO_STATIC_CONSTEXPR(bool, is_requirable = true); ASIO_STATIC_CONSTEXPR(bool, is_preferable = true); typedef bulk_guarantee_t<I> polymorphic_query_result_type; ASIO_CONSTEXPR sequenced_t() { } template <typename T> struct query_member : traits::query_member< typename bulk_guarantee_t<I>::template proxy<T>::type, sequenced_t> {}; template <typename T> struct query_static_constexpr_member : traits::query_static_constexpr_member< typename bulk_guarantee_t<I>::template static_proxy<T>::type, sequenced_t> {}; #if defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) \ && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) template <typename T> static ASIO_CONSTEXPR typename query_static_constexpr_member<T>::result_type static_query() ASIO_NOEXCEPT_IF(( query_static_constexpr_member<T>::is_noexcept)) { return query_static_constexpr_member<T>::value(); } template <typename E, typename T = decltype(sequenced_t::static_query<E>())> static ASIO_CONSTEXPR const T static_query_v = sequenced_t::static_query<E>(); #endif // defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) // && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) static ASIO_CONSTEXPR bulk_guarantee_t<I> value() { return sequenced_t(); } friend ASIO_CONSTEXPR bool operator==( const sequenced_t&, const sequenced_t&) { return true; } friend ASIO_CONSTEXPR bool operator!=( const sequenced_t&, const sequenced_t&) { return false; } friend ASIO_CONSTEXPR bool operator==( const sequenced_t&, const unsequenced_t<I>&) { return false; } friend ASIO_CONSTEXPR bool operator!=( const sequenced_t&, const unsequenced_t<I>&) { return true; } friend ASIO_CONSTEXPR bool operator==( const sequenced_t&, const parallel_t<I>&) { return false; } friend ASIO_CONSTEXPR bool operator!=( const sequenced_t&, const parallel_t<I>&) { return true; } }; #if defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) \ && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) template <int I> template <typename E, typename T> const T sequenced_t<I>::static_query_v; #endif // defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) // && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) template <int I> struct parallel_t { #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T> ASIO_STATIC_CONSTEXPR(bool, is_applicable_property_v = ( is_executor<T>::value || conditional< is_executor<T>::value, false_type, is_sender<T> >::type::value || conditional< is_executor<T>::value, false_type, is_scheduler<T> >::type::value)); #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) ASIO_STATIC_CONSTEXPR(bool, is_requirable = true); ASIO_STATIC_CONSTEXPR(bool, is_preferable = true); typedef bulk_guarantee_t<I> polymorphic_query_result_type; ASIO_CONSTEXPR parallel_t() { } template <typename T> struct query_member : traits::query_member< typename bulk_guarantee_t<I>::template proxy<T>::type, parallel_t> {}; template <typename T> struct query_static_constexpr_member : traits::query_static_constexpr_member< typename bulk_guarantee_t<I>::template static_proxy<T>::type, parallel_t> {}; #if defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) \ && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) template <typename T> static ASIO_CONSTEXPR typename query_static_constexpr_member<T>::result_type static_query() ASIO_NOEXCEPT_IF(( query_static_constexpr_member<T>::is_noexcept)) { return query_static_constexpr_member<T>::value(); } template <typename E, typename T = decltype(parallel_t::static_query<E>())> static ASIO_CONSTEXPR const T static_query_v = parallel_t::static_query<E>(); #endif // defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) // && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) static ASIO_CONSTEXPR bulk_guarantee_t<I> value() { return parallel_t(); } friend ASIO_CONSTEXPR bool operator==( const parallel_t&, const parallel_t&) { return true; } friend ASIO_CONSTEXPR bool operator!=( const parallel_t&, const parallel_t&) { return false; } friend ASIO_CONSTEXPR bool operator==( const parallel_t&, const unsequenced_t<I>&) { return false; } friend ASIO_CONSTEXPR bool operator!=( const parallel_t&, const unsequenced_t<I>&) { return true; } friend ASIO_CONSTEXPR bool operator==( const parallel_t&, const sequenced_t<I>&) { return false; } friend ASIO_CONSTEXPR bool operator!=( const parallel_t&, const sequenced_t<I>&) { return true; } }; #if defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) \ && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) template <int I> template <typename E, typename T> const T parallel_t<I>::static_query_v; #endif // defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) // && defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) } // namespace bulk_guarantee } // namespace detail typedef detail::bulk_guarantee_t<> bulk_guarantee_t; #if defined(ASIO_HAS_CONSTEXPR) || defined(GENERATING_DOCUMENTATION) constexpr bulk_guarantee_t bulk_guarantee; #else // defined(ASIO_HAS_CONSTEXPR) || defined(GENERATING_DOCUMENTATION) namespace { static const bulk_guarantee_t& bulk_guarantee = bulk_guarantee_t::instance; } #endif } // namespace execution #if !defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T> struct is_applicable_property<T, execution::bulk_guarantee_t> : integral_constant<bool, execution::is_executor<T>::value || conditional< execution::is_executor<T>::value, false_type, execution::is_sender<T> >::type::value || conditional< execution::is_executor<T>::value, false_type, execution::is_scheduler<T> >::type::value> { }; template <typename T> struct is_applicable_property<T, execution::bulk_guarantee_t::unsequenced_t> : integral_constant<bool, execution::is_executor<T>::value || conditional< execution::is_executor<T>::value, false_type, execution::is_sender<T> >::type::value || conditional< execution::is_executor<T>::value, false_type, execution::is_scheduler<T> >::type::value> { }; template <typename T> struct is_applicable_property<T, execution::bulk_guarantee_t::sequenced_t> : integral_constant<bool, execution::is_executor<T>::value || conditional< execution::is_executor<T>::value, false_type, execution::is_sender<T> >::type::value || conditional< execution::is_executor<T>::value, false_type, execution::is_scheduler<T> >::type::value> { }; template <typename T> struct is_applicable_property<T, execution::bulk_guarantee_t::parallel_t> : integral_constant<bool, execution::is_executor<T>::value || conditional< execution::is_executor<T>::value, false_type, execution::is_sender<T> >::type::value || conditional< execution::is_executor<T>::value, false_type, execution::is_scheduler<T> >::type::value> { }; #endif // !defined(ASIO_HAS_VARIABLE_TEMPLATES) namespace traits { #if !defined(ASIO_HAS_DEDUCED_QUERY_FREE_TRAIT) template <typename T> struct query_free_default<T, execution::bulk_guarantee_t, typename enable_if< can_query<T, execution::bulk_guarantee_t::unsequenced_t>::value >::type> { ASIO_STATIC_CONSTEXPR(bool, is_valid = true); ASIO_STATIC_CONSTEXPR(bool, is_noexcept = (is_nothrow_query<T, execution::bulk_guarantee_t::unsequenced_t>::value)); typedef execution::bulk_guarantee_t result_type; }; template <typename T> struct query_free_default<T, execution::bulk_guarantee_t, typename enable_if< !can_query<T, execution::bulk_guarantee_t::unsequenced_t>::value && can_query<T, execution::bulk_guarantee_t::sequenced_t>::value >::type> { ASIO_STATIC_CONSTEXPR(bool, is_valid = true); ASIO_STATIC_CONSTEXPR(bool, is_noexcept = (is_nothrow_query<T, execution::bulk_guarantee_t::sequenced_t>::value)); typedef execution::bulk_guarantee_t result_type; }; template <typename T> struct query_free_default<T, execution::bulk_guarantee_t, typename enable_if< !can_query<T, execution::bulk_guarantee_t::unsequenced_t>::value && !can_query<T, execution::bulk_guarantee_t::sequenced_t>::value && can_query<T, execution::bulk_guarantee_t::parallel_t>::value >::type> { ASIO_STATIC_CONSTEXPR(bool, is_valid = true); ASIO_STATIC_CONSTEXPR(bool, is_noexcept = (is_nothrow_query<T, execution::bulk_guarantee_t::parallel_t>::value)); typedef execution::bulk_guarantee_t result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_QUERY_FREE_TRAIT) #if !defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) \ || !defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) template <typename T> struct static_query<T, execution::bulk_guarantee_t, typename enable_if< execution::detail::bulk_guarantee_t<0>:: query_static_constexpr_member<T>::is_valid >::type> { ASIO_STATIC_CONSTEXPR(bool, is_valid = true); ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true); typedef typename execution::detail::bulk_guarantee_t<0>:: query_static_constexpr_member<T>::result_type result_type; static ASIO_CONSTEXPR result_type value() { return execution::detail::bulk_guarantee_t<0>:: query_static_constexpr_member<T>::value(); } }; template <typename T> struct static_query<T, execution::bulk_guarantee_t, typename enable_if< !execution::detail::bulk_guarantee_t<0>:: query_static_constexpr_member<T>::is_valid && !execution::detail::bulk_guarantee_t<0>:: query_member<T>::is_valid && traits::static_query<T, execution::bulk_guarantee_t::unsequenced_t>::is_valid >::type> { ASIO_STATIC_CONSTEXPR(bool, is_valid = true); ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true); typedef typename traits::static_query<T, execution::bulk_guarantee_t::unsequenced_t>::result_type result_type; static ASIO_CONSTEXPR result_type value() { return traits::static_query<T, execution::bulk_guarantee_t::unsequenced_t>::value(); } }; template <typename T> struct static_query<T, execution::bulk_guarantee_t, typename enable_if< !execution::detail::bulk_guarantee_t<0>:: query_static_constexpr_member<T>::is_valid && !execution::detail::bulk_guarantee_t<0>:: query_member<T>::is_valid && !traits::static_query<T, execution::bulk_guarantee_t::unsequenced_t>::is_valid && traits::static_query<T, execution::bulk_guarantee_t::sequenced_t>::is_valid >::type> { ASIO_STATIC_CONSTEXPR(bool, is_valid = true); ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true); typedef typename traits::static_query<T, execution::bulk_guarantee_t::sequenced_t>::result_type result_type; static ASIO_CONSTEXPR result_type value() { return traits::static_query<T, execution::bulk_guarantee_t::sequenced_t>::value(); } }; template <typename T> struct static_query<T, execution::bulk_guarantee_t, typename enable_if< !execution::detail::bulk_guarantee_t<0>:: query_static_constexpr_member<T>::is_valid && !execution::detail::bulk_guarantee_t<0>:: query_member<T>::is_valid && !traits::static_query<T, execution::bulk_guarantee_t::unsequenced_t>::is_valid && !traits::static_query<T, execution::bulk_guarantee_t::sequenced_t>::is_valid && traits::static_query<T, execution::bulk_guarantee_t::parallel_t>::is_valid >::type> { ASIO_STATIC_CONSTEXPR(bool, is_valid = true); ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true); typedef typename traits::static_query<T, execution::bulk_guarantee_t::parallel_t>::result_type result_type; static ASIO_CONSTEXPR result_type value() { return traits::static_query<T, execution::bulk_guarantee_t::parallel_t>::value(); } }; template <typename T> struct static_query<T, execution::bulk_guarantee_t::unsequenced_t, typename enable_if< execution::detail::bulk_guarantee::unsequenced_t<0>:: query_static_constexpr_member<T>::is_valid >::type> { ASIO_STATIC_CONSTEXPR(bool, is_valid = true); ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true); typedef typename execution::detail::bulk_guarantee::unsequenced_t<0>:: query_static_constexpr_member<T>::result_type result_type; static ASIO_CONSTEXPR result_type value() { return execution::detail::bulk_guarantee::unsequenced_t<0>:: query_static_constexpr_member<T>::value(); } }; template <typename T> struct static_query<T, execution::bulk_guarantee_t::unsequenced_t, typename enable_if< !execution::detail::bulk_guarantee::unsequenced_t<0>:: query_static_constexpr_member<T>::is_valid && !execution::detail::bulk_guarantee::unsequenced_t<0>:: query_member<T>::is_valid && !traits::query_free<T, execution::bulk_guarantee_t::unsequenced_t>::is_valid && !can_query<T, execution::bulk_guarantee_t::sequenced_t>::value && !can_query<T, execution::bulk_guarantee_t::parallel_t>::value >::type> { ASIO_STATIC_CONSTEXPR(bool, is_valid = true); ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true); typedef execution::bulk_guarantee_t::unsequenced_t result_type; static ASIO_CONSTEXPR result_type value() { return result_type(); } }; template <typename T> struct static_query<T, execution::bulk_guarantee_t::sequenced_t, typename enable_if< execution::detail::bulk_guarantee::sequenced_t<0>:: query_static_constexpr_member<T>::is_valid >::type> { ASIO_STATIC_CONSTEXPR(bool, is_valid = true); ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true); typedef typename execution::detail::bulk_guarantee::sequenced_t<0>:: query_static_constexpr_member<T>::result_type result_type; static ASIO_CONSTEXPR result_type value() { return execution::detail::bulk_guarantee::sequenced_t<0>:: query_static_constexpr_member<T>::value(); } }; template <typename T> struct static_query<T, execution::bulk_guarantee_t::parallel_t, typename enable_if< execution::detail::bulk_guarantee::parallel_t<0>:: query_static_constexpr_member<T>::is_valid >::type> { ASIO_STATIC_CONSTEXPR(bool, is_valid = true); ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true); typedef typename execution::detail::bulk_guarantee::parallel_t<0>:: query_static_constexpr_member<T>::result_type result_type; static ASIO_CONSTEXPR result_type value() { return execution::detail::bulk_guarantee::parallel_t<0>:: query_static_constexpr_member<T>::value(); } }; #endif // !defined(ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) // || !defined(ASIO_HAS_SFINAE_VARIABLE_TEMPLATES) #if !defined(ASIO_HAS_DEDUCED_STATIC_REQUIRE_TRAIT) template <typename T> struct static_require<T, execution::bulk_guarantee_t::unsequenced_t, typename enable_if< static_query<T, execution::bulk_guarantee_t::unsequenced_t>::is_valid >::type> { ASIO_STATIC_CONSTEXPR(bool, is_valid = (is_same<typename static_query<T, execution::bulk_guarantee_t::unsequenced_t>::result_type, execution::bulk_guarantee_t::unsequenced_t>::value)); }; template <typename T> struct static_require<T, execution::bulk_guarantee_t::sequenced_t, typename enable_if< static_query<T, execution::bulk_guarantee_t::sequenced_t>::is_valid >::type> { ASIO_STATIC_CONSTEXPR(bool, is_valid = (is_same<typename static_query<T, execution::bulk_guarantee_t::sequenced_t>::result_type, execution::bulk_guarantee_t::sequenced_t>::value)); }; template <typename T> struct static_require<T, execution::bulk_guarantee_t::parallel_t, typename enable_if< static_query<T, execution::bulk_guarantee_t::parallel_t>::is_valid >::type> { ASIO_STATIC_CONSTEXPR(bool, is_valid = (is_same<typename static_query<T, execution::bulk_guarantee_t::parallel_t>::result_type, execution::bulk_guarantee_t::parallel_t>::value)); }; #endif // !defined(ASIO_HAS_DEDUCED_STATIC_REQUIRE_TRAIT) } // namespace traits #endif // defined(GENERATING_DOCUMENTATION) } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_EXECUTION_BULK_GUARANTEE_HPP
[ "qicosmos@163.com" ]
qicosmos@163.com
8838e21b17311dc385b0d9299bd36c293915c3b0
18deab26ab7fecc40f6f9c5836486ea8138504b6
/Il2Native.Logic/impl/System/Diagnostics/Debugger.cpp
9cbaf1f470f919390047aa88dce34f19bb648ac6
[ "MIT" ]
permissive
Stretto/cs2cpp
5176139b6a669145865003f90586f8804024fd55
bd6afb242bc96df4b21b77e404c2b961309b796a
refs/heads/master
2020-04-05T22:43:24.484545
2017-06-22T07:42:37
2017-06-22T07:42:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
306
cpp
#include "CoreLib.h" // Method : System.Diagnostics.Debugger.IsAttached.get bool CoreLib::System::Diagnostics::Debugger::get_IsAttached() { throw 0xC000C000; } // Method : System.Diagnostics.Debugger.Break() void CoreLib::System::Diagnostics::Debugger::Break() { throw 0xC000C000; }
[ "duzhar@hotmail.com" ]
duzhar@hotmail.com
15ca2eb6578cef80655344f3510875ca03d7510f
41c7836da77c95250949d908f3e6235597b40e6b
/Old experimental/pizzaOrderingSystem/30_nov_3layertest/handler_test/ToppingSystem/Toppings.h
faf09c2ffaec35781b9994ce209c21999ecd3a2f
[]
no_license
brynjarorng/TeamEagle
22aa24d1e30dcce5acb41dcec7afd2eaab92ebf9
d13d40349718d838fa0fb861205b957452b07ff4
refs/heads/master
2021-08-30T03:53:51.876127
2017-12-15T23:18:41
2017-12-15T23:18:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
980
h
#ifndef TOPPINGS_H #define TOPPINGS_H #include <string> #include<iostream> #include <cstring> #include <string> using namespace std; class Toppings { public: Toppings(); //Initializes cname[0] = '\0' and price to 0.0. Toppings(string name, double price); //Sets this ->price to price, and converts name to a corresponding //charachter array. //string namegame(); friend ostream& operator << (ostream& outs, const Toppings& topping); //Outstreams name of topping followed by a whitespace and then the price //of the topping. friend istream& operator >> (istream& ins, Toppings& topping); //The order of instream is the following: //name then price. string get_name(); //Returns the name of topping double get_price(); private: static const int CNAME_SIZE = 21; char cname[CNAME_SIZE]; //Name of topping. double price; void append_null(int index); //Postcondtion: cname[index - 1] is now '\0' void convert_string_cstring(string in); }; #endif //TOPPINGS_H
[ "viktorsveins@gmail.com" ]
viktorsveins@gmail.com
3a771ab92ce63b207ed5ed3c06eec6cfb7dc6129
7ef8afb6e7770e59ae863d582ae2fd850a40a745
/src/alloy/compiler/compiler_pass.h
4ba38b6c49a23361bdded855202f3a2dc9c8cfd3
[]
no_license
Fire30/xenia
ab7b5eecbdf7d719e318e902930d131691dc9e40
15be1061d36649c1faf2eda571aaae434cde273b
refs/heads/master
2021-01-16T17:56:38.722987
2014-07-02T22:17:09
2014-07-02T22:17:09
21,152,219
1
0
null
null
null
null
UTF-8
C++
false
false
1,125
h
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #ifndef ALLOY_COMPILER_COMPILER_PASS_H_ #define ALLOY_COMPILER_COMPILER_PASS_H_ #include <alloy/core.h> #include <alloy/hir/hir_builder.h> namespace alloy { namespace runtime { class Runtime; } } namespace alloy { namespace compiler { class Compiler; class CompilerPass { public: CompilerPass(); virtual ~CompilerPass(); virtual int Initialize(Compiler* compiler); virtual int Run(hir::HIRBuilder* builder) = 0; protected: Arena* scratch_arena() const; protected: runtime::Runtime* runtime_; Compiler* compiler_; }; } // namespace compiler } // namespace alloy #endif // ALLOY_COMPILER_COMPILER_PASS_H_
[ "ben.vanik@gmail.com" ]
ben.vanik@gmail.com
412a10124311daa904b3625edf9745bb7abea78a
9c16d6b984c9a22c219bd2a20a02db21a51ba8d7
/components/browser_watcher/watcher_metrics_provider_win.h
e198c526e807a4c1e7c2d294796bc4b4089ded6a
[ "BSD-3-Clause" ]
permissive
nv-chromium/chromium-crosswalk
fc6cc201cb1d6a23d5f52ffd3a553c39acd59fa7
b21ec2ffe3a13b6a8283a002079ee63b60e1dbc5
refs/heads/nv-crosswalk-17
2022-08-25T01:23:53.343546
2019-01-16T21:35:23
2019-01-16T21:35:23
63,197,891
0
0
NOASSERTION
2019-01-16T21:38:06
2016-07-12T22:58:43
null
UTF-8
C++
false
false
1,924
h
// Copyright (c) 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_BROWSER_WATCHER_WATCHER_METRICS_PROVIDER_WIN_H_ #define COMPONENTS_BROWSER_WATCHER_WATCHER_METRICS_PROVIDER_WIN_H_ #include "base/macros.h" #include "base/strings/string16.h" #include "components/metrics/metrics_provider.h" namespace browser_watcher { // Provides stability data captured by the Chrome Watcher, namely the browser // process exit codes, as well as exit funnel metrics. // The exit funnel records a trace of named, timed events in registry per // process. For reporting, the trace is recorded as a sequence of events // named Stability.ExitFunnel.<eventname>, associated to the time // (in milliseconds) from first event in a trace. For a normal process exit, // the sequence might look like this: // - Stability.ExitFunnel.Logoff: 0 // - Stability.ExitFunnel.NotifyShutdown: 10 // - Stability.ExitFunnel.EndSession: 20 // - Stability.ExitFunnel.KillProcess: 30 class WatcherMetricsProviderWin : public metrics::MetricsProvider { public: static const char kBrowserExitCodeHistogramName[]; static const char kExitFunnelHistogramPrefix[]; // Initializes the reporter. If |report_exit_funnels| is false, the provider // will clear the registry data, but not report it. WatcherMetricsProviderWin(const base::char16* registry_path, bool report_exit_funnels); ~WatcherMetricsProviderWin() override; // metrics::MetricsProvider implementation. void ProvideStabilityMetrics( metrics::SystemProfileProto* system_profile_proto) override; private: base::string16 registry_path_; bool report_exit_funnels_; DISALLOW_COPY_AND_ASSIGN(WatcherMetricsProviderWin); }; } // namespace browser_watcher #endif // COMPONENTS_BROWSER_WATCHER_WATCHER_METRICS_PROVIDER_WIN_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
9b6f496f0db2b91aeca7d86f5500a6b9b7b10f54
5c619c3644deeaa0b7e414a1a3e14eae835c26e1
/tutorial/000 - intermediated/008 - Clean code/008 - Clean code/Triangulo.hpp
6013abf5eb74e5f6f2638c3c567979b3e03e460c
[]
no_license
dusong7/Advanced-c-cpp-Programming-Tutorial
0f38d0b21513afedc22e8f7e887f4a3ebf99483f
d1f3345fa38296b2dafb23a0fc1c625a91612133
refs/heads/master
2021-06-14T04:41:06.845183
2017-04-05T14:35:37
2017-04-05T14:35:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
499
hpp
// // Triangulo.hpp // 008 - Clean code // // Created by Victor Bolinches Marin on 24/11/15. // Copyright © 2015 Victor Bolinches Marin. All rights reserved. // #ifndef Triangulo_hpp #define Triangulo_hpp #include <stdio.h> #include "Triangulo.hpp" #include "Figura.hpp" #include <iostream> #include <sstream> using namespace std; class Triangulo: public Figura { public: Triangulo(){} string toString(); float perimetro(); float area(); }; #endif /* Triangulo_hpp */
[ "el_bolinches@hotmail.com" ]
el_bolinches@hotmail.com
76916007e86316e9a7949f2dbacc17a5d5f9bfef
305652c7bbdda46a7f4767a06c7e3573d8ab4b84
/codeforces/474/D.cpp
9aa055c3ad059d999eacfd9f31b7fb85de5a6cbb
[]
no_license
ImperishableMe/codeforces-submissions
cde2ac379aa0580937d935f1ece7d3681e45471a
9cd18f567c477f7392f2994c22168b4c6801d02c
refs/heads/master
2023-06-15T03:46:05.243797
2021-06-18T13:34:00
2021-07-11T07:20:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,215
cpp
#include <bits/stdc++.h> #define PII pair < int , int > #define PI 2.0*acos(0.0) #define ll long long int #define loop(i, a, n) for(int i = int (a); i <= int (n); i++) #define vi vector < int > #define pb push_back #define ceil(a, b) (a %b == 0)?(a/b):(a/b)+1 ll const inf = 1LL << 59 ; int const MX = 1e5 + 5 ; int const EPS = 1e-9; int const MOD = 1e9 + 7; using namespace std; //global variables int k; int dp[MX]; int cumsum[MX]; int way(int i) { if(i == 0) return 1; if(dp[i] != -1) return dp[i]; int ret1 = 0, ret2; if(i - k + 1 >= 0) ret1 = way(i - k); ret2 = way(i - 1); return dp[i] = (ret1 % MOD + ret2 % MOD) % MOD; } int main(){ // int n, k; int t,a,b; cin >> t >> k; memset(dp, -1 , sizeof dp); cumsum[0] = 0; for(int i = 1; i < MX; i++) cumsum[i] = (cumsum[i-1] + way(i)) % MOD; // cin >> n >> k; for(int i = 1; i <= t; i++) { int ans; cin >> a >> b; ans = cumsum[b] - cumsum[a-1]; if(ans < 0) ans = ( ans + MOD) % MOD; cout << ans << endl; } // //cout << way(1); return 0; }
[ "bishwajit0020@gmail.com" ]
bishwajit0020@gmail.com
5245f0a0854f2e50487e8d3356484e65fb871e51
ab18860c728aa14af6f46ae05305151bd4d40579
/GAME3001_W05_AStar/GAME3001_W05_AStar/GAME1017_Template_W01/Pathing.h
c863805b2c69eb2fc74cab37d448064aa3a147a3
[]
no_license
eorjs2020/AI_Project
4e1fb6d7640214bd9c173bde45d6abbe75f9466c
e48c73a084cc61638b896b92022806af89f09a81
refs/heads/master
2022-11-14T13:47:17.504090
2020-07-06T00:04:31
2020-07-06T00:04:31
276,232,649
0
0
null
null
null
null
UTF-8
C++
false
false
1,269
h
#pragma once #ifndef _PATHING_H_ #define _PATHING_H_ #include <SDL.h> #include <vector> class PathConnection; // Forward declaration required. class PathNode : public SDL_Point // Because why not? { public: PathNode(int x, int y); ~PathNode(); void Update(); void AddConnection(PathConnection* c); std::vector<PathConnection*>& GetConnections(); SDL_Point Pt() { return { x, y }; } double H() { return m_h; } void SetH(double h) { m_h = h; } private: double m_h; // Heuristic cost for node. std::vector<PathConnection*> m_connections; }; class PathConnection { public: PathConnection(PathNode* f, PathNode* t, double cost = 1.0); ~PathConnection() {} double GetCost() { return m_cost; } void SetCost(double cost) { m_cost = cost; } PathNode* GetFromNode() { return m_pFromNode; } PathNode* GetToNode() { return m_pToNode; } private: double m_cost; PathNode *m_pFromNode, *m_pToNode; }; struct NodeRecord { // Everything public by default. NodeRecord(PathNode* n = nullptr) :m_node(n), m_connection(nullptr), m_fromRecord(nullptr), m_costSoFar(0.0), m_totalCost(0.0){ } PathNode* m_node; PathConnection* m_connection; NodeRecord* m_fromRecord; double m_costSoFar; double m_totalCost; }; #endif
[ "eorjs2020@gmail.com" ]
eorjs2020@gmail.com
885706dce11a18df52747a8a0c28d5a9230eb115
410eeaa6918cd43187a24045a6269d6dc81371e3
/test/test.cpp
d39c31147a9838ec5d57fdd6c9f082e92b9a9d05
[]
no_license
aiadaniel/cocos-py
01c05b4133baffe2581cfb28760fefc5fb56e706
723d996dc4b844c2f0947f4c80b4bdb796a38a97
refs/heads/master
2022-03-02T14:39:49.580826
2019-08-29T09:56:24
2019-08-29T09:56:24
202,335,326
0
0
null
null
null
null
UTF-8
C++
false
false
7,720
cpp
#pragma comment (lib,"python27.lib") #include "python.h" //c++对象 class CTest { int _v; public: //相关python对象 PyObject *_object; public: CTest():_v(22),_object(NULL) { printf("CTest::CTest%p\n",this); } void AddRef(int v) { _v += v; printf("CTest::AddRef = %d\n",_v); } int DelRef() { printf("CTest::DelRef = %d\n",_v); if (_v == 0) { delete this; return 0; } return _v; } virtual ~CTest() { printf("CTest::~CTest %p\n",this); }; }; //对应脚本中的python对象,解析python脚本,会生成这么一个对象 struct PY_Test { PyObject_HEAD PyObject *ob_dict; CTest *ob_body; PyObject *ob_weaklist; }; //生成PY_Test对象 PyObject* CTest_New(PyTypeObject *type,PyObject *args,PyObject *kwds); //生成CTest对象 int CTest_Init(PyObject *pself,PyObject *args,PyObject *kwds); //导出的方法 PyMethodDef* CTest_GetMethods(); //python对象应用计数为0时调用 void CTest_Dealloc(PY_Test *self); //容器类对象使用 int CTest_Clear(PY_Test *self); //遍历 int CTest_Traverse(PY_Test *self,visitproc visit,void *args); //比较是否相等 int CTest_Compare(PY_Test *self,PyObject *cmp); //通过以下对象来创建PY_Test的python对象及其所有行为 PyTypeObject PY_TestType = { \ PyObject_HEAD_INIT(NULL) \ 0, /* ob_size */\ "CTest", /* tp_name */\ sizeof(PY_Test), /* tp_basicsize */\ 0, /* tp_itemsize */\ /* Methods to implement standard operations */ (destructor)(CTest_Dealloc), /*destructor tp_dealloc;*/\ 0, /* printfunc tp_print;*/\ 0, /*getattrfunc tp_getattr;*/\ 0, /*setattrfunc tp_setattr; */\ (cmpfunc)(CTest_Compare), /* tp_compare */\ 0, /* reprfunc tp_repr; */\ /* Method suites for standard classes */ 0, /* PyNumberMethods *tp_as_number; */\ 0, /* PySequenceMethods *tp_as_sequence; */\ 0, /* PyMappingMethods *tp_as_mapping; */\ /* More standard operations (here for binary compatibility) */ 0, /* hashfunc tp_hash; */\ 0, /* ternaryfunc tp_call; */\ 0, /* reprfunc tp_str; */\ 0, /* getattrofunc tp_getattro; */\ 0, /* setattrofunc tp_setattro; */\ /* Functions to access object as input/output buffer */ 0, /* PyBufferProcs *tp_as_buffer; */\ /* Flags to define presence of optional/expanded features */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */\ 0, /* const char *tp_doc; Documentation string */\ /* Assigned meaning in release 2.0 */ /* call function for all accessible objects */ (traverseproc)(CTest_Traverse), /* traverseproc tp_traverse; */\ /* delete references to contained objects */ (inquiry)(CTest_Clear), /* tp_clear; */\ /* Assigned meaning in release 2.1 */ /* rich comparisons */ 0, /* richcmpfunc tp_richcompare; */\ /* weak reference enabler */ offsetof(PY_Test,ob_weaklist), /* Py_ssize_t tp_weaklistoffset; */\ /* Added in release 2.2 */ /* Iterators */ 0, /* getiterfunc tp_iter; */\ 0, /* iternextfunc tp_iternext; */\ /* Attribute descriptor and subclassing stuff */ CTest_GetMethods(), /* struct PyMethodDef *tp_methods; */\ 0, /* struct PyMemberDef *tp_members; */\ 0, /* struct PyGetSetDef *tp_getset; */\ 0, /* struct _typeobject *tp_base; */\ 0, /* PyObject *tp_dict; */\ 0, /* descrgetfunc tp_descr_get; */\ 0, /* descrsetfunc tp_descr_set; */\ offsetof(PY_Test,ob_dict), /* Py_ssize_t tp_dictoffset; */\ (initproc)(CTest_Init), /* initproc tp_init; */\ 0, /* allocfunc tp_alloc; */\ CTest_New, /* newfunc tp_new; */ }; //生成PY_Test对象 PyObject* CTest_New(PyTypeObject *type,PyObject *args,PyObject *kwds) { PY_Test *self = NULL; self = (PY_Test *)type->tp_alloc(type,0); if (self != NULL) { self->ob_dict = PyDict_New(); self->ob_weaklist = NULL; self->ob_body = NULL; } return (PyObject*)self; } //生成CTest对象 int CTest_Init(PyObject *pself,PyObject *args,PyObject *kwds) { PY_Test *self = (PY_Test*)pself; CTest *node = new CTest(); if (node) { self->ob_body = node; node->_object = (PyObject*)self; return 1; } return 0; } PyObject* CTest_AddRef(PY_Test *self,PyObject *args) { int p1; if (PyArg_ParseTuple(args,"i",&p1)) { self->ob_body->AddRef(p1); } Py_INCREF(Py_None); return Py_None; } PyObject* CTest_DelRef(PY_Test *self,PyObject *args) { int iret = self->ob_body->DelRef(); return Py_BuildValue("i", iret); } //导出的方法 PyMethodDef* CTest_GetMethods() { static PyMethodDef methods[3] = { {"AddRef",(PyCFunction)CTest_AddRef,METH_VARARGS,""}, {"DelRef",(PyCFunction)CTest_DelRef,METH_NOARGS,""}, {0,0,0,0} }; return methods; } //python对象应用计数为0时调用 void CTest_Dealloc(PY_Test *self) { if (self->ob_dict) { Py_DECREF(self->ob_dict); self->ob_dict = NULL; } if (self->ob_body) { self->ob_body->DelRef(); } self->ob_type->tp_free((PyObject*)self); } //容器类对象使用 int CTest_Clear(PY_Test *self) { if (self->ob_dict) { Py_DECREF(self->ob_dict); self->ob_dict = NULL; } return 0; } //遍历 int CTest_Traverse(PY_Test *self,visitproc visit,void *args) { if (self->ob_dict) { return visit(self->ob_dict, args); } return 0; } //比较是否相等 int CTest_Compare(PY_Test *self,PyObject *cmp) { if (self->ob_body == ((PY_Test*)cmp)->ob_body) { return 0; } return 1; } /*****************************************************************************/ /*****************************************************************************/ //以下测试将C_test的python模块加入到系统中,脚本import C_test,就可以使用它导出的类与方法 PyMODINIT_FUNC TestInit() { PyObject *m = NULL; m = Py_InitModule("C_test", NULL); if (m == NULL) { return; } if (PyType_Ready(&PY_TestType) < 0) { return; } Py_INCREF(&PY_TestType); //添加类到模块,参数:模块指针、类名、类型 PyModule_AddObject(m, "CTest", (PyObject*)&PY_TestType); } #include "pythread.h" int main() { Py_Initialize(); PyRun_SimpleString("print 'hello py'"); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); TestInit(); //导入脚本zzz.py PyObject *pModule = PyImport_ImportModule("zzz"); //导入函数 PyObject *pFunc = PyObject_GetAttrString(pModule, "Func"); Py_DECREF(pModule); if (pFunc) { PyObject *result = PyEval_CallObject(pFunc,NULL); char *n = 0; PyArg_Parse(result,"s",&n); Py_XDECREF(pFunc); } Py_XDECREF(pModule); Py_Finalize(); return 0; }
[ "company@yahoo.com" ]
company@yahoo.com
f307ec174801f9217ac9cd70caee4f01aeb38d2f
572580660d475027fa349e47a078479222066726
/Server/kennel/testws/testws.cpp
8318cb416f6c426bb90edc50c044b2f00bc9b332
[]
no_license
SiteView/ecc82Server
30bae118932435e226ade01bfbb05b662742e6dd
084b06af3a7ca6c5abf5064e0d1f3f8069856d25
refs/heads/master
2021-01-10T21:11:37.487455
2013-01-16T09:22:02
2013-01-16T09:22:02
7,639,874
6
3
null
null
null
null
GB18030
C++
false
false
1,997
cpp
// testws.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "testws.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // 唯一的应用程序对象 CWinApp theApp; using namespace std; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { //test int nRetCode = 0; // 初始化 MFC 并在失败时显示错误 if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { // TODO: 更改错误代码以符合您的需要 _tprintf(_T("致命错误: MFC 初始化失败\n")); nRetCode = 1; } else { // TODO: 在此处为应用程序的行为编写代码。 } CString estr = ""; HMODULE hDll = LoadLibrary(".\\MonitorScheduleWeb.dll"); if( !hDll ) { estr+= " Failed to LoadLibrary: "; return false; } //typedef bool (*SendMsg)(const char *pszId, const char *pszText, const char *pszServer, const char *pszPort); typedef bool (*SendMsg)(string szId, string pszText, string pszServer, string pszPort, string &errorMsg); //typedef bool (*SendMsg)(string szId, string pszText, string pszServer, string pszPort); //typedef bool (*SendMsg)(char *, char *, char *, char *, char &); SendMsg sendmsg = (SendMsg)::GetProcAddress(hDll, "SendMsg"); if( !sendmsg ) { estr+= " 获取dll函数失败, Failed to GetProcAddress: SendMsg; "; return false; } else { bool bret = true; char strInputData[256] = {0}; sprintf(strInputData , "%s" , "eeeeee"); string errorMsg = ""; //bret = sendmsg("1.5.6", "ddddd#ddd#dfhfdsf#ggggggggggggg", "127.0.0.1", "8080", *strInputData); bret = sendmsg("1.5.6", "ddddd#ddd#dfhfdsf#ggggggggggggg", "127.0.0.1", "8080", errorMsg); //bret = sendmsg("1", "ddddd#ddd#dfhfdsf#ggggggggggggg", "127.0.0.1", "8080", *strInputData); //bret = sendmsg("xxx", "ddddd#ddd#dfhfdsf#ggggggggggggg", "dddddddddddddd", "dddd"); if(bret) { _tprintf(_T("sendmsg sucess\n")); } else { _tprintf(_T("sendmsg failed\n")); _tprintf(errorMsg.c_str()); } } return nRetCode; }
[ "xingyu.cheng@dragonflow.com" ]
xingyu.cheng@dragonflow.com
f37053f789af0bc4561f252333c5e1b3c09d8737
55a920e082b0ba7dc7b44c5edd05fd5d46ad3bc0
/inc/owVtkExport.h
942cc359d728469c07e60145f91162fe946b3653
[ "MIT" ]
permissive
openworm/sibernetic
874a6ccbc26b79d9826810852d9d0786f7597a64
8d2df73b689c72db5b87cd7909700a99c29f0701
refs/heads/development
2023-07-06T17:40:36.470692
2021-10-08T07:45:17
2021-10-08T07:45:17
4,505,793
244
87
NOASSERTION
2022-09-01T16:22:07
2012-05-31T09:17:16
C
UTF-8
C++
false
false
3,200
h
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2015 OpenWorm. * http://openworm.org * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT * * Contributors: * OpenWorm - http://openworm.org/people.html * * 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 OW_VTKEXPORT_H #define OW_VTKEXPORT_H #include "owConfigProperty.h" #include "owOpenCLConstant.h" #include "owPhysicsConstant.h" /* Function exportState() serves to export the current state to the VTK file. Following is exported: - Location of the particles - Types of the particles (Liquid, elastic, boundary as defined in owOpenCLConstant.h) - Velocity of the particles - Connections (CellType == 1) - Membranes (CellType == 2) - Muscle numbers (Positive for muscles, -1 for elastic connections, -2 for membranes) - Muscle activation (Positive for muscles, -1 for elastic connections, -2 for membranes) State in the time step N is saved to the file buffers/state_N.vtp. Possible improvements: TODO: Write data in binary to save some space */ namespace owVtkExport { extern bool isActive; /** Export the state in one time step to a VTK file * * @param iteration * Iteration number * @param config * Pointer to the owConfigProperty object it includes information about * @param position * Pointer to the position buffer * @param connections * Pointer to the connection buffer * @param velocity * Pointer to the velocity buffer * @param membranes * Pointer to the membranes buffer * @param muscleActivationSignal * Pointer to the muscle activation signal buffer */ void exportState(int iteration, owConfigProperty * config, float * position, float * connections, float * velocity, int * membranes, float * muscleActivationSignal); } #endif // #ifndef OW_VTKEXPORT_H
[ "viktor.sip@centrum.cz" ]
viktor.sip@centrum.cz
85ec67c77b1cc320296d02b5d50e19927e5d1fb4
176c99a334d7f88469b8cfb59e66b4b1b4dc1cbb
/enlarginghashtables.cpp
06b09ae6199faa375434eeb431881d79a2ca48ea
[]
no_license
shdltkdi12/acm
1f142d7a3fb1b26ca4755899a5f1cb34b44c82e3
fadb9245ecf03d480c7f49bbb97359faff2462ea
refs/heads/master
2020-07-22T03:50:52.311753
2020-07-05T11:41:45
2020-07-05T11:41:45
207,065,611
0
0
null
null
null
null
UTF-8
C++
false
false
1,232
cpp
#include <iostream> #include <vector> #include <bits/stdc++.h> #include <algorithm> std::vector<int> primes; int closest( int value) { auto const it = std::upper_bound(primes.begin(), primes.end(), value); return *it; } void SieveOfEratosthenes(int n) { bool prime[n]; memset(prime, true, sizeof(prime)); for (int p = 2; p <= sqrt(n); ++p) { if (prime[p]) { for (int i = p*2; i <=n ; i += p) prime[i] = false; } } for (int p = 2; p <= n; ++p) if (prime[p]) primes.push_back(p); } bool prime(int n) { if(n == 2) return true; for(int i = 2; i <= sqrt(n); ++i) { if(n % i == 0) return false; } return true; } int main() { int n; SieveOfEratosthenes(1000000); // not the greatest of ideas, but it does speed the execution up. while(std::cin >> n) { if(n==0) break; if(2*n < primes[primes.size()-1]){ std::cout << closest(2*n); if(!std::binary_search(primes.begin(), primes.end(), n)) std::cout << " (" << n << " is not prime)"; } else { for(int i = 2 * n + 1;;++i) { if(prime(i)) { std::cout << i; break; } } if(!prime(n)) std::cout << " (" << n << " is not prime)"; } std::cout << std::endl; } return 0; }
[ "izr0007@auburn.edu" ]
izr0007@auburn.edu
9df7d49328934294566bb85a2a7db5aeb8bba3ca
42592ce2eebff7f3cc1fe69f526d22504d1b46b2
/kinSel/hh4b_13TeV_kinSel.cc
617b4328eaf9b6985d8b444b3e5542aaca650fdd
[]
no_license
MDallOsso/hh4bNores
6a93709e502308fa388a23b9cdb1849a56f182d0
532cb94f963d9a0df67b6319ee86baf6c751c1b0
refs/heads/master
2021-01-22T23:20:17.713224
2015-12-01T13:29:43
2015-12-01T13:29:43
42,178,524
0
0
null
null
null
null
UTF-8
C++
false
false
49,403
cc
// Code for non resonant HH->bbbb in CMS Run2 // Step1 - KINEMATIC SELECTION // Author: Martino Dall'Osso // thanks Souvik Das (Univ. of Florida) & Caterina Vernieri (FNAL) // Sept 21th, 2015 // g++ `root-config --libs --cflags` hh4b_13TeV_kinSel.cc -o kinSel // ./kinSel BTagCSVRun2015C-D 1 Trg3b_pT20CSVL_4CSV 2 // option: sample, isData, option, 4thSelectionMethod, maxEvents //---------------------------------------------------------------- #define hh4b_kinSel_C #include <TH1F.h> #include <TH2F.h> #include <TFile.h> #include <TTree.h> #include <TChain.h> #include <TCanvas.h> #include <TLorentzVector.h> #include <iostream> #include <fstream> #include <iomanip> #include <vector> // selection parameters: //------------------------- bool yesTrg_hh4bFinal = true; //only (QuadTriple || DoubleTriple) bool yesTrg_hh4bQuadTriple = false; bool yesTrg_hh4bDoubleTriple = false; bool yesTrg_hh4bQuadDouble = false; //for trg efficiency bool yesTrg_hh4bDoubleDouble = false; //for trg efficiency bool yesTrg_hh4bAll = false; //include all the 4th paths float Jet_pt_cut_low = 20.; float deltaRCut = 0.5; //0.5 - for matching int nJets_cut = 4; float Jet_eta_cut = 10.; float CSV_cut = 0.605; //Run2: low 0.605; medium 0.890; high 0.970. Run1: low 0.679 (used in the first presentation). float nJets_CSVcut = 3; //number of Jets on which apply CSV cut // matrix parameters --> needed?... static const int binPt = 10; static const int binCSV = 8; static const int binEta = 4; //-------------------------- // environment //--------------- //WARNING: CHANGE ME!! static const std::string dataframVer="V15"; static const std::string MCframVer="V14"; static const std::string utilsFld="../utils/"; static const std::string dataFld="../data/"+dataframVer+"/"; static const std::string subdataFld=dataFld+"officialNtuples/"; static const std::string MCFld="../data/"+MCframVer+"/"; static const std::string subMCFld=MCFld+"officialNtuples/"; static const std::string step0Fld="../data/Step0/"; static const std::string plotsFld="plots/"+dataframVer+"/"; //dataVersion is the one that rules for next steps static const std::string matrixFld="jetsMatch_matrix/"; // struct and common functions //#include "../utils/HelperFunctions.h" #include "hh4b_13TeV_kinSel.h" //Histos are here #include "../utils/hh4bStructs.h" //------------- int main (int argc, char **argv) { //DEBUG!!!! std::string sample_, opt_, MCsample_RL_ = ""; bool isData_ ; int finalIndex_ = 2, maxEvents_ = 0; for(int i=1; i<argc; i++) { if(i==1) sample_ = argv[i]; if(i==2) isData_ = std::atoi(argv[i]); if(i==3) opt_ = argv[i]; if(i==4) finalIndex_ = std::atoi(argv[i]); if(i==5) maxEvents_ = std::atoi(argv[i]); if(i==6) MCsample_RL_ = argv[i]; } hh4b_kinSel kinSel (sample_,isData_, opt_, finalIndex_, maxEvents_, MCsample_RL_); kinSel.dokinSel(); return 0; } hh4b_kinSel::hh4b_kinSel(std::string sam, bool isD, std::string op, int fi, int mx , std::string MC){ sample=sam; opt=op; MCsample_RL=MC; isData=isD; finalIndex=fi; maxEvents=mx; if(sample == "M-260" || sample == "SM") isSignal = true; //debug else isSignal = false; setSumW2(); } //------------- // CORE FUNCTION //------------- void hh4b_kinSel::dokinSel() //final index -> to decide which method to use for the 4th jet matching: 0 MCTruth, 1 matrix, 2 CSV, 3 minMass //MCsample_RL -> MC sample used to fill RL matrix { //Histos -- optimize --> clone and empty... //open input file // if(!readFiles(inF)) return; //check-- std::string fname; if(isData) fname = step0Fld+"tree_Step0_"+dataframVer+"_"+sample+".root"; else fname = step0Fld+"tree_Step0_"+MCframVer+"_"+sample+".root"; TFile * inF = TFile::Open(fname.c_str()); if(!inF) return; inF->cd(); TTree *tree=(TTree*)inF->Get("tree"); //retrieve variables setBranches(tree); //std::cout<<Jet_pt[0]<<" "<<Jet_pt[1]<<" "<<Jet_pt[2]<< " "<<std::endl; //output file std::string eve = ""; if(maxEvents > 0) eve = "_" + std::to_string(maxEvents); outfilename=dataFld+"tree_Step1_"+sample+"_"+opt+eve+".root"; //dataVersion is the one that rules for next steps TFile *outfile=new TFile(outfilename.c_str(), "RECREATE"); //debug //output tree with brand new branches TTree *outtree = new TTree("tree", "tree_step1"); createTree(outtree); int nEvents; if(maxEvents>0) nEvents=maxEvents; else nEvents=tree->GetEntries(); //read Matrix to select 4th jet (only if RL method is selected) if(!readMatrix()) { if(finalIndex==1)return; } //------------------ // Loop over events //------------------ std::cout << "nEvents: " << nEvents << std::endl; for (int i=0; i<nEvents; ++i){ ++nCut0; jets_all.clear(); jets_inAcc.clear(); jets_inAcc_P.clear(); fJets_P.clear(); fJets_CSV.clear(); fJets.clear(); aJets.clear(); if((i%500000) == 0) std::cout << i <<std::endl; bool jet_inAcc [30]; bool foundHH=false; nJets_InAcc = 0; tree->GetEvent(i); //READ EVENT h_nJets->Fill(nJet); if(finalIndex==1 && isSignal && i<=0.5*nEvents) continue; // to use only second part of the sample if Signal MC //to not run on events used to fill the matrix else { std::vector<TLorentzVector> genB_P, genBISR_P; //if(!isData){ //to check jet matching for(int p=0; p<4; p++){ TLorentzVector b; //TLorentzVector bISR; //bISR.SetPtEtaPhiM(GenBfH_pt[p],GenBfH_eta[p],GenBfH_phi[p],GenBfH_mass[p]); b.SetPtEtaPhiM(GenBfH_pt[p],GenBfH_eta[p],GenBfH_phi[p],GenBfH_mass[p]); genB_P.push_back(b); //genBISR_P.push_back(b); } //} //----------------------- // 1.cut on trigger - new trigger path //----------------------- if(yesTrg_hh4bAll){ if(HLT_HH4bAll) ++nCut1; else continue; //break loop if not right trigger path } else if(yesTrg_hh4bFinal){ if(HLT_BIT_QuadTriple || HLT_BIT_DoubleTriple) ++nCut1; else continue; //break loop if not right trigger path } else if(yesTrg_hh4bQuadTriple){ if(HLT_BIT_QuadTriple) ++nCut1; else continue; //break loop if not right trigger path } else if(yesTrg_hh4bDoubleTriple){ if(HLT_BIT_DoubleTriple) ++nCut1; else continue; //break loop if not right trigger path } else if(yesTrg_hh4bQuadDouble){ if(HLT_BIT_QuadDouble) ++nCut1; else continue; //break loop if not right trigger path } else if(yesTrg_hh4bDoubleDouble){ if(HLT_BIT_DoubleDouble) ++nCut1; else continue; //break loop if not right trigger path } h_nJets_InAcc->Fill(nJets_InAcc); //weightPU? - debug //----------------------- // 2.cut on vtype //----------------------- if(1) ++nCut2; //debug - to be implemented.. else continue; //---------------------------------------- // fill Jet vector with jet sorted in pT //---------------------------------------- for (int j=0; j<nJet; ++j){ //loop on all the jets (only inAcc are saved) Jet je; je.CSV = Jet_btagCSV[j]; je.pT = Jet_pt[j]; je.mass = Jet_mass[j]; je.eta = Jet_eta[j]; je.phi = Jet_phi[j]; je.chMult = Jet_chMult[j]; je.leadTrackPt = Jet_leadTrackPt[j]; TLorentzVector jett = get_jetVector(&je); //debug!! je.Et = jett.Et(); jets_all.push_back(je); //all jets after trigger if ((fabs(Jet_eta[j])<Jet_eta_cut) && (Jet_pt[j]>Jet_pt_cut_low) ) {//debug //&& Jet_puId[j]>0 && && (Jet_id[j]>0) ++nJets_InAcc; jets_inAcc.push_back(je); } } //---------------------------------------------- // 3.cut on number of Jets in acceptance region //---------------------------------------------- if(nJets_InAcc>=nJets_cut) ++nCut3; else continue; //---------------------------------------------- // 4. jet sort in CSV + CSV cut on first 3 jets //---------------------------------------------- bool has4bTag = false; int bTag = 0; std::sort (jets_inAcc.begin(), jets_inAcc.end() ); // by csv - defined in declaration , cmp_CSV if(jets_inAcc[1].CSV>CSV_cut){ ++bTag2; bTag = 2; }; if(jets_inAcc[2].CSV>CSV_cut){ ++bTag3; bTag = 3; }; if(jets_inAcc[3].CSV>CSV_cut){ ++bTag4; bTag = 4; }; if(bTag < nJets_CSVcut) continue; //cut on jets sorted in btag ++nCut4; //fill jets vector (in acc sorted by csv): int NJetInAcc = jets_inAcc.size(); for(int l=0; l<NJetInAcc;l++){ //std::cout << jets_inAcc[l].CSV << std::endl; jets_inAcc_P.push_back(get_jetVector(&jets_inAcc[l])); //TLorentz - same order of jet_inAcc!! met.SetPtEtaPhiM(met_pt,met_eta,met_phi,met_mass); } //............. //debug--- move.... to check matching -- to be updated float dR=0; //check matching if MC --- DEBUG!!!!!!!!!! //------------------------- if(isSignal){ // Match first 3 jets with b and fill deltaR //------------ std::vector<TLorentzVector> genB_P_match; bool noJetMatch = false; std::vector<TLorentzVector>::iterator index; for(int l=0; l<3;l++){ float dRFin = deltaRCut; for(std::vector<TLorentzVector>::iterator it = genB_P.begin() ; it != genB_P.end(); ++it){ dR = jets_inAcc_P[l].DeltaR(*it); if(dR<dRFin) { dRFin=dR; index = it; } } if(dRFin!=deltaRCut){ genB_P_match.push_back(*index); genB_P.erase(index); //debug - improve!! if(l==0)h_jet1b_dr->Fill(dRFin); else if(l==1)h_jet2b_dr->Fill(dRFin); else if(l==2)h_jet3b_dr->Fill(dRFin); } else noJetMatch = true; } // Fill deltaR for all the fourth jet and find the 'MC Truth' (jet closest to remaining genB) //------------ float dRFinal = deltaRCut; for(int j=3; j<NJetInAcc; ++j){ dR = jets_inAcc_P[j].DeltaR(genB_P[0]); h_jet4b_drAll->Fill(dR,1./(NJetInAcc-3)); if(dR<dRFinal) { dRFinal=dR; InTrue = j; //indice del jet piu' vicino al partone rimasto } } if(dRFinal==deltaRCut) noJetMatch = true; // debug - removed.... //if(noJetMatch) continue; //skip event if there are no match for all the 4 jets -- debug !!!??? still valid?... h_jet4b_dr->Fill(dRFinal); //fill deltaR for all 4th jets not matched for(int j=3; j<NJetInAcc; ++j){ dR = jets_inAcc_P[j].DeltaR(genB_P[0]); if(j!=InTrue) h_jet4b_drNotMatched->Fill(dR,1./(NJetInAcc-4)); } // fill discriminating variables //------------ for(int j=3; j<NJetInAcc; ++j){ float DpT = jets_inAcc[2].pT - jets_inAcc[j].pT; //debug --- jet has same ordering of jets_P ?.. float DCSV = jets_inAcc[2].CSV - jets_inAcc[j].CSV; float Deta = fabs(jets_inAcc[2].eta) - fabs(jets_inAcc[j].eta); if(j==InTrue){ h_Jet4match_pT->Fill(jets_inAcc[j].pT); h_Jet4match_eta->Fill(jets_inAcc[j].eta); h_Jet4match_CSV->Fill(jets_inAcc[j].CSV); h_Jet4match_DpT3->Fill(DpT); h_Jet4match_DCSV3->Fill(DCSV); h_Jet4match_Deta3->Fill(Deta); } else{ // h_Jet4all_pT->Fill(jet[j].pT); debug // h_Jet4all_eta->Fill(jet[j].eta); // h_Jet4all_CSV->Fill(jet[j].CSV); h_Jet4all_DpT3->Fill(DpT); h_Jet4all_DCSV3->Fill(DCSV); h_Jet4all_Deta3->Fill(Deta); } } }//!isData //debug--- move.... //select 4th jet and match di-jets //----------------------------------------- float mAve; // with RL method //---------------- if(finalIndex == 1){ //read matrix and assign max R float Rmax = 0; for(int j=3; j<NJetInAcc; ++j){ int ipT = jets_inAcc[j].pT*(binPt-1)/300; if(ipT>binPt-1) ipT = binPt-1; int iCSV = jets_inAcc[j].CSV*binCSV; if(iCSV<0) iCSV =0; if(iCSV>(binCSV-1)) iCSV = binCSV-1; int ieta = fabs(jets_inAcc[j].eta*2); // //(binEta-1)/2 jet[j].eta*(binEta-1)/2; // if(ieta>binEta-1) ieta = binEta-1; // if(ieta>binEta-1) ieta = binEta-1; if(ieta<2) ieta = 0; else if(ieta<3) ieta = 1; else if(ieta<4) ieta = 2; else ieta = 3; float thisR = R[ipT][iCSV][ieta]; //if(i<0.5*nEvents+20){ // cout << j << " " << thisR << " " << jets_P[j].DeltaR(genB_P[0]) << endl; // cout << j << " " << jet[j].pT << " " << ipT << " " << iCSV << " " << ieta << endl; //} if(thisR>Rmax) { Rmax = thisR; In=j; } } dR = jets_inAcc_P[In].DeltaR(genB_P[0]); //matched?! h_jet4b_drMatrix->Fill(dR); if(In==InTrue)nRmaxOk++; jet4index = In; mAve = selectBestDiJets(jet4index); //choose best di-jets combination //if(mAve == -1){ ++nCut4b; continue;}; //4th jet CSV<0 h_M_matrix->Fill(mAve); h_HH_mass_matr->Fill(HH_P.M()); } // with MC truth // ---------------------------------- if(isSignal){ jet4index = InTrue; nMCTruth++; //1 truth per event.. mAve = selectBestDiJets(jet4index); //choose best di-jets combination //if(mAve == -1){ ++nCut4b; continue;}; //4th jet CSV<0 h_M_true->Fill(mAve); h_HH_mass_tr->Fill(HH_P.M()); } // with CSV // ---------------------------------- jet4index=3; if(3==InTrue)nCSVOk++; mAve = selectBestDiJets(jet4index); //choose best di-jets combination //if(mAve == -1){ ++nCut4b; continue;}; //4th jet CSV<0 h_M_csv->Fill(mAve); h_HH_mass_csv->Fill(HH_P.M()); // with minMass // ---------------------------------- jet4index=999; //to be implemented.... //now do it with the selected method (repetition!!..) foundHH = true; HHf++; jet4SelectionMethod(finalIndex); //to initialize jet4index selectBestDiJets(jet4index); //to chose best di-jets //if(mAve == -1){ ++nCut4b; continue;}; //4th jet CSV<0 -- not needed now //initialize higgs vectors for(int i=0;i<4;i++) { fJets.push_back(jets_inAcc[fJetsIndex[i]]); if(i<3) fJets_CSV.push_back(jets_inAcc[i]); else fJets_CSV.push_back(jets_inAcc[fJetsIndex[i]]); } //debug - make it better fJet1_CSV = fJets_CSV.at(0); fJet2_CSV = fJets_CSV.at(1); fJet3_CSV = fJets_CSV.at(2); fJet4_CSV = fJets_CSV.at(3); for(int i=0;i<4;i++) fJets_P.push_back(jets_inAcc_P[fJetsIndex[i]]); for(std::vector<hh4b_kinSel::Jet>::iterator it = jets_inAcc.begin()+4 ; it != jets_inAcc.end(); ++it){ //additional jets aJets.push_back(*it); } if(jets_inAcc_P[1].M() != fJets_P[1].M()) nMixJets++; //debug - to check fJets3avgCSV = (fJets_CSV[0].CSV+fJets_CSV[1].CSV+fJets_CSV[2].CSV)/3; fJets3minCSV = std::min({fJets_CSV[0].CSV,fJets_CSV[1].CSV,fJets_CSV[2].CSV}); fJets4avgCSV = (fJets_CSV[0].CSV+fJets_CSV[1].CSV+fJets_CSV[2].CSV+fJets_CSV[3].CSV)/4; Centr = ((fJets_P[0].Pt()/fJets_P[0].E())+(fJets_P[1].Pt()/fJets_P[1].E())+(fJets_P[2].Pt()/fJets_P[2].E())+(fJets_P[3].Pt()/fJets_P[3].E()))/4; //Centrality //angles computation: anglesComputation(); // Fill histos/tree with final variables //------------------------- if (foundHH){ //debug //bool efB1 = false; //bool efB2 = false; //---------------- //for(std::vector<TLorentzVector>::iterator it = fJets_P.begin() ; it != fJets_P.end(); ++it){ //count on deltaR to get efficiency.. /*if(fabs(gen_B1.Eta())<2.5 && gen_B1.Pt()>20 && fabs(gen_B2.Eta())<2.5 && gen_B2.Pt()>20){ if((*it).DeltaR(gen_B1)<0.5 && !efB1){ efB1 = true; effB1++; } if((*it).DeltaR(gen_B2)<0.5 && !efB2){ efB2 = true; effB2++; } h_genBfH1_DR->Fill((*it).DeltaR(gen_B1)); h_genBfH2_DR->Fill((*it).DeltaR(gen_B2)); }*/ //} //fill the Histos fillHistos(); //----------------------------------- // WINDOWS : cut on dijet masses (rectangle) //----------------------------------- /* if(dijetM_cut_low<c_diJet1[Ind].M() && c_diJet1[Ind].M()<dijetM_cut_high){ nCut5a++; if(dijetM_cut_low<c_diJet2[Ind].M() && c_diJet2[Ind].M()<dijetM_cut_high){ nCut5++; // cout << "inWindows " << nCut5 << " " << c_diJet1[Ind].M() << " " << c_diJet2[Ind].M() << endl; h_HH_massInReg->Fill((H1+H2).M()); h_HH_pTInReg->Fill((H1+H2).Pt()); h_H1_H2_massInReg->Fill(H1.M(), H2.M()); // count on deltaR to get efficiency.. if(fabs(gen_B1.Eta())<2.5 && gen_B1.Pt()>20 && fabs(gen_B2.Eta())<2.5 && gen_B2.Pt()>20){ if(fJets[0].DeltaR(gen_B1)<0.5 || fJets[0].DeltaR(gen_B2)<0.5) effBH1_wind++; else if(fJets[1].DeltaR(gen_B1)<0.5 || fJets[1].DeltaR(gen_B2)<0.5) effBH1_wind++; if(fJets[2].DeltaR(gen_B1)<0.5 || fJets[2].DeltaR(gen_B2)<0.5) effBH2_wind++; else if(fJets[3].DeltaR(gen_B1)<0.5 || fJets[3].DeltaR(gen_B2)<0.5) effBH2_wind++; } } } // windows*/ //ELIPTICAL WINDOWS -- TO BE IMPROVED if(withinElipse(H1_P.M(), H2_P.M())){ nCut5b++; h_H1_H2_massInReg2->Fill(H1_P.M(), H2_P.M()); } else h_H1_H2_massInReg3->Fill(H1_P.M(), H2_P.M()); // windows outtree->Fill(); //if(has4bTag) outtree4b->Fill(); non serve per ora }//if FOUND } // sample splitting } // Event loop // Some output (shell & log) -- debug - put it into a function... if(maxEvents!=0) logfilename = plotsFld+"log_"+sample+"_"+opt+"_"+std::to_string(maxEvents)+".dat"; else logfilename = plotsFld+"log_"+sample+"_"+opt+".dat"; // printOutput(logfilename, isData); // on shell //----------- // std::cout<<std::setprecision(2); // std::cout<<std::fixed; std::cout<< sample << " " << opt << " 4thJet:" << jet4SelectionMethod(finalIndex) << std::endl; std::cout<<"0. Input = "<< nCut0 << std::endl; std::cout<<"1. Trigger = "<< nCut1 << " , " <<(float)nCut2/nCut0*100<<"% " <<(float)nCut1/nCut0*100<<"%"<<std::endl; std::cout<<"2. 4 Jets in Acc = "<< nCut3 << " , " <<(float)nCut3/nCut2*100<<"% " <<(float)nCut3/nCut0*100<<"%"<<std::endl; std::cout<<"2JetsCSV "<< bTag2 << " " <<(float)bTag2/nCut3*100<< " " <<(float)bTag2/nCut0*100<<std::endl; std::cout<<"3JetsCSV "<< bTag3 << " " <<(float)bTag3/bTag2*100<< " " <<(float)bTag3/nCut0*100<<std::endl; std::cout<<"4JetsCSV "<< bTag4 << " " <<(float)bTag4/nCut3*100<< " " <<(float)bTag4/nCut0*100<<std::endl; std::cout<<"3. JetsCSVCut "<< nCut4 << " " <<(float)nCut4/nCut3*100<< " " <<(float)nCut4/nCut0*100<<std::endl; std::cout<<"HHfound = "<< HHf << " , " <<(float)HHf/nCut4*100<<"% " <<(float)HHf/nCut0*100<<"%"<<std::endl; // std::cout<<"Number of events with only diJet1 in mass windows = "<< (nCut5a-nCut5) << " , " << (float)(nCut5a-nCut5)/HHf*100<<"% " << (float)(nCut5a-nCut5)/nCut0*100<<"%"<<std::endl; // std::cout<<"Number of events in mass windows = "<< nCut5 << " , " <<(float)nCut5/(nCut5a-nCut5)*100<<"% " <<(float)nCut5/nCut0*100<<"%"<<std::endl; std::cout<<"In SR (elipse) = "<< nCut5b << " , " <<(float)nCut5b/HHf*100<<"% " <<(float)nCut5b/nCut0*100<<"%"<<std::endl; std::cout<<std::endl; std::cout<<"# event with 'mixed' jets = " << nMixJets << std::endl; std::cout << "# error fJets: " << errfJets << std::endl << std::endl; if(isSignal){ std::cout << "'ACCEPTANCE' (Ntrue/Nevents): " << (float)nMCTruth/nEvents*100 << std::endl; std::cout << "N true jets " << Ntr[0] << std::endl; std::cout << "nMCTruth " << nMCTruth << std::endl; std::cout << std::endl; } /* std::cout<<"eff B1 for HHfound = "<<effB1<< " " << (float)effB1/HHf*100 <<"%"<<std::endl; std::cout<<"eff B2 for HHfound = "<<effB2<< " " << (float)effB2/HHf*100 <<"%"<<std::endl; std::cout<<"eff Bh1 in windows = "<<effBH1_wind<< " " << (float)effBH1_wind/nCut5*100 <<"%"<<std::endl; std::cout<<"eff Bh2 in windows = "<<effBH2_wind<< " " << (float)effBH2_wind/nCut5*100 <<"%"<<std::endl;*/ // on file //----------- std::ofstream ofs (logfilename, std::ofstream::out); //ofs<<setprecision(2); //ofs<<fixed; ofs<< sample << " " << opt << " 4thJet:" << jet4SelectionMethod(finalIndex) << std::endl; ofs<<"Input "<< nCut0 << std::endl; ofs<<"Trigger "<< nCut1 << " " <<(float)nCut2/nCut0*100<< " " <<(float)nCut1/nCut0*100<<std::endl; ofs<<"4JetsInAcc "<< nCut3 << " " <<(float)nCut3/nCut2*100<< " " <<(float)nCut3/nCut0*100<<std::endl; ofs<<"2JetsCSV "<< bTag2 << " " <<(float)bTag2/nCut3*100<< " " <<(float)bTag2/nCut0*100<<std::endl; ofs<<"3JetsCSV "<< bTag3 << " " <<(float)bTag3/bTag2*100<< " " <<(float)bTag3/nCut0*100<<std::endl; ofs<<"4JetsCSV "<< bTag4 << " " <<(float)bTag4/nCut3*100<< " " <<(float)bTag4/nCut0*100<<std::endl; ofs<<"JetsCSVCut "<< nCut4 << " " <<(float)nCut4/nCut3*100<< " " <<(float)nCut4/nCut0*100<<std::endl; ofs<<"HH found "<< HHf << " " <<(float)HHf/nCut4*100<< " " <<(float)HHf/nCut0*100<<std::endl; ofs<<"In SR (elipse) "<< nCut5b << " " <<(float)nCut5b/HHf*100<< " " <<(float)nCut5b/nCut0*100<<std::endl; ofs<<std::endl; if(isSignal){ ofs << "'ACCEPTANCE' (Ntrue/Nevents): " << (float)nMCTruth/nEvents*100 << std::endl; ofs << "N true jets " << Ntr[0] <<std::endl; ofs << "nMCTruth " << nMCTruth << std::endl; ofs << std::endl; } ofs.close(); //write tree and close outtree->Write(); //outtree4b->Write(); outfile->Close(); //create Hist file and write histos if(maxEvents!=0){ histfilename = plotsFld+"Histograms_"+sample+"_"+opt+"_"+std::to_string(maxEvents)+".root"; } else { histfilename = plotsFld+"Histograms_"+sample+"_"+opt+".root"; } writeHistos(histfilename); //------------ std::cout<<"Wrote output files: "<<std::endl; std::cout<<histfilename<<std::endl; std::cout<<logfilename<<std::endl; std::cout<<outfilename<<std::endl <<std::endl; } //----------- hh4b_kinSel::~hh4b_kinSel(){ } //--------------- /* bool hh4b_kinSel::readFiles(TFile * f){ std::string fname, sam_; bool matches = false; if(isData) fname = step0Fld+"tree_Step0_"+dataframVer+"_"+sample+".root"; else fname = step0Fld+"tree_Step0_"+MCframVer+"_"+sample+".root"; f = TFile::Open(fname.c_str()); if(!f) return false; f->cd(); } */ //--------------- float hh4b_kinSel::selectBestDiJets(int k = 0){ //choose best di-jets combination, compute avg Higgs mass and initialize Higgs vector // if(jets_inAcc[k].CSV<=0.) return -1.; //check to avoid underflow in 4th jet. fJetsIndex.clear(); //new at every call... float M12=0,M13=0,M14=0, M23=0, M24=0, M34=0; M12 = (jets_inAcc_P[0] + jets_inAcc_P[1]).M(); M13 = (jets_inAcc_P[0] + jets_inAcc_P[2]).M(); M14 = (jets_inAcc_P[0] + jets_inAcc_P[k]).M(); M23 = (jets_inAcc_P[1] + jets_inAcc_P[2]).M(); M24 = (jets_inAcc_P[1] + jets_inAcc_P[k]).M(); M34 = (jets_inAcc_P[2] + jets_inAcc_P[k]).M(); float DM1, DM2, DM3; float Higgs_mAve = 9999; DM1= fabs(M12 - M34); DM2= fabs(M13 - M24); DM3= fabs(M14 - M23); if(DM1 < DM2 && DM1<DM3) { H1_P = jets_inAcc_P[0]+jets_inAcc_P[1]; H2_P = jets_inAcc_P[2]+jets_inAcc_P[k]; fJetsIndex.push_back(0); fJetsIndex.push_back(1); fJetsIndex.push_back(2); fJetsIndex.push_back(k); Higgs_mAve=(M12+M34)/2.; } if(DM2 < DM1 && DM2<DM3) { H1_P = jets_inAcc_P[0]+jets_inAcc_P[2]; H2_P = jets_inAcc_P[1]+jets_inAcc_P[k]; fJetsIndex.push_back(0); fJetsIndex.push_back(2); fJetsIndex.push_back(1); fJetsIndex.push_back(k); Higgs_mAve=(M13+M24)/2.; } if(DM3 < DM1 && DM3<DM2) { H1_P = jets_inAcc_P[0]+jets_inAcc_P[k]; H2_P = jets_inAcc_P[1]+jets_inAcc_P[2]; fJetsIndex.push_back(0); fJetsIndex.push_back(k); fJetsIndex.push_back(1); fJetsIndex.push_back(2); Higgs_mAve=(M14+M23)/2.; } //create diJet H1 = get_diJet(&H1_P); H2 = get_diJet(&H2_P); //create diHiggs HH_P = H1_P+H2_P; HH = get_diJet(&HH_P); return Higgs_mAve; } //---------------- bool hh4b_kinSel::readMatrix(){ //read matrix and calculate R - for 4th jet selection for(int ipT=0; ipT<binPt; ipT++){ for(int iCSV=0; iCSV<binCSV; iCSV++){ for(int ieta=0; ieta<binEta; ieta++){ nM[ipT][iCSV][ieta] = 0; nA[ipT][iCSV][ieta] = 0; } } } std::ifstream inmatrix; std::string fn = utilsFld+matrixFld+"nMnA_"+MCsample_RL+"_"+opt+".asc"; inmatrix.open(fn); if (inmatrix) { int i1, i2, i3; float sumnA=0, sumnM=0; for(int ipT=0; ipT<binPt; ipT++){ for(int iCSV=0; iCSV<binCSV; iCSV++){ for(int ieta=0; ieta<binEta; ieta++){ inmatrix >> i1 >> i2 >> i3 >> nM[ipT][iCSV][ieta] >> nA[ipT][iCSV][ieta]; if(i1!=ipT ||i2!=iCSV ||i3!=ieta) std::cout << "WARNING: matrix mismatch" << std::endl; if(nA[ipT][iCSV][ieta]>0) R[ipT][iCSV][ieta] = nM[ipT][iCSV][ieta]/nA[ipT][iCSV][ieta]; else R[ipT][iCSV][ieta] = 1; //cout << nM[ipT][iCSV][ieta] << " " << nA[ipT][iCSV][ieta] <<endl; sumnM+=nM[ipT][iCSV][ieta]; sumnA+=nA[ipT][iCSV][ieta]; if(nM[ipT][iCSV][ieta]!=0 || nM[ipT][iCSV][ieta]!=0) { std::cout << ipT << " " << iCSV << " " << ieta << " " << R[ipT][iCSV][ieta] << " +- " << R[ipT][iCSV][ieta]*sqrt(1/nM[ipT][iCSV][ieta]+ 1/nA[ipT][iCSV][ieta]) <<std::endl; } else std::cout << "nM or nA null" <<std::endl; } } } Rave=sumnM/sumnA; inmatrix.close(); return true; } else { std::cout << "WARNING: Unable to open matrix file " << fn << std::endl; return false; } } //---------------------- std::string hh4b_kinSel::jet4SelectionMethod(int index){ std::string method; if(index==0) { jet4index = InTrue; method = "MCTruth"; } else if(index==1) { jet4index = In; method = "RL"; } else if(index==2) { jet4index = 3; method = "CSV"; } else if(index==3) { jet4index = 99; //debug method = "minMass"; } return method; } //--------------- void hh4b_kinSel::anglesComputation(){ H1.CosThSt = computeCosThetaStar(H1_P,HH_P); H2.CosThSt = computeCosThetaStar(H2_P,HH_P); H1.dR = fJets_P[0].DeltaR(fJets_P[1]); H2.dR = fJets_P[2].DeltaR(fJets_P[3]); H1.dPhi = fJets_P[0].DeltaPhi(fJets_P[1]); H2.dPhi = fJets_P[2].DeltaPhi(fJets_P[3]); H1.dEta = fJets_P[0].Eta() - fJets_P[1].Eta(); H2.dEta = fJets_P[2].Eta() - fJets_P[3].Eta(); H1.dPhi_abs = abs(H1.dPhi); H2.dPhi_abs = abs(H2.dPhi); H1.dEta_abs = abs(H1.dEta); H2.dEta_abs = abs(H2.dEta); HH.dR = H1_P.DeltaR(H2_P); HH.dPhi = H1_P.DeltaPhi(H2_P); HH.dEta = H1_P.Eta() - H2_P.Eta(); HH.dPhi_abs = abs(HH.dPhi); HH.dEta_abs = abs(HH.dEta); } //--------------- //Retrieve variables void hh4b_kinSel::setBranches(TTree* tree){ tree->SetBranchAddress("nprimaryVertices", &(nPV)); tree->SetBranchAddress("Vtype", &(Vtype_)); tree->SetBranchAddress("evt",&evt); tree->SetBranchAddress("run",&run); // tree->SetBranchAddress("lumi",&lumi); tree->SetBranchAddress("nJet",&nJet); tree->SetBranchAddress("Jet_id",&Jet_id); tree->SetBranchAddress("Jet_puId",&Jet_puId); tree->SetBranchAddress("Jet_btagCSV",&Jet_btagCSV); tree->SetBranchAddress("Jet_pt",&Jet_pt); tree->SetBranchAddress("Jet_eta",&Jet_eta); tree->SetBranchAddress("Jet_phi",&Jet_phi); tree->SetBranchAddress("Jet_mass",&Jet_mass); tree->SetBranchAddress("Jet_chMult",&Jet_chMult); tree->SetBranchAddress("Jet_leadTrackPt",&Jet_leadTrackPt); tree->SetBranchAddress("met_pt",&met_pt); tree->SetBranchAddress("met_eta",&met_eta); tree->SetBranchAddress("met_phi",&met_phi); tree->SetBranchAddress("met_mass",&met_mass); if(isData){ tree->SetBranchAddress("HLT_BIT_HLT_QuadJet45_TripleBTagCSV0p67_v",&HLT_BIT_QuadTriple); tree->SetBranchAddress("HLT_BIT_HLT_QuadJet45_DoubleBTagCSV0p67_v",&HLT_BIT_QuadDouble); tree->SetBranchAddress("HLT_BIT_HLT_DoubleJet90_Double30_TripleBTagCSV0p67_v",&HLT_BIT_DoubleTriple); tree->SetBranchAddress("HLT_BIT_HLT_DoubleJet90_Double30_DoubleBTagCSV0p67_v",&HLT_BIT_DoubleDouble); tree->SetBranchAddress("HLT_HH4bAll",&HLT_HH4bAll); } else { tree->SetBranchAddress("puWeight", &(weightPU)); tree->SetBranchAddress("HLT_BIT_HLT_QuadJet45_TripleCSV0p5_v",&HLT_BIT_QuadTriple); tree->SetBranchAddress("HLT_BIT_HLT_QuadJet45_DoubleCSV0p5_v",&HLT_BIT_QuadDouble); tree->SetBranchAddress("HLT_BIT_HLT_DoubleJet90_Double30_TripleCSV0p5_v",&HLT_BIT_DoubleTriple); tree->SetBranchAddress("HLT_BIT_HLT_DoubleJet90_Double30_DoubleCSV0p5_v",&HLT_BIT_DoubleDouble); tree->SetBranchAddress("HLT_HH4bAll",&HLT_HH4bAll); if(isSignal){ //debug! tree->SetBranchAddress("nGenHiggsBoson",&nGenH); tree->SetBranchAddress("GenHiggsBoson_pt",&GenH_pt); tree->SetBranchAddress("GenHiggsBoson_mass",&GenH_mass); tree->SetBranchAddress("GenHiggsBoson_eta",&GenH_eta); tree->SetBranchAddress("GenHiggsBoson_phi",&GenH_phi); tree->SetBranchAddress("GenHiggsBoson_status",&GenH_status); tree->SetBranchAddress("nGenBQuarkFromH",&nGenBfH); tree->SetBranchAddress("GenBQuarkFromH_pdgId",&GenBfH_pdgId); tree->SetBranchAddress("GenBQuarkFromH_pt",&GenBfH_pt); tree->SetBranchAddress("GenBQuarkFromH_eta",&GenBfH_eta); tree->SetBranchAddress("GenBQuarkFromH_phi",&GenBfH_phi); tree->SetBranchAddress("GenBQuarkFromH_mass",&GenBfH_mass); tree->SetBranchAddress("GenBQuarkFromH_charge",&GenBfH_charge); tree->SetBranchAddress("GenBQuarkFromH_status",&GenBfH_status); tree->SetBranchAddress("nGenBQuarkFromHafterISR",&nGenBfHafterISR); tree->SetBranchAddress("GenBQuarkFromHafterISR_pdgId",&GenBfHafterISR_pdgId); tree->SetBranchAddress("GenBQuarkFromHafterISR_pt",&GenBfHafterISR_pt); tree->SetBranchAddress("GenBQuarkFromHafterISR_eta",&GenBfHafterISR_eta); tree->SetBranchAddress("GenBQuarkFromHafterISR_phi",&GenBfHafterISR_phi); tree->SetBranchAddress("GenBQuarkFromHafterISR_mass",&GenBfHafterISR_mass); } } } //--------------- void hh4b_kinSel::createTree(TTree* outtree){ //copy Step0 tree -- DEBUG --> not good .. loop needed to fill all jet info... outtree->Branch("nprimaryVertices", &(nPV)); outtree->Branch("Vtype", &(Vtype_)); outtree->Branch("evt",&evt); outtree->Branch("run",&run); outtree->Branch("nJet",&nJet); outtree->Branch("Jet_id",Jet_id); outtree->Branch("Jet_puId",Jet_puId); outtree->Branch("Jet_btagCSV",Jet_btagCSV); outtree->Branch("Jet_pt",Jet_pt); outtree->Branch("Jet_eta",Jet_eta); outtree->Branch("Jet_phi",Jet_phi); outtree->Branch("Jet_mass",Jet_mass); outtree->Branch("Jet_chMult",Jet_chMult); outtree->Branch("Jet_leadTrackPt",Jet_leadTrackPt); outtree->Branch("met_pt",met_pt); outtree->Branch("met_eta",met_eta); outtree->Branch("met_phi",met_phi); outtree->Branch("met_mass",met_mass); if(isData){ outtree->Branch("HLT_QuadJet45_TripleBTagCSV0p67",&HLT_BIT_QuadTriple); outtree->Branch("HLT_QuadJet45_DoubleBTagCSV0p67",&HLT_BIT_QuadDouble); outtree->Branch("HLT_DoubleJet90_Double30_TripleBTagCSV0p67",&HLT_BIT_DoubleTriple); outtree->Branch("HLT_DoubleJet90_Double30_DoubleBTagCSV0p67",&HLT_BIT_DoubleDouble); outtree->Branch("HH4bAll",&HLT_HH4bAll); } else { outtree->Branch("puWeight", &(weightPU)); outtree->Branch("HLT_QuadJet45_TripleCSV0p5",&HLT_BIT_QuadTriple); outtree->Branch("HLT_QuadJet45_DoubleCSV0p5",&HLT_BIT_QuadDouble); outtree->Branch("HLT_DoubleJet90_Double30_TripleCSV0p5",&HLT_BIT_DoubleTriple); outtree->Branch("HLT_DoubleJet90_Double30_DoubleCSV0p5",&HLT_BIT_DoubleDouble); outtree->Branch("HH4bAll",&HLT_HH4bAll); } //--------- //new variables outtree->Branch("fJet1_mass",&fJet1_CSV.mass); outtree->Branch("fJet1_pT",&fJet1_CSV.pT); outtree->Branch("fJet1_eta",&fJet1_CSV.eta); outtree->Branch("fJet1_phi",&fJet1_CSV.phi); outtree->Branch("fJet1_CSV",&fJet1_CSV.CSV); outtree->Branch("fJet1_Et",&fJet1_CSV.Et); outtree->Branch("fJet1_chMult",&fJet1_CSV.chMult); outtree->Branch("fJet1_leadTrackPt",&fJet1_CSV.leadTrackPt); outtree->Branch("fJet2_mass",&fJet2_CSV.mass); outtree->Branch("fJet2_pT",&fJet2_CSV.pT); outtree->Branch("fJet2_eta",&fJet2_CSV.eta); outtree->Branch("fJet2_phi",&fJet2_CSV.phi); outtree->Branch("fJet2_CSV",&fJet2_CSV.CSV); outtree->Branch("fJet2_Et",&fJet2_CSV.Et); outtree->Branch("fJet2_chMult",&fJet2_CSV.chMult); outtree->Branch("fJet2_leadTrackPt",&fJet2_CSV.leadTrackPt); outtree->Branch("fJet3_mass",&fJet3_CSV.mass); outtree->Branch("fJet3_pT",&fJet3_CSV.pT); outtree->Branch("fJet3_eta",&fJet3_CSV.eta); outtree->Branch("fJet3_phi",&fJet3_CSV.phi); outtree->Branch("fJet3_CSV",&fJet3_CSV.CSV); outtree->Branch("fJet3_Et",&fJet3_CSV.Et); outtree->Branch("fJet3_chMult",&fJet3_CSV.chMult); outtree->Branch("fJet3_leadTrackPt",&fJet3_CSV.leadTrackPt); outtree->Branch("fJet4_mass",&fJet4_CSV.mass); outtree->Branch("fJet4_pT",&fJet4_CSV.pT); outtree->Branch("fJet4_eta",&fJet4_CSV.eta); outtree->Branch("fJet4_phi",&fJet4_CSV.phi); outtree->Branch("fJet4_CSV",&fJet4_CSV.CSV); outtree->Branch("fJet4_Et",&fJet4_CSV.Et); outtree->Branch("fJet4_chMult",&fJet4_CSV.chMult); outtree->Branch("fJet4_leadTrackPt",&fJet4_CSV.leadTrackPt); outtree->Branch("fJets3avgCSV",&fJets3avgCSV); outtree->Branch("fJets3minCSV",&fJets3minCSV); outtree->Branch("fJets4avgCSV",&fJets4avgCSV); outtree->Branch("Centr",&Centr); //outtree->Branch("H1","diJet",&H1); outtree->Branch("H1_mass",&H1.mass); outtree->Branch("H1_pT",&H1.pT); outtree->Branch("H1_eta",&H1.eta); outtree->Branch("H1_phi",&H1.phi); outtree->Branch("H1_CosThSt",&H1.CosThSt); outtree->Branch("H1_dR",&H1.dR); outtree->Branch("H1_dPhi",&H1.dPhi); outtree->Branch("H1_dEta",&H1.dEta); outtree->Branch("H1_dPhi_abs",&H1.dPhi_abs); outtree->Branch("H1_dEta_abs",&H1.dEta_abs); outtree->Branch("H2_mass",&H2.mass); outtree->Branch("H2_pT",&H2.pT); outtree->Branch("H2_eta",&H2.eta); outtree->Branch("H2_phi",&H2.phi); outtree->Branch("H2_CosThSt",&H2.CosThSt); outtree->Branch("H2_dR",&H2.dR); outtree->Branch("H2_dPhi",&H2.dPhi); outtree->Branch("H2_dEta",&H2.dEta); outtree->Branch("H2_dPhi_abs",&H2.dPhi_abs); outtree->Branch("H2_dEta_abs",&H2.dEta_abs); outtree->Branch("HH_mass",&HH.mass); outtree->Branch("HH_pT",&HH.pT); outtree->Branch("HH_eta",&HH.eta); outtree->Branch("HH_phi",&HH.phi); outtree->Branch("HH_CosThSt",&HH.CosThSt); outtree->Branch("HH_dR",&HH.dR); outtree->Branch("HH_dPhi",&HH.dPhi); outtree->Branch("HH_dEta",&HH.dEta); outtree->Branch("HH_dPhi_abs",&HH.dPhi_abs); outtree->Branch("HH_dEta_abs",&HH.dEta_abs); } //--------------- void hh4b_kinSel::fillHistos(){ for(std::vector<hh4b_kinSel::Jet>::iterator it = jets_all.begin() ; it != jets_all.end(); ++it){ //additional jets h_JetsAll_pT->Fill((*it).pT); h_JetsAll_mass->Fill((*it).mass); h_JetsAll_eta->Fill((*it).eta); h_JetsAll_CSV->Fill((*it).CSV); h_JetsAll_phi->Fill((*it).phi); h_JetsAll_Et->Fill((*it).Et); h_JetsAll_chMult->Fill((*it).chMult); h_JetsAll_leadTrackPt->Fill((*it).leadTrackPt); } h_nJetsAll->Fill(jets_all.size()); for(std::vector<hh4b_kinSel::Jet>::iterator it = jets_inAcc.begin() ; it != jets_inAcc.end(); ++it){ //additional jets h_JetsAcc_pT->Fill((*it).pT); h_JetsAcc_eta->Fill((*it).eta); h_JetsAcc_mass->Fill((*it).mass); h_JetsAcc_CSV->Fill((*it).CSV); h_JetsAcc_phi->Fill((*it).phi); h_JetsAcc_Et->Fill((*it).Et); h_JetsAcc_chMult->Fill((*it).chMult); h_JetsAcc_leadTrackPt->Fill((*it).leadTrackPt); } h_nJetsAcc->Fill(jets_inAcc.size()); for(std::vector<hh4b_kinSel::Jet>::iterator it = fJets.begin() ; it != fJets.end(); ++it) { //4 final jets h_fJets_pT->Fill((*it).pT); h_fJets_eta->Fill((*it).eta); h_fJets_mass->Fill((*it).mass); h_fJets_CSV->Fill((*it).CSV); h_fJets_phi->Fill((*it).phi); h_fJets_Et->Fill((*it).Et); h_fJets_chMult->Fill((*it).chMult); h_fJets_leadTrackPt->Fill((*it).leadTrackPt); } h_fJets_Centr->Fill(Centr); //sum over 4 jets h_nfJets->Fill(fJets.size()); for(std::vector<hh4b_kinSel::Jet>::iterator it = aJets.begin() ; it != aJets.end(); ++it){ //additional jets h_aJets_pT->Fill((*it).pT); h_aJets_eta->Fill((*it).eta); h_aJets_mass->Fill((*it).mass); h_aJets_CSV->Fill((*it).CSV); h_aJets_phi->Fill((*it).phi); h_aJets_Et->Fill((*it).Et); h_aJets_chMult->Fill((*it).chMult); h_aJets_leadTrackPt->Fill((*it).leadTrackPt); } h_naJets->Fill(aJets.size()); //final jets sorted in CSV --- h_fJet1_mass->Fill(fJets_CSV[0].mass); h_fJet2_mass->Fill(fJets_CSV[1].mass); h_fJet3_mass->Fill(fJets_CSV[2].mass); h_fJet4_mass->Fill(fJets_CSV[3].mass); h_fJet1_pT->Fill(fJets_CSV[0].pT); h_fJet2_pT->Fill(fJets_CSV[1].pT); h_fJet3_pT->Fill(fJets_CSV[2].pT); h_fJet4_pT->Fill(fJets_CSV[3].pT); h_fJet1_Eta->Fill(fJets_CSV[0].eta); h_fJet2_Eta->Fill(fJets_CSV[1].eta); h_fJet3_Eta->Fill(fJets_CSV[2].eta); h_fJet4_Eta->Fill(fJets_CSV[3].eta); h_fJet1_CSV->Fill(fJets_CSV[0].CSV); h_fJet2_CSV->Fill(fJets_CSV[1].CSV); h_fJet3_CSV->Fill(fJets_CSV[2].CSV); h_fJet4_CSV->Fill(fJets_CSV[3].CSV); h_fJet1_phi->Fill(fJets_CSV[0].phi); h_fJet2_phi->Fill(fJets_CSV[1].phi); h_fJet3_phi->Fill(fJets_CSV[2].phi); h_fJet4_phi->Fill(fJets_CSV[3].phi); h_fJet1_Et->Fill(fJets_CSV[0].Et); h_fJet2_Et->Fill(fJets_CSV[1].Et); h_fJet3_Et->Fill(fJets_CSV[2].Et); h_fJet4_Et->Fill(fJets_CSV[3].Et); h_fJet1_chMult->Fill(fJets_CSV[0].chMult); h_fJet2_chMult->Fill(fJets_CSV[1].chMult); h_fJet3_chMult->Fill(fJets_CSV[2].chMult); h_fJet4_chMult->Fill(fJets_CSV[3].chMult); h_fJet1_leadTrackPt->Fill(fJets_CSV[0].leadTrackPt); h_fJet2_leadTrackPt->Fill(fJets_CSV[1].leadTrackPt); h_fJet3_leadTrackPt->Fill(fJets_CSV[2].leadTrackPt); h_fJet4_leadTrackPt->Fill(fJets_CSV[3].leadTrackPt); h_fJets3avg_CSV->Fill(fJets3avgCSV); h_fJets3min_CSV->Fill(fJets3minCSV); h_fJets4avg_CSV->Fill(fJets4avgCSV); h_H1_mass->Fill(H1.mass); h_H1_pT->Fill(H1.pT); h_H1_Eta->Fill(H1.eta); h_H1_Phi->Fill(H1.phi); h_H1_CosThSt->Fill(fabs(H1.CosThSt)); h_H1_deltaR->Fill(H1.dR); h_H1_deltaPhi->Fill(H1.dPhi); h_H1_deltaEta->Fill(H1.dEta); h_H1_deltaPhiVSpT->Fill(H1.dPhi,H1.pT); h_H2_mass->Fill(H2.mass); h_H2_pT->Fill(H2.pT); h_H2_Eta->Fill(H2.eta); h_H2_Phi->Fill(H2.phi); h_H2_CosThSt->Fill(fabs(H2.CosThSt)); h_H2_deltaR->Fill(H2.dR); h_H2_deltaPhi->Fill(H2.dPhi); h_H2_deltaEta->Fill(H2.dEta); h_H2_deltaPhiVSpT->Fill(H2.dPhi,H2.pT); h_H_mass->Fill(H1.mass); h_H_mass->Fill(H2.mass); h_H_pT->Fill(H1.pT); h_H_pT->Fill(H2.mass); h_H_Eta->Fill(H1.eta); h_H_Eta->Fill(H2.eta); h_H_Phi->Fill(H1.phi); h_H_Phi->Fill(H2.phi); h_H_CosThSt->Fill(fabs(H1.CosThSt)); h_H_CosThSt->Fill(fabs(H2.CosThSt)); h_HH_mass->Fill(HH.mass); h_HH_pT->Fill(HH.pT); h_HH_Eta->Fill(HH.eta); h_HH_Phi->Fill(HH.phi); h_H1_H2_mass->Fill(H1.mass, H2.mass); //leading H first h_HH_deltaR->Fill(HH.dR); h_HH_deltaPhi->Fill(HH.dPhi); h_HH_deltaEta->Fill(HH.dEta); //int region=withinRegion(H1_P.mass(), H2_P.mass(), 17.5, 37.5, 125, 125); h_MET->Fill(met.E()); h_Cuts->Fill(1,nCut0); h_Cuts->Fill(3,nCut1); //h_Cuts->Fill(5,nCut2); h_Cuts->Fill(5,nCut3); h_Cuts->Fill(7,nCut4); //h_Cuts->Fill(11,nCut4b); h_Cuts->Fill(9,HHf); h_Cuts->Fill(11,nCut5b); // h_Cuts->Fill(17,nCut5); } //-------------- void hh4b_kinSel::writeHistos(std::string histfilename){ TFile *tFile=new TFile(histfilename.c_str(), "RECREATE"); h_nJets->Write(); h_nJets_InAcc->Write(); h_nPV->Write(); //h_nPV_weighted->Write(); //h_HLT_HH4b->Write(); h_nJetsAll->Write(); h_JetsAll_mass->Write(); h_JetsAll_pT->Write(); h_JetsAll_eta->Write(); h_JetsAll_CSV->Write(); h_JetsAll_phi->Write(); h_JetsAll_Et->Write(); h_JetsAll_chMult->Write(); h_JetsAll_leadTrackPt->Write(); h_nJetsAcc->Write(); h_JetsAcc_mass->Write(); h_JetsAcc_pT->Write(); h_JetsAcc_eta->Write(); h_JetsAcc_CSV->Write(); h_JetsAcc_phi->Write(); h_JetsAcc_Et->Write(); h_JetsAcc_chMult->Write(); h_JetsAcc_leadTrackPt->Write(); h_nfJets->Write(); h_fJets_mass->Write(); h_fJets_pT->Write(); h_fJets_eta->Write(); h_fJets_CSV->Write(); h_fJets_phi->Write(); h_fJets_Et->Write(); h_fJets_chMult->Write(); h_fJets_leadTrackPt->Write(); h_fJets_Centr->Write(); h_naJets->Write(); h_aJets_mass->Write(); h_aJets_pT->Write(); h_aJets_eta->Write(); h_aJets_CSV->Write(); h_aJets_phi->Write(); h_aJets_Et->Write(); h_aJets_chMult->Write(); h_aJets_leadTrackPt->Write(); h_fJet1_mass->Write(); h_fJet2_mass->Write(); h_fJet3_mass->Write(); h_fJet4_mass->Write(); h_fJet1_pT->Write(); h_fJet2_pT->Write(); h_fJet3_pT->Write(); h_fJet4_pT->Write(); h_fJet1_Eta->Write(); h_fJet2_Eta->Write(); h_fJet3_Eta->Write(); h_fJet4_Eta->Write(); h_fJet1_CSV->Write(); h_fJet2_CSV->Write(); h_fJet3_CSV->Write(); h_fJet4_CSV->Write(); h_fJet1_phi->Write(); h_fJet2_phi->Write(); h_fJet3_phi->Write(); h_fJet4_phi->Write(); h_fJet1_Et->Write(); h_fJet2_Et->Write(); h_fJet3_Et->Write(); h_fJet4_Et->Write(); h_fJet1_chMult->Write(); h_fJet2_chMult->Write(); h_fJet3_chMult->Write(); h_fJet4_chMult->Write(); h_fJet1_leadTrackPt->Write(); h_fJet2_leadTrackPt->Write(); h_fJet3_leadTrackPt->Write(); h_fJet4_leadTrackPt->Write(); h_fJets3avg_CSV->Write(); h_fJets3min_CSV->Write(); h_fJets4avg_CSV->Write(); h_H_mass->Write(); h_H_pT->Write(); h_H_Eta->Write(); h_H_Phi->Write(); h_H_CosThSt->Write(); h_H1_mass->Write(); h_H1_pT->Write(); h_H1_Eta->Write(); h_H1_Phi->Write(); h_H1_CosThSt->Write(); h_H1_deltaR->Write(); h_H1_deltaPhi->Write(); h_H1_deltaEta->Write(); h_H1_deltaPhiVSpT->Write(); h_H2_mass->Write(); h_H2_pT->Write(); h_H2_Eta->Write(); h_H2_Phi->Write(); h_H2_CosThSt->Write(); h_H2_deltaR->Write(); h_H2_deltaPhi->Write(); h_H2_deltaEta->Write(); h_H2_deltaPhiVSpT->Write(); h_HH_mass->Write(); h_HH_pT->Write(); h_HH_Eta->Write(); h_HH_Phi->Write(); h_HH_deltaR->Write(); h_HH_deltaPhi->Write(); h_HH_deltaEta->Write(); h_H1_H2_mass->Write(); h_HH_massInReg->Write(); h_HH_pTInReg->Write(); h_H1_H2_massInReg->Write(); h_H1_H2_massInReg2->Write(); h_H1_H2_massInReg3->Write(); h_MET->Write(); h_Cuts->Write(); if(isSignal){ h_jet1b_dr->Write(); h_jet2b_dr->Write(); h_jet3b_dr->Write(); h_jet4b_dr->Write(); h_nGenH->Write(); h_genH_pT->Write(); h_genH_mass->Write(); h_genHH_mass->Write(); h_genH1_mass->Write(); h_genH2_mass->Write(); h_genB1Jets_DR->Write(); h_genBfH1_DR->Write(); h_genBfH2_DR->Write(); } tFile->Write(); tFile->Close(); } void hh4b_kinSel::printOutput(std::string logfilename, bool isData){ //improve... } //get_jetVector --> get TLorentzVector from Jet TLorentzVector hh4b_kinSel::get_jetVector(Jet* jj){ TLorentzVector jetv; jetv.SetPtEtaPhiM(jj->pT,jj->eta,jj->phi,jj->mass); return jetv; } //cmp_CSV --> Jets sorting by CSV ---DEBUG!!!! //bool hh4b_kinSel::cmp_CSV(const Jet& jet1, const Jet& jet2){ //return jet1.CSV > jet2.CSV; //} /*int hh4b_kinSel::dokinSel(std::string sample, bool isData, std::string opt, int finalIndex, int maxEvents , std::string MCsample_RL) { cout << "starting kin selection..." << endl; hh4b_kinSel(sample, isData, opt, finalIndex, maxEvents , MCsample_RL); return 0; }*/ void hh4b_kinSel::setSumW2(){ //debug -- better way to do it? h_Cuts->Sumw2(); h_nJets->Sumw2(); h_nJets_InAcc->Sumw2(); h_MET->Sumw2(); h_nJetsAll->Sumw2(); h_JetsAll_mass->Sumw2(); h_JetsAll_pT->Sumw2(); h_JetsAll_eta->Sumw2(); h_JetsAll_CSV->Sumw2(); h_JetsAll_phi->Sumw2(); h_JetsAll_Et->Sumw2(); h_JetsAll_chMult->Sumw2(); h_JetsAll_leadTrackPt->Sumw2(); h_nJetsAcc->Sumw2(); h_JetsAcc_mass->Sumw2(); h_JetsAcc_pT->Sumw2(); h_JetsAcc_eta->Sumw2(); h_JetsAcc_CSV->Sumw2(); h_JetsAcc_phi->Sumw2(); h_JetsAcc_Et->Sumw2(); h_JetsAcc_chMult->Sumw2(); h_JetsAcc_leadTrackPt->Sumw2(); h_nfJets->Sumw2(); h_fJets_mass->Sumw2(); h_fJets_pT->Sumw2(); h_fJets_eta->Sumw2(); h_fJets_CSV->Sumw2(); h_fJets_phi->Sumw2(); h_fJets_Et->Sumw2(); h_fJets_chMult->Sumw2(); h_fJets_leadTrackPt->Sumw2(); h_fJets_Centr->Sumw2(); h_naJets->Sumw2(); h_aJets_mass->Sumw2(); h_aJets_pT->Sumw2(); h_aJets_eta->Sumw2(); h_aJets_CSV->Sumw2(); h_aJets_phi->Sumw2(); h_aJets_Et->Sumw2(); h_aJets_chMult->Sumw2(); h_aJets_leadTrackPt->Sumw2(); h_fJet1_mass->Sumw2(); h_fJet2_mass->Sumw2(); h_fJet3_mass->Sumw2(); h_fJet4_mass->Sumw2(); h_fJet1_pT->Sumw2(); h_fJet2_pT->Sumw2(); h_fJet3_pT->Sumw2(); h_fJet4_pT->Sumw2(); h_fJet1_Eta->Sumw2(); h_fJet2_Eta->Sumw2(); h_fJet3_Eta->Sumw2(); h_fJet4_Eta->Sumw2(); h_fJet1_CSV->Sumw2(); h_fJet2_CSV->Sumw2(); h_fJet3_CSV->Sumw2(); h_fJet4_CSV->Sumw2(); h_fJet1_phi->Sumw2(); h_fJet2_phi->Sumw2(); h_fJet3_phi->Sumw2(); h_fJet4_phi->Sumw2(); h_fJet1_Et->Sumw2(); h_fJet2_Et->Sumw2(); h_fJet3_Et->Sumw2(); h_fJet4_Et->Sumw2(); h_fJet1_chMult->Sumw2(); h_fJet2_chMult->Sumw2(); h_fJet3_chMult->Sumw2(); h_fJet4_chMult->Sumw2(); h_fJet1_leadTrackPt->Sumw2(); h_fJet2_leadTrackPt->Sumw2(); h_fJet3_leadTrackPt->Sumw2(); h_fJet4_leadTrackPt->Sumw2(); h_fJets3avg_CSV->Sumw2(); h_fJets3min_CSV->Sumw2(); h_fJets4avg_CSV->Sumw2(); h_H_mass->Sumw2(); h_H_pT->Sumw2(); h_H_Phi->Sumw2(); h_H_Eta->Sumw2(); h_H_CosThSt->Sumw2(); h_H1_mass->Sumw2(); h_H1_pT->Sumw2(); h_H1_Phi->Sumw2(); h_H1_Eta->Sumw2(); h_H1_CosThSt->Sumw2(); h_H1_deltaR->Sumw2(); h_H1_deltaPhi->Sumw2(); h_H1_deltaEta->Sumw2(); h_H1_deltaPhi_abs ->Sumw2(); h_H1_deltaEta_abs->Sumw2(); h_H1_deltaPhiVSpT->Sumw2(); h_H2_mass->Sumw2(); h_H2_pT->Sumw2(); h_H2_Phi->Sumw2(); h_H2_Eta->Sumw2(); h_H2_CosThSt->Sumw2(); h_H2_deltaR->Sumw2(); h_H2_deltaPhi->Sumw2(); h_H2_deltaEta->Sumw2(); h_H2_deltaPhi_abs ->Sumw2(); h_H2_deltaEta_abs->Sumw2(); h_H2_deltaPhiVSpT->Sumw2(); h_HH_mass->Sumw2(); h_HH_pT->Sumw2(); h_HH_Eta->Sumw2(); h_HH_Phi->Sumw2(); h_HH_deltaR->Sumw2(); h_HH_deltaPhi->Sumw2(); h_HH_deltaEta->Sumw2(); h_H1_H2_mass->Sumw2(); h_HH_massInReg->Sumw2(); h_HH_pTInReg->Sumw2(); h_H1_H2_massInReg->Sumw2(); h_H1_H2_massInReg2->Sumw2(); h_H1_H2_massInReg3->Sumw2(); h_MET->Sumw2(); h_Cuts->Sumw2(); if(isSignal){ h_jet1b_dr->Sumw2(); h_jet2b_dr->Sumw2(); h_jet3b_dr->Sumw2(); h_jet4b_dr->Sumw2(); h_nGenH->Sumw2(); h_genH_pT->Sumw2(); h_genH_mass->Sumw2(); h_genHH_mass->Sumw2(); h_genH1_mass->Sumw2(); h_genH2_mass->Sumw2(); h_genB1Jets_DR->Sumw2(); h_genBfH1_DR->Sumw2(); h_genBfH2_DR->Sumw2(); } }
[ "martino.dall'osso@cern.ch" ]
martino.dall'osso@cern.ch
e800b428aa7a6cf23ad9c0fe2f7b004695d6c54f
8b87ec177751644caa2a26605b5940c380eeb0a8
/coding_test/2798.cpp
a62052a04c4062fc161ffaf5adca33a762c057f3
[]
no_license
oyunseong/cpp_coding_test
98ab8ca019a88c9229695248a14c154856057dc7
45a6be505f7a3d20d8a66ada27b9b911c2751c9c
refs/heads/master
2023-06-25T08:59:40.649092
2021-07-16T04:31:18
2021-07-16T04:31:18
355,225,994
0
0
null
null
null
null
UHC
C++
false
false
1,765
cpp
// 블랙잭 2798 //문제 //카지노에서 제일 인기 있는 게임 블랙잭의 규칙은 상당히 쉽다.카드의 합이 21을 넘지 않는 한도 내에서, 카드의 합을 최대한 크게 만드는 게임이다.블랙잭은 카지노마다 다양한 규정이 있다. // //한국 최고의 블랙잭 고수 김정인은 새로운 블랙잭 규칙을 만들어 상근, 창영이와 게임하려고 한다. // //김정인 버전의 블랙잭에서 각 카드에는 양의 정수가 쓰여 있다.그 다음, 딜러는 N장의 카드를 모두 숫자가 보이도록 바닥에 놓는다.그런 후에 딜러는 숫자 M을 크게 외친다. // //이제 플레이어는 제한된 시간 안에 N장의 카드 중에서 3장의 카드를 골라야 한다.블랙잭 변형 게임이기 때문에, 플레이어가 고른 카드의 합은 M을 넘지 않으면서 M과 최대한 가깝게 만들어야 한다. // //N장의 카드에 써져 있는 숫자가 주어졌을 때, M을 넘지 않으면서 M에 최대한 가까운 카드 3장의 합을 구해 출력하시오. #include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main() { int n; int m; int num; int sum=0; int min = 9999999; int result=0; cin >> n >> m; int *arr=NULL; if (n < 3 && n > 100) { return 0; } if (m < 10 && m > 30000) { return 0; } arr = new int[n]; for (int i = 0; i < n; i++) { cin >> num; if (num > 100000) { return 0; } arr[i] = num; } for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { sum = arr[i] + arr[j] + arr[k]; if (m - sum < min && m - sum >= 0) { min = m - sum; result = sum; } } } } cout << result; delete[] arr; return 0; }
[ "gkrlsanjf@naver.com" ]
gkrlsanjf@naver.com
b6226813346fd74a94a704bdb53a4e87546550bb
5b6f023032d06771fa88e002b51f4d61e30cdecf
/maya/source/MayaUtils.cpp
4c9aacffc37284d8a19910c344c13967d1a2ff2b
[]
no_license
jackytop/VARE
a91adbb7678c7ae8e95ef3709fb60dcce63de77a
d4f06d53bb3d02af56c272cf500bc3fd2336c278
refs/heads/master
2022-03-27T21:14:23.605602
2019-12-03T07:32:08
2019-12-03T07:32:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,507
cpp
//---------------// // MayaUtils.cpp // //-------------------------------------------------------// // author: Wanho Choi @ Dexter Studstd::ios // // last update: 2018.09.05 // //-------------------------------------------------------// #include <MayaUtils.h> MObject NodeNameToMObject( const MString& nodeName ) { MObject obj; MSelectionList sList; MStatus stat = MGlobal::getSelectionListByName( nodeName, sList ); if( !stat ) { return MObject::kNullObj; } sList.getDependNode( 0, obj ); return obj; } // dag node object of a transform node -> world matrix bool GetWorldMatrix( const MObject& dagNodeObj, MMatrix& worldMat ) { MStatus status = MS::kSuccess; MFnDagNode dagFn( dagNodeObj, &status ); if( status != MS::kSuccess ) { return false; } // Don't print any error messages here! MDagPath dagPath; status = dagFn.getPath( dagPath ); if( status != MS::kSuccess ) { return false; } // Don't print any error messages here! worldMat = dagPath.inclusiveMatrix(); return true; } void ApplyXForm( MPoint& p, const MMatrix& M ) { const double (*matrix)[4] = M.matrix; const double x=p.x, y=p.y, z=p.z; p.x = matrix[0][0]*x + matrix[1][0]*y + matrix[2][0]*z + matrix[3][0]; p.y = matrix[0][1]*x + matrix[1][1]*y + matrix[2][1]*z + matrix[3][1]; p.z = matrix[0][2]*x + matrix[1][2]*y + matrix[2][2]*z + matrix[3][2]; } void ApplyXForm( const MMatrix& M, const MPoint& p, MPoint& q ) { const double (*matrix)[4] = M.matrix; const double &x=p.x, &y=p.y, &z=p.z; q.x = matrix[0][0]*x + matrix[1][0]*y + matrix[2][0]*z + matrix[3][0]; q.y = matrix[0][1]*x + matrix[1][1]*y + matrix[2][1]*z + matrix[3][1]; q.z = matrix[0][2]*x + matrix[1][2]*y + matrix[2][2]*z + matrix[3][2]; } void Copy( Vec3fArray& to, const MPointArray& from ) { const unsigned int n = from.length(); if(!n) { to.clear(); return; } to.resize( n ); for( unsigned int i=0; i<n; ++i ) { Vec3f& q = to[i]; const MPoint& p = from[i]; q.x = (float)p.x; q.y = (float)p.y; q.z = (float)p.z; } } void Copy( Vec3fArray& to, const MVectorArray& from ) { const unsigned int n = from.length(); if(!n) { to.clear(); return; } to.resize( n ); for( unsigned int i=0; i<n; ++i ) { Vec3f& q = to[i]; const MVector& p = from[i]; q.x = (float)p.x; q.y = (float)p.y; q.z = (float)p.z; } } bool Convert( TriangleMesh& mesh, MObject& meshObj, bool vPosOnly, const char* uvSetName ) { if( meshObj.isNull() ) // no mesh object { mesh.clear(); return true; } if( !vPosOnly ) // assumption: different topology { mesh.clear(); } MStatus status = MS::kSuccess; MFnMesh meshFn( meshObj, &status ); if( status != MS::kSuccess ) { MGlobal::displayError( "Error@Convert(): Failed to get MFnMesh." ); mesh.reset(); return false; } MItMeshVertex vItr( meshObj, &status ); if( status != MS::kSuccess ) { MGlobal::displayError( "Error@Convert(): Failed to get MItMeshVertex." ); mesh.reset(); return false; } MItMeshPolygon fItr( meshObj, &status ); if( status != MS::kSuccess ) { MGlobal::displayError( "Error@Convert(): Failed to get MItMeshPolygon." ); mesh.reset(); return false; } const unsigned int numVertices = meshFn.numVertices(); const unsigned int numPolygons = meshFn.numPolygons(); ////////////////////// // vertex positions // int vIdx = 0; MPoint localPos; MMatrix localToWorld; MPointArray vP( numVertices ); // vertex positions if( GetWorldMatrix( meshObj, localToWorld ) ) { for( vItr.reset(); !vItr.isDone(); vItr.next(), ++vIdx ) { localPos = vItr.position( MSpace::kObject ); ApplyXForm( localToWorld, localPos, vP[vIdx] ); } } else { for( vItr.reset(); !vItr.isDone(); vItr.next(), ++vIdx ) { vP[vIdx] = vItr.position( MSpace::kWorld ); } } Copy( mesh.position, vP ); // mesh.position <- vP if( vPosOnly ) { return true; } ///////////////// // UV-set name // bool toConvertUV = true; MString uvSetNameStr; MFloatArray vU, vV; if( !meshFn.numUVSets() || !meshFn.numUVs() ) { toConvertUV = false; } else { MString inUVSetName( uvSetName ); if( inUVSetName.length() == 0 ) { toConvertUV = false; } else if( inUVSetName == MString("currentUVSet") ) { uvSetNameStr = meshFn.currentUVSetName(); } else { MStringArray uvSetNames; meshFn.getUVSetNames( uvSetNames ); const unsigned int numUVSets = uvSetNames.length(); for( unsigned int i=0; i<numUVSets; ++i ) { if( inUVSetName == uvSetNames[i] ) { uvSetNameStr = inUVSetName; break; } } } } if( toConvertUV ) { if( !meshFn.getUVs( vU, vV, &uvSetNameStr ) ) { toConvertUV = false; } } ////////////////////// // triangle indices // IndexArray& indices = mesh.indices; indices.reserve( numPolygons*2 ); for( fItr.reset(); !fItr.isDone(); fItr.next() ) { MIntArray vList; fItr.getVertices( vList ); const unsigned int vCount = vList.length(); if( vCount < 3 ) // invalid case { continue; } for( unsigned int i=0; i<vCount-2; ++i ) { indices.append( vList[0] ); indices.append( vList[i+1] ); indices.append( vList[i+2] ); } } Vec3fArray& uvw = mesh.uvw; uvw.reserve( numPolygons*2 ); if( toConvertUV ) { for( fItr.reset(); !fItr.isDone(); fItr.next() ) { MIntArray vList; fItr.getVertices( vList ); const unsigned int vCount = vList.length(); if( vCount < 3 ) // invalid case { continue; } MIntArray uvIndices; uvIndices.setLength( vCount ); for( unsigned int i=0; i<vCount; ++i ) { fItr.getUVIndex( i, uvIndices[i], &uvSetNameStr ); } for( unsigned int i=0; i<vCount-2; ++i ) { uvw.append( Vec3f( vU[uvIndices[0 ]], vV[uvIndices[0 ]], 0.f ) ); uvw.append( Vec3f( vU[uvIndices[i+1]], vV[uvIndices[i+1]], 0.f ) ); uvw.append( Vec3f( vU[uvIndices[i+2]], vV[uvIndices[i+2]], 0.f ) ); } } } return true; } float CurrentFPS() { float fps = 24.0f; MTime::Unit unit = MTime::uiUnit(); if( unit != MTime::kInvalid ) { MTime time( 1.0, MTime::kSeconds ); fps = static_cast<float>( time.as(unit) ); } if( fps <= 0.f ) { fps = 24.0f; } return fps; }
[ "jaegwang@outlook.com" ]
jaegwang@outlook.com
ed084d916f506c6a37a81ffd1c9f3ed00b27bfab
f678f7f88d23c4fbfc44a0299c07661c430b61b1
/src/noncryptographic/djb2hash32.hpp
d9cd827b6f24f644550a031fa5aa00d8cd850cc8
[ "MIT" ]
permissive
namralkeeg/QHashlib
e18d60138772349b3371292b3f2e1c6d0530ae4b
5b4fdb33833b6b0a1856c87a6d4696371aecfe59
refs/heads/master
2021-08-14T06:34:39.057859
2017-11-14T21:41:01
2017-11-14T21:41:01
108,071,443
0
0
null
null
null
null
UTF-8
C++
false
false
1,903
hpp
/* * Copyright (C) 2017 Larry Lopez * * 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 DJB2HASH32_HPP #define DJB2HASH32_HPP #include <hashalgorithm.hpp> namespace QHashlib { namespace noncryptographic { #ifndef DJB2_DEFAULT_SEED #define DJB2_DEFAULT_SEED UINT32_C(5381) #endif class Djb2Hash32 : public HashAlgorithm { public: Djb2Hash32(const quint32 &defaultSeed = DJB2_DEFAULT_SEED); virtual QByteArray hashFinal() override; virtual quint32 hashSize() override; virtual void initialize() override; protected: virtual void hashCore(const void *data, const quint64 &dataLength, const quint64 &startIndex) override; private: static const quint32 m_hashSize = std::numeric_limits<quint32>::digits; quint32 m_defaultSeed; quint32 m_hash; }; } // namespace noncryptographic } // namespace QHashlib #endif // DJB2HASH32_HPP
[ "namralkeeg@gmail.com" ]
namralkeeg@gmail.com
226e82304ac7fc64c1e0dc04085b6476592a476b
bf08df8a16a19c58e07ae29e08b0624767e99f3a
/MemoryManager/MemoryManager.cpp
5ddc0e962ada9878d5b8b94ddb29288b9379d144
[]
no_license
higgy300/OS_Project2
2279c80c58ad3748488e01d10f95c9429d6d078a
7ba04593b779a06c0c0c765488ec3e6195810165
refs/heads/master
2021-10-22T14:48:25.892884
2019-03-11T13:30:44
2019-03-11T13:30:44
171,611,142
0
0
null
null
null
null
UTF-8
C++
false
false
15,057
cpp
#include <utility> #include <cstring> #include <unistd.h> #include <cstdint> #include <functional> #include <vector> #include <cmath> #include <iostream> #include <cstdlib> #include <fcntl.h> #include <sys/types.h> #include <sys/syscall.h> #include "MemoryManager.h" #define MAX_WORDS 65536 #define MAX_WORD_SIZE_IN_BYTES 16 #define INVALID_WORD_SIZE "number of words for size cannot be zero. ERROR\n" #define USED 1 #define FREE 0 /* Constructor that sets native word size (for alignment) * and default allocator function for finding a memory * hole. */ MemoryManager::MemoryManager(unsigned wordSize, std::function<int(int, void*)> allocator) { /* Check if wordSize parameter is within a 16 byte limit because a word size cannot be greater than 16 bytes. That's 64 bits */ if (wordSize <= MAX_WORD_SIZE_IN_BYTES && wordSize > 0) word_size = static_cast<uint16_t>(wordSize); else if (wordSize == 0) // If the wordSize is zero word_size = 2; else // If the word size is greater than 16 bytes, use max of 16 bytes by default word_size = MAX_WORD_SIZE_IN_BYTES; // Make a copy of the allocator function (either bestFit() or worstFit()) this->allocator = allocator; } /* Releases all memory allocated by this object withoutc * leaking memory. */ MemoryManager::~MemoryManager() { // Deallocate every dynamic variable and vector shutdown(); } /* Instantiates a new block of memory of requested size, * no larger than 65536. Hint: you may use new char[...] */ void MemoryManager::initialize(size_t sizeInWords) { // Check if sizeInWords is less than the limit of 65536 if (!initialized) { if (sizeInWords < MAX_WORDS) { initialized = true; //num_of_words = static_cast<uint16_t>(ceil((double)sizeInWords / (double)word_size)); // How many blocks of one byte are needed to allocate this space? memory_byte_blocks = static_cast<uint32_t>(word_size * sizeInWords); std::vector<uint16_t> temp; // Allocate the space auto *memAddr = new uint8_t[memory_byte_blocks]; // Initialize memory spaces to zero // Store the starting address to the class object memory_addr = memAddr; /* Calculate how many blocks of 2 bytes are required to keep track of each word to be allocated in the giant block of memory and store it to the class object to be able to iterate later */ auto _bitmap_size = static_cast<uint16_t>(sizeInWords + 2); bitmap_size = _bitmap_size; // allocate the bitmap space auto *bitmap = new uint8_t[_bitmap_size]; // Initialize everything in bitmap to 0 for (int i = 0; i < _bitmap_size; i++) bitmap[i] = 0; // Save the initial bitmap address to the class object memory_bitmap = bitmap; // Store stream length in first two bytes of bitmap auto low_byte = (uint8_t)_bitmap_size; auto high_byte = (uint8_t)(_bitmap_size >> 8); memory_bitmap[0] = high_byte; memory_bitmap[1] = low_byte; // Mark all words in bitmap as free updateBitmap(2, _bitmap_size, false); /* Initialize list (4 = number of bytes), (0 = initial offset) * sizeInWords is the length of the hole in words */ temp.push_back(4); temp.push_back(0); temp.push_back(static_cast<unsigned short &&>(sizeInWords)); hole_list.swap(temp); } } //else //TODO:*************throw exception when sizeInWords is 0 } /* Releases memory block acquired during initialization. */ void MemoryManager::shutdown() { /* To prevent this function from being called twice in a row. the variable initialized will only change to true after initialize is called and it will only change to false after shutdown is called. This maintains a one to one ratio to prevent segmentation faults. */ if (initialized) { initialized = false; delete[]memory_addr; delete[]memory_bitmap; std::vector<uint16_t>().swap(hole_list); std::vector<uint16_t>().swap(proc_list); } } /* Allocates a block of memory. If no memory is available or * size is invalid, return nullptr. */ void* MemoryManager::allocate(size_t sizeInBytes) { // Check for valid parameter input if (sizeInBytes == 0) return nullptr; /* Calculate how many bytes are required to be able to allocate * from the giant block of memory */ auto num_words_required = static_cast<uint16_t>(ceil((double)sizeInBytes / (double) word_size)); /* Call the allocation algorithm currently assigned to the class object * to obtain the offset of starting memory address. Offset is the number * it takes from the first address of the giant block of space to the * location of the first word we are about to use */ int offset = allocator(num_words_required, (void*)&hole_list); int offset_in_single_bytes = offset * word_size; /* These are the addresses from the new block of memory we are about to allocate */ uint8_t* starting_addr = &memory_addr[offset_in_single_bytes]; /* Check if allocation algorithm did not fail. Else, return * a null pointer. */ if (offset >= 0) { /* Calculate bitmap index to determine where the new * block is marked as USED and the last index to stop * marking. */ int start = 2 + offset; int last = start + num_words_required; // Mark address space in bitmap as USED updateBitmap(start, last, true); // Update list of existing processes updateProcList(offset, num_words_required, false); /* Check if hole list is empty. If empty, return null pointer. * Otherwise, update hole list */ if (hole_list.size() == 1) return nullptr; else updateHoleList(); // Return starting address where new block of memory is allocated return (void*)starting_addr; } else return nullptr; } /* Frees the memory block within the memory manager so that * it can be reused. */ void MemoryManager::free(void *address) { // Cast void pointer parameter into a memory address of address space so we can do stuff with this address auto *free_addr = reinterpret_cast<uint8_t*>(address); //uint32_t offset = 0; /*for (auto itr = &memory_addr; itr != free_addr; itr++) { ++offset; }*/ auto offset = static_cast<uint16_t>((free_addr - memory_addr) / word_size); if (memory_bitmap[offset + 2] == FREE) return; else { /* Find the length of the block that was originally allocated to do a complete deallocation of the block and not just a single word deallocation */ uint16_t length = 0; for (uint16_t i = 0; i < proc_list.size(); i += 2) { if (proc_list[i] == offset) { length = proc_list[i + 1]; break; } } // Mark the block of memory as free updateBitmap(offset + 2, offset + 2 + length, false); // Update hole list updateHoleList(); // Update process list updateProcList(offset, 0, true); } } /* Changes the allocation algorithm to identifying the * memory hole to use for allocation. */ void MemoryManager::setAllocator(std::function<int(int, void*)> allocator) { this->allocator = allocator; } /* Uses standard POSIX calls to writehole list of * filename as text, returning -1 on error and 0 if successful. Format: "[START, LENGTH] - [START, LENGTH] ... " example: [0,10] - [12,2] - [20,6] */ int MemoryManager::dumpMemoryMap(char *filename) { int fd1 = open(filename, O_WRONLY | O_CREAT, S_IRWXU); if (fd1 == -1) { perror("File not opened.\n"); return -1; } else { std::string txt = "[" + std::to_string(hole_list[1]) + ", " + std::to_string(hole_list[2]); for (int i = 3; i < hole_list.size() - 1; i++) { txt += "] - [" + std::to_string(hole_list[i]) + ", " + std::to_string(hole_list[i + 1]); } txt += "]"; char buf[txt.length()]; for (int i = 0; i < txt.length() + 1; i++) { buf[i] = txt[i]; } write(fd1, buf, strlen(buf)); } close(fd1); return 0; } /* Returns a byte-stream of information (in binary) about * holes for use by the allocator function(little-Endian). */ void* MemoryManager::getList() { auto *ptrr = new uint16_t[hole_list.size()]; for (int i = 0; i < hole_list.size(); i++) { //std::cout << hole_list[i] << " "; ptrr[i] = hole_list[i]; } //std::cout << std::endl; return ptrr; } /* Returns a bit-stream of bits representing whether words * are used (1) or free (0).The first two bytes are the * size of the bitmap(little-Endian). The rest is the * bitmap, word-wise. */ void* MemoryManager::getBitmap() { // In the words of the wise: "I'll refactor this later" uint8_t adjusted_size = (memory_bitmap[1] - 2)/word_size; uint8_t *ptr = new uint8_t[adjusted_size + 2]; for (int i = 0; i < adjusted_size; i++) ptr[i] = 0; auto temp = memory_bitmap[0]; ptr[0] = adjusted_size; ptr[1] = temp; int bitmap_index = 2; int byte_number = 2; while (byte_number != adjusted_size + 2) { for (int i = 0; i < 8; i++) { //std::cout << (unsigned) memory_bitmap[bitmap_index]; ptr[byte_number] |= memory_bitmap[bitmap_index++] << i; } //std::cout << std::endl; ++byte_number; } return ptr; } /* Returns the word size used for alignment. */ unsigned MemoryManager::getWordSize() { return word_size; } /* Returns the byte-wise memory address of the beginning * of the memory block. */ void* MemoryManager::getMemoryStart() { return &memory_addr; } /* Returns the byte limit of the current memory block. */ unsigned MemoryManager::getMemoryLimit() { return memory_byte_blocks; } void MemoryManager::updateHoleList() { uint16_t temp_offset = 0, temp_length = 0; std::vector<uint16_t> temp_vect; for (int i = 2; i < bitmap_size; i++) { if (memory_bitmap[i] == 0) { temp_offset = (uint16_t )i; temp_length = 0; while (i < bitmap_size) { if (memory_bitmap[i] == 1) { break; } else { ++temp_length; ++i; } } temp_vect.push_back(temp_offset - 2); temp_vect.push_back(temp_length); } } auto temp_size = static_cast<uint16_t>(temp_vect.size() * 2); temp_vect.insert(temp_vect.begin(),temp_size); hole_list.swap(temp_vect); } void MemoryManager::updateProcList(int start, int len, bool removing) { // Check if we are removing a process or adding one to the list if (removing) { // We are removing a process. Let's check if the process list is empty if (proc_list.empty()) // The list is empty, let's call it a day and return return; else { // The list is not empty, we will now find where this process offset is in the vector std::vector<uint16_t >::iterator it; // Travers process list to find the potential address we will delete from the process vector for (it = proc_list.begin(); it != proc_list.end(); it++) { // Check to see if the offset entry exists in the process list if (*it == start) // Stop traversing process list if we find it break; else it++; } // Check one more time to see if we didn't find it. If we didn't, we don't do anything if (it >= proc_list.end()) return; // If we are here is because we found the entry and we are now going to erase it and the length entry too proc_list.erase(it); proc_list.erase(it); } } else { // We are NOT deleting a process! We are adding it! proc_list.push_back(static_cast<unsigned short &&>(start)); proc_list.push_back(static_cast<unsigned short &&>(len)); } } void MemoryManager::updateBitmap(int start, int last, bool allocate) { bool temp; if (allocate) temp = USED; else temp = FREE; for (int i = start; i < last; i++) memory_bitmap[i] = static_cast<uint8_t>(temp); } /***************** Memory Allocation Algorithms **********************/ /* Returns word offset of hole selected by the best fit * memory allocation algorithm, and -1 if there is no fit. */ int bestFit(int size, void *list) { int offset = -1, smallest_length = 2000000000; std::vector<uint16_t> &_list = *(static_cast<std::vector<uint16_t>*>(list)); uint16_t current_offset_in_vector = 0; uint16_t current_len_in_vector = 0; /* Check all holes to find smallest hole we can use to fit the * desired block of memory */ for (int i = 1; i < _list.size(); i += 2) { /* Does the block we are trying to allocate fit in the current * hole ? */ current_offset_in_vector = _list[i]; current_len_in_vector = _list[i + 1]; if (size <= _list[i + 1]) { /* It does fit! Is the hole smaller then the smallest hole we * have seen so far? */ if (_list[i + 1] <= smallest_length) { /* It is smaller! Let's mark it as smallest hole that can * fit our desired block of memory */ smallest_length = _list[i + 1]; offset = _list[i]; } } } return offset; } /* Returns word offset of hole selected by the worst fit * memory allocation algorithm, and -1 if there is no fit. */ int worstFit(int size, void *list) { int offset = -1, biggest_length = 0; std::vector<uint16_t> &_list = *(static_cast<std::vector<uint16_t>*>(list)); /* Check all holes to find smallest hole we can use to fit the * desired block of memory */ for (int i = 1; i < _list.size(); i += 2) { /* Does the block we are trying to allocate fit in the current * hole ? */ if (size <= _list[i + 1]) { /* It does fit! Is the hole bigger then the biggest hole we * have seen so far? */ if (_list[i + 1] >= biggest_length) { /* It is smaller! Let's mark it as smallest hole that can * fit our desired block of memory */ biggest_length = _list[i + 1]; offset = _list[i]; } } } return offset; }
[ "jhigueraballesteros@gmail.com" ]
jhigueraballesteros@gmail.com
39a9203fd66495c22a27000a5bc530c2e888eab1
480a80698fe30b301935611ae4257c8b6a6d83bb
/src/tests/TestBase.h
574f113ca9225b7edb638bf018135005b9a8ba30
[ "MIT" ]
permissive
AlexKent3141/OnePunchGo
c70e2b02cce03cd4954740731eb94f585a49b3ac
a86caaf421c8122222f72316171702617c519d28
refs/heads/master
2021-06-08T10:53:31.068688
2021-03-10T21:43:09
2021-03-10T21:43:09
90,786,277
3
0
MIT
2018-03-31T15:57:11
2017-05-09T19:55:09
C++
UTF-8
C++
false
false
369
h
#ifndef __TEST_BASE_H__ #define __TEST_BASE_H__ #include <vector> #include <string> // Base class for test types. class TestBase { public: // Get the source of the test cases. virtual std::string TestFileName() const = 0; // Execute test based on the given lines. virtual bool Run(const std::vector<std::string>&) = 0; }; #endif // __TEST_BASE_H__
[ "alex.kent1@hotmail.com" ]
alex.kent1@hotmail.com
c2e7d82d413733264cb5ecdfa6c78902d9f8300d
d3fcfbaa0e200f49cefe4b77388292402e428eb3
/Codeforces/727-C.cpp
4397195eac3f5d2362619cdad0a244b55285f32c
[]
no_license
edge555/Online-Judge-Solves
c3136b19dc2243e9676b57132d4162c554acaefb
452a85ea69d89a3691a04b5dfb7d95d1996b736d
refs/heads/master
2023-08-22T03:23:11.263266
2023-08-21T07:22:33
2023-08-21T07:22:33
145,904,907
14
3
null
null
null
null
UTF-8
C++
false
false
1,794
cpp
#include <bits/stdc++.h> #define FAST ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define pf printf #define sc scanf #define sf(num) scanf("%d",&num) #define sff(num1,num2) scanf("%d %d",&num1,&num2) #define sfff(num1,num2,num3) scanf("%d %d %d",&num1,&num2,&num3); #define sl(num) scanf("%lld",&num) #define sll(num1,num2) scanf("%lld %lld",&num1,&num2) #define slll(num1,num2,num3) scanf("%lld %lld %lld",&num1,&num2,&num3); #define rep(i,n) for(i=1;i<=n;i++) #define rep0(i,n) for(i=0;i<n;i++) #define reps(i,a,n) for(i=a;i<=n;i++) #define pb push_back #define mpp make_pair #define MOD 1000000007 #define fi first #define se second #define N 100005 #define mem(ara,n) memset(ara,n,sizeof(ara)) #define memb(ara) memset(ara,false,sizeof(ara)) #define all(x) (x).begin(),(x).end() #define sq(x) ((x)*(x)) #define pi pair<int,int> #define pii pair<pair<int,int>,pair<int,int> > #define db(x) cout<<#x<<" :: "<<x<<"\n"; #define dbb(x,y) cout<<#x<<" :: "<<x<<"\t"<<#y<<" :: "<<y<<"\n"; #define fr freopen("input.txt","r",stdin); #define fw freopen("output.txt","w",stdout); #define TIME cerr<<"Time : "<<(double)clock()/(double)CLOCKS_PER_SEC<<"s\n"; typedef long long int ll; using namespace std; int main() { int n,i,a,b,c; cin>>n; int x,y,z; vector<int>vec; cout<<"? 1 2"<<endl; fflush(stdout); cin>>x; cout<<"? 2 3"<<endl; fflush(stdout); cin>>y; cout<<"? 1 3"<<endl; fflush(stdout); cin>>z; a=(x+z-y)/2; b=x-a; c=z-a; vec.pb(a); vec.pb(b); vec.pb(c); int k,p; reps(k,4,n) { cout<<"? 1 "<<k<<endl; fflush(stdout); cin>>p; vec.pb(p-a); } pf("!"); fflush(stdout); rep0(i,n) { pf(" %d",vec[i]); fflush(stdout); } }
[ "shoaib27@student.sust.edu" ]
shoaib27@student.sust.edu
6b81279876635372ae968f8c57c81c98dac027ec
ac5685c9ccfb56adb877d89a3daca5b8ca840967
/LightOj 1071.cpp
fc810817be363da1ae78eda0ab0164b8dc95a452
[]
no_license
maknunlakme/LightOj-Solutions
6d9ab63d62cff853ce93e8c1737a4d55c8bd9180
ce03837470a692064077bc5cd3b78557d834158b
refs/heads/master
2020-04-08T12:20:16.361203
2018-11-27T13:54:12
2018-11-27T13:54:12
159,343,164
2
0
null
null
null
null
UTF-8
C++
false
false
1,267
cpp
#include<iostream> #include<cstdio> #include<cstring> #define INF 1000000000 #define X 110 using namespace std; int dp[X][X][X][4]; int mat[X][X]; int n,m; int rec(int r,int c1,int c2,int moves) { int &res=dp[r][c1][c2][moves]; if(res==-1) { res=0; if(moves==0) { if(c1+1<c2) { res=rec(r,c1+1,c2,0)+mat[r][c1+1]; } res=max(res,rec(r,c1,c2,1)); } if(moves==1) { if(c2+1<m) { res=rec(r,c1,c2+1,1)+mat[r][c2+1]; } res=max(res,rec(r,c1,c2,2)); } if(moves==2) { if(r+1<n) { res=rec(r+1,c1,c2,0)+mat[r+1][c1]+mat[r+1][c2]; } } } return res; } int main() { int test,i,j,t,last,ans; scanf("%d",&test); for(t=1; t<=test; t++) { memset(mat,0,sizeof mat); memset(dp,-1,sizeof dp); scanf("%d%d",&n,&m); for(i=0; i<n; i++) { for(j=0; j<m; j++) { scanf("%d",&mat[i][j]); } } ans=rec(0,0,1,0)+mat[0][0]+mat[0][1]; printf("Case %d: %d\n",t,ans); } return 0; }
[ "maknunsmail@gmail.com" ]
maknunsmail@gmail.com
971bb3f6f929a3ad3cbb740d627b60e29edd99c8
8f24ec947cb69b76ebe6db1c1c74f1e0a41b7c24
/Libraries/PIDController/PIDController.cpp
5a14d199c8714a2e1f396dcc4709ce767a1e3655
[]
no_license
kevinmcl001/Sphere-o-tron
22ecae77255072de8bc0ff44764dd77ff8577bb8
48de5b2f9ff1a60f52196060a4eafbc3da5afc3c
refs/heads/master
2016-09-10T03:29:53.181473
2015-11-11T11:10:42
2015-11-11T11:10:42
27,517,157
0
0
null
null
null
null
UTF-8
C++
false
false
1,935
cpp
// // Created for the *Balance-O-Matic* robotics project // Written by Kevin McLeod and Myles Shepherd, Summer 2014 // I haven't got a clue how all that copyright shit works // // PIDController.cpp // For all your control system needs! // // *Integral output term constrained to |255| // #include "Arduino.h" #include "PIDController.h" //PID controller default constructor //Just set everything to zero. It'll be fine. PIDController::PIDController() { setPoint = 0.0; error = 0.0; prevError = 0.0; sumError = 0.0; deltaError = 0.0; kP = 0.0; kI = 0.0; kD = 0.0; sumErrorMax = 0.0; } //Do literally everything float PIDController::calculate(float newAngle) { //Calculate errors error = newAngle - setPoint; sumError += error; sumError = constrain(sumError,-sumErrorMax,sumErrorMax); //Put a cap on the integral term deltaError = error - prevError; //Calculate PID output //Currently unbounded float output = error*kP + sumError*kI + deltaError*kD; //Save current error prevError = error; return output; } //Set all error terms to zero void PIDController::resetErrors() { error = 0; prevError = 0; sumError = 0; deltaError = 0; } //Set proportional gain void PIDController::setPGain(float gain) { kP = gain; } //Set integral gain void PIDController::setIGain(float gain) { kI = gain; } //Set derivative gain void PIDController::setDGain(float gain) { kD = gain; } //Set the maximum allowable sumError void PIDController::setSumErrorMax(float max) { sumErrorMax = max; } //Change setpoint void PIDController::setSetSetPoint(float newSetPoint) { setPoint = newSetPoint; } //Output all gain values [kP,kI,kD] void PIDController::getGains(float* gains) { gains[0] = kP; gains[1] = kI; gains[2] = kD; } //Output all PID errors [error,sumError,deltaError] void PIDController::getErrors(float* errors) { errors[0] = error; errors[1] = sumError; errors[2] = deltaError; } //1150x3597
[ "kevinmcleod@shaw.ca" ]
kevinmcleod@shaw.ca
95921c48e223614b16c898404cdc8fac8baf5ff7
9e37ea0499bceddaa313df8a30d958bd177c0969
/thread_support_library/thread_get_id_example.cpp
a6ca0a404101716a29715cfb443ebc94686ee43e
[]
no_license
JieTrancender/C-STL
088d67b2610e767ecc42caeb2a7b0a803d1f2117
9fd74c0f08661cea97e863bc7469d89e649c23ce
refs/heads/master
2021-01-21T04:27:34.386623
2017-09-10T01:59:55
2017-09-10T01:59:55
40,899,671
0
0
null
null
null
null
UTF-8
C++
false
false
1,183
cpp
/************************************************************************* > File Name: thread_get_id_example.cpp > Author: Jie Mo > Email: 582865471@vip.qq.com > Github: JieTrancender > Created Time: Tue Mar 15 16:35:14 2016 ************************************************************************/ //std::thread::id get_id() const; #include <iostream> #include <thread> #include <chrono> #include <mutex> std::mutex g_mutex; void foo() { std::this_thread::sleep_for(std::chrono::seconds(1)); } void func() { std::thread::id this_id = std::this_thread::get_id(); g_mutex.lock(); std::cout << "Thread: " << this_id << "executing...\n"; g_mutex.unlock(); std::this_thread::sleep_for(std::chrono::seconds(1)); } int main(int argc, char** argv) { std::thread t1(foo); std::thread::id t1_id = t1.get_id(); std::thread t2(foo); std::thread::id t2_id = t2.get_id(); std::cout << "t1's id: " << t1_id << std::endl; std::cout << "t2's id: " << t2_id << std::endl; std::cout << "main's id: " << std::this_thread::get_id() << std::endl; std::thread t3(func); std::thread t4(func); t1.join(); t2.join(); t3.join(); t4.join(); return 0; }
[ "582865471@qq.com" ]
582865471@qq.com
6f2299c62835972b3a8454c42f362a1fde682d02
522aafdf9b9acfef104af8aa578aaa7e410fac7e
/c++/str_len.cpp
2757498493e659d19cdabd18c48596017ad3c98c
[]
no_license
anu1/MyRepo
0863ef4c5de067b5cddc4894dc6f05f84f401597
7ae55e0f0afe540aba34ff93e277633b382a0c95
refs/heads/master
2021-01-19T13:04:12.474847
2017-06-20T12:17:39
2017-06-20T12:17:39
82,363,641
0
0
null
null
null
null
UTF-8
C++
false
false
202
cpp
#include <iostream> using namespace std; int main() { string str = "C++ Programming"; // you can also use str.length() cout << "String Length = " << str.size(); return 0; }
[ "nanuradhasarma@gmail.com" ]
nanuradhasarma@gmail.com
6c8b6a4f7f870bbf4cb4a8dbe74880fea185f198
22225b0d70d82ba81bfe1caee1d1939ab8da11f2
/src/test/getarg_tests.cpp
5c23fba7c49d03ab76593188913723c003517b57
[ "MIT" ]
permissive
TGIF-CoinVest/TGIF
0d59fff48b3eb5fa066a60da11797252606c48d3
5f539f705badeaaa28fe7584ac78273a8c4edb84
refs/heads/master
2020-05-03T03:43:27.325751
2019-03-29T12:40:42
2019-03-29T12:40:42
178,313,662
0
0
null
null
null
null
UTF-8
C++
false
false
4,655
cpp
// Copyright (c) 2012-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "util.h" #include "test/test_coinvest.h" #include <string> #include <vector> #include <boost/algorithm/string.hpp> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(getarg_tests, BasicTestingSetup) static void ResetArgs(const std::string& strArg) { std::vector<std::string> vecArg; if (strArg.size()) boost::split(vecArg, strArg, boost::is_space(), boost::token_compress_on); // Insert dummy executable name: vecArg.insert(vecArg.begin(), "testcoinvest"); // Convert to char*: std::vector<const char*> vecChar; BOOST_FOREACH(std::string& s, vecArg) vecChar.push_back(s.c_str()); ParseParameters(vecChar.size(), &vecChar[0]); } BOOST_AUTO_TEST_CASE(boolarg) { ResetArgs("-foo"); BOOST_CHECK(GetBoolArg("-foo", false)); BOOST_CHECK(GetBoolArg("-foo", true)); BOOST_CHECK(!GetBoolArg("-fo", false)); BOOST_CHECK(GetBoolArg("-fo", true)); BOOST_CHECK(!GetBoolArg("-fooo", false)); BOOST_CHECK(GetBoolArg("-fooo", true)); ResetArgs("-foo=0"); BOOST_CHECK(!GetBoolArg("-foo", false)); BOOST_CHECK(!GetBoolArg("-foo", true)); ResetArgs("-foo=1"); BOOST_CHECK(GetBoolArg("-foo", false)); BOOST_CHECK(GetBoolArg("-foo", true)); // New 0.6 feature: auto-map -nosomething to !-something: ResetArgs("-nofoo"); BOOST_CHECK(!GetBoolArg("-foo", false)); BOOST_CHECK(!GetBoolArg("-foo", true)); ResetArgs("-nofoo=1"); BOOST_CHECK(!GetBoolArg("-foo", false)); BOOST_CHECK(!GetBoolArg("-foo", true)); ResetArgs("-foo -nofoo"); // -nofoo should win BOOST_CHECK(!GetBoolArg("-foo", false)); BOOST_CHECK(!GetBoolArg("-foo", true)); ResetArgs("-foo=1 -nofoo=1"); // -nofoo should win BOOST_CHECK(!GetBoolArg("-foo", false)); BOOST_CHECK(!GetBoolArg("-foo", true)); ResetArgs("-foo=0 -nofoo=0"); // -nofoo=0 should win BOOST_CHECK(GetBoolArg("-foo", false)); BOOST_CHECK(GetBoolArg("-foo", true)); // New 0.6 feature: treat -- same as -: ResetArgs("--foo=1"); BOOST_CHECK(GetBoolArg("-foo", false)); BOOST_CHECK(GetBoolArg("-foo", true)); ResetArgs("--nofoo=1"); BOOST_CHECK(!GetBoolArg("-foo", false)); BOOST_CHECK(!GetBoolArg("-foo", true)); } BOOST_AUTO_TEST_CASE(stringarg) { ResetArgs(""); BOOST_CHECK_EQUAL(GetArg("-foo", ""), ""); BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), "eleven"); ResetArgs("-foo -bar"); BOOST_CHECK_EQUAL(GetArg("-foo", ""), ""); BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), ""); ResetArgs("-foo="); BOOST_CHECK_EQUAL(GetArg("-foo", ""), ""); BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), ""); ResetArgs("-foo=11"); BOOST_CHECK_EQUAL(GetArg("-foo", ""), "11"); BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), "11"); ResetArgs("-foo=eleven"); BOOST_CHECK_EQUAL(GetArg("-foo", ""), "eleven"); BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), "eleven"); } BOOST_AUTO_TEST_CASE(intarg) { ResetArgs(""); BOOST_CHECK_EQUAL(GetArg("-foo", 11), 11); BOOST_CHECK_EQUAL(GetArg("-foo", 0), 0); ResetArgs("-foo -bar"); BOOST_CHECK_EQUAL(GetArg("-foo", 11), 0); BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0); ResetArgs("-foo=11 -bar=12"); BOOST_CHECK_EQUAL(GetArg("-foo", 0), 11); BOOST_CHECK_EQUAL(GetArg("-bar", 11), 12); ResetArgs("-foo=NaN -bar=NotANumber"); BOOST_CHECK_EQUAL(GetArg("-foo", 1), 0); BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0); } BOOST_AUTO_TEST_CASE(doublecoinvest) { ResetArgs("--foo"); BOOST_CHECK_EQUAL(GetBoolArg("-foo", false), true); ResetArgs("--foo=verbose --bar=1"); BOOST_CHECK_EQUAL(GetArg("-foo", ""), "verbose"); BOOST_CHECK_EQUAL(GetArg("-bar", 0), 1); } BOOST_AUTO_TEST_CASE(boolargno) { ResetArgs("-nofoo"); BOOST_CHECK(!GetBoolArg("-foo", true)); BOOST_CHECK(!GetBoolArg("-foo", false)); ResetArgs("-nofoo=1"); BOOST_CHECK(!GetBoolArg("-foo", true)); BOOST_CHECK(!GetBoolArg("-foo", false)); ResetArgs("-nofoo=0"); BOOST_CHECK(GetBoolArg("-foo", true)); BOOST_CHECK(GetBoolArg("-foo", false)); ResetArgs("-foo --nofoo"); // --nofoo should win BOOST_CHECK(!GetBoolArg("-foo", true)); BOOST_CHECK(!GetBoolArg("-foo", false)); ResetArgs("-nofoo -foo"); // foo always wins: BOOST_CHECK(GetBoolArg("-foo", true)); BOOST_CHECK(GetBoolArg("-foo", false)); } BOOST_AUTO_TEST_SUITE_END()
[ "root@expvps.tgifglobal.net" ]
root@expvps.tgifglobal.net
11005a26b95fbaa7e67712845cd5a9c4898a2341
e9321204dfca38eaf12eca38f83476879c170441
/PDA/VTK-6.3.0/VTK-Release-build/Rendering/OpenGL/vtkOpenGLPropertyDefaultPropFunc_fs.cxx
935ff74fa43ee9c92c267436a05e46acd73d942a
[ "BSD-3-Clause" ]
permissive
jumperbeng/backup
1d96d471e4aa1adc1179fa78db02b08ff944f7ab
64e36db87446ddae132524e19fef45f2b1b01242
refs/heads/master
2021-07-14T08:27:34.831316
2017-10-17T04:09:31
2017-10-17T04:09:31
107,211,167
1
0
null
null
null
null
UTF-8
C++
false
false
1,406
cxx
/* DO NOT EDIT. * Generated by ../../bin/vtkEncodeString-6.3 * * Define the vtkOpenGLPropertyDefaultPropFunc_fs string. * * Generated from file: /home/jumper/Documents/PDA/VTK-6.3.0/Rendering/OpenGL/vtkOpenGLPropertyDefaultPropFunc_fs.glsl */ #include "vtkOpenGLPropertyDefaultPropFunc_fs.h" const char *vtkOpenGLPropertyDefaultPropFunc_fs = "// ============================================================================\n" "//\n" "// Program: Visualization Toolkit\n" "// Module: vtkOpenGLPropertyDefaultPropFunc_fs.glsl\n" "//\n" "// Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n" "// All rights reserved.\n" "// See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n" "//\n" "// This software is distributed WITHOUT ANY WARRANTY; without even\n" "// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n" "// PURPOSE. See the above copyright notice for more information.\n" "//\n" "// ============================================================================\n" "\n" "// Default fragment shader used on property.\n" "\n" "#version 110\n" "\n" "uniform int useTexture;\n" "uniform sampler2D texture;\n" "\n" "void propFuncFS()\n" "{\n" " if(useTexture==1)\n" " {\n" " gl_FragColor=gl_Color*texture2D(texture,gl_TexCoord[0].xy);\n" " }\n" " else\n" " {\n" " gl_FragColor=gl_Color;\n" " }\n" "}\n" "\n";
[ "wangzixuan828@gmail.com" ]
wangzixuan828@gmail.com
ebf5caf5e107bb67e80971e19890aa46fcfeadf1
85ad39072a7787968fd9beb27bf575e09c3de89f
/Board.h
735313027e8a6db958dd5b40185197b640fe0c02
[]
no_license
schmmd/chairequalsmoney
af5e5a76e4464dbc5f498621a63cfa64b9d06e9c
6c71b6097a5bb85d18114133433aaa8dcc122d92
refs/heads/main
2021-06-14T22:07:59.221380
2019-01-26T00:16:29
2019-01-26T00:16:29
167,283,869
0
0
null
null
null
null
UTF-8
C++
false
false
1,072
h
#ifndef _H_BOARD #define _H_BOARD #include <memory.h> #include <string.h> #include <stdio.h> class CBoard { public: CBoard() : _board(0) {} ~CBoard() { Free(); } void Create(int width, int height); void Clear() { memset(_board, 0, sizeof(bool) * _width * _height); } void Free(); bool InBounds(int x, int y) { if (x >= 0 && y >= 0 && x < Width() && y < Height()) return true; else return false; } bool Write(int index, char* szString, int size) { if ((int)(index + size) <= Size()) { memcpy(_board + index, szString, size); // _snprintf(_board + index, size, szString); return true; } else { return false; } } char Get(int x, int y ) { return _board[y * _width + x]; } char Get(int i) { return _board[i]; } void Set(int x, int y, char v) { _board[y * _width + x] = v; } int Width () { return _width; } int Height() { return _height; } int Size () { return _width * _height; } char* _board; private: int _width; int _height; int _right; int _bottom; }; #endif
[ "michael@schmitztech.com" ]
michael@schmitztech.com
7ba2eaf9eac7f07c1b43d445e18d0236a2bb1d83
622d9ea6d32d5cfa6682ac24c4c0aa43c7752bd3
/src/logger.cpp
de17b8696e71d665e651276e4e807b46113b1055
[ "MIT" ]
permissive
WesternCivilization/cpp-logger
af0f97d2209504357819ccc7bc2ababb9172360b
1a827a3784cece5beea7df2f173572b5b25284e0
refs/heads/master
2021-06-16T07:16:22.067508
2017-05-03T12:58:26
2017-05-03T12:58:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,373
cpp
#include "logger.h" #include <cstdarg> #include <cstdio> #include <cstdlib> #if defined(_WIN32) || defined(_WIN64) #include <winsock2.h> #else #include <pthread.h> #include <sys/syscall.h> #include <unistd.h> #endif // defined(_WIN32) || defined(_WIN64) #include "log_thread.h" namespace logger { bool Logger::InitConsoleLogger(FILE* output) { auto thread = Logger::Instance().Thread(); if (output == stderr) { thread->AddWriter(std::unique_ptr<StderrLogWriter>(new StderrLogWriter())); } else { thread->AddWriter(std::unique_ptr<StdoutLogWriter>(new StdoutLogWriter())); } return true; } bool Logger::InitFileLogger(const char* filename, int64_t maxFileSize, uint8_t maxBackupFiles) { auto thread = Logger::Instance().Thread(); auto fileLogWriter = std::unique_ptr<FileLogWriter>(new FileLogWriter(filename, maxFileSize, maxBackupFiles)); if (!fileLogWriter->Init()) { return false; } thread->AddWriter(std::move(fileLogWriter)); return true; } Logger::Logger() : m_level(LogLevel_INFO) { m_thread = std::make_shared<LogThread>(); } Logger::~Logger() {} std::shared_ptr<LogThread> Logger::Thread() { return m_thread; } #if defined(_WIN32) || defined(_WIN64) static int vasprintf(char** strp, const char* fmt, va_list ap) { int len = _vscprintf(fmt, ap); if (len == -1) { return -1; } size_t size = (size_t) (len + 1); *strp = (char*) malloc(size); if (*strp == nullptr) { return -1; } int result = vsnprintf(*strp, size, fmt, ap); if (result == -1) { free(*strp); return -1; } return result; } static int gettimeofday(struct timeval* tv, void* tz) { const UINT64 epochFileTime = 116444736000000000ULL; if (tv == NULL) { return -1; } FILETIME ft; GetSystemTimeAsFileTime(&ft); ULARGE_INTEGER li; li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; UINT64 t = (li.QuadPart - epochFileTime) / 10; tv->tv_sec = (long) (t / 1000000); tv->tv_usec = t % 1000000; return 0; } #endif // defined(_WIN32) || defined(_WIN64) static uint64_t getCurrentThreadID(); void Logger::Log(LogLevel level, const char* file, uint32_t line, const char* fmt, ...) { if (!isEnabled(level)) { return; } char* buf = nullptr; va_list arg; va_start(arg, fmt); if (vasprintf(&buf, fmt, arg) != -1) { LogMessage msg = {}; msg.level = level; gettimeofday(&msg.timestamp, nullptr); msg.threadID = getCurrentThreadID(); msg.file = file; msg.line = line; msg.content = buf; m_thread->Send(std::move(msg)); } else { fprintf(stderr, "ERROR: logger: vasprintf"); } va_end(arg); } static uint64_t getCurrentThreadID() { #if defined(_WIN32) || defined(_WIN64) return (uint64_t) GetCurrentThreadId(); #elif __linux__ return (uint64_t) syscall(SYS_gettid); #elif defined(__APPLE__) && defined(__MACH__) return (uint64_t) syscall(SYS_thread_selfid); #else return (uint64_t) pthread_self(); #endif // defined(_WIN32) || defined(_WIN64) } LogLevel Logger::level() { return m_level; } void Logger::setLevel(LogLevel level) { m_level = level; } bool Logger::isEnabled(LogLevel level) { return m_level <= level; } } // namespace logger
[ "yksz.dev@gmail.com" ]
yksz.dev@gmail.com
e0a762ee7680a654b3e4f56d4a6a404e37a1ad02
5ae7c963e97b1aa6ad6b9bbcfb581dcf5de68e8b
/mstoolkit/include/pepXMLWriter.h
fcc1513f1008d38bfcd7e174d6005ec5f8785430
[ "Apache-2.0" ]
permissive
vdemichev/DiaNN
7fcb7fefc2921319dfc976a2f89bc6a0b4920d39
7a1a722f5f7b187e4dcb316f3db514d8c6902b9c
refs/heads/master
2023-06-23T02:41:56.921023
2023-06-19T17:54:05
2023-06-19T17:54:05
125,283,280
178
49
NOASSERTION
2023-06-20T21:44:56
2018-03-14T22:46:20
C++
UTF-8
C++
false
false
13,151
h
/* Copyright 2005-2016, Michael R. Hoopmann 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 _PEPXMLWRITER_H #define _PEPXMLWRITER_H #include <cstdio> #include <cstdlib> #include <ctime> #include <string> #include <iostream> #include <vector> using namespace std; //Some simple data structures for PepXMLWriter (pxw) typedef struct pxwBasicXMLTag { string name; string value; } pxwBasicXMLTag; typedef struct pxwModAA{ int position; double mass; } pxwModAA; typedef struct pxwMSMSRunSummary { string base_name; string raw_data_type; string raw_data; string search_engine; } pxwMSMSRunSummary; typedef struct pxwProtein { string protein; char peptide_next_aa; char peptide_prev_aa; int protein_link_pos_a; int protein_link_pos_b; } pxwProtein; //Use classes for more complicated structures with dynamic arrays //and additional fuctions. class PXWModInfo{ public: double mod_cterm_mass; double mod_nterm_mass; string modified_peptide; PXWModInfo(){ mod_cterm_mass=0; mod_nterm_mass=0; modified_peptide.clear(); mods=new vector<pxwModAA>; } PXWModInfo(const PXWModInfo& s){ mod_cterm_mass=s.mod_cterm_mass; mod_nterm_mass=s.mod_nterm_mass; modified_peptide = s.modified_peptide; mods=new vector<pxwModAA>; for(size_t i=0;i<s.mods->size();i++) mods->push_back(s.mods->at(i)); } ~PXWModInfo(){ delete mods; } PXWModInfo& operator=(const PXWModInfo& s){ if(this!=&s){ mod_cterm_mass = s.mod_cterm_mass; mod_nterm_mass = s.mod_nterm_mass; modified_peptide = s.modified_peptide; delete mods; mods=new vector<pxwModAA>; for(size_t i=0;i<s.mods->size();i++) mods->push_back(s.mods->at(i)); } return *this; } void addMod(pxwModAA& p){ mods->push_back(p); } void addMod(int pos, double mass){ pxwModAA p; p.position=pos; p.mass=mass; addMod(p); } void clear(){ mod_cterm_mass=0; mod_nterm_mass=0; modified_peptide.clear(); mods->clear(); } pxwModAA& getMod(int index){ return mods->at(index); } pxwModAA& getMod(size_t index){ return mods->at(index); } size_t sizeMods(){ return mods->size(); } private: vector<pxwModAA>* mods; }; class PXWSearchSummary { public: string base_name; string search_database; string search_engine; string search_engine_version; int precursor_mass_type; //0=monoisotopic, 1=average int fragment_mass_type; //0=monoisotopic, 1=average vector<pxwBasicXMLTag>* parameters; PXWSearchSummary(){ base_name.clear(); search_database.clear(); search_engine.clear(); search_engine_version.clear(); precursor_mass_type=0; fragment_mass_type=0; parameters=new vector<pxwBasicXMLTag>; } PXWSearchSummary(const PXWSearchSummary& s){ base_name=s.base_name; search_database=s.search_database; search_engine=s.search_engine; search_engine_version=s.search_engine_version; precursor_mass_type=s.precursor_mass_type; fragment_mass_type=s.fragment_mass_type; parameters=new vector<pxwBasicXMLTag>; for(size_t i=0;i<s.parameters->size();i++) parameters->push_back(s.parameters->at(i)); } ~PXWSearchSummary(){ delete parameters; } PXWSearchSummary& operator=(const PXWSearchSummary& s){ if(this!=&s){ base_name=s.base_name; search_database = s.search_database; search_engine=s.search_engine; search_engine_version=s.search_engine_version; precursor_mass_type=s.precursor_mass_type; fragment_mass_type=s.fragment_mass_type; delete parameters; parameters=new vector<pxwBasicXMLTag>; for(size_t i=0;i<s.parameters->size();i++) parameters->push_back(s.parameters->at(i)); } return *this; } }; class PXWSearchHit { public: int hit_rank; string peptide; int num_tot_proteins; double calc_neutral_pep_mass; double calc_neutral_xl_mass; double massdiff; double xl_massdiff; PXWModInfo modInfo; string xlink_type; //na,loop,xl PXWSearchHit(){ hit_rank=0; peptide.clear(); num_tot_proteins=0; calc_neutral_pep_mass=0; calc_neutral_xl_mass=0; massdiff=0; xl_massdiff=0; modInfo.clear(); xlink_type="na"; proteins=new vector<pxwProtein>; searchScores=new vector<pxwBasicXMLTag>; xlScores=new vector<pxwBasicXMLTag>; } PXWSearchHit(const PXWSearchHit& s){ size_t i; hit_rank=s.hit_rank; peptide=s.peptide; num_tot_proteins=s.num_tot_proteins; calc_neutral_pep_mass=s.calc_neutral_pep_mass; calc_neutral_xl_mass=s.calc_neutral_xl_mass; massdiff=s.massdiff; xl_massdiff=s.xl_massdiff; modInfo=s.modInfo; xlink_type=s.xlink_type; proteins=new vector<pxwProtein>; searchScores=new vector<pxwBasicXMLTag>; xlScores=new vector<pxwBasicXMLTag>; for(i=0;i<s.proteins->size();i++) proteins->push_back(s.proteins->at(i)); for(i=0;i<s.searchScores->size();i++) searchScores->push_back(s.searchScores->at(i)); for(i=0;i<s.xlScores->size();i++) xlScores->push_back(s.xlScores->at(i)); } ~PXWSearchHit(){ delete proteins; delete searchScores; delete xlScores; } PXWSearchHit& operator=(const PXWSearchHit& s){ if(this!=&s){ size_t i; hit_rank=s.hit_rank; peptide=s.peptide; num_tot_proteins=s.num_tot_proteins; calc_neutral_pep_mass=s.calc_neutral_pep_mass; calc_neutral_xl_mass=s.calc_neutral_xl_mass; massdiff=s.massdiff; xl_massdiff=s.xl_massdiff; modInfo=s.modInfo; xlink_type=s.xlink_type; delete proteins; delete searchScores; delete xlScores; proteins=new vector<pxwProtein>; searchScores=new vector<pxwBasicXMLTag>; xlScores=new vector<pxwBasicXMLTag>; for(i=0;i<s.proteins->size();i++) proteins->push_back(s.proteins->at(i)); for(i=0;i<s.searchScores->size();i++) searchScores->push_back(s.searchScores->at(i)); for(i=0;i<s.xlScores->size();i++) xlScores->push_back(s.xlScores->at(i)); } return *this; } void addProtein(pxwProtein& p){ proteins->push_back(p); } void addProtein(char* protein, char peptide_next_aa, char peptide_prev_aa, int protein_link_pos_a = 0, int protein_link_pos_b = 0){ pxwProtein p; p.protein=protein; p.peptide_next_aa=peptide_next_aa; p.peptide_prev_aa=peptide_prev_aa; p.protein_link_pos_a = protein_link_pos_a; p.protein_link_pos_b = protein_link_pos_b; addProtein(p); } void addProtein(string& protein, char peptide_next_aa, char peptide_prev_aa, int protein_link_pos_a = 0, int protein_link_pos_b = 0){ pxwProtein p; p.protein=protein; p.peptide_next_aa=peptide_next_aa; p.peptide_prev_aa=peptide_prev_aa; p.protein_link_pos_a=protein_link_pos_a; p.protein_link_pos_b=protein_link_pos_b; addProtein(p); } void addScore(pxwBasicXMLTag& s){ searchScores->push_back(s); } void addScore(const char* name, const char* value){ pxwBasicXMLTag x; x.name=name; x.value=value; addScore(x); } void addScore(string& name, string& value){ pxwBasicXMLTag x; x.name=name; x.value=value; addScore(x); } void addXLScore(pxwBasicXMLTag& s){ xlScores->push_back(s); } void addXLScore(const char* name, const char* value){ pxwBasicXMLTag x; x.name=name; x.value=value; addXLScore(x); } void addXLScore(string& name, string& value){ pxwBasicXMLTag x; x.name=name; x.value=value; addXLScore(x); } void clear(){ hit_rank=0; peptide.clear(); num_tot_proteins=0; calc_neutral_pep_mass=0; calc_neutral_xl_mass=0; massdiff=0; xl_massdiff=0; xlink_type="na"; modInfo.clear(); proteins->clear(); searchScores->clear(); xlScores->clear(); } pxwProtein& getProtein(int index){ return proteins->at(index); } pxwProtein& getProtein(size_t index){ return proteins->at(index); } pxwBasicXMLTag& getScore(int index){ return searchScores->at(index); } pxwBasicXMLTag& getScore(size_t index){ return searchScores->at(index); } pxwBasicXMLTag& getXLScore(int index){ return xlScores->at(index); } pxwBasicXMLTag& getXLScore(size_t index){ return xlScores->at(index); } size_t sizeProteins(){ return proteins->size(); } size_t sizeScores(){ return searchScores->size(); } size_t sizeXLScores(){ return xlScores->size(); } private: vector<pxwProtein>* proteins; vector<pxwBasicXMLTag>* searchScores; vector<pxwBasicXMLTag>* xlScores; }; typedef struct pxwSearchHitPair{ PXWSearchHit* a; PXWSearchHit* b; string identifier; double mass; pxwSearchHitPair(){ a=NULL; b=NULL; identifier.clear(); mass=0; } pxwSearchHitPair(const pxwSearchHitPair& p){ a=NULL; b=NULL; identifier=p.identifier; mass=p.mass; if(p.a!=NULL) { a=new PXWSearchHit(); *a=*p.a; } if(p.b!=NULL){ b=new PXWSearchHit(); *b=*p.b; } } ~pxwSearchHitPair(){ if(a!=NULL) delete a; if(b!=NULL) delete b; } pxwSearchHitPair& operator=(const pxwSearchHitPair& p){ if(this!=&p){ if(a!=NULL) delete a; if(b!=NULL) delete b; a=NULL; b=NULL; identifier=p.identifier; mass=p.mass; if(p.a!=NULL) { a=new PXWSearchHit(); *a=*p.a; } if(p.b!=NULL){ b=new PXWSearchHit(); *b=*p.b; } } return *this; } } pxwSearchHitPair; typedef struct pxwSampleEnzyme{ string name; string cut; string no_cut; string sense; int maxNumInternalCleavages; int minNumTermini; } pxwSampleEnzyme; class PXWSpectrumQuery { public: string spectrum; int start_scan; int end_scan; double retention_time_sec; double precursor_neutral_mass; int assumed_charge; PXWSpectrumQuery(){ spectrum.clear(); start_scan=0; end_scan=0; retention_time_sec=0; precursor_neutral_mass=0; assumed_charge=0; searchHits=new vector<pxwSearchHitPair>; } PXWSpectrumQuery(const PXWSpectrumQuery& s){ spectrum=s.spectrum; start_scan=s.start_scan; end_scan=s.end_scan; retention_time_sec=s.retention_time_sec; precursor_neutral_mass=s.precursor_neutral_mass; assumed_charge=s.assumed_charge; searchHits=new vector<pxwSearchHitPair>; for(size_t i=0;i<s.searchHits->size();i++) searchHits->push_back(s.searchHits->at(i)); } ~PXWSpectrumQuery(){ delete searchHits; } PXWSpectrumQuery& operator=(const PXWSpectrumQuery& s){ if(this!=&s){ spectrum=s.spectrum; start_scan=s.start_scan; end_scan=s.end_scan; retention_time_sec=s.retention_time_sec; precursor_neutral_mass=s.precursor_neutral_mass; assumed_charge=s.assumed_charge; delete searchHits; searchHits=new vector<pxwSearchHitPair>; for(size_t i=0;i<s.searchHits->size();i++) searchHits->push_back(s.searchHits->at(i)); } return *this; } void addSearchHit(PXWSearchHit* s, PXWSearchHit* s2=NULL, string* xl=NULL, double* xlMass=NULL){ pxwSearchHitPair p; p.a = new PXWSearchHit(*s); if(s2!=NULL) { if(xl==NULL || xlMass==NULL){ printf("PXWSpectrumQuery.addSearchHit(): cross-linked peptides must contain linker and mass. Exiting.\n"); exit(-4); } p.b = new PXWSearchHit(*s2); } if(xl!=NULL) p.identifier=*xl; if(xlMass!=NULL) p.mass=*xlMass; searchHits->push_back(p); } void clear(){ searchHits->clear(); } pxwSearchHitPair& getSearchHit(int index){ return searchHits->at(index); } pxwSearchHitPair& getSearchHit(size_t index){ return searchHits->at(index); } size_t sizeSearchHits(){ return searchHits->size(); } private: vector<pxwSearchHitPair>* searchHits; }; class PepXMLWriter { public: PepXMLWriter(); ~PepXMLWriter(); void closePepXML (); bool createPepXML (char* fn, pxwMSMSRunSummary& run, pxwSampleEnzyme* enzyme=NULL, PXWSearchSummary* search=NULL); void writeSpectrumQuery (PXWSpectrumQuery& s); private: void addTab (); void deleteTab (); void resetTabs (); void writeAltProtein (pxwProtein& s); void writeModAAMass (pxwModAA& s); void writeModInfo (PXWModInfo& s); void writeLine (const char* str); void writeLinkedPeptide (PXWSearchHit& s, bool alpha=true); void writeSearchHit (pxwSearchHitPair& s); int index; int iTabs; int spQueryIndex; FILE* fptr; bool bTabs; bool bFileOpen; char strTabs[128]; vector<string> vTagState; }; #endif
[ "vadim.demichev@gmail.com" ]
vadim.demichev@gmail.com
806a8f75fb35f04a20245dc14f00f1c678bd2399
3c5cbd017550731ecf086e0a093380d5228b6306
/raiders3d.cpp
a3d76886c3c95c5ef1fb2aed365bf0f4b5c70bac
[]
no_license
floatyears/Tricks-For-3D
2dcb01b8b43a98f348e8fc558daaf414f6576044
1639e328184b2be985253eb9ff655f70137415f6
refs/heads/master
2021-01-23T07:26:37.415295
2015-09-20T11:51:11
2015-09-20T11:51:11
37,061,073
0
0
null
null
null
null
UTF-8
C++
false
false
29,831
cpp
// Raiders3D - RAIDERS3D.CPP -- our first 3D game // READ THIS! // To compile make sure to include DDRAW.LIB, DSOUND.LIB, // DINPUT.LIB, WINMM.LIB in the project link list, and of course // the C++ source modules T3DLIB1.CPP,T3DLIB2.CPP, and T3DLIB3.CPP // in the project!!! And the T3DLIB1.H,T3DLIB2.H, and T3DLIB3.H // header files in the working directory, so the compiler // can find them // to run the game make sure that your desktop is in 16bit // color mode with a resolution of 640x480 or higher // INCLUDES /////////////////////////////////////////////// #define INITGUID // make sure al the COM interfaces are available // instead of this you can include the .LIB file // DXGUID.LIB #define WIN32_LEAN_AND_MEAN #include <windows.h> // include important windows stuff #include <windowsx.h> #include <mmsystem.h> #include <iostream> // include important C/C++ stuff #include <conio.h> #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <string.h> #include <stdarg.h> #include <stdio.h> #include <math.h> #include <io.h> #include <fcntl.h> #include <ddraw.h> // directX includes #include <dsound.h> #include <dmksctrl.h> //#include <dmusici.h> #include <dmusicc.h> //#include <dmusicf.h> #include <dinput.h> #include "T3DLIB1.h" // game library includes #include "T3DLIB2.h" #include "T3DLIB3.h" // DEFINES //////////////////////////////////////////////// // defines for windows interface #define WINDOW_CLASS_NAME "WIN3DCLASS" // class name #define WINDOW_TITLE "T3D Graphics Console Ver 2.0" #define WINDOW_WIDTH 640 // size of window #define WINDOW_HEIGHT 480 #define WINDOW_BPP 16 // bitdepth of window (8,16,24 etc.) // note: if windowed and not // fullscreen then bitdepth must // be same as system bitdepth // also if 8-bit the a pallete // is created and attached #define WINDOWED_APP 1 // 0 not windowed, 1 windowed //////////////////////////////////////////////////////////// #define NUM_STARS 512 // number of stars in sim #define NUM_TIES 32 // number of tie fighters in sim // 3D engine constants #define NEAR_Z 10 // the near clipping plane #define FAR_Z 2000 // the far clipping plane #define VIEW_DISTANCE 320 // viewing distance from viewpoint // this gives a field of view of 90 degrees // when projected on a window of 640 wide // player constants #define CROSS_VEL 8 // speed that the cross hair moves #define PLAYER_Z_VEL 8 // virtual z velocity that player is moving // to simulate motion without moving // tie fighter model constants #define NUM_TIE_VERTS 10 #define NUM_TIE_EDGES 8 // explosiond #define NUM_EXPLOSIONS (NUM_TIES) // total number of explosions // game states #define GAME_RUNNING 1 #define GAME_OVER 0 // TYPES /////////////////////////////////////////////////// // this a 3D point typedef struct POINT3D_TYP { USHORT color; // color of point 16-bit float x,y,z; // coordinates of point in 3D } POINT3D, *POINT3D_PTR; // this is a 3D line, nothing more than two indices into a vertex list typedef struct LINE3D_TYP { USHORT color; // color of line 16-bit int v1,v2; // indices to endpoints of line in vertex list } LINE3D, *LINE3D_PTR; // a tie fighter typedef struct TIE_TYP { int state; // state of the tie, 0=dead, 1=alive float x, y, z; // position of the tie float xv,yv,zv; // velocity of the tie } TIE, *TIE_PTR; // a basic 3D vector used for velocity typedef struct VEC3D_TYP { float x,y,z; // coords of vector } VEC3D, *VEC3D_PTR; // a wireframe explosion typedef struct EXPL_TYP { int state; // state of explosion int counter; // counter for explosion USHORT color; // color of explosion // an explosion is a collection of edges/lines // based on the 3D model of the tie that is exploding POINT3D p1[NUM_TIE_EDGES]; // start point of edge n POINT3D p2[NUM_TIE_EDGES]; // end point of edge n VEC3D vel[NUM_TIE_EDGES]; // velocity of shrapnel } EXPL, *EXPL_PTR; // PROTOTYPES ///////////////////////////////////////////// // game console int Game_Init(void *parms=NULL); int Game_Shutdown(void *parms=NULL); int Game_Main(void *parms=NULL); // game functions void Init_Tie(int index); // GLOBALS //////////////////////////////////////////////// HWND main_window_handle = NULL; // save the window handle HINSTANCE main_instance = NULL; // save the instance char buffer[256]; // used to print text // the tie fighter is a collection of vertices connected by // lines that make up the shape. only one tie fighter see if // you can replicate it? POINT3D tie_vlist[NUM_TIE_VERTS]; // vertex list for the tie fighter model LINE3D tie_shape[NUM_TIE_EDGES]; // edge list for the tie fighter model TIE ties[NUM_TIES]; // tie fighters POINT3D stars[NUM_STARS]; // the starfield // some colors, note we can't build them until we know the bit // depth format 5.5.5 or 5.6.5, so we wait a minute and do it in the // Game_Init() function USHORT rgb_green, rgb_white, rgb_red, rgb_blue; // player vars float cross_x = 0, // cross hairs cross_y = 0; int cross_x_screen = WINDOW_WIDTH/2, // used for cross hair cross_y_screen = WINDOW_HEIGHT/2, target_x_screen = WINDOW_WIDTH/2, // used for targeter target_y_screen = WINDOW_HEIGHT/2; int player_z_vel = 4; // virtual speed of viewpoint/ship int cannon_state = 0; // state of laser cannon int cannon_count = 0; // laster cannon counter EXPL explosions[NUM_EXPLOSIONS]; // the explosiions int misses = 0; // tracks number of missed ships int hits = 0; // tracks number of hits int score = 0; // take a guess :) // music and sound stuff int main_track_id = -1, // main music track id laser_id = -1, // sound of laser pulse explosion_id = -1, // sound of explosion flyby_id = -1; // sound of tie fighter flying by int game_state = GAME_RUNNING; // state of game // FUNCTIONS ////////////////////////////////////////////// LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { // this is the main message handler of the system PAINTSTRUCT ps; // used in WM_PAINT HDC hdc; // handle to a device context // what is the message switch(msg) { case WM_CREATE: { // do initialization stuff here return(0); } break; case WM_PAINT: { // start painting hdc = BeginPaint(hwnd,&ps); // end painting EndPaint(hwnd,&ps); return(0); } break; case WM_DESTROY: { // kill the application PostQuitMessage(0); return(0); } break; default:break; } // end switch // process any messages that we didn't take care of return (DefWindowProc(hwnd, msg, wparam, lparam)); } // end WinProc // WINMAIN //////////////////////////////////////////////// int WINAPI WinMain( HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpcmdline, int ncmdshow) { // this is the winmain function WNDCLASS winclass; // this will hold the class we create HWND hwnd; // generic window handle MSG msg; // generic message HDC hdc; // generic dc PAINTSTRUCT ps; // generic paintstruct // first fill in the window class stucture winclass.style = CS_DBLCLKS | CS_OWNDC | CS_HREDRAW | CS_VREDRAW; winclass.lpfnWndProc = WindowProc; winclass.cbClsExtra = 0; winclass.cbWndExtra = 0; winclass.hInstance = hinstance; winclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); winclass.hCursor = LoadCursor(NULL, IDC_ARROW); winclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); winclass.lpszMenuName = NULL; winclass.lpszClassName = WINDOW_CLASS_NAME; // register the window class if (!RegisterClass(&winclass)) return(0); // create the window, note the test to see if WINDOWED_APP is // true to select the appropriate window flags if (!(hwnd = CreateWindow(WINDOW_CLASS_NAME, // class WINDOW_TITLE, // title (WINDOWED_APP ? (WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION) : (WS_POPUP | WS_VISIBLE)), 0,0, // x,y WINDOW_WIDTH, // width WINDOW_HEIGHT, // height NULL, // handle to parent NULL, // handle to menu hinstance,// instance NULL))) // creation parms return(0); // save the window handle and instance in a global main_window_handle = hwnd; main_instance = hinstance; // resize the window so that client is really width x height if (WINDOWED_APP) { // now resize the window, so the client area is the actual size requested // since there may be borders and controls if this is going to be a windowed app // if the app is not windowed then it won't matter RECT window_rect = {0,0,WINDOW_WIDTH-1,WINDOW_HEIGHT-1}; // make the call to adjust window_rect AdjustWindowRectEx(&window_rect, GetWindowStyle(main_window_handle), GetMenu(main_window_handle) != NULL, GetWindowExStyle(main_window_handle)); // save the global client offsets, they are needed in DDraw_Flip() window_client_x0 = -window_rect.left; window_client_y0 = -window_rect.top; // now resize the window with a call to MoveWindow() MoveWindow(main_window_handle, 0, // x position 0, // y position window_rect.right - window_rect.left, // width window_rect.bottom - window_rect.top, // height FALSE); // show the window, so there's no garbage on first render ShowWindow(main_window_handle, SW_SHOW); } // end if windowed // perform all game console specific initialization Game_Init(); // disable CTRL-ALT_DEL, ALT_TAB, comment this line out // if it causes your system to crash SystemParametersInfo(SPI_SCREENSAVERRUNNING, TRUE, NULL, 0); // enter main event loop while(1) { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { // test if this is a quit if (msg.message == WM_QUIT) break; // translate any accelerator keys TranslateMessage(&msg); // send the message to the window proc DispatchMessage(&msg); } // end if // main game processing goes here Game_Main(); } // end while // shutdown game and release all resources Game_Shutdown(); // enable CTRL-ALT_DEL, ALT_TAB, comment this line out // if it causes your system to crash SystemParametersInfo(SPI_SCREENSAVERRUNNING, FALSE, NULL, 0); // return to Windows like this return(msg.wParam); } // end WinMain // T3D II GAME PROGRAMMING CONSOLE FUNCTIONS //////////////// int Game_Init(void *parms) { // this function is where you do all the initialization // for your game int index; // used for looping Open_Error_File("error.txt"); // start up DirectDraw (replace the parms as you desire) DDraw_Init(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_BPP, WINDOWED_APP); // initialize directinput DInput_Init(); // acquire the keyboard DInput_Init_Keyboard(); // initialize directsound DSound_Init(); // load in sound fx explosion_id = DSound_Load_WAV("exp1.wav"); laser_id = DSound_Load_WAV("shocker.wav"); // initialize directmusic //DMusic_Init(); // load and start main music track //main_track_id = DMusic_Load_MIDI("midifile2.mid"); //DMusic_Play(main_track_id); // add calls to acquire other directinput devices here... // hide the mouse if (!WINDOWED_APP) ShowCursor(FALSE); // seed random number generator srand(Start_Clock()); // all your initialization code goes here... // create system colors rgb_green = RGB16Bit(0,255,0); rgb_white = RGB16Bit(255,255,255); rgb_blue = RGB16Bit(0,0,255); rgb_red = RGB16Bit(255,0,0); // create the starfield for (index=0; index < NUM_STARS; index++) { // randomly position stars in an elongated cylinder stretching from // the viewpoint 0,0,-d to the yon clipping plane 0,0,far_z stars[index].x = -WINDOW_WIDTH/2 + rand()%WINDOW_WIDTH; stars[index].y = -WINDOW_HEIGHT/2 + rand()%WINDOW_HEIGHT; stars[index].z = NEAR_Z + rand()%(FAR_Z - NEAR_Z); // set color of stars stars[index].color = rgb_white; } // end for index // create the tie fighter model // the vertex list for the tie fighter POINT3D temp_tie_vlist[NUM_TIE_VERTS] = // color, x,y,z { {rgb_white,-40,40,0}, // p0 {rgb_white,-40,0,0}, // p1 {rgb_white,-40,-40,0}, // p2 {rgb_white,-10,0,0}, // p3 {rgb_white,0,20,0}, // p4 {rgb_white,10,0,0}, // p5 {rgb_white,0,-20,0}, // p6 {rgb_white,40,40,0}, // p7 {rgb_white,40,0,0}, // p8 {rgb_white,40,-40,0}}; // p9 // copy the model into the real global arrays for (index=0; index<NUM_TIE_VERTS; index++) tie_vlist[index] = temp_tie_vlist[index]; // the edge list for the tie fighter LINE3D temp_tie_shape[NUM_TIE_EDGES] = // color, vertex 1, vertex 2 { {rgb_green,0,2 }, // l0 {rgb_green,1,3 }, // l1 {rgb_green,3,4 }, // l2 {rgb_green,4,5 }, // l3 {rgb_green,5,6 }, // l4 {rgb_green,6,3 }, // l5 {rgb_green,5,8 }, // l6 {rgb_green,7,9 } }; // l7 // copy the model into the real global arrays for (index=0; index<NUM_TIE_EDGES; index++) tie_shape[index] = temp_tie_shape[index]; // initialize the position of each tie fighter and it's velocity for (index=0; index<NUM_TIES; index++) { // initialize this tie fighter Init_Tie(index); } // end for index // return success return(1); } // end Game_Init /////////////////////////////////////////////////////////// int Game_Shutdown(void *parms) { // this function is where you shutdown your game and // release all resources that you allocated // shut everything down // release all your resources created for the game here.... // now directsound DSound_Stop_All_Sounds(); DSound_Shutdown(); // directmusic //DMusic_Delete_All_MIDI(); //DMusic_Shutdown(); // shut down directinput DInput_Shutdown(); // shutdown directdraw last DDraw_Shutdown(); // return success return(1); } // end Game_Shutdown ////////////////////////////////////////////////////////// void Start_Explosion(int tie) { // this starts an explosion based on the sent tie fighter // first hunt and see if an explosion is free for (int index=0; index < NUM_EXPLOSIONS; index++) { if (explosions[index].state==0) { // start this explosion up using the properties // if the tie figther index sent explosions[index].state = 1; // enable state of explosion explosions[index].counter = 0; // reset counter for explosion // set color of explosion explosions[index].color = rgb_green; // make copy of of edge list, so we can blow it up for (int edge=0; edge < NUM_TIE_EDGES; edge++) { // start point of edge explosions[index].p1[edge].x = ties[tie].x+tie_vlist[tie_shape[edge].v1].x; explosions[index].p1[edge].y = ties[tie].y+tie_vlist[tie_shape[edge].v1].y; explosions[index].p1[edge].z = ties[tie].z+tie_vlist[tie_shape[edge].v1].z; // end point of edge explosions[index].p2[edge].x = ties[tie].x+tie_vlist[tie_shape[edge].v2].x; explosions[index].p2[edge].y = ties[tie].y+tie_vlist[tie_shape[edge].v2].y; explosions[index].p2[edge].z = ties[tie].z+tie_vlist[tie_shape[edge].v2].z; // compute trajectory vector for edges explosions[index].vel[edge].x = ties[tie].xv - 8+rand()%16; explosions[index].vel[edge].y = ties[tie].yv - 8+rand()%16; explosions[index].vel[edge].z = -3+rand()%4; } // end for edge // done, so return return; } // end if found } // end for index } // end Start_Explosion /////////////////////////////////////////////////////////// void Process_Explosions(void) { // this processes all the explosions // loop thro all the explosions and render them for (int index=0; index<NUM_EXPLOSIONS; index++) { // test if this explosion is active? if (explosions[index].state==0) continue; for (int edge=0; edge<NUM_TIE_EDGES; edge++) { // must be exploding, update edges (shrapel) explosions[index].p1[edge].x+=explosions[index].vel[edge].x; explosions[index].p1[edge].y+=explosions[index].vel[edge].y; explosions[index].p1[edge].z+=explosions[index].vel[edge].z; explosions[index].p2[edge].x+=explosions[index].vel[edge].x; explosions[index].p2[edge].y+=explosions[index].vel[edge].y; explosions[index].p2[edge].z+=explosions[index].vel[edge].z; } // end for edge // test for terminatation of explosion? if (++explosions[index].counter > 100) explosions[index].state = explosions[index].counter = 0; } // end for index } // end Process_Explosions /////////////////////////////////////////////////////////// void Draw_Explosions(void) { // this draws all the explosions // loop thro all the explosions and render them for (int index=0; index<NUM_EXPLOSIONS; index++) { // test if this explosion is active? if (explosions[index].state==0) continue; // render this explosion // each explosion is made of a number of edges for (int edge=0; edge < NUM_TIE_EDGES; edge++) { POINT3D p1_per, p2_per; // used to hold perspective endpoints // test if edge if beyond near clipping plane if (explosions[index].p1[edge].z < NEAR_Z && explosions[index].p2[edge].z < NEAR_Z) continue; // step 1: perspective transform each end point p1_per.x = VIEW_DISTANCE*explosions[index].p1[edge].x/explosions[index].p1[edge].z; p1_per.y = VIEW_DISTANCE*explosions[index].p1[edge].y/explosions[index].p1[edge].z; p2_per.x = VIEW_DISTANCE*explosions[index].p2[edge].x/explosions[index].p2[edge].z; p2_per.y = VIEW_DISTANCE*explosions[index].p2[edge].y/explosions[index].p2[edge].z; // step 2: compute screen coords int p1_screen_x = WINDOW_WIDTH/2 + p1_per.x; int p1_screen_y = WINDOW_HEIGHT/2 - p1_per.y; int p2_screen_x = WINDOW_WIDTH/2 + p2_per.x; int p2_screen_y = WINDOW_HEIGHT/2 - p2_per.y; // step 3: draw the edge Draw_Clip_Line16(p1_screen_x, p1_screen_y, p2_screen_x, p2_screen_y, explosions[index].color,back_buffer, back_lpitch); } // end for edge } // end for index } // end Draw_Explosions ////////////////////////////////////////////////////////// void Move_Starfield(void) { // move the stars int index; // looping var // the stars are technically stationary,but we are going // to move them to simulate motion of the viewpoint for (index=0; index<NUM_STARS; index++) { // move the next star stars[index].z-=player_z_vel; // test for past near clipping plane if (stars[index].z <= NEAR_Z) stars[index].z = FAR_Z; } // end for index } // end Move_Starfield ///////////////////////////////////////////////////////// void Draw_Starfield(void) { // draw the stars in 3D using perspective transform int index; // looping var for (index=0; index<NUM_STARS; index++) { // draw the next star // step 1: perspective transform float x_per = VIEW_DISTANCE*stars[index].x/stars[index].z; float y_per = VIEW_DISTANCE*stars[index].y/stars[index].z; // step 2: compute screen coords int x_screen = WINDOW_WIDTH/2 + x_per; int y_screen = WINDOW_HEIGHT/2 - y_per; // clip to screen coords if (x_screen>=WINDOW_WIDTH || x_screen < 0 || y_screen >= WINDOW_HEIGHT || y_screen < 0) { // continue to next star continue; } // end if else { // else render to buffer ((USHORT *)back_buffer)[x_screen + y_screen*(back_lpitch >> 1)] = stars[index].color; } // end else } // end for index } // Draw_Starfield ///////////////////////////////////////////////////////// void Init_Tie(int index) { // this function starts a tie fighter up at the far end // of the universe and sends it our way! // position each tie in the viewing volume ties[index].x = -WINDOW_WIDTH + rand()%(2*WINDOW_WIDTH); ties[index].y = -WINDOW_HEIGHT + rand()%(2*WINDOW_HEIGHT); ties[index].z = 4*FAR_Z; // initialize velocity of tie fighter ties[index].xv = -4+rand()%8; ties[index].yv = -4+rand()%8; ties[index].zv = -4-rand()%64; // turn the tie fighter on ties[index].state = 1; } // end Init_Tie ///////////////////////////////////////////////////////// void Process_Ties(void) { // process the tie fighters and do AI (what there is of it!) int index; // looping var // move each tie fighter toward the viewpoint for (index=0; index<NUM_TIES; index++) { // is this one dead? if (ties[index].state==0) continue; // move the next star ties[index].z+=ties[index].zv; ties[index].x+=ties[index].xv; ties[index].y+=ties[index].yv; // test for past near clipping plane if (ties[index].z <= NEAR_Z) { // reset this tie Init_Tie(index); // another got away misses++; } // reset tie } // end for index } // Process_Ties ////////////////////////////////////////////////////////// void Draw_Ties(void) { // draw the tie fighters in 3D wireframe with perspective int index; // looping var // used to compute the bounding box of tie fighter // for collision detection int bmin_x, bmin_y, bmax_x, bmax_y; // draw each tie fighter for (index=0; index < NUM_TIES; index++) { // draw the next tie fighter // is this one dead? if (ties[index].state==0) continue; // reset the bounding box to impossible values bmin_x = 100000; bmax_x = -100000; bmin_y = 100000; bmax_y = -100000; // based on z-distance shade tie fighter // normalize the distance from 0 to max_z then // scale it to 255, so the closer the brighter USHORT rgb_tie_color = RGB16Bit(0,(255-255*(ties[index].z/(4*FAR_Z))),0); // each tie fighter is made of a number of edges for (int edge=0; edge < NUM_TIE_EDGES; edge++) { POINT3D p1_per, p2_per; // used to hold perspective endpoints // step 1: perspective transform each end point // note the translation of each point to the position of the tie fighter // that is the model is relative to the position of each tie fighter -- IMPORTANT p1_per.x = VIEW_DISTANCE*(ties[index].x+tie_vlist[tie_shape[edge].v1].x)/ (tie_vlist[tie_shape[edge].v1].z+ties[index].z); p1_per.y = VIEW_DISTANCE*(ties[index].y+tie_vlist[tie_shape[edge].v1].y)/ (tie_vlist[tie_shape[edge].v1].z+ties[index].z); p2_per.x = VIEW_DISTANCE*(ties[index].x+tie_vlist[tie_shape[edge].v2].x)/ (tie_vlist[tie_shape[edge].v2].z+ties[index].z); p2_per.y = VIEW_DISTANCE*(ties[index].y+tie_vlist[tie_shape[edge].v2].y)/ (tie_vlist[tie_shape[edge].v2].z+ties[index].z); // step 2: compute screen coords int p1_screen_x = WINDOW_WIDTH/2 + p1_per.x; int p1_screen_y = WINDOW_HEIGHT/2 - p1_per.y; int p2_screen_x = WINDOW_WIDTH/2 + p2_per.x; int p2_screen_y = WINDOW_HEIGHT/2 - p2_per.y; // step 3: draw the edge Draw_Clip_Line16(p1_screen_x, p1_screen_y, p2_screen_x, p2_screen_y, rgb_tie_color,back_buffer, back_lpitch); // update bounding box with next edge int min_x = min(p1_screen_x, p2_screen_x); int max_x = max(p1_screen_x, p2_screen_x); int min_y = min(p1_screen_y, p2_screen_y); int max_y = max(p1_screen_y, p2_screen_y); bmin_x = min(bmin_x, min_x); bmin_y = min(bmin_y, min_y); bmax_x = max(bmax_x, max_x); bmax_y = max(bmax_y, max_y); } // end for edge // test if this guy has been hit by lasers??? if (cannon_state==1) { // simple test of screen coords of bounding box contain laser target if (target_x_screen > bmin_x && target_x_screen < bmax_x && target_y_screen > bmin_y && target_y_screen < bmax_y) { // this tie is dead meat! Start_Explosion(index); // start sound DSound_Play(explosion_id ); // increase score score+=ties[index].z; // add one more hit hits++; // finally reset this tie figher Init_Tie(index); } // end if } // end if } // end for index } // end Draw_Ties ////////////////////////////////////////////////////////// int Game_Main(void *parms) { // this is the workhorse of your game it will be called // continuously in real-time this is like main() in C // all the calls for your game go here! int index; // looping var // start the timing clock Start_Clock(); // clear the drawing surface DDraw_Fill_Surface(lpddsback, 0); // read keyboard and other devices here DInput_Read_Keyboard(); // game logic here... if (game_state==GAME_RUNNING) { // move players crosshair if (keyboard_state[DIK_RIGHT]) { // move cross hair to right cross_x+=CROSS_VEL; // test for wraparound if (cross_x > WINDOW_WIDTH/2) cross_x = -WINDOW_WIDTH/2; } // end if if (keyboard_state[DIK_LEFT]) { // move cross hair to left cross_x-=CROSS_VEL; // test for wraparound if (cross_x < -WINDOW_WIDTH/2) cross_x = WINDOW_WIDTH/2; } // end if if (keyboard_state[DIK_DOWN]) { // move cross hair up cross_y-=CROSS_VEL; // test for wraparound if (cross_y < -WINDOW_HEIGHT/2) cross_y = WINDOW_HEIGHT/2; } // end if if (keyboard_state[DIK_UP]) { // move cross hair up cross_y+=CROSS_VEL; // test for wraparound if (cross_y > WINDOW_HEIGHT/2) cross_y = -WINDOW_HEIGHT/2; } // end if // speed of ship controls if (keyboard_state[DIK_A]) player_z_vel++; else if (keyboard_state[DIK_S]) player_z_vel--; // test if player is firing laser cannon if (keyboard_state[DIK_SPACE] && cannon_state==0) { // fire the cannon cannon_state = 1; cannon_count = 0; // save last position of targeter target_x_screen = cross_x_screen; target_y_screen = cross_y_screen; // make sound DSound_Play(laser_id); } // end if } // end if game running // process cannon, simple FSM ready->firing->cool // firing phase if (cannon_state == 1) if (++cannon_count > 15) cannon_state = 2; // cool down phase if (cannon_state == 2) if (++cannon_count > 20) cannon_state = 0; // move the starfield Move_Starfield(); // move and perform ai for ties Process_Ties(); // Process the explosions Process_Explosions(); // lock the back buffer and obtain pointer and width DDraw_Lock_Back_Surface(); // draw the starfield Draw_Starfield(); // draw the tie fighters Draw_Ties(); // draw the explosions Draw_Explosions(); // draw the crosshairs // first compute screen coords of crosshair // note inversion of y-axis cross_x_screen = WINDOW_WIDTH/2 + cross_x; cross_y_screen = WINDOW_HEIGHT/2 - cross_y; // draw the crosshair in screen coords Draw_Clip_Line16(cross_x_screen-16,cross_y_screen, cross_x_screen+16,cross_y_screen, rgb_red,back_buffer,back_lpitch); Draw_Clip_Line16(cross_x_screen,cross_y_screen-16, cross_x_screen,cross_y_screen+16, rgb_red,back_buffer,back_lpitch); Draw_Clip_Line16(cross_x_screen-16,cross_y_screen-4, cross_x_screen-16,cross_y_screen+4, rgb_red,back_buffer,back_lpitch); Draw_Clip_Line16(cross_x_screen+16,cross_y_screen-4, cross_x_screen+16,cross_y_screen+4, rgb_red,back_buffer,back_lpitch); // draw the laser beams if (cannon_state == 1) { if ((rand()%2 == 1)) { // right beam Draw_Clip_Line16(WINDOW_WIDTH-1, WINDOW_HEIGHT-1, -4+rand()%8+target_x_screen,-4+rand()%8+target_y_screen, RGB16Bit(0,0,rand()),back_buffer,back_lpitch); } // end if else { // left beam Draw_Clip_Line16(0, WINDOW_HEIGHT-1, -4+rand()%8+target_x_screen,-4+rand()%8+target_y_screen, RGB16Bit(0,0,rand()),back_buffer,back_lpitch); } // end if } // end if // done rendering, unlock back buffer surface DDraw_Unlock_Back_Surface(); // draw the informtion sprintf(buffer, "Score %d Kills %d Escaped %d", score, hits, misses); Draw_Text_GDI(buffer, 0,0,RGB(0,255,0), lpddsback); if (game_state==GAME_OVER) Draw_Text_GDI("G A M E O V E R", WINDOW_WIDTH/2-8*10,WINDOW_HEIGHT/2,RGB(255,255,255), lpddsback); // check if the music has finished, if so restart //if (DMusic_Status_MIDI(main_track_id)==MIDI_STOPPED) // DMusic_Play(main_track_id); // flip the surfaces DDraw_Flip(); // sync to 30ish fps Wait_Clock(30); // check for game state switch if (misses > 4*NUM_TIES) game_state = GAME_OVER; // check of user is trying to exit if (KEY_DOWN(VK_ESCAPE) || keyboard_state[DIK_ESCAPE]) { PostMessage(main_window_handle, WM_DESTROY,0,0); } // end if // return success return(1); } // end Game_Main //////////////////////////////////////////////////////////
[ "floatyears@californiacolleges.edu" ]
floatyears@californiacolleges.edu
bc8bf7aee8be26a6abe69f99e1dd85e85c8954d9
ab0a8234e443a6aa152b9f7b135a1e2560e9db33
/Server/CGSF/DatabaseLayer/SFMySQLAdaptor.h
f8b93a3c1cf43dc20a48783874c27377331d92c3
[]
no_license
zetarus/Americano
71c358d8d12b144c8858983c23d9236f7d0e941b
b62466329cf6f515661ef9fb9b9d2ae90a032a60
refs/heads/master
2023-04-08T04:26:29.043048
2018-04-19T11:21:14
2018-04-19T11:21:14
104,159,178
9
2
null
2023-03-23T12:10:51
2017-09-20T03:11:44
C++
UTF-8
C++
false
false
310
h
#pragma once #include "SFDBAdaptor.h" class SFMySQL; class SFMySQLAdaptor : public SFDBAdaptor { public: SFMySQLAdaptor(void); virtual ~SFMySQLAdaptor(void); SFMySQL* GetObject(){return m_pMySql;} protected: virtual BOOL Initialize(_DBConnectionInfo* pInfo) override; private: SFMySQL* m_pMySql; };
[ "sinyonzzang@gmail.com" ]
sinyonzzang@gmail.com
a82a69d4853f2541c6fbb86bebf0f6ba014e7e0f
e7e9d77d7fb7eee4d823cf94a586a5fa751d7054
/ptm_tm/plugin/tests/units/thrwctch_004.cc
5cb9aadd8be80f18d04e9b115977dbc8f5a6b003
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
mfs409/llvm-transmem
5b5b35dbf3bb89fe2e7013418177bbc78b872cd2
92bd8c320bc12113ce6e4b1aba1243af6475bef9
refs/heads/master
2021-07-08T12:33:04.943298
2020-08-05T01:45:26
2020-08-05T01:45:26
159,760,878
11
3
null
null
null
null
UTF-8
C++
false
false
1,313
cc
// Test of throw/catch behaviors // // When a transaction throws, and the exception is supposed to escape the // transaction, we should have one unsafe for the throw, and the transaction // should still commit. // // NB: "the transaction should still commit" is something that our actual TM // libraries may fail to do, e.g., if they are instantiated with // "NOEXCEPT" macros. This test uses CountingTM, which is // exception-safe, so this test should pass. #ifdef TEST_DRIVER #include "../include/harness.h" int test_catch_outside_tx(); int main() { report<int>("thrwctch_004", "Catch outside of transaction", {{test_catch_outside_tx(), 0}}, {{TM_STATS_UNSAFE, 1}, {TM_STATS_END_OUTER, 1}, {TM_STATS_TRANSLATE_NOTFOUND, 0}}); } #endif #ifdef TEST_OFILE1 #include "../../../common/tm_api.h" TX_SAFE int throw_dont_catch(int a) { int res = a * 2; if (a < 0) throw 1; return res; } #endif #ifdef TEST_OFILE2 #include <iostream> #include "../../../common/tm_api.h" int throw_dont_catch(int a); int test_catch_outside_tx() { try { TX_BEGIN { throw_dont_catch(-7); } TX_END; // should still commit } catch (int &i) { if (i != 1) { std::cout << "Error: {1} != {" << i << "}\n"; } } return 0; } #endif
[ "spear@lehigh.edu" ]
spear@lehigh.edu
f4481f7bdc0645d5a2401fcc14e584932cde02a7
378477ea0143d556fb3d01778e00fd572f555355
/Box2DGame/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h
276fa4f11f0aa7466c5d26d99853bc2e5d16d9f8
[]
no_license
joe564338/Box2dGame
2769c3979702ca4c90b2e7f67be91bab445651cd
cae624c11bc58a737c1c56fbbf832e9d382a3dd8
refs/heads/master
2021-08-24T21:06:21.851785
2017-11-21T12:07:39
2017-11-21T12:07:39
111,252,418
0
0
null
null
null
null
UTF-8
C++
false
false
1,494
h
/* * Copyright (c) 2006-2009 Erin Catto http://www.../.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef B2_EDGE_AND_POLYGON_CONTACT_H #define B2_EDGE_AND_POLYGON_CONTACT_H #include "b2Contact.h" class b2BlockAllocator; class b2EdgeAndPolygonContact : public b2Contact { public: static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); ~b2EdgeAndPolygonContact() {} void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override; }; #endif
[ "jmccully88@yahoo.com" ]
jmccully88@yahoo.com