blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
f64529db8a70a71e53f48e01285ff5a8dd59bfa2
688d5a8227bfd8e7e503a06b256d83f707cdb162
/pet/pet/PetSensitiveDetectorHelper.hh
2567753071c7861361098885dcab7d2a9146686d
[]
no_license
pavel1murat/murat
ea65ee1baf5b3335d080585b04e18d0304963097
d76111a73a18c150e6b5218fc411a2fd05e91e10
refs/heads/main
2023-06-11T07:22:18.986114
2023-05-24T16:35:22
2023-05-24T16:35:22
118,154,861
0
0
null
null
null
null
UTF-8
C++
false
false
3,589
hh
#ifndef murat_pet_PetSensitiveDetectorHelper_hh #define murat_pet_PetSensitiveDetectorHelper_hh // // Some helper functions to manage repeated tasks related to sensitive detectors. // // $Id: PetSensitiveDetectorHelper.hh,v 1.3 2013/10/15 23:41:14 murat Exp $ // $Author: murat $ // $Date: 2013/10/15 23:41:14 $ // // Original author Rob Kutschke // // From Mu2e #include "murat/pet/PetSensitiveDetector.hh" #include "MCDataProducts/inc/StepPointMCCollection.hh" #include "MCDataProducts/inc/StepInstanceName.hh" // From the art tool chain #include "fhiclcpp/ParameterSet.h" #include "cetlib/maybe_ref.h" // From C++ and STL #include <map> #include <memory> #include <string> #include <vector> // Forward references. namespace art { class Event; } namespace fhicl { class ParameterSet; } namespace mu2e { class SimpleConfig; class SimParticleHelper; class PetSensitiveDetectorHelper{ public: PetSensitiveDetectorHelper( fhicl::ParameterSet const& pset ); // Accept compiler generator d'tor, copy c'tor and assignment operator. // Register the sensitive detector with this class; to be called after G4 Initialize. void registerSensitiveDetectors(); // Create data products and pre-fill with input hits if any; to be called at the start of each event. void createProducts(const art::Event& evt, const SimParticleHelper& spHelper); // Attach the new per-event data products to the corresponding sensitive detector objects. void updateSensitiveDetectors( PhysicsProcessInfo& info, const SimParticleHelper& spHelper); // Put the data products into the event. void put( art::Event& event); // Return all of the instances names of the data products to be produced. std::vector<std::string> stepInstanceNamesToBeProduced() const; // Query the same info bool enabled(StepInstanceName::enum_type instance) const; // Return one of the StepPointMCCollections. cet::maybe_ref<StepPointMCCollection> steps( StepInstanceName::enum_type id ); // create SDs for arbitrary logical volumes as requiested void instantiateLVSDs(const SimpleConfig& config); private: // A helper class to hold information about each sensitive detector object. struct StepInstance { explicit StepInstance(StepInstanceName::enum_type astepName ): p(), stepName(StepInstanceName(astepName).name()), sensitiveDetector(0){ } explicit StepInstance(const std::string &name) : stepName(name) {} explicit StepInstance(): p(), stepName(), sensitiveDetector(nullptr){ } // Accept compiler written d'tor, copy c'tor and assignment operator. // See note 2 in the .cc file for why the collection is not held by pointer. // For historical reasons the two names are different; maybe some day we will synchronize them. StepPointMCCollection p; std::string stepName; PetSensitiveDetector* sensitiveDetector; }; // Enabled pre-defined StepPointMC collections, except the timevd. typedef std::map<StepInstanceName::enum_type,StepInstance> InstanceMap; InstanceMap stepInstances_; // Logical volumes requested to be sensitive typedef std::map<std::string,StepInstance> LVSDMap; LVSDMap lvsd_; // Existing hit collections that should be merged into the output typedef std::vector<art::InputTag> InputTags; InputTags preSimulatedHits_; }; } // end namespace mu2e #endif /* murat_pet_PetSensitiveDetectorHelper_hh */
[ "murat@fnal.gov" ]
murat@fnal.gov
b51e1bd77acb329f8a4a6bf52cc2b04014587ea6
a4ff0e0e0f1ecc0051f2538af2c00e5d43a41ba7
/gazebo/common/HeightmapData_TEST.cc
e43edd8a598d6802f92b9413b4d9323831ee7167
[ "Apache-2.0" ]
permissive
vvasco/gazebo
30fe1cf63ddd28f6e1b59804e2fce4945d005463
d7717154e9f3b691ceb0596cfaaee1624410f0b1
refs/heads/master
2022-11-26T09:29:08.751925
2020-01-25T01:21:15
2020-01-25T01:21:15
257,671,837
0
2
NOASSERTION
2020-04-21T17:50:25
2020-04-21T17:50:24
null
UTF-8
C++
false
false
3,061
cc
/* * Copyright (C) 2016 Open Source Robotics Foundation * * 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 <boost/filesystem.hpp> #include <gtest/gtest.h> #include "gazebo/common/CommonIface.hh" #include "gazebo/common/Dem.hh" #include "gazebo/common/HeightmapData.hh" #include "gazebo/common/ImageHeightmap.hh" #include "test_config.h" #include "test/util.hh" #define ELEVATION_TOL 1e-8 using namespace gazebo; class HeightmapDataLoaderTest : public gazebo::testing::AutoLogFixture { }; ///////////////////////////////////////////////// TEST_F(HeightmapDataLoaderTest, ImageHeightmap) { common::HeightmapData *heightmapData = NULL; std::string path; path = "file://media/materials/textures/heightmap_bowl.png"; heightmapData = common::HeightmapDataLoader::LoadTerrainFile( common::find_file(path)); EXPECT_TRUE(heightmapData != nullptr); common::ImageHeightmap *img = dynamic_cast<common::ImageHeightmap *>(heightmapData); EXPECT_TRUE(img != nullptr); // Check the heights and widths EXPECT_EQ(129, static_cast<int>(img->GetHeight())); EXPECT_EQ(129, static_cast<int>(img->GetWidth())); EXPECT_NEAR(0.99607843, img->GetMaxElevation(), ELEVATION_TOL); } #ifdef HAVE_GDAL ///////////////////////////////////////////////// TEST_F(HeightmapDataLoaderTest, DemHeightmap) { common::HeightmapData *heightmapData = NULL; boost::filesystem::path path = TEST_PATH; path /= "data/dem_squared.tif"; heightmapData = common::HeightmapDataLoader::LoadTerrainFile(path.string()); EXPECT_TRUE(heightmapData != nullptr); common::Dem *dem = dynamic_cast<common::Dem *>(heightmapData); EXPECT_TRUE(dem != nullptr); // Check the heights and widths EXPECT_EQ(129, static_cast<int>(dem->GetHeight())); EXPECT_EQ(129, static_cast<int>(dem->GetWidth())); EXPECT_FLOAT_EQ(3984.4849, dem->GetWorldHeight()); EXPECT_FLOAT_EQ(3139.7456, dem->GetWorldWidth()); EXPECT_FLOAT_EQ(65.3583, dem->GetMinElevation()); EXPECT_FLOAT_EQ(318.441, dem->GetMaxElevation()); // Check GetElevation() unsigned int width = dem->GetWidth(); unsigned int height = dem->GetHeight(); EXPECT_FLOAT_EQ(215.82324, dem->GetElevation(0, 0)); EXPECT_FLOAT_EQ(216.04961, dem->GetElevation(width - 1, 0)); EXPECT_FLOAT_EQ(142.2274, dem->GetElevation(0, height - 1)); EXPECT_FLOAT_EQ(209.14784, dem->GetElevation(width - 1, height - 1)); } #endif ///////////////////////////////////////////////// int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
[ "ichen@osrfoundation.org" ]
ichen@osrfoundation.org
bd8a97cb5c7e45ec663be21d5d71325f78255f84
7c56d35835f95fb8f5996b57d25abf669fad30a2
/Framework/Framework/src/lib/Event/WindowEvent/WindowEvent.h
46aa1ea944b640d208f2a4d6ea7baacc36ff2c05
[ "LicenseRef-scancode-warranty-disclaimer", "Zlib", "LicenseRef-scancode-happy-bunny", "MIT", "BSD-3-Clause" ]
permissive
kanekona/MyFramework
d6a79f76cc913353d01d84eb60728a785e014083
9c5f6d597106e491aa0c8b2fe83b79c79ac3ae1e
refs/heads/master
2020-04-27T08:25:20.003304
2019-10-20T05:24:52
2019-10-20T05:24:52
174,170,600
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
493
h
#pragma once #include <fstream> #include <sstream> class CWindowEvent { public: /** *@brief constructor *@param[in] ifstream& ifs ファイルデータ *@param[out] int* x X値 *@param[out] int* y Y値 */ explicit CWindowEvent(std::ifstream& ifs, int* x, int* y); /** *@brief constructor *@param[in] ifstream& ifs ファイルデータ *@param[out] WindowParameter* parameter */ explicit CWindowEvent(std::ifstream& ifs); /** *@brief destructor */ virtual ~CWindowEvent(); };
[ "amausakonata1932@gmail.com" ]
amausakonata1932@gmail.com
7a75dc149ec49f15b6bbfd918109aa127705eb94
6c376312457b8af43e372d10bbe6ba29f58cf99d
/DirectX11_BaseSystem/Include/Havok_SDK/Physics2012/Utilities/CharacterControl/StateMachine/hkpCharacterStateManager.h
db6ebf02ff0f1a852cfcb8bb997e7cbae09de43a
[]
no_license
kururu-zzz/DirectWrite
f3599ae83c0edefb574ccd9c0026a151a68fbfbf
19fe366832ec04cbcdb79db799eb8088ced376ad
refs/heads/master
2021-01-10T08:00:53.148408
2015-12-17T04:51:31
2015-12-17T04:51:31
48,152,937
1
0
null
null
null
null
UTF-8
C++
false
false
2,867
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2014 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_CHARACTER_STATE_MANAGER_H #define HK_CHARACTER_STATE_MANAGER_H #include <Physics2012/Utilities/CharacterControl/StateMachine/hkpCharacterState.h> class hkpCharacterState; /// The character state manager. The manager allows the user to add and remove their own /// derived states at runtime to the state machine. /// A state manager is designed to be shared between characters that have that same control mechanism. /// e.g., all Orcs might reuse the same single instance of a state manager. /// If you create your own custom states be careful about placing per character data there. /// You will be forced to instantiate one manager per character. A better alternative is to derive from /// the hkpCharacterInput class or use its user data member to point to per character info. class hkpCharacterStateManager : public hkReferencedObject { public: HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_CHARACTER); /// Initialises the array of states to return HK_NULL for all state types hkpCharacterStateManager(); // Removes references to all registered states ~hkpCharacterStateManager(); /// Registers a state for a given state type. This adds a reference to the registered. /// If a state already exists for this type then the reference to the existing state /// is removed. void registerState(hkpCharacterState* m_state, hkpCharacterStateType state); /// returns the state registered for the given type. /// If no state has been registered this returns HK_NULL hkpCharacterState* getState(hkpCharacterStateType initialState) const; private: hkpCharacterState* m_registeredState[HK_CHARACTER_MAX_STATE_ID]; }; #endif // HK_CHARACTER_STATE_MANAGER_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907) * * Confidential Information of Havok. (C) Copyright 1999-2014 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ "kurukuru.0844808@gmail.com" ]
kurukuru.0844808@gmail.com
9ea99328faf4dfa8acfb9511c28cf3c822804fe9
6adb9c51674ae34b89b3c65120c7bc5d81f4d091
/src/main.cpp
0e11328c6b2ff43007bd8409e6306c96a0b99c0a
[]
no_license
hegyibalint/BurbWatch
0a30cb87170c0c27e7f3844254c38767b7673900
febff0d097545755e8ecad40e29b6ec915ffa5c2
refs/heads/master
2023-04-10T22:57:36.878932
2021-05-02T08:48:46
2021-05-02T08:48:46
358,340,239
0
0
null
null
null
null
UTF-8
C++
false
false
377
cpp
#include <iostream> #include <thread> #include <exception> #include "FrameSource.h" int main(int argc, char **argv) { // auto renderer = NvEglRenderer::createEglRenderer( // "renderer0", 1280, 720, 0, 0 // ); // if (!renderer) { // throw std::runtime_error{"Cannot create renderer"}; // } FrameSource frameSource; frameSource.start(); // delete renderer; }
[ "balint.bence.hegyi@cern.ch" ]
balint.bence.hegyi@cern.ch
cf2dce51c62297f8d28e662fb536dca4649c0281
24f664aa2344d4f5d5e7b048ac4e85231715c4c8
/learn/hoocl/003-vadd_cpp.cc
974cafad12baba9ab7c187a799da33beac9d7afe
[]
no_license
speycode/clfuzz
79320655e879d1e0a06a481e8ec2e293c7c10db7
f2a96cf84a7971f70cb982c07b84207db407b3eb
refs/heads/master
2020-12-05T13:44:55.486419
2020-01-03T14:14:03
2020-01-03T14:15:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,293
cc
//------------------------------------------------------------------------------ // // Name: vadd_cpp.cpp // // Purpose: Elementwise addition of two vectors (c = a + b) // // c = a + b // // HISTORY: Written by Tim Mattson, June 2011 // Ported to C++ Wrapper API by Benedict Gaster, September 2011 // Updated to C++ Wrapper API v1.2 by Tom Deakin and // Simon McIntosh-Smith, October 2012 // Updated to C++ Wrapper v1.2.6 by Tom Deakin, August 2013 // //------------------------------------------------------------------------------ #include "third_party/opencl/cl.hpp" #include "./err_code.h" #include "./util.hpp" #include <cstdio> #include <cstdlib> #include <fstream> #include <iostream> #include <string> #include <vector> #include <stdlib.h> static unsigned int seed = 0xCEC; #ifndef DEVICE #define DEVICE CL_DEVICE_TYPE_DEFAULT #endif //------------------------------------------------------------------------------ static const float tolerance = 0.001f; static const size_t count = 1024; int main(void) { std::vector<float> h_a(count); // a vector std::vector<float> h_b(count); // b vector std::vector<float> h_c(count, 0xdeadbeef); // c = a + b cl::Buffer d_a; // device memory used for the input a vector cl::Buffer d_b; // device memory used for the input b vector cl::Buffer d_c; // device memory used for the output c vector // Fill vectors a and b with random float values for (size_t i = 0; i < count; i++) { h_a[i] = rand_r(&seed) / static_cast<float>(UINT32_MAX); h_b[i] = rand_r(&seed) / static_cast<float>(UINT32_MAX); } try { // Create a context cl::Context context(DEVICE); // Load in kernel source, creating a program object for the context cl::Program program(context, util::loadProgram("vadd.cl"), true); // Get the command queue cl::CommandQueue queue(context); // Create the kernel functor auto vadd = cl::make_kernel<cl::Buffer, cl::Buffer, cl::Buffer, int>( program, "vadd"); d_a = cl::Buffer(context, begin(h_a), end(h_a), true); d_b = cl::Buffer(context, begin(h_b), end(h_b), true); d_c = cl::Buffer(context, CL_MEM_WRITE_ONLY, sizeof(float) * count); util::Timer timer; vadd(cl::EnqueueArgs(queue, cl::NDRange(count)), d_a, d_b, d_c, static_cast<int>(count)); queue.finish(); double rtime = static_cast<double>(timer.getTimeMilliseconds()) / 1000.0; printf("\nThe kernels ran in %lf seconds\n", rtime); cl::copy(queue, d_c, begin(h_c), end(h_c)); // NOLINT // Test the results int correct = 0; float tmp; for (size_t i = 0; i < count; i++) { tmp = h_a[i] + h_b[i]; // expected value for d_c[i] tmp -= h_c[i]; // compute errors if (tmp * tmp < tolerance * tolerance) correct++; else printf(" tmp %f h_a %f h_b %f h_c %f \n", tmp, h_a[i], h_b[i], h_c[i]); } // summarize results printf("vector add to find C = A+B: %d out of %zu results were correct.\n", correct, count); } catch (cl::Error err) { std::cout << "Exception\n"; std::cerr << "ERROR: " << err.what() << "(" << err_code(err.err()) << ")\n"; } }
[ "chrisc.101@gmail.com" ]
chrisc.101@gmail.com
8af996fb5d8b35fcf8be031590863c5e141161e7
4dc9b9ff2c8cb15af3dec9211c06e81e0794bbe9
/Source/KrazyKarts/GoKartMovementComponent.h
547c4a5716370c9da4508db4bb6d23b8f17b8048
[]
no_license
chpehs/KrazyKarts
f38af03f7b4744b70cdce39714a81e7ddf13a02b
e18f2fe75f6a5568f9629276621e366374222509
refs/heads/master
2023-02-23T04:27:20.423502
2021-01-30T19:46:16
2021-01-30T19:46:16
334,497,887
0
0
null
null
null
null
UTF-8
C++
false
false
2,125
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "GoKartMovementComponent.generated.h" USTRUCT() struct FGoKartMove { GENERATED_USTRUCT_BODY() UPROPERTY() float Throttle; UPROPERTY() float SteeringThrow; UPROPERTY() float DeltaTime; UPROPERTY() float Time; bool IsValid() const { return FMath::Abs(Throttle) <= 1 && FMath::Abs(SteeringThrow) <= 1; } }; UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent)) class KRAZYKARTS_API UGoKartMovementComponent : public UActorComponent { GENERATED_BODY() public: // Sets default values for this component's properties UGoKartMovementComponent(); protected: // Called when the game starts virtual void BeginPlay() override; public: // Called every frame virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; void SimulateMove(const FGoKartMove& Move); FVector GetVelocity() { return Velocity; }; void SetVelocity(FVector Val) { Velocity = Val; }; void SetThrottle(float Val) { Throttle = Val; }; void SetSteeringThrow(float Val) { SteeringThrow = Val; }; FGoKartMove GetLastMove() { return LastMove; }; private: FGoKartMove CreateMove(float DeltaTime); FVector GetAirResistance(); FVector GetRollingResistance(); void ApplyRotation(float DeltaTime, float SteeringThrow); void UpdateLocationFromVelocity(float DeltaTime); // The mass of the car (kg). UPROPERTY(EditAnywhere) float Mass = 1000; // The force applied to the car when the throttle is fully down (N). UPROPERTY(EditAnywhere) float MaxDrivingForce = 10000; // Minimum radius of the car turning circle at full lock (m). UPROPERTY(EditAnywhere) float MinTurningRadius = 10; // Higher means more drag. UPROPERTY(EditAnywhere) float DragCoefficient = 16; // Higher means more rolling resistance. UPROPERTY(EditAnywhere) float RollingResistanceCoefficient = 0.015; FVector Velocity; float Throttle; float SteeringThrow; FGoKartMove LastMove; };
[ "stiflercorejz@gmail.com" ]
stiflercorejz@gmail.com
df188844ce2bd6c30481213e5faafff2e5ec70f0
7bf4223cbe760159ba54a52e44437956d6344e4e
/Walnut Grove/Tower Blue/src/main.cpp
51013d846f5d8656e7562839295c38a282558a11
[]
no_license
pinapelz/1010MTowerTakeover
a76fabc25751dacda6e34cb47e0bfd4198bf1bd4
59220ddb68cf936c8aecd1f7fb107275a106d187
refs/heads/master
2020-09-13T13:25:16.758166
2020-02-29T03:18:40
2020-02-29T03:18:40
222,796,667
0
0
null
null
null
null
UTF-8
C++
false
false
16,994
cpp
// ---- START VEXCODE CONFIGURED DEVICES ---- // Robot Configuration: // [Name] [Type] [Port(s)] // RightMotorB motor 2 // LeftMotorF motor 3 // RightMotorF motor 4 // LeftMotorB motor 11 // IntakeR motor 16 // IntakeL motor 12 // Pusher motor 20 // Lift motor 15 // Controller1 controller // Limit1 limit C // Limit2 limit A // Controller2 controller // ---- END VEXCODE CONFIGURED DEVICES ---- #include "vex.h" #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "v5.h" #include "v5_vcs.h" // using namespace vex; vex::competition Competition; int count = 0; int matchTimer = 105; void strafeLeft(int speed, int rotation) { // Move side ways to the left LeftMotorF.setVelocity(speed, velocityUnits::pct); LeftMotorB.setVelocity(speed, velocityUnits::pct); RightMotorF.setVelocity(speed, velocityUnits::pct); RightMotorB.setVelocity(speed, velocityUnits::pct); LeftMotorF.rotateFor(-rotation, rotationUnits::deg, false); RightMotorF.rotateFor(rotation, rotationUnits::deg, false); LeftMotorB.rotateFor(rotation, rotationUnits::deg, false); RightMotorB.rotateFor(-rotation, rotationUnits::deg, false); } void strafeRight(int speed, int rotation) { // Move side ways to the right LeftMotorF.setVelocity(-speed, velocityUnits::pct); LeftMotorB.setVelocity(-speed, velocityUnits::pct); RightMotorF.setVelocity(-speed, velocityUnits::pct); RightMotorB.setVelocity(-speed, velocityUnits::pct); LeftMotorF.rotateFor(-rotation, rotationUnits::deg, false); RightMotorF.rotateFor(rotation, rotationUnits::deg, false); LeftMotorB.rotateFor(rotation, rotationUnits::deg, false); RightMotorB.rotateFor(-rotation, rotationUnits::deg, false); } void storageFwd(int speed, int rotation) { // Move the pusher forward Pusher.setVelocity(speed, velocityUnits::pct); Pusher.rotateFor(-rotation, rotationUnits::deg, false); } void driveForward( int speed, int rotation) { // Drive forward function that uses motor degrees LeftMotorF.setVelocity(speed, velocityUnits::pct); LeftMotorB.setVelocity(speed, velocityUnits::pct); RightMotorF.setVelocity(speed, velocityUnits::pct); RightMotorB.setVelocity(speed, velocityUnits::pct); LeftMotorF.rotateFor(rotation, rotationUnits::deg, false); RightMotorF.rotateFor(rotation, rotationUnits::deg, false); LeftMotorB.rotateFor(rotation, rotationUnits::deg, false); RightMotorB.rotateFor(rotation, rotationUnits::deg, false); } void strafeLeftDrive(int speed) { // Move sideways to the left LeftMotorF.spin(vex::directionType::fwd, speed, vex::velocityUnits::pct); RightMotorF.spin(vex::directionType::rev, speed, vex::velocityUnits::pct); LeftMotorB.spin(vex::directionType::rev, speed, vex::velocityUnits::pct); RightMotorB.spin(vex::directionType::fwd, speed, vex::velocityUnits::pct); } void strafeRightDrive(int speed) { // Move side ways to the right LeftMotorF.spin(vex::directionType::rev, speed, vex::velocityUnits::pct); RightMotorF.spin(vex::directionType::fwd, speed, vex::velocityUnits::pct); LeftMotorB.spin(vex::directionType::fwd, speed, vex::velocityUnits::pct); RightMotorB.spin(vex::directionType::rev, speed, vex::velocityUnits::pct); } void placeCubes() { // Macro/Function used to place the cubes down with one // press of a button Lift.stop(brakeType::hold); // Stop the arm Pusher.setVelocity( 90, velocityUnits::pct); // Set the pusher speed to 90% of max speed Lift.stop(brakeType::hold); // Stop the arm Pusher.rotateFor(850, rotationUnits::deg, true); // Rotate the pusher by 375 degrees Lift.stop(brakeType::hold); // Stop the arm Pusher.setVelocity( 60, velocityUnits::pct); // Set the pusher speed to 60% of the max speed Lift.stop(brakeType::hold); // Stop the arm Pusher.rotateFor(375, rotationUnits::deg, true); // Rotate the pusher by another 375 degrees Lift.stop(brakeType::hold); // Stop the arm Pusher.setVelocity( 10, velocityUnits::pct); // Set the pusher speed to 10% of the full speed Lift.stop(brakeType::hold); // Stop the arm Pusher.rotateFor(60, rotationUnits::deg, true); // Rotate the pusher by 60 rotations Lift.stop(brakeType::hold); // Stop the arm } void driveBackward( int speed, int rotation) { // Drive backward function that uses motor degrees LeftMotorF.setVelocity(speed, velocityUnits::pct); LeftMotorB.setVelocity(speed, velocityUnits::pct); RightMotorF.setVelocity(speed, velocityUnits::pct); RightMotorB.setVelocity(speed, velocityUnits::pct); LeftMotorF.rotateFor(-rotation, rotationUnits::deg, false); RightMotorF.rotateFor(-rotation, rotationUnits::deg, false); LeftMotorB.rotateFor(-rotation, rotationUnits::deg, false); RightMotorB.rotateFor(-rotation, rotationUnits::deg, false); } void driveRight(int speed, int rotation) { // Turn left using motor degrees LeftMotorF.setVelocity(speed, velocityUnits::pct); LeftMotorB.setVelocity(speed, velocityUnits::pct); RightMotorF.setVelocity(speed, velocityUnits::pct); RightMotorB.setVelocity(speed, velocityUnits::pct); LeftMotorF.rotateFor(rotation, rotationUnits::deg, false); RightMotorF.rotateFor(-rotation, rotationUnits::deg, false); LeftMotorB.rotateFor(rotation, rotationUnits::deg, false); RightMotorB.rotateFor(-rotation, rotationUnits::deg, false); } void driveLeft(int speed, int rotation) { // Turn left at Y speed and for X rotations LeftMotorF.setVelocity(speed, velocityUnits::pct); LeftMotorB.setVelocity(speed, velocityUnits::pct); RightMotorF.setVelocity(speed, velocityUnits::pct); RightMotorB.setVelocity(speed, velocityUnits::pct); LeftMotorF.rotateFor(-rotation, rotationUnits::deg, false); RightMotorF.rotateFor(rotation, rotationUnits::deg, false); LeftMotorB.rotateFor(-rotation, rotationUnits::deg, false); RightMotorB.rotateFor(rotation, rotationUnits::deg, false); } void liftSpin(int speed, int rotation) { // Spin the arm at speed x and for y rotationUnits Lift.setVelocity(speed, velocityUnits::pct); Lift.rotateFor(rotation, rotationUnits::deg, true); } void spin(int time, int speed) { // Spin the intake for x amount of time and at y speed IntakeR.spin(vex::directionType::fwd, 100, vex::velocityUnits::pct); IntakeL.spin(vex::directionType::fwd, 100, vex::velocityUnits::pct); vex::task::sleep(time); } void stopall(int stopTime) { // Stop all the motors for specified time LeftMotorF.stop(); RightMotorF.stop(); LeftMotorB.stop(); RightMotorB.stop(); IntakeR.stop(); IntakeL.stop(); vex::task::sleep(stopTime); } void flipOut(void) { // The function we use to flip out the robot //********Move the pusher forward and backwards so that the pusher flips out /*Pusher.setVelocity(100, velocityUnits::pct); Pusher.rotateFor(900, rotationUnits::deg, true); vex::task::sleep(100); Pusher.setVelocity(100, velocityUnits::pct); Pusher.rotateFor(-700, rotationUnits::deg, true); vex::task::sleep(100);*/ Lift.setVelocity(100, velocityUnits::pct); Lift.rotateFor(-300, rotationUnits::deg, true); Lift.setVelocity(100, velocityUnits::pct); Lift.rotateFor(400, rotationUnits::deg, true); /* Pusher.setVelocity(100, velocityUnits::pct); // Set the pusher speed to 75 Pusher.rotateFor(-230, rotationUnits::deg, true); // Bring the pusher back*/ stopall(10); // Stop all motors for 10ms driveBackward(75, 75); // Backward vex::task::sleep(300); } const int cJoyDead = 8; const int cMotorMin = 15; const float cDriveExp = 1.4; int expDrive(int joyVal, float driveExp, int joyDead, int motorMin) { int joySign; int joyMax = 127 - joyDead; int joyLive = abs(joyVal) - joyDead; if (joyVal > 0) { joySign = 1; } else if (joyVal < 0) { joySign = -1; } else { joySign = 0; } int power = joySign * (motorMin + ((100 - motorMin) * pow(joyLive, driveExp) / pow(joyMax, driveExp))); return power; } // EXPO drive constants void autonomusA() { int driveforward = 1170; int driveforwardspeed = 40; Pusher.setVelocity(100, velocityUnits::pct); Pusher.rotateFor(1000, rotationUnits::deg, true); vex::task::sleep(100); Pusher.setVelocity(100, velocityUnits::pct); Pusher.rotateFor(-1000, rotationUnits::deg, true); vex::task::sleep(100); Lift.setVelocity(100, velocityUnits::pct); Lift.rotateFor(-300, rotationUnits::deg, true); Lift.setVelocity(100, velocityUnits::pct); Lift.rotateFor(280, rotationUnits::deg, true); stopall(10); // Stop all the motors for 10 milliseconds //**** Move forward while intaking the four cubes // There are stop lines every line to hold the arm in place after every action LeftMotorF.setVelocity( driveforwardspeed, velocityUnits::pct); // Set the Left Motor Forward to speed 30 Lift.stop(vex::brakeType::hold); // Stop arm LeftMotorB.setVelocity( driveforwardspeed, velocityUnits::pct); // Set the Left Motor Back to speed 30 Lift.stop(vex::brakeType::hold); // Stop arm RightMotorF.setVelocity( driveforwardspeed, velocityUnits::pct); // Set the Right Motor Forward to speed 30 Lift.stop(vex::brakeType::hold); // Stop arm RightMotorB.setVelocity( driveforwardspeed, velocityUnits::pct); // Set the Right Motor Back to speed 30 Lift.stop(vex::brakeType::hold); // Stop arm LeftMotorF.rotateFor(driveforward, rotationUnits::deg, false); // Rotate motor Left Front 1300 degrees Lift.stop(vex::brakeType::hold); // Stop arm RightMotorF.rotateFor(driveforward, rotationUnits::deg, false); // Rotate the Right Front wheel 1300 degrees Lift.stop(vex::brakeType::hold); // Stop the arm LeftMotorB.rotateFor(driveforward, rotationUnits::deg, false); // Rotate the Left Back wheel 1300 degrees Lift.stop(vex::brakeType::hold); // Stop the arm RightMotorB.rotateFor(driveforward, rotationUnits::deg, false); // Rotate the Right Back wheel by 1300 degrees IntakeR.spin(vex::directionType::rev, 127, vex::velocityUnits::pct); // Intake IntakeL.spin(vex::directionType::rev, 127, vex::velocityUnits::pct); // Intake Lift.stop(vex::brakeType::hold); vex::task::sleep(3200); //****************************Give the robot 4.35 seconds to do this task stopall(10); // Stop all motors for 10 milliseconds // NEED TO CHANGE driveRight(75, 882); // Turn right 820 motor degrees vex::task::sleep(1700); // Give the robot one second to do this task driveForward(60, 900); // Drive forward at 60 speed and 1170 motor degrees Lift.stop(vex::brakeType::hold); // Hold the arm in place vex::task::sleep(2000); // Give the robot 2 seconds to do this stopall(10); // Stop all motors for 10ms // Outtake for 750 milliseconds stopall(10); // Stop all motors driveForward(50, 100); // Drive forward for 50 degrees vex::task::sleep(300); // Give the robot 300 milliseconds to do this IntakeR.spin(vex::directionType::fwd, 50, vex::velocityUnits::pct); IntakeL.spin(vex::directionType::fwd, 50, vex::velocityUnits::pct); vex::task::sleep(150); placeCubes(); // Place the cubes using the function driveBackward(127, 200); // Back away from the cubes vex::task::sleep(300); Pusher.setVelocity(100, velocityUnits::pct); Pusher.rotateFor(-700, rotationUnits::deg, true); vex::task::sleep(100); // Give the robot 300 milliseconds to do this // END OF AUTONOMUS } void pidIntake(int desire){ LeftMotorB.resetRotation(); int kP = 100; int kI = 100000; int kD = 10000; int want = desire; int totalError = 0; bool done = false; double lastError = LeftMotorB.rotation(vex::rotationUnits::deg); while(done=false){ int curr = LeftMotorB.rotation(vex::rotationUnits::deg); int currError = curr- want; totalError += currError; int diff = currError - lastError; int currSpeed = currError/kP+totalError/kI + diff/kD; LeftMotorB.spin(directionType::fwd, currSpeed, vex::velocityUnits::pct); LeftMotorF.spin(directionType::fwd, currSpeed, vex::velocityUnits::pct); RightMotorB.spin(directionType::fwd, currSpeed, vex::velocityUnits::pct); RightMotorF.spin(directionType::fwd, currSpeed, vex::velocityUnits::pct); IntakeR.spin(vex::directionType::rev, 127, vex::velocityUnits::pct); // Intake IntakeL.spin(vex::directionType::rev, 127, vex::velocityUnits::pct); // Intake lastError = currError; if(currError==0){ done = true; } vex::task::sleep(20); } } void autoB(){ flipOut(); pidIntake(100); } void pre_auton(void) {} void autonomous(void) { int autonsequence = 1; if (autonsequence == 1) { autonomusA(); } else if(autonsequence==2){ autoB(); } } void timer1() { while (true) { this_thread::sleep_for(1000); count++; } } /********************************* Driver Control Code Below BADGES DOWN HERE /********************************* */ int intakeSpeed = 127; int outakeSpeed = 30; void usercontrol(void) { // Variables Used in OP Control thread myThread = thread(timer1); while (1) { // While the program is running int Ch1 = Controller1.Axis1.value() / 1.5; int Ch3 = Controller1.Axis3.value() / 2; int Ch4 = Controller1.Axis4.value() / 1.5; int Ch2 = Controller2.Axis3.value()/1.5; Pusher.spin(vex::directionType::fwd, Controller2.Axis3.value(), vex::velocityUnits::pct); LeftMotorF.spin(vex::directionType::fwd, Ch3 + Ch1 + Ch4, vex::velocityUnits::pct); LeftMotorB.spin(vex::directionType::fwd, Ch3 + Ch1 - Ch4, vex::velocityUnits::pct); RightMotorB.spin(vex::directionType::fwd, Ch3 - Ch1 + Ch4, vex::velocityUnits::pct); RightMotorF.spin(vex::directionType::fwd, Ch3 - Ch1 - Ch4, vex::velocityUnits::pct); if (Controller1.ButtonL2.pressing()) { IntakeL.spin(directionType::fwd, 127, vex::velocityUnits::pct); IntakeR.spin(directionType::fwd, 127, vex::velocityUnits::pct); Lift.stop(brakeType::hold); } // If L1 is held down then spin the intake forward else if (Controller1.ButtonR2.pressing()) { IntakeL.spin(directionType::rev, outakeSpeed, vex::velocityUnits::pct); IntakeR.spin(directionType::rev, outakeSpeed, vex::velocityUnits::pct); } if (Controller1.ButtonUp.pressing()) { outakeSpeed = 127; } if (Controller1.ButtonDown.pressing()) { outakeSpeed = 30; } // If Button R1 is pressed move the arm up else if (Controller1.ButtonL1.pressing()) { Lift.spin(directionType::rev, 127, vex::velocityUnits::pct); // Hopefully will be able to use Macros here } // If Button R2 is pressed move the arm down else if (Controller1.ButtonR1.pressing() ) { Lift.spin(directionType::fwd, 127, vex::velocityUnits::pct); // Hopefully will be able to use Macros here } else if (Controller1.ButtonR2.pressing()) { IntakeL.spin(directionType::rev, 127, vex::velocityUnits::pct); IntakeR.spin(directionType::rev, 127, vex::velocityUnits::pct); // Hopefully will be able to use Macros here } else if(Controller1.ButtonA.pressing()){ Pusher.spin(directionType::fwd, 45, vex::velocityUnits::pct); vex::task::sleep(10); } else if(Controller1.ButtonB.pressing()){ Pusher.spin(directionType::rev, 127, vex::velocityUnits::pct); vex::task::sleep(10); } // If Button R2 is pressed move the arm down else if (Controller1.ButtonL2.pressing()) { IntakeL.spin(directionType::fwd, 127, vex::velocityUnits::pct); IntakeR.spin(directionType::fwd, 127, vex::velocityUnits::pct); // Hopefully will be able to use Macros here } else{ Lift.stop(brakeType::hold); IntakeL.stop(); IntakeR.stop(); } if(Controller2.Axis3.value()==0){ Pusher.stop(brakeType::hold); } // Push the pusher forward when A is pressed } } int main() { // Set up callbacks for autonomous and driver control periods. Competition.autonomous(autonomous); Competition.drivercontrol(usercontrol); // Run the pre-autonomous function. pre_auton(); // Prevent main from exiting with an infinite loop. while (true) { wait(100, msec); } }
[ "noreply@github.com" ]
pinapelz.noreply@github.com
b855d19b481b5e3bfe272282a0b7e4f5ff45e90a
aaafa161d2f507249dfb984a1d322f803c927177
/src/tll/util/zlib.h
a8de93fd7b6d1da6794e5c94f4e303b526510a84
[ "MIT" ]
permissive
shramov/tll
4daf76af334c877b99a3f964a66536a1072aa3e7
72338ff3dcc351666ed86a814ebf093491820dc1
refs/heads/master
2023-08-17T13:06:39.833241
2023-08-16T08:12:10
2023-08-17T06:40:47
204,337,361
7
2
MIT
2021-11-04T19:54:37
2019-08-25T18:59:54
C++
UTF-8
C++
false
false
3,064
h
/* * Copyright (c) 2018-2021 Pavel Shramov <shramov@mexmat.net> * * tll is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. */ #ifndef _TLL_UTIL_ZLIB_H #define _TLL_UTIL_ZLIB_H #include <memory> #include <vector> #include <zlib.h> namespace tll::zlib { struct inflate_delete { void operator () (z_stream *ptr) const { inflateEnd(ptr); } }; struct deflate_delete { void operator () (z_stream *ptr) const { deflateEnd(ptr); } }; template <typename T, typename Buf> inline result_t<bool> decompress(const T &data, Buf & buf) { if (data.size() == 0) { buf.resize(0); return true; } z_stream stream = {0}; if (inflateInit2(&stream, MAX_WBITS + 32)) return error("Failed to init inflate stream"); std::unique_ptr<z_stream, inflate_delete> _stream { &stream }; buf.resize(data.size() * 2); stream.avail_in = data.size(); stream.next_in = (Bytef *) data.data(); stream.avail_out = buf.size(); stream.next_out = (Bytef *) buf.data(); do { auto r = inflate(&stream, Z_FINISH); if (r == Z_STREAM_END) break; if (r != Z_OK && r != Z_BUF_ERROR) return error("Failed to decompress data"); if (stream.avail_in == 0) return error("Truncated compressed data"); if (buf.size() * 2 > 16 * 1024 * 1024) return error("Requested too large buffer (> 16Mb)"); buf.resize(buf.size() * 2); stream.avail_out = buf.size() - stream.total_out; stream.next_out = stream.total_out + (Bytef *) buf.data(); } while (true); buf.resize(stream.total_out); return true; } template <typename T> inline result_t<std::vector<char>> decompress(const T &data) { std::vector<char> buf; auto r = decompress(data, buf); if (!r) return error(r.error()); return buf; } template <typename T, typename Buf> inline result_t<bool> compress(const T &data, Buf & buf, int level = Z_DEFAULT_COMPRESSION) { if (data.size() == 0) { buf.resize(0); return true; } z_stream stream = {0}; if (deflateInit(&stream, level)) return error("Failed to init deflate stream"); std::unique_ptr<z_stream, deflate_delete> _stream { &stream }; buf.resize(deflateBound(&stream, data.size())); stream.avail_in = data.size(); stream.next_in = (Bytef *) data.data(); stream.avail_out = buf.size(); stream.next_out = (Bytef *) buf.data(); do { auto r = deflate(&stream, Z_FINISH); if (r == Z_STREAM_END) break; if (r != Z_OK && r != Z_BUF_ERROR) return error("Failed to compress data"); if (buf.size() * 2 > 16 * 1024 * 1024) return error("Requested too large buffer (> 16Mb)"); buf.resize(buf.size() * 2); stream.avail_out = buf.size() - stream.total_out; stream.next_out = stream.total_out + (Bytef *) buf.data(); } while (true); buf.resize(stream.total_out); return true; } template <typename T> inline result_t<std::vector<char>> compress(const T &data, int level = Z_DEFAULT_COMPRESSION) { std::vector<char> buf; auto r = compress(data, buf, level); if (!r) return error(r.error()); return buf; } } // namespace tll::util #endif//_TLL_UTIL_ZLIB_H
[ "psha@nguni.psha.org.ru" ]
psha@nguni.psha.org.ru
506f375ba8390401680691c60d4a4e5a4b33501b
2dead05a1b143ecb5e5395d092516700a028a7aa
/IRScan/IRScan/GeneratedFiles/Debug/moc_IRScan.cpp
6b85d03107cfc4a61fa9487eeff18bf37892791c
[]
no_license
seafrog1984/QTIRScan
54e895e767c5343ccaeefdeb86068ad266b49746
814159ba066c0a5a3034ea6f03d740bf674f9c16
refs/heads/master
2020-05-18T19:43:40.512870
2020-01-22T17:35:28
2020-01-22T17:35:28
184,614,586
0
0
null
null
null
null
UTF-8
C++
false
false
7,318
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'IRScan.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.6.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../IRScan.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'IRScan.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.6.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_IRScan_t { QByteArrayData data[27]; char stringdata0[291]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_IRScan_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_IRScan_t qt_meta_stringdata_IRScan = { { QT_MOC_LITERAL(0, 0, 6), // "IRScan" QT_MOC_LITERAL(1, 7, 16), // "btn_scan_Clicked" QT_MOC_LITERAL(2, 24, 0), // "" QT_MOC_LITERAL(3, 25, 12), // "btn_focusFar" QT_MOC_LITERAL(4, 38, 10), // "btn_sysPar" QT_MOC_LITERAL(5, 49, 11), // "btn_setAuth" QT_MOC_LITERAL(6, 61, 13), // "btn_show_func" QT_MOC_LITERAL(7, 75, 13), // "btn_clockWise" QT_MOC_LITERAL(8, 89, 13), // "btn_antiClock" QT_MOC_LITERAL(9, 103, 9), // "btn_camUp" QT_MOC_LITERAL(10, 113, 11), // "btn_camDown" QT_MOC_LITERAL(11, 125, 11), // "btn_camLeft" QT_MOC_LITERAL(12, 137, 12), // "btn_camRight" QT_MOC_LITERAL(13, 150, 7), // "btn_reg" QT_MOC_LITERAL(14, 158, 7), // "btn_del" QT_MOC_LITERAL(15, 166, 10), // "btn_change" QT_MOC_LITERAL(16, 177, 7), // "btn_pre" QT_MOC_LITERAL(17, 185, 8), // "btn_next" QT_MOC_LITERAL(18, 194, 9), // "btn_start" QT_MOC_LITERAL(19, 204, 7), // "btn_end" QT_MOC_LITERAL(20, 212, 11), // "btn_dateSel" QT_MOC_LITERAL(21, 224, 11), // "btn_nameSel" QT_MOC_LITERAL(22, 236, 11), // "btn_showAll" QT_MOC_LITERAL(23, 248, 12), // "btn_sendData" QT_MOC_LITERAL(24, 261, 11), // "time_update" QT_MOC_LITERAL(25, 273, 9), // "customize" QT_MOC_LITERAL(26, 283, 7) // "Monitor" }, "IRScan\0btn_scan_Clicked\0\0btn_focusFar\0" "btn_sysPar\0btn_setAuth\0btn_show_func\0" "btn_clockWise\0btn_antiClock\0btn_camUp\0" "btn_camDown\0btn_camLeft\0btn_camRight\0" "btn_reg\0btn_del\0btn_change\0btn_pre\0" "btn_next\0btn_start\0btn_end\0btn_dateSel\0" "btn_nameSel\0btn_showAll\0btn_sendData\0" "time_update\0customize\0Monitor" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_IRScan[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 25, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 139, 2, 0x08 /* Private */, 3, 0, 140, 2, 0x08 /* Private */, 4, 0, 141, 2, 0x08 /* Private */, 5, 0, 142, 2, 0x08 /* Private */, 6, 0, 143, 2, 0x08 /* Private */, 7, 0, 144, 2, 0x08 /* Private */, 8, 0, 145, 2, 0x08 /* Private */, 9, 0, 146, 2, 0x08 /* Private */, 10, 0, 147, 2, 0x08 /* Private */, 11, 0, 148, 2, 0x08 /* Private */, 12, 0, 149, 2, 0x08 /* Private */, 13, 0, 150, 2, 0x08 /* Private */, 14, 0, 151, 2, 0x08 /* Private */, 15, 0, 152, 2, 0x08 /* Private */, 16, 0, 153, 2, 0x08 /* Private */, 17, 0, 154, 2, 0x08 /* Private */, 18, 0, 155, 2, 0x08 /* Private */, 19, 0, 156, 2, 0x08 /* Private */, 20, 0, 157, 2, 0x08 /* Private */, 21, 0, 158, 2, 0x08 /* Private */, 22, 0, 159, 2, 0x08 /* Private */, 23, 0, 160, 2, 0x08 /* Private */, 24, 0, 161, 2, 0x08 /* Private */, 25, 0, 162, 2, 0x08 /* Private */, 26, 0, 163, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void IRScan::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { IRScan *_t = static_cast<IRScan *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->btn_scan_Clicked(); break; case 1: _t->btn_focusFar(); break; case 2: _t->btn_sysPar(); break; case 3: _t->btn_setAuth(); break; case 4: _t->btn_show_func(); break; case 5: _t->btn_clockWise(); break; case 6: _t->btn_antiClock(); break; case 7: _t->btn_camUp(); break; case 8: _t->btn_camDown(); break; case 9: _t->btn_camLeft(); break; case 10: _t->btn_camRight(); break; case 11: _t->btn_reg(); break; case 12: _t->btn_del(); break; case 13: _t->btn_change(); break; case 14: _t->btn_pre(); break; case 15: _t->btn_next(); break; case 16: _t->btn_start(); break; case 17: _t->btn_end(); break; case 18: _t->btn_dateSel(); break; case 19: _t->btn_nameSel(); break; case 20: _t->btn_showAll(); break; case 21: _t->btn_sendData(); break; case 22: _t->time_update(); break; case 23: _t->customize(); break; case 24: _t->Monitor(); break; default: ; } } Q_UNUSED(_a); } const QMetaObject IRScan::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_IRScan.data, qt_meta_data_IRScan, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *IRScan::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *IRScan::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_IRScan.stringdata0)) return static_cast<void*>(const_cast< IRScan*>(this)); return QMainWindow::qt_metacast(_clname); } int IRScan::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 25) qt_static_metacall(this, _c, _id, _a); _id -= 25; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 25) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 25; } return _id; } QT_END_MOC_NAMESPACE
[ "seafrog1984@hotmail.com" ]
seafrog1984@hotmail.com
6c066d2472f545af70d537e258ef6686b65f0e3f
4fd97ff64e457d41820348aebaea704ca4abc48b
/src/plugins/legacy/medBinaryOperation/itkXorOperator.h
138258d7c6ebebc17288259958d098ed4ab5f580
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Florent2305/medInria-public
c075b2064b2fe96081197ce300777be5be18a339
595a2ce62c8864c4ecb8acbf0d50e32aa734ed8f
refs/heads/master
2023-08-08T00:41:51.671245
2023-04-12T07:46:33
2023-04-12T07:46:33
98,999,842
1
1
BSD-4-Clause
2021-05-31T08:38:28
2017-08-01T12:39:01
C++
UTF-8
C++
false
false
758
h
#pragma once /*========================================================================= medInria Copyright (c) INRIA 2013 - 2020. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include "medBinaryOperatorBase.h" #include "medBinaryOperationPluginExport.h" class itkXorOperatorPrivate; class MEDBINARYOPERATIONPLUGIN_EXPORT itkXorOperator : public medBinaryOperatorBase { Q_OBJECT public: virtual QString description() const; static bool registered(); }; dtkAbstractProcess *createitkXorOperator();
[ "florent.leray@inria.fr" ]
florent.leray@inria.fr
935427a3a3c32e03a489b48ee1071d38dbc504c7
1720530d0498a97cab209ae13535b9432bd42121
/Algorithm/Weighted_Job_Scheduling.cpp
e08a389ec97b20217dc9975ea4fdf30386b3ede4
[]
no_license
tienhsin/Practice
7f56e13267205648ac2b3f24a535f886f957bdb0
459eba90396b30f22ae358529029e3a879e0b4ef
refs/heads/master
2020-03-24T22:16:03.220620
2018-11-25T02:36:02
2018-11-25T02:36:02
143,076,678
0
0
null
null
null
null
UTF-8
C++
false
false
2,149
cpp
/* * * https://www.geeksforgeeks.org/weighted-job-scheduling/ * */ #include<iostream> #include<vector> #include<algorithm> #include<unordered_map> using namespace std; struct Job{ int start; int end; int val; Job(int s, int e, int v):start(s), end(e), val(v){} }; int findNext(vector<Job> &jobs, int cur){ for(int i=cur-1;i>=0;i--){ if(jobs[i].end <= jobs[cur].start) return i; } return -1; } //Time: O(n*2^n) int findMaxProfitRec(vector<Job> &jobs, int cur){ if(cur==0) return jobs[0].val; int next = findNext(jobs, cur); int incVal = jobs[cur].val; if(next!=-1) incVal += findMaxProfitRec(jobs, next); int exclVal = findMaxProfitRec(jobs, cur-1); return max(exclVal, incVal); } unordered_map<int, int> mem; //Time: ? int findMaxProfitMem(vector<Job> &jobs, int cur){ if(cur==0) return jobs[0].val; if(mem.count(cur)) return mem[cur]; int next = findNext(jobs, cur); int incVal = jobs[cur].val; if(next!=-1) incVal += findMaxProfitRec(jobs, next); int exclVal = findMaxProfitRec(jobs, cur-1); mem[cur] = max(exclVal, incVal); return mem[cur]; } int findMaxProfit(vector<Job> jobs){ sort(jobs.begin(), jobs.end(), [](Job &a, Job &b){ return a.end < b.end; }); int n=jobs.size()-1; return findMaxProfitMem(jobs, n); } int findMaxProfitDP(vector<Job> jobs){ sort(jobs.begin(), jobs.end(), [](Job &a, Job &b){ return a.end < b.end; }); int n=jobs.size(); vector<int> table(n,0); table[0]=jobs[0].val; for(int i=1;i<n;i++){ int incVal = jobs[i].val; int next = findNext(jobs,i-1); if(next!=-1) incVal+=table[next]; int exclVal = table[i-1]; table[i] = max(exclVal, incVal); } int res = table[n-1]; return res; } int main() { Job j1(3, 10, 20), j2(1, 2, 5), j3(6, 19, 100), j4(2, 100, 200); vector<Job> jobs{j1,j2,j3,j4}; cout << "The optimal profit is " << findMaxProfitDP(jobs) << endl; }
[ "anit528839911@gmail.com" ]
anit528839911@gmail.com
cf486b8bf7b7b899c4449ee1363981ed651b58c4
3c3c4db33b13a86f86f2efdb70020b2e8396b11f
/render/util/color_map.cpp
7e3eeddaec8b0b2cc428c3ff48f7b33c58f9c145
[ "MIT" ]
permissive
all-in-one-of/openMaelstrom
38327f51a6379639cfa11a44c1dc071cc21712bc
4e293eccecf9991135890c72e54e5b41dde297d7
refs/heads/master
2020-07-08T19:34:52.933890
2019-08-24T08:24:50
2019-08-24T08:24:50
203,757,810
0
0
MIT
2019-08-22T09:11:23
2019-08-22T09:11:21
null
UTF-8
C++
false
false
4,212
cpp
#include <QImage> #include <iostream> #include <render/util/color_map.h> #include <utility/helpers/log.h> #include <utility/identifier/uniform.h> GLuint colorMap::create1DTexture(QVector4D *colorMap, int32_t elements) { GLuint textureId_; // generate the specified number of texture objects glGenTextures(1, &textureId_); // assert(glGetError() == GL_NO_ERROR); // bind texture glBindTexture(GL_TEXTURE_1D, textureId_); // assert(glGetError() == GL_NO_ERROR); // tells OpenGL how the data that is going to be uploaded is aligned glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // assert(glGetError() == GL_NO_ERROR); glTexImage1D( GL_TEXTURE_1D, // Specifies the target texture. Must be GL_TEXTURE_1D or GL_PROXY_TEXTURE_1D. 0, // Specifies the level-of-detail number. Level 0 is the base image level. Level n is the // nth mipmap reduction image. GL_RGBA32F, elements, 0, // border: This value must be 0. GL_RGBA, GL_FLOAT, colorMap); // assert(glGetError() == GL_NO_ERROR); // texture sampling/filtering operation. glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // assert(glGetError() == GL_NO_ERROR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // assert(glGetError() == GL_NO_ERROR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // assert(glGetError() == GL_NO_ERROR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // assert(glGetError() == GL_NO_ERROR); glBindTexture(GL_TEXTURE_1D, 0); // assert(glGetError() == GL_NO_ERROR); return textureId_; } #include <utility/helpers/pathfinder.h> void colorMap::update() { static std::string old_colormap = ""; static size_t old_size = 0; if (old_colormap != get<parameters::render_colormap>()) { old_colormap = get<parameters::render_colormap>(); std::string file_name = resolveFile(std::string("cfg/") + get<parameters::render_colormap>() + ".png").string(); //std::string file_name = root_folder + get<parameters::render_colormap>() + ".png"; QImage img(1024, 1, QImage::Format_RGB32); //std::cout << file_name << " exists: " << fs::exists(file_name) << std::endl; for (int32_t it = 0; it < img.width(); ++it) img.setPixel(QPoint(it, 0), qRgb((float)it / (float)img.width() * 256.f, (float)it / (float)img.width() * 256.f, (float)it / (float)img.width() * 256.f)); if (std::experimental::filesystem::exists(file_name)) img.load(QString(file_name.c_str())); color_map = (QVector4D *)realloc(color_map, sizeof(QVector4D) * (img.width() + 1)); for (int32_t it = 0; it < img.width(); ++it) { QRgb col = img.pixel(QPoint(it, 0)); color_map[it] = QVector4D{(float)qRed(col) / 256.f, (float)qGreen(col) / 256.f, (float)qBlue(col) / 256.f, 1.f}; if(it == img.width()-1) color_map[it + 1] = QVector4D{ (float)qRed(col) / 256.f, (float)qGreen(col) / 256.f, (float)qBlue(col) / 256.f, 1.f }; } color_map_elements = img.width(); texunit = create1DTexture(color_map, color_map_elements); for (auto b : bindings) { auto [prog, texture_id, identifier] = b; prog->bind(); GLuint samplerLocation = prog->uniformLocation(identifier.c_str()); glUniform1i(samplerLocation, texture_id); glActiveTexture(GL_TEXTURE0 + texture_id); glBindTexture(GL_TEXTURE_1D, texunit); prog->release(); } old_size = bindings.size(); } else if (bindings.size() != old_size) { for (auto b : bindings) { auto [prog, texture_id, identifier] = b; prog->bind(); GLuint samplerLocation = prog->uniformLocation(identifier.c_str()); glUniform1i(samplerLocation, texture_id); glActiveTexture(GL_TEXTURE0 + texture_id); glBindTexture(GL_TEXTURE_1D, texunit); prog->release(); } old_size = bindings.size(); } } void colorMap::bind(QOpenGLShaderProgram *prog, GLint texture_id, std::string id) { bindings.emplace_back(prog, texture_id, id); } colorMap &colorMap::instance() { static colorMap inst; return inst; }
[ "rene.winchenbach@gmail.com" ]
rene.winchenbach@gmail.com
8450506b9662ef7a5fe793d106bfca12cbb7b665
19048fa3c92b3a01209de30023afd9e82f19284d
/洛谷/5019.cpp
71df2c1610e5766f1ac26a12f936b2ba209456bb
[]
no_license
fblogy/code
b73d1172f4e58f9ecbe1ffbcac925070cbd10881
ae8bded0caced69d0248bfcbd2396d6aa745820a
refs/heads/master
2020-03-25T16:53:03.864473
2019-07-01T07:57:31
2019-07-01T07:57:31
134,960,799
0
0
null
null
null
null
UTF-8
C++
false
false
1,148
cpp
#include<bits/stdc++.h> using namespace std; #define fi first #define se second #define mp make_pair #define pb push_back #define rep(i, a, b) for(int i=(a); i<(b); i++) #define per(i, a, b) for(int i=(b)-1; i>=(a); i--) #define sz(a) (int)a.size() #define de(a) cout << #a << " = " << a << endl #define dd(a) cout << #a << " = " << a << " " #define all(a) a.begin(), a.end() #define pw(x) (1ll<<(x)) #define endl "\n" typedef double db; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef vector<int> vi; const int P = 1e9 + 7; int add(int a, int b) {if((a += b) >= P) a -= P; return a;} int sub(int a, int b) {if((a -= b) < 0) a += P; return a;} int mul(int a, int b) {return 1ll * a * b % P;} int kpow(int a, int b) {int r=1;for(;b;b>>=1,a=mul(a,a)) {if(b&1)r=mul(r,a);}return r;} //---- const int N = 1e5 + 7; int n, a[N], ans; int main() { freopen("a.in","r",stdin); std::ios::sync_with_stdio(false); std::cin.tie(0); //cout << setiosflags(ios::fixed); //cout << setprecision(2); cin >> n; rep(i, 1, n+1) { cin >> a[i]; if (a[i] > a[i-1]) ans += a[i] - a[i-1]; } cout << ans; return 0; }
[ "39649744+fblogy@users.noreply.github.com" ]
39649744+fblogy@users.noreply.github.com
60921e65b3ccd75df36647520e28053511ce6fcb
5f7828acca6224ab84309f7457aa21a9ca3f8f94
/ticTacToe.cpp
98c6b24edc59e5312f045347ffefa424f4d4f688
[]
no_license
shivanandpradhan/Tic-tac-toe
e00f59cf8b60e349ea9ff2b28481b488b06125a9
de1208dad8173a9f9a00598fd655180cca4c7cfa
refs/heads/master
2023-03-17T08:57:08.162917
2021-03-03T10:02:16
2021-03-03T10:02:16
344,076,579
0
0
null
null
null
null
UTF-8
C++
false
false
8,162
cpp
// Tic Toc game......... #include<windows.h> #include<bits/stdc++.h> using namespace std; // this is for adding color... void Color(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } // creating a row box void createRowBox(char arr[], int i, int pos){ // this condition is for coloring the box where player has currently enter his value 'X' or 'O' if ((arr[i] == 'X' || arr[i] == 'O') && (i == pos)) { Color(78); // 78 signifies a background color of red. cout<<" "<<arr[i]<<" |"; Color(30); } // this condition is for coloring the box where player has previously enter his value 'X' or 'O' else if (arr[i] == 'X' || arr[i] == 'O') cout<<" "<<arr[i]<<" |"; // other than this leave an empty box. else cout<<" |"; } // creating a board of tic-toe on each turn of players void createBoard(char arr[],int pos){ cout<<"\n\t"; // top design of board with background as blue Color(30); cout<<"----------------------------------------------"<<endl; Color(2); for(int i = 0; i < 9; i+=3){ // run when the position is same as i // this condition is for coloring the box where player has currently enter his value 'X' or 'O' cout<<"\t"; Color(30); cout<<"|"; createRowBox(arr, i, pos); createRowBox(arr, i+1, pos); createRowBox(arr, i+2, pos); Color(2); cout<<"\n\t"; Color(30); cout<<"----------------------------------------------"<<endl; Color(2); } cout<<endl; Color(2); } // helper function for building row of Winner's Board void winnerHighliterRow( char arr[], int i, int l, int m, int n){ // this condition is for printing the pattern of winner's // if i match l, m or n, then color the background differently. if ((arr[i] == 'X' || arr[i] == 'O') && (i == l || i == m || i == n)){ Color(30); cout<<" "<<arr[i]<<" |"; Color(224); } // just print the value else if (arr[i] == 'X' || arr[i] == 'O'){ cout<<" "<<arr[i]<<" |"; } // empty box else{ cout<<" |"; } } // this function is again for printing the board for the winner // that will tell why winner is winning. // means represent the pattern he is forming. (with the help of background color) void winningHighliter(char arr[], int l, int m, int n){ cout<<"\n\t"; // top design of board with background as blue Color(224); cout<<"----------------------------------------------"<<endl; Color(2); for(int i = 0; i < 9; i+=3){ cout<<"\t"; Color(224); cout<<"|"; winnerHighliterRow(arr, i, l, m, n); winnerHighliterRow(arr, i+1, l, m, n); winnerHighliterRow(arr, i+2, l, m, n); Color(2); cout<<"\n\t"; Color(224); cout<<"----------------------------------------------"<<endl; Color(2); } cout<<endl; Color(2); } // this condition is used for checking the winner. // return the index of winning array which satisfies the condition of winning. int checkWinner(int w_arr[][3], char arr[]){ for (int i = 0; i < 8; i++){ if (arr[w_arr[i][0]] == arr[w_arr[i][1]] && arr[w_arr[i][1]] == arr[w_arr[i][2]]) return i; } return -1; } // main function int main(){ // winning array will contain all possible pos of winning int winning_array[][3] = { { 0, 1 , 2} , {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0,4,8}, {2,4,6} }; cout<<"\n---******----******--- Tic Tac Toe ---*******---******-----"<<endl; cout<<endl<<endl; int firstWin = 0, secondWin = 0; // get the names of first and second player. string fst, sec, currentWinner = fst; cout<<" Enter first Player Name : "; cin >> fst; cout<<endl; cout<<" Enter second Player Name : "; cin >> sec;cout<<endl; string choice; do{ // array of 9 number will represent the board for tic toe game. char arr[] = {'1','2','3','4','5','6','7','8', '9'}; cout<<"\n---------------------------------------------------------------------------------------------\n\n"; // display the empty board. cout<<"\n Empty Board for playing Tic Tac Toe Game"<<endl<<endl; // background blue; cout<<"\t"; Color(30); cout<<"--------------------------------------------"<<endl; Color(2); for(int i = 0; i < 9; i+=3){ cout<<"\t"; Color(30); cout<<"| "<<arr[i]<<" | "<<arr[i+1]<<" | "<<arr[i+2]<<" |"<<endl; Color(2); cout<<"\t"; Color(30); cout<<"--------------------------------------------"<<endl; Color(2); } cout<<endl; // setting the color to green. Color(2); bool first, second; (currentWinner == fst) ? second = true, first = false : first = true, second = false; // position variable int pos; int operation = 0; //run loop until any user wins. while (true){ // run on turn of first user. if (first) { do{ cout<<"\n\t Active Player - First : "<<fst<<endl<<endl; cout<<" Enter Position(1 - 9) where you want to write \'X\' : "; cin >> pos; cout<<endl; if (arr[pos-1] == 'X' || arr[pos-1] == 'O') cout<<"\n\tDon't Enter a Position where already is \'X\' or \'O\'"<<endl<<endl; }while(arr[pos-1] == 'X' || arr[pos-1] == 'O'); // if arr[pos-1] is not equals to 'x' then go and replace it with 'X' arr[pos-1] = 'X'; // now first user turn is over. // give the turn to second. first = false; second = true; } // run on second user's turn. else{ do{ cout<<"\n\t Active Player - Second : "<<sec<<endl<<endl; cout<<" Enter Position(1 - 9) where you want to write \'X\' : "; cin >> pos; cout<<endl; if (arr[pos-1] == 'X' || arr[pos-1] == 'O') cout<<"\n\tDon't Enter a Position where already is \'X\' or \'O\'"<<endl<<endl; } while(arr[pos-1] == 'X' || arr[pos-1] == 'O'); // if arr[pos-1] is not equals to 'O' then go and replace it with 'O' arr[pos-1] = 'O'; // now second user turn is over. // give the turn to first. second = false; first = true; } //increment the operation. // because we want to run this loop until all possible moves are over. operation++; // printing the board for the user with his move. cout<<endl<<" Now Board looks like :- "<<endl<<endl; createBoard(arr, pos-1); // check the winner. int chk_winner = checkWinner(winning_array, arr); // if this is not equals to -1 means there is some winner // where chk_winner represent the index of winning_array // means containing the possible moves due to which the user wins. if (chk_winner != -1){ // printing the Winner cout<<"\n ------*******---------- ******---------*******---------- ******--------"<<endl; cout<<"\n\t WINNER OF GAME => "; (first) ? currentWinner = sec : currentWinner = fst; cout<<currentWinner; cout<<endl; // increment the winning total of first and second user (first) ? secondWin++ : firstWin++; // display the winning times of first and second. cout<<"\n\t"<<fst<<" wins : "<< firstWin; cout<<"\t"<<sec <<" wins : "<<secondWin<<endl; cout<<"\n ------*******---------- ******---------*******---------- ******--------"<<endl; cout<<"\n\n\tWinner's Board :- "<<endl<<endl; // printing the board by highlighting the winning board. // means representing all moves that make the user to win the game. winningHighliter(arr, winning_array[chk_winner][0], winning_array[chk_winner][1], winning_array[chk_winner][2]); // now we found user so break the game of tic toe game. break; } // if operation is greater than 8 then all possible move is over. // so print the match is draw // and break the loop. if (operation > 8){ cout<<"Match Drawn"<<endl; break; } } cout<<"\n Do you want to Play Again (Type \"no\" for exit):- "; cin >> choice; cout<<endl; } while (choice != "no"); return 0; }
[ "shivanandpradhan0@gmail.com" ]
shivanandpradhan0@gmail.com
0e1f1bb43da3cf4bf43dd3f803eb3373f292d89c
9aff59f0a07411def77a7a8dfb292d8d19ec9c72
/Code/qt/net/server/TcpServer.h
ff3628675868785e6534db298767e472c30b17de
[]
no_license
mathieukapfer/sandbox
a676e3616c439e9b953227531ba2f10045cd4bb5
2c468c454a59ff38f82376cf3e0c83e1bada828d
refs/heads/master
2021-01-16T19:02:52.471713
2019-06-28T09:51:41
2019-06-28T09:51:41
27,293,078
0
0
null
null
null
null
UTF-8
C++
false
false
359
h
#ifndef TCPSERVER_H #define TCPSERVER_H #include <QtCore/QObject> class QTcpServer; class TcpServer: public QObject { Q_OBJECT public: TcpServer(); virtual ~TcpServer(); void listen(); bool isListening(); private slots: void echo(); private: QTcpServer *_tcpServer; char _buf[1024]; }; #endif /* TCPSERVER_H */
[ "mathieu.kapfer@non.schneider-electric.com" ]
mathieu.kapfer@non.schneider-electric.com
dc7f6872de2c460e98a76338a3eede043f94f42a
b0d59137a18166e48f95c1b5dd7ce2531fba470d
/submission3/restaurant/restaurant.h
097096325b312666bc12f902b2c124be06e1fbcb
[]
no_license
irfanmim/SleepNotFound
025f31479e4ea6029b7f7bbc3796bba4526dc391
38776015561dd8abfcc4460f352e7046ff1f4edb
refs/heads/master
2021-01-19T04:02:17.916204
2017-03-15T21:18:32
2017-03-15T21:18:32
84,420,948
0
0
null
null
null
null
UTF-8
C++
false
false
390
h
#ifndef RESTAURANT_H #define RESTAURANT_H #include "../facility/facility.h" /** @class Restaurant * Real class restaurant */ class Restaurant: public Facility{ public: /** @brief Constructor. * @param x absis lokasi * @param y oridnat lokasi * Konstruktor kelas restaurant */ Restaurant(int x,int y); /** @brief Method render. */ void Render(); }; #endif
[ "radioirfan@gmail.com" ]
radioirfan@gmail.com
c270979a9ef93775dbd269d796eefce55374b59d
cea82f8c7bfdbee74b28e6372c3a40bbdf6bccf1
/tests/libgoldmine/quotesourceclient_test.cpp
a9c485417617a2492ee71f321d4fc0b4a88f1707
[]
no_license
asakul/libgoldmine
5de94469efd30f9f2a357d6c5d621d3578106984
69e498c02f7bb63d65bb8eb34422c8c3d96c7e22
refs/heads/master
2020-04-06T03:33:58.198160
2016-09-16T14:32:25
2016-09-16T14:32:25
56,564,310
0
0
null
null
null
null
UTF-8
C++
false
false
1,210
cpp
#include "catch.hpp" #include "quotesource/quotesourceclient.h" #include "goldmine/data.h" #include "quotesource/quotesource.h" #include <boost/thread.hpp> using namespace goldmine; using namespace cppio; class TickSink : public QuoteSourceClient::Sink { public: virtual ~TickSink() { } void incomingTick(const std::string& ticker, const Tick& tick) override { ticks.push_back(std::make_pair(ticker, tick)); } std::vector<std::pair<std::string, Tick>> ticks; }; TEST_CASE("QuotesourceClient", "[quotesourceclient]") { auto manager = std::shared_ptr<IoLineManager>(createLineManager()); QuoteSourceClient client(manager, "inproc://quotesource"); auto sink = std::make_shared<TickSink>(); client.registerSink(sink); QuoteSource source(manager, "inproc://quotesource"); source.start(); client.startStream("t:FOO"); boost::this_thread::sleep_for(boost::chrono::milliseconds(100)); Tick tick; tick.timestamp = 12; tick.useconds = 0; tick.datatype = (int)Datatype::Price; tick.value = decimal_fixed(42, 0); tick.volume = 100; source.incomingTick("FOO", tick); client.stop(); source.stop(); REQUIRE(sink->ticks.size() == 1); REQUIRE(sink->ticks.front().second == tick); }
[ "denis@kasan.ws" ]
denis@kasan.ws
796e1b00ab3d7c0ad7b5e4050e94845909064e9f
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
/sstd_boost/sstd/libs/hana/test/tuple/special.fold_left.cpp
cf50618a653b5b2d727aeaf887d6ff4d6669f0c1
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
KqSMea8/sstd_library
9e4e622e1b01bed5de7322c2682539400d13dd58
0fcb815f50d538517e70a788914da7fbbe786ce1
refs/heads/master
2020-05-03T21:07:01.650034
2019-04-01T00:10:47
2019-04-01T00:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,318
cpp
// Copyright Louis Dionne 2013-2017 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #include <sstd/boost/hana/assert.hpp> #include <sstd/boost/hana/equal.hpp> #include <sstd/boost/hana/fold_left.hpp> #include <sstd/boost/hana/tuple.hpp> #include <sstd/boost/hana/type.hpp> namespace hana = boost::hana; template <typename ...> struct F { struct type; }; struct x0; struct x1; struct x2; struct x3; int main() { // tuple_t and initial state { auto f = hana::metafunction<F>; auto s = hana::type_c<struct initial_state>; BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::fold_left(hana::tuple_t<>, s, f), s )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::fold_left(hana::tuple_t<x0>, s, f), f(s, hana::type_c<x0>) )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::fold_left(hana::tuple_t<x0, x1>, s, f), f(f(s, hana::type_c<x0>), hana::type_c<x1>) )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::fold_left(hana::tuple_t<x0, x1, x2>, s, f), f(f(f(s, hana::type_c<x0>), hana::type_c<x1>), hana::type_c<x2>) )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::fold_left(hana::tuple_t<x0, x1, x2, x3>, s, f), f(f(f(f(s, hana::type_c<x0>), hana::type_c<x1>), hana::type_c<x2>), hana::type_c<x3>) )); } // tuple_t and no initial state { auto f = hana::metafunction<F>; BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::fold_left(hana::tuple_t<x0>, f), hana::type_c<x0> )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::fold_left(hana::tuple_t<x0, x1>, f), f(hana::type_c<x0>, hana::type_c<x1>) )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::fold_left(hana::tuple_t<x0, x1, x2>, f), f(f(hana::type_c<x0>, hana::type_c<x1>), hana::type_c<x2>) )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::fold_left(hana::tuple_t<x0, x1, x2, x3>, f), f(f(f(hana::type_c<x0>, hana::type_c<x1>), hana::type_c<x2>), hana::type_c<x3>) )); } }
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
0a650e2bf480bb50bb5b126887f676edb9d7a608
aabfbd4f6c940aa7c75195bd60d19a551fce3822
/summer_school_private/anymal_research/robot_utils/include/robot_utils/force_calibrators/ForceCalibratorBase.hpp
df6027d3369f5dcd39973b405c7a63d7c33fb732
[]
no_license
daoran/eth_supermegabot
9c5753507be243fc15133c9dfb1d0a5d4ff1d496
52b82300718c91344f41b4e11bbcf892d961af4b
refs/heads/master
2020-07-28T13:42:08.906212
2019-12-04T16:51:42
2019-12-04T16:51:42
209,428,875
1
1
null
2019-09-19T00:36:33
2019-09-19T00:36:33
null
UTF-8
C++
false
false
2,109
hpp
/* * ForceCalibratorBase.hpp * * Created on: Jan 31, 2017 * Author: Christian Gehring */ #pragma once #include <kindr/Core> #include <boost/thread.hpp> #include <string> #include <robot_utils/force_calibrators/ForceCalibratorCommand.hpp> #include <robot_utils/force_calibrators/ForceCalibratorStats.hpp> namespace robot_utils { class ForceCalibratorBase { public: ForceCalibratorBase(const std::string& name); virtual ~ForceCalibratorBase() = default; virtual bool store(const std::string& filename) = 0; virtual bool load(const std::string& filename) = 0; virtual bool isCalibrating() = 0; virtual bool startCalibration(bool wait = false) = 0; virtual bool wait() = 0; virtual bool initialize(double dt) = 0; virtual bool advance(double dt) = 0; virtual bool command(ForceCalibratorCommand& command) = 0; virtual bool getCalibratedForce(kindr::Force3D& calibratedForce, const kindr::Force3D& uncalibratedForce) = 0; virtual bool getCalibratedTorque(kindr::Torque3D& calibratedTorque, const kindr::Torque3D& uncalibratedTorque) = 0; virtual bool getCalibratedWrench(kindr::WrenchD& calibratedWrench, const kindr::WrenchD& uncalibratedWrench) { bool success = getCalibratedForce(calibratedWrench.getForce(), uncalibratedWrench.getForce()); success &= getCalibratedTorque(calibratedWrench.getTorque(), uncalibratedWrench.getTorque()); return success; } virtual void getStatistics(ForceCalibratorStats& statistics) = 0; const std::string& getName() const { return name_; } void setWrench(const kindr::WrenchD& wrench) { boost::unique_lock<boost::shared_mutex> lock{mutexWrench_}; wrench_ = wrench; } void setForce(const kindr::Force3D& force) { boost::unique_lock<boost::shared_mutex> lock{mutexWrench_}; wrench_.setForce(force); } void setTorque(const kindr::Torque3D& torque) { boost::unique_lock<boost::shared_mutex> lock{mutexWrench_}; wrench_.setTorque(torque); } protected: std::string name_; kindr::WrenchD wrench_; boost::shared_mutex mutexWrench_; }; } /* namespace robot_utils */
[ "hlin@ethz.ch" ]
hlin@ethz.ch
a6acff28413f0bf259266f235b12708cf57b531d
64058e1019497fbaf0f9cbfab9de4979d130416b
/c++/include/serial/impl/variant.inl
212aafd1c2da6301bdc18858f4361b4876d64c2b
[ "MIT" ]
permissive
OpenHero/gblastn
31e52f3a49e4d898719e9229434fe42cc3daf475
1f931d5910150f44e8ceab81599428027703c879
refs/heads/master
2022-10-26T04:21:35.123871
2022-10-20T02:41:06
2022-10-20T02:41:06
12,407,707
38
21
null
2020-12-08T07:14:32
2013-08-27T14:06:00
C++
UTF-8
C++
false
false
5,052
inl
#if defined(VARIANT__HPP) && !defined(VARIANT__INL) #define VARIANT__INL /* $Id: variant.inl 282780 2011-05-16 16:02:27Z gouriano $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Eugene Vasilchenko * * File Description: * !!! PUT YOUR DESCRIPTION HERE !!! */ inline const CChoiceTypeInfo* CVariantInfo::GetChoiceType(void) const { return m_ChoiceType; } inline CVariantInfo::EVariantType CVariantInfo::GetVariantType(void) const { return m_VariantType; } inline CVariantInfo* CVariantInfo::SetNoPrefix(void) { GetId().SetNoPrefix(); return this; } inline CVariantInfo* CVariantInfo::SetNotag(void) { GetId().SetNotag(); return this; } inline CVariantInfo* CVariantInfo::SetCompressed(void) { GetId().SetCompressed(); return this; } inline CVariantInfo* CVariantInfo::SetNsQualified(bool qualified) { GetId().SetNsQualified(qualified); return this; } inline bool CVariantInfo::IsInline(void) const { return GetVariantType() == eInlineVariant; } inline bool CVariantInfo::IsNonObjectPointer(void) const { return GetVariantType() == eNonObjectPointerVariant; } inline bool CVariantInfo::IsObjectPointer(void) const { return GetVariantType() == eObjectPointerVariant; } inline bool CVariantInfo::IsSubClass(void) const { return GetVariantType() == eSubClassVariant; } inline bool CVariantInfo::IsNotPointer(void) const { return (GetVariantType() & ePointerFlag) == 0; } inline bool CVariantInfo::IsPointer(void) const { return (GetVariantType() & ePointerFlag) != 0; } inline bool CVariantInfo::IsNotObject(void) const { return (GetVariantType() & eObjectFlag) == 0; } inline bool CVariantInfo::IsObject(void) const { return (GetVariantType() & eObjectFlag) != 0; } inline bool CVariantInfo::CanBeDelayed(void) const { return m_DelayOffset != eNoOffset; } inline CDelayBuffer& CVariantInfo::GetDelayBuffer(TObjectPtr object) const { return CTypeConverter<CDelayBuffer>::Get(CRawPointer::Add(object, m_DelayOffset)); } inline const CDelayBuffer& CVariantInfo::GetDelayBuffer(TConstObjectPtr object) const { return CTypeConverter<const CDelayBuffer>::Get(CRawPointer::Add(object, m_DelayOffset)); } inline TConstObjectPtr CVariantInfo::GetVariantPtr(TConstObjectPtr choicePtr) const { return m_GetConstFunction(this, choicePtr); } inline TObjectPtr CVariantInfo::GetVariantPtr(TObjectPtr choicePtr) const { return m_GetFunction(this, choicePtr); } inline void CVariantInfo::ReadVariant(CObjectIStream& stream, TObjectPtr choicePtr) const { m_ReadHookData.GetCurrentFunction()(stream, this, choicePtr); } inline void CVariantInfo::WriteVariant(CObjectOStream& stream, TConstObjectPtr choicePtr) const { m_WriteHookData.GetCurrentFunction()(stream, this, choicePtr); } inline void CVariantInfo::SkipVariant(CObjectIStream& stream) const { m_SkipHookData.GetCurrentFunction()(stream, this); } inline void CVariantInfo::CopyVariant(CObjectStreamCopier& stream) const { m_CopyHookData.GetCurrentFunction()(stream, this); } inline void CVariantInfo::DefaultReadVariant(CObjectIStream& stream, TObjectPtr choicePtr) const { m_ReadHookData.GetDefaultFunction()(stream, this, choicePtr); } inline void CVariantInfo::DefaultWriteVariant(CObjectOStream& stream, TConstObjectPtr choicePtr) const { m_WriteHookData.GetDefaultFunction()(stream, this, choicePtr); } inline void CVariantInfo::DefaultSkipVariant(CObjectIStream& stream) const { m_SkipHookData.GetDefaultFunction()(stream, this); } inline void CVariantInfo::DefaultCopyVariant(CObjectStreamCopier& stream) const { m_CopyHookData.GetDefaultFunction()(stream, this); } #endif /* def VARIANT__HPP && ndef VARIANT__INL */
[ "zhao.kaiyong@gmail.com" ]
zhao.kaiyong@gmail.com
e05870bacd08e7fa86c51843651a1d427d153fe7
302af8b2d0be567fe57b1e19d7393c5835d03e0f
/zerojudge/a053/a053.cpp
707a53003874bd61df4db51d2e56d448860f6fb3
[]
no_license
smallhand/codePractice
c2dec2222ceb9497f27018e19805d0604387cc3d
8dd7007fa9b2f145a5ab5d7f54a73441a9c64e1a
refs/heads/master
2021-01-15T15:32:34.316923
2019-04-29T03:30:47
2019-04-29T03:30:47
65,838,360
0
0
null
null
null
null
UTF-8
C++
false
false
296
cpp
#include <iostream> using namespace std; int main() { int a,b; while(cin>>a) { if(a<11) b=a*6; else if(a<21) b=60+(a-10)*2; else if(a<41) b=80+(a-20); else b=100; cout<<b<<endl; } return 0; }
[ "pc00083@gmail.com" ]
pc00083@gmail.com
95c740d652da150f5c5ccee589c6983b17c4e849
e82245a9e623ef3e2b4b9c02f0fd932c608c4484
/hackerrank.com/002-5t3v3nc4p1t41m4n4g3m3nt.cpp
c0ee21ce3f9139a6f08cb8adc5681e201dce5660
[]
no_license
Zylophone/Programming-for-Sport
33e8161028cfddce3b7a1243eb092070107342e3
193d6184f939303d8661f68d6fd06bdec95df351
refs/heads/master
2020-06-16T23:11:44.719286
2017-05-21T17:10:46
2017-05-21T17:10:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,098
cpp
// code may not work #include <vector> #include <iostream> #include <algorithm> using namespace std; struct Order { Order( int _price, int _size, char _dir ) : price(_price), size(_size), dir( _dir) {} int price; int size; char dir; }; int getClearingPrice( const std::vector< Order >& orders ) { std::vector< Order > buy_orders; std::vector< Order > sell_orders; for (Order order : orders) { if (order.dir == 'B') { buy_orders.push_back (order); } else if (order.dir == 'S') { sell_orders.push_back (order); } } // sort buy_orders by desc price std::sort(buy_orders.begin(), buy_orders.end(), [] (Order const& o1, Order const& o2) { return o1.price > o2.price; }); // sort sell_orders by asc price std::sort(sell_orders.begin(), sell_orders.end(), [] (Order const& o1, Order const& o2) { return o1.price < o2.price; }); // while someone is willing to // buy at a higher price than // someone else is willing to sell, // trade on // since we're looking for the minimum // clearing pice, always trade at the sell price if (buy_orders.size() == 0 || sell_orders.size() == 0) { return 0; } int b = 0; int s = 0; int units_traded = 0; int price_of_last_trade; Order buy_order = buy_orders[b]; Order sell_order = sell_orders[s]; while (b < buy_orders.size() && s < sell_orders.size()) { buy_order = buy_orders[b]; sell_order = sell_orders[s]; if (!(buy_order.price >= sell_order.price)) { break; } // trade the maximum number of units possible if (buy_order.size > sell_order.size) { // the entire sell order is filled units_traded = sell_order.size; s += 1; } else if (buy_order.size == sell_order.size) { // both orders are filled units_traded = sell_order.size; b += 1; s += 1; } else { // the entire buy order is filled units_traded = buy_order.size; b += 1; } buy_order.size -= units_traded; sell_order.size -= units_traded; price_of_last_trade = sell_order.price; } return price_of_last_trade; } int main() { std::vector< Order > orders; Order a(1,400,'B'); orders.push_back( a ); // Order b(2,300,'B'); // orders.push_back( b ); // Order c(3,200,'B'); // orders.push_back( c ); // Order d(4,100,'B'); // orders.push_back( d ); // Order e(5,0,'B'); // orders.push_back( e ); // Order f(5,400,'S'); // orders.push_back( f ); // Order g(4,300,'S'); // orders.push_back( g ); // Order h(3,200,'S'); // orders.push_back( h ); // Order i(2,100,'S'); // orders.push_back( i ); Order j(1,0,'S'); orders.push_back( j ); getClearingPrice( orders ); return 0; }
[ "jfv33@cornell.edu" ]
jfv33@cornell.edu
0e494403eee422cefa1c6bc332ea25c718c8d8ce
461234ac6487de86880efc6ffb1b7ec484e8bb6d
/src/tree/BinTree.cpp
70ac85d7106fa1e9fe17e28116e65eac65ac71e6
[ "MIT" ]
permissive
LeaveYeah/Sniffles
350bc478be7568369ef9789eb0e8b25d28a6912f
d3380a53842b71e8adad02143c454ea63e62a0cf
refs/heads/master
2020-06-12T14:39:18.960107
2020-01-21T09:21:17
2020-01-21T09:21:17
194,332,628
0
0
MIT
2019-06-28T20:52:13
2019-06-28T20:52:12
null
UTF-8
C++
false
false
4,838
cpp
/* * BinTree.cpp * * Created on: Sep 3, 2015 * Author: fsedlaze */ #include "BinTree.h" void BinTree::find(int item, tree_node **par, tree_node **loc) { tree_node *ptr, *ptrsave; if (root == NULL) { *loc = NULL; *par = NULL; return; } if (item == root->key) { *loc = root; *par = NULL; return; } if (item < root->key) { ptr = root->left; } else { ptr = root->right; } ptrsave = root; while (ptr != NULL) { if (item == ptr->key) { *loc = ptr; *par = ptrsave; return; } ptrsave = ptr; if (item < ptr->key) { ptr = ptr->left; } else { ptr = ptr->right; } } *loc = NULL; *par = ptrsave; } /* * Inserting Element into the Tree */ void BinTree::insert(tree_node *tree, int value) { if (root == NULL) { root = new tree_node; root->key = value; root->num = 1; root->left = NULL; root->right = NULL; std::cout << "Root tree_node is Added" << std::endl; return; } if (tree->key > value) { if (tree->left != NULL) { insert(tree->left, value); } else { tree->left = new tree_node; tree->left->key = value; tree->left->num = 1; (tree->left)->left = NULL; (tree->left)->right = NULL; std::cout << "tree_node Added To Left" << std::endl; return; } } else if (tree->key < value) { if (tree->right != NULL) { insert(tree->right, value); } else { tree->right = new tree_node; tree->right->key = value; tree->right->num = 1; (tree->right)->left = NULL; (tree->right)->right = NULL; std::cout << "tree_node Added To Right" << std::endl; return; } } else { // found element -> already exist! tree->num++; } } /* * Delete Element from the tree */ void BinTree::del(int key) { tree_node *parent, *location; if (root == NULL) { std::cout << "Tree empty" << std::endl; return; } find(key, &parent, &location); if (location == NULL) { std::cout << "Item not present in tree" << std::endl; return; } if (location->left == NULL && location->right == NULL) { case_a(parent, location); } if (location->left != NULL && location->right == NULL) { case_b(parent, location); } if (location->left == NULL && location->right != NULL) { case_b(parent, location); } if (location->left != NULL && location->right != NULL) { case_c(parent, location); } delete location; } /* * Case A */ void BinTree::case_a(tree_node *par, tree_node *loc) { if (par == NULL) { root = NULL; } else { if (loc == par->left) { par->left = NULL; } else { par->right = NULL; } } } /* * Case B */ void BinTree::case_b(tree_node *par, tree_node *loc) { tree_node *child; if (loc->left != NULL) { child = loc->left; } else { child = loc->right; } if (par == NULL) { root = child; } else { if (loc == par->left) { par->left = child; } else { par->right = child; } } } /* * Case C */ void BinTree::case_c(tree_node *par, tree_node *loc) { tree_node *ptr, *ptrsave, *suc, *parsuc; ptrsave = loc; ptr = loc->right; while (ptr->left != NULL) { ptrsave = ptr; ptr = ptr->left; } suc = ptr; parsuc = ptrsave; if (suc->left == NULL && suc->right == NULL) { case_a(parsuc, suc); } else { case_b(parsuc, suc); } if (par == NULL) { root = suc; } else { if (loc == par->left) { par->left = suc; } else { par->right = suc; } } suc->left = loc->left; suc->right = loc->right; } void BinTree::get_nodes(tree_node *ptr, std::vector<int> & nodes) { std::cout<<"get_nodes"<<std::endl; if (root == NULL) { std::cout << "Tree is empty" << std::endl; return; } if (ptr != NULL) { nodes.push_back(ptr->key); get_nodes(ptr->left,nodes); get_nodes(ptr->right,nodes); } } /* * Pre Order Traversal */ void BinTree::preorder(tree_node *ptr) { if (root == NULL) { std::cout << "Tree is empty" << std::endl; return; } if (ptr != NULL) { std::cout << ptr->key << " "; preorder(ptr->left); preorder(ptr->right); } } /* * In Order Traversal */ void BinTree::inorder(tree_node *ptr) { if (root == NULL) { std::cout << "Tree is empty" << std::endl; return; } if (ptr != NULL) { inorder(ptr->left); std::cout << ptr->key << " "; inorder(ptr->right); } } /* * Postorder Traversal */ void BinTree::postorder(tree_node *ptr) { if (root == NULL) { std::cout << "Tree is empty" << std::endl; return; } if (ptr != NULL) { postorder(ptr->left); postorder(ptr->right); std::cout << ptr->key << " "; } } /* * Display Tree Structure */ void BinTree::display(tree_node *ptr, int level) { int i; if (ptr != NULL) { display(ptr->right, level + 1); std::cout << std::endl; if (ptr == root) std::cout << "Root->: "; else { for (i = 0; i < level; i++) { std::cout << " "; } } std::cout << ptr->key; display(ptr->left, level + 1); } }
[ "fritz.sedlazeck@gmail.com" ]
fritz.sedlazeck@gmail.com
283713c40160f3dfaab835e369c8a9c5787dc9cd
4e94595b26a5f352497a01ef77d0c7a0f727b304
/Uva 11045/Uva 11045.cpp
5c25b3252d282dd5e1c4d1410190c422837e2e05
[]
no_license
Kimbbakar/Uva-Solutions
a14cfc4fedd2b2b768f124254d10141ed1b0c5cd
773cac3a26be894f256e7793cf77facc2c996830
refs/heads/master
2020-03-10T01:04:10.090798
2018-07-14T17:20:21
2018-07-14T17:20:21
129,099,615
1
0
null
null
null
null
UTF-8
C++
false
false
5,927
cpp
/* Problem name : Algorithm : Not Sure Yet Contest/Practice : Source : Comment : Whenever you start to believe yourself, people also start to believe in you Date : -- Last Update : 25-Mar-2015 */ #include<bits/stdc++.h> #define pause system("pause"); #define FOR(s,e,inc) for(int i=s;i<=e;i+=inc) #define mod 1000000007 #define UNIQUE(V) (V).erase(unique((V).begin(),(V).end()),(V).end())//vector must be sorted #define inf 1<<30 #define pb push_back #define ppb pop_back #define mp make_pair #define F first #define S second #define sz(x) ((int)x.size()) #define sqr(x) ( (x)* (x) ) #define eps 1e-9 #define lcm(x,y) (abs(x) /gcd(x,y))* abs(y) #define on(x,w) x|(1<<w) #define check(x,w) (x&(1<<w)) #define all(x) (x).begin(),(x).end() #define pf printf #define sf scanf #define pi acos(-1.0) #define reset(x,v) memset(x,v,sizeof(x)); #define AND && #define OR || #define what_is(x) cerr<<#x<<" is "<<x<<"\n"; typedef long long ll; typedef unsigned long long llu; using namespace std; template<class T> inline T mod_v(T num) { if(num>=0) return num%mod; else return (num%mod+mod)%mod; } template<class T> inline T gcd(T a,T b) { a=abs(a); b=abs(b); while(b) b ^= a ^= b ^= a %= b; return a; } template<class T> T fast_pow(T n , T p) { if(p==0) return 1; if(p%2) { T g=mod_v ( mod_v(n) * mod_v(fast_pow(n,p-1)) ); return g; } else { T g=fast_pow(n,p/2); g=mod_v( mod_v(g) * mod_v(g) ) ; return g; } } template<class T> inline T modInverse(T n) { return fast_pow(n,mod-2); } bool equalTo ( double a, double b ){ if ( fabs ( a - b ) <= eps ) return true; else return false; } bool notEqual ( double a, double b ){if ( fabs ( a - b ) > eps ) return true; else return false; } bool lessThan ( double a, double b ){ if ( a + eps < b ) return true; else return false; } bool lessThanEqual ( double a, double b ){if ( a < b + eps ) return true; else return false;} bool greaterThan ( double a, double b ){if ( a > b + eps ) return true;else return false;} bool greaterThanEqual ( double a, double b ){if ( a + eps > b ) return true;else return false;} #define debug(args...) {dbg,args; cerr<<endl;} struct debugger{ template<typename T> debugger& operator , (const T& v){ cerr<<v<<" "; return *this; } }dbg; int NextInt() { int n; scanf("%d", &n); return n; } long long NextLong() { long long n; scanf("%lld", &n); return n; } void print(int n){ printf("%d", n); } void println(int n){ printf("%d\n", n); } void println(long long n){ printf("%lld\n", n); } template<class T> inline int in(register T& num) { cin>>num; return 0; /* register char c=0; num=0; bool n=false; while(c<33)c=getchar(); while(c>33){ if(c=='-') n=true; else num=num*10+c-'0'; c=getchar(); } num=n?-num:num; return 1;*/ } /******* ! Code start from here ! *******/ /* max flow (dinitz algorithm) works on undirected graph can have loops, multiple edges, cycles */ #define MAXN 50 #define MAXE 200 #define SET(x) reset(x,-1) int src, snk, nNode, nEdge; int Q[MAXN], fin[MAXN], pro[MAXN], dist[MAXN]; int flow[MAXE], cap[MAXE], Next[MAXE], to[MAXE]; inline void init(int _src, int _snk, int _n) { src = _src, snk = _snk, nNode = _n, nEdge = 0; SET(fin); } inline void add(int u, int v, int _cap) { to[nEdge] = v, cap[nEdge] = _cap, flow[nEdge] = 0; Next[nEdge] = fin[u], fin[u] = nEdge++; to[nEdge] = u, cap[nEdge] = _cap, flow[nEdge] = 0; Next[nEdge] = fin[v], fin[v] = nEdge++; } bool bfs() { int st, en, i, u, v; SET(dist); dist[src] = st = en = 0; Q[en++] = src; while(st < en) { u = Q[st++]; for(i=fin[u]; i>=0; i=Next[i]) { v = to[i]; if(flow[i] < cap[i] && dist[v]==-1) { dist[v] = dist[u]+1; Q[en++] = v; } } } return dist[snk]!=-1; } int dfs(int u, int fl) { if(u==snk) return fl; for(int &e=pro[u], v, df; e>=0; e=Next[e]) { v = to[e]; if(flow[e] < cap[e] && dist[v]==dist[u]+1) { df = dfs(v, min(cap[e]-flow[e], fl)); if(df>0) { flow[e] += df; flow[e^1] -= df; return df; } } } return 0; } #define i64 int #define INF inf i64 dinitz() { i64 ret = 0; int df; while(bfs()) { for(int i=1; i<=nNode; i++) pro[i] = fin[i]; while(true) { df = dfs(src, INF); if(df) ret += (i64)df; else break; } } return ret; } int Maps(string s){ int v ; if( "XXL"==s) v = 2; else if("XL"==s) v = 3; else if("L"==s) v = 4; else if("M"==s) v = 5; else if("S"==s) v = 6; else if("XS"==s) v = 7; return v; } int main() { std::ios_base::sync_with_stdio(false); #ifdef kimbbakar freopen ( "E:/Code/in.txt", "r", stdin ); // freopen ( "E:/Code/out.txt", "w", stdout ); #endif int t,tcase=1; in(t); int n,m; string s; while(t--){ in(n),in(m); init(1,6+m+2, 6+m+2); n/=6; for(int i=8;i<8+m;i++) { // edge between tshirt and participant in(s); add(Maps(s),i,1); in(s); add(Maps(s),i,1); // edge between participant and sink add(i,8+m,1); } // edge between source and tshirt for(int i=2;i<=7;i++) add(1,i,n); cout<<(dinitz()>=m?"YES":"NO" )<<"\n"; } return 0; }
[ "chowdhuryosman04@gmail.com" ]
chowdhuryosman04@gmail.com
f99c57634eb64ea4323684fdb9624f1b4107bdb5
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_BTD_Fjordhawk_CarryingLoot_parameters.hpp
aa35f84c33037b3a18941a0df71d568ffdc514ea
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
1,073
hpp
#pragma once // ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_BTD_Fjordhawk_CarryingLoot_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function BTD_Fjordhawk_CarryingLoot.BTD_Fjordhawk_CarryingLoot_C.ReceiveConditionCheck struct UBTD_Fjordhawk_CarryingLoot_C_ReceiveConditionCheck_Params { class AActor** OwnerActor; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function BTD_Fjordhawk_CarryingLoot.BTD_Fjordhawk_CarryingLoot_C.ExecuteUbergraph_BTD_Fjordhawk_CarryingLoot struct UBTD_Fjordhawk_CarryingLoot_C_ExecuteUbergraph_BTD_Fjordhawk_CarryingLoot_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
597fb18184fa41551f932d97d90b4bdd4ee1fb70
6f2086fcc71c0decc3740b1055337b7eea6dcad3
/CodeforcesContests/CF_661_Div3/problemC.cpp
2862ea7fb061d05f0f3fdcccc1f5833c7ac0403e
[]
no_license
sanyamsinghal/ContestSolutions
24bd1635c62a256e81af28176b94a6567df0e0a4
ef2f1814d0bf46db8d75df6814fda5124324b608
refs/heads/master
2022-12-22T18:34:09.186967
2020-10-03T16:11:02
2020-10-03T16:11:02
279,047,684
1
0
null
null
null
null
UTF-8
C++
false
false
2,276
cpp
/* User:- sanyam */ #include <bits/stdc++.h> using namespace std; #define ip(x) \ ll x; \ cin >> x; #define op(x) cout << x; #define pb push_back #define mp make_pair #define ll long long int #define mod 1000000007 #define w(t) \ int t; \ cin >> t while (t--) #define triplet pair<int, pair<int, int>> #define vi vector<int> #define vll vector<ll> #define pi pair<int, int> #define pll pair<ll, ll> #define fastIO \ ios_base::sync_with_stdio(0); \ cin.tie(0); \ cout.tie(0); #define loop(i, k, n) for (ll i = k; i <= n; i++) #define loop2(i, k, n) for (ll i = k; i >= n; i--) #define init_arr(i, val) memset(i, val, sizeof(val)) #define sort_cut(x) (x).begin(), (x).end() /* #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> */ const ll inf = 1e18; const int N = 100001; void take_fileIO() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif return; } void printVector(vector<ll> &v) { for (ll x : v) cout << x << " "; cout << endl; } /* ---------------------Code-------------------- */ void solve() { ll n; cin >> n; vector<ll> arr(n); for (int i = 0; i < n; i++) cin >> arr[i]; set<ll> s; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { s.insert(arr[i] + arr[j]); } } sort(sort_cut(arr)); ll ans = 0; for (ll val : s) { ll low = 0, high = n - 1; ll curr = 0; while (low < high) { ll sum = arr[low] + arr[high]; if (sum == val) { curr++; low++; high--; } else if (sum < val) low++; else high--; } ans = max(ans, curr); } cout << ans << endl; } int main() { fastIO; take_fileIO(); int t; cin >> t; while (t--) { solve(); } return 0; }
[ "noreply@github.com" ]
sanyamsinghal.noreply@github.com
5a0522c3a1594d7be793ad043590d6a96af0d564
faf5c2db3fda903f16a1959edb9bc75134386274
/Problems/Segment Trees/HackerEarth/Vasya vs Rhezo.cpp
83f4fbc12d607bb9f7a2dc777f16930bd9d5c2e4
[]
no_license
nakshatra-bazukaa/cp
d703c206eadee52b73b67788f1ff650d8cd4e448
691090429d0a5aa93e40594339f52b968e22cb82
refs/heads/master
2023-04-23T04:42:22.880715
2021-05-01T14:15:56
2021-05-01T14:15:56
287,983,820
1
1
null
2020-10-01T17:52:07
2020-08-16T16:40:54
C++
UTF-8
C++
false
false
4,922
cpp
#include<bits/stdc++.h> using namespace std; #define IO ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); #define ll long long #define loop(n) for(ll i = 0; i < n; ++i) #define ff(i,j,n,m) for(ll i = 0; i < n; ++i) for(ll j = 0; j < m; ++j) #define f(i,s,e) for(ll i = s; i < e; ++i) #define fin(i,s,e) for(ll i = s; i <= e; ++i) #define r(i,s,e) for(ll i = e; i >= s; i--) #define pl pair<ll,ll> #define pcl pair<char,ll> #define vc vector<char> #define pi pair<int,int> #define vi vector<int> #define vpi vector<pi> #define vl vector<ll> #define vs vector<string> #define vpl vector<pl> #define vpcl vector<pcl> #define all(v) v.begin(), v.end() #define rev(v) reverse(all(v)) #define minE(v) *min_element(all(v)) #define maxE(v) *max_element(all(v)) #define mp make_pair #define uml unordered_map<ll,ll> #define umsl unordered_map<string,ll> #define umcl unordered_map<char,ll> #define oml map<ll,ll> #define maxpq priority_queue<ll> #define desc greater<ll>() #define minpq priority_queue<ll,vl,desc> #define F first #define S second #define endl "\n" #define mod 1000000007 #define precision(i) cout<<fixed; cout<<setprecision(i); #define gcd(a,b) __gcd(a,b) #define lcm(a,b) (a/(__gcd(a,b)))*b bool prime[1000001]; void sieve(){ prime[0] = false; prime[1] = false; for(ll i=2; i*i <= 1000000; i++) if(prime[i] == true) for(ll j = i*i; j <= 1000000; j += i) prime[j] = false; } bool isPrime(ll n){ if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (ll i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true; } inline bool isCoPrime(ll a, ll b){ return (__gcd(a, b) == 1) ? (true) : (false); } inline bool isPowerOfTwo (ll x){ return (x && (!(x&(x-1)))) ? (true) : (false); } void printDivisors(ll n){ fin(i, 1, sqrt(n)) if (n%i == 0) (n/i == i) ? (cout<<i<<endl) : (cout<<i<<' '<<n/i<<endl); } void printPrimeFactors(ll n){ while(n%2 == 0){ cout<<2<<endl; n /= 2; } for(ll i = 3; i <= sqrt(n); i += 2) while(n%i == 0){ cout<<i<<endl; n /= i; } if(n > 2) cout<<n<<endl; } void c_p_p(){ #ifndef ONLINE_JUDGE freopen("i.txt", "r", stdin); freopen("o.txt", "w", stdout); #endif } class Node{ public: int index, A, B; Node(){ A = 0; B = 0; index = 0; } }; void buildTree(int *A, int *B, Node *tree, int start, int end, int currNode){ if(start == end){ tree[currNode].A = A[start]; tree[currNode].B = B[start]; tree[currNode].index = start; return; } int mid = (start+end)/2; buildTree(A, B, tree, start, mid, 2*currNode); buildTree(A, B, tree, mid+1, end, 2*currNode+1); if(tree[2*currNode].A == tree[2*currNode+1].A){ if(tree[2*currNode].B < tree[2*currNode+1].B){ tree[currNode].A = tree[2*currNode].A; tree[currNode].B = tree[2*currNode].B; tree[currNode].index = tree[2*currNode].index; } else{ tree[currNode].A = tree[2*currNode+1].A; tree[currNode].B = tree[2*currNode+1].B; tree[currNode].index = tree[2*currNode+1].index; } } else if(tree[2*currNode].A > tree[2*currNode+1].A){ tree[currNode].A = tree[2*currNode].A; tree[currNode].B = tree[2*currNode].B; tree[currNode].index = tree[2*currNode].index; } else{ tree[currNode].A = tree[2*currNode+1].A; tree[currNode].B = tree[2*currNode+1].B; tree[currNode].index = tree[2*currNode+1].index; } } Node query(Node *tree, int start, int end, int currNode, int left, int right){ // Completly outside given range Node node; if(start>right || end<left) return node; // Completly inside given range if(start>=left && end<=right){ return tree[currNode]; } // Partially inside and partially outside int mid = (start+end)/2; Node ans1 = query(tree, start, mid, 2*currNode, left, right); Node ans2 = query(tree, mid+1, end, 2*currNode+1, left, right); if(ans1.A == ans2.A){ if(ans1.B < ans2.B){ return ans1; } else{ return ans2; } } else if(ans1.A > ans2.A){ return ans1; } else{ return ans2; } } void solve(int t){ int n; cin>>n; int *A = new int[n](); int *B = new int[n](); f(i, 0, n) cin>>A[i]; f(i, 0, n) cin>>B[i]; Node *tree = new Node[4*n](); buildTree(A, B, tree, 0, n-1, 1); int q; cin>>q; loop(q){ int x, y; cin>>x>>y; cout<<query(tree, 0, n-1, 1, x-1, y-1).index+1<<endl; } } int main(){ c_p_p(); // memset(prime, true, sizeof(prime)); // sieve(); IO int t = 1; // cin>>t; fin(i, 1, t) solve(i); return 0; }
[ "nakshatravasugupta@gmail.com" ]
nakshatravasugupta@gmail.com
522a9b86986f7ade789911d2a3e99c88e527667d
18df702758fa034d30f7e3573e9a986a93b5ba88
/app/aiserver/src/vendor/filter/eptz/RTNodeVFilterEptzDemo.h
84ed833633835149a2f59604f495d04c8b408ba1
[]
no_license
qiaoweibiao/merged
e8eedb87c73f12436fb26b8058ea295fc3e703c0
3b016b1330c2a148753d00c542aaa39e7f86e726
refs/heads/master
2023-08-25T01:53:59.791416
2021-10-25T19:22:50
2021-10-25T19:22:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,584
h
/* * Copyright 2020 Rockchip Electronics Co. LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef SRC_RT_TASK_TASK_NODE_FILTER_RTNODEVFILTEREPTZDEMO_H_ #define SRC_RT_TASK_TASK_NODE_FILTER_RTNODEVFILTEREPTZDEMO_H_ #include "rockit/RTTaskNode.h" #include "rockit/RTMediaRockx.h" #include "rockit/RTAIDetectResults.h" #include "eptz_algorithm.h" class RTNodeVFilterEptz : public RTTaskNode { public: RTNodeVFilterEptz(); virtual ~RTNodeVFilterEptz(); virtual RT_RET open(RTTaskNodeContext *context); virtual RT_RET process(RTTaskNodeContext *context); virtual RT_RET close(RTTaskNodeContext *context); private: RTRect mRoiRegion; INT32 mSrcWidth; INT32 mSrcHeight; INT32 mEptzWidth; INT32 mEptzHeight; float mClipRatio; INT32 mClipWidth; INT32 mClipHeight; INT32 mLastXY[4]; INT32 mTempXY[4]; EptzInitInfo mEptzInfo; }; #endif // SRC_RT_TASK_TASK_NODE_FILTER_RTNODEVFILTEREPTZDEMO_H_
[ "geierconstantinabc@gmail.com" ]
geierconstantinabc@gmail.com
de12962b86e28a8736456ab3506524265b588d32
4dfa6232cf91f1c04d50809915078dc71fb371b4
/dnn/src/x86/gaussian_blur/filter.h
1c2d5fc8ab179fc99dcb8429f1081a91f2797535
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
hookex/MegEngine
81c0539a3247873bdabe0e6f22e265e22249e98a
47fd33880d2db3cae98c55911bb29328cdd5d7e4
refs/heads/master
2022-08-01T02:04:06.431689
2020-05-22T11:10:17
2020-05-22T11:10:17
250,200,281
1
0
NOASSERTION
2020-03-26T08:22:39
2020-03-26T08:22:39
null
UTF-8
C++
false
false
42,516
h
/** * By downloading, copying, installing or using the software you agree to this license. * If you do not agree to this license, do not download, install, * copy or use the software. * * * License Agreement * For Open Source Computer Vision Library * (3-clause BSD License) * * Copyright (C) 2000-2020, Intel Corporation, all rights reserved. * Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. * Copyright (C) 2009-2016, NVIDIA Corporation, all rights reserved. * Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. * Copyright (C) 2015-2016, OpenCV Foundation, all rights reserved. * Copyright (C) 2015-2016, Itseez Inc., all rights reserved. * Copyright (C) 2019-2020, Xperience AI, all rights reserved. * Third party copyrights are property of their respective owners. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * 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 the 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 copyright holders 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. * * --------------------------------------------------------------------------- * \file dnn/src/x86/gaussian_blur/filter.h * * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2020 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * This file has been modified by Megvii ("Megvii Modifications"). * All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. * * --------------------------------------------------------------------------- */ #include "src/common/cv/filter.h" #include <cfloat> #include <cmath> #include <pmmintrin.h> #include <smmintrin.h> namespace megdnn { namespace megcv { namespace gaussian_blur { using namespace filter_common; struct RowVec_8u32s { RowVec_8u32s() {} RowVec_8u32s( const uchar * _kernel, int _len) { ksize = _len; kernel = (int*)_kernel; } MEGDNN_ATTRIBUTE_TARGET("sse2") int operator()(const uchar* _src, uchar* _dst, int width, int cn) const { int i = 0, k, _ksize = ksize; int* dst = (int*)_dst; const int * _kx = kernel; width *= cn; for( ; i <= width - 16; i += 16 ) { const uchar* src = _src + i; __m128i f, z = _mm_setzero_si128(), s0 = z, s1 = z, s2 = z, s3 = z; __m128i x0, x1, x2, x3; for( k = 0; k < _ksize; k++, src += cn ) { f = _mm_cvtsi32_si128(_kx[k]); f = _mm_shuffle_epi32(f, 0); f = _mm_packs_epi32(f, f); x0 = _mm_loadu_si128((const __m128i*)src); x2 = _mm_unpackhi_epi8(x0, z); x0 = _mm_unpacklo_epi8(x0, z); x1 = _mm_mulhi_epi16(x0, f); x3 = _mm_mulhi_epi16(x2, f); x0 = _mm_mullo_epi16(x0, f); x2 = _mm_mullo_epi16(x2, f); s0 = _mm_add_epi32(s0, _mm_unpacklo_epi16(x0, x1)); s1 = _mm_add_epi32(s1, _mm_unpackhi_epi16(x0, x1)); s2 = _mm_add_epi32(s2, _mm_unpacklo_epi16(x2, x3)); s3 = _mm_add_epi32(s3, _mm_unpackhi_epi16(x2, x3)); } _mm_store_si128((__m128i*)(dst + i), s0); _mm_store_si128((__m128i*)(dst + i + 4), s1); _mm_store_si128((__m128i*)(dst + i + 8), s2); _mm_store_si128((__m128i*)(dst + i + 12), s3); } for( ; i <= width - 4; i += 4 ) { const uchar* src = _src + i; __m128i f, z = _mm_setzero_si128(), s0 = z, x0, x1; for( k = 0; k < _ksize; k++, src += cn ) { f = _mm_cvtsi32_si128(_kx[k]); f = _mm_shuffle_epi32(f, 0); f = _mm_packs_epi32(f, f); x0 = _mm_cvtsi32_si128(*(const int*)src); x0 = _mm_unpacklo_epi8(x0, z); x1 = _mm_mulhi_epi16(x0, f); x0 = _mm_mullo_epi16(x0, f); s0 = _mm_add_epi32(s0, _mm_unpacklo_epi16(x0, x1)); } _mm_store_si128((__m128i*)(dst + i), s0); } return i; } int * kernel; size_t ksize; }; struct SymmRowSmallVec_8u32s { SymmRowSmallVec_8u32s() {} SymmRowSmallVec_8u32s( const uchar * _kernel, int _len) { kernel = (int *)_kernel; ksize = _len; } MEGDNN_ATTRIBUTE_TARGET("sse2") int operator()(const uchar* src, uchar* _dst, int width, int cn) const { int i = 0, j, k, _ksize = ksize; int* dst = (int*)_dst; const int * kx = kernel + _ksize/2; src += (_ksize/2)*cn; width *= cn; __m128i z = _mm_setzero_si128(); { if( _ksize == 1 ) return 0; if( _ksize == 3 ) { __m128i k0 = _mm_shuffle_epi32(_mm_cvtsi32_si128(kx[0]), 0), k1 = _mm_shuffle_epi32(_mm_cvtsi32_si128(kx[1]), 0); k0 = _mm_packs_epi32(k0, k0); k1 = _mm_packs_epi32(k1, k1); for( ; i <= width - 16; i += 16, src += 16 ) { __m128i x0, x1, x2, y0, y1, t0, t1, z0, z1, z2, z3; x0 = _mm_loadu_si128((__m128i*)(src - cn)); x1 = _mm_loadu_si128((__m128i*)src); x2 = _mm_loadu_si128((__m128i*)(src + cn)); y0 = _mm_add_epi16(_mm_unpackhi_epi8(x0, z), _mm_unpackhi_epi8(x2, z)); x0 = _mm_add_epi16(_mm_unpacklo_epi8(x0, z), _mm_unpacklo_epi8(x2, z)); y1 = _mm_unpackhi_epi8(x1, z); x1 = _mm_unpacklo_epi8(x1, z); t1 = _mm_mulhi_epi16(x1, k0); t0 = _mm_mullo_epi16(x1, k0); x2 = _mm_mulhi_epi16(x0, k1); x0 = _mm_mullo_epi16(x0, k1); z0 = _mm_unpacklo_epi16(t0, t1); z1 = _mm_unpackhi_epi16(t0, t1); z0 = _mm_add_epi32(z0, _mm_unpacklo_epi16(x0, x2)); z1 = _mm_add_epi32(z1, _mm_unpackhi_epi16(x0, x2)); t1 = _mm_mulhi_epi16(y1, k0); t0 = _mm_mullo_epi16(y1, k0); y1 = _mm_mulhi_epi16(y0, k1); y0 = _mm_mullo_epi16(y0, k1); z2 = _mm_unpacklo_epi16(t0, t1); z3 = _mm_unpackhi_epi16(t0, t1); z2 = _mm_add_epi32(z2, _mm_unpacklo_epi16(y0, y1)); z3 = _mm_add_epi32(z3, _mm_unpackhi_epi16(y0, y1)); _mm_store_si128((__m128i*)(dst + i), z0); _mm_store_si128((__m128i*)(dst + i + 4), z1); _mm_store_si128((__m128i*)(dst + i + 8), z2); _mm_store_si128((__m128i*)(dst + i + 12), z3); } } else if( _ksize == 5 ) { __m128i k0 = _mm_shuffle_epi32(_mm_cvtsi32_si128(kx[0]), 0), k1 = _mm_shuffle_epi32(_mm_cvtsi32_si128(kx[1]), 0), k2 = _mm_shuffle_epi32(_mm_cvtsi32_si128(kx[2]), 0); k0 = _mm_packs_epi32(k0, k0); k1 = _mm_packs_epi32(k1, k1); k2 = _mm_packs_epi32(k2, k2); for( ; i <= width - 16; i += 16, src += 16 ) { __m128i x0, x1, x2, y0, y1, t0, t1, z0, z1, z2, z3; x0 = _mm_loadu_si128((__m128i*)(src - cn)); x1 = _mm_loadu_si128((__m128i*)src); x2 = _mm_loadu_si128((__m128i*)(src + cn)); y0 = _mm_add_epi16(_mm_unpackhi_epi8(x0, z), _mm_unpackhi_epi8(x2, z)); x0 = _mm_add_epi16(_mm_unpacklo_epi8(x0, z), _mm_unpacklo_epi8(x2, z)); y1 = _mm_unpackhi_epi8(x1, z); x1 = _mm_unpacklo_epi8(x1, z); t1 = _mm_mulhi_epi16(x1, k0); t0 = _mm_mullo_epi16(x1, k0); x2 = _mm_mulhi_epi16(x0, k1); x0 = _mm_mullo_epi16(x0, k1); z0 = _mm_unpacklo_epi16(t0, t1); z1 = _mm_unpackhi_epi16(t0, t1); z0 = _mm_add_epi32(z0, _mm_unpacklo_epi16(x0, x2)); z1 = _mm_add_epi32(z1, _mm_unpackhi_epi16(x0, x2)); t1 = _mm_mulhi_epi16(y1, k0); t0 = _mm_mullo_epi16(y1, k0); y1 = _mm_mulhi_epi16(y0, k1); y0 = _mm_mullo_epi16(y0, k1); z2 = _mm_unpacklo_epi16(t0, t1); z3 = _mm_unpackhi_epi16(t0, t1); z2 = _mm_add_epi32(z2, _mm_unpacklo_epi16(y0, y1)); z3 = _mm_add_epi32(z3, _mm_unpackhi_epi16(y0, y1)); x0 = _mm_loadu_si128((__m128i*)(src - cn*2)); x1 = _mm_loadu_si128((__m128i*)(src + cn*2)); y1 = _mm_add_epi16(_mm_unpackhi_epi8(x0, z), _mm_unpackhi_epi8(x1, z)); y0 = _mm_add_epi16(_mm_unpacklo_epi8(x0, z), _mm_unpacklo_epi8(x1, z)); t1 = _mm_mulhi_epi16(y0, k2); t0 = _mm_mullo_epi16(y0, k2); y0 = _mm_mullo_epi16(y1, k2); y1 = _mm_mulhi_epi16(y1, k2); z0 = _mm_add_epi32(z0, _mm_unpacklo_epi16(t0, t1)); z1 = _mm_add_epi32(z1, _mm_unpackhi_epi16(t0, t1)); z2 = _mm_add_epi32(z2, _mm_unpacklo_epi16(y0, y1)); z3 = _mm_add_epi32(z3, _mm_unpackhi_epi16(y0, y1)); _mm_store_si128((__m128i*)(dst + i), z0); _mm_store_si128((__m128i*)(dst + i + 4), z1); _mm_store_si128((__m128i*)(dst + i + 8), z2); _mm_store_si128((__m128i*)(dst + i + 12), z3); } } } src -= (_ksize/2)*cn; kx -= _ksize/2; for( ; i <= width - 4; i += 4, src += 4 ) { __m128i f, s0 = z, x0, x1; for( k = j = 0; k < _ksize; k++, j += cn ) { f = _mm_cvtsi32_si128(kx[k]); f = _mm_shuffle_epi32(f, 0); f = _mm_packs_epi32(f, f); x0 = _mm_cvtsi32_si128(*(const int*)(src + j)); x0 = _mm_unpacklo_epi8(x0, z); x1 = _mm_mulhi_epi16(x0, f); x0 = _mm_mullo_epi16(x0, f); s0 = _mm_add_epi32(s0, _mm_unpacklo_epi16(x0, x1)); } _mm_store_si128((__m128i*)(dst + i), s0); } return i; } int * kernel; size_t ksize; }; struct SymmColumnSmallVec_32s8u { SymmColumnSmallVec_32s8u() {} SymmColumnSmallVec_32s8u(const uchar * _kernel, int _len, int _bits) { ksize = _len; kernel = (float *)malloc(sizeof(float)*ksize); for(size_t i=0; i<ksize; i++) kernel[i] = (float)(((int *)_kernel)[i]) * (1./(1<<_bits)); } SymmColumnSmallVec_32s8u(const SymmColumnSmallVec_32s8u& rhs) { ksize = rhs.ksize; kernel = (float*)malloc(sizeof(float)*ksize); memcpy(kernel, rhs.kernel, sizeof(float)*ksize); } SymmColumnSmallVec_32s8u& operator=(const SymmColumnSmallVec_32s8u& rhs) { ksize = rhs.ksize; kernel = (float*)malloc(sizeof(float)*ksize); memcpy(kernel, rhs.kernel, sizeof(float)*ksize); return *this; } ~SymmColumnSmallVec_32s8u() { free(kernel); } MEGDNN_ATTRIBUTE_TARGET("sse2") int operator()(const uchar** _src, uchar* dst, int & count, int width) const { int ksize2 = (ksize)/2; const float * ky = kernel + ksize2; int i = 0, k; const int ** src = (const int**)_src; const __m128i *S, *S0, *S1, *S2; if(ksize == 3 && count == 4) { __m128 f0 = _mm_load_ss(ky); f0 = _mm_shuffle_ps(f0, f0, 0); __m128 f1 = _mm_load_ss(ky+1); f1 = _mm_shuffle_ps(f1, f1, 0); for( ; i <= width - 16; i += 16 ) { __m128 s00, s01, s02, s03; __m128 s10, s11, s12, s13; __m128 s20, s21, s22, s23; __m128 d00, d01, d02, d03; __m128i d_0, d_1; S0 = (const __m128i*)(src[-1] + i); S1 = (const __m128i*)(src[0] + i); S2 = (const __m128i*)(src[1] + i); s20 = _mm_cvtepi32_ps(_mm_load_si128(S2)); s21 = _mm_cvtepi32_ps(_mm_load_si128(S2+1)); s22 = _mm_cvtepi32_ps(_mm_load_si128(S2+2)); s23 = _mm_cvtepi32_ps(_mm_load_si128(S2+3)); s10 = _mm_cvtepi32_ps(_mm_load_si128(S1)); d00 = _mm_mul_ps(s10, f0); s11 = _mm_cvtepi32_ps(_mm_load_si128(S1+1)); d01 = _mm_mul_ps(s11, f0); s12 = _mm_cvtepi32_ps(_mm_load_si128(S1+2)); d02 = _mm_mul_ps(s12, f0); s13 = _mm_cvtepi32_ps(_mm_load_si128(S1+3)); d03 = _mm_mul_ps(s13, f0); s00 = _mm_cvtepi32_ps(_mm_load_si128(S0)); d00 = _mm_add_ps(d00, _mm_mul_ps(_mm_add_ps(s00, s20), f1)); s01 = _mm_cvtepi32_ps(_mm_load_si128(S0+1)); d01 = _mm_add_ps(d01, _mm_mul_ps(_mm_add_ps(s01, s21), f1)); d_0 = _mm_packs_epi32(_mm_cvtps_epi32(d00), _mm_cvtps_epi32(d01)); s02 = _mm_cvtepi32_ps(_mm_load_si128(S0+2)); d02 = _mm_add_ps(d02, _mm_mul_ps(_mm_add_ps(s02, s22), f1)); s03 = _mm_cvtepi32_ps(_mm_load_si128(S0+3)); d03 = _mm_add_ps(d03, _mm_mul_ps(_mm_add_ps(s03, s23), f1)); d_1 = _mm_packs_epi32(_mm_cvtps_epi32(d02), _mm_cvtps_epi32(d03)); d_0 = _mm_packus_epi16(d_0, d_1); _mm_storeu_si128((__m128i*)(dst + i), d_0); S2 = (const __m128i*)(src[2] + i); s00 = _mm_cvtepi32_ps(_mm_load_si128(S2)); d00 = _mm_mul_ps(s20, f0); d00 = _mm_add_ps(d00, _mm_mul_ps(_mm_add_ps(s00, s10), f1)); s01 = _mm_cvtepi32_ps(_mm_load_si128(S2+1)); d01 = _mm_mul_ps(s21, f0); d01 = _mm_add_ps(d01, _mm_mul_ps(_mm_add_ps(s01, s11), f1)); d_0 = _mm_packs_epi32(_mm_cvtps_epi32(d00), _mm_cvtps_epi32(d01)); s02 = _mm_cvtepi32_ps(_mm_load_si128(S2+2)); d02 = _mm_mul_ps(s22, f0); d02 = _mm_add_ps(d02, _mm_mul_ps(_mm_add_ps(s02, s12), f1)); s03 = _mm_cvtepi32_ps(_mm_load_si128(S2+3)); d03 = _mm_mul_ps(s23, f0); d03 = _mm_add_ps(d03, _mm_mul_ps(_mm_add_ps(s03, s13), f1)); d_1 = _mm_packs_epi32(_mm_cvtps_epi32(d02), _mm_cvtps_epi32(d03)); d_0 = _mm_packus_epi16(d_0, d_1); _mm_storeu_si128((__m128i*)(dst + width + i), d_0); S2 = (const __m128i*)(src[3] + i); s10 = _mm_cvtepi32_ps(_mm_load_si128(S2)); d00 = _mm_mul_ps(s00, f0); d00 = _mm_add_ps(d00, _mm_mul_ps(_mm_add_ps(s20, s10), f1)); s11 = _mm_cvtepi32_ps(_mm_load_si128(S2+1)); d01 = _mm_mul_ps(s01, f0); d01 = _mm_add_ps(d01, _mm_mul_ps(_mm_add_ps(s21, s11), f1)); d_0 = _mm_packs_epi32(_mm_cvtps_epi32(d00), _mm_cvtps_epi32(d01)); s12 = _mm_cvtepi32_ps(_mm_load_si128(S2+2)); d02 = _mm_mul_ps(s02, f0); d02 = _mm_add_ps(d02, _mm_mul_ps(_mm_add_ps(s22, s12), f1)); s13 = _mm_cvtepi32_ps(_mm_load_si128(S2+3)); d03 = _mm_mul_ps(s03, f0); d03 = _mm_add_ps(d03, _mm_mul_ps(_mm_add_ps(s23, s13), f1)); d_1 = _mm_packs_epi32(_mm_cvtps_epi32(d02), _mm_cvtps_epi32(d03)); d_0 = _mm_packus_epi16(d_0, d_1); _mm_storeu_si128((__m128i*)(dst + width*2 + i), d_0); S2 = (const __m128i*)(src[4] + i); s20 = _mm_cvtepi32_ps(_mm_load_si128(S2)); d00 = _mm_mul_ps(s10, f0); d00 = _mm_add_ps(d00, _mm_mul_ps(_mm_add_ps(s00, s20), f1)); s21 = _mm_cvtepi32_ps(_mm_load_si128(S2+1)); d01 = _mm_mul_ps(s11, f0); d01 = _mm_add_ps(d01, _mm_mul_ps(_mm_add_ps(s01, s21), f1)); d_0 = _mm_packs_epi32(_mm_cvtps_epi32(d00), _mm_cvtps_epi32(d01)); s22 = _mm_cvtepi32_ps(_mm_load_si128(S2+2)); d02 = _mm_mul_ps(s12, f0); d02 = _mm_add_ps(d02, _mm_mul_ps(_mm_add_ps(s02, s22), f1)); s23 = _mm_cvtepi32_ps(_mm_load_si128(S2+3)); d03 = _mm_mul_ps(s13, f0); d03 = _mm_add_ps(d03, _mm_mul_ps(_mm_add_ps(s03, s23), f1)); d_1 = _mm_packs_epi32(_mm_cvtps_epi32(d02), _mm_cvtps_epi32(d03)); d_0 = _mm_packus_epi16(d_0, d_1); _mm_storeu_si128((__m128i*)(dst + width*3 + i), d_0); } for( ; i <= width - 4; i += 4 ) { __m128i x0; __m128 s0, s1, s2; __m128 d0, d1; s2 = _mm_cvtepi32_ps(_mm_load_si128((const __m128i*)(src[1] + i))); d1 = _mm_mul_ps(s2, f0); s1 = _mm_cvtepi32_ps(_mm_load_si128((const __m128i*)(src[0] + i))); d0 = _mm_mul_ps(s1, f0); s0 = _mm_cvtepi32_ps(_mm_load_si128((const __m128i*)(src[-1] + i))); d0 = _mm_add_ps(d0, _mm_mul_ps(_mm_add_ps(s0, s2), f1)); x0 = _mm_cvtps_epi32(d0); x0 = _mm_packs_epi32(x0, x0); x0 = _mm_packus_epi16(x0, x0); *(int*)(dst + i) = _mm_cvtsi128_si32(x0); s0 = _mm_cvtepi32_ps(_mm_load_si128((const __m128i*)(src[2] + i))); d0 = _mm_mul_ps(s0, f0); d1 = _mm_add_ps(d1, _mm_mul_ps(_mm_add_ps(s0, s1), f1)); x0 = _mm_cvtps_epi32(d1); x0 = _mm_packs_epi32(x0, x0); x0 = _mm_packus_epi16(x0, x0); *(int*)(dst + width + i) = _mm_cvtsi128_si32(x0); s1 = _mm_cvtepi32_ps(_mm_load_si128((const __m128i*)(src[3] + i))); d1 = _mm_mul_ps(s1, f0); d0 = _mm_add_ps(d0, _mm_mul_ps(_mm_add_ps(s2, s1), f1)); x0 = _mm_cvtps_epi32(d0); x0 = _mm_packs_epi32(x0, x0); x0 = _mm_packus_epi16(x0, x0); *(int*)(dst + width*2 + i) = _mm_cvtsi128_si32(x0); s2 = _mm_cvtepi32_ps(_mm_load_si128((const __m128i*)(src[4] + i))); d1 = _mm_add_ps(d1, _mm_mul_ps(_mm_add_ps(s0, s2), f1)); x0 = _mm_cvtps_epi32(d1); x0 = _mm_packs_epi32(x0, x0); x0 = _mm_packus_epi16(x0, x0); *(int*)(dst + width*3 + i) = _mm_cvtsi128_si32(x0); } float f_0 = *ky; float f_1 = *(ky+1); for( ; i < width; i ++ ) { float s0, s1, s2; float d0, d1; s2 = (float)(*(src[1] + i)); d1 = s2 * f_0; s1 = (float)(*(src[0] + i)); d0 = s1 * f_0; s0 = (float)(*(src[-1] + i)); d0 += (s0 + s2) * f_1; *(dst + i) = (uchar)((int)d0); s0 = (float)(*(src[2] + i)); d0 = s0 * f_0; d1 += (s0 + s1) * f_1; *(dst + width + i) = (uchar)((int)d1); s1 = (float)(*(src[3] + i)); d1 = s1 * f_0; d0 += (s2 + s1) * f_1; *(dst + width*2 + i) = (uchar)((int)d0); s2 = (float)(*(src[4] + i)); d1 += (s0 + s2) * f_1; *(dst + width*3 + i) = (uchar)((int)d1); } count -= 4; } else { for(; count >0 ; count --, src ++, dst += width) { i = 0; __m128 f0 = _mm_load_ss(ky); f0 = _mm_shuffle_ps(f0, f0, 0); for( ; i <= width - 16; i += 16 ) { __m128 s0, s1, s2, s3; __m128i x0, x1; S = (const __m128i*)(src[0] + i); s0 = _mm_cvtepi32_ps(_mm_load_si128(S)); s0 = _mm_mul_ps(s0, f0); s1 = _mm_cvtepi32_ps(_mm_load_si128(S+1)); s1 = _mm_mul_ps(s1, f0); s2 = _mm_cvtepi32_ps(_mm_load_si128(S+2)); s2 = _mm_mul_ps(s2, f0); s3 = _mm_cvtepi32_ps(_mm_load_si128(S+3)); s3 = _mm_mul_ps(s3, f0); for( k = 1; k <= ksize2; k++ ) { S = (const __m128i*)(src[k] + i); S2 = (const __m128i*)(src[-k] + i); __m128 f = _mm_load_ss(ky+k); f = _mm_shuffle_ps(f, f, 0); x0 = _mm_add_epi32(_mm_load_si128(S), _mm_load_si128(S2)); s0 = _mm_add_ps(s0, _mm_mul_ps(_mm_cvtepi32_ps(x0), f)); x1 = _mm_add_epi32(_mm_load_si128(S+1), _mm_load_si128(S2+1)); s1 = _mm_add_ps(s1, _mm_mul_ps(_mm_cvtepi32_ps(x1), f)); x0 = _mm_add_epi32(_mm_load_si128(S+2), _mm_load_si128(S2+2)); s2 = _mm_add_ps(s2, _mm_mul_ps(_mm_cvtepi32_ps(x0), f)); x1 = _mm_add_epi32(_mm_load_si128(S+3), _mm_load_si128(S2+3)); s3 = _mm_add_ps(s3, _mm_mul_ps(_mm_cvtepi32_ps(x1), f)); } x0 = _mm_packs_epi32(_mm_cvtps_epi32(s0), _mm_cvtps_epi32(s1)); x1 = _mm_packs_epi32(_mm_cvtps_epi32(s2), _mm_cvtps_epi32(s3)); x0 = _mm_packus_epi16(x0, x1); _mm_storeu_si128((__m128i*)(dst + i), x0); } for( ; i <= width - 4; i += 4 ) { __m128 f = _mm_load_ss(ky); f = _mm_shuffle_ps(f, f, 0); __m128i x0; __m128 s0 = _mm_cvtepi32_ps(_mm_load_si128((const __m128i*)(src[0] + i))); s0 = _mm_mul_ps(s0, f); for( k = 1; k <= ksize2; k++ ) { S = (const __m128i*)(src[k] + i); S2 = (const __m128i*)(src[-k] + i); f = _mm_load_ss(ky+k); f = _mm_shuffle_ps(f, f, 0); x0 = _mm_add_epi32(_mm_load_si128(S), _mm_load_si128(S2)); s0 = _mm_add_ps(s0, _mm_mul_ps(_mm_cvtepi32_ps(x0), f)); } x0 = _mm_cvtps_epi32(s0); x0 = _mm_packs_epi32(x0, x0); x0 = _mm_packus_epi16(x0, x0); *(int*)(dst + i) = _mm_cvtsi128_si32(x0); } float f_0 = *ky; for( ; i < width; i ++ ) { float d0; d0 = (float)(*(src[0] + i)) * f_0; for( k = 1; k <= ksize2; k++ ) d0 += ((float)(*(src[-k] + i)) + (float)(*(src[k] + i))) * (*(ky + k)); *(dst + i) = (uchar)((int)d0); } } } return i; } float * kernel; size_t ksize; }; struct SymmColumnVec_32s8u { SymmColumnVec_32s8u() {} SymmColumnVec_32s8u(const uchar * _kernel, int _len, int _bits) { ksize = _len; kernel = (float *)malloc(sizeof(float)*ksize); for(size_t i=0; i<ksize; i++) kernel[i] = (float)(((int *)_kernel)[i]) * (1./(1<<_bits)); } SymmColumnVec_32s8u(const SymmColumnVec_32s8u &rhs) { ksize = rhs.ksize; kernel = (float*)malloc(sizeof(float)*ksize); memcpy(kernel, rhs.kernel, sizeof(float)*ksize); } SymmColumnVec_32s8u& operator=(const SymmColumnVec_32s8u& rhs) { ksize = rhs.ksize; kernel = (float*)malloc(sizeof(float)*ksize); memcpy(kernel, rhs.kernel, sizeof(float)*ksize); return *this; } ~SymmColumnVec_32s8u() { free(kernel); } MEGDNN_ATTRIBUTE_TARGET("sse2") int operator()(const uchar** _src, uchar* dst, int & count, int width) const { (void)count; int ksize2 = (ksize)/2; const float * ky = kernel + ksize2; int i = 0, k; const int** src = (const int**)_src; const __m128i *S, *S2; __m128 f0 = _mm_load_ss(ky); f0 = _mm_shuffle_ps(f0, f0, 0); __m128 f; i = 0; for (; i <= width - 16; i += 16) { __m128 s0, s1, s2, s3; __m128i x0, x1; S = (const __m128i*)(src[0] + i); s0 = _mm_cvtepi32_ps(_mm_load_si128(S)); s0 = _mm_mul_ps(s0, f0); s1 = _mm_cvtepi32_ps(_mm_load_si128(S + 1)); s1 = _mm_mul_ps(s1, f0); s2 = _mm_cvtepi32_ps(_mm_load_si128(S + 2)); s2 = _mm_mul_ps(s2, f0); s3 = _mm_cvtepi32_ps(_mm_load_si128(S + 3)); s3 = _mm_mul_ps(s3, f0); for (k = 1; k <= ksize2; k++) { S = (const __m128i*)(src[k] + i); S2 = (const __m128i*)(src[-k] + i); f = _mm_load_ss(ky + k); f = _mm_shuffle_ps(f, f, 0); x0 = _mm_add_epi32(_mm_load_si128(S), _mm_load_si128(S2)); s0 = _mm_add_ps(s0, _mm_mul_ps(_mm_cvtepi32_ps(x0), f)); x1 = _mm_add_epi32(_mm_load_si128(S + 1), _mm_load_si128(S2 + 1)); s1 = _mm_add_ps(s1, _mm_mul_ps(_mm_cvtepi32_ps(x1), f)); x0 = _mm_add_epi32(_mm_load_si128(S + 2), _mm_load_si128(S2 + 2)); s2 = _mm_add_ps(s2, _mm_mul_ps(_mm_cvtepi32_ps(x0), f)); x1 = _mm_add_epi32(_mm_load_si128(S + 3), _mm_load_si128(S2 + 3)); s3 = _mm_add_ps(s3, _mm_mul_ps(_mm_cvtepi32_ps(x1), f)); } x0 = _mm_packs_epi32(_mm_cvtps_epi32(s0), _mm_cvtps_epi32(s1)); x1 = _mm_packs_epi32(_mm_cvtps_epi32(s2), _mm_cvtps_epi32(s3)); x0 = _mm_packus_epi16(x0, x1); _mm_storeu_si128((__m128i*)(dst + i), x0); } for (; i <= width - 4; i += 4) { __m128i x0; __m128 s0 = _mm_cvtepi32_ps( _mm_load_si128((const __m128i*)(src[0] + i))); s0 = _mm_mul_ps(s0, f0); for (k = 1; k <= ksize2; k++) { S = (const __m128i*)(src[k] + i); S2 = (const __m128i*)(src[-k] + i); f = _mm_load_ss(ky + k); f = _mm_shuffle_ps(f, f, 0); x0 = _mm_add_epi32(_mm_load_si128(S), _mm_load_si128(S2)); s0 = _mm_add_ps(s0, _mm_mul_ps(_mm_cvtepi32_ps(x0), f)); } x0 = _mm_cvtps_epi32(s0); x0 = _mm_packs_epi32(x0, x0); x0 = _mm_packus_epi16(x0, x0); *(int*)(dst + i) = _mm_cvtsi128_si32(x0); } return i; } float * kernel; size_t ksize; }; /////////////////////////////////////// 32f ////////////////////////////////// struct RowVec_32f { RowVec_32f() {} RowVec_32f( const uchar * _kernel, int _len) { ksize = _len; kernel = (float*)_kernel; } MEGDNN_ATTRIBUTE_TARGET("sse") int operator()(const uchar* _src, uchar* _dst, int width, int cn) const { int _ksize = ksize; const float* src0 = (const float*)_src; float* dst = (float*)_dst; const float* _kx = kernel; int i = 0, k; width *= cn; for( ; i <= width - 8; i += 8 ) { const float* src = src0 + i; __m128 f, s0 = _mm_setzero_ps(), s1 = s0, x0, x1; for( k = 0; k < _ksize; k++, src += cn ) { f = _mm_load_ss(_kx+k); f = _mm_shuffle_ps(f, f, 0); x0 = _mm_loadu_ps(src); x1 = _mm_loadu_ps(src + 4); s0 = _mm_add_ps(s0, _mm_mul_ps(x0, f)); s1 = _mm_add_ps(s1, _mm_mul_ps(x1, f)); } _mm_store_ps(dst + i, s0); _mm_store_ps(dst + i + 4, s1); } return i; } float * kernel; int ksize; }; struct SymmRowSmallVec_32f { SymmRowSmallVec_32f() {} SymmRowSmallVec_32f( const uchar * _kernel, int _len) { ksize = _len; kernel = (float*)_kernel; } MEGDNN_ATTRIBUTE_TARGET("sse2") int operator()(const uchar* _src, uchar* _dst, int width, int cn) const { int i = 0, _ksize = ksize; float* dst = (float*)_dst; const float* src = (const float*)_src + (_ksize/2)*cn; const float* kx = kernel + _ksize/2; width *= cn; { if( _ksize == 1 ) return 0; if( _ksize == 3 ) { __m128 k0 = _mm_set1_ps(kx[0]), k1 = _mm_set1_ps(kx[1]); for( ; i <= width - 8; i += 8, src += 8 ) { __m128 x0, x1, x2, y0, y1, y2; x0 = _mm_loadu_ps(src - cn); x1 = _mm_loadu_ps(src); x2 = _mm_loadu_ps(src + cn); y0 = _mm_loadu_ps(src - cn + 4); y1 = _mm_loadu_ps(src + 4); y2 = _mm_loadu_ps(src + cn + 4); x0 = _mm_mul_ps(_mm_add_ps(x0, x2), k1); y0 = _mm_mul_ps(_mm_add_ps(y0, y2), k1); x0 = _mm_add_ps(x0, _mm_mul_ps(x1, k0)); y0 = _mm_add_ps(y0, _mm_mul_ps(y1, k0)); _mm_store_ps(dst + i, x0); _mm_store_ps(dst + i + 4, y0); } } else if( _ksize == 5 ) { __m128 k0 = _mm_set1_ps(kx[0]), k1 = _mm_set1_ps(kx[1]), k2 = _mm_set1_ps(kx[2]); for( ; i <= width - 8; i += 8, src += 8 ) { __m128 x0, x1, x2, y0, y1, y2; x0 = _mm_loadu_ps(src - cn); x1 = _mm_loadu_ps(src); x2 = _mm_loadu_ps(src + cn); y0 = _mm_loadu_ps(src - cn + 4); y1 = _mm_loadu_ps(src + 4); y2 = _mm_loadu_ps(src + cn + 4); x0 = _mm_mul_ps(_mm_add_ps(x0, x2), k1); y0 = _mm_mul_ps(_mm_add_ps(y0, y2), k1); x0 = _mm_add_ps(x0, _mm_mul_ps(x1, k0)); y0 = _mm_add_ps(y0, _mm_mul_ps(y1, k0)); x2 = _mm_add_ps(_mm_loadu_ps(src + cn*2), _mm_loadu_ps(src - cn*2)); y2 = _mm_add_ps(_mm_loadu_ps(src + cn*2 + 4), _mm_loadu_ps(src - cn*2 + 4)); x0 = _mm_add_ps(x0, _mm_mul_ps(x2, k2)); y0 = _mm_add_ps(y0, _mm_mul_ps(y2, k2)); _mm_store_ps(dst + i, x0); _mm_store_ps(dst + i + 4, y0); } } } return i; } float * kernel; int ksize; }; struct SymmColumnVec_32f { SymmColumnVec_32f() { } SymmColumnVec_32f(const uchar * _kernel, int _len, int) { ksize = _len; kernel = (float*)_kernel; } MEGDNN_ATTRIBUTE_TARGET("sse2") int operator()(const uchar** _src, uchar* _dst, int &, int width) const { int ksize2 = (ksize)/2; const float* ky = kernel + ksize2; int i = 0, k; const float** src = (const float**)_src; const float *S, *S2; float* dst = (float*)_dst; { for( ; i <= width - 16; i += 16 ) { __m128 f = _mm_load_ss(ky); f = _mm_shuffle_ps(f, f, 0); __m128 s0, s1, s2, s3; __m128 x0, x1; S = src[0] + i; s0 = _mm_load_ps(S); s1 = _mm_load_ps(S+4); s0 = _mm_mul_ps(s0, f); s1 = _mm_mul_ps(s1, f); s2 = _mm_load_ps(S+8); s3 = _mm_load_ps(S+12); s2 = _mm_mul_ps(s2, f); s3 = _mm_mul_ps(s3, f); for( k = 1; k <= ksize2; k++ ) { S = src[k] + i; S2 = src[-k] + i; f = _mm_load_ss(ky+k); f = _mm_shuffle_ps(f, f, 0); x0 = _mm_add_ps(_mm_load_ps(S), _mm_load_ps(S2)); x1 = _mm_add_ps(_mm_load_ps(S+4), _mm_load_ps(S2+4)); s0 = _mm_add_ps(s0, _mm_mul_ps(x0, f)); s1 = _mm_add_ps(s1, _mm_mul_ps(x1, f)); x0 = _mm_add_ps(_mm_load_ps(S+8), _mm_load_ps(S2+8)); x1 = _mm_add_ps(_mm_load_ps(S+12), _mm_load_ps(S2+12)); s2 = _mm_add_ps(s2, _mm_mul_ps(x0, f)); s3 = _mm_add_ps(s3, _mm_mul_ps(x1, f)); } _mm_storeu_ps(dst + i, s0); _mm_storeu_ps(dst + i + 4, s1); _mm_storeu_ps(dst + i + 8, s2); _mm_storeu_ps(dst + i + 12, s3); } for( ; i <= width - 4; i += 4 ) { __m128 f = _mm_load_ss(ky); f = _mm_shuffle_ps(f, f, 0); __m128 x0, s0 = _mm_load_ps(src[0] + i); s0 = _mm_mul_ps(s0, f); for( k = 1; k <= ksize2; k++ ) { f = _mm_load_ss(ky+k); f = _mm_shuffle_ps(f, f, 0); S = src[k] + i; S2 = src[-k] + i; x0 = _mm_add_ps(_mm_load_ps(src[k]+i), _mm_load_ps(src[-k] + i)); s0 = _mm_add_ps(s0, _mm_mul_ps(x0, f)); // for test //s0 += _mm_add_ps(s0, _mm_mul_ps(_mm_load_ps(src[k]+i), f)); //s0 += _mm_add_ps(s0, _mm_mul_ps(_mm_load_ps(src[-k]+i), f)); } _mm_storeu_ps(dst + i, s0); } } return i; } float * kernel; int ksize; }; struct SymmColumnSmallVec_32f { SymmColumnSmallVec_32f() { } SymmColumnSmallVec_32f(const uchar * _kernel, int _len, int) { ksize = _len; kernel = (float*)_kernel; } MEGDNN_ATTRIBUTE_TARGET("sse2") int operator()(const uchar** _src, uchar* _dst, int & count, int width) const { (void)count; int ksize2 = (ksize)/2; const float* ky = kernel + ksize2; int i = 0; const float** src = (const float**)_src; const float *S0 = src[-1], *S1 = src[0], *S2 = src[1]; float* dst = (float*)_dst; if (ky[0] == 2 && ky[1] == 1) { for (; i <= width - 8; i += 8) { __m128 s0, s1, s2, s3, s4, s5; s0 = _mm_load_ps(S0 + i); s1 = _mm_load_ps(S0 + i + 4); s2 = _mm_load_ps(S1 + i); s3 = _mm_load_ps(S1 + i + 4); s4 = _mm_load_ps(S2 + i); s5 = _mm_load_ps(S2 + i + 4); s0 = _mm_add_ps(s0, _mm_add_ps(s4, _mm_add_ps(s2, s2))); s1 = _mm_add_ps(s1, _mm_add_ps(s5, _mm_add_ps(s3, s3))); _mm_storeu_ps(dst + i, s0); _mm_storeu_ps(dst + i + 4, s1); } } else if (ky[0] == -2 && ky[1] == 1) { for (; i <= width - 8; i += 8) { __m128 s0, s1, s2, s3, s4, s5; s0 = _mm_load_ps(S0 + i); s1 = _mm_load_ps(S0 + i + 4); s2 = _mm_load_ps(S1 + i); s3 = _mm_load_ps(S1 + i + 4); s4 = _mm_load_ps(S2 + i); s5 = _mm_load_ps(S2 + i + 4); s0 = _mm_add_ps(s0, _mm_sub_ps(s4, _mm_add_ps(s2, s2))); s1 = _mm_add_ps(s1, _mm_sub_ps(s5, _mm_add_ps(s3, s3))); _mm_storeu_ps(dst + i, s0); _mm_storeu_ps(dst + i + 4, s1); } } else { __m128 k0 = _mm_set1_ps(ky[0]), k1 = _mm_set1_ps(ky[1]); for (; i <= width - 8; i += 8) { __m128 s0, s1, x0, x1; s0 = _mm_load_ps(S1 + i); s1 = _mm_load_ps(S1 + i + 4); s0 = _mm_mul_ps(s0, k0); s1 = _mm_mul_ps(s1, k0); x0 = _mm_add_ps(_mm_load_ps(S0 + i), _mm_load_ps(S2 + i)); x1 = _mm_add_ps(_mm_load_ps(S0 + i + 4), _mm_load_ps(S2 + i + 4)); s0 = _mm_add_ps(s0, _mm_mul_ps(x0, k1)); s1 = _mm_add_ps(s1, _mm_mul_ps(x1, k1)); _mm_storeu_ps(dst + i, s0); _mm_storeu_ps(dst + i + 4, s1); } } return i; } float * kernel; int ksize; }; /*! * \brief get the column filter. * \tparam FT The inner buffer type, used to store the product of src and * filter. * \tparam DT The dst image type. */ template <typename FT, typename DT> static BaseColumnFilter* getLinearColumnFilter(Mat<FT>& kernel, int bits) { int ksize = kernel.cols(); int anchor = ksize / 2; uchar* kernel_str = static_cast<uchar*>(kernel.raw_ptr()); { if (ksize == 3) { if (std::is_same<DT, uchar>::value && std::is_same<FT, int>::value) return new SymmColumnSmallFilter<FixedPtCastEx<FT, DT>, SymmColumnSmallVec_32s8u>( kernel, anchor, FixedPtCastEx<FT, DT>(bits), SymmColumnSmallVec_32s8u(kernel_str, ksize, bits)); if (std::is_same<DT, float>::value && std::is_same<FT, float>::value) return new SymmColumnSmallFilter<FixedPtCastEx<FT, DT>, SymmColumnSmallVec_32f>( kernel, anchor, FixedPtCastEx<FT, DT>(0), SymmColumnSmallVec_32f(kernel_str, ksize, 0)); } if (std::is_same<DT, uchar>::value && std::is_same<FT, int>::value) return new SymmColumnFilter<FixedPtCastEx<FT, DT>, SymmColumnVec_32s8u>( kernel, anchor, FixedPtCastEx<FT, DT>(bits), SymmColumnVec_32s8u(kernel_str, ksize, bits)); if (std::is_same<DT, float>::value && std::is_same<FT, float>::value) return new SymmColumnFilter<FixedPtCastEx<FT, DT>, SymmColumnVec_32f>( kernel, anchor, FixedPtCastEx<FT, DT>(), SymmColumnVec_32f(kernel_str, ksize, 0)); } MegCVException( "Unsupported combination of source format and buffer format\n"); } /*! * \brief get the row filter. * \tparam ST The src image type. * \tparam FT The inner buffer type, used to store the product of src and * filter. */ template <typename ST, typename FT> static BaseRowFilter* getLinearRowFilter(Mat<FT>& kernel) { int ksize = kernel.cols(); int anchor = ksize / 2; uchar* kernel_str = static_cast<uchar*>(kernel.raw_ptr()); if (ksize <= 5) { if (std::is_same<ST, uchar>::value && std::is_same<FT, int>::value) return new SymmRowSmallFilter<ST, FT, SymmRowSmallVec_8u32s>( kernel, anchor, SymmRowSmallVec_8u32s(kernel_str, ksize)); if (std::is_same<ST, float>::value && std::is_same<FT, float>::value) return new SymmRowSmallFilter<ST, FT, SymmRowSmallVec_32f>( kernel, anchor, SymmRowSmallVec_32f(kernel_str, ksize)); } if (std::is_same<ST, uchar>::value && std::is_same<FT, int>::value) return new RowFilter<ST, FT, RowVec_8u32s>( kernel, anchor, RowVec_8u32s(kernel_str, ksize)); if (std::is_same<ST, float>::value && std::is_same<FT, float>::value) return new RowFilter<ST, FT, RowVec_32f>(kernel, anchor, RowVec_32f(kernel_str, ksize)); MegCVException( "Unsupported combination of source format and buffer format\n"); } } // namespace gaussian_blur } // namespace megcv } // namespace megdnn // vim: syntax=cpp.doxygen
[ "megengine@megvii.com" ]
megengine@megvii.com
f743dd0941b7a353b7b9d3c6f59247219e27239a
de1fb1283b293d6fe4d58bf3bb16509c2425ebb0
/src/code/YAAB_LPC2294_C++/YAAB2294/Interfaces/IWrite.h
9cf29730df10473bdb314128b553cb3b278194f1
[]
no_license
DVDPT/O-Maestro
b2bcb4dab89252f96d5496bb8349be7e9b7101b5
be4f53ea06b509a63ca8e7fa83c7ba11ff5d9b92
refs/heads/master
2020-05-20T09:34:32.938312
2011-09-28T10:51:25
2011-09-28T10:51:25
1,426,978
4
0
null
null
null
null
UTF-8
C++
false
false
272
h
/* * IWrite.h * * Created on: 17 de Mai de 2011 * Author: Sorcha */ #pragma once #include "Types.h" class IWrite { public: virtual void WriteString(const U8 * string, U32 length); virtual void WriteInt(U32 number); virtual void WriteChar(U8 character); };
[ "sorcha08@hotmail.com" ]
sorcha08@hotmail.com
67b116cf02f5c5461b9293179d67e9f39f110a99
1b8ae41e4e43429ba6c21b49fdfa7312ddee23b3
/dp_labs_and_solutions/dp_labs_and_solutions/dp_cpp_labs_and_solutions/decorator/lab/coffee_with_milk_with_sugar.h
6809f5fb1c622adf9ae6a7291d61ce628b4a273e
[]
no_license
Technipire/Cpp
9f8476a944497b82ce425a3d9191acb74337a129
78d4c89385216865b9a9f475055fca1ff600d2a4
refs/heads/master
2021-05-01T16:31:45.977554
2017-04-03T00:02:01
2017-04-03T00:02:01
32,282,437
1
0
null
null
null
null
UTF-8
C++
false
false
258
h
// coffee_with_milk_with_sugar.h #ifndef coffee_with_milk_with_sugar_header #define coffee_with_milk_with_sugar_header #include "coffee_with_milk.h" class coffee_with_milk_with_sugar : public coffee_with_milk { public: virtual void prepare(); }; #endif
[ "andyxian510@gmail.com" ]
andyxian510@gmail.com
3642158e8a4937ee8949a53bd7d6ab69f57b05f8
130d56db5e4e552922bdd4de887dda1d1d3827a7
/Exploited Firmware/nxp_fmuk66-v3/src/drivers/uavcan/include/dsdlc_generated/uavcan/protocol/GetDataTypeInfo.hpp
87939bd80f1beb6632daf2fcf387066f8c10428e
[]
no_license
plushpluto/PX4-Malicious
2028d6615ea0da2d6ebfd28c41821b3649736778
3db4ce3ecbfe6821043bb1dce6f651c4e606deb5
refs/heads/master
2023-07-01T10:20:01.551327
2021-08-15T13:19:16
2021-08-15T13:19:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,151
hpp
/* * UAVCAN data structure definition for libuavcan. * * Autogenerated, do not edit. * * Source file: /home/kss/PX4/src/drivers/uavcan/libuavcan/dsdl/uavcan/protocol/2.GetDataTypeInfo.uavcan */ #ifndef UAVCAN_PROTOCOL_GETDATATYPEINFO_HPP_INCLUDED #define UAVCAN_PROTOCOL_GETDATATYPEINFO_HPP_INCLUDED #include <uavcan/build_config.hpp> #include <uavcan/node/global_data_type_registry.hpp> #include <uavcan/marshal/types.hpp> #include <uavcan/protocol/DataTypeKind.hpp> /******************************* Source text ********************************** # # Get the implementation details of a given data type. # # Request is interpreted as follows: # - If the field 'name' is empty, the fields 'kind' and 'id' will be used to identify the data type. # - If the field 'name' is non-empty, it will be used to identify the data type; the # fields 'kind' and 'id' will be ignored. # uint16 id # Ignored if 'name' is non-empty DataTypeKind kind # Ignored if 'name' is non-empty uint8[<=80] name # Full data type name, e.g. "uavcan.protocol.GetDataTypeInfo" --- uint64 signature # Data type signature; valid only if the data type is known (see FLAG_KNOWN) uint16 id # Valid only if the data type is known (see FLAG_KNOWN) DataTypeKind kind # Ditto uint8 FLAG_KNOWN = 1 # This data type is defined uint8 FLAG_SUBSCRIBED = 2 # Subscribed to messages of this type uint8 FLAG_PUBLISHING = 4 # Publishing messages of this type uint8 FLAG_SERVING = 8 # Providing service of this type uint8 flags uint8[<=80] name # Full data type name ******************************************************************************/ /********************* DSDL signature source definition *********************** uavcan.protocol.GetDataTypeInfo saturated uint16 id uavcan.protocol.DataTypeKind kind saturated uint8[<=80] name --- saturated uint64 signature saturated uint16 id uavcan.protocol.DataTypeKind kind saturated uint8 flags saturated uint8[<=80] name ******************************************************************************/ #undef id #undef kind #undef name #undef signature #undef id #undef kind #undef flags #undef name #undef FLAG_KNOWN #undef FLAG_SUBSCRIBED #undef FLAG_PUBLISHING #undef FLAG_SERVING namespace uavcan { namespace protocol { struct UAVCAN_EXPORT GetDataTypeInfo_ { template <int _tmpl> struct Request_ { typedef const Request_<_tmpl>& ParameterType; typedef Request_<_tmpl>& ReferenceType; struct ConstantTypes { }; struct FieldTypes { typedef ::uavcan::IntegerSpec< 16, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > id; typedef ::uavcan::protocol::DataTypeKind kind; typedef ::uavcan::Array< ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate >, ::uavcan::ArrayModeDynamic, 80 > name; }; enum { MinBitLen = FieldTypes::id::MinBitLen + FieldTypes::kind::MinBitLen + FieldTypes::name::MinBitLen }; enum { MaxBitLen = FieldTypes::id::MaxBitLen + FieldTypes::kind::MaxBitLen + FieldTypes::name::MaxBitLen }; // Constants // Fields typename ::uavcan::StorageType< typename FieldTypes::id >::Type id; typename ::uavcan::StorageType< typename FieldTypes::kind >::Type kind; typename ::uavcan::StorageType< typename FieldTypes::name >::Type name; Request_() : id() , kind() , name() { ::uavcan::StaticAssert<_tmpl == 0>::check(); // Usage check #if UAVCAN_DEBUG /* * Cross-checking MaxBitLen provided by the DSDL compiler. * This check shall never be performed in user code because MaxBitLen value * actually depends on the nested types, thus it is not invariant. */ ::uavcan::StaticAssert<671 == MaxBitLen>::check(); #endif } bool operator==(ParameterType rhs) const; bool operator!=(ParameterType rhs) const { return !operator==(rhs); } /** * This comparison is based on @ref uavcan::areClose(), which ensures proper comparison of * floating point fields at any depth. */ bool isClose(ParameterType rhs) const; static int encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); static int decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); }; template <int _tmpl> struct Response_ { typedef const Response_<_tmpl>& ParameterType; typedef Response_<_tmpl>& ReferenceType; struct ConstantTypes { typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_KNOWN; typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_SUBSCRIBED; typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_PUBLISHING; typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_SERVING; }; struct FieldTypes { typedef ::uavcan::IntegerSpec< 64, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > signature; typedef ::uavcan::IntegerSpec< 16, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > id; typedef ::uavcan::protocol::DataTypeKind kind; typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > flags; typedef ::uavcan::Array< ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate >, ::uavcan::ArrayModeDynamic, 80 > name; }; enum { MinBitLen = FieldTypes::signature::MinBitLen + FieldTypes::id::MinBitLen + FieldTypes::kind::MinBitLen + FieldTypes::flags::MinBitLen + FieldTypes::name::MinBitLen }; enum { MaxBitLen = FieldTypes::signature::MaxBitLen + FieldTypes::id::MaxBitLen + FieldTypes::kind::MaxBitLen + FieldTypes::flags::MaxBitLen + FieldTypes::name::MaxBitLen }; // Constants static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_KNOWN >::Type FLAG_KNOWN; // 1 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_SUBSCRIBED >::Type FLAG_SUBSCRIBED; // 2 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_PUBLISHING >::Type FLAG_PUBLISHING; // 4 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_SERVING >::Type FLAG_SERVING; // 8 // Fields typename ::uavcan::StorageType< typename FieldTypes::signature >::Type signature; typename ::uavcan::StorageType< typename FieldTypes::id >::Type id; typename ::uavcan::StorageType< typename FieldTypes::kind >::Type kind; typename ::uavcan::StorageType< typename FieldTypes::flags >::Type flags; typename ::uavcan::StorageType< typename FieldTypes::name >::Type name; Response_() : signature() , id() , kind() , flags() , name() { ::uavcan::StaticAssert<_tmpl == 0>::check(); // Usage check #if UAVCAN_DEBUG /* * Cross-checking MaxBitLen provided by the DSDL compiler. * This check shall never be performed in user code because MaxBitLen value * actually depends on the nested types, thus it is not invariant. */ ::uavcan::StaticAssert<743 == MaxBitLen>::check(); #endif } bool operator==(ParameterType rhs) const; bool operator!=(ParameterType rhs) const { return !operator==(rhs); } /** * This comparison is based on @ref uavcan::areClose(), which ensures proper comparison of * floating point fields at any depth. */ bool isClose(ParameterType rhs) const; static int encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); static int decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); }; typedef Request_<0> Request; typedef Response_<0> Response; /* * Static type info */ enum { DataTypeKind = ::uavcan::DataTypeKindService }; enum { DefaultDataTypeID = 2 }; static const char* getDataTypeFullName() { return "uavcan.protocol.GetDataTypeInfo"; } static void extendDataTypeSignature(::uavcan::DataTypeSignature& signature) { signature.extend(getDataTypeSignature()); } static ::uavcan::DataTypeSignature getDataTypeSignature(); private: GetDataTypeInfo_(); // Don't create objects of this type. Use Request/Response instead. }; /* * Out of line struct method definitions */ template <int _tmpl> bool GetDataTypeInfo_::Request_<_tmpl>::operator==(ParameterType rhs) const { return id == rhs.id && kind == rhs.kind && name == rhs.name; } template <int _tmpl> bool GetDataTypeInfo_::Request_<_tmpl>::isClose(ParameterType rhs) const { return ::uavcan::areClose(id, rhs.id) && ::uavcan::areClose(kind, rhs.kind) && ::uavcan::areClose(name, rhs.name); } template <int _tmpl> int GetDataTypeInfo_::Request_<_tmpl>::encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; int res = 1; res = FieldTypes::id::encode(self.id, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::kind::encode(self.kind, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::name::encode(self.name, codec, tao_mode); return res; } template <int _tmpl> int GetDataTypeInfo_::Request_<_tmpl>::decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; int res = 1; res = FieldTypes::id::decode(self.id, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::kind::decode(self.kind, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::name::decode(self.name, codec, tao_mode); return res; } template <int _tmpl> bool GetDataTypeInfo_::Response_<_tmpl>::operator==(ParameterType rhs) const { return signature == rhs.signature && id == rhs.id && kind == rhs.kind && flags == rhs.flags && name == rhs.name; } template <int _tmpl> bool GetDataTypeInfo_::Response_<_tmpl>::isClose(ParameterType rhs) const { return ::uavcan::areClose(signature, rhs.signature) && ::uavcan::areClose(id, rhs.id) && ::uavcan::areClose(kind, rhs.kind) && ::uavcan::areClose(flags, rhs.flags) && ::uavcan::areClose(name, rhs.name); } template <int _tmpl> int GetDataTypeInfo_::Response_<_tmpl>::encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; int res = 1; res = FieldTypes::signature::encode(self.signature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::id::encode(self.id, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::kind::encode(self.kind, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::flags::encode(self.flags, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::name::encode(self.name, codec, tao_mode); return res; } template <int _tmpl> int GetDataTypeInfo_::Response_<_tmpl>::decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; int res = 1; res = FieldTypes::signature::decode(self.signature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::id::decode(self.id, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::kind::decode(self.kind, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::flags::decode(self.flags, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::name::decode(self.name, codec, tao_mode); return res; } /* * Out of line type method definitions */ inline ::uavcan::DataTypeSignature GetDataTypeInfo_::getDataTypeSignature() { ::uavcan::DataTypeSignature signature(0x88C93DC9F68D24FCULL); Request::FieldTypes::id::extendDataTypeSignature(signature); Request::FieldTypes::kind::extendDataTypeSignature(signature); Request::FieldTypes::name::extendDataTypeSignature(signature); Response::FieldTypes::signature::extendDataTypeSignature(signature); Response::FieldTypes::id::extendDataTypeSignature(signature); Response::FieldTypes::kind::extendDataTypeSignature(signature); Response::FieldTypes::flags::extendDataTypeSignature(signature); Response::FieldTypes::name::extendDataTypeSignature(signature); return signature; } /* * Out of line constant definitions */ template <int _tmpl> const typename ::uavcan::StorageType< typename GetDataTypeInfo_::Response_<_tmpl>::ConstantTypes::FLAG_KNOWN >::Type GetDataTypeInfo_::Response_<_tmpl>::FLAG_KNOWN = 1U; // 1 template <int _tmpl> const typename ::uavcan::StorageType< typename GetDataTypeInfo_::Response_<_tmpl>::ConstantTypes::FLAG_SUBSCRIBED >::Type GetDataTypeInfo_::Response_<_tmpl>::FLAG_SUBSCRIBED = 2U; // 2 template <int _tmpl> const typename ::uavcan::StorageType< typename GetDataTypeInfo_::Response_<_tmpl>::ConstantTypes::FLAG_PUBLISHING >::Type GetDataTypeInfo_::Response_<_tmpl>::FLAG_PUBLISHING = 4U; // 4 template <int _tmpl> const typename ::uavcan::StorageType< typename GetDataTypeInfo_::Response_<_tmpl>::ConstantTypes::FLAG_SERVING >::Type GetDataTypeInfo_::Response_<_tmpl>::FLAG_SERVING = 8U; // 8 /* * Final typedef */ typedef GetDataTypeInfo_ GetDataTypeInfo; namespace { const ::uavcan::DefaultDataTypeRegistrator< ::uavcan::protocol::GetDataTypeInfo > _uavcan_gdtr_registrator_GetDataTypeInfo; } } // Namespace protocol } // Namespace uavcan /* * YAML streamer specialization */ namespace uavcan { template <> class UAVCAN_EXPORT YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Request > { public: template <typename Stream> static void stream(Stream& s, ::uavcan::protocol::GetDataTypeInfo::Request::ParameterType obj, const int level); }; template <typename Stream> void YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Request >::stream(Stream& s, ::uavcan::protocol::GetDataTypeInfo::Request::ParameterType obj, const int level) { (void)s; (void)obj; (void)level; if (level > 0) { s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } } s << "id: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Request::FieldTypes::id >::stream(s, obj.id, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "kind: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Request::FieldTypes::kind >::stream(s, obj.kind, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "name: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Request::FieldTypes::name >::stream(s, obj.name, level + 1); } template <> class UAVCAN_EXPORT YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response > { public: template <typename Stream> static void stream(Stream& s, ::uavcan::protocol::GetDataTypeInfo::Response::ParameterType obj, const int level); }; template <typename Stream> void YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response >::stream(Stream& s, ::uavcan::protocol::GetDataTypeInfo::Response::ParameterType obj, const int level) { (void)s; (void)obj; (void)level; if (level > 0) { s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } } s << "signature: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response::FieldTypes::signature >::stream(s, obj.signature, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "id: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response::FieldTypes::id >::stream(s, obj.id, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "kind: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response::FieldTypes::kind >::stream(s, obj.kind, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "flags: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response::FieldTypes::flags >::stream(s, obj.flags, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "name: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response::FieldTypes::name >::stream(s, obj.name, level + 1); } } namespace uavcan { namespace protocol { template <typename Stream> inline Stream& operator<<(Stream& s, ::uavcan::protocol::GetDataTypeInfo::Request::ParameterType obj) { ::uavcan::YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Request >::stream(s, obj, 0); return s; } template <typename Stream> inline Stream& operator<<(Stream& s, ::uavcan::protocol::GetDataTypeInfo::Response::ParameterType obj) { ::uavcan::YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response >::stream(s, obj, 0); return s; } } // Namespace protocol } // Namespace uavcan #endif // UAVCAN_PROTOCOL_GETDATATYPEINFO_HPP_INCLUDED
[ "korkeep@naver.com" ]
korkeep@naver.com
97bbb9bfbe4d697832716266317245bf48c5d5ac
cf8ddfc720bf6451c4ef4fa01684327431db1919
/SDK/ARKSurvivalEvolved_StairSM_Stone_structs.hpp
12b0110017e6057055472c405163d6c69212f108
[ "MIT" ]
permissive
git-Charlie/ARK-SDK
75337684b11e7b9f668da1f15e8054052a3b600f
c38ca9925309516b2093ad8c3a70ed9489e1d573
refs/heads/master
2023-06-20T06:30:33.550123
2021-07-11T13:41:45
2021-07-11T13:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
255
hpp
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Basic.hpp" #include "ARKSurvivalEvolved_StairSM_Base_classes.hpp" namespace sdk { } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
ab39c04c4b64419e03e16beafe101de76cba4c47
c3b64f709d8594af531ae4078e3c881dd910e127
/src/RunAction.cc
cfed5fb89d3c8e4019b8081bbdaab70b1a4de5c2
[]
no_license
kyrsjo/Proton-Beam-Analysis
9fdf96d9c2ee4d571a8d4e53055ab2de10c6b5bd
aa5f3e5cc478e67776c72df625c5587c6d0ff845
refs/heads/main
2023-01-30T14:13:34.607302
2020-11-23T19:35:52
2020-11-23T19:35:52
314,208,706
0
0
null
2020-11-19T10:10:50
2020-11-19T10:10:49
null
UTF-8
C++
false
false
5,021
cc
#include "RunAction.hh" #include "PrimaryGeneratorAction.hh" #include "DetectorConstruction.hh" #include "G4RunManager.hh" #include "G4Run.hh" #include "G4AccumulableManager.hh" #include "G4LogicalVolumeStore.hh" #include "G4LogicalVolume.hh" #include "G4UnitsTable.hh" #include "G4SystemOfUnits.hh" RunAction::RunAction(G4String output) : G4UserRunAction(), OutputFile(output) { G4AnalysisManager* analysisManager = G4AnalysisManager::Instance(); analysisManager->SetVerboseLevel(1); G4double x_num = 200, x_min = -50, x_max = 50; G4double y_num = 200, y_min = -50, y_max = 50; G4double z_num = 800, z_min = 0.0, z_max = 200; G4double r_num = 200, r_min = 0.0, r_max = 50; G4double KE_num = 160, KE_min = 0.0, KE_max = 160000000; G4double LET_num = 200, LET_min = 0.0, LET_max = 10.0; //AllEnergyHistoID = analysisManager->CreateH3("AllEnergyHisto", "Energy Deposition by Particles", 400, -200.0, 200.0, 400, -200.0, 200.0, 200, 0., 200.0); ProtonEnergyHistoID = analysisManager->CreateH3("ProtonEnergyHisto", "Energy Deposition(Proton)", x_num, x_min, x_max, y_num, y_min, y_max, z_num, z_min, z_max); ProtonLongEnergyHistoID = analysisManager->CreateH1("ProtonLongEnergyHisto", "Energy Deposition(Proton)", z_num, z_min, z_max); // ProtonEnergyZHistoID = analysisManager->CreateH1("ProtonEnergyHisto", "Energy Deposition(Proton)", z_num, z_min, z_max); ProtonRadialHistoID = analysisManager->CreateH2("ProtonRadialHisto", "Energy Radial Deposition(Proton)", z_num, z_min, z_max, r_num, r_min, r_max); ProtonKEHistoID = analysisManager->CreateH2("ProtonKEHisto", "Kinetic Energy(Proton)", z_num, z_min, z_max, KE_num, KE_min, KE_max); NeutronKEHistoID = analysisManager->CreateH2("NeutronEnergyHisto", "Energy Deposition by Neutrons", z_num, z_min, z_max, KE_num, KE_min, KE_max); // ElectronEnergyHistoID = analysisManager->CreateH3("ElectronEnergyHisto", "Energy Deposition by Electron", 400, -200.0, 200.0, 400, -200.0, 200.0, 200, 0., 200.0); ParticlecountZ0HistID = analysisManager->CreateH1("ParticelCounter", "Number of Particles at Water Surface", 5, 0, 5); ProtonFluenceHistoID = analysisManager->CreateH1("ProtonFluence", "Number of Proton with depth", 200, 0, 200); Proton1FluenceHistoID = analysisManager->CreateH1("Proton1Fluence", "Number of Proton with depth", 200, 0, 200); Proton2FluenceHistoID = analysisManager->CreateH1("Proton2Fluence", "Number of Proton with depth", 200, 0, 200); Proton3FluenceHistoID = analysisManager->CreateH1("Proton3Fluence", "Number of Proton with depth", 200, 0, 200); Proton4FluenceHistoID = analysisManager->CreateH1("Proton4Fluence", "Number of Proton with depth", 200, 0, 200); Proton5FluenceHistoID = analysisManager->CreateH1("Proton5Fluence", "Number of Proton with depth", 200, 0, 200); Proton8FluenceHistoID = analysisManager->CreateH1("Proton8Fluence", "Number of Proton with depth", 200, 0, 200); Proton10FluenceHistoID = analysisManager->CreateH1("Proton10Fluence", "Number of Proton with depth", 200, 0, 200); Proton15FluenceHistoID = analysisManager->CreateH1("Proton15Fluence", "Number of Proton with depth", 200, 0, 200); Proton20FluenceHistoID = analysisManager->CreateH1("Proton20Fluence", "Number of Proton with depth", 200, 0, 200); Proton25FluenceHistoID = analysisManager->CreateH1("Proton25Fluence", "Number of Proton with depth", 200, 0, 200); //ProtonLongFluenceHistoID = analysisManager->CreateH1("ProtonLongFluence" , "Number of Proton with depth", 200, 0, 200); //ProtonLETdataHistoID = analysisManager->CreateH1("ProtonLETdataHisto", "LET data(Protons)",z_num, z_min, z_max); LETDisHistoID = analysisManager->CreateH2("LETHisto", "Proton LET Histo", z_num, z_min, z_max, 150, 0.0, 15.0 ); LETDataHistoID = analysisManager->CreateH1("LETDataHisto", "Proton LET Histo", z_num, z_min, z_max); LETData3DHistoID = analysisManager->CreateH3("LETData3DHisto", "Proton LET 3D Histo", x_num, x_min, x_max, y_num, y_min, y_max, z_num, z_min, z_max); NeutronFluenceHistoID = analysisManager->CreateH1("NeutronFluence", "Number of Neutron with depth", 200, 0, 200); } RunAction::~RunAction() { } void RunAction::BeginOfRunAction(const G4Run* run) { G4AnalysisManager* analysisManager = G4AnalysisManager::Instance(); analysisManager->OpenFile(OutputFile); } void RunAction::EndOfRunAction(const G4Run* run) { G4AnalysisManager* analysisManager = G4AnalysisManager::Instance(); analysisManager->Write(); analysisManager->CloseFile(); }
[ "noreply@github.com" ]
kyrsjo.noreply@github.com
9a3d71d2d5cd8a5d5d9b4dba8ea307a4d3bb4f17
b279667f2d4bb599c0031fb958144e3eeea79c9f
/Hp_table.cpp
c4bfb1a076ef9ba49be0eadbf6ab9f7b7de31ef1
[]
no_license
shiro0005/HEW-
cd45c2f30910aaeece2260acf7ed2cf18b085191
f9b20a86ffc0e62e7a14416d8cdf6313f19cc5a2
refs/heads/master
2020-09-28T00:14:43.559126
2020-03-06T07:54:31
2020-03-06T07:54:31
226,642,666
0
0
null
2020-03-06T07:54:33
2019-12-08T09:23:49
C++
UTF-8
C++
false
false
494
cpp
#include "Hp_table.h" D3DXVECTOR2 animeTableHp[10] = { {//1 D3DXVECTOR2(0.0f, 0.99f) }, {//2 D3DXVECTOR2(0.0f, 0.88f) }, {//3 D3DXVECTOR2(0.0f, 0.77f) }, {//4 D3DXVECTOR2(0.0f, 0.66f) }, {//5 D3DXVECTOR2(0.0f, 0.55f) }, {//6 D3DXVECTOR2(0.0f, 0.44f) }, {//7 D3DXVECTOR2(0.0f, 0.33f) }, {//8 D3DXVECTOR2(0.0f, 0.22f) }, {//9 D3DXVECTOR2(0.0f, 0.11f) }, {//10 D3DXVECTOR2(0.0f, 0.0f) }, }; D3DXVECTOR2 GetAnimTblHp(int set) { return animeTableHp[set]; }
[ "siawase.youta@gmail.com" ]
siawase.youta@gmail.com
21697acea8469d3f639e6c7fbffe7e667b0a1684
74ef401a3c11709c5cc0679e980988e7866970a0
/system/controlDict
e70a1b473155c60ccdb993c67f246c259cb46d7f
[]
no_license
sedwavefoam/Dohmen-Janssen-and-Hanes-2002
c485f8196b5154c9a5ba98fe3373f91c3b68b3e4
963fcf341af3904cd8d36d9ecbbeb15bc2147f9b
refs/heads/master
2020-03-16T12:53:15.931663
2019-11-16T03:03:06
2019-11-16T03:03:06
132,676,712
0
0
null
null
null
null
UTF-8
C++
false
false
1,451
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 1.7.1 | | \\ / A nd | Web: www.OpenFOAM.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "system"; object controlDict; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // application SedWaveRANSFoam; startFrom latestTime;//startTime; startTime 0; stopAt endTime; endTime 70; deltaT 0.00001; writeControl adjustableRunTime; writeInterval 0.1; purgeWrite 0; writeFormat ascii; writePrecision 6; writeCompression uncompressed; timeFormat general; timePrecision 6; runTimeModifiable on; adjustTimeStep yes; maxCo 0.1; maxAlphaCo 0.1; maxDeltaT 1e-03; libs ( "libOpenFOAM.so" "libgroovyBC.so" ) ; // ************************************************************************* //
[ "noreply@github.com" ]
sedwavefoam.noreply@github.com
8c5cadb945f69b98b8a41a5e26cc2478835ff428
9280fea108f5b3912629de7851f6bbbde561c9a4
/src/common/optimization/test/test_cache_states.hpp
9cfa54f4a15f557d5aceaa3fe86bac1606a70e52
[ "MIT", "Apache-2.0" ]
permissive
bytetok/vde
93071992618b7c539cd618eaae24d65f1099295b
ff8950abbb72366ed3072de790c405de8875ecc3
refs/heads/main
2023-08-23T15:08:14.644017
2021-10-09T03:59:09
2021-10-09T03:59:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,673
hpp
// Copyright 2019 the Autoware Foundation // // 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. // // Co-developed by Tier IV, Inc. and Apex.AI, Inc. #ifndef TEST_CACHE_STATES_HPP_ #define TEST_CACHE_STATES_HPP_ #include <gtest/gtest.h> #include <optimization/utils.hpp> #include <functional> #include <vector> #include <map> namespace autoware { namespace common { namespace optimization { template<typename ValT, typename CompareFuncT = decltype(std::equal_to<ValT>())> void do_test( const ComputeMode & mode, ValT val1, ValT val2, ExpressionTerm term, CompareFuncT comparator = CompareFuncT()) { auto get_an_unset_term = [](const ComputeMode & mode) { if (!mode.score()) { return ExpressionTerm::SCORE; } else if (!mode.jacobian()) { return ExpressionTerm::JACOBIAN; } else if (!mode.hessian()) { return ExpressionTerm::HESSIAN; } else { // Make sure there is an unset term before calling this function. EXPECT_TRUE(false); return ExpressionTerm::SCORE; // Dummy value for completeness } }; // Make sure val1 and val2 are different ASSERT_FALSE(comparator(val1, val2)); CacheStateMachine<ValT, CompareFuncT> csm{comparator}; csm.update(val1, mode); EXPECT_TRUE(csm.is_cached(val1, term)); EXPECT_FALSE(csm.is_cached(val2, term)); if (mode != ComputeMode{}.set_score().set_jacobian().set_hessian()) { const auto unset_term = get_an_unset_term(mode); EXPECT_FALSE(csm.is_cached(val1, unset_term)); EXPECT_FALSE(csm.is_cached(val2, unset_term)); } } class CacheStateMachineTest : public ::testing::Test { public: CacheStateMachineTest() { m_mode_map.emplace( ExpressionTerm::SCORE, std::vector<ComputeMode>{ ComputeMode{}.set_score(), ComputeMode{}.set_score().set_jacobian(), ComputeMode{}.set_score().set_hessian(), ComputeMode{}.set_score().set_jacobian().set_hessian(), }); m_mode_map.emplace( ExpressionTerm::JACOBIAN, std::vector<ComputeMode>{ ComputeMode{}.set_jacobian(), ComputeMode{}.set_jacobian().set_score(), ComputeMode{}.set_jacobian().set_hessian(), ComputeMode{}.set_jacobian().set_score().set_hessian(), }); m_mode_map.emplace( ExpressionTerm::HESSIAN, std::vector<ComputeMode>{ ComputeMode{}.set_hessian(), ComputeMode{}.set_hessian().set_score(), ComputeMode{}.set_hessian().set_jacobian(), ComputeMode{}.set_hessian().set_jacobian().set_score(), }); } protected: void SetUp() { for (const auto & mode : m_mode_map[ExpressionTerm::SCORE]) { ASSERT_TRUE(mode.score()); } for (const auto & mode : m_mode_map[ExpressionTerm::JACOBIAN]) { ASSERT_TRUE(mode.jacobian()); } for (const auto & mode : m_mode_map[ExpressionTerm::HESSIAN]) { ASSERT_TRUE(mode.hessian()); } } std::map<ExpressionTerm, std::vector<ComputeMode>> m_mode_map; }; } // namespace optimization } // namespace common } // namespace autoware #endif // TEST_CACHE_STATES_HPP_
[ "Will.Heitman@utdallas.edu" ]
Will.Heitman@utdallas.edu
f4955d47bf6c4bb56730e3a5af6c4ac3ec54d66a
0a26bc4f3b3562cdd454d0618ddcd5dd7524f930
/operator/operator/cast.cpp
400429faf16c63e8509df449ad8c5c9384850433
[ "Apache-2.0" ]
permissive
nihui/Tengine-Convert-Tools
cdf7b82a4bf0916974f50e5793160436ecade606
1d18533b2c08481de02f647a7dfdc33036a565bf
refs/heads/master
2023-03-03T05:49:45.636354
2021-02-15T12:48:31
2021-02-15T12:48:31
339,140,308
1
0
Apache-2.0
2021-02-15T16:38:13
2021-02-15T16:38:13
null
UTF-8
C++
false
false
1,197
cpp
/* * 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. */ /* * Copyright (c) 2019, Open AI Lab * Author: ddzhao@openailab.com */ #include "operator/cast.hpp" namespace TEngine { void Cast::SetSchema(void) { Input({"input:float32"}) .Output({"output:float32"}) .SetAttr("type_from", 0) .SetAttr("type_to", 0) .SetDoc(R"DOC(Cast Operator)DOC"); } } // namespace TEngine
[ "248857878@qq.com" ]
248857878@qq.com
23f8702608911f0a80b58a46cc52f539ae6f05d0
6fe26c7fb9f3ed167e0c78c73870986a450e1d8a
/Milestone-2/Reference-project/my_ip_hls/my_ip_hls_tb.cpp
c910eecf2da6ce853e16cd10f0b895ee60304978
[ "MIT" ]
permissive
CSpyridakis/Reconfigurable-Computing
17b0bbd9b879c4dcf430d9b3fd682e1e2d254b4d
345316489786c6470e47c66b0bf4a73d2ac4b0c0
refs/heads/master
2021-06-30T03:55:05.568758
2020-10-13T20:22:04
2020-10-13T20:22:04
173,803,738
0
3
null
null
null
null
UTF-8
C++
false
false
765
cpp
#include <hls_stream.h> #include <ap_int.h> #include <iostream> #include <stdint.h> using namespace hls; #include "my_ip_hls.hpp" #define STREAM_TEST_ITERATIONS 100 int main() { uint32 i = 0; stream<axiWord> slaveIn("slaveIn"); stream<axiWord> masterOut("masterOut"); for (i=0;i<STREAM_TEST_ITERATIONS;i++) { axiWord dataIn = {0,0,0}; dataIn.data = i+1; dataIn.strb = 0b1111; if (i == STREAM_TEST_ITERATIONS-1) dataIn.last = 1; else dataIn.last = 0; slaveIn.write(dataIn); my_ip_hls(slaveIn, masterOut); if (!masterOut.empty()) { axiWord dataOut = {0,0,0}; masterOut.read(dataOut); printf("%d: read data: %u\n",(int)i, (int)dataOut.data); } else { printf("%d: no data available!\n",(int)i); } } return 0; }
[ "spyridakischristos@gmail.com" ]
spyridakischristos@gmail.com
eb2e4126e940e8d3e54e7168de617c667423755e
5fa98392c6f8f18ecefe773ee1dd86251bc5f2dc
/src/obj/cards/card.cpp
c0c14de7d7860ad70b3045e828c87b41991583a5
[]
no_license
Alir3za97/RoyaleClash
04eee019e4fe833df4643f008d22289097582ea0
336a9c68b139601f4702446f26f96a9d20b3a999
refs/heads/master
2021-01-09T20:40:59.650942
2016-07-22T22:47:34
2016-07-22T22:47:34
61,951,641
0
0
null
null
null
null
UTF-8
C++
false
false
2,287
cpp
// // Created by mareal on 6/27/16. // #include <settings.h> #include "card.h" #include <src/obj/cards/troops/lava_hound.h> #include <src/obj/cards/troops/balloon.h> #include <src/obj/cards/troops/minion_horde.h> #include <src/obj/cards/troops/ice_wizard.h> #include <src/obj/cards/troops/dark_prince.h> #include <src/obj/cards/troops/miner.h> #include <src/obj/cards/troops/valkyrie.h> #include <src/obj/cards/troops/witch.h> #include <src/obj/cards/troops/royal_giant.h> #include <src/obj/cards/troops/hog_rider.h> #include <src/obj/cards/mirror.h> #include <src/obj/cards/spells/zap.h> #include <src/obj/cards/spells/rage.h> #include <src/obj/cards/buildings/furnace.h> #include <src/obj/cards/buildings/inferno_tower.h> Card::Card() { } Card::Card(const QPixmap& img, QPointF pos) : QGraphicsPixmapItem(img){ setPos(pos); } Card* Card::createCard(int which) { Card* card = 0; if(Setting::cardNames[which] == "lava") card = new LavaHound(); else if(Setting::cardNames[which] == "balloon") card = new Balloon(); else if(Setting::cardNames[which] == "minion-horde") card = new MinionHorde(); else if(Setting::cardNames[which] == "ice-wizard") card = new IceWizard(); else if(Setting::cardNames[which] == "dark-prince") card = new DarkPrince(); else if(Setting::cardNames[which] == "miner") card = new Miner(); else if(Setting::cardNames[which] == "valkyrie") card = new Valkyrie(); else if(Setting::cardNames[which] == "witch") card = new Witch(); else if(Setting::cardNames[which] == "royale-giant") card = new RoyalGiant(); else if(Setting::cardNames[which] == "hog-rider") card = new HogRider(); else if(Setting::cardNames[which] == "mirror") card = new Mirror(); else if(Setting::cardNames[which] == "zap") card = new Zap(); else if(Setting::cardNames[which] == "rage") card = new Rage(); else if(Setting::cardNames[which] == "furnace") card = new Furnace(); else if(Setting::cardNames[which] == "inferno-tower") card = new InfernoTower(); QPixmap pix; pix.convertFromImage(QImage(Setting::picturesPath[which]).scaled(QSize(30, 37))); card -> setPixmap(pix); return card; }
[ "alir3za97@gmail.com" ]
alir3za97@gmail.com
f6e7d91051f7bd75828cb91bdf7907460de6a92f
b005adeb2a0bde1bcc848beb39ed94f35d5d4c2a
/Course/Course Examples/Class and constructors/deepCopy02.cpp
9868cf4d3ecf2ce9ba3a4f048ce0fe551306a661
[ "MIT" ]
permissive
tigercosmos/CSIE1212
2593a65c3aef71bbccb89b56b3c71c7363fb413d
00ea11441e3d922d7421f542378e95a9b21b11a3
refs/heads/master
2021-04-26T23:05:58.136525
2018-06-12T07:39:06
2018-06-12T07:39:06
123,930,817
3
1
null
null
null
null
UTF-8
C++
false
false
1,542
cpp
// How to avoid shallow copy #include <cstdlib> #include <iostream> using namespace std; class myVec { public: myVec(int n){size=n; data=new int[size];}; myVec(){size=10; data=new int[size];}; myVec(const myVec& a); // copy constructor from a ~myVec(){delete [] data;}; myVec& operator=(const myVec& a); // assignment operator from a void print(); // Print data int *data; int size; }; void myVec::print(){ cout << "["; for (int i=0; i<size; i++) cout << data[i] << " "; cout << "]" << endl; } // Copy constructor myVec::myVec(const myVec& a) { // copy constructor from a size = a.size; // copy sizes data = new int[size]; // allocate new array for (int i=0; i<size; i++) // copy the vector contents data[i]=a.data[i]; } // Assignment operator myVec& myVec::operator=(const myVec& a) { // assignment operator from a if (this != &a) { // avoid self-assignment delete [] data; // delete old array size = a.size; // set new size data = new int[size]; // allocate new array for (int i=0; i<size; i++) // copy the vector contents data[i]=a.data[i]; } return *this; } int main(){ myVec a(5); myVec b=a; // Copy constructor, same as "myVec b=myVec(a);" myVec c; c=a; // Assignment operator a.data[0]=2; b.data[1]=4; c.data[2]=6; cout << "a: "; a.print(); cout << "b: "; b.print(); cout << "c: "; c.print(); cout << a.data << endl; cout << b.data << endl; cout << c.data << endl; return EXIT_SUCCESS; }
[ "phy.tiger@gmail.com" ]
phy.tiger@gmail.com
c1cfb045de98adbb7825180d09b4a345f1d5db84
4593c780288a80a02d30df706a7326c380e5f7cf
/phantom.hpp
1f93f524134d21e17b9b25f3a5f03ea2c04a91a0
[]
no_license
kcroo/ChurchOfTheDamned
e3f0527503ed45eaff4ead0ad85e54e5c3e4a442
eb355992ea91520606466cddf20b6f721d7c94e3
refs/heads/master
2020-06-19T21:07:12.893931
2020-01-03T01:35:20
2020-01-03T01:35:20
196,873,090
0
0
null
null
null
null
UTF-8
C++
false
false
532
hpp
/************************************************************************************************** Program Name: Final Project File: phantom.hpp Author: Kirsten Corrao Date: 02/28/2019 Description: this is the header file for Phantom, which is a derived class of Character. ***************************************************************************************************/ #ifndef PHANTOM_HPP #define PHANTOM_HPP #include "character.hpp" class Phantom : public Character { private: public: Phantom(); ~Phantom(); }; #endif
[ "kirstencorrao@gmail.com" ]
kirstencorrao@gmail.com
a1fdd86e17ba38d447d67f42a86786ae05f3d663
a3f9ead37fe92d7dd39e7163acf31bdb7d094e29
/Classes/Interpreter/QBasicMessages.cpp
ea32259eb3357c98db519901b8556a72c91c3ba4
[]
no_license
momons/NikuQBasic
40493fd8f655097689294104b3cde9b778b5683d
34d53566b3edf7cc04c8d37b34ccf6b65ae817fe
refs/heads/master
2021-01-23T03:16:19.906482
2017-09-13T16:55:25
2017-09-13T16:55:25
86,062,368
0
0
null
2017-09-13T16:55:26
2017-03-24T11:45:58
C++
UTF-8
C++
false
false
2,088
cpp
// // QBasicMessages.cpp // NikuQBasic // // Created by HaraKazunari on 2017/03/28. // // #include "QBasicMessages.h" #include "StringUtil.h" /** インスタンス */ QBasicMessages *QBasicMessages::interpreterMessagesInstance; /** * インスタンスシェア * @return インスタンス */ QBasicMessages *QBasicMessages::sharedInstance() { static once_flag flag; // 一度だけコール call_once(flag,initialize); return QBasicMessages::interpreterMessagesInstance; } /** * 初期化 */ void QBasicMessages::initialize() { QBasicMessages::interpreterMessagesInstance = new QBasicMessages(); QBasicMessages::interpreterMessagesInstance->build(); } /** * デストラクタ */ QBasicMessages::~QBasicMessages() { delete QBasicMessages::interpreterMessagesInstance; } /** * メッセージ取得 * @param key キー * @param params パラメータ * @return メッセージ */ string QBasicMessages::getMessage(const string &key, const char *params) { if (localizable.find(key) == localizable.end()) { return key; } if (params == nullptr) { return localizable[key]; } ostringstream os; os << localizable[key] << *params; return os.str(); } /** * メッセージ一覧作成 */ void QBasicMessages::build() { FileUtils *fileUtil = FileUtils::getInstance(); // カレント言語取得 LanguageType language = Application::getInstance()->getCurrentLanguage(); if (language == LanguageType::JAPANESE) { fileUtil->addSearchPath("ja.lproj"); } else { fileUtil->addSearchPath("en.lproj"); } // ファイル名を読み込み string fullpath = fileUtil->fullPathForFilename("Localize.strings"); string strings = fileUtil->getStringFromFile(fullpath); if (strings.empty()) { return; } vector<string> stringLines; StringUtil::split(stringLines, strings, "\";\n"); for(auto it = stringLines.begin();it != stringLines.end();it++) { vector<string> stringKeyValue; StringUtil::split(stringKeyValue, *it, "=\""); if(stringKeyValue.size() == 2){ localizable[stringKeyValue[0]] = stringKeyValue[1]; } } }
[ "nikuQ@HaraKazunari-no-MacBook-Pro-4.local" ]
nikuQ@HaraKazunari-no-MacBook-Pro-4.local
8a9f1882bf740571511e78e8662c304c7ea02793
8a184384b97ccca7256396ae2fdaa92a0635384d
/Main/Database.cpp
c162341c03f6bbca498718da5e433ce170168479
[]
no_license
P0RUNGA/BMS
66db4db0e8aa24539b3f0d9dcdcf86993e42349d
f2d0e533240f568f0f2408e4f4a1f2247adcefbe
refs/heads/master
2020-04-15T10:50:48.515709
2017-02-23T14:09:52
2017-02-23T14:09:52
68,272,092
0
0
null
null
null
null
GB18030
C++
false
false
7,262
cpp
#include "stdafx.h" #include "Database.h" #include <iostream> #include <sstream> using namespace std; const char * DB_NAME = "mian.db"; bool Database::openDatabase() { // 开启数据库 this->pDB = NULL; int nRes = sqlite3_open(DB_NAME, &pDB); if (nRes != SQLITE_OK) { cout << "开启数据库失败: " << sqlite3_errmsg(pDB); sqlite3_close(pDB); return false; } else { // 开启数据库成功 return true; } } void Database::closeDatabase() { /* 关闭数据库 */ sqlite3_close(this->pDB); } int Database::selectAllResult(void * NotUsed, int argc, char ** argv, char ** azColName) { /* 回调函数 */ for (int i = 0; i < argc; i++) { cout << azColName[i] << " = " << (argv[i] ? argv[i] : "NULL") << " "; } cout << endl; return 0; } void Database::SQLite_query(const char * sql, int(*callback)(void *, int, char**, char**)) { char* cErrMsg; int nRes = sqlite3_exec(pDB, sql, callback, NULL, &cErrMsg); if (nRes != SQLITE_OK) { cout << "数据库操作失败: " << cErrMsg << endl; sqlite3_free(cErrMsg); sqlite3_close(pDB); } else { cout << "数据库操作成功! " << endl; } } /*可以判断书本库存,也可以判断借书者可借书的数量*/ bool Database::isEnough(const char * strSql) { int is_bEnough; is_bEnough = getIntFiled(strSql); if (is_bEnough == 0) { return false; } else { return true; } } int Database::getIntFiled(const char * strSql) { int filed; sqlite3_stmt* stmt; int nRes = sqlite3_prepare(pDB, strSql, -1, &stmt, NULL); if (nRes != SQLITE_OK) { cout << "数据库操作错误!" << sqlite3_errmsg(pDB) << endl; return -1; sqlite3_finalize(stmt); sqlite3_close(pDB); } else { while (sqlite3_step(stmt) == SQLITE_ROW) { filed = sqlite3_column_int(stmt, 0); break; } sqlite3_finalize(stmt); return filed; } } const char* Database::getStringFiled(const char * strSql) { char* filed = nullptr; sqlite3_stmt* stmt; int nRes = sqlite3_prepare(pDB, strSql, -1, &stmt, NULL); if (nRes != SQLITE_OK) { cout << "数据库操作错误!" << sqlite3_errmsg(pDB) << endl; return NULL; sqlite3_finalize(stmt); sqlite3_close(pDB); } else { while (sqlite3_step(stmt) == SQLITE_ROW) { filed = (char *)sqlite3_column_text(stmt, 0); break; } sqlite3_finalize(stmt); return filed; } } void Database::subFiled(const char* filed1, const char* table, const char* filed2, const char* limit) { // 取出旧的value stringstream strSql1; strSql1 << "SELECT " << filed1 << " FROM " << table << " WHERE " << filed2 << " = '" << limit << "'"; int oValue = getIntFiled(strSql1.str().c_str()); // 插入新的value stringstream strSql2; strSql2 << "UPDATE " << table << " SET " << filed1 << " = " << (oValue - 1) << " WHERE " << filed2 << " = '" << limit << "'"; SQLite_query(strSql2.str().c_str()); } void Database::addFiled(const char * filed1, const char * table, const char * filed2, const char * limit) { // 取出旧的value stringstream strSql1; strSql1 << "SELECT " << filed1 << " FROM " << table << " WHERE " << filed2 << " = '" << limit << "'"; int oValue = getIntFiled(strSql1.str().c_str()); // 插入新的value stringstream strSql2; strSql2 << "UPDATE " << table << " SET " << filed1 << " = " << (oValue + 1) << " WHERE " << filed2 << " = '" << limit << "'"; SQLite_query(strSql2.str().c_str()); } void Database::subFiled(const char * filed1, const char * table, const char * filed2, int limit) { // 取出旧的value stringstream strSql1; strSql1 << "SELECT " << filed1 << " FROM " << table << " WHERE " << filed2 << " = " << limit; int oValue = getIntFiled(strSql1.str().c_str()); // 插入新的value stringstream strSql2; strSql2 << "UPDATE " << table << " SET " << filed1 << " = " << (oValue - 1) << " WHERE " << filed2 << " = " << limit; SQLite_query(strSql2.str().c_str()); } void Database::addFiled(const char * filed1, const char * table, const char * filed2, int limit) { // 取出旧的value stringstream strSql1; strSql1 << "SELECT " << filed1 << " FROM " << table << " WHERE " << filed2 << " = " << limit; int oValue = getIntFiled(strSql1.str().c_str()); // 插入新的value stringstream strSql2; strSql2 << "UPDATE " << table << " SET " << filed1 << " = " << (oValue + 1) << " WHERE " << filed2 << " = " << limit; SQLite_query(strSql2.str().c_str()); } void Database::bookTOMap() { // 清空原先的map bookMap.erase(bookMap.begin(), bookMap.end()); int id, page, total, stock; string name, author, publish; sqlite3_stmt* stmt; int nRes = sqlite3_prepare(pDB, "SELECT * FROM book", -1, &stmt, NULL); if (nRes != SQLITE_OK) { cout << "数据库操作错误!" << sqlite3_errmsg(pDB) << endl; sqlite3_finalize(stmt); sqlite3_close(pDB); } else { while (sqlite3_step(stmt) == SQLITE_ROW) { // 获取各个字段数据 id = sqlite3_column_int(stmt, 0); name = (char* )sqlite3_column_text(stmt, 1); author = (char* )sqlite3_column_text(stmt, 2); publish = (char* )sqlite3_column_text(stmt, 3); page = sqlite3_column_int(stmt, 4); total = sqlite3_column_int(stmt, 5); stock = sqlite3_column_int(stmt, 6); // 先放入Book对象 Book book; book.SetBookMsg(name, author, publish, page, total, stock, id); // 插入map bookMap.insert(map<string, Book>::value_type(name, book)); } sqlite3_finalize(stmt); } } void Database::borrowerTOMap() { // 清空原先的map borrowerMap.erase(borrowerMap.begin(), borrowerMap.end()); int card, canborrow, have; string name; sqlite3_stmt* stmt; int nRes = sqlite3_prepare(pDB, "SELECT * FROM borrower", -1, &stmt, NULL); if (nRes != SQLITE_OK) { cout << "数据库操作错误!" << sqlite3_errmsg(pDB) << endl; sqlite3_finalize(stmt); sqlite3_close(pDB); } else { while (sqlite3_step(stmt) == SQLITE_ROW) { // 获取各个字段数据 card = sqlite3_column_int(stmt, 0); name = (char*)sqlite3_column_text(stmt, 1); canborrow = sqlite3_column_int(stmt, 2); have = sqlite3_column_int(stmt, 3); // 先放入Borrower对象 Borrower borrower(card, name.c_str(), canborrow, have); // 插入map borrowerMap.insert(map<int, Borrower>::value_type(card, borrower)); } sqlite3_finalize(stmt); } } void Database::listTOMap() { // 清空原先的map listMap.erase(listMap.begin(), listMap.end()); int id, bid, card; string name, books, bdate, rdate; sqlite3_stmt* stmt; int nRes = sqlite3_prepare(pDB, "SELECT * FROM list", -1, &stmt, NULL); if (nRes != SQLITE_OK) { cout << "数据库操作错误!" << sqlite3_errmsg(pDB) << endl; sqlite3_finalize(stmt); sqlite3_close(pDB); } else { while (sqlite3_step(stmt) == SQLITE_ROW) { // 获取各个字段数据 id = sqlite3_column_int(stmt, 0); card = sqlite3_column_int(stmt, 1); name = (char*)sqlite3_column_text(stmt, 2); bid = sqlite3_column_int(stmt, 3); books = (char*)sqlite3_column_text(stmt, 4); bdate = (char*)sqlite3_column_text(stmt, 5); rdate = (char*)sqlite3_column_text(stmt, 6); // 先放入List结构体对象 List list = { id, card, name, bid, books, bdate, rdate }; // 插入map listMap.insert(map<string, List>::value_type(books, list)); } sqlite3_finalize(stmt); } }
[ "3066463563@qq.com" ]
3066463563@qq.com
d3190a4141089e711bb42a7cd069b5a5b81fe6f0
04c70a565ccadd403cec8c58b668f681014efa16
/src/DigiTree.cc
49f36d26152f4e2b322572ac9c007b59a2087ea6
[]
no_license
michaelplesser/H4Analysis
7ea413159605a0deef3e7251a52b03081a46c8a2
f7ca8fcebee1071efbda81597232b2385e116265
refs/heads/master
2020-04-03T10:01:18.753321
2018-11-13T14:05:16
2018-11-13T14:05:16
155,182,077
0
0
null
2018-10-29T09:05:25
2018-10-29T09:05:24
null
UTF-8
C++
false
false
3,869
cc
#include "interface/DigiTree.h" DigiTree::DigiTree(uint64* idx, TTree* tree, string prefix) { prefix_=prefix; tree_ = tree ? tree : new TTree(); index=idx; } void DigiTree::Init(vector<string>& names, vector<string>& timetypes) { //---allocate enough space for all channels n_channels = names.size(); n_times = timetypes.size()*n_channels; channels = new int[n_channels]; time_types = new int[n_times]; pedestal = new float[n_channels]; b_charge = new float[n_channels]; b_slope = new float[n_channels]; b_rms = new float[n_channels]; time = new float[n_channels*n_times]; time_chi2 = new float[n_channels*n_times]; time_slope = new float[n_channels*n_times]; maximum = new float[n_channels]; time_maximum = new float[n_channels]; amp_max = new float[n_channels]; time_max = new float[n_channels]; chi2_max = new float[n_channels]; charge_tot = new float[n_channels]; charge_sig = new float[n_channels]; fit_ampl = new float[n_channels]; fit_time = new float[n_channels]; fit_chi2 = new float[n_channels]; calibration = new float[n_channels]; //---channels branches for(unsigned int iCh=0; iCh<n_channels; iCh++) { channels[iCh]=iCh; tree_->Branch(names[iCh].c_str(), &(channels[iCh]), (names[iCh]+"/I").c_str()); } //---time types branches for(unsigned int iT=0; iT<timetypes.size(); iT++) { time_types[iT]=iT*n_channels; tree_->Branch(timetypes[iT].c_str(), &(time_types[iT]), (timetypes[iT]+"/I").c_str()); } //---global branches string size_var = "n_"+prefix_+"channels"; string size_time_var = "n_"+prefix_+"timetypes"; tree_->Branch("index", index, "index/l"); tree_->Branch(size_var.c_str(), &n_channels, (size_var+"/i").c_str()); tree_->Branch(size_time_var.c_str(), &n_times, (size_time_var+"/i").c_str()); tree_->Branch((prefix_+"pedestal").c_str(), pedestal, (prefix_+"pedestal["+size_var+"]/F").c_str()); tree_->Branch((prefix_+"b_charge").c_str(), b_charge, (prefix_+"b_charge["+size_var+"]/F").c_str()); tree_->Branch((prefix_+"b_slope").c_str(), b_slope, (prefix_+"b_slope["+size_var+"]/F").c_str()); tree_->Branch((prefix_+"b_rms").c_str(), b_rms, (prefix_+"b_rms["+size_var+"]/F").c_str()); tree_->Branch((prefix_+"time").c_str(), time, (prefix_+"time["+size_time_var+"]/F").c_str()); tree_->Branch((prefix_+"time_chi2").c_str(), time_chi2, (prefix_+"time_chi2["+size_time_var+"]/F").c_str()); tree_->Branch((prefix_+"time_slope").c_str(), time_slope, (prefix_+"time_slope["+size_time_var+"]/F").c_str()); tree_->Branch((prefix_+"maximum").c_str(), maximum, (prefix_+"maximum["+size_var+"]/F").c_str()); tree_->Branch((prefix_+"time_maximum").c_str(), time_maximum, (prefix_+"time_maximum["+size_var+"]/F").c_str()); tree_->Branch((prefix_+"amp_max").c_str(), amp_max, (prefix_+"amp_max["+size_var+"]/F").c_str()); tree_->Branch((prefix_+"time_max").c_str(), time_max, (prefix_+"time_max["+size_var+"]/F").c_str()); tree_->Branch((prefix_+"chi2_max").c_str(), chi2_max, (prefix_+"chi2_max["+size_var+"]/F").c_str()); tree_->Branch((prefix_+"charge_tot").c_str(), charge_tot, (prefix_+"charge_tot["+size_var+"]/F").c_str()); tree_->Branch((prefix_+"charge_sig").c_str(), charge_sig, (prefix_+"charge_sig["+size_var+"]/F").c_str()); tree_->Branch((prefix_+"fit_ampl").c_str(), fit_ampl, (prefix_+"fit_ampl["+size_var+"]/F").c_str()); tree_->Branch((prefix_+"fit_time").c_str(), fit_time, (prefix_+"fit_time["+size_var+"]/F").c_str()); tree_->Branch((prefix_+"fit_chi2").c_str(), fit_chi2, (prefix_+"fit_chi2["+size_var+"]/F").c_str()); tree_->Branch((prefix_+"calibration").c_str(), calibration, (prefix_+"calibration["+size_var+"]/F").c_str()); } DigiTree::~DigiTree() {}
[ "plesser.michael@gmail.com" ]
plesser.michael@gmail.com
68e064774f055996ae57d4bae428523cff61eb40
7008a119bb08279a03f93b8e106fb3f56ede6110
/sketcherMaeReading.h
fa0a57171e4f8acaa3d0e33969eaa0ca87667d16
[ "BSD-3-Clause" ]
permissive
schrodinger/coordgenlibs
2c53d2130204a4a38201d0f1938e0994944ced55
6a1485643feb71c6d609d263f28751004c733cf7
refs/heads/master
2023-08-31T05:09:59.887467
2023-08-28T12:15:46
2023-08-28T12:15:46
94,079,967
32
27
BSD-3-Clause
2023-08-28T12:23:30
2017-06-12T09:41:41
C++
UTF-8
C++
false
false
2,490
h
#pragma once /// // Shim for creating sketcherMolecules from .mae files. #include "sketcherMinimizerMolecule.h" #include "maeparser/MaeConstants.hpp" #include "maeparser/Reader.hpp" /// // A very simple utility function to parse a mae::Block into a 2D // sketcherMinimizerMolecule. Anything beyond atomic number, x and y coordinates // and bond orders will be ignored (i.e. no chiralities or stereo bonds will be // parsed). // sketcherMinimizerMolecule* mol_from_mae_block(schrodinger::mae::Block& block) { auto molecule = new sketcherMinimizerMolecule(); // Atom data is in the m_atom indexed block { const auto atom_data = block.getIndexedBlock(schrodinger::mae::ATOM_BLOCK); // All atoms are gauranteed to have these three field names: const auto atomic_numbers = atom_data->getIntProperty(schrodinger::mae::ATOM_ATOMIC_NUM); const auto xs = atom_data->getRealProperty(schrodinger::mae::ATOM_X_COORD); const auto ys = atom_data->getRealProperty(schrodinger::mae::ATOM_Y_COORD); const auto size = atomic_numbers->size(); // atomic numbers, and x, y, and z coordinates for (size_t i = 0; i < size; ++i) { auto atom = molecule->addNewAtom(); atom->setAtomicNumber(atomic_numbers->at(i)); atom->setCoordinates(sketcherMinimizerPointF( static_cast<float>(xs->at(i)), static_cast<float>(ys->at(i)))); } } // Bond data is in the m_bond indexed block try { const auto bond_data = block.getIndexedBlock(schrodinger::mae::BOND_BLOCK); // All bonds are gauranteed to have these three field names: auto from_atoms = bond_data->getIntProperty(schrodinger::mae::BOND_ATOM_1); auto to_atoms = bond_data->getIntProperty(schrodinger::mae::BOND_ATOM_2); auto orders = bond_data->getIntProperty(schrodinger::mae::BOND_ORDER); const auto size = from_atoms->size(); for (size_t i = 0; i < size; ++i) { // Maestro atoms are 1 indexed! auto* from_atom = molecule->getAtoms().at(from_atoms->at(i) - 1); auto* to_atom = molecule->getAtoms().at(to_atoms->at(i) - 1); auto bond = molecule->addNewBond(from_atom, to_atom); bond->setBondOrder(orders->at(i)); } } catch (const std::out_of_range&) { // no bonds. } return molecule; }
[ "dan.nealschneider@schrodinger.com" ]
dan.nealschneider@schrodinger.com
7e0631eaf9f370bf9383bd9ec9b736b3b3ef2c62
c20c4812ac0164c8ec2434e1126c1fdb1a2cc09e
/Source/Source/Common/SO3World/Src/KCharacter.h
0a88c4a76e126530f4763bff21fa743e67bb114b
[ "MIT" ]
permissive
uvbs/FullSource
f8673b02e10c8c749b9b88bf18018a69158e8cb9
07601c5f18d243fb478735b7bdcb8955598b9a90
refs/heads/master
2020-03-24T03:11:13.148940
2018-07-25T18:30:25
2018-07-25T18:30:25
142,408,505
2
2
null
2018-07-26T07:58:12
2018-07-26T07:58:12
null
GB18030
C++
false
false
55,075
h
/************************************************************************/ /* 角色 */ /* Copyright : Kingsoft 2005 */ /* Author : Zhu Jianqiu */ /* History : */ /* 2004.12.30 Create */ /* Comment : */ /* 角色是玩家和NPC的共同基类 */ /************************************************************************/ #ifndef _KCHARACTER_H_ #define _KCHARACTER_H_ #include <list> #include <bitset> #include "Global.h" #include "SO3Result.h" #include "KAttribute.h" #include "KSceneObject.h" #include "KThreatList.h" #include "KItem.h" #include "KTarget.h" #include "KSkill.h" #include "KSkillDebug.h" #include "KAIVM.h" #include "KBuffList.h" class KPatrolPath; class KLootList; class KItem; // 根据ID判断是否是玩家,玩家ID的高2位为0 #define IS_NPC(ID) ((ID) & 0x40000000) #define IS_PLAYER(ID) (!IS_NPC(ID)) #define MAX_HIT_VALUE 10000 #define MAX_PARTY_EFFECT_RANGE (40 * 64) #define GET_SWIM_WATER_LINE(nHeight) ((nHeight) * 7 / 10) #define IS_UNDER_WATER(nWaterLine, nCharacterHeight) ((nWaterLine) >= (nCharacterHeight) * 9 / 10) #define AI_TARGET_GROUP_MAX_COUNT 32 #define FLOTAGE_COEFFICIENT 512 // 该结构用于接收技能运算的结果 struct KSKILL_CALCULATE_RESULT { BOOL bShield; BOOL bHitTarget; BOOL bSkillDodge; BOOL bCriticalStrike; BOOL bImmunity; BOOL bParry; BOOL bInsight; int nSkillEffectResult[serTotal]; BOOL bPhysicsBlock; BOOL bSolarMagicBlock; BOOL bNeutralMagicBlock; BOOL bLunarMagicBlock; BOOL bPoisonBlock; BOOL bBuffResist; BOOL bBuffImmunity; int nBuffID; int nBuffLevel; struct { KSKILL_EFFECT_TYPE eType; DWORD dwID; int nLevel; } EffectSrc; }; // -------------- Over time action ----------------------> // 持续一段时间的行为 enum KOT_ACTION_TYPE { otActionIdle, otActionSkillPrepare, otActionSkillChannel, otActionRecipePrepare, otActionPickPrepare, otActionPicking, otActionCustomPrepare, otActionCustomChannel, otActionUseItemPrepare }; struct KProfessionSkill { KTarget Target; DWORD dwCraftID; DWORD dwRecipeID; DWORD dwSourceItemID; //发起生活技能的道具ID,这个有可能是配方书,也有可能是一个消耗道具 }; struct KOT_ACTION_PARAM { KOT_ACTION_TYPE eActionType; union { KSkillRecipePointer SkillRecipePointer; DWORD dwDoodadID; DWORD dwItemID; } Data; KTarget Target; KProfessionSkill ProfessionSkill; int nEndFrame; union { int nNextActFrame; // 通道技下用这个表示下一次作用时间 int nPrepareFrame; // 吟唱技下用这个表示该技能本身吟唱时间 }; int nBeatBackCount; // 吟唱/通道被打退的计数 DWORD dwScriptID; // CustomOTAction会带一个脚本 BOOL bIsBreakable; // 是否会被攻击打断 #ifdef _CLIENT DWORD dwEndAniID; // 使用道具 #endif }; struct KAUTO_CAST_SKILL_PARAM { KSkillRecipePointer SkillRecipePointer; BOOL bMelee; int* pnCastCycle; int nPreCastFrame; }; // <-------------- Over time event ---------------------- // 角色走动,寻路的结果 enum KMOVE_RESULT { mrInvalid, mrSucceed, // 正常移动了 mrOutOfMap, // 到地图边缘了,无效的区域 mrObstacle, // 有障碍,无法前进 mrDeleteSelf, // 在客户端,进入同步范围之外,把自己删除了 mrReachTarget, // 已经到达目标 mrTotal }; enum KSKILL_HIT_RESULT { shrInvalid = 0, shrHit, shrMiss, shrDodge, shrParry, shrInsight, shrCriticalStrike, shrTotal }; enum KAI_TARGET_TYPE { aittInvalid = -3, aittSelectTarget = -2, aittSkillTarget = -1, aittLastSelectTarget = 0, aittLastSkillTarget, aittAttackTarget, aittCustomTarget1, aittCustomTarget2, aittCustomTarget3, aittCustomTarget4, aittTotal }; enum KAI_RECORD_SKILL_TYPE { airstInvalid = -1, airstSelectSkill, airstCastSkill, airstHitSkill, airstBehitSkill, airstTotal }; class KCharacter : public KSceneObject { public: KCharacter(); virtual ~KCharacter(); BOOL Init(); void UnInit(); void Activate(void); public: // 杂项 char m_szName[_NAME_LEN]; // 角色名 #ifdef _CLIENT char m_szTitle[TITLE_LEN]; // 称号 #endif CHARACTER_GENDER m_eGender; CHARACTER_KIND m_eKind; // 角色类型 DWORD m_dwClassID; // 分类ID CHARACTER_RACE m_eRace; // 角色种族 DWORD m_dwForceID; // 势力 DWORD m_dwGuardForceID; // 受该势力的守卫保护 int m_nLevel; // 角色等级 DWORD m_dwCharacterAction; // 表情状态 DWORD m_dwModelID; // 模型ID #ifdef _SERVER BOOL m_bStealthy; // 隐身 #endif #ifdef _SERVER // 有的NPC是玩家专有的,只向其Owner同步 // 之所以放到Character里面,是为了代码简单,省得到处判断IS_NPC DWORD m_dwOwner; #endif DECLARE_LUA_STRING(Name, _NAME_LEN); #ifdef _CLIENT DECLARE_LUA_STRING(Title, TITLE_LEN); #endif DECLARE_LUA_ENUM(Gender); DECLARE_LUA_ENUM(Kind); DECLARE_LUA_DWORD(ClassID); DECLARE_LUA_ENUM(Race); DECLARE_LUA_DWORD(ForceID); DECLARE_LUA_DWORD(GuardForceID); DECLARE_LUA_INTEGER(Level); DECLARE_LUA_DWORD(CharacterAction); DECLARE_LUA_DWORD(ModelID); #ifdef _SERVER DECLARE_LUA_DWORD(Owner); #endif // -------------- 移动相关 --------------------------------------------------> CHARACTER_MOVE_STATE m_eMoveState; // 移动状态 BOOL m_bSlip; int m_nJumpLimitFrame; int m_nVelocityXY; // 水平速度 int m_nDirectionXY; // 水平速度方向 int m_nVelocityZ; // 垂直速度 int m_nDestX; int m_nDestY; // 收敛速度,比如在Run时,瞬时速度会受到打滑,重力等影响而变化,最终速度收敛于这个值 int m_nConvergenceSpeed; int m_nRunSpeed; int m_nRunSpeedBase; int m_nMoveSpeedPercent; int m_nCurrentGravity; int m_nGravity; int m_nGravityBase; int m_nGravityPercent; int m_nJumpCount; // 跳跃计数器 int m_nMaxJumpCount; // 最大跳跃次数 int m_nDropDefence; // 抗摔伤系数, [0 - 1024] int m_nJumpSpeed; // 跳跃的垂直初速度 int m_nJumpSpeedBase; int m_nJumpSpeedPercent; int m_nDivingCount; int m_nDivingFrame; // 最大潜水时间 int m_nDivingFrameBase; int m_nDivingFramePercent; int m_nWaterFlyAbility; // 是否可以水上漂 BOOL m_bTryPathState; // 是否正在绕路过程之中 int m_nTryPathSide; // 正在往左还是往右绕路 int m_nTryPathDestX; // 绕路开始的时候的移动目标点X int m_nTryPathDestY; // 绕路开始的时候的移动目标点Y #ifdef _SERVER // 玩家或NPC释放某些要求自动朝向的技能时将此标记设为true, // 当玩家主动改变朝向时将此标记设为false,取消自动朝向。 BOOL m_bAutoTurnFlag; #endif // 自动飞行相关 int m_nCurrentTrack; // 当前移动轨迹。 int m_nFromNode; // 起始结点 int m_nTargetCity; // 目的城市 DECLARE_LUA_ENUM(MoveState); DECLARE_LUA_INTEGER(VelocityXY); DECLARE_LUA_INTEGER(DirectionXY); DECLARE_LUA_INTEGER(VelocityZ); DECLARE_LUA_INTEGER(DestX); DECLARE_LUA_INTEGER(DestY); DECLARE_LUA_INTEGER(RunSpeed); DECLARE_LUA_INTEGER(RunSpeedBase); DECLARE_LUA_INTEGER(MoveSpeedPercent); DECLARE_LUA_INTEGER(MaxJumpCount); DECLARE_LUA_INTEGER(Gravity); DECLARE_LUA_INTEGER(GravityBase); DECLARE_LUA_INTEGER(GravityPercent); DECLARE_LUA_INTEGER(JumpSpeed); DECLARE_LUA_INTEGER(JumpSpeedBase); DECLARE_LUA_INTEGER(JumpSpeedPercent); DECLARE_LUA_INTEGER(DropDefence); DECLARE_LUA_INTEGER(DivingCount); DECLARE_LUA_INTEGER(DivingFrame); DECLARE_LUA_INTEGER(DivingFrameBase); DECLARE_LUA_INTEGER(DivingFramePercent); DECLARE_LUA_INTEGER(WaterFlyAbility); // -------------- 潜能 ------------------------------------------------------> int m_nCurrentStrength; // 力量:主要影响人物的外功伤害 int m_nStrengthBase; int m_nStrengthBasePercentAdd; int m_nCurrentAgility; // 身法:主要影响人物的行动速度,攻击速度,命中率,闪避率。 int m_nAgilityBase; int m_nAgilityBasePercentAdd; int m_nCurrentVitality; // 体质:主要影响人物的生命值。 int m_nVitalityBase; int m_nVitalityBasePercentAdd; int m_nCurrentSpirit; // 根骨:主要影响人物的内力值,内功系伤害。 int m_nSpiritBase; int m_nSpiritBasePercentAdd; int m_nCurrentSpunk; // 精神: 主要影响人物的生命恢复速度和内力恢复速度. int m_nSpunkBase; int m_nSpunkBasePercentAdd; DECLARE_LUA_INTEGER(CurrentStrength); DECLARE_LUA_INTEGER(StrengthBase); DECLARE_LUA_INTEGER(StrengthBasePercentAdd); DECLARE_LUA_INTEGER(CurrentAgility); DECLARE_LUA_INTEGER(AgilityBase); DECLARE_LUA_INTEGER(AgilityBasePercentAdd); DECLARE_LUA_INTEGER(CurrentVitality); DECLARE_LUA_INTEGER(VitalityBase); DECLARE_LUA_INTEGER(VitalityBasePercentAdd); DECLARE_LUA_INTEGER(CurrentSpirit); DECLARE_LUA_INTEGER(SpiritBase); DECLARE_LUA_INTEGER(SpiritBasePercentAdd); DECLARE_LUA_INTEGER(CurrentSpunk); DECLARE_LUA_INTEGER(SpunkBase); DECLARE_LUA_INTEGER(SpunkBasePercentAdd); // --------------- 生命 ------------------------------------------------------> // m_nMaxLife = m_nMaxLifeBase * (1024 + m_nMaxLifePercentAdd) / 1024 + m_nMaxLiftAdditional; // 非战斗状态回血计算公式: // m_nLifeReplenish + (m_nLifeReplenish * m_nLifeReplenishCoefficient) + (m_nMaxLife * m_nLifeReplenishPercent) + m_nLifeReplenishExt // // 战斗状态回血计算公式: // (m_nLifeReplenish * m_nLifeReplenishCoefficient) + (m_nMaxLife * m_nLifeReplenishPercent) + m_nLifeReplenishExt int m_nCurrentLife; // 当前生命 int m_nMaxLife; // 生命最大值 int m_nMaxLifeBase; // 仅取决于职业,等级 int m_nMaxLifePercentAdd; // 生命最大值增加百分比 int m_nMaxLifeAdditional; // 追加的生命最大值 int m_nLifeReplenish; // 生命点数恢复速度 = m_nSpunkLifeReplenish + 其他(装备或BUFF加成等) int m_nLifeReplenishPercent; // 生命百分比恢复速度, 单位1/1024 int m_nLifeReplenishCoefficient;// 生命点数恢复速度的系数,单位1/1024 int m_nLifeReplenishExt; // 附加生命恢复点数 DECLARE_LUA_INTEGER(CurrentLife); DECLARE_LUA_INTEGER(MaxLife); DECLARE_LUA_INTEGER(MaxLifeBase); DECLARE_LUA_INTEGER(MaxLifePercentAdd); DECLARE_LUA_INTEGER(MaxLifeAdditional); DECLARE_LUA_INTEGER(LifeReplenish); DECLARE_LUA_INTEGER(LifeReplenishPercent); DECLARE_LUA_INTEGER(LifeReplenishCoefficient); DECLARE_LUA_INTEGER(LifeReplenishExt); // ---------------- 内力 -----------------------------------------------------> int m_nCurrentMana; int m_nMaxMana; int m_nMaxManaBase; int m_nMaxManaPercentAdd; int m_nMaxManaAdditional; int m_nManaReplenish; // 回蓝点数 = m_nSpunkManareplenish + 其他(装备或BUFF加成等) int m_nManaReplenishPercent; int m_nManaReplenishCoefficient; int m_nManaReplenishExt; DECLARE_LUA_INTEGER(CurrentMana); DECLARE_LUA_INTEGER(MaxMana); DECLARE_LUA_INTEGER(MaxManaBase); DECLARE_LUA_INTEGER(MaxManaPercentAdd); DECLARE_LUA_INTEGER(MaxManaAdditional); DECLARE_LUA_INTEGER(ManaReplenish); DECLARE_LUA_INTEGER(ManaReplenishPercent); DECLARE_LUA_INTEGER(ManaReplenishCoefficient); DECLARE_LUA_INTEGER(ManaReplenishExt); // --------------- 怒气 -------------------------------------------------------> int m_nCurrentRage; int m_nMaxRage; int m_nRageReplenish; DECLARE_LUA_INTEGER(CurrentRage); DECLARE_LUA_INTEGER(MaxRage); DECLARE_LUA_INTEGER(RageReplenish); // --------------- 战斗杂项 ---------------------------------------------------> int m_nDodge; // 闪避点数 = m_Dodege int m_nDodgeBaseRate; BOOL m_bFightState; BOOL m_bSheathFlag; // 武器位置标记,true表示不在手上,false表示在手上 BOOL m_bSystemShield; // 系统无敌盾 BOOL m_bPositiveShield; // 正面效果屏蔽,屏蔽所有正向效果(如加血,Buff)技能 BOOL m_bNegativeShield; // 负面效果屏蔽,屏蔽所有负向效果(如伤害, Debuff)技能 int m_nGlobalBlock; // 无类型格挡 int m_nGlobalDamageAbsorb; // 无类型限制的吸收伤害 int m_nGlobalDamageManaShield; // 无类型限制的内力抵消伤害 int m_nDamageToLifeForSelf; // 把伤害转为自己的生命 int m_nDamageToManaForSelf; // 把伤害转为自己的内力 int m_nBeatBackRate; int m_nStunStrikeRate; // 击晕率 int m_nKnockedBackRate; // 被击退率 int m_nKnockedOffRate; // 被击飞率 int m_nKnockedDownRate; // 被击倒率 int m_nRepulsedRate; // 被击滑步率 int m_nPullRate; // 被拉扯率 BOOL m_bImmortal; // 不会死去 int m_nMountingRate; // 被打下马的抵抗概率 int m_nAccumulateValue; // 蓄气值 int m_nParryBaseRate; int m_nParry; // 招架点数 int m_nParryBase; int m_nParryPercent; int m_nParryValue; // 招架值,决定招架减免的伤害 int m_nParryValueBase; int m_nParryValuePercent; int m_nSense; // 洞察值 与NPC的识破有关 int m_nStrain; // 应变值 和Player抵抗Npc的识破有关 int m_nStrainBase; int m_nStrainPercent; int m_nToughnessBaseRate; int m_nToughness; // 韧性值 用来减少被会心的几率 int m_nToughnessBase; int m_nToughnessPercent; int m_nDecriticalDamagePowerBaseKiloNumRate; int m_nDecriticalDamagePower; // 减少会心伤害 int m_nDecriticalDamagePowerBase; int m_nDecriticalDamagePowerPercent; int m_nTransferDamageToManaPercent; //伤害转为内力 int m_nModifyCostManaPercent; // 人物技能的消耗修正 DWORD m_dwAddDamageByDstMoveStateMask; // 根据目标的移动状态增加伤害的掩码 int m_nAddDamagePercentByDstMoveState; // 根据目标的移动状态增加伤害的百分比 DWORD m_dwTransferDamageToCharacter; int m_nTransferDamagePercent; DWORD m_dwTransferTherapyToCharacter; int m_nTransferTherapyPercent; // -->[破绽] #ifdef _SERVER int m_nUpperWeak; // 上段破绽 int m_nMiddleWeak; // 中段破绽 int m_nLowerWeak; // 下段破绽 #endif int m_nUpperWeakShield; // 上段破绽盾 int m_nMiddleWeakShield; // 中段破绽盾 int m_nLowerWeakShield; // 下段破绽盾 int m_nUpperWeakLevel; // 破绽级别(0,低,中,高) int m_nMiddleWeakLevel; int m_nLowerWeakLevel; DECLARE_LUA_INTEGER(UpperWeakLevel); DECLARE_LUA_INTEGER(MiddleWeakLevel); DECLARE_LUA_INTEGER(LowerWeakLevel); // [破绽]<-- // 偷取敌方生命百分比: 指对敌方造成伤害后,伤害中的多少比例转化为自己的生命,单位(1/1024) // 偷取敌方内力百分比: 比如玩家A被B攻击,A受到最终伤害1000点,这时,A可以偷取B的内力(1000 * m_nStealManaPercent / 1024) DECLARE_LUA_INTEGER(Dodge); DECLARE_LUA_INTEGER(DodgeBaseRate); DECLARE_LUA_BOOL(FightState); DECLARE_LUA_BOOL(SheathFlag); DECLARE_LUA_BOOL(PositiveShield); DECLARE_LUA_BOOL(NegativeShield); DECLARE_LUA_INTEGER(GlobalBlock); DECLARE_LUA_INTEGER(GlobalDamageAbsorb); DECLARE_LUA_INTEGER(GlobalDamageManaShield); DECLARE_LUA_INTEGER(DamageToLifeForSelf); DECLARE_LUA_INTEGER(DamageToManaForSelf); DECLARE_LUA_INTEGER(BeatBackRate); DECLARE_LUA_INTEGER(StunStrikeRate); DECLARE_LUA_INTEGER(KnockedBackRate); DECLARE_LUA_INTEGER(KnockedOffRate); DECLARE_LUA_INTEGER(ParryBaseRate); DECLARE_LUA_INTEGER(Parry); DECLARE_LUA_INTEGER(Sense); DECLARE_LUA_INTEGER(Strain); DECLARE_LUA_INTEGER(ToughnessBaseRate); DECLARE_LUA_INTEGER(Toughness); DECLARE_LUA_INTEGER(DecriticalDamagePowerBaseKiloNumRate); DECLARE_LUA_INTEGER(DecriticalDamagePower); DECLARE_LUA_INTEGER(ParryValue); DECLARE_LUA_INTEGER(MountingRate); DECLARE_LUA_INTEGER(AccumulateValue); // -------------- 外功 ------------------------------------------------------> int m_nMeleeWeaponDamageBase; int m_nMeleeWeaponDamageRand; DECLARE_LUA_INTEGER(MeleeWeaponDamageBase); DECLARE_LUA_INTEGER(MeleeWeaponDamageRand); int m_nRangeWeaponDamageBase; int m_nRangeWeaponDamageRand; DECLARE_LUA_INTEGER(RangeWeaponDamageBase); DECLARE_LUA_INTEGER(RangeWeaponDamageRand); int m_nSkillPhysicsDamage; int m_nSkillPhysicsDamageRand; int m_nSkillPhysicsDamagePercent; int m_nPhysicsDamageCoefficient; // 外功伤害加成系数, 在伤害计算流程的最后会乘上这个系数(所取的数值是被伤害人身上的) int m_nPhysicsAttackPower; int m_nPhysicsAttackPowerBase; int m_nPhysicsAttackPowerPercent; int m_nPhysicsHitBaseRate; int m_nPhysicsHitValue; //int m_nAgilityCriticalStrike; // 身法影响的外功致命一击值 int m_nPhysicsCriticalStrikeBaseRate; int m_nPhysicsCriticalStrike; // 外功致命一击值 = m_nAgilityCriticalStrike + 其他(装备或BUFF加成等) int m_nPhysicsCriticalStrikeBase; int m_nPhysicsCriticalDamagePowerBaseKiloNumRate; // 增加会心伤害 int m_nPhysicsCriticalDamagePower; int m_nPhysicsCriticalDamagePowerBase; int m_nPhysicsCriticalDamagePowerPercent; int m_nPhysicsResistPercent; // 外功克性,针对削弱目标的外功防御 int m_nPhysicsOvercome; int m_nPhysicsOvercomeBase; int m_nPhysicsOvercomePercent; // 外功防御 // int m_nPhysicsDefence; int m_nPhysicsDefenceAdd; int m_nPhysicsDefenceMax; // 外功防御力, 用于计算"m_nPhysicsDefence" int m_nPhysicsShield; int m_nPhysicsShieldBase; int m_nPhysicsShieldPercent; int m_nPhysicsShieldAdditional; // 外功反弹,该值是直接反弹给攻击者的伤害点数,但是并不会减少自己受到的伤害数值 // 外功反弹百分比,该值会减少自己所受伤害,并将伤害反弹给对方, 单位(1/1024),数值 [0, 1024] int m_nPhysicsReflection; int m_nPhysicsReflectionPercent; int m_nPhysicsBlock; int m_nPhysicsDamageAbsorb; int m_nPhysicsDamageManaShield; DECLARE_LUA_INTEGER(PhysicsAttackPower); DECLARE_LUA_INTEGER(SkillPhysicsDamageRand); DECLARE_LUA_INTEGER(PhysicsHitValue); DECLARE_LUA_INTEGER(PhysicsHitBaseRate); DECLARE_LUA_INTEGER(PhysicsCriticalStrike); DECLARE_LUA_INTEGER(PhysicsCriticalStrikeBaseRate); DECLARE_LUA_INTEGER(PhysicsResistPercent); DECLARE_LUA_INTEGER(PhysicsCriticalDamagePowerBaseKiloNumRate); DECLARE_LUA_INTEGER(PhysicsCriticalDamagePower); DECLARE_LUA_INTEGER(PhysicsOvercome); DECLARE_LUA_INTEGER(PhysicsShield); DECLARE_LUA_INTEGER(PhysicsReflection); DECLARE_LUA_INTEGER(PhysicsReflectionPercent); DECLARE_LUA_INTEGER(PhysicsBlock); DECLARE_LUA_INTEGER(PhysicsDamageAbsorb); DECLARE_LUA_INTEGER(PhysicsDamageManaShield); // -------------- 阳性内功 ------------------------------------------------------> int m_nSkillSolarDamage; int m_nSkillSolarDamageRand; int m_nSkillSolarDamagePercent; int m_nSolarDamageCoefficient; // 阳性内功伤害加成系数, 在伤害计算流程的最后会乘上这个系数(所取的数值是被伤害人身上的) int m_nSolarAttackPower; int m_nSolarAttackPowerBase; int m_nSolarAttackPowerPercent; int m_nSolarHitBaseRate; int m_nSolarHitValue; int m_nSolarCriticalStrikeBaseRate; int m_nSolarCriticalStrike; int m_nSolarCriticalStrikeBase; int m_nSolarCriticalDamagePowerBaseKiloNumRate; // 增加会心伤害 int m_nSolarCriticalDamagePower; int m_nSolarCriticalDamagePowerBase; int m_nSolarCriticalDamagePowerPercent; int m_nSolarOvercome; int m_nSolarOvercomeBase; int m_nSolarOvercomePercent; int m_nSolarMagicResistPercent; // 抵抗百分比 int m_nSolarMagicShield; // 防御力,这个数值最终会用来查表获得防御系数 int m_nSolarMagicShieldBase; int m_nSolarMagicShieldPercent; int m_nSolarMagicReflection; int m_nSolarMagicReflectionPercent; int m_nSolarMagicBlock; int m_nSolarDamageAbsorb; int m_nSolarDamageManaShield; DECLARE_LUA_INTEGER(SolarAttackPower); DECLARE_LUA_INTEGER(SolarHitValue); DECLARE_LUA_INTEGER(SolarHitBaseRate); DECLARE_LUA_INTEGER(SolarCriticalStrike); DECLARE_LUA_INTEGER(SolarCriticalStrikeBaseRate); DECLARE_LUA_INTEGER(SolarCriticalDamagePowerBaseKiloNumRate); DECLARE_LUA_INTEGER(SolarCriticalDamagePower); DECLARE_LUA_INTEGER(SolarOvercome); DECLARE_LUA_INTEGER(SolarMagicShield); DECLARE_LUA_INTEGER(SolarMagicResistPercent); DECLARE_LUA_INTEGER(SolarMagicReflection); DECLARE_LUA_INTEGER(SolarMagicReflectionPercent); DECLARE_LUA_INTEGER(SolarMagicBlock); DECLARE_LUA_INTEGER(SolarDamageAbsorb); DECLARE_LUA_INTEGER(SolarDamageManaShield); // -------------- 中性内功 ------------------------------------------------------> int m_nSkillNeutralDamage; int m_nSkillNeutralDamageRand; int m_nSkillNeutralDamagePercent; int m_nNeutralDamageCoefficient; // 中性内功伤害加成系数, 在伤害计算流程的最后会乘上这个系数(所取的数值是被伤害人身上的) int m_nNeutralAttackPower; int m_nNeutralAttackPowerBase; int m_nNeutralAttackPowerPercent; int m_nNeutralHitBaseRate; int m_nNeutralHitValue; int m_nNeutralCriticalStrikeBaseRate; int m_nNeutralCriticalStrike; int m_nNeutralCriticalStrikeBase; int m_nNeutralCriticalDamagePowerBaseKiloNumRate; // 增加会心伤害 int m_nNeutralCriticalDamagePower; int m_nNeutralCriticalDamagePowerBase; int m_nNeutralCriticalDamagePowerPercent; int m_nNeutralOvercome; int m_nNeutralOvercomeBase; int m_nNeutralOvercomePercent; int m_nNeutralMagicResistPercent; // 抵抗百分比 int m_nNeutralMagicShield; // 防御力,这个数值最终会用来查表获得防御系数 int m_nNeutralMagicShieldBase; int m_nNeutralMagicShieldPercent; int m_nNeutralMagicReflection; int m_nNeutralMagicReflectionPercent; int m_nNeutralMagicBlock; int m_nNeutralDamageAbsorb; int m_nNeutralDamageManaShield; DECLARE_LUA_INTEGER(NeutralAttackPower); DECLARE_LUA_INTEGER(NeutralHitValue); DECLARE_LUA_INTEGER(NeutralHitBaseRate); DECLARE_LUA_INTEGER(NeutralCriticalStrike); DECLARE_LUA_INTEGER(NeutralCriticalStrikeBaseRate); DECLARE_LUA_INTEGER(NeutralCriticalDamagePowerBaseKiloNumRate); DECLARE_LUA_INTEGER(NeutralCriticalDamagePower); DECLARE_LUA_INTEGER(NeutralOvercome); DECLARE_LUA_INTEGER(NeutralMagicShield); DECLARE_LUA_INTEGER(NeutralMagicResistPercent); DECLARE_LUA_INTEGER(NeutralMagicReflection); DECLARE_LUA_INTEGER(NeutralMagicReflectionPercent); DECLARE_LUA_INTEGER(NeutralMagicBlock); DECLARE_LUA_INTEGER(NeutralDamageAbsorb); DECLARE_LUA_INTEGER(NeutralDamageManaShield); // -------------- 阴性内功 ------------------------------------------------------> int m_nSkillLunarDamage; int m_nSkillLunarDamageRand; int m_nSkillLunarDamagePercent; int m_nLunarDamageCoefficient; // 阴性内功伤害加成系数, 在伤害计算流程的最后会乘上这个系数(所取的数值是被伤害人身上的) int m_nLunarAttackPower; int m_nLunarAttackPowerBase; int m_nLunarAttackPowerPercent; int m_nLunarHitBaseRate; int m_nLunarHitValue; int m_nLunarCriticalStrikeBaseRate; int m_nLunarCriticalStrike; int m_nLunarCriticalStrikeBase; int m_nLunarCriticalDamagePowerBaseKiloNumRate; // 增加会心伤害 int m_nLunarCriticalDamagePower; int m_nLunarCriticalDamagePowerBase; int m_nLunarCriticalDamagePowerPercent; int m_nLunarOvercome; // 克性 int m_nLunarOvercomeBase; int m_nLunarOvercomePercent; int m_nLunarMagicResistPercent; // 抵抗百分比 int m_nLunarMagicShield; // 防御力,这个数值最终会用来查表获得防御系数 int m_nLunarMagicShieldBase; int m_nLunarMagicShieldPercent; int m_nLunarMagicReflection; int m_nLunarMagicReflectionPercent; int m_nLunarMagicBlock; int m_nLunarDamageAbsorb; int m_nLunarDamageManaShield; DECLARE_LUA_INTEGER(LunarAttackPower); DECLARE_LUA_INTEGER(LunarHitValue); DECLARE_LUA_INTEGER(LunarHitBaseRate); DECLARE_LUA_INTEGER(LunarCriticalStrike); DECLARE_LUA_INTEGER(LunarCriticalStrikeBaseRate); DECLARE_LUA_INTEGER(LunarCriticalDamagePowerBaseKiloNumRate); DECLARE_LUA_INTEGER(LunarCriticalDamagePower); DECLARE_LUA_INTEGER(LunarOvercome); DECLARE_LUA_INTEGER(LunarMagicShield); DECLARE_LUA_INTEGER(LunarMagicResistPercent); DECLARE_LUA_INTEGER(LunarMagicReflection); DECLARE_LUA_INTEGER(LunarMagicReflectionPercent); DECLARE_LUA_INTEGER(LunarMagicBlock); DECLARE_LUA_INTEGER(LunarDamageAbsorb); DECLARE_LUA_INTEGER(LunarDamageManaShield); // -------------- 毒性 ----------------------------------------------------------> int m_nSkillPoisonDamage; int m_nSkillPoisonDamageRand; int m_nSkillPoisonDamagePercent; int m_nPoisonDamageCoefficient; // 毒性内功伤害加成系数, 在伤害计算流程的最后会乘上这个系数(所取的数值是被伤害人身上的) int m_nPoisonAttackPower; int m_nPoisonAttackPowerBase; int m_nPoisonAttackPowerPercent; int m_nPoisonHitBaseRate; int m_nPoisonHitValue; int m_nPoisonCriticalStrikeBaseRate; int m_nPoisonCriticalStrike; int m_nPoisonCriticalStrikeBase; int m_nPoisonCriticalDamagePowerBaseKiloNumRate; // 增加会心伤害 int m_nPoisonCriticalDamagePower; int m_nPoisonCriticalDamagePowerBase; int m_nPoisonCriticalDamagePowerPercent; int m_nPoisonOvercome; // 克性 int m_nPoisonOvercomeBase; int m_nPoisonOvercomePercent; int m_nPoisonMagicResistPercent; // 抵抗百分比 int m_nPoisonMagicShield; // 防御力,这个数值最终会用来查表获得防御系数 int m_nPoisonMagicShieldBase; int m_nPoisonMagicShieldPercent; int m_nPoisonMagicReflection; int m_nPoisonMagicReflectionPercent; int m_nPoisonMagicBlock; int m_nPoisonDamageAbsorb; int m_nPoisonDamageManaShield; DECLARE_LUA_INTEGER(PoisonAttackPower); DECLARE_LUA_INTEGER(PoisonHitValue); DECLARE_LUA_INTEGER(PoisonHitBaseRate); DECLARE_LUA_INTEGER(PoisonCriticalStrike); DECLARE_LUA_INTEGER(PoisonCriticalStrikeBaseRate); DECLARE_LUA_INTEGER(PoisonCriticalDamagePowerBaseKiloNumRate); DECLARE_LUA_INTEGER(PoisonCriticalDamagePower); DECLARE_LUA_INTEGER(PoisonOvercome); DECLARE_LUA_INTEGER(PoisonMagicShield); DECLARE_LUA_INTEGER(PoisonMagicResistPercent); DECLARE_LUA_INTEGER(PoisonMagicReflection); DECLARE_LUA_INTEGER(PoisonMagicReflectionPercent); DECLARE_LUA_INTEGER(PoisonMagicBlock); DECLARE_LUA_INTEGER(PoisonDamageAbsorb); DECLARE_LUA_INTEGER(PoisonDamageManaShield); // ---------------------------- 治疗(生命回复) ------------------------------------------------- int m_nTherapyPower; int m_nTherapyPowerBase; // 基础治疗能力 int m_nTherapyPowerPercent; int m_nSkillTherapy; // 技能相关的治疗效果 int m_nSkillTherapyRand; int m_nSkillTherapyPercent; int m_nTherapyCoefficient; // 治疗效果加成系数, 在伤害计算流程的最后会乘上这个系数(所取的数值是被伤害人身上的) int m_nBeTherapyCoefficient; // 被治疗加成系数 DECLARE_LUA_INTEGER(TherapyPower); DECLARE_LUA_INTEGER(SkillTherapy); // --------------------------- 新手技能有关 ---------------------------------------------------- int m_nNoneWeaponAttackSpeedBase; // 空手时拳头的攻击速度 // 当人物身上没有装备近程武器时,就用m_nNoneWeaponAttackSpeedBase替代m_nMeleeWeaponAttackSpeedBase来计算 // m_nMeleeWeaponAttackSpeed的值. int m_nMeleeWeaponAttackSpeed; // 近战攻击速度, 单位 帧/次数 int m_nMeleeWeaponAttackSpeedBase; // 近战攻击速度基础, 单位 次数/(1024*帧),如果这个值为512,则就是说 512/1024 = 0.5次/帧 int m_nMeleeWeaponAttackSpeedPercentAdd; int m_nMeleeWeaponAttackSpeedAdditional; int m_nRangeWeaponAttackSpeed; // 远程攻击速度, 单位 帧/次数 int m_nRangeWeaponAttackSpeedBase; // 远程攻击速度基础, 单位 次数/帧 int m_nRangeWeaponAttackSpeedPercentAdd; int m_nRangeWeaponAttackSpeedAdditional; DECLARE_LUA_INTEGER(NoneWeaponAttackSpeedBase); DECLARE_LUA_INTEGER(MeleeWeaponAttackSpeed); DECLARE_LUA_INTEGER(MeleeWeaponAttackSpeedBase); DECLARE_LUA_INTEGER(MeleeWeaponAttackSpeedPercentAdd); DECLARE_LUA_INTEGER(MeleeWeaponAttackSpeedAdditional); DECLARE_LUA_INTEGER(RangeWeaponAttackSpeed); DECLARE_LUA_INTEGER(RangeWeaponAttackSpeedBase); DECLARE_LUA_INTEGER(RangeWeaponAttackSpeedPercentAdd); DECLARE_LUA_INTEGER(RangeWeaponAttackSpeedAdditional); // --------------------------------------------------------------------------------------------- int m_nIgnoreOtherAlarmRange; // 忽视他人(NPC)警戒范围 int m_nSelfAlarmRangeRevise; // 对自身警戒范围的修正; 一般用于NPC int m_nOtherAlarmRangeRevise; // 对他人警戒范围的修正 int m_nResistBehaveConstraintPercent; // 角色脱离现有行为受控状态的概率, 基数为1024 int m_nUnarmCounter; // -------------------------------- 禁魔相关 --------------------------------------------------- char m_nSilenceRefCounter[sktTotal - 1]; // 根据技能的 KindType 禁魔。 // -------------------------------- 免疫相关 --------------------------------------------------- std::bitset<sftTotal> m_ImmunityFlag;// 根据BUFF的 FunctionType 免疫。 // ------------------------------ 技能条件标志 ------------------------------------------------- DWORD m_dwSkillCastFlag; // --------------- 记录唯一作用的BUFF此时作用的角色ID ------------------------------------ DWORD m_dwBuffEffectSoleTargetID; public: // m_dwRepresentState描述了角色身上的魔法特效状态(其实是三个特效ID的组合), 一共描述了三个效果: // 1. 脚底下踩的. // 2. 身上缠绕的. // 3. 头上顶着的. BYTE m_byRepresentState[brpTotal]; BOOL GetRepresentState(KBUFF_REPRESENT_POS nPos, DWORD& rdwRepresentID); public: #ifdef _CLIENT KThreatList m_ThreatList; // 仇恨表 #endif //_CLIENT #ifdef _SERVER KSimpThreatList m_SimpThreatList; int m_nThreatTime; // 仇恨消退间隔 int m_nActiveBaseThreatCoefficient; // 主动产生的基础仇恨系数 int m_nActiveDamageThreatCoefficient; // 主动产生的伤害仇恨系数 int m_nActiveTherapyThreatCoefficient; // 主动产生的治疗仇恨系数 int m_nPassiveBaseThreatCoefficient; // 被动产生的基础仇恨系数 int m_nPassiveDamageThreatCoefficient; // 被动产生的伤害仇恨系数 int m_nPassiveTherapyThreatCoefficient; // 被动产生的治疗仇恨系数 int m_nOverThreatPercent; BOOL m_bToDie; DWORD m_dwKillerID; BOOL ModifyThreat(THREAT_TYPE eType, int nThreatValue); // 用于技能直接修改对方仇恨值 int AdjustThreat(THREAT_TYPE eTheatType, int nThreatValue); #endif //_SERVER int m_nBattleFieldSide; // 战场所属 DECLARE_LUA_INTEGER(BattleFieldSide); // 新AI相关 public: struct KCharacterAIData { int nAIType; int nOriginPosX; int nOriginPosY; int nOriginPosZ; int nOriginDirection; int nReturnPosX; int nReturnPosY; int nReturnPosZ; int nPatrolPathID; KPatrolPath* pPatrolPath; int nPatrolOrderIndex; int nEscapeCount; static DWORD dwAIEventSrc; static int nAIEventParam; static int nTargetGroupCount; int nCannotAttactCount; int nSkillFailedCount; int nSkillType; DWORD dwRespondCharacterID; // 记录呼叫者的ID int nAITotalDamageValue; DWORD dwProtectCampMark; // 受保护的阵营标记 DWORD dwProtectForceMark; // 受保护的势力标记(掩码) KTarget ChoiceTarget[aittTotal]; DWORD nRecordSkillID[airstTotal]; DWORD nRecordSkillLevel[airstTotal]; BOOL bSpecialSelectTarget; static KCharacter* TargetGroup[AI_TARGET_GROUP_MAX_COUNT]; } m_AIData; // DECLARE_LUA_DWORD(AIEventSrc); DWORD getAIEventSrc(void) {return m_AIData.dwAIEventSrc;}; // DECLARE_LUA_INTEGER(AIEventParam); DWORD getAIEventParam(void) {return m_AIData.nAIEventParam;}; // DECLARE_LUA_INTEGER(AITotalDamageValue); DWORD getAITotalDamageValue(void) {return m_AIData.nAITotalDamageValue;}; public: #ifdef _CLIENT BOOL PrepareSkill(DWORD dwSkillID, DWORD dwSkillLevel, KTarget& rTarget, int nPrepareFrame, int nEndFrame); #endif #ifdef _SERVER SKILL_RESULT_CODE CastSkill(DWORD dwSkillID, DWORD dwSkillLevel, KTarget& rTarget); SKILL_RESULT_CODE CastSkillSub(KCharacter* pLogicCaster, DWORD dwSkillID, DWORD dwSkillLevel, KTarget& rTarget); SKILL_RESULT_CODE CastSkillAccumulate(DWORD dwSkillID, DWORD dwSkillLevel, KTarget& rTarget); #else SKILL_RESULT_CODE CastSkill(DWORD dwSkillID, DWORD dwSkillLevel, KTarget& rTarget, DWORD dwBulletID); SKILL_RESULT_CODE CastSkillSub(KCharacter* pLogicCaster, DWORD dwSkillID, DWORD dwSkillLevel, KTarget& rTarget, DWORD dwBulletID); #endif BOOL ProcessCommonSkillActive(const KSKILL_RECIPE_KEY& crSkillRecipeKey); inline int GetWalkSpeed() { if (IS_PLAYER(m_dwID)) { return m_nRunSpeed * 6 / 20; } return m_nRunSpeed * 6 / 28; } // 强制停止状态(到Stand),不论原来是什么状态 BOOL Stop(void); // 该函数用于修正坐标范围 BOOL EmendateDestCoordinate(int& nDestX, int& nDestY); BOOL Stand(BOOL bSyncSelf); BOOL WalkTo(int nDestX, int nDestY, BOOL bBroadcast, int nWalkSpeed = 0); // 当WalkSpeed等于0时,取Character身上的走路速度 BOOL RunTo(int nDestX, int nDestY, BOOL bBroadcast, int nRunSpeed = 0); // 当RunSpeed等于0时,取Character身上的跑步速度 BOOL SwimTo(int nDestX, int nDestY, BOOL bBroadcast); BOOL Jump(BOOL bStandJump, int nJumpDirection, BOOL bSyncSelf); BOOL SitDown(BOOL bSyncSelf); BOOL AutoFly(int nFromNode, int nToCity); BOOL Dash(int nFrame, int nDirectionXY, int nVelocityXY, int nVelocityZ); BOOL Pull(int nFrame, int nDirectionXY, int nVelocityXY, int nVelocityZ); BOOL Repulsed(int nFrame, int nDirectionXY, int nVelocityXY); BOOL KnockedDown(int nFrame); BOOL KnockedBack(int nDirection, int nDistance, int nVelocityXY); BOOL KnockedOff(int nDirection, int nDistance, int nVelocityXY); BOOL Halt(); // 眩晕 BOOL Freeze(); // 定身 BOOL Entrap(); BOOL CheckDie(); // 死亡 BOOL Action(DWORD dwCharacterID, DWORD dwActionType); // 动作 BOOL TurnTo(int nNewDirection, BOOL bBroadcast); BOOL PitchTo(int nNewDirection, BOOL bBroadcast); BOOL MoveTo(int nX, int nY, int nZ, BOOL bIgnoreBlock, BOOL bBroadcast); BOOL GoToHell(DWORD dwKiller = ERROR_ID); const char* GetName(); protected: BOOL m_bOnTalk; // 是否正在和NPC对话 public: int m_nFearCounter; // 恐惧计数器 int m_nMoveFrameCounter; public: BOOL SelectTarget(TARGET_TYPE eTargetType, DWORD dwTargetID); KTarget m_SelectTarget; KTarget m_SkillTarget; public: BOOL CheckFear(); // 状态处理函数 BOOL OnStand(){ return true; } BOOL OnWalk(){ return true; } BOOL OnRun(){ return true; } BOOL OnJump(){ return true; } BOOL OnSwimJump(){ return true; } BOOL OnSit(){ return true; } BOOL OnPassiveMove(); BOOL OnDash(); BOOL OnPull(); BOOL OnRepulsed(); BOOL OnHalt(){ return true; } BOOL OnFreeze(){ return true; } BOOL OnEntrap(){ return true; } BOOL OnDeath(); BOOL OnRise(); BOOL OnSkid(); void SetMoveState(int nState); public: // ------------- 持续一段时间的行为 ----------------------> BOOL DoOTAction(KOT_ACTION_PARAM& rParam); void DoActionIdle(void); void DoAutoCastSkill(KAUTO_CAST_SKILL_PARAM& param); void DoAutoCastSkillIdle(void); BOOL DoSkillPrepare(KSkillRecipePointer& rSkillRecipePointer, int nPrepareFrame, int nEndFrame); BOOL DoSkillChannel(KSkillRecipePointer& rSkillRecipePointer, int nChannelFrame); BOOL DoRecipePrepare(KProfessionSkill* pProfessionSkill, int nFrame); BOOL DoPickPrepare(KDoodad* pDoodad, int nFrame); BOOL DoPicking(KDoodad* pDoodad); BOOL DoCustomOTActionPrepare(BOOL bIsBreakable, int nFrame, KTarget& crTarget, DWORD dwScriptID); BOOL DoCustomOTActionChannel(BOOL bIsBreakable, int nFrame, KTarget& crTarget, DWORD dwScriptID); KOT_ACTION_PARAM m_OTActionParam; KAUTO_CAST_SKILL_PARAM m_AutoCastSkillParam; // -------------- 对吟唱修改的掩码,和技能相对应 --------------> DWORD m_dwDirectCastMask; void ProcessOTAction(); void ProcessAutoCastSkill(); #ifdef _SERVER void DoAutoTurn(); // 技能自动朝向代码,不是Action状态机的组成部分 void DoSitDown(KDoodad* pDoodad); // 坐到一个Doodad上,与打坐不同,不改变移动状态,也不影响回血 #endif BOOL OnSkillPrepare(); BOOL OnSkillChannel(); BOOL OnRecipePrepare(); BOOL OnPickPrepare(); BOOL OnPicking(); void OnUseItemPrepare(); BOOL OnCustomOTActionPrepare(); BOOL OnCustomOTActionChannel(); BOOL OnBreakPickPrepare(KOT_ACTION_PARAM& rNewAction); BOOL OnBreakPicking(KOT_ACTION_PARAM& rNewAction); // <------------- 持续一段时间的行为 ---------------------- public: BOOL UpdateMoveParameter(); void InvalidateMoveState(int nDelayFrame, BOOL bMoveSyncSelf); void RecordPosition(KPOSITION_RECORD* pRecord); BOOL ReversePosition(KPOSITION_RECORD* pRecord); BOOL ForwardPosition(int nFrame); void ProcessMove(); private: void ProcessAutoFly(); int GetFrictionDirection(); BOOL ProcessAcceleration(); // 自身加速度计算 void ProcessHorizontalMove(); // 水平移动 void ProcessHorizontalMoveStupid(); void ProcessHorizontalMoveSmart(); void ProcessVerticalMove(); // 垂直移动 void ProcessDrowning(); BOOL CellMoveStupid(int nStepLength); BOOL CellMoveSmart(int nStepLength); int TryMove(int nStepLength, int nDirection, int* pnObstacleDirection); BOOL IgnoreDynamicObstacle(); void ProcessDynamicObstacle(); BOOL ProcessDropDamage(); BOOL ProcessDropSpeed(); BOOL CheckSlip(); int m_nMoveSyncFrame; BOOL m_bMoveSyncSelf; public: // 获取吃水深度, 在水中是,返回一个大于0的值表示吃水深度,否则返回0 // 吃水深度指水面与人物脚下的高度差 int GetWaterline(); // 获取人物主观的移动意愿方向 int GetSubjectiveDirection(); // 获取主观移动速度 int GetSubjectiveVelocity(); public: void ApplyAttribute(KAttribute* pAttr); void UnApplyAttribute(KAttribute* pAttr); BOOL CallAttributeFunction(int nKey, BOOL bApply, int nValue1, int nValue2); void UpdateAllState(); void UpdateWeaponAttackSpeed(); void UpdateBaseState(); // Life & Mana void UpdateAllAttackPowerValue(); void UpdateAllShieldValue(); void UpdateAllCriticalStrikeValue(); void UpdateAllBattleState(); BOOL SetForceID(DWORD dwForceID); int m_nNextReplenishFrame; void AttribReplenish(); void ReviseAttribValue(); void CheckFightFlag(); virtual BOOL ChangeRegion(KRegion* pRegion) = 0; // 处理角色的状态机 void RunStateMachine(); friend class KAIController; friend class KAIBase; friend class KSkill; friend class KBuffList; friend class KItemList; #ifdef _SERVER public: void AddBullet(KSKILL_BULLET* pBullet); BOOL ApplyBullet(KSKILL_BULLET *pBullet); void ClearBullet(); void CheckBullet(); void ProcessBullet(KSKILL_BULLET *pBullet); KSKILL_BULLET* m_pBulletListHead; private: KSKILL_HIT_RESULT JudgeSkillHit(KSKILL_BULLET* pBullet); #endif public: // 技能属性链表运算流程的参数 struct KSKILL_ATTRIBUTE_PARAM { KSkillRecipePointer SkillRecipePointer; DWORD dwSkillSrcID; int nSkillSrcLevel; KCharacter* pSkillSrc; KCharacter* pSkillDst; BOOL bCriticalStrike; // 是否暴击 BOOL bParray; // 是否被招架 BOOL bInsight; // 是否被识破 // 发技能者的参数,伤害计算时要用,特别是Dot KSKILL_BULLET* pBullet; int nPhysicsDamage; // 外功伤害点数 int nSolarDamage; // 阳性内功伤害 int nNeutralDamage; // 中性内功伤害 int nLunarDamage; // 阴性内功伤害 int nPoisonDamage; // 毒性伤害点数 int nDamgeToLifeForSelf; // 偷取对方生命点数 int nDamgeToManaForSelf; // 偷取对方内力点数 int nTherapy; // 治疗能力 int nCriDamagePower; // 暴击的伤害加成 int nBaseThreatCoefficient; int nDamageThreatCoefficient; int nTherapyThreatCoefficient; BOOL bDot; int nStackNum; int nDamageAddPercent; // 技能秘笈对伤害的加成,不分类型。 DWORD dwAddDamageByDstMoveStateMask; int nAddDamagePercentByDstMoveState; }; KSKILL_ATTRIBUTE_PARAM* m_pSkillAttributeParam; KSKILL_CALCULATE_RESULT* m_pSrcSkillCalculateResult; KSKILL_CALCULATE_RESULT* m_pDstSkillCalculateResult; int m_nSkillStackDepth; // 该结构用于抽象不同类型的伤害运算参数 struct KDAMAGE_CALCULATE_PARAM { KCharacter* pSkillSrc; BOOL bCriticalStrikeFlag; // 是否暴击 int nDamageValue; // 攻击数值 int nDstResistPercent; // 抗性百分比 int nDstDefenceCoefficient; // 防御系数 int* pnDstMaxTypedDamageAbsorb; // 有类型的伤害吸收 int* pnDstMaxTypedDamageManaShield; // 有类型的ManaShield int nDstPointReflection; // 点数反弹 int nDstPercentReflection; // 百分比反弹 int nDamageToLifeForSrc; // 伤害转化为释放者的生命 int nDamageToManaForSrc; // 伤害转化为释放者的内力 int nDamageToLifeForSrcTeam; // 伤害转化为释放者的小队所有成员的生命 int nDamageToManaForSrcTeam; // 伤害转化为释放者的小队所有成员的内力 int* pnDstTypedDamage; // 对目标的有类型伤害存放到这里 int nDstTypedDamageCoefficient; }; // 击倒 BOOL ProcessKnockedDown(int nFrame); // 击退 BOOL ProcessKnockedBackExhale(int nDistance, int nVelocityXY); // 水平方向上被击退(方向背向着技能释放者) BOOL ProcessKnockedBackConvergence(int nDistance, int nVelocityXY); // 水平方向上被击退(方向向着技能释放者) BOOL ProcessKnockedBackRandom(int nDistance, int nVelocityXY); // 水平方向上被击退(方向随机) BOOL ProcessKnockedBackSrcFace(int nDistance, int nVelocityXY); // 水平方向上被击退(方向为技能释放者的朝向) // 击飞 BOOL ProcessKnockedOffParabola(int nDistance, int nVelocityXY); // 呈抛物线被击飞(水平上的方向向着技能释放者) // 被抓到身边 BOOL ProcessPull(KCharacter* pCharacter, int nVelocityXY); // 滑步处理 BOOL ProcessRepulsed(int nFrame); // 恐惧 BOOL ProcessFear(int nDistance); // 复活 BOOL ProcessRevive(int nLife, int nMana); BOOL ProcessTherapy(int nTherapyValue); BOOL ProcessDamage(int nDamageType, int nDamageValue); BOOL ConcludeResult(DWORD dwBulletID, BOOL bCriticalStrikeFlag, int* pnRetDamageValue); private: BOOL CalculateDamage(const KDAMAGE_CALCULATE_PARAM &crParam); public: KBuffList m_BuffList; public: #ifdef _SERVER typedef std::vector<KUSER_SKILL_EVENT> KUSER_SKILL_EVENT_VECTOR; KUSER_SKILL_EVENT_VECTOR m_SkillEventVector; // 注意: "KUSER_SKILL_EVENT_VECTOR SkillEvent"不是引用传值是故意这样写的 // 因为技能事件处罚技能可能去修改原来的Vector void OnSkillEvent( KSkill* pSkill, int nEventType, KUSER_SKILL_EVENT_VECTOR SkillEvent, KCharacter* pCaster, KCharacter* pTarget ); void CheckBeatBreak(KSkill* pSkill); // 打断, 现在只对通道技有效 void CheckBeatBack(); #endif void OnOTActionBeatBack(int nFrame); void OnDamage(KCharacter* pAttackter, int nDamage); DWORD GetMapID(); BOOL CanDialog(KCharacter* pCharacter); BOOL CanDoAction(KCharacter* pCharacter, DWORD dwAction); #ifdef _SERVER // 设置隐身、现身 void Stealth(BOOL bStealthy); #endif #ifdef _SERVER public: int m_nLastBroadcastLife; #endif // -------------------------- 调试 ---------------------------------------------> KSkillDebug m_SkillDebug; int LuaAttach(Lua_State* L); int LuaDetach(Lua_State* L); int LuaDetachAll(Lua_State* L); // <----------------------------------------------------------------------------- KAIVM m_AIVM; public: // 脚本接口函数 int LuaSetModelID(Lua_State* L); int LuaSetTarget(Lua_State* L); int LuaGetTarget(Lua_State* L); int LuaGetSkillTarget(Lua_State* L); int LuaCastSkillXYZ(Lua_State* L); int LuaCastSkill(Lua_State* L); void HostStand(); void HostJump(BOOL bStandJump, int nDirectionXY); void HostDash(int nDirection, int nDistance, int nVelocityXY); void HostTurnTo(int nNewDirection); void HostPitchTo(int nNewDirection); int LuaAutoFly(Lua_State* L); int LuaStop(Lua_State* L); int LuaStand(Lua_State* L); int LuaRunTo(Lua_State* L); int LuaWalkTo(Lua_State* L); int LuaSwimTo(Lua_State* L); int LuaJump(Lua_State* L); int LuaDash(Lua_State* L); int LuaTurnTo(Lua_State* L); int LuaPitchTo(Lua_State* L); int LuaPatrol(Lua_State* L); int LuaSitDown(Lua_State* L); int LuaDie(Lua_State* L); int LuaDoAction(Lua_State* L); int LuaGetAIType(Lua_State* L); int LuaSetAIType(Lua_State* L); int LuaSetAIDebug(Lua_State* L); int LuaSetAIProtectCampMarkAndForceMark(Lua_State* L); #ifdef _CLIENT int LuaGetBuffList(Lua_State* L); #endif int LuaCancelBuff(Lua_State* L); int LuaSetSheath(Lua_State* L); int LuaGetMapID(Lua_State* L); int LuaCanDialog(Lua_State* L); #ifdef _SERVER int LuaAddBuff(Lua_State* L); int LuaGetBuff(Lua_State* L); int LuaDelBuff(Lua_State* L); int LuaDelGroupBuff(Lua_State* L); int LuaDelMultiGroupBuffByFunctionType(Lua_State* L); int LuaSetBuffNextActiveFrame(Lua_State* L); int LuaSetBuffLeftActiveCount(Lua_State* L); int LuaClearAllThreat(Lua_State* L); int LuaSetForceID(Lua_State* L); int LuaSetPosition(Lua_State* L); #endif int LuaFireAIEvent(Lua_State* L); #ifdef _SERVER int LuaSetCustomInteger4(Lua_State* L); int LuaGetCustomInteger4(Lua_State* L); int LuaSetCustomInteger2(Lua_State* L); int LuaGetCustomInteger2(Lua_State* L); int LuaSetCustomInteger1(Lua_State* L); int LuaGetCustomInteger1(Lua_State* L); int LuaSetCustomUnsigned4(Lua_State* L); int LuaGetCustomUnsigned4(Lua_State* L); int LuaSetCustomUnsigned2(Lua_State* L); int LuaGetCustomUnsigned2(Lua_State* L); int LuaSetCustomUnsigned1(Lua_State* L); int LuaGetCustomUnsigned1(Lua_State* L); int LuaSetCustomBoolean(Lua_State* L); int LuaGetCustomBoolean(Lua_State* L); // 偏移量, 第几个Bit(从左到右, 从0开始计数), 数值为true/false int LuaSetCustomBitValue(Lua_State* L); int LuaGetCustomBitValue(Lua_State* L); int LuaSetCustomString(Lua_State* L); int LuaGetCustomString(Lua_State* L); #endif int LuaGetSkillPrepareState(Lua_State* L); #ifdef _SERVER int LuaTraceSelectTargetThreat(Lua_State* L); #endif int LuaSetAIOriginPos(Lua_State* L); int LuaGetAIOriginPos(Lua_State* L); #ifdef _SERVER // 设置隐身、现身的接口 int LuaStealth(Lua_State* L); #endif }; int g_GetRelation(KCharacter* pSrcCharacter, KCharacter* pDstCharacter); size_t PainText2TalkData(size_t uBuffSize, BYTE* pbyBuff, const char cszText[]); #endif //_KCHARACTER_H_
[ "dark.hades.1102@GAMIL.COM" ]
dark.hades.1102@GAMIL.COM
bc5cf50a7548a29ee2c27f77359ae6b32da7a391
8f4ae9007524454e1d1b29da1b9e09efa9782056
/Petya and Strings/main.cpp
73822a3681703a1888e20011275293ad1d9485b9
[]
no_license
MasterIceZ/Codeforces
9f34edc633a74a265e1b0cc344b1038f21f01684
d01718dc350eb18de6891ec264fb656b1a772f28
refs/heads/master
2023-02-02T14:06:51.463838
2020-12-19T14:36:18
2020-12-19T14:36:18
285,296,287
0
0
null
2020-12-19T14:36:19
2020-08-05T13:28:46
C++
UTF-8
C++
false
false
449
cpp
#include <iostream> #include <string> using namespace std; int32_t main (){ string s,t; cin >> s; cin >> t; for(int i=0; i<s.length(); ++i){ s[i]=tolower(s[i]); } for(int i=0; i<t.length(); ++i){ t[i]=tolower(t[i]); } if(s==t){ cout << "0" << endl; } else if(s>t){ cout << "1" << endl; } else{ cout << "-1" << endl; } return 0; }
[ "mastericez890@gmail.com" ]
mastericez890@gmail.com
57f3c6b8e01c5929154b29bc6c79c1ce297c27dc
511b50d5f2ee844c6e85e834c7ab901c8aeafcc6
/Source/charlee/Enemy.cpp
eb6964aa0bf0c6137d6ab6a5df2711b30147e62c
[]
no_license
cherleey/charlee
195eaed53cfe3d9032d29a0084e8a9dc02b313f0
0d2527a76a94b299bc532fe06a323f27e4fd98ee
refs/heads/master
2021-01-23T16:50:20.162941
2017-09-14T01:17:52
2017-09-14T01:17:52
102,745,133
0
0
null
null
null
null
UTF-8
C++
false
false
8,595
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "Enemy.h" #include "MeleeWeapon.h" #include "RespawnPoint.h" #include "EngineUtils.h" // Sets default values AEnemy::AEnemy() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; SightSphere = CreateDefaultSubobject<USphereComponent>(TEXT("SightSphere")); SightSphere->OnComponentBeginOverlap.AddDynamic(this, &AEnemy::OnSightOverlapBegin); SightSphere->AttachTo(RootComponent); AttackRangeSphere = CreateDefaultSubobject<USphereComponent>(TEXT("AttackRangeSphere")); AttackRangeSphere->OnComponentBeginOverlap.AddDynamic(this, &AEnemy::OnAttackRangeOverlapBegin); AttackRangeSphere->OnComponentEndOverlap.AddDynamic(this, &AEnemy::OnAttackRangeOverlapEnd); AttackRangeSphere->AttachTo(RootComponent); RespawnPoint = NULL; MeleeWeapon = NULL; RangeWeapon = NULL; BPMeleeWeapon = NULL; BPRangeWeapon = NULL; } // Called when the game starts or when spawned void AEnemy::BeginPlay() { Super::BeginPlay(); AttackAnimTime = 1.5f; MaxHp = 100.f; Hp = MaxHp; Damage = 1; AttackTimeout = 0; RangeAttackTimeout = 2.3f; AttackAnimTimeout = 1.5f; RangeAttackAnimTimeout = 1.f; eState = IDLE; Target = NULL; RangeTarget = NULL; bAttacking = false; bInSight = false; bInAttackRange = false; OriginLocation = this->GetActorLocation(); for (TActorIterator<AActor> ActorItr(GetWorld()); ActorItr; ++ActorItr) { if (ActorItr->GetName().Contains(TEXT("Respawn"))) { RespawnPoint = Cast<ARespawnPoint>(*ActorItr); } } } // Called every frame void AEnemy::Tick(float DeltaTime) { Super::Tick(DeltaTime); SwitchState(DeltaTime); CheckAlly(); if (RangeWeapon && bAttacking) { if (!RayCast() || Target->GetName().Contains(TEXT("Enemy"))) return; RangeAttackTime += DeltaTime; if (RangeAttackTime >= RangeAttackTimeout) { AGunEffect* Effect = GetWorld()->SpawnActor<AGunEffect>(BPGunEffect, ImpactPoint, FRotator(0)); RangeTarget->TakeDamage(Damage + RangeWeapon->GetDamage(), FDamageEvent(), this->GetInstigatorController(), this); RangeAttackTime = 0; } } } // Called to bind functionality to input void AEnemy::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); } void AEnemy::MoveTo(AActor * OtherActor, float DeltaTime) { if (!Target) return; FVector Dir = Target->GetActorLocation() - GetActorLocation(); Dir.Normalize(); FRotator Rotation = Dir.Rotation(); Rotation.Pitch = 0; AddMovementInput(Dir, Speed * DeltaTime); RootComponent->SetWorldRotation(Rotation); } void AEnemy::Rotate() { FVector Dir = Target->GetActorLocation() - GetActorLocation(); Dir.Normalize(); FRotator Rotation = Dir.Rotation(); Rotation.Pitch = 0; RootComponent->SetWorldRotation(Rotation); } void AEnemy::OnSightOverlapBegin_Implementation(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult &SweepResult) { if (OtherActor->GetName().Contains(TEXT("Enemy"))) Ally.Add(Cast<AEnemy>(OtherActor)); if (!OtherActor->GetName().Contains(TEXT("Avatar"))) return; if (OtherActor != NULL && OtherActor != this && OtherComp != NULL && eState != RUN) { bInSight = true; Target = OtherActor; } } void AEnemy::OnAttackRangeOverlapBegin_Implementation(UPrimitiveComponent * OverlappedComp, AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult) { if (!OtherActor->GetName().Contains(TEXT("Avatar"))) return; if (OtherActor != NULL && OtherActor != this && OtherComp != NULL && eState != ATTACK) { bInAttackRange = true; Target = OtherActor; } } void AEnemy::OnAttackRangeOverlapEnd_Implementation(UPrimitiveComponent * OverlappedComp, AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 OtherBodyIndex) { if (!OtherActor->GetName().Contains(TEXT("Avatar"))) return; if (OtherActor != NULL && OtherActor != this && OtherComp != NULL) bInAttackRange = false; } bool AEnemy::IsAttacking() { return bAttacking; } void AEnemy::PostInitializeComponents() { Super::PostInitializeComponents(); if (BPMeleeWeapon) { Speed = 250.f; MeleeWeapon = GetWorld()->SpawnActor<AMeleeWeapon>(BPMeleeWeapon); if (BPMeleeWeapon) { const USkeletalMeshSocket* socket = this->GetMesh()->GetSocketByName("RightHandSocket"); socket->AttachActor((AActor*)MeleeWeapon, this->GetMesh()); MeleeWeapon->WeaponHolder = this; } } if (BPRangeWeapon) { Speed = 100.f; RangeWeapon = GetWorld()->SpawnActor<APistol>(BPRangeWeapon, this->GetActorLocation(), this->GetActorRotation()); if (BPRangeWeapon) { const USkeletalMeshSocket* socket = this->GetMesh()->GetSocketByName("RightHandSocketForRange"); socket->AttachActor((AActor*)RangeWeapon, this->GetMesh()); } } } void AEnemy::SwitchState(float DeltaTime) { if (!bInSight && !bInAttackRange && !Target) eState = IDLE; else if (bInSight && !bInAttackRange) { eState = RUN; DEBUG(Log, asdf); } else if (bInSight && bInAttackRange) eState = ATTACK; switch (eState) { case IDLE: MoveTo(Target, DeltaTime); bAttacking = false; break; case RUN: if (MeleeWeapon) { if (AttackAnimTime < AttackAnimTimeout && bAttacking) { AttackAnimTime += DeltaTime; break; } else { MoveTo(Target, DeltaTime); bAttacking = false; AttackAnimTime = 0; break; } } else { if (AttackAnimTime < RangeAttackAnimTimeout && bAttacking) { AttackAnimTime += DeltaTime; break; } else { MoveTo(Target, DeltaTime); bAttacking = false; AttackAnimTime = 0; break; } } case ATTACK: if (MeleeWeapon) { AttackAnimTime += DeltaTime; bAttacking = true; if (AttackAnimTime >= AttackAnimTimeout) AttackAnimTime = 0; Rotate(); break; } else { AttackAnimTime += DeltaTime; bAttacking = true; if (AttackAnimTime >= RangeAttackAnimTimeout) AttackAnimTime = 0; Rotate(); break; } case HIT: bAttacking = false; break; case DIE: bAttacking = false; break; } } void AEnemy::SwordSwing() { if (MeleeWeapon) MeleeWeapon->Swing(); } float AEnemy::TakeDamage(float DamageAmount, FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser) { //const float ActualDamage = Super::TakeDamage(Damage, DamageEvent, EventInstigator, DamageCauser); if (DamageAmount >= 0) { if (!Target) Target = DamageCauser; Hp -= DamageAmount; } if (Hp <= 0) SetHidden(true); return DamageAmount; } void AEnemy::SetHidden(bool bHidden) { this->SetActorEnableCollision(!bHidden); this->SetActorHiddenInGame(bHidden); if(MeleeWeapon) { MeleeWeapon->SetActorEnableCollision(!bHidden); MeleeWeapon->SetActorHiddenInGame(bHidden); } if (RangeWeapon) { RangeWeapon->SetActorEnableCollision(!bHidden); RangeWeapon->SetActorHiddenInGame(bHidden); } if (bHidden) { Target = NULL; Hp = MaxHp; this->SetActorLocation(OriginLocation); RespawnPoint->DecreaseActiveCount(); eState = IDLE; bInAttackRange = false; bInSight = false; Ally.Empty(); } } AEnemy::STATE AEnemy::GetState() { return eState; } void AEnemy::CheckAlly() { if (Ally.Num() == 0 || Target) return; auto iter = Ally.CreateIterator(); for (; iter; ++iter) { if (eState == IDLE) Target = (*iter)->GetTarget(); } } AActor * AEnemy::GetTarget() { return Target; } AMeleeWeapon * AEnemy::GetMeleeWeapon() { return MeleeWeapon; } APistol* AEnemy::GetRangeWeapon() { return RangeWeapon; } bool AEnemy::RayCast() { FHitResult RV_Hit(ForceInit); FCollisionQueryParams RV_TraceParams = FCollisionQueryParams(FName(TEXT("RV_Trace")), true, this); RV_TraceParams.bTraceComplex = true; RV_TraceParams.bTraceAsyncScene = true; RV_TraceParams.bReturnPhysicalMaterial = true; RV_TraceParams.AddIgnoredActor(this); FVector Start = this->GetActorLocation() + (this->GetActorRotation().Vector()); FVector End = this->GetActorLocation() + (this->GetActorRotation().Vector() * 10000); bool bTraced = GetWorld()->LineTraceSingleByChannel(RV_Hit, Start, End, ECC_Pawn, RV_TraceParams); if (bTraced) { RangeAttackTime += GetWorld()->DeltaTimeSeconds; ImpactPoint = RV_Hit.ImpactPoint; RangeTarget = RV_Hit.GetActor(); } return bTraced; } bool AEnemy::IsMelee() { if (MeleeWeapon) return true; else return false; }
[ "31400524+cherleey@users.noreply.github.com" ]
31400524+cherleey@users.noreply.github.com
f47e3249fb5aa0961cd07dff4419166fb38d53cb
5d90665826eaaf50da6bebc7d83cee121f2696e1
/(2020.10.01)SIMPLE_GAME_SERVER2/cAcceptor.cpp
42680b0c6314fb60609498e00ea7c2e300dac54a
[]
no_license
leewonbae/Server
7a1c1225f556bd0e66a47bfa23d1f21bcd3e5523
6bd9dcf74c6536eb5c4ce675f4ffce6396b77112
refs/heads/master
2023-01-16T08:00:44.324343
2020-11-25T05:57:58
2020-11-25T05:57:58
293,429,337
0
0
null
null
null
null
UTF-8
C++
false
false
696
cpp
#include "cAcceptor.h" cAcceptor::cAcceptor() { } cAcceptor::~cAcceptor() { } void cAcceptor::InitServer() { WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); mListensock = socket(AF_INET, SOCK_STREAM, 0); SOCKADDR_IN serveraddr; serveraddr.sin_family = AF_INET; serveraddr.sin_port = htons(PORT); serveraddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY); bind(mListensock, (SOCKADDR*)&serveraddr, sizeof(serveraddr)); listen(mListensock, SOMAXCONN); } SOCKET cAcceptor::Accept_client() { SOCKADDR_IN clientaddr; int len = sizeof(clientaddr); SOCKET clientsock = accept(mListensock, (SOCKADDR*)&clientaddr, &len); return clientsock; }
[ "noreply@github.com" ]
leewonbae.noreply@github.com
1a467582625329bd4ba70becc361614c177ed95c
011006ca59cfe75fb3dd84a50b6c0ef6427a7dc3
/codeforces/practice/D_Ehab_s_Last_Corollary.cpp
ddffcf85f3397623eb7fb2cc965e4022023c5e9c
[]
no_license
ay2306/Competitive-Programming
34f35367de2e8623da0006135cf21ba6aec34049
8cc9d953b09212ab32b513acf874dba4fa1d2848
refs/heads/master
2021-06-26T16:46:28.179504
2021-01-24T15:32:57
2021-01-24T15:32:57
205,185,905
5
3
null
null
null
null
UTF-8
C++
false
false
1,422
cpp
// Um_nik's approach // We just consider first k nodes // Either there is a cycle, in which case we print it // Other these nodes are tree and we just print odd height or even height #include<bits/stdc++.h> using namespace std; const int N = 1e5+10; int a,b,n,m,k,par[N],lev[N]; vector<int> g[N]; void dfs(int s){ lev[s] = lev[par[s]] + 1; for(int i: g[s]){ if(i == par[s])continue; if(lev[i] == 0){ par[i] = s; dfs(i); }else{ int endingPoint = i; int cur = s; while(1){ vector<int> ans; while(true){ ans.emplace_back(cur); if(cur == endingPoint)break; cur = par[cur]; } cout << "2 " << ans.size() << "\n"; for(int i: ans)cout << i << " "; exit(0); } } } } int main(){ cin >> n >> m >> k; for(int i = 0; i < m; ++i){ cin >> a >> b; if(a > k || b > k)continue; g[a].emplace_back(b); g[b].emplace_back(a); } for(int i = 1; i <= k; ++i)if(!lev[i])dfs(i); vector<int> ans[2]; for(int i = 1; i <= k; ++i)ans[lev[i]&1].emplace_back(i); if(ans[0].size() < ans[1].size())swap(ans[1],ans[0]); ans[0].resize((k+1)/2); cout << "1\n"; for(int i: ans[0])cout << i << " "; return 0; }
[ "mahajan.ayush2306@gmail.com" ]
mahajan.ayush2306@gmail.com
56ffc8158ffd1e34c0765e35728901812c1935c3
dc61e8c951f9e91930c2edff8a53c32d7a99bb94
/src/core/processors/processorfactory.cpp
4ff216a3cf6d993eb24eac6dc4eb385352e23103
[ "BSD-2-Clause" ]
permissive
johti626/inviwo
d4b2766742522d3c8d57c894a60e345ec35beafc
c429a15b972715157b99f3686b05d581d3e89e92
refs/heads/master
2021-01-17T08:14:10.118104
2016-05-25T14:38:33
2016-05-25T14:46:31
31,444,269
2
0
null
2015-02-27T23:45:02
2015-02-27T23:45:01
null
UTF-8
C++
false
false
2,513
cpp
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2012-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY 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 <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/common/inviwomodule.h> #include <inviwo/core/processors/processorfactory.h> #include <inviwo/core/io/serialization/serializable.h> #include <inviwo/core/util/stringconversion.h> namespace inviwo { bool ProcessorFactory::registerObject(ProcessorFactoryObject* processor) { if (!StandardFactory<Processor, ProcessorFactoryObject>::registerObject(processor)) { LogWarn("Processor with class name: " << processor->getClassIdentifier() << " is already registerd"); return false; } if (splitString(processor->getClassIdentifier(), '.').size() < 3) { LogWarn( "All processor classIdentifiers should be named using reverse DNS " "(org.inviwo.processor) not like: " << processor->getClassIdentifier()) } return true; } } // namespace
[ "eriksunden85@gmail.com" ]
eriksunden85@gmail.com
00bc89b85991ddb5082ee4022b6e834d1814086d
e925668933da9be726221594e2c834bea1508134
/POJ_3468/poj3468.cpp
3d84de3e224bccdea2b8e650e0eaeb746cf9259a
[]
no_license
XuZhichao1998/SegmentTree-kuangbin
a483b5fdc2d82f327a10ccf49047e23bd3c72a76
439c14f0a2a1199ea9b206c9c71e0e3b2f1aea36
refs/heads/main
2023-03-08T00:55:07.607598
2021-02-23T02:55:12
2021-02-23T02:55:12
341,401,734
1
0
null
null
null
null
UTF-8
C++
false
false
4,206
cpp
#include <iostream> #include <cstdio> #include <vector> #include <string> const int MAX_NODE_COUNT = 262141+5; //经过测试,长度小于100000的数组建树需要的最大节点个数为262141 const int ROOT_INDEX = 1; class SegmentTree { public: void init(int arr_length, int max_length); void input_array(int array_size); void build(int left, int right, int rt); long long update(int left, int right, int rt, int update_left, int update_right, int add); long long query(int left, int right, int rt, int query_left, int query_right); private: std::vector<long long> sum; std::vector<long long> lazy; std::vector<int> arr; void push_down(int rt, int left, int right); }; void SegmentTree::init(int arr_length, int max_length) { arr.resize(arr_length+1); sum.resize(max_length); lazy.resize(max_length); } void SegmentTree::input_array(int array_size) { for (int i = 1; i <= array_size; ++i) { std::cin>>arr[i]; } } void SegmentTree::build(int left,int right,int rt) { lazy[rt] = 0; if (left == right) { sum[rt] = arr[right]; return; } int mid = (left + right) >> 1; build(left, mid, rt<<1); build(mid+1, right, rt<<1|1); sum[rt] = sum[rt<<1] + sum[rt<<1|1]; return; } long long SegmentTree::update(int left, int right, int rt, int update_left, int update_right, int add) { if (update_left > right || update_right < left) { return sum[rt]; } if(update_left <= left && right <= update_right) { sum[rt] += 1ll * add * (right - left + 1); lazy[rt] += add; return sum[rt]; } int mid = (left + right) >> 1; push_down(rt, left, right); long long sum_lson = update(left, mid, rt<<1, update_left, update_right, add); long long sum_rson = update(mid+1, right, rt<<1|1, update_left, update_right, add); return sum[rt] = sum_lson + sum_rson; } long long SegmentTree::query(int left, int right, int rt, int query_left, int query_right) { if (query_left > right || query_right < left) { return 0; } if (query_left <= left && right <= query_right) { return sum[rt]; } int mid = (left + right) >> 1; push_down(rt, left, right); long long sum_lson = query(left, mid, rt<<1, query_left, query_right); long long sum_rson = query(mid+1, right, rt<<1|1, query_left, query_right); return sum_lson + sum_rson; } void SegmentTree::push_down(int rt,int left,int right) { if (lazy[rt] != 0) { int mid = (left + right) >> 1; int lson = rt << 1; int rson = rt << 1 | 1; lazy[lson] += lazy[rt]; lazy[rson] += lazy[rt]; sum[lson] += lazy[rt] * (mid - left + 1); sum[rson] += lazy[rt] * (right - mid); lazy[rt] = 0; } } void getMaxSize(int left,int right,int rt,int & maxx) { maxx = std::max(maxx,rt); if (left == right) { return; } int mid = (left + right) >> 1; getMaxSize(left,mid,rt<<1,maxx); getMaxSize(mid+1,right,rt<<1|1,maxx); } int getMinSize(int n) { int maxx = 0; getMaxSize(1,n,1,maxx); return maxx; } int main(int argc,const char * argv[]) { // freopen("in.txt", "r", stdin); std::ios::sync_with_stdio(false); std::cin.tie(0); SegmentTree * ptree = new SegmentTree(); ptree->init(100000, MAX_NODE_COUNT); int arr_length, query_count; while (std::cin>>arr_length>>query_count) { ptree->input_array(arr_length); ptree->build(1,arr_length,ROOT_INDEX); std::string op; while (query_count--) { std::cin>>op; if (op == "Q") { int qleft; int qright; std::cin>>qleft>>qright; std::cout<<ptree->query(1, arr_length, ROOT_INDEX, qleft, qright)<<"\n"; } else if (op == "C") { int update_left; int update_right; int add_val; std::cin>>update_left>>update_right>>add_val; ptree->update(1, arr_length, ROOT_INDEX, update_left, update_right, add_val); } } } delete ptree; return 0; }
[ "xuzhichao01@baidu.com" ]
xuzhichao01@baidu.com
5a4771ab0dd26a11a0a08f568dbb2b0c0b40c58f
29e758cd2f43b4a4a306753c648f4db84f525d28
/Assignments/Assignment 4/Gaddis_8thEd_Ch5_Menu/main.cpp
5259b47c93a52ff0da79f0d5c3196fa65e2ebefe
[]
no_license
js2664118/StanleyJonathan_CSCCIS5_Spring2018
eb023fb18f62990b0050844d3fd41fea53547fe2
a8cd8de61b28b37e05040748d2543e2e9ebd2919
refs/heads/master
2021-04-09T11:26:04.292846
2018-06-05T18:07:59
2018-06-05T18:07:59
125,410,445
0
0
null
null
null
null
UTF-8
C++
false
false
5,214
cpp
/* * File: main.cpp * Author: Jonathan Stanley * Created on March 15, 2018, 12:30 PM * Purpose: Menu for all ten Chapter 4 problems */ //System Libraries Here #include <iostream> #include <cstdlib> #include <iomanip> #include <cmath> using namespace std; //User Libraries Here //Global Constants Only, No Global Variables //Like PI, e, Gravity, or conversions //Function Prototypes Here //Program Execution Begins Here int main(int argc, char** argv) { //Declare all Variables Here int choice; //Variable to hold users choice int cont; //Variable to ask the user if they want to continue //Input or initialize values Here do { cout<<"Which problem would you like to see?"<<endl; cout<<"Enter 1 for Sums of Numbers"<<endl; cout<<"Enter 2 for Ocean Levels"<<endl; cout<<"Enter 3 for Calories Burned"<<endl; cout<<"Enter 4 for Membership Fees"<<endl; cout<<"Enter 5 for Distance Traveled"<<endl; cout<<"Enter 6 for Pennies for Pay"<<endl; cout<<"Enter 7 for Celsius to Fahrenheit"<<endl; cout<<"Enter 8 for "<<endl; cout<<"Enter 9 for "<<endl; cin>>choice; //Process/Calculations Here switch (choice){ case 1:{ //Declare all Variables Here int num; //Variable to hold the number that the user enters int total; //Variable to hold the total of sums //Input or initialize values Here cout<<"Please enter a non-negative number between 1 and 50"<<endl; cin>>num; while (num<1||num>50){ cout<<"Please enter a valid number between 1 and 50"<<endl; cin>>num; } for (int count=0;count<=num;count++){ total+=count; } //Process/Calculations Here cout<<"The sum of the number up to "<<num<<" is "<<total<<endl; //Exit break; } case 2:{ //Declare all Variables Here float level=1.5; //How much the ocean level is rising float total; //Hold the total for what ocean levels will be //Process/Calculations Here for (int count=1;count<=25;count++){ total+=level; cout<<"The ocean level has risen by "<<total<<" millimeters after "<<count<<" year(s)"<<endl; } //Exit break; } case 3:{ //Declare all Variables Here float cal=3.6; //Variable to hold the amount of calories burned per min. float calburn; //Variable to hold the amount of calories burned int min=5; //Variable to hold how many minutes have passed //Process/Calculations Here for (int count=1;count<=6;count++){ calburn=cal*count; cout<<"You burned "<<calburn<<" after "<<min<<" minute(s)"<<endl; min+=5; } //Exit break; } case 4:{ //Declare all Variables Here int fees=2500; //Variable to hold the original membership fee float inc=1.04; //Variable to hold the percentage difference float rate; //Variable to hold difference in money //Process/Calculations Here for (int count=1;count<=6;count++){ rate=fees*inc; cout<<"The new membership fee after "<<count<<" year(s) is "<<rate<<endl; inc+=0.04; } //Exit break; } case 5:{ //Declare all Variables Here int speed; //Variable to hold how fast the user is going int hours; //Variable to hold how many hours traveled int dist; //Distance traveled //Input or initialize values Here cout<<"What was the speed of the vehicle in MPH"<<endl; cin>>speed; cout<<"How many hours has the vehicle been traveling"<<endl; cin>>hours; for (int count=1;count<=hours;count++){ dist=speed*count; cout<<"Distance Traveled "<<dist<<" miles over "<<count<<" hour(s)"<<endl; } //Process/Calculations Here //Exit break; } case 6:{ //Declare all Variables Here float penny=0.01; //Value of penny int days; //Number of days worked float total=0.01; //Total amount of pay //Input or initialize values Here cout<<"Please enter the number of days worked"<<endl; cin>>days; //Process/Calculations Here cout<<setprecision(2)<<fixed<<showpoint<<endl; for (int count=1;count<=days;count++){ cout<<"On day "<<count<<" you earned $"<<penny<<" with a Total= "<<total<<endl; penny*=2; total+=penny; } //Exit break; } case 7:{ //Declare all Variables Here float celsius,fahr; //to hold Celsius and Fahrenheit temperatures //Input or initialize values Here celsius=0; //Process/Calculations Here for (int count=1;count<=20;count++){ fahr=(celsius*1.8)+32; cout<<"Celsius = "<<celsius<<" Fahrenheit = "<<fahr<<endl; celsius++; } //Exit break; } case 8:{} case 9:{} } cout<<"Would you like to see another problem? Enter 1 for yes and 2 for no"<<endl; cin>>cont; }while (cont!=2); //Exit return 0; }
[ "jmstanley6165@gmail.com" ]
jmstanley6165@gmail.com
558eec79690ce15715369d49605d8f4ffc709b7d
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/WebKit/public/platform/WebURLError.h
9fdbe756640b8983e9566e6af4714539d78d7ff5
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
3,198
h
/* * Copyright (C) 2009 Google 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 name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WebURLError_h #define WebURLError_h #include "WebString.h" #include "WebURL.h" namespace blink { class ResourceError; struct WebURLError { // A namespace for "reason" to support various layers generating // resource errors. WebKit does not care about the value of this // string as it will just be passed via callbacks to the consumer. WebString domain; // A numeric error code detailing the reason for this error. A value // of 0 means no error. WebKit does not interpret the meaning of other // values and normally just forwards this error information back to the // embedder (see for example WebFrameClient). int reason; // A flag showing whether or not "unreachableURL" has a copy in the // cache that was too stale to return for this request. bool staleCopyInCache; // A flag showing whether this error should be treated as a cancellation, // e.g. we do not show console errors for cancellations. bool isCancellation; // A flag showing whether this error is the result of a request being // ignored (e.g. through shouldOverrideUrlLoading). bool wasIgnoredByHandler; // The url that failed to load. WebURL unreachableURL; // A description for the error. WebString localizedDescription; WebURLError() : reason(0), staleCopyInCache(false), isCancellation(false), wasIgnoredByHandler(false) {} #if INSIDE_BLINK BLINK_PLATFORM_EXPORT WebURLError(const ResourceError&); BLINK_PLATFORM_EXPORT WebURLError& operator=(const ResourceError&); BLINK_PLATFORM_EXPORT operator ResourceError() const; #endif }; } // namespace blink #endif
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
f0120e2c8deb33e9e466c3cba5a31d26f003adfb
d2299e00b125cefa2eaf13c403544d2235abaa6e
/C++/PG_제일 작은 수 제거.cpp
9b319f73d0032d36ff51f44c2b6d6bf6ad558d78
[]
no_license
SehoonKwon/Study_Programmers
75a20bd67cb5b8c4cb97ee40b416be48efe80968
274830119a203bf3ae9538d7bfe8ac391109169c
refs/heads/master
2023-08-16T06:06:29.239546
2021-10-07T08:06:54
2021-10-07T08:06:54
293,795,945
0
0
null
null
null
null
UTF-8
C++
false
false
450
cpp
#include <string> #include <vector> using namespace std; vector<int> solution(vector<int> arr) { vector<int> answer; if(arr.size() == 1) { answer.push_back(-1); return answer; } int MIN = (int)1e9, idx = -1; for(int i=0; i<arr.size(); i++) { if(arr[i]<MIN) { MIN = arr[i]; idx = i; } } arr.erase(arr.begin() + idx); return arr; }
[ "noreply@github.com" ]
SehoonKwon.noreply@github.com
d985a77027d3ce90e45471d1e59fef69f1f36213
c30a2f3e22d0ffb281b1fe9d2e3d5d9442811d98
/MultiTextureShaderClass.cpp
618a85a101c5452e2f6b55e95c15b42144cfb8ff
[]
no_license
ShootingStarGames/DirectX
9e18966707e06172809ca329f5b5b26fbeea214d
fe84f7e7bbe7df6b324b91b6bf84a4cdf0dc34da
refs/heads/master
2020-03-22T17:13:58.052745
2018-09-10T11:56:23
2018-09-10T11:56:23
140,382,698
0
0
null
null
null
null
UHC
C++
false
false
6,700
cpp
#include "stdafx.h" #include "MultiTextureShaderClass.h" MultiTextureShaderClass::MultiTextureShaderClass() { } MultiTextureShaderClass::MultiTextureShaderClass(const MultiTextureShaderClass &) { } MultiTextureShaderClass::~MultiTextureShaderClass() { } bool MultiTextureShaderClass::Initialize(ID3D11Device *device, HWND hwnd) { return InitializeShader(device, hwnd, L"./hlsl/AlphamapVertexShader.hlsl", L"./hlsl/AlphamapPixelShader.hlsl"); } void MultiTextureShaderClass::Shutdown() { ShutdownShader(); } bool MultiTextureShaderClass::Render(ID3D11DeviceContext *deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix , int textureNum, ID3D11ShaderResourceView **textureArray) { if (!SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, textureNum,textureArray)) { return false; } RenderShader(deviceContext, indexCount); return true; } bool MultiTextureShaderClass::InitializeShader(ID3D11Device *device, HWND hwnd, WCHAR *vsFilename, WCHAR *psFilename) { ID3D10Blob* errorMessage = nullptr; ID3D10Blob* vertexShaderBuffer = nullptr; HRESULT result = D3DCompileFromFile(vsFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &vertexShaderBuffer, &errorMessage); if (FAILED(result)) { if (errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, vsFilename); } else { MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK); } return false; } ID3D10Blob* pixelShaderBuffer = nullptr; result = D3DCompileFromFile(psFilename, NULL, NULL, "main", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &pixelShaderBuffer, &errorMessage); if (FAILED(result)) { if (errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, psFilename); } else { MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK); } return false; } result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader); if (FAILED(result)) { return false; } result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); if (FAILED(result)) { return false; } // 정점 입력 레이아웃을 만듭니다. if (FAILED(InitializeLayout(device, vertexShaderBuffer))) { return false; } // 더 이상 사용되지 않는 정점 셰이더 퍼버와 픽셀 셰이더 버퍼를 해제합니다. vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; // 정점 셰이더에 있는 행렬 상수 버퍼의 구조체를 작성합니다. D3D11_BUFFER_DESC matrixBufferDesc; matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; // 상수 버퍼 포인터를 만들어 이 클래스에서 정점 셰이더 상수 버퍼에 접근할 수 있게 합니다. result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer); if (FAILED(result)) { return false; } // 텍스처 샘플러 상태 구조체를 생성 및 설정합니다. D3D11_SAMPLER_DESC samplerDesc; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; // 텍스처 샘플러 상태를 만듭니다. result = device->CreateSamplerState(&samplerDesc, &m_sampleState); if (FAILED(result)) { return false; } return true; } void MultiTextureShaderClass::ShutdownShader() { ShaderClass::ShutdownShader(); } HRESULT MultiTextureShaderClass::InitializeLayout(ID3D11Device *device, ID3D10Blob *vertexShaderBuffer) { D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "TEXCOORD"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; // 레이아웃의 요소 수를 가져옵니다. UINT numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // 정점 입력 레이아웃을 만듭니다. return device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout); } bool MultiTextureShaderClass::SetShaderParameters(ID3D11DeviceContext *deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix ,int textureNum, ID3D11ShaderResourceView **textureArray) { worldMatrix = XMMatrixTranspose(worldMatrix); viewMatrix = XMMatrixTranspose(viewMatrix); projectionMatrix = XMMatrixTranspose(projectionMatrix); // 상수 버퍼의 내용을 쓸 수 있도록 잠급니다. D3D11_MAPPED_SUBRESOURCE mappedResource; if (FAILED(deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource))) { return false; } // 상수 버퍼의 데이터에 대한 포인터를 가져옵니다. MatrixBufferType* dataPtr = (MatrixBufferType*)mappedResource.pData; // 상수 버퍼에 행렬을 복사합니다. dataPtr->world = worldMatrix; dataPtr->view = viewMatrix; dataPtr->projection = projectionMatrix; // 상수 버퍼의 잠금을 풉니다. deviceContext->Unmap(m_matrixBuffer, 0); // 정점 셰이더에서의 상수 버퍼의 위치를 설정합니다. unsigned int bufferNumber = 0; // 마지막으로 정점 셰이더의 상수 버퍼를 바뀐 값으로 바꿉니다. deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer); // 픽셀 셰이더에서 셰이더 텍스처 리소스를 설정합니다. deviceContext->PSSetShaderResources(0, textureNum, textureArray); return true; }
[ "36808020+ShootingStarGames@users.noreply.github.com" ]
36808020+ShootingStarGames@users.noreply.github.com
a5ce71af1298a6c8422b1568ce0d081ce9e424c6
937d4cbee661cc6a044dd119704e1ed8f1b4c6a5
/src/main.cpp
9f21ef3e4cfe2fc953dd3b67bf347b220accf8ed
[]
no_license
fo2rist/tictactoeunlimited
5cd6a40b1758bbd8e094704416be245fb6a11191
6944ee3816790fc7fcca25c0eac69147723ba3d7
refs/heads/master
2021-05-04T16:37:52.055666
2018-02-05T04:32:12
2018-02-05T04:32:12
120,254,716
0
0
null
null
null
null
UTF-8
C++
false
false
1,096
cpp
// Drilldown navigation project template #include "TicTacToeUnlimited.hpp" #include <bb/cascades/Application> #include <QLocale> #include <QTranslator> // include JS Debugger / CS Profiler enabler // this feature is enabled by default in the debug build only #include <Qt/qdeclarativedebug.h> using namespace bb::cascades; Q_DECL_EXPORT int main(int argc, char **argv) { // this is where the server is started etc Application app(argc, argv); // localization support QTranslator translator; QString locale_string = QLocale().name(); QString filename = QString( "TicTacToeUnlimited_%1" ).arg( locale_string ); if (translator.load(filename, "app/native/qm")) { app.installTranslator( &translator ); } // create the application pane object to init UI etc. new TicTacToeUnlimited(&app); // we complete the transaction started in the app constructor and start the client event loop here return Application::exec(); // when loop is exited the Application deletes the scene which deletes all its children (per qt rules for children) }
[ "fo2@inbox.ru" ]
fo2@inbox.ru
d285e358256d0f6bcadcb3790cf1805afb0abc01
6f9be1b6c5bb8957cef6bd39a06b54b883905d48
/String/K-Longest-Common-Substring.cpp
07056a8ebc6d17db5bb1c314cc41c158c107b329
[]
no_license
GJnghost/ACM-Template-by-forever97
24a3a7268463f11bf5d7d1aeb637699fd53e8169
8104a199ac28246b2dd62b304e2fc94130c4042d
refs/heads/master
2022-11-28T06:24:06.032431
2020-08-14T08:11:20
2020-08-14T08:11:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,826
cpp
/* 求k个串的最长公共子串 并输出字典序最小的一个 */ const int N = 4050, M = 210; using namespace std; int nxt[M], n; char dict[N][M]; void get_nxt(char *a, int n) { int i, j; for (nxt[0] = j = -1, i = 1; i < n; nxt[i++] = j) { while (~j && a[j + 1] != a[i]) j = nxt[j]; if (a[j + 1] == a[i]) j++; } } int LongestPre(char *s, int len) { get_nxt(s, len); for (int i = 1; i < n; i++) { char *p = dict[i]; int ans = 0; for (int j = -1; *p; p++) { while (~j && s[j + 1] != *p) j = nxt[j]; if (s[j + 1] == *p) { j++; ans = max(ans, j + 1); } if (j == len - 1) j = nxt[j]; } len = min(len, ans); } return len; } int main() { while (scanf("%d", &n) && n) { getchar(); for (int i = 0; i < n; i++) gets(dict[i]); int len = strlen(dict[0]), ans = 0, pos = 0; for (int i = 0; i < len; i++) { int tmp = LongestPre(dict[0] + i, len - i); if (tmp >= ans) { if (tmp > ans) ans = tmp, pos = i; else { bool flag = 1; for (int t = 0; t < ans; t++) { if (dict[0][pos + t] > dict[0][i + t]) break; else if (dict[0][pos + t] < dict[0][i + t]) { flag = 0; break; } } if (flag) pos = i; } } } if (ans) { for (int i = 0; i < ans; i++) putchar(dict[0][pos + i]); puts(""); } else puts("IDENTITY LOST"); } return 0; }
[ "857426255@qq.com" ]
857426255@qq.com
d6b3a77e4d39928618308a9eb28f2ab4140bcd86
60240cad692f6e82b730a1a4982ec42729ea1541
/source/glbinding-aux/source/glrevision.h
fc47546e0041f5f9033be0e59665e160804116bf
[ "MIT" ]
permissive
dutow/glbinding
961e6ab073ef8365f1fcb155d65e0476683febcd
ac12883c4387650c29dbbf01278b7198083750d9
refs/heads/master
2023-03-04T03:06:15.238095
2019-06-27T08:43:13
2019-06-27T08:43:13
195,656,058
0
0
MIT
2019-07-07T13:43:50
2019-07-07T13:43:50
null
UTF-8
C++
false
false
167
h
#pragma once namespace glbinding { const unsigned int GL_REVISION = 0; ///< The revision of the gl.xml at the time of code generation. } // namespace glbinding
[ "willyscheibel@gmx.de" ]
willyscheibel@gmx.de
33b15d1de5d2b9412cf882b6e588fabf6886fecf
eab2ea8f23a1c7d88a69f973e9f32b16ce103259
/binary search(maximum element).cpp
fd1c88168f98ae1d970e676b26e08019a7ac3394
[]
no_license
apaarkamal/miscellaneous-codes
73a973a0f66973c15262b0a0dae2e8776ac3b0ae
df822d1dc06b7cb5426bbb04256179c5b5b04641
refs/heads/master
2020-06-12T19:50:16.772416
2019-12-02T05:59:03
2019-12-02T05:59:03
194,406,672
6
10
null
null
null
null
UTF-8
C++
false
false
615
cpp
int lf = 0, rt = 1e15; while (lf <= rt) { int mid = (lf + rt) / 2; // cout<<lf<<" "<<mid<<" "<<rt<<" "<<ans<<'\n'; if (check(mid)) { ans = mid; lf = mid + 1; } else { rt = mid - 1; } } cout << ans; /////////////////////////// OR /////////////////////// while (lo < hi) { long long mid = (lo + hi + 1) / 2; if (can(mid)) lo = mid; else hi = mid - 1; } cout << lo; //////////////////////// while (l <= h) { ll mid = (l + h) / 2; if (check(mid)) { ans = mid; l = mid + 1; } else h = mid - 1; } cout << ans;
[ "apaarsaxena@gmail.com" ]
apaarsaxena@gmail.com
1794919774cc57344997703f641c0ed2fa3a1a62
610df9f15c34a266107adf68b02906b0f44fe780
/exprtk/ExpressionNode.h
c8688bf6ffc919f183271fb3598ff6472104194b
[]
no_license
FrontPictures/exprtk
2d04937a78779ef3d6bf3b636809cac2c4bfcf43
4b60993986c6e9ca00e567fb43e54500b1cf578b
refs/heads/master
2023-08-24T20:31:46.872648
2021-10-13T16:40:17
2021-10-13T16:40:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,041
h
#ifndef EXPRESSIONNODE_H #define EXPRESSIONNODE_H #include <vector> #include <limits> #include <complex> #include <deque> #include <algorithm> #include "OperatorType.h" namespace exprtk { namespace details { template<typename Node> struct node_collector_interface { typedef Node *node_ptr_t; typedef Node **node_pp_t; typedef std::vector<node_pp_t> noderef_list_t; virtual ~node_collector_interface() {} virtual void collect_nodes(noderef_list_t &) {} }; template<typename Node> struct node_depth_base; template<typename T> class expression_node : public node_collector_interface<expression_node<T>>, public node_depth_base<expression_node<T>> { public: // clang-format off enum node_type { e_none , e_null , e_constant , e_unary , e_binary , e_binary_ext , e_trinary , e_quaternary , e_vararg , e_conditional , e_while , e_repeat , e_for , e_switch , e_mswitch , e_return , e_retenv , e_variable , e_stringvar , e_stringconst , e_stringvarrng , e_cstringvarrng , e_strgenrange , e_strconcat , e_stringvarsize , e_strswap , e_stringsize , e_stringvararg , e_function , e_vafunction , e_genfunction , e_strfunction , e_strcondition , e_strccondition , e_add , e_sub , e_mul , e_div , e_mod , e_pow , e_lt , e_lte , e_gt , e_gte , e_eq , e_ne , e_and , e_nand , e_or , e_nor , e_xor , e_xnor , e_in , e_like , e_ilike , e_inranges , e_ipow , e_ipowinv , e_abs , e_acos , e_acosh , e_asin , e_asinh , e_atan , e_atanh , e_ceil , e_cos , e_cosh , e_exp , e_expm1 , e_floor , e_log , e_log10 , e_log2 , e_log1p , e_neg , e_pos , e_round , e_sin , e_sinc , e_sinh , e_sqrt , e_tan , e_tanh , e_cot , e_sec , e_csc , e_r2d , e_d2r , e_d2g , e_g2d , e_notl , e_sgn , e_erf , e_erfc , e_ncdf , e_frac , e_trunc , e_uvouv , e_vov , e_cov , e_voc , e_vob , e_bov , e_cob , e_boc , e_vovov , e_vovoc , e_vocov , e_covov , e_covoc , e_vovovov , e_vovovoc , e_vovocov , e_vocovov , e_covovov , e_covocov , e_vocovoc , e_covovoc , e_vococov , e_sf3ext , e_sf4ext , e_nulleq , e_strass , e_vector , e_vecelem , e_rbvecelem , e_rbveccelem , e_vecdefass , e_vecvalass , e_vecvecass , e_vecopvalass , e_vecopvecass , e_vecfunc , e_vecvecswap , e_vecvecineq , e_vecvalineq , e_valvecineq , e_vecvecarith , e_vecvalarith , e_valvecarith , e_vecunaryop , e_vecondition , e_break , e_continue , e_swap }; // clang-format on typedef T value_type; typedef expression_node<T> *expression_ptr; typedef node_collector_interface<expression_node<T>> nci_t; typedef typename nci_t::noderef_list_t noderef_list_t; typedef node_depth_base<expression_node<T>> ndb_t; virtual ~expression_node() {} inline virtual T value() const { return std::numeric_limits<T>::quiet_NaN(); } inline virtual expression_node<T> *branch(const std::size_t &index = 0) const { return reinterpret_cast<expression_ptr>(index * 0); } inline virtual node_type type() const { return e_none; } }; template <typename T> inline bool is_generally_string_node(const expression_node<T>* node) { if (node) { switch (node->type()) { case expression_node<T>::e_stringvar : case expression_node<T>::e_stringconst : case expression_node<T>::e_stringvarrng : case expression_node<T>::e_cstringvarrng : case expression_node<T>::e_strgenrange : case expression_node<T>::e_strass : case expression_node<T>::e_strconcat : case expression_node<T>::e_strfunction : case expression_node<T>::e_strcondition : case expression_node<T>::e_strccondition : case expression_node<T>::e_stringvararg : return true; default : return false; } } return false; } inline bool is_true(const double v) { return std::not_equal_to<double>()(0.0,v); } inline bool is_true(const long double v) { return std::not_equal_to<long double>()(0.0L,v); } inline bool is_true(const float v) { return std::not_equal_to<float>()(0.0f,v); } template <typename T> inline bool is_true(const std::complex<T>& v) { return std::not_equal_to<std::complex<T> >()(std::complex<T>(0),v); } template <typename T> inline bool is_true(const expression_node<T>* node) { return std::not_equal_to<T>()(T(0),node->value()); } template <typename T> inline bool is_true(const std::pair<expression_node<T>*,bool>& node) { return std::not_equal_to<T>()(T(0),node.first->value()); } template <typename T> inline bool is_false(const expression_node<T>* node) { return std::equal_to<T>()(T(0),node->value()); } template <typename T> inline bool is_false(const std::pair<expression_node<T>*,bool>& node) { return std::equal_to<T>()(T(0),node.first->value()); } template <typename T> inline bool is_unary_node(const expression_node<T>* node) { return node && (details::expression_node<T>::e_unary == node->type()); } template <typename T> inline bool is_neg_unary_node(const expression_node<T>* node) { return node && (details::expression_node<T>::e_neg == node->type()); } template <typename T> inline bool is_binary_node(const expression_node<T>* node) { return node && (details::expression_node<T>::e_binary == node->type()); } template <typename T> inline bool is_variable_node(const expression_node<T>* node) { return node && (details::expression_node<T>::e_variable == node->type()); } template <typename T> inline bool is_ivariable_node(const expression_node<T>* node) { return node && ( details::expression_node<T>::e_variable == node->type() || details::expression_node<T>::e_vecelem == node->type() || details::expression_node<T>::e_rbvecelem == node->type() || details::expression_node<T>::e_rbveccelem == node->type() ); } template <typename T> inline bool is_vector_elem_node(const expression_node<T>* node) { return node && (details::expression_node<T>::e_vecelem == node->type()); } template <typename T> inline bool is_rebasevector_elem_node(const expression_node<T>* node) { return node && (details::expression_node<T>::e_rbvecelem == node->type()); } template <typename T> inline bool is_rebasevector_celem_node(const expression_node<T>* node) { return node && (details::expression_node<T>::e_rbveccelem == node->type()); } template <typename T> inline bool is_vector_node(const expression_node<T>* node) { return node && (details::expression_node<T>::e_vector == node->type()); } template <typename T> inline bool is_ivector_node(const expression_node<T>* node) { if (node) { switch (node->type()) { case details::expression_node<T>::e_vector : case details::expression_node<T>::e_vecvalass : case details::expression_node<T>::e_vecvecass : case details::expression_node<T>::e_vecopvalass : case details::expression_node<T>::e_vecopvecass : case details::expression_node<T>::e_vecvecswap : case details::expression_node<T>::e_vecvecarith : case details::expression_node<T>::e_vecvalarith : case details::expression_node<T>::e_valvecarith : case details::expression_node<T>::e_vecunaryop : case details::expression_node<T>::e_vecondition : return true; default : return false; } } else return false; } template <typename T> inline bool is_constant_node(const expression_node<T>* node) { return node && (details::expression_node<T>::e_constant == node->type()); } template <typename T> inline bool is_null_node(const expression_node<T>* node) { return node && (details::expression_node<T>::e_null == node->type()); } template <typename T> inline bool is_break_node(const expression_node<T>* node) { return node && (details::expression_node<T>::e_break == node->type()); } template <typename T> inline bool is_continue_node(const expression_node<T>* node) { return node && (details::expression_node<T>::e_continue == node->type()); } template <typename T> inline bool is_swap_node(const expression_node<T>* node) { return node && (details::expression_node<T>::e_swap == node->type()); } template <typename T> inline bool is_function(const expression_node<T>* node) { return node && (details::expression_node<T>::e_function == node->type()); } template <typename T> inline bool is_return_node(const expression_node<T>* node) { return node && (details::expression_node<T>::e_return == node->type()); } template <typename T> class unary_node; template <typename T> inline bool is_negate_node(const expression_node<T>* node) { if (node && is_unary_node(node)) { return (details::e_neg == static_cast<const unary_node<T>*>(node)->operation()); } else return false; } template <typename T> inline bool branch_deletable(expression_node<T>* node) { return (0 != node) && !is_variable_node(node) && !is_string_node (node) ; } template <std::size_t N, typename T> inline bool all_nodes_valid(expression_node<T>* (&b)[N]) { for (std::size_t i = 0; i < N; ++i) { if (0 == b[i]) return false; } return true; } template <typename T, typename Allocator, template <typename, typename> class Sequence> inline bool all_nodes_valid(const Sequence<expression_node<T>*,Allocator>& b) { for (std::size_t i = 0; i < b.size(); ++i) { if (0 == b[i]) return false; } return true; } template <std::size_t N, typename T> inline bool all_nodes_variables(expression_node<T>* (&b)[N]) { for (std::size_t i = 0; i < N; ++i) { if (0 == b[i]) return false; else if (!is_variable_node(b[i])) return false; } return true; } template <typename T, typename Allocator, template <typename, typename> class Sequence> inline bool all_nodes_variables(Sequence<expression_node<T>*,Allocator>& b) { for (std::size_t i = 0; i < b.size(); ++i) { if (0 == b[i]) return false; else if (!is_variable_node(b[i])) return false; } return true; } template <typename Node> class node_collection_destructor { public: typedef node_collector_interface<Node> nci_t; typedef typename nci_t::node_ptr_t node_ptr_t; typedef typename nci_t::node_pp_t node_pp_t; typedef typename nci_t::noderef_list_t noderef_list_t; static void delete_nodes(node_ptr_t& root) { std::vector<node_pp_t> node_delete_list; node_delete_list.reserve(1000); collect_nodes(root, node_delete_list); for (std::size_t i = 0; i < node_delete_list.size(); ++i) { node_ptr_t& node = *node_delete_list[i]; delete node; node = reinterpret_cast<node_ptr_t>(0); } } private: static void collect_nodes(node_ptr_t& root, noderef_list_t& node_delete_list) { std::deque<node_ptr_t> node_list; node_list.push_back(root); node_delete_list.push_back(&root); noderef_list_t child_node_delete_list; child_node_delete_list.reserve(1000); while (!node_list.empty()) { node_list.front()->collect_nodes(child_node_delete_list); if (!child_node_delete_list.empty()) { for (std::size_t i = 0; i < child_node_delete_list.size(); ++i) { node_pp_t& node = child_node_delete_list[i]; node_list.push_back(*node); } node_delete_list.insert( node_delete_list.end(), child_node_delete_list.begin(), child_node_delete_list.end()); child_node_delete_list.clear(); } node_list.pop_front(); } std::reverse(node_delete_list.begin(), node_delete_list.end()); } }; template <typename NodeAllocator, typename T, std::size_t N> inline void free_all_nodes(NodeAllocator& node_allocator, expression_node<T>* (&b)[N]) { for (std::size_t i = 0; i < N; ++i) { free_node(node_allocator,b[i]); } } template <typename NodeAllocator, typename T, typename Allocator, template <typename, typename> class Sequence> inline void free_all_nodes(NodeAllocator& node_allocator, Sequence<expression_node<T>*,Allocator>& b) { for (std::size_t i = 0; i < b.size(); ++i) { free_node(node_allocator,b[i]); } b.clear(); } template <typename NodeAllocator, typename T> inline void free_node(NodeAllocator&, expression_node<T>*& node) { if ((0 == node) || is_variable_node(node) || is_string_node(node)) { return; } node_collection_destructor<expression_node<T> > ::delete_nodes(node); } template <typename T> inline void destroy_node(expression_node<T>*& node) { if (0 != node) { node_collection_destructor<expression_node<T> > ::delete_nodes(node); } } template <typename Node> struct node_depth_base { typedef Node* node_ptr_t; typedef std::pair<node_ptr_t,bool> nb_pair_t; node_depth_base() : depth_set(false) , depth(0) {} virtual ~node_depth_base() {} virtual std::size_t node_depth() const { return 1; } std::size_t compute_node_depth(const Node* const& node) const { if (!depth_set) { depth = 1 + (node ? node->node_depth() : 0); depth_set = true; } return depth; } std::size_t compute_node_depth(const nb_pair_t& branch) const { if (!depth_set) { depth = 1 + (branch.first ? branch.first->node_depth() : 0); depth_set = true; } return depth; } template <std::size_t N> std::size_t compute_node_depth(const nb_pair_t (&branch)[N]) const { if (!depth_set) { depth = 0; for (std::size_t i = 0; i < N; ++i) { if (branch[i].first) { depth = std::max(depth,branch[i].first->node_depth()); } } depth += 1; depth_set = true; } return depth; } template <typename BranchType> std::size_t compute_node_depth(const BranchType& n0, const BranchType& n1) const { if (!depth_set) { depth = 1 + std::max(compute_node_depth(n0), compute_node_depth(n1)); depth_set = true; } return depth; } template <typename BranchType> std::size_t compute_node_depth(const BranchType& n0, const BranchType& n1, const BranchType& n2) const { if (!depth_set) { depth = 1 + std::max( std::max(compute_node_depth(n0), compute_node_depth(n1)), compute_node_depth(n2)); depth_set = true; } return depth; } template <typename BranchType> std::size_t compute_node_depth(const BranchType& n0, const BranchType& n1, const BranchType& n2, const BranchType& n3) const { if (!depth_set) { depth = 1 + std::max( std::max(compute_node_depth(n0), compute_node_depth(n1)), std::max(compute_node_depth(n2), compute_node_depth(n3))); depth_set = true; } return depth; } template <typename Allocator, template <typename, typename> class Sequence> std::size_t compute_node_depth(const Sequence<node_ptr_t, Allocator>& branch_list) const { if (!depth_set) { for (std::size_t i = 0; i < branch_list.size(); ++i) { if (branch_list[i]) { depth = std::max(depth, compute_node_depth(branch_list[i])); } } depth_set = true; } return depth; } template <typename Allocator, template <typename, typename> class Sequence> std::size_t compute_node_depth(const Sequence<nb_pair_t,Allocator>& branch_list) const { if (!depth_set) { for (std::size_t i = 0; i < branch_list.size(); ++i) { if (branch_list[i].first) { depth = std::max(depth, compute_node_depth(branch_list[i].first)); } } depth_set = true; } return depth; } mutable bool depth_set; mutable std::size_t depth; template <typename NodeSequence> void collect(node_ptr_t const& node, const bool deletable, NodeSequence& delete_node_list) const { if ((0 != node) && deletable) { delete_node_list.push_back(const_cast<node_ptr_t*>(&node)); } } template <typename NodeSequence> void collect(const nb_pair_t& branch, NodeSequence& delete_node_list) const { collect(branch.first, branch.second, delete_node_list); } template <typename NodeSequence> void collect(Node*& node, NodeSequence& delete_node_list) const { collect(node, branch_deletable(node), delete_node_list); } template <std::size_t N, typename NodeSequence> void collect(const nb_pair_t(&branch)[N], NodeSequence& delete_node_list) const { for (std::size_t i = 0; i < N; ++i) { collect(branch[i].first, branch[i].second, delete_node_list); } } template <typename Allocator, template <typename, typename> class Sequence, typename NodeSequence> void collect(const Sequence<nb_pair_t, Allocator>& branch, NodeSequence& delete_node_list) const { for (std::size_t i = 0; i < branch.size(); ++i) { collect(branch[i].first, branch[i].second, delete_node_list); } } template <typename Allocator, template <typename, typename> class Sequence, typename NodeSequence> void collect(const Sequence<node_ptr_t, Allocator>& branch_list, NodeSequence& delete_node_list) const { for (std::size_t i = 0; i < branch_list.size(); ++i) { collect(branch_list[i], branch_deletable(branch_list[i]), delete_node_list); } } template <typename Boolean, typename AllocatorT, typename AllocatorB, template <typename, typename> class Sequence, typename NodeSequence> void collect(const Sequence<node_ptr_t, AllocatorT>& branch_list, const Sequence<Boolean, AllocatorB>& branch_deletable_list, NodeSequence& delete_node_list) const { for (std::size_t i = 0; i < branch_list.size(); ++i) { collect(branch_list[i], branch_deletable_list[i], delete_node_list); } } }; template <typename T> class null_node final : public expression_node<T> { public: inline T value() const { return std::numeric_limits<T>::quiet_NaN(); } inline typename expression_node<T>::node_type type() const { return expression_node<T>::e_null; } }; template <typename T, std::size_t N> inline void construct_branch_pair(std::pair<expression_node<T>*,bool> (&branch)[N], expression_node<T>* b, const std::size_t& index) { if (b && (index < N)) { branch[index] = std::make_pair(b,branch_deletable(b)); } } template <typename T> inline void construct_branch_pair(std::pair<expression_node<T>*,bool>& branch, expression_node<T>* b) { if (b) { branch = std::make_pair(b,branch_deletable(b)); } } template <std::size_t N, typename T> inline void init_branches(std::pair<expression_node<T>*,bool> (&branch)[N], expression_node<T>* b0, expression_node<T>* b1 = reinterpret_cast<expression_node<T>*>(0), expression_node<T>* b2 = reinterpret_cast<expression_node<T>*>(0), expression_node<T>* b3 = reinterpret_cast<expression_node<T>*>(0), expression_node<T>* b4 = reinterpret_cast<expression_node<T>*>(0), expression_node<T>* b5 = reinterpret_cast<expression_node<T>*>(0), expression_node<T>* b6 = reinterpret_cast<expression_node<T>*>(0), expression_node<T>* b7 = reinterpret_cast<expression_node<T>*>(0), expression_node<T>* b8 = reinterpret_cast<expression_node<T>*>(0), expression_node<T>* b9 = reinterpret_cast<expression_node<T>*>(0)) { construct_branch_pair(branch, b0, 0); construct_branch_pair(branch, b1, 1); construct_branch_pair(branch, b2, 2); construct_branch_pair(branch, b3, 3); construct_branch_pair(branch, b4, 4); construct_branch_pair(branch, b5, 5); construct_branch_pair(branch, b6, 6); construct_branch_pair(branch, b7, 7); construct_branch_pair(branch, b8, 8); construct_branch_pair(branch, b9, 9); } } // namespace details typedef details::expression_node<double> *expression_node_ptr; inline expression_node_ptr error_node() { return reinterpret_cast<expression_node_ptr>(0); } } // namespace exprtk #endif // EXPRESSIONNODE_H
[ "vladimir.zibarov@frontpictures.com" ]
vladimir.zibarov@frontpictures.com
4a09226b392d86e2585f607cfc755426450ba77c
d53547e06b39f80e0d32aec73c2fc154f4b77041
/include/Game.h
e11b10e04d87bc3c9e6a9f2aa6a5e5f9f5a66c67
[]
no_license
kapildd/DodgeTheBalls
ba753557145ddb0f2ede30205f1614e27ed12570
99f794f2807c87aecf57387504549e19cfcdaa83
refs/heads/master
2021-01-10T20:28:21.429627
2020-06-17T16:16:06
2020-06-17T16:16:06
3,916,967
0
0
null
null
null
null
UTF-8
C++
false
false
1,387
h
#ifndef _GAME_H_ #define _GAME_H_ #define GLFW_INCLUDE_GLU #include <GL/freeglut.h> #include <GLFW/glfw3.h> #include "Constants.h" #include "GUISession.h" #include "GameState.h" #include "GameUtil.h" #include "MouseTracker.h" #include "Window.h" class Game { const char *WINDOW_TITLE = "Dodge The Balls"; const char *INITIAL_MESSAGE = "Press ENTER or S to start:"; GUISession *session; Window *mainWindow; MouseTracker *mouseTracker; GameState *gameState; bool start, finish; int startTime, endTime; bool checkBound; inline bool isNotRunning() { return !start; } inline bool isFinished() { return finish; } inline bool isStartPressed(GLFWwindow *window) { return (glfwGetKey(window, GLFW_KEY_ENTER) || glfwGetKey(window, 'S')); } inline bool isRestartPressed(GLFWwindow *window) { return glfwGetKey(window, 'R'); } void gameEnvironmentInit(); void startGame(); void checkBoundary(std::vector<Ball> &balls); void dropAll(std::vector<Ball> &balls); void checkCollision(std::vector<Ball> &balls, Ball &mouseBall); void updateGameState(); void displayInit(); void paintBall(Vector3<int> &color, Ball &b); void drawFinishScreen(); void drawInitialScreen(); void renderGameState(); void refreshScreen(GLFWwindow *window); public: Game(int argc, char *argv[]); ~Game(); void runMainLoop(); }; #endif /* _GAME_H_ */
[ "kapileyes@gmail.com" ]
kapileyes@gmail.com
749270230a137314f696ac9bd7dc87318dbe68c7
670528de454c41ca9a213f5d313b9d9bb4d94c3b
/PA2/semestralniProjekt/frajtluk/src/fileManager.h
6a219960bba250acd8fb24083077931f33c7312a
[]
no_license
AytonDev/CVUT
a34b52e306a309d7662a1049539babc50b437f4f
6c00e31ce5bc17231b65b757fd43f507adf139d3
refs/heads/master
2020-03-20T21:46:28.831522
2018-06-18T14:28:23
2018-06-18T14:28:23
137,759,699
0
0
null
null
null
null
UTF-8
C++
false
false
1,821
h
// // Created by Lukáš Frajt on 13/05/2018. // #ifndef SEMESTRALNIPROJEKT_FILEMANAGER_H #define SEMESTRALNIPROJEKT_FILEMANAGER_H #include "player.h" #include "textQuestion.h" #include "multiTextQuestion.h" #include "trueFalseQuestion.h" #include "orderQuestion.h" #include "pickOneQuestion.h" #include "pickManyQuestion.h" #include <string> #include <cstdio> #include <vector> #include <iostream> #include <fstream> #define PATH_TO_FILE "./examples/" using namespace std; /* * Comment */ class CFileManager { public: /** * @brief Construct a new CFileManager object * * @param quizesFileName name of the quizzesFile */ CFileManager(string quizesFileName); /** * @brief Save quiz to the CSV file * * @param quiz CQuizManager object */ virtual void SaveQuiz(const CQuizManager &quiz) const = 0; /** * @brief loads quizzes from the file. IF something fail returns false, else returns true. * Push quizzes to the vector * * @param quizzes vector of quizzes * @return true if everything is ok * @return false if something fail */ virtual bool LoadQuizzes(vector<CQuizManager> &quizzes) const = 0; /** * @brief save question to the file. * * @param question returns * @param fileName */ virtual void SaveQuestion(const CBaseQuestion &question, string fileName) const = 0; /** * @brief loads question to the file. * * @param fileName * @param quiz * @return true if everything is ok * @return false if something fail */ virtual bool LoadQuestions(string fileName, CQuizManager &quiz) const = 0; protected: string m_QuizesFileName; string quizFile; string scoreFile; }; #endif //SEMESTRALNIPROJEKT_FILEMANGER_H
[ "lukasfrajt@frajtluk-ntb.wifi.nat" ]
lukasfrajt@frajtluk-ntb.wifi.nat
f0b164e329c4d6deb3745ec3723b44c2c09986d7
f60796674e5410ce733f8e7de704bce5e5a0a45b
/Source/Virtusonic/FretFinger/FretFingerController.h
8345fa8bc39ace1688b50cab46237211c43e0381
[ "Apache-2.0" ]
permissive
lkunic/Virtusonic
835303be940167606865041ebadc18f122a21f34
97b2cbf90ee707b7d609f0a739ebdf183a6f8c90
refs/heads/master
2022-09-05T05:19:01.719724
2022-09-01T21:03:02
2022-09-01T21:03:02
63,863,141
0
0
null
null
null
null
UTF-8
C++
false
false
786
h
// Copyright (c) Luka Kunic, 2016. #pragma once #include "Components/ActorComponent.h" #include "FretFinger.h" #include "FretFingerController.generated.h" UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class VIRTUSONIC_API UFretFingerController : public UActorComponent { GENERATED_BODY() public: // Sets default values for this component's properties UFretFingerController(); // The fret finger references are added through the actor blueprint for the instrument UFUNCTION(BlueprintCallable, Category = "FretFinger") void AddFretFinger(AFretFinger *fretFinger); // Public getters int32 GetFretFingerCount(); AFretFinger* GetFretFinger(int32 index); private: UPROPERTY(EditAnywhere, Category = "FretFinger") TArray<AFretFinger*> mFretFingers; };
[ "lkunic@outlook.com" ]
lkunic@outlook.com
cd341a7b80ab8ba9de15ff22d71d4b4baae8b6e2
005ccfb1c014f4534a8dd8126020e940f360aae2
/andtut.cpp
6c4c437d58af0862fa34ddbd441c782f3c8173c4
[]
no_license
rafalcode/libjp
4ab20a08f50278fbb5598cc057143f70f3144610
70a4b003c807a6a64c925f744fefa99143382dca
refs/heads/master
2021-11-30T19:29:55.639579
2021-11-20T00:00:57
2021-11-20T00:00:57
235,455,000
0
0
null
null
null
null
UTF-8
C++
false
false
2,640
cpp
/* I got the following code from Andrew White. * ref. http://www.andrewewhite.net/wordpress/2008/09/02/very-simple-jpeg-writer-in-c-c/ * However, its very lazy .. one r two functions are mentioend which can't be found anywhere. * in Xlib nor on the net. * it seems to be pseudo code really. * and distracted me from my purpose as usual. */ /* First, do some setup and take a screen shot using Xlib. Note that Xlib this has next to nothing to do with the JPEG code and is only included to create a context. In the end, the info and screen_shot object will have some meta-data about the image that we will be making into a JPEG. The buffer vector will hold raw RGB values for screen shot. */ #include <jpeglib.h> int main() { vector<char> buffer; XInfo_t xinfo = getXInfo(":0"); XImage* screen_shot = takeScreenshot(xinfo, buffer); /* Now we need to open an output file for the jpeg. */ FILE* outfile = fopen("/tmp/andtest.jpeg", "wb"); if (!outfile) throw FormattedException("%s:%d Failed to open output file", __FILE__, __LINE__); /* Now, lets setup the libjpeg objects. Note this is setup for my screen shot so we are using RGB color space. */ struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_stdio_dest(&cinfo, outfile); cinfo.image_width = xinfo.width; cinfo.image_height = xinfo.height; cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; /* Call the setup defualts helper function to give us a starting point. Note, don’t call any of the helper functions before you call this, they will no effect if you do. Then call other helper functions, here I call the set quality. Then start the compression.*/ jpeg_set_defaults(&cinfo); /*set the quality [0..100] */ jpeg_set_quality (&cinfo, 75, true); jpeg_start_compress(&cinfo, true); /* Next we setup a pointer and start looping though lines in the image. Notice that the row_pointer is set to the first byte of the row via some pointer math/magic. Once the pointer is calculated, do a write_scanline. */ JSAMPROW row_pointer; /* pointer to a single row */ while (cinfo.next_scanline < cinfo.image_height) { row_pointer = (JSAMPROW) &buffer[cinfo.next_scanline*(screen_shot->depth>>3)*screen_shot->width]; jpeg_write_scanlines(&cinfo, &row_pointer, 1); } /* Finally, call finish and in my case close the connection to the X server. */ jpeg_finish_compress(&cinfo); XCloseDisplay(xinfo.display); /* standard one: in Xlib.h */ }
[ "ramonfallon@gmail.com" ]
ramonfallon@gmail.com
19da39eb7eecd1d326f86ede9540773ca9d26cc6
8dce1bf646ecd4512ee5725a42af0406b8f3ff87
/src/qt/sendcoinsdialog.cpp
75661b99fa6e9012ea5d72e25979daa83a7a81f7
[ "MIT" ]
permissive
forkee/FootyCash
746c2e7fb98a1ba6053e66ae49aac16ef2922723
693712e9a196d51020fa2d5a78a0cbc4f823e39a
refs/heads/master
2021-06-21T12:51:16.191353
2017-08-14T08:45:09
2017-08-14T08:45:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,757
cpp
#include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "addressbookpage.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "askpassphrasedialog.h" #include "base58.h" #include "coincontrol.h" #include "coincontroldialog.h" #include <QMessageBox> #include <QTextDocument> #include <QScrollBar> #include <QClipboard> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a FootyCash address (e.g. DESKGUCwGyLdepa5aJUwRCGS4agCVmUoGB)")); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont()); connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &))); // Coin Control: clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels())); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { if(!model || !model->getOptionsModel()) return; QList<SendCoinsRecipient> recipients; bool valid = true; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount), Qt::escape(rcp.label), rcp.address)); } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus; if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) sendstatus = model->sendCoins(recipients); else sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed!"), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { delete ui->entries->takeAt(0)->widget(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); QCoreApplication::instance()->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { delete entry; updateRemoveEnabled(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseBitcoinURI(uri, &rv)) { CBitcoinAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(stake); Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(model && model->getOptionsModel()) { ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), balance)); } } void SendCoinsDialog::updateDisplayUnit() { setBalance(model->getBalance(), 0, 0, 0); } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" "))); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { QApplication::clipboard()->setText(ui->labelCoinControlBytes->text()); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { QApplication::clipboard()->setText(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Low output" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" "))); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (model) { if (state == Qt::Checked) CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get(); else CoinControlDialog::coinControl->destChange = CNoDestination(); } ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); ui->labelCoinControlChangeLabel->setEnabled((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString & text) { if (model) { CoinControlDialog::coinControl->destChange = CBitcoinAddress(text.toStdString()).Get(); // label for the change address ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); if (text.isEmpty()) ui->labelCoinControlChangeLabel->setText(""); else if (!CBitcoinAddress(text.toStdString()).IsValid()) { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: Invalid FootyCash address")); } else { QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else { CPubKey pubkey; CKeyID keyid; CBitcoinAddress(text.toStdString()).GetKeyID(keyid); if (model->getPubKey(keyid, pubkey)) ui->labelCoinControlChangeLabel->setText(tr("(no label)")); else { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: unknown change address")); } } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
[ "FootyCash@gmail.com" ]
FootyCash@gmail.com
1467ac93bed8889553f3de54aab20a00bf08c15e
9f81d77e028503dcbb6d7d4c0c302391b8fdd50c
/google/cloud/dialogflow_cx/internal/transition_route_groups_auth_decorator.h
3f461e77499b03c1d50fb752d10b88839ed93ce3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
googleapis/google-cloud-cpp
b96a6ee50c972371daa8b8067ddd803de95f54ba
178d6581b499242c52f9150817d91e6c95b773a5
refs/heads/main
2023-08-31T09:30:11.624568
2023-08-31T03:29:11
2023-08-31T03:29:11
111,860,063
450
351
Apache-2.0
2023-09-14T21:52:02
2017-11-24T00:19:31
C++
UTF-8
C++
false
false
3,143
h
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/dialogflow/cx/v3/transition_route_group.proto #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_DIALOGFLOW_CX_INTERNAL_TRANSITION_ROUTE_GROUPS_AUTH_DECORATOR_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_DIALOGFLOW_CX_INTERNAL_TRANSITION_ROUTE_GROUPS_AUTH_DECORATOR_H #include "google/cloud/dialogflow_cx/internal/transition_route_groups_stub.h" #include "google/cloud/internal/unified_grpc_credentials.h" #include "google/cloud/version.h" #include <memory> #include <set> #include <string> namespace google { namespace cloud { namespace dialogflow_cx_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN class TransitionRouteGroupsAuth : public TransitionRouteGroupsStub { public: ~TransitionRouteGroupsAuth() override = default; TransitionRouteGroupsAuth( std::shared_ptr<google::cloud::internal::GrpcAuthenticationStrategy> auth, std::shared_ptr<TransitionRouteGroupsStub> child); StatusOr<google::cloud::dialogflow::cx::v3::ListTransitionRouteGroupsResponse> ListTransitionRouteGroups( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ListTransitionRouteGroupsRequest const& request) override; StatusOr<google::cloud::dialogflow::cx::v3::TransitionRouteGroup> GetTransitionRouteGroup( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::GetTransitionRouteGroupRequest const& request) override; StatusOr<google::cloud::dialogflow::cx::v3::TransitionRouteGroup> CreateTransitionRouteGroup( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3:: CreateTransitionRouteGroupRequest const& request) override; StatusOr<google::cloud::dialogflow::cx::v3::TransitionRouteGroup> UpdateTransitionRouteGroup( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3:: UpdateTransitionRouteGroupRequest const& request) override; Status DeleteTransitionRouteGroup( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3:: DeleteTransitionRouteGroupRequest const& request) override; private: std::shared_ptr<google::cloud::internal::GrpcAuthenticationStrategy> auth_; std::shared_ptr<TransitionRouteGroupsStub> child_; }; GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace dialogflow_cx_internal } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_DIALOGFLOW_CX_INTERNAL_TRANSITION_ROUTE_GROUPS_AUTH_DECORATOR_H
[ "noreply@github.com" ]
googleapis.noreply@github.com
03cc0b6e3a23af6654ea4cddcde97a8cfb9c61c0
daf5d13186d5f50660fbd4b5613c807ac8403aee
/components/service/ucloud/videorecog/src/model/GetAsyncJobResultRequest.cc
f41f234ef8d5669dcd5ea6c39d887749d8a63d24
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
kerrylinux/alios-things
4350a2535e3682309a35472928272f324f260bf3
fcd091e6f96f054caed0ecec02aad15717fd424c
refs/heads/master
2023-03-29T06:20:55.405541
2021-03-25T10:01:39
2021-03-25T10:01:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,406
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/videorecog/model/GetAsyncJobResultRequest.h> using AlibabaCloud::Videorecog::Model::GetAsyncJobResultRequest; GetAsyncJobResultRequest::GetAsyncJobResultRequest() : RpcServiceRequest("videorecog", "2020-03-20", "GetAsyncJobResult") { setMethod(HttpRequest::Method::Post); } GetAsyncJobResultRequest::~GetAsyncJobResultRequest() {} bool GetAsyncJobResultRequest::getAsync()const { return async_; } void GetAsyncJobResultRequest::setAsync(bool async) { async_ = async; setBodyParameter("Async", async ? "true" : "false"); } std::string GetAsyncJobResultRequest::getJobId()const { return jobId_; } void GetAsyncJobResultRequest::setJobId(const std::string& jobId) { jobId_ = jobId; setBodyParameter("JobId", jobId); }
[ "noreply@github.com" ]
kerrylinux.noreply@github.com
aabadc9f58b1c81cb283a7c66af4f97b47ec4af4
9fcc3b454b7c97862a9845ab49cc299f11d13fec
/src/cg_opencl/oclConstants.h
f8751ab0a795b605844b11791af0dd8f1bf4243a
[ "MIT" ]
permissive
cualquiercosa327/ocl-lights
b0768457bdbdea5d4c42bcce04a0c0ff77a6a19c
507fa27b9940b5ef900d66853ef7e5e1e4ff267d
refs/heads/master
2021-06-21T17:58:04.243186
2017-08-27T13:32:37
2017-08-27T13:32:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
304
h
/*! \file oclConstants.h * \brief Enter description here. * \author Georgi Gerganov */ #pragma once namespace OCL { namespace Constants { namespace LogTags { constexpr auto kBaseManager = "BaseManager"; } namespace KernelNames { constexpr auto kBuffersFillFloat = "buffers_fill_float"; } } }
[ "ggerganov@gmail.com" ]
ggerganov@gmail.com
e29ef8120073c5e084176f221cc827639fa56da0
e902237e75136afbce099a36d1b28e45a97a7a38
/codeforces/8xx/822B.cpp
147bef831bfd86b968b51a3e66245cbce83848ce
[]
no_license
kronos/Task-solutions
40e5930c18bbaf079c33a36ace17524bda519232
ef729f7a27a79af92d82716e9bc20e5f70772117
refs/heads/master
2021-01-22T02:35:12.910777
2018-09-09T15:42:44
2018-09-09T15:42:44
295,781
2
0
null
null
null
null
UTF-8
C++
false
false
599
cpp
#include <iostream> #include <set> #include <vector> #include <map> #include <algorithm> #include <math.h> using namespace std; int n, m; string s, t; int cnt[1000]; int main() { cin >> n >> m; cin >> s >> t; for (int i = 0; i <= m-n; i++) { for (int j = 0; j < n; j++) { if (s[j] != t[i + j]) { cnt[i]++; } } } int imax = 0; for (int i = 1; i <= m-n; i++) { if (cnt[i] < cnt[imax]) { imax = i; } } cout << cnt[imax] << endl; for (int i = 0; i < n; i++) { if (s[i] != t[i+imax]) { cout << i + 1 << " "; } } return 0; }
[ "hronya@gmail.com" ]
hronya@gmail.com
d6f4284428c1b023c448358430eb24c883a2adc3
9be246df43e02fba30ee2595c8cec14ac2b355d1
/vgui2/controls/ProgressBox.cpp
b8de6f21504ba6fb5fbe32a47e9975f026dc4d9c
[]
no_license
Clepoy3/LeakNet
6bf4c5d5535b3824a350f32352f457d8be87d609
8866efcb9b0bf9290b80f7263e2ce2074302640a
refs/heads/master
2020-05-30T04:53:22.193725
2019-04-12T16:06:26
2019-04-12T16:06:26
189,544,338
18
5
null
2019-05-31T06:59:39
2019-05-31T06:59:39
null
WINDOWS-1252
C++
false
false
8,283
cpp
//========= Copyright © 1996-2003, Valve LLC, All rights reserved. ============ // // The copyright to the contents herein is the property of Valve, L.L.C. // The contents may be used and/or copied only with the written permission of // Valve, L.L.C., or in accordance with the terms and conditions stipulated in // the agreement/contract under which the contents have been supplied. // // Purpose: // // $NoKeywords: $ //============================================================================= #include <vgui/IInput.h> #include <vgui/ILocalize.h> #include <vgui/ISurface.h> #include <vgui/ISystem.h> #include <KeyValues.h> #include <vgui_controls/Button.h> #include <vgui_controls/Controls.h> #include <vgui_controls/Label.h> #include <vgui_controls/ProgressBar.h> #include <vgui_controls/ProgressBox.h> // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> using namespace vgui; #ifndef max #define max(a,b) (((a) > (b)) ? (a) : (b)) #endif //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- ProgressBox::ProgressBox(const char *title, const char *text, const char *pszUnknownTimeString, Panel *parent) : Frame(parent, NULL, false) { SetTitle(title, true); m_pMessageLabel = new Label(this, NULL, pszUnknownTimeString); const wchar_t *ws = localize()->Find(text); if (ws) { wcsncpy(m_wcsInfoString, ws, sizeof(m_wcsInfoString) / sizeof(wchar_t)); } else { m_wcsInfoString[0] = 0; } ws = localize()->Find(pszUnknownTimeString); if (ws) { wcsncpy(m_wszUnknownTimeString, ws, sizeof(m_wszUnknownTimeString) / sizeof(wchar_t)); } else { m_wszUnknownTimeString[0] = 0; } Init(); } //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- ProgressBox::ProgressBox(const wchar_t *wszTitle, const wchar_t *wszText, const wchar_t *wszUnknownTimeString, Panel *parent) : Frame(parent, NULL, false) { SetTitle(wszTitle, true); m_pMessageLabel = new Label(this, NULL, wszUnknownTimeString); wcsncpy(m_wcsInfoString, wszText, sizeof(m_wcsInfoString) / sizeof(wchar_t)); wcsncpy(m_wszUnknownTimeString, wszUnknownTimeString, sizeof(m_wszUnknownTimeString) / sizeof(wchar_t)); Init(); } //----------------------------------------------------------------------------- // Purpose: Constructor Helper //----------------------------------------------------------------------------- void ProgressBox::Init() { SetMenuButtonResponsive(false); SetMinimizeButtonVisible(false); SetCloseButtonVisible(false); SetSizeable(false); SetSize(384, 128); m_flCurrentProgress = 0.0f; m_flFirstProgressUpdate = -0.1f; m_flLastProgressUpdate = 0.0f; m_pProgressBar = new ProgressBar(this, NULL); m_pProgressBar->SetVisible(false); } //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- ProgressBox::~ProgressBox() { } //----------------------------------------------------------------------------- // Purpose: resize the message label //----------------------------------------------------------------------------- void ProgressBox::ApplySchemeSettings(IScheme *pScheme) { BaseClass::ApplySchemeSettings(pScheme); int wide, tall; m_pMessageLabel->GetContentSize(wide, tall); SetSize(384, tall + 92); m_pMessageLabel->SetSize(344, tall); } //----------------------------------------------------------------------------- // Purpose: Put the message box into a modal state // Does not suspend execution - use addActionSignal to get return value //----------------------------------------------------------------------------- void ProgressBox::DoModal(Frame *pFrameOver) { ShowWindow(pFrameOver); input()->SetAppModalSurface(GetVPanel()); } //----------------------------------------------------------------------------- // Purpose: Activates the window //----------------------------------------------------------------------------- void ProgressBox::ShowWindow(Frame *pFrameOver) { // move to the middle of the screen // get the screen size int wide, tall; // get our dialog size GetSize(wide, tall); if (pFrameOver) { int frameX, frameY; int frameWide, frameTall; pFrameOver->GetPos(frameX, frameY); pFrameOver->GetSize(frameWide, frameTall); SetPos((frameWide - wide) / 2 + frameX, (frameTall - tall) / 2 + frameY); } else { int swide, stall; surface()->GetScreenSize(swide, stall); // put the dialog in the middle of the screen SetPos((swide - wide) / 2, (stall - tall) / 2); } BaseClass::Activate(); } //----------------------------------------------------------------------------- // Purpose: Put the text and OK buttons in correct place //----------------------------------------------------------------------------- void ProgressBox::PerformLayout() { int x, y, wide, tall; GetClientArea(x, y, wide, tall); wide += x; tall += y; int leftEdge = x + 16; m_pMessageLabel->SetPos(leftEdge, y + 12); m_pProgressBar->SetPos(leftEdge, y + 14 + m_pMessageLabel->GetTall() + 2); m_pProgressBar->SetSize(wide - 44, 24); BaseClass::PerformLayout(); } //----------------------------------------------------------------------------- // Purpose: updates progress bar, range [0, 1] //----------------------------------------------------------------------------- void ProgressBox::SetProgress(float progress) { Assert(progress >= 0.0f && progress <= 1.0f); m_pProgressBar->SetProgress(progress); m_pProgressBar->SetVisible(true); // store off timings for calculating time remaining if (m_flFirstProgressUpdate < 0.0f) { m_flFirstProgressUpdate = (float)system()->GetFrameTime(); } m_flCurrentProgress = progress; m_flLastProgressUpdate = (float)system()->GetFrameTime(); } //----------------------------------------------------------------------------- // Purpose: called every render //----------------------------------------------------------------------------- void ProgressBox::OnThink() { // calculate the progress made if (m_flFirstProgressUpdate >= 0.0f && m_wcsInfoString[0]) { wchar_t timeRemaining[128]; if (ProgressBar::ConstructTimeRemainingString(timeRemaining, sizeof(timeRemaining), m_flFirstProgressUpdate, (float)system()->GetFrameTime(), m_flCurrentProgress, m_flLastProgressUpdate, true)) { wchar_t unicode[256]; localize()->ConstructString(unicode, sizeof(unicode), m_wcsInfoString, 1, timeRemaining); m_pMessageLabel->SetText(unicode); } else { m_pMessageLabel->SetText(m_wszUnknownTimeString); } } } //----------------------------------------------------------------------------- // Purpose: Deletes self when closed //----------------------------------------------------------------------------- void ProgressBox::OnClose() { BaseClass::OnClose(); // modal surface is released on deletion MarkForDeletion(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void ProgressBox::OnShutdownRequest() { // Shutdown the dialog PostMessage(this, new KeyValues("Close")); } //----------------------------------------------------------------------------- // Purpose: Toggles visibility of the close box. //----------------------------------------------------------------------------- void ProgressBox::DisableCloseButton(bool state) { BaseClass::SetCloseButtonVisible(state); } //----------------------------------------------------------------------------- // Purpose: Message map //----------------------------------------------------------------------------- MessageMapItem_t ProgressBox::m_MessageMap[] = { MAP_MESSAGE( ProgressBox, "ShutdownRequest", OnShutdownRequest ), }; IMPLEMENT_PANELMAP(ProgressBox, BaseClass);
[ "uavxp29@gmail.com" ]
uavxp29@gmail.com
b64693f1b4c0728cada2af7285f2306da3a2a7c1
a9f3dd9722687682e65d98cd69190f1af4a3e5d5
/Core/library_loader/elf_utils.h
7af490d41a5436cbe650a97814721316d88e0c6a
[ "MIT" ]
permissive
codeteenager/lynx-native
20cc4a02c474c84e8cd9a242c000c1520412dd19
149b895b03f05fb34ab6fa3b66e739d2e5d6f35b
refs/heads/master
2020-03-19T03:05:38.414000
2018-05-30T06:49:09
2018-05-30T06:49:09
135,694,315
1
0
null
2018-06-01T09:00:30
2018-06-01T09:00:30
null
UTF-8
C++
false
false
349
h
#ifndef BASE_LIBRARY_LOADER_ELF_UTILS_H_ #define BASE_LIBRARY_LOADER_ELF_UTILS_H_ #include "library_loader/user_elf.h" #include "string.h" namespace elf { void CallVoidFunction(void* ptr); unsigned long SysVHash(const char* symbol); unsigned long GNUHash(const char* symbol); const char* LeafName(const char* path); } // namespace elf #endif
[ "leedongjx@gmail.com" ]
leedongjx@gmail.com
eb8aa0f7ffe65559e7634a86c58720153d38a973
58a3caa2acbc1db538331170876e34ad5ad7e160
/zh/szg_zh_180525_naprendszer_meo_kr/01_OGLBase/GLconversions.hpp
27a8f2e09f484c37b5a5b714f558ec7b51ae8b62
[]
no_license
8emi95/elte-ik-szg
b55271dbf95d6e2d1cbbf42a924d74d28aec1b38
f66c2582a8796c569bb5cf70ecc31e56e5132b01
refs/heads/master
2020-11-24T02:28:30.235368
2020-10-20T16:56:12
2020-10-20T16:56:12
227,925,339
0
0
null
null
null
null
UTF-8
C++
false
false
10,392
hpp
#pragma once #include <GL\glew.h> #include <GL\GL.h> #include <utility> #include <string> #include <vector> #include <array> #include <type_traits> /* Convenience conversion functions to simplify the creation of ShaderObject objects using the _vs, _tcs, _tes, _gs, _fs, and _comp suffices. */ using TypeSourcePair = std::pair<GLuint, std::string>; inline TypeSourcePair operator"" _vs (const char * str, size_t len) { return std::make_pair(GL_VERTEX_SHADER, std::string{ str, len }); } inline TypeSourcePair operator"" _tcs (const char * str, size_t len) { return std::make_pair(GL_TESS_CONTROL_SHADER, std::string{ str, len }); } inline TypeSourcePair operator"" _tes (const char * str, size_t len) { return std::make_pair(GL_TESS_EVALUATION_SHADER, std::string{ str, len }); } inline TypeSourcePair operator"" _gs (const char * str, size_t len) { return std::make_pair(GL_GEOMETRY_SHADER, std::string{ str, len }); } inline TypeSourcePair operator"" _fs (const char * str, size_t len) { return std::make_pair(GL_FRAGMENT_SHADER, std::string{ str, len }); } inline TypeSourcePair operator"" _comp(const char * str, size_t len) { return std::make_pair(GL_COMPUTE_SHADER, std::string{ str, len }); } /* Enabler templates to restruct SetUniform utility function instantiations to supported types only. */ template <typename T> using IsValidBaseType = std::enable_if_t< std::is_same_v<T, GLint> || std::is_same_v<T, GLuint> || std::is_same_v<T, GLfloat> || std::is_same_v<T, GLdouble> >; #ifdef GLM_VERSION template <typename T, glm::precision P = glm::defaultp> using IsValidGLMVectorType = std::enable_if_t< std::is_base_of_v<glm::tvec1<typename T::value_type, P>, T> || std::is_base_of_v<glm::tvec2<typename T::value_type, P>, T> || std::is_base_of_v<glm::tvec3<typename T::value_type, P>, T> || std::is_base_of_v<glm::tvec4<typename T::value_type, P>, T> >; template <typename T, glm::precision P = glm::defaultp> using IsValidGLMMatrixType = std::enable_if_t< std::is_base_of_v<glm::tmat2x2<typename T::value_type, P>, T> || std::is_base_of_v<glm::tmat2x3<typename T::value_type, P>, T> || std::is_base_of_v<glm::tmat2x4<typename T::value_type, P>, T> || std::is_base_of_v<glm::tmat3x2<typename T::value_type, P>, T> || std::is_base_of_v<glm::tmat3x4<typename T::value_type, P>, T> || std::is_base_of_v<glm::tmat3x4<typename T::value_type, P>, T> || std::is_base_of_v<glm::tmat4x2<typename T::value_type, P>, T> || std::is_base_of_v<glm::tmat4x3<typename T::value_type, P>, T> || std::is_base_of_v<glm::tmat4x4<typename T::value_type, P>, T> >; #endif /* Convert types to OpenGL type GLenum values listed in https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glVertexAttribPointer.xhtml */ template <typename T> constexpr GLenum NativeTypeToOpenGLType() { static_assert(true, "Non-supported vertex attribute type"); } template <> constexpr GLenum NativeTypeToOpenGLType<float>() { return GL_FLOAT; } template <> constexpr GLenum NativeTypeToOpenGLType<double>() { return GL_DOUBLE; } // we have to provide these extraction functions because tvec<*,*>::length(), cols(), rows() are not defined as a constexpr... template<typename T> constexpr std::pair<size_t, size_t> ComponentCount() { return std::make_pair(1, 1); } #ifdef GLM_VERSION #define COMPONENT_COUNT_SPECIALIZATION(TYPE, DIM_X, DIM_Y) template<> constexpr std::pair<size_t, size_t> ComponentCount<TYPE>() { return std::make_pair(DIM_X, DIM_Y); } COMPONENT_COUNT_SPECIALIZATION(glm::vec2, 2, 1) COMPONENT_COUNT_SPECIALIZATION(glm::vec3, 3, 1) COMPONENT_COUNT_SPECIALIZATION(glm::vec4, 4, 1) COMPONENT_COUNT_SPECIALIZATION(glm::mat2, 2, 2) COMPONENT_COUNT_SPECIALIZATION(glm::mat3, 3, 3) COMPONENT_COUNT_SPECIALIZATION(glm::mat4, 4, 4) COMPONENT_COUNT_SPECIALIZATION(glm::mat4x3, 4, 3) COMPONENT_COUNT_SPECIALIZATION(glm::mat4x2, 4, 2) COMPONENT_COUNT_SPECIALIZATION(glm::mat3x2, 3, 2) COMPONENT_COUNT_SPECIALIZATION(glm::mat3x4, 3, 4) COMPONENT_COUNT_SPECIALIZATION(glm::mat2x3, 2, 3) COMPONENT_COUNT_SPECIALIZATION(glm::mat2x4, 2, 4) #endif /* Extract primitive type of argument, i.e. what is the base type (e.g. float) of whatever construct (e.g. glm::vec3, glm::mat4, etc.) we received. */ template <typename T, typename C = void> struct GLExtractPrimitiveType; template <typename T> struct GLExtractPrimitiveType<T, IsValidBaseType<T>> { using primitive_type = T;}; #ifdef GLM_VERSION template <typename T> struct GLExtractPrimitiveType<T, IsValidGLMVectorType<T>> { using primitive_type = typename T::value_type; }; template <typename T> struct GLExtractPrimitiveType<T, IsValidGLMMatrixType<T>> { using primitive_type = typename T::value_type; }; #endif /* Selection of appropriate OpenGL glUniform* function, depending on argument primitive type. */ template <typename T, int N, int M> inline void CallSetter(GLint, GLsizei, const T*) { } #define CALL_SETTER_VECTOR_SPECIALIZATION(TYPE, DIM_X, FUNCTION) template <> inline void CallSetter<TYPE, DIM_X, 1>(GLint pLoc, GLsizei pCount, const TYPE* pArg) { FUNCTION(pLoc, pCount, pArg); } #define CALL_SETTER_MATRIX_SPECIALIZATION(TYPE, DIM_X, DIM_Y, FUNCTION) template <> inline void CallSetter<TYPE, DIM_X, DIM_Y>(GLint pLoc, GLsizei pCount, const TYPE* pArg) { FUNCTION(pLoc, pCount, GL_FALSE, pArg); } CALL_SETTER_VECTOR_SPECIALIZATION(GLint, 1, glUniform1iv ) CALL_SETTER_VECTOR_SPECIALIZATION(GLint, 2, glUniform2iv ) CALL_SETTER_VECTOR_SPECIALIZATION(GLint, 3, glUniform3iv ) CALL_SETTER_VECTOR_SPECIALIZATION(GLint, 4, glUniform4iv ) CALL_SETTER_VECTOR_SPECIALIZATION(GLuint, 1, glUniform1uiv) CALL_SETTER_VECTOR_SPECIALIZATION(GLuint, 2, glUniform2uiv) CALL_SETTER_VECTOR_SPECIALIZATION(GLuint, 3, glUniform3uiv) CALL_SETTER_VECTOR_SPECIALIZATION(GLuint, 4, glUniform4uiv) CALL_SETTER_VECTOR_SPECIALIZATION(GLfloat, 1, glUniform1fv ) CALL_SETTER_VECTOR_SPECIALIZATION(GLfloat, 2, glUniform2fv ) CALL_SETTER_VECTOR_SPECIALIZATION(GLfloat, 3, glUniform3fv ) CALL_SETTER_VECTOR_SPECIALIZATION(GLfloat, 4, glUniform4fv ) CALL_SETTER_VECTOR_SPECIALIZATION(GLdouble, 1, glUniform1dv ) CALL_SETTER_VECTOR_SPECIALIZATION(GLdouble, 2, glUniform2dv ) CALL_SETTER_VECTOR_SPECIALIZATION(GLdouble, 3, glUniform3dv ) CALL_SETTER_VECTOR_SPECIALIZATION(GLdouble, 4, glUniform4dv ) CALL_SETTER_MATRIX_SPECIALIZATION(GLfloat, 4, 4, glUniformMatrix4fv) CALL_SETTER_MATRIX_SPECIALIZATION(GLfloat, 3, 3, glUniformMatrix3fv) CALL_SETTER_MATRIX_SPECIALIZATION(GLfloat, 2, 2, glUniformMatrix2fv) CALL_SETTER_MATRIX_SPECIALIZATION(GLfloat, 4, 3, glUniformMatrix4x3fv) CALL_SETTER_MATRIX_SPECIALIZATION(GLfloat, 4, 2, glUniformMatrix4x2fv) CALL_SETTER_MATRIX_SPECIALIZATION(GLfloat, 3, 4, glUniformMatrix3x4fv) CALL_SETTER_MATRIX_SPECIALIZATION(GLfloat, 2, 4, glUniformMatrix2x4fv) CALL_SETTER_MATRIX_SPECIALIZATION(GLfloat, 3, 2, glUniformMatrix3x2fv) CALL_SETTER_MATRIX_SPECIALIZATION(GLfloat, 2, 3, glUniformMatrix2x3fv) CALL_SETTER_MATRIX_SPECIALIZATION(GLdouble, 4, 4, glUniformMatrix4dv) CALL_SETTER_MATRIX_SPECIALIZATION(GLdouble, 3, 3, glUniformMatrix3dv) CALL_SETTER_MATRIX_SPECIALIZATION(GLdouble, 2, 2, glUniformMatrix2dv) CALL_SETTER_MATRIX_SPECIALIZATION(GLdouble, 4, 3, glUniformMatrix4x3dv) CALL_SETTER_MATRIX_SPECIALIZATION(GLdouble, 4, 2, glUniformMatrix4x2dv) CALL_SETTER_MATRIX_SPECIALIZATION(GLdouble, 3, 4, glUniformMatrix3x4dv) CALL_SETTER_MATRIX_SPECIALIZATION(GLdouble, 2, 4, glUniformMatrix2x4dv) CALL_SETTER_MATRIX_SPECIALIZATION(GLdouble, 3, 2, glUniformMatrix3x2dv) CALL_SETTER_MATRIX_SPECIALIZATION(GLdouble, 2, 3, glUniformMatrix2x3dv) /* Extract the type of the argument elements. In case of a scalar, this means the type of the argument. In case of containers this, boils down to the type of the array elements. */ template <typename T> struct ElementInfo { using value_type = T; }; template <typename T> struct ElementInfo<std::vector<T>> { using value_type = T; }; template <typename T, size_t N> struct ElementInfo<std::array<T, N>> { using value_type = T; }; template <typename T, size_t N> struct ElementInfo<T[N]> { using value_type = T; }; /* Compute the length of the container in _elements_ in types that our SetUniform supports. */ template <typename T> constexpr GLsizei ContainerLength(const T&) { return 1; } template <typename T, size_t N> constexpr GLsizei ContainerLength(const std::array<T, N>&) { return N; } template <typename T, size_t N> constexpr GLsizei ContainerLength(const T(&)[N]) { return N; } template <typename T> constexpr GLsizei ContainerLength(const std::vector<T>& pArr) { return (GLsizei)pArr.size(); } /* Compute the length of the container in _bytes_. */ template <typename T> constexpr GLsizei ContainerSizeInBytes(const T&) { return sizeof(T); } template <typename T, size_t N> constexpr GLsizei ContainerSizeInBytes(const std::array<T, N>&) { return N*sizeof(T); } template <typename T, size_t N> constexpr GLsizei ContainerSizeInBytes(const T(&)[N]) { return N*sizeof(T); } template <typename T> constexpr GLsizei ContainerSizeInBytes(const std::vector<T>& pArr) { return (GLsizei)(pArr.size()*sizeof(T)); } /* Get a pointer to the beginning of the container. In case of non-contagious containers this should involve the creation of a contagious copy of the contents of the passed in containers. */ template <typename T> constexpr const T* PointerToStart(const T& pArg) { return &pArg; } template <typename T, size_t N> constexpr const T* PointerToStart(const std::array<T, N>& pArg) { return &pArg[0]; } template <typename T, size_t N> constexpr const T* PointerToStart(const T(&pArg)[N]) { return &pArg[0]; } template <typename T> constexpr const T* PointerToStart(const std::vector<T>& pArg) { return pArg.empty() ? nullptr: pArg.data(); } /* Helper constexpr to determine if the supplied parameter is a supported contagious container or not. */ template<typename T> struct HasContiguousStorage : public std::false_type { }; template<typename T> struct HasContiguousStorage<std::vector<T>> : public std::true_type {}; template<typename T, size_t N> struct HasContiguousStorage<std::array<T, N>> : public std::true_type {}; template<typename T, size_t N> struct HasContiguousStorage< T[N]> : public std::true_type {}; template <typename T, typename R = void> using IsContiguousContainer = std::enable_if_t<HasContiguousStorage< T>::value, R>;
[ "8emi95@inf.elte.hu" ]
8emi95@inf.elte.hu
1f91dc2b1b30a29ba07ae7777e3fef5be3c919aa
93a8bf81266dd9561294690f99fa6a6e2516e040
/Compression/QRCode/QRCode.cpp
6e6f72f25a91b8d0e972da2bc06394d40f086e33
[]
no_license
Samyo34/Master2
a4bd7626f8f680646868e07c24c7b3c1996b37a5
7d63edbd9078468d70b62024ff69fcda0a362251
refs/heads/master
2021-01-01T05:46:59.606386
2015-12-06T10:48:54
2015-12-06T10:48:54
42,724,706
0
0
null
null
null
null
UTF-8
C++
false
false
3,920
cpp
#include "image_ppm.h" #include <stdio.h> #include <stdlib.h> #include <iostream> #include <cmath> using namespace std; int getMax(OCTET* in, int lignes, int colonnes){ int max=0; for(int i=0;i<lignes;i++){ for(int j=0;j<colonnes;j++){ if(in[i*lignes+j]>max){ max = in[i*lignes+j]; } } } return max; } int getMin(OCTET* in,int lignes, int colonnes){ int min = 255; for(int i=0;i<lignes;i++){ for(int j=0;j<colonnes;j++){ if(in[i*lignes+j]<min){ min = in[i*lignes+j]; } } } return min; } void binarisation(OCTET* in, OCTET* out, int lignes, int colonnes, int min, int max){ int th = (max-min)/2; for(int i=0;i<lignes;i++){ for(int j = 0;j<colonnes;j++){ if(in[i*lignes+j]>th){ out[i*lignes+j]=255; }else{ out[i*lignes+j]=0; } } } } int vote(OCTET* ImgIn,int posI,int posJ, int lignes, int colonnes,int p, int th){ int nbSup =0; int nbInf=0; for(int i=posI;i<posI+p;i++){ for(int j=posJ;j<posJ+p;j++){ if(ImgIn[i*lignes+j]>th){ nbSup++; }else{ nbInf++; } } } if(nbSup>nbInf){ return 255; }else{ return 0; } } void binarisationByVote(OCTET* in, OCTET* out, int lignes, int colonnes, int min, int max, int p){ int th = (max-min)/2; int res; for(int i=0;i<lignes;i+=p){ for(int j = 0;j<colonnes;j+=p){ res = vote(in,i,j,lignes,colonnes,p,th); for(int x=0;x<p;x++){ for(int y=0;y<p;y++){ if(res>0){ out[(i+x)*lignes+(j+y)]=255; }else{ out[(i+x)*lignes+(j+y)]=0; } } } } } } /* *Retourne un tableau contenant la moyenne des ndg et l'ecart type de la fenetre centré en x,y */ float* getLocal(OCTET* in, int lignes, int colonnes, int tailleFenetre, int x, int y){ int taille = (tailleFenetre-1)/2; int debX = x-taille; int debY = y-taille; int finX = x+taille; int finY = y+taille; float* tab = new float[2]; float somme =0; int cpt =0; if(debX<=0){ debX=x; } if(debY<=0){ debY=y; } if(finX>=lignes){ finX = lignes; } if(finY>=colonnes){ finY = colonnes; } for(int i=debX;i<finX;i++){ for(int j=debY;j<finY;j++){ somme += in[(i*lignes+j)]; cpt++; } } tab[0]=somme/(float)cpt; for(int i=debX;i<finX;i++){ for(int j=debY;j<finY;j++){ somme += pow(in[(i*lignes+j)]-tab[0],2); } } tab[1]=somme/(float)cpt; return tab; } void binarisationLocal(OCTET* in, OCTET* out, int lignes, int colonnes, int tailleFenetre){ float* tab; float seuil; for(int i=0;i<lignes;i++){ for(int j=0;j<colonnes;j++){ tab = getLocal(in, lignes, colonnes,tailleFenetre,i,j); seuil = tab[0] + 0.2 * tab[1]; std::cout<<seuil<<std::endl; if(in[i*lignes+j]>seuil){ out[i*lignes+j]=255; }else{ out[i*lignes+j]=0; } } } } int main(int argc, char* argv[]){ char cNomImgLue[250]; int* p; char bin[250] = "binarisation.pgm"; char bin2[250] = "binarisationByVote.pgm"; char bin3[250] = "binarisationLocal.pgm"; int lignes, colonnes, nTaille, S; if (argc != 3) { printf("Usage: ImageIn.pgm taille_module\n"); exit (1) ; } sscanf (argv[1],"%s",cNomImgLue); //sscanf (argv[2],"%d",p); OCTET *ImgIn, *ImgOut, *ImgOut2,*ImgOut3; lire_nb_lignes_colonnes_image_pgm(cNomImgLue, &lignes, &colonnes); nTaille = lignes * colonnes; allocation_tableau(ImgIn, OCTET, nTaille); lire_image_pgm(cNomImgLue, ImgIn, lignes * colonnes); allocation_tableau(ImgOut, OCTET, nTaille); allocation_tableau(ImgOut2, OCTET, nTaille); allocation_tableau(ImgOut3,OCTET, nTaille); int min = getMin(ImgIn,lignes,colonnes); int max = getMax(ImgIn,lignes,colonnes); binarisation(ImgIn,ImgOut,lignes,colonnes,min,max); binarisationByVote(ImgIn,ImgOut2,lignes,colonnes,min,max,7); binarisationLocal(ImgIn, ImgOut3,lignes,colonnes,7); ecrire_image_pgm(bin, ImgOut, lignes, colonnes); ecrire_image_pgm(bin2, ImgOut2, lignes, colonnes); ecrire_image_pgm(bin3,ImgOut3,lignes,colonnes); free(ImgIn); return 1; }
[ "sambricas@hotmail.com" ]
sambricas@hotmail.com
d419d16112c8c5f95e682aab18ff13482ad941d3
c964a9b36a3d3203ceec0f3e63a8bf680bb94ea4
/MyAssist/nlp++/tools/util/BeamSearch.h
234d77e9967c7c046e09932515bfbf4f3956b3e1
[]
no_license
benlm54/myassist-repo
f95bc3c5b033acd19294047b67e35e9fcfa91bd5
fd24c3bb4eeb86b88e2d0052a6d272f3cdbc6c7f
refs/heads/master
2021-03-12T22:22:40.330433
2013-01-09T23:18:56
2013-01-09T23:18:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,890
h
#ifndef BEAMSEARCH #define BEAMSEARCH #include "BeamSearchContextGenerator.h" #include "../model/MaxentModel.h" #include "SequenceValidator.h" #include "Cache.h" #include "../model/Sequence.h" #include "Sequence.h" #include "Heap.h" #include "ListHeap.h" #include <string> #include <vector> #include <cmath> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreemnets. 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. */ namespace opennlp { namespace tools { namespace util { using opennlp::model::MaxentModel; /// <summary> /// Performs k-best search over sequence. This is based on the description in /// Ratnaparkhi (1998), PhD diss, Univ. of Pennsylvania. /// </summary> /// <seealso cref= Sequence </seealso> /// <seealso cref= SequenceValidator </seealso> /// <seealso cref= BeamSearchContextGenerator </seealso> template<typename T> class BeamSearch { private: //ORIGINAL LINE: private static final Object[] EMPTY_ADDITIONAL_CONTEXT = new Object[0]; //JAVA TO C++ CONVERTER WARNING: Since the array size is not known in this declaration, Java to C++ Converter has converted this array to a pointer. You will need to call 'delete[]' where appropriate: //JAVA TO C++ CONVERTER TODO TASK: Native C++ only allows initialization of static const integral fields in their declarations: static const void *EMPTY_ADDITIONAL_CONTEXT = new Object[0]; protected: int size; BeamSearchContextGenerator<T> *cg; MaxentModel *model; private: SequenceValidator<T> *validator; //ORIGINAL LINE: private double[] probs; //JAVA TO C++ CONVERTER WARNING: Since the array size is not known in this declaration, Java to C++ Converter has converted this array to a pointer. You will need to call 'delete[]' where appropriate: double *probs; Cache *contextsCache; static const int zeroLog = -100000; /// <summary> /// Creates new search object. /// </summary> /// <param name="size"> The size of the beam (k). </param> /// <param name="cg"> the context generator for the model. </param> /// <param name="model"> the model for assigning probabilities to the sequence outcomes. </param> public: //JAVA TO C++ CONVERTER TODO TASK: Calls to same-class constructors are not supported in C++ prior to C++11: BeamSearch(int size, BeamSearchContextGenerator<T> *cg, MaxentModel *model) //this(size, cg, model, nullptr, 0); { } //JAVA TO C++ CONVERTER TODO TASK: Calls to same-class constructors are not supported in C++ prior to C++11: BeamSearch(int size, BeamSearchContextGenerator<T> *cg, MaxentModel *model, int cacheSize) //this(size, cg, model, nullptr, cacheSize); { } BeamSearch(int size, BeamSearchContextGenerator<T> *cg, MaxentModel *model, SequenceValidator<T> *validator, int cacheSize) { this->size = size; this->cg = cg; this->model = model; this->validator = validator; if (cacheSize > 0) { contextsCache = new Cache(cacheSize); } this->probs = new double[model->getNumOutcomes()]; } /// <summary> /// Note: /// This method will be private in the future because clients can now /// pass a validator to validate the sequence. /// </summary> /// <seealso cref= SequenceValidator </seealso> private: bool validSequence(int i, T inputSequence[], std::string outcomesSequence[], const std::string &outcome) { if (validator != 0) { return validator->validSequence(i, inputSequence, outcomesSequence, outcome); } else { return true; } } public: virtual Sequence *bestSequences(int numSequences, T sequence[], Object additionalContext[]) { return bestSequences(numSequences, sequence, additionalContext, zeroLog); } /// <summary> /// Returns the best sequence of outcomes based on model for this object. /// </summary> /// <param name="numSequences"> The maximum number of sequences to be returned. </param> /// <param name="sequence"> The input sequence. </param> /// <param name="additionalContext"> An Object[] of additional context. This is passed to the context generator blindly with the assumption that the context are appropiate. </param> /// <param name="minSequenceScore"> A lower bound on the score of a returned sequence. </param> /// <returns> An array of the top ranked sequences of outcomes. </returns> virtual Sequence *bestSequences(int numSequences, T sequence[], Object additionalContext[], double minSequenceScore) { Heap<Sequence*> *prev = new ListHeap<Sequence*>(size); Heap<Sequence*> *next = new ListHeap<Sequence*>(size); Heap<Sequence*> *tmp; prev->add(new Sequence()); if (additionalContext == 0) { additionalContext = EMPTY_ADDITIONAL_CONTEXT; } for (int i = 0; i < sizeof(sequence) / sizeof(sequence[0]); i++) { int sz = __min(size, prev->size()); for (int sc = 0; prev->size() > 0 && sc < sz; sc++) { Sequence *top = prev->extract(); std::vector<std::string> tmpOutcomes = top->getOutcomes(); //ORIGINAL LINE: String[] outcomes = tmpOutcomes.toArray(new String[tmpOutcomes.size()]); //JAVA TO C++ CONVERTER WARNING: Since the array size is not known in this declaration, Java to C++ Converter has converted this array to a pointer. You will need to call 'delete[]' where appropriate: std::string *outcomes = tmpOutcomes.toArray(new std::string[tmpOutcomes.size()]); //ORIGINAL LINE: String[] contexts = cg.getContext(i, sequence, outcomes, additionalContext); //JAVA TO C++ CONVERTER WARNING: Since the array size is not known in this declaration, Java to C++ Converter has converted this array to a pointer. You will need to call 'delete[]' where appropriate: std::string *contexts = cg->getContext(i, sequence, outcomes, additionalContext); //ORIGINAL LINE: double[] scores; //JAVA TO C++ CONVERTER WARNING: Since the array size is not known in this declaration, Java to C++ Converter has converted this array to a pointer. You will need to call 'delete[]' where appropriate: double *scores; if (contextsCache != 0) { scores = static_cast<double[]>(contextsCache->get_Renamed(contexts)); if (scores == 0) { scores = model->eval(contexts, probs); contextsCache->put(contexts,scores); } } else { scores = model->eval(contexts, probs); } double temp_scores[scores->length]; for (int c = 0; c < scores->length; c++) { temp_scores[c] = scores[c]; } Arrays::sort(temp_scores); double min = temp_scores[__max(0,scores->length - size)]; for (int p = 0; p < scores->length; p++) { if (scores[p] < min) continue; //only advance first "size" outcomes std::string out = model->getOutcome(p); if (validSequence(i, sequence, outcomes, out)) { Sequence *ns = new Sequence(top, out, scores[p]); if (ns->getScore() > minSequenceScore) { next->add(ns); } } } if (next->size() == 0) //if no advanced sequences, advance all valid { for (int p = 0; p < scores->length; p++) { std::string out = model->getOutcome(p); if (validSequence(i, sequence, outcomes, out)) { Sequence *ns = new Sequence(top, out, scores[p]); if (ns->getScore() > minSequenceScore) { next->add(ns); } } } } } // make prev = next; and re-init next (we reuse existing prev set once we clear it) prev->clear(); tmp = prev; prev = next; next = tmp; } int numSeq = __min(numSequences, prev->size()); Sequence topSequences[numSeq]; for (int seqIndex = 0; seqIndex < numSeq; seqIndex++) { topSequences[seqIndex] = prev->extract(); } return topSequences; } /// <summary> /// Returns the best sequence of outcomes based on model for this object. /// </summary> /// <param name="sequence"> The input sequence. </param> /// <param name="additionalContext"> An Object[] of additional context. This is passed to the context generator blindly with the assumption that the context are appropiate. /// </param> /// <returns> The top ranked sequence of outcomes or null if no sequence could be found </returns> virtual Sequence *bestSequence(T sequence[], Object additionalContext[]) { //ORIGINAL LINE: Sequence sequences[] = bestSequences(1, sequence, additionalContext,zeroLog); //JAVA TO C++ CONVERTER WARNING: Since the array size is not known in this declaration, Java to C++ Converter has converted this array to a pointer. You will need to call 'delete[]' where appropriate: Sequence *sequences = bestSequences(1, sequence, additionalContext,zeroLog); if (sequences->length > 0) return sequences[0]; else return 0; } }; } } } #endif //#ifndef BEAMSEARCH
[ "benlm54@gmail.com" ]
benlm54@gmail.com
07a4f488b3f94ffb208c0d5336a2f06776698395
3670f46666214ef5e1ce6765e47b24758f3614a9
/oneflow/user/ops/broadcast_div_grad_op.cpp
fd597a8768ceec3420649de9adc7a5a07f4040f0
[ "Apache-2.0" ]
permissive
ashing-zhang/oneflow
0b8bb478ccd6cabea2dca0864defddab231919bf
70db228a4d361c916f8f8d85e908795b479e5d20
refs/heads/master
2022-12-14T21:13:46.752535
2020-09-07T03:08:52
2020-09-07T03:08:52
293,535,931
1
0
Apache-2.0
2020-09-07T13:28:25
2020-09-07T13:28:24
null
UTF-8
C++
false
false
2,378
cpp
/* Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "oneflow/core/framework/framework.h" namespace oneflow { REGISTER_USER_OP("broadcast_div_grad") .Input("y") .Input("z") .Input("dz") .Output("dy") .SetTensorDescInferFn([](user_op::InferContext* ctx) -> Maybe<void> { *ctx->TensorDesc4ArgNameAndIndex("dy", 0) = *ctx->TensorDesc4ArgNameAndIndex("y", 0); return Maybe<void>::Ok(); }) .SetBatchAxisInferFn(user_op::BatchAxisInferFnUtil::NaiveInferBatchAxis) .SetGetSbpFn([](user_op::SbpContext* ctx) -> Maybe<void> { const Shape& y_shape = ctx->LogicalTensorDesc4InputArgNameAndIndex("y", 0).shape(); const Shape& z_shape = ctx->LogicalTensorDesc4InputArgNameAndIndex("z", 0).shape(); CHECK_LE_OR_RETURN(y_shape.NumAxes(), z_shape.NumAxes()); FOR_RANGE(int64_t, i, 0, y_shape.NumAxes()) { const int64_t axis_y = y_shape.NumAxes() - 1 - i; const int64_t axis_z = z_shape.NumAxes() - 1 - i; if (y_shape.At(axis_y) == z_shape.At(axis_z)) { ctx->NewBuilder() .Split(user_op::OpArg("y", 0), axis_y) .Split(user_op::OpArg("z", 0), axis_z) .Split(user_op::OpArg("dz", 0), axis_z) .Split(user_op::OpArg("dy", 0), axis_y) .Build(); } } ctx->NewBuilder() .Broadcast(user_op::OpArg("y", 0)) .PartialSum(user_op::OpArg("z", 0)) .Broadcast(user_op::OpArg("dz", 0)) .Broadcast(user_op::OpArg("dy", 0)) .Build(); ctx->NewBuilder() .Broadcast(user_op::OpArg("y", 0)) .Broadcast(user_op::OpArg("z", 0)) .PartialSum(user_op::OpArg("dz", 0)) .Broadcast(user_op::OpArg("dy", 0)) .Build(); return Maybe<void>::Ok(); }); } // namespace oneflow
[ "noreply@github.com" ]
ashing-zhang.noreply@github.com
fb7cdc7f19966491f988f8db49f3c8364bfd5fcc
1af49694004c6fbc31deada5618dae37255ce978
/media/gpu/chromeos/image_processor_test.cc
c13ee59f2d3fecbb74dd9fe703d22fdc2e23edba
[ "BSD-3-Clause" ]
permissive
sadrulhc/chromium
59682b173a00269ed036eee5ebfa317ba3a770cc
a4b950c23db47a0fdd63549cccf9ac8acd8e2c41
refs/heads/master
2023-02-02T07:59:20.295144
2020-12-01T21:32:32
2020-12-01T21:32:32
317,678,056
3
0
BSD-3-Clause
2020-12-01T21:56:26
2020-12-01T21:56:25
null
UTF-8
C++
false
false
15,641
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include <string> #include <tuple> #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/hash/md5.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "media/base/video_frame.h" #include "media/base/video_frame_layout.h" #include "media/base/video_types.h" #include "media/gpu/chromeos/fourcc.h" #include "media/gpu/chromeos/image_processor.h" #include "media/gpu/test/image.h" #include "media/gpu/test/image_processor/image_processor_client.h" #include "media/gpu/test/video_frame_file_writer.h" #include "media/gpu/test/video_frame_helpers.h" #include "media/gpu/test/video_frame_validator.h" #include "media/gpu/test/video_test_environment.h" #include "mojo/core/embedder/embedder.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/geometry/size.h" namespace media { namespace { const char* usage_msg = "usage: image_processor_test\n" "[--gtest_help] [--help] [-v=<level>] [--vmodule=<config>] " "[--save_images]\n"; const char* help_msg = "Run the image processor tests.\n\n" "The following arguments are supported:\n" " --gtest_help display the gtest help and exit.\n" " --help display this help and exit.\n" " -v enable verbose mode, e.g. -v=2.\n" " --vmodule enable verbose mode for the specified module.\n" " --save_images write images processed by a image processor to\n" " the \"<testname>\" folder.\n"; bool g_save_images = false; media::test::VideoTestEnvironment* g_env; // Files for pixel format conversion test. // TODO(crbug.com/944822): Use kI420Image for I420 -> NV12 test case. It is // currently disabled because there is currently no way of creating DMABUF I420 // buffer by NativePixmap. // constexpr const base::FilePath::CharType* kI420Image = // FILE_PATH_LITERAL("bear_320x192.i420.yuv"); const base::FilePath::CharType* kNV12Image = FILE_PATH_LITERAL("bear_320x192.nv12.yuv"); const base::FilePath::CharType* kRGBAImage = FILE_PATH_LITERAL("bear_320x192.rgba"); const base::FilePath::CharType* kBGRAImage = FILE_PATH_LITERAL("bear_320x192.bgra"); const base::FilePath::CharType* kYV12Image = FILE_PATH_LITERAL("bear_320x192.yv12.yuv"); // Files for scaling test. const base::FilePath::CharType* kNV12Image720P = FILE_PATH_LITERAL("puppets-1280x720.nv12.yuv"); const base::FilePath::CharType* kNV12Image360P = FILE_PATH_LITERAL("puppets-640x360.nv12.yuv"); const base::FilePath::CharType* kNV12Image270P = FILE_PATH_LITERAL("puppets-480x270.nv12.yuv"); const base::FilePath::CharType* kNV12Image180P = FILE_PATH_LITERAL("puppets-320x180.nv12.yuv"); const base::FilePath::CharType* kNV12Image360PIn480P = FILE_PATH_LITERAL("puppets-640x360_in_640x480.nv12.yuv"); // Files for rotation test. const base::FilePath::CharType* kNV12Image90 = FILE_PATH_LITERAL("bear_192x320_90.nv12.yuv"); const base::FilePath::CharType* kNV12Image180 = FILE_PATH_LITERAL("bear_320x192_180.nv12.yuv"); const base::FilePath::CharType* kNV12Image270 = FILE_PATH_LITERAL("bear_192x320_270.nv12.yuv"); class ImageProcessorParamTest : public ::testing::Test, public ::testing::WithParamInterface< std::tuple<base::FilePath, base::FilePath>> { public: void SetUp() override {} void TearDown() override { model_frames_.clear(); } std::unique_ptr<test::ImageProcessorClient> CreateImageProcessorClient( const test::Image& input_image, const std::vector<VideoFrame::StorageType>& input_storage_types, test::Image* const output_image, const std::vector<VideoFrame::StorageType>& output_storage_types) { bool is_single_planar_input = true; bool is_single_planar_output = true; #if defined(ARCH_CPU_ARM_FAMILY) // [Ugly Hack] In the use scenario of V4L2ImageProcessor in // V4L2VideoEncodeAccelerator. ImageProcessor needs to read and write // contents with arbitrary offsets. The format needs to be multi planar. is_single_planar_input = !IsYuvPlanar(input_image.PixelFormat()); is_single_planar_output = !IsYuvPlanar(output_image->PixelFormat()); #endif Fourcc input_fourcc = *Fourcc::FromVideoPixelFormat( input_image.PixelFormat(), is_single_planar_input); Fourcc output_fourcc = *Fourcc::FromVideoPixelFormat( output_image->PixelFormat(), is_single_planar_output); auto input_layout = test::CreateVideoFrameLayout(input_image.PixelFormat(), input_image.Size()); auto output_layout = test::CreateVideoFrameLayout( output_image->PixelFormat(), output_image->Size()); LOG_ASSERT(input_layout && output_layout); ImageProcessor::PortConfig input_config( input_fourcc, input_image.Size(), input_layout->planes(), input_image.VisibleRect(), input_storage_types); ImageProcessor::PortConfig output_config( output_fourcc, output_image->Size(), output_layout->planes(), output_image->VisibleRect(), output_storage_types); int rotation = ((output_image->Rotation() - input_image.Rotation() + 4) % 4) * 90; VideoRotation relative_rotation = VIDEO_ROTATION_0; switch (rotation) { case 0: relative_rotation = VIDEO_ROTATION_0; break; case 90: relative_rotation = VIDEO_ROTATION_90; break; case 180: relative_rotation = VIDEO_ROTATION_180; break; case 270: relative_rotation = VIDEO_ROTATION_270; break; default: NOTREACHED() << "Invalid rotation: " << rotation; return nullptr; } // TODO(crbug.com/917951): Select more appropriate number of buffers. constexpr size_t kNumBuffers = 1; LOG_ASSERT(output_image->IsMetadataLoaded()); std::vector<std::unique_ptr<test::VideoFrameProcessor>> frame_processors; // TODO(crbug.com/944823): Use VideoFrameValidator for RGB formats. // Validating processed frames is currently not supported when a format is // not YUV or when scaling images. if (IsYuvPlanar(input_fourcc.ToVideoPixelFormat()) && IsYuvPlanar(output_fourcc.ToVideoPixelFormat())) { if (input_image.Size() == output_image->Size()) { auto vf_validator = test::MD5VideoFrameValidator::Create( {output_image->Checksum()}, output_image->PixelFormat()); LOG_ASSERT(vf_validator); frame_processors.push_back(std::move(vf_validator)); } else if (input_fourcc == output_fourcc) { // Scaling case. LOG_ASSERT(output_image->Load()); scoped_refptr<const VideoFrame> model_frame = CreateVideoFrameFromImage(*output_image); LOG_ASSERT(model_frame) << "Failed to create from image"; model_frames_ = {model_frame}; auto vf_validator = test::SSIMVideoFrameValidator::Create( base::BindRepeating(&ImageProcessorParamTest::GetModelFrame, base::Unretained(this))); frame_processors.push_back(std::move(vf_validator)); } } if (g_save_images) { base::FilePath output_dir = base::FilePath(base::FilePath::kCurrentDirectory) .Append(g_env->GetTestOutputFilePath()); test::VideoFrameFileWriter::OutputFormat saved_file_format = IsYuvPlanar(output_fourcc.ToVideoPixelFormat()) ? test::VideoFrameFileWriter::OutputFormat::kYUV : test::VideoFrameFileWriter::OutputFormat::kPNG; frame_processors.push_back( test::VideoFrameFileWriter::Create(output_dir, saved_file_format)); } auto ip_client = test::ImageProcessorClient::Create( input_config, output_config, kNumBuffers, relative_rotation, std::move(frame_processors)); return ip_client; } private: scoped_refptr<const VideoFrame> GetModelFrame(size_t frame_index) const { if (frame_index >= model_frames_.size()) { LOG(ERROR) << "Failed to get model frame with index=" << frame_index; ADD_FAILURE(); return nullptr; } return model_frames_[frame_index]; } std::vector<scoped_refptr<const VideoFrame>> model_frames_; }; TEST_P(ImageProcessorParamTest, ConvertOneTime_MemToMem) { // Load the test input image. We only need the output image's metadata so we // can compare checksums. test::Image input_image(std::get<0>(GetParam())); test::Image output_image(std::get<1>(GetParam())); ASSERT_TRUE(input_image.Load()); ASSERT_TRUE(output_image.LoadMetadata()); auto ip_client = CreateImageProcessorClient( input_image, {VideoFrame::STORAGE_OWNED_MEMORY}, &output_image, {VideoFrame::STORAGE_OWNED_MEMORY}); ASSERT_TRUE(ip_client); ip_client->Process(input_image, output_image); EXPECT_TRUE(ip_client->WaitUntilNumImageProcessed(1u)); EXPECT_EQ(ip_client->GetErrorCount(), 0u); EXPECT_EQ(ip_client->GetNumOfProcessedImages(), 1u); EXPECT_TRUE(ip_client->WaitForFrameProcessors()); } #if BUILDFLAG(IS_ASH) // We don't yet have the function to create Dmabuf-backed VideoFrame on // platforms except ChromeOS. So MemToDmabuf test is limited on ChromeOS. TEST_P(ImageProcessorParamTest, ConvertOneTime_DmabufToMem) { // Load the test input image. We only need the output image's metadata so we // can compare checksums. test::Image input_image(std::get<0>(GetParam())); test::Image output_image(std::get<1>(GetParam())); ASSERT_TRUE(input_image.Load()); ASSERT_TRUE(output_image.LoadMetadata()); auto ip_client = CreateImageProcessorClient( input_image, {VideoFrame::STORAGE_DMABUFS}, &output_image, {VideoFrame::STORAGE_OWNED_MEMORY}); ASSERT_TRUE(ip_client); ip_client->Process(input_image, output_image); EXPECT_TRUE(ip_client->WaitUntilNumImageProcessed(1u)); EXPECT_EQ(ip_client->GetErrorCount(), 0u); EXPECT_EQ(ip_client->GetNumOfProcessedImages(), 1u); EXPECT_TRUE(ip_client->WaitForFrameProcessors()); } TEST_P(ImageProcessorParamTest, ConvertOneTime_DmabufToDmabuf) { // Load the test input image. We only need the output image's metadata so we // can compare checksums. test::Image input_image(std::get<0>(GetParam())); test::Image output_image(std::get<1>(GetParam())); ASSERT_TRUE(input_image.Load()); ASSERT_TRUE(output_image.LoadMetadata()); auto ip_client = CreateImageProcessorClient(input_image, {VideoFrame::STORAGE_DMABUFS}, &output_image, {VideoFrame::STORAGE_DMABUFS}); ASSERT_TRUE(ip_client); ip_client->Process(input_image, output_image); EXPECT_TRUE(ip_client->WaitUntilNumImageProcessed(1u)); EXPECT_EQ(ip_client->GetErrorCount(), 0u); EXPECT_EQ(ip_client->GetNumOfProcessedImages(), 1u); EXPECT_TRUE(ip_client->WaitForFrameProcessors()); } // Although GpuMemoryBuffer is a cross platform class, code for image processor // test is designed only for ChromeOS. So this test runs on ChromeOS only. TEST_P(ImageProcessorParamTest, ConvertOneTime_GmbToGmb) { // Load the test input image. We only need the output image's metadata so we // can compare checksums. test::Image input_image(std::get<0>(GetParam())); test::Image output_image(std::get<1>(GetParam())); ASSERT_TRUE(input_image.Load()); ASSERT_TRUE(output_image.LoadMetadata()); auto ip_client = CreateImageProcessorClient( input_image, {VideoFrame::STORAGE_GPU_MEMORY_BUFFER}, &output_image, {VideoFrame::STORAGE_GPU_MEMORY_BUFFER}); ASSERT_TRUE(ip_client); ip_client->Process(input_image, output_image); EXPECT_TRUE(ip_client->WaitUntilNumImageProcessed(1u)); EXPECT_EQ(ip_client->GetErrorCount(), 0u); EXPECT_EQ(ip_client->GetNumOfProcessedImages(), 1u); EXPECT_TRUE(ip_client->WaitForFrameProcessors()); } #endif // BUILDFLAG(IS_ASH) // BGRA -> NV12 // I420 -> NV12 // RGBA -> NV12 // YV12 -> NV12 INSTANTIATE_TEST_SUITE_P( PixelFormatConversionToNV12, ImageProcessorParamTest, ::testing::Values(std::make_tuple(kBGRAImage, kNV12Image), // TODO(crbug.com/944822): Add I420 -> NV12 test case. // There is currently no way of creating DMABUF // I420 buffer by NativePixmap. // std::make_tuple(kI420Image, kNV12Image), std::make_tuple(kRGBAImage, kNV12Image), std::make_tuple(kYV12Image, kNV12Image))); INSTANTIATE_TEST_SUITE_P( NV12DownScaling, ImageProcessorParamTest, ::testing::Values(std::make_tuple(kNV12Image720P, kNV12Image360P), std::make_tuple(kNV12Image720P, kNV12Image270P), std::make_tuple(kNV12Image720P, kNV12Image180P), std::make_tuple(kNV12Image360P, kNV12Image270P), std::make_tuple(kNV12Image360P, kNV12Image180P))); // Crop 360P frame from 480P. INSTANTIATE_TEST_SUITE_P(NV12Cropping, ImageProcessorParamTest, ::testing::Values(std::make_tuple(kNV12Image360PIn480P, kNV12Image360P))); // Crop 360p frame from 480P and scale the area to 270P. INSTANTIATE_TEST_SUITE_P(NV12CroppingAndScaling, ImageProcessorParamTest, ::testing::Values(std::make_tuple(kNV12Image360PIn480P, kNV12Image270P))); // Rotate frame to specified rotation. // Now only VaapiIP maybe support rotaion. INSTANTIATE_TEST_SUITE_P( NV12Rotation, ImageProcessorParamTest, ::testing::Values(std::make_tuple(kNV12Image, kNV12Image90), std::make_tuple(kNV12Image, kNV12Image180), std::make_tuple(kNV12Image, kNV12Image270), std::make_tuple(kNV12Image180, kNV12Image90), std::make_tuple(kNV12Image180, kNV12Image))); #if BUILDFLAG(IS_ASH) // TODO(hiroh): Add more tests. // MEM->DMABUF (V4L2VideoEncodeAccelerator), #endif } // namespace } // namespace media int main(int argc, char** argv) { base::CommandLine::Init(argc, argv); // Print the help message if requested. This needs to be done before // initializing gtest, to overwrite the default gtest help message. const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); LOG_ASSERT(cmd_line); if (cmd_line->HasSwitch("help")) { std::cout << media::usage_msg << "\n" << media::help_msg; return 0; } base::CommandLine::SwitchMap switches = cmd_line->GetSwitches(); for (base::CommandLine::SwitchMap::const_iterator it = switches.begin(); it != switches.end(); ++it) { if (it->first.find("gtest_") == 0 || // Handled by GoogleTest it->first == "v" || it->first == "vmodule") { // Handled by Chrome continue; } if (it->first == "save_images") { media::g_save_images = true; } else { std::cout << "unknown option: --" << it->first << "\n" << media::usage_msg; return EXIT_FAILURE; } } testing::InitGoogleTest(&argc, argv); auto* const test_environment = new media::test::VideoTestEnvironment; media::g_env = reinterpret_cast<media::test::VideoTestEnvironment*>( testing::AddGlobalTestEnvironment(test_environment)); return RUN_ALL_TESTS(); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
a6b85ed7dff4e3ae011f81cabf9b728ed339a868
04c8626f3d4dcddaf78df8da156804023d73c285
/src/Handler/HistoricalDataEndEventHandler.cpp
94405710dfcf5ab1e3a98773499659879e0e8305
[]
no_license
lvhui/OpenKit
0d787a6121c209e702dade0f824f6aab12a523d3
963ec4b0491d651ee1f11df972aa39d3166deac2
refs/heads/master
2020-12-27T15:28:37.281907
2015-04-03T10:22:18
2015-04-03T10:22:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,939
cpp
#include <QuantKit/HistoricalDataEndEventHandler.h> #include <QuantKit/HistoricalDataEndEventArgs.h> namespace QuantKit { class HistoricalDataEndEventHandlerPrivate : public QSharedData { public: HistoricalDataEndEventHandlerPrivate(const QVariant& object, IntPtr method); virtual ~HistoricalDataEndEventHandlerPrivate(); public: virtual IAsyncResult beginInvoke(const QVariant& sender, const HistoricalDataEndEventArgs& args, const AsyncCallback& callback, const QVariant& object) Q_DECL_OVERRIDE; virtual void endInvoke(const IAsyncResult& result) Q_DECL_OVERRIDE; virtual void invoke(const QVariant& sender, const HistoricalDataEndEventArgs& e) Q_DECL_OVERRIDE; virtual HistoricalDataEndEventHandlerPrivate* clone() Q_DECL_OVERRIDE { return new HistoricalDataEndEventHandlerPrivate(*this); } }; } // namepsace QuantKit using namespace QuantKit; HistoricalDataEndEventHandlerPrivate::HistoricalDataEndEventHandlerPrivate(const QVariant& object, IntPtr method) { } HistoricalDataEndEventHandlerPrivate::~HistoricalDataEndEventHandlerPrivate () { } IAsyncResult HistoricalDataEndEventHandlerPrivate::beginInvoke(const QVariant& sender, const HistoricalDataEndEventArgs& args, const AsyncCallback& callback, const QVariant& object) { } void HistoricalDataEndEventHandlerPrivate::endInvoke(const IAsyncResult& result) { } void HistoricalDataEndEventHandlerPrivate::invoke(const QVariant& sender, const HistoricalDataEndEventArgs& e) { } // Pubic API HistoricalDataEndEventHandler::HistoricalDataEndEventHandler(const QVariant& object, IntPtr method) : d_ptr(new HistoricalDataEndEventHandlerPrivate(object, method)) { } HistoricalDataEndEventHandler::~HistoricalDataEndEventHandler() { } HistoricalDataEndEventHandler::HistoricalDataEndEventHandler (const HistoricalDataEndEventHandler &other) : d_ptr(other.d_ptr) { } HistoricalDataEndEventHandler& HistoricalDataEndEventHandler::operator=(const HistoricalDataEndEventHandler &other) { d_ptr = other.d_ptr; return *this; } bool HistoricalDataEndEventHandler::operator==(const HistoricalDataEndEventHandler &other) const { if(d_ptr && other.d_ptr) return (*d_ptr == *other.d_ptr); else return (d_ptr==other.d_ptr); } IAsyncResult HistoricalDataEndEventHandler::beginInvoke(const QVariant& sender, const HistoricalDataEndEventArgs& args, const AsyncCallback& callback, const QVariant& object) { return d_ptr->beginInvoke(sender, args, callback, object); } void HistoricalDataEndEventHandler::endInvoke(const IAsyncResult& result) { d_ptr->endInvoke(result); } void HistoricalDataEndEventHandler::invoke(const QVariant& sender, const HistoricalDataEndEventArgs& e) { d_ptr->invoke(sender, e); } QDebug operator<<(QDebug dbg, const HistoricalDataEndEventHandler& historicaldataendeventhandler) { return dbg << historicaldataendeventhandler.toString(); }
[ "gaoxiaojun@gmail.com" ]
gaoxiaojun@gmail.com
be999d77862f015dd7e33385a451fd4a20545ea5
bb58908af18c25df93d85f82edf98a38c373b239
/src/DRgui_impl.cpp
150fc6cbf76c6dda41703687489a966ac25a65e6
[]
no_license
reflek/DR_pi
31ab088e30daec94f5cd3bf5820fdc4301bbff3c
90c7022f648dc142344add98979665fc0d413970
refs/heads/master
2021-05-12T16:29:39.215526
2016-09-10T14:39:53
2016-09-10T14:39:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,585
cpp
/****************************************************************************** * * Project: OpenCPN * Purpose: DR Plugin * Author: Mike Rossiter * *************************************************************************** * Copyright (C) 2013 by Mike Rossiter * * $EMAIL$ * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * *************************************************************************** */ #include "DRgui_impl.h" #include <wx/progdlg.h> #include <wx/wx.h> #include "wx/dir.h" #include <list> #include <cmath> #include "DR_pi.h" class Position; class DR_pi; #define FAIL(X) do { error = X; goto failed; } while(0) CfgDlg::CfgDlg( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : CfgDlgDef( parent, id, title, pos, size, style ) { } Dlg::Dlg( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : DlgDef( parent, id, title, pos, size, style ) { this->Fit(); dbg=false; //for debug output set to true } void Dlg::Addpoint(TiXmlElement* Route, wxString ptlat, wxString ptlon, wxString ptname, wxString ptsym, wxString pttype){ //add point TiXmlElement * RoutePoint = new TiXmlElement( "rtept" ); RoutePoint->SetAttribute("lat", ptlat.mb_str()); RoutePoint->SetAttribute("lon", ptlon.mb_str()); TiXmlElement * Name = new TiXmlElement( "name" ); TiXmlText * text = new TiXmlText( ptname.mb_str() ); RoutePoint->LinkEndChild( Name ); Name->LinkEndChild( text ); TiXmlElement * Symbol = new TiXmlElement( "sym" ); TiXmlText * text1 = new TiXmlText( ptsym.mb_str() ); RoutePoint->LinkEndChild( Symbol ); Symbol->LinkEndChild( text1 ); TiXmlElement * Type = new TiXmlElement( "type" ); TiXmlText * text2 = new TiXmlText( pttype.mb_str() ); RoutePoint->LinkEndChild( Type ); Type->LinkEndChild( text2 ); Route->LinkEndChild( RoutePoint ); //done adding point } void Dlg::OnPSGPX( wxCommandEvent& event ) { Calculate(event, true, 1); } void Dlg::OnClose(wxCloseEvent& event) { plugin->OnDRDialogClose(); } bool Dlg::OpenXML() { Position my_position; my_positions.clear(); int response = wxID_CANCEL; int my_count = 0; wxArrayString file_array; wxString filename; wxFileDialog openDialog( this, _( "Import GPX Route file" ), m_gpx_path, wxT ( "" ), wxT ( "GPX files (*.gpx)|*.gpx|All files (*.*)|*.*" ), wxFD_OPEN | wxFD_MULTIPLE ); response = openDialog.ShowModal(); if( response == wxID_OK ) { openDialog.GetPaths( file_array ); // Record the currently selected directory for later use if( file_array.GetCount() ) { wxFileName fn( file_array[0] ); filename = file_array[0]; m_gpx_path = fn.GetPath(); } } else if(response = wxID_CANCEL){ return false; } TiXmlDocument doc; wxString error; wxProgressDialog *progressdialog = NULL; if(!doc.LoadFile(filename.mb_str())){ FAIL(_("Failed to load file: ") + filename); } else { TiXmlElement *root = doc.RootElement(); if(!strcmp(root->Value(), "rte")) FAIL(_("rte Invalid xml file")); int count = 0; for(TiXmlElement* e = root->FirstChildElement(); e; e = e->NextSiblingElement()) count++; int i=0; for(TiXmlElement* e = root->FirstChildElement(); e; e = e->NextSiblingElement(), i++) { if(progressdialog) { if(!progressdialog->Update(i)) return true; } else { if(1) { progressdialog = new wxProgressDialog( _("Route"), _("Loading"), count, this, wxPD_CAN_ABORT | wxPD_ELAPSED_TIME | wxPD_REMAINING_TIME); } } for(TiXmlElement* f = e->FirstChildElement(); f; f = f->NextSiblingElement()) { if(!strcmp(f->Value(), "rtept")) { wxString rte_lat = wxString::FromUTF8(f->Attribute("lat")); wxString rte_lon = wxString::FromUTF8(f->Attribute("lon")); my_position.lat = rte_lat; my_position.lon = rte_lon; my_positions.push_back(my_position); } //else if(!strcmp(f->Value(), "extensions")) { //rte_start = wxString::FromUTF8(f->Attribute("opencpn:start")); //rte_end = wxString::FromUTF8(f->Attribute("opencpn:end")); //} } } } delete progressdialog; return true; failed: delete progressdialog; wxMessageDialog mdlg(this, error, _("DR"), wxOK | wxICON_ERROR); mdlg.ShowModal(); return false; } void Dlg::Calculate( wxCommandEvent& event, bool write_file, int Pattern ){ if(OpenXML()){ bool error_occured=false; // double dist, fwdAz, revAz; double lat1,lon1; // if(!this->m_Lat1->GetValue().ToDouble(&lat1)){ lat1=0.0;} // if(!this->m_Lon1->GetValue().ToDouble(&lon1)){ lon1=0.0;} int num_hours; num_hours = this->m_Nship->GetSelection(); // wxString str_countPts = wxString::Format(wxT("%d"), (int)num_hours); // wxMessageBox(str_countPts,_T("count_hours")); lat1 = 0.0; lon1 = 0.0; //if (error_occured) wxMessageBox(_T("error in conversion of input coordinates")); //error_occured=false; wxString s; if (write_file){ wxFileDialog dlg(this, _("Export DR Positions in GPX file as"), wxEmptyString, wxEmptyString, _T("GPX files (*.gpx)|*.gpx|All files (*.*)|*.*"), wxFD_SAVE|wxFD_OVERWRITE_PROMPT); if (dlg.ShowModal() == wxID_CANCEL){ error_occured=true; // the user changed idea... return; } //dlg.ShowModal(); s=dlg.GetPath(); // std::cout<<s<< std::endl; if (dlg.GetPath() == wxEmptyString){ error_occured=true; if (dbg) printf("Empty Path\n");} } //Validate input ranges if (!error_occured){ if (std::abs(lat1)>90){ error_occured=true; } if (std::abs(lon1)>180){ error_occured=true; } if (error_occured) wxMessageBox(_("error in input range validation")); } //Start GPX TiXmlDocument doc; TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "utf-8", "" ); doc.LinkEndChild( decl ); TiXmlElement * root = new TiXmlElement( "gpx" ); TiXmlElement * Route = new TiXmlElement( "rte" ); TiXmlElement * RouteName = new TiXmlElement( "name" ); TiXmlText * text4 = new TiXmlText( this->m_Route->GetValue().ToUTF8() ); if (write_file){ doc.LinkEndChild( root ); root->SetAttribute("version", "0.1"); root->SetAttribute("creator", "DR_pi by Rasbats"); root->SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); root->SetAttribute("xmlns:gpxx","http://www.garmin.com/xmlschemas/GpxExtensions/v3" ); root->SetAttribute("xsi:schemaLocation", "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"); root->SetAttribute("xmlns:opencpn","http://www.opencpn.org"); Route->LinkEndChild( RouteName ); RouteName->LinkEndChild( text4 ); TiXmlElement * Extensions = new TiXmlElement( "extensions" ); TiXmlElement * StartN = new TiXmlElement( "opencpn:start" ); TiXmlText * text5 = new TiXmlText( "Start" ); Extensions->LinkEndChild( StartN ); StartN->LinkEndChild( text5 ); TiXmlElement * EndN = new TiXmlElement( "opencpn:end" ); TiXmlText * text6 = new TiXmlText( "End" ); Extensions->LinkEndChild( EndN ); EndN->LinkEndChild( text6 ); Route->LinkEndChild( Extensions ); } switch ( Pattern ) { case 1: { if (dbg) cout<<"DR Calculation\n"; double speed=0; int interval=1; if(!this->m_Speed_PS->GetValue().ToDouble(&speed)){ speed=5.0;} // 5 kts default speed interval = m_Nship->GetCurrentSelection();//S=1 speed = speed*interval; int n=0; //int multiplier=1; double lati, loni; double latN[100], lonN[100]; double latF, lonF; Position my_point; double value, value1; for(std::vector<Position>::iterator it = my_positions.begin(); it != my_positions.end(); it++){ if(!(*it).lat.ToDouble(&value)){ /* error! */ } lati = value; if(!(*it).lon.ToDouble(&value1)){ /* error! */ } loni = value1; latN[n] = lati; lonN[n] = loni; n++;//0,1,2,3 } my_positions.clear(); n--;//n = 2, 0,1,2 int routepoints = n+1; //3 double myDist, myBrng, myDistForBrng; int count_pts; double remaining_dist, myLast, route_dist; remaining_dist = 0; route_dist= 0; myLast = 0; myDistForBrng =0; double total_dist = 0; int i,c; bool skip = false; bool inloop = false; bool setF = false; latF = latN[0]; lonF = lonN[0]; // Start of new logic for (i=0; i<n; i++){ // n is number of routepoints // save the routepoint my_point.lat = wxString::Format(wxT("%f"),latN[i]); my_point.lon = wxString::Format(wxT("%f"),lonN[i]); my_point.routepoint = 1; my_point.wpt_num = wxString::Format(wxT("%d"),(int)i); my_points.push_back(my_point); if (i==0){ // First F is a routepoint latF = latN[i]; lonF = lonN[i]; } DistanceBearingMercator(latN[i + 1], lonN[i + 1],latF, lonF, &myDist, &myBrng); total_dist = total_dist + myDist; if (total_dist > speed){ // DR point after route point // route_dist = total_dist - myDist; remaining_dist = speed - route_dist; DistanceBearingMercator( latN[i + 1], lonN[i + 1], latN[i], lonN[i],&myDist, &myBrng); destLoxodrome(latN[i], lonN[i], myBrng, remaining_dist, &lati, &loni); // Put in DR after many route points my_point.lat = wxString::Format(wxT("%f"),lati); my_point.lon = wxString::Format(wxT("%f"),loni); my_point.routepoint = 0; my_points.push_back(my_point); latF = lati; lonF = loni; total_dist = 0; // // DistanceBearingMercator(latN[i + 1], lonN[i + 1], latF, lonF, &myDistForBrng, &myBrng); if (myDistForBrng > speed){ // put in the DR positions // count_pts = (int)floor(myDistForBrng/speed); // remaining_dist = myDistForBrng - (count_pts*speed); DistanceBearingMercator(latN[i + 1], lonN[i + 1], latF, lonF, &myDistForBrng, &myBrng); for (c = 1; c <= count_pts ; c++){ destLoxodrome(latF, lonF, myBrng, speed*c, &lati, &loni); // print mid points my_point.lat = wxString::Format(wxT("%f"),lati); my_point.lon = wxString::Format(wxT("%f"),loni); my_point.routepoint = 0; my_points.push_back(my_point); // End of prints } latF = lati; lonF = loni; total_dist = 0; // // // All the DR positions inserted } if (total_dist == 0){ DistanceBearingMercator(latN[i + 1], lonN[i + 1], latF, lonF, &myDistForBrng, &myBrng); total_dist = myDistForBrng; latF = latN[i+1]; lonF = lonN[i+1]; } } else{ // latF = latN[i+1]; lonF = lonN[i+1]; // // // // } // } // End of new logic // print the last routepoint my_point.lat = wxString::Format(wxT("%f"),latN[i]); my_point.lon = wxString::Format(wxT("%f"),lonN[i]); my_point.routepoint = 1; my_point.wpt_num = wxString::Format(wxT("%d"),(int)i); my_points.push_back(my_point); // for(std::vector<Position>::iterator itOut = my_points.begin(); itOut != my_points.end(); itOut++){ //wxMessageBox((*it).lat, _T("*it.lat")); double value, value1; if(!(*itOut).lat.ToDouble(&value)){ /* error! */ } lati = value; if(!(*itOut).lon.ToDouble(&value1)){ /* error! */ } loni = value1; if ((*itOut).routepoint == 1){ if (write_file){Addpoint(Route, wxString::Format(wxT("%f"),lati), wxString::Format(wxT("%f"),loni), (*itOut).wpt_num ,_T("diamond"),_T("WPT"));} } else{ if ((*itOut).routepoint == 0){ if (write_file){Addpoint(Route, wxString::Format(wxT("%f"),lati), wxString::Format(wxT("%f"),loni), _T("DR") ,_T("square"),_T("WPT"));} } } } my_points.clear(); break; } default: { // Note the colon, not a semicolon cout<<"Error, bad input, quitting\n"; break; } } if (write_file){ root->LinkEndChild( Route ); // check if string ends with .gpx or .GPX if (!wxFileExists(s)){ s = s + _T(".gpx"); } wxCharBuffer buffer=s.ToUTF8(); if (dbg) std::cout<< buffer.data()<<std::endl; doc.SaveFile( buffer.data() );} //} //end of if no error occured if (error_occured==true) { wxLogMessage(_("Error in calculation. Please check input!") ); wxMessageBox(_("Error in calculation. Please check input!") ); } } }
[ "miker@members.swis.net" ]
miker@members.swis.net
728d735d8f49ba36c0ec81fed45efcf667ded187
50662dac46e7c2d6714ab3844146db1cb6db6ebb
/engine/Display/EntityImage.cpp
459d8bb12b5e8d12d54eaa9473f8198aa6e7719b
[]
no_license
Happy-Ferret-Entertainment/creatures3
d3eae9889cdefbfae5390ae0066433cf86b21e03
321245bed27cbacb52421d95c9ff4f0bf67a49eb
refs/heads/master
2023-07-30T10:00:28.437468
2021-09-22T17:31:18
2021-09-22T17:31:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,502
cpp
// -------------------------------------------------------------------------- // Filename: EntityImage.cpp // Class: EntityImage // Purpose: This class is the interface to the rest of C2e. This class // is closely based on the C2 entity and will evolve as required. // // // // Description: ///* Notes: // // An entity is a 'thing' that exists in the game world (unlike a sprite // for example, which only exists in the computer). Entities are contained // within the various types of Object (creatures, machines, etc.); some // objects may contain several Entities. // // Entities are the things that get redrawn when a rectangle is invalidated. // A library of pointers to all extant entities is stored in EntityLib[] // for this purpose. // // Entities are ALWAYS encapsulated in Objects of one kind or another. Thus, // although each entity contains its own X&Y members, these get set as // appropriate by the Object which owns them, and don't need to be // initialised when creating the entity itself. Thus, entities can be // created dynamically by the objects that contain them. // // // Entities: // // // Entity Simplest form of entity, instantiated for use // | within SimpleObjects and CompoundObjects. // | Also serves as base class for articulated entities, // | for encapsulation within Creatures. // | Whereas a Sprite uniquely represents a given bitmap, // | several Entities can refer to the same Sprite // | - an Entity represents the simplest individual // | object in the world; several Entities may LOOK // | the same, but ARE different. // | // | // BodyPart // | | // | Body Parts of articulated objects. A Limb is connected to // | one or no daughter Limbs (eg. a thigh Limb connects // | to a shin Limb); A Body is similar, but connects // Limb to several Limb chains. The BodyPart class contains // methods & data that are common to both types // Body & Limb classes contain pointers to BodyData // or LimbData classes respectively. // // The BodyPart Entities contain pointers to LimbData // or BodyData structs, which contain the XY // information that is common to all BodyParts with // the same appearance. // // // // // // // History: // ------- Chris Wylie Created // 11Nov98 Alima Added comments. // Changed Class and file names from Object to EntityImage. // Introducing Methods from the C2 Entity class. // -------------------------------------------------------------------------- #ifdef _MSC_VER #pragma warning(disable:4786 4503) #endif #include "EntityImage.h" #include "Sprite.h" #include "CompressedSprite.h" #include "SharedGallery.h" #include "../AgentManager.h" #include "MainCamera.h" #include "ErrorMessageHandler.h" #include "../resource.h" #include "FastEntityImage.h" #include "DisplayEngine.h" #include "Line.h" #include "../App.h" //make sure that this is serializable CREATURES_IMPLEMENT_SERIAL( EntityImage) EntityImage::EntityImage(): mySprite(NULL), myGallery(NULL), myFastEntityImage(0), myOverlayGallery(0), myCurrentOverlayIndex(-1), myReadArchivedGalleryFlag(1), myCurrentBaseImageIndex(0), myAbsoluteBaseImage(0), myCurrentImageIndex (0), mySavedImageIndexState(0), myFrameRate(1), myFrameCount(0), myCurrentWidth(0), myCurrentHeight(0), myVisibleFlag(0), mySpriteIsCameraShy(false) { ; } EntityImage::EntityImage(FilePath const& galleryName, int32 numimages, int32 plane, int32 worldx, int32 worldy, uint32 baseimage, uint32 currentimage ) :myNumberOfImages(numimages), myOverlayGallery(0), myCurrentOverlayIndex(-1), myFastEntityImage(0), mySprite(0), myReadArchivedGalleryFlag(1), myFrameRate(1), myFrameCount(0), myCurrentWidth(0), myCurrentHeight(0), myVisibleFlag(0), mySpriteIsCameraShy(false) { myPlane = plane; myGallery = NULL; // keep these values for when the gallery gets reset myDefaultGalleryName = galleryName; myDefaultBaseImage = baseimage; myCurrentImageIndex = baseimage; myCurrentBaseImageIndex = baseimage; // allow for entity images with blank galleries now if(!galleryName.empty()) { SetGallery(galleryName, baseimage); // check that you now have a gallery if(!myGallery) { char buf[_MAX_PATH] = "\0"; std::string string = ErrorMessageHandler::Format(theDisplayErrorTag, (int)DisplayEngine::sidNoGalleryCreated, std::string("EntityImage::EntityImage"), galleryName.GetFullPath().c_str()); throw EntityImageException(string,__LINE__); } Init(plane,//plane worldx, // world x worldy, // world y baseimage, // base image currentimage, numimages); } } void EntityImage::YouAreCameraShy(bool really) { mySpriteIsCameraShy = really; mySprite->YouAreCameraShy(really); } bool EntityImage::AreYouCameraShy() { return mySprite->AreYouCameraShy(); } void EntityImage::Init(int32 plane,//plane int32 worldx, // world x int32 worldy, // world y uint32 baseimage, // base image uint32 currentimage, uint32 numimages) { // myNumberOfImages is relative to myAbsoluteBaseImage (baseimage) if(numimages) myNumberOfImages = numimages; else myNumberOfImages = myGallery->GetCount() - baseimage; myAnimLength = 0; myPlane = plane; myWorldPosition.SetX(worldx); myWorldPosition.SetY(worldy); myCurrentBaseImageIndex = baseimage; myAbsoluteBaseImage = baseimage; myCurrentImageIndex = baseimage; mySavedImageIndexState = currentimage; SetCurrentBitmap(); Link(); } EntityImage::~EntityImage() { Unlink(); if(myGallery) { SharedGallery::RemoveGallery(myGallery); myGallery = NULL; } ResetLines(); if(mySprite) { delete mySprite; mySprite = NULL; } if(myFastEntityImage) { myFastEntityImage->Destroy(); } } // when reloading the skeleton we don't want to register // the entity image with the display until the very last minute void EntityImage::Link(bool forceLink /*=false*/) { if(myReadArchivedGalleryFlag || forceLink) { theMainView.Add(this); myVisibleFlag = true; } } void EntityImage::Unlink() { theMainView.Remove(this); myVisibleFlag = false; } void EntityImage::MakeFastImage() { theMainView.MakeFastImage(*this); // the fast object should now do what it // has to do to get drawn wash your hands of it Unlink(); } void EntityImage::AdoptMe(FastEntityImage* boyAmIFast) { myFastEntityImage = boyAmIFast; } void EntityImage::LosingFastImage() { myFastEntityImage = NULL; } // ---------------------------------------------------------------------- // Method: SetGallery // Arguments: galleryName - file name containg the sprites for this entity // baseImage - the image in the sprite file that this // particular entity will start from // numImages - the number of images for this sprite // // // Returns: None // // Description: Create a gallery for this entity and set up a // sprite to hold your current image data in this base class // the number of images is largely ignored, override if you // want to utilise it // // ---------------------------------------------------------------------- bool EntityImage::SetGallery(FilePath const& galleryName, uint32 baseimage, uint32 numImages /*= 0*/, bool reset /*= true*/) { if(galleryName.GetFullPath().empty()) return false; myAbsoluteBaseImage = baseimage; // if you already have a gallery get rid of it if(myGallery && myGallery->GetName() != galleryName) { SharedGallery::theSharedGallery(). RemoveGallery(myGallery); myGallery = 0; } if (!myGallery) { // entity images can use one of several galleries // let the gallery decide which type of sprite to create myGallery = SharedGallery::theSharedGallery().CreateGallery(galleryName); // now we have a gallery we can create our sprite if(myGallery) { if(mySprite) { delete mySprite; mySprite = NULL; } Sprite* sprite = myGallery->CreateSprite(this); ASSERT(sprite); SetSprite(sprite); // gallery could be reset during the game // so we need to update the current width and height of // any new bitmap if( reset ) myCurrentImageIndex = baseimage; SetCurrentBitmap(); return true; } } return false; } // ---------------------------------------------------------------------- // Method: SetOverlayGallery // Arguments: galleryName - file name containg the sprites for this entity // // // Returns: None // // Description: Create an overlay gallery for this entity. Certain // types of entity (body parts) will want to replace their // normal image by one from an overlay gallery. The overlay // gallery is optional and must be created explicitly if // it is needed. // // ---------------------------------------------------------------------- void EntityImage::SetOverlayGallery(FilePath const& galleryName) { if(galleryName.GetFullPath().empty()) return; // If you have a gallery, and it is not the one you want... if(myOverlayGallery && myOverlayGallery->GetName() != galleryName) { SharedGallery::theSharedGallery(). RemoveGallery(myOverlayGallery); myOverlayGallery = NULL; } // If no gallery yet... if (!myOverlayGallery) { // entity images can use one of several galleries // let the gallery decide which type of sprite to create myOverlayGallery = SharedGallery::theSharedGallery().CreateGallery(galleryName); } //char db[256]; // sprintf(db, "SetOverlayGallery %s\n", galleryName.c_str()); // OutputDebugString(db); } bool EntityImage::SetOverlayIndex(int32 image, int32 layer) { myCurrentOverlayIndex = image; if(myOverlayGallery ) { if(myCurrentOverlayIndex != -1) { mySprite->ShowBitmap(layer); return mySprite->SetBitmap(myOverlayGallery->GetBitmap(image),layer); } else { mySprite->ShowBitmap(0); } } return false; } // ---------------------------------------------------------------------- // Method: GetBitmap // Arguments: index - index into sprite gallery // // Returns: pointer to the selected bitmap // // Description: returns a bitmap specified by index // // ---------------------------------------------------------------------- Bitmap* EntityImage::GetBitmap(int32 index) { _ASSERT(myGallery); return myGallery->GetBitmap(index); } void EntityImage::DestroyGallery() { _ASSERT(myGallery); SharedGallery::theSharedGallery().RemoveGallery(myGallery); } // ---------------------------------------------------------------------- // Method: GetCurrentBitmap // Arguments: None // // Returns: pointer to the currently showing bitmap // // Description: returns a bitmap sopecified by the current Image Index // // ---------------------------------------------------------------------- Bitmap* EntityImage::GetCurrentBitmap() { _ASSERT(myGallery); return myGallery->GetBitmap(myCurrentImageIndex); } bool EntityImage::SetCurrentBitmap() { // bounds checking here? the gallery checks for // overall out of bounds we have no means of checking // whether the agent engineer has exceeded individual // sprite bounds if(mySprite) return mySprite->SetBitmap(GetBitmap(myCurrentImageIndex),0); return false; } void EntityImage::SetPose(int32 pose) { // kill any running anim myAnimLength = 0; // set image index into gallery*/ myCurrentImageIndex = myCurrentBaseImageIndex + pose; SetCurrentBitmap(); } // ---------------------------------------------------------------------- // Method: SetCurrentIndex // Arguments: image - the absolute index of the image in the gallery // file // // Returns: None // // Description: updates the current image index and bitmap // // ---------------------------------------------------------------------- void EntityImage::SetCurrentIndex(uint32 image) { myCurrentImageIndex = image; SetCurrentBitmap(); } void EntityImage::HideCurrentBitmap() { mySprite->HideBitmap(0); } void EntityImage::ShowCurrentBitmap() { mySprite->ShowBitmap(0); } // ---------------------------------------------------------------------- // Method: SetCurrentIndexFromBase // Arguments: image - the index of the image in the gallery // file as an offset from the base. // // Returns: None // // Description: updates the current image index and bitmap // // ---------------------------------------------------------------------- void EntityImage::SetCurrentIndexFromBase(uint32 image) { myCurrentImageIndex = myCurrentBaseImageIndex + image; SetCurrentBitmap(); } /* int32 EntityImage::GetWidth() const { ASSERT(mySprite); return mySprite->GetWidth(); } int32 EntityImage::GetHeight() const { ASSERT(mySprite); return mySprite->GetHeight(); } */ // ---------------------------------------------------------------------- // Method: GetLsrgestBound // Arguments: rect - a rect structure to receive the bounds // // Returns: Cycle through bitmaps in your gallery and get the largest // bound // // ---------------------------------------------------------------------- void EntityImage::GetLargestBound(RECT& rect) { for (uint32 i = myAbsoluteBaseImage; i< myAbsoluteBaseImage + myNumberOfImages; i++) { GetBitmap(i)->UpdateBoundIfLarger(rect); } } // ---------------------------------------------------------------------- // Method: SetSprite // Arguments: sprite - set the first sprite in my list // // Returns: None // // ---------------------------------------------------------------------- void EntityImage::SetSprite(Sprite* sprite) { _ASSERT(sprite); mySprite=sprite; mySprite->SetPlane(myPlane); YouAreCameraShy(mySpriteIsCameraShy); } // ---------------------------------------------------------------------- // Method: Visible // Arguments: test - rectangle to test my position against // // Returns: true if this entity is visible within the bounds of the // rectangle supplied. false otherwise // // ---------------------------------------------------------------------- bool EntityImage::Visible(const RECT& test) { // compute dl & dr as the left and right bounds of // the object, relative to the View rectangle // if (myPlane&0x80000000) return FALSE; int dl = GetWorldX() - test.left; int dr = dl+GetWidth(); return (((dl > (test.right - test.left) ) ||(test.bottom < GetWorldY()) ||(dr<0) ||(test.top > (GetWorldY() + GetHeight())))? 0:1) ; } // ---------------------------------------------------------------------- // Method: IsPixelTransparent // Arguments: imageIndex - the sprite image to test // if this is -1 then use the current image // x - x coordinate of the pixel to test // y - y coordinate of the pixel to test // // Returns: true if the pixel at the given coordinates is transparent // false otherwise // // ---------------------------------------------------------------------- bool EntityImage::IsPixelTransparent(uint32 x, uint32 y, int32 imageIndex/* =-1*/) { if(imageIndex == -1) imageIndex = myCurrentImageIndex; // make the world coordinates local to the bitmap x -= myWorldPosition.GetX(); y -= myWorldPosition.GetY(); return myGallery->IsPixelTransparent(x, y, imageIndex); } void EntityImage::CentreMe() { int32 x; int32 y; ASSERT(mySprite); mySprite->CentreMe(x,y); myWorldPosition.SetX(x); myWorldPosition.SetY(y); } bool EntityImage::Write(CreaturesArchive &archive) const { archive << myPlane << myWorldPosition; archive << mySpriteIsCameraShy; archive << myGallery->GetName(); archive << myAbsoluteBaseImage; archive << myCurrentImageIndex; archive << myCurrentBaseImageIndex; archive << myNumberOfImages; archive << myDefaultBaseImage; archive << mySavedImageIndexState; archive << myReadArchivedGalleryFlag; // a gallery of possible overlays if( myOverlayGallery ) archive << myOverlayGallery->GetName(); else archive << FilePath(); archive << myCurrentOverlayIndex; for(int32 i= 0; i < MaxAnimLength;i++) { archive << myAnim[i]; } archive <<myAnimLength; // 0 if no anim playing archive << myAnimNext; // next frame to show archive << myFrameRate; archive << myFrameCount; archive << myCurrentWidth << myCurrentHeight; archive << myVisibleFlag; return true; } bool EntityImage::Read(CreaturesArchive &archive) { int32 version = archive.GetFileVersion(); if(version >= 3) { archive >> myPlane; archive >> myWorldPosition; archive >> mySpriteIsCameraShy; FilePath galleryName; archive >> galleryName; if(galleryName.empty()) { std::string string = ErrorMessageHandler::Format(theDisplayErrorTag, (int)DisplayEngine::sidGalleryNotSpecified, std::string("EntityImage::Read")); throw EntityImageException(string, __LINE__); } archive >> myAbsoluteBaseImage; archive >> myCurrentImageIndex; archive >> myCurrentBaseImageIndex; archive >> myNumberOfImages; archive >> myDefaultBaseImage; archive >> mySavedImageIndexState; archive >> myReadArchivedGalleryFlag; if(myReadArchivedGalleryFlag) { SetGallery(galleryName,myAbsoluteBaseImage, 0, false); } archive >> galleryName; if(myReadArchivedGalleryFlag) { // a gallery of possible overlays if(!galleryName.empty()) { SetOverlayGallery(galleryName); } } archive >> myCurrentOverlayIndex; for(int32 i= 0; i < MaxAnimLength;i++) { archive >> myAnim[i]; } archive >>myAnimLength; // 0 if no anim playing archive >> myAnimNext; // next frame to show archive >> myFrameRate; archive >> myFrameCount; archive >> myCurrentWidth >> myCurrentHeight; archive >> myVisibleFlag; } else { _ASSERT(false); return false; } // success SetCurrentBitmap(); if(myVisibleFlag) Link(); return true; } void EntityImage::SetFrameRate(const uint8 rate) { if (rate < 1) return; myFrameRate = rate; myFrameCount = 0; } void EntityImage::SetAnim( const uint8* newanim, int length ) { ASSERT( length <= MaxAnimLength ); // allow SetAnim(NULL) if( newanim == NULL || length == 0 || length > MaxAnimLength ) { myAnimLength = 0; return; } // check for malicious agent engineers if( newanim[0] == AnimWrapValue ) { myAnimLength = 0; return; } //memcpy( myAnim, newanim, length ); for(int i=0; i < length; i++) myAnim[i] = newanim[i]; myAnimLength = length; myAnimNext = 0; } bool EntityImage::ValidateAnim( const uint8* newanim, int length ) { ASSERT( length <= MaxAnimLength ); // allow SetAnim(NULL) if( newanim == NULL || length == 0 || length > MaxAnimLength ) return true; // check for malicious agent engineers if( newanim[0] == AnimWrapValue ) return true; // loop through animation string, looking for errors for (int i = 0; i < length; ++i) { int pose = *(newanim + i); // stop at anim wrap value if (pose == AnimWrapValue) { // check wrap point is OK if there is one if (i < length - 1) { int wrap = *(newanim + i + 1); if (wrap < 0 || wrap >= i) return false; } break; } // check pose OK if (!ValidatePose(pose)) return false; } return true; } bool EntityImage::SetBaseAndCurrentIndex(uint32 baseimage) { // check new POSE is in range if(baseimage + myAbsoluteBaseImage < myGallery->GetCount() && baseimage < myNumberOfImages) { // change the value uint32 old_value = myCurrentBaseImageIndex; myCurrentBaseImageIndex = myAbsoluteBaseImage + baseimage; // check any animation string in progress is valid // Darn, we have to check if our animation can cope :( uint8 testAnim[MaxAnimLength]; for(int i=0; i < MaxAnimLength; i++) testAnim[i] = (uint8)(myAnim[i]); if (!ValidateAnim(testAnim, myAnimLength)) { // if invalid anim, go back to old base myCurrentBaseImageIndex = old_value; return false; } return true; } return false; } bool EntityImage::AnimOver() { return (myAnimLength == 0); } void EntityImage::Animate() { // anim running? if( !myAnimLength ) return; //Return if not time for an animation tick :) if (++myFrameCount % myFrameRate) return; uint32 frame = myAnim[ myAnimNext ]; if( frame == AnimWrapValue ) { // if there is a number after AnimWrapValue, loop back to that frame if( myAnimNext < myAnimLength - 1 ) myAnimNext = myAnim[ myAnimNext + 1]; else myAnimNext = 0; frame = myAnim[ myAnimNext ]; } // add some runtime bounds checking here? myCurrentImageIndex = myCurrentBaseImageIndex + frame; if(myCurrentImageIndex >= myAbsoluteBaseImage + myNumberOfImages) { myCurrentImageIndex = myAbsoluteBaseImage; } ASSERT( myCurrentImageIndex < myGallery->GetCount() ); SetCurrentBitmap(); // frame advance, anim over? if( ++myAnimNext >= myAnimLength ) myAnimLength = 0; // kill kill kill! } uint16* EntityImage::GetImageData() const { return mySprite->GetImageData(); } void EntityImage::SetPlane(int plane) { myPlane = plane; mySprite->SetPlane(plane); theMainView.UpdatePlane(this); // Now for each Line, update its plane... if (myLines.empty()) return; std::vector<Line*>::iterator it; for(it = myLines.begin(); it != myLines.end(); it++) { Line* l = (*it); l->SetPlane(myPlane); theMainView.Remove(l); theMainView.Add(l); } } void EntityImage::ResetLines() { if (myLines.empty()) return; std::vector<Line*>::iterator it; for(it = myLines.begin(); it != myLines.end(); it++) { delete (*it); } myLines.clear(); } void EntityImage::DrawLine( int32 x1, int32 y1, int32 x2, int32 y2 , uint8 lineColourRed /*= 0*/, uint8 lineColourGreen /*= 0*/, uint8 lineColourBlue /*= 0*/, uint8 stippleon /* =0*/, uint8 stippleoff/* = 0*/, uint32 stipplestartAt/* = 0*/) { myLines.push_back(new Line(x1,y1,x2,y2,lineColourRed,lineColourGreen,lineColourBlue, stippleon,stippleoff,stipplestartAt,theApp.GetLinePlane())); } bool EntityImage::ResetMainGallery(FilePath &name) { // if there is no name then we are swapping in the // normal default gallery if(name.empty()) { name = myDefaultGalleryName; myCurrentImageIndex = mySavedImageIndexState; } else { // we are replacing the normal gallery // save the last index mySavedImageIndexState = myCurrentImageIndex; } Unlink(); myCurrentImageIndex = myDefaultBaseImage; myCurrentBaseImageIndex = myDefaultBaseImage; bool ok= SetGallery(name,myDefaultBaseImage); Link(); return myGallery ? true : false; } bool EntityImage::RemoveGallery() { bool done = false; Unlink(); done = SharedGallery::theSharedGallery().RemoveCreatureGallery(myGallery); myGallery =NULL; return done; } void EntityImage::ReloadGallery(FilePath const& galleryName, uint32 baseimage, uint32 numImages /*= 0*/) { myCurrentBaseImageIndex = baseimage; SetGallery(galleryName,baseimage,numImages); } void EntityImage::SetPosition(int32 x, int32 y) { myWorldPosition.SetX(x); myWorldPosition.SetY(y); } bool EntityImage::Visible(int32 scope) { RECT r; GetBound(r); return theMainView.Visible(r,scope); } void EntityImage::PrepareForReloadingGallery() { Unlink(); myGallery = NULL; } bool EntityImage::IsMirrored() { _ASSERT(mySprite); return mySprite->IsMirrored(); } void EntityImage::DrawMirrored(bool mirror) { mySprite->DrawMirrored(mirror); }
[ "sjm@sjm.io" ]
sjm@sjm.io
babb00be1e02c1507b4c0f7ff95cb052bb95b032
a09441d80a52ec8b6f7ef2c165a921313853658a
/scripts/single_tetrode/visualizers/BasicSpikeViewer/ArteTetrodePlot.h
e21fc69a8f495dd9363a164defa00d2b0576539c
[]
no_license
wilsonlab/arte-backend
3979ff0eb8143ec93ad7a098a3ca2ade5023d5d0
6351d3a4a944458430f97ce469c36110dd202814
refs/heads/master
2020-12-24T05:58:34.664900
2016-06-27T22:19:31
2016-06-27T22:19:31
32,036,245
2
1
null
2016-06-27T22:19:31
2015-03-11T19:13:18
C
UTF-8
C++
false
false
1,613
h
#ifndef ARTE_PLOT_H #define ARTE_PLOT_H #if defined(__linux__) #include <GL/glut.h> #else #include <GLUT/glut.h> #endif #include <list> #include <math.h> #include "ArteAxes.h" #include "ArteTitleBox.h" #include "ArteUIElement.h" #include "TetrodeSource.h" #include "PlotUtils.h" #include "ArteKeyEvent.h" class ArteTetrodePlot : public ArteUIElement{ char *plotTitle; std::list<ArteAxes> axesList; ArteTitleBox titleBox; TetrodeSource tetSource; bool enabled; bool enableTitle; void drawTitle(); double titleHeight; void *ptr; bool limitsChanged; double limits[4][2]; ArteAxes* selectedAxes; int selectedAxesN; void zoomAxes(int n, bool xdim, int zoomval); void zoomProjection (int n, bool xdim, int zoomval); void zoomWaveform (int n, bool xdim, int zoomval); void panAxes(int n, bool xdim, int panval); void panProjection (int n, bool xdim, int panval); void panWaveform(int n, bool xdim, int panval); void initLimits(); public: ArteTetrodePlot(); ArteTetrodePlot(int x, int y,int w,int h, char *n); void initAxes(); void redraw(); void setTitle(char *n); void setEnabled(bool enabled); bool getEnabled(); void setDataSource(TetrodeSource tp); void setPosition(int,int,double,double); TetrodeSource *getDataSource(); int getNumberOfAxes(); void clearOnNextDraw(bool c); void setTitleEnabled(bool e); void mouseDown(int x, int y); void mouseDragX(int dx, bool shift, bool ctr); void mouseDragY(int dy, bool shift, bool ctr); bool processKeyEvent(ArteKeyEvent k); }; #endif
[ "stuart.layton@gmail.com" ]
stuart.layton@gmail.com
1bc187b4011ab2ee77b844999ee3e1bf3ed6ceb7
9be573b87220a3f9c02f17b987b16dc90ac6b048
/keshe/train/selbuy.cpp
9ef3efe3ec2c0dd6ba283d0448c6611d9dbafc01
[]
no_license
shuai1126/keshe
c72aeae176aa947f49a2a3fe8778acabbe10a365
fab075306412c645a5746b8812db26608b055a54
refs/heads/master
2020-03-22T10:42:50.991682
2018-07-13T01:30:18
2018-07-13T01:30:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,787
cpp
#include "selbuy.h" #include "ui_selbuy.h" QString TrainNumber10; QString Date10; QString Departure10; QString Terminal10; QString DepTime10; QString SeatType10; QString Typetype; extern QString AccountNumber1; SelBuy::SelBuy(QWidget *parent) : QWidget(parent), ui(new Ui::SelBuy) { ui->setupUi(this); QFile qssfile(":/style/base.qss"); qssfile.open(QFile::ReadOnly); QString qss; qss = qssfile.readAll(); this->setStyleSheet(qss); ui->tableWidget->setColumnCount(5); ui->tableWidget->setRowCount(2); ui->tableWidget->setItem(0,0,new QTableWidgetItem("车次")); ui->tableWidget->setItem(0,1,new QTableWidgetItem("出发日期")); ui->tableWidget->setItem(0,2,new QTableWidgetItem("出发时间")); ui->tableWidget->setItem(0,3,new QTableWidgetItem("到达时间")); ui->tableWidget->setItem(0,4,new QTableWidgetItem("途经站点")); } SelBuy::~SelBuy() { delete ui; } void SelBuy::sendDataTrain(QString TrainNumber, QString Date) { QSqlQuery query; QString result; TrainNumber10 = TrainNumber; Date10 = Date; ui->tableWidget->setItem(1,0,new QTableWidgetItem(TrainNumber)); ui->tableWidget->setItem(1,1,new QTableWidgetItem(Date)); result = "select DepTime,ArrTime,PassStation,Type,BussRE,FirRE,SecRE,SeRE,SleHRE,SleSRE from TrainInformation where TrainNumber = '"+TrainNumber+"' and Date = '"+Date+"';"; query.exec(result); while(query.next()) { ui->tableWidget->setItem(1,2,new QTableWidgetItem(query.value(0).toString())); ui->tableWidget->setItem(1,3,new QTableWidgetItem(query.value(1).toString())); ui->tableWidget->setItem(1,4,new QTableWidgetItem(query.value(2).toString())); Typetype = query.value(3).toString(); if(query.value(3).toString() == "G"){ if(query.value(4) != "0"){ remain1 = query.value(4).toInt(); ui->comboBox->addItem(tr("商务座")); } if(query.value(5) != "0"){ remain2 = query.value(5).toInt(); ui->comboBox->addItem(tr("一等座")); } if(query.value(6) != "0"){ remain3 = query.value(6).toInt(); ui->comboBox->addItem(tr("二等座")); } if(query.value(4) == "0" && query.value(5) == "0" && query.value(6) == "0"){ QMessageBox::critical(this,"错误",tr("无剩余车票!")); } } if(query.value(3).toString() == "K"){ if(query.value(7) != "0"){ remain1 = query.value(7).toInt(); ui->comboBox->addItem(tr("硬座")); } if(query.value(8) != "0"){ remain2 = query.value(8).toInt(); ui->comboBox->addItem(tr("硬卧")); } if(query.value(9) != "0"){ remain3 = query.value(9).toInt(); ui->comboBox->addItem(tr("软卧")); } if(query.value(7) == "0" && query.value(8) == "0" && query.value(9) == "0"){ QMessageBox::critical(this,"错误",tr("无剩余车票!")); } } } result = "select Departure,Terminal,DepTime from TrainInformation where TrainNumber = '"+TrainNumber+"' and Date = '"+Date+"';"; query.exec(result); while(query.next()) { Departure10 = query.value(0).toString(); Terminal10 = query.value(1).toString(); DepTime10 = query.value(2).toString(); } } void SelBuy::on_pushButton_2_clicked() { this->close(); } void SelBuy::on_pushButton_3_clicked() { SeatType10 = ui->comboBox->currentText(); AddCustomer *a = new AddCustomer;//跳转到添加/删除顾客并购买车票界面 a->show(); }
[ "1042820762@qq.com" ]
1042820762@qq.com
1448b9d31ccb64ce284c32858b94981f457fc54a
1f49df904649fd99e2c63a53c73ba3d56541d71c
/src/caller/task.cc
77b1aeafb875cbf428fbb123583184c45a4bf4b7
[ "GPL-3.0-or-later", "LGPL-2.1-or-later", "GPL-3.0-only", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "Zlib", "BSD-3-Clause", "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "bzip2-1.0.6", "LicenseRef-scancode-proprietary-lic...
permissive
sakkayaphab/bolt
6cec7e693d4cbc29f748ffb76c35772abb0b2574
75cfd6fdb7399e141e93008c5382ae23bc99d90d
refs/heads/master
2020-06-30T04:11:54.775819
2020-02-11T23:26:39
2020-02-11T23:26:39
139,722,229
1
0
MIT
2018-07-26T11:48:02
2018-07-04T12:56:20
Go
UTF-8
C++
false
false
961
cc
#include "task.h" #include <map> #include <iostream> #include "evidencefinder.h" Task::Task(SampleStat samplestat_T, FileManager *filepath_T, std::string target_chromosome_T) { samplestat = samplestat_T; filepath = filepath_T; target_chromosome = target_chromosome_T; } void Task::setRange(uint64_t t_pos, uint64_t t_end) { taskrange.pos = t_pos; taskrange.end = t_end; } void Task::setBamHeader(bam_hdr_t t_bam_header) { bam_header = t_bam_header; } void Task::setHtsIndex(hts_idx_t *index) { bam_index = index; } void Task::execute() { EvidenceFinder evidencefinder(&samplestat, filepath, &target_chromosome); evidencefinder.setBamHeader(&bam_header); evidencefinder.setHtsIndex(bam_index); // std::string compare = "chr1"; // if (target_chromosome == compare) // { evidencefinder.execute(); // } } void Task::showTaskDone() { std::cout << "✓ " << target_chromosome << std::endl; }
[ "noreply@github.com" ]
sakkayaphab.noreply@github.com
c677dc31ade8c79da42f8c47f22cf0ff1ffba56b
2de766db3b23b1ae845396fbb30615c01cc1604e
/zoj/20/2912'.cpp
b548d800dff80b9522887e999eea224e34867646
[]
no_license
delta4d/AlgoSolution
313c5d0ff72673927ad3862ee7b8fb432943b346
5f6f89578d5aa37247a99b2d289d638f76c71281
refs/heads/master
2020-04-21T01:28:35.690529
2015-01-29T13:38:54
2015-01-29T13:38:54
8,221,423
1
0
null
2013-04-09T15:10:20
2013-02-15T16:09:33
C++
UTF-8
C++
false
false
1,113
cpp
#include <cstdio> #include <vector> #include <cstring> #include <algorithm> using namespace std; typedef long long LL; const int MAXN = 10000; struct node { int x; int y; int w; } e[MAXN]; vector<int> conn[MAXN]; int num[MAXN]; void dfs(int root, int parent) { int i, t; for (i=0; i!=conn[root].size(); ++i) { t = conn[root][i]; if (t == parent) continue; dfs(t, root); num[root] += num[t]; } } int main() { int tc; int m, n; int i, j, k; int x, y, w; int r, s, t; double sum; //freopen("f:\\in.txt", "r", stdin); scanf("%d", &tc); while (tc--) { scanf("%d", &n); for (i=0; i<n; ++i) conn[i].clear(); for (i=0; i<n-1; ++i) { scanf("%d %d %d", &x, &y, &w); e[i].x = x, e[i].y = y, e[i].w = w; conn[x].push_back(y); conn[y].push_back(x); } num[0] = 0; for (i=1; i<n; ++i) num[i] = 1; dfs(0, -1); sum = 0.0; num[0] = 1111111111; for (i=0; i<n-1; ++i) { k = min(num[e[i].x], num[e[i].y]); sum += 1.0 * k * (n - k) * e[i].w; } printf("%.3lf\n", sum*2.0/(double(n)*double(n-1))); } return 0; }
[ "delta4d@gmail.com" ]
delta4d@gmail.com
5292c702f95ae4b0c4cf6d4a2c0e043be954c7e4
88ae8695987ada722184307301e221e1ba3cc2fa
/chrome/browser/ui/views/incognito_clear_browsing_data_dialog_browsertest.cc
0aa2a3561d3e5dff3967ee06fa059630367b2feb
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
7,289
cc
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/raw_ptr.h" #include "base/run_loop.h" #include "base/test/bind.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/test/test_browser_dialog.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/toolbar_button_provider.h" #include "chrome/browser/ui/views/incognito_clear_browsing_data_dialog.h" #include "chrome/browser/ui/views/incognito_clear_browsing_data_dialog_coordinator.h" #include "chrome/browser/ui/views/profiles/avatar_toolbar_button.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" #include "chrome/common/chrome_features.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/test/browser_test.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/test/widget_test.h" #include "ui/views/widget/widget_observer.h" namespace { class IncognitoClearBrowsingDataDialogTest : public InProcessBrowserTest { public: void OpenDialog(IncognitoClearBrowsingDataDialogInterface::Type type) { incognito_browser_ = CreateIncognitoBrowser(browser()->profile()); auto* coordinator = GetCoordinator(); coordinator->Show(type); EXPECT_TRUE(coordinator->IsShowing()); } Browser* GetIncognitoBrowser() { return incognito_browser_; } IncognitoClearBrowsingDataDialog* GetDialogView() { return GetCoordinator()->GetIncognitoClearBrowsingDataDialogForTesting(); } views::Widget* GetDialogWidget() { auto* dialog_view = GetDialogView(); return dialog_view ? dialog_view->GetWidget() : nullptr; } IncognitoClearBrowsingDataDialogCoordinator* GetCoordinator() { return IncognitoClearBrowsingDataDialogCoordinator::GetOrCreateForBrowser( incognito_browser_); } private: raw_ptr<Browser, DanglingUntriaged> incognito_browser_ = nullptr; }; // Used to test that the bubble widget is destroyed before the browser. class BubbleWidgetDestroyedObserver : public views::WidgetObserver { public: explicit BubbleWidgetDestroyedObserver(views::Widget* bubble_widget) { bubble_widget->AddObserver(this); } ~BubbleWidgetDestroyedObserver() override = default; // views::WidgetObserver: void OnWidgetDestroyed(views::Widget* widget) override { ASSERT_GT(BrowserList::GetIncognitoBrowserCount(), 0u); } }; } // namespace class IncognitoClearBrowsingDataDialogBrowserTest : public SupportsTestDialog<IncognitoClearBrowsingDataDialogTest> { public: void ShowUi(const std::string& name) override { OpenDialog(IncognitoClearBrowsingDataDialogInterface::Type::kDefaultBubble); } }; IN_PROC_BROWSER_TEST_F(IncognitoClearBrowsingDataDialogBrowserTest, InvokeUi_default) { ShowAndVerifyUi(); } IN_PROC_BROWSER_TEST_F(IncognitoClearBrowsingDataDialogTest, TestDialogIsShown_DefaultBubble) { OpenDialog(IncognitoClearBrowsingDataDialogInterface::Type::kDefaultBubble); auto* incognito_cbd_dialog_view = GetDialogView(); ASSERT_TRUE(GetCoordinator()->IsShowing()); ASSERT_EQ(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL, incognito_cbd_dialog_view->GetDialogButtons()); ASSERT_TRUE( incognito_cbd_dialog_view->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK)); ASSERT_TRUE(incognito_cbd_dialog_view->IsDialogButtonEnabled( ui::DIALOG_BUTTON_CANCEL)); } IN_PROC_BROWSER_TEST_F(IncognitoClearBrowsingDataDialogTest, TestCloseWindowsButton) { base::HistogramTester histogram_tester; OpenDialog(IncognitoClearBrowsingDataDialogInterface::Type::kDefaultBubble); auto destroyed_observer = BubbleWidgetDestroyedObserver(GetDialogView()->GetWidget()); GetDialogView()->AcceptDialog(); histogram_tester.ExpectBucketCount( "Incognito.ClearBrowsingDataDialog.ActionType", IncognitoClearBrowsingDataDialog::DialogActionType::kCloseIncognito, 1); ui_test_utils::WaitForBrowserToClose(GetIncognitoBrowser()); ASSERT_EQ(0u, BrowserList::GetIncognitoBrowserCount()); } IN_PROC_BROWSER_TEST_F(IncognitoClearBrowsingDataDialogTest, TestCancelButton) { base::HistogramTester histogram_tester; OpenDialog(IncognitoClearBrowsingDataDialogInterface::Type::kDefaultBubble); views::test::WidgetDestroyedWaiter destroyed_waiter(GetDialogWidget()); GetDialogView()->Cancel(); histogram_tester.ExpectBucketCount( "Incognito.ClearBrowsingDataDialog.ActionType", IncognitoClearBrowsingDataDialog::DialogActionType::kCancel, 1); destroyed_waiter.Wait(); ASSERT_FALSE(GetCoordinator()->IsShowing()); ASSERT_FALSE(GetDialogView()); } IN_PROC_BROWSER_TEST_F(IncognitoClearBrowsingDataDialogTest, TestBrowserCloseEventClosesDialogFirst) { OpenDialog(IncognitoClearBrowsingDataDialogInterface::Type::kDefaultBubble); auto destroyed_observer = BubbleWidgetDestroyedObserver(GetDialogWidget()); CloseBrowserSynchronously(GetIncognitoBrowser()); ASSERT_EQ(0u, BrowserList::GetIncognitoBrowserCount()); } IN_PROC_BROWSER_TEST_F(IncognitoClearBrowsingDataDialogTest, ClearBrowsingDataNavigationInIncognito) { Browser* incognito_browser = CreateIncognitoBrowser(); ui_test_utils::SendToOmniboxAndSubmit(incognito_browser, "chrome://settings/clearBrowserData"); std::u16string current_tab_title; ui_test_utils::GetCurrentTabTitle(incognito_browser, &current_tab_title); EXPECT_EQ(u"about:blank", current_tab_title); auto* coordinator = IncognitoClearBrowsingDataDialogCoordinator::FromBrowser( incognito_browser); ASSERT_TRUE(coordinator->IsShowing()); } IN_PROC_BROWSER_TEST_F(IncognitoClearBrowsingDataDialogTest, TestDialogIsShown_HistoryDisclaimerBubble) { OpenDialog(IncognitoClearBrowsingDataDialogInterface::Type:: kHistoryDisclaimerBubble); auto* incognito_cbd_dialog_view = GetDialogView(); ASSERT_TRUE(GetCoordinator()->IsShowing()); ASSERT_EQ(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL, incognito_cbd_dialog_view->GetDialogButtons()); ASSERT_TRUE( incognito_cbd_dialog_view->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK)); ASSERT_TRUE(incognito_cbd_dialog_view->IsDialogButtonEnabled( ui::DIALOG_BUTTON_CANCEL)); } IN_PROC_BROWSER_TEST_F(IncognitoClearBrowsingDataDialogTest, TestCloseIncognitoButton) { OpenDialog(IncognitoClearBrowsingDataDialogInterface::Type:: kHistoryDisclaimerBubble); GetDialogView()->CancelDialog(); ui_test_utils::WaitForBrowserToClose(GetIncognitoBrowser()); ASSERT_EQ(0u, BrowserList::GetIncognitoBrowserCount()); } IN_PROC_BROWSER_TEST_F(IncognitoClearBrowsingDataDialogTest, TestGotItButton) { OpenDialog(IncognitoClearBrowsingDataDialogInterface::Type:: kHistoryDisclaimerBubble); views::test::WidgetDestroyedWaiter destroyed_waiter(GetDialogWidget()); GetDialogView()->AcceptDialog(); destroyed_waiter.Wait(); ASSERT_FALSE(GetCoordinator()->IsShowing()); ASSERT_FALSE(GetDialogView()); }
[ "jengelh@inai.de" ]
jengelh@inai.de
aaa6da071576876a588e932d91444f86255f12b7
5266d0d079e2d412ef698248d8edc55649623031
/jianzhioffer_数组中的逆序对/jianzhioffer数组中的逆序对.cpp
db9e8cca5cde1ab0cabf6399fd0bd509987934bc
[]
no_license
sunxu123/JianZhiOffer
7e225b15c4ad96272d61fec9e1c86ec26856a560
f5b877d5c831abc30937813b56f6522541563ad3
refs/heads/master
2020-03-07T14:52:56.082976
2018-03-31T14:21:20
2018-03-31T14:21:20
127,538,523
0
0
null
null
null
null
UTF-8
C++
false
false
1,748
cpp
// jianzhioffer数组中的逆序对.cpp : Defines the entry point for the console application. //在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007 /* 输入 1,2,3,4,5,6,7,0 输出 7 */ #include "stdafx.h" #include <iostream> #include <vector> #include <map> using namespace std; class Solution1 { public: int InversePairs(vector<int> data) { int sum = 0; for (int i = 0; i < data.size(); i++) { for (int j = i; j < data.size(); j++) { if (data[i] > data[j]) sum++; } } return sum % 1000000007; } }; /* 1,2,3,4,5,6,7,0 1-0 2-0 3-0 7-0 */ class Solution { public: int InversePairs(vector<int> data) { int sum = 0; map<int, int> weizhi; for (int i = 0; i < data.size(); i++) weizhi[data[i]] = i; for (int i = 0; i < weizhi.size(); i++) { cout << weizhi[i] << endl; sum += weizhi[i]; /*for (int j = 0; j < weizhi.size(); j++) { if (weizhi[j] > weizhi[i]) weizhi[j]--; }*/ } //sum += weizhi[i]; return sum % 1000000007; } }; int main() { Solution s; //cout << s.InversePairs({ 1,2,3,4,5,6,7,0 }) << endl;//7 cout << s.InversePairs({ 364,637,341,406,747,995,234,971,571,219,993,407,416,366,315,301,601,650,418,355,460,505,360,965,516,648,727,667,465,849,455,181,486,149,588,233,144,174,557,67,746,550,474,162,268,142,463,221,882,576,604,739,288,569,256,936,275,401,497,82,935,983,583,523,697,478,147,795,380,973,958,115,773,870,259,655,446,863,735,784,3,671,433,630,425,930,64,266,235,187,284,665,874,80,45,848,38,811,267,575 }) << endl;//2519 return 0; }
[ "sun199412065012@live.shop.edu.cn" ]
sun199412065012@live.shop.edu.cn
14bc257fb1e77f926b6a001cddef98798ad6fad4
f6e09c20045ea8b3ac13b6b26914238d00187983
/Src/usb/cdc/slcan.cpp
3f106a30271a5ce900d7588344368bc8693a2692
[]
no_license
hackthedumpster/alt-link-stm32f103xb-public
be5e905e9d44e6c1e604176fcc9ae25d6e7060fb
f42124d4f20428f4a232023ce57b61be40471c8e
refs/heads/master
2022-03-31T15:49:50.816917
2020-01-25T04:22:29
2020-01-25T04:22:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,285
cpp
#include "usbd_cdc.h" #include "mcp2515.h" #include "stm32f1xx_hal_cortex.h" extern CDC_WorkMemory CDC; extern MCP mcp; class SLCan { private: std::size_t overwrite_size_; char GetChar(std::size_t read_idx) { const uint32_t i = SLCAN_INDEX; std::uint8_t data; if (read_idx < APP_RX_DATA_SIZE + overwrite_size_) { data = CDC.d[i].UsbOutBuffer[read_idx]; } else { data = CDC.d[i].UsbOutBuffer[read_idx & (APP_RX_DATA_SIZE - 1)]; } return static_cast<char>(data); } void GetChars(char buf[], std::size_t size, std::size_t read_idx) { for (std::uint32_t i = 0; i < size; i++) buf[i] = GetChar(read_idx + i); } std::uint8_t HexToInt(const char c) { if ('0' <= c && c <= '9') { return static_cast<std::uint32_t>(c - '0'); } else if ('A' <= c && c <= 'F') { return static_cast<std::uint32_t>(c - 'A' + 10); } else if ('a' <= c && c <= 'f') { return static_cast<std::uint32_t>(c - 'A' + 10); } else { return 0; } } std::uint8_t GetBin(std::size_t read_idx) { auto char1 = GetChar(read_idx); auto char2 = GetChar(read_idx + 1); return static_cast<std::uint8_t>((HexToInt(char1) << 4) + HexToInt(char2)); } void GetBins(std::uint8_t buf[], std::size_t bytes, std::size_t read_idx) { for (uint32_t i = 0; i < bytes; i++) buf[i] = GetBin(read_idx + i * 2); } std::uint32_t IdToInt(const char id[], std::uint32_t length) { std::uint32_t int_id = 0; for (std::uint32_t i = 0; i < length; i++) { int_id = (int_id << 4) + HexToInt(id[i]); } return int_id; } std::uint32_t GetStdId(std::size_t read_idx) { char id[3]; GetChars(id, 3, read_idx); return IdToInt(id, 3); } std::uint32_t GetExtId(std::size_t read_idx) { char id[8]; GetChars(id, 8, read_idx); return IdToInt(id, 8); } std::uint32_t GetLen(std::size_t read_idx) { char len_hex = GetChar(read_idx); return HexToInt(len_hex); } void HexToBuf(const char* hex, std::uint8_t* buf, std::size_t buf_bytes) { for (std::uint32_t i = 0; i < buf_bytes; i++) { buf[i] = (HexToInt(hex[i * 2]) << 8) + HexToInt(hex[i * 2 + 1]); } } public: bool ParseCommand(std::size_t read_idx/*, std::uint32_t size*/) { char command = GetChar(read_idx); switch(command) { case 'S': { char bitrate_hex = GetChar(read_idx + 1); std::uint32_t bitrate = 100 * 1000; // 100Kbps switch (bitrate_hex) { case '0': bitrate = 10 * 1000; break; case '1': bitrate = 20 * 1000; break; case '2': bitrate = 50 * 1000; break; case '3': bitrate = 100 * 1000; break; case '4': bitrate = 125 * 1000; break; case '5': bitrate = 250 * 1000; break; case '6': bitrate = 500 * 1000; break; case '7': bitrate = 800 * 1000; break; case '8': bitrate = 1000 * 1000; break; } return mcp.SetBitrate(bitrate); } case 'O': // Open return mcp.SetEvent(SEQ_EVENT::OPEN); case 'L': // Listen (silent) return mcp.SetEvent(SEQ_EVENT::LISTEN); case 'l': // Open + Loopback return mcp.SetEvent(SEQ_EVENT::OPEN_LOOPBACK); case 'C': // Close return mcp.SetEvent(SEQ_EVENT::CLOSE); case 'M': // Acceptance mask // Not supported return mcp.SetEvent(SEQ_EVENT::UNKNOWN); case 'm': // Acceptance value // Not supported return mcp.SetEvent(SEQ_EVENT::UNKNOWN); case 't': // 11bit ID frame case 'T': // 29bit ID frame case 'r': // 11bit ID RTR frame case 'R': // 29bit ID RTR frame if (mcp.CanTransmit()) { bool rtr = (command == 'r' || command == 'R'); bool ext = (command == 'T' || command == 'R'); std::uint32_t id; if (ext) id = GetStdId(read_idx + 1); else id = GetExtId(read_idx + 1); std::size_t len_offset = 1 + (ext ? 8 : 3); std::uint32_t len = GetLen(read_idx + len_offset); if (len > 8) len = 8; if (!rtr) { std::uint8_t buf[8]; GetBins(buf, len, read_idx + 5); return mcp.Transmit(ext, rtr, id, buf, len); } else { return mcp.Transmit(ext, rtr, id, nullptr, len); } } else { return false; } case 'Z': // timestamp if (GetChar(read_idx + 1) == '1') return mcp.SetEvent(SEQ_EVENT::TIMESTAMP_ON); else return mcp.SetEvent(SEQ_EVENT::TIMESTAMP_OFF); case 'F': // Read FIFO information return mcp.SetEvent(SEQ_EVENT::FLAGS); case 'V': // Version return mcp.SetEvent(SEQ_EVENT::VERSION); case 'v': // Minor version return mcp.SetEvent(SEQ_EVENT::MINOR); case 'N': // Serial number return mcp.SetEvent(SEQ_EVENT::SERIAL); default: return mcp.SetEvent(SEQ_EVENT::UNKNOWN); } } std::int32_t Parse(std::size_t read_idx, std::size_t overwrite_size, std::uint32_t size) { overwrite_size_ = overwrite_size; std::int32_t last_pos = -1; for (auto i = 0U; i < size; i++) { // Parse data when delimiter('\r') was found. if (GetChar(read_idx + i) == '\r') { if (ParseCommand(last_pos + 1/*, i - last_pos - 1*/) == false) break; last_pos = i; } } return last_pos + 1; } }; SLCan slcan; extern "C" void SLCAN_Init(); extern "C" void SLCAN_Run_In_Thread_Mode(); extern "C" uint32_t SLCAN_GetWritePos(); void SLCAN_Init() { const std::uint32_t i = SLCAN_INDEX; mcp.Initialize(); mcp.SetNotificationBuffer(CDC.d[i].UserTxBuffer, sizeof(CDC.d[i].UserTxBuffer)); } static void SLCAN_Parse() { const std::uint32_t i = SLCAN_INDEX; if (CDC.d[i].UsbOutBufReadPos == CDC.d[i].UsbOutBufWritePos) return; std::uint32_t read_idx = CDC.d[i].UsbOutBufReadPos & (APP_RX_DATA_SIZE - 1); std::uint32_t buffsize; std::size_t overwritesize; // Disable USB OUT interrupt to get consistent value HAL_NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn); buffsize = CDC.d[i].UsbOutBufWritePos - CDC.d[i].UsbOutBufReadPos; overwritesize = CDC.d[i].UsbOutOverWriteSize; HAL_NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn); // When previous read position was in overwrite area, add APP_RX_DATA_SIZE. if (CDC.d[i].UsbOutBufReadPosInOverwrite) read_idx += APP_RX_DATA_SIZE; auto parsed_size = slcan.Parse(read_idx, overwritesize, buffsize); if (parsed_size > 0) { if (read_idx + parsed_size >= APP_RX_DATA_SIZE + overwritesize) { CDC.d[i].UsbOutBufReadPosInOverwrite = 0; // [NOTE] It is safe write UsbOutOverWriteSize here because USB OUT // callback does not write before updating UsbOutBufReadPos. CDC.d[i].UsbOutOverWriteSize = 0; } else if (read_idx + parsed_size >= APP_RX_DATA_SIZE) { CDC.d[i].UsbOutBufReadPosInOverwrite = 1; } CDC.d[i].UsbOutBufReadPos += parsed_size; } } void SLCAN_Run_In_Thread_Mode() { SLCAN_Parse(); mcp.Run_In_Thread_Mode(); } uint32_t SLCAN_GetWritePos() { return mcp.GetNotificationWritePos(); }
[ "hirox777@gmail.com" ]
hirox777@gmail.com
cff5e13fb4ba41eb3dc7cb5d700d746bb9eb1c91
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/abc050/B/4253599.cpp
79c1ac5a12f1497be0d80383a616239487aa6740
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
551
cpp
#include <iostream> using namespace std; #include <algorithm> #include <string> #include <vector> #define ll long long struct s1 { int timu; int time; }; int main() { ll n,m; cin>>n; int a[n]; ll sum=0; for(int i=0;i<n;i++) { cin>>a[i]; sum=sum+a[i]; } cin>>m; s1 s[m]; for(int i=0;i<m;i++) { cin>>s[i].timu>>s[i].time; } ll t=sum; for(int i=0;i<m;i++) { sum=sum-a[s[i].timu-1]+s[i].time; cout<<sum<<endl; sum=t; } return 0; }
[ "kwnafi@yahoo.com" ]
kwnafi@yahoo.com
cca2dabe468b2cc5c307ef2e6f4ab3149e0fbeac
5c2b0f5b71a53ed7705325620b6c7f2606d14e28
/src/remaining/scanner.cc
c38b80ada8ca1009cf8b0099312fe64f62b1f278
[]
no_license
atthom/TDDB44
054fd50fba919f9f137f5d2ee9d7ad92ec770081
789f4da34e98b8073f50df3b84098a5871086844
refs/heads/master
2020-12-24T06:16:00.992917
2017-01-04T15:10:47
2017-01-04T15:10:47
73,484,647
0
0
null
null
null
null
UTF-8
C++
false
false
65,778
cc
#line 2 "scanner.cc" #line 4 "scanner.cc" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart(yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif extern int yyleng; extern FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = (yy_hold_char); \ YY_RESTORE_YY_MORE_OFFSET \ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; static int yy_n_chars; /* number of characters read into yy_ch_buf */ int yyleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = (char *) 0; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow yywrap()'s to do buffer switches * instead of setting up a fresh yyin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; void yyrestart (FILE *input_file ); void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ); YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ); void yy_delete_buffer (YY_BUFFER_STATE b ); void yy_flush_buffer (YY_BUFFER_STATE b ); void yypush_buffer_state (YY_BUFFER_STATE new_buffer ); void yypop_buffer_state (void ); static void yyensure_buffer_stack (void ); static void yy_load_buffer_state (void ); static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file ); #define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER ) YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ); YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str ); YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len ); void *yyalloc (yy_size_t ); void *yyrealloc (void *,yy_size_t ); void yyfree (void * ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) #define yywrap(n) 1 #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; typedef int yy_state_type; extern int yylineno; int yylineno = 1; extern char *yytext; #define yytext_ptr yytext static yy_state_type yy_get_previous_state (void ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ); static int yy_get_next_buffer (void ); static void yy_fatal_error (yyconst char msg[] ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 55 #define YY_END_OF_BUFFER 56 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[150] = { 0, 1, 1, 0, 0, 0, 0, 56, 54, 1, 53, 54, 6, 7, 15, 13, 10, 14, 2, 16, 51, 5, 3, 11, 4, 12, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 8, 9, 44, 48, 49, 48, 48, 46, 55, 1, 0, 41, 40, 50, 44, 0, 50, 51, 0, 17, 18, 52, 52, 52, 52, 52, 52, 21, 52, 52, 52, 20, 52, 52, 19, 22, 52, 52, 52, 52, 52, 0, 45, 47, 0, 50, 0, 0, 42, 50, 0, 50, 0, 50, 25, 52, 52, 52, 26, 52, 24, 52, 27, 28, 52, 52, 52, 23, 52, 43, 0, 50, 0, 50, 50, 52, 52, 52, 30, 52, 52, 52, 52, 52, 29, 52, 50, 50, 32, 33, 31, 35, 52, 52, 52, 52, 34, 52, 52, 52, 36, 52, 52, 37, 38, 52, 39, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 15, 16, 17, 18, 1, 1, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 28, 29, 30, 31, 32, 33, 28, 34, 35, 36, 37, 38, 39, 28, 40, 28, 41, 1, 42, 1, 43, 1, 44, 45, 46, 47, 48, 49, 50, 51, 52, 28, 28, 53, 54, 55, 56, 57, 28, 58, 59, 60, 61, 62, 63, 28, 64, 28, 65, 1, 66, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[67] = { 0, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1 } ; static yyconst flex_int16_t yy_base[157] = { 0, 0, 0, 64, 65, 0, 0, 270, 271, 267, 271, 66, 271, 271, 271, 271, 271, 271, 255, 66, 68, 250, 271, 248, 271, 271, 49, 51, 50, 57, 57, 50, 0, 51, 58, 61, 71, 60, 73, 71, 79, 75, 271, 271, 0, 271, 271, 253, 253, 271, 271, 255, 99, 271, 241, 102, 271, 241, 111, 122, 128, 271, 271, 0, 97, 74, 102, 106, 101, 0, 105, 106, 111, 0, 121, 109, 0, 0, 114, 111, 125, 117, 122, 177, 271, 271, 238, 227, 146, 235, 271, 142, 223, 221, 220, 216, 0, 138, 131, 125, 0, 149, 0, 141, 0, 0, 156, 130, 148, 0, 151, 271, 215, 214, 213, 209, 181, 145, 155, 152, 0, 165, 156, 170, 161, 162, 0, 175, 165, 79, 0, 0, 0, 0, 172, 178, 186, 176, 0, 176, 174, 183, 0, 184, 183, 0, 0, 198, 0, 271, 246, 249, 252, 82, 255, 258, 261 } ; static yyconst flex_int16_t yy_def[157] = { 0, 149, 1, 150, 150, 151, 151, 149, 149, 149, 149, 152, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 149, 149, 154, 149, 149, 149, 149, 149, 149, 149, 152, 149, 155, 149, 149, 156, 149, 149, 149, 149, 149, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 149, 149, 149, 155, 149, 149, 156, 149, 149, 149, 149, 149, 149, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 149, 149, 149, 149, 149, 149, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 149, 149, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 153, 0, 149, 149, 149, 149, 149, 149, 149 } ; static yyconst flex_int16_t yy_nxt[338] = { 0, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 32, 33, 32, 32, 34, 35, 36, 37, 38, 32, 39, 32, 40, 41, 32, 42, 43, 8, 26, 27, 28, 29, 30, 31, 32, 32, 33, 32, 34, 35, 36, 37, 38, 32, 39, 32, 40, 41, 32, 44, 8, 46, 46, 53, 54, 47, 47, 56, 66, 73, 48, 48, 57, 58, 64, 59, 67, 65, 68, 63, 70, 72, 71, 69, 74, 60, 129, 75, 78, 76, 79, 80, 81, 66, 73, 82, 53, 54, 64, 77, 67, 65, 97, 68, 70, 72, 71, 69, 74, 87, 60, 75, 78, 96, 76, 79, 80, 81, 91, 88, 82, 98, 102, 77, 49, 49, 97, 93, 92, 59, 94, 99, 94, 100, 101, 95, 103, 104, 96, 105, 106, 107, 108, 110, 88, 109, 98, 102, 112, 113, 112, 117, 118, 92, 119, 99, 122, 100, 101, 114, 103, 125, 104, 105, 106, 107, 120, 108, 110, 109, 121, 123, 128, 126, 127, 124, 117, 118, 119, 130, 131, 122, 132, 133, 114, 125, 134, 135, 116, 136, 137, 120, 138, 139, 140, 121, 123, 126, 127, 141, 124, 142, 143, 130, 131, 144, 132, 145, 133, 146, 134, 147, 135, 136, 137, 148, 115, 138, 139, 140, 129, 113, 128, 95, 141, 142, 143, 116, 113, 144, 115, 145, 90, 146, 87, 147, 54, 111, 90, 54, 148, 45, 45, 45, 50, 50, 50, 52, 52, 52, 83, 51, 83, 86, 85, 86, 89, 89, 89, 84, 62, 61, 55, 51, 149, 7, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149 } ; static yyconst flex_int16_t yy_chk[338] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 4, 11, 11, 3, 4, 19, 27, 33, 3, 4, 19, 20, 26, 20, 28, 26, 29, 153, 30, 31, 30, 29, 34, 20, 129, 35, 37, 36, 38, 39, 40, 27, 33, 41, 52, 52, 26, 36, 28, 26, 65, 29, 30, 31, 30, 29, 34, 55, 20, 35, 37, 64, 36, 38, 39, 40, 58, 55, 41, 66, 71, 36, 3, 4, 65, 59, 58, 59, 60, 67, 60, 68, 70, 60, 72, 74, 64, 75, 78, 79, 80, 82, 55, 81, 66, 71, 88, 91, 88, 97, 98, 58, 99, 67, 103, 68, 70, 91, 72, 107, 74, 75, 78, 79, 101, 80, 82, 81, 101, 106, 128, 108, 110, 106, 97, 98, 99, 117, 118, 103, 119, 121, 91, 107, 122, 123, 116, 124, 125, 101, 127, 134, 135, 101, 106, 108, 110, 136, 106, 137, 139, 117, 118, 140, 119, 141, 121, 143, 122, 144, 123, 124, 125, 147, 115, 127, 134, 135, 114, 113, 112, 95, 136, 137, 139, 94, 93, 140, 92, 141, 89, 143, 87, 144, 86, 83, 57, 54, 147, 150, 150, 150, 151, 151, 151, 152, 152, 152, 154, 51, 154, 155, 48, 155, 156, 156, 156, 47, 23, 21, 18, 9, 7, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[56] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, }; static yy_state_type yy_last_accepting_state; static char *yy_last_accepting_cpos; extern int yy_flex_debug; int yy_flex_debug = 0; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET char *yytext; #line 1 "scanner.l" #line 2 "scanner.l" #include <stdlib.h> #include <string.h> //#include "scanner.hh" // This is where you put #include directives as needed for later labs. // include "ast.hh", parser.hh" in that order #include "ast.hh" #include "parser.hh" int column = 0; extern YYLTYPE yylloc; // Used for position information, see below. /* If you want to include any flex declarations, this is where to do it. */ /* {DIGIT}+"."{DIGIT}* \}.*$ */ /* Position information is entered into the yylloc variable, so we will be able to generate good error messages later in later phases. */ /* Your code should be entered below the %%. Expressions to handle the following: Diesel comments, Diesel string constants, Diesel identifiers, integers, reals, and whitespace. */ #line 629 "scanner.cc" #define INITIAL 0 #define c_comment 1 #define c_string 2 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif static int yy_init_globals (void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int yylex_destroy (void ); int yyget_debug (void ); void yyset_debug (int debug_flag ); YY_EXTRA_TYPE yyget_extra (void ); void yyset_extra (YY_EXTRA_TYPE user_defined ); FILE *yyget_in (void ); void yyset_in (FILE * in_str ); FILE *yyget_out (void ); void yyset_out (FILE * out_str ); int yyget_leng (void ); char *yyget_text (void ); int yyget_lineno (void ); void yyset_lineno (int line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap (void ); #else extern int yywrap (void ); #endif #endif static void yyunput (int c,char *buf_ptr ); #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void ); #else static int input (void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int yylex (void); #define YY_DECL int yylex (void) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; #line 59 "scanner.l" #line 821 "scanner.cc" if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_load_buffer_state( ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of yytext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 150 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 271 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { int yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) yylineno++; ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: YY_RULE_SETUP #line 61 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; } YY_BREAK case 2: YY_RULE_SETUP #line 67 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_DOT; } YY_BREAK case 3: YY_RULE_SETUP #line 73 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_SEMICOLON; } YY_BREAK case 4: YY_RULE_SETUP #line 79 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_EQ; } YY_BREAK case 5: YY_RULE_SETUP #line 85 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_COLON; } YY_BREAK case 6: YY_RULE_SETUP #line 91 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_LEFTPAR; } YY_BREAK case 7: YY_RULE_SETUP #line 97 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_RIGHTPAR; } YY_BREAK case 8: YY_RULE_SETUP #line 103 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_LEFTBRACKET; } YY_BREAK case 9: YY_RULE_SETUP #line 109 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_RIGHTBRACKET; } YY_BREAK case 10: YY_RULE_SETUP #line 115 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_COMMA; } YY_BREAK case 11: YY_RULE_SETUP #line 121 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_LESSTHAN; } YY_BREAK case 12: YY_RULE_SETUP #line 127 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_GREATERTHAN; } YY_BREAK case 13: YY_RULE_SETUP #line 133 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_ADD; } YY_BREAK case 14: YY_RULE_SETUP #line 139 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_SUB; } YY_BREAK case 15: YY_RULE_SETUP #line 145 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_MUL; } YY_BREAK case 16: YY_RULE_SETUP #line 151 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_RDIV; } YY_BREAK case 17: YY_RULE_SETUP #line 157 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_ASSIGN; } YY_BREAK case 18: YY_RULE_SETUP #line 163 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_NOTEQ; } YY_BREAK case 19: YY_RULE_SETUP #line 171 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_OF; } YY_BREAK case 20: YY_RULE_SETUP #line 177 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_IF; } YY_BREAK case 21: YY_RULE_SETUP #line 183 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_DO; } YY_BREAK case 22: YY_RULE_SETUP #line 189 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_OR; } YY_BREAK case 23: YY_RULE_SETUP #line 195 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_VAR; } YY_BREAK case 24: YY_RULE_SETUP #line 201 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_END; } YY_BREAK case 25: YY_RULE_SETUP #line 207 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_AND; } YY_BREAK case 26: YY_RULE_SETUP #line 213 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_IDIV; } YY_BREAK case 27: YY_RULE_SETUP #line 219 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_MOD; } YY_BREAK case 28: YY_RULE_SETUP #line 225 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_NOT; } YY_BREAK case 29: YY_RULE_SETUP #line 231 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_THEN; } YY_BREAK case 30: YY_RULE_SETUP #line 237 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_ELSE; } YY_BREAK case 31: YY_RULE_SETUP #line 243 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_CONST; } YY_BREAK case 32: YY_RULE_SETUP #line 249 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_ARRAY; } YY_BREAK case 33: YY_RULE_SETUP #line 255 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_BEGIN; } YY_BREAK case 34: YY_RULE_SETUP #line 261 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_WHILE; } YY_BREAK case 35: YY_RULE_SETUP #line 267 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_ELSIF; } YY_BREAK case 36: YY_RULE_SETUP #line 273 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_RETURN; } YY_BREAK case 37: YY_RULE_SETUP #line 279 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_PROGRAM; } YY_BREAK case 38: YY_RULE_SETUP #line 285 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_FUNCTION; } YY_BREAK case 39: YY_RULE_SETUP #line 291 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; return T_PROCEDURE; } YY_BREAK case 40: YY_RULE_SETUP #line 299 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; yylval.str = sym_tab->pool_install(sym_tab->fix_string(yytext)); return T_STRINGCONST; } YY_BREAK case 41: /* rule 41 can match eol */ YY_RULE_SETUP #line 307 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column =0; yyerror("Newline in string"); } YY_BREAK case 42: *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 314 "scanner.l" column = 0; /* Skip single-line comment */ YY_BREAK case 43: YY_RULE_SETUP #line 315 "scanner.l" column=0; YY_BREAK case 44: YY_RULE_SETUP #line 317 "scanner.l" { column += yyleng; BEGIN(c_comment); } YY_BREAK case 45: YY_RULE_SETUP #line 325 "scanner.l" { column += 2; BEGIN(INITIAL); } YY_BREAK case 46: YY_RULE_SETUP #line 330 "scanner.l" { column += 2; BEGIN(INITIAL); } YY_BREAK case 47: YY_RULE_SETUP #line 335 "scanner.l" { column += 2; yyerror("Suspicious comment"); } YY_BREAK case 48: YY_RULE_SETUP #line 339 "scanner.l" column++; /* Skip stuff in comments */ YY_BREAK case 49: /* rule 49 can match eol */ YY_RULE_SETUP #line 340 "scanner.l" column = 0; YY_BREAK case YY_STATE_EOF(c_comment): #line 341 "scanner.l" { yyerror("Unterminated comment"); yyterminate(); } YY_BREAK case 50: YY_RULE_SETUP #line 347 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; yylval.rval = atof(yytext); return T_REALNUM; } YY_BREAK case 51: YY_RULE_SETUP #line 354 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; yylval.ival = atoi(yytext); return T_INTNUM; } YY_BREAK case 52: YY_RULE_SETUP #line 361 "scanner.l" { yylloc.first_line = yylineno; yylloc.first_column = column; column += yyleng; yylval.pool_p = sym_tab->pool_install(sym_tab->capitalize(yytext)); return T_IDENT; } YY_BREAK case 53: /* rule 53 can match eol */ YY_RULE_SETUP #line 369 "scanner.l" { column = 0; } YY_BREAK case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(c_string): #line 373 "scanner.l" yyterminate(); YY_BREAK case 54: YY_RULE_SETUP #line 374 "scanner.l" yyerror("Illegal character"); YY_BREAK case 55: YY_RULE_SETUP #line 375 "scanner.l" ECHO; YY_BREAK #line 1447 "scanner.cc" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_c_buf_p); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( yywrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (void) { register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = (yytext_ptr); register int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) ((yy_c_buf_p) - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), (size_t) num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart(yyin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (void) { register yy_state_type yy_current_state; register char *yy_cp; yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 150 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { register int yy_is_jam; register char *yy_cp = (yy_c_buf_p); register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 150 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 149); return yy_is_jam ? 0 : yy_current_state; } static void yyunput (int c, register char * yy_bp ) { register char *yy_cp; yy_cp = (yy_c_buf_p); /* undo effects of setting up yytext */ *yy_cp = (yy_hold_char); if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) { /* need to shift things up to make room */ /* +2 for EOB chars. */ register int number_to_move = (yy_n_chars) + 2; register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; register char *source = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) *--dest = *--source; yy_cp += (int) (dest - source); yy_bp += (int) (dest - source); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size; if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) YY_FATAL_ERROR( "flex scanner push-back overflow" ); } *--yy_cp = (char) c; if ( c == '\n' ){ --yylineno; } (yytext_ptr) = yy_bp; (yy_hold_char) = *yy_cp; (yy_c_buf_p) = yy_cp; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) #else static int input (void) #endif { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\0'; else { /* need more input */ int offset = (yy_c_buf_p) - (yytext_ptr); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart(yyin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap( ) ) return EOF; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\0'; /* preserve yytext */ (yy_hold_char) = *++(yy_c_buf_p); if ( c == '\n' ) yylineno++; ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ void yyrestart (FILE * input_file ) { if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_init_buffer(YY_CURRENT_BUFFER,input_file ); yy_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } static void yy_load_buffer_state (void) { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer(b,file ); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * */ void yy_delete_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) yyfree((void *) b->yy_ch_buf ); yyfree((void *) b ); } #ifndef __cplusplus extern int isatty (int ); #endif /* __cplusplus */ /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file ) { int oerrno = errno; yy_flush_buffer(b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ void yy_flush_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) { if (new_buffer == NULL) return; yyensure_buffer_stack(); /* This block is copied from yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ void yypop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void yyensure_buffer_stack (void) { int num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer(b ); return b; } /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string (yyconst char * yystr ) { return yy_scan_bytes(yystr,strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, int _yybytes_len ) { YY_BUFFER_STATE b; char *buf; yy_size_t n; int i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) yyalloc(n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer(buf,n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg ) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = (yy_hold_char); \ (yy_c_buf_p) = yytext + yyless_macro_arg; \ (yy_hold_char) = *(yy_c_buf_p); \ *(yy_c_buf_p) = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. * */ int yyget_lineno (void) { return yylineno; } /** Get the input stream. * */ FILE *yyget_in (void) { return yyin; } /** Get the output stream. * */ FILE *yyget_out (void) { return yyout; } /** Get the length of the current token. * */ int yyget_leng (void) { return yyleng; } /** Get the current token. * */ char *yyget_text (void) { return yytext; } /** Set the current line number. * @param line_number * */ void yyset_lineno (int line_number ) { yylineno = line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * * @see yy_switch_to_buffer */ void yyset_in (FILE * in_str ) { yyin = in_str ; } void yyset_out (FILE * out_str ) { yyout = out_str ; } int yyget_debug (void) { return yy_flex_debug; } void yyset_debug (int bdebug ) { yy_flex_debug = bdebug ; } static int yy_init_globals (void) { /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ /* We do not touch yylineno unless the option is enabled. */ yylineno = 1; (yy_buffer_stack) = 0; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; (yy_c_buf_p) = (char *) 0; (yy_init) = 0; (yy_start) = 0; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy (void) { /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(); } /* Destroy the stack itself. */ yyfree((yy_buffer_stack) ); (yy_buffer_stack) = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ yy_init_globals( ); return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s ) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *yyalloc (yy_size_t size ) { return (void *) malloc( size ); } void *yyrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void yyfree (void * ptr ) { free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 375 "scanner.l"
[ "thom.jalabert@gmail.com" ]
thom.jalabert@gmail.com
e95e8b8850afa08a16dcbf54c213ee53fec2d7cd
ce5eeed0b46cea3413df54a4fa2f9a059cca1073
/src/dsound_dll.cpp
a61396f47e9fdc3b89b40fd92787dd9ea3ce6667
[]
no_license
nmlgc/thvorbis
12e78892157d4ab30b4357ca03960c6b6818a868
121db14fd4defc6f521b7ee4c015ee005bfd561e
refs/heads/master
2016-09-14T03:37:42.969159
2016-04-12T19:54:18
2016-04-12T19:54:18
57,005,480
4
0
null
null
null
null
UTF-8
C++
false
false
2,316
cpp
/* * Touhou Vorbis Compressor * * ---- * * DirectSound API hooks. * (DLL hooking adopted from jisakujien's "noflashmyon" source.) */ #include <windows.h> extern "C" { #include "sysdll.h" } #include "thvc_mmsystem.h" #include "dsound_dll.h" #ifndef NO_DSOUND_HOOK #include "thvc_IDirectSound8.h" #endif // global variables // ================ HMODULE gl_hDSound = NULL; #ifdef DECODE_AT_UNLOCK const DWORD gl_BGMBufferSize = 0x56220; #else const DWORD gl_BGMBufferSize = 0xAC440; #endif // Functions // --------- DLL_FUNC_DEF(dsound, DirectSoundCreate); DLL_FUNC_DEF(dsound, DirectSoundCreate8); DLL_FUNC_DEF(dsound, DirectSoundEnumerateA); // --------- // ================ HRESULT DirectSoundCreate(LPCGUID lpcGuidDevice, LPDIRECTSOUND* ppDS, LPUNKNOWN pUnkOuter) { return dsound_DirectSoundCreate(lpcGuidDevice, ppDS, pUnkOuter); } HRESULT DirectSoundEnumerateA(LPDSENUMCALLBACK lpDSEnumCallback, LPVOID lpContext) { return dsound_DirectSoundEnumerateA(lpDSEnumCallback, lpContext); } #ifdef THVC_IDIRECTSOUND8_H thvc_IDirectSound8* gl_IDirectSound8 = NULL; HRESULT DirectSoundCreate8(LPCGUID lpcGuidDevice, LPDIRECTSOUND8* ppDS8, LPUNKNOWN pUnkOuter) { // Get pointer to original object HRESULT Ret = dsound_DirectSoundCreate8(lpcGuidDevice, ppDS8, pUnkOuter); if(Ret != DS_OK) return Ret; // Create our object gl_IDirectSound8 = new thvc_IDirectSound8(*ppDS8); *ppDS8 = gl_IDirectSound8; return Ret; } #else HRESULT DirectSoundCreate8(LPCGUID lpcGuidDevice, LPDIRECTSOUND8* ppDS8, LPUNKNOWN pUnkOuter) { return dsound_DirectSoundCreate8(lpcGuidDevice, ppDS8, pUnkOuter); } #endif extern "C" { int dsound_init(HANDLE hModule) { OutputDebugString("DSOUND: Init called.\r\n"); // Initialisation if(LoadSystemDll(&gl_hDSound, "dsound.dll", 1)) return -1; // dsound.dll functions DLL_GET_PROC_ADDRESS(gl_hDSound, dsound, DirectSoundCreate); DLL_GET_PROC_ADDRESS(gl_hDSound, dsound, DirectSoundCreate8); DLL_GET_PROC_ADDRESS(gl_hDSound, dsound, DirectSoundEnumerateA); return 0; } void dsound_exit() { OutputDebugString("DSOUND: Exit called.\r\n"); // Release system dlls if(gl_hDSound) FreeLibrary(gl_hDSound); } } #ifdef DSOUND_DLL int InitInstance(HMODULE hProc) {return dsound_init(hProc);} void ExitInstance() {dsound_exit();} #endif
[ "nmlgc@nmlgc.net" ]
nmlgc@nmlgc.net
821d186b97dd106ce744776e9d0042d9e201f5fb
e0e70173cd5dd2e50877a75ab0d3e8db431e4701
/P1046.cpp
4cc4691d472f9dfda83cd405448a785e567968b9
[]
no_license
2mrmikeliu/CPP
0ede83f51ce0b2cc79a6007eb335e654a1ce55f8
e552ee8a28cdbdd82bb83d9c571eb7edb92af2a5
refs/heads/master
2020-03-27T18:04:16.530126
2018-10-19T09:00:19
2018-10-19T09:00:19
146,896,279
0
0
null
null
null
null
UTF-8
C++
false
false
247
cpp
#include <iostream> #include <cstdlib> #include <cstdio> using namespace std; int main() { int arr[10],hig,s=0; for (int i=0;i<10;i++) { cin>>arr[i]; } cin>>hig; for (int i=0;i<10;i++) { if(hig+30>=arr[i])s++; } cout<<s; return 0; }
[ "server_mike@outlook.com" ]
server_mike@outlook.com
eacffc96ec3b3b9ec459f40ee82f5577efb770e4
044045d33dddff1e1a4e912334e40bc89c1a5f34
/hmwk/3/system_model/particle_system/particle_state/src/hamiltonian_particle_state.cc
4a9180d0aff45e2d3bdbd8beca4eb8f6335fd9df
[ "MIT" ]
permissive
ForrestHurley/compPhys
b9e991fb6ad7f8decc18c034fe95fb6b128b3258
34c2d93b77858150a1c099deff812d961ab6378d
refs/heads/master
2020-03-27T20:06:13.996869
2018-11-14T21:51:02
2018-11-14T21:51:02
147,038,795
0
0
null
null
null
null
UTF-8
C++
false
false
1,186
cc
#include "hamiltonian_particle_state.h" HamiltonianParticleState::HamiltonianParticleState( SmoothCoordinateSpace* position_space, SmoothCoordinateSpace* momentum_space) : ParticleState(std::vector<SmoothCoordinateSpace*>{position_space, momentum_space}) {} void HamiltonianParticleState::AddParticle( const Coordinate& position, const Coordinate& momentum) { ParticleState::AddParticle(std::vector<Coordinate>{position, momentum}); } void HamiltonianParticleState::AddStationaryParticle( const Coordinate& position) { AddParticle( position, coordinate_spaces.at(1)->getOrigin().getCoordinate()); } SmoothCoordinateSpace* HamiltonianParticleState::getPositionSpace() const { return getComponentSpace(0); } SmoothCoordinateSpace* HamiltonianParticleState::getMomentumSpace() const { return getComponentSpace(1); } const std::vector<SmoothCoordinateSpace::SmoothCoordinatePoint*>& HamiltonianParticleState::getPositions() const { return getStateComponent(0); //0 is the positions } const std::vector<SmoothCoordinateSpace::SmoothCoordinatePoint*>& HamiltonianParticleState::getMomenta() const { return getStateComponent(1); //1 is the momenta }
[ "forrestelihurley0@gmail.com" ]
forrestelihurley0@gmail.com
779b5430e6cc4d277d2a5615fb3cffdfda5d50e1
b62da36591fa1b51ed8fcbcf51c183382412abdc
/libcul/src/CULInterface.cpp
96cf5b226c9cf09dccebd23d7acfd0640ead0ca0
[]
no_license
bartekordek/CUL
ec3201627caffb88acd37fb733988de9c59f9472
3e9321ac8d1956200f84dd857331fdd81b60f881
refs/heads/master
2023-08-14T21:18:18.274526
2023-07-20T15:24:53
2023-07-20T15:24:53
98,740,869
0
0
null
2023-09-10T08:08:17
2017-07-29T15:20:21
C++
UTF-8
C++
false
false
6,168
cpp
#include "CUL/CULInterface.hpp" #include "CUL/Memory/MemoryPool.hpp" #include "CUL/Threading/ThreadUtils.hpp" #include "CUL/Filesystem/FSApi.hpp" #include "CUL/Filesystem/FileFactory.hpp" #include "CUL/Graphics/IImageLoader.hpp" #include "CUL/Log/ILogContainer.hpp" #include "GenericUtils/IConfigFileConcrete.hpp" #include "CUL/GenericUtils/ConsoleUtilities.hpp" #include "Threading/IThreadUtilConcrete.hpp" #include "CUL/GenericUtils/Singleton.hpp" #include "CUL/STL_IMPORTS/STD_iostream.hpp" #include "CUL/STL_IMPORTS/STD_new.hpp" #include "CUL/STL_IMPORTS/STD_memory_resource.hpp" static std::array<std::byte, 8192> g_bufferBlocks; static std::pmr::monotonic_buffer_resource g_buffer_src( &g_bufferBlocks, sizeof( g_bufferBlocks ) ); static std::pmr::vector<void*> g_allocatedBlocks( &g_buffer_src ); static CUL::LOG::ILogger* g_logger = nullptr; using namespace CUL; #if CUL_GLOBAL_MEMORY_POOL #endif // #if CUL_GLOBAL_MEMORY_POOL CULInterface* CULInterface::s_instance = nullptr; CULInterface* CULInterface::createInstance( const FS::Path& configFile ) { if( s_instance == nullptr ) { auto instance = new CULInterface( configFile ); instance->initialize(); } return s_instance; } CULInterface* CULInterface::getInstance() { return s_instance; } CULInterface::CULInterface( const FS::Path& configFilePath ): m_configFilePath( configFilePath ) { CUL::Assert::simple( s_instance == nullptr ); s_instance = this; } void CULInterface::initialize() { m_fileFactory = new FS::FileFactory( this ); m_fsApi.reset( FS::FSApi::crateInstance( "FSApiFS", m_fileFactory, this ) ); m_logger = LOG::LOG_CONTAINER::getLogger(); if( !m_configFilePath.getPath().empty() ) { m_configFile = loadConfigFile( m_configFilePath ); } m_imageLoader.reset( Graphics::IImageLoader::createConcrete( m_configFile, this ) ); m_logger->log( "Initialized logger." ); if( !g_logger ) { g_logger = m_logger; } #if CUL_GLOBAL_MEMORY_POOL CUL::Memory::MemoryPool::s_logger = m_logger; #endif // #if CUL_GLOBAL_MEMORY_POOL m_sysFonts = OSUtils::ISystemFonts::createConcrete( m_fsApi.get(), m_logger ); m_args.reset( new GUTILS::ConsoleUtilities() ); m_threadUtils = new ThreadUtils(); } GUTILS::IConfigFile* CULInterface::getConfig() const { return m_configFile; } CUL::LOG::ILogger* CULInterface::getLogger() { return m_logger; } FS::FSApi* CULInterface::getFS() { return m_fsApi.get(); } OSUtils::ISystemFonts* CULInterface::getSystemFonts() { return m_sysFonts; } FS::FileFactory* CULInterface::getFF() { return m_fileFactory; } Graphics::IImageLoader* CULInterface::getImageLoader() { return m_imageLoader.get(); } GUTILS::ConsoleUtilities* CULInterface::getConsoleUtils() { return m_args.get(); } ThreadUtils& CULInterface::getThreadUtils() { return *m_threadUtils; } GUTILS::IConfigFile* CULInterface::loadConfigFile( const FS::Path& path ) { return new GUTILS::IConfigFileConcrete( path, this ); } CULInterface::~CULInterface() { delete m_sysFonts; m_sysFonts = nullptr; delete m_threadUtils; m_threadUtils = nullptr; LOG::LOG_CONTAINER::destroyLogger(); #if CUL_GLOBAL_MEMORY_POOL Memory::MemoryPool::s_logger = m_logger; #endif // #if CUL_GLOBAL_MEMORY_POOL g_logger = nullptr; m_logger = nullptr; s_instance = nullptr; } #if CUL_GLOBAL_MEMORY_POOL void* operator new( std::size_t size ) { if( Singleton<Memory::MemoryPool>::getInstance().isInitialized() ) { void* result = Singleton<Memory::MemoryPool>::getInstance().getMemory( size ); if( result ) { //addMe( result ); return result; } else { return std::malloc( size ); } } else { void* p = std::malloc( size ); return p; } } void* operator new[]( std::size_t size ) { if( Singleton<Memory::MemoryPool>::getInstance().isInitialized() ) { void* result = Singleton<Memory::MemoryPool>::getInstance().getMemory( size ); if( result ) { //addMe( result ); return result; } else { return std::malloc( size ); } } else { void* p = std::malloc( size ); return p; } } void operator delete( void* p ) throw() { if( Singleton<Memory::MemoryPool>::getInstance().isInitialized() && Singleton<Memory::MemoryPool>::getInstance().exist( p ) ) { Singleton<Memory::MemoryPool>::getInstance().release( p ); } else { //if( findMe( p ) ) //{ // std::cerr << "Trying to release old stack ptr.\n"; //} std::free( p ); } } void operator delete( void* p, std::size_t targetSize ) throw() { if( Singleton<Memory::MemoryPool>::getInstance().isInitialized() && Singleton<Memory::MemoryPool>::getInstance().exist( p ) ) { Singleton<Memory::MemoryPool>::getInstance().release( p, targetSize ); } else { //if( findMe(p) ) //{ // std::cerr << "Trying to release old stack ptr.\n"; //} std::free( p ); } } void operator delete[]( void* p ) throw() { if( Singleton<Memory::MemoryPool>::getInstance().isInitialized() && Singleton<Memory::MemoryPool>::getInstance().exist( p ) ) { Singleton<Memory::MemoryPool>::getInstance().release( p ); } else { //if( findMe( p ) ) //{ // std::cerr << "Trying to release old stack ptr.\n"; //} std::free( p ); } } void operator delete[]( void* p, std::size_t /* targetSize */ ) throw() { if( Singleton<Memory::MemoryPool>::getInstance().isInitialized() && Singleton<Memory::MemoryPool>::getInstance().exist( p ) ) { Singleton<Memory::MemoryPool>::getInstance().release( p ); } else { //if( findMe( p ) ) //{ // std::cerr << "Trying to release old stack ptr.\n"; //} std::free( p ); } } #endif // #ifdef CUL_GLOBAL_MEMORY_POOL
[ "bartekordek@gmail.com" ]
bartekordek@gmail.com
899817537e9c3defd6060431081a80363a6a104b
4260931a5fbbb068e3378a00abebd494486e193e
/src/test/multisig_tests.cpp
35f1e9e63331baa07c3dac7ab7f5b83b3ac49b42
[ "MIT" ]
permissive
binariumpay/binarium
2a0d09aef38859ee7f0b65e5ec8684b363d0ab14
9f5de397da53eae9765d7d7495c8106b122ee3ab
refs/heads/master
2023-01-20T20:24:28.352931
2023-01-12T18:52:59
2023-01-12T18:52:59
117,983,211
25
10
MIT
2021-03-27T21:49:04
2018-01-18T12:59:04
C++
UTF-8
C++
false
false
11,947
cpp
// Copyright (c) 2011-2013 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 "key.h" #include "keystore.h" #include "policy/policy.h" #include "script/script.h" #include "script/script_error.h" #include "script/interpreter.h" #include "script/sign.h" #include "uint256.h" #include "test/test_binarium.h" #ifdef ENABLE_WALLET #include "wallet/wallet_ismine.h" #endif #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> using namespace std; typedef vector<unsigned char> valtype; BOOST_FIXTURE_TEST_SUITE(multisig_tests, BasicTestingSetup) CScript sign_multisig(CScript scriptPubKey, vector<CKey> keys, CTransaction transaction, int whichIn) { uint256 hash = SignatureHash(scriptPubKey, transaction, whichIn, SIGHASH_ALL); CScript result; result << OP_0; // CHECKMULTISIG bug workaround BOOST_FOREACH(const CKey &key, keys) { vector<unsigned char> vchSig; BOOST_CHECK(key.Sign(hash, vchSig)); vchSig.push_back((unsigned char)SIGHASH_ALL); result << vchSig; } return result; } BOOST_AUTO_TEST_CASE(multisig_verify) { unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC; ScriptError err; CKey key[4]; for (int i = 0; i < 4; i++) key[i].MakeNewKey(true); CScript a_and_b; a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript a_or_b; a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript escrow; escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; CMutableTransaction txFrom; // Funding transaction txFrom.vout.resize(3); txFrom.vout[0].scriptPubKey = a_and_b; txFrom.vout[1].scriptPubKey = a_or_b; txFrom.vout[2].scriptPubKey = escrow; CMutableTransaction txTo[3]; // Spending transaction for (int i = 0; i < 3; i++) { txTo[i].vin.resize(1); txTo[i].vout.resize(1); txTo[i].vin[0].prevout.n = i; txTo[i].vin[0].prevout.hash = txFrom.GetHash(); txTo[i].vout[0].nValue = 1; } vector<CKey> keys; CScript s; // Test a AND b: keys.assign(1,key[0]); keys.push_back(key[1]); s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK(VerifyScript(s, a_and_b, flags, MutableTransactionSignatureChecker(&txTo[0], 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); for (int i = 0; i < 4; i++) { keys.assign(1,key[i]); s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, flags, MutableTransactionSignatureChecker(&txTo[0], 0), &err), strprintf("a&b 1: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err)); keys.assign(1,key[1]); keys.push_back(key[i]); s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, flags, MutableTransactionSignatureChecker(&txTo[0], 0), &err), strprintf("a&b 2: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } // Test a OR b: for (int i = 0; i < 4; i++) { keys.assign(1,key[i]); s = sign_multisig(a_or_b, keys, txTo[1], 0); if (i == 0 || i == 1) { BOOST_CHECK_MESSAGE(VerifyScript(s, a_or_b, flags, MutableTransactionSignatureChecker(&txTo[1], 0), &err), strprintf("a|b: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } else { BOOST_CHECK_MESSAGE(!VerifyScript(s, a_or_b, flags, MutableTransactionSignatureChecker(&txTo[1], 0), &err), strprintf("a|b: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } } s.clear(); s << OP_0 << OP_1; BOOST_CHECK(!VerifyScript(s, a_or_b, flags, MutableTransactionSignatureChecker(&txTo[1], 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_SIG_DER, ScriptErrorString(err)); for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { keys.assign(1,key[i]); keys.push_back(key[j]); s = sign_multisig(escrow, keys, txTo[2], 0); if (i < j && i < 3 && j < 3) { BOOST_CHECK_MESSAGE(VerifyScript(s, escrow, flags, MutableTransactionSignatureChecker(&txTo[2], 0), &err), strprintf("escrow 1: %d %d", i, j)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } else { BOOST_CHECK_MESSAGE(!VerifyScript(s, escrow, flags, MutableTransactionSignatureChecker(&txTo[2], 0), &err), strprintf("escrow 2: %d %d", i, j)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } } } BOOST_AUTO_TEST_CASE(multisig_IsStandard) { CKey key[4]; for (int i = 0; i < 4; i++) key[i].MakeNewKey(true); txnouttype whichType; CScript a_and_b; a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(::IsStandard(a_and_b, whichType)); CScript a_or_b; a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(::IsStandard(a_or_b, whichType)); CScript escrow; escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; BOOST_CHECK(::IsStandard(escrow, whichType)); CScript one_of_four; one_of_four << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << ToByteVector(key[3].GetPubKey()) << OP_4 << OP_CHECKMULTISIG; BOOST_CHECK(!::IsStandard(one_of_four, whichType)); CScript malformed[6]; malformed[0] << OP_3 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; malformed[1] << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; malformed[2] << OP_0 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; malformed[3] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_0 << OP_CHECKMULTISIG; malformed[4] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_CHECKMULTISIG; malformed[5] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()); for (int i = 0; i < 6; i++) BOOST_CHECK(!::IsStandard(malformed[i], whichType)); } BOOST_AUTO_TEST_CASE(multisig_Solver1) { // Tests Solver() that returns lists of keys that are // required to satisfy a ScriptPubKey // // Also tests IsMine() and ExtractDestination() // // Note: ExtractDestination for the multisignature transactions // always returns false for this release, even if you have // one key that would satisfy an (a|b) or 2-of-3 keys needed // to spend an escrow transaction. // CBasicKeyStore keystore, emptykeystore, partialkeystore; CKey key[3]; CTxDestination keyaddr[3]; for (int i = 0; i < 3; i++) { key[i].MakeNewKey(true); keystore.AddKey(key[i]); keyaddr[i] = key[i].GetPubKey().GetID(); } partialkeystore.AddKey(key[0]); { vector<valtype> solutions; txnouttype whichType; CScript s; s << ToByteVector(key[0].GetPubKey()) << OP_CHECKSIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK(solutions.size() == 1); CTxDestination addr; BOOST_CHECK(ExtractDestination(s, addr)); BOOST_CHECK(addr == keyaddr[0]); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_DUP << OP_HASH160 << ToByteVector(key[0].GetPubKey().GetID()) << OP_EQUALVERIFY << OP_CHECKSIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK(solutions.size() == 1); CTxDestination addr; BOOST_CHECK(ExtractDestination(s, addr)); BOOST_CHECK(addr == keyaddr[0]); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK_EQUAL(solutions.size(), 4U); CTxDestination addr; BOOST_CHECK(!ExtractDestination(s, addr)); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); BOOST_CHECK(!IsMine(partialkeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK_EQUAL(solutions.size(), 4U); vector<CTxDestination> addrs; int nRequired; BOOST_CHECK(ExtractDestinations(s, whichType, addrs, nRequired)); BOOST_CHECK(addrs[0] == keyaddr[0]); BOOST_CHECK(addrs[1] == keyaddr[1]); BOOST_CHECK(nRequired == 1); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); BOOST_CHECK(!IsMine(partialkeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK(solutions.size() == 5); } } BOOST_AUTO_TEST_CASE(multisig_Sign) { // Test SignSignature() (and therefore the version of Solver() that signs transactions) CBasicKeyStore keystore; CKey key[4]; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(true); keystore.AddKey(key[i]); } CScript a_and_b; a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript a_or_b; a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript escrow; escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; CMutableTransaction txFrom; // Funding transaction txFrom.vout.resize(3); txFrom.vout[0].scriptPubKey = a_and_b; txFrom.vout[1].scriptPubKey = a_or_b; txFrom.vout[2].scriptPubKey = escrow; CMutableTransaction txTo[3]; // Spending transaction for (int i = 0; i < 3; i++) { txTo[i].vin.resize(1); txTo[i].vout.resize(1); txTo[i].vin[0].prevout.n = i; txTo[i].vin[0].prevout.hash = txFrom.GetHash(); txTo[i].vout[0].nValue = 1; } for (int i = 0; i < 3; i++) { BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i)); } } BOOST_AUTO_TEST_SUITE_END()
[ "RodionKarimov@yandex.ru" ]
RodionKarimov@yandex.ru
605a2e22cf618575f4daf967b6387a84908741eb
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5765824346324992_0/C++/Temirulan/a.cpp
6ae52280efc2ed64b167cad4d1c9b33d34253044
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
2,063
cpp
#include <iostream> #include <cmath> #include <cstdio> #include <cstring> #include <cstdlib> #include <cassert> #include <ctime> #include <sstream> #include <algorithm> #include <functional> #include <numeric> #include <string> #include <vector> #include <queue> #include <stack> #include <map> #include <set> using namespace std; #define f first #define s second #define pb push_back #define mp make_pair #define ll long long #define pii pair < int, int > #define pll pair < long long, long long> #define ull unsigned long long #define y1 stupid_cmath #define left stupid_left #define right stupid_right #define vi vector <int> #define sz(a) (int)a.size() #define forit(it, s) for(__typeof(s.begin()) it = s.begin(); it != s.end(); it++) #define all(a) a.begin(), a.end() #define sqr(x) ((x) * (x)) const int inf = (int)1e9; const int mod = inf + 7; const double eps = 1e-9; const double pi = acos(-1.0); int t, b, a[20000], n; ll calc(ll t) { ll ans = 0; for(int i = 0; i < b; i++) { ans += (t + a[i] - 1) / a[i]; ans = min(ans, (ll)1e18); } return ans; } bool cmp(pii a, pii b) { if(a.f != b.f) return a.f < b.f; return a.s > b.s; } void solve(int num) { scanf("%d%d", &b, &n); for(int i = 0; i < b; i++) { scanf("%d", a + i); } ll l = 0, r = (ll)1e18; ll ans = r; while(l <= r) { ll mid = (l + r) >> 1; if(calc(mid) >= n) { ans = mid; r = mid - 1; } else l = mid + 1; } int res = -1; ll k = calc(ans); vector<int> v; ll x = inf; for(int i = 0; i < b; i++) { x = min(x, ans % a[i]); } for(int i = 0; i < b; i++) { if(ans % a[i] == x) v.pb(i + 1); } reverse(all(v)); res = v[k-n]; /* for(int i = 0; i < b; i++) cout << v[i].f << " " << v[i].s << endl; k -= n; cout << k << endl; res = v[k].s; */ printf("Case #%d: %d\n", num, res); } int main(){ scanf("%d", &t); for(int i = 1; i <= t; i++) solve(i); return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
d23077c91f4f97ba26b499540fae9f96ac076d97
a8ca6de0e1d5823e981263d0d2c96bd7e798075f
/Source/DroneGame/DroneGameCharacter.cpp
1568044f8a38318caf09cbc271be2a70620e6b19
[]
no_license
clempers/DroneGame
247f49e660facb6e8f9e098e51536039076739e4
d9233151867a36edc731b925054892173014cab2
refs/heads/master
2020-05-21T10:49:18.417376
2017-03-11T02:56:48
2017-03-11T02:56:48
84,619,501
0
0
null
null
null
null
UTF-8
C++
false
false
5,309
cpp
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "DroneGame.h" #include "Kismet/HeadMountedDisplayFunctionLibrary.h" #include "DroneGameCharacter.h" ////////////////////////////////////////////////////////////////////////// // ADroneGameCharacter ADroneGameCharacter::ADroneGameCharacter() { // Set size for collision capsule GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); // set our turn rates for input BaseTurnRate = 45.f; BaseLookUpRate = 45.f; bBackwards = false; // Don't rotate when the controller rotates. Let that just affect the camera. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = false; // Character moves in the direction of input... GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate GetCharacterMovement()->JumpZVelocity = 600.f; GetCharacterMovement()->AirControl = 0.2f; // Create a camera boom (pulls in towards the player if there is a collision) CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller // Create a follow camera FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera")); FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm // Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character) // are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++) } ////////////////////////////////////////////////////////////////////////// // Input void ADroneGameCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { // Set up gameplay key bindings check(PlayerInputComponent); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping); PlayerInputComponent->BindAxis("MoveForward", this, &ADroneGameCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &ADroneGameCharacter::MoveRight); // We have 2 versions of the rotation bindings to handle different kinds of devices differently // "turn" handles devices that provide an absolute delta, such as a mouse. // "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); PlayerInputComponent->BindAxis("TurnRate", this, &ADroneGameCharacter::TurnAtRate); PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); PlayerInputComponent->BindAxis("LookUpRate", this, &ADroneGameCharacter::LookUpAtRate); // handle touch devices PlayerInputComponent->BindTouch(IE_Pressed, this, &ADroneGameCharacter::TouchStarted); PlayerInputComponent->BindTouch(IE_Released, this, &ADroneGameCharacter::TouchStopped); // VR headset functionality PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &ADroneGameCharacter::OnResetVR); } void ADroneGameCharacter::OnResetVR() { UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition(); } void ADroneGameCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location) { Jump(); } void ADroneGameCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location) { StopJumping(); } void ADroneGameCharacter::TurnAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void ADroneGameCharacter::LookUpAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds()); } void ADroneGameCharacter::MoveForward(float Value) { if (Value < 0.0f) bBackwards = true; else bBackwards = false; if ((Controller != NULL) && (Value != 0.0f)) { // find out which way is forward const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get forward vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); if (Value > 0) AddMovementInput(Direction, Value); else AddMovementInput(Direction, Value / 10.0f); } } void ADroneGameCharacter::MoveRight(float Value) { if ( (Controller != NULL) && (Value != 0.0f) ) { // find out which way is right const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get right vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); // add movement in that direction if (!bBackwards) AddMovementInput(Direction, Value); else AddMovementInput(Direction, Value / 10.0f); } }
[ "dclemson@andrew.cmu.edu" ]
dclemson@andrew.cmu.edu
83f56271e20d436fc5ee10139237e2c7bc476e0d
b40ff801c83d048177b37e46ab3f4cbc60d51f30
/Rpackages/Rcpp/include/Rcpp/internal/export.h
6b3a173006f0d3ea704936d2750f77f77189c0df
[]
no_license
murphyjames04/sablefish
3423d64c1d07e6a1848826604874f03bbe444cdb
ef790f9775c82921604c2dcb72ce6690c9c30e13
refs/heads/master
2020-05-17T09:19:51.620950
2013-07-23T22:18:09
2013-07-23T22:18:09
11,323,999
0
1
null
null
null
null
UTF-8
C++
false
false
5,914
h
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- /* :tabSize=4:indentSize=4:noTabs=false:folding=explicit:collapseFolds=1: */ // // export.h: Rcpp R/C++ interface class library -- // // Copyright (C) 2010 - 2013 Dirk Eddelbuettel and Romain Francois // Copyright (C) 2013 Rice University // // This file is part of Rcpp. // // Rcpp is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // Rcpp 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 Rcpp. If not, see <http://www.gnu.org/licenses/>. #ifndef Rcpp__internal__export__h #define Rcpp__internal__export__h namespace Rcpp{ namespace internal{ template <typename T> std::wstring as_string_elt__impl( SEXP x, R_len_t i, Rcpp::traits::true_type ){ const char* y = char_get_string_elt( x, i ) ; return std::wstring(y, y+strlen(y) ) ; } template <typename T> std::string as_string_elt__impl( SEXP x, R_len_t i, Rcpp::traits::false_type ){ return char_get_string_elt( x, i ) ; } template <typename T> const std::basic_string< typename Rcpp::traits::char_type<T>::type > as_string_elt( SEXP x, R_len_t i ){ return as_string_elt__impl<T>( x, i, typename Rcpp::traits::is_wide_string<T>::type() ) ; } /* iterating */ template <typename InputIterator, typename value_type> void export_range__impl( SEXP x, InputIterator first, ::Rcpp::traits::false_type ) { const int RTYPE = ::Rcpp::traits::r_sexptype_traits<value_type>::rtype ; typedef typename ::Rcpp::traits::storage_type<RTYPE>::type STORAGE ; SEXP y = PROTECT( ::Rcpp::r_cast<RTYPE>(x) ) ; STORAGE* start = ::Rcpp::internal::r_vector_start<RTYPE>(y) ; std::copy( start, start + ::Rf_length(y), first ) ; UNPROTECT(1) ; } template <typename InputIterator, typename value_type> void export_range__impl( SEXP x, InputIterator first, ::Rcpp::traits::true_type ) { const int RTYPE = ::Rcpp::traits::r_sexptype_traits<value_type>::rtype ; typedef typename ::Rcpp::traits::storage_type<RTYPE>::type STORAGE ; SEXP y = PROTECT( ::Rcpp::r_cast<RTYPE>(x) ) ; STORAGE* start = ::Rcpp::internal::r_vector_start<RTYPE>(y) ; std::transform( start, start + ::Rf_length(y) , first, caster<STORAGE,value_type> ) ; UNPROTECT(1) ; } template <typename InputIterator, typename value_type> void export_range__dispatch( SEXP x, InputIterator first, ::Rcpp::traits::r_type_primitive_tag ) { export_range__impl<InputIterator,value_type>( x, first, typename ::Rcpp::traits::r_sexptype_needscast<value_type>() ); } template <typename InputIterator, typename value_type> void export_range__dispatch( SEXP x, InputIterator first, ::Rcpp::traits::r_type_string_tag ) { if( ! ::Rf_isString( x) ) throw ::Rcpp::not_compatible( "expecting a string vector" ) ; R_len_t n = ::Rf_length(x) ; for( R_len_t i=0; i<n; i++, ++first ){ *first = as_string_elt<typename std::iterator_traits<InputIterator>::value_type> ( x, i ) ; } } template <typename InputIterator> void export_range( SEXP x, InputIterator first ) { export_range__dispatch<InputIterator,typename std::iterator_traits<InputIterator>::value_type>( x, first, typename ::Rcpp::traits::r_type_traits<typename std::iterator_traits<InputIterator>::value_type>::r_category() ); } /* indexing */ template <typename T, typename value_type> void export_indexing__impl( SEXP x, T& res, ::Rcpp::traits::false_type ) { const int RTYPE = ::Rcpp::traits::r_sexptype_traits<value_type>::rtype ; typedef typename ::Rcpp::traits::storage_type<RTYPE>::type STORAGE ; SEXP y = PROTECT( ::Rcpp::r_cast<RTYPE>(x) ) ; STORAGE* start = ::Rcpp::internal::r_vector_start<RTYPE>(y) ; R_len_t size = ::Rf_length(y) ; for( R_len_t i=0; i<size; i++){ res[i] = start[i] ; } UNPROTECT(1) ; /* y */ } template <typename T, typename value_type> void export_indexing__impl( SEXP x, T& res, ::Rcpp::traits::true_type ) { const int RTYPE = ::Rcpp::traits::r_sexptype_traits<value_type>::rtype ; typedef typename ::Rcpp::traits::storage_type<RTYPE>::type STORAGE ; SEXP y = PROTECT( ::Rcpp::r_cast<RTYPE>(x) ) ; STORAGE* start = ::Rcpp::internal::r_vector_start<RTYPE>(y) ; R_len_t size = ::Rf_length(y) ; for( R_len_t i=0; i<size; i++){ res[i] = caster<STORAGE,value_type>(start[i]) ; } UNPROTECT(1) ; /* y */ } template <typename T, typename value_type> void export_indexing__dispatch( SEXP x, T& res, ::Rcpp::traits::r_type_primitive_tag ) { export_indexing__impl<T,value_type>( x, res, typename ::Rcpp::traits::r_sexptype_needscast<value_type>() ); } template <typename T, typename value_type> void export_indexing__dispatch( SEXP x, T& res, ::Rcpp::traits::r_type_string_tag ) { if( ! ::Rf_isString( x) ) throw Rcpp::not_compatible( "expecting a string vector" ) ; R_len_t n = ::Rf_length(x) ; for( R_len_t i=0; i<n; i++ ){ res[i] = as_string_elt< value_type >( x, i) ; } } template <typename T, typename value_type> void export_indexing( SEXP x, T& res ) { export_indexing__dispatch<T,value_type>( x, res, typename ::Rcpp::traits::r_type_traits<value_type>::r_category() ); } } } #endif
[ "murphyjames04@gmai.com" ]
murphyjames04@gmai.com
243efc2e61b4e72412b61a365e0a5d2388188dbd
6bfb0c97b4509acc259a5744f942878e0d468d9a
/recursion/suranshAndString.cpp
eadf5e322056bdecf5ee710ce904a87f62dcbe1a
[]
no_license
sabeelhps/CBlocks
0c3588aa833f65dd360aafaab18b9969b2832942
c69cb4ed08c328cc9965464198e4e803f104dca5
refs/heads/master
2021-05-22T01:57:32.782521
2020-04-04T05:31:47
2020-04-04T05:31:47
252,917,420
0
0
null
null
null
null
UTF-8
C++
false
false
627
cpp
#include <iostream> #include <vector> #include <algorithm> #include<cstring> #include<set> using namespace std; string str=""; string merge(string a,string b){ int i=0; int j=0; while(i<a.size()&&j<b.size()){ if(a[i]<b[j]){ str+=a[i++]; }else{ str+=b[j++]; } } while(i<a.size()){ str+=a[i++]; } while(j<b.size()){ str+=b[j++]; } return str; } int main(){ string a; string b; int t; cin>>t; while(t--){ cin>>a>>b; str.clear(); cout<<merge(a,b)<<endl; } return 0; }
[ "sabeelhps@gmail.com" ]
sabeelhps@gmail.com