blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8a57c1f387fc75f0a08327c83b976d48af2a6d59 | 04c8b70ffac1a9da918130627fc3f03ac733a4e1 | /devel/include/comp0037_mapper/RequestMapUpdateResponse.h | 79a6f439efc1c8abbf8fa0feabf754933e5a9adc | [] | no_license | AtomAnu/COMP0037_CW3 | 8a9340735727435a5a49dff034235f04ea2d1d52 | c1672a94c6817c4a36f74655f4780702c765f6b2 | refs/heads/master | 2022-04-24T16:28:59.579031 | 2020-04-27T21:22:25 | 2020-04-27T21:22:25 | 258,858,993 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,736 | h | // Generated by gencpp from file comp0037_mapper/RequestMapUpdateResponse.msg
// DO NOT EDIT!
#ifndef COMP0037_MAPPER_MESSAGE_REQUESTMAPUPDATERESPONSE_H
#define COMP0037_MAPPER_MESSAGE_REQUESTMAPUPDATERESPONSE_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>
#include <comp0037_mapper/MapUpdate.h>
namespace comp0037_mapper
{
template <class ContainerAllocator>
struct RequestMapUpdateResponse_
{
typedef RequestMapUpdateResponse_<ContainerAllocator> Type;
RequestMapUpdateResponse_()
: initialMapUpdate() {
}
RequestMapUpdateResponse_(const ContainerAllocator& _alloc)
: initialMapUpdate(_alloc) {
(void)_alloc;
}
typedef ::comp0037_mapper::MapUpdate_<ContainerAllocator> _initialMapUpdate_type;
_initialMapUpdate_type initialMapUpdate;
typedef boost::shared_ptr< ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> const> ConstPtr;
}; // struct RequestMapUpdateResponse_
typedef ::comp0037_mapper::RequestMapUpdateResponse_<std::allocator<void> > RequestMapUpdateResponse;
typedef boost::shared_ptr< ::comp0037_mapper::RequestMapUpdateResponse > RequestMapUpdateResponsePtr;
typedef boost::shared_ptr< ::comp0037_mapper::RequestMapUpdateResponse const> RequestMapUpdateResponseConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace comp0037_mapper
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'comp0037_mapper': ['/home/ros_user/COMP0037_CW3/src/comp0037_mapper/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< ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> >
{
static const char* value()
{
return "c38a84a7069507e7645c74bfe20d6807";
}
static const char* value(const ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xc38a84a7069507e7ULL;
static const uint64_t static_value2 = 0x645c74bfe20d6807ULL;
};
template<class ContainerAllocator>
struct DataType< ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> >
{
static const char* value()
{
return "comp0037_mapper/RequestMapUpdateResponse";
}
static const char* value(const ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> >
{
static const char* value()
{
return "comp0037_mapper/MapUpdate initialMapUpdate\n\
\n\
================================================================================\n\
MSG: comp0037_mapper/MapUpdate\n\
Header header\n\
\n\
bool isPriorMap\n\
\n\
float32 scale\n\
int16[] extentInCells\n\
float32 resolution\n\
\n\
float32[] occupancyGrid\n\
float32[] deltaOccupancyGrid\n\
================================================================================\n\
MSG: std_msgs/Header\n\
# Standard metadata for higher-level stamped data types.\n\
# This is generally used to communicate timestamped data \n\
# in a particular coordinate frame.\n\
# \n\
# sequence ID: consecutively increasing ID \n\
uint32 seq\n\
#Two-integer timestamp that is expressed as:\n\
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\
# time-handling sugar is provided by the client library\n\
time stamp\n\
#Frame this data is associated with\n\
# 0: no frame\n\
# 1: global frame\n\
string frame_id\n\
";
}
static const char* value(const ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.initialMapUpdate);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct RequestMapUpdateResponse_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::comp0037_mapper::RequestMapUpdateResponse_<ContainerAllocator>& v)
{
s << indent << "initialMapUpdate: ";
s << std::endl;
Printer< ::comp0037_mapper::MapUpdate_<ContainerAllocator> >::stream(s, indent + " ", v.initialMapUpdate);
}
};
} // namespace message_operations
} // namespace ros
#endif // COMP0037_MAPPER_MESSAGE_REQUESTMAPUPDATERESPONSE_H
| [
"a.anuchitanukul@gmail.com"
] | a.anuchitanukul@gmail.com |
c90dcc6b7f732478151293d4505b59812f6ca99f | 9b8f76b321fe389d8272455883e42ed6b1c00c55 | /Exercícios C/Exercício de modulo.cpp | c6f03db1f110ffd84848fba06582699f6811d1c4 | [] | no_license | GabrielsNN-98/Atividades-Senai | 0e9842709e96e06e1b68fe31bb22acf2fcf6018c | c9b3e193c0b874c1c7a4bf768f1ee9f360ab1cc7 | refs/heads/master | 2021-01-05T07:25:47.738571 | 2020-02-16T19:27:45 | 2020-02-16T19:27:45 | 240,930,813 | 2 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 930 | cpp | #include<conio.h>
#include<stdio.h>
#include<locale.h>
int n1,n2,op;
void lerDados(){
printf("Informe dois números: \n\n");
scanf("\n\n%d %d",&n1,&n2);
printf("\n\nAgora, informe o tipo de operação que queira fazer digitando o número correspondente a mesma. \n(1=Soma, 2=Subtração, 3=Multiplicação e 4=Divisão.): ");
scanf("%d",&op);
}
int soma (){
return n1+n2;
}
int subt(){
return n1-n2;
}
int mult(){
return n1*n2;
}
float div(){
return n1/n2;
}
int main(){
setlocale(LC_ALL, "Portuguese");
lerDados();
if(op==1){
printf("\nO resultado da soma entre %d e %d é %d.",n1,n2,soma());
}
else if (op==2){
printf("\nO resultado da subtração entre %d e %d é %d.",n1,n2,subt());
}
else if (op==3){
printf("\nO resultado da multiplicação entre %d e %d é %d.",n1,n2,mult());
}
else if (op==4){
printf("\nO resultado da divisão entre %d e %d é %.2f.",n1,n2,div());
}
getch();
}
| [
"gabrielsousaamorimcerqueira@gmail.com"
] | gabrielsousaamorimcerqueira@gmail.com |
64f7c5cdbfd5aef537eabda8e7b64df162470124 | fec81bfe0453c5646e00c5d69874a71c579a103d | /blazetest/src/mathtest/operations/smatsvecmult/LCbVCa.cpp | 62d97c236567ebdc38d4f32c85bb8dde02617a38 | [
"BSD-3-Clause"
] | permissive | parsa/blaze | 801b0f619a53f8c07454b80d0a665ac0a3cf561d | 6ce2d5d8951e9b367aad87cc55ac835b054b5964 | refs/heads/master | 2022-09-19T15:46:44.108364 | 2022-07-30T04:47:03 | 2022-07-30T04:47:03 | 105,918,096 | 52 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 4,481 | cpp | //=================================================================================================
/*!
// \file src/mathtest/operations/smatsvecmult/LCbVCa.cpp
// \brief Source file for the LCbVCa sparse matrix/sparse vector multiplication math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/CompressedVector.h>
#include <blaze/math/LowerMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/operations/smatsvecmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'LCbVCa'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
using LCb = blaze::LowerMatrix< blaze::CompressedMatrix<TypeB> >;
using VCa = blaze::CompressedVector<TypeA>;
// Creator type definitions
using CLCb = blazetest::Creator<LCb>;
using CVCa = blazetest::Creator<VCa>;
// Running tests with small matrices and vectors
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=LCb::maxNonZeros( i ); ++j ) {
for( size_t k=0UL; k<=i; ++k ) {
RUN_SMATSVECMULT_OPERATION_TEST( CLCb( i, j ), CVCa( i, k ) );
}
}
}
// Running tests with large matrices and vectors
RUN_SMATSVECMULT_OPERATION_TEST( CLCb( 67UL, 7UL ), CVCa( 67UL, 7UL ) );
RUN_SMATSVECMULT_OPERATION_TEST( CLCb( 127UL, 13UL ), CVCa( 127UL, 13UL ) );
RUN_SMATSVECMULT_OPERATION_TEST( CLCb( 64UL, 8UL ), CVCa( 64UL, 8UL ) );
RUN_SMATSVECMULT_OPERATION_TEST( CLCb( 128UL, 16UL ), CVCa( 128UL, 16UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse matrix/sparse vector multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
432120cbce485885ac0c103f0964128a83873eef | 1ce2ab94ab83dfa91df393320d89bbb086451106 | /sorting and searching/selectionSort.cpp | ff48f3efe3edda60633506329482458ab1ae741c | [] | no_license | Swapnil-Garg16/Data-Structures | 396ac2211eaec402cbfa5ea204f7ec4824c55e30 | 578b1879130ec2f50dd46086f5b45d48305c4977 | refs/heads/master | 2022-12-08T11:02:45.841209 | 2020-08-24T20:02:33 | 2020-08-24T20:02:33 | 273,741,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 581 | cpp | //selection sort
#include<stdio.h>
#include<stdlib.h>
void selectionSort(int *arr, int n)
{
int i,j,min,t;
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1; j<n;j++)
{
if(arr[j] < arr[min])
min=j;
}
t=arr[i];
arr[i]=arr[min];
arr[min] = t;
}
}
void printArray(int *arr, int n)
{
int i;
for(i=0;i<n;i++)
printf("%d ",arr[i]);
}
int main()
{
int n,i,index,no;
int *arr;
printf("Enter the no of elements\n");
scanf("%d",&n);
arr = (int *)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
selectionSort(arr,n);
printArray(arr,n);
}
| [
"10002001@hmel.int"
] | 10002001@hmel.int |
4e93040bb4d50ad0609143e079baf02efce1a0d1 | 9dc602674d32e79112c3e5598977d9d69470fa90 | /ex6-7/main.cpp | d22f8e706d8d5dac9e0d3697079db718e57dcc4c | [] | no_license | meravboim/cpp-ariel | e2a992aa12143b5d196b13aa65085a50ece27687 | 1523fab6067ccf15395d8865b898a78b1246b79f | refs/heads/master | 2021-04-15T12:25:14.306114 | 2018-06-11T13:09:36 | 2018-06-11T13:09:36 | 126,877,150 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,530 | cpp | #include "TicTacToe.h"
#include "DummyPlayers.h"
#include "Champion.h"
void printResults(const TicTacToe& game) {
cout << endl << "The final board is " << endl << game.board();
cout << "And the winner is " << game.winner().name()
<< ", playing as " << game.winner().getChar() << "!" << endl;
}
void playAndPrintResults(TicTacToe& game, Player& xPlayer, Player& oPlayer) {
game.play(xPlayer, oPlayer);
printResults(game);
}
void playAndPrintWinner(TicTacToe& game, Player& xPlayer, Player& oPlayer) {
game.play(xPlayer, oPlayer);
cout << "The winner is " << game.winner().name()
<< ", playing as " << game.winner().getChar() << "!" << endl;
}
int main() {
TicTacToe game(4); // Initializes a game on a 4x4 board
XYPlayer player1;
YXPlayer player2;
IllegalPlayer player3;
ExceptionPlayer player4;
playAndPrintResults(game, player1, player2);
/*
The final board is
XXXX
O...
O...
O...
And the winner is XYPlayer, playing as X!
*/
playAndPrintResults(game, player2, player1);
/*
The final board is
XOOO
X...
X...
X...
And the winner is YXPlayer, playing as X!
*/
playAndPrintResults(game, player1, player3);
/*
The final board is
X...
....
....
....
And the winner is XYPlayer, playing as X!
*/
playAndPrintResults(game, player3, player1);
/*
The final board is
XO..
....
....
....
And the winner is XYPlayer, playing as O!
*/
playAndPrintResults(game, player2, player4);
/*
The final board is
X...
....
....
....
And the winner is YXPlayer, playing as X!
*/
playAndPrintResults(game, player4, player2);
/*
The final board is
....
....
....
....
And the winner is YXPlayer, playing as O!
*/
Champion champion;
playAndPrintWinner(game, champion, player1);
// The winner is <your name>, playing as X!
playAndPrintWinner(game, player1, champion);
// The winner is <your name>, playing as O!
playAndPrintWinner(game, champion, player2);
// The winner is <your name>, playing as X!
playAndPrintWinner(game, player2, champion);
// The winner is <your name>, playing as O!
playAndPrintWinner(game, champion, player3);
// The winner is <your name>, playing as X!
playAndPrintWinner(game, player3, champion);
// The winner is <your name>, playing as O!
playAndPrintWinner(game, champion, player4);
// The winner is <your name>, playing as X!
playAndPrintWinner(game, player4, champion);
// The winner is <your name>, playing as O!
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
509f7f9d0ab1c7dd6bf2fc5a008a49e96bc882a0 | c67e2f5a8c34025762ebcc1d2c9a1c6201efc4a2 | /GroupManager.h | de82d32187610f7b1d39c53d8d4e79c1ffe9c2aa | [] | no_license | cmwilli5/Project_Gunner | 0fa0e8dec4abba0947fc1c4f7d89ae17e6762f04 | ce3b3ea3b2b04298cf0205e7b8270efd53b8362f | refs/heads/master | 2020-04-13T21:55:33.395442 | 2017-03-23T02:03:37 | 2017-03-23T02:03:37 | 50,155,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | h | #ifndef GROUPMANAGER_H_INCLUDED
#define GROUPMANAGER_H_INCLUDED
#include <unordered_map>
#include <string>
#include <cstdint>
#include <vector>
class EntityManager;
// class that groups various entities under a common identifier and allows retrieval of IDs by group
class GroupManager {
private:
std::unordered_map<std::string, std::vector<uint32_t> > entityIDs;
EntityManager* manager;
public:
GroupManager(EntityManager* manager);
void groupEntity(std::string group, uint32_t entityID);
void ungroupEntity(std::string group, uint32_t entityID);
void ungroupEntity(uint32_t entityID);
void removeGroup(std::string group);
std::vector<uint32_t> const* getIDGroup(std::string group);
};
#endif // GROUPMANAGER_H_INCLUDED
| [
"corithianmw96@gmail.com"
] | corithianmw96@gmail.com |
a878b8ef6268efe98de47b436e294958a07eee75 | a61c69e690618a952ac2e743f98c2cff31759718 | /Modules/Platform/App/Sources/Methane/Platform/MacOS/AppDelegate.hh | 508f213e68e86e0461e89b3cd728c45b7d984811 | [
"Apache-2.0"
] | permissive | endlessMagic/MethaneKit | f231f533484a2db19b2ebd4128fafbc6b613bf7d | 7e914b34d458316614dda28221610399e327c35a | refs/heads/master | 2023-02-11T10:52:11.730420 | 2020-09-19T20:02:10 | 2020-09-19T20:02:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,562 | hh | /******************************************************************************
Copyright 2019-2020 Evgeny Gorodetskiy
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.
*******************************************************************************
FILE: Methane/Platform/MacOS/AppDelegate.h
MacOS application delegate implementation.
******************************************************************************/
#include "AppViewController.hh"
#include <Methane/Platform/AppBase.h>
#import <Cocoa/Cocoa.h>
namespace Methane { namespace Platform { class AppMac; } }
@interface AppDelegate : NSObject<NSApplicationDelegate>
@property (nonatomic, strong, nonnull) IBOutlet AppViewController* viewController;
@property (nonatomic, readonly, nullable) NSWindow* window;
- (id _Nullable) initWithApp : (Methane::Platform::AppMac* _Nonnull) p_app andSettings : (const Methane::Platform::AppBase::Settings* _Nonnull) p_settings;
- (void) run;
- (void) alert : (nonnull NSString*) ns_title withInformation: (nonnull NSString*) ns_info andStyle: (NSAlertStyle) ns_alert_style;
@end
| [
"evsgor@gmail.com"
] | evsgor@gmail.com |
d50c5dbcc4a662405c6cdd3292612b3f3b5eb700 | 26570bfae1946ee91d106baaf8f5ac82efc992c9 | /ET4QA2/ET4AD copy.hpp | 61ce7540ebbcadc392b5deb727bae8fcee512ed3 | [] | no_license | unitsea-developer/ET4QA | addf260adc969f77fdc2dc2273c1bc93e43cbfb1 | 6ef5f2b9957d109155a9c1756f5fcdc5acc5c9b0 | refs/heads/master | 2020-04-26T22:36:52.858933 | 2014-06-11T14:15:55 | 2014-06-11T14:15:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 135,693 | hpp |
/*!
* Software to compute derivatives.
*/
/*!
* This library is dual-licensed: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation. For the terms of this
* license, see licenses/gpl_v3.txt or <http://www.gnu.org/licenses/>.
*
* You are free to use this library under the terms of the GNU General
* Public License, 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.
*
* Alternatively, you can license this library under a commercial
* license.
*
* ET4AD Commercial License (ET4ADCL)
* ==================================
* ---------------------------------------------------------------------
*
* The license is non-exclusively granted to a single person or company,
* per payment of the license fee, for the lifetime of that person or
* company. The license is non-transferable.
*
* The ET4ADCL grants the licensee the right to use ET4AD in commercial
* closed-source projects. Modifications may be made to ET4AD with no
* obligation to release the modified source code. ET4AD (or pieces
* thereof) may be included in any number of projects authored (in whole
* or in part) by the licensee.
*
* The licensee may use any version of ET4AD, past, present or future,
* as is most convenient. This license does not entitle the licensee to
* receive any technical support, updates or bug fixes, except as such are
* made publicly available to all ET4AD users.
*
* The licensee may not sub-license ET4AD itself, meaning that any
* commercially released product containing all or parts of ET4AD must
* have added functionality beyond what is available in ET4AD;
* ET4AD itself may not be re-licensed by the licensee.
*
* To obtain a commercial license agreement, contact:
*
* Matthew Supernaw
* msupernaw@gmail.com
*
*/
/*!
* File: ET4AD.hpp
* Author: matthewsupernaw
*
* Created on May 11, 2014, 8:24 AM
*/
#ifndef AD_ET4AD_HPP
#define AD_ET4AD_HPP
#include <stdint.h>
#include <cmath>
#include <vector>
#include <set>
#include <iostream>
#include <stack>
#define USE_MM_CACHE_MAP
//#define USE_HASH_TABLE
//this is the most crucial part of the software....we need a fast map!
#ifdef USE_MM_CACHE_MAP
#include "support/cache-table-0.2/mm/cache_map.hpp"
#include "support/cache-table-0.2/mm/cache_set.hpp"
#elif defined(USE_TR1_UNORDERED_MAP)
#include <tr1/unordered_map>
#elif defined(USE_HASH_TABLE)
#include "support/hash_table/hashtable.h"
#elif defined(USE_JUDY_ARRAY)
#include "support/judy-code/src/Judy.h"
#else
#include <map>
#endif
namespace ad {
enum Operation {
MINUS = 0,
PLUS,
MULTIPLY,
DIVIDE,
SIN,
COS,
TAN,
ASIN,
ACOS,
ATAN,
ATAN2, //atan(adnumber,adnumber)
ATAN3, //atan(T,adnumber)
ATAN4, //atan(adnumber,T)
SQRT,
POW, //pow(adnumber,adnumber)
POW1, //pow(T,adnumber)
POW2, //pow(adnumber,T)
LOG,
LOG10,
EXP,
SINH,
COSH,
TANH,
ABS,
FABS,
FLOOR,
CEIL,
CONSTANT,
VARIABLE,
NONE
};
/**
* Statement class is used store the expression in a post-order vector.
* Ultimately used for higher order derivatives and expression string
* building.
*
* @param op
*/
template<class REAL_T>
class Statement {
public:
Statement(const Operation &op) : op_m(op) {
}
Statement(const Operation &op, const REAL_T &value) : op_m(op), value_m(value) {
}
Statement(const Operation &op, const REAL_T &value, const uint32_t &id) : op_m(op), value_m(value), id_m(id) {
}
Operation op_m;
REAL_T value_m;
uint32_t id_m;
};
/*!
* Creates a unique identifier.
* @return
*/
class IDGenerator {
public:
static IDGenerator * instance();
const uint32_t next() {
return ++_id;
}
const uint32_t current() {
return _id;
}
private:
IDGenerator() : _id(0) {
}
uint32_t _id;
};
static IDGenerator* only_copy;
inline IDGenerator *
IDGenerator::instance() {
if (!only_copy) {
only_copy = new IDGenerator();
}
return only_copy;
}
template<class REAL_T>
class Variable;
template<class REAL_T, class A>
struct ExpressionBase {
public:
ExpressionBase() : id_m(0) {
}
ExpressionBase(const uint32_t & id) : id_m(id) {
}
const A & Cast() const {
return static_cast<const A&> (*this);
}
inline const REAL_T GetValue() const {
return Cast().GetValue();
}
inline const uint32_t GetId() const {
return id_m;
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
Cast().GetIdRange(min, max);
}
/**
* Compute or get the stored derivative with respect to the unique
* identifier id.
*
* @param id
* @param found
* @return
*/
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
return Cast().Derivative(id, found, index);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
Cast().Push(statements);
}
virtual void PushIds(std::set<uint32_t> &ids) const = 0;
uint32_t id_m;
private:
ExpressionBase& operator=(const ExpressionBase & exp) const {
return *this;
};
};
template<class REAL_T>
struct Literal : public ExpressionBase<REAL_T, Literal<REAL_T> > {
Literal(const REAL_T & value) : value_m(value) {
}
inline const REAL_T GetValue() const {
return this->value_m;
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
return 0;
};
void Push(std::vector<Statement<REAL_T> > &statements) const {
statements.push_back(Statement<REAL_T > (CONSTANT, value_m));
}
void PushIds(std::set<uint32_t> &ids) const {
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
}
const REAL_T &value_m;
};
template <class REAL_T, class LHS, class RHS>
struct Add : public ExpressionBase<REAL_T, Add<REAL_T, LHS, RHS> > {
Add(const ExpressionBase<REAL_T, LHS>& lhs, const ExpressionBase<REAL_T, RHS>& rhs)
: lhs_m(lhs.Cast()), rhs_m(rhs.Cast()) {
}
inline const REAL_T GetValue() const {
return lhs_m.GetValue() + rhs_m.GetValue();
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
return lhs_m.Derivative(id, found) + rhs_m.Derivative(id, found);
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
lhs_m.GetIdRange(min, max);
rhs_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->lhs_m.Push(statements);
this->rhs_m.Push(statements);
statements.push_back(Statement<REAL_T > (PLUS));
}
void PushIds(std::set<uint32_t> &ids) const {
this->lhs_m.PushIds(ids);
this->rhs_m.PushIds(ids);
}
private:
const LHS& lhs_m;
const RHS& rhs_m;
};
template <class REAL_T, class LHS, class RHS>
inline
Add<REAL_T, LHS, RHS> operator+(const ExpressionBase<REAL_T, LHS>& a,
const ExpressionBase<REAL_T, RHS>& b) {
return Add<REAL_T, LHS, RHS > (a.Cast(), b.Cast());
}
template <class REAL_T, class LHS, class RHS>
struct Minus : public ExpressionBase<REAL_T, Minus<REAL_T, LHS, RHS> > {
Minus(const ExpressionBase<REAL_T, LHS>& lhs, const ExpressionBase<REAL_T, RHS>& rhs)
: lhs_m(lhs.Cast()), rhs_m(rhs.Cast()) {
}
inline const REAL_T GetValue() const {
return lhs_m.GetValue() - rhs_m.GetValue();
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
return lhs_m.Derivative(id, found) - rhs_m.Derivative(id, found);
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
lhs_m.GetIdRange(min, max);
rhs_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->lhs_m.Push(statements);
this->rhs_m.Push(statements);
statements.push_back(Statement<REAL_T > (MINUS));
}
void PushIds(std::set<uint32_t> &ids) const {
this->lhs_m.PushIds(ids);
this->rhs_m.PushIds(ids);
}
protected:
private:
const LHS& lhs_m;
const RHS& rhs_m;
};
template <class REAL_T, class LHS, class RHS>
inline const
Minus<REAL_T, LHS, RHS> operator-(const ExpressionBase<REAL_T, LHS>& lhs,
const ExpressionBase<REAL_T, RHS>& rhs) {
return Minus<REAL_T, LHS, RHS > (lhs.Cast(), rhs.Cast());
}
template <class REAL_T, class LHS, class RHS>
struct Multiply : public ExpressionBase<REAL_T, Multiply<REAL_T, LHS, RHS> > {
Multiply(const ExpressionBase<REAL_T, LHS>& lhs, const ExpressionBase<REAL_T, RHS>& rhs)
: lhs_m(lhs.Cast()), rhs_m(rhs.Cast()) {
}
inline const REAL_T GetValue() const {
return lhs_m.GetValue() * rhs_m.GetValue();
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
// std::cout << "* " << a_.Derivative(id, found) << "*" << b_ << " +" <<a_ << " * " << b_.Derivative(id, found) << " \n";
return lhs_m.Derivative(id, found) * rhs_m.GetValue() + lhs_m.GetValue() * rhs_m.Derivative(id, found);
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
lhs_m.GetIdRange(min, max);
rhs_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->lhs_m.Push(statements);
this->rhs_m.Push(statements);
statements.push_back(Statement<REAL_T > (MULTIPLY));
}
void PushIds(std::set<uint32_t> &ids) const {
this->lhs_m.PushIds(ids);
this->rhs_m.PushIds(ids);
}
private:
const LHS& lhs_m;
const RHS& rhs_m;
};
template <class REAL_T, class LHS, class RHS>
inline const
Multiply<REAL_T, LHS, RHS> operator*(const ExpressionBase<REAL_T, LHS>& lhs,
const ExpressionBase<REAL_T, RHS>& rhs) {
return Multiply<REAL_T, LHS, RHS > (lhs.Cast(), rhs.Cast());
}
template <class REAL_T, class LHS, class RHS>
struct Divide : public ExpressionBase<REAL_T, Divide<REAL_T, LHS, RHS> > {
Divide(const ExpressionBase<REAL_T, LHS>& lhs, const ExpressionBase<REAL_T, RHS>& rhs)
: lhs_m(lhs.Cast()), rhs_m(rhs.Cast()) {
}
inline const REAL_T GetValue() const {
return lhs_m.GetValue() / rhs_m.GetValue();
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
return (lhs_m.Derivative(id, found) * rhs_m.GetValue() - lhs_m.GetValue() * rhs_m.Derivative(id, found)) / (rhs_m.GetValue() * rhs_m.GetValue());
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
lhs_m.GetIdRange(min, max);
rhs_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->lhs_m.Push(statements);
this->rhs_m.Push(statements);
statements.push_back(Statement<REAL_T > (DIVIDE));
}
void PushIds(std::set<uint32_t> &ids) const {
this->lhs_m.PushIds(ids);
this->rhs_m.PushIds(ids);
}
private:
const LHS& lhs_m;
const RHS& rhs_m;
};
template <class REAL_T, class LHS, class RHS>
inline const
Divide<REAL_T, LHS, RHS> operator/(const ExpressionBase<REAL_T, LHS>& lhs,
const ExpressionBase<REAL_T, RHS>& rhs) {
return Divide<REAL_T, LHS, RHS > (lhs.Cast(), rhs.Cast());
}
template <class REAL_T, class LHS>
struct LiteralAdd : public ExpressionBase<REAL_T, LiteralAdd<REAL_T, LHS> > {
LiteralAdd(const ExpressionBase<REAL_T, LHS>& lhs, const REAL_T & rhs)
: lhs_m(lhs.Cast()), rhs_m(rhs) {
}
inline const REAL_T GetValue() const {
return lhs_m.GetValue() + rhs_m;
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
return lhs_m.Derivative(id, found);
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
lhs_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->lhs_m.Push(statements);
statements.push_back(Statement<REAL_T > (CONSTANT, rhs_m));
statements.push_back(Statement<REAL_T > (PLUS));
}
void PushIds(std::set<uint32_t> &ids) const {
this->lhs_m.PushIds(ids);
}
private:
const LHS& lhs_m;
REAL_T rhs_m;
};
template <class REAL_T, class LHS>
inline const
LiteralAdd<REAL_T, LHS> operator+(const ExpressionBase<REAL_T, LHS>& lhs,
const REAL_T& rhs) {
return LiteralAdd<REAL_T, LHS > (lhs.Cast(), rhs);
}
template <class REAL_T, class RHS>
inline const
LiteralAdd<REAL_T, RHS> operator+(const REAL_T& lhs,
const ExpressionBase<REAL_T, RHS>& rhs) {
return LiteralAdd<REAL_T, RHS > (rhs.Cast(), lhs);
}
template <class REAL_T, class LHS>
struct LiteralMinus : public ExpressionBase<REAL_T, LiteralMinus<REAL_T, LHS> > {
LiteralMinus(const ExpressionBase<REAL_T, LHS>& lhs, const REAL_T & rhs)
: lhs_m(lhs.Cast()), rhs_m(rhs) {
}
inline const REAL_T GetValue() const {
return lhs_m.GetValue() - rhs_m;
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
return lhs_m.Derivative(id, found);
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
lhs_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->lhs_m.Push(statements);
statements.push_back(Statement<REAL_T > (CONSTANT, rhs_m));
statements.push_back(Statement<REAL_T > (MINUS));
}
void PushIds(std::set<uint32_t> &ids) const {
this->lhs_m.PushIds(ids);
}
private:
const LHS& lhs_m;
REAL_T rhs_m;
};
template <class REAL_T, class RHS>
struct MinusLiteral : public ExpressionBase<REAL_T, MinusLiteral<REAL_T, RHS> > {
MinusLiteral(const REAL_T & lhs, const ExpressionBase<REAL_T, RHS>& rhs)
: rhs_m(rhs.Cast()), lhs_m(lhs) {
}
inline const REAL_T GetValue() const {
return lhs_m - rhs_m.GetValue();
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
return -1.0 * rhs_m.Derivative(id, found);
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
rhs_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
statements.push_back(Statement<REAL_T > (CONSTANT, lhs_m));
this->rhs_m.Push(statements);
statements.push_back(Statement<REAL_T > (MINUS));
}
void PushIds(std::set<uint32_t> &ids) const {
this->rhs_m.PushIds(ids);
}
private:
const RHS& rhs_m;
REAL_T lhs_m;
};
template <class REAL_T, class LHS>
inline const
LiteralMinus<REAL_T, LHS> operator-(const ExpressionBase<REAL_T, LHS>& lhs,
const REAL_T& rhs) {
return LiteralMinus<REAL_T, LHS > (lhs.Cast(), rhs);
}
template <class REAL_T, class RHS>
inline const
MinusLiteral<REAL_T, RHS> operator-(const REAL_T& lhs,
const ExpressionBase<REAL_T, RHS>& rhs) {
return MinusLiteral<REAL_T, RHS > (lhs, rhs.Cast());
}
template <class REAL_T, class LHS>
struct LiteralTimes : public ExpressionBase<REAL_T, LiteralTimes<REAL_T, LHS> > {
LiteralTimes(const REAL_T & lhs, const ExpressionBase<REAL_T, LHS>& rhs)
: lhs_m(lhs), rhs_m(rhs.Cast()) {
}
inline const REAL_T GetValue() const {
return lhs_m * rhs_m.GetValue();
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
return rhs_m.Derivative(id, found) * lhs_m;
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
rhs_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
statements.push_back(Statement<REAL_T > (CONSTANT, lhs_m));
this->rhs_m.Push(statements);
statements.push_back(Statement<REAL_T > (MULTIPLY));
}
void PushIds(std::set<uint32_t> &ids) const {
this->rhs_m.PushIds(ids);
}
private:
const LHS& rhs_m;
REAL_T lhs_m;
};
template <class REAL_T, class LHS>
struct TimesLiteral : public ExpressionBase<REAL_T, TimesLiteral<REAL_T, LHS> > {
TimesLiteral(const ExpressionBase<REAL_T, LHS>& lhs, const REAL_T & rhs)
: lhs_m(lhs.Cast()), rhs_m(rhs) {
}
inline const REAL_T GetValue() const {
return lhs_m.GetValue() * rhs_m;
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
return rhs_m * lhs_m.Derivative(id, found);
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
lhs_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->lhs_m.Push(statements);
statements.push_back(Statement<REAL_T > (CONSTANT, rhs_m));
statements.push_back(Statement<REAL_T > (MULTIPLY));
}
void PushIds(std::set<uint32_t> &ids) const {
this->lhs_m.PushIds(ids);
}
private:
const LHS& lhs_m;
REAL_T rhs_m;
};
template <class REAL_T, class LHS>
inline const
TimesLiteral<REAL_T, LHS> operator*(const ExpressionBase<REAL_T, LHS>& lhs,
const REAL_T& rhs) {
return TimesLiteral<REAL_T, LHS > (lhs.Cast(), rhs);
}
template <class REAL_T, class RHS>
inline const
LiteralTimes<REAL_T, RHS> operator*(const REAL_T& lhs,
const ExpressionBase<REAL_T, RHS>& rhs) {
return LiteralTimes<REAL_T, RHS > (lhs, rhs.Cast());
}
template <class REAL_T, class RHS>
struct LiteralDivide : public ExpressionBase<REAL_T, LiteralDivide<REAL_T, RHS> > {
LiteralDivide(const REAL_T & lhs, const ExpressionBase<REAL_T, RHS>& rhs)
: rhs_m(rhs.Cast()), lhs_m(lhs) {
}
inline const REAL_T GetValue() const {
return lhs_m / rhs_m.GetValue();
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
return ( -rhs_m.Derivative(id, found) * lhs_m) / (rhs_m.GetValue() * rhs_m.GetValue());
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
rhs_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
statements.push_back(Statement<REAL_T > (CONSTANT, lhs_m));
this->rhs_m.Push(statements);
statements.push_back(Statement<REAL_T > (DIVIDE));
}
void PushIds(std::set<uint32_t> &ids) const {
this->rhs_m.PushIds(ids);
}
private:
const RHS& rhs_m;
REAL_T lhs_m;
};
template <class REAL_T, class LHS>
struct DivideLiteral : public ExpressionBase<REAL_T, DivideLiteral<REAL_T, LHS> > {
DivideLiteral(const ExpressionBase<REAL_T, LHS>& lhs, const REAL_T & rhs)
: lhs_m(lhs.Cast()), rhs_m(rhs) {
}
inline const REAL_T GetValue() const {
return lhs_m.GetValue() / rhs_m;
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
return (lhs_m.Derivative(id, found) * rhs_m) / (rhs_m * rhs_m);
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
lhs_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->lhs_m.Push(statements);
statements.push_back(Statement<REAL_T > (CONSTANT, rhs_m));
statements.push_back(Statement<REAL_T > (DIVIDE));
}
void PushIds(std::set<uint32_t> &ids) const {
this->lhs_m.PushIds(ids);
}
private:
const LHS& lhs_m;
REAL_T rhs_m;
};
template <class REAL_T, class LHS>
inline const
DivideLiteral<REAL_T, LHS> operator/(const ExpressionBase<REAL_T, LHS>& lhs,
const REAL_T& rhs) {
return DivideLiteral<REAL_T, LHS > (lhs.Cast(), rhs);
}
template <class REAL_T, class RHS>
inline const
LiteralDivide<REAL_T, RHS> operator/(const REAL_T& lhs,
const ExpressionBase<REAL_T, RHS>& rhs) {
return LiteralDivide<REAL_T, RHS > (lhs, rhs.Cast());
}
template <class REAL_T, class EXPR>
struct Sin : public ExpressionBase<REAL_T, Sin<REAL_T, EXPR> > {
Sin(const ExpressionBase<REAL_T, EXPR>& a)
: expr_m(a.Cast()) {
}
inline const REAL_T GetValue() const {
return std::sin(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
return dx * std::cos(expr_m.GetValue());
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (SIN));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR>
struct Cos : public ExpressionBase<REAL_T, Cos<REAL_T, EXPR> > {
Cos(const ExpressionBase<REAL_T, EXPR>& expr)
: expr_m(expr.Cast()) {
}
inline const REAL_T GetValue() const {
return std::cos(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
return dx*-1.0 * std::sin(expr_m.GetValue());
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (COS));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR>
struct Tan : public ExpressionBase<REAL_T, Tan<REAL_T, EXPR> > {
Tan(const ExpressionBase<REAL_T, EXPR>& expr)
: expr_m(expr.Cast()) {
}
inline const REAL_T GetValue() const {
return std::tan(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
REAL_T v = expr_m.GetValue();
return dx * ((1.0 / std::cos(v))*(1.0 / std::cos(v)));
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (TAN));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR>
struct ASin : public ExpressionBase<REAL_T, ASin<REAL_T, EXPR> > {
ASin(const ExpressionBase<REAL_T, EXPR>& expr)
: expr_m(expr.Cast()) {
}
inline const REAL_T GetValue() const {
return std::asin(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
REAL_T v = expr_m.GetValue();
return (dx * static_cast<REAL_T> (1.0) / std::pow((static_cast<REAL_T> (1.0) - std::pow(v, static_cast<REAL_T> (2.0))), static_cast<REAL_T> (0.5)));
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (ASIN));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR>
struct ACos : public ExpressionBase<REAL_T, ACos<REAL_T, EXPR> > {
ACos(const ExpressionBase<REAL_T, EXPR>& a)
: expr_m(a.Cast()) {
}
inline const REAL_T GetValue() const {
return std::acos(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
REAL_T v = expr_m.GetValue();
return (dx * static_cast<REAL_T> (-1.0) / std::pow((static_cast<REAL_T> (1.0) - std::pow(v, static_cast<REAL_T> (2.0))), static_cast<REAL_T> (0.5)));
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (ACOS));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR>
struct ATan : public ExpressionBase<REAL_T, ATan<REAL_T, EXPR> > {
ATan(const ExpressionBase<REAL_T, EXPR>& expr)
: expr_m(expr.Cast()) {
}
inline const REAL_T GetValue() const {
return std::atan(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
REAL_T v = expr_m.GetValue();
return (dx * 1.0 / (v * v + 1.0));
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (ATAN));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR1, class EXPR2>
struct ATan2 : public ExpressionBase<REAL_T, ATan2<REAL_T, EXPR1, EXPR2> > {
ATan2(const ExpressionBase<REAL_T, EXPR1>& expr1, const ExpressionBase<REAL_T, EXPR2>& expr2)
: expr1_m(expr1.Cast()), expr2_m(expr2.Cast()) {
}
inline const REAL_T GetValue() const {
return std::atan2(expr1_m.GetValue(), expr2_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr1_m.Derivative(id, found);
if (found) {
REAL_T v = expr1_m.GetValue();
REAL_T v2 = expr2_m.GetValue();
return ((v2 * dx) / (v * v + (v2 * v2)));
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr1_m.GetIdRange(min, max);
expr2_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->expr1_m.Push(statements);
this->expr2_m.Push(statements);
statements.push_back(Statement<REAL_T > (ATAN));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr2_m.PushIds(ids);
this->expr2_m.PushIds(ids);
}
private:
const EXPR1& expr1_m;
const EXPR2& expr2_m;
};
template <class REAL_T, class EXPR1>
struct ATan2Literal : public ExpressionBase<REAL_T, ATan2Literal<REAL_T, EXPR1> > {
ATan2Literal(const ExpressionBase<REAL_T, EXPR1>& expr1, const REAL_T & expr2)
: expr1_m(expr1.Cast()), expr2_m(expr2) {
}
inline const REAL_T GetValue() const {
return std::atan2(expr1_m.GetValue(), expr2_m);
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr1_m.Derivative(id, found);
if (found) {
REAL_T v = expr1_m.GetValue();
REAL_T v2 = expr2_m;
return ((v2 * dx) / (v * v + (v2 * v2)));
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr1_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->expr1_m.Push(statements);
statements.push_back(Statement<REAL_T > (CONSTANT, expr2_m));
statements.push_back(Statement<REAL_T > (ATAN2));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr1_m.PushIds(ids);
}
private:
const EXPR1& expr1_m;
const REAL_T& expr2_m;
};
template <class REAL_T, class EXPR2>
struct LiteralATan2 : public ExpressionBase<REAL_T, LiteralATan2<REAL_T, EXPR2> > {
LiteralATan2(const REAL_T& expr1, const ExpressionBase<REAL_T, EXPR2>& expr2)
: expr1_m(expr1), expr2_m(expr2.Cast()) {
}
inline const REAL_T GetValue() const {
return std::atan2(expr1_m, expr2_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = 0;
if (found) {
REAL_T v = expr1_m;
REAL_T v2 = expr2_m.GetValue();
return ((v2 * dx) / (v * v + (v2 * v2)));
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr2_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
statements.push_back(Statement<REAL_T > (CONSTANT, expr1_m));
expr2_m.Push(statements);
statements.push_back(Statement<REAL_T > (ATAN2));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr2_m.PushIds(ids);
}
private:
const REAL_T& expr1_m;
const ExpressionBase<REAL_T, EXPR2>& expr2_m;
};
template <class REAL_T, class EXPR>
struct Sqrt : public ExpressionBase<REAL_T, Sqrt<REAL_T, EXPR> > {
Sqrt(const ExpressionBase<REAL_T, EXPR>& a)
: expr_m(a.Cast()) {
}
inline const REAL_T GetValue() const {
return std::sqrt(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
return dx * .5 / std::sqrt(expr_m.GetValue());
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (SQRT));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR1, class EXPR2>
struct Pow : public ExpressionBase<REAL_T, Pow<REAL_T, EXPR1, EXPR2> > {
Pow(const ExpressionBase<REAL_T, EXPR1>& expr1, const ExpressionBase<REAL_T, EXPR2>& expr2)
: expr1_m(expr1.Cast()), expr2_m(expr2.Cast()) {
}
inline const REAL_T GetValue() const {
return std::pow(expr1_m.GetValue(), expr2_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr1_m.Derivative(id, found);
REAL_T dx2 = expr2_m.Derivative(id, found);
if (found) {
REAL_T v = expr1_m.GetValue();
REAL_T v2 = expr2_m.GetValue();
return (dx * v2) *std::pow(v, (v2 - static_cast<REAL_T> (1.0)));
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr1_m.GetIdRange(min, max);
expr2_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->expr1_m.Push(statements);
this->expr2_m.Push(statements);
statements.push_back(Statement<REAL_T > (POW));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr1_m.PushIds(ids);
this->expr2_m.Push(ids);
}
private:
const EXPR1& expr1_m;
const EXPR2& expr2_m;
};
template <class REAL_T, class EXPR>
struct PowLiteral : public ExpressionBase<REAL_T, PowLiteral<REAL_T, EXPR> > {
PowLiteral(const ExpressionBase<REAL_T, EXPR>& expr, const REAL_T & literal)
: expr_m(expr.Cast()), literal_m(literal) {
}
inline const REAL_T GetValue() const {
return std::pow(expr_m.GetValue(), literal_m);
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
REAL_T v = expr_m.GetValue();
REAL_T v2 = literal_m;
return (dx * v2) *std::pow(v, (v2 - static_cast<REAL_T> (1.0)));
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
this->expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (CONSTANT, literal_m));
statements.push_back(Statement<REAL_T > (POW));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
const REAL_T& literal_m;
};
template <class REAL_T, class EXPR>
struct LiteralPow : public ExpressionBase<REAL_T, LiteralPow<REAL_T, EXPR> > {
LiteralPow(const REAL_T& literal, const ExpressionBase<REAL_T, EXPR>& expr)
: literal_m(literal), expr_m(expr.Cast()) {
}
inline const REAL_T GetValue() const {
return std::pow(literal_m, expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
// REAL_t dx = 0.0;
// if (found) {
// REAL_t v = a_;
// REAL_t v2 = b_.GetValue();
//
// return (dx * v2) *std::pow(v, (v2 - 1.0));
// } else {
// return 0.0;
// }
return 0.0;
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
statements.push_back(Statement<REAL_T > (CONSTANT, literal_m));
this->expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (POW));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const REAL_T& literal_m;
const ExpressionBase<REAL_T, EXPR>& expr_m;
};
template <class REAL_T, class EXPR>
struct Log : public ExpressionBase<REAL_T, Log<REAL_T, EXPR> > {
Log(const ExpressionBase<REAL_T, EXPR>& expr)
: expr_m(expr.Cast()) {
}
inline const REAL_T GetValue() const {
return std::log(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
return (dx * 1.0) / expr_m.GetValue();
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (LOG));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR>
struct Log10 : public ExpressionBase<REAL_T, Log10<REAL_T, EXPR> > {
Log10(const ExpressionBase<REAL_T, EXPR>& expr)
: expr_m(expr.Cast()) {
}
inline const REAL_T GetValue() const {
return std::log10(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
return (dx * 1.0) / (expr_m.GetValue() * std::log(10.0));
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (LOG10));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR>
struct Exp : public ExpressionBase<REAL_T, Exp<REAL_T, EXPR> > {
Exp(const ExpressionBase<REAL_T, EXPR>& expr)
: expr_m(expr.Cast()) {
}
inline const REAL_T GetValue() const {
return std::exp(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
bool f = false;
REAL_T dx = expr_m.Derivative(id, f);
if (f) {
found = true;
return dx * std::exp(expr_m.GetValue());
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (EXP));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR>
struct MFExp : public ExpressionBase<REAL_T, MFExp<REAL_T, EXPR> > {
MFExp(const ExpressionBase<REAL_T, EXPR>& expr)
: expr_m(expr.Cast()) {
}
inline const REAL_T GetValue() const {
REAL_T x = expr_m.GetValue();
REAL_T b = REAL_T(60);
if (x <= b && x >= REAL_T(-1) * b) {
return std::exp(x);
} else if (x > b) {
return std::exp(b)*(REAL_T(1.) + REAL_T(2.) * (x - b)) / (REAL_T(1.) + x - b);
} else {
return std::exp(REAL_T(-1) * b)*(REAL_T(1.) - x - b) / (REAL_T(1.) + REAL_T(2.) * (REAL_T(-1) * x - b));
}
//
// return std::exp(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
return dx * this->GetValue();
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (EXP));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR>
struct Sinh : public ExpressionBase<REAL_T, Sinh<REAL_T, EXPR> > {
Sinh(const ExpressionBase<REAL_T, EXPR>& expr)
: expr_m(expr.Cast()) {
}
inline const REAL_T GetValue() const {
return std::sinh(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
return dx * std::cosh(expr_m.GetValue());
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (SINH));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR>
struct Cosh : public ExpressionBase<REAL_T, Cosh<REAL_T, EXPR> > {
Cosh(const ExpressionBase<REAL_T, EXPR>& expr)
: expr_m(expr.Cast()) {
}
inline const REAL_T GetValue() const {
return std::cosh(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
return dx * std::sinh(expr_m.GetValue());
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (COSH));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR>
struct Tanh : public ExpressionBase<REAL_T, Tanh<REAL_T, EXPR> > {
Tanh(const ExpressionBase<REAL_T, EXPR>& expr)
: expr_m(expr.Cast()) {
}
inline const REAL_T GetValue() const {
return std::tanh(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
REAL_T v = expr_m.GetValue();
return dx * (1.0 / std::cosh(v))*(1.0 / std::cosh(v));
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (TANH));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR>
struct Fabs : public ExpressionBase<REAL_T, Fabs<REAL_T, EXPR> > {
Fabs(const ExpressionBase<REAL_T, EXPR>& expr)
: expr_m(expr.Cast()) {
}
inline const REAL_T GetValue() const {
return std::fabs(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
REAL_T dx = expr_m.Derivative(id, found);
if (found) {
REAL_T v = expr_m.GetValue();
return (dx * v) / std::fabs(v);
} else {
return 0.0;
}
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (FABS));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR>
struct Floor : public ExpressionBase<REAL_T, Floor<REAL_T, EXPR> > {
Floor(const ExpressionBase<REAL_T, EXPR>& a)
: expr_m(a.Cast()) {
}
inline const REAL_T GetValue() const {
return std::floor(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
return 0.0;
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (FLOOR));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
template <class REAL_T, class EXPR>
struct Ceil : public ExpressionBase<REAL_T, Ceil<REAL_T, EXPR> > {
Ceil(const ExpressionBase<REAL_T, EXPR>& expr)
: expr_m(expr.Cast()) {
}
inline const REAL_T GetValue() const {
return std::ceil(expr_m.GetValue());
}
inline const REAL_T Derivative(const uint32_t &id, bool &found, uint32_t index = 0) const {
return 0.0;
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
expr_m.GetIdRange(min, max);
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
expr_m.Push(statements);
statements.push_back(Statement<REAL_T > (CEIL));
}
void PushIds(std::set<uint32_t> &ids) const {
this->expr_m.PushIds(ids);
}
private:
const EXPR& expr_m;
};
}
namespace std {
/**
* Write the expression value to std::ostream out.
* @param out
* @param exp
* @return
*/
template<class REAL_T, class A>
inline std::ostream& operator<<(std::ostream &out, const ad::ExpressionBase<REAL_T, A> &exp) {
out << exp.GetValue();
return out;
}
/**
* Override for the sin function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::Sin<REAL_T, EXPR> sin(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::Sin<REAL_T, EXPR > (expr.Cast());
}
/**
* Override for the cos function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::Cos<REAL_T, EXPR> cos(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::Cos<REAL_T, EXPR > (expr.Cast());
}
/**
* Override for the tan function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::Tan<REAL_T, EXPR> tan(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::Tan<REAL_T, EXPR > (expr.Cast());
}
/**
* Override for the asin function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::ASin<REAL_T, EXPR> asin(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::ASin<REAL_T, EXPR > (expr.Cast());
}
/**
* Override for the asin function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::ACos<REAL_T, EXPR> acos(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::ACos<REAL_T, EXPR > (expr.Cast());
}
/**
* Override for the atan function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::ATan<REAL_T, EXPR> atan(const ad::ExpressionBase<REAL_T, EXPR>& a) {
return ad::ATan<REAL_T, EXPR > (a.Cast());
}
/**
* Override for the atan2 function in namespace std.
*
* @param expr1
* @param expr2
* @return
*/
template <class REAL_T, class EXPR1, class EXPR2>
inline
ad::ATan2<REAL_T, EXPR1, EXPR2> atan2(const ad::ExpressionBase<REAL_T, EXPR1>& expr1,
const ad::ExpressionBase<REAL_T, EXPR2>& expr2) {
return ad::ATan2<REAL_T, EXPR1, EXPR2 > (expr1.Cast(), expr2.Cast());
}
/**
* Override for the atan2 function in namespace std.
*
* @param expr1
* @param val
* @return
*/
template <class REAL_T, class EXPR>
inline
ad::ATan2Literal<REAL_T, EXPR> atan2(const ad::ExpressionBase<REAL_T, EXPR>& expr,
const REAL_T& val) {
return ad::ATan2Literal<REAL_T, EXPR > (expr.Cast(), val);
}
/**
* Override for the atan2 function in namespace std.
*
* @param expr1
* @param expr2
* @return
*/
template <class REAL_T, class EXPR>
inline
ad::LiteralATan2<REAL_T, EXPR> atan2(const REAL_T& val,
const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::LiteralATan2<REAL_T, EXPR > (val, expr.Cast());
}
/**
* Override for the sqrt function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::Sqrt<REAL_T, EXPR> sqrt(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::Sqrt<REAL_T, EXPR > (expr.Cast());
}
/**
* Override for the pow function in namespace std.
*
* @param expr1
* @param expr2
* @return
*/
template <class REAL_T, class EXPR1, class EXPR2>
inline
ad::Pow<REAL_T, EXPR1, EXPR2> pow(const ad::ExpressionBase<REAL_T, EXPR1>& expr1,
const ad::ExpressionBase<REAL_T, EXPR2>& expr2) {
return ad::Pow<REAL_T, EXPR1, EXPR2 > (expr1.Cast(), expr2.Cast());
}
/**
* Override for the pow function in namespace std.
*
* @param expr1
* @param val
* @return
*/
template <class REAL_T, class EXPR>
inline
ad::PowLiteral<REAL_T, EXPR> pow(const ad::ExpressionBase<REAL_T, EXPR>& expr,
const REAL_T& val) {
return ad::PowLiteral<REAL_T, EXPR > (expr.Cast(), val);
}
/**
* Override for the pow function in namespace std.
*
* @param val
* @param expr2
* @return
*/
template <class REAL_T, class EXPR>
inline
ad::LiteralPow<REAL_T, EXPR> pow(const REAL_T& val,
const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::LiteralPow<REAL_T, EXPR > (val, expr.Cast());
}
/**
* Override for the log function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::Log<REAL_T, EXPR> log(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::Log<REAL_T, EXPR > (expr.Cast());
}
/**
* Override for the log function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::Log10<REAL_T, EXPR> log10(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::Log10<REAL_T, EXPR > (expr.Cast());
}
/**
* Override for the exp function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::Exp<REAL_T, EXPR> exp(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::Exp<REAL_T, EXPR > (expr.Cast());
}
template<class REAL_T, class EXPR>
inline const const ad::MFExp<REAL_T, EXPR> mfexp(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::MFExp<REAL_T, EXPR > (expr.Cast());
}
/**
* Override for the sinh function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::Sinh<REAL_T, EXPR> sinh(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::Sinh<REAL_T, EXPR > (expr.Cast());
}
/**
* Override for the cosh function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::Cosh<REAL_T, EXPR> cosh(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::Cosh<REAL_T, EXPR > (expr.Cast());
}
/**
* Override for the tanh function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::Tanh<REAL_T, EXPR> tanh(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::Tanh<REAL_T, EXPR > (expr.Cast());
}
/**
* Override for the fabs function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::Fabs<REAL_T, EXPR> fabs(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::Fabs<REAL_T, EXPR > (expr.Cast());
}
/**
* Override for the floor function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::Floor<REAL_T, EXPR> floor(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::Floor<REAL_T, EXPR > (expr.Cast());
}
/**
* Override for the ceil function in namespace std.
*
* @param expr
* @return
*/
template<class REAL_T, class EXPR>
inline const ad::Ceil<REAL_T, EXPR> ceil(const ad::ExpressionBase<REAL_T, EXPR>& expr) {
return ad::Ceil<REAL_T, EXPR > (expr.Cast());
}
}
namespace ad {
/**
* Interface class for storing variable information. The point of this class
* is to provide flexibility of the storage for the variables information.
* For instance, it may be desired to store the data in a database or on
* the disk rather than in memory.
*/
template<class REAL_T>
class VariableStorage {
ad::Variable<REAL_T>* variable_m;
public:
VariableStorage(ad::Variable<REAL_T>* variable) : variable_m(variable) {
}
virtual const REAL_T GetDerivative(const uint32_t &id) = 0;
};
/**
* Variable class used for calculations and storage of computed derivatives.
*
* Derivatives are only computed for variables marked as independent
* variables. To make a variable independent use:
*
* constructor:
*
* Variable(const REAL_T& value, bool is_independent = false)
*
* or
*
* Member Function:
*
* void SetAsIndependent(const bool &is_independent)
*
*
*
*/
template<class REAL_T>
class Variable : public ExpressionBase<REAL_T, Variable<REAL_T> > {
REAL_T value_m;
uint32_t iv_id_m; //id when is a independent variable.
std::string name_m;
bool bounded_m;
REAL_T min_boundary_m;
REAL_T max_boundary_m;
bool is_independent_m;
uint32_t iv_min; //if this variable is caching derivatives, this is the min independent variable.
uint32_t iv_max; //if this variable is caching derivatives, this is the max independent variable.
// static std::set<uint32_t> independent_variables_g;
static bool is_recording_g;
static bool is_supporting_arbitrary_order;
#ifdef USE_MM_CACHE_MAP
typedef mm::cache_map<uint32_t, double> GradientMap;
typedef std::set<uint32_t> indepedndent_variables;
typedef std::set<uint32_t> ::const_iterator const_indepedndent_variables_iterator;
typedef std::set<uint32_t> ::iterator indepedndent_variables_iterator;
typedef mm::cache_map<uint32_t, mm::cache_map<uint32_t, double> > MixedPartialsMap;
typedef GradientMap::const_iterator const_grads_iterator;
typedef GradientMap::iterator grads_iterator;
typedef MixedPartialsMap::const_iterator const_patrials_iterator;
typedef MixedPartialsMap::iterator partials_iterator;
#elif defined(USE_TR1_UNORDERED_MAP)
typedef std::tr1::unordered_map<uint32_t, double> GradientMap;
typedef std::tr1::unordered_map<uint32_t, std::tr1::unordered_map<uint32_t, double> > MixedPartialsMap;
typedef GradientMap::const_iterator const_grads_iterator;
typedef GradientMap::iterator grads_iterator;
typedef MixedPartialsMap::const_iterator const_patrials_iterator;
typedef MixedPartialsMap::iterator partials_iterator;
#elif defined(USE_HASH_TABLE)
typedef HashTable GradientMap;
#else
typedef std::map<uint32_t, double> GradientMap;
typedef std::map<uint32_t, std::map<uint32_t, double> > MixedPartialsMap;
typedef GradientMap::const_iterator const_grads_iterator;
typedef GradientMap::iterator grads_iterator;
typedef MixedPartialsMap::const_iterator const_patrials_iterator;
typedef MixedPartialsMap::iterator partials_iterator;
#endif
GradientMap gradients_m;
indepedndent_variables ids_m;
// std::vector<bool> has_m;
typedef std::vector<Statement<REAL_T> > ExpressionStatements;
ExpressionStatements statements_m;
public:
static uint32_t misses_g;
/**
* Default conclassor.
*/
Variable() : ExpressionBase<REAL_T, Variable<REAL_T> >(0), value_m(0.0), bounded_m(false), is_independent_m(false), iv_id_m(0) {
iv_min = std::numeric_limits<uint32_t>::max();
iv_max = std::numeric_limits<uint32_t>::min();
if (Variable::is_recording_g) {
if (Variable::IsSupportingArbitraryOrder()) {
this->statements_m.push_back(Statement<REAL_T > (VARIABLE, this->GetValue(), this->GetId()));
}
}
}
/**
* Conclass a variable with a initial value. Optional parameter to make
* it a independent variable.
*
* @param value
* @param is_independent
*/
Variable(const REAL_T& value, bool is_independent = false) : is_independent_m(is_independent), ExpressionBase<REAL_T, Variable<REAL_T> >(0), value_m(value), iv_id_m(0) {
iv_min = std::numeric_limits<uint32_t>::max();
iv_max = std::numeric_limits<uint32_t>::min();
if (is_independent) {
// this->id_m = IDGenerator::instance()->next();
this->SetAsIndependent(is_independent);
this->bounded_m = false;
this->min_boundary_m = std::numeric_limits<REAL_T>::min();
this->max_boundary_m = std::numeric_limits<REAL_T>::max();
// Variable::independent_variables_g.insert(this->GetId());
if (Variable::IsSupportingArbitraryOrder()) {
this->statements_m.push_back(Statement<REAL_T > (VARIABLE, this->GetValue(), this->GetId()));
}
}
}
/**
* Copy conclassor.
*
* @param rhs
*/
Variable(const Variable& orig) {
value_m = orig.GetValue();
this->id_m = orig.GetId();
this->iv_id_m = orig.iv_id_m;
orig.PushIds(ids_m);
#if defined(USE_HASH_TABLE)
this->gradients_m = HashTable(orig.gradients_m);
#else
this->gradients_m.insert(orig.gradients_m.begin(), orig.gradients_m.end());
#endif
this->is_independent_m = orig.is_independent_m;
this->bounded_m = orig.bounded_m;
this->min_boundary_m = orig.min_boundary_m;
this->max_boundary_m = orig.max_boundary_m;
iv_min = orig.iv_min;
iv_max = orig.iv_max;
if (Variable::IsSupportingArbitraryOrder()) {
orig.Push(this->statements_m);
}
}
/**
* Conclasss a variable from expression expr.
* @param rhs
*/
template<class T>
Variable(const ExpressionBase<REAL_T, T>& expr) {
//has_m.resize(IDGenerator::instance()->current() + 1);
this->bounded_m = false;
iv_min = std::numeric_limits<uint32_t>::max();
iv_max = std::numeric_limits<uint32_t>::min();
if (Variable::is_recording_g) {
// this->id_m = expr.GetId();
// ind_iterator it;
// for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
// bool found = false;
//#if defined(USE_HASH_TABLE)
// this->gradients_m.Insert(*it)->value = expr.Derivative(*it, found);
//#else
// this->gradients_m[(*it)] = expr.Derivative(*it, found);
//#endif
//
// }
expr.PushIds(ids_m);
//expr.GetIdRange(this->iv_min, this->iv_max);
indepedndent_variables_iterator it;
// for (uint32_t i = this->iv_min; i< this->iv_max + 1; i++) {
for (it = this->ids_m.begin(); it != ids_m.end(); ++it) {
bool found = false;
this->gradients_m[*it] = expr.Derivative(*it, found);
}
if (Variable::IsSupportingArbitraryOrder()) {
expr.Push(this->statements_m);
}
}
value_m = expr.GetValue();
}
~Variable() {
#if !defined(USE_HASH_TABLE)
// if (this->is_independent_m) {
// this->independent_variables_g.erase(this->GetId());
// }
this->statements_m.clear();
this->gradients_m.clear();
#endif
}
size_t Size() {
return this->statements_m.size();
}
const REAL_T Diff(const Variable &wrt) {
if (this->statements_m.size() == 0) {
return 0.0;
}
std::vector<std::pair<REAL_T, REAL_T> > v;
v.reserve(this->statements_m.size());
std::stack<std::pair<REAL_T, REAL_T>,
std::vector<std::pair<REAL_T, REAL_T> > > stack;
// ad::Stack<std::pair<T, T> > stack;
bool found = false;
int size = this->statements_m.size();
std::pair<REAL_T, REAL_T> lhs = std::pair<REAL_T, REAL_T > (0, 0);
std::pair<REAL_T, REAL_T> rhs = std::pair<REAL_T, REAL_T > (0, 0);
// Statement<REAL_T>* edata = (Statement<REAL_T>*)this->statements_m.data();
// std::cout << this->statements_m.size() << "\n\n";
for (int i = 0; i < size; i++) {
REAL_T temp = 0;
switch (statements_m[i].op_m) {
case CONSTANT:
stack.push(std::pair<REAL_T, REAL_T > (statements_m[i].value_m, 0.0));
break;
case VARIABLE:
if (statements_m[i].id_m == wrt.GetId() && wrt.GetId() > 0) {
found = true;
//f(x) = x
//f'(x) = 1
stack.push(std::pair<REAL_T, REAL_T > (statements_m[i].value_m, 1.0));
} else {//constant
//f(x) = C
//f'(x) = 0
stack.push(std::pair<REAL_T, REAL_T > (statements_m[i].value_m, 0.0));
}
break;
case PLUS:
rhs = stack.top();
stack.pop();
lhs = stack.top();
stack.pop();
stack.push(std::pair<REAL_T, REAL_T > (lhs.first + rhs.first, lhs.second + rhs.second));
// ret = lhs.second + rhs.second;
break;
case MINUS:
rhs = stack.top();
stack.pop();
lhs = stack.top();
stack.pop();
stack.push(std::pair<REAL_T, REAL_T > (lhs.first - rhs.first, lhs.second - rhs.second));
// ret = lhs.second-rhs.second;
break;
case MULTIPLY:
rhs = stack.top();
stack.pop();
lhs = stack.top();
stack.pop();
temp = lhs.second * rhs.first + lhs.first * rhs.second;
// std::cout << "* " <<lhs.second <<"*"<< rhs.first<<" +"<< lhs.first<<" * "<<rhs.second << " \n";
stack.push(std::pair<REAL_T, REAL_T > (lhs.first * rhs.first, temp));
// ret =temp;
break;
case DIVIDE:
rhs = stack.top();
stack.pop();
lhs = stack.top();
stack.pop();
// std::cout<<lhs.first<<" "<<rhs.first<<"\n";
// temp = (lhs.second * rhs.first - lhs.first * rhs.second) / (rhs.first * rhs.first);
stack.push(std::pair<REAL_T, REAL_T > (lhs.first / rhs.first, 1));
// ret = temp;
break;
case SIN:
lhs = stack.top();
stack.pop();
if (found) {
stack.push(std::pair<REAL_T, REAL_T > (std::sin(lhs.first), lhs.second * std::cos(lhs.first)));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::sin(lhs.first), 0));
}
break;
case COS:
lhs = stack.top();
stack.pop();
if (found) {
stack.push(std::pair<REAL_T, REAL_T > (std::cos(lhs.first), lhs.second * (-1.0) * std::sin(lhs.first)));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::cos(lhs.first), 0));
}
break;
case TAN:
lhs = stack.top();
stack.pop();
if (found) {
temp = lhs.second * ((1.0 / std::cos(lhs.first))*(1.0 / std::cos(lhs.first)));
stack.push(std::pair<REAL_T, REAL_T > (std::tan(lhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::tan(lhs.first), 0));
}
break;
case ASIN:
lhs = stack.top();
stack.pop();
if (found) {
temp = (lhs.second * 1.0 / std::pow((static_cast<REAL_T> (1.0) - std::pow(lhs.first, static_cast<REAL_T> (2.0))), static_cast<REAL_T> (0.5)));
stack.push(std::pair<REAL_T, REAL_T > (std::asin(lhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::asin(lhs.first), 0));
}
break;
case ACOS:
lhs = stack.top();
stack.pop();
if (found) {
temp = (lhs.second * (-1.0) / std::pow((static_cast<REAL_T> (1.0) - std::pow(lhs.first, static_cast<REAL_T> (2.0))), static_cast<REAL_T> (0.5)));
stack.push(std::pair<REAL_T, REAL_T > (std::acos(lhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::acos(lhs.first), (0)));
}
break;
case ATAN:
lhs = stack.top();
stack.pop();
if (found) {
temp = (lhs.second * (1.0) / (lhs.first * lhs.first + (1.0)));
stack.push(std::pair<REAL_T, REAL_T > (std::atan(lhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::atan(lhs.first), (0)));
}
break;
case ATAN2:
rhs = stack.top();
stack.pop();
lhs = stack.top();
stack.pop();
if (found) {
temp = (rhs.first * lhs.second / (lhs.first * lhs.first + (rhs.first * rhs.first)));
stack.push(std::pair<REAL_T, REAL_T > (std::atan2(lhs.first, rhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::atan2(lhs.first, rhs.first), (0)));
}
break;
case SQRT:
lhs = stack.top();
stack.pop();
if (found) {
temp = lhs.second * (.5) / std::sqrt(lhs.first);
stack.push(std::pair<REAL_T, REAL_T > (std::sqrt(lhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::sqrt(lhs.first), (0)));
}
break;
case POW:
rhs = stack.top();
stack.pop();
lhs = stack.top();
stack.pop();
if (found) {
temp = (lhs.second * rhs.first) *
std::pow(lhs.first, (rhs.first - static_cast<REAL_T> (1.0)));
stack.push(std::pair<REAL_T, REAL_T > (std::pow(lhs.first, rhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::pow(lhs.first, rhs.first), (0)));
}
break;
case LOG:
lhs = stack.top();
stack.pop();
if (found) {
temp = (lhs.second * (1.0)) / lhs.first;
stack.push(std::pair<REAL_T, REAL_T > (std::log(lhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::log(lhs.first), (0)));
}
break;
case LOG10:
lhs = stack.top();
stack.pop();
if (found) {
temp = (lhs.second * (1.0)) / (lhs.first * std::log((10.0)));
stack.push(std::pair<REAL_T, REAL_T > (std::log10(lhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::log10(lhs.first), (0)));
}
break;
case EXP:
lhs = stack.top();
stack.pop();
if (found) {
temp = lhs.second * std::exp(lhs.first);
stack.push(std::pair<REAL_T, REAL_T > (std::exp(lhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::exp(lhs.first), (0)));
}
break;
case SINH:
lhs = stack.top();
stack.pop();
if (found) {
temp = lhs.second * std::cosh(lhs.first);
stack.push(std::pair<REAL_T, REAL_T > (std::sinh(lhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::sinh(lhs.first), (0)));
}
break;
case COSH:
lhs = stack.top();
stack.pop();
if (found) {
temp = lhs.second * std::sinh(lhs.first);
stack.push(std::pair<REAL_T, REAL_T > (std::cosh(lhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::cosh(lhs.first), (0)));
}
break;
case TANH:
lhs = stack.top();
stack.pop();
if (found) {
temp = lhs.second * ((1.0) / std::cosh(lhs.first))*((1.0) / std::cosh(lhs.first));
stack.push(std::pair<REAL_T, REAL_T > (std::tanh(lhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::tanh(lhs.first), (0)));
}
break;
case FABS:
lhs = stack.top();
stack.pop();
if (found) {
temp = (lhs.second * lhs.first) /
std::fabs(lhs.first);
stack.push(std::pair<REAL_T, REAL_T > (std::fabs(lhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::fabs(lhs.first), (0)));
}
break;
case ABS:
lhs = stack.top();
stack.pop();
if (found) {
temp = (lhs.second * lhs.first) /
std::fabs(lhs.first);
stack.push(std::pair<REAL_T, REAL_T > (std::fabs(lhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::fabs(lhs.first), (0)));
}
break;
case FLOOR:
lhs = stack.top();
stack.pop();
if (found) {
temp = (0); //lhs.second * T(std::floor(lhs.first));
stack.push(std::pair<REAL_T, REAL_T > (std::floor(lhs.first), temp));
} else {
stack.push(std::pair<REAL_T, REAL_T > (std::floor(lhs.first), (0)));
}
break;
case NONE:
std::cout << "nothing to do here.\n";
break;
default:
break;
}
}
return stack.top().second;
}
/**
* Control function. If true, derivatives are computed. If false
* expressions are only evaluated.
*
* @param is_recording
*/
static void SetRecording(const bool &is_recording) {
Variable::is_recording_g = is_recording;
}
/**
* If true, derivatives are calculated and stored. If false,
* expressions are evaluated for value only.
*
* @return
*/
static bool IsRecording() {
return Variable::is_recording_g;
}
/**
* If set to true, the expression is recorded into a vector of
* statements that can be manipulated to compute derivatives of
* arbitrary order. This functionality is costly and is rarely required,
* thus default setting is false.
*
* @param support_arbitrary_order
*/
static void SetSupportArbitraryOrder(const bool &support_arbitrary_order) {
Variable::is_supporting_arbitrary_order = support_arbitrary_order;
}
/*
* If true, expressions are recorded into a vector of statements that
* can be used later to compute derivatives of arbitrary order, or
* be used to build expression strings.
*
*/
static bool IsSupportingArbitraryOrder() {
return Variable::is_supporting_arbitrary_order;
}
/**
* Returns the value of this variable.
*
* @return
*/
inline const REAL_T GetValue() const {
return this->value_m;
}
/**
* Sets the value of this variable. If the variable is bounded,
* the value will be set between the min and max boundary. If the
* value is less than the minimum boundary, the variables value is
* set to minimum boundary. If the value is greater than the maximum
* boundary, the variables value is set to maximum boundary. If the
* value is signaling nan, the value is set to the mid point between
* the min and max boundary.
*
* @param value
*/
void SetValue(const REAL_T &value) {
if (this->bounded_m) {
if (value != value) {//nan
this->value_m = this->min_boundary_m + (this->max_boundary_m - this->min_boundary_m) / 2.0;
return;
}
if (value<this->min_boundary_m) {
this->value_m = this->min_boundary_m;
} else if (value>this->max_boundary_m) {
this->value_m = this->max_boundary_m;
} else {
this->value_m = value;
}
} else {
this->value_m = value;
}
}
/**
* Returns the name of this variable. Names are not initialized and
* if it is not set this function will return a empty string.
* @return
*/
std::string GetName() const {
return name_m;
}
/**
* Set the name of this variable.
*
* @param name
*/
void SetName(std::string name) {
this->name_m = name;
}
/**
* Returns true if this variable is bounded. Otherwise,
* false.
*
* @return
*/
bool IsBounded() {
return this->bounded_m;
}
/**
* Set the min and max boundary for this variable.
* @param min
* @param max
*/
void SetBounds(const REAL_T& min, const REAL_T& max) {
this->bounded_m = true;
this->max_boundary_m = max;
this->min_boundary_m = min;
this->SetValue(this->GetValue());
}
/**
* Return the minimum boundary for this variable. The default value
* is the results of std::numeric_limits<REAL_t>::min().
*
* @return
*/
const REAL_T GetMinBoundary() {
return this->min_boundary_m;
}
/**
* Return the maximum boundary for this variable. The default value
* is the results of std::numeric_limits<REAL_t>::max().
*
* @return
*/
const REAL_T GetMaxBoundary() {
return this->max_boundary_m;
}
/**
* Make this Variable an independent variable. If set to true,
* the Variables unique identifier is registered in the static set
* of independent variables. During function evaluations, gradient
* information is accumulated in post-order wrt to variables in the
* static set of independent variables. If set false, this Variables
* unique identifier will be removed from the set, if it existed.
*
*
* To access the derivative wrt to a Variable, call function:
*
* const REAL_t wrt(const Variable & ind)
*
*
* @param is_independent
*/
void SetAsIndependent(const bool &is_independent) {
if (this->iv_id_m == 0) {
this->iv_id_m = IDGenerator::instance()->next();
if (Variable<REAL_T>::IsSupportingArbitraryOrder()) {
this->statements_m.clear();
this->statements_m.push_back(Statement<REAL_T > (VARIABLE, this->GetValue(), this->GetId()));
}
this->id_m = iv_id_m;
if (this->iv_min == std::numeric_limits<uint32_t>::max() && this->iv_max == std::numeric_limits<uint32_t>::min()) {
this->iv_max = this->GetId();
this->iv_min = this->GetId();
}
}
if (this->is_independent_m && !is_independent) {
// Variable::independent_variables_g.erase(this->GetId());
this->id_m = 0;
this->is_independent_m = false;
}
if (!this->is_independent_m && is_independent) {
// Variable::independent_variables_g.insert(this->GetId());
this->id_m = this->iv_id_m;
this->is_independent_m = true;
}
}
bool IsIndependent() {
return this->is_independent_m;
}
/**
* Returns the derivative with respect to a variables who's
* unique identifier is equal to the parameter id.
*
* @param id
* @param found
* @return
*/
const REAL_T Derivative(const uint32_t &id, bool &found) const {
if (this->GetId() == id) {
found = true;
return 1.0;
} else {
#if defined(USE_HASH_TABLE)
HashTable::Cell* entry = this->gradients_m.Lookup(id);
if (entry != NULL) {
return entry->value;
} else {
return 0.0;
}
#else
// if (id >= this->iv_min && id <= this->iv_max) {
const_grads_iterator git = this->gradients_m.find(id);
if (git != this->gradients_m.end()) {
found = true;
return git->second;
} else {
Variable<REAL_T>::misses_g++;
return 0.0;
}
}
#endif
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
if (this->iv_min < min) {
min = this->iv_min;
}
if (this->iv_max > max) {
max = this->iv_max;
}
if (this->GetId() > 0) {
if (this->GetId() < min) {
min = this->GetId();
}
// if (this->GetId()) {
// max = this->GetId();
// }
}
//
// if (min == std::numeric_limits<uint32_t>::max()) {
// min = max;
// }
// std::cout << min << " " << max << "\n";
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
statements.insert(statements.end(), this->statements_m.begin(), statements_m.end());
// if (this->statements_m.size() > 0) {
// statements.insert(statements.end(), this->statements_m.begin(), statements_m.end());
// } else {
// statements.push_back(Statement<REAL_T > (VARIABLE, this->GetValue(), this->GetId()));
// }
}
void PushIds(std::set<uint32_t> &ids) const {
if (this->GetId() != 0) {
// uint32_t id = uint32_t
ids.insert(this->GetId());
} else {
ids.insert(this->ids_m.begin(), this->ids_m.end());
}
}
/**
* Finds the derivative in the encapsulated gradient map
* w.r.t a variable.
*
* @param ind
* @return
*/
const REAL_T WRT(const Variable & ind) {
#if defined(USE_HASH_TABLE)
HashTable::Cell* entry = this->gradients_m.Lookup(ind.GetId());
if (entry != NULL) {
return entry->value;
} else {
return 0.0;
}
#else
const_grads_iterator git = this->gradients_m.find(ind.GetId());
if (git != this->gradients_m.end()) {
return git->second;
} else {
return 0;
}
#endif
}
/**
* Finds the derivative in the encapsulated gradient map
* w.r.t a variable.
* @param ind
* @return
*/
const REAL_T WRT(const Variable & ind) const {
#if defined(USE_HASH_TABLE)
HashTable::Cell* entry = this->gradients_m.Lookup(ind.GetId());
if (entry != NULL) {
return entry->value;
} else {
return 0.0;
}
#else
const_grads_iterator git = this->gradients_m.find(ind.GetId());
if (git != this->gradients_m.end()) {
return git->second;
} else {
return 0;
}
#endif
}
const std::string Serialize() {
}
void Deserialize(const std::string &str) {
}
/**
* Set the variable equal to the real type rhs.
*
* The gradient map will be cleared.
*
* @param rhs
* @return
*/
Variable& operator=(const REAL_T& rhs) {
this->SetValue(rhs);
// iv_min = std::numeric_limits<uint32_t>::max();
// iv_max = std::numeric_limits<uint32_t>::min();
#if defined(USE_HASH_TABLE)
this->gradients_m.Clear();
#else
this->gradients_m.clear();
if (Variable::IsRecording()) {
if (Variable::is_supporting_arbitrary_order) {
this->statements_m.clear();
this->statements_m.push_back(Statement<REAL_T > (VARIABLE, this->GetValue(), this->GetId()));
}
}
#endif
return *this;
}
/**
* Sets the value of this Variable to that of rhs. Derivatives
* are stored in the encapsulated gradient map.
*
* @param rhs
* @return
*/
Variable& operator=(const Variable& other) {
// this->id = other.getId();
//has_m.resize(IDGenerator::instance()->current() + 1);
value_m = other.GetValue();
other.PushIds(ids_m);
// this->gradients.clear();
if (ad::Variable<REAL_T>::is_recording_g) {
#if defined(USE_HASH_TABLE)
ind_iterator it;
for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
bool found = false;
this->gradients_m.Insert(*it)->value = other.Derivative(*it, found);
// std::cout<<"diff wrt "<<(*it)<<" = " <<rhs.Derivative(*it, found);
}
#else
// this->gradients.insert(rhs.gradients.begin(), rhs.gradients.end());
// ind_iterator it;
// for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
// bool found = false;
// this->gradients_m[(*it)] = other.Derivative(*it, found);
// // std::cout<<"diff wrt "<<(*it)<<" = " <<rhs.Derivative(*it, found);
// }
// other.GetIdRange(this->iv_min, this->iv_max);
// for (uint32_t i = this->iv_min; i < this->iv_max + 1; i++) {
indepedndent_variables_iterator it;
// for (uint32_t i = this->iv_min; i< this->iv_max + 1; i++) {
for (it = this->ids_m.begin(); it != ids_m.end(); ++it) {
bool found = true;
this->gradients_m[*it] = other.Derivative(*it, found);
}
#endif
if (Variable::is_supporting_arbitrary_order) {
std::vector<Statement<REAL_T> > temp_stmnt;
other.Push(temp_stmnt);
this->statements_m = temp_stmnt;
}
}
this->is_independent_m = other.is_independent_m;
return *this;
}
/**
* Set the Variables value to the result of the expression rhs.
* Derivatives are calculated and stored in the encapsulated
* gradient map.
* @param rhs
* @return
*/
template<class T>
Variable& operator=(const ExpressionBase<REAL_T, T>& expr) {
// this->id_m = expr.GetId();
//has_m.resize(IDGenerator::instance()->current() + 1);
if (Variable::is_recording_g) {
// ind_iterator it; // = this->gradients.lower_bound();
#if defined(USE_HASH_TABLE)
for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
bool found = false;
this->gradients_m.Insert(*it)->value = expr.Derivative(*it, found);
// std::cout<<"diff wrt "<<(*it)<<" = " <<rhs.Derivative(*it, found);
}
#else
// for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
// bool found = false;
// this->gradients_m[(*it)] = expr.Derivative(*it, found);
// // std::cout<<"diff wrt "<<(*it)<<" = " <<rhs.Derivative(*it, found);
// }
#endif
expr.PushIds(ids_m);
// expr.GetIdRange(this->iv_min, this->iv_max);
// for (uint32_t i = this->iv_min; i< this->iv_max + 1; i++) {
indepedndent_variables_iterator it;
// for (uint32_t i = this->iv_min; i< this->iv_max + 1; i++) {
for (it = this->ids_m.begin(); it != ids_m.end(); ++it) {
bool found = false;
this->gradients_m[*it] = expr.Derivative(*it, found);
}
// expr.GetIdRange(this->iv_min, this->iv_max);
if (Variable::is_supporting_arbitrary_order) {
std::vector<Statement<REAL_T> > temp_stmnt;
expr.Push(temp_stmnt);
this->statements_m = temp_stmnt;
}
}
value_m = expr.GetValue();
return *this;
}
/**
*
* @param rhs
* @return
*/
template<class T>
Variable& operator+=(const ExpressionBase<REAL_T, T>& rhs) {
// return *this = (*this +rhs);
//has_m.resize(IDGenerator::instance()->current() + 1);
if (Variable::is_recording_g) {
#if defined(USE_HASH_TABLE)
for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
bool found = false;
this->gradients_m.Insert(*it)->value = this->gradients_m.Lookup(*it)->value + rhs.Derivative(*it, found);
}
#else
// for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
// bool found = false;
// this->gradients_m[(*it)] = this->gradients_m[(*it)] + rhs.Derivative(*it, found);
// }
#endif
// rhs.GetIdRange(this->iv_min, this->iv_max);
// for (uint32_t i = this->iv_min; i < this->iv_max + 1; i++) {
indepedndent_variables_iterator it;
rhs.PushIds(ids_m);
// for (uint32_t i = this->iv_min; i< this->iv_max + 1; i++) {
for (it = this->ids_m.begin(); it != ids_m.end(); ++it) {
bool found = true;
this->gradients_m[*it] = this->gradients_m[*it] + rhs.Derivative(*it, found);
}
if (Variable::is_supporting_arbitrary_order) {
rhs.Push(this->statements_m);
this->statements_m.push_back(Statement<REAL_T > (PLUS));
}
}
this->value_m += rhs.GetValue();
return *this;
}
Variable& operator+=(Variable& rhs) {
if (Variable::is_recording_g) {
//has_m.resize(IDGenerator::instance()->current() + 1);
#if defined(USE_HASH_TABLE)
for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
bool found = false;
this->gradients_m.Insert(*it)->value = this->gradients_m.Lookup(*it)->value + rhs.Derivative(*it, found);
}
#else
// for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
// bool found = false;
// this->gradients_m[(*it)] = this->gradients_m[(*it)] + rhs.Derivative(*it, found);
// }
#endif
// rhs.GetIdRange(this->iv_min, this->iv_max);
// for (uint32_t i = this->iv_min; i < this->iv_max + 1; i++) {
indepedndent_variables_iterator it;
rhs.PushIds(ids_m);
// for (uint32_t i = this->iv_min; i< this->iv_max + 1; i++) {
for (it = this->ids_m.begin(); it != ids_m.end(); ++it) {
bool found = true;
this->gradients_m[*it] = this->gradients_m[*it] + rhs.Derivative(*it, found);
}
if (Variable::is_supporting_arbitrary_order) {
rhs.Push(this->statements_m);
this->statements_m.push_back(Statement<REAL_T > (PLUS));
}
}
// rhs.GetIdRange(this->iv_min, this->iv_max);
this->value_m += rhs.GetValue();
return *this;
}
template<class T>
Variable& operator-=(const ExpressionBase<REAL_T, T>& rhs) {
return *this = (*this -rhs);
// if (Variable::is_recording_g) {
// ind_iterator it;
//#if defined(USE_HASH_TABLE)
// for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
// bool found = false;
// this->gradients_m.Insert((*it))->value = (this->gradients_m.Lookup(*it)->value - rhs.Derivative(*it, found));
// }
//#else
// for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
// bool found = false;
// this->gradients_m[(*it)] = (this->gradients_m[(*it)] - rhs.Derivative(*it, found));
// }
//#endif
// if (Variable::is_supporting_arbitrary_order) {
// rhs.Push(this->statements_m);
// this->statements_m.push_back(Statement(MINUS));
// }
// }
// this->value_m -= rhs.GetValue();
// return *this;
}
Variable& operator-=(Variable& rhs) {
if (Variable::is_recording_g) {
//has_m.resize(IDGenerator::instance()->current() + 1);
#if defined(USE_HASH_TABLE)
for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
bool found = false;
this->gradients_m.Insert((*it))->value = (this->gradients_m.Lookup(*it)->value - rhs.Derivative(*it, found));
}
#else
// for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
// bool found = false;
// this->gradients_m[(*it)] = (this->gradients_m[(*it)] - rhs.Derivative(*it, found));
// }
#endif
// rhs.GetIdRange(this->iv_min, this->iv_max);
// for (uint32_t i = this->iv_min; i < this->iv_max + 1; i++) {
indepedndent_variables_iterator it;
rhs.PushIds(ids_m);
// for (uint32_t i = this->iv_min; i< this->iv_max + 1; i++) {
for (it = this->ids_m.begin(); it != ids_m.end(); ++it) {
bool found = true;
this->gradients_m[*it] = this->gradients_m[*it] - rhs.Derivative(*it, found);
}
if (Variable::is_supporting_arbitrary_order) {
rhs.Push(this->statements_m);
this->statements_m.push_back(Statement<REAL_T > (MINUS));
}
}
this->value_m -= rhs.GetValue();
return *this;
}
template<class T>
Variable& operator*=(const ExpressionBase<REAL_T, T>& rhs) {
return *this = (*this * rhs);
// if (Variable::is_recording_g) {
// ind_iterator it;
//#if defined(USE_HASH_TABLE)
// for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
// bool found = false;
// this->gradients_m.Insert(*it)->value = this->gradients_m.Lookup(*it)->value * rhs.GetValue() + this->GetValue() * rhs.Derivative(*it, found);
// // std::cout<<"diff wrt "<<(*it)<<" = " <<rhs.Derivative(*it, found);
// }
//#else
// for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
// bool found = false;
// this->gradients_m[(*it)] = this->gradients_m[(*it)] * rhs.GetValue() + this->GetValue() * rhs.Derivative(*it, found);
// // std::cout<<"diff wrt "<<(*it)<<" = " <<rhs.Derivative(*it, found);
// }
//#endif
// if (Variable::is_supporting_arbitrary_order) {
// rhs.Push(this->statements_m);
// this->statements_m.push_back(Statement(MULTIPLY));
// }
// }
// this->value_m *= rhs.GetValue();
return *this;
}
Variable& operator*=(Variable& rhs) {
if (Variable::is_recording_g) {
//has_m.resize(IDGenerator::instance()->current() + 1);
#if defined(USE_HASH_TABLE)
for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
bool found = false;
this->gradients_m.Insert(*it)->value = this->gradients_m.Lookup(*it)->value * rhs.GetValue() + this->GetValue() * rhs.Derivative(*it, found);
// std::cout<<"diff wrt "<<(*it)<<" = " <<rhs.Derivative(*it, found);
}
#else
// for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
// bool found = false;
// this->gradients_m[(*it)] = this->gradients_m[(*it)] * rhs.GetValue() + this->GetValue() * rhs.Derivative(*it, found);
// // std::cout<<"diff wrt "<<(*it)<<" = " <<rhs.Derivative(*it, found);
// }
#endif
//
// rhs.GetIdRange(this->iv_min, this->iv_max);
// for (uint32_t i = this->iv_min; i < this->iv_max + 1; i++) {
indepedndent_variables_iterator it;
rhs.PushIds(ids_m);
// for (uint32_t i = this->iv_min; i< this->iv_max + 1; i++) {
for (it = this->ids_m.begin(); it != ids_m.end(); ++it) {
bool found = true;
this->gradients_m[*it] = this->gradients_m[*it] * rhs.GetValue() + this->GetValue() * rhs.Derivative(*it, found);
}
if (Variable::is_supporting_arbitrary_order) {
rhs.Push(this->statements_m);
this->statements_m.push_back(Statement<REAL_T > (MULTIPLY));
}
}
this->value_m *= rhs.GetValue();
return *this;
}
template<class T>
Variable& operator/=(const ExpressionBase<REAL_T, T>& rhs) {
return *this = (*this / rhs);
// if (Variable::is_recording_g) {
// ind_iterator it;
//#if defined(USE_HASH_TABLE)
// for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
// bool found = false;
// this->gradients_m.Insert(*it)->value = (this->gradients_m.Lookup(*it)->value * rhs.GetValue() - this->GetValue() * rhs.Derivative(*it, found)) / (rhs.GetValue() * rhs.GetValue());
// // std::cout<<"diff wrt "<<(*it)<<" = " <<rhs.Derivative(*it, found);
// }
//#else
// for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
// bool found = false;
// this->gradients_m[(*it)] = (this->gradients_m[(*it)] * rhs.GetValue() - this->GetValue() * rhs.Derivative(*it, found)) / (rhs.GetValue() * rhs.GetValue());
// // std::cout<<"diff wrt "<<(*it)<<" = " <<rhs.Derivative(*it, found);
// }
//#endif
// if (Variable::is_supporting_arbitrary_order) {
// rhs.Push(this->statements_m);
// this->statements_m.push_back(Statement(DIVIDE));
// }
// }
// this->value_m /= rhs.GetValue();
return *this;
}
Variable& operator/=(Variable& rhs) {
if (Variable::is_recording_g) {
//has_m.resize(IDGenerator::instance()->current() + 1);
#if defined(USE_HASH_TABLE)
for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
bool found = false;
this->gradients_m.Insert(*it)->value = (this->gradients_m.Lookup(*it)->value * rhs.GetValue() - this->GetValue() * rhs.Derivative(*it, found)) / (rhs.GetValue() * rhs.GetValue());
// std::cout<<"diff wrt "<<(*it)<<" = " <<rhs.Derivative(*it, found);
}
#else
// for (it = Variable::independent_variables_g.begin(); it != Variable::independent_variables_g.end(); ++it) {
// bool found = false;
// this->gradients_m[(*it)] = (this->gradients_m[(*it)] * rhs.GetValue() - this->GetValue() * rhs.Derivative(*it, found)) / (rhs.GetValue() * rhs.GetValue());
// // std::cout<<"diff wrt "<<(*it)<<" = " <<rhs.Derivative(*it, found);
// }
#endif
// rhs.GetIdRange(this->iv_min, this->iv_max);
// for (uint32_t i = this->iv_min; i < this->iv_max + 1; i++) {
indepedndent_variables_iterator it;
rhs.PushIds(ids_m);
// for (uint32_t i = this->iv_min; i< this->iv_max + 1; i++) {
for (it = this->ids_m.begin(); it != ids_m.end(); ++it) {
bool found = true;
this->gradients_m[*it] = (this->gradients_m[*it] * rhs.GetValue() - this->GetValue() * rhs.Derivative(*it, found)) / (rhs.GetValue() * rhs.GetValue());
//
}
if (Variable::is_supporting_arbitrary_order) {
rhs.Push(this->statements_m);
this->statements_m.push_back(Statement<REAL_T > (DIVIDE));
}
}
this->value_m /= rhs.GetValue();
return *this;
}
// And likewise for a Literal on the rhs
Variable& operator+=(const REAL_T& rhs) {
value_m += rhs;
if (Variable::IsRecording()) {
if (Variable::is_supporting_arbitrary_order) {
this->statements_m.push_back(Statement<REAL_T > (CONSTANT, rhs));
this->statements_m.push_back(Statement<REAL_T > (PLUS));
}
}
return *this;
}
Variable& operator-=(const REAL_T& rhs) {
if (Variable::IsRecording()) {
if (Variable::is_supporting_arbitrary_order) {
this->statements_m.push_back(Statement<REAL_T > (CONSTANT, rhs));
this->statements_m.push_back(Statement<REAL_T > (MINUS));
}
}
value_m -= rhs;
return *this;
}
Variable& operator*=(const REAL_T& rhs) {
if (Variable::IsRecording()) {
if (Variable::is_supporting_arbitrary_order) {
this->statements_m.push_back(Statement<REAL_T > (CONSTANT, rhs));
this->statements_m.push_back(Statement<REAL_T > (MULTIPLY));
}
}
return *this = (*this * rhs);
}
Variable& operator/=(const REAL_T& rhs) {
if (Variable::IsRecording()) {
if (Variable::is_supporting_arbitrary_order) {
this->statements_m.push_back(Statement<REAL_T > (CONSTANT, rhs));
this->statements_m.push_back(Statement<REAL_T > (DIVIDE));
}
}
return *this = (*this / rhs);
}
};
//list of independent variables by unique identifier.
// template<class REAL_T>
// std::set<uint32_t> Variable<REAL_T>::independent_variables_g;
template<class REAL_T>
uint32_t Variable<REAL_T>::misses_g = 0;
template<class REAL_T>
bool Variable<REAL_T>::is_recording_g = true;
template<class REAL_T>
bool Variable<REAL_T>::is_supporting_arbitrary_order = false;
template<class REAL_T>
class Var : public ExpressionBase<REAL_T, Var<REAL_T> > {
REAL_T value_m;
uint32_t iv_id_m; //id when is a independent Var.
std::string name_m;
bool bounded_m;
REAL_T min_boundary_m;
REAL_T max_boundary_m;
bool is_independent_m;
std::vector<REAL_T> gradient_m;
uint32_t iv_min; //if this Var is caching derivatives, this is the min independent Var.
uint32_t iv_max; //if this Var is caching derivatives, this is the max independent Var.
// static std::set<uint32_t> independent_Vars_g;
static bool is_recording_g;
static bool is_supporting_arbitrary_order;
// std::vector<bool> has_m;
typedef std::vector<Statement<REAL_T> > ExpressionStatements;
ExpressionStatements statements_m;
public:
/**
* Default conclassor.
*/
Var() : ExpressionBase<REAL_T, Var<REAL_T> >(0), value_m(0.0), bounded_m(false), is_independent_m(false), iv_id_m(0) {
}
/**
* Conclass a Var with a initial value. Optional parameter to make
* it a independent Var.
*
* @param value
* @param is_independent
*/
Var(const REAL_T& value, bool is_independent = false) : is_independent_m(is_independent), ExpressionBase<REAL_T, Var<REAL_T> >(0), value_m(value), iv_id_m(0) {
iv_min = std::numeric_limits<uint32_t>::max();
iv_max = std::numeric_limits<uint32_t>::min();
if (is_independent) {
// this->id_m = IDGenerator::instance()->next();
this->SetAsIndependent(is_independent);
this->bounded_m = false;
this->min_boundary_m = std::numeric_limits<REAL_T>::min();
this->max_boundary_m = std::numeric_limits<REAL_T>::max();
}
}
/**
* Copy conclassor.
*
* @param rhs
*/
Var(const Var& orig) {
value_m = orig.GetValue();
this->id_m = orig.GetId();
this->iv_id_m = orig.iv_id_m;
this->is_independent_m = orig.is_independent_m;
this->bounded_m = orig.bounded_m;
this->min_boundary_m = orig.min_boundary_m;
this->max_boundary_m = orig.max_boundary_m;
iv_min = orig.iv_min;
iv_max = orig.iv_max;
this->gradient_m = orig.gradient_m;
}
/**
* Conclasss a Var from expression expr.
* @param rhs
*/
template<class T>
Var(const ExpressionBase<REAL_T, T>& expr) {
//has_m.resize(IDGenerator::instance()->current() + 1);
this->bounded_m = false;
iv_min = std::numeric_limits<uint32_t>::max();
iv_max = std::numeric_limits<uint32_t>::min();
if (Var::is_recording_g) {
this->gradient_m.resize(IDGenerator::instance()->current() + 1);
expr.GetIdRange(this->iv_min, this->iv_max);
for (int i = this->iv_min; i < this->iv_max + 1; i++) {
bool found = false;
this->gradient_m[i] = expr.Derivative(i, found);
}
}
value_m = expr.GetValue();
}
~Var() {
#if !defined(USE_HASH_TABLE)
// if (this->is_independent_m) {
// this->independent_Vars_g.erase(this->GetId());
// }
this->statements_m.clear();
// this->gradients_m.clear();
#endif
}
size_t Size() {
return this->statements_m.size();
}
/**
* Control function. If true, derivatives are computed. If false
* expressions are only evaluated.
*
* @param is_recording
*/
static void SetRecording(const bool &is_recording) {
Var::is_recording_g = is_recording;
}
/**
* If true, derivatives are calculated and stored. If false,
* expressions are evaluated for value only.
*
* @return
*/
static bool IsRecording() {
return Var::is_recording_g;
}
/**
* If set to true, the expression is recorded into a vector of
* statements that can be manipulated to compute derivatives of
* arbitrary order. This functionality is costly and is rarely required,
* thus default setting is false.
*
* @param support_arbitrary_order
*/
static void SetSupportArbitraryOrder(const bool &support_arbitrary_order) {
Var::is_supporting_arbitrary_order = support_arbitrary_order;
}
/*
* If true, expressions are recorded into a vector of statements that
* can be used later to compute derivatives of arbitrary order, or
* be used to build expression strings.
*
*/
static bool IsSupportingArbitraryOrder() {
return Var::is_supporting_arbitrary_order;
}
/**
* Returns the value of this Var.
*
* @return
*/
inline const REAL_T GetValue() const {
return this->value_m;
}
/**
* Sets the value of this Var. If the Var is bounded,
* the value will be set between the min and max boundary. If the
* value is less than the minimum boundary, the Vars value is
* set to minimum boundary. If the value is greater than the maximum
* boundary, the Vars value is set to maximum boundary. If the
* value is signaling nan, the value is set to the mid point between
* the min and max boundary.
*
* @param value
*/
void SetValue(const REAL_T &value) {
if (this->bounded_m) {
if (value != value) {//nan
this->value_m = this->min_boundary_m + (this->max_boundary_m - this->min_boundary_m) / 2.0;
return;
}
if (value<this->min_boundary_m) {
this->value_m = this->min_boundary_m;
} else if (value>this->max_boundary_m) {
this->value_m = this->max_boundary_m;
} else {
this->value_m = value;
}
} else {
this->value_m = value;
}
}
/**
* Returns the name of this Var. Names are not initialized and
* if it is not set this function will return a empty string.
* @return
*/
std::string GetName() const {
return name_m;
}
/**
* Set the name of this Var.
*
* @param name
*/
void SetName(std::string name) {
this->name_m = name;
}
/**
* Returns true if this Var is bounded. Otherwise,
* false.
*
* @return
*/
bool IsBounded() {
return this->bounded_m;
}
/**
* Set the min and max boundary for this Var.
* @param min
* @param max
*/
void SetBounds(const REAL_T& min, const REAL_T& max) {
this->bounded_m = true;
this->max_boundary_m = max;
this->min_boundary_m = min;
this->SetValue(this->GetValue());
}
/**
* Return the minimum boundary for this Var. The default value
* is the results of std::numeric_limits<REAL_t>::min().
*
* @return
*/
const REAL_T GetMinBoundary() {
return this->min_boundary_m;
}
/**
* Return the maximum boundary for this Var. The default value
* is the results of std::numeric_limits<REAL_t>::max().
*
* @return
*/
const REAL_T GetMaxBoundary() {
return this->max_boundary_m;
}
/**
* Make this Var an independent Var. If set to true,
* the Vars unique identifier is registered in the static set
* of independent Vars. During function evaluations, gradient
* information is accumulated in post-order wrt to Vars in the
* static set of independent Vars. If set false, this Vars
* unique identifier will be removed from the set, if it existed.
*
*
* To access the derivative wrt to a Var, call function:
*
* const REAL_t wrt(const Var & ind)
*
*
* @param is_independent
*/
void SetAsIndependent(const bool &is_independent) {
if (this->iv_id_m == 0) {
this->iv_id_m = IDGenerator::instance()->next();
this->id_m = iv_id_m;
if (this->iv_min == std::numeric_limits<uint32_t>::max() && this->iv_max == std::numeric_limits<uint32_t>::min()) {
this->iv_max = this->GetId();
this->iv_min = this->GetId();
}
}
if (this->is_independent_m && !is_independent) {
// Var::independent_Vars_g.erase(this->GetId());
this->id_m = 0;
this->is_independent_m = false;
}
if (!this->is_independent_m && is_independent) {
// Var::independent_Vars_g.insert(this->GetId());
this->id_m = this->iv_id_m;
this->is_independent_m = true;
}
}
bool IsIndependent() {
return this->is_independent_m;
}
/**
* Returns the derivative with respect to a Vars who's
* unique identifier is equal to the parameter id.
*
* @param id
* @param found
* @return
*/
const REAL_T Derivative(const uint32_t &id, bool &found) const {
if (this->GetId() == id) {
found = true;
return 1.0;
} else {
if (id <= this->gradient_m.size()) {
REAL_T d = gradient_m[id];
if (d != 0) {
found = true;
return d;
} else {
return 0;
}
}
}
return 0.0;
}
void GetIdRange(uint32_t &min, uint32_t & max) const {
if (this->iv_min < min) {
min = this->iv_min;
}
if (this->iv_max > max) {
max = this->iv_max;
}
if (this->GetId() > 0) {
if (this->GetId() < min) {
min = this->GetId();
}
// if (this->GetId()) {
// max = this->GetId();
// }
}
//
// if (min == std::numeric_limits<uint32_t>::max()) {
// min = max;
// }
// std::cout << min << " " << max << "\n";
}
void Push(std::vector<Statement<REAL_T> > &statements) const {
statements.insert(statements.end(), this->statements_m.begin(), statements_m.end());
// if (this->statements_m.size() > 0) {
// statements.insert(statements.end(), this->statements_m.begin(), statements_m.end());
// } else {
// statements.push_back(Statement<REAL_T > (Var, this->GetValue(), this->GetId()));
// }
}
/**
* Finds the derivative in the encapsulated gradient map
* w.r.t a Var.
*
* @param ind
* @return
*/
const REAL_T WRT(const Var & ind) {
if (ind.GetId()<this->gradient_m.size()) {
return this->gradient_m[ind.GetId()];
} else {
return 0.0;
}
}
/**
* Finds the derivative in the encapsulated gradient map
* w.r.t a Var.
* @param ind
* @return
*/
const REAL_T WRT(const Var & ind) const {
if (ind.GetId()<this->gradient_m.size()) {
return this->gradient_m[ind.GetId()];
} else {
return 0.0;
}
}
const std::string Serialize() {
}
void Deserialize(const std::string &str) {
}
/**
* Set the Var equal to the real type rhs.
*
* The gradient map will be cleared.
*
* @param rhs
* @return
*/
Var& operator=(const REAL_T& rhs) {
this->SetValue(rhs);
if (Var::IsRecording()) {
this->gradient_m.clear();
}
return *this;
}
/**
* Sets the value of this Var to that of rhs. Derivatives
* are stored in the encapsulated gradient map.
*
* @param rhs
* @return
*/
Var& operator=(const Var& other) {
value_m = other.GetValue();
if (ad::Var<REAL_T>::is_recording_g) {
this->gradient_m = other.gradient_m;
}
this->is_independent_m = other.is_independent_m;
return *this;
}
/**
* Set the Vars value to the result of the expression rhs.
* Derivatives are calculated and stored in the encapsulated
* gradient map.
* @param rhs
* @return
*/
template<class T>
Var& operator=(const ExpressionBase<REAL_T, T>& expr) {
// this->id_m = expr.GetId();
//has_m.resize(IDGenerator::instance()->current() + 1);
if (Var::is_recording_g) {
this->gradient_m.resize(IDGenerator::instance()->current() + 1);
expr.GetIdRange(this->iv_min, this->iv_max);
for (int i = this->iv_min; i < this->iv_max + 1; i++) {
bool found = false;
this->gradient_m[i] = expr.Derivative(i, found);
}
}
value_m = expr.GetValue();
return *this;
}
/**
*
* @param rhs
* @return
*/
template<class T>
Var& operator+=(const ExpressionBase<REAL_T, T>& rhs) {
return *this = (*this +rhs);
// //has_m.resize(IDGenerator::instance()->current() + 1);
// if (Var::is_recording_g) {
//
// }
// this->value_m += rhs.GetValue();
// return *this;
}
Var& operator+=(Var& rhs) {
if (Var::is_recording_g) {
this->gradient_m.resize(IDGenerator::instance()->current() + 1);
rhs.GetIdRange(this->iv_min, this->iv_max);
for (int i = this->iv_min; i < this->iv_max + 1; i++) {
bool found = false;
this->gradient_m[i] = this->gradient_m[i] + rhs.Derivative(i, found);
}
}
this->value_m += rhs.GetValue();
return *this;
}
template<class T>
Var& operator-=(const ExpressionBase<REAL_T, T>& rhs) {
return *this = (*this -rhs);
}
Var& operator-=(Var& rhs) {
if (Var::is_recording_g) {
this->gradient_m.resize(IDGenerator::instance()->current() + 1);
rhs.GetIdRange(this->iv_min, this->iv_max);
for (int i = this->iv_min; i < this->iv_max + 1; i++) {
bool found = false;
this->gradient_m[i] = this->gradient_m[i] - rhs.Derivative(i, found);
}
}
this->value_m -= rhs.GetValue();
return *this;
}
template<class T>
Var& operator*=(const ExpressionBase<REAL_T, T>& rhs) {
return *this = (*this * rhs);
return *this;
}
Var& operator*=(Var& rhs) {
if (Var::is_recording_g) {
}
this->value_m *= rhs.GetValue();
return *this;
}
template<class T>
Var& operator/=(const ExpressionBase<REAL_T, T>& rhs) {
return *this = (*this / rhs);
return *this;
}
Var& operator/=(Var& rhs) {
if (Var::is_recording_g) {
}
this->value_m /= rhs.GetValue();
return *this;
}
// And likewise for a Literal on the rhs
Var& operator+=(const REAL_T& rhs) {
value_m += rhs;
if (Var::IsRecording()) {
if (Var::is_supporting_arbitrary_order) {
this->statements_m.push_back(Statement<REAL_T > (CONSTANT, rhs));
this->statements_m.push_back(Statement<REAL_T > (PLUS));
}
}
return *this;
}
Var& operator-=(const REAL_T& rhs) {
if (Var::IsRecording()) {
if (Var::is_supporting_arbitrary_order) {
this->statements_m.push_back(Statement<REAL_T > (CONSTANT, rhs));
this->statements_m.push_back(Statement<REAL_T > (MINUS));
}
}
value_m -= rhs;
return *this;
}
Var& operator*=(const REAL_T& rhs) {
if (Var::IsRecording()) {
if (Var::is_supporting_arbitrary_order) {
this->statements_m.push_back(Statement<REAL_T > (CONSTANT, rhs));
this->statements_m.push_back(Statement<REAL_T > (MULTIPLY));
}
}
return *this = (*this * rhs);
}
Var& operator/=(const REAL_T& rhs) {
if (Var::IsRecording()) {
if (Var::is_supporting_arbitrary_order) {
this->statements_m.push_back(Statement<REAL_T > (CONSTANT, rhs));
this->statements_m.push_back(Statement<REAL_T > (DIVIDE));
}
}
return *this = (*this / rhs);
}
};
template<class REAL_T>
bool Var<REAL_T>::is_recording_g = true;
template<class REAL_T, class T, class TT>
inline const int operator==(const ad::ExpressionBase<REAL_T, T>& lhs, const ad::ExpressionBase<REAL_T, TT>& rhs) {
return lhs.GetValue() == rhs.GetValue();
}
template<class REAL_T, class T, class TT>
inline const int operator!=(const ad::ExpressionBase<REAL_T, T>& lhs, const ad::ExpressionBase<REAL_T, TT>& rhs) {
return lhs.GetValue() != rhs.GetValue();
}
template<class REAL_T, class T, class TT>
inline const int operator<(const ad::ExpressionBase<REAL_T, T>& lhs, const ad::ExpressionBase<REAL_T, TT>& rhs) {
return lhs.GetValue() < rhs.GetValue();
}
template<class REAL_T, class T, class TT>
inline const int operator>(const ad::ExpressionBase<REAL_T, T>& lhs, const ad::ExpressionBase<REAL_T, TT>& rhs) {
return lhs.GetValue() > rhs.GetValue();
}
template<class REAL_T, class T, class TT>
inline const int operator<=(const ad::ExpressionBase<REAL_T, T>& lhs, const ad::ExpressionBase<REAL_T, TT>& rhs) {
return lhs.GetValue() <= rhs.GetValue();
}
template<class REAL_T, class T, class TT>
inline const int operator>=(const ad::ExpressionBase<REAL_T, T>& lhs, const ad::ExpressionBase<REAL_T, TT>& rhs) {
return lhs.GetValue() >= rhs.GetValue();
}
template<class REAL_T, class T>
inline const int operator==(const REAL_T &lhs, const ad::ExpressionBase<REAL_T, T>& rhs) {
return lhs == rhs.GetValue();
}
template<class REAL_T, class T>
inline const int operator!=(const REAL_T &lhs, const ad::ExpressionBase<REAL_T, T>& rhs) {
return lhs != rhs.GetValue();
}
template<class REAL_T, class T>
inline const int operator<(const REAL_T &lhs, const ad::ExpressionBase<REAL_T, T>& rhs) {
return lhs < rhs.GetValue();
}
template<class REAL_T, class T>
inline const int operator>(const REAL_T &lhs, const ad::ExpressionBase<REAL_T, T>& rhs) {
return lhs > rhs.GetValue();
}
template<class REAL_T, class T>
inline const int operator<=(const REAL_T &lhs, const ad::ExpressionBase<REAL_T, T>& rhs) {
return lhs <= rhs.GetValue();
}
template<class REAL_T, class T>
inline const int operator>=(const REAL_T &lhs, const ad::ExpressionBase<REAL_T, T>& rhs) {
return lhs >= rhs.GetValue();
}
template<class REAL_T, class T>
inline const int operator==(const ad::ExpressionBase<REAL_T, T>& lhs, const REAL_T &rhs) {
return lhs.GetValue() == rhs;
}
template<class REAL_T, class T>
inline const int operator!=(const ad::ExpressionBase<REAL_T, T>& lhs, const REAL_T &rhs) {
return lhs.GetValue() != rhs;
}
template<class REAL_T, class T>
inline const int operator<(const ad::ExpressionBase<REAL_T, T>& lhs, const REAL_T &rhs) {
return lhs.GetValue() <= rhs;
}
template<class REAL_T, class T>
inline const int operator>(const ad::ExpressionBase<REAL_T, T>& lhs, const REAL_T &rhs) {
return lhs.GetValue() > rhs;
}
template<class REAL_T, class T>
inline const int operator<=(const ad::ExpressionBase<REAL_T, T>& lhs, const REAL_T &rhs) {
return lhs.GetValue() <= rhs;
}
template<class REAL_T, class T>
inline const int operator>=(const ad::ExpressionBase<REAL_T, T>& lhs, const REAL_T &rhs) {
return lhs.GetValue() >= rhs;
}
}
/**
* Array components.
*/
namespace array {
}
#endif /* ETAD_HPP */
| [
"matthewsupernaw@192.168.0.6"
] | matthewsupernaw@192.168.0.6 |
691905f597b4cffa3eaa34cc10ac1fa68a629438 | 15fa84be8a4bd33cf3cb8fb28ae515cf4ad6883f | /src/Directory.cpp | 64711f117b959dc67f68cc9eb51f33925d730cb8 | [] | no_license | SherwinKing/Cache-Coherence-Sim | fcea5b53e91ef5f3f477c6914861d8d49dac75be | e48acc18395ac6b60701c0062604be20e92bbaf7 | refs/heads/main | 2023-04-29T21:08:42.880918 | 2021-05-14T03:58:47 | 2021-05-14T03:58:47 | 365,085,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,695 | cpp | #include "Directory.h"
long Directory::getLineID(long address){
// effectively tag+set
return address >> b_;
}
long Directory::getLineID(long setID, long tag){
return setID | tag << s_;
}
/**
* @return true when line already exist, false means not in any caches
*/
bool Directory::getLine(DirectoryLine** line_ptr, long lineID){
auto it = directory_.find(lineID);
if(it == directory_.end()){
*line_ptr = new DirectoryLine(numCaches_);
directory_.insert({lineID, *line_ptr});
return false;
}
*line_ptr = it->second;
return true;
}
Response Directory::requestHandler(Request request, int sourceID){
if(mode_ == DIRECTORY)
return requestHandler_DIREC(request, sourceID);
if(mode_ == TOKEN)
return requestHandler_TOKEN(request, sourceID);
}
void Directory::evictionHandler(int sourceID, long setID, long tag, int token){
if(mode_ == DIRECTORY)
evictionHandler_DIREC(sourceID, setID, tag, token);
if(mode_ == TOKEN)
evictionHandler_TOKEN(sourceID, setID, tag, token);
}
Response Directory::requestHandler_TOKEN(Request request, int sourceID){
Response response(TOKEN_RESPONSE);
assert(request.getRequestType() == TOKEN_REQUEST_R ||
request.getRequestType() == TOKEN_REQUEST_W);
assert(request.getCoherenceType() == TOKEN);
long address = request.getRequestAddress();
long lineID = getLineID(address);
DirectoryLine* line;
bool if_exist = getLine(&line, lineID);
// add memory fetch latency
if(!if_exist)
stat_.addLatency(-1, 200);
if(request.getRequestType() == TOKEN_REQUEST_R){
if(line->token_pool_ > 0){
line->token_pool_--;
response.setTokenNum(1);
}
else
response.setTokenNum(0);
}
if(request.getRequestType() == TOKEN_REQUEST_W){
if(line->token_pool_ > 0){
response.setTokenNum(line->token_pool_);
line->token_pool_ = 0;
}
else
response.setTokenNum(0);
}
return response;
}
void Directory::evictionHandler_TOKEN(int sourceID, long setID, long tag, int token){
long lineID = getLineID(setID, tag);
DirectoryLine* line;
bool if_exist = getLine(&line, lineID);
assert(if_exist);
assert(token >= 0);
line->token_pool_ += token;
if(line->token_pool_ == numCaches_){
directory_.erase(lineID);
delete line;
}
}
Response Directory::requestHandler_DIREC(Request request, int sourceID){
Response response(DIRECTORY_RESPONSE);
assert(request.getRequestType() == DIRECTORY_REQUEST_R ||
request.getRequestType() == DIRECTORY_REQUEST_W);
assert(request.getCoherenceType() == DIRECTORY);
long address = request.getRequestAddress();
long lineID = getLineID(address);
DirectoryLine* line;
bool if_exist = getLine(&line, lineID);
// memory fetch latency
if(!if_exist)
stat_.addLatency(-1, 200);
// read operation
if(request.getRequestType() == DIRECTORY_REQUEST_R){
// read miss means cache does not have the line
assert(!line->presence_[sourceID]);
if(line->dirty_){
std::list<int> cacheOwnerID;
for(int i=0; i<numCaches_; i++){
if(line->presence_[i])
cacheOwnerID.push_back(i);
}
// only one cache can be on M state
assert(cacheOwnerID.size() == 1);
line->dirty_ = false;
line->presence_[sourceID] = true;
response.setCacheOwnerIDs(cacheOwnerID);
}
else{
std::list<int> cacheOwnerIDs;
for(int i=0; i<numCaches_; i++){
if(line->presence_[i])
cacheOwnerIDs.push_back(i);
}
line->presence_[sourceID] = true;
response.setCacheOwnerIDs(cacheOwnerIDs);
}
}
// write operation
if(request.getRequestType() == DIRECTORY_REQUEST_W){
if(line->dirty_){
std::list<int> cacheOwnerID;
for(int i=0; i<numCaches_; i++){
if(line->presence_[i]){
cacheOwnerID.push_back(i);
line->presence_[i] = false;
}
}
assert(cacheOwnerID.size() == 1);
line->presence_[sourceID] = true;
response.setCacheOwnerIDs(cacheOwnerID);
}
else{
std::list<int> cacheOwnerIDs;
for(int i=0; i<numCaches_; i++){
if(i == sourceID)
continue;
if(line->presence_[i]){
cacheOwnerIDs.push_back(i);
line->presence_[i] = false;
}
}
line->dirty_ = true;
line->presence_[sourceID] = true;
response.setCacheOwnerIDs(cacheOwnerIDs);
}
}
return response;
}
void Directory::evictionHandler_DIREC(int sourceID, long setID, long tag, int token){
long lineID = getLineID(setID, tag);
DirectoryLine* line;
bool if_exist = getLine(&line, lineID);
assert(if_exist);
// evicted line might be invalid
//assert(line->presence_[sourceID]);
line->presence_[sourceID] = false;
if(line->dirty_){
for(auto p : line->presence_)
assert(!p);
directory_.erase(lineID);
delete line;
}
else{
bool any_valid = false;
for(auto p : line->presence_)
if(p) any_valid = true;
if(!any_valid){
directory_.erase(lineID);
delete line;
}
}
}
| [
"qiuje98@outlook.com"
] | qiuje98@outlook.com |
f7c87fed327b6be955f3c83c5f488cdf313068f9 | cae710ed9f38e5c87c99ae5eca1a9cb2efa0bcad | /psol/include/net/instaweb/rewriter/public/css_filter.h | 0d0d9a377d4a466221adec03c084007ee4ef31a3 | [
"Apache-2.0"
] | permissive | sambacha/nginx2 | 2de50c98ebdd1d65d159f921f88c426249a4940b | ed70546e69d0357831adfd982104c077ac23970b | refs/heads/master | 2023-03-28T07:35:32.013909 | 2021-03-27T17:25:36 | 2021-03-27T17:25:36 | 349,439,159 | 0 | 0 | Apache-2.0 | 2021-03-19T13:52:06 | 2021-03-19T13:50:16 | C++ | UTF-8 | C++ | false | false | 17,259 | h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 NET_INSTAWEB_REWRITER_PUBLIC_CSS_FILTER_H_
#define NET_INSTAWEB_REWRITER_PUBLIC_CSS_FILTER_H_
#include "net/instaweb/rewriter/cached_result.pb.h"
#include "net/instaweb/rewriter/public/css_hierarchy.h"
#include "net/instaweb/rewriter/public/css_resource_slot.h"
#include "net/instaweb/rewriter/public/css_url_encoder.h"
#include "net/instaweb/rewriter/public/output_resource_kind.h"
#include "net/instaweb/rewriter/public/resource.h"
#include "net/instaweb/rewriter/public/resource_slot.h"
#include "net/instaweb/rewriter/public/rewrite_context.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_filter.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/rewriter/public/server_context.h"
#include "net/instaweb/rewriter/public/single_rewrite_context.h"
#include "pagespeed/kernel/base/basictypes.h"
#include "pagespeed/kernel/base/scoped_ptr.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/html/html_element.h"
#include "pagespeed/kernel/html/html_node.h"
#include "pagespeed/kernel/http/google_url.h"
#include "pagespeed/kernel/util/url_segment_encoder.h"
namespace Css {
class Stylesheet;
} // namespace Css
namespace net_instaweb {
class AssociationTransformer;
class AsyncFetch;
class CssImageRewriter;
class CacheExtender;
class ImageCombineFilter;
class ImageRewriteFilter;
class MessageHandler;
class RewriteDomainTransformer;
class Statistics;
class UpDownCounter;
class Variable;
// Find and parse all CSS in the page and apply transformations including:
// minification, combining, refactoring, and optimizing sub-resources.
//
// Currently only does basic minification.
//
// Note that CssCombineFilter currently does combining (although there is a bug)
// but CssFilter will eventually replace this.
//
// Currently only deals with inline <style> tags and external <link> resources.
// It does not consider style= attributes on arbitrary elements.
class CssFilter : public RewriteFilter {
public:
class Context;
CssFilter(RewriteDriver* driver,
// TODO(sligocki): Temporary pattern until we figure out a better
// way to do this without passing all filters around everywhere.
CacheExtender* cache_extender,
ImageRewriteFilter* image_rewriter,
ImageCombineFilter* image_combiner);
virtual ~CssFilter();
// May be called multiple times, in case there are multiple statistics
// objects.
static void InitStats(Statistics* statistics);
// Initialize & Terminate must be paired.
static void Initialize();
static void Terminate();
// Add this filters related options to the given vector.
static void AddRelatedOptions(StringPieceVector* target);
virtual void StartDocumentImpl();
virtual void StartElementImpl(HtmlElement* element);
virtual void Characters(HtmlCharactersNode* characters);
virtual void EndElementImpl(HtmlElement* element);
virtual const char* Name() const { return "CssFilter"; }
virtual const char* id() const { return RewriteOptions::kCssFilterId; }
virtual void EncodeUserAgentIntoResourceContext(
ResourceContext* context) const;
static const char kBlocksRewritten[];
static const char kParseFailures[];
static const char kFallbackRewrites[];
static const char kFallbackFailures[];
static const char kRewritesDropped[];
static const char kTotalBytesSaved[];
static const char kTotalOriginalBytes[];
static const char kUses[];
static const char kCharsetMismatch[];
static const char kInvalidUrl[];
static const char kLimitExceeded[];
static const char kMinifyFailed[];
static const char kRecursion[];
static const char kComplexQueries[];
RewriteContext* MakeNestedFlatteningContextInNewSlot(
const ResourcePtr& resource, const GoogleString& location,
CssFilter::Context* rewriter, RewriteContext* parent,
CssHierarchy* hierarchy);
virtual const RewriteOptions::Filter* RelatedFilters(int* num_filters) const {
*num_filters = merged_filters_size_;
return merged_filters_;
}
virtual const StringPieceVector* RelatedOptions() const {
return related_options_;
}
protected:
virtual RewriteContext* MakeRewriteContext();
virtual const UrlSegmentEncoder* encoder() const;
virtual RewriteContext* MakeNestedRewriteContext(
RewriteContext* parent, const ResourceSlotPtr& slot);
private:
friend class Context;
friend class CssFlattenImportsContext; // for statistics
friend class CssHierarchy; // for statistics
enum InlineCssKind {
kInsideStyleTag,
kAttributeWithoutUrls,
kAttributeWithUrls
};
Context* MakeContext(RewriteDriver* driver,
RewriteContext* parent);
// Starts the asynchronous rewrite process for inline CSS 'text'.
void StartInlineRewrite(HtmlCharactersNode* text,
HtmlElement* parent_element);
// Starts the asynchronous rewrite process for inline CSS inside the given
// element's given style attribute.
void StartAttributeRewrite(HtmlElement* element,
HtmlElement::Attribute* style,
InlineCssKind inline_css_kind);
// Starts the asynchronous rewrite process for external CSS referenced by
// attribute 'src' of 'link'.
void StartExternalRewrite(HtmlElement* link, HtmlElement::Attribute* src);
ResourcePtr MakeInlineResource(StringPiece content);
CssFilter::Context* StartRewriting(const ResourceSlotPtr& slot);
// Get the charset of the HTML being parsed which can be specified in the
// driver's headers, defaulting to ISO-8859-1 if isn't. Then, if a charset
// is specified in the given element, check that they agree, and if not
// return false and set the failure reason, otherwise return true and assign
// the first charset to '*charset'.
bool GetApplicableCharset(const HtmlElement* element,
GoogleString* charset,
GoogleString* failure_reason) const;
// Get the media specified in the given element, if any. Returns true if
// media were found false if not.
bool GetApplicableMedia(const HtmlElement* element,
StringVector* media) const;
bool in_style_element_; // Are we in a style element?
// This is meaningless if in_style_element_ is false:
HtmlElement* style_element_; // The element we are in.
// The charset extracted from a meta tag, if any.
GoogleString meta_tag_charset_;
// Filters we delegate to.
CacheExtender* cache_extender_;
ImageRewriteFilter* image_rewrite_filter_;
ImageCombineFilter* image_combiner_;
// Statistics
// # of CSS blocks (CSS files, <style> blocks or style= attributes)
// successfully rewritten.
Variable* num_blocks_rewritten_;
// # of CSS blocks that rewriter failed to parse.
Variable* num_parse_failures_;
// # of CSS blocks that failed to be parsed, but were rewritten in the
// fallback path.
Variable* num_fallback_rewrites_;
// # of CSS blocks that failed to be rewritten in the fallback path.
Variable* num_fallback_failures_;
// # of CSS rewrites which were not applied because they made the CSS larger
// and did not rewrite any images in it/flatten any other CSS files into it.
Variable* num_rewrites_dropped_;
// # of bytes saved from rewriting CSS (including minification and the
// increase of bytes from longer image URLs and the increase of bytes
// from @import flattening).
// TODO(sligocki): This should consider the input size to be the input sizes
// of all CSS files flattened into this one. Currently it does not.
UpDownCounter* total_bytes_saved_;
// Sum of original bytes of all successfully rewritten CSS blocks.
// total_bytes_saved_ / total_original_bytes_ should be the
// average percentage reduction of CSS block size.
Variable* total_original_bytes_;
// # of uses of rewritten CSS (updating <link> href= attributes,
// <style> contents or style= attributes).
Variable* num_uses_;
// # of times CSS was not flattened because of a charset mismatch.
Variable* num_flatten_imports_charset_mismatch_;
// # of times CSS was not flattened because of an invalid @import URL.
Variable* num_flatten_imports_invalid_url_;
// # of times CSS was not flattened because the resulting CSS too big.
Variable* num_flatten_imports_limit_exceeded_;
// # of times CSS was not flattened because minification failed.
Variable* num_flatten_imports_minify_failed_;
// # of times CSS was not flattened because of recursive imports.
Variable* num_flatten_imports_recursion_;
// # of times CSS was not flattened because it had complex media queries.
Variable* num_flatten_imports_complex_queries_;
CssUrlEncoder encoder_;
// The filters related to this filter.
static const RewriteOptions::Filter* merged_filters_;
static int merged_filters_size_;
// The options related to this filter.
static StringPieceVector* related_options_;
DISALLOW_COPY_AND_ASSIGN(CssFilter);
};
// Context used by CssFilter under async flow.
class CssFilter::Context : public SingleRewriteContext {
public:
Context(CssFilter* filter, RewriteDriver* driver,
RewriteContext* parent,
CacheExtender* cache_extender,
ImageRewriteFilter* image_rewriter,
ImageCombineFilter* image_combiner,
ResourceContext* context);
virtual ~Context();
// Setup rewriting for inline, attribute, or external CSS.
void SetupInlineRewrite(HtmlElement* style_element, HtmlCharactersNode* text);
void SetupAttributeRewrite(HtmlElement* element,
HtmlElement::Attribute* src,
InlineCssKind inline_css_kind);
void SetupExternalRewrite(HtmlElement* element,
const GoogleUrl& base_gurl,
const GoogleUrl& trim_gurl);
// Starts nested rewrite jobs for any imports or images contained in the CSS.
// Marked public, so that it's accessible from CssHierarchy.
void RewriteCssFromNested(RewriteContext* parent, CssHierarchy* hierarchy);
// Specialization to absolutify URLs in input resource in case of rewrite
// fail or deadline exceeded.
virtual bool SendFallbackResponse(StringPiece output_url_base,
StringPiece input_contents,
AsyncFetch* async_fetch,
MessageHandler* handler);
CssResourceSlotFactory* slot_factory() { return &slot_factory_; }
CssHierarchy* mutable_hierarchy() { return &hierarchy_; }
protected:
bool PolicyPermitsRendering() const override;
void Render() override;
virtual void Harvest();
virtual bool Partition(OutputPartitions* partitions,
OutputResourceVector* outputs);
virtual void RewriteSingle(const ResourcePtr& input,
const OutputResourcePtr& output);
virtual const char* id() const { return filter_->id(); }
virtual OutputResourceKind kind() const { return kRewrittenResource; }
virtual GoogleString CacheKeySuffix() const;
virtual const UrlSegmentEncoder* encoder() const;
// Implements UserAgentCacheKey method of RewriteContext.
virtual GoogleString UserAgentCacheKey(
const ResourceContext* resource_context) const;
private:
void GetCssBaseUrlToUse(const ResourcePtr& input_resource,
GoogleUrl* css_base_gurl_to_use);
void GetCssTrimUrlToUse(const ResourcePtr& input_resource,
const StringPiece& output_url_base,
GoogleUrl* css_base_gurl_to_use);
void GetCssTrimUrlToUse(const ResourcePtr& input_resource,
const OutputResourcePtr& output_resource,
GoogleUrl* css_base_gurl_to_use);
bool RewriteCssText(const GoogleUrl& css_base_gurl,
const GoogleUrl& css_trim_gurl,
const StringPiece& in_text,
int64 in_text_size,
bool text_is_declarations,
MessageHandler* handler);
// Starts nested rewrite jobs for any imports or images contained in the CSS.
void RewriteCssFromRoot(const GoogleUrl& css_base_gurl,
const GoogleUrl& css_trim_gurl,
const StringPiece& in_text, int64 in_text_size,
bool has_unparseables, Css::Stylesheet* stylesheet);
// Fall back to using CssTagScanner to find the URLs and rewrite them
// that way. Like RewriteCssFromRoot, output is written into output
// resource in Harvest(). Called if CSS Parser fails to parse doc.
// Returns whether or not fallback rewriting succeeds. Fallback can fail
// if URLs in CSS are not parseable.
bool FallbackRewriteUrls(const GoogleUrl& css_base_gurl,
const GoogleUrl& css_trim_gurl,
const StringPiece& in_text);
// Tries to write out a (potentially edited) stylesheet out to out_text,
// and returns whether we should consider the result as an improvement.
bool SerializeCss(int64 in_text_size,
const Css::Stylesheet* stylesheet,
const GoogleUrl& css_base_gurl,
const GoogleUrl& css_trim_gurl,
bool previously_optimized,
bool stylesheet_is_declarations,
bool add_utf8_bom,
GoogleString* out_text,
MessageHandler* handler);
// Used by the asynchronous rewrite callbacks (RewriteSingle + Harvest) to
// determine if what is being rewritten is a style attribute or a stylesheet,
// since an attribute comprises only declarations, unlike a stlyesheet.
bool IsInlineAttribute() const {
return (rewrite_inline_attribute_ != NULL);
}
// Determine the appropriate image inlining threshold based upon whether we're
// in an html file (<style> tag or style= attribute) or in an external css
// file.
int64 ImageInlineMaxBytes() const;
virtual bool ScheduleViaCentralController() { return true; }
CssFilter* filter_;
scoped_ptr<CssImageRewriter> css_image_rewriter_;
ImageRewriteFilter* image_rewrite_filter_;
CssResourceSlotFactory slot_factory_;
CssHierarchy hierarchy_;
bool css_rewritten_;
bool has_utf8_bom_;
// Are we performing a fallback rewrite?
bool fallback_mode_;
// Transformer used by CssTagScanner to rewrite URLs if we failed to
// parse CSS. This will only be defined if CSS parsing failed.
scoped_ptr<AssociationTransformer> fallback_transformer_;
// Backup transformer for AssociationTransformer. Absolutifies URLs and
// rewrites their domains as necessary if they can't be cache extended.
scoped_ptr<RewriteDomainTransformer> absolutifier_;
// The element containing the CSS being rewritten, either a script element
// (inline), a link element (external), or anything with a style attribute.
HtmlElement* rewrite_element_;
// Style element containing inline CSS (see StartInlineRewrite) -or-
// any element with a style attribute (see StartAttributeRewrite), or
// NULL if we're rewriting external stuff.
HtmlElement* rewrite_inline_element_;
// Node with inline CSS to rewrite, or NULL if we're rewriting external stuff.
HtmlCharactersNode* rewrite_inline_char_node_;
// The style attribute associated with rewrite_inline_element_. Mutually
// exclusive with rewrite_inline_char_node_ since style elements cannot
// have style attributes.
HtmlElement::Attribute* rewrite_inline_attribute_;
// Indicates the kind of CSS inline CSS we are rewriting (<style> vs. style=,
// and whether we've noticed any URLs). Only valid if the other
// rewrite_inline_ fields reflect us doing inline rewriting.
InlineCssKind rewrite_inline_css_kind_;
// Information needed for nested rewrites or finishing up serialization.
int64 in_text_size_;
GoogleUrl initial_css_base_gurl_;
GoogleUrl initial_css_trim_gurl_;
scoped_ptr<GoogleUrl> base_gurl_for_fallback_;
scoped_ptr<GoogleUrl> trim_gurl_for_fallback_;
ResourcePtr input_resource_;
OutputResourcePtr output_resource_;
DISALLOW_COPY_AND_ASSIGN(Context);
};
} // namespace net_instaweb
#endif // NET_INSTAWEB_REWRITER_PUBLIC_CSS_FILTER_H_
| [
"janitor@contractshark.io"
] | janitor@contractshark.io |
3d594ff5b6445b9faa65fbcb0065599b85f30850 | 06efb9f40fe49409c266e427d49d0d96b9d48de1 | /srLib/srDyn/srISLAND.h | 4e5678fd6522ceea5a941ebf7f04f01812386d58 | [] | no_license | 0000duck/srLib_HCRL | 844cd3557ffb9778556acf0fac74064f75686e82 | ffcdd4613feae7e763e89307516f51018bd2d9ce | refs/heads/master | 2020-07-16T14:00:41.599361 | 2018-01-30T20:07:50 | 2018-01-30T20:07:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,425 | h |
#include "srDyn/srConstraint.h"
#include "srDyn/srSystem.h"
#include "LieGroup/_array.h"
//-- LCP Solver PGS
#define LCP_PGS_RANDOMLY_REORDER_CONSTRAINTS 1
#define LCP_PGS_OPTION_DEFAULT_ITERMAX 30
#define LCP_PGS_OPTION_DEFAULT_SOR_W 0.9
#define LCP_PGS_OPTION_DEFAULT_EPS_EA 1E-3
#define LCP_PGS_OPTION_DEFAULT_EPS_RESIDUAL 1E-6
#define LCP_PGS_OPTION_DEFAULT_EPS_DIVIDE 1E-9
//***********************************************//
struct PGSOption
{
int itermax;
SR_REAL sor_w;
SR_REAL eps_ea;
SR_REAL eps_res;
SR_REAL eps_div;
void SetDefault();
};
bool LCPSolver_PGS____MARK3(int n, int nskip, int nub, SR_REAL * A, SR_REAL * x, SR_REAL * b,
SR_REAL * lo, SR_REAL * hi, int * findex, PGSOption * option);
bool LCPSolver_PGS____MARK4(int n, int nskip, int nub, SR_REAL * A, SR_REAL * x, SR_REAL * b,
SR_REAL * lo, SR_REAL * hi, int * findex, PGSOption * option);
bool LCPSolver_SPARSE_PGS____MARK1(int n, int * r, int * c, int * rowofs, SR_REAL * A,
SR_REAL * x, SR_REAL * b, SR_REAL * lo, SR_REAL * hi,
int * findex, PGSOption * option);
// given (A,b,lo,hi), solve the LCP problem: A*x = b+w, where each x(i),w(i)
// satisfies one of
// (1) x = lo, w >= 0
// (2) x = hi, w <= 0
// (3) lo < x < hi, w = 0
// A is a matrix of dimension n*n, everything else is a vector of size n*1.
// lo and hi can be +/- dInfinity as needed. the first `nub' variables are
// unbounded, i.e. hi and lo are assumed to be +/- dInfinity.
//
// we restrict lo(i) <= 0 and hi(i) >= 0.
//
// the original data (A,b) may be modified by this function.
//
// if the `findex' (friction index) parameter is non-negative, it points to an array
// of index values. in this case constraints that have findex[i] >= 0, the lo and hi values
// for the special constraints are set:
// hi[i] = abs( hi[i] * x[findex[i]] )
// lo[i] = -hi[i]
// and the solution continues. this mechanism allows a friction approximation
// to be implemented. the first `nub' variables are assumed to have findex < 0.
class ISLAND
{
public:
// MARK8
ConstraintInfo m_cinfo;
srSystem* m_ID;
ConstraintPtrArray m_AllConstraints;
int m_nConstraints;
void _PGS_Solve_Constraint_____________________MARK7(PGSOption * option);
void _SPARSE_PGS_Solve_Constraint______________MARK11(PGSOption * option);
};
| [
"junhyeokahn91@gmail.com"
] | junhyeokahn91@gmail.com |
5cde2ff55b5ca75beaf1a714adef8a508bd9fde9 | 0b11c8c54b1e71ae935ea032376e785be8bfb65e | /3963_37.cpp | 149725fafea4a417295872b3cf13b5db0081135b | [] | no_license | wyx150137/wyx-infinity37-ac-code-on-BZOJ | 320bef65927b065c938dec97c44fc599fac14176 | 5a1cc0803e0356e59f6e679e6aed23f8374ab67b | refs/heads/master | 2020-06-25T01:45:51.676298 | 2017-07-12T23:45:45 | 2017-07-12T23:45:45 | 96,950,945 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,739 | cpp |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 1e5+5;
struct data
{
int d,p,r,g,id;
ll x,y;
void read()
{
scanf("%d%d%d%d",&d,&p,&r,&g);
x = g,y = r-p-(ll)d*g-g;
}
}a[N],t[N];
struct Point
{
ll x,y;
Point(ll _x=0,ll _y=0):x(_x),y(_y){}
friend Point operator -(const Point &a,const Point &b)
{return Point(a.x-b.x,a.y-b.y);}
friend double operator *(const Point &a,const Point &b)
{return (double)a.x*b.y-(double)a.y*b.x;}
}ch[N],p[N];
ll f[N];
inline bool cmp1(const data &a,const data &b)
{return a.d<b.d;}
inline bool cmp2(int i,int j)
{return a[i].x==a[j].x?a[i].y+f[a[i].id]<a[j].y+f[a[j].id]:a[i].x<a[j].x;}
inline ll Val(ll k,const Point &p){return k*p.x+p.y;}
void solve(int l,int r)
{
if(l==r){f[l] = max(f[l-1],f[l]);return ;}
int mid = (l+r)>>1;
solve(l,mid);
int n = 0,m = 0;
for(int i = l;i<= mid;i++)if(f[a[i].id]>=a[i].p)
p[++n] = Point(a[i].x,a[i].y+f[a[i].id]);
for(int i = 1;i<= n;i++)
{
while(m>1&&(ch[m]-ch[m-1])*(p[i]-ch[m-1])>=0)m--;
ch[++m] = p[i];
}
int j = 1;
for(int i = mid+1;i<= r;i++)
{
while(j<m&&Val(a[i].d,ch[j+1])>=Val(a[i].d,ch[j]))j++;
if(j<=m)f[i] = max(f[i],Val(a[i].d,ch[j]));
}
solve(mid+1,r);
int p1 = l,p2 = mid+1;
for(int i = l;i<=r;i++)
{
if(p2>r||(p1<=mid&&cmp2(p1,p2)))t[i]=a[p1++];
else t[i] = a[p2++];
}
for(int i = l;i<= r;i++)a[i]=t[i];
}
int main()
{
int n,d;
int cas = 0;
while(scanf("%d%lld%d",&n,&f[0],&d)!=EOF)
{
if(n==0&&f[0]==0&&d==0)break;
for(int i = 1;i<= n;i++)a[i].read();
a[++n].d = d+1;
sort(a+1,a+n+1,cmp1);
for(int i = 1;i<= n;i++)a[i].id = i,f[i] = 0;
solve(1,n);
printf("Case %d: %lld\n",++cas,f[n]);
}
return 0;
}
| [
"wyx150137@users.noreply.github.com"
] | wyx150137@users.noreply.github.com |
34efc3120ed868eb74767ebd64885100a83586cc | 6ed044303730e547ccbc8dd1c37deec3d4f16c71 | /llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h | 080dc3ea24747bacd43fd7f586dfea1d41ab34e6 | [
"NCSA"
] | permissive | magickli/LLVM | ab42e263ea11598c350b27b4eb9c546183691255 | 74343550fc10fbca95a8b7d7b4bd160945b85ef1 | refs/heads/master | 2021-01-19T13:41:40.712275 | 2017-09-03T09:20:27 | 2017-09-03T09:20:27 | 100,849,489 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,850 | h | //===- llvm/CodeGen/DwarfCompileUnit.h - Dwarf Compile Unit -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains support for writing dwarf compile unit.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DWARFCOMPILEUNIT_H
#define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFCOMPILEUNIT_H
#include "DbgValueHistoryCalculator.h"
#include "DwarfDebug.h"
#include "DwarfUnit.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/CodeGen/DIE.h"
#include "llvm/CodeGen/LexicalScopes.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/Support/Casting.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <memory>
namespace llvm {
class AsmPrinter;
class DwarfFile;
class GlobalVariable;
class MCExpr;
class MCSymbol;
class MDNode;
class DwarfCompileUnit final : public DwarfUnit {
/// A numeric ID unique among all CUs in the module
unsigned UniqueID;
/// The attribute index of DW_AT_stmt_list in the compile unit DIE, avoiding
/// the need to search for it in applyStmtList.
DIE::value_iterator StmtListValue;
/// Skeleton unit associated with this unit.
DwarfCompileUnit *Skeleton = nullptr;
/// The start of the unit within its section.
MCSymbol *LabelBegin;
/// The start of the unit macro info within macro section.
MCSymbol *MacroLabelBegin;
using ImportedEntityList = SmallVector<const MDNode *, 8>;
using ImportedEntityMap = DenseMap<const MDNode *, ImportedEntityList>;
ImportedEntityMap ImportedEntities;
/// GlobalNames - A map of globally visible named entities for this unit.
StringMap<const DIE *> GlobalNames;
/// GlobalTypes - A map of globally visible types for this unit.
StringMap<const DIE *> GlobalTypes;
// List of range lists for a given compile unit, separate from the ranges for
// the CU itself.
SmallVector<RangeSpanList, 1> CURangeLists;
// List of ranges for a given compile unit.
SmallVector<RangeSpan, 2> CURanges;
// The base address of this unit, if any. Used for relative references in
// ranges/locs.
const MCSymbol *BaseAddress = nullptr;
DenseMap<const MDNode *, DIE *> AbstractSPDies;
DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables;
/// \brief Construct a DIE for the given DbgVariable without initializing the
/// DbgVariable's DIE reference.
DIE *constructVariableDIEImpl(const DbgVariable &DV, bool Abstract);
bool isDwoUnit() const override;
DenseMap<const MDNode *, DIE *> &getAbstractSPDies() {
if (isDwoUnit() && !DD->shareAcrossDWOCUs())
return AbstractSPDies;
return DU->getAbstractSPDies();
}
DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> &getAbstractVariables() {
if (isDwoUnit() && !DD->shareAcrossDWOCUs())
return AbstractVariables;
return DU->getAbstractVariables();
}
public:
DwarfCompileUnit(unsigned UID, const DICompileUnit *Node, AsmPrinter *A,
DwarfDebug *DW, DwarfFile *DWU);
unsigned getUniqueID() const { return UniqueID; }
DwarfCompileUnit *getSkeleton() const {
return Skeleton;
}
bool includeMinimalInlineScopes() const;
void initStmtList();
/// Apply the DW_AT_stmt_list from this compile unit to the specified DIE.
void applyStmtList(DIE &D);
/// A pair of GlobalVariable and DIExpression.
struct GlobalExpr {
const GlobalVariable *Var;
const DIExpression *Expr;
};
/// Get or create global variable DIE.
DIE *
getOrCreateGlobalVariableDIE(const DIGlobalVariable *GV,
ArrayRef<GlobalExpr> GlobalExprs);
/// addLabelAddress - Add a dwarf label attribute data and value using
/// either DW_FORM_addr or DW_FORM_GNU_addr_index.
void addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
const MCSymbol *Label);
/// addLocalLabelAddress - Add a dwarf label attribute data and value using
/// DW_FORM_addr only.
void addLocalLabelAddress(DIE &Die, dwarf::Attribute Attribute,
const MCSymbol *Label);
DwarfCompileUnit &getCU() override { return *this; }
unsigned getOrCreateSourceID(StringRef FileName, StringRef DirName) override;
void addImportedEntity(const DIImportedEntity* IE) {
DIScope *Scope = IE->getScope();
assert(Scope && "Invalid Scope encoding!");
if (!isa<DILocalScope>(Scope))
// No need to add imported enities that are not local declaration.
return;
auto *LocalScope = cast<DILocalScope>(Scope)->getNonLexicalBlockFileScope();
ImportedEntities[LocalScope].push_back(IE);
}
/// addRange - Add an address range to the list of ranges for this unit.
void addRange(RangeSpan Range);
void attachLowHighPC(DIE &D, const MCSymbol *Begin, const MCSymbol *End);
/// \brief Find DIE for the given subprogram and attach appropriate
/// DW_AT_low_pc and DW_AT_high_pc attributes. If there are global
/// variables in this scope then create and insert DIEs for these
/// variables.
DIE &updateSubprogramScopeDIE(const DISubprogram *SP);
void constructScopeDIE(LexicalScope *Scope,
SmallVectorImpl<DIE *> &FinalChildren);
/// \brief A helper function to construct a RangeSpanList for a given
/// lexical scope.
void addScopeRangeList(DIE &ScopeDIE, SmallVector<RangeSpan, 2> Range);
void attachRangesOrLowHighPC(DIE &D, SmallVector<RangeSpan, 2> Ranges);
void attachRangesOrLowHighPC(DIE &D,
const SmallVectorImpl<InsnRange> &Ranges);
/// \brief This scope represents inlined body of a function. Construct
/// DIE to represent this concrete inlined copy of the function.
DIE *constructInlinedScopeDIE(LexicalScope *Scope);
/// \brief Construct new DW_TAG_lexical_block for this scope and
/// attach DW_AT_low_pc/DW_AT_high_pc labels.
DIE *constructLexicalScopeDIE(LexicalScope *Scope);
/// constructVariableDIE - Construct a DIE for the given DbgVariable.
DIE *constructVariableDIE(DbgVariable &DV, bool Abstract = false);
DIE *constructVariableDIE(DbgVariable &DV, const LexicalScope &Scope,
DIE *&ObjectPointer);
/// A helper function to create children of a Scope DIE.
DIE *createScopeChildrenDIE(LexicalScope *Scope,
SmallVectorImpl<DIE *> &Children,
bool *HasNonScopeChildren = nullptr);
/// \brief Construct a DIE for this subprogram scope.
void constructSubprogramScopeDIE(const DISubprogram *Sub, LexicalScope *Scope);
DIE *createAndAddScopeChildren(LexicalScope *Scope, DIE &ScopeDIE);
void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
/// \brief Construct import_module DIE.
DIE *constructImportedEntityDIE(const DIImportedEntity *Module);
void finishSubprogramDefinition(const DISubprogram *SP);
void finishVariableDefinition(const DbgVariable &Var);
/// Find abstract variable associated with Var.
using InlinedVariable = DbgValueHistoryMap::InlinedVariable;
DbgVariable *getExistingAbstractVariable(InlinedVariable IV,
const DILocalVariable *&Cleansed);
DbgVariable *getExistingAbstractVariable(InlinedVariable IV);
void createAbstractVariable(const DILocalVariable *DV, LexicalScope *Scope);
/// Set the skeleton unit associated with this unit.
void setSkeleton(DwarfCompileUnit &Skel) { Skeleton = &Skel; }
unsigned getLength() {
return sizeof(uint32_t) + // Length field
getHeaderSize() + getUnitDie().getSize();
}
void emitHeader(bool UseOffsets) override;
MCSymbol *getLabelBegin() const {
assert(getSection());
return LabelBegin;
}
MCSymbol *getMacroLabelBegin() const {
return MacroLabelBegin;
}
/// Add a new global name to the compile unit.
void addGlobalName(StringRef Name, const DIE &Die,
const DIScope *Context) override;
/// Add a new global name present in a type unit to this compile unit.
void addGlobalNameForTypeUnit(StringRef Name, const DIScope *Context);
/// Add a new global type to the compile unit.
void addGlobalType(const DIType *Ty, const DIE &Die,
const DIScope *Context) override;
/// Add a new global type present in a type unit to this compile unit.
void addGlobalTypeUnitType(const DIType *Ty, const DIScope *Context);
const StringMap<const DIE *> &getGlobalNames() const { return GlobalNames; }
const StringMap<const DIE *> &getGlobalTypes() const { return GlobalTypes; }
/// Add DW_AT_location attribute for a DbgVariable based on provided
/// MachineLocation.
void addVariableAddress(const DbgVariable &DV, DIE &Die,
MachineLocation Location);
/// Add an address attribute to a die based on the location provided.
void addAddress(DIE &Die, dwarf::Attribute Attribute,
const MachineLocation &Location);
/// Start with the address based on the location provided, and generate the
/// DWARF information necessary to find the actual variable (navigating the
/// extra location information encoded in the type) based on the starting
/// location. Add the DWARF information to the die.
void addComplexAddress(const DbgVariable &DV, DIE &Die,
dwarf::Attribute Attribute,
const MachineLocation &Location);
/// Add a Dwarf loclistptr attribute data and value.
void addLocationList(DIE &Die, dwarf::Attribute Attribute, unsigned Index);
void applyVariableAttributes(const DbgVariable &Var, DIE &VariableDie);
/// Add a Dwarf expression attribute data and value.
void addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr);
void applySubprogramAttributesToDefinition(const DISubprogram *SP,
DIE &SPDie);
/// getRangeLists - Get the vector of range lists.
const SmallVectorImpl<RangeSpanList> &getRangeLists() const {
return (Skeleton ? Skeleton : this)->CURangeLists;
}
/// getRanges - Get the list of ranges for this unit.
const SmallVectorImpl<RangeSpan> &getRanges() const { return CURanges; }
SmallVector<RangeSpan, 2> takeRanges() { return std::move(CURanges); }
void setBaseAddress(const MCSymbol *Base) { BaseAddress = Base; }
const MCSymbol *getBaseAddress() const { return BaseAddress; }
};
} // end namespace llvm
#endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFCOMPILEUNIT_H
| [
"1029901708@qq.com"
] | 1029901708@qq.com |
1ff97172401b527bf34b61d90e83b4f139db5ac4 | 34d37dcf2186dfa0a2655d1d7471d37394895919 | /GLSLRayMarching/GLSLRayMarching/MacShaderDemo/Mac3Scene.h | eb094e61b0794c9e8a9a9538f89c61bd55a1828c | [
"MIT"
] | permissive | shinjiyu/GLSLRayMarching | c8544a57a8b0bbd23258b8e61959703bf83e5730 | 5e879cc8e5498a083b5b68c570f05c21e5e23189 | refs/heads/master | 2023-07-04T18:45:31.163172 | 2021-09-03T03:25:14 | 2021-09-03T03:25:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 864 | h | //////////////////////////////////////////////////////////////////////////////////
// Copyright(c) 2020, Lin Koon Wing Macgyver, macgyvercct@yahoo.com.hk //
// //
// Author : Mac Lin //
// Module : Magnum Engine v0.7.0 //
// Date : 05/Nov/2020 //
// //
//////////////////////////////////////////////////////////////////////////////////
#ifndef _Mac3Scene_h_
#define _Mac3Scene_h_
#include "Platform.h"
#include "Scene.h"
class Mac3Scene : public Scene
{
public:
Mac3Scene();
virtual ~Mac3Scene();
protected:
virtual bool OnConstruct() override;
virtual bool OnStart() override;
virtual bool OnUpdate() override;
virtual bool OnPause() override;
virtual void OnResume() override;
virtual void OnStop() override;
virtual void OnDestruct() override;
};
#endif | [
"guanronlin@tencent.com"
] | guanronlin@tencent.com |
5aeb7fcdef3218d358f32ea263d6e56f090dc2d1 | 3c051f3283abed02fb5dc1c02723d291a88215ad | /Classes/RenderScene.h | 6843857cf07cf8b666c597808d5d88fc418baba4 | [] | no_license | Struti/GrafBead | 040db8d70852262899b73d60521ab0617aac7fa9 | f84911b5f91a00240c911ce3098eded7a4339164 | refs/heads/master | 2020-03-17T14:03:08.823890 | 2018-05-17T07:16:01 | 2018-05-17T07:16:01 | 133,655,797 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,259 | h | #pragma once
#include <vector>
#include <string>
#include "Camera.h"
#include "Object.h"
#include "Water.h"
#include "SkyBox.h"
#include "InfiniteShore.h"
namespace ti
{
struct SceneSettings
{
glm::ivec2 shadowmapResolution;
};
/*
A scene that holds the objects and gui to be rendered.
Supports light, shadows, skybox, multiple cameras.
*/
class RenderScene
{
public:
/*
Retrieves the current active scene. It is used for rendering.
*/
static RenderScene* getActiveScene();
RenderScene(std::string name);
~RenderScene();
void initialize(const SceneSettings& settings);
void update();
void render();
void setActiveCamera(int cameraIndex);
void setWater(Water* water);
void setSky(SkyBox* sky);
void setLight(DirectionalLight* light);
void setInfiniteShore(InfiniteShore* shore);
void addCamera(Camera* camera);
void addObject(Object* obj);
Camera* getActiveCamera();
Camera* getCamera(int index);
std::vector<Camera*> getCameras();
private:
static RenderScene* active_camerascene_;
Camera* active_camera_;
Water* water;
SkyBox* sky;
DirectionalLight* light;
InfiniteShore* shore_;
std::string scene_name_;
std::vector<Object*> objects_;
std::vector<Camera*> cameras_;
};
} | [
"struti.alex69@gmail.com"
] | struti.alex69@gmail.com |
c8ed1db62b724562dc5819f2a5247e81004c8528 | cede4e1d3041ecbe61738b131e77640aee68963f | /labs/functions/pointDistance.cpp | 38c26fcac0c58012256f14c76372a4f4358826a9 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | lbutler115/CPP-Fundamentals | 1b31e7cb5e454da777132e4b5481de1aaaa20486 | cb24374ed3b4b0a90bd9c54a677dd36344512195 | refs/heads/master | 2023-07-24T14:43:23.086621 | 2021-09-08T15:38:50 | 2021-09-08T15:38:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,250 | cpp | /*
Functions Lab
Updated By: FIXME1
CSCI 111
Date: FIXME2
Program prompts the user to enter two points in the form (x1, y1) and (x2, y2) and finds the distance between the two points using a function.
Algorithm steps:
1. Define a function called findDistance(…) that takes four parameters x1, y1 and x2, y2 as two points
a. finds the distance between them using the equation: √((x2-x1)^2 + (y2-y1)^2)
b. returns the calculated distance value
2. Prompt user to enter two points in (x, y) format
3. Store them into 4 individual variables
4. Call function getDistance by passing 4 entered numbers as arguments
5. Display results with proper description. Format output numbers to 2 decimal points.
6. Test and validate that program output is correct for a given set of input points.
7. BONUS - (10 points) Using a loop repeat step 2-6 until the user wants to quit.
*/
#include <iostream>
#include <cstdio>
#include <cassert>
#include <cmath>
using namespace std;
const float epsilon = 1e-5; // 0.00001 accuracy upto 5 decimal points; error of margin
// function prototypes
// Function that calculates the distance between two points
// x1, y1 and x2, y2 and returns the calculated value
double findDistance(int, int, int, int);
// test function that runs automated testing
void test();
// function clears the screen system call
// NOTE: system call is not a security best pracice!
void clearScreen() {
// use "cls" in windows and "clear" command in Mac and Linux
#ifdef _WIN32
system("clS");
#else
system("clear");
#endif
}
int main()
{
int x1, y1, x2, y2; // variables to store two points (x1, y1) and (x2, y2)
char ch;
//FIXME-bonus - 10 bonus points - add loop until user wants to quit
// the loop will execute the following block of code
{
clearScreen();
cout << "Program calculates distance between 2 points on a 2D coordinate." << endl;
cout << "Enter a point in the form (x, y): ";
// parse the input stream
cin >> ch >> x1 >> ch >> y1 >> ch; // value stored in ch is ignored
printf("(x1, y1) = (%d, %d)\n", x1, y1);
cout << "Enter a second point in the form (x, y): ";
//FIXME3 - Read/parse the second point and store data into variables x2 and y2
//FIXME4 - Call test function
//FIXME5 - call findDistance function passing proper arguments
//FIXME6 – Using printf function display the returned distance with proper description
}
cin.ignore(1000, '\n');
cout << "Enter to quit the program: ";
cin.get();
cout << "Good bye..." << endl;
return 0;
}
double findDistance(int x1, int y1, int x2, int y2)
{
// FIXME7 - Find the distance between (x1, y1) and (x2, y2)
// following the algorithm in step 1
// return the calculated distance
return 0.000000;
}
// test function that test findDistance function with 3 test cases
void test()
{
float result = findDistance(4, 3, 5, 1);
float expected = 2.236067f;
assert( fabs(result - expected) <= epsilon); //accept the result if it's less than the error of margin
// FIXME8 - add at least two more test cases
cerr << "all tests passed..." << endl;
}
| [
"rambasnet@gmail.com"
] | rambasnet@gmail.com |
bc5844653092014b55f4ae80aea08224ea1c5211 | 2555e9165e0b58c2f4a2d97fc37a4423b197ec10 | /test/middle_lan_test.cpp | 2b720928beb18d54daee53fa4e24e39277fdfa43 | [] | no_license | xinnjie/a-simple-compiler | 986e032934df97b072101c218169fe95d01cc887 | ae5676deac2175d7a83113d3d72def235f1d4113 | refs/heads/master | 2021-09-01T01:33:51.359462 | 2017-12-24T05:55:55 | 2017-12-24T05:55:55 | 114,639,170 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 577 | cpp |
#include <iostream>
#include "../symbols_related/TableManager.h"
#include "../middle_lan_related/MiddleLanOperand.h"
#include "../middle_lan_related/Node.h"
using namespace std;
int main() {
TableManager table_manager;
auto left_operand = make_shared<MiddleLanConstant>(Rvalue(table_manager, table_manager.TYPE_INT, "15"));
auto a = table_manager.insert_basic_variable("a", table_manager.TYPE_INT);
auto right_operand = make_shared<MiddleLanVariable>(a);
auto sentence = MiddleSentence(tag::ASSIGN, left_operand, nullptr, right_operand);
return 0;
}
| [
"contact_xinjie@163.com"
] | contact_xinjie@163.com |
4953cb7e3d328d51a9d614a9be9024f20db4b7e7 | 617dd3babeda167d7e017b82f70e83058b8c9441 | /Section 17 - Iterator/Boost Iterator Facade/main.cpp | ad5b7b2a64cb7283d145eb47b9d210aa78297aec | [] | no_license | nmctwisp/Design-Patterns-in-Modern-CPP | 7c21239cb75a38ef2812940ee07affaff096357a | ec2bb4ce12686185206d41745847aa24e30bb695 | refs/heads/master | 2023-01-08T08:49:16.296562 | 2020-11-09T21:54:43 | 2020-11-09T21:54:43 | 266,839,243 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 977 | cpp | #include <string>
#include <boost/iterator/iterator_facade.hpp>
#include <algorithm>
#include <iostream>
struct Node {
std::string value;
Node* next{ nullptr };
Node(const std::string& value) : value(value) {}
Node(const std::string& value, Node* parent) : value(value) {
parent->next = this;
}
};
struct ListIterator : boost::iterator_facade<ListIterator, Node, boost::forward_traversal_tag> {
Node* current{ nullptr };
ListIterator() {};
ListIterator(Node* current) : current(current) {}
private:
friend class boost::iterator_core_access;
void increment() { current = current->next; };
bool equal(const ListIterator& other) const {
return other.current == current;
}
Node& dereference() const {
return *current;
}
};
int main() {
Node alpha{ "alpha" };
Node beta{ "beta", &alpha };
Node gamma{ "gamma", &beta };
std::for_each(ListIterator{ &alpha }, ListIterator{}, [](const Node& n) {
std::cout << n.value << std::endl;
});
return 0;
} | [
"chen.yam@iongroup.com"
] | chen.yam@iongroup.com |
0feb3e997e843b4c7cf6d40218860bc7e03ff275 | a950b4dd000b561dff1fa791badcda204a2296ac | /Pods/FirebaseFirestore/Firestore/core/src/firebase/firestore/local/local_view_changes.cc | 1048b7c9680065a3148bba296bafe8e8c621cec2 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | permissive | dmitrydnl/SimpleMessenger | 862c3fe0f954829f3108108bc8b65c743523819f | 963aae82c44b30d34fc7fc77a11409692090a6a0 | refs/heads/master | 2020-12-15T00:57:10.624316 | 2020-01-26T15:43:18 | 2020-01-26T15:43:18 | 234,936,901 | 6 | 1 | MIT | 2020-01-26T15:43:19 | 2020-01-19T17:22:33 | Swift | UTF-8 | C++ | false | false | 1,722 | cc | /*
* Copyright 2019 Google
*
* 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 "Firestore/core/src/firebase/firestore/local/local_view_changes.h"
#include "Firestore/core/src/firebase/firestore/core/view_snapshot.h"
namespace firebase {
namespace firestore {
namespace local {
using core::DocumentViewChange;
using core::ViewSnapshot;
using model::DocumentKeySet;
using model::TargetId;
LocalViewChanges LocalViewChanges::FromViewSnapshot(
const core::ViewSnapshot& snapshot, model::TargetId target_id) {
DocumentKeySet added_keys;
DocumentKeySet removed_keys;
for (const DocumentViewChange& doc_change : snapshot.document_changes()) {
switch (doc_change.type()) {
case DocumentViewChange::Type::Added:
added_keys = added_keys.insert(doc_change.document().key());
break;
case DocumentViewChange::Type::Removed:
removed_keys = removed_keys.insert(doc_change.document().key());
break;
default:
// Do nothing.
break;
}
}
return LocalViewChanges(target_id, std::move(added_keys),
std::move(removed_keys));
}
} // namespace local
} // namespace firestore
} // namespace firebase
| [
"48892069+Captious99@users.noreply.github.com"
] | 48892069+Captious99@users.noreply.github.com |
e09e2ae39d6ad9aa46db6eb4f657440cbc3f73ee | 23ab2621eacee9bb90bb9cf16702805f047535ee | /engine/source/runtime/assets/asset_manager.h | 887b773d4296d6a502676615925cc77c5e159bbe | [] | no_license | caomw/EtherealEngine | bbe20c1ccab6b06ba1b6761ddd6a48b1d640ef42 | 3ce78b71107cfe346645f937f556829cc868a5a6 | refs/heads/master | 2021-01-11T17:10:12.574855 | 2017-01-21T17:16:54 | 2017-01-21T17:16:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,068 | h | #pragma once
#include <functional>
#include <unordered_map>
#include "core/common/type_traits.hpp"
#include "core/common/string.h"
#include "core/events/delegate.hpp"
#include "../system/filesystem.h"
#include "load_request.hpp"
namespace runtime
{
/// aliases
template<typename T>
using RequestContainer = std::unordered_map<std::string, LoadRequest<T>>;
struct Storage
{
//-----------------------------------------------------------------------------
// Name : ~Storage (virtual )
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
virtual ~Storage() = default;
//-----------------------------------------------------------------------------
// Name : clear (virtual )
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
virtual void clear() = 0;
//-----------------------------------------------------------------------------
// Name : clear (virtual )
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
virtual void clear(const std::string& protocol) = 0;
};
template<typename T>
struct TStorage : Storage
{
//-----------------------------------------------------------------------------
// Name : ~TStorage ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
~TStorage() = default;
//-----------------------------------------------------------------------------
// Name : clear ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
void clear()
{
container.clear();
}
//-----------------------------------------------------------------------------
// Name : clear ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
void clear(const std::string& protocol)
{
auto containerCopy = container;
for (auto& pair : containerCopy)
{
const auto& id = pair.first;
if (string_utils::begins_with(id, protocol, true))
{
pair.second.wait_until_ready();
container.erase(id);
}
}
}
//-----------------------------------------------------------------------------
// Name : load_from_memory_default ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
static void load_from_memory_default(const fs::path&, const std::uint8_t*, std::uint32_t, LoadRequest<T>&) {}
//-----------------------------------------------------------------------------
// Name : load_from_file_default ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
static void load_from_file_default(const fs::path&, const fs::path&, bool, LoadRequest<T>&) {}
//-----------------------------------------------------------------------------
// Name : save_to_file_default ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
static void save_to_file_default(const fs::path&, const AssetHandle<T>&) {}
/// key, data, size, outRequest
delegate<void(const std::string&, const std::uint8_t*, std::uint32_t, LoadRequest<T>&)> load_from_memory = load_from_memory_default;
/// key, absolutKey, async, outReqeust
delegate<void(const std::string&, const fs::path&, bool, LoadRequest<T>&)> load_from_file = load_from_file_default;
/// absolutKey, asset
delegate<void(const fs::path&, const AssetHandle<T>&)> save_to_file = save_to_file_default;
/// Storage container
std::unordered_map<std::string, LoadRequest<T>> container;
/// Extention
std::string ext;
};
template<typename T>
inline fs::path get_absolute_key(const std::string& toLowerKey, T storage)
{
fs::path absoluteKey = fs::resolve_protocol(toLowerKey);
fs::path dir = absoluteKey;
dir.remove_filename();
std::string file = absoluteKey.filename().string();
absoluteKey = fs::absolute(dir / fs::path(file + storage->ext));
return absoluteKey;
};
class AssetManager : public core::Subsystem
{
public:
void setup();
//-----------------------------------------------------------------------------
// Name : add ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
template <typename S>
void add(std::shared_ptr<TStorage<S>> system)
{
storages.insert(std::make_pair(core::TypeInfo::id<Storage, TStorage<S>>(), system));
}
//-----------------------------------------------------------------------------
// Name : add ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
template <typename S, typename ... Args>
std::shared_ptr<TStorage<S>> add(Args && ... args)
{
auto s = std::make_shared<TStorage<S>>(std::forward<Args>(args) ...);
add(s);
return s;
}
//-----------------------------------------------------------------------------
// Name : get_storage ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
template <typename S>
std::shared_ptr<TStorage<S>> get_storage()
{
auto it = storages.find(core::TypeInfo::id<Storage, TStorage<S>>());
assert(it != storages.end());
return it == storages.end()
? std::shared_ptr<TStorage<S>>()
: std::shared_ptr<TStorage<S>>(std::static_pointer_cast<TStorage<S>>(it->second));
}
//-----------------------------------------------------------------------------
// Name : clear ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
void clear()
{
for (auto& pair : storages)
{
auto& storage = pair.second;
storage->clear();
}
}
//-----------------------------------------------------------------------------
// Name : clear ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
void clear(const std::string& protocol)
{
for (auto& pair : storages)
{
auto& storage = pair.second;
storage->clear(protocol);
}
}
//-----------------------------------------------------------------------------
// Name : create_asset_from_memory ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
template<typename T>
LoadRequest<T>& create_asset_from_memory(
const std::string& key,
const std::uint8_t* data,
const std::uint32_t& size)
{
auto storage = get_storage<T>();
return create_asset_from_memory_impl<T>(key, data, size, storage->container, storage->load_from_memory);
}
//-----------------------------------------------------------------------------
// Name : rename_asset ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
template<typename T>
void rename_asset(
const std::string& key,
const std::string& new_key)
{
auto storage = get_storage<T>();
auto absolute_key = get_absolute_key(key, storage);
auto absolute_new_key = get_absolute_key(new_key, storage);
// rename compiled assets
fs::rename(absolute_key, absolute_new_key, std::error_code{});
auto& request = storage->container[key];
storage->container[new_key] = request;
storage->container[new_key].asset.link->id = new_key;
storage->container.erase(key);
}
//-----------------------------------------------------------------------------
// Name : clear_asset ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
template<typename T>
void clear_asset(
const std::string& key)
{
auto storage = get_storage<T>();
auto& request = storage->container[key];
request.asset.link->asset.reset();
request.asset.link->id.clear();
storage->container.erase(key);
}
//-----------------------------------------------------------------------------
// Name : delete_asset ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
template<typename T>
void delete_asset(
const std::string& key)
{
auto storage = get_storage<T>();
fs::path absolute_key = get_absolute_key(key, storage);
fs::remove(absolute_key, std::error_code{});
auto& request = storage->container[key];
request.asset.link->asset.reset();
request.asset.link->id.clear();
storage->container.erase(key);
}
//-----------------------------------------------------------------------------
// Name : load ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
template<typename T>
LoadRequest<T>& load(
const std::string& key,
bool async,
bool force = false)
{
auto storage = get_storage<T>();
//if embedded resource
if (key.find("embedded") != std::string::npos)
{
return find_or_create_asset_impl<T>(key, storage->container);
}
else
{
const fs::path absoluteKey = get_absolute_key(key, storage);
return load_asset_from_file_impl<T>(key, absoluteKey, async, force, storage->container, storage->load_from_file);
}
}
//-----------------------------------------------------------------------------
// Name : save ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
template<typename T>
void save(const AssetHandle<T>& asset)
{
auto storage = get_storage<T>();
const fs::path absoluteKey = get_absolute_key(asset.id(), storage);
storage->save_to_file(absoluteKey, asset);
}
template<typename T>
void create_asset_entry(
const std::string& key
)
{
auto storage = get_storage<T>();
find_or_create_asset_impl<T>(key, storage->container);
}
private:
//-----------------------------------------------------------------------------
// Name : load_asset_from_file_impl ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
template<typename T, typename F>
LoadRequest<T>& load_asset_from_file_impl(
const std::string& key,
const fs::path& absoluteKey,
bool async,
bool force,
RequestContainer<T>& container,
F&& loadFunc
)
{
auto it = container.find(key);
if (it != std::end(container))
{
auto& request = it->second;
if (force)
{
loadFunc(key, absoluteKey, async, request);
}
else if (!async && !request.is_ready())
{
request.wait_until_ready();
}
return request;
}
else if (!fs::exists(absoluteKey, std::error_code{}))
{
static LoadRequest<T> emptyRequest;
return emptyRequest;
}
else
{
auto& request = find_or_create_asset_impl(key, container);
//Dispatch the loading
loadFunc(key, absoluteKey, async, request);
return request;
}
}
//-----------------------------------------------------------------------------
// Name : create_asset_from_memory_impl ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
template<typename T, typename F>
LoadRequest<T>& create_asset_from_memory_impl(
const std::string& key,
const std::uint8_t* data,
const std::uint32_t& size,
RequestContainer<T>& container,
F&& loadFunc
)
{
auto it = container.find(key);
if (it != std::end(container))
{
// If there is already a loading request.
auto& request = it->second;
return request;
}
else
{
auto& request = find_or_create_asset_impl(key, container);
//Dispatch the loading
loadFunc(key, data, size, request);
return request;
}
}
//-----------------------------------------------------------------------------
// Name : find_or_create_asset_impl ()
/// <summary>
///
///
///
/// </summary>
//-----------------------------------------------------------------------------
template<typename T>
LoadRequest<T>& find_or_create_asset_impl(
const std::string& key,
RequestContainer<T>& container
)
{
auto& request = container[key];
return request;
}
/// Different storages
std::unordered_map<core::TypeInfo::index_t, std::shared_ptr<Storage>> storages;
};
} | [
"nikolai.p.ivanov@gmail.com"
] | nikolai.p.ivanov@gmail.com |
1afad0b656554bbee0706152816042dbc2c6ccb1 | 6a919b52b0fbc5b7c548c8e817a17c355296abce | /vox_compute_ishock/vox_compute_ishock_params.h | 5107f8ad2f504be28e24e08269648fa25fa28273 | [] | no_license | yuliangguo/fragment_process | 4e167477f302f84282ddd228395df16e9285660c | 3a502ef6c3f95cde4f96f55db4d049c4883dc3a8 | refs/heads/master | 2021-09-02T14:24:51.074315 | 2018-01-03T06:30:11 | 2018-01-03T06:30:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,389 | h | // This is dborl/algo/vox_compute_ishock/vox_compute_ishock_params.h
//:
// \file
// \brief parameter set for compute_ishock algorithm
//
// \author Nhon Trinh (ntrinh@lems.brown.edu)
// \date May 17, 2008
//
// \verbatim
// Modifications
//
// \endverbatim
// update by Maruthi Narayanan (mn@lems.brown.edu)
//
#ifndef vox_compute_ishock_params_h_
#define vox_compute_ishock_params_h_
#include "../dborl/algo/dborl_algo_params.h"
//: put all the additional params into this class, and add them
// to the parameter list in the constructor so that
// all the files related to the parameter set of the algorithm are
// generated automatically via the methods of the base class
// no need to overwrite any of the methods in the base class thanks
// to the parameter list
class vox_compute_ishock_params : public dborl_algo_params
{
public:
//: Constructor
vox_compute_ishock_params(vcl_string algo_name);
// MEMBER VARIABLES
//: Save result to the object folder?
dborl_parameter<bool> save_to_object_folder_;
//: Name of input object
dborl_parameter<vcl_string> input_object_name_;
//: passes the folder of the input object
dborl_parameter<vcl_string> input_object_dir_;
//: passes the input association dir
dborl_parameter<vcl_string> input_assoc_dir_;
//: extension of the input contour file ( .cem,.cemv,.con)
dborl_parameter<vcl_string> input_contour_extension_;
//: extension of the image ( .cem,.cemv,.con)
dborl_parameter<vcl_string> input_image_extension_;
//: extension of output file
dborl_parameter<vcl_string> output_extension_;
// if written to this folder as opposed to object folder then the shock graph
// gets associated to the input object.
// if nothing is written here, nothing gets associated
dborl_parameter<vcl_string> output_shock_folder_;
//: Number of iterations for valid shock computation
dborl_parameter<int> num_iter_;
//: Perform gap transform on intrinsinc shock graph
dborl_parameter<bool> gap_transform_;
//: Add a bounding box to vsol for shock computation
dborl_parameter<bool> add_bbox_;
//: tag for intrinsinc shock computation
vcl_string tag_compute_ishock_;
//: tag for gap transform
vcl_string tag_gap_transform_;
//: tag for sample shock
vcl_string tag_sample_shock_;
};
#endif //_vox_compute_ishock_params_h
| [
"yuliang_guo@brown.edu"
] | yuliang_guo@brown.edu |
e751c94529f031a17107b715eb7038b100a68453 | 8227345e776cc996b11407bbc7ef9337d571cebd | /src/core/input/training_io.cc | 848cba69627cc04373403c24c0c90d3b04a7e280 | [
"Apache-2.0"
] | permissive | atlimited/jumanpp | 3d7821d48bc7899122ec403fa87c0166114c769d | 4a2a73a621947d5f9282f0a46aaa5b89c9bf1d83 | refs/heads/master | 2021-04-09T13:59:25.219244 | 2018-03-18T15:55:40 | 2018-03-18T15:55:40 | 125,741,724 | 1 | 0 | Apache-2.0 | 2018-03-18T15:53:25 | 2018-03-18T15:53:25 | null | UTF-8 | C++ | false | false | 1,456 | cc | //
// Created by Arseny Tolmachev on 2017/03/23.
//
#include "training_io.h"
namespace jumanpp {
namespace core {
namespace input {
namespace {
Status readStr2IdMap(const dic::DictionaryField &fld,
util::FlatMap<StringPiece, i32> *map) {
auto &s2i = *map;
if (fld.columnType != spec::FieldType::String) {
return JPPS_INVALID_PARAMETER
<< "training data reader allows only string-typed fields, field "
<< fld.name << " was not";
}
if (fld.emptyValue.size() != 0) {
s2i[fld.emptyValue] = 0;
}
core::dic::impl::StringStorageTraversal everything{fld.strings};
StringPiece data;
while (everything.next(&data)) {
s2i[data] = everything.position();
}
return Status::Ok();
}
} // namespace
Status TrainFieldsIndex::initialize(const CoreHolder &core) {
auto &spec = core.spec().training;
storages_.resize(spec.fields.size());
for (i32 i = 0; i < spec.fields.size(); ++i) {
auto &tf = spec.fields[i];
auto &dicFld = core.dic().fields().at(tf.fieldIdx);
auto &str2int = storages_[dicFld.stringStorageIdx];
if (str2int.size() == 0) {
// string storage was not read yet
JPP_RETURN_IF_ERROR(readStr2IdMap(dicFld, &str2int));
}
fields_.push_back({dicFld.name, &str2int, tf.fieldIdx, i});
}
surfaceFieldIdx_ = spec.fields[spec.surfaceIdx].number;
return Status::Ok();
}
} // namespace input
} // namespace core
} // namespace jumanpp | [
"eiennohito@gmail.com"
] | eiennohito@gmail.com |
197c40111e52af5186d5b00c4ed01585210a4f3f | 3814889cd0a9778945d1ec66d6766039f665d283 | /Server/WindowsService.cpp | 3b706ae0197642c459caa6dcc468746cf850888d | [] | no_license | Kir14/windowsService | 012c4eeead6e15d2269f46e90c610bf456dbaea7 | e557553e8d6aa6c8ba21f5f53f1525c383c71771 | refs/heads/master | 2022-12-09T03:02:26.528992 | 2020-09-15T10:40:59 | 2020-09-15T10:40:59 | 273,273,267 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,796 | cpp | #pragma once
#include <WinSock2.h>
#include "Server.h"
SERVICE_STATUS g_ServiceStatus = { 0 };
SERVICE_STATUS_HANDLE g_StatusHandle = NULL;
VOID WINAPI ServiceMain(DWORD argc, LPTSTR* argv);
VOID WINAPI ServiceCtrlHandler(DWORD);
DWORD WINAPI ServiceWorkerThread(LPVOID lpParam);
#define SERVICE_NAME TEXT("CHAT_SERVICE")
int main(int argc, char* argv[])
{
SERVICE_TABLE_ENTRY ServiceTable[] =
{
{(LPWSTR)SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain},
{NULL, NULL}
};
if (StartServiceCtrlDispatcher(ServiceTable) == FALSE)
{
return GetLastError();
}
return 0;
}
VOID WINAPI ServiceMain(DWORD argc, LPTSTR* argv)
{
DWORD Status = E_FAIL;
// Register our service control handler with the SCM
g_StatusHandle = RegisterServiceCtrlHandler(SERVICE_NAME, ServiceCtrlHandler);
if (g_StatusHandle == NULL)
{
return;
}
// Tell the service controller we are starting
ZeroMemory(&g_ServiceStatus, sizeof(g_ServiceStatus));
g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
g_ServiceStatus.dwControlsAccepted = 0;
g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
g_ServiceStatus.dwWin32ExitCode = 0;
g_ServiceStatus.dwServiceSpecificExitCode = 0;
g_ServiceStatus.dwCheckPoint = 0;
if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE)
{
OutputDebugString(
L"SetServiceStatus returned error");
}
/*
* Perform tasks necessary to start the service here
*/
// Create a service stop event to wait on later
g_ServiceStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (g_ServiceStopEvent == NULL)
{
// Error creating event
// Tell service controller we are stopped and exit
g_ServiceStatus.dwControlsAccepted = 0;
g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
g_ServiceStatus.dwWin32ExitCode = GetLastError();
g_ServiceStatus.dwCheckPoint = 1;
if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE)
{
OutputDebugString(
L"SetServiceStatus returned error");
}
return;
}
// Tell the service controller we are started
g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
g_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
g_ServiceStatus.dwWin32ExitCode = 0;
g_ServiceStatus.dwCheckPoint = 0;
if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE)
{
OutputDebugString(
L"SetServiceStatus returned error");
}
// Start a thread that will perform the main task of the service
HANDLE hThread = CreateThread(NULL, 0, ServiceWorkerThread, NULL, 0, NULL);
// Wait until our worker thread exits signaling that the service needs to stop
WaitForSingleObject(hThread, INFINITE);
CloseHandle(g_ServiceStopEvent);
// Tell the service controller we are stopped
g_ServiceStatus.dwControlsAccepted = 0;
g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
g_ServiceStatus.dwWin32ExitCode = 0;
g_ServiceStatus.dwCheckPoint = 3;
if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE)
{
OutputDebugString(
L"SetServiceStatus returned error");
}
return;
}
VOID WINAPI ServiceCtrlHandler(DWORD CtrlCode)
{
switch (CtrlCode)
{
case SERVICE_CONTROL_STOP:
if (g_ServiceStatus.dwCurrentState != SERVICE_RUNNING)
break;
g_ServiceStatus.dwControlsAccepted = 0;
g_ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
g_ServiceStatus.dwWin32ExitCode = 0;
g_ServiceStatus.dwCheckPoint = 4;
if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE)
{
OutputDebugString(
L"ServiceCtrlHandler: SetServiceStatus returned error");
}
// This will signal the worker thread to start shutting down
SetEvent(g_ServiceStopEvent );
break;
default:
break;
}
}
DWORD WINAPI ServiceWorkerThread(LPVOID lpParam)
{
Server();
ListenConnection();
StopServer();
return ERROR_SUCCESS;
}
| [
"62447478+Kir14@users.noreply.github.com"
] | 62447478+Kir14@users.noreply.github.com |
46c7087c556943ff1032ad1ca21c1e2aa2c16f24 | eb17197dbec678b3fbf538692758d27c52419e5e | /src/pessoa.hpp | 863b197077ea196fb49b9ac24e73e967eaf7132b | [] | no_license | GuilhermeSaito/SignInUpUsingCpp | 28456ed6e47de60b0fcb8957014f1bf85186da10 | bebf081d574d276565c32b595750b192385f35ff | refs/heads/master | 2023-04-11T15:01:25.052786 | 2021-04-14T01:28:07 | 2021-04-14T01:28:07 | 357,736,454 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,590 | hpp | #pragma once
#include <iostream>
class Pessoa
{
private:
std::string nome;
std::string cpf;
std::string rg;
std::string dataNascimento;
std::string naturalidade;
std::string estadoNascimento;
std::string genero;
std::string estadoCivil;
std::string cep;
const int numeroCasa;
std::string telefoneResidencial;
std::string telefoneCelular;
std::string email;
std::string senha;
public:
Pessoa(const std::string n = "",
const std::string c = "",
const std::string r = "",
const std::string dN = "",
const std::string nat = "",
const std::string eN = "",
const std::string g = "",
const std::string eC = "",
const std::string cp = "",
const int nC = -1,
const std::string tR = "",
const std::string tC = "",
const std::string em = "",
const std::string se = "");
~Pessoa();
const std::string getNome() const;
const std::string getCpf() const;
const std::string getRg() const;
const std::string getDataNascimento() const;
const std::string getNaturalidade() const;
const std::string getEstadoNascimento() const;
const std::string getGenero() const;
const std::string getEstadoCivil() const;
const std::string getCep() const;
const int getNumeroCasa() const;
const std::string getTelefoneResidencial() const;
const std::string gettelefoneCelular() const;
const std::string getEmail() const;
const std::string getSenha() const;
}; | [
"guilhermetoshiosaito@gmail.com"
] | guilhermetoshiosaito@gmail.com |
754fdf83e153ca6bae0eb35bba219d026c23ee8c | 887f8aa4d74450ecd98bd20eb56ed1646fd393e9 | /cv/test.cpp | b8e1484d7e2d5e174c8ca4594be7bca30e1e4bc9 | [] | no_license | sean-purcell/Cube | f687e776cfb909a70fe770c46f6edeb3f00935c4 | 9fd81d11ed4755311871e5f1f4d67cd15c5c9966 | refs/heads/master | 2022-09-09T19:09:42.422056 | 2014-06-19T04:13:58 | 2014-06-19T04:13:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 865 | cpp | #include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;
int main(int, char** argc)
{
VideoCapture cap(atoi(argc[1])); // open the default camera
if(!cap.isOpened()) // check if we succeeded
{
cout << "Error opening camera!";
return -1;
}
Mat edges;
namedWindow("edges",1);
namedWindow("normal", 1);
for(;;)
{
Mat frame;
cap >> frame; // get a new frame from camera
cvtColor(frame, edges, CV_BGR2GRAY);
GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
Canny(edges, edges, 0, 30, 3);
imshow("edges", edges);
imshow("normal", frame);
if(waitKey(3) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
| [
"iburinoc@gmail.com"
] | iburinoc@gmail.com |
92f4336401401aef7176de94aba49050a3d160d4 | d1add090b88e3d2879564cf4bce30d7b0a675a64 | /arraysum.cpp | c5d45a9472ff68e28f1dff45b2e03e230622e2d7 | [] | no_license | ssonata/ssongta | 25acb5c17e4ff11ae219149e66cb8bb11b627085 | bf35ffb8fd15c581a16c58b390d6daae52d9fce0 | refs/heads/master | 2021-01-02T09:44:51.489034 | 2018-08-07T10:08:06 | 2018-08-07T10:08:06 | 99,286,797 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270 | cpp | #include <iostream>
using namespace std;
int arraysum(int n, int *data)
{
if(n <= 0) return 0;
else return arraysum(n-1 , data) + data[n];
}
int main()
{
int arr[10];
for(int i = 1; i < 11; i ++)
{
arr[i] = i;
}
cout << arraysum(10, arr)<< endl;
return 0;
}
| [
"rrgghh@nate.com"
] | rrgghh@nate.com |
70e4a51b00adb20705eff0a023e4eb0a271e3b43 | e836c3654f9c4f64ce3bb61bd7108f4209f39bb2 | /module/include/atlmfc/afxribbonbuttonsgroup.h | f3acccbbb6645e737c4da5cf8b41d641ecba27ed | [
"MIT"
] | permissive | t4wE/pvpgn-magic-builder | 6c16e6f10629ec758809851bc357aa4e2793108e | f9c9d536f0681e3dcf5aefccf53a9a12b0a2909a | refs/heads/master | 2022-06-24T12:44:54.237991 | 2022-04-24T11:27:41 | 2022-04-24T11:27:41 | 228,243,646 | 0 | 0 | MIT | 2019-12-15T20:00:19 | 2019-12-15T20:00:18 | null | UTF-8 | C++ | false | false | 4,247 | h | // This MFC Library source code supports the Microsoft Office Fluent User Interface
// (the "Fluent UI") and is provided only as referential material to supplement the
// Microsoft Foundation Classes Reference and related electronic documentation
// included with the MFC C++ library software.
// License terms to copy, use or distribute the Fluent UI are available separately.
// To learn more about our Fluent UI licensing program, please visit
// http://msdn.microsoft.com/officeui.
//
// Copyright (C) Microsoft Corporation
// All rights reserved.
#pragma once
#include "afxcontrolbarutil.h"
#include "afxbaseribbonelement.h"
#include "afxtoolbarimages.h"
#ifdef _AFX_PACKING
#pragma pack(push, _AFX_PACKING)
#endif
#ifdef _AFX_MINREBUILD
#pragma component(minrebuild, off)
#endif
class CMFCRibbonButtonsGroup : public CMFCRibbonBaseElement
{
friend class CMFCRibbonBar;
friend class CMFCRibbonCollector;
friend class CMFCRibbonConstructor;
DECLARE_DYNCREATE(CMFCRibbonButtonsGroup)
// Construction
public:
CMFCRibbonButtonsGroup();
CMFCRibbonButtonsGroup(CMFCRibbonBaseElement* pButton);
virtual ~CMFCRibbonButtonsGroup();
// Attributes
public:
void SetImages(CMFCToolBarImages* pImages, CMFCToolBarImages* pHotImages, CMFCToolBarImages* pDisabledImages);
BOOL HasImages() const { return m_Images.GetCount() > 0; }
const CSize GetImageSize() const;
int GetCount() const { return (int) m_arButtons.GetSize(); }
CMFCRibbonBaseElement* GetButton(int i) const
{
ASSERT_VALID(m_arButtons [i]);
return m_arButtons [i];
}
// Operations
public:
void AddButton(CMFCRibbonBaseElement* pButton);
void AddButtons(const CList<CMFCRibbonBaseElement*, CMFCRibbonBaseElement*>& lstButtons);
void RemoveAll();
// Overrides
public:
virtual CSize GetRegularSize(CDC* pDC);
virtual void OnDrawImage(CDC* pDC, CRect rectImage, CMFCRibbonBaseElement* pButton, int nImageIndex);
virtual void SetParentCategory(CMFCRibbonCategory* pCategory);
protected:
virtual void OnDraw(CDC* pDC);
virtual void OnUpdateCmdUI(CMFCRibbonCmdUI* pCmdUI, CFrameWnd* pTarget, BOOL bDisableIfNoHndler);
virtual void OnAfterChangeRect(CDC* pDC);
virtual void OnShow(BOOL bShow);
virtual CMFCRibbonBaseElement* HitTest(CPoint point);
virtual BOOL CanBeStretched() { return FALSE; }
virtual BOOL IsAlignByColumn() const { return FALSE; }
virtual BOOL IsQuickAccessToolBar() const { return FALSE; }
virtual CMFCRibbonBaseElement* Find(const CMFCRibbonBaseElement* pElement);
virtual CMFCRibbonBaseElement* FindByID(UINT uiCmdID);
virtual CMFCRibbonBaseElement* FindByData(DWORD_PTR dwData);
virtual CMFCRibbonBaseElement* FindByOriginal(CMFCRibbonBaseElement* pOriginal);
virtual CMFCRibbonBaseElement* GetPressed();
virtual CMFCRibbonBaseElement* GetDroppedDown();
virtual CMFCRibbonBaseElement* GetHighlighted();
/// <summary>
/// Returns a focused element. </summary>
/// <returns> A pointer to a focused element or NULL.</returns>
virtual CMFCRibbonBaseElement* GetFocused();
virtual BOOL ReplaceByID(UINT uiCmdID, CMFCRibbonBaseElement* pElem);
virtual void CopyFrom(const CMFCRibbonBaseElement& src);
virtual void SetParentMenu(CMFCRibbonPanelMenuBar* pMenuBar);
virtual void SetOriginal(CMFCRibbonBaseElement* pOriginal);
virtual void GetElementsByID(UINT uiCmdID, CArray<CMFCRibbonBaseElement*, CMFCRibbonBaseElement*>& arButtons);
virtual void GetItemIDsList(CList<UINT,UINT>& lstItems) const;
virtual int AddToListBox(CMFCRibbonCommandsListBox* pWndListBox, BOOL bDeep);
virtual void AddToKeyList(CArray<CMFCRibbonKeyTip*,CMFCRibbonKeyTip*>& arElems);
virtual void OnRTLChanged(BOOL bIsRTL);
virtual void CleanUpSizes();
virtual void SetParentRibbonBar(CMFCRibbonBar* pRibbonBar);
virtual CMFCRibbonBaseElement* GetFirstTabStop();
virtual CMFCRibbonBaseElement* GetLastTabStop();
virtual void GetVisibleElements(CArray<CMFCRibbonBaseElement*, CMFCRibbonBaseElement*>& arElements);
// Attributes
protected:
CArray<CMFCRibbonBaseElement*, CMFCRibbonBaseElement*> m_arButtons;
CMFCToolBarImages m_Images;
CMFCToolBarImages m_HotImages;
CMFCToolBarImages m_DisabledImages;
};
#ifdef _AFX_MINREBUILD
#pragma component(minrebuild, on)
#endif
#ifdef _AFX_PACKING
#pragma pack(pop)
#endif
| [
"harpywar@gmail.com"
] | harpywar@gmail.com |
8bcb841887fa6c3ad414b1e76a14e54bf3dafd18 | 6c77cf237697f252d48b287ae60ccf61b3220044 | /aws-cpp-sdk-waf-regional/include/aws/waf-regional/model/GetXssMatchSetRequest.h | eccc856eb0865be59c4f19ec1d5c0292f447e341 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | Gohan/aws-sdk-cpp | 9a9672de05a96b89d82180a217ccb280537b9e8e | 51aa785289d9a76ac27f026d169ddf71ec2d0686 | refs/heads/master | 2020-03-26T18:48:43.043121 | 2018-11-09T08:44:41 | 2018-11-09T08:44:41 | 145,232,234 | 1 | 0 | Apache-2.0 | 2018-08-30T13:42:27 | 2018-08-18T15:42:39 | C++ | UTF-8 | C++ | false | false | 4,269 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <aws/waf-regional/WAFRegional_EXPORTS.h>
#include <aws/waf-regional/WAFRegionalRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace WAFRegional
{
namespace Model
{
/**
* <p>A request to get an <a>XssMatchSet</a>.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/waf-regional-2016-11-28/GetXssMatchSetRequest">AWS
* API Reference</a></p>
*/
class AWS_WAFREGIONAL_API GetXssMatchSetRequest : public WAFRegionalRequest
{
public:
GetXssMatchSetRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "GetXssMatchSet"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>The <code>XssMatchSetId</code> of the <a>XssMatchSet</a> that you want to
* get. <code>XssMatchSetId</code> is returned by <a>CreateXssMatchSet</a> and by
* <a>ListXssMatchSets</a>.</p>
*/
inline const Aws::String& GetXssMatchSetId() const{ return m_xssMatchSetId; }
/**
* <p>The <code>XssMatchSetId</code> of the <a>XssMatchSet</a> that you want to
* get. <code>XssMatchSetId</code> is returned by <a>CreateXssMatchSet</a> and by
* <a>ListXssMatchSets</a>.</p>
*/
inline void SetXssMatchSetId(const Aws::String& value) { m_xssMatchSetIdHasBeenSet = true; m_xssMatchSetId = value; }
/**
* <p>The <code>XssMatchSetId</code> of the <a>XssMatchSet</a> that you want to
* get. <code>XssMatchSetId</code> is returned by <a>CreateXssMatchSet</a> and by
* <a>ListXssMatchSets</a>.</p>
*/
inline void SetXssMatchSetId(Aws::String&& value) { m_xssMatchSetIdHasBeenSet = true; m_xssMatchSetId = std::move(value); }
/**
* <p>The <code>XssMatchSetId</code> of the <a>XssMatchSet</a> that you want to
* get. <code>XssMatchSetId</code> is returned by <a>CreateXssMatchSet</a> and by
* <a>ListXssMatchSets</a>.</p>
*/
inline void SetXssMatchSetId(const char* value) { m_xssMatchSetIdHasBeenSet = true; m_xssMatchSetId.assign(value); }
/**
* <p>The <code>XssMatchSetId</code> of the <a>XssMatchSet</a> that you want to
* get. <code>XssMatchSetId</code> is returned by <a>CreateXssMatchSet</a> and by
* <a>ListXssMatchSets</a>.</p>
*/
inline GetXssMatchSetRequest& WithXssMatchSetId(const Aws::String& value) { SetXssMatchSetId(value); return *this;}
/**
* <p>The <code>XssMatchSetId</code> of the <a>XssMatchSet</a> that you want to
* get. <code>XssMatchSetId</code> is returned by <a>CreateXssMatchSet</a> and by
* <a>ListXssMatchSets</a>.</p>
*/
inline GetXssMatchSetRequest& WithXssMatchSetId(Aws::String&& value) { SetXssMatchSetId(std::move(value)); return *this;}
/**
* <p>The <code>XssMatchSetId</code> of the <a>XssMatchSet</a> that you want to
* get. <code>XssMatchSetId</code> is returned by <a>CreateXssMatchSet</a> and by
* <a>ListXssMatchSets</a>.</p>
*/
inline GetXssMatchSetRequest& WithXssMatchSetId(const char* value) { SetXssMatchSetId(value); return *this;}
private:
Aws::String m_xssMatchSetId;
bool m_xssMatchSetIdHasBeenSet;
};
} // namespace Model
} // namespace WAFRegional
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
65a86548430a9b360204518d0f6fcef1b8dcd754 | b193a4bf6ab67851256cca7f2f3259a5c57d7180 | /offside.cpp | a62d908f9d1983f6d4883be019fcf62efcc911b3 | [] | no_license | kaushik12048/Spoj_Solutions | ec133fb82bd6b1e9fe20a156183d111d42b21f07 | 20a893fd5ea9bd108ec367ddce71d3092ab63a4c | refs/heads/master | 2016-08-10T11:56:05.796740 | 2015-05-25T06:56:24 | 2015-05-25T06:56:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 899 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
while(1){
// printf("working");
int x,y,i;
scanf("%d %d",&x,&y);
if(x==0 && y==0)
break;
int arr[x],val[y],min1=INT_MAX,min2=INT_MAX,t=INT_MAX,min3=INT_MAX;
memset(arr,0,sizeof(arr));
memset(val,0,sizeof(val));
for(i=0;i<x;i++){
scanf("%d",&arr[i]);
min3=min(min3,arr[i]);}
for(i=0;i<y;i++){
scanf("%d",&val[i]);
/* sort(arr,arr+x);
sort(val,val+y);
if(arr[0]<val[1])
printf("Y\n");
else
printf("N\n");
*/
if(val[i]<=min1)
{ t=min1;
min1=val[i];
}
if(t!=min2 || val[i]!=min1)
if(val[i]!=min1)
min2=val[i];
else
min2=t;
// printf("%d %d %d\n",val[i],min1,min2);
}
t=0;
// printf("%d %d\n",min1,min2);
// if(t==0)
if(min3<min2)
printf("Y\n");
else
printf("N\n");
}
return 0;
}
| [
"kaushik12048@iiitd.ac.in"
] | kaushik12048@iiitd.ac.in |
79db64f12a00a6f4f8c4b65564ba730da3d03fda | 7d5b22941862884b36f111f9eddea956275b03b6 | /OpenGL/Windows/_PROGRAMMABLE_/13_Sphere_ADS_PV/Sphere_ADS_PV.cpp | 9ef9ca3f7ca6bcaa29ed380010aa1391e1c70d59 | [] | no_license | blckopps/RTR_Assignments | df6d9845111a862cca7a7d03a1104acc62359c7d | 6a05a2cb9c8dfef1d4313c97c48e26f5035db61e | refs/heads/master | 2022-12-10T14:39:07.063238 | 2020-05-22T19:54:59 | 2020-05-22T19:54:59 | 295,221,570 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,102 | cpp | #include<Windows.h>
#include<stdio.h>
#include<gl/glew.h>
#include<gl/GL.h>
#include"vmath.h"
#include"Sphere.h"
using namespace vmath;
#pragma comment(lib,"openGL32.lib")
#pragma comment(lib,"glew32.lib")
#pragma comment(lib,"Sphere.lib")
#define WIN_WIDTH 800
#define WIN_HEIGHT 600
FILE *gpfile = NULL;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
enum
{
AMC_ATTRIBUTES_POSITION = 0,
AMC_ATTRIBUTES_COLOR,
AMC_ATTRIBUTES_NORMAL,
AMC_ATTRIBUTES_TEXCOORD0
};
//GLOBAL VARIABLES
bool bFullScreen = false;
DWORD dwstyle;
WINDOWPLACEMENT wpPrev = { sizeof(WINDOWPLACEMENT) };
HWND ghwnd = NULL;
bool gbActiveWindow = false;
HDC ghdc = NULL;
HGLRC ghrc = NULL;
GLuint gShaderProgramObject;
//vao vbo
GLuint vao_sphere;
GLuint vbo_position_vbo;
GLuint vbo_normals_vbo;
GLuint vbo_element_vbo;
//Transformation matrix uniforms
GLuint modelMatrixUniform;
GLuint viewMatrixUniform;
GLuint projectionUniform;
mat4 perspectiveProjectionMatrix;
//shader uniforms
GLuint isLKeyIsPressedUniforms;
GLuint laUniform;
GLuint ldUniform;
GLuint lsUniform;
GLuint kaUniform;
GLuint kdUniform;
GLuint ksUniform;
GLuint shininessUniform;
GLuint lightPositionUniform;
bool isLighting = false;
//sphere var
float sphere_vertices[1146];
float sphere_normals[1146];
float sphere_textures[764];
unsigned short sphere_elements[2280];
GLsizei gNumVertices, gNumElements;
//light array
float lightAmbient[4] = { 0.0f, 0.0f, 0.0f, 0.0f};
float lightDifuse[4] = { 1.0f, 1.0f, 1.0f, 1.0f};
float lightSpecular[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
//material array
float materialAmbient[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
float materialDifuse[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
float materialSpecular[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
float lightPosition[4] = { 100.0f, 100.0f, 100.0f, 1.0f};
float materialShininess = 50.0f;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int iCmdShow)
{
//FUnction declaration
int initialize(void);
void display(void);
//void update();
//variable decl
int iret = 0;
bool bdone = false;
WNDCLASSEX wndclass;
HWND hwnd;
MSG msg;
TCHAR szAppName[] = TEXT("MYWINDOW ");
if (fopen_s(&gpfile, "log.txt", "w") != 0)
{
MessageBox(NULL, TEXT("Cant create log"), TEXT("ERROR!!!"), MB_OK);
}
else
{
fwprintf(gpfile, TEXT("log file created\n"));
}
wndclass.cbSize = sizeof(WNDCLASSEX);
wndclass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.lpfnWndProc = WndProc;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wndclass.lpszClassName = szAppName;
wndclass.lpszMenuName = NULL;
wndclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassEx(&wndclass);
//create window
hwnd = CreateWindowEx(WS_EX_APPWINDOW,
szAppName,
TEXT("SPHERE_ADS_PV-SHUBHAM"),
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPCHILDREN | WS_VISIBLE,
100,
100,
WIN_WIDTH,
WIN_HEIGHT,
NULL,
NULL,
hInstance,
NULL);
ghwnd = hwnd;
iret = initialize();
//handling return values and create log
if (iret == -1)
{
fwprintf(gpfile, TEXT("CHoice pixel format failed!!\n"));
DestroyWindow(hwnd);
}
else if (iret == -2)
{
fwprintf(gpfile, TEXT("SetPixelFormat failed!! \n"));
DestroyWindow(hwnd);
}
else if (iret == -3)
{
fwprintf(gpfile, TEXT("create context failed\n"));
DestroyWindow(hwnd);
}
else if (iret == -4)
{
fwprintf(gpfile, TEXT("wgl make current failed!!\n"));
DestroyWindow(hwnd);
}
else
{
fwprintf(gpfile, TEXT("Initialization Successful"));
}
ShowWindow(hwnd, iCmdShow);
SetForegroundWindow(hwnd);
SetFocus(hwnd);
//call in game loop UpdateWindow(hwnd);
while (bdone == false)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
{
bdone = true;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
if (gbActiveWindow == true)
{
//here call update
//update();
}
display();
}
}
return((int)msg.wParam);
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
//FUnction Declarations
void resize(int, int);
void uninitialize(void);
void toogle_screen(void);
switch (iMsg)
{
case WM_CHAR:
switch (wParam)
{
case 'l':
case 'L':
if (isLighting == false)
{
isLighting = true;
}
else
{
isLighting = false;
}
break;
default:
break;
}
break;
case WM_KEYDOWN:
switch (wParam)
{
case 0x46:
// MessageBox(hwnd,TEXT("P BUTTON PRESSED!!"),TEXT("BUTTON P"),MB_OK);
toogle_screen();
break;
case VK_ESCAPE:
if (bFullScreen == true) //We should exit from fullscreen and then destroy the window.
{
SetWindowLong(ghwnd,
GWL_STYLE,
dwstyle |
WS_OVERLAPPEDWINDOW);
SetWindowPlacement(ghwnd, &wpPrev);
SetWindowPos(ghwnd,
HWND_TOP,
0, 0, 0, 0,
SWP_NOZORDER |
SWP_FRAMECHANGED |
SWP_NOMOVE |
SWP_NOSIZE |
SWP_NOOWNERZORDER);
ShowCursor(TRUE);
}
DestroyWindow(hwnd);
break;
}
break;
case WM_SETFOCUS:
gbActiveWindow = true;
break;
case WM_KILLFOCUS:
gbActiveWindow = false;
break;
case WM_SIZE:
resize(LOWORD(lParam), HIWORD(lParam));
break;
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_ERASEBKGND:
return 0;
case WM_DESTROY:
//MessageBox(hwnd,TEXT("This is WM_DESTROY!!"),TEXT("In Wm_DESTROY"),MB_OK);
uninitialize();
PostQuitMessage(0);
break;
}
return(DefWindowProc(hwnd, iMsg, wParam, lParam));
}
//User Defined Functions
void toogle_screen(void)
{
//MONITORINFO mi;
if (bFullScreen == false)
{
dwstyle = GetWindowLong(ghwnd, GWL_STYLE);
if (dwstyle & WS_OVERLAPPEDWINDOW)
{
MONITORINFO mi = { sizeof(MONITORINFO) };
if (GetWindowPlacement(ghwnd, &wpPrev) && GetMonitorInfo(MonitorFromWindow(ghwnd, MONITORINFOF_PRIMARY), &mi))
{
SetWindowLong(ghwnd, GWL_STYLE, dwstyle&~WS_OVERLAPPEDWINDOW);
SetWindowPos(ghwnd,
HWND_TOP,
mi.rcMonitor.left,
mi.rcMonitor.top,
mi.rcMonitor.right - mi.rcMonitor.left,
mi.rcMonitor.bottom - mi.rcMonitor.top,
SWP_NOZORDER | SWP_FRAMECHANGED);
}
}
ShowCursor(FALSE);
bFullScreen = true;
}
else
{
SetWindowLong(ghwnd,
GWL_STYLE,
dwstyle |
WS_OVERLAPPEDWINDOW);
SetWindowPlacement(ghwnd, &wpPrev);
SetWindowPos(ghwnd,
HWND_TOP,
0, 0, 0, 0,
SWP_NOZORDER |
SWP_FRAMECHANGED |
SWP_NOMOVE |
SWP_NOSIZE |
SWP_NOOWNERZORDER);
ShowCursor(TRUE);
bFullScreen = false;
}
}
int initialize(void)
{
void resize(int, int);
void uninitialize(void);
//shader objects
GLuint gVertexShaderObject;
GLuint gFragmentShaderObject;
PIXELFORMATDESCRIPTOR pfd;
int iPixelFormatIndex;
GLenum result;
//code
ZeroMemory(&pfd, sizeof(PPIXELFORMATDESCRIPTOR));
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cRedBits = 8;
pfd.cGreenBits = 8;
pfd.cBlueBits = 8;
pfd.cAlphaBits = 8;
pfd.cDepthBits = 32;
ghdc = GetDC(ghwnd);
iPixelFormatIndex = ChoosePixelFormat(ghdc, &pfd);
if (iPixelFormatIndex == 0)
{
return -1;
}
if (SetPixelFormat(ghdc, iPixelFormatIndex, &pfd) == FALSE)
{
return -2;
}
ghrc = wglCreateContext(ghdc);
if (ghrc == NULL)
{
return -3;
}
if (wglMakeCurrent(ghdc, ghrc) == FALSE)
{
return -4;
}
///programmable Pipeline changes..
result = glewInit();
if (result != GLEW_OK)
{
fwprintf(gpfile, TEXT("glewInit failed"));
uninitialize();
DestroyWindow(ghwnd);
}
//************VERTEX SHADER***************************
//Define vertex shader Object
gVertexShaderObject = glCreateShader(GL_VERTEX_SHADER);
//write vertex shader code
//
const GLchar* vertexShaderSourceCode =
"#version 430 core" \
"\n" \
"in vec4 vPosition;" \
"in vec3 vNormal;" \
"uniform mat4 u_model_matrix;" \
"uniform mat4 u_view_matrix;" \
"uniform mat4 u_projection_matrix;" \
"uniform int islkeypressed;" \
"uniform vec3 u_la;" \
"uniform vec3 u_ld;" \
"uniform vec3 u_ls;" \
"uniform vec3 u_ka;" \
"uniform vec3 u_kd;" \
"uniform vec3 u_ks;" \
"uniform float u_shininess;" \
"uniform vec4 u_light_position;" \
"out vec3 phong_ads_light;" \
"void main(void)" \
"{" \
"if(islkeypressed == 1)" \
"{" \
"vec4 eye_coordinates = u_view_matrix * u_model_matrix * vPosition;" \
"vec3 tnorm = normalize(mat3(u_view_matrix * u_model_matrix) * vNormal);" \
"vec3 light_direction = normalize(vec3(u_light_position - eye_coordinates));" \
"float tn_dot_ldirection = max(dot(light_direction, tnorm), 0);" \
"vec3 reflection_vector = reflect(-light_direction, tnorm);" \
"vec3 viewer_vector = normalize(vec3(-eye_coordinates));" \
"vec3 ambient = u_la * u_ka;" \
"vec3 difuse = u_ld * u_kd * tn_dot_ldirection;" \
"vec3 specular = u_ls * u_ks * pow(max(dot(reflection_vector,viewer_vector),0),u_shininess);" \
"phong_ads_light = ambient + difuse + specular;" \
"}" \
"else" \
"{" \
"phong_ads_light = vec3(1.0, 1.0, 1.0);" \
"}" \
"gl_Position = u_projection_matrix * u_view_matrix * u_model_matrix * vPosition;" \
" } ";
//specify vertex source code to vetex shader object
glShaderSource(gVertexShaderObject,
1,
(GLchar **)&vertexShaderSourceCode,
NULL);
//compile vertex shader code
glCompileShader(gVertexShaderObject);
//Error checking
GLint iShaderCompilationStatus = 0;
GLint iInfoLength = 0;
GLchar *szInfoLog = NULL;
glGetShaderiv(gVertexShaderObject,
GL_COMPILE_STATUS,
&iShaderCompilationStatus);
if (iShaderCompilationStatus == GL_FALSE)
{
glGetShaderiv(gVertexShaderObject,
GL_INFO_LOG_LENGTH,
&iInfoLength);
if (iInfoLength > 0)
{
szInfoLog = (GLchar *)malloc(iInfoLength);
if (szInfoLog != NULL)
{
GLsizei writtened;
glGetShaderInfoLog(gVertexShaderObject,
iInfoLength,
&writtened,
szInfoLog);
fprintf(gpfile, "ERROR:VERTEX SHADER:%s", szInfoLog);
free(szInfoLog);
uninitialize();
DestroyWindow(ghwnd);
exit(0);
}
}
}
//********************FRAGMENT SHADER*****************
gFragmentShaderObject = glCreateShader(GL_FRAGMENT_SHADER);
//write vertex shader code
//
const GLchar * fragmentShaderSourceCode =
"#version 430 core" \
"\n" \
"out vec4 fragColor;" \
"uniform int islkeypressed;" \
"in vec3 phong_ads_light;" \
"void main(void)" \
"{" \
"if(islkeypressed == 1)" \
"{" \
"fragColor = vec4(phong_ads_light, 1.0);" \
"}" \
"else" \
"{" \
"fragColor = vec4(phong_ads_light, 1.0);" \
"}" \
"}";
//specify vertex source code to vetex shader object
glShaderSource(gFragmentShaderObject,
1,
(GLchar **)&fragmentShaderSourceCode,
NULL);
//compile vertex shader code
glCompileShader(gFragmentShaderObject);
//Error checking
iShaderCompilationStatus = 0;
iInfoLength = 0;
szInfoLog = NULL;
glGetShaderiv(gFragmentShaderObject,
GL_COMPILE_STATUS,
&iShaderCompilationStatus);
if (iShaderCompilationStatus == GL_FALSE)
{
glGetShaderiv(gFragmentShaderObject,
GL_INFO_LOG_LENGTH,
&iInfoLength);
if (iInfoLength > 0)
{
szInfoLog = (GLchar *)malloc(iInfoLength);
if (szInfoLog != NULL)
{
GLsizei writtened;
glGetShaderInfoLog(gFragmentShaderObject,
iInfoLength,
&writtened,
szInfoLog);
fprintf(gpfile, "ERROR:FRAGMENT SHADER:%s", szInfoLog);
free(szInfoLog);
uninitialize();
DestroyWindow(ghwnd);
exit(0);
}
}
}
//Create shader program object
gShaderProgramObject = glCreateProgram();
//Attach vertex,fragment shader program
glAttachShader(gShaderProgramObject, gVertexShaderObject);
glAttachShader(gShaderProgramObject, gFragmentShaderObject);
//*** PRELINKING BINDING TO VERTEX ATTRIBUTES***
glBindAttribLocation(gShaderProgramObject,
AMC_ATTRIBUTES_POSITION,
"vPosition");
glBindAttribLocation(gShaderProgramObject,
AMC_ATTRIBUTES_NORMAL,
"vNormal");
//link above shader program
glLinkProgram(gShaderProgramObject);
// ***ERROR CHECKING LINKING********
//Error checking for program linking
GLint iShaderLinkStatus = 0;
iInfoLength = 0;
szInfoLog = NULL;
glGetProgramiv(gShaderProgramObject,
GL_LINK_STATUS,
&iShaderLinkStatus);
if (iShaderCompilationStatus == GL_FALSE)
{
glGetProgramiv(gShaderProgramObject,
GL_INFO_LOG_LENGTH,
&iInfoLength);
if (iInfoLength > 0)
{
szInfoLog = (GLchar *)malloc(iInfoLength);
if (szInfoLog != NULL)
{
GLsizei wr;
glGetShaderInfoLog(gShaderProgramObject,
iInfoLength,
&wr,
szInfoLog);
fwprintf(gpfile, TEXT("ERROR:SHADER LINK:%s"), szInfoLog);
free(szInfoLog);
uninitialize();
DestroyWindow(ghwnd);
exit(0);
}
}
}
///***POST LINKING GETTING UNIFORMS**
//getting light uniforms locations
isLKeyIsPressedUniforms = glGetUniformLocation(gShaderProgramObject, "islkeypressed");
laUniform = glGetUniformLocation(gShaderProgramObject, "u_la");
ldUniform = glGetUniformLocation(gShaderProgramObject, "u_ld");
lsUniform = glGetUniformLocation(gShaderProgramObject, "u_ls");
kaUniform = glGetUniformLocation(gShaderProgramObject, "u_ka");
kdUniform = glGetUniformLocation(gShaderProgramObject, "u_kd");
ksUniform = glGetUniformLocation(gShaderProgramObject, "u_ks");
shininessUniform = glGetUniformLocation(gShaderProgramObject, "u_shininess");
lightPositionUniform = glGetUniformLocation(gShaderProgramObject, "u_light_position");
//getting transformation matrices uniform locations
modelMatrixUniform = glGetUniformLocation(gShaderProgramObject, "u_model_matrix");
viewMatrixUniform = glGetUniformLocation(gShaderProgramObject, "u_view_matrix");
projectionUniform = glGetUniformLocation(gShaderProgramObject, "u_projection_matrix");
fwprintf(gpfile, TEXT("Post link success!!\n"));
//sphere
getSphereVertexData(sphere_vertices, sphere_normals, sphere_textures, sphere_elements);
gNumVertices = getNumberOfSphereVertices();
gNumElements = getNumberOfSphereElements();
//VAO AND VBO
glGenVertexArrays(1, &vao_sphere);
glBindVertexArray(vao_sphere);
//position
glGenBuffers(1, &vbo_position_vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo_position_vbo);
glBufferData(GL_ARRAY_BUFFER,
sizeof(sphere_vertices),
sphere_vertices,
GL_STATIC_DRAW);
glVertexAttribPointer(AMC_ATTRIBUTES_POSITION,
3,
GL_FLOAT,
GL_FALSE,
0,
NULL);
glEnableVertexAttribArray(AMC_ATTRIBUTES_POSITION);
glBindBuffer(GL_ARRAY_BUFFER, 0);
//normal
glGenBuffers(1, &vbo_normals_vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo_normals_vbo);
glBufferData(GL_ARRAY_BUFFER,
sizeof(sphere_normals),
sphere_normals,
GL_STATIC_DRAW);
glVertexAttribPointer(AMC_ATTRIBUTES_NORMAL,
3,
GL_FLOAT,
GL_FALSE,
0,
NULL);
glEnableVertexAttribArray(AMC_ATTRIBUTES_NORMAL);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// element vbo
glGenBuffers(1, &vbo_element_vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_element_vbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(sphere_elements), sphere_elements, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
//unbind vao
glBindVertexArray(0);
//START:
//END:
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClearDepth(1.0f);
perspectiveProjectionMatrix = mat4::identity();
resize(WIN_WIDTH, WIN_HEIGHT);
return 0;
}
void resize(int width, int height)
{
if (height == 0)
{
height = 1;
}
glViewport(0, 0, (GLsizei)width, (GLsizei)height);
perspectiveProjectionMatrix =
perspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 100.0f);
}
void display(void)
{
//fwprintf(gpfile,TEXT("In Display\n"));
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(gShaderProgramObject);
//declare matrices
mat4 viewMatrix;
mat4 modelMatrix;
//make identity matrices
viewMatrix = mat4::identity();
modelMatrix = mat4::identity();
//Do transformations...
modelMatrix = translate(0.0f, 0.0f, -3.0f);
//send neccessary matrix to shader in respective uniforms
//key events uniforms
if (isLighting == true)
{
glUniform1i(isLKeyIsPressedUniforms, 1);
glUniform1f(shininessUniform, materialShininess);
glUniform3fv(laUniform, 1, lightAmbient);
glUniform3fv(ldUniform, 1, lightDifuse);
glUniform3fv(lsUniform, 1, lightSpecular);
glUniform3fv(kaUniform, 1, materialAmbient);
glUniform3fv(kdUniform, 1, materialDifuse);
glUniform3fv(ksUniform, 1, materialSpecular);
glUniform4fv(lightPositionUniform, 1, lightPosition);
}
else
{
glUniform1i(isLKeyIsPressedUniforms, 0);
}
glUniformMatrix4fv(modelMatrixUniform,
1,
GL_FALSE,
modelMatrix
);
glUniformMatrix4fv(viewMatrixUniform,
1,
GL_FALSE,
viewMatrix
);
glUniformMatrix4fv(projectionUniform,
1,
GL_FALSE,
perspectiveProjectionMatrix);
//Bind with vao
//similarly bind with texture in any
glBindVertexArray(vao_sphere);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_element_vbo);
glDrawElements(GL_TRIANGLES, gNumElements, GL_UNSIGNED_SHORT, 0);
glBindVertexArray(0);
glUseProgram(0);
SwapBuffers(ghdc);
//fwprintf(gpfile,TEXT("End OF display\n"));
}
void uninitialize(void)
{
if (vbo_element_vbo)
{
glDeleteBuffers(1, &vbo_element_vbo);
vbo_element_vbo = 0;
}
if (vbo_normals_vbo)
{
glDeleteVertexArrays(1, &vbo_normals_vbo);
vbo_normals_vbo = 0;
}
if (vbo_position_vbo)
{
glDeleteVertexArrays(1, &vbo_position_vbo);
vbo_position_vbo = 0;
}
////shader uninitialize code
GLsizei shaderCount;
GLsizei shaderNumber;
if (gShaderProgramObject)
{
glUseProgram(gShaderProgramObject);
glGetProgramiv(gShaderProgramObject,
GL_ATTACHED_SHADERS,
&shaderCount);
GLuint *pShaders = (GLuint*)malloc(sizeof(GLuint)*shaderCount);
if (pShaders)
{
glGetAttachedShaders(gShaderProgramObject,
shaderCount,
&shaderCount,
pShaders);
for (shaderNumber = 0; shaderNumber < shaderCount; shaderNumber++)
{
glDetachShader(gShaderProgramObject,
pShaders[shaderNumber]);
glDeleteShader(pShaders[shaderNumber]);
pShaders[shaderNumber] = 0;
}
free(pShaders);
}
glDeleteProgram(gShaderProgramObject);
gShaderProgramObject = 0;
glUseProgram(0);
}
if (bFullScreen == true)
{
SetWindowLong(ghwnd,
GWL_STYLE,
dwstyle |
WS_OVERLAPPEDWINDOW);
SetWindowPlacement(ghwnd, &wpPrev);
SetWindowPos(ghwnd,
HWND_TOP,
0, 0, 0, 0,
SWP_NOZORDER |
SWP_FRAMECHANGED |
SWP_NOMOVE |
SWP_NOSIZE |
SWP_NOOWNERZORDER);
ShowCursor(TRUE);
}
if (wglGetCurrentContext() == ghrc)
{
wglMakeCurrent(NULL, NULL);
}
if (ghrc)
{
wglDeleteContext(ghrc);
ghrc = NULL;
}
if (ghdc)
{
ReleaseDC(ghwnd, ghdc);
ghdc = NULL;
}
}
| [
"shubhambendre96@gmail.com"
] | shubhambendre96@gmail.com |
74d63cc7204a1b2b6410cdf5416c982737ff8e38 | 2a4920c4d712e86e28d634d71c4c415062107173 | /ext/messageevent.cpp | 317f1e29ef65ae2cc947f8a985923ea9b7e17b6c | [] | no_license | vbatts/Quassel-Ruby | bd157a2c5eb79dc45a54b5c383c4bbb53a100adf | 0ac351175ba87e737c2f17e2cfcfb7de88bfe283 | refs/heads/master | 2020-12-25T11:15:25.384827 | 2012-02-23T14:30:43 | 2012-02-23T14:30:43 | 3,526,057 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38 | cpp | ../quassel/src/common/messageevent.cpp | [
"yaohan.chen@gmail.com"
] | yaohan.chen@gmail.com |
3ccd93b084422380ee299c57e621b9e414125180 | 03e537c15e2859a8a272c6a26af0507895db2991 | /电阻读数器Dlg.cpp | 29360242138191e1898d7afacd31c3a8ee9315df | [] | no_license | wimiDev/- | 618f49be7ee6e7aae4e0af7b29405edfcd6a42b3 | 194b845eeb3ce2708c27f5a8532be9f9c11d4ee6 | refs/heads/master | 2021-01-16T22:17:59.362403 | 2014-12-25T07:29:04 | 2014-12-25T07:29:04 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,266 | cpp | // 电阻读数器Dlg.cpp : implementation file
//
#include "stdafx.h"
#include "电阻读数器.h"
#include "电阻读数器Dlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
int Getfive();
int Getfour();
int Getthree();
int Gettwo();
int Getone();
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMyDlg dialog
CMyDlg::CMyDlg(CWnd* pParent /*=NULL*/)
: CDialog(CMyDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CMyDlg)
m_out = _T("");
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CMyDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CMyDlg)
DDX_Control(pDX, IDC_COMBO5, m_five);
DDX_Control(pDX, IDC_COMBO4, m_four);
DDX_Control(pDX, IDC_COMBO3, m_three);
DDX_Control(pDX, IDC_COMBO2, m_two);
DDX_Control(pDX, IDC_COMBO1, m_one);
DDX_Text(pDX, IDC_OUT, m_out);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CMyDlg, CDialog)
//{{AFX_MSG_MAP(CMyDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_OK, OnOk)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMyDlg message handlers
BOOL CMyDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
}
void CMyDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CMyDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CMyDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CMyDlg::OnOk()
{
/*获取用户输入数据*/
int t1,t2,t3,t4,t5;
CString range="";
t1=Getone();
t2=Gettwo();
t3=Getthree();
t4=Getfour();
t5=Getfive();
if(t5==1)
{
range="+-1";
}
else if(t5==2)
{
range="+-2";
}
else if(t5==5)
{
range="+-0.5";
}
else if(t5==6)
{
range="+-0.25";
}
else if(t5==7)
{
range="+-0.1";
}
else if(t5==10)
{
range="+-5";
}
else if(t5==11)
{
range="+-10";
}
m_out.Format("%d欧<%s>",FAdd(t1,t2,t3,t4),range);
UpdateData(FALSE);
}
int CMyDlg::Getone()
{/*获取第一环*/
CString Snum1="";
int num1=0;
GetDlgItem(IDC_COMBO1)->GetWindowText(Snum1);
if(Snum1=="黑")
{
num1=0;
}
if(Snum1=="棕")
{
num1=1;
}
if(Snum1=="红")
{
num1=2;
}
if(Snum1=="橙")
{
num1=3;
}
if(Snum1=="黄")
{
num1=4;
}
if(Snum1=="绿")
{
num1=5;
}if(Snum1=="蓝")
{
num1=6;
}
if(Snum1=="紫")
{
num1=7;
}
if(Snum1=="灰")
{
num1=8;
}
if(Snum1=="白")
{
num1=9;
}
return num1;
}
int CMyDlg::Gettwo()
{/*获取第二环*/
CString Snum2="";
int num2=0;
GetDlgItem(IDC_COMBO2)->GetWindowText(Snum2);
if(Snum2=="黑")
{
num2=0;
}
if(Snum2=="棕")
{
num2=1;
}
if(Snum2=="红")
{
num2=2;
}
if(Snum2=="橙")
{
num2=3;
}
if(Snum2=="黄")
{
num2=4;
}
if(Snum2=="绿")
{
num2=5;
}if(Snum2=="蓝")
{
num2=6;
}
if(Snum2=="紫")
{
num2=7;
}
if(Snum2=="灰")
{
num2=8;
}
if(Snum2=="白")
{
num2=9;
}
return num2;
}
int CMyDlg::Getthree()
{
/*获取第三环*/
CString Snum3="";
int num3=0;
GetDlgItem(IDC_COMBO3)->GetWindowText(Snum3);
if(Snum3=="黑")
{
num3=0;
}
if(Snum3=="棕")
{
num3=1;
}
if(Snum3=="红")
{
num3=2;
}
if(Snum3=="橙")
{
num3=3;
}
if(Snum3=="黄")
{
num3=4;
}
if(Snum3=="绿")
{
num3=5;
}if(Snum3=="蓝")
{
num3=6;
}
if(Snum3=="紫")
{
num3=7;
}
if(Snum3=="灰")
{
num3=8;
}
if(Snum3=="白")
{
num3=9;
}
return num3;
}
int CMyDlg::Getfour()
{/*获取第四环*/
CString Snum4="";
int num4=0;
GetDlgItem(IDC_COMBO4)->GetWindowText(Snum4);
if(Snum4=="黑")
{
num4=0;
}
if(Snum4=="棕")
{
num4=1;
}
if(Snum4=="红")
{
num4=2;
}
if(Snum4=="橙")
{
num4=3;
}
if(Snum4=="黄")
{
num4=4;
}
if(Snum4=="绿")
{
num4=5;
}if(Snum4=="蓝")
{
num4=6;
}
if(Snum4=="紫")
{
num4=7;
}
if(Snum4=="灰")
{
num4=8;
}
if(Snum4=="白")
{
num4=9;
}
return num4;
}
int CMyDlg::Getfive()
{/*获取第五环*/
CString Snum5="";
int num5=0;
GetDlgItem(IDC_COMBO5)->GetWindowText(Snum5);
if(Snum5=="黑")
{
num5=0;
}
if(Snum5=="棕")
{
num5=1;
}
if(Snum5=="红")
{
num5=2;
}
if(Snum5=="橙")
{
num5=3;
}
if(Snum5=="黄")
{
num5=4;
}
if(Snum5=="绿")
{
num5=5;
}if(Snum5=="蓝")
{
num5=6;
}
if(Snum5=="紫")
{
num5=7;
}
if(Snum5=="灰")
{
num5=8;
}
if(Snum5=="白")
{
num5=9;
}
if(Snum5=="金")
{
num5=10;
}
if(Snum5=="银")
{
num5=11;
}
return num5;
}
int CMyDlg::FAdd(int n1,int n2,int n3,int n4)
{
long int temp=1,sum;
n1=n1*100;
n2=n2*10;
for(int i=1;i<=n4;i++)
{
temp=temp*10;
}
sum=(n1+n2+n3)*temp;
return sum;
}
| [
"1422778658@qq.com"
] | 1422778658@qq.com |
6a0c66b640a095bab3bda3ee795902c9234d32e1 | fec81bfe0453c5646e00c5d69874a71c579a103d | /blazetest/src/mathtest/operations/dvecdvecinner/VDbV5b.cpp | 863b61ff21fa22c1dfb5e230601d3aa7580df260 | [
"BSD-3-Clause"
] | permissive | parsa/blaze | 801b0f619a53f8c07454b80d0a665ac0a3cf561d | 6ce2d5d8951e9b367aad87cc55ac835b054b5964 | refs/heads/master | 2022-09-19T15:46:44.108364 | 2022-07-30T04:47:03 | 2022-07-30T04:47:03 | 105,918,096 | 52 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 3,760 | cpp | //=================================================================================================
/*!
// \file src/mathtest/operations/dvecdvecinner/VDbV5b.cpp
// \brief Source file for the VDbV5b dense vector/dense vector inner product math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/StaticVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/operations/dvecdvecinner/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'VDbV5b'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Vector type definitions
using VDb = blaze::DynamicVector<TypeB>;
using V5b = blaze::StaticVector<TypeB,5UL>;
// Creator type definitions
using CVDb = blazetest::Creator<VDb>;
using CV5b = blazetest::Creator<V5b>;
// Running the tests
RUN_DVECDVECINNER_OPERATION_TEST( CVDb( 5UL ), CV5b() );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector inner product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
c9166012f489c2045c087fe0f893c4dd17483534 | f29aea2926172c13af28b2ae9e30c3f6dd7ca5a4 | /CrossingTheRoad/GameCrossingTheRoad/GameCrossingTheRoad/Traffic.cpp | a625dd90b2337fcc863d60e7a2b291cf8855495b | [] | no_license | VoQuocThang/CrossingTheRoadGame | fdd227945976b9c963826312cbb4bf6ca8ecd22b | a47d7e948a5f1746248c2e5124fe19ece6210a5a | refs/heads/master | 2020-04-19T02:09:52.411525 | 2019-01-28T03:28:19 | 2019-01-28T03:28:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 370 | cpp | #include "stdafx.h"
#include "Traffic.h"
Traffic::Traffic(){
Time = tick;
_x = _y = 0;
}
Traffic::Traffic(int x, int y) {
Time = tick;
_x = x;
_y = y;
}
void Traffic::paint() {
if (isRed()) {
gotoXY(_x, _y);
TextColor(ColorCode_Red);
putchar(219);
}
else {
gotoXY(_x, _y);
TextColor(ColorCode_Green);
putchar(219);
}
}
Traffic::~Traffic()
{
}
| [
"1712162@student.hcmus.edu.vn"
] | 1712162@student.hcmus.edu.vn |
14fd414d2b1efb4c4ebba1e61f85f647ed5717fd | 64fab2429ec6554a1acc900fcac5019725cb84b1 | /SYN.h | 4edbf4cd35d0ec0aaa4528d2f0363fc92e9b2f90 | [] | no_license | YihuaLiang/C-language-Compile | 461c6e0de96b3717e29450d6c8a474348b393a4a | 86b6892ac86842d9f5abc506ab00a4f33ad1d7a2 | refs/heads/master | 2020-07-08T19:18:16.650040 | 2019-08-22T09:05:08 | 2019-08-22T09:05:08 | 203,754,882 | 2 | 3 | null | null | null | null | GB18030 | C++ | false | false | 12,273 | h | #ifndef LEX
#define LEX
#include "write_xml\tinystr.h"
#include "write_xml\tinyxml.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <cstring>
#include <iostream>
using namespace std;
//函数传参,当前位置的值,当前位置
//提供词法分析得到的当前值
//使用前,给词法分析的结尾 + #表示结束
int point = 0;//当前指针 - 当返回时,指向的位置不是# 说明在中间位置出现了错误
struct ww
{
char value[255];
char type[20];
int line;
}word[200];
//注意对行数的字符->数字问题
//valid值不再需要 因此直接放弃
void write(TiXmlElement * pNew)
{
TiXmlElement *pTxt = new TiXmlElement(word[point].type);
pNew->LinkEndChild(pTxt);
TiXmlText * Content = new TiXmlText(word[point].value);
pTxt->LinkEndChild(Content);
}
void read(char target[])
{
int num = 0;
TiXmlDocument mydoc(target);//xml文档对象
bool loadOk = mydoc.LoadFile();//加载文档
if (!loadOk)
{
cout << "could not load the test file.Error:" << mydoc.ErrorDesc() << endl;
exit(1);
}
TiXmlElement *RootElement = mydoc.RootElement(); //根元素, Info
TiXmlElement *pEle = RootElement;
TiXmlElement *pTokens = pEle->FirstChildElement();
//遍历该结点
for (TiXmlElement *tokenElement = pTokens->FirstChildElement();//第一个子元素
tokenElement != NULL;
tokenElement = tokenElement->NextSiblingElement())//下一个兄弟元素
{
TiXmlAttribute *pAttr = tokenElement->FirstAttribute();//第一个属性
int j = 0;
for (TiXmlElement *sonElement = tokenElement->FirstChildElement();
sonElement != NULL;
sonElement = sonElement->NextSiblingElement(), j++)
{
j %= 4;
if (j == 0)
strcpy(word[num].value, sonElement->FirstChild()->Value());
else if (j == 1)
strcpy(word[num].type, sonElement->FirstChild()->Value());
else if (j == 2)
{
char tmp_line[20];
strcpy(tmp_line, sonElement->FirstChild()->Value());
//转化数字和字符
int len = strlen(tmp_line);
word[num].line = 0;
for (int k = len - 1; k >= 0; k--)
{
word[num].line += pow(10, len - k - 1)*(tmp_line[k] - '0');
}
}
else
num++;
}
}
}
void CMPL_UNIT(TiXmlElement * pEnd);
void FUNC_LIST(TiXmlElement * pEnd);
void FUNC_DEF(TiXmlElement * pEnd);
void TYPE_SPEC(TiXmlElement * pEnd);
void PARA_LIST(TiXmlElement * pEnd);
void ARGUMENT(TiXmlElement * pEnd);
void CODE_BLOCK(TiXmlElement * pEnd);
void STMT_LIST(TiXmlElement * pEnd);
void STMT(TiXmlElement * pEnd);
void RTN_STMT(TiXmlElement * pEnd);
void ASSIGN_STMT(TiXmlElement * pEnd);
void EXPR(TiXmlElement * pEnd);
void EXPR2(TiXmlElement * pEnd);
void TERM(TiXmlElement * pEnd);
void TERM2(TiXmlElement * pEnd);
void FACTOR(TiXmlElement * pEnd);
void WHILE(TiXmlElement * pEnd);
void CONDITION(TiXmlElement * pEnd);
void IF(TiXmlElement * pEnd);
void ELSEIF(TiXmlElement * pEnd);
void RELATION(TiXmlElement * pEnd);
void DECLARE(TiXmlElement * pEnd);
void DECLARE_STMT(TiXmlElement * pEnd);
void CMPL_UNIT(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("CMPL_UNIT");
pEnd->LinkEndChild(pNew);
FUNC_LIST(pNew);
}
//求FOLLOW集合
void FUNC_LIST(TiXmlElement * pEnd)
{ //不取空的情况
if (strcmp(word[point].value, "#") != 0)
{
TiXmlElement *pNew = new TiXmlElement("FUNC_LIST");
pEnd->LinkEndChild(pNew);
FUNC_DEF(pNew);
FUNC_LIST(pNew);
}
}
void FUNC_DEF(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("FUNC_DEF");
pEnd->LinkEndChild(pNew);
TYPE_SPEC(pNew);
if (strcmp(word[point].type, "identifer") == 0)//说明是变量
{
write(pNew);
point++;
if (strcmp(word[point].value, "(") == 0)
{
write(pNew);
point++;
PARA_LIST(pNew);
if (strcmp(word[point].value, ")") == 0)
{
write(pNew);
point++;
CODE_BLOCK(pNew);
}
}
}
}
void TYPE_SPEC(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("TYPE_SPEC");
pEnd->LinkEndChild(pNew);
if (strcmp(word[point].value, "int") == 0 ||
strcmp(word[point].value, "void") == 0)
{
write(pNew);
point++;
}
}
//FOLLOW集合
void PARA_LIST(TiXmlElement * pEnd)
{
if (strcmp(word[point].value, ")") != 0)
{
TiXmlElement *pNew = new TiXmlElement("PARA_LIST");
pEnd->LinkEndChild(pNew);
ARGUMENT(pNew);
if (strcmp(word[point].value, ",") == 0)
{
write(pNew);
point++;
PARA_LIST(pNew);
}
}
}
void ARGUMENT(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("ARGUMENT");
pEnd->LinkEndChild(pNew);
TYPE_SPEC(pNew);
if (strcmp(word[point].type, "identifer") == 0)
{
write(pNew);
point++;
}
}
void CODE_BLOCK(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("CODE_BLOCK");
pEnd->LinkEndChild(pNew);
if (strcmp(word[point].value, "{") == 0)
{
write(pNew);
point++;
STMT_LIST(pNew);
if (strcmp(word[point].value, "}") == 0)
{
write(pNew);
point++;
}
}
}
//FOLLOW集合
void STMT_LIST(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("STMT_LIST");
pEnd->LinkEndChild(pNew);
if (strcmp(word[point].value, "}") != 0)
{
STMT(pNew);
STMT_LIST(pNew);
}
}
void STMT(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("STMT");
pEnd->LinkEndChild(pNew);
if (strcmp(word[point].value, "return") == 0)
{
RTN_STMT(pNew);
if (strcmp(word[point].value, ";") == 0)
{
write(pNew);
point++;
}
}
//观察first集合的不同,选择值
else if (strcmp(word[point].type, "identifer") == 0)
{
ASSIGN_STMT(pNew);
if (strcmp(word[point].value, ";") == 0)
{
write(pNew);
point++;
}
}
else if (strcmp(word[point].value, "int") == 0)
{
DECLARE(pNew);
if (strcmp(word[point].value, ";") == 0)
{
write(pNew);
point++;
}
}
else if (strcmp(word[point].value, "if") == 0) IF(pNew);
else if (strcmp(word[point].value, "while") == 0) WHILE(pNew);
}
void RTN_STMT(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("RTN_STMT");
pEnd->LinkEndChild(pNew);
if (strcmp(word[point].value, "return") == 0)
{
write(pNew);
point++;
EXPR(pNew);
/*if (strcmp(word[point].value, ";") == 0)
{
write(pNew);
point++;
}*/
}
}
void ASSIGN_STMT(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("ASSIGN_STMT");
pEnd->LinkEndChild(pNew);
if (strcmp(word[point].type, "identifer") == 0)
{
write(pNew);
point++;
if (strcmp(word[point].value, "=") == 0)
{
write(pNew);
point++;
EXPR(pNew);
/*if (strcmp(word[point].value, ";") == 0)
{
write(pNew);
point++;
}*/
}
}
}
void EXPR(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("EXPR");
pEnd->LinkEndChild(pNew);
TERM(pNew);
EXPR2(pNew);
}
//FOLLOW集合
void EXPR2(TiXmlElement * pEnd)
{
if (strcmp(word[point].value, ";") != 0 &&
strcmp(word[point].value, ")") != 0 &&
strcmp(word[point].value, ",") != 0 &&
strcmp(word[point].value, "<") != 0 &&
strcmp(word[point].value, ">") != 0 &&
strcmp(word[point].value, "<=") != 0 &&
strcmp(word[point].value, ">=") != 0 &&
strcmp(word[point].value, "!=") != 0 &&
strcmp(word[point].value, "==") != 0)
{
TiXmlElement *pNew = new TiXmlElement("EXPR2");
pEnd->LinkEndChild(pNew);
if (strcmp(word[point].value, "+") == 0)
{
write(pNew);
point++;
TERM(pNew);
EXPR2(pNew);
}
else if (strcmp(word[point].value, "-") == 0)
{
point++;
TERM(pNew);
EXPR2(pNew);
}
}
}
void TERM(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("TERM");
pEnd->LinkEndChild(pNew);
FACTOR(pNew);
TERM2(pNew);
}
//FOLLOW集合;
void TERM2(TiXmlElement * pEnd)
{
if (strcmp(word[point].value, ";") != 0 &&
strcmp(word[point].value, ")") != 0 &&
strcmp(word[point].value, ",") != 0 &&
strcmp(word[point].value, "+") != 0 &&
strcmp(word[point].value, "-") != 0 &&
strcmp(word[point].value, "<") != 0 &&
strcmp(word[point].value, ">") != 0 &&
strcmp(word[point].value, "<=") != 0 &&
strcmp(word[point].value, ">=") != 0 &&
strcmp(word[point].value, "!=") != 0 &&
strcmp(word[point].value, "==") != 0
)
{
TiXmlElement *pNew = new TiXmlElement("TERM2");
pEnd->LinkEndChild(pNew);
if (strcmp(word[point].value, "*") == 0)
{
write(pNew);
point++;
FACTOR(pNew);
EXPR2(pNew);
}
else if (strcmp(word[point].value, "/") == 0)
{
write(pNew);
point++;
FACTOR(pNew);
EXPR2(pNew);
}
}
}
void FACTOR(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("FACTOR");
pEnd->LinkEndChild(pNew);
if (strcmp(word[point].type, "identifer") == 0)//当是标识符时
{
write(pNew);
point++;
}
else if (strcmp(word[point].type, "const_i") == 0 ||
strcmp(word[point].type, "const_f") == 0 ||
strcmp(word[point].type, "stringLiteral") == 0 ||
strcmp(word[point].type, "characterConstant") == 0)//当是常量时
{
write(pNew);
point++;
}
else if (strcmp(word[point].value, "(") == 0)
{
write(pNew);
point++;
EXPR(pNew);
if (strcmp(word[point].value, ")") == 0)
{
write(pNew);
point++;
}
}
}
void IF(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("IF");
pEnd->LinkEndChild(pNew);
if (strcmp(word[point].value, "if") == 0)
{
write(pNew);
point++;
if (strcmp(word[point].value, "(") == 0)
{
write(pNew);
point++;
CONDITION(pNew);
if (strcmp(word[point].value, ")") == 0)
{
write(pNew);
point++;
CODE_BLOCK(pNew);
ELSEIF(pNew);
}
}
}
}
void ELSEIF(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("ELSEIF");
pEnd->LinkEndChild(pNew);
if (strcmp(word[point].value, "if") != 0 &&
strcmp(word[point].value, "return") != 0 &&
strcmp(word[point].value, "while") != 0 &&
strcmp(word[point].type, "identifer") != 0)
{
if (strcmp(word[point].value, "else") == 0)
{
write(pNew);
point++;
CODE_BLOCK(pNew);
}
}
}
void WHILE(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("WHILE");
pEnd->LinkEndChild(pNew);
if (strcmp(word[point].value, "while") == 0)
{
write(pNew);
point++;
if (strcmp(word[point].value, "(") == 0)
{
write(pNew);
point++;
CONDITION(pNew);
if (strcmp(word[point].value, ")") == 0)
{
write(pNew);
point++;
CODE_BLOCK(pNew);
}
}
}
}
void CONDITION(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("CONDITION");
pEnd->LinkEndChild(pNew);
EXPR(pNew);
RELATION(pNew);
EXPR(pNew);
}
void RELATION(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("RELATION");
pEnd->LinkEndChild(pNew);
int flag = 0;
if (strcmp(word[point].value, ">") == 0) {flag = 1; }
else if (strcmp(word[point].value, ">=") == 0) {flag = 1;}
else if (strcmp(word[point].value, "==") == 0) {flag = 1;}
else if (strcmp(word[point].value, "<") == 0) {flag = 1; }
else if (strcmp(word[point].value, "<=") == 0) {flag = 1;}
else if (strcmp(word[point].value, "!=") == 0) {flag = 1;}
if (flag == 1)
{
write(pNew);
point++;
}
}
void DECLARE(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("DECLARE");
pEnd->LinkEndChild(pNew);
TYPE_SPEC(pNew);
DECLARE_STMT(pNew);
}
void DECLARE_STMT(TiXmlElement * pEnd)
{
TiXmlElement *pNew = new TiXmlElement("DECLARE_STMT");
pEnd->LinkEndChild(pNew);
if (strcmp(word[point].type, "identifer") == 0 &&
strcmp(word[point + 1].value, "=") != 0)
{
write(pNew);
point++;
/*if (strcmp(word[point].value, ";") == 0)
{ write(pNew);
point++;
}*/
if (strcmp(word[point].value, ",") == 0)
{
write(pNew);
point++;
DECLARE_STMT(pNew);
}
}
else if (strcmp(word[point].type, "identifer") == 0&&
strcmp(word[point+1].value, "=") == 0)
{
ASSIGN_STMT(pNew);
if (strcmp(word[point].value, ",") == 0)
{
write(pNew);
point++;
DECLARE_STMT(pNew);
}
}
}
#endif // LEX.h
| [
"noreply@github.com"
] | noreply@github.com |
fd11844e9f19df222e6f6d8382c5930be1211bd5 | 42f40805c9379fb68a5caf15583a36db38a9647a | /FPSProject/Source/FPSProject/FPSCharacter.h | 586f38e350b746576a181c6c902e887ce0a502b4 | [] | no_license | TeamSuperSmash/ue4cc-TerrenceChan | 73302eef525f6a9f7ee08777b510772d66c294dd | f7e09be85b357f894d087f5b749c4a996a141d1a | refs/heads/master | 2020-03-15T10:20:13.240073 | 2018-06-12T16:30:19 | 2018-06-12T16:30:19 | 132,096,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,544 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "FPSProject.h"
#include "GameFramework/Character.h"
#include "Camera/CameraComponent.h"
#include "FPSProjectile.h"
#include "FPSCharacter.generated.h"
UCLASS()
class FPSPROJECT_API AFPSCharacter : public ACharacter
{
GENERATED_BODY()
public:
// Sets default values for this character's properties
AFPSCharacter();
float speedMultiplier = 10.0f;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
UFUNCTION()
void MoveForward(float value);
UFUNCTION()
void MoveRight(float value);
UFUNCTION()
void SetYawSensitivity(float value);
UFUNCTION()
void SetPitchSensitivity(float value);
UFUNCTION()
void StartJump();
UFUNCTION()
void StopJump();
UFUNCTION()
void Fire();
// FPS Camera.
UPROPERTY(VisibleAnywhere)
UCameraComponent* FPSCameraComponent;
UPROPERTY(VisibleDefaultsOnly, Category = Mesh)
USkeletalMeshComponent* FPSMesh;
UPROPERTY(EditAnywhere, Category = Gameplay)
FVector MuzzleOffset;
UPROPERTY(EditDefaultsOnly, Category = Projectile)
TSubclassOf<class AFPSProjectile> ProjectileClass;
}; | [
"roxes2112@yahoo.com"
] | roxes2112@yahoo.com |
56eb38e5896b798cabd3db2fb8734f6f6f336ebb | d678a380ad8db03eaf785a6f490f60a11e90c036 | /GeoFeatures/Internal/boost/mpl/aux_/preprocessed/no_ttp/equal_to.hpp | 7f9f1bebf91afed80a831a29b6c3834287ebd975 | [
"BSL-1.0",
"Apache-2.0"
] | permissive | Niko-r/geofeatures | 0eaa09c65bd9c7e47c3da7bb69e2f20776ba557c | b3b1311f7836b700d47064490e3d7533b8d574ee | refs/heads/master | 2020-05-29T11:07:11.474367 | 2016-07-16T01:43:36 | 2016-07-16T01:43:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,357 | hpp |
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// Preprocessed version of "boost/mpl/equal_to.hpp" header
// -- DO NOT modify by hand!
namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace mpl {
template<
typename Tag1
, typename Tag2
>
struct equal_to_impl
: if_c<
( BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag1)
> BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag2)
)
, aux::cast2nd_impl< equal_to_impl< Tag1,Tag1 >,Tag1, Tag2 >
, aux::cast1st_impl< equal_to_impl< Tag2,Tag2 >,Tag1, Tag2 >
>::type
{
};
/// for Digital Mars C++/compilers with no CTPS/TTP support
template<> struct equal_to_impl< na,na >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename Tag > struct equal_to_impl< na,Tag >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename Tag > struct equal_to_impl< Tag,na >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename T > struct equal_to_tag
{
typedef typename T::tag type;
};
template<
typename BOOST_MPL_AUX_NA_PARAM(N1)
, typename BOOST_MPL_AUX_NA_PARAM(N2)
>
struct equal_to
: equal_to_impl<
typename equal_to_tag<N1>::type
, typename equal_to_tag<N2>::type
>::template apply< N1,N2 >::type
{
BOOST_MPL_AUX_LAMBDA_SUPPORT(2, equal_to, (N1, N2))
};
BOOST_MPL_AUX_NA_SPEC2(2, 2, equal_to)
}}
namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace mpl {
template<>
struct equal_to_impl< integral_c_tag,integral_c_tag >
{
template< typename N1, typename N2 > struct apply
{
BOOST_STATIC_CONSTANT(bool, value =
( BOOST_MPL_AUX_VALUE_WKND(N1)::value ==
BOOST_MPL_AUX_VALUE_WKND(N2)::value )
);
typedef bool_<value> type;
};
};
}}
| [
"tony@mobilegridinc.com"
] | tony@mobilegridinc.com |
9afb552dca1af31aa07ebb433ddd2000dea9e3c7 | 1d0e1d37c30665114495fae6032da32e554d961a | /application/src/windowing/imgui_init.h | dda4ecc67e37c0740b09bc0de9b166feedb425fd | [] | no_license | junnys6018/GBC-Emulator | 49be342f5fd93e3d454838ffc92416e7cca3e16e | 1536457ceb9ef9ef4ef35b0923f66fb2f62ab950 | refs/heads/master | 2023-08-03T09:45:58.931200 | 2021-09-11T15:46:42 | 2021-09-11T15:51:10 | 386,638,308 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 265 | h | #pragma once
#include <glad/glad.h>
#include <GLFW/glfw3.h>
namespace app
{
class ImGuiLayer
{
public:
static void initialize(GLFWwindow* window);
static void shutdown();
static void begin();
static void end();
};
} | [
"junkanglim1@gmail.com"
] | junkanglim1@gmail.com |
dbd25fe0c6a1345456692f4fe6ffea579f6789ff | cadcbdd8b8eb5ea02b2139dfcf2221e50fc424e9 | /Source.Arm/Spline.h | d214f60ebb0df80925938bfd39603bd311115ecf | [
"MIT"
] | permissive | sp4cerat/Deformation-Styles-using-Spline-Skinning | b79b8112ef6bff60a2724e5f03b0d21e7df6344d | 2e9e9b5b0629cdad91d335434e1f4fb54a48a0a2 | refs/heads/master | 2021-01-10T21:04:48.079480 | 2015-08-02T12:04:27 | 2015-08-02T12:04:27 | 40,077,871 | 14 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 11,230 | h | // ---------------------------------------- //
class SplineTex{public:
int width,height;
float *data_nbtpx;
float *data_nbtpy;
float *data_nbtpz;
float *data_params;
int num_params;
int handle_params;
int handle_pose;
int handle_nbtpx;
int handle_nbtpy;
int handle_nbtpz;
int handle_b;
int handle_nbtpx_out;
int handle_nbtpy_out;
int handle_nbtpz_out;
int handle_nbtpx_out2;
int handle_nbtpy_out2;
int handle_nbtpz_out2;
void update_params()
{
if (handle_params==-1)
{
handle_params = GFX::NewFloatRectTex(num_params,height,(char*)data_params,true);
}
else
{
GLuint type = GL_TEXTURE_RECTANGLE_ARB;
glBindTexture(type,handle_params);GFX::get_error();
glTexSubImage2D(type,0,0,0,num_params,height,GL_RGBA,GL_FLOAT,data_params);
GFX::get_error();
glBindTexture(type,0);
}
}
};
// ---------------------------------------- //
class Spline { public:
vec3f p1,p2,p3;
vec3f d1,d2;
vec3f normal;
float angle , twist ;
float center_distort;
vec3f d1_before,d2_after;
vec3f result_pos;
vec3f result_normal;
vec3f result_tan;
vec3f result_cotan;
vec3f bind_normal;
vec3f bind_normal_cmp;
float bind_angle;
matrix44 result_matrix;
matrix44 spline_space;
matrix44 spline_space_inv;
matrix44 spline_space_inv_parent;
matrix44 spline_m0, spline_m0_inv;
matrix44 spline_m1, spline_m1_inv;
matrix44 spline_m1_init, spline_m1_init_inv;
matrix44 spline_xform;
void set ( vec3f p1_in,vec3f p2_in,vec3f p3_in, float angle=0, float twist=0, matrix44& parent=matrix44() )
{
//center_distort = 0;
/*
this->p1 = p1_in;
this->p2 = p2_in;
this->p3 = p3_in;
d1 = p2 - p1;
d2 = p3 - p2;
vec3f d1n = d1; d1n.normalize();
vec3f d2n = d2; d2n.normalize();
vec3f delta = d2n-d1n;
if ( delta.length() > 0.001 )
{
normal.cross(d1,d2);
}
else
{
if ( (d1-vec3f(1,1,1)).length() > 0.001 )
normal.cross( d1, vec3f(1,1,1) );
else
normal.cross( d1, vec3f(0,0,1) );
}
bind_normal_cmp = vec3f::normalize ( normal );
*/
vector3 pp1 = parent * vector3( p1_in.x,p1_in.y,p1_in.z);
vector3 pp2 = parent * vector3( p2_in.x,p2_in.y,p2_in.z);
vector3 pp3 = parent * vector3( p3_in.x,p3_in.y,p3_in.z);
vec3f p1(pp1.x,pp1.y,pp1.z);
vec3f p2(pp2.x,pp2.y,pp2.z);
vec3f p3(pp3.x,pp3.y,pp3.z);
this->p1 = p1;
this->p2 = p2;
this->p3 = p3;
this->angle = angle;
this->twist = twist;
d1 = p2 - p1;
d2 = p3 - p2;
vec3f d1n = d1; d1n.normalize();
vec3f d2n = d2; d2n.normalize();
vec3f delta = d2n-d1n;
float len_d1_d2 = d1.length()+d2.length();
d1_before = d1n * len_d1_d2;
d2_after = d2n * len_d1_d2;
if ( delta.length() > 0.001 )
{
normal.cross(d1,d2);
}
else
{
if ( (d1-vec3f(1,1,1)).length() > 0.001 )
normal.cross( d1, vec3f(1,1,1) );
else
normal.cross( d1, vec3f(0,0,1) );
}
result_normal = normal = vec3f::normalize (normal);
vec3f bnc = result_normal + p1;
matrix44 parent_inv = parent; parent_inv.invert();
vector3 nn = parent_inv * vector3( bnc.x,bnc.y,bnc.z);
bind_normal_cmp = vec3f::normalize ( vec3f(nn.x,nn.y,nn.z) - p1_in );
bind_angle = bind_normal.angle2( bind_normal_cmp , p2_in-p1_in );
get_at(0);
spline_space = result_matrix;
delta = d1n * (d1.length()+d2.length());
spline_space.m[2][0] = delta.x;
spline_space.m[2][1] = delta.y;
spline_space.m[2][2] = delta.z;
spline_m0 = result_matrix;
spline_m1_init = result_matrix;
spline_m1_init.m[3][0] = p1.x+delta.x;
spline_m1_init.m[3][1] = p1.y+delta.y;
spline_m1_init.m[3][2] = p1.z+delta.z;
get_at(1);
spline_m1 = result_matrix;
spline_m0_inv = spline_m0 ; spline_m0_inv.invert();
spline_m1_inv = spline_m1 ; spline_m1_inv.invert();
spline_m1_init_inv = spline_m1_init; spline_m1_init_inv.invert();
spline_space_inv = spline_space ; spline_space_inv.invert();
// Transform Matrix of the spline
spline_xform = spline_m1_init_inv * spline_m1;
// Transform from World to Spline-space
spline_space_inv_parent = parent * spline_space_inv;
}
void get_at ( float a , bool rotate=true)
{
if (a>1) a=1;
if (a<0) a=0;
float p=float(this->spline_hardness);//GFX::mouseY*5);
float powa=pow(float(a),float(p));
float pow1a=pow(float(1-a),float(p));
float cos_a = a*powa;//cos ( 0.5f * M_PI * a );
float sin_a = 1-(1-a)*pow1a;//sin ( 0.5f * M_PI * a );
float cos_da = powa;//cos ( 0.5f * M_PI * a );
float sin_da = pow1a;//sin ( 0.5f * M_PI * a );
result_pos = p1 + d1 * sin_a + d2 * cos_a;
result_tan = (d1 * sin_da + d2 * cos_da).normalize();
result_cotan.cross( result_tan,result_normal);
//result_cotan = (d1 * sin_a + d2 * cos_a).normalize();
matrix44 m;
m.m[0][0] = result_normal.x;
m.m[0][1] = result_normal.y;
m.m[0][2] = result_normal.z;
m.m[0][3] = 0;
m.m[1][0] = result_cotan.x;
m.m[1][1] = result_cotan.y;
m.m[1][2] = result_cotan.z;
m.m[1][3] = 0;
m.m[2][0] = result_tan.x;
m.m[2][1] = result_tan.y;
m.m[2][2] = result_tan.z;
m.m[2][3] = 0;
m.m[3][0] = result_pos.x;
m.m[3][1] = result_pos.y;
m.m[3][2] = result_pos.z;
m.m[3][3] = 1;
if(rotate)
{
matrix44 r;
r.ident();
r.rotate_z(angle+twist*a);//-bind_angle+
result_matrix = r*m;
}
else
{
result_matrix = m;
}
result_normal.x = result_matrix.m[0][0];
result_normal.y = result_matrix.m[0][1];
result_normal.z = result_matrix.m[0][2];
result_cotan.x = result_matrix.m[1][0];
result_cotan.y = result_matrix.m[1][1];
result_cotan.z = result_matrix.m[1][2];
}
void draw()
{
GFX::SetTex ( 0 );
// GFX::Line ( p1, p2 , vec3f (1,1,1) );
// GFX::Line ( p2, p3 , vec3f (1,1,1) );
//center_distort = 1;
get_at(0);
vec3f distort = this->result_cotan * center_distort;
vec3f pp1 = p1 + distort;
vec3f pp3 = p3 + distort;
glPushMatrix();
glColor3f(0,0,0);
glTranslatef(pp1.x,pp1.y,pp1.z);
glutSolidSphere(0.1,7,7);
glPopMatrix();
glPushMatrix();
glTranslatef(pp3.x,pp3.y,pp3.z);
glutSolidSphere(0.1,7,7);
glPopMatrix();
int segments = 10;
static vec3f result_pos_old;
for ( int i = 0 ; i <= segments ; i++)
{
float a = float(i)/float(segments);
result_pos_old = result_pos+distort;
get_at ( a , true);
if (i>0)
GFX::Line (
result_pos_old,
result_pos+distort,
vec3f (0,0,0) );
/*
GFX::Line (
result_pos ,
result_pos + result_normal*0.3,
vec3f (1,0,0) );
GFX::Line (
result_pos ,
result_pos + result_cotan*0.3,
vec3f (0,0,1) );
*/
}
}
// one line = one spline
void sample_mats(matrix44 *m,int num)
{
for(int a = 0;a<num;a++)
{
this->get_at(float(a)/float(num-1),false);
m[a]=this->result_matrix;
m[a].invert_simpler();
}
}
int deformation_style;
float spline_hardness;
float spline_twist_adjust;
void set_style(int i)
{
deformation_style = i;
}
void set_hardness(float f)
{
spline_hardness = f;
}
void set_twist_adjust(float f)
{
spline_twist_adjust = f;
}
void set_params_to_tex(SplineTex &tex, int y)
{
int ofs = y*tex.num_params*4; // 5 params, 4 floats per param
tex.data_params[ofs++] = p1.x;
tex.data_params[ofs++] = p1.y;
tex.data_params[ofs++] = p1.z;
tex.data_params[ofs++] = angle-bind_angle;
//printf("an:%3.3f %3.3f\n",angle,bind_angle);
tex.data_params[ofs++] = d1.x;
tex.data_params[ofs++] = d1.y;
tex.data_params[ofs++] = d1.z;
tex.data_params[ofs++] = twist;
tex.data_params[ofs++] = d2.x;
tex.data_params[ofs++] = d2.y;
tex.data_params[ofs++] = d2.z;
tex.data_params[ofs++] = -sin(angle-bind_angle);
tex.data_params[ofs++] = normal.x;
tex.data_params[ofs++] = normal.y;
tex.data_params[ofs++] = normal.z;
tex.data_params[ofs++] = -cos(angle-bind_angle);
get_at(0,true);
matrix44 r;
r.ident();
r.rotate_z(bind_angle);//-bind_angle+
r = result_matrix;
float angle = 2*(d1.angle(d2) / M_PI); angle = angle;
tex.data_params[ofs++] = r.m[1][0];//result_cotan.x;
tex.data_params[ofs++] = r.m[1][1];//result_cotan.y;
tex.data_params[ofs++] = r.m[1][2];//result_cotan.z;
tex.data_params[ofs++] = ( angle > 1 ) ? 1 : angle ;
this->center_distort = 0.0;//006;
tex.data_params[ofs++] = deformation_style;//
tex.data_params[ofs++] = spline_hardness;
tex.data_params[ofs++] = spline_twist_adjust;
tex.data_params[ofs++] = center_distort ;// center distort
}
void sample(SplineTex &tex, int y,matrix44 *mats=NULL)
{
GFX::mouseY = 0;
for(int a = 0;a<tex.width;a++)
{
float a01 = float(a)/float(tex.width-1);
int ofs = (a + y * tex.width)*4;
this->get_at(a01,false);
matrix44 m = this->result_matrix;
matrix44 r;
r.rotate_z((-bind_angle+angle+twist*a01));
if (mats) m = mats[a]*r*m;
else
{
m.invert_simpler();
}
for (int i=0;i<3;i++)
for (int j=0;j<3;j++)
{
if ( m.m[i][j] < -1 ) m.m[i][j] = -1;
if ( m.m[i][j] > 1 ) m.m[i][j] = 1;
}
float scale =256;
tex.data_nbtpx[ofs+0] = m.m[0][0];//*scale;
tex.data_nbtpx[ofs+1] = m.m[1][0];//*scale;
tex.data_nbtpx[ofs+2] = m.m[2][0];//*scale;
tex.data_nbtpx[ofs+3] = m.m[3][0];//*scale;
tex.data_nbtpy[ofs+0] = m.m[0][1];//*scale;
tex.data_nbtpy[ofs+1] = m.m[1][1];//*scale;
tex.data_nbtpy[ofs+2] = m.m[2][1];//*scale;
tex.data_nbtpy[ofs+3] = m.m[3][1];//*scale;
tex.data_nbtpz[ofs+0] = m.m[0][2];//*scale;
tex.data_nbtpz[ofs+1] = m.m[1][2];//*scale;
tex.data_nbtpz[ofs+2] = m.m[2][2];//*scale;
tex.data_nbtpz[ofs+3] = m.m[3][2];//*scale;
}
set_params_to_tex( tex, y);
}
float get_offset_result_angle;
float get_offset_result_distance;
float get_lin_offset()
{
float a = (result_pos-p1).length() / (p3-p1).length();
if (a>1)return 1;
if (a<0)return 0;
return a;
}
float get_offset(vec3f pos, float a = 0.5f, float add_a=0.25f)
{
if(add_a<0.001)
{
matrix44 res_inv = result_matrix; res_inv.invert_simpler();
vec3f inplane = res_inv * vector3 (pos.x,pos.y,pos.z);
get_offset_result_angle =
0.75+0.5+atan2(inplane.y,inplane.x)/(2*M_PI);
if(get_offset_result_angle > 1 ) get_offset_result_angle-=1.0f;
float border = 1.0/128.0 ;
get_offset_result_angle = get_offset_result_angle * (1.0-2*border)+border;
if(get_offset_result_angle<border)
{
get_offset_result_angle = border;
get_offset_result_distance = 0;
}
if(get_offset_result_angle>1-border)
{
get_offset_result_angle = 1-border;
get_offset_result_distance = 0;
}
return a;
}
GFX::mouseY = 0;
if (add_a==0.25f/2)
{
this->get_at(0,false);
vec3f w( pos.x-result_pos.x,
pos.y-result_pos.y,
pos.z-result_pos.z);
float d = w.dot(this->result_tan);
if (d<0) return 0;
this->get_at(1,false);
w = vec3f( pos.x-result_pos.x,
pos.y-result_pos.y,
pos.z-result_pos.z);
d = w.dot(this->result_tan);
if (d>0) return 1;
// return 0.5;
}
this->get_at(a,false);
vec3f w( pos.x-result_pos.x,
pos.y-result_pos.y,
pos.z-result_pos.z);
float d = w.dot(this->result_tan);
if (d>0)
return get_offset(pos,a+add_a,add_a/2);
else
return get_offset(pos,a-add_a,add_a/2);
}
};//class spline
// ---------------------------------------- //
| [
"sternentraeumer@gmail.com"
] | sternentraeumer@gmail.com |
a2b314687c88b744ee1a6fa29b43d54a9caf07d6 | 4940030ffff9cf98608ac7af3380d4b76597f8d3 | /src/qt/openuridialog.cpp | 77925b8db2d8546619d0f3be5b949cd0ec60af6b | [
"MIT"
] | permissive | herbsters/herbsters | a78f5dc969f3efc69e58ce535b548773cdeec815 | 51d6997794d7a0ff5eaec6e649cb661e8acc5194 | refs/heads/master | 2023-06-08T14:34:40.412743 | 2023-06-04T23:42:56 | 2023-06-04T23:42:56 | 275,106,857 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,241 | cpp | // Copyright (c) 2011-2014 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 "openuridialog.h"
#include "ui_openuridialog.h"
#include "guiutil.h"
#include "walletmodel.h"
#include <QUrl>
OpenURIDialog::OpenURIDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OpenURIDialog)
{
ui->setupUi(this);
#if QT_VERSION >= 0x040700
ui->uriEdit->setPlaceholderText("herbsters:");
#endif
}
OpenURIDialog::~OpenURIDialog()
{
delete ui;
}
QString OpenURIDialog::getURI()
{
return ui->uriEdit->text();
}
void OpenURIDialog::accept()
{
SendCoinsRecipient rcp;
if(GUIUtil::parseherbstersURI(getURI(), &rcp))
{
/* Only accept value URIs */
QDialog::accept();
} else {
ui->uriEdit->setValid(false);
}
}
void OpenURIDialog::on_selectFileButton_clicked()
{
QString filename = GUIUtil::getOpenFileName(this, tr("Select payment request file to open"), "", "", nullptr);
if(filename.isEmpty())
return;
QUrl fileUri = QUrl::fromLocalFile(filename);
ui->uriEdit->setText("herbsters:?r=" + QUrl::toPercentEncoding(fileUri.toString()));
}
| [
"support@herbsters.com"
] | support@herbsters.com |
ad12860afdfe65890e4c29efbecd651de518c7d2 | 1a77b5eac40055032b72e27e720ac5d43451bbd6 | /フォーム対応/VisualC++/CLR/Chap7/Dr53/Dr53/stdafx.cpp | ddd0c48987e2714b99229a4c41e40fcd530a094d | [] | no_license | motonobu-t/algorithm | 8c8d360ebb982a0262069bb968022fe79f2c84c2 | ca7b29d53860eb06a357eb268f44f47ec9cb63f7 | refs/heads/master | 2021-01-22T21:38:34.195001 | 2017-05-15T12:00:51 | 2017-05-15T12:01:00 | 85,451,237 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 256 | cpp | // stdafx.cpp : 標準インクルード Dr53.pch のみを
// 含むソース ファイルは、プリコンパイル済みヘッダーになります。
// stdafx.obj にはプリコンパイル済み型情報が含まれます。
#include "stdafx.h"
| [
"rx_78_bd@yahoo.co.jp"
] | rx_78_bd@yahoo.co.jp |
6507149811560024cea44968f51dc431f68793a5 | 92e5c8e8f6638676af8d14c30598abe97256e3e0 | /code/cpp/climbing-stairs.cc | 7d7515d72dfc0399d05c5abf9b538a175fccf48f | [
"MIT"
] | permissive | soumyarooproy/leetcode_solutions | 4abcd357fb94b2d7ab4cf63a250df6ebb49c01d2 | 0e565cc137dea74c4f72bdcc8108bc11a298f409 | refs/heads/master | 2021-03-19T18:11:26.818247 | 2018-04-13T20:15:01 | 2018-04-13T20:15:01 | 101,521,994 | 0 | 0 | null | 2017-09-17T19:11:02 | 2017-08-27T01:01:57 | C++ | UTF-8 | C++ | false | false | 691 | cc | // TLE, 09/09/2017
// Time : O(n^n)
// Space : O(1)
// TODO : Recursive approach below, improve using memoization (same as Fibonacci)
class Solution {
public:
int climbStairs(int n)
{
return (n < 3) ? n : climbStairs(n - 1) + climbStairs(n - 2);
}
};
/*--------------------------------------------------------------------------*/
// 0 ms, 09/09/2017
// Time : O(n)
// Space : O(1)
// Bottom-up
class Solution {
public:
int climbStairs(int n)
{
if (n < 2)
return 1;
int c1 = 1, c2 = 2;
for (int i = 3; i <= n; ++i) {
int c = c1 + c2;
c1 = c2;
c2 = c;
}
return c2;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
d938b53a30e77a20c61200f40ab1bfd1c51b9ec7 | 75452de12ec9eea346e3b9c7789ac0abf3eb1d73 | /sdk/lib/ui/scenic/cpp/tests/session_test.cc | 2080756900da0253bf2cdf6be85327f82a2bae0e | [
"BSD-3-Clause"
] | permissive | oshunter/fuchsia | c9285cc8c14be067b80246e701434bbef4d606d1 | 2196fc8c176d01969466b97bba3f31ec55f7767b | refs/heads/master | 2022-12-22T11:30:15.486382 | 2020-08-16T03:41:23 | 2020-08-16T03:41:23 | 287,920,017 | 2 | 2 | BSD-3-Clause | 2022-12-16T03:30:27 | 2020-08-16T10:18:30 | C++ | UTF-8 | C++ | false | false | 6,544 | cc | // Copyright 2020 The Fuchsia 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 "sdk/lib/ui/scenic/cpp/session.h"
#include <lib/gtest/test_loop_fixture.h>
#include <lib/zx/channel.h>
#include <zircon/types.h>
#include <gtest/gtest.h>
#include "lib/ui/scenic/cpp/commands.h"
namespace {
class MockScenicSession : public scenic::Session {
public:
MockScenicSession(fuchsia::ui::scenic::SessionPtr client) : Session(std::move(client)) {}
void Flush() override {
num_flushed_++;
commands_.clear();
};
int64_t num_flushed_ = 0;
size_t num_commands() { return commands_.size(); }
int64_t num_bytes() { return commands_num_bytes_; }
int64_t num_handles() { return commands_num_handles_; }
};
class ScenicSessionFlushTest : public ::gtest::TestLoopFixture {
public:
ScenicSessionFlushTest() = default;
~ScenicSessionFlushTest() override = default;
std::unique_ptr<MockScenicSession> session_;
protected:
void SetUp() override {
zx::channel client_end, server_end;
zx::channel::create(0, &client_end, &server_end);
fuchsia::ui::scenic::SessionPtr client;
client.Bind(std::move(client_end));
session_ = std::make_unique<MockScenicSession>(std::move(client));
}
void TearDown() override { session_.reset(); }
};
TEST_F(ScenicSessionFlushTest, AddOneInputCommand) {
fuchsia::ui::input::SendPointerInputCmd send_pointer_input_cmd;
fuchsia::ui::input::Command input_cmd;
input_cmd.set_send_pointer_input(send_pointer_input_cmd);
fuchsia::ui::scenic::Command cmd;
cmd.set_input(std::move(input_cmd));
session_->Enqueue(std::move(cmd));
EXPECT_EQ(session_->num_flushed_, 1);
EXPECT_EQ(session_->num_commands(), 0u);
EXPECT_EQ(session_->num_bytes(),
// See commands_sizing_test.cc for details.
scenic::kEnqueueRequestBaseNumBytes + 104u);
EXPECT_EQ(session_->num_handles(),
// See commands_sizing_test.cc for details.
0u);
}
TEST_F(ScenicSessionFlushTest, AddTwoInputCommands) {
for (int64_t i = 0; i < 2; ++i) {
fuchsia::ui::input::SendPointerInputCmd send_pointer_input_cmd;
fuchsia::ui::input::Command input_cmd;
input_cmd.set_send_pointer_input(send_pointer_input_cmd);
fuchsia::ui::scenic::Command cmd;
cmd.set_input(std::move(input_cmd));
session_->Enqueue(std::move(cmd));
}
EXPECT_EQ(session_->num_flushed_, 2);
EXPECT_EQ(session_->num_commands(), 0u);
// The overriden Flush does not reset byte and handle counts, so we accumulate each
// command's size.
EXPECT_EQ(session_->num_bytes(),
// See commands_sizing_test.cc for details.
scenic::kEnqueueRequestBaseNumBytes + 2 * 104u);
EXPECT_EQ(session_->num_handles(),
// See commands_sizing_test.cc for details.
0u);
}
TEST_F(ScenicSessionFlushTest, AddTenNonInputCommandsThenOneInputCommand) {
for (int64_t i = 0; i < 10; ++i) {
fuchsia::ui::gfx::MemoryArgs memory_args;
fuchsia::ui::gfx::ResourceArgs resource_args;
resource_args.set_memory(std::move(memory_args));
fuchsia::ui::gfx::CreateResourceCmd create_resource_cmd;
create_resource_cmd.resource = std::move(resource_args);
fuchsia::ui::gfx::Command gfx_cmd;
gfx_cmd.set_create_resource(std::move(create_resource_cmd));
fuchsia::ui::scenic::Command cmd;
cmd.set_gfx(std::move(gfx_cmd));
session_->Enqueue(std::move(cmd));
}
// We accumulate all commands (without ever flushing).
EXPECT_EQ(session_->num_flushed_, 0u);
EXPECT_EQ(session_->num_commands(), 10u);
EXPECT_EQ(session_->num_bytes(),
// See commands_sizing_test.cc for details.
scenic::kEnqueueRequestBaseNumBytes + 10 * 104u);
EXPECT_EQ(session_->num_handles(),
// See commands_sizing_test.cc for details.
10 * 1u);
{
fuchsia::ui::input::SendPointerInputCmd send_pointer_input_cmd;
fuchsia::ui::input::Command input_cmd;
input_cmd.set_send_pointer_input(send_pointer_input_cmd);
fuchsia::ui::scenic::Command cmd;
cmd.set_input(std::move(input_cmd));
session_->Enqueue(std::move(cmd));
}
// Since input commands are eagerly flushed, we send all eleven commands at
// once.
EXPECT_EQ(session_->num_flushed_, 1u);
EXPECT_EQ(session_->num_commands(), 0u);
EXPECT_EQ(session_->num_bytes(),
// See commands_sizing_test.cc for details.
scenic::kEnqueueRequestBaseNumBytes + 11 * 104u);
EXPECT_EQ(session_->num_handles(),
// See commands_sizing_test.cc for details.
10 * 1u);
}
TEST_F(ScenicSessionFlushTest, AddNonInputCommandThenPresent) {
// Enqueue CreateResourceCmd
{
fuchsia::ui::gfx::MemoryArgs memory_args;
fuchsia::ui::gfx::ResourceArgs resource_args;
resource_args.set_memory(std::move(memory_args));
fuchsia::ui::gfx::CreateResourceCmd create_resource_cmd;
create_resource_cmd.resource = std::move(resource_args);
fuchsia::ui::gfx::Command gfx_cmd;
gfx_cmd.set_create_resource(std::move(create_resource_cmd));
fuchsia::ui::scenic::Command cmd;
cmd.set_gfx(std::move(gfx_cmd));
session_->Enqueue(std::move(cmd));
}
// The enqueued command has not been flushed, but will be when we present.
EXPECT_EQ(session_->num_flushed_, 0);
// Present
auto callback = [&](fuchsia::images::PresentationInfo info) {};
session_->Present(0u, std::move(callback));
// And check that we've flushed.
EXPECT_EQ(session_->num_flushed_, 1);
}
TEST_F(ScenicSessionFlushTest, AddNonInputCommandThenPresent2) {
// Enqueue CreateResourceCmd
{
fuchsia::ui::gfx::MemoryArgs memory_args;
fuchsia::ui::gfx::ResourceArgs resource_args;
resource_args.set_memory(std::move(memory_args));
fuchsia::ui::gfx::CreateResourceCmd create_resource_cmd;
create_resource_cmd.resource = std::move(resource_args);
fuchsia::ui::gfx::Command gfx_cmd;
gfx_cmd.set_create_resource(std::move(create_resource_cmd));
fuchsia::ui::scenic::Command cmd;
cmd.set_gfx(std::move(gfx_cmd));
session_->Enqueue(std::move(cmd));
}
// The enqueued command has not been flushed, but will be when we present.
EXPECT_EQ(session_->num_flushed_, 0);
// Present2
auto callback = [&](fuchsia::scenic::scheduling::FuturePresentationTimes info) {};
session_->Present2(0u, 0u, std::move(callback));
// And check that we've flushed.
EXPECT_EQ(session_->num_flushed_, 1);
}
} // namespace
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
4013fbea40605a932969b09669d980253cacb8dd | c0fabe3f31bee8c626ea141ef7130059fbf9008b | /src/View/Account_UIjiemian.cpp | f45d484da979a6bbf8981a859180e579e976e28c | [] | no_license | wangto/src | 9a8e51ef0615d216242642b62f220d9e3e9a95e4 | 346feefdc359bd39777ad00f7a1c0167beed1198 | refs/heads/master | 2020-06-06T02:13:17.295446 | 2015-07-23T11:35:50 | 2015-07-23T11:35:50 | 39,559,424 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,482 | cpp | /*
* Account_UI.c
*
* Created on: 2015年5月8日
* Author: Administrator
*/
#include "Account_UI.h"
#include "../Common/List.h"
#include "../Service/Account.h"
#include "../Service/EntityKey.h"
#include "Account_UI.h"
/* #include<conio.h>
#include<windows.h> */
#include <stdio.h>
#include<assert.h>
#include<string.h>
#include <unistd.h>
#include <sys/time.h>
void Account_UI_MgtEntry()
int SysLogin();
{
int id,chioce;
char password[30],username[30];
printf("\n=========================================================\n");
printf("\n*********************用 户 登 录*************************\n");
printf("请选择您的登录方式,按0退出。\n");
printf("---------------1、游客登录---------------\n");
printf("---------------2、员工登录---------------\n");
printf("---------------0、退出-------------------\n");
printf("\n*********************************************************\n");
printf("\n=========================================================\n");
scanf("%d",&chioce);
switch(chioce)
{
case 1:
break;
case 2:
{
printf("\n=======================================================\n");
printf("\n*********************信 息 填 写***********************\n");
printf("请输入您的信息:\n");
printf("请输入您的ID:");
scanf("%d",&id);
printf("请输入您的用户名:\n");
scanf("%s",username);
printf("请输入密码:\n");
scanf("%s",password);
printf("\n*******************************************************\n");
printf("\n=======================================================\n");
}
case 0:return;
}
printf("\n");
}
//管理系统用户功能入口函数,显示用户账号管理菜单
void Account_UI_add(account_list_t list )
{
int choice,id;
char password[30],username[30];
printf("\n=========================================================\n");
printf("\n*******************添 加 账 户 信 息*********************\n");
printf("\n请您选择,退出请按0:\n");
printf("------------------------1、信息添加------------------------\n");
printf("------------------------0、退出----------------------------\n");
printf("\n*********************************************************\n");
printf("\n=========================================================\n");
scanf("%d",choice);
switch(choice)
{
case 1:
{
printf("\n=======================================================\n");
printf("\n*******************添 加 账 户 信 息*******************\n");
printf("请输入新添加的信息:\n");
printf("请输入您的ID:\n");
scanf("%d",&id);
printf("请输入新添加的用户名:\n");
scanf("%s",username);
printf("请输入密码:\n");
scanf("%s",password);
printf("\n*******************************************************\n")
printf("\n=======================================================\n");
}
case 0:return;
}
printf("\n");
}
//添加一个用户账号信息
int Account_UI_Modify(account_list_t list )
{
int choice,id;
char password[30],username[30],newpassword[30];
printf("\n=========================================================\n");
printf("\n*******************修 改 账 户 密 码*********************\n");
printf("\n请您选择,退出请按0:\n");
printf("------------------------1、密码修改------------------------\n");
printf("------------------------0、退出----------------------------\n");
printf("\n*********************************************************\n");
printf("\n=========================================================\n");
scanf("%d",choice);
switch(choice)
{
case 1:
{
printf("\n=========================================================\n");
printf("\n*******************修 改 账 户 密 码*********************\n");
printf("请输入您的信息:\n");
printf("请输入您的ID:");
scanf("%d",&id);
printf("请输入您的用户名:\n");
scanf("%s",username);
printf("请输入旧密码:\n");
scanf("%s",password);
printf("请输入新密码:\n");
scanf("%s",newpassword);
printf("\n*******************************************************\n");
printf("\n=======================================================\n");
}
case 0:return;
}
printf("\n");
}
//根据用户账号名修改用户账号密码,不存在这个用户账号名,提示出错信息
int Account_UI_Delete(account_list_t list ,char usrName[])
{
int choice,id;
printf("\n=========================================================\n");
printf("\n*********************账 户 删 除*************************\n");
printf("\n请您选择,退出请按0:\n");
printf("------------------------1、账户删除------------------------\n");
printf("------------------------0、退出----------------------------\n");
printf("\n*********************************************************\n");
printf("\n=========================================================\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
printf("\n=========================================================\n");
printf("\n**********************账 户 删 除************************\n");
printf("请输入您的信息:\n");
printf("请输入您的ID:");
scanf("%d",&id);
{
if(组长我觉得这里要调用一些我不知道的东西,所以你自己来)
printf("账户信息错误!!");
else
printf("删除成功");
}
printf("\n*******************************************************\n");
printf("\n=======================================================\n");
}
case 0:return;
}
printf("\n");
}
//根据用户账号名删除一个已经存在的用户账号信息,如果不存在这个用户账号名,提示出错信息
int Account_UI_Query(account_list_t list ,char usrName[])
{
int choice;
char username[30];
printf("\n=========================================================\n");
printf("\n*********************账 户 查 找*************************\n");
printf("\n请您选择,退出请按0:\n");
printf("\n----------------------1、账户查找------------------------\n");
printf("\n----------------------0、退出----------------------------\n");
printf("\n*********************************************************\n");
printf("\n=========================================================\n");
scanf("%d",choice);
switch(choice)
{
case 1:
{
printf("\n=========================================================\n");
printf("\n*********************账 户 查 找*************************\n");
printf("请输入您的用户名:\n");
scanf("%s",username);
printf("组长这里貌似也是调用、、、、、")
printf("\n*********************************************************\n");
printf("\n=========================================================\n");
}
case 0:return;
}
printf("\n");
}
//根据用户账号名查找该用户账号是否存在,存在返回1,否则返回0,并提示错误信息
| [
"wangtong19951128@qq.com"
] | wangtong19951128@qq.com |
03128e1ba04161b0aeb8680aa90f0e89e5ece537 | 78f67ed8f1d48907584e4215d944296b2f973588 | /221.maximal-square.cpp | 02cc042df62a90d6594f520d3c3155980af03c39 | [] | no_license | Beniko95J/leetcode_new | c2882efe2c8cb9d18bcbde3468d32b92cfc57002 | 784f9584bc201074d0f0db8dfee782b625070baa | refs/heads/master | 2020-11-30T18:10:04.864868 | 2020-03-07T05:58:08 | 2020-03-07T05:58:08 | 230,452,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 846 | cpp | /*
* @lc app=leetcode id=221 lang=cpp
*
* [221] Maximal Square
*/
// @lc code=start
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if (matrix.size() == 0 || matrix.at(0).size() == 0) return 0;
int dp[matrix.size()][matrix.at(0).size()];
int res = 0;
for (size_t i = 0; i < matrix.size(); i++) {
for (size_t j = 0; j < matrix.at(0).size(); j++) {
if (i == 0 || j == 0) dp[i][j] = matrix.at(i).at(j) - '0';
else {
dp[i][j] = matrix.at(i).at(j) == '1' ? min({dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]}) + 1 : 0;
}
res = max(res, dp[i][j]);
}
}
return res * res;
}
};
// @lc code=end
| [
"benik@LAPTOP-E48R6A5C.localdomain"
] | benik@LAPTOP-E48R6A5C.localdomain |
87d2b5b272f9381774771eb3256bd437e6ab443e | b278327780b8f44e28e38ce2fa00d199245debc5 | /src/cflie/CCRTPPacket.cpp | 51eab95285cd0ddf0268212cc89d5d5b41cbd9b4 | [
"BSD-3-Clause"
] | permissive | xabre/libcflie | 91f37b3ec18c063ce074467580605d5a42bec548 | 5baaa2d4fbed87ab12a9470e1e0048dd860b65b1 | refs/heads/master | 2020-12-29T00:55:31.269264 | 2013-11-15T22:58:40 | 2013-11-15T22:58:40 | 15,871,914 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,584 | cpp | // Copyright (c) 2013, Jan Winkler <winkler@cs.uni-bremen.de>
// 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 Universität Bremen nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "cflie/CCRTPPacket.h"
CCRTPPacket::CCRTPPacket(int nPort) {
this->basicSetup();
this->setPort(nPort);
}
CCRTPPacket::CCRTPPacket(char *cData, int nDataLength, int nPort) {
this->basicSetup();
this->setPort(nPort);
this->setData(cData, nDataLength);
}
CCRTPPacket::CCRTPPacket(char cData, int nPort) {
this->basicSetup();
this->setPort(nPort);
this->setData(&cData, 1);
}
CCRTPPacket::~CCRTPPacket() {
this->clearData();
}
void CCRTPPacket::basicSetup() {
m_cData = NULL;
m_nDataLength = 0;
m_nPort = 0;
m_nChannel = 0;
m_bIsPingPacket = false;
}
void CCRTPPacket::setData(char *cData, int nDataLength) {
this->clearData();
m_cData = new char[nDataLength]();
memcpy(m_cData, cData, nDataLength);
m_nDataLength = nDataLength;
}
char *CCRTPPacket::data() {
return m_cData;
}
int CCRTPPacket::dataLength() {
return m_nDataLength;
}
void CCRTPPacket::clearData() {
if(m_cData != NULL) {
delete[] m_cData;
m_cData = NULL;
m_nDataLength = 0;
}
}
char *CCRTPPacket::sendableData() {
char *cSendable = new char[this->sendableDataLength()]();
if(m_bIsPingPacket) {
cSendable[0] = 0xff;
} else {
// Header byte
cSendable[0] = (m_nPort << 4) | 0b00001100 | (m_nChannel & 0x03);
// Payload
memcpy(&cSendable[1], m_cData, m_nDataLength);
// Finishing byte
//cSendable[m_nDataLength + 1] = 0x27;
}
return cSendable;
}
int CCRTPPacket::sendableDataLength() {
if(m_bIsPingPacket) {
return 1;
} else {
return m_nDataLength + 1;//2;
}
}
void CCRTPPacket::setPort(int nPort) {
m_nPort = nPort;
}
int CCRTPPacket::port() {
return m_nPort;
}
void CCRTPPacket::setChannel(int nChannel) {
m_nChannel = nChannel;
}
int CCRTPPacket::channel() {
return m_nChannel;
}
void CCRTPPacket::setIsPingPacket(bool bIsPingPacket) {
m_bIsPingPacket = bIsPingPacket;
}
bool CCRTPPacket::isPingPacket() {
return m_bIsPingPacket;
}
| [
"winkler@cs.uni-bremen.de"
] | winkler@cs.uni-bremen.de |
f48897665d4e8ceb2a06f372c67dc655c546f684 | 1c546675bc1ccb5bafda94975f5c9491805dc73a | /poc/maven-resolver-cpp/src/MavenVersionResult.h | 30258e21fbeffb7abb57f64a5d56f1b18b632192 | [] | no_license | Jean-Emile/kevoree-IoT | db05f7ed14d6916d7b0e26700c01691a2c167996 | 3b4177ea01dc07f19c3195309ffed53d066e9f76 | refs/heads/master | 2016-09-05T18:07:14.309159 | 2013-10-18T12:59:34 | 2013-10-18T12:59:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 631 | h | #ifndef MAVENVERSIONRESULT_H_
#define MAVENVERSIONRESULT_H_
#include <string>
class MavenVersionResult
{
public:
MavenVersionResult();
virtual ~MavenVersionResult();
std::string getLastUpdate();
void setLastUpdate(std::string lastUpdate);
std::string getValue();
void setValue(std::string value);
std::string getUrl_origin();
void setUrl_origin(std::string url_origin);
bool isNotDeployed();
void setNotDeployed(bool notDeployed);
bool isPrior(MavenVersionResult remote);
private:
std::string value;
std::string lastUpdate;
std::string url_origin;
bool notDeployed ;
};
#endif /*MAVENVERSIONRESULT_H_*/
| [
"jedartois@gmail.com"
] | jedartois@gmail.com |
284e2da22b9be39c3ba40674e6c1e568cc679f94 | c2d270aff0a4d939f43b6359ac2c564b2565be76 | /src/chrome/browser/chromeos/file_manager/file_tasks.cc | db496b3cf3f40d59715c495f52c4211e3d7b5ee9 | [
"BSD-3-Clause"
] | permissive | bopopescu/QuicDep | dfa5c2b6aa29eb6f52b12486ff7f3757c808808d | bc86b705a6cf02d2eade4f3ea8cf5fe73ef52aa0 | refs/heads/master | 2022-04-26T04:36:55.675836 | 2020-04-29T21:29:26 | 2020-04-29T21:29:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,016 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/file_manager/file_tasks.h"
#include <stddef.h>
#include <map>
#include "apps/launcher.h"
#include "base/bind.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/chromeos/drive/file_task_executor.h"
#include "chrome/browser/chromeos/file_manager/app_id.h"
#include "chrome/browser/chromeos/file_manager/arc_file_tasks.h"
#include "chrome/browser/chromeos/file_manager/file_browser_handlers.h"
#include "chrome/browser/chromeos/file_manager/fileapi_util.h"
#include "chrome/browser/chromeos/file_manager/open_util.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/extensions/application_launch.h"
#include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
#include "chrome/common/extensions/api/file_browser_handlers/file_browser_handler.h"
#include "chrome/common/extensions/api/file_manager_private.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/pref_names.h"
#include "chromeos/chromeos_switches.h"
#include "components/drive/drive_api_util.h"
#include "components/drive/drive_app_registry.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "extensions/browser/api/file_handlers/mime_util.h"
#include "extensions/browser/entry_info.h"
#include "extensions/browser/extension_host.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extension_util.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension_set.h"
#include "storage/browser/fileapi/file_system_url.h"
#include "third_party/WebKit/common/mime_util/mime_util.h"
using extensions::Extension;
using extensions::api::file_manager_private::Verb;
using extensions::app_file_handler_util::FindFileHandlersForEntries;
using storage::FileSystemURL;
namespace file_manager {
namespace file_tasks {
namespace {
// The values "file" and "app" are confusing, but cannot be changed easily as
// these are used in default task IDs stored in preferences.
const char kFileBrowserHandlerTaskType[] = "file";
const char kFileHandlerTaskType[] = "app";
const char kDriveAppTaskType[] = "drive";
const char kArcAppTaskType[] = "arc";
// Drive apps always use the action ID.
const char kDriveAppActionID[] = "open-with";
// Converts a TaskType to a string.
std::string TaskTypeToString(TaskType task_type) {
switch (task_type) {
case TASK_TYPE_FILE_BROWSER_HANDLER:
return kFileBrowserHandlerTaskType;
case TASK_TYPE_FILE_HANDLER:
return kFileHandlerTaskType;
case TASK_TYPE_DRIVE_APP:
return kDriveAppTaskType;
case TASK_TYPE_ARC_APP:
return kArcAppTaskType;
case TASK_TYPE_UNKNOWN:
case NUM_TASK_TYPE:
break;
}
NOTREACHED();
return "";
}
// Converts a string to a TaskType. Returns TASK_TYPE_UNKNOWN on error.
TaskType StringToTaskType(const std::string& str) {
if (str == kFileBrowserHandlerTaskType)
return TASK_TYPE_FILE_BROWSER_HANDLER;
if (str == kFileHandlerTaskType)
return TASK_TYPE_FILE_HANDLER;
if (str == kDriveAppTaskType)
return TASK_TYPE_DRIVE_APP;
if (str == kArcAppTaskType)
return TASK_TYPE_ARC_APP;
return TASK_TYPE_UNKNOWN;
}
// Legacy Drive task extension prefix, used by CrackTaskID.
const char kDriveTaskExtensionPrefix[] = "drive-app:";
const size_t kDriveTaskExtensionPrefixLength =
arraysize(kDriveTaskExtensionPrefix) - 1;
// Returns true if path_mime_set contains a Google document.
bool ContainsGoogleDocument(const std::vector<extensions::EntryInfo>& entries) {
for (const auto& it : entries) {
if (drive::util::HasHostedDocumentExtension(it.path))
return true;
}
return false;
}
// Leaves tasks handled by the file manger itself as is and removes all others.
void KeepOnlyFileManagerInternalTasks(std::vector<FullTaskDescriptor>* tasks) {
std::vector<FullTaskDescriptor> filtered;
for (size_t i = 0; i < tasks->size(); ++i) {
if ((*tasks)[i].task_descriptor().app_id == kFileManagerAppId)
filtered.push_back((*tasks)[i]);
}
tasks->swap(filtered);
}
// Returns true if the given task is a handler by built-in apps like the Files
// app itself or QuickOffice etc. They are used as the initial default app.
bool IsFallbackFileHandler(const file_tasks::TaskDescriptor& task) {
if (task.task_type != file_tasks::TASK_TYPE_FILE_BROWSER_HANDLER &&
task.task_type != file_tasks::TASK_TYPE_FILE_HANDLER)
return false;
const char* const kBuiltInApps[] = {
kFileManagerAppId, kVideoPlayerAppId, kGalleryAppId, kTextEditorAppId,
};
for (size_t i = 0; i < arraysize(kBuiltInApps); ++i) {
if (task.app_id == kBuiltInApps[i])
return true;
}
return false;
}
void ExecuteByArcAfterMimeTypesCollected(
Profile* profile,
const TaskDescriptor& task,
const std::vector<FileSystemURL>& file_urls,
const FileTaskFinishedCallback& done,
extensions::app_file_handler_util::MimeTypeCollector* mime_collector,
std::unique_ptr<std::vector<std::string>> mime_types) {
if (ExecuteArcTask(profile, task, file_urls, *mime_types)) {
done.Run(extensions::api::file_manager_private::TASK_RESULT_MESSAGE_SENT);
} else {
done.Run(extensions::api::file_manager_private::TASK_RESULT_FAILED);
}
}
void PostProcessFoundTasks(
Profile* profile,
const std::vector<extensions::EntryInfo>& entries,
const FindTasksCallback& callback,
std::unique_ptr<std::vector<FullTaskDescriptor>> result_list) {
// Google documents can only be handled by internal handlers.
if (ContainsGoogleDocument(entries))
KeepOnlyFileManagerInternalTasks(result_list.get());
ChooseAndSetDefaultTask(*profile->GetPrefs(), entries, result_list.get());
callback.Run(std::move(result_list));
}
} // namespace
FullTaskDescriptor::FullTaskDescriptor(const TaskDescriptor& task_descriptor,
const std::string& task_title,
const Verb task_verb,
const GURL& icon_url,
bool is_default,
bool is_generic_file_handler)
: task_descriptor_(task_descriptor),
task_title_(task_title),
task_verb_(task_verb),
icon_url_(icon_url),
is_default_(is_default),
is_generic_file_handler_(is_generic_file_handler) {}
FullTaskDescriptor::~FullTaskDescriptor() {}
FullTaskDescriptor::FullTaskDescriptor(const FullTaskDescriptor& other) =
default;
void UpdateDefaultTask(PrefService* pref_service,
const std::string& task_id,
const std::set<std::string>& suffixes,
const std::set<std::string>& mime_types) {
if (!pref_service)
return;
if (!mime_types.empty()) {
DictionaryPrefUpdate mime_type_pref(pref_service,
prefs::kDefaultTasksByMimeType);
for (std::set<std::string>::const_iterator iter = mime_types.begin();
iter != mime_types.end(); ++iter) {
mime_type_pref->SetWithoutPathExpansion(
*iter, base::MakeUnique<base::Value>(task_id));
}
}
if (!suffixes.empty()) {
DictionaryPrefUpdate mime_type_pref(pref_service,
prefs::kDefaultTasksBySuffix);
for (std::set<std::string>::const_iterator iter = suffixes.begin();
iter != suffixes.end(); ++iter) {
// Suffixes are case insensitive.
std::string lower_suffix = base::ToLowerASCII(*iter);
mime_type_pref->SetWithoutPathExpansion(
lower_suffix, base::MakeUnique<base::Value>(task_id));
}
}
}
std::string GetDefaultTaskIdFromPrefs(const PrefService& pref_service,
const std::string& mime_type,
const std::string& suffix) {
VLOG(1) << "Looking for default for MIME type: " << mime_type
<< " and suffix: " << suffix;
std::string task_id;
if (!mime_type.empty()) {
const base::DictionaryValue* mime_task_prefs =
pref_service.GetDictionary(prefs::kDefaultTasksByMimeType);
DCHECK(mime_task_prefs);
LOG_IF(ERROR, !mime_task_prefs) << "Unable to open MIME type prefs";
if (mime_task_prefs &&
mime_task_prefs->GetStringWithoutPathExpansion(mime_type, &task_id)) {
VLOG(1) << "Found MIME default handler: " << task_id;
return task_id;
}
}
const base::DictionaryValue* suffix_task_prefs =
pref_service.GetDictionary(prefs::kDefaultTasksBySuffix);
DCHECK(suffix_task_prefs);
LOG_IF(ERROR, !suffix_task_prefs) << "Unable to open suffix prefs";
std::string lower_suffix = base::ToLowerASCII(suffix);
if (suffix_task_prefs)
suffix_task_prefs->GetStringWithoutPathExpansion(lower_suffix, &task_id);
VLOG_IF(1, !task_id.empty()) << "Found suffix default handler: " << task_id;
return task_id;
}
std::string MakeTaskID(const std::string& app_id,
TaskType task_type,
const std::string& action_id) {
return base::StringPrintf("%s|%s|%s",
app_id.c_str(),
TaskTypeToString(task_type).c_str(),
action_id.c_str());
}
std::string TaskDescriptorToId(const TaskDescriptor& task_descriptor) {
return MakeTaskID(task_descriptor.app_id,
task_descriptor.task_type,
task_descriptor.action_id);
}
bool ParseTaskID(const std::string& task_id, TaskDescriptor* task) {
DCHECK(task);
std::vector<std::string> result = base::SplitString(
task_id, "|", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
// Parse a legacy task ID that only contain two parts. Drive tasks are
// identified by a prefix "drive-app:" on the extension ID. The legacy task
// IDs can be stored in preferences.
if (result.size() == 2) {
if (base::StartsWith(result[0], kDriveTaskExtensionPrefix,
base::CompareCase::SENSITIVE)) {
task->task_type = TASK_TYPE_DRIVE_APP;
task->app_id = result[0].substr(kDriveTaskExtensionPrefixLength);
} else {
task->task_type = TASK_TYPE_FILE_BROWSER_HANDLER;
task->app_id = result[0];
}
task->action_id = result[1];
return true;
}
if (result.size() != 3)
return false;
TaskType task_type = StringToTaskType(result[1]);
if (task_type == TASK_TYPE_UNKNOWN)
return false;
task->app_id = result[0];
task->task_type = task_type;
task->action_id = result[2];
return true;
}
bool ExecuteFileTask(Profile* profile,
const GURL& source_url,
const TaskDescriptor& task,
const std::vector<FileSystemURL>& file_urls,
const FileTaskFinishedCallback& done) {
UMA_HISTOGRAM_ENUMERATION("FileBrowser.ViewingTaskType", task.task_type,
NUM_TASK_TYPE);
// ARC apps needs mime types for launching. Retrieve them first.
if (task.task_type == TASK_TYPE_ARC_APP) {
extensions::app_file_handler_util::MimeTypeCollector* mime_collector =
new extensions::app_file_handler_util::MimeTypeCollector(profile);
mime_collector->CollectForURLs(
file_urls,
base::Bind(&ExecuteByArcAfterMimeTypesCollected, profile, task,
file_urls, done, base::Owned(mime_collector)));
return true;
}
// drive::FileTaskExecutor is responsible to handle drive tasks.
if (task.task_type == TASK_TYPE_DRIVE_APP) {
DCHECK_EQ(kDriveAppActionID, task.action_id);
drive::FileTaskExecutor* executor =
new drive::FileTaskExecutor(profile, task.app_id);
executor->Execute(file_urls, done);
return true;
}
// Get the extension.
const Extension* extension = extensions::ExtensionRegistry::Get(
profile)->enabled_extensions().GetByID(task.app_id);
if (!extension)
return false;
// Execute the task.
if (task.task_type == TASK_TYPE_FILE_BROWSER_HANDLER) {
return file_browser_handlers::ExecuteFileBrowserHandler(
profile,
extension,
task.action_id,
file_urls,
done);
} else if (task.task_type == TASK_TYPE_FILE_HANDLER) {
std::vector<base::FilePath> paths;
for (size_t i = 0; i != file_urls.size(); ++i)
paths.push_back(file_urls[i].path());
apps::LaunchPlatformAppWithFileHandler(
profile, extension, task.action_id, paths);
if (!done.is_null())
done.Run(extensions::api::file_manager_private::TASK_RESULT_MESSAGE_SENT);
return true;
}
NOTREACHED();
return false;
}
void FindDriveAppTasks(const drive::DriveAppRegistry& drive_app_registry,
const std::vector<extensions::EntryInfo>& entries,
std::vector<FullTaskDescriptor>* result_list) {
DCHECK(result_list);
bool is_first = true;
typedef std::map<std::string, drive::DriveAppInfo> DriveAppInfoMap;
DriveAppInfoMap drive_app_map;
for (std::vector<extensions::EntryInfo>::const_iterator it = entries.begin();
it != entries.end(); ++it) {
const base::FilePath& file_path = it->path;
const std::string& mime_type = it->mime_type;
// Return immediately if a file not on Drive is found, as Drive app tasks
// work only if all files are on Drive.
if (!drive::util::IsUnderDriveMountPoint(file_path))
return;
std::vector<drive::DriveAppInfo> app_info_list;
drive_app_registry.GetAppsForFile(file_path.Extension(),
mime_type,
&app_info_list);
if (is_first) {
// For the first file, we store all the info.
for (size_t j = 0; j < app_info_list.size(); ++j)
drive_app_map[app_info_list[j].app_id] = app_info_list[j];
} else {
// For remaining files, take the intersection with the current
// result, based on the app id.
std::set<std::string> app_id_set;
for (size_t j = 0; j < app_info_list.size(); ++j)
app_id_set.insert(app_info_list[j].app_id);
for (DriveAppInfoMap::iterator iter = drive_app_map.begin();
iter != drive_app_map.end();) {
if (app_id_set.count(iter->first) == 0) {
drive_app_map.erase(iter++);
} else {
++iter;
}
}
}
is_first = false;
}
for (DriveAppInfoMap::const_iterator iter = drive_app_map.begin();
iter != drive_app_map.end(); ++iter) {
const drive::DriveAppInfo& app_info = iter->second;
TaskDescriptor descriptor(app_info.app_id,
TASK_TYPE_DRIVE_APP,
kDriveAppActionID);
GURL icon_url = drive::util::FindPreferredIcon(
app_info.app_icons,
drive::util::kPreferredIconSize);
result_list->push_back(FullTaskDescriptor(
descriptor, app_info.app_name, Verb::VERB_OPEN_WITH, icon_url,
false /* is_default */, false /* is_generic_file_handler */));
}
}
bool IsGoodMatchFileHandler(
const extensions::FileHandlerInfo& file_handler_info,
const std::vector<extensions::EntryInfo>& entries) {
if (file_handler_info.extensions.count("*") > 0 ||
file_handler_info.types.count("*") > 0 ||
file_handler_info.types.count("*/*") > 0)
return false;
// If text/* file handler matches with unsupported text mime type, we don't
// regard it as good match.
if (file_handler_info.types.count("text/*")) {
for (const auto& entry : entries) {
if (blink::IsUnsupportedTextMimeType(entry.mime_type))
return false;
}
}
// We consider it a good match if no directories are selected.
for (const auto& entry : entries) {
if (entry.is_directory)
return false;
}
return true;
}
void FindFileHandlerTasks(Profile* profile,
const std::vector<extensions::EntryInfo>& entries,
std::vector<FullTaskDescriptor>* result_list) {
DCHECK(!entries.empty());
DCHECK(result_list);
const extensions::ExtensionSet& enabled_extensions =
extensions::ExtensionRegistry::Get(profile)->enabled_extensions();
for (extensions::ExtensionSet::const_iterator iter =
enabled_extensions.begin();
iter != enabled_extensions.end();
++iter) {
const Extension* extension = iter->get();
// Check that the extension can be launched via an event. This includes all
// platform apps plus whitelisted extensions.
if (!CanLaunchViaEvent(extension))
continue;
if (profile->IsOffTheRecord() &&
!extensions::util::IsIncognitoEnabled(extension->id(), profile))
continue;
typedef std::vector<const extensions::FileHandlerInfo*> FileHandlerList;
FileHandlerList file_handlers =
FindFileHandlersForEntries(*extension, entries);
if (file_handlers.empty())
continue;
// If the new ZIP unpacker is disabled, then hide its handlers, so we don't
// show both the legacy one and the new one in Files app for ZIP files.
if (extension->id() == extension_misc::kZIPUnpackerExtensionId &&
base::CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kDisableNewZIPUnpacker)) {
continue;
}
// A map which has as key a handler verb, and as value a pair of the
// handler with which to open the given entries and a boolean marking
// if the handler is a good match.
std::map<std::string, std::pair<const extensions::FileHandlerInfo*, bool>>
handlers_for_entries;
// Show the first good matching handler of each verb supporting the given
// entries that corresponds to the app. If there doesn't exist such handler,
// show the first matching handler of the verb.
for (const extensions::FileHandlerInfo* handler : file_handlers) {
bool good_match = IsGoodMatchFileHandler(*handler, entries);
auto it = handlers_for_entries.find(handler->verb);
if (it == handlers_for_entries.end() ||
(!it->second.second /* existing handler not a good match */ &&
good_match)) {
handlers_for_entries[handler->verb] =
std::make_pair(handler, good_match);
}
}
for (const auto& entry : handlers_for_entries) {
const extensions::FileHandlerInfo* handler = entry.second.first;
std::string task_id = file_tasks::MakeTaskID(
extension->id(), file_tasks::TASK_TYPE_FILE_HANDLER, handler->id);
GURL best_icon = extensions::ExtensionIconSource::GetIconURL(
extension, drive::util::kPreferredIconSize,
ExtensionIconSet::MATCH_BIGGER,
false); // grayscale
// If file handler doesn't match as good match, regards it as generic file
// handler.
const bool is_generic_file_handler =
!IsGoodMatchFileHandler(*handler, entries);
Verb verb;
if (handler->verb == extensions::file_handler_verbs::kAddTo) {
verb = Verb::VERB_ADD_TO;
} else if (handler->verb == extensions::file_handler_verbs::kPackWith) {
verb = Verb::VERB_PACK_WITH;
} else if (handler->verb == extensions::file_handler_verbs::kShareWith) {
verb = Verb::VERB_SHARE_WITH;
} else {
// Only kOpenWith is a valid remaining verb. Invalid verbs should fall
// back to it.
DCHECK(handler->verb == extensions::file_handler_verbs::kOpenWith);
verb = Verb::VERB_OPEN_WITH;
}
result_list->push_back(FullTaskDescriptor(
TaskDescriptor(extension->id(), file_tasks::TASK_TYPE_FILE_HANDLER,
handler->id),
extension->name(), verb, best_icon, false /* is_default */,
is_generic_file_handler));
}
}
}
void FindFileBrowserHandlerTasks(
Profile* profile,
const std::vector<GURL>& file_urls,
std::vector<FullTaskDescriptor>* result_list) {
DCHECK(!file_urls.empty());
DCHECK(result_list);
file_browser_handlers::FileBrowserHandlerList common_tasks =
file_browser_handlers::FindFileBrowserHandlers(profile, file_urls);
if (common_tasks.empty())
return;
const extensions::ExtensionSet& enabled_extensions =
extensions::ExtensionRegistry::Get(profile)->enabled_extensions();
for (file_browser_handlers::FileBrowserHandlerList::const_iterator iter =
common_tasks.begin();
iter != common_tasks.end();
++iter) {
const FileBrowserHandler* handler = *iter;
const std::string extension_id = handler->extension_id();
const Extension* extension = enabled_extensions.GetByID(extension_id);
DCHECK(extension);
// TODO(zelidrag): Figure out how to expose icon URL that task defined in
// manifest instead of the default extension icon.
const GURL icon_url = extensions::ExtensionIconSource::GetIconURL(
extension, extension_misc::EXTENSION_ICON_SMALL,
ExtensionIconSet::MATCH_BIGGER,
false); // grayscale
result_list->push_back(FullTaskDescriptor(
TaskDescriptor(extension_id, file_tasks::TASK_TYPE_FILE_BROWSER_HANDLER,
handler->id()),
handler->title(), Verb::VERB_NONE /* no verb for FileBrowserHandler */,
icon_url, false /* is_default */, false /* is_generic_file_handler */));
}
}
void FindExtensionAndAppTasks(
Profile* profile,
const std::vector<extensions::EntryInfo>& entries,
const std::vector<GURL>& file_urls,
const FindTasksCallback& callback,
std::unique_ptr<std::vector<FullTaskDescriptor>> result_list) {
// 3. Continues from FindAllTypesOfTasks. Find and append file handler tasks.
FindFileHandlerTasks(profile, entries, result_list.get());
// 4. Find and append file browser handler tasks. We know there aren't
// duplicates because "file_browser_handlers" and "file_handlers" shouldn't
// be used in the same manifest.json.
FindFileBrowserHandlerTasks(profile, file_urls, result_list.get());
// Done. Apply post-filtering and callback.
PostProcessFoundTasks(profile, entries, callback, std::move(result_list));
}
void FindAllTypesOfTasks(Profile* profile,
const drive::DriveAppRegistry* drive_app_registry,
const std::vector<extensions::EntryInfo>& entries,
const std::vector<GURL>& file_urls,
const FindTasksCallback& callback) {
DCHECK(profile);
std::unique_ptr<std::vector<FullTaskDescriptor>> result_list(
new std::vector<FullTaskDescriptor>);
// 1. Find Drive app tasks, if the drive app registry is present.
if (drive_app_registry)
FindDriveAppTasks(*drive_app_registry, entries, result_list.get());
// 2. Find and append ARC handler tasks.
FindArcTasks(profile, entries, std::move(result_list),
base::Bind(&FindExtensionAndAppTasks, profile, entries,
file_urls, callback));
}
void ChooseAndSetDefaultTask(const PrefService& pref_service,
const std::vector<extensions::EntryInfo>& entries,
std::vector<FullTaskDescriptor>* tasks) {
// Collect the task IDs of default tasks from the preferences into a set.
std::set<std::string> default_task_ids;
for (std::vector<extensions::EntryInfo>::const_iterator it = entries.begin();
it != entries.end(); ++it) {
const base::FilePath& file_path = it->path;
const std::string& mime_type = it->mime_type;
std::string task_id = file_tasks::GetDefaultTaskIdFromPrefs(
pref_service, mime_type, file_path.Extension());
default_task_ids.insert(task_id);
}
// Go through all the tasks from the beginning and see if there is any
// default task. If found, pick and set it as default and return.
for (size_t i = 0; i < tasks->size(); ++i) {
FullTaskDescriptor* task = &tasks->at(i);
DCHECK(!task->is_default());
const std::string task_id = TaskDescriptorToId(task->task_descriptor());
if (base::ContainsKey(default_task_ids, task_id)) {
task->set_is_default(true);
return;
}
}
// No default tasks found. If there is any fallback file browser handler,
// make it as default task, so it's selected by default.
for (size_t i = 0; i < tasks->size(); ++i) {
FullTaskDescriptor* task = &tasks->at(i);
DCHECK(!task->is_default());
if (IsFallbackFileHandler(task->task_descriptor())) {
task->set_is_default(true);
return;
}
}
}
} // namespace file_tasks
} // namespace file_manager
| [
"rdeshm0@aptvm070-6.apt.emulab.net"
] | rdeshm0@aptvm070-6.apt.emulab.net |
f70298194badedeba6ab2867490d4c31c91db264 | cd2fa5ea8f8e58b6ae292236e4e5f3b4a14cbc20 | /file/FilePass.hpp | 2701e678c3e243ce5d1e9440bd4032cee842a72c | [] | no_license | squarespirit/caltech10as | d2778b869665109bb8cedb28088ef9f85a2970dd | 8f0419c1ecf963b51d6dcbce9a796f3667c13e2b | refs/heads/master | 2020-05-18T15:53:59.016088 | 2019-05-09T22:25:03 | 2019-05-09T22:25:03 | 184,510,772 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 394 | hpp | #pragma once
#include "line/Line.hpp"
/**
* FilePass is an interface for what to do with each line of assembly
* during a pass over the assembly file.
*/
class FilePass {
public:
/**
* Process a line of assembly.
* orig is the original line.
* line is a reference to the parsed line.
*/
virtual void processLine(std::string const &orig, Line const &line) = 0;
}; | [
"mewu@caltech.edu"
] | mewu@caltech.edu |
259df20293b696346392c356b70e870106cb9354 | 37512c1ee07405f3213b009466479e34203ce550 | /core/include/layers/conv_layer.h | 6a560c2dc824293ee592734f3b81dedb1cc5b585 | [
"MIT"
] | permissive | antonok-edm/DNNMark | a57ddeb192172c039753e756ea8c3e4ceb667f66 | b050817ef609a08d28d91ec736a77f74bda323e3 | refs/heads/develop | 2020-07-04T08:40:33.944502 | 2017-05-15T23:50:50 | 2017-05-15T23:50:50 | 73,863,367 | 0 | 1 | null | 2016-11-15T23:06:59 | 2016-11-15T23:06:59 | null | UTF-8 | C++ | false | false | 10,569 | h | // The MIT License (MIT)
//
// Copyright (c) 2016 Northeastern University
//
// 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 CORE_INCLUDE_LAYERS_CONV_LAYER_H_
#define CORE_INCLUDE_LAYERS_CONV_LAYER_H_
#include "dnn_layer.h"
namespace dnnmark {
template <typename T>
class ConvolutionLayer : public Layer<T> {
// using declaration for calling member from base class
using Layer<T>::p_dnnmark_;
using Layer<T>::layer_id_;
using Layer<T>::previous_layer_name_;
using Layer<T>::input_dim_;
using Layer<T>::output_dim_;
using Layer<T>::bottom_desc_;
using Layer<T>::top_desc_;
using Layer<T>::data_manager_;
using Layer<T>::num_bottoms_;
using Layer<T>::bottoms_;
using Layer<T>::bottom_chunk_ids_;
using Layer<T>::bottom_diffs_;
using Layer<T>::bottom_diff_chunk_ids_;
using Layer<T>::num_tops_;
using Layer<T>::tops_;
using Layer<T>::top_chunk_ids_;
using Layer<T>::top_diffs_;
using Layer<T>::top_diff_chunk_ids_;
private:
ConvolutionParam conv_param_;
// Convolution specific descriptor
ConvolutionDesc<T> desc_;
// Layer weights
Data<T> *weights_;
int weights_chunk_id_;
Data<T> *weights_diff_;
int weights_diff_chunk_id_;
// Algorithm specific parameters
cudnnConvolutionFwdAlgo_t fwd_algo_;
cudnnConvolutionBwdFilterAlgo_t bwd_filter_algo_;
cudnnConvolutionBwdDataAlgo_t bwd_data_algo_;
size_t fwd_workspace_size_;
size_t bwd_data_workspace_size_;
size_t bwd_filter_workspace_size_;
void *fwd_workspace_;
void *bwd_data_workspace_;
void *bwd_filter_workspace_;
public:
ConvolutionLayer(DNNMark<T> *p_dnnmark)
: Layer<T>(p_dnnmark),
conv_param_(), desc_() {
Layer<T>::has_learnable_params_ = true;
}
ConvolutionParam *getConvParam() { return &conv_param_; }
void Setup() {
// Set up indispensable stuff here
Layer<T>::Setup();
// Set convolution related descriptors
desc_.Set(conv_param_, input_dim_.c_);
// Set up convolution related data
if (input_dim_.n_ != 0 && input_dim_.c_ != 0 &&
input_dim_.h_ != 0 && input_dim_.w_ != 0) {
//
// Standalone mode
//
// Compute dimension of output data
ComputeOutputDim();
// Set top tensor
top_desc_.Set(output_dim_.n_,
output_dim_.c_,
output_dim_.h_,
output_dim_.w_);
// Prepare top data
int top_size = output_dim_.n_ *
output_dim_.c_ *
output_dim_.h_ *
output_dim_.w_;
for (int i = 0; i < num_tops_; i++) {
top_chunk_ids_.push_back(
data_manager_->CreateData(top_size));
tops_.push_back(
data_manager_->GetData(top_chunk_ids_[i]));
top_diff_chunk_ids_.push_back(
data_manager_->CreateData(top_size));
top_diffs_.push_back(
data_manager_->GetData(top_diff_chunk_ids_[i]));
}
}
// Only one set of weights is considered
int weights_size = conv_param_.output_num_ *
input_dim_.c_ *
conv_param_.kernel_size_h_ *
conv_param_.kernel_size_w_;
weights_chunk_id_ = data_manager_->CreateData(weights_size);
weights_ = data_manager_->GetData(weights_chunk_id_);
weights_diff_chunk_id_ =
data_manager_->CreateData(weights_size);
weights_diff_ = data_manager_->GetData(weights_diff_chunk_id_);
// Fill the weight data
weights_->Filler();
// Set up convolution forward algorithm related parameters
CUDNN_CALL(cudnnGetConvolutionForwardAlgorithm(
p_dnnmark_->getRunMode() == COMPOSED ?
p_dnnmark_->GetHandle()->GetCudnn(layer_id_):
p_dnnmark_->GetHandle()->GetCudnn(),
bottom_desc_.Get(),
desc_.GetFilter(),
desc_.GetConv(),
top_desc_.Get(),
conv_param_.conv_fwd_pref_,
-1,
&fwd_algo_));
CUDNN_CALL(cudnnGetConvolutionForwardWorkspaceSize(
p_dnnmark_->getRunMode() == COMPOSED ?
p_dnnmark_->GetHandle()->GetCudnn(layer_id_):
p_dnnmark_->GetHandle()->GetCudnn(),
bottom_desc_.Get(),
desc_.GetFilter(),
desc_.GetConv(),
top_desc_.Get(),
fwd_algo_,
&fwd_workspace_size_));
CUDA_CALL(cudaMalloc(&fwd_workspace_, fwd_workspace_size_));
// Set up convolution backward algorithm related parameters
CUDNN_CALL(cudnnGetConvolutionBackwardFilterAlgorithm(
p_dnnmark_->getRunMode() == COMPOSED ?
p_dnnmark_->GetHandle()->GetCudnn(layer_id_):
p_dnnmark_->GetHandle()->GetCudnn(),
bottom_desc_.Get(),
top_desc_.Get(),
desc_.GetConv(),
desc_.GetFilter(),
conv_param_.conv_bwd_filter_pref_,
-1,
&bwd_filter_algo_));
CUDNN_CALL(cudnnGetConvolutionBackwardFilterWorkspaceSize(
p_dnnmark_->getRunMode() == COMPOSED ?
p_dnnmark_->GetHandle()->GetCudnn(layer_id_):
p_dnnmark_->GetHandle()->GetCudnn(),
bottom_desc_.Get(),
top_desc_.Get(),
desc_.GetConv(),
desc_.GetFilter(),
bwd_filter_algo_,
&bwd_filter_workspace_size_));
CUDA_CALL(cudaMalloc(&bwd_filter_workspace_, bwd_filter_workspace_size_));
CUDNN_CALL(cudnnGetConvolutionBackwardDataAlgorithm(
p_dnnmark_->getRunMode() == COMPOSED ?
p_dnnmark_->GetHandle()->GetCudnn(layer_id_):
p_dnnmark_->GetHandle()->GetCudnn(),
desc_.GetFilter(),
top_desc_.Get(),
desc_.GetConv(),
bottom_desc_.Get(),
conv_param_.conv_bwd_data_pref_,
-1,
&bwd_data_algo_));
CUDNN_CALL(cudnnGetConvolutionBackwardDataWorkspaceSize(
p_dnnmark_->getRunMode() == COMPOSED ?
p_dnnmark_->GetHandle()->GetCudnn(layer_id_):
p_dnnmark_->GetHandle()->GetCudnn(),
desc_.GetFilter(),
top_desc_.Get(),
desc_.GetConv(),
bottom_desc_.Get(),
bwd_data_algo_,
&bwd_data_workspace_size_));
CUDA_CALL(cudaMalloc(&bwd_data_workspace_, bwd_data_workspace_size_));
}
void ComputeOutputDim() {
output_dim_.n_ = input_dim_.n_;
output_dim_.c_ = conv_param_.output_num_;
output_dim_.h_ = (input_dim_.h_ +
2 * conv_param_.pad_h_ - conv_param_.kernel_size_h_) /
conv_param_.stride_u_ + 1;
output_dim_.w_ = (input_dim_.w_ +
2 * conv_param_.pad_w_ - conv_param_.kernel_size_w_) /
conv_param_.stride_v_ + 1;
}
void ForwardPropagation() {
// Fill the bottom data
if (p_dnnmark_->getRunMode() == STANDALONE ||
!previous_layer_name_.compare("null")) {
for (int i = 0; i < num_bottoms_; i++) {
bottoms_[i]->Filler();
}
}
// Convolution forward computation
cudaProfilerStart();
for (int i = 0; i < num_bottoms_; i++) {
CUDNN_CALL(cudnnConvolutionForward(
p_dnnmark_->getRunMode() == COMPOSED ?
p_dnnmark_->GetHandle()->GetCudnn(layer_id_):
p_dnnmark_->GetHandle()->GetCudnn(),
DataType<T>::one,
bottom_desc_.Get(), bottoms_[i]->Get(),
desc_.GetFilter(), weights_->Get(),
desc_.GetConv(),
fwd_algo_, fwd_workspace_, fwd_workspace_size_,
DataType<T>::zero,
top_desc_.Get(), tops_[i]->Get()));
}
cudaProfilerStop();
// TODO: evaluate the necessity of freeing memory here
// Free the workspace
CUDA_CALL(cudaFree(fwd_workspace_));
}
void BackwardPropagation() {
if (p_dnnmark_->getRunMode() == STANDALONE ||
!previous_layer_name_.compare("null")) {
// Fill the top data and top diff data
for (int i = 0; i < num_tops_; i++) {
tops_[i]->Filler();
top_diffs_[i]->Filler();
}
// Fill the bottom data
for (int i = 0; i < num_bottoms_; i++) {
bottoms_[i]->Filler();
}
}
// Convolution forward computation
cudaProfilerStart();
for (int i = 0; i < num_tops_; i++) {
CUDNN_CALL(cudnnConvolutionBackwardFilter(
p_dnnmark_->getRunMode() == COMPOSED ?
p_dnnmark_->GetHandle()->GetCudnn(layer_id_):
p_dnnmark_->GetHandle()->GetCudnn(),
DataType<T>::one,
bottom_desc_.Get(), bottoms_[i]->Get(),
top_desc_.Get(), top_diffs_[i]->Get(),
desc_.GetConv(),
bwd_filter_algo_,
bwd_filter_workspace_, bwd_filter_workspace_size_,
DataType<T>::zero,
desc_.GetFilter(), weights_diff_->Get()));
CUDNN_CALL(cudnnConvolutionBackwardData(
p_dnnmark_->getRunMode() == COMPOSED ?
p_dnnmark_->GetHandle()->GetCudnn(layer_id_):
p_dnnmark_->GetHandle()->GetCudnn(),
DataType<T>::one,
desc_.GetFilter(), weights_->Get(),
top_desc_.Get(), top_diffs_[i]->Get(),
desc_.GetConv(),
bwd_data_algo_,
bwd_data_workspace_, bwd_data_workspace_size_,
DataType<T>::zero,
bottom_desc_.Get(), bottoms_[i]->Get()));
}
cudaProfilerStop();
// TODO: evaluate the necessity of freeing memory here
// Free the workspace
CUDA_CALL(cudaFree(bwd_data_workspace_));
CUDA_CALL(cudaFree(bwd_filter_workspace_));
}
};
} // namespace dnnmark
#endif // CORE_INCLUDE_LAYERS_CONV_LAYER_H_
| [
"antonok35@gmail.com"
] | antonok35@gmail.com |
e5ce4c4e363aface5cda235592242c8ffa8dc6ff | d42c8cc7c8e4df67c80c74efef4fa1c0ae480cea | /2019-05-21-src/UthreadsMultiCore/SimpleTest/SimpleTest.cpp | 53d72e09a04548eb4c0dd00b3496cf09e9d0610a | [] | no_license | isel-leic-so/SO-1819v-LI42D | fbec6c46569238849233a768e61055a446825ba7 | 3d0c3808fc1977fee4635e89bd6a27c14ee0d200 | refs/heads/master | 2020-04-27T08:53:06.767136 | 2019-06-11T13:25:33 | 2019-06-11T13:25:33 | 174,190,410 | 22 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,318 | cpp | // SimpleTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "usynch.h"
#include "List.h"
/////////////////////////////////////////////
//
// CCISEL
// 2007-2011
//
// UThread Library First Test
//
// Jorge Martins, 2011
////////////////////////////////////////////
#define DEBUG
#define MAX_THREADS 10
#include <crtdbg.h>
#include <stdio.h>
#include "..\Include\Uthread.h"
///////////////////////////////////////////////////////////////
// //
// Test 1: N threads, each one printing its number M times //
// //
///////////////////////////////////////////////////////////////
ULONG Test1_Count;
VOID Test1_Thread (UT_ARGUMENT Argument) {
UCHAR Char;
ULONG Index;
Char = (UCHAR) Argument;
for (Index = 0; Index < 10000; ++Index) {
putchar(Char);
if ((rand() % 4) == 0) {
UtYield();
}
}
++Test1_Count;
}
VOID Test1 () {
ULONG Index;
Test1_Count = 0;
printf("\n :: Test 1 - BEGIN :: \n\n");
for (Index = 0; Index < MAX_THREADS; ++Index) {
UtCreate(Test1_Thread, (UT_ARGUMENT) ('0' + Index));
}
UtRun();
//_ASSERTE(Test1_Count == MAX_THREADS);
printf("\n\n :: Test 1 - END :: \n");
}
int main () {
UtInit();
Test1();
getchar();
UtEnd();
return 0;
}
| [
"jmartins@isel.pt"
] | jmartins@isel.pt |
719f725b03d04116462510fe42c8b02b4a4a57fd | 3db023edb0af1dcf8a1da83434d219c3a96362ba | /windows_nt_3_5_source_code/NT-782/PRIVATE/WINDOWS/GDI/OPENGL/GLU/NURBS/CORE/CURVELIS.H | a3c4e6c6139a8e61c674baaee62a6d8c0af6766f | [] | no_license | xiaoqgao/windows_nt_3_5_source_code | de30e9b95856bc09469d4008d76191f94379c884 | d2894c9125ff1c14028435ed1b21164f6b2b871a | refs/heads/master | 2022-12-23T17:58:33.768209 | 2020-09-28T20:20:18 | 2020-09-28T20:20:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,229 | h | /**************************************************************************
* *
* Copyright (C) 1992, Silicon Graphics, Inc. *
* *
* These coded instructions, statements, and computer programs contain *
* unpublished proprietary information of Silicon Graphics, Inc., and *
* are protected by Federal copyright law. They may not be disclosed *
* to third parties or copied or duplicated in any form, in whole or *
* in part, without the prior written consent of Silicon Graphics, Inc. *
* *
**************************************************************************/
/*
* curvelist.h - $Revision: 1.1 $
*/
#ifndef __CURVELIST_H__
#define __CURVELIST_H__
#include "types.h"
#include "defines.h"
class Mapdesc;
class Quilt;
class Curve;
class Curvelist
{
friend class Subdivider;
public:
Curvelist( Quilt *, REAL, REAL );
Curvelist( Curvelist &, REAL );
~Curvelist( void );
int cullCheck( void );
void getstepsize( void );
int needsSamplingSubdivision();
private:
Curve *curve;
float range[3];
int needsSubdivision;
float stepsize;
};
#endif /* __CURVELIST_H__ */
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
457c1b9ecee7811e4d88f17785a5dc4ffd4f2438 | 0f250ed1e28eac28c3b832ec43e741ce393ec416 | /TestObject.cpp | b7ec1797aec1c73215b899366d0de8c5e5f9b497 | [] | no_license | kokojae/SSBEngine | 08b26e555a5b8299eae2b16d2067d99133b84ef6 | 052e3586cf75926b35bc7c4d18d685ff831e7e02 | refs/heads/master | 2020-12-29T10:50:58.895734 | 2020-02-11T07:09:43 | 2020-02-11T07:09:43 | 238,579,474 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,899 | cpp | #include "TestObject.h"
#include "Animation.h"
#include "InputManager.h"
#include "Camera.h"
#include "Scene.h"
#include "Bullet.h"
#include "GraphicManager.h"
TestObject::TestObject()
{
}
TestObject::~TestObject()
{
}
void TestObject::Init()
{
name = "Player";
animation->SetAnimation("TestImage");
position = { 0.0f,0.0f };
sortingLayer = 5;
}
void TestObject::Update()
{
PlayerMove();
MouseInput();
}
void TestObject::OnRender()
{
GraphicManager::RenderText("Player", position);
}
void TestObject::LateUpdate()
{
CameraMove();
}
void TestObject::Release()
{
GameManager::nowScene->nextScene = "Main";
}
void TestObject::PlayerMove()
{
if (InputManager::GetKey(InputManager::KeyCode::W))
{
position.y -= 5.0f;
}
if (InputManager::GetKey(InputManager::KeyCode::A))
{
position.x -= 5.0f;
}
if (InputManager::GetKey(InputManager::KeyCode::S))
{
position.y += 5.0f;
}
if (InputManager::GetKey(InputManager::KeyCode::D))
{
position.x += 5.0f;
}
//rotation += 0.1f;
if (rotation > 360.0f)
{
rotation -= 360.0f;
}
//float ss = abs(sin(D3DXToRadian(rotation) * 3.0f) * 2.0f) + 1.0f;
//scale.x = scale.y = ss;
//scale.x = abs(sin(D3DXToRadian(rotation)));
//scale.y = abs(sin(D3DXToRadian(rotation)));
}
void TestObject::MouseInput()
{
auto mousePosition = InputManager::mousePosition;
auto diff = mousePosition - position;
auto rotation = atan2(diff.y, diff.x);
TestObject::rotation = D3DXToDegree(rotation);
D3DXVECTOR2 normal;
D3DXVec2Normalize(&normal, &diff);
if (InputManager::GetKeyDown(InputManager::KeyCode::MOUSE0))
{
auto bullet = Instantiate<Bullet>(position);
if (bullet != nullptr)
{
bullet->SetOption(normal, 10.0f);
}
}
}
void TestObject::CameraMove()
{
//Camera::position = position;
//position = InputManager::mousePosition;
auto diff = position - Camera::position;
Camera::position += diff * 0.05f;
}
| [
"54296776+kokojae@users.noreply.github.com"
] | 54296776+kokojae@users.noreply.github.com |
cf8392b55b520514acb7e4da19ac0624ef9d0f65 | 874124925d861bc8d003f09490d823f44d1b0ca0 | /src/include/math.hpp | 5a8aabc6e541bf584f094671c9a2b2460d51eb72 | [
"MIT"
] | permissive | foxostro/PinkTopaz | 2e5555b0495e493d3ca8bafbd98dd1b00e099bdd | cd8275a93ea34a56f640f915d4b6c769e82e9dc2 | refs/heads/master | 2021-01-22T22:24:07.097116 | 2018-06-17T04:14:59 | 2018-06-17T04:15:01 | 85,535,947 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,667 | hpp | //
// math.hpp
// PinkTopaz
//
// Created by Andrew Fox on 3/14/16.
//
//
#ifndef math_hpp
#define math_hpp
#include <algorithm>
#include <glm/glm.hpp>
#if defined(_MSC_VER)
#include <intrin.h>
#define __lzcnt32 _lzcnt_u32
#else
#include <x86intrin.h>
#endif
#if defined(__LZCNT__)
inline uint32_t ilog2(uint32_t x)
{
// See <https://stackoverflow.com/a/11376759/2403342> for details.
return (uint32_t)(8*sizeof(unsigned long long) - __lzcnt64(x) - 1);
}
#else
inline uint32_t ilog2(uint32_t x)
{
// See <http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious>
uint32_t r = 0;
while (x >>= 1) {
r++;
}
return r;
}
#endif // defined(__LZCNT__)
#if defined(__LZCNT__)
inline uint32_t roundUpToPowerOfTwo(uint32_t x)
{
return 1 << (32 - __lzcnt32(x - 1));
}
#else
inline uint32_t roundUpToPowerOfTwo(uint32_t v)
{
// See <http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2>
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
#endif // defined(__LZCNT__)
#if defined(__POPCNT__)
inline bool isPowerOfTwo(uint32_t x)
{
return _mm_popcnt_u32(x) == 1;
}
#else
inline bool isPowerOfTwo(uint32_t x)
{
// See <http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2>
return (x && !(x & (x - 1)));
}
#endif // defined(__POPCNT__)
template<typename T> inline
const T& clamp(const T &value, const T &min, const T &max)
{
return std::min(std::max(value, min), max);
}
inline float dot3(const glm::vec3 &a, const glm::vec4 &b)
{
return a.x*b.x + a.y*b.y + a.z*b.z;
}
#endif /* math_hpp */
| [
"foxostro@gmail.com"
] | foxostro@gmail.com |
0311ac8408c1d656a87c7cf5a719743aa63b897c | 05ace75fffe21a2d375e3611571f1a815d3c0fbc | /5.4.2/Core/src/server/game/Handlers/ChannelHandler.cpp | c841ca5f83adfc4d7be5954fe45606d562197401 | [] | no_license | DeKaDeNcE/Project-WoW | 97fcf9b505f2cd87e2fb17b27d92d960cdc12668 | 9307425445316cc4e88c73e116d4ea4d440d5ac2 | refs/heads/master | 2021-05-27T09:11:53.994059 | 2014-02-20T06:29:42 | 2014-02-20T06:29:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,588 | cpp | /*
* Copyright (C) 2011-2014 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2014 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ObjectMgr.h" // for normalizePlayerName
#include "ChannelMgr.h"
#include "Player.h"
#include "WorldSession.h"
void WorldSession::HandleJoinChannel(WorldPacket& recvPacket)
{
uint32 channelId;
uint32 channelLength, passLength;
std::string channelName, password;
recvPacket >> channelId;
passLength = recvPacket.ReadBits(7);
uint8 unknown1 = recvPacket.ReadBit(); // unknown bit
channelLength = recvPacket.ReadBits(7);
uint8 unknown2 = recvPacket.ReadBit(); // unknown bit
password = recvPacket.ReadString(passLength);
channelName = recvPacket.ReadString(channelLength);
TC_LOG_DEBUG("chat.system", "CMSG_JOIN_CHANNEL %s Channel: %u, unk1: %u, unk2: %u, channel: %s, password: %s",
GetPlayerInfo().c_str(), channelId, unknown1, unknown2, channelName.c_str(), password.c_str());
if (channelId)
{
ChatChannelsEntry const* channel = sChatChannelsStore.LookupEntry(channelId);
if (!channel)
return;
AreaTableEntry const* zone = GetAreaEntryByAreaID(GetPlayer()->GetZoneId());
if (!zone || !GetPlayer()->CanJoinConstantChannelInZone(channel, zone))
return;
}
if (channelName.empty())
return;
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
{
cMgr->setTeam(GetPlayer()->GetTeam());
if (Channel* channel = cMgr->GetJoinChannel(channelName, channelId))
channel->JoinChannel(GetPlayer(), password);
}
}
void WorldSession::HandleLeaveChannel(WorldPacket& recvPacket)
{
uint32 channelId;
std::string channelName;
recvPacket >> channelId;
uint32 length = recvPacket.ReadBits(8);
channelName = recvPacket.ReadString(length);
TC_LOG_DEBUG("chat.system", "CMSG_LEAVE_CHANNEL %s Channel: %s, unk1: %u",
GetPlayerInfo().c_str(), channelName.c_str(), channelId);
if (channelName.empty())
return;
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
{
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->LeaveChannel(GetPlayer(), true);
cMgr->LeftChannel(channelName);
}
}
void WorldSession::HandleChannelList(WorldPacket& recvPacket)
{
uint32 channelId;
recvPacket >> channelId; // flags
recvPacket.ReadBit();
uint32 length = recvPacket.ReadBits(7);
recvPacket.ReadBits(7);
recvPacket.ReadBit();
std::string channelName = recvPacket.ReadString(length);
TC_LOG_DEBUG("chat.system", "%s %s Channel: %s",
recvPacket.GetOpcode() == CMSG_CHANNEL_DISPLAY_LIST ? "CMSG_CHANNEL_DISPLAY_LIST" : "CMSG_CHANNEL_LIST",
GetPlayerInfo().c_str(), channelName.c_str());
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->List(GetPlayer());
}
void WorldSession::HandleChannelPassword(WorldPacket& recvPacket)
{
uint32 nameLength = recvPacket.ReadBits(8);
uint32 passLength = recvPacket.ReadBits(7);
std::string channelName = recvPacket.ReadString(nameLength);
std::string password = recvPacket.ReadString(passLength);
TC_LOG_DEBUG("chat.system", "CMSG_CHANNEL_PASSWORD %s Channel: %s, Password: %s",
GetPlayerInfo().c_str(), channelName.c_str(), password.c_str());
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->Password(GetPlayer(), password);
}
void WorldSession::HandleChannelSetOwner(WorldPacket& recvPacket)
{
uint32 channelLength = recvPacket.ReadBits(8);
uint32 nameLength = recvPacket.ReadBits(7);
std::string targetName = recvPacket.ReadString(nameLength);
std::string channelName = recvPacket.ReadString(channelLength);
TC_LOG_DEBUG("chat.system", "CMSG_CHANNEL_SET_OWNER %s Channel: %s, Target: %s",
GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str());
if (!normalizePlayerName(targetName))
return;
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->SetOwner(GetPlayer(), targetName);
}
void WorldSession::HandleChannelOwner(WorldPacket& recvPacket)
{
uint32 length = recvPacket.ReadBits(8);
std::string channelName = recvPacket.ReadString(length);
TC_LOG_DEBUG("chat.system", "CMSG_CHANNEL_OWNER %s Channel: %s",
GetPlayerInfo().c_str(), channelName.c_str());
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->SendWhoOwner(GetPlayer()->GetGUID());
}
void WorldSession::HandleChannelModerator(WorldPacket& recvPacket)
{
uint32 channelLength = recvPacket.ReadBits(8);
uint32 nameLength = recvPacket.ReadBits(7);
std::string targetName = recvPacket.ReadString(nameLength);
std::string channelName = recvPacket.ReadString(channelLength);
TC_LOG_DEBUG("chat.system", "CMSG_CHANNEL_MODERATOR %s Channel: %s, Target: %s",
GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str());
if (!normalizePlayerName(targetName))
return;
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->SetModerator(GetPlayer(), targetName);
}
void WorldSession::HandleChannelUnmoderator(WorldPacket& recvPacket)
{
uint32 nameLength = recvPacket.ReadBits(7);
uint32 channelLength = recvPacket.ReadBits(8);
std::string channelName = recvPacket.ReadString(channelLength);
std::string targetName = recvPacket.ReadString(nameLength);
TC_LOG_DEBUG("chat.system", "CMSG_CHANNEL_UNMODERATOR %s Channel: %s, Target: %s",
GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str());
if (!normalizePlayerName(targetName))
return;
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->UnsetModerator(GetPlayer(), targetName);
}
void WorldSession::HandleChannelMute(WorldPacket& recvPacket)
{
uint32 channelLength = recvPacket.ReadBits(8);
uint32 nameLength = recvPacket.ReadBits(7);
std::string channelName = recvPacket.ReadString(channelLength);
std::string targetName = recvPacket.ReadString(nameLength);
TC_LOG_DEBUG("chat.system", "CMSG_CHANNEL_MUTE %s Channel: %s, Target: %s",
GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str());
if (!normalizePlayerName(targetName))
return;
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->SetMute(GetPlayer(), targetName);
}
void WorldSession::HandleChannelUnmute(WorldPacket& recvPacket)
{
uint32 nameLength = recvPacket.ReadBits(8);
uint32 channelLength = recvPacket.ReadBits(7);
std::string targetName = recvPacket.ReadString(nameLength);
std::string channelName = recvPacket.ReadString(channelLength);
TC_LOG_DEBUG("chat.system", "CMSG_CHANNEL_UNMUTE %s Channel: %s, Target: %s",
GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str());
if (!normalizePlayerName(targetName))
return;
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->UnsetMute(GetPlayer(), targetName);
}
void WorldSession::HandleChannelInvite(WorldPacket& recvPacket)
{
uint32 nameLength = recvPacket.ReadBits(7);
uint32 channelLength = recvPacket.ReadBits(8);
std::string targetName = recvPacket.ReadString(nameLength);
std::string channelName = recvPacket.ReadString(channelLength);
TC_LOG_DEBUG("chat.system", "CMSG_CHANNEL_INVITE %s Channel: %s, Target: %s",
GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str());
if (!normalizePlayerName(targetName))
return;
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->Invite(GetPlayer(), targetName);
}
void WorldSession::HandleChannelKick(WorldPacket& recvPacket)
{
uint32 channelLength = recvPacket.ReadBits(8);
uint32 nameLength = recvPacket.ReadBits(7);
std::string channelName = recvPacket.ReadString(channelLength);
std::string targetName = recvPacket.ReadString(nameLength);
TC_LOG_DEBUG("chat.system", "CMSG_CHANNEL_KICK %s Channel: %s, Target: %s",
GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str());
if (!normalizePlayerName(targetName))
return;
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->Kick(GetPlayer(), targetName);
}
void WorldSession::HandleChannelBan(WorldPacket& recvPacket)
{
uint32 channelLength, nameLength;
std::string channelName, targetName;
channelLength = recvPacket.ReadBits(8);
nameLength = recvPacket.ReadBits(7);
targetName = recvPacket.ReadString(nameLength);
channelName = recvPacket.ReadString(channelLength);
TC_LOG_DEBUG("chat.system", "CMSG_CHANNEL_BAN %s Channel: %s, Target: %s",
GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str());
if (!normalizePlayerName(targetName))
return;
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->Ban(GetPlayer(), targetName);
}
void WorldSession::HandleChannelUnban(WorldPacket& recvPacket)
{
uint32 channelLength = recvPacket.ReadBits(7);
uint32 nameLength = recvPacket.ReadBits(8);
std::string targetName = recvPacket.ReadString(nameLength);
std::string channelName = recvPacket.ReadString(channelLength);
TC_LOG_DEBUG("chat.system", "CMSG_CHANNEL_UNBAN %s Channel: %s, Target: %s",
GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str());
if (!normalizePlayerName(targetName))
return;
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->UnBan(GetPlayer(), targetName);
}
void WorldSession::HandleChannelAnnouncements(WorldPacket& recvPacket)
{
uint32 length = recvPacket.ReadBits(8);
std::string channelName = recvPacket.ReadString(length);
TC_LOG_DEBUG("chat.system", "CMSG_CHANNEL_ANNOUNCEMENTS %s Channel: %s",
GetPlayerInfo().c_str(), channelName.c_str());
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->Announce(GetPlayer());
}
void WorldSession::HandleChannelDisplayListQuery(WorldPacket &recvPacket)
{
// this should be OK because the 2 function _were_ the same
HandleChannelList(recvPacket);
}
void WorldSession::HandleGetChannelMemberCount(WorldPacket &recvPacket)
{
std::string channelName;
recvPacket >> channelName;
TC_LOG_DEBUG("chat.system", "CMSG_GET_CHANNEL_MEMBER_COUNT %s Channel: %s",
GetPlayerInfo().c_str(), channelName.c_str());
if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeam()))
{
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
{
TC_LOG_DEBUG("chat.system", "SMSG_CHANNEL_MEMBER_COUNT %s Channel: %s Count: %u",
GetPlayerInfo().c_str(), channelName.c_str(), channel->GetNumPlayers());
WorldPacket data(SMSG_CHANNEL_MEMBER_COUNT, channel->GetName().size() + 1 + 4);
data << channel->GetName();
data << uint8(channel->GetFlags());
data << uint32(channel->GetNumPlayers());
SendPacket(&data);
}
}
}
void WorldSession::HandleSetChannelWatch(WorldPacket& recvPacket)
{
std::string channelName;
recvPacket >> channelName;
TC_LOG_DEBUG("chat.system", "CMSG_SET_CHANNEL_WATCH %s Channel: %s",
GetPlayerInfo().c_str(), channelName.c_str());
/*
if (ChannelMgr* cMgr = channelMgr(GetPlayer()->GetTeam()))
if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer()))
channel->JoinNotify(GetPlayer());
*/
}
| [
"pat_66696@hotmail.com"
] | pat_66696@hotmail.com |
2628d6eb6222f52290c648dfec0e921fdcfe67ee | a8653ca84ad1a72097efe80e1e214994e09cab1b | /src/core/common/exceptions/NotFoundError.h | 38c76a40320fa4159d42f0060887623a289529eb | [] | no_license | GEO-Protocol/GEO-network-client | c2d6069f15a833f4eea717b101de5602e5bf4de7 | daffc8d7e1e64b7ef3c0d27d807986b07adfff25 | refs/heads/develop | 2021-06-04T05:47:58.510637 | 2021-03-21T06:51:15 | 2021-03-21T06:51:15 | 59,763,647 | 16 | 5 | null | 2019-03-31T11:04:59 | 2016-05-26T15:54:47 | C | UTF-8 | C++ | false | false | 233 | h | #ifndef GEO_NETWORK_CLIENT_NOTFOUNDERROR_H
#define GEO_NETWORK_CLIENT_NOTFOUNDERROR_H
#include "Exception.h"
class NotFoundError: public Exception {
using Exception::Exception;
};
#endif //GEO_NETWORK_CLIENT_NOTFOUNDERROR_H
| [
"dima.chizhevsky@gmail.com"
] | dima.chizhevsky@gmail.com |
8c6d622016783b83b238d3527b9e1756078b04f6 | 96a6e4d55541d841f1ea5863099daaf7e4ade012 | /Images/src/ImagesApp.cpp | b29cb6954e8d2dc09d57a28f1495a2f2befe2bb6 | [] | no_license | KarmicDemon/Cinder-Basics | b6a40b589af5628be42bafdc2a570ee2b1ed3a19 | b6842fe49e4dc0cbcaa2e182239123547f96e7fd | refs/heads/master | 2021-01-20T12:51:48.342135 | 2017-05-16T18:46:00 | 2017-05-16T18:46:00 | 90,419,334 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,705 | cpp | #include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/gl/Texture.h"
#include "cinder/ImageIo.h"
#include "Resources.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class ImagesApp : public App {
public:
void draw() override;
void keyDown(KeyEvent event) override;
void setup() override;
private:
gl::TextureRef picture;
gl::TextureRef res;
gl::TextureRef original;
gl::TextureRef red;
gl::TextureRef green;
gl::TextureRef blue;
gl::TextureRef current;
enum class ShowMode {
Complete, Red, Green, Blue
};
ShowMode showMode;
gl::TextureRef texture;
};
void ImagesApp::setup() {
picture = gl::Texture::create(loadImage(loadAsset("karma.jpg")));
res = gl::Texture::create(loadImage(loadResource(RES_KARMA)));
Surface image = loadImage(loadResource(RES_KARMA));
Surface redImage = image.clone();
Surface::Iter redIter = redImage.getIter();
while (redIter.line()) {
while (redIter.pixel()) {
redIter.g() = 0;
redIter.b() = 0;
}
}
Surface greenImage = image.clone();
Surface::Iter greenIter = greenImage.getIter();
while (greenIter.line()) {
while (greenIter.pixel()) {
greenIter.r() = 0;
greenIter.b() = 0;
}
}
Surface blueImage = image.clone();
Surface::Iter blueIter = blueImage.getIter();
while (blueIter.line()) {
while (blueIter.pixel()) {
blueIter.r() = 0;
blueIter.g() = 0;
}
}
original = gl::Texture::create(image);
red = gl::Texture::create(redImage);
green = gl::Texture::create(greenImage);
blue = gl::Texture::create(blueImage);
//current = original;
showMode = ShowMode::Complete;
}
void ImagesApp::draw() {
gl::clear( Color( 0, 0, 0 ) );
//loading from assets
//gl::draw(picture, getWindowBounds());
//loading from resources
//gl::draw(res, getWindowBounds());
//surfaces and showing individual primary color models
//gl::draw(current, getWindowBounds());
//texture primary color models
switch (showMode) {
case ShowMode::Complete:
gl::color(1, 1, 1);
break;
case ShowMode::Red:
gl::color(1, 0, 0);
break;
case ShowMode::Green:
gl::color(0, 1, 0);
break;
case ShowMode::Blue:
gl::color(0, 0, 1);
break;
}
gl::draw(res, getWindowBounds());
}
void ImagesApp::keyDown(KeyEvent event) {
const char ch = event.getChar();
switch (ch) {
case 'r':
showMode = ShowMode::Red;
current = red;
break;
case 'g':
showMode = ShowMode::Green;
current = green;
break;
case 'b':
showMode = ShowMode::Blue;
current = blue;
break;
case 'a':
showMode = ShowMode::Complete;
current = original;
break;
default:
break;
}
}
CINDER_APP( ImagesApp, RendererGl )
| [
"uchederek@yahoo.com"
] | uchederek@yahoo.com |
157c8025960f89f7af56795745e8e5f17828abe9 | d8260015c8ea8b003f72b3d9f06cae50629520dc | /LTexture.h | 5e3ed322077d684d5fa7cf6504770d2c7855223d | [] | no_license | PrzemekTomczyk/online-gaming-tag-proj | a246745a9d4b7e9a4ca938a4b190d33091874433 | 643cafd7336fedb354bf44765b6312b7d370fce2 | refs/heads/master | 2020-09-24T21:10:28.872407 | 2019-12-12T16:57:33 | 2019-12-12T16:57:33 | 225,844,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,083 | h | #pragma once
#include <string>
#include <SDL.h>
#include <SDL_image.h>
class LTexture
{
public:
//Initializes variables
LTexture();
//Deallocates memory
~LTexture();
//Loads image at specified path
bool loadFromFile(std::string path, SDL_Renderer *gRenderer);
#ifdef _SDL_TTF_H
//Creates image from font string
LTexture(string fontpath);
bool loadFromRenderedText(std::string textureText, SDL_Color textColor, SDL_Renderer *gRenderer);
TTF_Font *gFont;
#endif
//Deallocates texture
void free();
//Set color modulation
void setColor(Uint8 red, Uint8 green, Uint8 blue);
//Set blending
void setBlendMode(SDL_BlendMode blending);
//Set alpha modulation
void setAlpha(Uint8 alpha);
//Renders texture at given point
void render(int x, int y, SDL_Renderer *gRenderer = NULL, SDL_Rect* clip = NULL, double angle = 0.0, SDL_Point* center = NULL, SDL_RendererFlip flip = SDL_FLIP_NONE);
//Gets image dimensions
int getWidth();
int getHeight();
private:
//The actual hardware texture
SDL_Texture* mTexture;
//Image dimensions
int mWidth;
int mHeight;
}; | [
"C00218004@itcarlow.ie"
] | C00218004@itcarlow.ie |
687dc9b4df4943134a662849e2538264ce8f96d3 | c65ac57d233a317fc31ad08401d69dbacb713784 | /src/Statut.cpp | 9382c3f4866a24f4cebb99cc1f62864f0aaaa83f | [] | no_license | gionko/ZeldaROTH | 3816c515d939c43c8202c8c0d8085c9d8413c317 | 25250fe58bfb7f66278d99aa957ea0606b98a82c | refs/heads/master | 2021-04-09T20:13:50.918886 | 2016-06-11T20:46:26 | 2016-06-11T20:46:26 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 8,157 | cpp | /*
Zelda Return of the Hylian
Copyright (C) 2005-2008 Vincent Jouillat
Please send bugreports with examples or suggestions to www.zeldaroth.fr
*/
#include "Statut.h"
#include "Joueur.h"
#include "Monde.h"
#include "Menu.h"
#include "Texte.h"
#include "Projectile.h"
#include "Jeu.h"
#include "3ds/gfx_3ds.h"
#include <iostream>
Statut::Statut(Jeu* jeu) : gpJeu(jeu), jauge(false), valjauge(0), maxjauge(10), nivjauge(50) {
imageStatut = IMG_Load("romfs:/images/statut/statut.png");
imageChiffre = IMG_Load("romfs:/images/statut/chiffres.png");
imageInventaire = IMG_Load("romfs:/images/statut/inventaire.png");
SDL_SetColorKey(imageStatut,SDL_SRCCOLORKEY,SDL_MapRGB(imageStatut->format,0,0,255));
SDL_SetColorKey(imageChiffre,SDL_SRCCOLORKEY,SDL_MapRGB(imageChiffre->format,0,0,255));
}
Statut::~Statut() {
SDL_FreeSurface(imageStatut);
SDL_FreeSurface(imageChiffre);
SDL_FreeSurface(imageInventaire);
}
void Statut::draw(SDL_Surface* gpScreen) {
drawBoss(gpScreen);
drawItems(gpScreen);
drawVie(gpScreen);
drawMagie(gpScreen);
}
void Statut::drawBoss(SDL_Surface* gpScreen) {
SDL_Rect src;
SDL_Rect dst;
//jauge vie boss
if (valjauge<0) valjauge=0;
if (jauge==false) valjauge=0;
if (jauge==true || nivjauge<50) {
if (jauge==true && valjauge>0 && nivjauge>0) nivjauge--;
if (jauge==false && nivjauge<50) nivjauge++;
src.h = 10;src.w = 100;
dst.x = 110;dst.y = 220+nivjauge;
src.x=100;src.y=45;
SDL_BlitSurface(imageStatut, &src, gpScreen, &dst);
if (maxjauge==0) maxjauge=1;
if(valjauge>maxjauge) valjauge = maxjauge;
src.w = (valjauge*90)/maxjauge;src.h = 10;
dst.x = 115;dst.y = 220+nivjauge;
src.x=5+90-src.w;src.y=45;
SDL_BlitSurface(imageStatut, &src, gpScreen, &dst);
}
}
void Statut::drawMagie(SDL_Surface* gpScreen) {
SDL_Rect src;
SDL_Rect dst;
Joueur* gpJoueur = gpJeu->getJoueur();
bool oni = gpJoueur->getOnilink();
//jauge oni
if (oni) {
src.h = 45;src.w = 10;
dst.x = 10;dst.y = 10;
src.x=212;src.y=0;
SDL_BlitSurface(imageStatut, &src, gpScreen, &dst);
src.h = (gpJoueur->getOnijauge()*32)/gpJoueur->getOnimax();src.w = 8;
dst.x = 10;dst.y = 18+32-((gpJoueur->getOnijauge()*32)/gpJoueur->getOnimax());
src.x=202;src.y=8;
SDL_BlitSurface(imageStatut, &src, gpScreen, &dst);
}
//jauge magie
if (gpJoueur->hasObjet(O_LANTERNE)) {
src.h = 45; src.w = 16; src.x = 0; src.y = 0;
if (oni) dst.x=20; else dst.x = 10; dst.y = 10;
SDL_BlitSurface(imageStatut, &src, gpScreen, &dst);
//demi magie
if (gpJoueur->getMagieMax()>32) {
src.h = 8; src.w = 16; src.x = 186; src.y = 37;
SDL_BlitSurface(imageStatut, &src, gpScreen, &dst);
}
src.h = (gpJoueur->getMagie()/(gpJoueur->getMagieMax()/32));src.w = 8;
if (oni) dst.x=24; else dst.x = 14;
dst.y = 50-(gpJoueur->getMagie()/(gpJoueur->getMagieMax()/32));
src.x=124;src.y=8;
SDL_BlitSurface(imageStatut, &src, gpScreen, &dst);
}
//emplacement objet
if (gpJoueur->hasObjet(O_SAC_BOMBES) || gpJoueur->hasBouteille(0)) {
src.h = 22;src.w = 22; src.x=17; src.y=5;
if (oni) dst.x=37; else dst.x = 27; dst.y = 15;
SDL_BlitSurface(imageStatut, &src, gpScreen, &dst);
}
src.h = 17;src.w = 16;
if (oni) dst.x=40; else dst.x = 30; dst.y = 15;;dst.y=18;
//bool test=false;
switch (gpJoueur->getObjet()) {
case 0 : src.x=0; src.y=0; if (gpJoueur->hasObjet(O_ARC)==2)src.y=85; break;
case 1 : src.x=16; src.y=0; break;
case 2 : src.x=32; src.y=0; break;
case 3 : src.x=0; src.y=17; break;
case 4 : src.x=16; src.y=17; break;
case 5 : src.x=32; src.y=17; break;
case 6 : src.x=0; src.y=34; break;
case 7 : src.x=16; src.y=34; break;
case 8 : src.x=32; src.y=34; if (gpJoueur->hasObjet(O_GANTS)==1)src.y=85; break;
default :
src.x=0;
if(gpJoueur->hasBouteille(gpJoueur->getObjet()-9)==3)src.x=16;
if(gpJoueur->hasBouteille(gpJoueur->getObjet()-9)==4)src.x=32;
if(gpJoueur->hasBouteille(gpJoueur->getObjet()-9)>1)src.y=51;
if(gpJoueur->hasBouteille(gpJoueur->getObjet()-9)==1)src.y=68;
break;
}
if(gpJoueur->getObjet() < 9) {
if (gpJoueur->hasObjet(gpJoueur->getObjet()))
if (gpJoueur->getObjet() != 2 || gpJoueur->getBombe())
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
}
else {
if(gpJoueur->hasBouteille(gpJoueur->getObjet()-9))
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
}
}
void Statut::drawVie(SDL_Surface* gpScreen) {
SDL_Rect src;
SDL_Rect dst;
Joueur* gpJoueur = gpJeu->getJoueur();
//life
src.h = 7;src.w = 44;
dst.x = 250;dst.y = 10;
src.x=158;src.y=0;
SDL_BlitSurface(imageStatut, &src, gpScreen, &dst);
for(int i=0; i < gpJoueur->getVieMax()/2; i++) {
src.h = 7; src.w = 7;
dst.x = 233+((i%10)*8);dst.y = 19+8*((int)(i/10));
src.y=9;
if (gpJoueur->getVie()-(i*2)>1)src.x=141;
if (gpJoueur->getVie()-(i*2)==1)src.x=149;
if (gpJoueur->getVie()-(i*2)<1)src.x=157;
SDL_BlitSurface(imageStatut, &src, gpScreen, &dst);
}
}
void Statut::drawItems(SDL_Surface* gpScreen) {
SDL_Rect src;
SDL_Rect dst;
Joueur* gpJoueur = gpJeu->getJoueur();
//rubis
src.h = 8;src.w = 8;
dst.x =129;dst.y = 10;
src.x=52;src.y=0;
SDL_BlitSurface(imageStatut, &src, gpScreen, &dst);
if (gpJoueur->getRubisMax() > 99)
drawNombre(gpScreen, gpJoueur->getRubis(), gpJoueur->getRubisMax(),121,20,3);
else
drawNombre(gpScreen, gpJoueur->getRubis(), gpJoueur->getRubisMax(),121,20,2);
//bombes
if (gpJoueur->hasObjet(O_SAC_BOMBES)) {
src.h = 8;src.w = 8;
dst.x =157;dst.y = 10;
src.x=80;src.y=0;
SDL_BlitSurface(imageStatut, &src, gpScreen, &dst);
drawNombre(gpScreen, gpJoueur->getBombe(), gpJoueur->getBombeMax(),153,20,2);
}
//fleches
if (gpJoueur->hasObjet(O_ARC)) {
src.h = 8;src.w = 14;
dst.x =178;dst.y = 10;
src.x=101;
if (gpJoueur->hasObjet(O_ARC) == 5) src.y=21; else src.y=0;
SDL_BlitSurface(imageStatut, &src, gpScreen, &dst);
drawNombre(gpScreen, gpJoueur->getFleche(), gpJoueur->getFlecheMax(),177,20,2);
}
//clées
if (gpJeu->isDonjon()) {
src.h = 8;src.w = 8;
dst.x =89;dst.y = 10;
src.x=50;src.y=28;
SDL_BlitSurface(imageStatut, &src, gpScreen, &dst);
if (gpJoueur->getCle() > 9)
drawNombre(gpScreen, gpJoueur->getCle(), 99,81,20,2);
else
drawNombre(gpScreen, gpJoueur->getCle(), 99,89,20,1);
}
}
void Statut::drawNombre(SDL_Surface* gpScreen, int val, int max, int x, int y, int nb) {
int val2;
SDL_Rect src;
SDL_Rect dst;
src.h = 8;src.w = 8;
dst.x = x;dst.y = y;
//si on commence par les centaines
if (nb >= 3) {
val2 = val/100;
src.x = (val2%5)*8;
src.y = ((int)(val2/5))*8;
if (val == max) src.y += 16;
SDL_BlitSurface(imageChiffre, &src, gpScreen, &dst);
dst.x += 8;
}
//les dizaines
if (nb >= 2) {
val2 = (val%100)/10;
src.x = (val2%5)*8;
src.y = ((int)(val2/5))*8;
if (val == max) src.y += 16;
SDL_BlitSurface(imageChiffre, &src, gpScreen, &dst);
dst.x += 8;
}
//unitées
val2 = val%10;
src.x = (val2%5)*8;
src.y = ((int)(val2/5))*8;
if (val == max) src.y += 16;
SDL_BlitSurface(imageChiffre, &src, gpScreen, &dst);
}
void Statut::setJauge(bool b) {jauge=b;}
void Statut::setValJauge(int i) {valjauge=i;}
void Statut::setMaxJauge(int i) {maxjauge=i;}
| [
"nop90nop90@gmail.com"
] | nop90nop90@gmail.com |
31464de2e5408303e52af1b7689e79c47a6abb28 | ad2dceb884ae1538d6b2a02ea0c76fffd6226014 | /graph.cpp | e1ee20a17329484e9c196304447477d87ca5bcb2 | [] | no_license | TitovIe/diplom_new | 2bf34ec7c105efa6b642bbd339e811b3c827756b | 286d7f36aa947018cc7571e6ab77dd2d591a8880 | refs/heads/master | 2020-06-01T10:39:49.866006 | 2019-06-07T13:59:40 | 2019-06-07T13:59:40 | 190,752,024 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,412 | cpp | #include "graph.h"
Graph::Graph(mt19937& gen){
Gen_Ji_start_vector(gen);
Gen_sigma_vector(gen);
}
void Graph::Gen_sigma_vector(mt19937 &gen) {
MonteCarlo(sigmai_vector, gen);
}
/*Генерируем стартовые векторы Jij и pij*/
void Graph::Gen_Ji_start_vector(mt19937& gen){
uniform_real_distribution<double>
urd_right(Graph::alfa, Graph::beta);
uniform_real_distribution<double>
urd_left(-Graph::beta, -Graph::alfa);
uniform_int_distribution<int> urd_false_true(0, 1);
Ji_vector.reserve(Graph::N);
constraint_vector.reserve(Graph::N);
vector<double> Jij_start_vector(Graph::N - 1);
vector<double> constraint_start_vector(Graph::N - 1);
for(int k = 0; k < Graph::N; k++){
Ji_vector.push_back(Jij_start_vector);
constraint_vector.push_back(constraint_start_vector);
}
for(int i = 0; i < Graph::N; i++) {
for (int j = i; j < Graph::N - 1; j++) {
if (urd_false_true(gen) == 0) {
Ji_vector[i][j] = urd_left(gen);
} else Ji_vector[i][j] = urd_right(gen);;
Ji_vector[j + 1][i] = Ji_vector[i][j];
constraint_vector[i][j] = 1 / lambda * Ji_vector[i][j];
constraint_vector[j + 1][i] = constraint_vector[i][j];
}
}
}
//Генерация M выборок спинов методом метрополиса
void MonteCarlo(vector<vector<int>>& samples, mt19937 &gen){
uniform_int_distribution<int> urd_false_true(0, 1);
uniform_real_distribution<double> probability(0, 1);
uniform_int_distribution<int> choise_spin(0, Graph::N - 1);
const int T = 273;
const double k = 1.38 * pow(10, -23);
const double beta = 1/k/T;
const int number_step = 100;
int number_spin;
double E_prev, E_after, E_delta;
// Данные, которые хотим получить
vector<vector<double>> Jij_true;
Jij_true.push_back({0.7, 0, 0});
Jij_true.push_back({0.7, 0.41, -0.99});
Jij_true.push_back({0, 0.41, 0.5});
Jij_true.push_back({0, -0.99, 0.5});
// Jij_true.push_back({0.7, 0, 0.5, 0, 0.6, -0.4, 0.59, 0.8});
// Jij_true.push_back({0.7, 0.41, 0, -0.8, 0, 0.6, -0,5, 0.8});
// Jij_true.push_back({0, 0.41, 0, -0.5, 0, 0, 0.5, 0});
// Jij_true.push_back({0.5, 0, 0, 0.4, -0.46, 0, 0, -0.8});
// Jij_true.push_back({0, -0.8, -0.5, 0.4, 0.9, -0.55, 0, -0.7});
// Jij_true.push_back({0.6, 0, 0, -0.46, 0.9, 0, 0.9, 0});
// Jij_true.push_back({-0.4, 0.6, 0, 0, -0.55, 0, 0, 0});
// Jij_true.push_back({0.59, -0.5, 0.5, 0, 0, 0.9, 0, 0});
// Jij_true.push_back({0.8, 0.8, 0, -0.8, -0.7, 0, 0, 0});
// Начальная конфигурация рандомно заполняется
vector<int> sigma_vector;
for (int j = 0; j < Graph::N; j++) {
if (urd_false_true(gen) == 0)
sigma_vector.push_back(-1);
else
sigma_vector.push_back(1);
}
/*Генерируем M выборок. Каждая новая конфигурация - через 100 итераций.
* Каждая итерацию выбираем какой то узел и с вероятностью 50% делаем следующие операции.
* Считаем энергию системы с текущим значением спина. Переворачиваем его
* и снова считаем. Если deltaЕ < 0, оставляем перевернутым. В противном случае
* с вероятностью ext(-beta * E_delta) оставляем перевернутым. */
for(int j = 0; j < Graph::M; j++) {
for (int i = 0; i < number_step; i++){
if(probability(gen) < 0.5)
continue;
number_spin = choise_spin(gen);
E_prev = Jij_sum_calc(Jij_true, sigma_vector);
sigma_vector[number_spin] *= -1;
E_after = Jij_sum_calc(Jij_true, sigma_vector);
E_delta = E_after - E_prev;
if(E_delta > 0){
if(probability(gen) > exp(-beta * E_delta))
sigma_vector[number_spin] *= -1;
}
}
samples.push_back(sigma_vector);
}
}
//Считаем энергию системы
double Jij_sum_calc(const vector<vector<double>>& Jij_vector,
const vector<int>& sigma_vector){
double Jij_sum = 0;
for(int i = 0; i < Jij_vector.size(); i++){
for(int j = i, k = j + 1; j < Jij_vector[i].size(); j++, k++){
Jij_sum += -Jij_vector[i][j]
* sigma_vector[i]
* sigma_vector[k];
}
}
return Jij_sum;
}
vector<vector<int>>& Graph::Get_m_samples() {
return sigmai_vector;
}
vector<vector<double>>& Graph::Get_Ji_vector() {
return Ji_vector;
}
void Graph::Print_Ji() {
for(const auto& i : Get_Ji_vector()){
cout << i << endl;
}
cout << endl;
}
void Graph::Print_sigma_all() {
for(const auto& sample : sigmai_vector)
Print_sigma_sample(sample);
}
void Graph::Print_sigma_sample(const vector<int>& sample) {
for(const auto& i : sample) {
cout << i << " ";
}
cout << endl;
}
vector<vector<double>>& Graph::Get_constraint_vector() {
return constraint_vector;
}
ostream& operator << (ostream& os, const vector<double>& v) {
for (const auto &j : v) {
os.width(10);
os << j << " ";
}
return os;
}
Graph& GetClobalObject()
{
static mt19937 gen(time(0));
static Graph graph(gen);
return graph;
}
/*Приводим к нулю Jij такие,которые < alfa/2 */
void Jij_to_zero(Graph& g){
for(int i = 0; i < Graph::N; i++){
for(int j = i; j < Graph::N - 1; j++){
g.Get_Ji_vector()[i][j] = (g.Get_Ji_vector()[i][j]
+ g.Get_Ji_vector()[j + 1][i]) / 2;
if(g.Get_Ji_vector()[i][j] > -Graph::alfa / 2
&& g.Get_Ji_vector()[i][j] < Graph::alfa / 2)
g.Get_Ji_vector()[i][j] = 0;
g.Get_Ji_vector()[j + 1][i] = g.Get_Ji_vector()[i][j];
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
41a902d61af2ca77304b3ba3858314c80ba16074 | f66ca7e6d96638d129c73e4dab57223ee57bd7fe | /SortArrayByParity/sort_array_by_parity_2.cpp | 82206306a65dd48cb2187c04d871939bc5272821 | [
"MIT"
] | permissive | suzyz/leetcode_practice | e4a5ab30b60318dc087452daef7dab51727d396a | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | refs/heads/master | 2021-01-19T01:17:49.194902 | 2019-01-12T13:27:56 | 2019-01-12T13:27:56 | 95,619,304 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 361 | cpp | // in place
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
int n = A.size();
int i = 0;
for (int j = 0; j < n; ++j)
if (A[j]%2 == 0) {
int tmp = A[j];
A[j] = A[i];
A[i] = tmp;
i++;
}
return A;
}
}; | [
"suzyzhang0@gmail.com"
] | suzyzhang0@gmail.com |
1a0a3f375999e291560c94bf4125ff1170acb01a | 7f62f204ffde7fed9c1cb69e2bd44de9203f14c8 | /DboServer/Server/GameServer/SpawnObject.cpp | 3ef28abc9829e012a20a1635f30d0cec2f17eb46 | [] | no_license | 4l3dx/DBOGLOBAL | 9853c49f19882d3de10b5ca849ba53b44ab81a0c | c5828b24e99c649ae6a2953471ae57a653395ca2 | refs/heads/master | 2022-05-28T08:57:10.293378 | 2020-05-01T00:41:08 | 2020-05-01T00:41:08 | 259,094,679 | 3 | 3 | null | 2020-04-29T17:06:22 | 2020-04-26T17:43:08 | null | UTF-8 | C++ | false | false | 8,748 | cpp | #include "stdafx.h"
#include "CPlayer.h"
#include "NtlPacketGU.h"
#include "NtlStringW.h"
CSpawnObject::CSpawnObject(eOBJTYPE eObjType)
:CGameObject(eObjType)
{
Init();
m_vCurLoc = CNtlVector::ZERO;
m_vCurDir = CNtlVector::ZERO;
m_worldLinker.SetOwner(this);
m_worldCellLinker.SetOwner(this);
m_worldZoneLinker.SetOwner(this);
}
CSpawnObject::~CSpawnObject()
{
if (!m_bIsDeleted)
this->Destroy();
}
//--------------------------------------------------------------------------------------//
// SPAWN MY OBJECT
//--------------------------------------------------------------------------------------//
void CSpawnObject::EncodeInsertPacket(CPlayer* pPlayer)
{
//if (pPlayer->GetVisibleCount() > NTL_MAX_NUMBER_OF_PLAYERS_IN_VISIBLE_AREA)
// return;
if (pPlayer->IsVisible(GetID()) == false)
{
pPlayer->AddVisibleObject(GetID());
CNtlPacket packet(sizeof(sGU_OBJECT_CREATE));
sGU_OBJECT_CREATE * res = (sGU_OBJECT_CREATE *)packet.GetPacketData();
res->wOpCode = GU_OBJECT_CREATE;
res->handle = GetID();
res->sObjectInfo.objType = GetObjType();
CopyToObjectInfo(&res->sObjectInfo, pPlayer->GetCharID());
packet.SetPacketLen(sizeof(sGU_OBJECT_CREATE));
pPlayer->SendPacket(&packet);
}
}
//--------------------------------------------------------------------------------------//
// REMOVE MY OBJECT
//--------------------------------------------------------------------------------------//
void CSpawnObject::EncodeRemovePacket(CPlayer* pPlayer)
{
if (!pPlayer || !pPlayer->IsInitialized())
return;
if (pPlayer->IsVisible(GetID()))
{
pPlayer->RemoveVisibleObject(GetID());
CNtlPacket packet(sizeof(sGU_OBJECT_DESTROY));
sGU_OBJECT_DESTROY * sPacket = (sGU_OBJECT_DESTROY *)packet.GetPacketData();
sPacket->handle = GetID();
sPacket->wOpCode = GU_OBJECT_DESTROY;
packet.SetPacketLen(sizeof(sGU_OBJECT_DESTROY));
pPlayer->SendPacket(&packet);
}
}
bool CSpawnObject::Create()
{
return CGameObject::Create();
}
void CSpawnObject::Destroy()
{
}
void CSpawnObject::Init()
{
m_worldID = INVALID_WORLDID;
m_bIsLocValidityChecked = false;
mapNameTblidx = INVALID_TBLIDX;
m_pCurWorld = nullptr;
m_pCurWorldCell = nullptr;
m_pCurWorldZone = nullptr;
}
bool CSpawnObject::IsLocInWorldBoundary(CNtlVector& rLoc, CWorld* pWorld)
{
if (pWorld)
{
if(pWorld->IsInBoundary(rLoc))
return true;
if (!m_bIsLocValidityChecked)
{
ERR_LOG(LOG_USER, "rLoc is invalid location., ObjType[%u], GetID() = %u, rLoc = (%f, %f, %f), pWorld->GetID() = %u", GetObjType(), GetID(), rLoc.x, rLoc.y, rLoc.z, pWorld->GetID());
m_bIsLocValidityChecked = true;
}
return false;
}
return true;
}
void CSpawnObject::OnEnterWorld(CWorld* pWorld)
{
m_pCurWorld = pWorld;
}
void CSpawnObject::OnLeaveWorld(CWorld* pWorld)
{
m_pCurWorld = NULL;
}
void CSpawnObject::OnEnterWorldCell(CWorldCell* pWorldCell)
{
if (pWorldCell)
{
m_pCurWorldCell = pWorldCell;
m_pCurWorldCell->AddObject(this);
if (IsPC())
pWorldCell->UpdateNearbyPlayerCount_Enter();
}
}
void CSpawnObject::OnLeaveWorldCell(CWorldCell* pWorldCell)
{
if (m_pCurWorldCell)
{
if (IsPC())
{
if (m_pCurWorldCell == pWorldCell)
pWorldCell->UpdateNearbyPlayerCount_Leave();
else
{
ERR_LOG(LOG_USER, "m_pCurWorldCell != pWorldCell");
}
}
m_pCurWorldCell->RemoveObject(this);
m_pCurWorldCell = NULL;
}
}
void CSpawnObject::OnEnterWorldZone(CWorldZone* pWorldZone)
{
if (pWorldZone)
{
m_pCurWorldZone = pWorldZone;
pWorldZone->AddObject(this);
}
else
{
ERR_LOG(LOG_SYSTEM, "pWorldZone == NULL");
}
}
void CSpawnObject::OnLeaveWorldZone(CWorldZone* pWorldZone)
{
if (pWorldZone)
{
pWorldZone->RemoveObject(this);
m_pCurWorldZone = NULL;
}
}
void CSpawnObject::OnEnterWorldComplete()
{
}
bool CSpawnObject::SetCurLoc(sVECTOR3& loc, CWorld *pDestWorld/*= NULL*/)
{
CNtlVector rVec(loc);
if (IsLocInWorldBoundary(rVec, pDestWorld))
m_vCurLoc = loc;
else
return false;
return true;
}
bool CSpawnObject::SetCurLoc(CNtlVector& loc, CWorld *pDestWorld/*= NULL*/)
{
if (IsLocInWorldBoundary(loc, pDestWorld))
m_vCurLoc = loc;
else
return false;
//if (IsPC())
//{
// printf("%f %f %f | %f %f %f \n", m_vCurLoc.x, m_vCurLoc.y, m_vCurLoc.z, loc.x, loc.y, loc.z);
//}
return true;
}
void CSpawnObject::Broadcast(CNtlPacket* pPacket, CSpawnObject* except)
{
if (m_pCurWorldCell)
m_pCurWorldCell->Broadcast(pPacket, except, false);
else
{
if (IsPC())
SendPacket(pPacket);
}
}
void CSpawnObject::BroadcastToNeighbor(CNtlPacket* pPacket)
{
if (m_pCurWorldCell)
m_pCurWorldCell->Broadcast(pPacket, this, false);
}
//WORLDID CSpawnObject::GetWorldID()
//{
// if (m_pCurWorld)
// return m_pCurWorld->GetID();
//
// return INVALID_WORLDID;
//}
TBLIDX CSpawnObject::GetWorldTblidx()
{
if (m_pCurWorld)
return m_pCurWorld->GetIdx();
return INVALID_TBLIDX;
}
bool CSpawnObject::IsInRange(CNtlVector& rLoc, float fRange)
{
CNtlVector result(rLoc - GetCurLoc());
result.y = 0.0f;
//if (IsPC())
// printf("result.SquaredLength() %f range %f\n", result.SquaredLength(), fRange * fRange);
return result.SquaredLength() <= (fRange*fRange);
}
bool CSpawnObject::IsInRange(CSpawnObject* pTarget, float fRange)
{
if (m_worldID == pTarget->GetWorldID())
{
return IsInRange(pTarget->GetCurLoc(), fRange);
}
return false;
}
bool CSpawnObject::IsInRange3(CNtlVector& rLoc, float fRange)
{
CNtlVector result(rLoc - GetCurLoc());
return result.SquaredLength() <= (fRange*fRange);
}
bool CSpawnObject::IsInRange3(CSpawnObject* pTarget, float fRange)
{
if (m_worldID == pTarget->GetWorldID())
{
return IsInRange3(pTarget->GetCurLoc(), fRange);
}
return false;
}
bool CSpawnObject::IsInRangeWithTolerance(CNtlVector& rLoc, float fRange, float fTolerance)
{
return IsInRange(rLoc, fRange + fTolerance);
}
bool CSpawnObject::IsOutRange(CNtlVector& rLoc, float fRange)
{
CNtlVector result(rLoc);
result.operator-=(GetCurLoc());
result.y = 0;
return fRange <= result.Length();
}
bool CSpawnObject::IsOutRangeWithTolerance(CNtlVector& rLoc, float fRange, float fTolerance)
{
if (fRange <= 10.0f)
return true;
return IsOutRange(rLoc, fRange - 10.0f);
}
float CSpawnObject::GetDistance(CSpawnObject* pTarget)
{
return GetDistance(pTarget->GetCurLoc()) - (GetObjectRadius() + pTarget->GetObjectRadius());
}
float CSpawnObject::GetDistance(CNtlVector& rLoc)
{
CNtlVector vTemp(rLoc - GetCurLoc());
vTemp.y = 0.0f;
return vTemp.Normalize();
}
float CSpawnObject::GetDistance3(CNtlVector & rLoc)
{
CNtlVector vTemp(rLoc - GetCurLoc());
return vTemp.Normalize();
}
bool CSpawnObject::IsFrontSide(CSpawnObject* pTarget)
{
CNtlVector vTemp, vDir;
float fValue;
vDir = GetCurDir() * GetObjectRadius();
vTemp = GetCurLoc() + vDir;
vTemp = pTarget->GetCurLoc() - vTemp;
vTemp.y = 0.0f;
vDir = GetCurDir();
vDir.y = 0.0f;
fValue = vDir.Dot(vTemp);
return fValue >= 0.0f;
}
bool CSpawnObject::IsInDegreeAngle(CSpawnObject* pTarget, int nDegree)
{
int nNewDegree = 0;
CNtlVector vCurDir, vStandard, vTemp;
if (nDegree < 0)
nNewDegree = 360 - -nDegree % 360;
else
nNewDegree = nDegree % 360;
vCurDir = GetCurDir();
vCurDir.y = 0.0f;
vCurDir.SafeNormalize();
vCurDir *= GetObjectRadius();
vTemp = GetCurLoc() + vCurDir;
RotateVector(vStandard, &vCurDir, ConvertDegreeToRadian(nNewDegree / 2));
vTemp = pTarget->GetCurLoc() - vTemp;
vTemp.y = 0.0f;
vTemp.SafeNormalize();
return vCurDir.Dot(vTemp) >= vCurDir.Dot(vStandard);
}
bool CSpawnObject::IsInRangeFront(CSpawnObject* pTarget, float fRange)
{
if (IsInRange(pTarget, fRange))
return IsFrontSide(pTarget);
return false;
}
bool CSpawnObject::IsInRangeBack(CSpawnObject* pTarget, float fRange)
{
if (IsInRange(pTarget, fRange))
{
return IsFrontSide(pTarget) == false;
}
return false;
}
void CSpawnObject::GetPcInRange(float fRange, std::vector<CPlayer*>& rVec)
{
CWorldCell* pWorldCell = GetCurWorldCell();
if (pWorldCell)
{
int nLoopCount = 0;
CWorldCell::QUADPAGE page = pWorldCell->GetCellQuadPage(GetCurLoc());
for (int dir = CWorldCell::QUADDIR_SELF; dir <= CWorldCell::QUADDIR_VERTICAL; dir++)
{
CWorldCell* pWorldCellSibling = pWorldCell->GetQuadSibling(page, (CWorldCell::QUADDIR)dir);
if (pWorldCellSibling)
{
CPlayer* pTarget = (CPlayer*)pWorldCellSibling->GetObjectList()->GetFirst(OBJTYPE_PC);
while (pTarget && pTarget->IsInitialized())
{
++nLoopCount;
if (nLoopCount > 5000)
{
ERR_LOG(LOG_GENERAL, "INFINITE LOOP FOUND");
}
if (IsInRange(pTarget, fRange))
{
rVec.push_back(pTarget);
}
pTarget = (CPlayer*)pWorldCellSibling->GetObjectList()->GetNext(pTarget->GetWorldCellObjectLinker());
}
}
}
}
} | [
"64261665+dboguser@users.noreply.github.com"
] | 64261665+dboguser@users.noreply.github.com |
4740ee2fbee9148c2e7dc7be84b480cf3e6154c1 | 6a8c288232595d6bd3cdb016b5147cb2cda13b10 | /DataHiding/src/goodExample/sailBoatClass.cpp | a6fd8328969586883d09f513c35ff96105cee5a3 | [] | no_license | Mizzen-Mast/FoundationalPrinciplesofSecurity | 78455ebacdcd88f0cc8fad75e774c4e16bd1c4a6 | e5efbf3ad3b4905833a68a6b134169a66038ea81 | refs/heads/master | 2022-03-04T08:14:33.593623 | 2019-08-28T21:13:39 | 2019-08-28T21:13:39 | 107,818,444 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,269 | cpp | #include "sailBoat.h"
SailBoat::SailBoat() {
SailBoat::mastDiameter = 0;
SailBoat::mastLength = 0;
SailBoat::jibLength = 0;
SailBoat::boomLength = 0;
SailBoat::mainSailSize = 0;
SailBoat::backStaySize = 0;
SailBoat::keelWeight = 0;
SailBoat::windSpeed = 0;
SailBoat::mainSailDesignPattern = "Juliaset Fractal";
SailBoat::jibDesignPattern = "MandelBrot Fractal";
SailBoat::position = 0;
}
SailBoat::~SailBoat(){};
double SailBoat::getMastDiameter() {
return mastDiameter;
}
double SailBoat::getMastLength() {
return mastLength;
}
double SailBoat::getJibLength() {
return jibLength;
}
double SailBoat::getMainSailSize() {
return mainSailSize;
}
double SailBoat::getBackStaySize() {
return backStaySize;
}
double SailBoat::getKeelWeight() {
return keelWeight;
}
double SailBoat::getWindSpeed() {
return windSpeed;
}
double SailBoat::getPosition() {
return position;
}
std::string SailBoat::getMainSailDesignPattern() {
return mainSailDesignPattern;
}
std::string SailBoat::getJibDesignPattern() {
return jibDesignPattern;
}
//setters
double SailBoat::setMastDiameter(double setValue) {
mastDiameter=setValue;
return mastDiameter;
}
double SailBoat::setMastLength(double setValue) {
mastLength=setValue;
return mastLength;
}
double SailBoat::setJibLength(double setValue) {
jibLength=setValue;
return jibLength;
}
double SailBoat::setMainSailSize(double setValue) {
mainSailSize=setValue;
return mainSailSize;
}
double SailBoat::setBackStaySize(double setValue) {
backStaySize=setValue;
return backStaySize;
}
double SailBoat::setKeelWeight(double setValue) {
keelWeight=setValue;
return keelWeight;
}
double SailBoat::setWindSpeed(double setValue) {
windSpeed=setValue;
return keelWeight;
}
double SailBoat::setPosition(double setValue) {
position=setValue;
return position;
}
std::string SailBoat::setMainSailDesignPattern(std::string setValue) {
mainSailDesignPattern=setValue;
return mainSailDesignPattern;
}
std::string SailBoat::setJibDesignPattern(std::string setValue) {
jibDesignPattern=setValue;
return jibDesignPattern;
}
void SailBoat::sailTheBoat(double time){
double previousPosition = position;
position = previousPosition + (windSpeed * time);
}
| [
"kyle.clayson@gmail.com"
] | kyle.clayson@gmail.com |
43a5b1ac1be3c1fd2176c29db89bbaffa3244f90 | 4cd09308970bdf727bad48be671d2f00dd0e4ba2 | /include/circuits/FastGarbledBooleanCircuit.hpp | 067c2170e1030858a9912aefb9ad399b3416dba4 | [
"MIT"
] | permissive | zpleefly/libscapi | da1dce7deed4ed9cd7777c8551499d34116b9881 | 27d7d964d645ed111c2cc9870087971cf13e24f4 | refs/heads/master | 2022-07-21T18:25:14.557370 | 2018-11-04T09:54:18 | 2018-11-04T09:54:18 | 157,436,012 | 0 | 0 | MIT | 2022-07-06T20:57:49 | 2018-11-13T19:40:01 | C++ | UTF-8 | C++ | false | false | 20,538 | hpp | /**
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
* Copyright (c) 2016 LIBSCAPI (http://crypto.biu.ac.il/SCAPI)
* This file is part of the SCAPI project.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* 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.
*
* We request that any publication and/or code referring to and/or based on SCAPI contain an appropriate citation to SCAPI, including a reference to
* http://crypto.biu.ac.il/SCAPI.
*
* Libscapi uses several open source libraries. Please see these projects for any further licensing issues.
* For more information , See https://github.com/cryptobiu/libscapi/blob/master/LICENSE.MD
*
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
*/
#pragma once
//#include <ScGarbledCircuitNoFixedKey/GarbledBooleanCircuit.h>
//#include <ScGarbledCircuitNoFixedKey/FastGarblingFourToTwoNoAssumptions.h>
//#include <ScGarbledCircuitNoFixedKey/FastGarblingFreeXorHalfGatesFixedKeyAssumptions.h>
#include <ScGarbledCircuit/RowReductionGarbledBooleanCircuit.h>
#include <ScGarbledCircuit/StandardGarbledBooleanCircuit.h>
#include <ScGarbledCircuit/FreeXorGarbledBooleanCircuit.h>
#include <ScGarbledCircuit/HalfGatesGarbledBooleanCircuit.h>
#include "../infra/Common.hpp"
#include "BooleanCircuits.hpp"
#include <openssl/rand.h>
/**
* This is a general interface for garbled tables holder. <P>
* There are multiple ways to hold a garbled tables, each one of them will have a concrete class that implement this interface.
*/
class GarbledTablesHolder {
public:
/**
* There are cases when we do not know which concrete holder we use and we need a general function that returns the garbled tables.
* Thus we add this function that returns the tables in the most basic format - that all classes should have the ability to translate to - byte[][].
* @return the garbled tables in a byte[][] format.
*/
virtual byte** toDoubleByteArray() =0 ;
virtual int getArraySize(int arrIndex) = 0;
};
/**
* This class holds the garbled tables of the justGarbled circuit.<p>
* In just garbled the garbled tables is held in one dimensional byte array. Thus, when we wish to
* relate to it as a double byte array as held in SCAPI, we use a double byte array whose first location
* holds the one dimensional byte array.
* The garbled circuit will hold an instance of this class. <p>
* This way, when we want to change the garbled tables, we just have to change the pointer of the tables in this class.
*/
class JustGarbledGarbledTablesHolder : public GarbledTablesHolder {
private:
byte* garbledTables;
int size;
public:
/**
* Sets the given garbled tables.
* @param garbledTables
*/
JustGarbledGarbledTablesHolder(byte* garbledTables, int size) {
this->garbledTables = garbledTables;
this->size = size;
};
byte** toDoubleByteArray() override {
byte** garbledTablesInZeroLocation = new byte*[1];
garbledTablesInZeroLocation[0] = garbledTables;
return garbledTablesInZeroLocation;
};
/**
* Sets the given garbled tables. <P>
* This allows changing the circuit inner content with no time.
* @param garbledTables of the circuit.
*/
void setGarbledTables(byte* garbledTables, int size) {
this->garbledTables = garbledTables;
this->size = size;
};
int getArraySize(int arrIndex) override {
if (arrIndex != 0)
throw invalid_argument("JustGarbledGarbledTablesHolder has only one array");
return size;
};
};
/**
* A class that hold the values used to create the circuit. <p>
* These values are:<P>
* 1. Both keys of the input and the output wires.<p>
* 2. The translation table of the circuit.<p>
*/
class FastCircuitCreationValues {
private:
byte* allInputWireValues=NULL;
byte* allOutputWireValues = NULL;
byte* translationTable = NULL;
public:
FastCircuitCreationValues() {};
/**
* Sets the given arguments.
* @param allInputWireValues Both keys for all input wires.
* @param allOutputWireValues Both keys for all output wires.
* @param translationTable Signal bits of all output wires.
*/
FastCircuitCreationValues(byte* allInputWireValues, byte* allOutputWireValues, byte* translationTable) {
this->allInputWireValues = allInputWireValues;
this->allOutputWireValues = allOutputWireValues;
this->translationTable = translationTable;
}
byte* getAllInputWireValues() { return allInputWireValues; };
byte* getAllOutputWireValues() { return allOutputWireValues; };
byte* getTranslationTable() { return translationTable; };
};
/**
* {@code FastGarbledBooleanCircuit} is a general interface for all basic garbled circuits.
* Fast garbled boolean circuit includes the same functionality as the regular garbled boolean circuit
* but it does it faster due to simpler data structures.<p>
* As the garbledBooleanCircuit interface, fast garbled circuits have four main operations: <p>
* 1. The {@link #garble()} function that generates the keys and creates the garbled tables. <p>
* 2. The {@link #compute()} function computes a result on a garbled circuit whose input has been set. <p>
* 3. The {@link #verify(BooleanCircuit, Map)} method is used in the case of a malicious adversary to verify that the garbled circuit
* created is an honest garbling of the agreed upon non garbled circuit. For example, the constructing party constructs many garbled circuits and
* the second party chooses all but one of them to verify and test the honesty of the constructing party.<p>
* 4. The {@link #translate(Map)} that translates the garbled output from {@link #compute()} into meaningful output.<p>
*/
class FastGarbledBooleanCircuit {
public:
/**
* This method generates both keys for each wire. Then, creates the garbled table according to those values.<p>
* @return FastCircuitCreationValues contains both keys for each input and output wire and the translation table.
*/
virtual FastCircuitCreationValues garble()=0;
/**
* This method generates both keys for each input wire using the seed.
* It then creates the garbled table according to those values.<p>
* @param seed Used to initialize the prg.
* @return FastCircuitCreationValues Contains both keys for each input and output wire and the translation table.
*/
virtual FastCircuitCreationValues garble(byte * seed)=0;
/**
* This method takes an array containing the <b> non garbled</b> values, both keys for all input wires and the party number which the inputs belong to. <p>
* This method then performs the lookup on the allInputWireValues according to the party number and returns the keys
* of the corresponding input bits.
* @param ungarbledInputBits An array containing the <b> non garbled</b> value for each input wire of the given party number.
* @param allInputWireValues The array containing both garbled values (keys) for each input wire.
* The input values are placed one after another, meaning that the input values are in the following format:
* [k0,0 k0,1 k1,0 k1,1 k2,0 k2,1 ....] (while k0,1 is key 1 of wire 0).
* @param partyNumber The number of party which the inputs belong to.
* @return an array containing a single key of each input wire of the given party.
*/
virtual byte* getGarbledInputFromUngarbledInput(byte* ungarbledInputBits, byte* allInputWireValues, int partyNumber) = 0;
virtual void setInputs(vector<byte> & garbledInputs)=0;
/**
* This method computes the circuit using the given inputs. <p>
* It returns an array containing the garbled output. This output can be translated via the {@link #translate()} method.
* @param garbledInput A single key for each input wire.
* @return returns an array containing the garbled value of each output wire.
* @throws NotAllInputsSetException if the given inputs array does not includes a key for all input wires.
*/
virtual byte* compute() = 0;
/**
* The verify method is used in the case of malicious adversaries.<p>
* Alice constructs n circuits and Bob can verify n-1 of them (of his choice) to confirm that they are indeed garbling of the
* agreed upon non garbled circuit. In order to verify, Alice has to give Bob both keys for each of the input wires.
* @param allInputWireValues An array containing both keys for each input wire.
* The input values are placed one after another, meaning that the input values are in the following format:
* [k0,0 k0,1 k1,0 k1,1 k2,0 k2,1 ....] (while k0,1 is key 1 of wire 0).
* @return {@code true} if this {@code GarbledBooleanCircuit} is a garbling the given keys, {@code false} if it is not.
*/
virtual bool verify(byte* allInputWireValues) = 0;
/**
* This function behaves exactly as the verify(vector<byte> allInputWireValues) method except the last part.
* The verify function verifies that the translation table matches the resulted output garbled values, while this function does not check it
* but return the resulted output garbled values.
* @param allInputWireValues An array containing both keys for each input wire.
* The input values are placed one after another, meaning that the input values are in the following format:
* [k0,0 k0,1 k1,0 k1,1 k2,0 k2,1 ....] (while k0,1 is key 1 of wire 0).
* @param allOutputWireValues An array containing both keys for each output wire.
* The output values are placed one after another, meaning that the output values are in the following format:
* [k0,0 k0,1 k1,0 k1,1 k2,0 k2,1 ....] (while k0,1 is key 1 of wire 0).
* When calling the function this array should be empty and will be filled during the process of the function.
* @return {@code true} if this {@code GarbledBooleanCircuit} is a garbling the given keys, {@code false} if it is not.
*/
virtual bool internalVerify(byte* allInputWireValues, byte* allOutputWireValues)=0;
/**
* This function does the last part of the verify function. It gets both keys of each output wire and checks that
* their signal bits match the corresponding bit in the translation table.<p>
*
* The internalVerify function followed by this function are actually executes the whole verify of the circuit.
* @param allOutputWireValues both keys of each output wire.
* The output values are placed one after another, meaning that the output values are in the following format:
* [k0,0 k0,1 k1,0 k1,1 k2,0 k2,1 ....] (while k0,1 is key 1 of wire 0).
* @return {@code true} if the given keys match the translation table ,{@code false} if not.
*/
virtual bool verifyTranslationTable(byte* allOutputWireValues)=0;
/**
* Translates the garbled output obtained from the {@link #compute()} function into a meaningful(i.e. 0-1) output.<p>
* @param garbledOutput An array contains the garbled output.
* @return an array contains the output bit for each output wire.
*/
virtual byte* translate(byte* garbledOutput)=0;
/**
* Verifies that the given garbledOutput is valid values according to the given all OutputWireValues. <p>
* Meaning, for each output wire, checks that the garbled wire is one of the two possibilities.
* Then, translates the garbled output obtained from the {@link #compute()} function into a meaningful(i.e. 0-1) output.<p>
* @param garbledOutput An array contains the garbled output.
* @param allOutputWireValues both values for each output wire.
* The output values are placed one after another, meaning that the output values are in the following format:
* [k0,0 k0,1 k1,0 k1,1 k2,0 k2,1 ....] (while k0,1 is key 1 of wire 0).
* @return an array contains the output bit for each output wire.
* @throws CheatAttemptException if there is a garbledOutput values that is not one of the two possibilities.
*/
virtual byte* verifiedTranslate(byte* garbledOutput, byte* allOutputWireValues)=0;
/**
* The garbled tables are stored in the circuit for all the gates. This method returns the garbled tables. <p>
* This function is useful if we would like to pass many garbled circuits built on the same boolean circuit. <p>
* This is a compact way to define a circuit, that is, two garbled circuit with the same multi encryption scheme and the same
* basic boolean circuit only differ in the garbled tables and the translation table. <p>
* Thus we can hold one garbled circuit for all the circuits and only replace the garbled tables (and the translation tables if
* necessary). The advantage is that the size of the tables only is much smaller that all the information stored in the circuit
* (gates and other member variables). The size becomes important when sending large circuits.
*
*/
virtual GarbledTablesHolder * getGarbledTables()=0;
/**
* Sets the garbled tables of this circuit.<p>
* This function is useful if we would like to pass many garbled circuits built on the same boolean circuit. <p>
* This is a compact way to define a circuit, that is, two garbled circuit with the same multi encryption scheme and the same
* basic boolean circuit only differ in the garbled tables and the translation table. <p>
* Thus we can hold one garbled circuit for all the circuits and only replace the garbled tables (and the translation tables if necessary).
* The advantage is that the size of the tables only is much smaller that all the information stored in the circuit (gates and other
* member variables). The size becomes important when sending large circuits.<p>
* The receiver of the circuits will set the garbled tables for the relevant circuit.
*/
virtual void setGarbledTables(GarbledTablesHolder * garbledTables)=0;
/**
* Returns the translation table of the circuit. <P>
* This is necessary since the constructor of the circuit may want to pass the translation table to an other party. <p>
* Usually, this will be used when the other party (not the constructor of the circuit) creates a circuit, sets the garbled tables
* and needs the translation table as well to complete the construction of the circuit.
* @return the translation table of the circuit.
*/
virtual byte* getTranslationTable()=0;
virtual int getTranslationTableSize() =0;
/**
* Sets the translation table of the circuit. <p>
* This is necessary when the garbled tables where set and we would like to compute the circuit later on.
* @param translationTable This value should match the garbled tables of the circuit.
*/
virtual void setTranslationTable(byte* translationTable)=0;
/**
* Returns the input wires' indices of the given party.
* @param partyNumber The number of the party which we need his input wire indices.
* @return an array contains the indices of the input wires of the given party number.
* @throws NoSuchPartyException In case the given party number is not valid.
*/
virtual int* getInputWireIndices(int partyNumber) = 0;
/**
* @return an array containing the indices of the circuit's output wires.
*/
virtual int* getOutputWireIndices()=0;
/**
* @return an array containing the indices of the circuit's input wires.
*/
virtual int* getInputWireIndices()=0;
/**
* Returns the number of input wires of the given party.
* @param partyNumber the number of the party which we need his number of inputs.
* @return the number of inputs of this circuit.
* @throws NoSuchPartyException In case the given party number is not valid.
*/
virtual int getNumberOfInputs(int partyNumber) = 0;
virtual int getNumberOfOutputs() = 0;
/**
* Returns the number of parties using this circuit.
*
*/
virtual int getNumberOfParties()=0;
/**
*
* @return the size of the keys, in bytes.
*/
virtual int getKeySize()=0;
};
class NativeGarbledBooleanCircuitImpl : public FastGarbledBooleanCircuit {
public:
FastCircuitCreationValues garble() override;
FastCircuitCreationValues garble(byte * seed) override;
bool verify(byte* allInputWireValues) override;
byte* getGarbledInputFromUngarbledInput(byte* ungarbledInputBits, byte* allInputWireValues, int partyNumber) override;
void setInputs(vector<byte>& garbledInputs) override { this->garbledInputs = garbledInputs; };
byte* verifiedTranslate(byte* garbledOutput, byte * allOutputWireValues) override { return NULL; }
int* getInputWireIndices(int partyNumber) override;
byte* getTranslationTable() override { return garbledCircuitPtr->getTranslationTable(); };
int getTranslationTableSize() override { return garbledCircuitPtr->getNumberOfOutputs(); };
void setTranslationTable(byte* translationTable) override {
garbledCircuitPtr->setTranslationTable(translationTable);
};
int* getOutputWireIndices() override { return garbledCircuitPtr->getOutputIndices(); };
int getNumberOfInputs(int partyNumber) override { return garbledCircuitPtr->getNumOfInputsForEachParty()[partyNumber - 1]; };
int getNumberOfOutputs() { return garbledCircuitPtr->getNumberOfOutputs(); };
int getNumberOfParties() override { return garbledCircuitPtr->getNumberOfParties(); };
int* getInputWireIndices() override { return garbledCircuitPtr->getInputIndices(); };
int getKeySize() override { return SCAPI_NATIVE_KEY_SIZE; };
byte* translate(byte * garbledOutput) override;
bool verifyTranslationTable(byte* allOutputWireValues) override;
~NativeGarbledBooleanCircuitImpl() { delete garbledCircuitPtr; };
protected:
static const int SCAPI_NATIVE_KEY_SIZE = 16; // the number of bytes in each just garbled key
GarbledBooleanCircuit * garbledCircuitPtr = NULL; // pointer to the native garbledCircuit object
vector<byte> garbledInputs;
};
/**
* A concrete implementation of FastGarbledBooleanCircuit that is a wrapper for a code of SCAPI written in c++y.<p>
* The circuit can be used as a regular circuit in java and the actual calculations are done in the c++ jni dll
* calling functions in the Native SCAPI library. In some cases, there is a need to get back information that
* is stored in the java class (such as the garbled tables, input keys, etc). This java wrapper gives us
* the flexibility to work from java, for example with 2 parties and sending information via the java channel.
*
* @author Cryptography and Computer Security Research Group Department of Computer Science Bar-Ilan University (Meital Levy)
*
*/
//class ScNativeGarbledBooleanCircuitNoFixedKey : public NativeGarbledBooleanCircuitImpl {
//public:
// /*
// * fileName the name of the circuit file.
// * isFreeXor a flag indicating the use of the optimization of FreeXor
// */
// ScNativeGarbledBooleanCircuitNoFixedKey(string fileName, bool isFreeXor);
// byte* compute() override;
// bool internalVerify(byte * allInputWireValues, byte* allOutputWireValues) override;
// byte* verifyTranslate(byte* garbledOutput, byte* bothOutputKeys);
// GarbledTablesHolder * getGarbledTables() override;
// void setGarbledTables(GarbledTablesHolder * garbledTables) override;
//};
class ScNativeGarbledBooleanCircuit : public NativeGarbledBooleanCircuitImpl {
public:
enum CircuitType {
FREE_XOR_HALF_GATES,
FREE_XOR_ROW_REDUCTION,
FREE_XOR_STANDARD,
STANDARD
};
ScNativeGarbledBooleanCircuit(string fileName, CircuitType type, bool isNonXorOutputsRequired);
byte* compute() override;
bool internalVerify(byte * allInputWireValues, byte* allOutputWireValues) override;
GarbledTablesHolder * getGarbledTables() override;
void setGarbledTables(GarbledTablesHolder * garbledTables) override;
private:
bool isNonXorOutputsRequired;
int getGarbledTableSize();
};
inline void* aligned_malloc(size_t size, size_t align) {
void *result;
#ifdef _MSC_VER
result = _aligned_malloc(size, align);
#else
if (posix_memalign(&result, align, size)) result = 0;
#endif
return result;
};
inline void aligned_free(void *ptr) {
#ifdef _MSC_VER
_aligned_free(ptr);
#else
free(ptr);
#endif
}; | [
"asaf.kleinbort@gmail.com"
] | asaf.kleinbort@gmail.com |
e557705e0433eb76821e4f772a9fdf895b812ee3 | 3a2ac36d1c0f7ddeeef562fa1d48c2ca0a62d023 | /Module_01/ex06/HumanB.hpp | d8a9d591dc3a0a136df99f16b2a4382c4b969d77 | [] | no_license | qmarow/Modules | 9db05dd456e0aa92286c5943eeb4de416a21711b | 97968808020b3f5afdd95f2412ebd3879b619baa | refs/heads/main | 2023-03-05T10:09:45.684308 | 2021-02-06T08:58:41 | 2021-02-06T08:58:41 | 326,410,910 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 225 | hpp | #ifndef HUMANB_HPP
#define HUMANB_HPP
#include "Weapon.hpp"
class HumanB{
private:
std::string name;
Weapon *weapon;
public:
HumanB(std::string name);
void setWeapon(Weapon &club);
void attack();
};
#endif | [
"noreply@github.com"
] | noreply@github.com |
49b793ef061acb86bd2b59c01eb8ed2192b7bc94 | 323f282dc86794da456edd66badefdc8f0f4b604 | /code/bess/core/modules/queue.cc | 56cddcd2d53eed5df961814242ad98f24ca256f2 | [
"BSD-3-Clause"
] | permissive | bestephe/loom | 4c9ce219cfb1e018e920a34c3a72c24d31f91ed7 | 9ad9062c4d313ff611d48a1e104fedbf06bc6d61 | refs/heads/master | 2020-04-20T22:07:47.523484 | 2019-02-04T20:09:31 | 2019-02-04T20:09:31 | 169,129,128 | 26 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 7,110 | cc | // Copyright (c) 2014-2016, The Regents of the University of California.
// Copyright (c) 2016-2017, Nefeli Networks, 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:
//
// * 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 names of the copyright holders nor the names of their
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 "queue.h"
#include "../mem_alloc.h"
#include "../utils/format.h"
#define DEFAULT_QUEUE_SIZE 1024
const Commands Queue::cmds = {
{"set_burst", "QueueCommandSetBurstArg",
MODULE_CMD_FUNC(&Queue::CommandSetBurst), Command::THREAD_SAFE},
{"set_size", "QueueCommandSetSizeArg",
MODULE_CMD_FUNC(&Queue::CommandSetSize), Command::THREAD_UNSAFE},
{"get_status", "QueueCommandGetStatusArg",
MODULE_CMD_FUNC(&Queue::CommandGetStatus), Command::THREAD_SAFE}};
int Queue::Resize(int slots) {
struct llring *old_queue = queue_;
struct llring *new_queue;
int bytes = llring_bytes_with_slots(slots);
int ret;
new_queue = static_cast<llring *>(mem_alloc_ex(bytes, alignof(llring), 0));
if (!new_queue) {
return -ENOMEM;
}
ret = llring_init(new_queue, slots, 0, 1);
if (ret) {
mem_free(new_queue);
return -EINVAL;
}
/* migrate packets from the old queue */
if (old_queue) {
bess::Packet *pkt;
while (llring_sc_dequeue(old_queue, (void **)&pkt) == 0) {
ret = llring_sp_enqueue(new_queue, pkt);
if (ret == -LLRING_ERR_NOBUF) {
bess::Packet::Free(pkt);
}
}
mem_free(old_queue);
}
queue_ = new_queue;
if (backpressure_) {
AdjustWaterLevels();
}
return 0;
}
CommandResponse Queue::Init(const bess::pb::QueueArg &arg) {
task_id_t tid;
CommandResponse err;
tid = RegisterTask(nullptr);
if (tid == INVALID_TASK_ID) {
return CommandFailure(ENOMEM, "Task creation failed");
}
burst_ = bess::PacketBatch::kMaxBurst;
if (arg.backpressure()) {
LOG(INFO) << "Backpressure enabled";
backpressure_ = true;
}
if (arg.size() != 0) {
err = SetSize(arg.size());
if (err.error().code() != 0) {
return err;
}
} else {
size_ = DEFAULT_QUEUE_SIZE;
int ret = Resize(DEFAULT_QUEUE_SIZE);
if (ret) {
return CommandFailure(-ret);
}
}
if (arg.prefetch()) {
prefetch_ = true;
}
return CommandSuccess();
}
void Queue::DeInit() {
bess::Packet *pkt;
if (queue_) {
while (llring_sc_dequeue(queue_, (void **)&pkt) == 0) {
bess::Packet::Free(pkt);
}
mem_free(queue_);
}
}
std::string Queue::GetDesc() const {
const struct llring *ring = queue_;
return bess::utils::Format("%u/%u", llring_count(ring), ring->common.slots);
}
/* from upstream */
void Queue::ProcessBatch(bess::PacketBatch *batch) {
int queued =
llring_mp_enqueue_burst(queue_, (void **)batch->pkts(), batch->cnt());
if (backpressure_ && llring_count(queue_) > high_water_) {
SignalOverload();
}
if (queued < batch->cnt()) {
bess::Packet::Free(batch->pkts() + queued, batch->cnt() - queued);
}
}
/* to downstream */
struct task_result Queue::RunTask(void *) {
if (children_overload_ > 0) {
return {
.block = true, .packets = 0, .bits = 0,
};
}
bess::PacketBatch batch;
const int burst = ACCESS_ONCE(burst_);
const int pkt_overhead = 24;
uint64_t total_bytes = 0;
uint32_t cnt = llring_sc_dequeue_burst(queue_, (void **)batch.pkts(), burst);
if (cnt == 0) {
return {.block = true, .packets = 0, .bits = 0};
}
batch.set_cnt(cnt);
if (prefetch_) {
for (uint32_t i = 0; i < cnt; i++) {
total_bytes += batch.pkts()[i]->total_len();
rte_prefetch0(batch.pkts()[i]->head_data());
}
} else {
for (uint32_t i = 0; i < cnt; i++) {
total_bytes += batch.pkts()[i]->total_len();
}
}
RunNextModule(&batch);
if (backpressure_ && llring_count(queue_) < low_water_) {
SignalUnderload();
}
return {.block = false,
.packets = cnt,
.bits = (total_bytes + cnt * pkt_overhead) * 8};
}
CommandResponse Queue::CommandSetBurst(
const bess::pb::QueueCommandSetBurstArg &arg) {
uint64_t burst = arg.burst();
if (burst > bess::PacketBatch::kMaxBurst) {
return CommandFailure(EINVAL, "burst size must be [0,%zu]",
bess::PacketBatch::kMaxBurst);
}
burst_ = burst;
return CommandSuccess();
}
CommandResponse Queue::SetSize(uint64_t size) {
if (size < 4 || size > 16384) {
return CommandFailure(EINVAL, "must be in [4, 16384]");
}
if (size & (size - 1)) {
return CommandFailure(EINVAL, "must be a power of 2");
}
int ret = Resize(size);
if (ret) {
return CommandFailure(-ret);
}
size_ = size;
return CommandSuccess();
}
CommandResponse Queue::CommandSetSize(
const bess::pb::QueueCommandSetSizeArg &arg) {
return SetSize(arg.size());
}
CommandResponse Queue::CommandGetStatus(
const bess::pb::QueueCommandGetStatusArg &) {
bess::pb::QueueCommandGetStatusResponse resp;
resp.set_count(llring_count(queue_));
resp.set_size(size_);
return CommandSuccess(resp);
}
void Queue::AdjustWaterLevels() {
high_water_ = static_cast<uint64_t>(size_ * kHighWaterRatio);
low_water_ = static_cast<uint64_t>(size_ * kLowWaterRatio);
}
CheckConstraintResult Queue::CheckModuleConstraints() const {
CheckConstraintResult status = CHECK_OK;
if (num_active_tasks() - tasks().size() < 1) { // Assume multi-producer.
LOG(ERROR) << "Queue has no producers";
status = CHECK_NONFATAL_ERROR;
}
if (tasks().size() > 1) { // Assume single consumer.
LOG(ERROR) << "More than one consumer for the queue" << name();
return CHECK_FATAL_ERROR;
}
return status;
}
ADD_MODULE(Queue, "queue",
"terminates current task and enqueue packets for new task")
| [
"brentstephens@cs.wisc.edu"
] | brentstephens@cs.wisc.edu |
5e65aabd8fdad89cc0d0d267326c369013094e34 | 25abd807ca135a5c268255515f6d493c229903be | /cppwinrt/impl/Windows.AI.MachineLearning.Preview.0.h | 85bb3787719d1c6221fe792a990694a6baab8938 | [
"Apache-2.0"
] | permissive | RakeshShrestha/C-Calendar-Library | 670924ae3204d8737d8f43c47e54fe113d202265 | 6525707089891b0710e34769f7aeaea0c79271a1 | refs/heads/master | 2022-05-16T15:26:37.102822 | 2022-04-28T08:45:58 | 2022-04-28T08:45:58 | 33,488,761 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,654 | h | // WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.200117.5
#ifndef WINRT_Windows_AI_MachineLearning_Preview_0_H
#define WINRT_Windows_AI_MachineLearning_Preview_0_H
WINRT_EXPORT namespace winrt::Windows::Foundation
{
template <typename TResult> struct IAsyncOperation;
}
WINRT_EXPORT namespace winrt::Windows::Foundation::Collections
{
template <typename T> struct IIterable;
template <typename K, typename V> struct IMapView;
template <typename K, typename V> struct IMap;
struct IPropertySet;
}
WINRT_EXPORT namespace winrt::Windows::Graphics::Imaging
{
enum class BitmapPixelFormat : int32_t;
}
WINRT_EXPORT namespace winrt::Windows::Storage
{
struct IStorageFile;
}
WINRT_EXPORT namespace winrt::Windows::Storage::Streams
{
struct IRandomAccessStreamReference;
}
WINRT_EXPORT namespace winrt::Windows::AI::MachineLearning::Preview
{
enum class FeatureElementKindPreview : int32_t
{
Undefined = 0,
Float = 1,
UInt8 = 2,
Int8 = 3,
UInt16 = 4,
Int16 = 5,
Int32 = 6,
Int64 = 7,
String = 8,
Boolean = 9,
Float16 = 10,
Double = 11,
UInt32 = 12,
UInt64 = 13,
Complex64 = 14,
Complex128 = 15,
};
enum class LearningModelDeviceKindPreview : int32_t
{
LearningDeviceAny = 0,
LearningDeviceCpu = 1,
LearningDeviceGpu = 2,
LearningDeviceNpu = 3,
LearningDeviceDsp = 4,
LearningDeviceFpga = 5,
};
enum class LearningModelFeatureKindPreview : int32_t
{
Undefined = 0,
Tensor = 1,
Sequence = 2,
Map = 3,
Image = 4,
};
struct IImageVariableDescriptorPreview;
struct IInferencingOptionsPreview;
struct ILearningModelBindingPreview;
struct ILearningModelBindingPreviewFactory;
struct ILearningModelDescriptionPreview;
struct ILearningModelEvaluationResultPreview;
struct ILearningModelPreview;
struct ILearningModelPreviewStatics;
struct ILearningModelVariableDescriptorPreview;
struct IMapVariableDescriptorPreview;
struct ISequenceVariableDescriptorPreview;
struct ITensorVariableDescriptorPreview;
struct ImageVariableDescriptorPreview;
struct InferencingOptionsPreview;
struct LearningModelBindingPreview;
struct LearningModelDescriptionPreview;
struct LearningModelEvaluationResultPreview;
struct LearningModelPreview;
struct LearningModelVariableDescriptorPreview;
struct MapVariableDescriptorPreview;
struct SequenceVariableDescriptorPreview;
struct TensorVariableDescriptorPreview;
}
namespace winrt::impl
{
template <> struct category<Windows::AI::MachineLearning::Preview::IImageVariableDescriptorPreview>{ using type = interface_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::IInferencingOptionsPreview>{ using type = interface_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::ILearningModelBindingPreview>{ using type = interface_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::ILearningModelBindingPreviewFactory>{ using type = interface_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::ILearningModelDescriptionPreview>{ using type = interface_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::ILearningModelEvaluationResultPreview>{ using type = interface_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::ILearningModelPreview>{ using type = interface_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::ILearningModelPreviewStatics>{ using type = interface_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::ILearningModelVariableDescriptorPreview>{ using type = interface_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::IMapVariableDescriptorPreview>{ using type = interface_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::ISequenceVariableDescriptorPreview>{ using type = interface_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::ITensorVariableDescriptorPreview>{ using type = interface_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::ImageVariableDescriptorPreview>{ using type = class_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::InferencingOptionsPreview>{ using type = class_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::LearningModelBindingPreview>{ using type = class_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::LearningModelDescriptionPreview>{ using type = class_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::LearningModelEvaluationResultPreview>{ using type = class_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::LearningModelPreview>{ using type = class_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::LearningModelVariableDescriptorPreview>{ using type = class_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::MapVariableDescriptorPreview>{ using type = class_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::SequenceVariableDescriptorPreview>{ using type = class_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::TensorVariableDescriptorPreview>{ using type = class_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::FeatureElementKindPreview>{ using type = enum_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::LearningModelDeviceKindPreview>{ using type = enum_category; };
template <> struct category<Windows::AI::MachineLearning::Preview::LearningModelFeatureKindPreview>{ using type = enum_category; };
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::ImageVariableDescriptorPreview> = L"Windows.AI.MachineLearning.Preview.ImageVariableDescriptorPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::InferencingOptionsPreview> = L"Windows.AI.MachineLearning.Preview.InferencingOptionsPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::LearningModelBindingPreview> = L"Windows.AI.MachineLearning.Preview.LearningModelBindingPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::LearningModelDescriptionPreview> = L"Windows.AI.MachineLearning.Preview.LearningModelDescriptionPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::LearningModelEvaluationResultPreview> = L"Windows.AI.MachineLearning.Preview.LearningModelEvaluationResultPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::LearningModelPreview> = L"Windows.AI.MachineLearning.Preview.LearningModelPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::LearningModelVariableDescriptorPreview> = L"Windows.AI.MachineLearning.Preview.LearningModelVariableDescriptorPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::MapVariableDescriptorPreview> = L"Windows.AI.MachineLearning.Preview.MapVariableDescriptorPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::SequenceVariableDescriptorPreview> = L"Windows.AI.MachineLearning.Preview.SequenceVariableDescriptorPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::TensorVariableDescriptorPreview> = L"Windows.AI.MachineLearning.Preview.TensorVariableDescriptorPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::FeatureElementKindPreview> = L"Windows.AI.MachineLearning.Preview.FeatureElementKindPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::LearningModelDeviceKindPreview> = L"Windows.AI.MachineLearning.Preview.LearningModelDeviceKindPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::LearningModelFeatureKindPreview> = L"Windows.AI.MachineLearning.Preview.LearningModelFeatureKindPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::IImageVariableDescriptorPreview> = L"Windows.AI.MachineLearning.Preview.IImageVariableDescriptorPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::IInferencingOptionsPreview> = L"Windows.AI.MachineLearning.Preview.IInferencingOptionsPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::ILearningModelBindingPreview> = L"Windows.AI.MachineLearning.Preview.ILearningModelBindingPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::ILearningModelBindingPreviewFactory> = L"Windows.AI.MachineLearning.Preview.ILearningModelBindingPreviewFactory";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::ILearningModelDescriptionPreview> = L"Windows.AI.MachineLearning.Preview.ILearningModelDescriptionPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::ILearningModelEvaluationResultPreview> = L"Windows.AI.MachineLearning.Preview.ILearningModelEvaluationResultPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::ILearningModelPreview> = L"Windows.AI.MachineLearning.Preview.ILearningModelPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::ILearningModelPreviewStatics> = L"Windows.AI.MachineLearning.Preview.ILearningModelPreviewStatics";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::ILearningModelVariableDescriptorPreview> = L"Windows.AI.MachineLearning.Preview.ILearningModelVariableDescriptorPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::IMapVariableDescriptorPreview> = L"Windows.AI.MachineLearning.Preview.IMapVariableDescriptorPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::ISequenceVariableDescriptorPreview> = L"Windows.AI.MachineLearning.Preview.ISequenceVariableDescriptorPreview";
template <> inline constexpr auto& name_v<Windows::AI::MachineLearning::Preview::ITensorVariableDescriptorPreview> = L"Windows.AI.MachineLearning.Preview.ITensorVariableDescriptorPreview";
template <> inline constexpr guid guid_v<Windows::AI::MachineLearning::Preview::IImageVariableDescriptorPreview>{ 0x7AE1FA72,0x029E,0x4DC5,{ 0xA2,0xF8,0x5F,0xB7,0x63,0x15,0x41,0x50 } };
template <> inline constexpr guid guid_v<Windows::AI::MachineLearning::Preview::IInferencingOptionsPreview>{ 0x47BC8205,0x4D36,0x47A9,{ 0x8F,0x68,0xFF,0xCB,0x33,0x9D,0xD0,0xFC } };
template <> inline constexpr guid guid_v<Windows::AI::MachineLearning::Preview::ILearningModelBindingPreview>{ 0x93C901E8,0x6C78,0x4B4F,{ 0xAE,0xC1,0xA6,0xBB,0x9E,0x69,0x16,0x24 } };
template <> inline constexpr guid guid_v<Windows::AI::MachineLearning::Preview::ILearningModelBindingPreviewFactory>{ 0x48B8219F,0x1E51,0x4D77,{ 0xAE,0x50,0x3E,0xC1,0x64,0xAD,0x34,0x80 } };
template <> inline constexpr guid guid_v<Windows::AI::MachineLearning::Preview::ILearningModelDescriptionPreview>{ 0xF52C09C6,0x8611,0x40AD,{ 0x8E,0x59,0xDE,0x3F,0xD7,0x03,0x0A,0x40 } };
template <> inline constexpr guid guid_v<Windows::AI::MachineLearning::Preview::ILearningModelEvaluationResultPreview>{ 0xDF25EA9F,0x9863,0x4088,{ 0x84,0x98,0x87,0xA1,0xF4,0x68,0x6F,0x92 } };
template <> inline constexpr guid guid_v<Windows::AI::MachineLearning::Preview::ILearningModelPreview>{ 0x049C266A,0x93B4,0x478C,{ 0xAE,0xB8,0x70,0x15,0x7B,0xF0,0xFF,0x94 } };
template <> inline constexpr guid guid_v<Windows::AI::MachineLearning::Preview::ILearningModelPreviewStatics>{ 0x164BBB60,0x8465,0x4786,{ 0x8B,0x93,0x2C,0x16,0xA8,0x92,0x89,0xD7 } };
template <> inline constexpr guid guid_v<Windows::AI::MachineLearning::Preview::ILearningModelVariableDescriptorPreview>{ 0xB13DF682,0xFC30,0x492B,{ 0x8E,0xA0,0xED,0x1F,0x53,0xC0,0xB0,0x38 } };
template <> inline constexpr guid guid_v<Windows::AI::MachineLearning::Preview::IMapVariableDescriptorPreview>{ 0x3CB38370,0xC02B,0x4236,{ 0xB3,0xE8,0x6B,0xDC,0xA4,0x9C,0x31,0x29 } };
template <> inline constexpr guid guid_v<Windows::AI::MachineLearning::Preview::ISequenceVariableDescriptorPreview>{ 0x9CD8F292,0x98B2,0x4530,{ 0xA1,0xB6,0x2D,0xED,0x5F,0xEC,0xBC,0x26 } };
template <> inline constexpr guid guid_v<Windows::AI::MachineLearning::Preview::ITensorVariableDescriptorPreview>{ 0xA80F501A,0x9AAC,0x4233,{ 0x97,0x84,0xAC,0xEA,0xF9,0x25,0x10,0xB5 } };
template <> struct default_interface<Windows::AI::MachineLearning::Preview::ImageVariableDescriptorPreview>{ using type = Windows::AI::MachineLearning::Preview::IImageVariableDescriptorPreview; };
template <> struct default_interface<Windows::AI::MachineLearning::Preview::InferencingOptionsPreview>{ using type = Windows::AI::MachineLearning::Preview::IInferencingOptionsPreview; };
template <> struct default_interface<Windows::AI::MachineLearning::Preview::LearningModelBindingPreview>{ using type = Windows::AI::MachineLearning::Preview::ILearningModelBindingPreview; };
template <> struct default_interface<Windows::AI::MachineLearning::Preview::LearningModelDescriptionPreview>{ using type = Windows::AI::MachineLearning::Preview::ILearningModelDescriptionPreview; };
template <> struct default_interface<Windows::AI::MachineLearning::Preview::LearningModelEvaluationResultPreview>{ using type = Windows::AI::MachineLearning::Preview::ILearningModelEvaluationResultPreview; };
template <> struct default_interface<Windows::AI::MachineLearning::Preview::LearningModelPreview>{ using type = Windows::AI::MachineLearning::Preview::ILearningModelPreview; };
template <> struct default_interface<Windows::AI::MachineLearning::Preview::LearningModelVariableDescriptorPreview>{ using type = Windows::AI::MachineLearning::Preview::ILearningModelVariableDescriptorPreview; };
template <> struct default_interface<Windows::AI::MachineLearning::Preview::MapVariableDescriptorPreview>{ using type = Windows::AI::MachineLearning::Preview::IMapVariableDescriptorPreview; };
template <> struct default_interface<Windows::AI::MachineLearning::Preview::SequenceVariableDescriptorPreview>{ using type = Windows::AI::MachineLearning::Preview::ISequenceVariableDescriptorPreview; };
template <> struct default_interface<Windows::AI::MachineLearning::Preview::TensorVariableDescriptorPreview>{ using type = Windows::AI::MachineLearning::Preview::ITensorVariableDescriptorPreview; };
template <> struct abi<Windows::AI::MachineLearning::Preview::IImageVariableDescriptorPreview>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_BitmapPixelFormat(int32_t*) noexcept = 0;
virtual int32_t __stdcall get_Width(uint32_t*) noexcept = 0;
virtual int32_t __stdcall get_Height(uint32_t*) noexcept = 0;
};
};
template <> struct abi<Windows::AI::MachineLearning::Preview::IInferencingOptionsPreview>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_PreferredDeviceKind(int32_t*) noexcept = 0;
virtual int32_t __stdcall put_PreferredDeviceKind(int32_t) noexcept = 0;
virtual int32_t __stdcall get_IsTracingEnabled(bool*) noexcept = 0;
virtual int32_t __stdcall put_IsTracingEnabled(bool) noexcept = 0;
virtual int32_t __stdcall get_MaxBatchSize(int32_t*) noexcept = 0;
virtual int32_t __stdcall put_MaxBatchSize(int32_t) noexcept = 0;
virtual int32_t __stdcall get_MinimizeMemoryAllocation(bool*) noexcept = 0;
virtual int32_t __stdcall put_MinimizeMemoryAllocation(bool) noexcept = 0;
virtual int32_t __stdcall get_ReclaimMemoryAfterEvaluation(bool*) noexcept = 0;
virtual int32_t __stdcall put_ReclaimMemoryAfterEvaluation(bool) noexcept = 0;
};
};
template <> struct abi<Windows::AI::MachineLearning::Preview::ILearningModelBindingPreview>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall Bind(void*, void*) noexcept = 0;
virtual int32_t __stdcall BindWithProperties(void*, void*, void*) noexcept = 0;
virtual int32_t __stdcall Clear() noexcept = 0;
};
};
template <> struct abi<Windows::AI::MachineLearning::Preview::ILearningModelBindingPreviewFactory>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall CreateFromModel(void*, void**) noexcept = 0;
};
};
template <> struct abi<Windows::AI::MachineLearning::Preview::ILearningModelDescriptionPreview>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_Author(void**) noexcept = 0;
virtual int32_t __stdcall get_Name(void**) noexcept = 0;
virtual int32_t __stdcall get_Domain(void**) noexcept = 0;
virtual int32_t __stdcall get_Description(void**) noexcept = 0;
virtual int32_t __stdcall get_Version(int64_t*) noexcept = 0;
virtual int32_t __stdcall get_Metadata(void**) noexcept = 0;
virtual int32_t __stdcall get_InputFeatures(void**) noexcept = 0;
virtual int32_t __stdcall get_OutputFeatures(void**) noexcept = 0;
};
};
template <> struct abi<Windows::AI::MachineLearning::Preview::ILearningModelEvaluationResultPreview>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_CorrelationId(void**) noexcept = 0;
virtual int32_t __stdcall get_Outputs(void**) noexcept = 0;
};
};
template <> struct abi<Windows::AI::MachineLearning::Preview::ILearningModelPreview>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall EvaluateAsync(void*, void*, void**) noexcept = 0;
virtual int32_t __stdcall EvaluateFeaturesAsync(void*, void*, void**) noexcept = 0;
virtual int32_t __stdcall get_Description(void**) noexcept = 0;
virtual int32_t __stdcall get_InferencingOptions(void**) noexcept = 0;
virtual int32_t __stdcall put_InferencingOptions(void*) noexcept = 0;
};
};
template <> struct abi<Windows::AI::MachineLearning::Preview::ILearningModelPreviewStatics>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall LoadModelFromStorageFileAsync(void*, void**) noexcept = 0;
virtual int32_t __stdcall LoadModelFromStreamAsync(void*, void**) noexcept = 0;
};
};
template <> struct abi<Windows::AI::MachineLearning::Preview::ILearningModelVariableDescriptorPreview>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_Name(void**) noexcept = 0;
virtual int32_t __stdcall get_Description(void**) noexcept = 0;
virtual int32_t __stdcall get_ModelFeatureKind(int32_t*) noexcept = 0;
virtual int32_t __stdcall get_IsRequired(bool*) noexcept = 0;
};
};
template <> struct abi<Windows::AI::MachineLearning::Preview::IMapVariableDescriptorPreview>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_KeyKind(int32_t*) noexcept = 0;
virtual int32_t __stdcall get_ValidStringKeys(void**) noexcept = 0;
virtual int32_t __stdcall get_ValidIntegerKeys(void**) noexcept = 0;
virtual int32_t __stdcall get_Fields(void**) noexcept = 0;
};
};
template <> struct abi<Windows::AI::MachineLearning::Preview::ISequenceVariableDescriptorPreview>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_ElementType(void**) noexcept = 0;
};
};
template <> struct abi<Windows::AI::MachineLearning::Preview::ITensorVariableDescriptorPreview>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_DataType(int32_t*) noexcept = 0;
virtual int32_t __stdcall get_Shape(void**) noexcept = 0;
};
};
template <typename D>
struct consume_Windows_AI_MachineLearning_Preview_IImageVariableDescriptorPreview
{
[[nodiscard]] WINRT_IMPL_AUTO(Windows::Graphics::Imaging::BitmapPixelFormat) BitmapPixelFormat() const;
[[nodiscard]] WINRT_IMPL_AUTO(uint32_t) Width() const;
[[nodiscard]] WINRT_IMPL_AUTO(uint32_t) Height() const;
};
template <> struct consume<Windows::AI::MachineLearning::Preview::IImageVariableDescriptorPreview>
{
template <typename D> using type = consume_Windows_AI_MachineLearning_Preview_IImageVariableDescriptorPreview<D>;
};
template <typename D>
struct consume_Windows_AI_MachineLearning_Preview_IInferencingOptionsPreview
{
[[nodiscard]] WINRT_IMPL_AUTO(Windows::AI::MachineLearning::Preview::LearningModelDeviceKindPreview) PreferredDeviceKind() const;
WINRT_IMPL_AUTO(void) PreferredDeviceKind(Windows::AI::MachineLearning::Preview::LearningModelDeviceKindPreview const& value) const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) IsTracingEnabled() const;
WINRT_IMPL_AUTO(void) IsTracingEnabled(bool value) const;
[[nodiscard]] WINRT_IMPL_AUTO(int32_t) MaxBatchSize() const;
WINRT_IMPL_AUTO(void) MaxBatchSize(int32_t value) const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) MinimizeMemoryAllocation() const;
WINRT_IMPL_AUTO(void) MinimizeMemoryAllocation(bool value) const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) ReclaimMemoryAfterEvaluation() const;
WINRT_IMPL_AUTO(void) ReclaimMemoryAfterEvaluation(bool value) const;
};
template <> struct consume<Windows::AI::MachineLearning::Preview::IInferencingOptionsPreview>
{
template <typename D> using type = consume_Windows_AI_MachineLearning_Preview_IInferencingOptionsPreview<D>;
};
template <typename D>
struct consume_Windows_AI_MachineLearning_Preview_ILearningModelBindingPreview
{
WINRT_IMPL_AUTO(void) Bind(param::hstring const& name, Windows::Foundation::IInspectable const& value) const;
WINRT_IMPL_AUTO(void) Bind(param::hstring const& name, Windows::Foundation::IInspectable const& value, Windows::Foundation::Collections::IPropertySet const& metadata) const;
WINRT_IMPL_AUTO(void) Clear() const;
};
template <> struct consume<Windows::AI::MachineLearning::Preview::ILearningModelBindingPreview>
{
template <typename D> using type = consume_Windows_AI_MachineLearning_Preview_ILearningModelBindingPreview<D>;
};
template <typename D>
struct consume_Windows_AI_MachineLearning_Preview_ILearningModelBindingPreviewFactory
{
WINRT_IMPL_AUTO(Windows::AI::MachineLearning::Preview::LearningModelBindingPreview) CreateFromModel(Windows::AI::MachineLearning::Preview::LearningModelPreview const& model) const;
};
template <> struct consume<Windows::AI::MachineLearning::Preview::ILearningModelBindingPreviewFactory>
{
template <typename D> using type = consume_Windows_AI_MachineLearning_Preview_ILearningModelBindingPreviewFactory<D>;
};
template <typename D>
struct consume_Windows_AI_MachineLearning_Preview_ILearningModelDescriptionPreview
{
[[nodiscard]] WINRT_IMPL_AUTO(hstring) Author() const;
[[nodiscard]] WINRT_IMPL_AUTO(hstring) Name() const;
[[nodiscard]] WINRT_IMPL_AUTO(hstring) Domain() const;
[[nodiscard]] WINRT_IMPL_AUTO(hstring) Description() const;
[[nodiscard]] WINRT_IMPL_AUTO(int64_t) Version() const;
[[nodiscard]] WINRT_IMPL_AUTO(Windows::Foundation::Collections::IMapView<hstring, hstring>) Metadata() const;
[[nodiscard]] WINRT_IMPL_AUTO(Windows::Foundation::Collections::IIterable<Windows::AI::MachineLearning::Preview::ILearningModelVariableDescriptorPreview>) InputFeatures() const;
[[nodiscard]] WINRT_IMPL_AUTO(Windows::Foundation::Collections::IIterable<Windows::AI::MachineLearning::Preview::ILearningModelVariableDescriptorPreview>) OutputFeatures() const;
};
template <> struct consume<Windows::AI::MachineLearning::Preview::ILearningModelDescriptionPreview>
{
template <typename D> using type = consume_Windows_AI_MachineLearning_Preview_ILearningModelDescriptionPreview<D>;
};
template <typename D>
struct consume_Windows_AI_MachineLearning_Preview_ILearningModelEvaluationResultPreview
{
[[nodiscard]] WINRT_IMPL_AUTO(hstring) CorrelationId() const;
[[nodiscard]] WINRT_IMPL_AUTO(Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>) Outputs() const;
};
template <> struct consume<Windows::AI::MachineLearning::Preview::ILearningModelEvaluationResultPreview>
{
template <typename D> using type = consume_Windows_AI_MachineLearning_Preview_ILearningModelEvaluationResultPreview<D>;
};
template <typename D>
struct consume_Windows_AI_MachineLearning_Preview_ILearningModelPreview
{
WINRT_IMPL_AUTO(Windows::Foundation::IAsyncOperation<Windows::AI::MachineLearning::Preview::LearningModelEvaluationResultPreview>) EvaluateAsync(Windows::AI::MachineLearning::Preview::LearningModelBindingPreview const& binding, param::hstring const& correlationId) const;
WINRT_IMPL_AUTO(Windows::Foundation::IAsyncOperation<Windows::AI::MachineLearning::Preview::LearningModelEvaluationResultPreview>) EvaluateFeaturesAsync(param::map<hstring, Windows::Foundation::IInspectable> const& features, param::hstring const& correlationId) const;
[[nodiscard]] WINRT_IMPL_AUTO(Windows::AI::MachineLearning::Preview::LearningModelDescriptionPreview) Description() const;
[[nodiscard]] WINRT_IMPL_AUTO(Windows::AI::MachineLearning::Preview::InferencingOptionsPreview) InferencingOptions() const;
WINRT_IMPL_AUTO(void) InferencingOptions(Windows::AI::MachineLearning::Preview::InferencingOptionsPreview const& value) const;
};
template <> struct consume<Windows::AI::MachineLearning::Preview::ILearningModelPreview>
{
template <typename D> using type = consume_Windows_AI_MachineLearning_Preview_ILearningModelPreview<D>;
};
template <typename D>
struct consume_Windows_AI_MachineLearning_Preview_ILearningModelPreviewStatics
{
WINRT_IMPL_AUTO(Windows::Foundation::IAsyncOperation<Windows::AI::MachineLearning::Preview::LearningModelPreview>) LoadModelFromStorageFileAsync(Windows::Storage::IStorageFile const& modelFile) const;
WINRT_IMPL_AUTO(Windows::Foundation::IAsyncOperation<Windows::AI::MachineLearning::Preview::LearningModelPreview>) LoadModelFromStreamAsync(Windows::Storage::Streams::IRandomAccessStreamReference const& modelStream) const;
};
template <> struct consume<Windows::AI::MachineLearning::Preview::ILearningModelPreviewStatics>
{
template <typename D> using type = consume_Windows_AI_MachineLearning_Preview_ILearningModelPreviewStatics<D>;
};
template <typename D>
struct consume_Windows_AI_MachineLearning_Preview_ILearningModelVariableDescriptorPreview
{
[[nodiscard]] WINRT_IMPL_AUTO(hstring) Name() const;
[[nodiscard]] WINRT_IMPL_AUTO(hstring) Description() const;
[[nodiscard]] WINRT_IMPL_AUTO(Windows::AI::MachineLearning::Preview::LearningModelFeatureKindPreview) ModelFeatureKind() const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) IsRequired() const;
};
template <> struct consume<Windows::AI::MachineLearning::Preview::ILearningModelVariableDescriptorPreview>
{
template <typename D> using type = consume_Windows_AI_MachineLearning_Preview_ILearningModelVariableDescriptorPreview<D>;
};
template <typename D>
struct consume_Windows_AI_MachineLearning_Preview_IMapVariableDescriptorPreview
{
[[nodiscard]] WINRT_IMPL_AUTO(Windows::AI::MachineLearning::Preview::FeatureElementKindPreview) KeyKind() const;
[[nodiscard]] WINRT_IMPL_AUTO(Windows::Foundation::Collections::IIterable<hstring>) ValidStringKeys() const;
[[nodiscard]] WINRT_IMPL_AUTO(Windows::Foundation::Collections::IIterable<int64_t>) ValidIntegerKeys() const;
[[nodiscard]] WINRT_IMPL_AUTO(Windows::AI::MachineLearning::Preview::ILearningModelVariableDescriptorPreview) Fields() const;
};
template <> struct consume<Windows::AI::MachineLearning::Preview::IMapVariableDescriptorPreview>
{
template <typename D> using type = consume_Windows_AI_MachineLearning_Preview_IMapVariableDescriptorPreview<D>;
};
template <typename D>
struct consume_Windows_AI_MachineLearning_Preview_ISequenceVariableDescriptorPreview
{
[[nodiscard]] WINRT_IMPL_AUTO(Windows::AI::MachineLearning::Preview::ILearningModelVariableDescriptorPreview) ElementType() const;
};
template <> struct consume<Windows::AI::MachineLearning::Preview::ISequenceVariableDescriptorPreview>
{
template <typename D> using type = consume_Windows_AI_MachineLearning_Preview_ISequenceVariableDescriptorPreview<D>;
};
template <typename D>
struct consume_Windows_AI_MachineLearning_Preview_ITensorVariableDescriptorPreview
{
[[nodiscard]] WINRT_IMPL_AUTO(Windows::AI::MachineLearning::Preview::FeatureElementKindPreview) DataType() const;
[[nodiscard]] WINRT_IMPL_AUTO(Windows::Foundation::Collections::IIterable<int64_t>) Shape() const;
};
template <> struct consume<Windows::AI::MachineLearning::Preview::ITensorVariableDescriptorPreview>
{
template <typename D> using type = consume_Windows_AI_MachineLearning_Preview_ITensorVariableDescriptorPreview<D>;
};
}
#endif
| [
"rakesh.shrestha@gmail.com"
] | rakesh.shrestha@gmail.com |
3de645412b5b329fb0ba96bc3c3065b270bd076d | 3d4f69dba44f5e285c19c6762494073148011bbe | /solution/2218. Maximum Value of K Coins From Piles/2218_01.cpp | 8dea1cc0ca4d5af0f1042b15cf7193bbaea956b0 | [] | no_license | cmeslo/leetcode | a0fd9826aaf77380c6cfb6bd24f26024345077be | 9b304046c2727364a3c9e5c513cb312fabdc729e | refs/heads/master | 2023-08-31T02:34:56.962597 | 2023-08-30T17:06:07 | 2023-08-30T17:06:07 | 96,622,859 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 690 | cpp | class Solution {
public:
int maxValueOfCoins(vector<vector<int>>& piles, int k) {
mem.resize(piles.size(), vector<int>(k + 1, -1));
return dp(piles, k, 0);
}
private:
vector<vector<int>> mem;
int dp(vector<vector<int>>& piles, int k, int i) {
if (i == piles.size() || k == 0) return 0;
if (mem[i][k] != -1) return mem[i][k];
int res = dp(piles, k, i + 1);
int sum = 0;
int limit = min(k, (int)piles[i].size());
for (int j = 0; j < limit; ++j) {
sum += piles[i][j];
res = max(res, sum + dp(piles, k - j - 1, i + 1));
}
return mem[i][k] = res;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
41c6ff1e0d34e34ecc509e3de4c619241db91d1f | 8c0e6eb11c97ff4976421d82684350ad62819427 | /Design Patterns/Decorator/cdecorator.h | d546a8fb5edcb26ea31ac003368b508f914aa5b3 | [] | no_license | sarathjoseph/Design-Patterns | 1b60a40c874f63dfd007d92b16bd66bef92d3168 | 7941c2674817cbe66c8a90df3ae18012bb9b6894 | refs/heads/master | 2016-09-12T11:49:02.274313 | 2016-05-11T01:36:33 | 2016-05-11T01:36:33 | 57,447,597 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 274 | h | #pragma once
#include "component.h"
class ComponentDecorator : public Component {
public:
ComponentDecorator(Component* componentInstance);
~ComponentDecorator();
Component * component;
virtual string getConfiguration();
virtual int getCost();
}; | [
"sarathcjoseph@gmail.com"
] | sarathcjoseph@gmail.com |
d02df26bce65dd26153aec1660ac9d69c16f80e1 | 0782cedc1ff961380d6bc2f6ab99aedcad5abbd1 | /json/Parser.hpp | c29e4d7d585c3e578a3f5eae952a9b0dcb194be6 | [] | no_license | pb82/lua-experiments | 47f0813936b8743f5201d9e386c21515180d1fd9 | 483eb1f196eb614c4fe4daea2318c86836e21aba | refs/heads/master | 2020-03-07T19:08:39.505877 | 2018-05-01T23:41:27 | 2018-05-01T23:41:27 | 127,663,258 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,745 | hpp | #ifndef PARSER_H
#define PARSER_H
#include <stack>
#include <ctype.h>
#include <stdint.h>
#include <exception>
#include "Utf8.hpp"
#include "Value.hpp"
namespace JSON {
// JSON escape characters that may appear
// after a reverse solidus
const char ESC_REVERSE_SOLIUDS = 92;
const char ESC_QUOTATION_MARK = 34;
const char ESC_SOLIDUS = 47;
const char ESC_BACKSPACE = 98;
const char ESC_FORMFEED = 102;
const char ESC_NEWLINE = 110;
const char ESC_CARRET = 114;
const char ESC_HORIZONTAL_TAB = 116;
const char ESC_UNICODE = 117;
// Use 32 bit characters for unicode strings
typedef std::basic_string<int32_t> wideString;
// Represents a JSON parser
class Parser {
public:
Parser() : parseIndex(0), lineNumber(1) { }
void parse(Value& object, const std::string& source);
void parse(Value& object, const char * source);
private:
void reset() {
lineNumber = 1;
parseIndex = 0;
while(!objectStack.empty()) {
objectStack.pop();
}
}
// Increment the parse index until a non-whitespace character
// is encountered.
void clearWhitespace() {
while (hasNext() && isspace(source.at(parseIndex))) {
if (peek() == 10 || peek() == 12 || peek() == 13) {
lineNumber++;
}
parseIndex++;
}
}
// Increase the parse index but ignore the current character
void consume() {
parseIndex++;
}
// End of Stream reached?
bool hasNext() const {
return parseIndex < source.length();
}
// Return a reference to the current character in the
// stream and increase the index.
char& next() {
if (!hasNext()) {
// End of Stream already reached?
throw std::runtime_error("Unexpected end of stream");
}
// Increase the line number. This is used to print
// the position when a parse error occurs.
if (peek() == '\n') {
lineNumber++;
}
return source.at(parseIndex++);
}
// Return a reference to the current character in the
// stream without increasing the index.
char& peek() {
if (!hasNext()) {
// End of Stream already reached?
throw std::runtime_error("Unexpected end of stream");
}
return source.at(parseIndex);
}
// Return a reference to the top item on the stack.
// The top item usually holds a reference to the
// current array / object at the parse position.
Value& top() const {
return *objectStack.top();
}
// Store a parsed value and return a reference
// to it
Value& store(const Value& val) {
if (top().is(JSON_ARRAY)) {
// Current parse position is inside an array:
// Append the new item to the end of the array
top().push_back(val);
return top().asMutable<Array>().back();
} else if (top().is(JSON_OBJECT)) {
// Current parse position is inside an object:
// Read the current property and store the new item
// under this property inside the current object.
top()[currentProperty.str().c_str()] = val;
return top()[currentProperty.str().c_str()];
} else {
// Parse position is not inside an array and not
// inside an object. Put the new item on the top
// of the stack.
top() = val;
return top();
}
}
// Tests if a character is allowed for numeric expressions.
bool validNumericChar(char code) const {
return (code >= 48 && code <= 57)
|| (code == 46) // '.'
|| (code == 45) // '-'
|| (code == 43) // '+'
|| (code == 69) // 'E'
|| (code == 101); // 'e'
}
// Tests if a character is allowed to introduce a numeric
// expression.
bool validNumericStartingChar(char code) const {
return (code >= 48 && code <= 57)
|| (code == 45); // '-'
}
// Valid digit within an \u2360 unicode escape?
bool validHexDigit(char code) const {
return (code >= 48 && code <= 57)
|| (code >= 65 && code <= 70)
|| (code >= 97 && code <= 102);
}
void parseObject();
void parseProperty();
void parseValue();
void parseString();
void parseArray();
void parseBoolean();
void parseNumber();
void parseNull();
void escapeChar();
void readUTF8Escape();
unsigned int parseIndex;
unsigned int lineNumber;
std::string source;
std::ostringstream currentProperty;
std::ostringstream currentString;
// Since std::stack<Value&> is not possible use
// a pointer here
std::stack<Value *> objectStack;
};
/**
* { ... }
*/
inline void Parser::parseObject() {
clearWhitespace();
if (next() == '{') {
clearWhitespace();
// Push a new object on the stack
objectStack.push(&store(Object {}));
if (peek() != '}') {
// Parse object properties
while (hasNext()) {
parseProperty();
clearWhitespace();
if (hasNext() && peek() != ',') {
break;
} else {
// Another property to parse. Get rid
// of the ',' and go on...
consume(); // ','
}
}
}
// End of properties
clearWhitespace();
if (peek() == '}') {
consume(); // '}'
// Done with parsing the object.
// Pop it from the stack, since this is no longer
// the reference object for eventual coming items.
objectStack.pop();
return;
} else {
// Objects must end with ...}
throw std::runtime_error("Objects must end with }");
}
} else {
// Objects have to start with {...
throw std::runtime_error("Objects must start with {");
}
}
/**
* ...:
*/
inline void Parser::parseProperty() {
// Reset currentProperty buffer
currentProperty.str("");
clearWhitespace();
// Properties must start with '"'
if (peek() == ESC_QUOTATION_MARK) {
consume(); // '"'
while (peek() != ESC_QUOTATION_MARK) {
currentProperty << next();
}
// Properties must end with '"'
if (next() != ESC_QUOTATION_MARK) {
throw std::runtime_error("Properties must end with\"");
} else {
clearWhitespace();
// ...": ...
// Properties must be in the form of
// "key": value
if (peek() != ':') {
throw std::runtime_error("Expected colon");
} else {
consume(); // ':'
// Parse the value
// :...
parseValue();
}
}
} else {
throw std::runtime_error("Parse error in property");
}
}
/**
* :...
*/
inline void Parser::parseValue() {
clearWhitespace();
// Decide the type of the value on the stream
switch(peek()) {
case '{':
parseObject();
return;
case '"':
parseString();
return;
case '[':
parseArray();
return;
case 'n':
parseNull();
return;
case 't':
case 'f':
parseBoolean();
return;
default:
// If none of the former types matched always try to
// parse a number.
if (validNumericStartingChar(peek())) {
parseNumber();
return;
} else {
throw std::runtime_error("Parser error in value");
}
}
}
/**
* null
*/
inline void Parser::parseNull() {
currentString.str("");
// Read the next four characters and test if they
// are equal to 'null'
for (int i=0;i<4;i++) {
currentString << next();
}
if (currentString.str().compare("null") == 0) {
store(Value());
} else {
throw std::runtime_error("Parse error in null");
}
}
/**
* numbers
*/
inline void Parser::parseNumber() {
currentString.str("");
while (hasNext() && validNumericChar(peek())) {
currentString << next();
}
store(fromString<double>(currentString.str()));
}
/**
* true | false
*/
inline void Parser::parseBoolean() {
currentString.str("");
// consume lowercase letters
while (hasNext() && peek() >= 97 && peek() <= 122) {
currentString << next();
}
bool result;
if (currentString.str().compare("true") == 0) {
result = true;
} else if (currentString.str().compare("false") == 0) {
result = false;
} else {
throw std::runtime_error("Parse error in boolean");
}
store(result);
}
/**
* "..."
*/
inline void Parser::parseString() {
// Reset string buffer
currentString.str("");
consume(); // '"'
while (peek() != ESC_QUOTATION_MARK) {
// String contains an escaped character?
if (peek() == ESC_REVERSE_SOLIUDS) {
escapeChar();
} else {
currentString << next();
}
}
consume(); // '"'
store(currentString.str());
}
/**
* \...
*/
inline void Parser::escapeChar() {
consume(); // REVERSE_SOLIDUS
// Decide which escape character follows
switch(peek()) {
case ESC_BACKSPACE:
consume();
currentString << (char) 8;
break;
case ESC_HORIZONTAL_TAB:
consume();
currentString << (char) 9;
break;
case ESC_NEWLINE:
consume();
currentString << (char) 10;
break;
case ESC_FORMFEED:
consume();
currentString << (char) 12;
break;
case ESC_CARRET:
consume();
currentString << (char) 13;
break;
case ESC_QUOTATION_MARK:
case ESC_REVERSE_SOLIUDS:
case ESC_SOLIDUS:
currentString << next();
break;
case ESC_UNICODE:
// a \u occured
// read the following sequence and insert it's
// unicode representation into the string.
readUTF8Escape();
break;
default:
throw std::runtime_error("Parse error in escape sequence");
}
}
inline void Parser::readUTF8Escape() {
consume(); // u
int codePoint = -1;
std::string tmp(4,32);
std::stringstream ss;
std::string result;
wideString str32;
for (unsigned int index=0;index<tmp.length();index++) {
if (!hasNext() || !validHexDigit(peek())) {
throw std::runtime_error("Parse error in UTF8");
}
tmp[index] = next();
}
ss << std::hex << tmp;
ss >> codePoint;
str32.push_back(codePoint);
utf8::utf32to8(str32.begin(), str32.end(), std::back_inserter(result));
currentString << result;
}
/**
* [...]
*/
inline void Parser::parseArray() {
consume(); // '['
objectStack.push(&store(Array {}));
clearWhitespace();
// Empty array?
if (peek() == ']') {
consume(); // ']'
objectStack.pop();
return;
}
while(hasNext()) {
parseValue();
clearWhitespace();
if (peek() != ',') {
break;
} else {
consume(); // ','
}
}
if (peek() != ']') {
throw std::runtime_error("Parse error in array");
} else {
consume(); // ']'
}
objectStack.pop();
}
/**
* Entry points
*/
inline void Parser::parse(Value& value, const std::string &source) {
reset();
if (source.length() > 0) {
value = null;
this->source = source;
objectStack.push(&value);
parseValue();
clearWhitespace();
if (parseIndex < source.length()) {
throw std::runtime_error("Parse error");
}
}
}
inline void Parser::parse(Value& value, const char *source) {
std::string _source(source);
parse(value, _source);
}
}
#endif // PARSER_H
| [
"pbraun@redhat.com"
] | pbraun@redhat.com |
e11b1d206ca8dd6972dd853436706ae2df59e0a4 | d374c5b0caf4c375069f77c0efc6fc08867a3635 | /SurfaceReconstruction/SurfaceReconstruction/Scene/Tree/NodesIterator.h | f61a4c920339b6b253c102f1a09c3724b4e7c34f | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | namibj/TSR | 7466750b09caaf1d470d0f042c7e60877fcf8fc4 | df14f4a9fc175b2a6b0c14b3ace924f2364afe7b | refs/heads/master | 2021-07-20T03:02:56.959890 | 2020-07-01T17:37:42 | 2020-07-01T17:37:42 | 195,549,270 | 0 | 0 | NOASSERTION | 2019-07-06T14:36:14 | 2019-07-06T14:36:14 | null | UTF-8 | C++ | false | false | 4,046 | h | /*
* Copyright (C) 2018 by Author: Aroudj, Samir
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the License.txt file for details.
*/
#ifndef _SCENE_TREE_NODES_ITERATOR_H_
#define _SCENE_TREE_NODES_ITERATOR_H_
#include <vector>
#include "Platform/DataTypes.h"
#include "SurfaceReconstruction/Scene/Tree/NodesChecker.h"
#include "SurfaceReconstruction/Scene/Tree/Nodes.h"
// todo comments
namespace SurfaceReconstruction
{
// forward Declarations
class Tree;
class NodesIterator
{
public:
NodesIterator(const Tree &tree, const NodesChecker *nodesChecker = NULL);
~NodesIterator();
inline uint32 getDepth() const;
/** Returns the index of the node (relative to the nodes entered in the constructor) at which this iterator currently points or
Nodes::INVALID_INDEX if the iterator went through all non-ignored nodes and points at the end.
@return Returns Nodes::INVALID_INDEX if isAtTheEnd is true or the current node index (index is relative to the entered nodes). */
inline uint32 getNodeIndex() const;
/** Returns the scope of the node the iterator currently points at.
@return The returnded scope identifies and describes the extent of the node at which this iterator currently points. */
inline Scope getScope() const;
/** Returns true if the iterator currently points at a leaf node.
@return Returns true if the iterator is currently at a leaf node without children.*/
inline bool isAtLeaf() const;
/** Returns true if there are no nodes to be traversed anymore.
@return Returns false if the iterator has not gone over all nodes yet. */
inline bool isAtTheEnd() const;
/** Goes through the nodes in depth first order whereas the iterator stops / goes over the parent node first.
In particular, the order of node traversal is: 0.: current node; 1.: for all children: traverseNodes(child i).\n
For example, for a tree with only 3 layers (root node, child nodes & grand child nodes):\n
node,\n
child 0, grand child 0/0, ..., grand child 0/Nodes::CHILD_COUNT - 1,\n
child 1, grand child 1/0, ..., grand child 1/Nodes::CHILD_COUNT - 1,\n
child 2, grand child 2/0, ..., grand child 2/Nodes::CHILD_COUNT - 1, ...\n
*/
void goToNext();
/** Goes through the nodes as defined by goToNext().
@see See goToNext().*/
inline void operator ++();
private:
bool goDown();
void popStack();
protected:
// stack for nodes traversal
std::vector<uint32> mChildIndices; /// Stores for each stack layer / tree level the current relative child which is currently traversed.
std::vector<Scope> mScopes; /// Stores for each stack layer / tree level the current scope of the node which is currently traversed.
// nodes which are traversed
const Nodes &mNodes; /// These nodes are traversed by this iterator.
const NodesChecker *mChecker; /// Test whether nodes are ignored during traversal.
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// inline function definitions ////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline uint32 NodesIterator::getDepth() const
{
return (uint32) (mChildIndices.size() - 1);
}
inline uint32 NodesIterator::getNodeIndex() const
{
if (isAtTheEnd())
return Nodes::INVALID_INDEX;
return mScopes.back().getNodeIndex();
}
inline Scope NodesIterator::getScope() const
{
if (isAtTheEnd())
return Scope();
return mScopes.back();
}
inline bool NodesIterator::isAtLeaf() const
{
return mNodes.isLeaf(getNodeIndex());
}
inline bool NodesIterator::isAtTheEnd() const
{
return mScopes.empty();
}
inline void NodesIterator::operator ++()
{
goToNext();
}
}
#endif // _SCENE_TREE_NODES_ITERATOR_H_ | [
"samir.aroudj@gris.informatik.tu-darmstadt.de"
] | samir.aroudj@gris.informatik.tu-darmstadt.de |
48e8610dad01da384eccb01b3d720d7345196b3e | 6774aefed7980c80def661120198c8c28cbe25bd | /Engine/Crypto/MD5.h | b7ecbc48f2ca8264231c3ffed89284742617dba3 | [] | no_license | Nekuromento/SDL2D | 0faf082d4bc09d4e3d23b0d7fdaba75238fad445 | 0c3d27dec7b7044beb5b865fa2be5e8308589e92 | refs/heads/master | 2021-01-21T22:26:05.950288 | 2014-10-07T09:55:49 | 2014-10-07T09:55:49 | 14,039,330 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 996 | h | #pragma once
#include <cstdlib>
class String;
struct MD5 {
// By default overload resolution always uses 'const uint8_t*' constructor
// even for static arrays, so we fix that with a wrapper
// with implicit constructor
struct ConstByte {
const uint8_t* const data;
ConstByte(const uint8_t* const data) :
data{ data }
{}
};
static const size_t Size = 16;
static const size_t BlockSize = 64;
struct Digest {
uint8_t data[Size];
bool operator== (const Digest& other);
bool operator!= (const Digest& other);
String toString();
};
Digest operator() (ConstByte data, const size_t length);
template<size_t N>
Digest operator() (const uint8_t (&data)[N], const size_t length = N) {
const uint8_t* const bytes = data;
return operator() (bytes, length < N ? length : N);
}
Digest operator() (const String& data);
};
| [
"max.klyga@gmail.com"
] | max.klyga@gmail.com |
d7045c763c11126441ccc506a87b9b2ff0b3a916 | b384a418e620ab14f7fb4d6b4c21e1e11b4ebd6b | /NinjaGaiden/Game/Object/Enemy/Bird.cpp | cbeeeddbdb1b241fbd77b32a558ff3f7fabdef8c | [] | no_license | jokojookoo0104/game | 7bcfb48759b4588327ea14ca87bf20c686ae611e | c60f463c72d393fb750bca5c17133f59350bb6b7 | refs/heads/master | 2022-01-09T01:18:46.321894 | 2019-06-14T17:36:44 | 2019-06-14T17:36:44 | 177,139,674 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,450 | cpp | #include "Bird.h"
#include "../Player/Player.h"
#include "../../Logging/Debug.h"
#include <math.h>
#include "../../Framework/MCIPlayer.h"
Brid::Brid() {
}
void Brid::init() {
this->SetObjectType(BRID);
this->position.z = 0.0f;
this->isActive = false;
objectHeight = objectWidth = 1;
SetVeclocity(0.0f, 0.0f);
top = bottom = 0;
isCollidePlayer = false;
state = FOLLOW;
finishFly = 0;
destination = 0;
score = 300;
time = 0;
this->sprite = new map<ENEMY_STATE, Sprite*>();
this->sprite
->insert(pair<ENEMY_STATE, Sprite*>(ENEMY_STATE::FOLLOW,
new Sprite(TEXTURE->Get(ID_TEXTURE_MAP_1_ENEMY), PATH_TEXTURE_MAP_1_ENEMY_Eagle_follow, 2, 0.075f)));
this->sprite
->insert(pair<ENEMY_STATE, Sprite*>(ENEMY_STATE::DEAD,
new Sprite(TEXTURE->Get(ID_TEXTURE_MAP_1_ENEMY_DIE_FIRE), PATH_TEXTURE_MAP_1_ENEMY_ENEMY_DIE, 3, 0.03f)));
}
Brid::Brid(vector<int> activeArea, int positionX, int positionY) {
this->activeArea = activeArea;
SetPosition(positionX, positionY);
init();
}
Brid::~Brid() {
if (this->sprite != NULL) {
for (auto i = this->sprite->begin(); i != this->sprite->end(); i++) {
delete i->second;
this->sprite->erase(i);
}
delete this->sprite;
}
}
void Brid::UpdatteActiveArea(float t) {
if (state == DEAD && !isActive) {
if (PLAYER->GetPosition().x >= activeArea.at(0)
&& PLAYER->GetPosition().x <= activeArea.at(1)
&& PLAYER->GetDirection() == RIGHT) {
this->sprite->at(ENEMY_STATE::DEAD)->Reset();
SetPosition(lastPos.x, lastPos.y);
state = FOLLOW;
isActive = true;
direction = LEFT;
}
else {
if (PLAYER->GetPosition().x >= activeArea.at(2)
&& PLAYER->GetPosition().x <= activeArea.at(3)
&& PLAYER->GetDirection() == LEFT) {
this->sprite->at(ENEMY_STATE::DEAD)->Reset();
SetPosition(lastPos.x, lastPos.y);
state = FOLLOW;
isActive = true;
direction = RIGHT;
}
}
if (direction == RIGHT) {
SetVx(200.0f);
SetVy(0.0f);
}
if (direction == LEFT) {
SetVx(-200.0f);
SetVy(0.0f);
}
}
if (!isActive && state != DEAD) {
if (PLAYER->GetPosition().x >= activeArea.at(0)
&& PLAYER->GetPosition().x <= activeArea.at(1)
&& PLAYER->GetDirection() == RIGHT) {
isActive = true;
direction = LEFT;
SetVx(-200.0f);
}
else {
if (PLAYER->GetPosition().x >= activeArea.at(2)
&& PLAYER->GetPosition().x <= activeArea.at(3)
&& PLAYER->GetDirection() == LEFT) {
isActive = true;
direction = RIGHT;
SetVx(200.0f);
}
}
}
}
void Brid::FollowPlayer(float t) {
if (direction == LEFT) {
if (position.x < PLAYER->GetPosition().x) {
direction = RIGHT;
}
}
if (direction == RIGHT) {
if (position.x > PLAYER->GetPosition().x) {
direction = LEFT;
}
}
int width = GetBoundingBox().right - GetBoundingBox().left;
float dx = 0;
RECT rect = PLAYER->GetBoundingBox();
if (position.x > PLAYER->GetPosition().x) {
dx = GetBoundingBox().left - rect.right;
}
else {
dx = rect.left - GetBoundingBox().right;
}
if (veclocity.x < 0) {
if (dx <= 10) {
destination = PLAYER->GetPosition().x - 190.0f;
}
else if (dx <= 30 && dx > 10) {
destination = PLAYER->GetPosition().x - 150.0f;
}
else if (dx <= 100 && dx > 30) {
destination = PLAYER->GetPosition().x - 100.0f;
}
if (position.x - width < destination && dx < 75 && veclocity.x > -310) {
SetVx(0);
finishFly = 1;
}
}
else if (veclocity.x > 0) {
if (dx <= 10) {
destination = PLAYER->GetPosition().x + 190.0f;
}
else if (dx <= 30 && dx > 10) {
destination = PLAYER->GetPosition().x + 150.0f;
}
else if (dx <= 100 && dx > 30) {
destination = PLAYER->GetPosition().x + 100.0f;
}
if (position.x + width > destination && dx < 75 && veclocity.x < 310) {
SetVx(0);
finishFly = 2;
}
}
else {
if (finishFly == 1 || finishFly == 2) {
if (time >= 0.125f) {
time = 0;
finishFly = 0;
}
else {
time += t;
if (position.y > PLAYER->GetPosition().y + 10) {
SetVy(50);
}
}
}
}
if (finishFly == 0) {
float vy = PLAYER->GetVeclocity().y;
veclocity.y = vy * 0.5;
float distanceX = PLAYER->GetPosition().x - position.x;
float log = log10(abs((distanceX)) * 30 + 10);
log = (exp(0.75 + log)) / 40;
veclocity.x += distanceX < 0 ? log * -1 : log;
float temp = (PLAYER->GetPosition().y + 2 - position.y);
if (temp < 45 && temp > 0) {
temp += 45;
}
temp = temp < 0 ? temp : temp;
veclocity.y += temp;
}
}
void Brid::Update(float t, vector<Object*>* object) {
if (PLAYER->isFreezeTime()) {
if (isActive) {
SetVeclocity(0, 0);
Object::Update(t);
HandleCollision(object);
PLAYER->KillEnemy(this);
if (state == DEAD) {
sprite->at(this->state)->NextSprite(t);
if (sprite->at(this->state)->GetIsComplete()) {
sprite->at(this->state)->SetIndex(2);
sprite->at(this->state)->SetScale(1.0f);
isActive = false;
}
this->sprite->at(ENEMY_STATE::FOLLOW)->Reset();
SetVx(0.0f);
}
}
return;
}
UpdatteActiveArea(t);
if (isActive) {
Object::Update(t);
RECT rect = sprite->at(this->state)->GetBoudingBoxFromCurrentSprite();
Object::updateBoundingBox(rect);
sprite->at(this->state)->NextSprite(t);
if (state != DEAD) {
HandleCollision(object);
FollowPlayer(t);
PLAYER->KillEnemy(this);
}
else {
if (sprite->at(this->state)->GetIsComplete()) {
sprite->at(this->state)->SetIndex(2);
sprite->at(this->state)->SetScale(1.0f);
state = DEAD;
SetPosition(lastPos.x, lastPos.y);
isActive = false;
}
}
}
}
void Brid::Dead() {
state = DEAD;
SetVeclocity(0.0f, 0.0f);
objectHeight = objectWidth = 1;
time = 0;
destination = 0;
PLAYER->AddScore(this->score);
MCIPLAYER->Play(SOUND_ENEMY_DIE);
}
void Brid::HandleCollision(vector<Object*>* object) {
vector<CollisionHandler*>* coEvents = new vector<CollisionHandler*>();
vector<CollisionHandler*>* coEventsResult = new vector<CollisionHandler*>();
coEvents->clear();
if (isActive) {
Object::CalcPotentialCollisions(object, coEvents);
}
if (coEvents->size() == 0) {
Object::PlusPosition(this->deltaX, this->deltaY);
}
else {
float min_tx, min_ty, nx = 0, ny;
this->FilterCollision(coEvents, coEventsResult, min_tx, min_ty, nx, ny);
this->PlusPosition(min_tx * this->deltaX + nx * 0.2f, min_ty*this->deltaY + ny * 0.2f);
for (UINT i = 0; i < coEventsResult->size(); i++) {
CollisionHandler* e = coEventsResult->at(i);
if (e->object->GetObjectType() == OBJECT_TYPE::MAIN_CHARACTER) {
if (!PLAYER->GetWounded()) {
if (PLAYER->GetState() == JUMP_ATK) {
state = ENEMY_STATE::DEAD;
MCIPLAYER->Play(SOUND_ENEMY_DIE);
PLAYER->AddScore(score);
}
else {
PLAYER->Wounded(e->nx, e->ny, this, direction);
}
}
if (e->nx != 0) {
Object::PlusPosition(this->deltaX, 0.0f);
}
if (e->ny != 0) {
Object::PlusPosition(0.0f, this->deltaY);
}
continue;
}
else if (e->object->GetObjectType() == OBJECT_TYPE::SQUARE) {
if (e->nx != 0) {
Object::PlusPosition(this->deltaX, 0.0f);
}
if (e->ny != 0) {
Object::PlusPosition(0.0f, this->deltaY);
}
}
}
}
for (UINT i = 0; i < coEvents->size(); i++) {
delete coEvents->at(i);
}
coEventsResult->clear();
delete coEvents;
delete coEventsResult;
}
void Brid::Render() {
if (isActive) {
switch (this->direction) {
case RIGHT:
if (state == ENEMY_STATE::DEAD) {
sprite->at(this->state)->SetScale(sprite->at(this->state)->GetScale() + 0.015f);
sprite->at(this->state)->DrawSprite(Object::GetTransformObjectPositionByCamera(), true, -5, -5);
}
else {
sprite->at(this->state)->DrawSprite(Object::GetTransformObjectPositionByCamera(), true);
}
break;
case LEFT:
if (state == ENEMY_STATE::DEAD) {
sprite->at(this->state)->SetScale(sprite->at(this->state)->GetScale() + 0.015f);
sprite->at(this->state)->DrawSprite(Object::GetTransformObjectPositionByCamera(), false, -5, -5);
}
else {
sprite->at(this->state)->DrawSprite(Object::GetTransformObjectPositionByCamera(), false);
}
break;
default:
break;
}
}
}
void Brid::ResetState() {
if (isActive) {
isActive = false;
SetPosition(lastPos.x, lastPos.y);
SetVx(0.0f);
SetVy(0.0f);
if (this->state == DEAD) {
this->sprite->at(ENEMY_STATE::DEAD)->Reset();
sprite->at(this->state)->SetScale(1.0f);
}
state = ENEMY_STATE::FOLLOW;
objectHeight = objectWidth = 1;
}
}
| [
"37903274+jokojookoo0104@users.noreply.github.com"
] | 37903274+jokojookoo0104@users.noreply.github.com |
96fa4db9856ff7d827b318bbab789ed44e4fb77d | de31c132730cb32c46454b168e5b682461c53516 | /API/Support/oldOpenCVcppCode/source/pyramid-template-matcher.h | aa9a17b7fcb6a062077cabeb5106a0ef2a87d0d3 | [
"MIT"
] | permissive | kensoh/SikuliX1 | a70c0c4d26fdcf159139ac2e8711ac612982025a | a4feaa44c83bc75ff2541dd3eaba454dd216f9bf | refs/heads/master | 2020-07-31T06:49:39.935035 | 2019-09-17T07:08:48 | 2019-09-17T07:08:48 | 210,520,732 | 1 | 0 | MIT | 2019-09-24T05:41:36 | 2019-09-24T05:41:36 | null | UTF-8 | C++ | false | false | 3,453 | h | /*
* Copyright 2010-2016, Sikuli.org, sikulix.com
* Released under the MIT License.
*
*/
#ifndef _PYRAMID_TEMPLATE_MATCHER_
#define _PYRAMID_TEMPLATE_MATCHER_
#include <stdio.h>
#include <iostream>
#include "opencv.hpp"
#include "find-result.h"
#include "vision.h"
#ifdef ENABLE_GPU
#include <opencv2/gpu/gpu.hpp>
#endif
// select how images are downsampled
#define USE_RESIZE 1
#define USE_PYRDOWN 0
using namespace cv;
using namespace std;
struct MatchingData {
Mat source, target;
Mat source_gray, target_gray;
Scalar mean, stddev;
bool use_gray;
inline MatchingData(){
}
inline MatchingData(const Mat& source_, const Mat& target_) : source(source_), target(target_){
use_gray = false;
meanStdDev( target, mean, stddev );
}
inline MatchingData createSmallData(float factor){
Mat new_source, new_target;
resize(source, target, new_source, new_target, factor);
MatchingData newData(new_source, new_target);
if(use_gray)
newData.useGray(true);
return newData;
}
inline void resize(const Mat& source, const Mat& target, Mat& out_source, Mat& out_target, float factor){
#if USE_PYRDOWN
// Faster
pyrDown(source, out_source);
pyrDown(target, out_target);
#endif
#if USE_RESIZE
cv::resize(source, out_source, Size(source.cols/factor, source.rows/factor),INTER_NEAREST);
cv::resize(target, out_target, Size(target.cols/factor, target.rows/factor),INTER_NEAREST);
#endif
}
inline bool isSameColor() const{
return stddev[0]+stddev[1]+stddev[2]+stddev[3] <= 1e-5;
}
inline bool isBlack() const{
return (mean[0]+mean[1]+mean[2]+mean[3] <= 1e-5) && isSameColor();
}
inline bool isSourceSmallerThanTarget() const{
return source.rows < target.rows || source.cols < target.cols;
}
inline const Mat& getOrigSource() const{
return source;
}
inline const Mat& getOrigTarget() const{
return target;
}
inline const Mat& getSource() const{
return use_gray? source_gray : source;
}
inline const Mat& getTarget() const{
return use_gray? target_gray : target;
}
inline bool useGray() const{
return use_gray;
}
inline bool useGray(bool flag){
use_gray = flag;
if(use_gray){
cvtColor(source, source_gray, CV_RGB2GRAY);
cvtColor(target, target_gray, CV_RGB2GRAY);
}
return flag;
}
inline void setSourceROI(const Rect& roi){
if(use_gray)
source_gray.adjustROI(roi.y, roi.y+roi.height, roi.x, roi.x+roi.width);
else
source.adjustROI(roi.y, roi.y+roi.height, roi.x, roi.x+roi.width);
}
};
class PyramidTemplateMatcher{
private:
bool _use_gpu;
void init();
public:
PyramidTemplateMatcher(){
init();
}
PyramidTemplateMatcher(const MatchingData& data, int levels, float factor);
~PyramidTemplateMatcher();
virtual FindResult next();
protected:
PyramidTemplateMatcher* createSmallMatcher(int level);
double findBest(const MatchingData& data, Rect* roi, Mat& out_result, Point& out_location);
void eraseResult(int x, int y, int xmargin, int ymargin);
FindResult nextFromLowerPyramid();
MatchingData data;
float factor;
bool _hasMatchedResult;
double _detectedScore;
Point _detectedLoc;
PyramidTemplateMatcher* lowerPyramid;
Mat result;
#ifdef ENABLE_GPU
gpu::GpuMat gResult;
#endif
};
#endif
| [
"rmhdevelop@me.com"
] | rmhdevelop@me.com |
3ec4dada957eafd634da74dbe32ad064561c7c48 | 7109a13d884a642ffacd235421fca80367be9648 | /uva/10300/10300.cpp | 474a9fe3caa469e85d3d8fafe1e03cce397f9de5 | [
"MIT"
] | permissive | Diamond-Dewan/OnlineJudgeProblemSolution | 9c57b658589d616365fcc0e3e5a25e15c8afd1c2 | 87f97d22959e61606cc05e254f87f15f7534c01b | refs/heads/master | 2021-01-22T21:49:17.184968 | 2017-03-19T11:36:22 | 2017-03-19T11:36:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 356 | cpp | #include<stdio.h>
int main()
{
long long a,t,n,b,c,i,j,s;
while(scanf("%lld",&t)==1)
{
for(i=0;i<t;i++)
{
s=0;
scanf("%lld",&n);
for(j=0;j<n;j++)
{
scanf("%lld %lld %lld",&a,&b,&c);
s+=a*c;
}
printf("%lld\n",s);
}
}
return 0;
}
| [
"shipuahamed01@gmail.com"
] | shipuahamed01@gmail.com |
1cd4ef6444af7fcf6bb3877247cbb61f8f4f58e0 | f7d1bdcbfb65712fe6abdc6016a3351c1723e0c6 | /5.Transition/Dokumentation/Bilag/Kode/Drone/flightControl.h | 0af619d0688ed48b1ed513b467e333236246ff26 | [] | no_license | Opstrup/quadrocopter_bachelor | 3e4d9f435b46b556a405196855be73669c78aae4 | bfd2c1f380825177b87b334b7f3c84260ff34d5a | refs/heads/master | 2020-06-11T18:56:46.859606 | 2015-01-14T19:18:31 | 2015-01-14T19:18:31 | 19,458,733 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | h | #ifndef flightControl
#include <avr/io.h>
#include "Arduino.h"
#pragma once
class flightControl
{
public:
flightControl();
boolean checkIfControllerIsOn();
float getBearingFromCompas();
float calDistToTarget(float current_lat, float current_long, float target_lat, float target_long);
float calBearingToTarget(float current_lat, float current_long, float target_lat, float target_long);
void initMotors();
void calibrateMotors();
void setPWM(int change_value, String mode);
void armMotors();
void disarmMotors();
void throttle(int);
void yaw(int);
void pitch(int);
void roll(int);
void flightmode(int);
void alttitudehold(int);
private:
};
#endif | [
"the-twin@hotmail.com"
] | the-twin@hotmail.com |
fb09b731406a43f951d839d8fae8c71184a84a12 | c7083e834d7390b22aeeb214c201b9508026515b | /HelloGL/HelloGL/GLUTCallbacks.cpp | a334a6d05cefbdb1d925b98cbe301574f770aadd | [] | no_license | OP3-Daodu/OpenGL-1 | 26cd27faf2c12400666ab9aa576b3d6e5b19fc33 | 002694d359425b33a084d0534ba942b2f3877575 | refs/heads/master | 2022-12-10T04:21:05.002687 | 2020-08-13T20:40:02 | 2020-08-13T20:40:02 | 287,375,050 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 822 | cpp | // Includes
#include "GLUTCallbacks.h"
#include "HelloGL.h"
// Namespace implementation
namespace GLUTCallbacks
{
namespace
{
// Initialise to a null pointer before we do anything
HelloGL* helloGL = nullptr;
}
void Init(HelloGL* gl)
{
helloGL = gl;
}
void Display()
{
if (helloGL != nullptr)
{
helloGL->Display();
}
}
void Timer (int preferredRefresh)
{
if (helloGL != nullptr)
{
int updateTime = glutGet(GLUT_ELAPSED_TIME);
helloGL->Update();
updateTime = glutGet(GLUT_ELAPSED_TIME) - updateTime;
glutTimerFunc(preferredRefresh - updateTime, GLUTCallbacks::Timer, preferredRefresh);
}
}
void Keyboard(unsigned char key, int x, int y)
{
if (helloGL != nullptr)
{
helloGL->Keyboard(key, x, y);
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
8d9b7155874574263e8f5b36aca7d47b0fe878db | 44c060728c7267a09757849aef85d5f57b808bd6 | /Addons/itc_land_common/config/ui/defines.hpp | 99b81dd2181a4bf2417707d8292857c59da17a9e | [] | no_license | itc-addons/ITC_Land_Systems | 0813486c27128e03dc51208a07f37071b50db859 | e1d09001a2f9b8583a523b9342a3dfac7aae3034 | refs/heads/master | 2022-06-10T05:33:35.014197 | 2022-03-01T22:25:46 | 2022-03-01T22:25:46 | 129,454,155 | 16 | 9 | null | 2021-03-08T21:15:10 | 2018-04-13T21:15:08 | SQF | UTF-8 | C++ | false | false | 1,666 | hpp | #define GUI_GRID_W (0.025)
#define GUI_GRID_H (0.04)
#define CT_STATIC 0
#define CT_BUTTON 1
#define CT_EDIT 2
#define CT_SLIDER 3
#define CT_COMBO 4
#define CT_LISTBOX 5
#define CT_TOOLBOX 6
#define CT_CHECKBOXES 7
#define CT_PROGRESS 8
#define CT_HTML 9
#define CT_STATIC_SKEW 10
#define CT_ACTIVETEXT 11
#define CT_TREE 12
#define CT_STRUCTURED_TEXT 13
#define CT_CONTEXT_MENU 14
#define CT_CONTROLS_GROUP 15
#define CT_XKEYDESC 40
#define CT_XBUTTON 41
#define CT_XLISTBOX 42
#define CT_XSLIDER 43
#define CT_XCOMBO 44
#define CT_ANIMATED_TEXTURE 45
#define CT_OBJECT 80
#define CT_OBJECT_ZOOM 81
#define CT_OBJECT_CONTAINER 82
#define CT_OBJECT_CONT_ANIM 83
#define CT_LINEBREAK 98
#define CT_USER 99
#define CT_MAP 100
#define CT_MAP_MAIN 101 // Static styles
#define ST_POS 0x0F
#define ST_HPOS 0x03
#define ST_VPOS 0x0C
#define ST_LEFT 0x00
#define ST_RIGHT 0x01
#define ST_CENTER 0x02
#define ST_DOWN 0x04
#define ST_UP 0x08
#define ST_VCENTER 0x0c
#define ST_TYPE 0xF0
#define ST_SINGLE 0
#define ST_MULTI 16
#define ST_TITLE_BAR 32
#define ST_PICTURE 48
#define ST_FRAME 64
#define ST_BACKGROUND 80
#define ST_GROUP_BOX 96
#define ST_GROUP_BOX2 112
#define ST_HUD_BACKGROUND 128
#define ST_TILE_PICTURE 144
#define ST_WITH_RECT 160
#define ST_LINE 176
#define ST_SHADOW 0x100
#define ST_NO_RECT 0x200
#define ST_KEEP_ASPECT_RATIO 0x800
#define ST_TITLE ST_TITLE_BAR + ST_CENTER
// Slider styles
#define SL_DIR 0x400
#define SL_VERT 0
#define SL_HORZ 0x400
#define SL_TEXTURES 0x10
// Listbox styles
#define LB_TEXTURES 0x10
#define LB_MULTI 0x20
#define FontM "TahomaB"
#define ROWPOS(y) ((0.015*y)*SafeZoneW)
#define COLPOS(x) ((0.015*x)*SafeZoneW) | [
"asmsandrew@googlemail.com"
] | asmsandrew@googlemail.com |
5e54260f2dfc1e497686cff8553846433013d260 | 9cb280bce37dc0c8b91ed271dc3fa7b9b06b39b0 | /practice/forloop.cpp | 6103e7c7d77cd3ad088faba37b4ac6593b0ffbfc | [] | no_license | bhattathakur/ResearchStuff | 158d0039f05eb3d4a8c1f98943aa0821a543757c | 7d8fc4caff553bd69f31b8b89193b028c2bf19c7 | refs/heads/master | 2020-03-22T22:50:57.103338 | 2018-07-13T00:43:59 | 2018-07-13T00:43:59 | 140,773,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 135 | cpp | #include<iostream>
using namespace std;
int main()
{
for(int i=0;i<70;i++)
{
cout<<"__";
cout<<"__";
}
return 0;
} | [
"bhattathakur2015@gmail.com"
] | bhattathakur2015@gmail.com |
5b9bfdbb6584935fa8be1e02e3dd47ebdf27cc31 | 69b646aed85d1ddd36a16be6e430b0eeb3a484ba | /Semester 5/PDP/tema6/main.cpp | c250c6a3fcf3735ba32c502f833ddf533da27fd9 | [] | no_license | cinnamonbreakfast/uni_implementations | 90e73685bc05a16261a4552be752086bdb7d60da | 382323c5ae1b919dcc59212e4a0036d9fe845d9d | refs/heads/master | 2021-06-16T04:54:46.505269 | 2021-04-02T16:56:08 | 2021-04-02T16:56:08 | 186,228,326 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,517 | cpp | #include <iostream>
#include "helper.h"
#include "thread_pool.h"
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
std::atomic<int> count(0);
int trials = 10;
void hamiltonian_task(
const std::vector<int>& permutation,
const std::shared_ptr<Graph>& graph,
std::atomic<bool> &foundFlag
) {
count++;
if (count % 1000 == 0)
std::cout << count << '\n';
int n = permutation.size();
for(int i = 0; i < n - 1; i++) {
if (!graph->is_neighbour(permutation[i], permutation[i+1])) {
return;
}
}
if(!graph->is_neighbour(permutation[n - 1], permutation[0])) {
return;
}
print_hamiltonian_path(permutation);
foundFlag = true;
}
void experiment(
std::shared_ptr<std::vector<std::vector<int>>> perms,
std::shared_ptr<Graph> graph,
int num_threads, int trial_c,
std::atomic<bool> &foundFlag
) {
std::cout << "EXPERIMENT " << num_threads << ' ' << trial_c << "/ " << trials << '\n';
count = 0;
sleep(2);
auto thread_pool = std::make_shared<ThreadPool>(num_threads);
for(int i = 0; i < perms->size(); i++) {
if (foundFlag) break;
thread_pool->enqueue([i, &perms, &graph, &foundFlag] () {
hamiltonian_task((*perms)[i], graph, foundFlag);
});
}
thread_pool->close();
}
int main() {
srand(0); // NOLINT(cert-msc51-cpp)
int n = 8;
auto perms = generate_permutations(n);
std::cout << "TOTAL " << perms->size() << '\n';
auto graph = generate_graph(n, 0.15);
graph->printGraph();
sleep(5);
for(int tr = 1; tr <= 10; tr++) {
std::atomic<bool> isHamiltonian(false);
double executionTime = 0;
double time, mean, variance;
std::vector<double> timings;
timings.reserve(trials);
for(int trial_c = 0; trial_c < trials; trial_c++) {
time = time_execution_seconds([&perms, &graph, tr, trial_c, &isHamiltonian] () {
experiment(perms, graph, tr, trial_c, isHamiltonian);
});
executionTime += time;
timings.push_back(time);
}
mean = executionTime / trials;
variance = calculate_variance(timings, mean);
std::cout << "HAMILTONIAN " << tr << (isHamiltonian ? " TRUE " : " FALSE ")
<< "MEAN " << mean << " VARIANCE " << variance << '\n';
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
706cc20e0107709b5b18afb875df34a886f95380 | 071dbdd1546d8ca65f927001d6a65c4f93ae1d39 | /C++pra/C++pra/ShotPower.h | 8e43a5ddd82ca809ad5b439495d50378676ef688 | [] | no_license | tmykmrt/Shooting_Game | 17f00b1ef1092808a081c87f25569335452bf536 | 902c27748dcb0b14ee94c72850dd8e11351f6155 | refs/heads/master | 2020-04-03T06:09:07.582843 | 2019-06-15T07:00:15 | 2019-06-15T07:00:15 | 155,067,136 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 549 | h | #pragma once
#include"NumRange.h"
/**
* @file PlayerShotTrigger.h
* @brief 射撃に必要な力の管理
* @date 2019 1/1
*/
class ShotPower
{
public:
ShotPower();
ShotPower(float max,float recoveFrame);
~ShotPower();
void Init(float max, float recoveFrame);
// 消費する
void Consume(float usePow);
// 使用する力が足りているか
bool IsEnough(float usePower);
// チャージ
void Chage();
// 割合
// ※一時的な
float Rate();
NumRange* NowPow();
private:
NumRange pow;
// チャージ値
float recovePow;
};
| [
"xyz2ndg@gmail.com-"
] | xyz2ndg@gmail.com- |
97c7a468d0ef0c6517b61b15259a3298c0ec3a8f | ab48480d3ef86da74f705bec321b72f702098dff | /PolygonRender/model.h | 8f9184db361461e64ea3b534a464eff5c073b7a1 | [] | no_license | gra98rus/Graphics | f1434c3d152cd1be383985482d8621a6fa2aa0a3 | cd67122661ca44442a266a52e556dc3c3883e698 | refs/heads/master | 2020-12-22T04:53:15.433952 | 2020-01-28T06:41:59 | 2020-01-28T06:41:59 | 228,612,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,494 | h | #ifndef MODEL_H
#define MODEL_H
#include <QImage>
#include "spline.h"
#include "item.h"
#include "systemcoordtransformer.h"
#include <QVector>
#include "camera.h"
#include "lightsource.h"
class Model
{
public:
Model();
void draw(QImage &image);
void drawSpline(bool pointDraw, QImage &image);
void addPointSpline(double x, double y);
void addSplineForItem(Spline & spline, double x, double y, double z, double scale);
void deleteLastItem();
void drawCube(QImage &image);
void addRotate(double alpha, double betta);
void setScaleItem(double scale, int i);
void setXItem(double x, int i);
void setYItem(double y, int i);
void setZItem(double z, int i);
void set_nItem(int n, int i);
void set_kItem(int k, int i);
Spline getSpline(int i);
void setSpline(Spline spline, int i);
private:
SystemCoordTransformer transformer;
double xMaxModel = 100;
double yMaxModel = 100;
double zMaxModel = 100;
QVector<Spline*> splines;
QVector<Item*> items;
Camera camera;
LightSource lightSourse;// = LightSource(QVector4D(2, 2, 2, 1));
QVector<QVector2D> controlPoints = {QVector2D(100, 100), QVector2D(150, 120), QVector2D(400, 500), QVector2D(800, 700), QVector2D(900, 920), QVector2D(700, 300)};
Spline splineTest = Spline(controlPoints);
Item * itemTest = new Item(splineTest, 0, 0, 0, 1);
};
#endif // MODEL_H
| [
"gra98rus@yandex.ru"
] | gra98rus@yandex.ru |
fb40b70fbe5e42ed3b0fdace88eb646c36c9b99c | 1df31d68f2d63939a95c6dd29eb550f99a2421a3 | /80/80/80.cpp | 35a17e0b28df26a72a53333b26963b9737e7cb18 | [] | no_license | o0serena0o/2020_koi | 85f941fc70aa41ee7fca5b70eb3da4de2f9fb033 | 985290d94af590651b4d38857f74f76a0e22ad1f | refs/heads/master | 2020-12-26T18:24:07.757933 | 2020-07-04T06:16:49 | 2020-07-04T06:16:49 | 237,595,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 307 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
int main()
{
int a = 0, b = 0;
int k = 0, j = 0;
scanf_s("%d %d", &a, &b);
for (int i = a; i <= b; i++)
{
if (i % 2 == 0)
{
k = k + i;
}
if (i % 2 != 0)
{
j = j + i;
}
}
printf("짝수합 : %d 홀수합 : %d", k, j);
} | [
"57519051+o0serena0o@users.noreply.github.com"
] | 57519051+o0serena0o@users.noreply.github.com |
b77cd8c5ffee026b47b0e5b631df1415107f94aa | 34a85ceb59766ca7e9f0e0d071ee0424962cb85c | /src/lectureFichiers.cpp | 42db8c6cbe09f9c06f08198e452757c2bb871549 | [] | no_license | LogicalKip/CUR | c807c0371fae9998a47d980c3c22c55b382c8dc5 | f549149fd16ef55c867a467fe287e3e96ab89cec | refs/heads/master | 2021-01-21T21:54:32.712761 | 2016-03-14T09:09:30 | 2016-03-14T09:09:30 | 18,462,292 | 0 | 2 | null | null | null | null | ISO-8859-1 | C++ | false | false | 9,440 | cpp |
#include <iostream>
#include <fstream>
#include "../include/main.hpp"
#include "../include/constantes.hpp"
#include "../include/fonctionsBoucles.hpp"
#include "../include/autresFonctions.hpp"
#include "../include/fonctionsAnnexes.hpp"
#include "../include/lectureFichiers.hpp"
#include "../include/calculPrealable.hpp"
using std::cin;
using std::cout;
using std::endl;
using std::ifstream;
char equivalentMajuscule(char lettreRecue)
{
if (lettreRecue >= 'a' && lettreRecue <= 'z')
return lettreRecue - ('a' - 'A');
else
return lettreRecue;
}
char equivalentMinuscule(char lettreRecue)
{
if (lettreRecue >= 'A' && lettreRecue <= 'Z')
return lettreRecue + ('a' - 'A');
else
return lettreRecue;
}
void affecterBonus(Carte *card, AbilityType type, int modificateur, int minimum)
{
card->bonus.type = type;
card->bonus.modificateur = modificateur;
card->bonus.minimum = minimum;
card->bonus.condition = NO_CONDITION;
}
void definirBonus(Carte *card, int compteur)
{
if (card->clan == "lajunta")
affecterBonus(card, AUGMENTER_DEGATS, 2, 0);
else if (card->clan == "junkz")
affecterBonus(card, AUGMENTER_ATTAQUE, 8, 0);
else if (card->clan == "pussycats")
affecterBonus(card, DIMINUER_DEGATS, -2, 1);
else if (card->clan == "fangpiclang")
affecterBonus(card, AUGMENTER_DEGATS, 2, 0);
else if (card->clan == "uppers")
affecterBonus(card, DIMINUER_ATTAQUE, -10, 3);
else if (card->clan == "montana")
affecterBonus(card, DIMINUER_ATTAQUE, -12, 8);
else if (card->clan == "sentinel")
affecterBonus(card, AUGMENTER_ATTAQUE, 8, 0);
else if (card->clan == "sakrohm")
affecterBonus(card, DIMINUER_ATTAQUE, -8, 3);
else if (card->clan == "skeelz")
affecterBonus(card, PROTECTION_POUVOIR, 0, 0);
else if (card->clan == "gheist")
affecterBonus(card, STOP_POUVOIR, 0, 0);
else if (card->clan == "roots")
affecterBonus(card, STOP_POUVOIR, 0, 0);
else if (card->clan == "nightmare")
affecterBonus(card, STOP_BONUS, 0, 0);
else if (card->clan == "piranas")
affecterBonus(card, STOP_BONUS, 0, 0);
else if (card->clan == "allstars")
affecterBonus(card, DIMINUER_PUISSANCE, -2, 1);
else if (card->clan == "bangers")
affecterBonus(card, AUGMENTER_PUISSANCE, 2, 0);
else if (card->clan == "uluwatu")
affecterBonus(card, AUGMENTER_PUISSANCE, 2, 0);
else if (card->clan == "freaks")
affecterBonus(card, POISON, -2, 3);
else if (card->clan == "jungo")
affecterBonus(card, GAIN_VIE, 2, 0);
else if (card->clan == "berzerk")
affecterBonus(card, PERTE_VIE, -2, 2);
else if (card->clan == "rescue")
affecterBonus(card, AUGMENTER_ATTAQUE, 3 * compteur, 0);
else
erreur(card->clan + " : Clan is unknown. Must be defined in lectureFichiers/definirBonus()\n");
}
void miseEnPlaceDesBonus()
{
miseEnPlaceDesBonusPourUnCamp(carteAlliee);
miseEnPlaceDesBonusPourUnCamp(carteEnnemie);
}
void miseEnPlaceDesBonusPourUnCamp(Carte equipe[4])
{
int compteur = 0;
for (int i = 0 ; i < 4 ; i++)
{
compteur = 0;
for (int z = 0 ; z < 4 ; z++)
{//on compte combien ils sont du meme clan
if (equipe[i].clan == equipe[z].clan)
compteur++;
}
if (compteur >= 2 && (equipe[0].nom != equipe[1].nom || equipe[0].nom != equipe[2].nom || equipe[0].nom != equipe[3].nom))
definirBonus(&equipe[i], compteur);
else
{
equipe[i].bonus.type = NOTHING;
equipe[i].bonus.modificateur = 0;
equipe[i].bonus.minimum = 0;
}
}
}
AbilityType stringToAbilityType(string s)
{
AbilityType res;
if (s == "NOTHING")
res = NOTHING;
else if (s == "STOP_BONUS")
res = STOP_BONUS;
else if (s == "STOP_POUVOIR")
res = STOP_POUVOIR;
else if (s == "PROTECTION_POUVOIR")
res = PROTECTION_POUVOIR;
else if (s == "PROTECTION_BONUS")
res = PROTECTION_BONUS;
else if (s == "AUGMENTER_PUISSANCE")
res = AUGMENTER_PUISSANCE;
else if (s == "DIMINUER_PUISSANCE")
res = DIMINUER_PUISSANCE;
else if (s == "AUGMENTER_DEGATS")
res = AUGMENTER_DEGATS;
else if (s == "DIMINUER_DEGATS")
res = DIMINUER_DEGATS;
else if (s == "AUGMENTER_ATTAQUE")
res = AUGMENTER_ATTAQUE;
else if (s == "DIMINUER_ATTAQUE")
res = DIMINUER_ATTAQUE;
else if (s == "POISON")
res = POISON;
else if (s == "GAIN_VIE")
res = GAIN_VIE;
else if (s == "PERTE_VIE")
res = PERTE_VIE;
else if (s == "GAIN_PILLZ")
res = GAIN_PILLZ;
else if (s == "PERTE_PILLZ")
res = PERTE_PILLZ;
else if (s == "COPIER_DEGATS")
res = COPIER_DEGATS;
else if (s == "COPIER_PUISSANCE")
res = COPIER_PUISSANCE;
else if (s == "PROTECTION_PUISSANCE")
res = PROTECTION_PUISSANCE;
else if (s == "PROTECTION_DEGATS")
res = PROTECTION_DEGATS;
else {
res = NOTHING;
erreur(s + " is not known as any ability type");
}
return res;
}
AbilityCondition stringToAbilityCondition(string s)
{
AbilityCondition res;
if (s == "No_condition")
res = NO_CONDITION;
else if (s == "Support")
res = SUPPORT;
else if (s == "Stop")
res = EN_CAS_DE_STOP;
else if (s == "Courage")
res = COURAGE;
else if (s == "Revanche")
res = REVANCHE;
else if (s == "Confiance")
res = CONFIANCE;
else if (s == "Défaite")
res = DEFAITE;
else if (s == "Contrecoup")
res = CONTRECOUP;
else {
erreur(s + " is not known as any condition type");
res = NO_CONDITION;
}
return res;
}
bool foundCard(string nomCherche, Carte *card)
{
bool cardFound = false;
ifstream file(CARDS_DB_FILENAME);//FIXME need to close/whatever the filestream ?
if (file.bad() || file.fail() || ! file.good())
{
cout << "There was a problem opening " << CARDS_DB_FILENAME << "." << endl;
exit(EXIT_FAILURE);
}
int pMod, pMin, puissance, degats, etoiles;
string nom, clan, pType, pCond;
while (file >> pType >> pMod >> pMin >> pCond >> puissance >> degats >> etoiles >> nom >> clan)
{
if (nom == "Trinmkkt" || nom == "Skrumxxt")
nom[7] = 'T';
else if (nom == "Graksmxxt")//possiblité d'aller plus vite en prenant 10 lignes de plus.
nom[8] = 'T';// TODO MAJ quand de nouveaux sakrhom ou autres persos aux noms abominables apparaissent
if (nom == nomCherche)
{
cout << "Card found : " << nom << endl;
card->pouvoir.type = stringToAbilityType(pType);
card->pouvoir.modificateur = pMod;
card->pouvoir.minimum = pMin;
card->pouvoir.condition = stringToAbilityCondition(pCond);
card->puissance = puissance;
card->degatsDeBase = degats;
card->nombreDEtoiles = etoiles;
card->nom = nom;
card->clan = clan;
cardFound = true;
break;
}
}
if (! cardFound)
{
cout << "ERROR : cannot find the card : " << nomCherche << "." << endl <<
"Check for spelling and replace spaces with underscores (_)." << endl <<
"Examples : Tanaereva_Cr, No_Nam, TrinmkkT, Miss_Lulabee, Slyde" << endl;
}
return cardFound;
}
void lectureDesFichiers()
{
string nom;
for (int i = 0 ; i < 4 ; i++)
{
do
{
#ifdef EQUIPES_TEST
if (i == 0)
nom = "gibson";
if (i == 1)
nom = "thormund";
if (i == 2)
nom = "chiro";
if (i == 3)
nom = "no_nam";
#else
cout << endl << "What is your " << getOrdinal(i + 1) << " card ? : ";
cin >> nom;
#endif
normalizeCasing(nom);
}
while (!foundCard(nom, &carteAlliee[i]));
}
cout << endl;
for (int i = 0 ; i < 4 ; i++)
{
do
{
#ifdef EQUIPES_TEST
if (i == 0)
nom = "kinjo";
if (i == 1)
nom = "sakazuki";
if (i == 2)
nom = "lewis";
if (i == 3)
nom = "yu_mei";
#else
cout << endl << "What is the opponent's " << getOrdinal(i+1) << " card ? : ";
cin >> nom;
#endif
normalizeCasing(nom);
}
while (!foundCard(nom, &carteEnnemie[i]));
}
miseEnPlaceDesBonus();
computeSupport();
}
void computeSupport()
{
for (int i = 0 ; i < 4 ; i++)
{
int compteur = 0, compteurEnnemi = 0;
for (int z = 0 ; z < 4 ; z++)
{//on compte combien ils sont du meme clan
if (carteAlliee[i].clan == carteAlliee[z].clan)
compteur++;
if (carteEnnemie[i].clan == carteEnnemie[z].clan)
compteurEnnemi++;
}
if (carteAlliee[i].pouvoir.condition == SUPPORT)
carteAlliee[i].pouvoir.modificateur *= compteur;
if (carteEnnemie[i].pouvoir.condition == SUPPORT)
carteEnnemie[i].pouvoir.modificateur *= compteurEnnemi;
}
}
| [
"charles.collombert@gmail.com"
] | charles.collombert@gmail.com |
0b372c6724134ae63b18af6327389ffc6087cdf3 | 448429f1fc4e4f2b4615e59d05106e201adead17 | /src/modules/init.cpp | 22b41e2b264be2ada996accce898a114ac747d19 | [] | no_license | emeraldlang/emerald | 7a27eb84cb436c646f2b25a72dddbd650bae1282 | b83ce8d385c795dddb005754c6aa8c272bcb5af8 | refs/heads/master | 2022-01-29T02:57:39.012249 | 2021-10-18T21:58:10 | 2021-10-18T21:58:10 | 184,795,763 | 26 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,903 | cpp | /* Emerald - Procedural and Object Oriented Programming Language
** Copyright (C) 2018 Zach Perkitny
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "emerald/modules/init.h"
#include "emerald/module_registry.h"
#include "emerald/modules/bytecode.h"
#include "emerald/modules/collections.h"
#include "emerald/modules/core.h"
#include "emerald/modules/datetime.h"
#include "emerald/modules/gc.h"
#include "emerald/modules/io.h"
#include "emerald/modules/net.h"
#include "emerald/modules/process.h"
namespace emerald {
namespace modules {
void add_module_inits_to_registry() {
NativeModuleInitRegistry::add_module_init("bytecode", init_bytecode_module);
NativeModuleInitRegistry::add_module_init("collections", init_collections_module);
NativeModuleInitRegistry::add_module_init("core", init_core_module);
NativeModuleInitRegistry::add_module_init("datetime", init_datetime_module);
NativeModuleInitRegistry::add_module_init("gc", init_gc_module);
NativeModuleInitRegistry::add_module_init("io", init_io_module);
NativeModuleInitRegistry::add_module_init("net", init_net_module);
NativeModuleInitRegistry::add_module_init("process", init_process_module);
}
} // namespace modules
} // namespace emerald
| [
"zvpiscool@gmail.com"
] | zvpiscool@gmail.com |
865f48872cd4551f09f5888e8357050b9b2fed56 | cd1e4eababa89659b79fe70e964b9f311b877e13 | /inc/moo/Prerequisites.h | a370bdc5ccc4747b7f4a25a962c9a3f9146b7d65 | [] | no_license | luada/GameEngine | 725f72fb8573384b3c0128f283ffcc7e251265d6 | b8cfb28e593e80642df94e46ac51554bc4e86d1f | refs/heads/master | 2020-04-08T20:02:53.102842 | 2018-11-29T14:56:03 | 2018-11-29T14:56:03 | 159,682,074 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 838 | h | #ifndef ___Prerequisites_H__
#define ___Prerequisites_H__
#include <OgrePrerequisites.h>
//-----------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------
namespace MM
{
// Bring common types from Ogre namespace
using Ogre::Real;
using Ogre::uchar;
using Ogre::ushort;
using Ogre::uint;
using Ogre::ulong;
using Ogre::uint8;
using Ogre::uint16;
using Ogre::uint32;
using Ogre::String;
// Some simple types
typedef Ogre::Vector2 Point;
typedef std::map<String, String> NameValuePairList;
enum AnimationType
{
AT_FULL,
AT_FROZE,
AT_DISABLE,
};
}
#define FairySpecialCaseRenderQueue Ogre::RENDER_QUEUE_9
#endif // ___Prerequisites_H__
| [
"451215953@qq.com"
] | 451215953@qq.com |
0386a811fc5916eea5f869115d75b8b60b26df72 | 8d86d4a327220f92e76723bbf655b0121fad9289 | /TestApps/Rosetta/BNN/Prebuilt/Synth/_sds/vhls/top/solution/syn/systemc/a0_top_mul_mul_20s_1bkb.h | 86e0ab29ab813704936805f1779bc2c0baf7edeb | [
"MIT"
] | permissive | HansGiesen/hls_tuner | 3cd7d8143ddeb704091b62ef6640ccb75d16867b | 9c8d03737d1115f4e5cfa03cabc2334ea8b3ca19 | refs/heads/master | 2023-07-15T09:50:13.636478 | 2021-08-26T16:49:00 | 2021-08-26T16:49:00 | 191,989,889 | 2 | 1 | MIT | 2019-09-19T18:16:39 | 2019-06-14T18:35:31 | VHDL | UTF-8 | C++ | false | false | 1,012 | h | // ==============================================================
// File generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC
// Version: 2017.1
// Copyright (C) 1986-2017 Xilinx, Inc. All Rights Reserved.
//
// ==============================================================
#ifndef __a0_top_mul_mul_20s_1bkb__HH__
#define __a0_top_mul_mul_20s_1bkb__HH__
#include "ACMP_smul_ss.h"
#include <systemc>
template<
int ID,
int NUM_STAGE,
int din0_WIDTH,
int din1_WIDTH,
int dout_WIDTH>
SC_MODULE(a0_top_mul_mul_20s_1bkb) {
sc_core::sc_in< sc_dt::sc_lv<din0_WIDTH> > din0;
sc_core::sc_in< sc_dt::sc_lv<din1_WIDTH> > din1;
sc_core::sc_out< sc_dt::sc_lv<dout_WIDTH> > dout;
ACMP_smul_ss<ID, 1, din0_WIDTH, din1_WIDTH, dout_WIDTH> ACMP_smul_ss_U;
SC_CTOR(a0_top_mul_mul_20s_1bkb): ACMP_smul_ss_U ("ACMP_smul_ss_U") {
ACMP_smul_ss_U.din0(din0);
ACMP_smul_ss_U.din1(din1);
ACMP_smul_ss_U.dout(dout);
}
};
#endif //
| [
"giesen@seas.upenn.edu"
] | giesen@seas.upenn.edu |
0d2ae0744c5bdd467430e5f1e78ef2a1dfbc961c | 996b561e2481dc21ccf30b0cac6344a30b65db62 | /TransformBinComTree/TransformBinComTree.cpp | 0e76cdba36a23ea5ca07ba6def5b668351ec116e | [] | no_license | Vaskow/TransformTrees | f5e2ba27eca209a057debd82c9b1923f3c94a094 | 45858141ecc29a51b9fd3a4b5e3b5471f0cad7ce | refs/heads/master | 2023-08-04T15:03:00.299416 | 2023-07-26T17:07:29 | 2023-07-26T17:07:29 | 209,830,187 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,911 | cpp | // TransformBinComTree.cpp : Определяет точку входа для приложения.
//
//#include "framework.h"
#include "TransformBinComTree.h"
#include "BinTree.h"
#include "ComTree.h"
#include "commdlg.h"
#define MAX_LOADSTRING 100
// Глобальные переменные:
HINSTANCE hInst; // текущий экземпляр
WCHAR szTitle[MAX_LOADSTRING]; // текст строки заголовка
WCHAR szWindowClass[MAX_LOADSTRING]; // имя класса главного окна
TCHAR filePath[MAX_PATH] = TEXT(""); // путь до файла со структурой дерева
bool pressedOpen = false; // нажата кнопка открыть файл (в диалоговом окне)
LPCWSTR s = L"Error, when print big common tree 659 line";
// Отправить объявления функций, включенных в этот модуль кода:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// Инициализация глобальных строк
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_TRANSFORMBINCOMTREE, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Выполнить инициализацию приложения:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TRANSFORMBINCOMTREE));
MSG msg;
// Цикл основного сообщения:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// ФУНКЦИЯ: MyRegisterClass()
//
// ЦЕЛЬ: Регистрирует класс окна.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_TRANSFORMBINCOMTREE));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_TRANSFORMBINCOMTREE);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// ФУНКЦИЯ: InitInstance(HINSTANCE, int)
//
// ЦЕЛЬ: Сохраняет маркер экземпляра и создает главное окно
//
// КОММЕНТАРИИ:
//
// В этой функции маркер экземпляра сохраняется в глобальной переменной, а также
// создается и выводится главное окно программы.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // сохранить маркер экземпляра в глобальной переменной
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
HWND ButtonTransfBinTr = CreateWindow(
L"BUTTON",
L"Получить бинарное дерево и преобразовать его в дерево общего вида",
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles
40, // x position
60, // y position
500, // Button width
50, // Button height
hWnd, // Parent window
(HMENU)ID_TransfBinTree,
(HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE),
NULL);
HWND ButtonTransfComTr = CreateWindow(
L"BUTTON",
L"Получить дерево общего вида и преобразовать его в бинарное дерево",
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles
700, // x position
60, // y position
500, // Button width
50, // Button height
hWnd, // Parent window
(HMENU)ID_TransfComTree,
(HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE),
NULL);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
void OpenFileDialog()
{
OPENFILENAME OpenFileName = { 0 };
ZeroMemory(&OpenFileName, sizeof(OpenFileName));
OpenFileName.lStructSize = sizeof(OpenFileName);
OpenFileName.lpstrFilter = L"Text Files (*.txt)\0*.txt";
OpenFileName.lpstrFile = filePath;
OpenFileName.lpstrFile[0] = L'\0';
OpenFileName.nMaxFile = sizeof(filePath) / sizeof(TCHAR);
OpenFileName.lpstrFileTitle = NULL;
OpenFileName.nMaxFileTitle = 0;
OpenFileName.lpstrInitialDir = NULL;
OpenFileName.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (GetOpenFileName(&OpenFileName)) {
pressedOpen = true;
}
else pressedOpen = false;
}
//
// ФУНКЦИЯ: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// ЦЕЛЬ: Обрабатывает сообщения в главном окне.
//
// WM_COMMAND - обработать меню приложения
// WM_PAINT - отрисовка главного окна
// WM_DESTROY - отправить сообщение о выходе и вернуться
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
RECT Rect;
HDC hdc;
static HDC hCmpDC;
HBITMAP hBmp;
static BinTree bt;
static ComTree ct;
static BinTree btOfct;
static ComTree ctOfbt;
//Флаг отрисовки бинарного дерева и полученного из него общего дерева
static bool printBinTree = false;
//Флаг отрисовки общего дерева и полученного из него бинарного дерева
static bool printComTree = false;
//Флаг необходимости считывания дерева из файла
static bool needReadTreeFile = false;
static int heightPrintTree = 150; //высота, с которой начинает рисоваться дерево
POINT aptStar[6] = { 50,2, 2,98, 98,33, 2,33, 98,98, 50,2 };
switch (message)
{
case WM_SIZE:
//InvalidateRect(hWnd, 0, TRUE);
//UpdateWindow(hWnd);
break;
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Разобрать выбор в меню:
switch (wmId)
{
case ID_TransfBinTree:
printBinTree = true;
printComTree = false;
needReadTreeFile = true;
OpenFileDialog();
InvalidateRect(hWnd, 0, TRUE);
UpdateWindow(hWnd);
break;
case ID_TransfComTree:
printComTree = true;
printBinTree = false;
needReadTreeFile = true;
OpenFileDialog();
InvalidateRect(hWnd, 0, TRUE);
UpdateWindow(hWnd);
break;
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
hdc = BeginPaint(hWnd, &ps);
GetClientRect(hWnd, &Rect);
SetWindowExtEx(hdc, 2000, 2000, NULL);
SetViewportExtEx(hdc, Rect.right, Rect.bottom, NULL);
// Закраска фоновым цветом
LOGBRUSH br;
br.lbStyle = BS_SOLID;
br.lbColor = 0xEECCCC;
HBRUSH brush;
brush = CreateBrushIndirect(&br);
FillRect(hdc, &Rect, brush);
DeleteObject(brush);
//TextOut(hdc, 5, 5, filePath, lstrlen(filePath));
if (printBinTree && pressedOpen)
{
heightPrintTree = 150;
if (needReadTreeFile)
{
const wstring wnameBT = filePath;
const string nameBT(wnameBT.begin(), wnameBT.end());
bt.ReadBinTreeFromFile(nameBT);
needReadTreeFile = false;
}
heightPrintTree = bt.PaintBinTree(hdc, heightPrintTree);
ctOfbt.TransformInComTree(bt);
ctOfbt.PaintComTree(hdc, heightPrintTree);
}
else if (printComTree && pressedOpen)
{
heightPrintTree = 150;
if (needReadTreeFile)
{
const wstring wnameCT = filePath;
const string nameCT(wnameCT.begin(), wnameCT.end());
ct.ReadComTreeFromFile(nameCT);
needReadTreeFile = false;
}
heightPrintTree = ct.PaintComTree(hdc, heightPrintTree);
ct.TransformInBinTree(btOfct);
btOfct.PaintBinTree(hdc, heightPrintTree);
}
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Обработчик сообщений для окна "О программе".
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
| [
"Vaskow342@yandex.ru"
] | Vaskow342@yandex.ru |
bfb517edf61c01bdf8fabcb95b9abcf7fee3b583 | a34fe1a599b010d5e3f75a6f7838c8ecbf998a74 | /boost/spirit/home/support/standard.hpp | cdc24b5a2295344bd90cbfe93fb6671b8b9e8a40 | [] | no_license | flmello/4thArticleIntel | 78652a9957c507beb4b7be6d8560076211134c0c | 2c204799553a0ca85b6baf1a1ff9876254fd4800 | refs/heads/master | 2021-08-23T03:45:51.554811 | 2017-12-03T01:32:27 | 2017-12-03T01:32:27 | 112,890,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,487 | hpp | /*=============================================================================
Copyright (c) 2001-2007 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(SPIRIT_STANDARD_JAN_31_2006_0529PM)
#define SPIRIT_STANDARD_JAN_31_2006_0529PM
#include <boost/spirit/home/support/char_class.hpp>
#include <boost/xpressive/proto/proto.hpp>
namespace boost { namespace spirit { namespace standard
{
typedef spirit::char_class::standard char_set;
namespace tag = spirit::char_class::tag;
template <typename Class>
struct make_tag
: proto::terminal<spirit::char_class::key<char_set, Class> > {};
typedef make_tag<tag::alnum>::type alnum_type;
typedef make_tag<tag::alpha>::type alpha_type;
typedef make_tag<tag::blank>::type blank_type;
typedef make_tag<tag::cntrl>::type cntrl_type;
typedef make_tag<tag::digit>::type digit_type;
typedef make_tag<tag::graph>::type graph_type;
typedef make_tag<tag::print>::type print_type;
typedef make_tag<tag::punct>::type punct_type;
typedef make_tag<tag::space>::type space_type;
typedef make_tag<tag::xdigit>::type xdigit_type;
alnum_type const alnum = {{}};
alpha_type const alpha = {{}};
blank_type const blank = {{}};
cntrl_type const cntrl = {{}};
digit_type const digit = {{}};
graph_type const graph = {{}};
print_type const print = {{}};
punct_type const punct = {{}};
space_type const space = {{}};
xdigit_type const xdigit = {{}};
typedef proto::terminal<
spirit::char_class::no_case_tag<char_set> >::type
no_case_type;
no_case_type const no_case = no_case_type();
typedef proto::terminal<
spirit::char_class::lower_case_tag<char_set> >::type
lower_type;
typedef proto::terminal<
spirit::char_class::upper_case_tag<char_set> >::type
upper_type;
lower_type const lower = lower_type();
upper_type const upper = upper_type();
#if defined(__GNUC__)
inline void silence_unused_warnings__standard()
{
(void) alnum; (void) alpha; (void) blank; (void) cntrl; (void) digit;
(void) graph; (void) print; (void) punct; (void) space; (void) xdigit;
}
#endif
}}}
#endif
| [
"flavioluis.mello@gmail.com"
] | flavioluis.mello@gmail.com |
daa5ad1e6cb27d8e1b55686aa6a06a4084c5112a | 00c399fb751538d486b8621eb9a9762b571a9b23 | /src/06_create_swapchain/create_swapchain_capi.cpp | e4deeb92d7ea2917cc8f797cefcca6183b82dfd0 | [
"MIT"
] | permissive | VulkanWorks/vulkan_samples_2019 | 7f1c8a6c07fff02429008d0aa8d08321046e7082 | 09b5e199bf53b21b266aae97a11b60bcca0a8825 | refs/heads/master | 2020-09-08T12:46:30.473941 | 2019-09-07T05:39:07 | 2019-09-07T05:39:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,687 | cpp | #include <cstring>
#include <iostream>
#include <vector>
#include <algorithm>
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <vulkan/vulkan.h>
#include <common/config.h>
int main( int argc, const char *argv[] ) {
auto config = common::parse_configs( argc, argv );
glfwInit();
std::vector< const char* > ext;
std::vector< const char* > layers;
uint32_t required_ext_count = 0u;
const auto required_ext = glfwGetRequiredInstanceExtensions( &required_ext_count );
for( uint32_t i = 0u; i != required_ext_count; ++i )
ext.emplace_back( required_ext[ i ] );
VkApplicationInfo application_info;
application_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
application_info.pNext = nullptr;
application_info.pApplicationName = config.prog_name.c_str();
application_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
application_info.pEngineName ="sample_engine";
application_info.engineVersion = VK_MAKE_VERSION(1, 0, 0);
application_info.apiVersion = VK_API_VERSION_1_1;
if( config.validation ) layers.emplace_back( "VK_LAYER_LUNARG_standard_validation" );
VkInstanceCreateInfo create_instance_info;
create_instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
create_instance_info.pNext = nullptr;
create_instance_info.flags = 0;
create_instance_info.pApplicationInfo = &application_info;
create_instance_info.enabledLayerCount = layers.size();
create_instance_info.ppEnabledLayerNames = layers.data();
create_instance_info.enabledExtensionCount = ext.size();
create_instance_info.ppEnabledExtensionNames = ext.data();
VkInstance instance;
VkResult result = vkCreateInstance(
&create_instance_info,
nullptr,
&instance
);
if( result != VK_SUCCESS ) {
vkDestroyInstance(
instance,
nullptr
);
glfwTerminate();
return 1;
}
uint32_t device_count = 0;
if( vkEnumeratePhysicalDevices( instance, &device_count, nullptr ) != VK_SUCCESS ) {
vkDestroyInstance(
instance,
nullptr
);
glfwTerminate();
return 1;
}
if( device_count == 0 ) {
std::cerr << "利用可能なデバイスがない" << std::endl;
return 1;
}
std::vector< VkPhysicalDevice > devices;
devices.resize( device_count );
if( vkEnumeratePhysicalDevices( instance, &device_count, devices.data() ) != VK_SUCCESS ) {
std::cerr << "利用可能なデバイスを取得できない" << std::endl;
vkDestroyInstance(
instance,
nullptr
);
glfwTerminate();
return 1;
}
std::vector< const char* > dext{ VK_KHR_SWAPCHAIN_EXTENSION_NAME };
std::vector< const char* > dlayers;
devices.erase( std::remove_if( devices.begin(), devices.end(), [&]( const auto &device ) -> bool {
uint32_t ext_count = 0u;
if( vkEnumerateDeviceExtensionProperties( device, nullptr, &ext_count, nullptr ) != VK_SUCCESS )
return true;
std::vector< VkExtensionProperties > avail_dext;
avail_dext.resize( ext_count );
if( vkEnumerateDeviceExtensionProperties( device, nullptr, &ext_count, avail_dext.data() ) != VK_SUCCESS )
return true;
for( const char *w: dext )
if( std::find_if( avail_dext.begin(), avail_dext.end(), [&]( const auto &v ) { return !strcmp( v.extensionName, w ); } ) == avail_dext.end() ) return true;
uint32_t layer_count = 0u;
if( vkEnumerateDeviceLayerProperties( device, &layer_count, nullptr ) != VK_SUCCESS )
return true;
std::vector< VkLayerProperties > avail_dlayers;
avail_dlayers.resize( layer_count );
if( vkEnumerateDeviceLayerProperties( device, &layer_count, avail_dlayers.data() ) != VK_SUCCESS )
return true;
for( const char *w: dlayers )
if( std::find_if( avail_dlayers.begin(), avail_dlayers.end(), [&]( const auto &v ) { return !strcmp( v.layerName, w ); } ) == avail_dlayers.end() ) return true;
uint32_t queue_props_count = 0u;
vkGetPhysicalDeviceQueueFamilyProperties( device, &queue_props_count, nullptr );
std::vector< VkQueueFamilyProperties > queue_props;
queue_props.resize( queue_props_count );
vkGetPhysicalDeviceQueueFamilyProperties( device, &queue_props_count, queue_props.data() );
bool has_compatible_queue = false;
for( uint32_t i = 0; i < queue_props.size(); ++i ) {
if( glfwGetPhysicalDevicePresentationSupport( instance, device, i ) ) {
has_compatible_queue = true;
break;
}
}
return !has_compatible_queue;
} ), devices.end() );
if( devices.empty() ) {
std::cerr << "必要な拡張とレイヤーを備えたデバイスがない" << std::endl;
vkDestroyInstance( instance, nullptr );
glfwTerminate();
return 1;
}
std::cout << "利用可能なデバイス" << std::endl;
for( unsigned int index = 0u; index != devices.size(); ++index ) {
VkPhysicalDeviceProperties prop;
vkGetPhysicalDeviceProperties( devices[ index ], &prop );
std::cout << index << ": " << prop.deviceName << std::endl;
}
glfwWindowHint( GLFW_CLIENT_API, GLFW_NO_API );
GLFWwindow *window = glfwCreateWindow( config.width, config.height, config.prog_name.c_str(), config.fullscreen ? glfwGetPrimaryMonitor() : nullptr, nullptr );
if( !window ) {
std::cerr << "ウィンドウを作成できない" << std::endl;
vkDestroyInstance( instance, nullptr );
glfwTerminate();
return 1;
}
VkSurfaceKHR surface;
if( glfwCreateWindowSurface( instance, window, nullptr, &surface ) != VK_SUCCESS ) {
std::cerr << "サーフェスを作成できない" << std::endl;
glfwDestroyWindow( window );
vkDestroyInstance( instance, nullptr );
glfwTerminate();
return 1;
}
if( config.device_index >= devices.size() ) {
std::cerr << config.device_index << "番目のデバイスは存在しない" << std::endl;
vkDestroySurfaceKHR( instance, surface, nullptr );
glfwDestroyWindow( window );
vkDestroyInstance( instance, nullptr );
glfwTerminate();
return 1;
}
const auto &physical_device = devices[ config.device_index ];
uint32_t queue_props_count;
vkGetPhysicalDeviceQueueFamilyProperties( physical_device, &queue_props_count, nullptr );
std::vector< VkQueueFamilyProperties > queue_props( queue_props_count );
vkGetPhysicalDeviceQueueFamilyProperties( physical_device, &queue_props_count, queue_props.data() );
std::vector< VkBool32 > supported;
supported.reserve( queue_props.size() );
for( uint32_t i = 0; i < queue_props.size(); ++i ) {
VkBool32 v;
if( vkGetPhysicalDeviceSurfaceSupportKHR( physical_device, i, surface, &v ) != VK_SUCCESS ) {
vkDestroySurfaceKHR( instance, surface, nullptr );
glfwDestroyWindow( window );
vkDestroyInstance( instance, nullptr );
glfwTerminate();
return 1;
}
supported.emplace_back( v );
}
uint32_t graphics_queue_index = std::distance( queue_props.begin(), std::find_if( queue_props.begin(), queue_props.end(), []( const auto &v ) { return bool( v.queueFlags & VK_QUEUE_GRAPHICS_BIT ); } ) );
uint32_t present_queue_index =
( graphics_queue_index != queue_props.size() && supported[ graphics_queue_index ] == VK_TRUE ) ?
graphics_queue_index :
std::distance( supported.begin(), std::find( supported.begin(), supported.end(), VK_TRUE ) );
if( graphics_queue_index == queue_props.size() || present_queue_index == queue_props.size() ) {
std::cerr << "必要なキューが備わっていない " << std::endl;
vkDestroySurfaceKHR( instance, surface, nullptr );
glfwDestroyWindow( window );
vkDestroyInstance( instance, nullptr );
glfwTerminate();
return 1;
}
const float priority = 0.0f;
std::vector< VkDeviceQueueCreateInfo > queues;
VkDeviceQueueCreateInfo graphics_queue_create_info;
graphics_queue_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
graphics_queue_create_info.pNext = nullptr;
graphics_queue_create_info.flags = 0;
graphics_queue_create_info.queueFamilyIndex = graphics_queue_index;
graphics_queue_create_info.queueCount = 1;
graphics_queue_create_info.pQueuePriorities = &priority;
queues.push_back( graphics_queue_create_info );
if ( graphics_queue_index != present_queue_index ) {
VkDeviceQueueCreateInfo present_queue_create_info;
present_queue_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
present_queue_create_info.pNext = nullptr;
present_queue_create_info.flags = 0;
present_queue_create_info.queueFamilyIndex = present_queue_index;
present_queue_create_info.queueCount = 1;
present_queue_create_info.pQueuePriorities = &priority;
queues.push_back( present_queue_create_info );
}
VkPhysicalDeviceFeatures features;
vkGetPhysicalDeviceFeatures( physical_device, &features );
VkDeviceCreateInfo device_create_info;
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_create_info.pNext = nullptr;
device_create_info.flags = 0;
device_create_info.queueCreateInfoCount = queues.size();
device_create_info.pQueueCreateInfos = queues.data();
device_create_info.enabledLayerCount = dlayers.size();
device_create_info.ppEnabledLayerNames = dlayers.data();
device_create_info.enabledExtensionCount = dext.size();
device_create_info.ppEnabledExtensionNames = dext.data();
device_create_info.pEnabledFeatures = &features;
VkDevice device;
vkCreateDevice( physical_device, &device_create_info, nullptr, &device );
VkQueue graphics_queue;
VkQueue present_queue;
if( graphics_queue_index != present_queue_index ) {
vkGetDeviceQueue( device, graphics_queue_index, 0, &graphics_queue );
vkGetDeviceQueue( device, present_queue_index, 0, &present_queue );
}
else {
vkGetDeviceQueue( device, graphics_queue_index, 0, &graphics_queue );
present_queue = graphics_queue;
}
uint32_t formats_count = 0u;
if( vkGetPhysicalDeviceSurfaceFormatsKHR( physical_device, surface, &formats_count, nullptr ) != VK_SUCCESS ) {
std::cout << "利用可能なピクセルフォーマットを取得できない" << std::endl;
vkDestroyDevice( device, nullptr );
vkDestroySurfaceKHR( instance, surface, nullptr );
glfwDestroyWindow( window );
vkDestroyInstance( instance, nullptr );
glfwTerminate();
return 1;
}
std::vector< VkSurfaceFormatKHR > formats( formats_count );
if( vkGetPhysicalDeviceSurfaceFormatsKHR( physical_device, surface, &formats_count, formats.data() ) != VK_SUCCESS ) {
std::cout << "利用可能なピクセルフォーマットを取得できない" << std::endl;
vkDestroyDevice( device, nullptr );
vkDestroySurfaceKHR( instance, surface, nullptr );
glfwDestroyWindow( window );
vkDestroyInstance( instance, nullptr );
glfwTerminate();
return 1;
}
if( formats.empty() ) {
std::cerr << "利用可能なピクセルフォーマットが無い" << std::endl;
vkDestroyDevice( device, nullptr );
vkDestroySurfaceKHR( instance, surface, nullptr );
glfwDestroyWindow( window );
vkDestroyInstance( instance, nullptr );
glfwTerminate();
return 1;
}
auto selected_format = std::find_if( formats.begin(), formats.end(), []( const auto &v ) { return v.format == VK_FORMAT_B8G8R8A8_UNORM; } );
if( selected_format == formats.end() ) {
selected_format = std::find_if( formats.begin(), formats.end(), []( const auto &v ) { return v.format == VK_FORMAT_R8G8B8A8_UNORM; } );
if( selected_format == formats.end() ) {
std::cerr << "利用可能なピクセルフォーマットが無い" << std::endl;
vkDestroyDevice( device, nullptr );
vkDestroySurfaceKHR( instance, surface, nullptr );
glfwDestroyWindow( window );
vkDestroyInstance( instance, nullptr );
glfwTerminate();
return 1;
}
}
const auto &format = *selected_format;
VkSurfaceCapabilitiesKHR surface_capabilities;
if( vkGetPhysicalDeviceSurfaceCapabilitiesKHR( physical_device, surface, &surface_capabilities ) != VK_SUCCESS ) {
std::cout << "ケーパビリティを取得できない" << std::endl;
vkDestroyDevice( device, nullptr );
vkDestroySurfaceKHR( instance, surface, nullptr );
glfwDestroyWindow( window );
vkDestroyInstance( instance, nullptr );
glfwTerminate();
return 1;
}
VkExtent2D swapchain_extent;
if ( surface_capabilities.currentExtent.width == static_cast< uint32_t >( -1 ) ) {
swapchain_extent.width = config.width;
swapchain_extent.height = config.height;
} else {
swapchain_extent = surface_capabilities.currentExtent;
config.width = surface_capabilities.currentExtent.width;
config.height = surface_capabilities.currentExtent.height;
}
const uint32_t swapchain_image_count = std::min(
surface_capabilities.minImageCount + 1,
surface_capabilities.maxImageCount
);
VkSwapchainCreateInfoKHR swapchain_create_info;
swapchain_create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapchain_create_info.pNext = nullptr;
swapchain_create_info.flags = 0;
swapchain_create_info.surface = surface;
swapchain_create_info.minImageCount = swapchain_image_count;
swapchain_create_info.imageFormat = format.format;
swapchain_create_info.imageColorSpace = format.colorSpace;
swapchain_create_info.imageExtent = swapchain_extent;
swapchain_create_info.imageArrayLayers = 1;
swapchain_create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
swapchain_create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
swapchain_create_info.queueFamilyIndexCount = 0;
swapchain_create_info.pQueueFamilyIndices = nullptr;
swapchain_create_info.preTransform =
( surface_capabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR ) ?
VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR :
surface_capabilities.currentTransform;
swapchain_create_info.presentMode = VK_PRESENT_MODE_FIFO_KHR;
swapchain_create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
swapchain_create_info.clipped = true;
swapchain_create_info.oldSwapchain = VK_NULL_HANDLE;
VkSwapchainKHR swapchain;
if( vkCreateSwapchainKHR( device, &swapchain_create_info, nullptr, &swapchain ) != VK_SUCCESS ) {
std::cout << "スワップチェインを作成できない" << std::endl;
vkDestroyDevice( device, nullptr );
vkDestroySurfaceKHR( instance, surface, nullptr );
glfwDestroyWindow( window );
vkDestroyInstance( instance, nullptr );
glfwTerminate();
return 1;
}
vkDestroySwapchainKHR( device, swapchain, nullptr );
vkDestroyDevice( device, nullptr );
vkDestroySurfaceKHR( instance, surface, nullptr );
glfwDestroyWindow( window );
vkDestroyInstance( instance, nullptr );
glfwTerminate();
}
| [
"fadis@quaternion.sakura.ne.jp"
] | fadis@quaternion.sakura.ne.jp |
f03c6924246ab329a9f694fd205877b0a41ddcfb | a4a9194b64bb9efbf2a02f9010ad93c99c9d6e76 | /latihan 9.cpp | d687c270742e945880d3ced8e63e95c58b1d8f6f | [] | no_license | vianaanesianti08/viana-anesianti-dewi | bcbfa9fb373c35f218a073f2c110c75f8c4e4cc6 | a9390d7169927ce1ddc12bd2d5908c177acfe058 | refs/heads/master | 2021-01-11T22:06:03.214867 | 2017-01-14T06:58:53 | 2017-01-14T06:58:53 | 78,921,963 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613 | cpp | #include <stdio.h>
#include <conio.h>
#include <iostream.h>
main()
{
float a,b,c,d,e,f,x,y;
clrscr();
cout<<"Masukan Nilai x =";
cin>>x;
cout<<"Masukan Nilai Y =";
cin>>y;
a=x==y;
b=x!=y;
c=x>y;
d=x<y;
e=x>=y;
f=x<=y;
cout<<endl;
cout<<"Hasil dari"<<x<<"=="<<y<<"="<<a<<endl;
cout<<"Hasil dari"<<x<<"!="<<y<<"="<<b<<endl;
cout<<"Hasil dari"<<x<<">"<<y<<"="<<c<<endl;
cout<<"Hasil dari"<<x<<"<"<<y<<"="<<d<<endl;
cout<<"Hasil dari"<<x<<">="<<y<<"="<<e<<endl;
cout<<"Hasil dari"<<x<<"<="<<y<<"="<<f<<endl;
getch();
}
| [
"noreply@github.com"
] | noreply@github.com |
b93c05cb472f284388818e1a20a6bbb47006ddcd | 080546554edb19d68ed1d80f6247f1b7526cff14 | /C++ Sena/while statement/ejemplo2.cpp | babc31c0d29e07d08d2d339988fca7b9d3a03aaa | [] | no_license | MrFufux/C-Course-LVL-1 | a6035be451dcd670ee022f7a2ea546ead4c98916 | 731b8c76c6550fae911f3aa4c6eed2db50647dc5 | refs/heads/main | 2023-01-19T20:12:18.428552 | 2020-11-28T05:55:31 | 2020-11-28T05:55:31 | 315,964,903 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 796 | cpp | //-----------------------------EJEMPLO DE WHILE LOOP--------------------------------------------------
//UN ESTUDIANTE RECIBE 5 CALIFICACIONES Y SE DEBE DETERMINAR EL PROMEDIO ALCANZADO POR EL.
#include<iostream>
using namespace std;
int main () {
int contador_notas = 1;
float nota, promedio = 0.0, acumulador_notas = 0.0;
cout<<"A continuacion digite las 5 notas acumuladas en el semestre para asi determinar su promedio en el semestre: \n";
while(contador_notas <= 5)
{
cout<<"\nDigita la nota "<<contador_notas<< ": ";
cin>>nota;
acumulador_notas = acumulador_notas + nota;
contador_notas ++;
}
promedio = acumulador_notas / 5;
cout<< "\nEl promedio de las notas es: "<<promedio<<endl;
system ("pause");
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
d93bb1a7ba89cef542fbeb25f184ba7540e6d8b5 | e952f4ae6ba097b18ebe56705ead70eba80bc89d | /szakdolgozat/codes/weatherStationInit.ino | 5e8b3d7270f47a6585d8d9851d8336b9cb418e29 | [] | no_license | sassnorbert99/szakdolgozat | cca35b7de32d159de8485b0750a2ec62f108a62f | 80a3afd98ec0f940cf9ca1f95a32706971dc32f2 | refs/heads/master | 2023-05-07T01:33:08.431649 | 2021-06-02T11:41:42 | 2021-06-02T11:41:42 | 300,655,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | ino | #include <LiquidCrystal_I2C.h>
#include <hd44780.h>
//cime a 0x27 16 karakteres es 2 sorban fog elhelyezkedni
LiquidCrystal_I2C lcd(0x27,16,2);
//igy fog kinezni a fok jele
byte degree_symbol[8] =
{
0b00111,
0b00101,
0b00111,
0b00000,
0b00000,
0b00000,
0b00000
};
int pin=11; //pin
volatile unsigned long duration=0;
unsigned char i[5];
unsigned int j[40];
unsigned char value=0;
unsigned answer=0;
int z=0;
int b=1;
| [
"sassnorbert99@gmail.com"
] | sassnorbert99@gmail.com |
7970801f1348406f4d8ce3c4e3565e64cf1b7766 | 0f08276e557de8437759659970efc829a9cbc669 | /problems/p586.h | 6d4b9f1a530917547c4031c1ce309fd8a5cab19b | [] | no_license | petru-d/leetcode-solutions-reboot | 4fb35a58435f18934b9fe7931e01dabcc9d05186 | 680dc63d24df4c0cc58fcad429135e90f7dfe8bd | refs/heads/master | 2023-06-14T21:58:53.553870 | 2021-07-11T20:41:57 | 2021-07-11T20:41:57 | 250,795,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 65 | h | #pragma once
namespace p586
{
class Solution
{
};
}
| [
"berserk.ro@gmail.com"
] | berserk.ro@gmail.com |
6cf7561ac1bd3d865680192751ff4f76996004d7 | 4baae7226b66e70624abd523377904a1b429689b | /Classes/Enemy.cpp | bcb88f997b86902dd704239f0e1a5246f4f8ceda | [] | no_license | chenleijava/bonefly1.0 | 18e831a50e18229c4d8a289fa1a4d6d0dc345f1e | 0582d73acde9aff0b47a90f9e82dd535637c87e0 | refs/heads/master | 2020-06-03T22:20:09.776531 | 2014-10-23T12:23:40 | 2014-10-23T12:23:40 | 24,678,157 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,235 | cpp | #include "Enemy.h"
#include "Effect.h"
#include "ActionForEnemy.h"
Enemy::Enemy( Node *gameStage, StructEnemyType &enemyType ) :gameStage( gameStage ), enemyType(enemyType )
{
}
Enemy::~Enemy( )
{
}
bool Enemy::init( )
{
if(!Sprite::init( ))
{
return false;
}
hp = enemyType.hp;
score = enemyType.score;//得分
powers = enemyType.powers;
this->initWithSpriteFrameName(enemyType.enemyPicName);
//fire
this->schedule(schedule_selector( Enemy::fire ), 1.5f);
return true;
}
//************************************
// Method: creatEnemy may be like a factory
// FullName: Enemy::creatEnemy
// Access: public static
// Returns: Enemy *
// Qualifier:
// Parameter: int enemyType
// Parameter: int canHurt
// Parameter: int speedY
// Parameter: int bulletType
// Parameter: int ownType
//************************************
Enemy * Enemy::creatEnemy( Node *gameStage, StructEnemyType &enemyType )
{
auto enemy = new Enemy(gameStage, enemyType);
if (enemy&&enemy->init())
{
enemy->autorelease( );
return enemy;
}
delete enemy;
enemy = NULL;
return enemy;
}
void Enemy::destory( )
{
if(hp <= 0){
//explosion effect flame
auto effect = Effect::CreateEffect( );
effect->explosion(gameStage, this->getPosition( ));
//explosion effect of particle
auto config = Config::getInstance( );
if(config->geteffectState( ))
{
SimpleAudioEngine::getInstance( )->playEffect( ship_explode_effect0 );
}
config->setScore( config->getScore( ) + score );
//log("current get score is :%d",config->getScore () );
this->unschedule(schedule_selector( Enemy::fire ) );
this->removeFromParent( );
}
}
int Enemy::hurt( int &_canHurt )
{
return hp -= _canHurt;
}
Rect Enemy::rect( )
{
return Kit::getRect( this );
}
//creat bullet and fire -- create bullet obj ,add to the game stage
void Enemy::fire( float dt )
{
auto config = Config::getInstance( );
auto enemyPosition = this->getPosition( );
auto dx = enemyPosition.x;
auto dy = enemyPosition.y + 10;
float offset = 0;
auto type = config->getInstance()->getBulletByType(enemyType.bulletType);
for (int i = 0; i != powers;++i)
{
//left
auto bullet = Bullet::createBullet(type.canHurt
, type.speedY, type.picName, type.ownType);
bullet->setPosition(Vec2(dx - offset, dy));
gameStage->addChild(bullet, BULLET_Z_ORDER);
config->enemy_bullet_list->pushBack(bullet);
//right
bullet = Bullet::createBullet(type.canHurt
, type.speedY, type.picName, type.ownType);
bullet->setPosition(Vec2(dx + offset, dy));
gameStage->addChild(bullet, BULLET_Z_ORDER);
config->enemy_bullet_list->pushBack(bullet);
offset += 25;
}
}
void Enemy::stopFire( )
{
this->unschedule( schedule_selector( Enemy::fire ) );
}
void Enemy::boneDestory(Node *node)
{
//explosion effect flame
// auto effect = Effect::CreateEffect();
//effect->explosion(gameStage, this->getPosition());
Kit::addParticle(bone_exploding_plist, node, this->getPosition());
//explosion effect of particle
auto config = Config::getInstance();
if (config->geteffectState())
{
SimpleAudioEngine::getInstance()->playEffect(ship_explode_effect0);
}
this->unschedule(schedule_selector(Enemy::fire));
this->removeFromParent();
}
| [
"502959937@qq.com"
] | 502959937@qq.com |
fa218f022685bc21de260a7dc7f8d6b94d238361 | 012d3cbff982eefd122313f010fafe68dca10aa4 | /Less Then Dungeon 0.3/Quest_Escape.cpp | 206e7472af79e5b8075b9331977fd3b39bf0ce04 | [] | no_license | lobi112/Less_Than_Dungeon_0.3 | 19eb320bed20e75a92b55ed9f480d81306ecffc9 | 9e888a41b25e6bca8cd148610211827bbaa48558 | refs/heads/master | 2022-04-13T00:38:07.206861 | 2020-04-11T11:16:15 | 2020-04-11T11:16:15 | 254,850,740 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 6,389 | cpp | #include "Header.h"//Выход
void quest_escape(MyHero& Hero)
{
system("cls");
string choice="0";
int portal=0;
while (1)
{
cout << "Перед вами находится портал, рядом сидит чёрный ворон." << endl;
cout << "1) Портал." << endl;
cout << "2) Поговорить с вороном." << endl;
cout << "3) Уйти." << endl;
cout << Hero.name << ": ";
cin >> choice;
if (choice == "1" || choice == "Портал" || choice == "портал")
{
system("cls");
while (1)
{
cout << "Вы подошли к порталу." << endl;
cout << "1) Войти." << endl;
cout << "2) Починить." << endl;
cout << "3) Назад." << endl;
cout << Hero.name << ": ";
cin >> choice;
if ((choice == "1" || choice == "Портал" || choice == "портал") && portal == 1)
{
Hero.win = 1;
cout << Hero.name << ": Ну что же, пора уходить." << endl;
_getch();
cout << "Вы входите в портал и через секунду пропадаете из виду." << endl;
cout << "Вслед за вами тёмное подземелье покидает и ворон." << endl << endl;
system("pause");
break;
}
if ((choice == "1" || choice == "Портал" || choice == "портал") && portal == 0)
{
cout << Hero.name << ": Портал всё ещё неактивен, нужно вставить кристалл." << endl << endl;
system("pause");
system("cls");
continue;
}
if ((choice == "2" || choice == "Починить" || choice == "починить") && Hero.charge_cristall == 1 && portal == 0)
{
portal++;
cout << "Вы возващаете кристалл на место." << endl;
cout << "Происходит яркая синяя вспышка, портал испускает свистящий звук, после чего открывается проход." << endl;
_getch();
cout << Hero.name << ": Кажется, сработало." << endl;
_getch();
cout << "Ворон : Кто бы мог подумать, у тебя получилось !" << endl;
cout << "Ворон : Только иди первым, я сразу за тобой." << endl << endl;
system("pause");
system("cls");
continue;
}
else if ((choice == "2" || choice == "Починить" || choice == "починить") && portal == 1)
{
cout << Hero.name << ": Портал уже работает, не думаю, что ему нужно что-то ещё." << endl << endl;
system("pause");
system("cls");
continue;
}
else if ((choice == "2" || choice == "Починить" || choice == "починить") && Hero.charge_cristall == 0)
{
cout << "Вы возващаете кристалл на место." << endl;
cout << "Происходит короткая вспышка, после чего всё возвращается к прежднему состоянию." << endl;
_getch();
cout << Hero.name << ": Кристалл недостаточно силён, ничего не выйдет." << endl;
_getch();
cout << "Ворон : Я думал, что у тебя достаточно ума, чтобы догадаться." << endl << endl;
system("pause");
system("cls");
continue;
}
if (choice == "3" || choice == "Назад" || choice == "назад")
{
cout << Hero.name << " : Пожалуй, вернусь сюда позже." << endl;
_getch();
system("cls");
break;
}
}
if ((choice == "1" || choice == "Портал" || choice == "портал") && portal == 1)
{
break;
}
else continue;
}
if (choice == "2")
{
system("cls");
while (1)
{
cout << "Вы наклоняетесь к ворону." << endl;
cout << "1) Как ты научился говорить ?" << endl;
cout << "2) Как тебя зовут ?" << endl;
cout << "3) Видел что-нибудь в округе ?" << endl;
cout << "4) Назад." << endl;
cout << Hero.name << ": ";
cin >> choice;
if (choice == "1")
{
cout << Hero.name << " Ты первый ворон на моей памяти, который умеет говорить." << endl;
cout << Hero.name << " Как ты этому научился ?" << endl;
_getch();
cout << "Ворон : Не знаю, до того как я попал сюда, меня никто не понимал." << endl;
_getch();
system("cls");
continue;
}
if (choice == "2")
{
cout << Hero.name << " : Как тебя зовут ?" << endl;
_getch();
cout << "Ворон : Альберт." << endl;
_getch();
cout << "Ворон : Себя можешь не называть, у меня хорошая память." << endl;
_getch();
system("cls");
continue;
}
if (choice == "3")
{
cout << Hero.name << " : Видел что-нибудь, пока пролетал округу ?" << endl;
_getch();
cout << "Ворон : Немного, я ведь ворон, а не сова." << endl;
_getch();
cout << "Ворон : Но остановившись в одной из комнат, меня чуть не проглотил деревянный ящик." << endl;
_getch();
cout << "Ворон : В общем, я бы посоветовал быть осторожней." << endl;
_getch();
system("cls");
continue;
}
if (choice == "4" || choice == "Назад" || choice == "назад")
{
cout << Hero.name << " : Мне нужно идти." << endl;
_getch();
system("cls");
break;
}
cout << "Если хочешь что-то от меня узнать, подбирай вопросы правильно." << endl;
_getch();
}
continue;
}
if (choice == "3" || choice == "Уйти" || choice == "уйти")
{
cout << Hero.name << " : Я пойду, никуда не улетай." << endl;
cout << "Ворон : Я никуда и не собирался." << endl;
_getch();
break;
}
}
} | [
"dimon.tuleninov@mail.ru"
] | dimon.tuleninov@mail.ru |
13f243745c18b4de91fe44f7d98d4a55382d21b4 | 587ffa75197b19b6c41d1f438606f47100dcd4e4 | /src/code/net/socket/SocketAddress.cpp | 1b27a5682b4af9faeaa0c0d20a72083f51b90206 | [] | no_license | LiPengfei19820619/XPlat | 9f04e4d32ae3cc4136826071319e7cd356fca7a6 | 3d6fca99da2fa95e2cdf4e9eac9bc437082735bc | refs/heads/master | 2020-06-08T04:10:53.771234 | 2015-11-16T14:26:27 | 2015-11-16T14:26:27 | 42,654,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 266 | cpp |
#include "XPlat_SocketAddress.h"
#include "InetSocketAddress.h"
using namespace XPLAT;
ISocketAddress * ISocketAddress::Create(const std::string & strIPAddr, unsigned short u16Port)
{
return CInetSocketAddress::CreateIPV4SocketAddress(strIPAddr, u16Port);
}
| [
"22201846@qq.com"
] | 22201846@qq.com |
b690de04f92b824e4d8430759277ca6e2cb60c78 | 2e5e6001e2c87a2541aa9ea1876a12293dd098e9 | /src/ofxUniversalMedia.h | 6c208e0e017764fcc3d7bcf57ec6076716f5a673 | [] | no_license | perevalovds/ofxUniversalMedia | 31195b8f7563e962160555eb2113ebca64283832 | 0c84ec4c87624cf70cb15960c964cdedb7c17279 | refs/heads/master | 2020-07-21T09:46:27.246321 | 2020-03-25T13:16:12 | 2020-03-25T13:16:12 | 206,821,145 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,714 | h | #pragma once
//Abstract media class
#include "ofMain.h"
struct ofxUniversalMedia {
ofxUniversalMedia() {}
//Properties of the media
virtual bool has_image() { return false; }
virtual bool has_sound() { return false; }
//Loading
virtual bool load(string file_name) { return false; }
//optional with preloading option:
virtual bool load(string file_name, bool preload) { return false; }
virtual void close() {}
virtual void update() {}
virtual void draw(float x, float y, float w, float h) {}
virtual void play(bool looped) {}
virtual void stop() {}
virtual bool finished() { return true; }
bool is_loaded() { return loaded; }
//Getters //NOTE: currently not implemented
//Related to image
virtual ofTexture *get_texture() { return NULL; }
virtual int width() { return 0; }
virtual int height() { return 0; }
//Related to sound
virtual void set_volume(float v) {}
//------------------------------------------------------------
//Related to image sequences
//Methods for storing images
static const int Decode_None = 0; //No decode, just load image files
static const int Decode_To_CPU = 1; //Decode to CPU images
static const int Decode_To_GPU = 2; //Decode to GPU textures
virtual bool load_image_sequence(string folder_name, double frame_rate, int decode_method) { return false; }
//manual mode moves to the next frame on each update call
//it returns false if not implemented
//set frame rate (currently implemented for image sequances only)
virtual bool set_frame_rate(float fr_rate) { return false; }
//Most useful for image sequences to have full control on it
virtual bool set_manual_mode(bool manual) { return false; }
protected:
int loaded = 0;
};
| [
"perevalovds@gmail.com"
] | perevalovds@gmail.com |
da680ecd70c2a824ec00ca7a4a63d8a8149ff72a | c963958323984427bf29e17ba544d78a9b1739fd | /CFleshEffectTarget.h | b24f21b198ee9d52eb5ac2e94d3a4467498dd24c | [] | no_license | hentaidad/gmod-sdk | ada3beae43af4b6da401155f783b3132860b027b | 8c451b5c57a1ced3da4a686ffb2cd83e42adcc3f | refs/heads/master | 2020-03-19T05:25:36.394975 | 2018-06-03T18:35:43 | 2018-06-03T18:35:43 | 135,929,392 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 482 | h | //***********************************************
// SDK Generated by ValveGen (written by Chod)
// File: CFleshEffectTarget.h
//***********************************************
#pragma once
#include "CBaseEntity.h"
#pragma pack(push,1)
class CFleshEffectTarget :
public CBaseEntity // 0x1340
{
public:
unsigned char _0x1340[0x48];
float m_flRadius; // 0x1388
unsigned char _0x138c[0x8];
float m_flScaleTime; // 0x1394
};
#pragma pack(pop)
| [
"noreply@github.com"
] | noreply@github.com |
9a6d68502e0b0059a79ab6948c40e6ab232414a3 | b3bf5ae6f161c6996f2471a51ed9b3cc483a1b5e | /application/ImageProcessor.cpp | 9b0bd43c51b6088c2a9f54d2c97bafb0da43ef56 | [] | no_license | souravran/FaceRecognizer | 452361560abcf96d73c469854928633c620048b5 | b851e72977b6d48b2018f5f9b203e99f74841437 | refs/heads/master | 2021-01-21T13:11:41.146171 | 2016-04-16T13:37:26 | 2016-04-16T13:37:26 | 55,132,304 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,971 | cpp | /*
* ImageProcessor.cpp
*
* Created on: Dec 3, 2015
* Author: sourav
*/
//-------------------------------------------------------------------------------------------------
// Project Includes
//-------------------------------------------------------------------------------------------------
#include <application/ImageProcessor.h>
//-------------------------------------------------------------------------------------------------
// Global Includes
//-------------------------------------------------------------------------------------------------
#define IMAGE_SAMPLE_FILE "data/0.jpg"
namespace facerecognition {
using namespace cv;
ImageProcessor::ImageProcessor() {}
ImageProcessor::~ImageProcessor() {}
bool ImageProcessor::SuccessImageSmoothing() {
Mat inputImage, outputImage;
inputImage = imread(IMAGE_SAMPLE_FILE,1);
if (inputImage.empty()){
std::cout << "Error occurred while reading input image!" << std::endl;
return false;
}
std::cout << "Input image resolution is : ["<< inputImage.cols << " X " << inputImage.rows <<"]"<< std::endl;
namedWindow("Source", 1);
imshow("Source", inputImage);
for (int i = 1; i < 5; i++) {
std::string value = std::to_string(i);
std::string name = value + " x " + value;
blur(inputImage, outputImage, Size(i, i), Point(-1, -1), 4);
namedWindow(name,1);
imshow(name, outputImage);
}
waitKey(0);
destroyAllWindows();
return true;
}
int ImageProcessor::SuccessEdgeDetection(){
VideoCapture initiateCapture;
Mat originalImage, greyScaleImage, inputImageEdge, imageDetectEdges;
vector<vector<Point> > contoursStore;
vector<Vec4i> contoursHierarchy;
RNG inputImageRing(12345);
initiateCapture.open(0);
if (!initiateCapture.isOpened()) {
std::cout << " camera opened error" << std::endl;
return -1;
}
namedWindow("Edge Detection", 1);
while (true) {
initiateCapture >> originalImage;
if (!originalImage.empty()) {
// convert image to gray scale
cvtColor(originalImage, greyScaleImage, CV_BGR2GRAY);
// blurring image
blur(originalImage, inputImageEdge, Size(3, 3));
// detecting edges using canny edge detection
Canny(inputImageEdge, imageDetectEdges, 10, 100, 3, true);
findContours(imageDetectEdges, contoursStore, contoursHierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
Mat drawing = Mat::zeros(imageDetectEdges.size(), CV_8UC3);
for (int i = 0; i< contoursStore.size(); i++) {
drawContours(originalImage, contoursStore, i, Scalar(0, 0, 255), 1, 8, contoursHierarchy, 0, Point());
}
// now show the frames in window
imshow("Edge Detection", originalImage);
}
if (waitKey(30) >= 0) break;
}
}
} /* namespace facerecognition */
| [
"souravran@gmail.com"
] | souravran@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.