blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
f0d3dc83292c2546392dadbf1e3a38d6251635a5
fdf4796be7673359f1610e50d9da7c1ecd93ccb2
/Color.cpp
10f474dcf4c9f690a8f30c790740b8c4290e9f75
[]
no_license
jeckel/LightSpace
b089422c76f6ab890e6ace7810174ec86a8bf1db
ff74cbd07c2cfd39951e00cc33656fb8f5cdf68d
refs/heads/master
2016-09-01T20:45:59.612811
2013-06-17T19:10:03
2013-06-17T19:10:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,614
cpp
#include "Color.h" #include <pgmspace.h> /** * Convert separate R,G,B into combined 32-bit GRB * @param byte r Red color * @param byte g Green color * @param byte b Blue color * @return struct CRGB */ struct CRGB Color(byte r, byte g, byte b) { struct CRGB led; led.r = r; led.g = g; led.b = b; return led; }; /** * Calculate R G B from Hue * @param float v1 * @param float v2 * @param float vH * @return float */ float Hue_2_RGB( float v1, float v2, float vH ) //Function Hue_2_RGB { if ( vH < 0 ) vH += 1; if ( vH > 1 ) vH -= 1; if ( ( 6 * vH ) < 1 ) return ( v1 + ( v2 - v1 ) * 6 * vH ); if ( ( 2 * vH ) < 1 ) return ( v2 ); if ( ( 3 * vH ) < 2 ) return ( v1 + ( v2 - v1 ) * (.66-vH) * 6 ); return ( v1 ); } /** * Calculate RGB color from Hue/Saturation/Lightness * @param float H Hue from 0 to 1 * @param float S Saturation from 0 to 1 * @param float L Lightness from 0 to 1 * @return struct CRGB */ struct CRGB HSL(float H, float S, float L) { struct CRGB color; float var_1; float var_2; float Hu=H+.33; float Hd=H-.33; if ( S == 0 ) //HSL from 0 to 1 { color.r = L * 255; //RGB results from 0 to 255 color.g = L * 255; color.b = L * 255; } else { if ( L < 0.5 ) var_2 = L * ( 1 + S ); else var_2 = ( L + S ) - ( S * L ); var_1 = 2 * L - var_2; color.r = round(255 * Hue_2_RGB( var_1, var_2, Hu )); color.g = round(255 * Hue_2_RGB( var_1, var_2, H )); color.b = round(255 * Hue_2_RGB( var_1, var_2, Hd )); } return color; } /** * Fire color palete stored in Flash Memory to optiomize SRAM capabilities */ PROGMEM prog_uchar fireColorPalette[] = { 0,0,0,0,4,0,0,8,0,0,12,0,0,16,1,0,20,1,0,24,1,0,28,2, 0,32,2,0,36,3,0,40,3,0,44,4,0,48,5,0,52,5,0,56,6,0,60,7, 0,64,8,0,68,9,0,72,10,0,76,11,0,80,13,0,84,14,0,88,15,0,92,17, 0,96,18,0,100,20,0,104,21,0,108,23,0,112,25,0,116,26,0,120,28,0,124,30, 0,128,32,0,132,34,0,136,36,0,140,38,0,144,41,0,148,43,0,152,45,0,156,48, 0,160,50,0,164,53,0,168,55,0,172,58,0,176,61,0,180,64,0,184,66,0,188,69, 0,192,72,0,196,75,0,200,78,0,204,82,0,208,85,0,212,88,0,216,91,0,220,95, 0,224,98,0,228,102,0,232,106,0,236,109,0,240,113,0,244,117,0,248,121,0,252,125, 1,255,128,5,255,132,9,255,136,13,255,140,17,255,144,21,255,148,25,255,151,29,255,155, 33,255,158,37,255,162,41,255,165,45,255,169,49,255,172,53,255,175,57,255,178,61,255,181, 65,255,184,69,255,187,73,255,190,77,255,193,81,255,196,85,255,198,89,255,201,93,255,204, 97,255,206,101,255,208,105,255,211,109,255,213,113,255,215,117,255,218,121,255,220,125,255,222, 129,255,224,133,255,226,137,255,228,141,255,230,145,255,231,149,255,233,153,255,235,157,255,236, 161,255,238,165,255,239,169,255,240,173,255,242,177,255,243,181,255,244,185,255,245,189,255,246, 193,255,247,197,255,248,201,255,249,205,255,250,209,255,251,213,255,252,217,255,252,221,255,253, 225,255,253,229,255,254,233,255,254,237,255,254,241,255,255,245,255,255,249,255,255,253,255,255, 255,255,255 }; /** * Get fire color from palette * @param byte x Coordinate in palette * @return struct CRGB */ struct CRGB getFireColorFromPalette(byte x) { if (x > 128) x = 128; return Color(pgm_read_byte_near(fireColorPalette + x * 3 + 1), pgm_read_byte_near(fireColorPalette + x * 3 + 2), pgm_read_byte_near(fireColorPalette + x * 3)); }
[ "jeckel@jeckel.fr" ]
jeckel@jeckel.fr
9808391d426c06019d5607273571678c97fb16fe
aa143bf7597d0193d63c3085ba3c5836c16f22b6
/30_Days_of_Code/Day_08_Dictionaries_and_Maps.cpp
145785faa08822f1bce0100d94c114df0c706181
[ "Apache-2.0" ]
permissive
softctrl/hackerrank_codes
ed46a41070feded63b3e7f161855a7a0f4d77cbb
b67684a82906ee9176297d786137c07f9df2b195
refs/heads/master
2020-04-12T05:01:01.772693
2016-11-09T19:43:37
2016-11-09T19:43:37
62,399,539
0
0
null
null
null
null
UTF-8
C++
false
false
662
cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <map> using namespace std; int main() { map<string, string> agenda; int n; cin >> n; while (n--) { string name; string phone_number; cin >> name >> phone_number; agenda.insert(make_pair(name, phone_number)); } string query; while (cin >> query) { map<string, string>::iterator pos = agenda.find(query); if (pos == agenda.end()) { cout << "Not found" << endl; } else { cout << query << "=" << pos->second << endl; } } return 0; }
[ "noreply@github.com" ]
noreply@github.com
c68f7750ebdc4d9c5cf6528b54ac77f1789306eb
82df259362bfd44e9c445c7868abd31601c94a1a
/Gataringan/Main/NewGLUT/Texture2D.cpp
b609b33af9443d8cda1ab7438271302d1ae29d48
[ "MIT" ]
permissive
RuiMitchellDaSilva/OldProjects
2ddc9a99910a59d081c69a9b646d9d9711768ab9
9b797d45e8b1bfe3bf843671eedde4c59037d176
refs/heads/master
2021-01-15T22:34:35.270226
2015-02-05T23:35:10
2015-02-05T23:35:10
30,382,783
0
0
null
null
null
null
UTF-8
C++
false
false
1,218
cpp
#include "Texture2D.h" #include <iostream> #include <fstream> using namespace std; Texture2D::Texture2D(){} Texture2D::~Texture2D(){} bool Texture2D::Load(char* path, int width, int height) { char* tempTextureData; int fileSize; ifstream inFile; _width = width; _height = height; inFile.open(path, ios::binary); if (!inFile.good()) { cerr << "Unable to open texture file" << path << endl; return false; } inFile.seekg(0, ios::end); //Seeks for the end of file being read fileSize = (int)inFile.tellg(); //Get current position in file till the end, giving the total file size tempTextureData = new char[fileSize]; //create a new array to store data inFile.seekg(0, ios::beg); //Seek back to beginning of file inFile.read(tempTextureData, fileSize); //Read all data within file in one go inFile.close(); //Close the file cout << path << " texture file has successfully loaded" << endl; glGenTextures(1, &_ID); //Get next Texture ID glBindTexture(GL_TEXTURE_2D, _ID); //Bind the texture to the ID glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, tempTextureData); delete[] tempTextureData; //Clear up the data as we don't need this any more return true; }
[ "ruialexandro@hotmail.co.uk" ]
ruialexandro@hotmail.co.uk
76e566edcee5e0e4fe0a55521174697cb2ad328e
db89ce4d4cbca8060eadc3a59f8ebf2eaae1d8a9
/morehouse/other/foo.cpp
2dd17648f49350d7fc21e22b008b90e006482e9a
[]
no_license
fgxbzns/ngs
c71dce4c2589b1a902f7316da73264d84044e56a
2ad466b1c837e18462795ea4fc64f432f71a5166
refs/heads/master
2021-01-01T18:42:35.357045
2015-04-28T20:41:40
2015-04-28T20:41:40
10,322,991
0
0
null
null
null
null
UTF-8
C++
false
false
176
cpp
// filename: foo.cpp #include <stdio.h> extern "C" char* myprint(char *str) { puts(str); return str; } extern "C" float add(float a, float b) { return a + b; }
[ "fgxbzns@gmail.com" ]
fgxbzns@gmail.com
1d6f017e6b65395bf05eef4cd84e5adbed2fceb8
d761e11c779aea4677ecf8b7cbf28e0a401f6525
/src/include/EnumeratedFileReader.hpp
8b96dcf44184beb5b259e61b43beb63499c07ab7
[]
no_license
derrick0714/infer
e5d717a878ff51fef6c9b55c444c2448d85f5477
7fabf5bfc34302eab2a6d2867cb4c22a6401ca73
refs/heads/master
2016-09-06T10:37:16.794445
2014-02-12T00:09:34
2014-02-12T00:09:34
7,787,601
5
1
null
null
null
null
UTF-8
C++
false
false
3,142
hpp
#ifndef INFER_INCLUDE_ENUMERATEDFILEREADER_HPP_ #define INFER_INCLUDE_ENUMERATEDFILEREADER_HPP_ #include "DataTypeTraits.hpp" #include "ErrorStatus.hpp" template <typename ReaderType, typename ReadEnumeratorType> class EnumeratedFileReader { public: typedef reader_type_tag category; typedef typename ReaderType::value_type value_type; /// \brief Constructor EnumeratedFileReader(); ErrorStatus init(boost::shared_ptr <ReadEnumeratorType> enumerator); /// \brief Destructor ~EnumeratedFileReader(); /// \brief Read an object /// \param obj the object to read /// \returns true if the object was read successfully, false otherwise. /// \note a return value of false does not indicate an error on it's own. /// Cast to bool to check for error. False here could just mean there's /// nothing left to read. ErrorStatus read(value_type &obj) { return _read(obj, typename ReaderType::category()); } private: /// \brief Read from a file reader /// \param obj the ob ErrorStatus _read(value_type &obj, file_reader_type_tag); /// \brief The currently opened file reader boost::shared_ptr <ReaderType> _reader; /// \brief The read enumerator to use for determining file names boost::shared_ptr <ReadEnumeratorType> _enumerator; /// \brief An itrator over the files to read from typename ReadEnumeratorType::iterator _file; }; template <typename ReaderType, typename ReadEnumeratorType> EnumeratedFileReader<ReaderType, ReadEnumeratorType>:: EnumeratedFileReader() :_reader(new ReaderType), // shared_ptr deletes this when it loses scope _enumerator(), _file() { } template <typename ReaderType, typename ReadEnumeratorType> ErrorStatus EnumeratedFileReader<ReaderType, ReadEnumeratorType>:: init(boost::shared_ptr <ReadEnumeratorType> enumerator) { _enumerator = enumerator; _file = _enumerator->begin(); if (_file == _enumerator -> end()) { return E_EOF; } return _reader -> open(*_file); } template <typename ReaderType, typename ReadEnumeratorType> EnumeratedFileReader<ReaderType, ReadEnumeratorType>:: ~EnumeratedFileReader() { if (_reader -> isOpen()) { // why would anyone be done with an EnumratedFileReader if they're not // done reading from it? Just in case... _reader -> close(); } } template <typename ReaderType, typename ReadEnumeratorType> ErrorStatus EnumeratedFileReader<ReaderType, ReadEnumeratorType>:: _read(value_type &obj, file_reader_type_tag) { static ErrorStatus errorStatus; // is the reader open? if (!_reader -> isOpen()) { return E_NOTOPEN; } // call read() errorStatus = _reader -> read(obj); // does _reader have an error? if (errorStatus != E_EOF) { return errorStatus; } // _reader has nothing left to read. close it. if ((errorStatus = _reader->close()) != E_SUCCESS) { return errorStatus; } // time to get the next file ++_file; if (_file == _enumerator -> end()) { // no more files. we're done here return E_EOF; } // open the next file if ((errorStatus = _reader -> open(*_file)) != E_SUCCESS) { return errorStatus; } // let's try that again return _read(obj, typename ReaderType::category()); } #endif
[ "derrick0714@gmail.com" ]
derrick0714@gmail.com
bca2a914749518bd2a68d6af6209e7bb25c8c37f
5286798f369775a6607636a7c97c87d2a4380967
/thirdparty/cgal/CGAL-5.1/include/CGAL/Nef_2/Bounding_box_2.h
1de0bf8f42674dc40f331f92b6a474a90f06e5d8
[ "GPL-3.0-only", "LGPL-2.1-or-later", "LicenseRef-scancode-proprietary-license", "GPL-1.0-or-later", "LGPL-2.0-or-later", "MIT", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference", "MIT-0", "LGPL-3.0-only", "LGPL-3.0-or-later" ]
permissive
MelvinG24/dust3d
d03e9091c1368985302bd69e00f59fa031297037
c4936fd900a9a48220ebb811dfeaea0effbae3ee
refs/heads/master
2023-08-24T20:33:06.967388
2021-08-10T10:44:24
2021-08-10T10:44:24
293,045,595
0
0
MIT
2020-09-05T09:38:30
2020-09-05T09:38:29
null
UTF-8
C++
false
false
3,305
h
// Copyright (c) 1997-2000 Max-Planck-Institute Saarbruecken (Germany). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // // $URL: https://github.com/CGAL/cgal/blob/v5.1/Nef_2/include/CGAL/Nef_2/Bounding_box_2.h $ // $Id: Bounding_box_2.h 0779373 2020-03-26T13:31:46+01:00 Sébastien Loriot // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial // // // Author(s) : Peter Hachenberger <hachenberger@mpi-sb.mpg.de> #ifndef CGAL_BOUNDING_BOX_D_H #define CGAL_BOUNDING_BOX_D_H #include <CGAL/license/Nef_2.h> #include<CGAL/Box_intersection_d/Box_d.h> namespace CGAL { // template<typename T, typename K> class Bounding_box_2; template<class T,typename Kernel> class Bounding_box_2 { typedef typename Kernel::Point_2 Point; typedef typename Kernel::Standard_point_2 SPoint; typedef typename Kernel::Standard_direction_2 SDirection; public: template<typename Vertex_iterator> Bounding_box_2(Vertex_iterator , Vertex_iterator ) { CGAL_error_msg( "dummy interface"); } Point intersection_ray_bbox(const SPoint& , const SDirection& ) { CGAL_error_msg( "dummy interface"); return Point(); } }; template<typename Kernel> class Bounding_box_2<Tag_false,Kernel> : Box_intersection_d::Box_d<typename Kernel::Standard_FT,2> { typedef typename Kernel::Standard_FT SFT; typedef typename Kernel::Standard_RT SRT; typedef typename Box_intersection_d::Box_d<SFT,2> Box; typedef typename Kernel::Point_2 Point; typedef typename Kernel::Standard_point_2 SPoint; typedef typename Kernel::Standard_direction_2 SDirection; // typedef typename Kernel::Direction_2 Direction; typedef typename Kernel::Standard_line_2 SLine; template<typename Vertex_handle> static SFT* vertex2point(Vertex_handle v, SFT p[2]) { p[0] = v->point()[0]; p[1] = v->point()[1]; return p; } public: using Box::extend; using Box::min_coord; using Box::max_coord; template<typename Vertex_iterator> Bounding_box_2(Vertex_iterator begin, Vertex_iterator end) { SFT p[2]; vertex2point(begin,p); *((Box*) this) = Box(p,p); // (Box) *this = Box(p,p); for(++begin;begin != end; ++begin) extend(vertex2point(begin,p)); } Point intersection_ray_bbox(const SPoint& p, const SDirection& d) { int dim = d.delta(0) == 0 ? 1 : 0; CGAL_assertion(d.delta(dim) != 0); SPoint minmax; if(dim == 0) minmax = d.delta(dim) < 0 ? SPoint(this->min_coord(0).numerator(),SRT(0),this->min_coord(0).denominator()) : SPoint(this->max_coord(0).numerator(),SRT(0),this->max_coord(0).denominator()); else minmax = d.delta(dim) < 0 ? SPoint(SRT(0),this->min_coord(0).numerator(),this->min_coord(0).denominator()) : SPoint(SRT(0),this->max_coord(0).numerator(),this->max_coord(0).denominator()); SLine l1(p,d); SLine l2 = dim == 0 ? SLine(minmax, SDirection(0,1)) : SLine(minmax, SDirection(1,0)); Object o = intersection(l1,l2); if(assign(minmax,o)) { Kernel K; return K.construct_point(minmax); } CGAL_error_msg( "code not robust - l2 must be constructed to" " be non-collinear with l1"); return Point(); } }; } //namespace CGAL #endif // CGAL_BOUNDING_BOX_D_H
[ "huxingyi@msn.com" ]
huxingyi@msn.com
88ad858b6b7622144c49fb3b242013cace1a774a
0142093a25d0f9eff75d071a150d03875bb6003c
/week1/徐睿康/找出元音字符.cpp
4e3b2a7723bc1bfbf15de4e5a7e06dae6aa9f151
[]
no_license
zzcym/NEUQ-ACM-Solution
616971279a77d373ac1b276419f88aea9bae847c
6725c8dbf6f3a342064d4d645a6166eb7f9bbb42
refs/heads/main
2023-08-31T10:21:38.829611
2021-10-25T15:49:22
2021-10-25T15:49:22
421,091,552
1
0
null
null
null
null
UTF-8
C++
false
false
203
cpp
using namespace std; int a[100010],n,m,x,y,flag; string s[100010]; char c; int main(){ cin>>n; for(int i=1;i<=n;i++){ cin>>c; if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u') cout<<c; } }
[ "noreply@github.com" ]
noreply@github.com
d60bad33d905566429b558e2c0102c336baf91a8
591b05d3812c9422c1033afad9f71bb2407bb7f2
/Game/Game/EnemyPlayer.h
198d3a5e25b4920ef117dcca1acfebdb89d9003e
[]
no_license
PavelMarishev/Tanks
63c7bcbb36f92522116f5df018ef8d50c60dbbcc
90e25ea4fe535140c1ad5b3dfbd0a9732a161090
refs/heads/master
2021-01-13T14:46:22.690441
2016-12-15T18:59:49
2016-12-15T18:59:49
76,584,791
0
0
null
null
null
null
UTF-8
C++
false
false
1,235
h
#pragma once #include "MovingObject.h" #include "bullet.h" #include <SFML\Graphics.hpp> using namespace sf; class EnemyPlayer :public MovingObject { private: Texture dead; Sprite s_dead; bullet eBullet; bool bulleton = false; Clock clock; int where = 0; public: EnemyPlayer(String p, int x, int y) :MovingObject(p, x, y) { } void enemyAnalizer(){ if (alive){ if (Keyboard::isKeyPressed(Keyboard::Y)) alive = false; // press Y to kill if (clock.getElapsedTime().asMilliseconds() >= 500){ where = rand() % 6; clock.restart(); } switch (where){ case 1: moveTo('l'); break; case 2: moveTo('r'); break; case 3: moveTo('u'); break; case 4: moveTo('d'); break; case 5: bulleton = true; bullet bul(getRot(), getSprite().getPosition()); eBullet = bul; eBullet.setSprite('b'); break; } if (bulleton){ if (!eBullet.getLife()) bulleton = false; eBullet.go(); } } else{ dead.loadFromFile("images/tanks/deadblue00.png"); s_dead.setTexture(dead); s_dead.setTextureRect(IntRect(75, 80, 90, 90)); setSprite(s_dead); } } bool getBulleton(){ return bulleton; } bullet getBullet(){ return eBullet; } };
[ "karthusss@ya.ru" ]
karthusss@ya.ru
57135e57b1f1925242e99b8d7eef3862218f196e
b0b0b7ad6b0984594686dffd81be69199a3a71bb
/Charts/TRChartsObjc/TRChartsObjc/Support/DateFormatterInterfaceMarshaller.hh
e26f1e42ed942482ee423834a42e455de3f285f3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
thesurix/TRCharts
582ddf4de95b4b963cf164d771cddccf3b7f1c09
24f2dbc1bbd234e7bb8aa802578a3a5ff72eb7a2
refs/heads/master
2020-04-17T00:54:06.566075
2019-01-20T13:38:43
2019-01-20T13:38:43
166,066,992
0
0
null
2019-01-16T15:51:16
2019-01-16T15:51:15
null
UTF-8
C++
false
false
1,575
hh
/******************************************************************************* * Copyright 2015 Thomson Reuters * * 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. *******************************************************************************/ /* NOTE: This file is autogenerated, do not edit this file directly.*/ #import <TRCodegenSupportObjc/Marshaller.hh> #import <TRChartsObjc/DateFormatter.h> #import <TRCharts/DateFormatter.hpp> namespace TRChartsObjc { class DateFormatterInterfaceMarshaller : public CodegenSupportObjc::Marshaller<std::shared_ptr<Charts::DateFormatter>, id> { public: virtual std::shared_ptr<Charts::DateFormatter> marshall(const CodegenSupportObjc::StrongAnyPtr & in) const; virtual CodegenSupportObjc::StrongAnyPtr unmarshall(const std::shared_ptr<Charts::DateFormatter> & in) const; virtual std::shared_ptr<Charts::DateFormatter> marshallBoxed(const id & in) const; virtual id unmarshallBoxed(const std::shared_ptr<Charts::DateFormatter> & in) const; virtual void init(void) const; private: class Proxy; }; }
[ "francisco.estevezgarcia@thomsonreuters.com" ]
francisco.estevezgarcia@thomsonreuters.com
2ba9377e59ebdd89cab1f260943d645da2a72e9d
f52bf7316736f9fb00cff50528e951e0df89fe64
/Platform/vendor/samsung/common/packages/apps/SBrowser/src/content/browser/browser_plugin/browser_plugin_host_browsertest.cc
26b783c135baecdb2f894614040fb0cb9c7de82b
[ "BSD-3-Clause" ]
permissive
git2u/sm-t530_KK_Opensource
bcc789ea3c855e3c1e7471fc99a11fd460b9d311
925e57f1f612b31ea34c70f87bc523e7a7d53c05
refs/heads/master
2021-01-19T21:32:06.678681
2014-11-21T23:09:45
2014-11-21T23:09:45
48,746,810
0
1
null
2015-12-29T12:35:13
2015-12-29T12:35:13
null
UTF-8
C++
false
false
58,698
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/memory/singleton.h" #include "base/run_loop.h" #include "base/string_util.h" #include "base/strings/string_split.h" #include "base/test/test_timeouts.h" #include "base/utf_string_conversions.h" #include "content/browser/browser_plugin/browser_plugin_guest.h" #include "content/browser/browser_plugin/browser_plugin_host_factory.h" #include "content/browser/browser_plugin/test_browser_plugin_embedder.h" #include "content/browser/browser_plugin/test_browser_plugin_guest.h" #include "content/browser/browser_plugin/test_browser_plugin_guest_manager.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/view_messages.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_view_host_observer.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "content/shell/shell.h" #include "content/test/content_browser_test.h" #include "content/test/content_browser_test_utils.h" #include "net/base/net_util.h" #include "net/test/spawned_test_server.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" #include "webkit/glue/webdropdata.h" using WebKit::WebInputEvent; using WebKit::WebMouseEvent; using content::BrowserPluginEmbedder; using content::BrowserPluginGuest; using content::BrowserPluginHostFactory; using content::WebContentsImpl; namespace { const char kHTMLForGuest[] = "data:text/html,<html><body>hello world</body></html>"; const char kHTMLForGuestBusyLoop[] = "data:text/html,<html><head><script type=\"text/javascript\">" "function PauseMs(timems) {" " document.title = \"start\";" " var date = new Date();" " var currDate = null;" " do {" " currDate = new Date();" " } while (currDate - date < timems)" "}" "function StartPauseMs(timems) {" " setTimeout(function() { PauseMs(timems); }, 0);" "}" "</script></head><body></body></html>"; const char kHTMLForGuestTouchHandler[] = "data:text/html,<html><body><div id=\"touch\">With touch</div></body>" "<script type=\"text/javascript\">" "function handler() {}" "function InstallTouchHandler() { " " document.getElementById(\"touch\").addEventListener(\"touchstart\", " " handler);" "}" "function UninstallTouchHandler() { " " document.getElementById(\"touch\").removeEventListener(\"touchstart\", " " handler);" "}" "</script></html>"; const char kHTMLForGuestWithTitle[] = "data:text/html," "<html><head><title>%s</title></head>" "<body>hello world</body>" "</html>"; const char kHTMLForGuestAcceptDrag[] = "data:text/html,<html><body>" "<script>" "function dropped() {" " document.title = \"DROPPED\";" "}" "</script>" "<textarea id=\"text\" style=\"width:100%; height: 100%\"" " ondrop=\"dropped();\">" "</textarea>" "</body></html>"; const char kHTMLForGuestWithSize[] = "data:text/html," "<html>" "<body style=\"margin: 0px;\">" "<img style=\"width: 100%; height: 400px;\"/>" "</body>" "</html>"; std::string GetHTMLForGuestWithTitle(const std::string& title) { return base::StringPrintf(kHTMLForGuestWithTitle, title.c_str()); } } // namespace namespace content { // Test factory for creating test instances of BrowserPluginEmbedder and // BrowserPluginGuest. class TestBrowserPluginHostFactory : public BrowserPluginHostFactory { public: virtual BrowserPluginGuestManager* CreateBrowserPluginGuestManager() OVERRIDE { guest_manager_instance_count_++; if (message_loop_runner_) message_loop_runner_->Quit(); return new TestBrowserPluginGuestManager(); } virtual BrowserPluginGuest* CreateBrowserPluginGuest( int instance_id, WebContentsImpl* web_contents) OVERRIDE { return new TestBrowserPluginGuest(instance_id, web_contents); } // Also keeps track of number of instances created. virtual BrowserPluginEmbedder* CreateBrowserPluginEmbedder( WebContentsImpl* web_contents) OVERRIDE { return new TestBrowserPluginEmbedder(web_contents); } // Singleton getter. static TestBrowserPluginHostFactory* GetInstance() { return Singleton<TestBrowserPluginHostFactory>::get(); } // Waits for at least one embedder to be created in the test. Returns true if // we have a guest, false if waiting times out. void WaitForGuestManagerCreation() { // Check if already have created an instance. if (guest_manager_instance_count_ > 0) return; // Wait otherwise. message_loop_runner_ = new MessageLoopRunner(); message_loop_runner_->Run(); } protected: TestBrowserPluginHostFactory() : guest_manager_instance_count_(0) {} virtual ~TestBrowserPluginHostFactory() {} private: // For Singleton. friend struct DefaultSingletonTraits<TestBrowserPluginHostFactory>; scoped_refptr<MessageLoopRunner> message_loop_runner_; int guest_manager_instance_count_; DISALLOW_COPY_AND_ASSIGN(TestBrowserPluginHostFactory); }; // Test factory class for browser plugin that creates guests with short hang // timeout. class TestShortHangTimeoutGuestFactory : public TestBrowserPluginHostFactory { public: virtual BrowserPluginGuest* CreateBrowserPluginGuest( int instance_id, WebContentsImpl* web_contents) OVERRIDE { BrowserPluginGuest* guest = new TestBrowserPluginGuest(instance_id, web_contents); guest->set_guest_hang_timeout_for_testing(TestTimeouts::tiny_timeout()); return guest; } // Singleton getter. static TestShortHangTimeoutGuestFactory* GetInstance() { return Singleton<TestShortHangTimeoutGuestFactory>::get(); } protected: TestShortHangTimeoutGuestFactory() {} virtual ~TestShortHangTimeoutGuestFactory() {} private: // For Singleton. friend struct DefaultSingletonTraits<TestShortHangTimeoutGuestFactory>; DISALLOW_COPY_AND_ASSIGN(TestShortHangTimeoutGuestFactory); }; // A transparent observer that can be used to verify that a RenderViewHost // received a specific message. class RenderViewHostMessageObserver : public RenderViewHostObserver { public: RenderViewHostMessageObserver(RenderViewHost* host, uint32 message_id) : RenderViewHostObserver(host), message_id_(message_id), message_received_(false) { } virtual ~RenderViewHostMessageObserver() {} void WaitUntilMessageReceived() { if (message_received_) return; message_loop_runner_ = new MessageLoopRunner(); message_loop_runner_->Run(); } void ResetState() { message_received_ = false; } // IPC::Listener implementation. virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE { if (message.type() == message_id_) { message_received_ = true; if (message_loop_runner_) message_loop_runner_->Quit(); } return false; } private: scoped_refptr<MessageLoopRunner> message_loop_runner_; uint32 message_id_; bool message_received_; DISALLOW_COPY_AND_ASSIGN(RenderViewHostMessageObserver); }; class BrowserPluginHostTest : public ContentBrowserTest { public: BrowserPluginHostTest() : test_embedder_(NULL), test_guest_(NULL), test_guest_manager_(NULL) {} virtual void SetUp() OVERRIDE { // Override factory to create tests instances of BrowserPlugin*. content::BrowserPluginEmbedder::set_factory_for_testing( TestBrowserPluginHostFactory::GetInstance()); content::BrowserPluginGuest::set_factory_for_testing( TestBrowserPluginHostFactory::GetInstance()); content::BrowserPluginGuestManager::set_factory_for_testing( TestBrowserPluginHostFactory::GetInstance()); ContentBrowserTest::SetUp(); } virtual void TearDown() OVERRIDE { content::BrowserPluginEmbedder::set_factory_for_testing(NULL); content::BrowserPluginGuest::set_factory_for_testing(NULL); ContentBrowserTest::TearDown(); } virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { // Enable browser plugin in content_shell for running test. command_line->AppendSwitch(switches::kEnableBrowserPluginForAllViewTypes); } static void SimulateSpaceKeyPress(WebContents* web_contents) { SimulateKeyPress(web_contents, ui::VKEY_SPACE, false, // control. false, // shift. false, // alt. false); // command. } static void SimulateTabKeyPress(WebContents* web_contents) { SimulateKeyPress(web_contents, ui::VKEY_TAB, false, // control. false, // shift. false, // alt. false); // command. } // Executes the javascript synchronously and makes sure the returned value is // freed properly. void ExecuteSyncJSFunction(RenderViewHost* rvh, const std::string& jscript) { scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(rvh, jscript); } bool IsAttributeNull(RenderViewHost* rvh, const std::string& attribute) { scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(rvh, "document.getElementById('plugin').getAttribute('" + attribute + "');"); return value->GetType() == Value::TYPE_NULL; } // Removes all attributes in the comma-delimited string |attributes|. void RemoveAttributes(RenderViewHost* rvh, const std::string& attributes) { std::vector<std::string> attributes_list; base::SplitString(attributes, ',', &attributes_list); std::vector<std::string>::const_iterator itr; for (itr = attributes_list.begin(); itr != attributes_list.end(); ++itr) { ExecuteSyncJSFunction(rvh, "document.getElementById('plugin')" "." + *itr + " = null;"); } } // This helper method does the following: // 1. Start the test server and navigate the shell to |embedder_url|. // 2. Execute custom pre-navigation |embedder_code| if provided. // 3. Navigate the guest to the |guest_url|. // 4. Verify that the guest has been created and has completed loading. void StartBrowserPluginTest(const std::string& embedder_url, const std::string& guest_url, bool is_guest_data_url, const std::string& embedder_code) { ASSERT_TRUE(test_server()->Start()); GURL test_url(test_server()->GetURL(embedder_url)); NavigateToURL(shell(), test_url); WebContentsImpl* embedder_web_contents = static_cast<WebContentsImpl*>( shell()->web_contents()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( embedder_web_contents->GetRenderViewHost()); // Focus the embedder. rvh->Focus(); // Allow the test to do some operations on the embedder before we perform // the first navigation of the guest. if (!embedder_code.empty()) ExecuteSyncJSFunction(rvh, embedder_code); if (!is_guest_data_url) { test_url = test_server()->GetURL(guest_url); ExecuteSyncJSFunction( rvh, base::StringPrintf("SetSrc('%s');", test_url.spec().c_str())); } else { ExecuteSyncJSFunction( rvh, base::StringPrintf("SetSrc('%s');", guest_url.c_str())); } // Wait to make sure embedder is created/attached to WebContents. TestBrowserPluginHostFactory::GetInstance()->WaitForGuestManagerCreation(); test_embedder_ = static_cast<TestBrowserPluginEmbedder*>( embedder_web_contents->GetBrowserPluginEmbedder()); ASSERT_TRUE(test_embedder_); test_guest_manager_ = static_cast<TestBrowserPluginGuestManager*>( embedder_web_contents->GetBrowserPluginGuestManager()); ASSERT_TRUE(test_guest_manager_); test_guest_manager_->WaitForGuestAdded(); // Verify that we have exactly one guest. const TestBrowserPluginGuestManager::GuestInstanceMap& instance_map = test_guest_manager_->guest_web_contents_for_testing(); EXPECT_EQ(1u, instance_map.size()); WebContentsImpl* test_guest_web_contents = static_cast<WebContentsImpl*>( instance_map.begin()->second); test_guest_ = static_cast<TestBrowserPluginGuest*>( test_guest_web_contents->GetBrowserPluginGuest()); test_guest_->WaitForLoadStop(); } TestBrowserPluginEmbedder* test_embedder() const { return test_embedder_; } TestBrowserPluginGuest* test_guest() const { return test_guest_; } TestBrowserPluginGuestManager* test_guest_manager() const { return test_guest_manager_; } private: TestBrowserPluginEmbedder* test_embedder_; TestBrowserPluginGuest* test_guest_; TestBrowserPluginGuestManager* test_guest_manager_; DISALLOW_COPY_AND_ASSIGN(BrowserPluginHostTest); }; // This test loads a guest that has a busy loop, and therefore it hangs the // guest. // // Disabled on Windows and Linux since it is flaky. crbug.com/164812 // THIS TEST IS ALWAYS FLAKY. DO NOT ENABLE AGAIN WITHOUT REWRITING. #if defined(OS_WIN) || defined(OS_LINUX) #define MAYBE_GuestUnresponsive DISABLED_GuestUnresponsive #else #define MAYBE_GuestUnresponsive GuestUnresponsive #endif IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, MAYBE_GuestUnresponsive) { // Override the hang timeout for guest to be very small. content::BrowserPluginGuest::set_factory_for_testing( TestShortHangTimeoutGuestFactory::GetInstance()); const char kEmbedderURL[] = "files/browser_plugin_embedder_guest_unresponsive.html"; StartBrowserPluginTest( kEmbedderURL, kHTMLForGuestBusyLoop, true, std::string()); // Wait until the busy loop starts. { const string16 expected_title = ASCIIToUTF16("start"); content::TitleWatcher title_watcher(test_guest()->web_contents(), expected_title); // Hang the guest for a length of time. int spin_time = 10 * TestTimeouts::tiny_timeout().InMilliseconds(); ExecuteSyncJSFunction( test_guest()->web_contents()->GetRenderViewHost(), base::StringPrintf("StartPauseMs(%d);", spin_time).c_str()); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } { const string16 expected_title = ASCIIToUTF16("done"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); // Send a mouse event to the guest. SimulateMouseClick(test_embedder()->web_contents(), 0, WebKit::WebMouseEvent::ButtonLeft); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } // Verify that the embedder has received the 'unresponsive' and 'responsive' // events. RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(rvh, "unresponsiveCalled"); bool result = false; ASSERT_TRUE(value->GetAsBoolean(&result)); EXPECT_TRUE(result); value = content::ExecuteScriptAndGetValue(rvh, "responsiveCalled"); result = false; ASSERT_TRUE(value->GetAsBoolean(&result)); EXPECT_TRUE(result); } // This test ensures that if guest isn't there and we resize the guest (from // js), it remembers the size correctly. // // Initially we load an embedder with a guest without a src attribute (which has // dimension 640x480), resize it to 100x200, and then we set the source to a // sample guest. In the end we verify that the correct size has been set. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, NavigateAfterResize) { const gfx::Size nxt_size = gfx::Size(100, 200); const std::string embedder_code = base::StringPrintf( "SetSize(%d, %d);", nxt_size.width(), nxt_size.height()); const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, kHTMLForGuest, true, embedder_code); // Wait for the guest to receive a damage buffer of size 100x200. // This means the guest will be painted properly at that size. test_guest()->WaitForDamageBufferWithSize(nxt_size); } IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, AdvanceFocus) { const char kEmbedderURL[] = "files/browser_plugin_focus.html"; const char* kGuestURL = "files/browser_plugin_focus_child.html"; StartBrowserPluginTest(kEmbedderURL, kGuestURL, false, std::string()); SimulateMouseClick(test_embedder()->web_contents(), 0, WebKit::WebMouseEvent::ButtonLeft); BrowserPluginHostTest::SimulateTabKeyPress(test_embedder()->web_contents()); // Wait until we focus into the guest. test_guest()->WaitForFocus(); // TODO(fsamuel): A third Tab key press should not be necessary. // The browser plugin will take keyboard focus but it will not // focus an initial element. The initial element is dependent // upon tab direction which WebKit does not propagate to the plugin. // See http://crbug.com/147644. BrowserPluginHostTest::SimulateTabKeyPress(test_embedder()->web_contents()); BrowserPluginHostTest::SimulateTabKeyPress(test_embedder()->web_contents()); BrowserPluginHostTest::SimulateTabKeyPress(test_embedder()->web_contents()); test_guest()->WaitForAdvanceFocus(); } // This test opens a page in http and then opens another page in https, forcing // a RenderViewHost swap in the web_contents. We verify that the embedder in the // web_contents gets cleared properly. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, EmbedderChangedAfterSwap) { net::SpawnedTestServer https_server( net::SpawnedTestServer::TYPE_HTTPS, net::SpawnedTestServer::kLocalhost, base::FilePath(FILE_PATH_LITERAL("content/test/data"))); ASSERT_TRUE(https_server.Start()); // 1. Load an embedder page with one guest in it. const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, kHTMLForGuest, true, std::string()); // 2. Navigate to a URL in https, so we trigger a RenderViewHost swap. GURL test_https_url(https_server.GetURL( "files/browser_plugin_title_change.html")); content::WindowedNotificationObserver swap_observer( content::NOTIFICATION_WEB_CONTENTS_SWAPPED, content::Source<WebContents>(test_embedder()->web_contents())); NavigateToURL(shell(), test_https_url); swap_observer.Wait(); TestBrowserPluginEmbedder* test_embedder_after_swap = static_cast<TestBrowserPluginEmbedder*>( static_cast<WebContentsImpl*>(shell()->web_contents())-> GetBrowserPluginEmbedder()); // Verify we have a no embedder in web_contents (since the new page doesn't // have any browser plugin). ASSERT_TRUE(!test_embedder_after_swap); ASSERT_NE(test_embedder(), test_embedder_after_swap); } // This test opens two pages in http and there is no RenderViewHost swap, // therefore the embedder created on first page navigation stays the same in // web_contents. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, EmbedderSameAfterNav) { const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, kHTMLForGuest, true, std::string()); WebContentsImpl* embedder_web_contents = test_embedder()->web_contents(); // Navigate to another page in same host and port, so RenderViewHost swap // does not happen and existing embedder doesn't change in web_contents. GURL test_url_new(test_server()->GetURL( "files/browser_plugin_title_change.html")); const string16 expected_title = ASCIIToUTF16("done"); content::TitleWatcher title_watcher(shell()->web_contents(), expected_title); NavigateToURL(shell(), test_url_new); LOG(INFO) << "Start waiting for title"; string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); LOG(INFO) << "Done navigating to second page"; TestBrowserPluginEmbedder* test_embedder_after_nav = static_cast<TestBrowserPluginEmbedder*>( embedder_web_contents->GetBrowserPluginEmbedder()); // Embedder must not change in web_contents. ASSERT_EQ(test_embedder_after_nav, test_embedder()); } // This test verifies that hiding the embedder also hides the guest. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, BrowserPluginVisibilityChanged) { const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, kHTMLForGuest, true, std::string()); // Hide the Browser Plugin. RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); ExecuteSyncJSFunction( rvh, "document.getElementById('plugin').style.visibility = 'hidden'"); // Make sure that the guest is hidden. test_guest()->WaitUntilHidden(); } IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, EmbedderVisibilityChanged) { const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, kHTMLForGuest, true, std::string()); // Hide the embedder. test_embedder()->web_contents()->WasHidden(); // Make sure that hiding the embedder also hides the guest. test_guest()->WaitUntilHidden(); } // This test verifies that calling the reload method reloads the guest. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, ReloadGuest) { const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, kHTMLForGuest, true, std::string()); test_guest()->ResetUpdateRectCount(); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); ExecuteSyncJSFunction(rvh, "document.getElementById('plugin').reload()"); test_guest()->WaitForReload(); } // This test verifies that calling the stop method forwards the stop request // to the guest's WebContents. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, StopGuest) { const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, kHTMLForGuest, true, std::string()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); ExecuteSyncJSFunction(rvh, "document.getElementById('plugin').stop()"); test_guest()->WaitForStop(); } // Verifies that installing/uninstalling touch-event handlers in the guest // plugin correctly updates the touch-event handling state in the embedder. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, AcceptTouchEvents) { const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; StartBrowserPluginTest( kEmbedderURL, kHTMLForGuestTouchHandler, true, std::string()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); // The embedder should not have any touch event handlers at this point. EXPECT_FALSE(rvh->has_touch_handler()); // Install the touch handler in the guest. This should cause the embedder to // start listening for touch events too. RenderViewHostMessageObserver observer(rvh, ViewHostMsg_HasTouchEventHandlers::ID); ExecuteSyncJSFunction(test_guest()->web_contents()->GetRenderViewHost(), "InstallTouchHandler();"); observer.WaitUntilMessageReceived(); EXPECT_TRUE(rvh->has_touch_handler()); // Uninstalling the touch-handler in guest should cause the embedder to stop // listening for touch events. observer.ResetState(); ExecuteSyncJSFunction(test_guest()->web_contents()->GetRenderViewHost(), "UninstallTouchHandler();"); observer.WaitUntilMessageReceived(); EXPECT_FALSE(rvh->has_touch_handler()); } IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, Renavigate) { const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; StartBrowserPluginTest( kEmbedderURL, GetHTMLForGuestWithTitle("P1"), true, std::string()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); // Navigate to P2 and verify that the navigation occurred. { const string16 expected_title = ASCIIToUTF16("P2"); content::TitleWatcher title_watcher(test_guest()->web_contents(), expected_title); ExecuteSyncJSFunction( rvh, base::StringPrintf( "SetSrc('%s');", GetHTMLForGuestWithTitle("P2").c_str())); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } // Navigate to P3 and verify that the navigation occurred. { const string16 expected_title = ASCIIToUTF16("P3"); content::TitleWatcher title_watcher(test_guest()->web_contents(), expected_title); ExecuteSyncJSFunction( rvh, base::StringPrintf( "SetSrc('%s');", GetHTMLForGuestWithTitle("P3").c_str())); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } // Go back and verify that we're back at P2. { const string16 expected_title = ASCIIToUTF16("P2"); content::TitleWatcher title_watcher(test_guest()->web_contents(), expected_title); ExecuteSyncJSFunction(rvh, "Back();"); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(rvh, "CanGoBack()"); bool result = false; ASSERT_TRUE(value->GetAsBoolean(&result)); EXPECT_TRUE(result); value = content::ExecuteScriptAndGetValue(rvh, "CanGoForward()"); result = false; ASSERT_TRUE(value->GetAsBoolean(&result)); EXPECT_TRUE(result); } // Go forward and verify that we're back at P3. { const string16 expected_title = ASCIIToUTF16("P3"); content::TitleWatcher title_watcher(test_guest()->web_contents(), expected_title); ExecuteSyncJSFunction(rvh, "Forward();"); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(rvh, "CanGoForward()"); bool result = true; ASSERT_TRUE(value->GetAsBoolean(&result)); EXPECT_FALSE(result); } // Go back two entries and verify that we're back at P1. { const string16 expected_title = ASCIIToUTF16("P1"); content::TitleWatcher title_watcher(test_guest()->web_contents(), expected_title); ExecuteSyncJSFunction(rvh, "Go(-2);"); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(rvh, "CanGoBack()"); bool result = true; ASSERT_TRUE(value->GetAsBoolean(&result)); EXPECT_FALSE(result); } } // This tests verifies that reloading the embedder does not crash the browser // and that the guest is reset. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, ReloadEmbedder) { const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, kHTMLForGuest, true, std::string()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); // Change the title of the page to 'modified' so that we know that // the page has successfully reloaded when it goes back to 'embedder' // in the next step. { const string16 expected_title = ASCIIToUTF16("modified"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); ExecuteSyncJSFunction(rvh, base::StringPrintf("SetTitle('%s');", "modified")); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } // Reload the embedder page, and verify that the reload was successful. // Then navigate the guest to verify that the browser process does not crash. { const string16 expected_title = ASCIIToUTF16("embedder"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); test_embedder()->web_contents()->GetController().Reload(false); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); ExecuteSyncJSFunction( test_embedder()->web_contents()->GetRenderViewHost(), base::StringPrintf("SetSrc('%s');", kHTMLForGuest)); test_guest_manager()->WaitForGuestAdded(); const TestBrowserPluginGuestManager::GuestInstanceMap& instance_map = test_guest_manager()->guest_web_contents_for_testing(); WebContentsImpl* test_guest_web_contents = static_cast<WebContentsImpl*>( instance_map.begin()->second); TestBrowserPluginGuest* new_test_guest = static_cast<TestBrowserPluginGuest*>( test_guest_web_contents->GetBrowserPluginGuest()); ASSERT_TRUE(new_test_guest != NULL); // Wait for the guest to send an UpdateRectMsg, meaning it is ready. new_test_guest->WaitForUpdateRectMsg(); } } IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, TerminateGuest) { const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, kHTMLForGuest, true, std::string()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); ExecuteSyncJSFunction(rvh, "document.getElementById('plugin').terminate()"); // Expect the guest to crash. test_guest()->WaitForExit(); } // This test verifies that the guest is responsive after crashing and going back // to a previous navigation entry. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, BackAfterTerminateGuest) { const char* kEmbedderURL = "files/browser_plugin_embedder.html"; StartBrowserPluginTest( kEmbedderURL, GetHTMLForGuestWithTitle("P1"), true, std::string()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); // Navigate to P2 and verify that the navigation occurred. { const string16 expected_title = ASCIIToUTF16("P2"); content::TitleWatcher title_watcher(test_guest()->web_contents(), expected_title); ExecuteSyncJSFunction( rvh, base::StringPrintf( "SetSrc('%s');", GetHTMLForGuestWithTitle("P2").c_str())); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } // Kill the guest. ExecuteSyncJSFunction(rvh, "document.getElementById('plugin').terminate()"); // Expect the guest to report that it crashed. test_guest()->WaitForExit(); // Go back and verify that we're back at P1. { const string16 expected_title = ASCIIToUTF16("P1"); content::TitleWatcher title_watcher(test_guest()->web_contents(), expected_title); ExecuteSyncJSFunction(rvh, "Back();"); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } // Send an input event and verify that the guest receives the input. SimulateMouseClick(test_embedder()->web_contents(), 0, WebKit::WebMouseEvent::ButtonLeft); test_guest()->WaitForInput(); } IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, LoadStart) { const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, "about:blank", true, std::string()); const string16 expected_title = ASCIIToUTF16(kHTMLForGuest); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); // Renavigate the guest to |kHTMLForGuest|. RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); ExecuteSyncJSFunction(rvh, base::StringPrintf("SetSrc('%s');", kHTMLForGuest)); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, LoadAbort) { const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, "about:blank", true, std::string()); { // Navigate the guest to "close-socket". const string16 expected_title = ASCIIToUTF16("ERR_EMPTY_RESPONSE"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); GURL test_url = test_server()->GetURL("close-socket"); ExecuteSyncJSFunction( rvh, base::StringPrintf("SetSrc('%s');", test_url.spec().c_str())); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } { // Navigate the guest to an illegal chrome:// URL. const string16 expected_title = ASCIIToUTF16("ERR_INVALID_URL"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); GURL test_url("chrome://newtab"); ExecuteSyncJSFunction( rvh, base::StringPrintf("SetSrc('%s');", test_url.spec().c_str())); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } { // Navigate the guest to an illegal file:// URL. const string16 expected_title = ASCIIToUTF16("ERR_ABORTED"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); GURL test_url("file://foo"); ExecuteSyncJSFunction( rvh, base::StringPrintf("SetSrc('%s');", test_url.spec().c_str())); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } } IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, LoadRedirect) { const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, "about:blank", true, std::string()); const string16 expected_title = ASCIIToUTF16("redirected"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); // Navigate with a redirect and wait until the title changes. GURL redirect_url(test_server()->GetURL( "server-redirect?files/title1.html")); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); ExecuteSyncJSFunction( rvh, base::StringPrintf("SetSrc('%s');", redirect_url.spec().c_str())); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); // Verify that we heard a loadRedirect during the navigation. scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(rvh, "redirectOldUrl"); std::string result; EXPECT_TRUE(value->GetAsString(&result)); EXPECT_EQ(redirect_url.spec().c_str(), result); value = content::ExecuteScriptAndGetValue(rvh, "redirectNewUrl"); EXPECT_TRUE(value->GetAsString(&result)); EXPECT_EQ(test_server()->GetURL("files/title1.html").spec().c_str(), result); } // Always failing in the win7_aura try bot. See http://crbug.com/181107. #if defined(OS_WIN) && defined(USE_AURA) #define MAYBE_AcceptDragEvents DISABLED_AcceptDragEvents #else #define MAYBE_AcceptDragEvents AcceptDragEvents #endif // Tests that a drag-n-drop over the browser plugin in the embedder happens // correctly. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, MAYBE_AcceptDragEvents) { const char kEmbedderURL[] = "files/browser_plugin_dragging.html"; StartBrowserPluginTest( kEmbedderURL, kHTMLForGuestAcceptDrag, true, std::string()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); // Get a location in the embedder outside of the plugin. base::ListValue *start, *end; scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(rvh, "dragLocation()"); ASSERT_TRUE(value->GetAsList(&start) && start->GetSize() == 2); double start_x, start_y; ASSERT_TRUE(start->GetDouble(0, &start_x) && start->GetDouble(1, &start_y)); // Get a location in the embedder that falls inside the plugin. value = content::ExecuteScriptAndGetValue(rvh, "dropLocation()"); ASSERT_TRUE(value->GetAsList(&end) && end->GetSize() == 2); double end_x, end_y; ASSERT_TRUE(end->GetDouble(0, &end_x) && end->GetDouble(1, &end_y)); WebDropData drop_data; GURL url = GURL("https://www.domain.com/index.html"); drop_data.url = url; // Pretend that the URL is being dragged over the embedder. Start the drag // from outside the plugin, then move the drag inside the plugin and drop. // This should trigger appropriate messages from the embedder to the guest, // and end with a drop on the guest. The guest changes title when a drop // happens. const string16 expected_title = ASCIIToUTF16("DROPPED"); content::TitleWatcher title_watcher(test_guest()->web_contents(), expected_title); rvh->DragTargetDragEnter(drop_data, gfx::Point(start_x, start_y), gfx::Point(start_x, start_y), WebKit::WebDragOperationEvery, 0); rvh->DragTargetDragOver(gfx::Point(end_x, end_y), gfx::Point(end_x, end_y), WebKit::WebDragOperationEvery, 0); rvh->DragTargetDrop(gfx::Point(end_x, end_y), gfx::Point(end_x, end_y), 0); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } // This test verifies that round trip postMessage works as expected. // 1. The embedder posts a message 'testing123' to the guest. // 2. The guest receives and replies to the message using the event object's // source object: event.source.postMessage('foobar', '*') // 3. The embedder receives the message and uses the event's source // object to do one final reply: 'stop' // 4. The guest receives the final 'stop' message. // 5. The guest acks the 'stop' message with a 'stop_ack' message. // 6. The embedder changes its title to 'main guest' when it sees the 'stop_ack' // message. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, PostMessage) { const char* kTesting = "testing123"; const char* kEmbedderURL = "files/browser_plugin_embedder.html"; const char* kGuestURL = "files/browser_plugin_post_message_guest.html"; StartBrowserPluginTest(kEmbedderURL, kGuestURL, false, std::string()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); { const string16 expected_title = ASCIIToUTF16("main guest"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); // By the time we get here 'contentWindow' should be ready because the // guest has completed loading. ExecuteSyncJSFunction( rvh, base::StringPrintf("PostMessage('%s, false');", kTesting)); // The title will be updated to "main guest" at the last stage of the // process described above. string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } } // This is the same as BrowserPluginHostTest.PostMessage but also // posts a message to an iframe. // TODO(fsamuel): This test should replace the previous test once postMessage // iframe targeting is fixed (see http://crbug.com/153701). IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, DISABLED_PostMessageToIFrame) { const char* kTesting = "testing123"; const char* kEmbedderURL = "files/browser_plugin_embedder.html"; const char* kGuestURL = "files/browser_plugin_post_message_guest.html"; StartBrowserPluginTest(kEmbedderURL, kGuestURL, false, std::string()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); { const string16 expected_title = ASCIIToUTF16("main guest"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); ExecuteSyncJSFunction( rvh, base::StringPrintf("PostMessage('%s, false');", kTesting)); // The title will be updated to "main guest" at the last stage of the // process described above. string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } { content::TitleWatcher ready_watcher(test_embedder()->web_contents(), ASCIIToUTF16("ready")); RenderViewHostImpl* guest_rvh = static_cast<RenderViewHostImpl*>( test_guest()->web_contents()->GetRenderViewHost()); GURL test_url = test_server()->GetURL( "files/browser_plugin_post_message_guest.html"); ExecuteSyncJSFunction( guest_rvh, base::StringPrintf( "CreateChildFrame('%s');", test_url.spec().c_str())); string16 actual_title = ready_watcher.WaitAndGetTitle(); EXPECT_EQ(ASCIIToUTF16("ready"), actual_title); content::TitleWatcher iframe_watcher(test_embedder()->web_contents(), ASCIIToUTF16("iframe")); ExecuteSyncJSFunction( rvh, base::StringPrintf("PostMessage('%s', true);", kTesting)); // The title will be updated to "iframe" at the last stage of the // process described above. actual_title = iframe_watcher.WaitAndGetTitle(); EXPECT_EQ(ASCIIToUTF16("iframe"), actual_title); } } IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, LoadStop) { const char* kEmbedderURL = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, "about:blank", true, std::string()); const string16 expected_title = ASCIIToUTF16("loadStop"); content::TitleWatcher title_watcher( test_embedder()->web_contents(), expected_title); // Renavigate the guest to |kHTMLForGuest|. RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); ExecuteSyncJSFunction(rvh, base::StringPrintf("SetSrc('%s');", kHTMLForGuest)); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, LoadCommit) { const char* kEmbedderURL = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, "about:blank", true, std::string()); const string16 expected_title = ASCIIToUTF16( base::StringPrintf("loadCommit:%s", kHTMLForGuest)); content::TitleWatcher title_watcher( test_embedder()->web_contents(), expected_title); // Renavigate the guest to |kHTMLForGuest|. RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); ExecuteSyncJSFunction(rvh, base::StringPrintf("SetSrc('%s');", kHTMLForGuest)); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); scoped_ptr<base::Value> is_top_level = content::ExecuteScriptAndGetValue(rvh, "commitIsTopLevel"); bool top_level_bool = false; EXPECT_TRUE(is_top_level->GetAsBoolean(&top_level_bool)); EXPECT_EQ(true, top_level_bool); } // This test verifies that if a browser plugin is hidden before navigation, // the guest starts off hidden. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, HiddenBeforeNavigation) { const char* kEmbedderURL = "files/browser_plugin_embedder.html"; const std::string embedder_code = "document.getElementById('plugin').style.visibility = 'hidden'"; StartBrowserPluginTest( kEmbedderURL, kHTMLForGuest, true, embedder_code); EXPECT_FALSE(test_guest()->visible()); } // This test verifies that if we lose the guest, and get a new one, // the new guest will inherit the visibility state of the old guest. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, VisibilityPreservation) { const char* kEmbedderURL = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, kHTMLForGuest, true, std::string()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); // Hide the BrowserPlugin. ExecuteSyncJSFunction( rvh, "document.getElementById('plugin').style.visibility = 'hidden';"); test_guest()->WaitUntilHidden(); // Kill the current guest. ExecuteSyncJSFunction(rvh, "document.getElementById('plugin').terminate();"); test_guest()->WaitForExit(); // Get a new guest. ExecuteSyncJSFunction(rvh, "document.getElementById('plugin').reload();"); test_guest()->WaitForLoadStop(); // Verify that the guest is told to hide. test_guest()->WaitUntilHidden(); } // This test verifies that if a browser plugin is focused before navigation then // the guest starts off focused. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, FocusBeforeNavigation) { const char* kEmbedderURL = "files/browser_plugin_embedder.html"; const std::string embedder_code = "document.getElementById('plugin').focus();"; StartBrowserPluginTest( kEmbedderURL, kHTMLForGuest, true, embedder_code); RenderViewHostImpl* guest_rvh = static_cast<RenderViewHostImpl*>( test_guest()->web_contents()->GetRenderViewHost()); // Verify that the guest is focused. scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(guest_rvh, "document.hasFocus()"); bool result = false; ASSERT_TRUE(value->GetAsBoolean(&result)); EXPECT_TRUE(result); } // This test verifies that if we lose the guest, and get a new one, // the new guest will inherit the focus state of the old guest. // crbug.com/170249 IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, DISABLED_FocusPreservation) { const char* kEmbedderURL = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, kHTMLForGuest, true, std::string()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); RenderViewHostImpl* guest_rvh = static_cast<RenderViewHostImpl*>( test_guest()->web_contents()->GetRenderViewHost()); { // Focus the BrowserPlugin. This will have the effect of also focusing the // current guest. ExecuteSyncJSFunction(rvh, "document.getElementById('plugin').focus();"); // Verify that key presses go to the guest. SimulateSpaceKeyPress(test_embedder()->web_contents()); test_guest()->WaitForInput(); // Verify that the guest is focused. scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(guest_rvh, "document.hasFocus()"); bool result = false; ASSERT_TRUE(value->GetAsBoolean(&result)); EXPECT_TRUE(result); } // Kill the current guest. ExecuteSyncJSFunction(rvh, "document.getElementById('plugin').terminate();"); test_guest()->WaitForExit(); { // Get a new guest. ExecuteSyncJSFunction(rvh, "document.getElementById('plugin').reload();"); test_guest()->WaitForLoadStop(); // Verify that the guest is focused. scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(guest_rvh, "document.hasFocus()"); bool result = false; ASSERT_TRUE(value->GetAsBoolean(&result)); EXPECT_TRUE(result); } } IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, FocusTracksEmbedder) { const char* kEmbedderURL = "files/browser_plugin_embedder.html"; StartBrowserPluginTest(kEmbedderURL, kHTMLForGuest, true, std::string()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); RenderViewHostImpl* guest_rvh = static_cast<RenderViewHostImpl*>( test_guest()->web_contents()->GetRenderViewHost()); { // Focus the BrowserPlugin. This will have the effect of also focusing the // current guest. ExecuteSyncJSFunction(rvh, "document.getElementById('plugin').focus();"); // Verify that key presses go to the guest. SimulateSpaceKeyPress(test_embedder()->web_contents()); test_guest()->WaitForInput(); // Verify that the guest is focused. scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(guest_rvh, "document.hasFocus()"); bool result = false; ASSERT_TRUE(value->GetAsBoolean(&result)); EXPECT_TRUE(result); } // Blur the embedder. test_embedder()->web_contents()->GetRenderViewHost()->Blur(); test_guest()->WaitForBlur(); } // This test verifies that if a browser plugin is in autosize mode before // navigation then the guest starts auto-sized. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, AutoSizeBeforeNavigation) { const char* kEmbedderURL = "files/browser_plugin_embedder.html"; const std::string embedder_code = "document.getElementById('plugin').minwidth = 300;" "document.getElementById('plugin').minheight = 200;" "document.getElementById('plugin').maxwidth = 600;" "document.getElementById('plugin').maxheight = 400;" "document.getElementById('plugin').autosize = true;"; StartBrowserPluginTest( kEmbedderURL, kHTMLForGuestWithSize, true, embedder_code); // Verify that the guest has been auto-sized. test_guest()->WaitForViewSize(gfx::Size(300, 400)); } // This test verifies that enabling autosize resizes the guest and triggers // a 'sizechanged' event. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, AutoSizeAfterNavigation) { const char* kEmbedderURL = "files/browser_plugin_embedder.html"; StartBrowserPluginTest( kEmbedderURL, kHTMLForGuestWithSize, true, std::string()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); { const string16 expected_title = ASCIIToUTF16("AutoSize(300, 400)"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); ExecuteSyncJSFunction( rvh, "document.getElementById('plugin').minwidth = 300;" "document.getElementById('plugin').minheight = 200;" "document.getElementById('plugin').maxwidth = 600;" "document.getElementById('plugin').maxheight = 400;" "document.getElementById('plugin').autosize = true;"); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } { // Change the minwidth and verify that it causes relayout. const string16 expected_title = ASCIIToUTF16("AutoSize(350, 400)"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); ExecuteSyncJSFunction( rvh, "document.getElementById('plugin').minwidth = 350;"); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } { // Turn off autoSize and verify that the guest resizes to fit the container. ExecuteSyncJSFunction( rvh, "document.getElementById('plugin').autosize = null;"); test_guest()->WaitForViewSize(gfx::Size(640, 480)); } } // Test for regression http://crbug.com/162961. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, GetRenderViewHostAtPositionTest) { const char kEmbedderURL[] = "files/browser_plugin_embedder.html"; const std::string embedder_code = base::StringPrintf("SetSize(%d, %d);", 100, 100); StartBrowserPluginTest(kEmbedderURL, kHTMLForGuestWithSize, true, embedder_code); // Check for render view host at position (150, 150) that is outside the // bounds of our guest, so this would respond with the render view host of the // embedder. test_embedder()->WaitForRenderViewHostAtPosition(150, 150); ASSERT_EQ(test_embedder()->web_contents()->GetRenderViewHost(), test_embedder()->last_rvh_at_position_response()); } // Flaky on Win Aura Tests (1) bot. See http://crbug.com/233087. #if defined(OS_WIN) && defined(USE_AURA) #define MAYBE_ChangeWindowName DISABLED_ChangeWindowName #else #define MAYBE_ChangeWindowName ChangeWindowName #endif IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, MAYBE_ChangeWindowName) { const char kEmbedderURL[] = "files/browser_plugin_naming_embedder.html"; const char* kGuestURL = "files/browser_plugin_naming_guest.html"; StartBrowserPluginTest(kEmbedderURL, kGuestURL, false, std::string()); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); // Verify that the plugin's name is properly initialized. { scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue( rvh, "document.getElementById('plugin').name"); std::string result; EXPECT_TRUE(value->GetAsString(&result)); EXPECT_EQ("start", result); } { // Open a channel with the guest, wait until it replies, // then verify that the plugin's name has been updated. const string16 expected_title = ASCIIToUTF16("guest"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); ExecuteSyncJSFunction(rvh, "OpenCommChannel();"); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue( rvh, "document.getElementById('plugin').name"); std::string result; EXPECT_TRUE(value->GetAsString(&result)); EXPECT_EQ("guest", result); } { // Set the plugin's name and verify that the window.name of the guest // has been updated. const string16 expected_title = ASCIIToUTF16("foobar"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); ExecuteSyncJSFunction(rvh, "document.getElementById('plugin').name = 'foobar';"); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } } // This test verifies that all autosize attributes can be removed // without crashing the plugin, or throwing errors. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, RemoveAutosizeAttributes) { const char* kEmbedderURL = "files/browser_plugin_embedder.html"; const std::string embedder_code = "document.getElementById('plugin').minwidth = 300;" "document.getElementById('plugin').minheight = 200;" "document.getElementById('plugin').maxwidth = 600;" "document.getElementById('plugin').maxheight = 400;" "document.getElementById('plugin').name = 'name';" "document.getElementById('plugin').src = 'foo';" "document.getElementById('plugin').autosize = '';"; StartBrowserPluginTest( kEmbedderURL, kHTMLForGuestWithSize, true, embedder_code); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); RemoveAttributes(rvh, "maxheight, maxwidth, minheight, minwidth, autosize"); // Verify that the guest resizes to fit the container (and hasn't crashed). test_guest()->WaitForViewSize(gfx::Size(640, 480)); EXPECT_TRUE(IsAttributeNull(rvh, "maxheight")); EXPECT_TRUE(IsAttributeNull(rvh, "maxwidth")); EXPECT_TRUE(IsAttributeNull(rvh, "minheight")); EXPECT_TRUE(IsAttributeNull(rvh, "minwidth")); EXPECT_TRUE(IsAttributeNull(rvh, "autosize")); } // This test verifies that autosize works when some of the parameters are unset. IN_PROC_BROWSER_TEST_F(BrowserPluginHostTest, PartialAutosizeAttributes) { const char* kEmbedderURL = "files/browser_plugin_embedder.html"; const std::string embedder_code = "document.getElementById('plugin').minwidth = 300;" "document.getElementById('plugin').minheight = 200;" "document.getElementById('plugin').maxwidth = 700;" "document.getElementById('plugin').maxheight = 600;" "document.getElementById('plugin').autosize = '';"; StartBrowserPluginTest( kEmbedderURL, kHTMLForGuestWithSize, true, embedder_code); RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>( test_embedder()->web_contents()->GetRenderViewHost()); { // Remove an autosize attribute and verify that it causes relayout. const string16 expected_title = ASCIIToUTF16("AutoSize(640, 400)"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); RemoveAttributes(rvh, "minwidth"); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } { // Remove an autosize attribute and verify that it causes relayout. // Also tests that when minwidth > maxwidth, minwidth = maxwidth. const string16 expected_title = ASCIIToUTF16("AutoSize(700, 480)"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); RemoveAttributes(rvh, "maxheight"); ExecuteSyncJSFunction( rvh, "document.getElementById('plugin').minwidth = 800;" "document.getElementById('plugin').minheight = 800;"); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } { // Remove maxwidth and make sure the size returns to plugin size. const string16 expected_title = ASCIIToUTF16("AutoSize(640, 480)"); content::TitleWatcher title_watcher(test_embedder()->web_contents(), expected_title); RemoveAttributes(rvh, "maxwidth"); string16 actual_title = title_watcher.WaitAndGetTitle(); EXPECT_EQ(expected_title, actual_title); } } } // namespace content
[ "digixp2006@gmail.com" ]
digixp2006@gmail.com
7c7bb054544672b1af9179d3b01856e47cbe3d14
708411bb427239c8bc33bcd019d1c99c60adc572
/Duel/gen/template/Type.hpp
ae20a99e136bcc9f3ab66b0f7c1316e3f0088154
[]
no_license
TNFSH-Programming-Contest/2019NHSPC-TNFSH-Final
6386a67001696aa027b8e38b3519169ced4a9cd7
7c0677cb8193f441c3913d7b30c4b1a1ae014697
refs/heads/master
2022-09-30T17:40:15.530620
2020-01-30T13:35:51
2020-01-30T13:35:51
211,501,295
0
0
null
null
null
null
UTF-8
C++
false
false
31
hpp
struct QUERY { int l,r; };
[ "noreply@github.com" ]
noreply@github.com
4984b1e4213c43afe6590d1482c9390e4bc6aaba
39a1bd091b84a0e3a2062b5759decb76bc59ed83
/996B/996B.cpp
156df383b3eba26d6a6b89f162636c4afbe10bcb
[]
no_license
kunnapatt/Competitive
15801e1db97d56890a57d0e9417614dd8d6f7184
0107fd77d8b3a86e163632667bf729384c176f92
refs/heads/master
2022-01-06T18:37:56.391755
2019-05-19T17:09:30
2019-05-19T17:09:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
517
cpp
#include <bits/stdc++.h> using namespace std ; #define FOR(i, a, b) for(int i = a ; i < b ; i++) #define vi vector<int> #define vii vector<long> //#define long long long int main(){ int n ; while ( cin >> n ){ vi a(n+1) ; FOR(i, 0, n){ cin >> a[i] ; } for(int i = 0, j = 0 ; ; i++, j++){ if ( i == n ) i = 0 ; if ( a[i] <= j ) { cout << i+1 << endl ; break ; } } } return 0 ; }
[ "folk_qq@hotmail.com" ]
folk_qq@hotmail.com
d0595b6090c6f04b20e18e20a39a08316eed58e2
1847c33753e6d7b060c53c9b9e9653a5b2b6e686
/MIST_LFR_1st_round_interchange/MIST_LFR_1st_round_interchange.ino
3eb9ff54b4fed51faab5326249a90b220ff893bb
[]
no_license
Akash-Rayhan/RadioActive
f89b67713de6a180b4d210ff3b73ec1bba8207bb
85d15a984258bac595e0c2572ed71c4ca67b3938
refs/heads/master
2020-05-04T15:31:37.815565
2019-04-04T18:47:02
2019-04-04T18:47:02
179,244,494
1
0
null
null
null
null
UTF-8
C++
false
false
8,435
ino
/* P controll using Weighted Average */ //#include <ResponsiveAnalogRead.h> #define Kp 140 #define Kd 10 #define Ki 0 //PID error segment float prevError = 0; float error = 0; float tError = 0; float dError = 0; //Sensor segment int sensorData[7] = {0, 0, 0, 0, 0, 0, 0}; int midSensorValue[7] = {0, 0, 0, 0, 0, 0, 0}; int countSensor = 0; float sumSensor = 0; float avgSensor = 0; //Logic segment bool leftTurn = 0; bool rightTurn = 0; bool pidControl = 0; bool whiteLine = 0; bool fullBlack = 0; bool fullWhite = 0; bool lineEnd = 0; //Motor speed setup float dSpeed = 0; float leftSpeed = 0; float rightSpeed = 0; float baseSpeed = 100; float maxSpeed = 200;//2X of baseSpeed //Pin decleration #define leftMotorUp 28 #define leftMotorDown 26 #define rightMotorUp 30 #define rightMotorDown 32 #define leftMotorPWM 5 #define rightMotorPWM 6 int fLineLED = 23; int leftLED = 33; int rightLED = 35; const int sensors[7] = {A7, A6, A5, A4, A3, A2, A1}; #define irPin 34 #define rulePin 2 bool rule = 0; //0 for left, 1 for right void setup() { Serial.begin(9600); for (int i = 0; i < 7; i++) pinMode(sensors[i], INPUT); pinMode(leftMotorUp, OUTPUT); pinMode(leftMotorDown, OUTPUT); pinMode(rightMotorUp, OUTPUT); pinMode(rightMotorDown, OUTPUT); pinMode(leftMotorPWM, OUTPUT); pinMode(rightMotorPWM, OUTPUT); pinMode(rulePin, INPUT); pinMode(irPin, OUTPUT); pinMode(fLineLED, OUTPUT); pinMode(leftLED, OUTPUT); pinMode(rightLED, OUTPUT); digitalWrite(fLineLED, 1); calibrateIR(); digitalWrite(fLineLED, 0); } //This function is for calibrating the IR sensors //host: 'setup()' void calibrateIR() { int white[7] = {0, 0, 0, 0, 0, 0, 0}; int black[7] = {1023, 1023, 1023, 1023, 1023, 1023, 1023}; leftSpeed = -75; rightSpeed = 75; for (int k = 0; k < 4; k++) { leftSpeed = -leftSpeed; rightSpeed = -rightSpeed; driveMotor(); for (int j = 0; j < 32; j++) { if (k == 0 || k == 3) delay(12); else delay(25); for (int i = 0; i < 7; i++) { int a = 0, b = 0; digitalWrite(irPin, HIGH); //glow the emitter for 500 microseconds delayMicroseconds(500); a = analogRead(sensors[i]); digitalWrite(irPin, LOW); //turn off the emitter for 500 microseconds delayMicroseconds(500); b = analogRead(sensors[i]); sensorData[i] = a - b; white[i] = (sensorData[i] > white[i]) ? sensorData[i] : white[i]; black[i] = (sensorData[i] < black[i]) ? sensorData[i] : black[i]; } } } for (int i = 0; i < 7; i++) { midSensorValue[i] = (white[i] + black[i]) / 2; } } // Execution fuction void loop() { readSensor(); sensorAnalysis(); if(lineEnd == 1) findWay(); else if (pidControl == 1) setPID(); else if (leftTurn == 1) setLeft(); else if (rightTurn == 1) setRight(); //----------------------------- partition if (pidControl == 0) resetPID(); digitalWrite(fLineLED, whiteLine); digitalWrite(leftLED, leftTurn); digitalWrite(rightLED, rightTurn); driveMotor(); printData(); } //This function is for sensing the IR, SONAR & WHEEL ENCODER //host: 'loop()' void readSensor() { rule = digitalRead(rulePin); readIR(); //readSonar(); } //IR Sensing //host: 'readSensor()' void readIR() { sumSensor = 0; avgSensor = 0; countSensor = 0; for (int i = 0; i < 7; i++) { bool sensorActive = 0; digitalWrite(irPin, HIGH); //glow the emitter for 500 microseconds delayMicroseconds(500); int a = analogRead(sensors[i]); digitalWrite(irPin, LOW); //turn off the emitter for 500 microseconds delayMicroseconds(500); int b = analogRead(sensors[i]); int c = a - b; //if ((whiteLine == 0 && c > midSensorValue[i]) || (whiteLine == 1 && c < midSensorValue[i])) { //if start at White Line if ((whiteLine == 0 && c < midSensorValue[i]) || (whiteLine == 1 && c > midSensorValue[i])) { //if Start at Black Line sensorData[i] = i - 3; sensorActive = 1; } else sensorData[i] = 0; sumSensor += sensorData[i]; if (sensorActive == 1) countSensor++; } if (countSensor == 0) avgSensor = 0; else avgSensor = sumSensor / countSensor; } //This function analyzes sensor data //host: 'loop()' void sensorAnalysis() { if (countSensor == 0) {//White Surface fullWhite = 1; lineEnd = 0; if(pidControl == 1){ pidControl = 0; rightTurn = 0; leftTurn = 0; lineEnd = 1; } else if(fullBlack == 1){ fullBlack = 0; if(rightTurn == 1){ pidControl = 0; leftTurn = 0; } else if(leftTurn == 1){ pidControl = 0; rightTurn = 0; } } else{ rightTurn = 0; leftTurn = 0; if (rule == 0) rightTurn = 1; else leftTurn = 1; } } else if (countSensor == 7) {// Black Surface -> Turning Left fullBlack = 1; pidControl = 0; rightTurn = 0; leftTurn = 0; if (rule == 0) leftTurn = 1; else rightTurn = 1; } else {// Line if (rule == 0 && (sumSensor < 0 && (sensorData[0] == -3 || countSensor > 3))) { //Possible Left Way leftTurn = 1; pidControl = 0; rightTurn = 0; } else if (rule == 1 && (sumSensor > 0 && (sensorData[6] == 3 || countSensor > 3))) { //Possible Right Way rightTurn = 1; pidControl = 0; leftTurn = 0; } else if (countSensor == 0) ; else if(countSensor > 0 && (sensorData[0] == 0 || sensorData[6] == 0)){// forward line pidControl = 1; fullBlack = 0; leftTurn = 0; rightTurn = 0; } } } //This function resets the motor speeds using PID Algorithm //host: 'loop()' void resetPID() { error = 0; tError = 0; } //This function sets the motor speeds using PID Algorithm //host: 'loop()' void setPID() { prevError = error; error = avgSensor; dError = error - prevError; tError += error; dSpeed = Kp * error + Kd * dError; // + Ki * tError if (error > -1.5 && error < 1.5) baseSpeed = 150; else baseSpeed = 80; rightSpeed = baseSpeed - dSpeed; leftSpeed = baseSpeed + dSpeed; if (rightSpeed > maxSpeed) rightSpeed = maxSpeed; if (leftSpeed > maxSpeed) leftSpeed = maxSpeed; if (rightSpeed < -maxSpeed) rightSpeed = -maxSpeed; if (leftSpeed < - maxSpeed) leftSpeed = -maxSpeed; } //This 2 functions set the motor speeds to turn //host: 'loop()' void setLeft() { //90deg turn at 0.448sec leftSpeed = -100; rightSpeed = 100; } void setRight() { leftSpeed = 100; rightSpeed = -100; } void findWay(){ leftSpeed = 100; rightSpeed = 100; driveMotor(); delay(100); readSensor(); leftSpeed = 0; rightSpeed = 0; driveMotor(); if (countSensor <= 5 && sensorData[0] == -3 && sensorData[6] == 3){ // Line color Changed whiteLine = !whiteLine; lineEnd = 0; } else if (countSensor == 0 || rule == 0) leftTurn = 1; else if (countSensor == 0 || rule == 1) rightTurn = 1; //lineEnd = 0; } //This function drives the motors //host: 'loop()' void driveMotor() { if (rightSpeed >= 0) { analogWrite(rightMotorPWM, rightSpeed); digitalWrite(rightMotorDown, LOW); digitalWrite(rightMotorUp, HIGH); } else { analogWrite(rightMotorPWM, -rightSpeed); digitalWrite(rightMotorUp, LOW); digitalWrite(rightMotorDown, HIGH); } if (leftSpeed >= 0) { analogWrite(leftMotorPWM, leftSpeed); digitalWrite(leftMotorDown, LOW); digitalWrite(leftMotorUp, HIGH); } else { analogWrite(leftMotorPWM, -leftSpeed); digitalWrite(leftMotorUp, LOW); digitalWrite(leftMotorDown, HIGH); } } //This function prints out all the data throughout the whole program //host: 'loop()' void printData() { //for(int i=0; i<7; i++){ //Serial.print(sensorData[i]); //Serial.print("\t"); //Serial.print("\t"); //Serial.print(white[i]); //Serial.print("\t"); /// Serial.print(black[i]); //} /* Serial.print(countSensor); Serial.print("\t"); Serial.print(sumSensor); Serial.print("\t"); Serial.print(avgSensor); Serial.print("\t"); Serial.print(whiteLine); Serial.print("\t"); Serial.print(error); Serial.print("\t"); Serial.print(leftSpeed); Serial.print("\t"); Serial.print(rightSpeed); Serial.print("\t"); Serial.print(fLine); Serial.print("\t"); Serial.print(pidControl); Serial.print("\t"); */ //Serial.println("\t"); }
[ "akash18rayhan@gmail.com" ]
akash18rayhan@gmail.com
e33f8fd18631568b5f9c008ced03dd2ed80d710d
85b009be7fc1c31c98cd36220a43429c102b634a
/linkedlists/cycledetection_hashing.cpp
ad2862132d61200155add9d72216f40a9857a890
[]
no_license
shikharkrdixit/cppstuff
19e4233cc81b04805bc598131a4ee12366f43836
a7206ef1845fd974bda80993f3cb80d9d7faf220
refs/heads/main
2023-08-02T04:51:21.634336
2021-09-29T17:13:42
2021-09-29T17:13:42
364,998,778
0
0
null
null
null
null
UTF-8
C++
false
false
975
cpp
#include <iostream> #include <bits/stdc++.h> #include <unordered_map> using namespace std; struct Node { int val; struct Node* next; }; bool detectLoop(struct Node* ptr) { unordered_map<Node*, bool> cycdet; Node* temp = ptr; while (temp != NULL) { if (cycdet[temp] != false) return true; cycdet[temp] = true; temp=temp->next; } return false; } int main() { struct Node* head = new Node; head->val = 2; struct Node* l1 = new Node; l1->val = 8; head->next = l1; struct Node* l2 = new Node; l2->val = 3; l1->next = l2; struct Node* l3 = new Node; l3->val = 5; l2->next = l3; struct Node* l4 = new Node; l4->val = 10; l3->next = l4; l4->next = l2; // 2->8->3->5->10-- // ^ | // | | // |_ _ __ _| if (detectLoop(head)) cout << "Loop Present\n"; else cout << "No Loops\n"; return 0; }
[ "sdixit362@gmail.com" ]
sdixit362@gmail.com
f590d664045573f13910c92854aa77db43cc5863
f78f3069f33a3460bb79fc4fde50a0c97e70dc31
/OpencvTest1/OpencvTest1/Cmpare.h
744ca7cd46fb39d2980805a8f35dcf8b99d1798f
[]
no_license
xuehaolan/d-star-lite
da10928ffbfb90c09f068699ee0f0cad743207b8
00921f9cd6a0584c45584ccbff02c6a3d0a6816d
refs/heads/master
2021-06-12T14:09:23.932460
2017-04-08T08:38:23
2017-04-08T08:38:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
193
h
#pragma once #include "Node.h" class Cmpare { public: Cmpare(); ~Cmpare(); //int h(const CNode* nd1, const CNode* nd2) const; bool operator()(const CNode* nd1, const CNode* nd2) const; };
[ "haolan@zju.edu.cn" ]
haolan@zju.edu.cn
d2269d3c3b5ec8c2444279773d3d2570be95a1b2
9be246df43e02fba30ee2595c8cec14ac2b355d1
/cl_dll/c_prop_vehicle.h
66da9ac88234402389415efcd64991883a24e08b
[]
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
3,045
h
//========= Copyright © 1996-2004, Valve LLC, All rights reserved. ============ // // Purpose: // //============================================================================= #ifndef C_PROP_VEHICLE_H #define C_PROP_VEHICLE_H #pragma once #include "IClientVehicle.h" class C_PropVehicleDriveable : public C_BaseAnimating, public IClientVehicle { DECLARE_CLASS( C_PropVehicleDriveable, C_BaseAnimating ); public: DECLARE_CLIENTCLASS(); DECLARE_INTERPOLATION(); C_PropVehicleDriveable(); ~C_PropVehicleDriveable(); public: // IClientVehicle overrides. virtual void OnEnteredVehicle( C_BasePlayer *pPlayer ); virtual void GetVehicleViewPosition( int nRole, Vector *pOrigin, QAngle *pAngles ); virtual void GetVehicleFOV( float &flFOV ) { return; } virtual void DrawHudElements(); virtual bool IsPassengerUsingStandardWeapons( int nRole = VEHICLE_DRIVER ) { return false; } virtual void UpdateViewAngles( C_BasePlayer *pLocalPlayer, CUserCmd *pCmd ); virtual void DampenEyePosition( Vector &vecVehicleEyePos, QAngle &vecVehicleEyeAngles ); virtual C_BasePlayer* GetPassenger( int nRole ); virtual int GetPassengerRole( C_BasePlayer *pEnt ); virtual void GetVehicleClipPlanes( float &flZNear, float &flZFar ) const; public: // C_BaseEntity overrides. virtual IClientVehicle* GetClientVehicle() { return this; } virtual C_BaseEntity *GetVehicleEnt() { return this; } virtual void SetupMove( C_BasePlayer *player, CUserCmd *ucmd, IMoveHelper *pHelper, CMoveData *move ) {} virtual void ProcessMovement( C_BasePlayer *pPlayer, CMoveData *pMoveData ) {} virtual void FinishMove( C_BasePlayer *player, CUserCmd *ucmd, CMoveData *move ) {} virtual bool IsPredicted() const { return false; } virtual void ItemPostFrame( C_BasePlayer *pPlayer ) {} virtual bool IsSelfAnimating() { return false; }; protected: virtual void RestrictView( float *pYawBounds, float *pPitchBounds, float *pRollBounds, QAngle &vecViewAngles ); protected: CHandle<C_BasePlayer> m_hPlayer; int m_nSpeed; int m_nRPM; float m_flThrottle; int m_nBoostTimeLeft; int m_nHasBoost; int m_nScannerDisabledWeapons; int m_nScannerDisabledVehicle; Vector m_vecLookCrosshair; CInterpolatedVar<Vector> m_iv_vecLookCrosshair; Vector m_vecGunCrosshair; CInterpolatedVar<Vector> m_iv_vecGunCrosshair; // timers/flags for flashing icons on hud int m_iFlashTimer; bool m_bLockedDim; bool m_bLockedIcon; int m_iScannerWepFlashTimer; bool m_bScannerWepDim; bool m_bScannerWepIcon; int m_iScannerVehicleFlashTimer; bool m_bScannerVehicleDim; bool m_bScannerVehicleIcon; float m_flSequenceChangeTime; bool m_bEnterAnimOn; bool m_bExitAnimOn; bool m_bWasEntering; Vector m_vecLastEyePos; Vector m_vecLastEyeTarget; Vector m_vecEyeSpeed; Vector m_vecTargetSpeed; }; #endif // C_PROP_VEHICLE_H
[ "uavxp29@gmail.com" ]
uavxp29@gmail.com
9de5e6bcf175ba57fc3559f626bfbc26f48d8972
9ead30376893877e9d7747073462b86c7c5fdb5b
/libs/QRadHw/rawio.cpp
c88d40e5d0e4a9286462346c016f085a101d0524
[]
no_license
MarcoBueno1/qrad
3633398fd333a232e36a603dc471f6f1d122a1af
9215ef47e065345deb92b2139489092aa6ff94e2
refs/heads/master
2020-04-08T16:58:27.383242
2019-07-19T19:40:28
2019-07-19T19:40:28
159,544,545
0
0
null
null
null
null
ISO-8859-15
C++
false
false
19,363
cpp
/* win32/rawio.c - ioctl() emulation module for hdparm for Windows */ /* - by Christian Franke (C) 2006-7 -- freely distributable */ #define RAWIO_INTERNAL #include "rawio.h" #include "fs.h" #include "hdreg.h" #include <stdio.h> #include <stddef.h> // offsetof() #include <string.h> #include <errno.h> //#include <io.h> #define WIN32_LEAN_AND_MEAN #include <windows.h> #if _MSC_VER >= 1400 #define _WIN32_WINNT 0x0502 #include <winioctl.h> #endif #ifndef INVALID_SET_FILE_POINTER #define INVALID_SET_FILE_POINTER ((DWORD)-1) #endif ///////////////////////////////////////////////////////////////////////////// #ifndef IOCTL_STORAGE_RESET_DEVICE #define IOCTL_STORAGE_RESET_DEVICE 0x2d5004 #endif #ifndef IOCTL_DISK_GET_DRIVE_GEOMETRY #define IOCTL_DISK_GET_DRIVE_GEOMETRY 0x070000 typedef enum _MEDIA_TYPE { Unknown } MEDIA_TYPE; typedef struct _DISK_GEOMETRY { LARGE_INTEGER Cylinders; MEDIA_TYPE MediaType; DWORD TracksPerCylinder; DWORD SectorsPerTrack; DWORD BytesPerSector; } DISK_GEOMETRY; #endif // IOCTL_DISK_GET_DRIVE_GEOMETRY typedef char ASSERT_SIZEOF_DISK_GEOMETRY[sizeof(DISK_GEOMETRY) == 24]; #ifndef IOCTL_DISK_GET_LENGTH_INFO #define IOCTL_DISK_GET_LENGTH_INFO 0x07405c typedef struct _GET_LENGTH_INFORMATION { LARGE_INTEGER Length; } GET_LENGTH_INFORMATION; #endif // IOCTL_DISK_GET_LENGTH_INFO typedef char ASSERT_SIZEOF_GET_LENGTH_INFORMATION[sizeof(GET_LENGTH_INFORMATION) == 8]; #ifndef SMART_RCV_DRIVE_DATA typedef struct _IDEREGS { UCHAR bFeaturesReg; UCHAR bSectorCountReg; UCHAR bSectorNumberReg; UCHAR bCylLowReg; UCHAR bCylHighReg; UCHAR bDriveHeadReg; UCHAR bCommandReg; UCHAR bReserved; } IDEREGS; #endif // SMART_RCV_DRIVE_DATA typedef char ASSERT_SIZEOF_IDEREGS[sizeof(IDEREGS) == 8]; #ifndef IOCTL_IDE_PASS_THROUGH #define IOCTL_IDE_PASS_THROUGH 0x04d028 #endif #pragma pack(1) typedef struct _ATA_PASS_THROUGH { IDEREGS IdeReg; ULONG DataBufferSize; UCHAR DataBuffer[1]; } ATA_PASS_THROUGH; #pragma pack() typedef char ASSERT_SIZEOF_ATA_PASS_THROUGH[sizeof(ATA_PASS_THROUGH) == 12+1]; #ifndef IOCTL_ATA_PASS_THROUGH #define IOCTL_ATA_PASS_THROUGH 0x04d02c typedef struct _ATA_PASS_THROUGH_EX { USHORT Length; USHORT AtaFlags; UCHAR PathId; UCHAR TargetId; UCHAR Lun; UCHAR ReservedAsUchar; ULONG DataTransferLength; ULONG TimeOutValue; ULONG ReservedAsUlong; ULONG/*_PTR*/ DataBufferOffset; UCHAR PreviousTaskFile[8]; UCHAR CurrentTaskFile[8]; } ATA_PASS_THROUGH_EX; typedef char ASSERT_SIZEOF_ATA_PASS_THROUGH_EX[sizeof(ATA_PASS_THROUGH_EX) == 40]; #define ATA_FLAGS_DRDY_REQUIRED 0x01 #define ATA_FLAGS_DATA_IN 0x02 #define ATA_FLAGS_DATA_OUT 0x04 #define ATA_FLAGS_48BIT_COMMAND 0x08 #endif //ŽIOCTL_ATA_PASS_THROUGH #ifndef SMART_RCV_DRIVE_DATA #define SMART_RCV_DRIVE_DATA 0x07c088 #pragma pack(1) typedef struct _SENDCMDINPARAMS { ULONG cBufferSize; IDEREGS irDriveRegs; UCHAR bDriveNumber; UCHAR bReserved[3]; ULONG dwReserved[4]; UCHAR bBuffer[1]; } SENDCMDINPARAMS; typedef struct _DRIVERSTATUS { UCHAR bDriverError; UCHAR bIDEError; UCHAR bReserved[2]; ULONG dwReserved[2]; } DRIVERSTATUS; typedef struct _SENDCMDOUTPARAMS { ULONG cBufferSize; DRIVERSTATUS DriverStatus; UCHAR bBuffer[1]; } SENDCMDOUTPARAMS; #pragma pack() #endif // SMART_RCV_DRIVE_DATA typedef char ASSERT_SIZEOF_SENDCMDINPARAMS [sizeof(SENDCMDINPARAMS) == 32+1]; typedef char ASSERT_SIZEOF_SENDCMDOUTPARAMS[sizeof(SENDCMDOUTPARAMS) == 16+1]; ///////////////////////////////////////////////////////////////////////////// int win32_debug; static void print_ide_regs(const IDEREGS * ri, const IDEREGS * ro) { if (ri) printf(" In : CMD=0x%02x, FR=0x%02x, SC=0x%02x, SN=0x%02x, CL=0x%02x, CH=0x%02x, SEL=0x%02x\n", ri->bCommandReg, ri->bFeaturesReg, ri->bSectorCountReg, ri->bSectorNumberReg, ri->bCylLowReg, ri->bCylHighReg, ri->bDriveHeadReg); if (ro) printf(" Out: STS=0x%02x,ERR=0x%02x, SC=0x%02x, SN=0x%02x, CL=0x%02x, CH=0x%02x, SEL=0x%02x\n", ro->bCommandReg, ro->bFeaturesReg, ro->bSectorCountReg, ro->bSectorNumberReg, ro->bCylLowReg, ro->bCylHighReg, ro->bDriveHeadReg); } ///////////////////////////////////////////////////////////////////////////// static int ide_pass_through(HANDLE hdevice, IDEREGS * regs, void * data, unsigned datasize) { unsigned int size = sizeof(ATA_PASS_THROUGH)-1 + datasize; ATA_PASS_THROUGH * buf = (ATA_PASS_THROUGH *)VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); DWORD num_out; const unsigned char magic = 0xcf; if (!buf) { errno = ENOMEM; return -1; } buf->IdeReg = *regs; buf->DataBufferSize = datasize; if (datasize) buf->DataBuffer[0] = magic; if (!DeviceIoControl(hdevice, IOCTL_IDE_PASS_THROUGH, buf, size, buf, size, &num_out, NULL)) { long err = GetLastError(); if (win32_debug) { printf(" IOCTL_IDE_PASS_THROUGH failed, Error=%ld\n", err); print_ide_regs(regs, NULL); } VirtualFree(buf, 0, MEM_RELEASE); errno = ENOSYS; return -1; } if (buf->IdeReg.bCommandReg/*Status*/ & 0x01) { if (win32_debug) { printf(" IOCTL_IDE_PASS_THROUGH command failed:\n"); print_ide_regs(regs, &buf->IdeReg); } VirtualFree(buf, 0, MEM_RELEASE); errno = EIO; return -1; } if (datasize) { if (!(num_out == size && buf->DataBuffer[0] != magic)) { if (win32_debug) { printf(" IOCTL_IDE_PASS_THROUGH output data missing (%lu, %lu)\n", num_out, buf->DataBufferSize); print_ide_regs(regs, &buf->IdeReg); } VirtualFree(buf, 0, MEM_RELEASE); errno = EIO; return -1; } memcpy(data, buf->DataBuffer, datasize); } if (win32_debug) { printf(" IOCTL_IDE_PASS_THROUGH succeeded, bytes returned: %lu (buffer %lu)\n", num_out, buf->DataBufferSize); print_ide_regs(regs, &buf->IdeReg); } *regs = buf->IdeReg; VirtualFree(buf, 0, MEM_RELEASE); return 0; } ///////////////////////////////////////////////////////////////////////////// static int ata_pass_through(HANDLE hdevice, IDEREGS * regs, void * data, int datasize) { typedef struct { ATA_PASS_THROUGH_EX apt; ULONG Filler; UCHAR ucDataBuf[512]; } ATA_PASS_THROUGH_EX_WITH_BUFFERS; ATA_PASS_THROUGH_EX_WITH_BUFFERS ab; IDEREGS * ctfregs; unsigned int size; DWORD num_out; const unsigned char magic = 0xcf; memset(&ab, 0, sizeof(ab)); ab.apt.Length = sizeof(ATA_PASS_THROUGH_EX); //ab.apt.PathId = 0; //ab.apt.TargetId = 0; //ab.apt.Lun = 0; ab.apt.TimeOutValue = 10; size = offsetof(ATA_PASS_THROUGH_EX_WITH_BUFFERS, ucDataBuf); ab.apt.DataBufferOffset = size; if (datasize) { if (!(data && 0 <= datasize && datasize <= (int)sizeof(ab.ucDataBuf))) { errno = EINVAL; return -1; } ab.apt.AtaFlags = ATA_FLAGS_DATA_IN; ab.apt.DataTransferLength = datasize; size += datasize; ab.ucDataBuf[0] = magic; } else { //ab.apt.AtaFlags = 0; //ab.apt.DataTransferLength = 0; } ctfregs = (IDEREGS *)ab.apt.CurrentTaskFile; *ctfregs = *regs; if (!DeviceIoControl(hdevice, IOCTL_ATA_PASS_THROUGH, &ab, size, &ab, size, &num_out, NULL)) { long err = GetLastError(); if (win32_debug) { printf(" IOCTL_ATA_PASS_THROUGH failed, Error=%ld\n", err); print_ide_regs(regs, NULL); } errno = ENOSYS; return -1; } if (ctfregs->bCommandReg/*Status*/ & 0x01) { if (win32_debug) { printf(" IOCTL_ATA_PASS_THROUGH command failed:\n"); print_ide_regs(regs, ctfregs); } *regs = *ctfregs; errno = EIO; return -1; } if (datasize) memcpy(data, ab.ucDataBuf, datasize); if (win32_debug) { printf(" IOCTL_ATA_PASS_THROUGH succeeded, bytes returned: %lu\n", num_out); print_ide_regs(regs, ctfregs); } *regs = *ctfregs; return 0; } ///////////////////////////////////////////////////////////////////////////// static int smart_rcv_drive_data(HANDLE hdevice, IDEREGS * regs, void * data, unsigned datasize) { SENDCMDINPARAMS inpar; unsigned char outbuf[sizeof(SENDCMDOUTPARAMS)-1 + 512]; const SENDCMDOUTPARAMS * outpar; DWORD num_out; memset(&inpar, 0, sizeof(inpar)); inpar.irDriveRegs = *regs; inpar.irDriveRegs.bDriveHeadReg = 0xA0; //inpar.bDriveNumber = 0; inpar.cBufferSize = 512; if (datasize != 512) { errno = EINVAL; return -1; } memset(&outbuf, 0, sizeof(outbuf)); if (!DeviceIoControl(hdevice, SMART_RCV_DRIVE_DATA, &inpar, sizeof(SENDCMDINPARAMS)-1, outbuf, sizeof(SENDCMDOUTPARAMS)-1 + 512, &num_out, NULL)) { long err = GetLastError(); if (win32_debug) { printf(" SMART_RCV_DRIVE_DATA failed, Error=%ld\n", err); print_ide_regs(regs, NULL); } errno = ENOSYS; return -1; } outpar = (const SENDCMDOUTPARAMS *)outbuf; if (outpar->DriverStatus.bDriverError || outpar->DriverStatus.bIDEError) { if (win32_debug) { printf(" SMART_RCV_DRIVE_DATA failed, DriverError=0x%02x, IDEError=0x%02x\n", outpar->DriverStatus.bDriverError, outpar->DriverStatus.bIDEError); print_ide_regs(regs, NULL); } errno = (!outpar->DriverStatus.bIDEError ? ENOSYS : EIO); return -1; } memcpy(data, outpar->bBuffer, 512); if (win32_debug) { printf(" SMART_RCV_DRIVE_DATA suceeded, bytes returned: %lu (buffer %lu)\n", num_out, outpar->cBufferSize); print_ide_regs(regs, NULL); } return 0; } ///////////////////////////////////////////////////////////////////////////// static int try_ata_pass_through(HANDLE hdevice, IDEREGS * regs, void * data, int datasize) { static char avail = 0x7; int rc; if (avail & 0x1) { rc = ata_pass_through(hdevice, regs, data, datasize); if (rc >= 0 || errno != ENOSYS) return rc; avail &= ~0x1; } if ((avail & 0x2) && datasize >= 0) { rc = ide_pass_through(hdevice, regs, data, datasize); if (rc >= 0 || errno != ENOSYS) return rc; avail &= ~0x2; } if ((avail & 0x4) && regs->bCommandReg == WIN_IDENTIFY) { rc = smart_rcv_drive_data(hdevice, regs, data, datasize); if (rc >= 0 || errno != ENOSYS) return rc; avail &= ~0x4; } if (win32_debug) { printf(" No ATA PASS THROUGH I/O control available\n"); print_ide_regs(regs, NULL); } errno = ENOSYS; return -1; } ///////////////////////////////////////////////////////////////////////////// static int get_disk_geometry(HANDLE h, DISK_GEOMETRY * geo) { DWORD num_out; if (!DeviceIoControl(h, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, geo, sizeof(*geo), &num_out, NULL)) { long err = GetLastError(); if (win32_debug) printf(" IOCTL_DISK_GET_DRIVE_GEOMETRY failed, Error=%ld\n", err); errno = (err == ERROR_INVALID_FUNCTION ? ENOSYS : EIO); return -1; } if (win32_debug) printf(" IOCTL_DISK_GET_DRIVE_GEOMETRY succeeded, bytes returned: %lu\n", num_out); return 0; } static __int64 get_disk_length(HANDLE h) { DWORD num_out; GET_LENGTH_INFORMATION li; if (!DeviceIoControl(h, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &li, sizeof(li), &num_out, NULL)) { long err = GetLastError(); if (win32_debug) printf(" IOCTL_DISK_GET_LENGTH_INFO failed, Error=%ld\n", err); errno = (err == ERROR_INVALID_FUNCTION ? ENOSYS : EIO); return -1; } if (win32_debug) printf(" IOCTL_DISK_GET_LENGTH_INFO succeeded, bytes returned: %lu\n", num_out); return li.Length.QuadPart; } ///////////////////////////////////////////////////////////////////////////// static int reset_device(HANDLE h) { DWORD num_out; if (!DeviceIoControl(h, IOCTL_STORAGE_RESET_DEVICE, NULL, 0, NULL, 0, &num_out, NULL)) { long err = GetLastError(); if (win32_debug) printf(" IOCTL_STORAGE_RESET_DEVICE failed, Error=%ld\n", err); errno = (err == ERROR_INVALID_FUNCTION || err == ERROR_NOT_SUPPORTED ? ENOSYS : EIO); return -1; } if (win32_debug) printf(" IOCTL_STORAGE_RESET_DEVICE succeeded\n"); return 0; } ///////////////////////////////////////////////////////////////////////////// static char is_cd = 0; int win32_open(const char * name, unsigned flags, unsigned perm) { int len; char drv[1+1] = ""; unsigned cdno = ~0; int n1 = -1; char path[50]; HANDLE h; DWORD crflags; (void)perm; SECURITY_DESCRIPTOR sd; SECURITY_ATTRIBUTES sa; InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE); sa.lpSecurityDescriptor=&sd; sa.bInheritHandle=TRUE; if (!strncmp("/dev/", name, 5)) name += 5; len = strlen(name); if (sscanf(name, "%*[hs]d%1[a-z]%n", drv, &n1) == 1 && n1 == len) { sprintf(path, "\\\\.\\PhysicalDrive%d", drv[0] - 'a'); is_cd = 0; } else if (sscanf(name, "scd%u%n", &cdno, (n1=-1, &n1)) == 1 && n1 == len && cdno <= 15) { sprintf(path, "\\\\.\\CdRom%u", cdno); is_cd = 1; } else { errno = EINVAL; return -1; } crflags = (flags & O_DIRECT ? FILE_FLAG_NO_BUFFERING : 0); if ((h = CreateFileA(path, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, crflags, 0)) == INVALID_HANDLE_VALUE) { long err = GetLastError(); if (win32_debug) printf("%s: cannot open, Error=%ld\n", path, err); if (err == ERROR_FILE_NOT_FOUND) errno = ENOENT; else if (err == ERROR_ACCESS_DENIED) errno = EACCES; else errno = EIO; return -1; } if (win32_debug) printf("%s: successfully opened\n", path); return (int)h; } int win32_close(int fd) { CloseHandle((HANDLE)fd); return 0; } int win32_read(int fd, char * buf, int size) { DWORD num_read; if (!ReadFile((HANDLE)fd, buf, size, &num_read, NULL)) { errno = EIO; return -1; } return num_read; } long win32_lseek(int fd, long offset, int where) { DWORD pos; if (where != SEEK_SET) { errno = EINVAL; return -1; } pos = SetFilePointer((HANDLE)fd, offset, 0, FILE_BEGIN); if (pos == INVALID_SET_FILE_POINTER) { errno = EIO; return -1; } return pos; } static void fix_id_string(unsigned char * s, int n) { int i; for (i = 0; i < n-1; i+=2) { unsigned char c = s[i]; s[i] = s[i+1]; s[i+1] = c; } for (i = n-1; i > 0 && s[i] == ' '; i--) s[i] = 0; } int win32_ioctl(int fd, int code, void * arg) { int rc = 0; switch (code) { #ifdef BLKGETSIZE case BLKGETSIZE: case BLKGETSIZE64: { __int64 size = get_disk_length((HANDLE)fd); if (size < 0 && errno == ENOSYS) { DISK_GEOMETRY dg; rc = get_disk_geometry((HANDLE)fd, &dg); if (rc) break; size = dg.Cylinders.QuadPart * dg.TracksPerCylinder * dg.SectorsPerTrack * dg.BytesPerSector; } if (code == BLKGETSIZE) *(unsigned *)arg = (unsigned)(size >> 9); else *(unsigned __int64 *)arg = size; } break; #endif #ifdef HDIO_GETGEO case HDIO_GETGEO: case HDIO_GETGEO_BIG: { DISK_GEOMETRY dg; rc = get_disk_geometry((HANDLE)fd, &dg); if (rc) break; if (code == HDIO_GETGEO) { struct hd_geometry * gp = (struct hd_geometry *)arg; gp->cylinders = (unsigned short)(dg.Cylinders.LowPart <= 0xffff ? dg.Cylinders.LowPart : 0xffff); gp->heads = (unsigned char)(dg.TracksPerCylinder <= 0xff ? dg.TracksPerCylinder : 0xff); gp->sectors = (unsigned char)(dg.SectorsPerTrack <= 0xff ? dg.SectorsPerTrack : 0xff); gp->start = 0; } else { struct hd_big_geometry * gp = (struct hd_big_geometry *)arg; gp->cylinders = dg.Cylinders.LowPart; gp->heads = (unsigned char)(dg.TracksPerCylinder <= 0xff ? dg.TracksPerCylinder : 0xff); gp->sectors = (unsigned char)(dg.SectorsPerTrack <= 0xff ? dg.SectorsPerTrack : 0xff); gp->start = 0; } } break; #endif #ifdef HDIO_GET_IDENTITY case HDIO_GET_IDENTITY: if (!arg) // Flush break; { struct hd_driveid * id = (struct hd_driveid *)arg; IDEREGS regs = {0,0,0,0,0,0,0,0}; regs.bCommandReg = (!is_cd ? WIN_IDENTIFY : WIN_PIDENTIFY); regs.bSectorCountReg = 1; rc = try_ata_pass_through((HANDLE)fd, &regs, id, 512); if (rc) break; fix_id_string(id->model, sizeof(id->model)); fix_id_string(id->fw_rev, sizeof(id->fw_rev)); fix_id_string(id->serial_no, sizeof(id->serial_no)); } break; #endif #ifdef HDIO_GET_ACOUSTIC case HDIO_GET_ACOUSTIC: if (!arg) // Flush break; { struct hd_driveid id; IDEREGS regs = {0,0,0,0,0,0,0,0}; memset(&id, 0, sizeof(id)); regs.bCommandReg = (!is_cd ? WIN_IDENTIFY : WIN_PIDENTIFY); regs.bSectorCountReg = 1; rc = try_ata_pass_through((HANDLE)fd, &regs, &id, 512); if (rc) break; *(long *)arg = (id.words94_125[0] & 0xff); } break; #endif #ifdef HDIO_DRIVE_RESET case HDIO_DRIVE_RESET: rc = reset_device((HANDLE)fd); break; #endif #ifdef HDIO_DRIVE_CMD case HDIO_DRIVE_CMD: if (!arg) // Flush break; { // input: // [0]: COMMAND // [1]: SECTOR NUMBER (SMART) or SECTOR COUNT (other) // [2]: FEATURE // [3]: SECTOR COUNT (transfer size) // output: // [0]: STATUS // [1]: ERROR // [2]: SECTOR COUNT // [3]: (undefined?) // [4...]: data unsigned char * idebuf = (unsigned char *)arg; IDEREGS regs = {0,0,0,0,0,0,0,0}; regs.bCommandReg = idebuf[0]; regs.bFeaturesReg = idebuf[2]; if (idebuf[3]) regs.bSectorCountReg = idebuf[3]; else regs.bSectorCountReg = idebuf[1]; rc = try_ata_pass_through((HANDLE)fd, &regs, idebuf+4, idebuf[3] * 512); idebuf[0] = regs.bCommandReg; // STS idebuf[1] = regs.bFeaturesReg; // ERR idebuf[2] = regs.bSectorCountReg; } break; #endif default: errno = ENOSYS; rc = -1; break; } return rc; } //#include <fcntl.h> //#include <unistd.h> //#include <QString> #define O_RDONLY 00 #define O_WRONLY 01 #define O_RDWR 02 int main( int argc, char *argv[]) { struct hd_driveid id; int fd = win32_open("/dev/hda", O_RDONLY, 0); // HANDLE hClientIbold = 0; // handle do mailslot de transmissao // hClientIbold= CreateMailslot ( szClientIbold, 0, MaxEspResposta, NULL ); // hClientIbold= CreateMailslot ( szClientIbold, 0, 0, &sa ); if ( fd < 0 ) { fd = win32_open("/dev/sda", O_RDONLY,0); } if (fd < 0) { perror("/dev/sda"); } memset(&id,0,sizeof(struct hd_driveid)); // int win32_ioctl(int fd, int code, void * arg) if(!win32_ioctl(fd, HDIO_GET_IDENTITY, &id)) { // QString s1; // id.serial_no does not save space for string termination const int serialSize = sizeof(id.serial_no); char buf[serialSize + 1]; memcpy(buf, id.serial_no, serialSize); buf[serialSize] = '\0'; /* s1.sprintf("%s", buf); s1 = s1.trimmed(); if ( s1.contains("-") ) s1.replace("-","_"); */ win32_close(fd); printf("Lido:%s \n", buf); return 0; } perror("ioctl"); return 0; }
[ "root@debian.marco" ]
root@debian.marco
67956e9f66f52ab4aaf2db0b5fa7ccd657196fae
aa9d1768e645238a1ce67e35d76a088e4aaab9a8
/C++_course/03处理数据/floatnum.cpp
5e3ed617e33309066804e8110787ab97ad94006d
[]
no_license
f15534666671/Cplusplus_course_clion
f0f639f2607d9d12bf4c6d3d121e3c4a20400611
fd3d0541e7321f0f90aed0137c0c818c64ce3ae1
refs/heads/master
2020-06-07T13:49:45.297835
2019-06-21T05:24:47
2019-06-21T05:24:47
193,036,043
0
0
null
null
null
null
UTF-8
C++
false
false
521
cpp
// floatnum.cpp -- floating-point types #include <iostream> int main() { using namespace std; cout.setf(ios_base::fixed, ios_base::floatfield); float tub = 10.0 / 3.0; double mint = 10.0 / 3.0; const float million = 1.0e6; cout << "tub = " << tub; cout << ", a million tubs = " << million * tub; cout << ", \nand ten million tubs = "; cout << 10 * million * tub << endl; cout << "mint = " << mint << " and a million mints = "; cout << million * mint << endl; return 0; }
[ "f15534666671@163.com" ]
f15534666671@163.com
7eb1203103e44d335e1093bdc1fe51314b95df1f
381e2b6c8608f50d76e886c63e721b672525da40
/MSoC_Lab1_p1/MSoC_Lab1_p1/main.cpp
b1e45d521b71211414e7b966a7868285afb7398a
[]
no_license
alon21034/MSoC_Lab1
e0a0baacf6ac1c93f5cfad7728ffb7b2132d11d8
e3798354bf2135c5b077553a94038df1e86093b9
refs/heads/master
2020-06-12T20:55:53.832830
2013-03-26T03:05:50
2013-03-26T03:06:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
957
cpp
#include <systemc.h> #include "Counter.h" #include "Stimulus.h" #include "Display.h" int sc_main( int argc, char** argv ) { /*- Signal Declaration -*/ sc_time SIM_TIME( 500, SC_NS ); sc_clock clk ("clk", 10 ); sc_signal<int> Value; sc_signal<bool> Enable; sc_signal<bool> UpDown; sc_signal<bool> Reset; /*- Instantiation and Net Connection -*/ Counter iCounter( "iCounter" ); iCounter.iclk( clk ); iCounter.Reset( Reset ); iCounter.Enable( Enable ); iCounter.UpDown( UpDown ); iCounter.Value( Value ); Stimulus iStimulus( "iStimulus" ); iStimulus.iclk( clk ); iStimulus.Enable( Enable ); iStimulus.Reset( Reset ); iStimulus.UpDown( UpDown ); Display iDisplay( "iDisplay"); iDisplay.Value( Value ); /*- Run Simulation -*/ sc_start( SIM_TIME ); /*- Clean Up -*/ return 0; }
[ "vince@cardinalblue.com" ]
vince@cardinalblue.com
ba552a65b2dcb402124a364f609a24d9b3a2eb27
bacb3adfc1af9d6c8202f7b93c16515f6d2836ae
/Post_power.ino
a6fc66afd8e7eb7659bb87a7390330821a75e4dd
[]
no_license
whatnick/IoTaWatt
b5a585ae3fe13f1272bec39e23183621a4fe51d1
eeb56becd6dcb041284b9c272d108e7c791b8759
refs/heads/master
2021-01-01T05:47:34.528091
2016-12-30T07:49:39
2016-12-30T07:49:39
77,670,703
2
1
null
2016-12-30T07:51:58
2016-12-30T07:51:57
null
UTF-8
C++
false
false
2,405
ino
void post_power() { String req = "GET /input/post.json?" "&node="; req += String(node); // If Serial link is active, log power to it. if(Serial) { Serial.print(", VRMS="); Serial.print(Vrms,1); Serial.print("("); Serial.print(offset[0]); Serial.print(","); Serial.print(samplesPerCycle); Serial.print(")"); for(int i=1; i <= channels; i++) { if(channelActive[i]) { Serial.print(", ("); Serial.print(i); Serial.print(")"); Serial.print(averageWatts[i],0); // Uncomment to print power factor Serial.print("["); Serial.print(averageWatts[i]/averageVA[i],4); Serial.print("]"); } } Serial.println(); } if (reply_pending) { if(Serial)Serial.println("Previous request timed out."); cloudServer.flush(); cloudServer.stop(); reply_pending = false; } if(!cloudServer.connected()) { cloudServer.flush(); cloudServer.stop(); check_internet(); char url[80]; cloudURL.toCharArray(url, 80); int connect_rtc = cloudServer.connect(url, 80); if (connect_rtc != 1) { if(Serial) { Serial.print("failed to connect to:"); Serial.print(cloudURL); Serial.print(", rtc="); Serial.println(connect_rtc); } return; } } req += "&csv="; int commas = 0; for (int i = 1; i <= channels; i++) { if(channelActive[i]) { while(commas > 0) { req += ","; commas--; } req += String(long(averageWatts[i]+.5)); } commas++; } req += "&apikey="; req += apikey; cloudServer.println(req); if(Serial)Serial.println(req); reply_pending = true; return; } void checkdata() { if (!reply_pending) return; int data_length = cloudServer.available(); if (data_length < 2) return; char o = cloudServer.read(); char k = cloudServer.read(); if (o == 'o' & k == 'k')reply_pending = false; else { if(Serial)Serial.print(o); Serial.print(k); while (cloudServer.available()) if(Serial)Serial.print(cloudServer.read()); } while (cloudServer.available()) cloudServer.read(); cloudServer.stop(); return; } boolean check_internet(void) { // int rtc = Ethernet.maintain(); // if(rtc == 1 || rtc == 3) return(false); return(true); }
[ "noreply@github.com" ]
noreply@github.com
27731ea7a938f9c13cd933ddc8904e48bae0f452
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/git/gumtree/git_repos_function_4521_git-2.14.1.cpp
7b49aa9e77164b79d38f2d9b3e685fbf2531d179
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
105
cpp
int hashmap_bucket(const struct hashmap *map, unsigned int hash) { return hash & (map->tablesize - 1); }
[ "993273596@qq.com" ]
993273596@qq.com
a44779aef554963785f5d0ab028e94a98e40addf
6ddaa91f8509f2223cea0d4d783c4c165b7a2dc8
/MorphDSL/ANTLRCompiler/MorphDSL3Lexer.hpp
93da2b0307dd97f3aeb34a4bed06af7fe1b05f7c
[]
no_license
Unsttopabull/MorphDSL
4fae568ea1be902a0a9f0f0456663a1a9bbac87c
364610f3528e90cf6fb34eb3b1f579cb03453bc6
refs/heads/master
2021-01-16T21:00:54.148003
2015-07-13T14:39:01
2015-07-13T14:41:25
31,203,899
0
0
null
null
null
null
UTF-8
C++
false
false
8,463
hpp
/** \file * This C++ header file was generated by $ANTLR version 3.4.1-SNAPSHOT * * - From the grammar source file : T.g * - On : 2012-09-17 18:17:43 * - for the lexer : MorphDSL3LexerLexer * * Editing it, at least manually, is not wise. * * C++ language generator and runtime by Gokulakannan Somasundaram ( heavy lifting from C Run-time by Jim Idle ) * * * The lexer MorphDSL3Lexer has the callable functions (rules) shown below, * which will invoke the code for the associated rule in the source grammar * assuming that the input stream is pointing to a token/text stream that could begin * this rule. * * For instance if you call the first (topmost) rule in a parser grammar, you will * get the results of a full parse, but calling a rule half way through the grammar will * allow you to pass part of a full token stream to the parser, such as for syntax checking * in editors and so on. * */ // [The "BSD license"] // Copyright (c) 2005-2009 Gokulakannan Somasundaram. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef _MorphDSL3Lexer_H #define _MorphDSL3Lexer_H /* ============================================================================= * Standard antlr3 C++ runtime definitions */ #include "..\stdafx.h" #include <antlr3.hpp> /* End of standard antlr 3 runtime definitions * ============================================================================= */ #ifdef WIN32 // Disable: Unreferenced parameter, - Rules with parameters that are not used // constant conditional, - ANTLR realizes that a prediction is always true (synpred usually) // initialized but unused variable - tree rewrite variables declared but not needed // Unreferenced local variable - lexer rule declares but does not always use _type // potentially unitialized variable used - retval always returned from a rule // unreferenced local function has been removed - susually getTokenNames or freeScope, they can go without warnigns // // These are only really displayed at warning level /W4 but that is the code ideal I am aiming at // and the codegen must generate some of these warnings by necessity, apart from 4100, which is // usually generated when a parser rule is given a parameter that it does not use. Mostly though // this is a matter of orthogonality hence I disable that one. // #pragma warning( disable : 4100 ) #pragma warning( disable : 4101 ) #pragma warning( disable : 4127 ) #pragma warning( disable : 4189 ) #pragma warning( disable : 4505 ) #pragma warning( disable : 4701 ) #endif namespace User { class MorphDSL3Lexer; class MorphDSL3Parser; template<class ImplTraits> class UserTraits : public antlr3::CustomTraitsBase<ImplTraits> { public: //for using the token stream which deleted the tokens, once it is reduced to a rule //but it leaves the start and stop tokens. So they can be accessed as usual static const bool TOKENS_ACCESSED_FROM_OWNING_RULE = true; }; typedef antlr3::Traits< MorphDSL3Lexer, MorphDSL3Parser, UserTraits > MorphDSL3LexerTraits; typedef MorphDSL3LexerTraits MorphDSL3ParserTraits; /* If you don't want the override it is like this. class MorphDSL3Lexer; class MorphDSL3Parser; typedef antlr3::Traits< MorphDSL3Lexer, MorphDSL3Parser > MorphDSL3LexerTraits; typedef MorphDSL3LexerTraits MorphDSL3ParserTraits; */ typedef MorphDSL3LexerTraits MorphDSL3LexerImplTraits; class MorphDSL3LexerTokens { public: /** Symbolic definitions of all the tokens that the lexer will work with. * \{ * * Antlr will define EOF, but we can't use that as it it is too common in * in C header files and that would be confusing. There is no way to filter this out at the moment * so we just undef it here for now. That isn't the value we get back from C recognizers * anyway. We are looking for ANTLR_TOKEN_EOF. */ enum Tokens { EOF_TOKEN = MorphDSL3LexerImplTraits::CommonTokenType::TOKEN_EOF , T__9 = 9 , T__10 = 10 , T__11 = 11 , T__12 = 12 , T__13 = 13 , T__14 = 14 , T__15 = 15 , T__16 = 16 , T__17 = 17 , T__18 = 18 , T__19 = 19 , T__20 = 20 , T__21 = 21 , T__22 = 22 , T__23 = 23 , T__24 = 24 , T__25 = 25 , T__26 = 26 , T__27 = 27 , T__28 = 28 , T__29 = 29 , T__30 = 30 , T__31 = 31 , T__32 = 32 , T__33 = 33 , T__34 = 34 , T__35 = 35 , T__36 = 36 , T__37 = 37 , T__38 = 38 , T__39 = 39 , T__40 = 40 , T__41 = 41 , T__42 = 42 , T__43 = 43 , T__44 = 44 , T__45 = 45 , T__46 = 46 , ID = 4 , DOUBLENUMBER = 5 , NUMBER = 6 , WS = 7 , COMMENT = 8 }; }; /** Context tracking structure for MorphDSL3Lexer */ class MorphDSL3Lexer : public MorphDSL3LexerImplTraits::BaseLexerType , public MorphDSL3LexerTokens { public: typedef MorphDSL3LexerImplTraits ImplTraits; typedef MorphDSL3Lexer ComponentType; typedef ComponentType::StreamType StreamType; typedef MorphDSL3LexerImplTraits::BaseLexerType BaseType; typedef ImplTraits::RecognizerSharedStateType<StreamType> RecognizerSharedStateType; typedef StreamType InputType; static const bool IsFiltered = false; private: public: MorphDSL3Lexer(InputType* instream); MorphDSL3Lexer(InputType* instream, RecognizerSharedStateType* state); void init(InputType* instream ); void mT__9( ); void mT__10( ); void mT__11( ); void mT__12( ); void mT__13( ); void mT__14( ); void mT__15( ); void mT__16( ); void mT__17( ); void mT__18( ); void mT__19( ); void mT__20( ); void mT__21( ); void mT__22( ); void mT__23( ); void mT__24( ); void mT__25( ); void mT__26( ); void mT__27( ); void mT__28( ); void mT__29( ); void mT__30( ); void mT__31( ); void mT__32( ); void mT__33( ); void mT__34( ); void mT__35( ); void mT__36( ); void mT__37( ); void mT__38( ); void mT__39( ); void mT__40( ); void mT__41( ); void mT__42( ); void mT__43( ); void mT__44( ); void mT__45( ); void mT__46( ); void mID( ); void mDOUBLENUMBER(); void mNUMBER(); void mWS( ); void mCOMMENT(); void mTokens( ); const char * getGrammarFileName(); void reset(); ~MorphDSL3Lexer(); }; // Function protoypes for the constructor functions that external translation units // such as delegators and delegates may wish to call. // /* End of token definitions for MorphDSL3Lexer * ============================================================================= */ /** } */ } #endif /* END - Note:Keep extra line feed to satisfy UNIX systems */
[ "martinkraner@outlook.com" ]
martinkraner@outlook.com
3dc4d9ec973f8419b7b782ac466f2dd399bc6520
254eb66260f276f6c6a303ea6cb26148b33b0dac
/Wrapper/Mmaths/Mvec2.h
31dcd921d671cb75f1e0e9cf50e28bbb30c13cca
[]
no_license
L4ZZA/UnmanagedCodeWrapper
4624c5dbef9580afdccaea3b306396ce00916f14
0f92ba38989c2d4b266164a4bdc9fcfbd441bd5a
refs/heads/master
2021-09-24T08:04:44.751472
2018-10-05T10:23:32
2018-10-05T10:23:32
124,081,227
1
0
null
null
null
null
UTF-8
C++
false
false
1,658
h
#pragma once #include "../ManagedObject.h" #include "Core.h" using namespace System; namespace CLIWrapper { // See this docs // https://docs.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp public ref class Vec2 : public ManagedObject<core::maths::vec2> { public: // Constructor Vec2(); Vec2(float xPos, float yPos); Vec2(const Vec2^ other); // X Position property float X { public: float get() { return m_Instance->x; } private: void set(float value) {} } // Y Position property float Y { public: float get() { return m_Instance->y; } private: void set(float value) {} } void Add(Vec2 other); void Subtract(Vec2 other); void Multiply(Vec2 other); void Divide(Vec2 other); //TODO: //friend vec2& operator+(vec2 left, const vec2& right); //friend vec2& operator-(vec2 left, const vec2& right); //friend vec2& operator*(vec2 left, const vec2& right); //friend vec2& operator/(vec2 left, const vec2& right); //bool operator==(const vec2& other); //bool operator!=(const vec2& other); //vec2& operator+=(const vec2& other); //vec2& operator-=(const vec2& other); //vec2& operator*=(const vec2& other); //vec2& operator/=(const vec2& other); //friend std::ostream& operator<<(std::ostream& stream, const vec2& vector); }; }
[ "pietro.lazz@gmail.com" ]
pietro.lazz@gmail.com
2fe50daccb1b88bee48d9ee61de2e0a231463f57
18356da162612a99e0534e2ed72b023fbdb0003a
/448-find-all-numbers-disappeared-in-an-array-[easy]/solution.cpp
5bceb19ebabcec88c086ac9f09cbe01521f1be1c
[]
no_license
sora-k/coding-problems
217c84c0b3387c949ce5b39a6be806c835dba30f
819205d090da3b2ebd163c3367bf512bfe76219b
refs/heads/master
2021-01-20T14:28:33.251665
2017-05-08T09:59:45
2017-05-08T09:59:45
68,570,388
0
0
null
null
null
null
UTF-8
C++
false
false
1,493
cpp
//448. Find All Numbers Disappeared in an Array // started 4/6/17 8:40AM - 8:48AM // 9:00AM - 9:24AM // 9:34AM - 9:54AM /* Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. Example: Input: [4,3,2,7,8,2,3,1] Output: [5,6] */ class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { vector<int> result; int current, tmp, current_ind; for(int i = 0; i < nums.size(); ++i){//sort elements in array to their corresponding indices current = nums[i]; current_ind = current - 1; while(current_ind != i && nums[current_ind] != current){ tmp = nums[current - 1]; nums[current_ind] = current; nums[i] = tmp; current_ind = tmp - 1; current = tmp; } } for(int i = 0; i < nums.size(); ++i){//get the missing elements current_ind = nums[i] - 1; if(current_ind != i){ result.push_back(i + 1); } } return result; } }; /* [1] [2,1] [4,3,2,7,8,2,3,1] [5,1,3,3,2,4] */
[ "sora-k@users.noreply.github.com" ]
sora-k@users.noreply.github.com
cc2c662dcf636e55cf1dfba6194ef7dbe2a686b6
bfd8933c9605067202e1fbe4dbd38e9be7d319eb
/Lib/Chip/CM4/Nordic/nrf52/QDEC.hpp
ddb53d2f910bbdcf49b0e10667f177c125542217
[ "Apache-2.0" ]
permissive
gitter-badger/Kvasir-1
91968c6c2bfae38a33e08fafb87de399e450a13c
a9ea942f54b764e27dbab9c74e5f0f97390a778e
refs/heads/master
2020-12-24T18:23:36.275985
2016-02-24T22:06:57
2016-02-24T22:06:57
52,541,357
0
0
null
2016-02-25T16:54:18
2016-02-25T16:54:18
null
UTF-8
C++
false
false
22,335
hpp
#pragma once #include "Register/Utility.hpp" namespace Kvasir { //Quadrature Decoder namespace NonetasksStart{ ///<Task starting the quadrature decoder using Addr = Register::Address<0x40012000,0xffffffff,0,unsigned>; } namespace NonetasksStop{ ///<Task stopping the quadrature decoder using Addr = Register::Address<0x40012004,0xffffffff,0,unsigned>; } namespace NonetasksReadclracc{ ///<Read and clear ACC and ACCDBL using Addr = Register::Address<0x40012008,0xffffffff,0,unsigned>; } namespace NonetasksRdclracc{ ///<Read and clear ACC using Addr = Register::Address<0x4001200c,0xffffffff,0,unsigned>; } namespace NonetasksRdclrdbl{ ///<Read and clear ACCDBL using Addr = Register::Address<0x40012010,0xffffffff,0,unsigned>; } namespace NoneeventsSamplerdy{ ///<Event being generated for every new sample value written to the SAMPLE register using Addr = Register::Address<0x40012100,0xffffffff,0,unsigned>; } namespace NoneeventsReportrdy{ ///<Non-null report ready using Addr = Register::Address<0x40012104,0xffffffff,0,unsigned>; } namespace NoneeventsAccof{ ///<ACC or ACCDBL register overflow using Addr = Register::Address<0x40012108,0xffffffff,0,unsigned>; } namespace NoneeventsDblrdy{ ///<Double displacement(s) detected using Addr = Register::Address<0x4001210c,0xffffffff,0,unsigned>; } namespace NoneeventsStopped{ ///<QDEC has been stopped using Addr = Register::Address<0x40012110,0xffffffff,0,unsigned>; } namespace Noneshorts{ ///<Shortcut register using Addr = Register::Address<0x40012200,0xffffff80,0,unsigned>; ///Shortcut between EVENTS_REPORTRDY event and TASKS_READCLRACC task enum class ReportrdyreadclraccVal { disabled=0x00000000, ///<Disable shortcut enabled=0x00000001, ///<Enable shortcut }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,ReportrdyreadclraccVal> reportrdyReadclracc{}; namespace ReportrdyreadclraccValC{ constexpr Register::FieldValue<decltype(reportrdyReadclracc)::Type,ReportrdyreadclraccVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(reportrdyReadclracc)::Type,ReportrdyreadclraccVal::enabled> enabled{}; } ///Shortcut between EVENTS_SAMPLERDY event and TASKS_STOP task enum class SamplerdystopVal { disabled=0x00000000, ///<Disable shortcut enabled=0x00000001, ///<Enable shortcut }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,SamplerdystopVal> samplerdyStop{}; namespace SamplerdystopValC{ constexpr Register::FieldValue<decltype(samplerdyStop)::Type,SamplerdystopVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(samplerdyStop)::Type,SamplerdystopVal::enabled> enabled{}; } ///Shortcut between EVENTS_REPORTRDY event and TASKS_RDCLRACC task enum class ReportrdyrdclraccVal { disabled=0x00000000, ///<Disable shortcut enabled=0x00000001, ///<Enable shortcut }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,ReportrdyrdclraccVal> reportrdyRdclracc{}; namespace ReportrdyrdclraccValC{ constexpr Register::FieldValue<decltype(reportrdyRdclracc)::Type,ReportrdyrdclraccVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(reportrdyRdclracc)::Type,ReportrdyrdclraccVal::enabled> enabled{}; } ///Shortcut between EVENTS_REPORTRDY event and TASKS_STOP task enum class ReportrdystopVal { disabled=0x00000000, ///<Disable shortcut enabled=0x00000001, ///<Enable shortcut }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,ReportrdystopVal> reportrdyStop{}; namespace ReportrdystopValC{ constexpr Register::FieldValue<decltype(reportrdyStop)::Type,ReportrdystopVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(reportrdyStop)::Type,ReportrdystopVal::enabled> enabled{}; } ///Shortcut between EVENTS_DBLRDY event and TASKS_RDCLRDBL task enum class DblrdyrdclrdblVal { disabled=0x00000000, ///<Disable shortcut enabled=0x00000001, ///<Enable shortcut }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,DblrdyrdclrdblVal> dblrdyRdclrdbl{}; namespace DblrdyrdclrdblValC{ constexpr Register::FieldValue<decltype(dblrdyRdclrdbl)::Type,DblrdyrdclrdblVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(dblrdyRdclrdbl)::Type,DblrdyrdclrdblVal::enabled> enabled{}; } ///Shortcut between EVENTS_DBLRDY event and TASKS_STOP task enum class DblrdystopVal { disabled=0x00000000, ///<Disable shortcut enabled=0x00000001, ///<Enable shortcut }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,DblrdystopVal> dblrdyStop{}; namespace DblrdystopValC{ constexpr Register::FieldValue<decltype(dblrdyStop)::Type,DblrdystopVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(dblrdyStop)::Type,DblrdystopVal::enabled> enabled{}; } ///Shortcut between EVENTS_SAMPLERDY event and TASKS_READCLRACC task enum class SamplerdyreadclraccVal { disabled=0x00000000, ///<Disable shortcut enabled=0x00000001, ///<Enable shortcut }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,SamplerdyreadclraccVal> samplerdyReadclracc{}; namespace SamplerdyreadclraccValC{ constexpr Register::FieldValue<decltype(samplerdyReadclracc)::Type,SamplerdyreadclraccVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(samplerdyReadclracc)::Type,SamplerdyreadclraccVal::enabled> enabled{}; } } namespace Noneintenset{ ///<Enable interrupt using Addr = Register::Address<0x40012304,0xffffffe0,0,unsigned>; ///Write '1' to Enable interrupt on EVENTS_SAMPLERDY event enum class SamplerdyVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled set=0x00000001, ///<Enable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,SamplerdyVal> samplerdy{}; namespace SamplerdyValC{ constexpr Register::FieldValue<decltype(samplerdy)::Type,SamplerdyVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(samplerdy)::Type,SamplerdyVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(samplerdy)::Type,SamplerdyVal::set> set{}; } ///Write '1' to Enable interrupt on EVENTS_REPORTRDY event enum class ReportrdyVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled set=0x00000001, ///<Enable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,ReportrdyVal> reportrdy{}; namespace ReportrdyValC{ constexpr Register::FieldValue<decltype(reportrdy)::Type,ReportrdyVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(reportrdy)::Type,ReportrdyVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(reportrdy)::Type,ReportrdyVal::set> set{}; } ///Write '1' to Enable interrupt on EVENTS_ACCOF event enum class AccofVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled set=0x00000001, ///<Enable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,AccofVal> accof{}; namespace AccofValC{ constexpr Register::FieldValue<decltype(accof)::Type,AccofVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(accof)::Type,AccofVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(accof)::Type,AccofVal::set> set{}; } ///Write '1' to Enable interrupt on EVENTS_DBLRDY event enum class DblrdyVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled set=0x00000001, ///<Enable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,DblrdyVal> dblrdy{}; namespace DblrdyValC{ constexpr Register::FieldValue<decltype(dblrdy)::Type,DblrdyVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(dblrdy)::Type,DblrdyVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(dblrdy)::Type,DblrdyVal::set> set{}; } ///Write '1' to Enable interrupt on EVENTS_STOPPED event enum class StoppedVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled set=0x00000001, ///<Enable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,StoppedVal> stopped{}; namespace StoppedValC{ constexpr Register::FieldValue<decltype(stopped)::Type,StoppedVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(stopped)::Type,StoppedVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(stopped)::Type,StoppedVal::set> set{}; } } namespace Noneintenclr{ ///<Disable interrupt using Addr = Register::Address<0x40012308,0xffffffe0,0,unsigned>; ///Write '1' to Clear interrupt on EVENTS_SAMPLERDY event enum class SamplerdyVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled clear=0x00000001, ///<Disable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,SamplerdyVal> samplerdy{}; namespace SamplerdyValC{ constexpr Register::FieldValue<decltype(samplerdy)::Type,SamplerdyVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(samplerdy)::Type,SamplerdyVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(samplerdy)::Type,SamplerdyVal::clear> clear{}; } ///Write '1' to Clear interrupt on EVENTS_REPORTRDY event enum class ReportrdyVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled clear=0x00000001, ///<Disable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,ReportrdyVal> reportrdy{}; namespace ReportrdyValC{ constexpr Register::FieldValue<decltype(reportrdy)::Type,ReportrdyVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(reportrdy)::Type,ReportrdyVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(reportrdy)::Type,ReportrdyVal::clear> clear{}; } ///Write '1' to Clear interrupt on EVENTS_ACCOF event enum class AccofVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled clear=0x00000001, ///<Disable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,AccofVal> accof{}; namespace AccofValC{ constexpr Register::FieldValue<decltype(accof)::Type,AccofVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(accof)::Type,AccofVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(accof)::Type,AccofVal::clear> clear{}; } ///Write '1' to Clear interrupt on EVENTS_DBLRDY event enum class DblrdyVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled clear=0x00000001, ///<Disable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,DblrdyVal> dblrdy{}; namespace DblrdyValC{ constexpr Register::FieldValue<decltype(dblrdy)::Type,DblrdyVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(dblrdy)::Type,DblrdyVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(dblrdy)::Type,DblrdyVal::clear> clear{}; } ///Write '1' to Clear interrupt on EVENTS_STOPPED event enum class StoppedVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled clear=0x00000001, ///<Disable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,StoppedVal> stopped{}; namespace StoppedValC{ constexpr Register::FieldValue<decltype(stopped)::Type,StoppedVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(stopped)::Type,StoppedVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(stopped)::Type,StoppedVal::clear> clear{}; } } namespace Noneenable{ ///<Enable the quadrature decoder using Addr = Register::Address<0x40012500,0xfffffffe,0,unsigned>; ///Enable or disable the quadrature decoder enum class EnableVal { disabled=0x00000000, ///<Disable enabled=0x00000001, ///<Enable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,EnableVal> enable{}; namespace EnableValC{ constexpr Register::FieldValue<decltype(enable)::Type,EnableVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(enable)::Type,EnableVal::enabled> enabled{}; } } namespace Noneledpol{ ///<LED output pin polarity using Addr = Register::Address<0x40012504,0xfffffffe,0,unsigned>; ///LED output pin polarity enum class LedpolVal { activelow=0x00000000, ///<Led active on output pin low activehigh=0x00000001, ///<Led active on output pin high }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,LedpolVal> ledpol{}; namespace LedpolValC{ constexpr Register::FieldValue<decltype(ledpol)::Type,LedpolVal::activelow> activelow{}; constexpr Register::FieldValue<decltype(ledpol)::Type,LedpolVal::activehigh> activehigh{}; } } namespace Nonesampleper{ ///<Sample period using Addr = Register::Address<0x40012508,0xfffffff0,0,unsigned>; ///Sample period. The SAMPLE register will be updated for every new sample enum class SampleperVal { v128us=0x00000000, ///<128 us v256us=0x00000001, ///<256 us v512us=0x00000002, ///<512 us v1024us=0x00000003, ///<1024 us v2048us=0x00000004, ///<2048 us v4096us=0x00000005, ///<4096 us v8192us=0x00000006, ///<8192 us v16384us=0x00000007, ///<16384 us v32ms=0x00000008, ///<32768 us v65ms=0x00000009, ///<65536 us v131ms=0x0000000a, ///<131072 us }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,SampleperVal> sampleper{}; namespace SampleperValC{ constexpr Register::FieldValue<decltype(sampleper)::Type,SampleperVal::v128us> v128us{}; constexpr Register::FieldValue<decltype(sampleper)::Type,SampleperVal::v256us> v256us{}; constexpr Register::FieldValue<decltype(sampleper)::Type,SampleperVal::v512us> v512us{}; constexpr Register::FieldValue<decltype(sampleper)::Type,SampleperVal::v1024us> v1024us{}; constexpr Register::FieldValue<decltype(sampleper)::Type,SampleperVal::v2048us> v2048us{}; constexpr Register::FieldValue<decltype(sampleper)::Type,SampleperVal::v4096us> v4096us{}; constexpr Register::FieldValue<decltype(sampleper)::Type,SampleperVal::v8192us> v8192us{}; constexpr Register::FieldValue<decltype(sampleper)::Type,SampleperVal::v16384us> v16384us{}; constexpr Register::FieldValue<decltype(sampleper)::Type,SampleperVal::v32ms> v32ms{}; constexpr Register::FieldValue<decltype(sampleper)::Type,SampleperVal::v65ms> v65ms{}; constexpr Register::FieldValue<decltype(sampleper)::Type,SampleperVal::v131ms> v131ms{}; } } namespace Nonesample{ ///<Motion sample value using Addr = Register::Address<0x4001250c,0x00000000,0,unsigned>; ///Last motion sample constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> sample{}; } namespace Nonereportper{ ///<Number of samples to be taken before REPORTRDY and DBLRDY events can be generated using Addr = Register::Address<0x40012510,0xfffffff0,0,unsigned>; ///Specifies the number of samples to be accumulated in the ACC register before the REPORTRDY and DBLRDY events can be generated enum class ReportperVal { v10smpl=0x00000000, ///<10 samples / report v40smpl=0x00000001, ///<40 samples / report v80smpl=0x00000002, ///<80 samples / report v120smpl=0x00000003, ///<120 samples / report v160smpl=0x00000004, ///<160 samples / report v200smpl=0x00000005, ///<200 samples / report v240smpl=0x00000006, ///<240 samples / report v280smpl=0x00000007, ///<280 samples / report v1smpl=0x00000008, ///<1 sample / report }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,ReportperVal> reportper{}; namespace ReportperValC{ constexpr Register::FieldValue<decltype(reportper)::Type,ReportperVal::v10smpl> v10smpl{}; constexpr Register::FieldValue<decltype(reportper)::Type,ReportperVal::v40smpl> v40smpl{}; constexpr Register::FieldValue<decltype(reportper)::Type,ReportperVal::v80smpl> v80smpl{}; constexpr Register::FieldValue<decltype(reportper)::Type,ReportperVal::v120smpl> v120smpl{}; constexpr Register::FieldValue<decltype(reportper)::Type,ReportperVal::v160smpl> v160smpl{}; constexpr Register::FieldValue<decltype(reportper)::Type,ReportperVal::v200smpl> v200smpl{}; constexpr Register::FieldValue<decltype(reportper)::Type,ReportperVal::v240smpl> v240smpl{}; constexpr Register::FieldValue<decltype(reportper)::Type,ReportperVal::v280smpl> v280smpl{}; constexpr Register::FieldValue<decltype(reportper)::Type,ReportperVal::v1smpl> v1smpl{}; } } namespace Noneacc{ ///<Register accumulating the valid transitions using Addr = Register::Address<0x40012514,0x00000000,0,unsigned>; ///Register accumulating all valid samples (not double transition) read from the SAMPLE register constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> acc{}; } namespace Noneaccread{ ///<Snapshot of the ACC register, updated by the READCLRACC or RDCLRACC task using Addr = Register::Address<0x40012518,0x00000000,0,unsigned>; ///Snapshot of the ACC register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> accread{}; } namespace Nonedbfen{ ///<Enable input debounce filters using Addr = Register::Address<0x40012528,0xfffffffe,0,unsigned>; ///Enable input debounce filters enum class DbfenVal { disabled=0x00000000, ///<Debounce input filters disabled enabled=0x00000001, ///<Debounce input filters enabled }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,DbfenVal> dbfen{}; namespace DbfenValC{ constexpr Register::FieldValue<decltype(dbfen)::Type,DbfenVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(dbfen)::Type,DbfenVal::enabled> enabled{}; } } namespace Noneledpre{ ///<Time period the LED is switched ON prior to sampling using Addr = Register::Address<0x40012540,0xfffffe00,0,unsigned>; ///Period in us the LED is switched on prior to sampling constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,0),Register::ReadWriteAccess,unsigned> ledpre{}; } namespace Noneaccdbl{ ///<Register accumulating the number of detected double transitions using Addr = Register::Address<0x40012544,0xfffffff0,0,unsigned>; ///Register accumulating the number of detected double or illegal transitions. ( SAMPLE = 2 ). constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> accdbl{}; } namespace Noneaccdblread{ ///<Snapshot of the ACCDBL, updated by the READCLRACC or RDCLRDBL task using Addr = Register::Address<0x40012548,0xfffffff0,0,unsigned>; ///Snapshot of the ACCDBL register. This field is updated when the READCLRACC or RDCLRDBL task is triggered. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> accdblread{}; } }
[ "holmes.odin@gmail.com" ]
holmes.odin@gmail.com
9b10d649a3732efab5064baba852239776663a86
11ef4bbb8086ba3b9678a2037d0c28baaf8c010e
/Source Code/server/binaries/chromium/gen/headless/public/devtools/internal/type_conversions_page.h
e535f9b5905fa5898e6d3a4717bed4371fdbd59a
[]
no_license
lineCode/wasmview.github.io
8f845ec6ba8a1ec85272d734efc80d2416a6e15b
eac4c69ea1cf0e9af9da5a500219236470541f9b
refs/heads/master
2020-09-22T21:05:53.766548
2019-08-24T05:34:04
2019-08-24T05:34:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
72,947
h
// This file is generated // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef HEADLESS_PUBLIC_DEVTOOLS_INTERNAL_TYPE_CONVERSIONS_PAGE_H_ #define HEADLESS_PUBLIC_DEVTOOLS_INTERNAL_TYPE_CONVERSIONS_PAGE_H_ #include "headless/public/devtools/domains/types_page.h" #include "headless/public/internal/value_conversions.h" namespace headless { namespace internal { template <> struct FromValue<page::Frame> { static std::unique_ptr<page::Frame> Parse(const base::Value& value, ErrorReporter* errors) { return page::Frame::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::Frame& value) { return value.Serialize(); } template <> struct FromValue<page::FrameResource> { static std::unique_ptr<page::FrameResource> Parse(const base::Value& value, ErrorReporter* errors) { return page::FrameResource::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FrameResource& value) { return value.Serialize(); } template <> struct FromValue<page::FrameResourceTree> { static std::unique_ptr<page::FrameResourceTree> Parse(const base::Value& value, ErrorReporter* errors) { return page::FrameResourceTree::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FrameResourceTree& value) { return value.Serialize(); } template <> struct FromValue<page::FrameTree> { static std::unique_ptr<page::FrameTree> Parse(const base::Value& value, ErrorReporter* errors) { return page::FrameTree::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FrameTree& value) { return value.Serialize(); } template <> struct FromValue<page::TransitionType> { static page::TransitionType Parse(const base::Value& value, ErrorReporter* errors) { if (!value.is_string()) { errors->AddError("string enum value expected"); return page::TransitionType::LINK; } if (value.GetString() == "link") return page::TransitionType::LINK; if (value.GetString() == "typed") return page::TransitionType::TYPED; if (value.GetString() == "address_bar") return page::TransitionType::ADDRESS_BAR; if (value.GetString() == "auto_bookmark") return page::TransitionType::AUTO_BOOKMARK; if (value.GetString() == "auto_subframe") return page::TransitionType::AUTO_SUBFRAME; if (value.GetString() == "manual_subframe") return page::TransitionType::MANUAL_SUBFRAME; if (value.GetString() == "generated") return page::TransitionType::GENERATED; if (value.GetString() == "auto_toplevel") return page::TransitionType::AUTO_TOPLEVEL; if (value.GetString() == "form_submit") return page::TransitionType::FORM_SUBMIT; if (value.GetString() == "reload") return page::TransitionType::RELOAD; if (value.GetString() == "keyword") return page::TransitionType::KEYWORD; if (value.GetString() == "keyword_generated") return page::TransitionType::KEYWORD_GENERATED; if (value.GetString() == "other") return page::TransitionType::OTHER; errors->AddError("invalid enum value"); return page::TransitionType::LINK; } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::TransitionType& value) { switch (value) { case page::TransitionType::LINK: return std::make_unique<base::Value>("link"); case page::TransitionType::TYPED: return std::make_unique<base::Value>("typed"); case page::TransitionType::ADDRESS_BAR: return std::make_unique<base::Value>("address_bar"); case page::TransitionType::AUTO_BOOKMARK: return std::make_unique<base::Value>("auto_bookmark"); case page::TransitionType::AUTO_SUBFRAME: return std::make_unique<base::Value>("auto_subframe"); case page::TransitionType::MANUAL_SUBFRAME: return std::make_unique<base::Value>("manual_subframe"); case page::TransitionType::GENERATED: return std::make_unique<base::Value>("generated"); case page::TransitionType::AUTO_TOPLEVEL: return std::make_unique<base::Value>("auto_toplevel"); case page::TransitionType::FORM_SUBMIT: return std::make_unique<base::Value>("form_submit"); case page::TransitionType::RELOAD: return std::make_unique<base::Value>("reload"); case page::TransitionType::KEYWORD: return std::make_unique<base::Value>("keyword"); case page::TransitionType::KEYWORD_GENERATED: return std::make_unique<base::Value>("keyword_generated"); case page::TransitionType::OTHER: return std::make_unique<base::Value>("other"); }; NOTREACHED(); return nullptr; } template <> struct FromValue<page::NavigationEntry> { static std::unique_ptr<page::NavigationEntry> Parse(const base::Value& value, ErrorReporter* errors) { return page::NavigationEntry::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::NavigationEntry& value) { return value.Serialize(); } template <> struct FromValue<page::ScreencastFrameMetadata> { static std::unique_ptr<page::ScreencastFrameMetadata> Parse(const base::Value& value, ErrorReporter* errors) { return page::ScreencastFrameMetadata::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ScreencastFrameMetadata& value) { return value.Serialize(); } template <> struct FromValue<page::DialogType> { static page::DialogType Parse(const base::Value& value, ErrorReporter* errors) { if (!value.is_string()) { errors->AddError("string enum value expected"); return page::DialogType::ALERT; } if (value.GetString() == "alert") return page::DialogType::ALERT; if (value.GetString() == "confirm") return page::DialogType::CONFIRM; if (value.GetString() == "prompt") return page::DialogType::PROMPT; if (value.GetString() == "beforeunload") return page::DialogType::BEFOREUNLOAD; errors->AddError("invalid enum value"); return page::DialogType::ALERT; } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::DialogType& value) { switch (value) { case page::DialogType::ALERT: return std::make_unique<base::Value>("alert"); case page::DialogType::CONFIRM: return std::make_unique<base::Value>("confirm"); case page::DialogType::PROMPT: return std::make_unique<base::Value>("prompt"); case page::DialogType::BEFOREUNLOAD: return std::make_unique<base::Value>("beforeunload"); }; NOTREACHED(); return nullptr; } template <> struct FromValue<page::AppManifestError> { static std::unique_ptr<page::AppManifestError> Parse(const base::Value& value, ErrorReporter* errors) { return page::AppManifestError::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::AppManifestError& value) { return value.Serialize(); } template <> struct FromValue<page::LayoutViewport> { static std::unique_ptr<page::LayoutViewport> Parse(const base::Value& value, ErrorReporter* errors) { return page::LayoutViewport::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::LayoutViewport& value) { return value.Serialize(); } template <> struct FromValue<page::VisualViewport> { static std::unique_ptr<page::VisualViewport> Parse(const base::Value& value, ErrorReporter* errors) { return page::VisualViewport::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::VisualViewport& value) { return value.Serialize(); } template <> struct FromValue<page::Viewport> { static std::unique_ptr<page::Viewport> Parse(const base::Value& value, ErrorReporter* errors) { return page::Viewport::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::Viewport& value) { return value.Serialize(); } template <> struct FromValue<page::FontFamilies> { static std::unique_ptr<page::FontFamilies> Parse(const base::Value& value, ErrorReporter* errors) { return page::FontFamilies::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FontFamilies& value) { return value.Serialize(); } template <> struct FromValue<page::FontSizes> { static std::unique_ptr<page::FontSizes> Parse(const base::Value& value, ErrorReporter* errors) { return page::FontSizes::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FontSizes& value) { return value.Serialize(); } template <> struct FromValue<page::ClientNavigationReason> { static page::ClientNavigationReason Parse(const base::Value& value, ErrorReporter* errors) { if (!value.is_string()) { errors->AddError("string enum value expected"); return page::ClientNavigationReason::FORM_SUBMISSION_GET; } if (value.GetString() == "formSubmissionGet") return page::ClientNavigationReason::FORM_SUBMISSION_GET; if (value.GetString() == "formSubmissionPost") return page::ClientNavigationReason::FORM_SUBMISSION_POST; if (value.GetString() == "httpHeaderRefresh") return page::ClientNavigationReason::HTTP_HEADER_REFRESH; if (value.GetString() == "scriptInitiated") return page::ClientNavigationReason::SCRIPT_INITIATED; if (value.GetString() == "metaTagRefresh") return page::ClientNavigationReason::META_TAG_REFRESH; if (value.GetString() == "pageBlockInterstitial") return page::ClientNavigationReason::PAGE_BLOCK_INTERSTITIAL; if (value.GetString() == "reload") return page::ClientNavigationReason::RELOAD; errors->AddError("invalid enum value"); return page::ClientNavigationReason::FORM_SUBMISSION_GET; } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ClientNavigationReason& value) { switch (value) { case page::ClientNavigationReason::FORM_SUBMISSION_GET: return std::make_unique<base::Value>("formSubmissionGet"); case page::ClientNavigationReason::FORM_SUBMISSION_POST: return std::make_unique<base::Value>("formSubmissionPost"); case page::ClientNavigationReason::HTTP_HEADER_REFRESH: return std::make_unique<base::Value>("httpHeaderRefresh"); case page::ClientNavigationReason::SCRIPT_INITIATED: return std::make_unique<base::Value>("scriptInitiated"); case page::ClientNavigationReason::META_TAG_REFRESH: return std::make_unique<base::Value>("metaTagRefresh"); case page::ClientNavigationReason::PAGE_BLOCK_INTERSTITIAL: return std::make_unique<base::Value>("pageBlockInterstitial"); case page::ClientNavigationReason::RELOAD: return std::make_unique<base::Value>("reload"); }; NOTREACHED(); return nullptr; } template <> struct FromValue<page::AddScriptToEvaluateOnLoadParams> { static std::unique_ptr<page::AddScriptToEvaluateOnLoadParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::AddScriptToEvaluateOnLoadParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::AddScriptToEvaluateOnLoadParams& value) { return value.Serialize(); } template <> struct FromValue<page::AddScriptToEvaluateOnLoadResult> { static std::unique_ptr<page::AddScriptToEvaluateOnLoadResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::AddScriptToEvaluateOnLoadResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::AddScriptToEvaluateOnLoadResult& value) { return value.Serialize(); } template <> struct FromValue<page::AddScriptToEvaluateOnNewDocumentParams> { static std::unique_ptr<page::AddScriptToEvaluateOnNewDocumentParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::AddScriptToEvaluateOnNewDocumentParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::AddScriptToEvaluateOnNewDocumentParams& value) { return value.Serialize(); } template <> struct FromValue<page::AddScriptToEvaluateOnNewDocumentResult> { static std::unique_ptr<page::AddScriptToEvaluateOnNewDocumentResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::AddScriptToEvaluateOnNewDocumentResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::AddScriptToEvaluateOnNewDocumentResult& value) { return value.Serialize(); } template <> struct FromValue<page::BringToFrontParams> { static std::unique_ptr<page::BringToFrontParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::BringToFrontParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::BringToFrontParams& value) { return value.Serialize(); } template <> struct FromValue<page::BringToFrontResult> { static std::unique_ptr<page::BringToFrontResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::BringToFrontResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::BringToFrontResult& value) { return value.Serialize(); } template <> struct FromValue<page::CaptureScreenshotFormat> { static page::CaptureScreenshotFormat Parse(const base::Value& value, ErrorReporter* errors) { if (!value.is_string()) { errors->AddError("string enum value expected"); return page::CaptureScreenshotFormat::JPEG; } if (value.GetString() == "jpeg") return page::CaptureScreenshotFormat::JPEG; if (value.GetString() == "png") return page::CaptureScreenshotFormat::PNG; errors->AddError("invalid enum value"); return page::CaptureScreenshotFormat::JPEG; } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::CaptureScreenshotFormat& value) { switch (value) { case page::CaptureScreenshotFormat::JPEG: return std::make_unique<base::Value>("jpeg"); case page::CaptureScreenshotFormat::PNG: return std::make_unique<base::Value>("png"); }; NOTREACHED(); return nullptr; } template <> struct FromValue<page::CaptureScreenshotParams> { static std::unique_ptr<page::CaptureScreenshotParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::CaptureScreenshotParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::CaptureScreenshotParams& value) { return value.Serialize(); } template <> struct FromValue<page::CaptureScreenshotResult> { static std::unique_ptr<page::CaptureScreenshotResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::CaptureScreenshotResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::CaptureScreenshotResult& value) { return value.Serialize(); } template <> struct FromValue<page::CaptureSnapshotFormat> { static page::CaptureSnapshotFormat Parse(const base::Value& value, ErrorReporter* errors) { if (!value.is_string()) { errors->AddError("string enum value expected"); return page::CaptureSnapshotFormat::MHTML; } if (value.GetString() == "mhtml") return page::CaptureSnapshotFormat::MHTML; errors->AddError("invalid enum value"); return page::CaptureSnapshotFormat::MHTML; } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::CaptureSnapshotFormat& value) { switch (value) { case page::CaptureSnapshotFormat::MHTML: return std::make_unique<base::Value>("mhtml"); }; NOTREACHED(); return nullptr; } template <> struct FromValue<page::CaptureSnapshotParams> { static std::unique_ptr<page::CaptureSnapshotParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::CaptureSnapshotParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::CaptureSnapshotParams& value) { return value.Serialize(); } template <> struct FromValue<page::CaptureSnapshotResult> { static std::unique_ptr<page::CaptureSnapshotResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::CaptureSnapshotResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::CaptureSnapshotResult& value) { return value.Serialize(); } template <> struct FromValue<page::ClearDeviceMetricsOverrideParams> { static std::unique_ptr<page::ClearDeviceMetricsOverrideParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::ClearDeviceMetricsOverrideParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ClearDeviceMetricsOverrideParams& value) { return value.Serialize(); } template <> struct FromValue<page::ClearDeviceMetricsOverrideResult> { static std::unique_ptr<page::ClearDeviceMetricsOverrideResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::ClearDeviceMetricsOverrideResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ClearDeviceMetricsOverrideResult& value) { return value.Serialize(); } template <> struct FromValue<page::ClearDeviceOrientationOverrideParams> { static std::unique_ptr<page::ClearDeviceOrientationOverrideParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::ClearDeviceOrientationOverrideParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ClearDeviceOrientationOverrideParams& value) { return value.Serialize(); } template <> struct FromValue<page::ClearDeviceOrientationOverrideResult> { static std::unique_ptr<page::ClearDeviceOrientationOverrideResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::ClearDeviceOrientationOverrideResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ClearDeviceOrientationOverrideResult& value) { return value.Serialize(); } template <> struct FromValue<page::ClearGeolocationOverrideParams> { static std::unique_ptr<page::ClearGeolocationOverrideParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::ClearGeolocationOverrideParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ClearGeolocationOverrideParams& value) { return value.Serialize(); } template <> struct FromValue<page::ClearGeolocationOverrideResult> { static std::unique_ptr<page::ClearGeolocationOverrideResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::ClearGeolocationOverrideResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ClearGeolocationOverrideResult& value) { return value.Serialize(); } template <> struct FromValue<page::CreateIsolatedWorldParams> { static std::unique_ptr<page::CreateIsolatedWorldParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::CreateIsolatedWorldParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::CreateIsolatedWorldParams& value) { return value.Serialize(); } template <> struct FromValue<page::CreateIsolatedWorldResult> { static std::unique_ptr<page::CreateIsolatedWorldResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::CreateIsolatedWorldResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::CreateIsolatedWorldResult& value) { return value.Serialize(); } template <> struct FromValue<page::DeleteCookieParams> { static std::unique_ptr<page::DeleteCookieParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::DeleteCookieParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::DeleteCookieParams& value) { return value.Serialize(); } template <> struct FromValue<page::DeleteCookieResult> { static std::unique_ptr<page::DeleteCookieResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::DeleteCookieResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::DeleteCookieResult& value) { return value.Serialize(); } template <> struct FromValue<page::DisableParams> { static std::unique_ptr<page::DisableParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::DisableParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::DisableParams& value) { return value.Serialize(); } template <> struct FromValue<page::DisableResult> { static std::unique_ptr<page::DisableResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::DisableResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::DisableResult& value) { return value.Serialize(); } template <> struct FromValue<page::EnableParams> { static std::unique_ptr<page::EnableParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::EnableParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::EnableParams& value) { return value.Serialize(); } template <> struct FromValue<page::EnableResult> { static std::unique_ptr<page::EnableResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::EnableResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::EnableResult& value) { return value.Serialize(); } template <> struct FromValue<page::GetAppManifestParams> { static std::unique_ptr<page::GetAppManifestParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetAppManifestParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetAppManifestParams& value) { return value.Serialize(); } template <> struct FromValue<page::GetAppManifestResult> { static std::unique_ptr<page::GetAppManifestResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetAppManifestResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetAppManifestResult& value) { return value.Serialize(); } template <> struct FromValue<page::GetInstallabilityErrorsParams> { static std::unique_ptr<page::GetInstallabilityErrorsParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetInstallabilityErrorsParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetInstallabilityErrorsParams& value) { return value.Serialize(); } template <> struct FromValue<page::GetInstallabilityErrorsResult> { static std::unique_ptr<page::GetInstallabilityErrorsResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetInstallabilityErrorsResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetInstallabilityErrorsResult& value) { return value.Serialize(); } template <> struct FromValue<page::GetCookiesParams> { static std::unique_ptr<page::GetCookiesParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetCookiesParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetCookiesParams& value) { return value.Serialize(); } template <> struct FromValue<page::GetCookiesResult> { static std::unique_ptr<page::GetCookiesResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetCookiesResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetCookiesResult& value) { return value.Serialize(); } template <> struct FromValue<page::GetFrameTreeParams> { static std::unique_ptr<page::GetFrameTreeParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetFrameTreeParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetFrameTreeParams& value) { return value.Serialize(); } template <> struct FromValue<page::GetFrameTreeResult> { static std::unique_ptr<page::GetFrameTreeResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetFrameTreeResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetFrameTreeResult& value) { return value.Serialize(); } template <> struct FromValue<page::GetLayoutMetricsParams> { static std::unique_ptr<page::GetLayoutMetricsParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetLayoutMetricsParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetLayoutMetricsParams& value) { return value.Serialize(); } template <> struct FromValue<page::GetLayoutMetricsResult> { static std::unique_ptr<page::GetLayoutMetricsResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetLayoutMetricsResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetLayoutMetricsResult& value) { return value.Serialize(); } template <> struct FromValue<page::GetNavigationHistoryParams> { static std::unique_ptr<page::GetNavigationHistoryParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetNavigationHistoryParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetNavigationHistoryParams& value) { return value.Serialize(); } template <> struct FromValue<page::GetNavigationHistoryResult> { static std::unique_ptr<page::GetNavigationHistoryResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetNavigationHistoryResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetNavigationHistoryResult& value) { return value.Serialize(); } template <> struct FromValue<page::ResetNavigationHistoryParams> { static std::unique_ptr<page::ResetNavigationHistoryParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::ResetNavigationHistoryParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ResetNavigationHistoryParams& value) { return value.Serialize(); } template <> struct FromValue<page::ResetNavigationHistoryResult> { static std::unique_ptr<page::ResetNavigationHistoryResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::ResetNavigationHistoryResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ResetNavigationHistoryResult& value) { return value.Serialize(); } template <> struct FromValue<page::GetResourceContentParams> { static std::unique_ptr<page::GetResourceContentParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetResourceContentParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetResourceContentParams& value) { return value.Serialize(); } template <> struct FromValue<page::GetResourceContentResult> { static std::unique_ptr<page::GetResourceContentResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetResourceContentResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetResourceContentResult& value) { return value.Serialize(); } template <> struct FromValue<page::GetResourceTreeParams> { static std::unique_ptr<page::GetResourceTreeParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetResourceTreeParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetResourceTreeParams& value) { return value.Serialize(); } template <> struct FromValue<page::GetResourceTreeResult> { static std::unique_ptr<page::GetResourceTreeResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::GetResourceTreeResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GetResourceTreeResult& value) { return value.Serialize(); } template <> struct FromValue<page::HandleJavaScriptDialogParams> { static std::unique_ptr<page::HandleJavaScriptDialogParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::HandleJavaScriptDialogParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::HandleJavaScriptDialogParams& value) { return value.Serialize(); } template <> struct FromValue<page::HandleJavaScriptDialogResult> { static std::unique_ptr<page::HandleJavaScriptDialogResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::HandleJavaScriptDialogResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::HandleJavaScriptDialogResult& value) { return value.Serialize(); } template <> struct FromValue<page::NavigateParams> { static std::unique_ptr<page::NavigateParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::NavigateParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::NavigateParams& value) { return value.Serialize(); } template <> struct FromValue<page::NavigateResult> { static std::unique_ptr<page::NavigateResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::NavigateResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::NavigateResult& value) { return value.Serialize(); } template <> struct FromValue<page::NavigateToHistoryEntryParams> { static std::unique_ptr<page::NavigateToHistoryEntryParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::NavigateToHistoryEntryParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::NavigateToHistoryEntryParams& value) { return value.Serialize(); } template <> struct FromValue<page::NavigateToHistoryEntryResult> { static std::unique_ptr<page::NavigateToHistoryEntryResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::NavigateToHistoryEntryResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::NavigateToHistoryEntryResult& value) { return value.Serialize(); } template <> struct FromValue<page::PrintToPDFTransferMode> { static page::PrintToPDFTransferMode Parse(const base::Value& value, ErrorReporter* errors) { if (!value.is_string()) { errors->AddError("string enum value expected"); return page::PrintToPDFTransferMode::RETURN_AS_BASE64; } if (value.GetString() == "ReturnAsBase64") return page::PrintToPDFTransferMode::RETURN_AS_BASE64; if (value.GetString() == "ReturnAsStream") return page::PrintToPDFTransferMode::RETURN_AS_STREAM; errors->AddError("invalid enum value"); return page::PrintToPDFTransferMode::RETURN_AS_BASE64; } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::PrintToPDFTransferMode& value) { switch (value) { case page::PrintToPDFTransferMode::RETURN_AS_BASE64: return std::make_unique<base::Value>("ReturnAsBase64"); case page::PrintToPDFTransferMode::RETURN_AS_STREAM: return std::make_unique<base::Value>("ReturnAsStream"); }; NOTREACHED(); return nullptr; } template <> struct FromValue<page::PrintToPDFParams> { static std::unique_ptr<page::PrintToPDFParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::PrintToPDFParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::PrintToPDFParams& value) { return value.Serialize(); } template <> struct FromValue<page::PrintToPDFResult> { static std::unique_ptr<page::PrintToPDFResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::PrintToPDFResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::PrintToPDFResult& value) { return value.Serialize(); } template <> struct FromValue<page::ReloadParams> { static std::unique_ptr<page::ReloadParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::ReloadParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ReloadParams& value) { return value.Serialize(); } template <> struct FromValue<page::ReloadResult> { static std::unique_ptr<page::ReloadResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::ReloadResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ReloadResult& value) { return value.Serialize(); } template <> struct FromValue<page::RemoveScriptToEvaluateOnLoadParams> { static std::unique_ptr<page::RemoveScriptToEvaluateOnLoadParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::RemoveScriptToEvaluateOnLoadParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::RemoveScriptToEvaluateOnLoadParams& value) { return value.Serialize(); } template <> struct FromValue<page::RemoveScriptToEvaluateOnLoadResult> { static std::unique_ptr<page::RemoveScriptToEvaluateOnLoadResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::RemoveScriptToEvaluateOnLoadResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::RemoveScriptToEvaluateOnLoadResult& value) { return value.Serialize(); } template <> struct FromValue<page::RemoveScriptToEvaluateOnNewDocumentParams> { static std::unique_ptr<page::RemoveScriptToEvaluateOnNewDocumentParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::RemoveScriptToEvaluateOnNewDocumentParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::RemoveScriptToEvaluateOnNewDocumentParams& value) { return value.Serialize(); } template <> struct FromValue<page::RemoveScriptToEvaluateOnNewDocumentResult> { static std::unique_ptr<page::RemoveScriptToEvaluateOnNewDocumentResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::RemoveScriptToEvaluateOnNewDocumentResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::RemoveScriptToEvaluateOnNewDocumentResult& value) { return value.Serialize(); } template <> struct FromValue<page::ScreencastFrameAckParams> { static std::unique_ptr<page::ScreencastFrameAckParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::ScreencastFrameAckParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ScreencastFrameAckParams& value) { return value.Serialize(); } template <> struct FromValue<page::ScreencastFrameAckResult> { static std::unique_ptr<page::ScreencastFrameAckResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::ScreencastFrameAckResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ScreencastFrameAckResult& value) { return value.Serialize(); } template <> struct FromValue<page::SearchInResourceParams> { static std::unique_ptr<page::SearchInResourceParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SearchInResourceParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SearchInResourceParams& value) { return value.Serialize(); } template <> struct FromValue<page::SearchInResourceResult> { static std::unique_ptr<page::SearchInResourceResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SearchInResourceResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SearchInResourceResult& value) { return value.Serialize(); } template <> struct FromValue<page::SetAdBlockingEnabledParams> { static std::unique_ptr<page::SetAdBlockingEnabledParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetAdBlockingEnabledParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetAdBlockingEnabledParams& value) { return value.Serialize(); } template <> struct FromValue<page::SetAdBlockingEnabledResult> { static std::unique_ptr<page::SetAdBlockingEnabledResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetAdBlockingEnabledResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetAdBlockingEnabledResult& value) { return value.Serialize(); } template <> struct FromValue<page::SetBypassCSPParams> { static std::unique_ptr<page::SetBypassCSPParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetBypassCSPParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetBypassCSPParams& value) { return value.Serialize(); } template <> struct FromValue<page::SetBypassCSPResult> { static std::unique_ptr<page::SetBypassCSPResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetBypassCSPResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetBypassCSPResult& value) { return value.Serialize(); } template <> struct FromValue<page::SetDeviceMetricsOverrideParams> { static std::unique_ptr<page::SetDeviceMetricsOverrideParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetDeviceMetricsOverrideParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetDeviceMetricsOverrideParams& value) { return value.Serialize(); } template <> struct FromValue<page::SetDeviceMetricsOverrideResult> { static std::unique_ptr<page::SetDeviceMetricsOverrideResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetDeviceMetricsOverrideResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetDeviceMetricsOverrideResult& value) { return value.Serialize(); } template <> struct FromValue<page::SetDeviceOrientationOverrideParams> { static std::unique_ptr<page::SetDeviceOrientationOverrideParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetDeviceOrientationOverrideParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetDeviceOrientationOverrideParams& value) { return value.Serialize(); } template <> struct FromValue<page::SetDeviceOrientationOverrideResult> { static std::unique_ptr<page::SetDeviceOrientationOverrideResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetDeviceOrientationOverrideResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetDeviceOrientationOverrideResult& value) { return value.Serialize(); } template <> struct FromValue<page::SetFontFamiliesParams> { static std::unique_ptr<page::SetFontFamiliesParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetFontFamiliesParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetFontFamiliesParams& value) { return value.Serialize(); } template <> struct FromValue<page::SetFontFamiliesResult> { static std::unique_ptr<page::SetFontFamiliesResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetFontFamiliesResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetFontFamiliesResult& value) { return value.Serialize(); } template <> struct FromValue<page::SetFontSizesParams> { static std::unique_ptr<page::SetFontSizesParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetFontSizesParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetFontSizesParams& value) { return value.Serialize(); } template <> struct FromValue<page::SetFontSizesResult> { static std::unique_ptr<page::SetFontSizesResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetFontSizesResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetFontSizesResult& value) { return value.Serialize(); } template <> struct FromValue<page::SetDocumentContentParams> { static std::unique_ptr<page::SetDocumentContentParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetDocumentContentParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetDocumentContentParams& value) { return value.Serialize(); } template <> struct FromValue<page::SetDocumentContentResult> { static std::unique_ptr<page::SetDocumentContentResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetDocumentContentResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetDocumentContentResult& value) { return value.Serialize(); } template <> struct FromValue<page::SetDownloadBehaviorBehavior> { static page::SetDownloadBehaviorBehavior Parse(const base::Value& value, ErrorReporter* errors) { if (!value.is_string()) { errors->AddError("string enum value expected"); return page::SetDownloadBehaviorBehavior::DENY; } if (value.GetString() == "deny") return page::SetDownloadBehaviorBehavior::DENY; if (value.GetString() == "allow") return page::SetDownloadBehaviorBehavior::ALLOW; if (value.GetString() == "default") return page::SetDownloadBehaviorBehavior::DEFAULT; errors->AddError("invalid enum value"); return page::SetDownloadBehaviorBehavior::DENY; } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetDownloadBehaviorBehavior& value) { switch (value) { case page::SetDownloadBehaviorBehavior::DENY: return std::make_unique<base::Value>("deny"); case page::SetDownloadBehaviorBehavior::ALLOW: return std::make_unique<base::Value>("allow"); case page::SetDownloadBehaviorBehavior::DEFAULT: return std::make_unique<base::Value>("default"); }; NOTREACHED(); return nullptr; } template <> struct FromValue<page::SetDownloadBehaviorParams> { static std::unique_ptr<page::SetDownloadBehaviorParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetDownloadBehaviorParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetDownloadBehaviorParams& value) { return value.Serialize(); } template <> struct FromValue<page::SetDownloadBehaviorResult> { static std::unique_ptr<page::SetDownloadBehaviorResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetDownloadBehaviorResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetDownloadBehaviorResult& value) { return value.Serialize(); } template <> struct FromValue<page::SetGeolocationOverrideParams> { static std::unique_ptr<page::SetGeolocationOverrideParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetGeolocationOverrideParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetGeolocationOverrideParams& value) { return value.Serialize(); } template <> struct FromValue<page::SetGeolocationOverrideResult> { static std::unique_ptr<page::SetGeolocationOverrideResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetGeolocationOverrideResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetGeolocationOverrideResult& value) { return value.Serialize(); } template <> struct FromValue<page::SetLifecycleEventsEnabledParams> { static std::unique_ptr<page::SetLifecycleEventsEnabledParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetLifecycleEventsEnabledParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetLifecycleEventsEnabledParams& value) { return value.Serialize(); } template <> struct FromValue<page::SetLifecycleEventsEnabledResult> { static std::unique_ptr<page::SetLifecycleEventsEnabledResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetLifecycleEventsEnabledResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetLifecycleEventsEnabledResult& value) { return value.Serialize(); } template <> struct FromValue<page::SetTouchEmulationEnabledConfiguration> { static page::SetTouchEmulationEnabledConfiguration Parse(const base::Value& value, ErrorReporter* errors) { if (!value.is_string()) { errors->AddError("string enum value expected"); return page::SetTouchEmulationEnabledConfiguration::MOBILE; } if (value.GetString() == "mobile") return page::SetTouchEmulationEnabledConfiguration::MOBILE; if (value.GetString() == "desktop") return page::SetTouchEmulationEnabledConfiguration::DESKTOP; errors->AddError("invalid enum value"); return page::SetTouchEmulationEnabledConfiguration::MOBILE; } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetTouchEmulationEnabledConfiguration& value) { switch (value) { case page::SetTouchEmulationEnabledConfiguration::MOBILE: return std::make_unique<base::Value>("mobile"); case page::SetTouchEmulationEnabledConfiguration::DESKTOP: return std::make_unique<base::Value>("desktop"); }; NOTREACHED(); return nullptr; } template <> struct FromValue<page::SetTouchEmulationEnabledParams> { static std::unique_ptr<page::SetTouchEmulationEnabledParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetTouchEmulationEnabledParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetTouchEmulationEnabledParams& value) { return value.Serialize(); } template <> struct FromValue<page::SetTouchEmulationEnabledResult> { static std::unique_ptr<page::SetTouchEmulationEnabledResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetTouchEmulationEnabledResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetTouchEmulationEnabledResult& value) { return value.Serialize(); } template <> struct FromValue<page::StartScreencastFormat> { static page::StartScreencastFormat Parse(const base::Value& value, ErrorReporter* errors) { if (!value.is_string()) { errors->AddError("string enum value expected"); return page::StartScreencastFormat::JPEG; } if (value.GetString() == "jpeg") return page::StartScreencastFormat::JPEG; if (value.GetString() == "png") return page::StartScreencastFormat::PNG; errors->AddError("invalid enum value"); return page::StartScreencastFormat::JPEG; } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::StartScreencastFormat& value) { switch (value) { case page::StartScreencastFormat::JPEG: return std::make_unique<base::Value>("jpeg"); case page::StartScreencastFormat::PNG: return std::make_unique<base::Value>("png"); }; NOTREACHED(); return nullptr; } template <> struct FromValue<page::StartScreencastParams> { static std::unique_ptr<page::StartScreencastParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::StartScreencastParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::StartScreencastParams& value) { return value.Serialize(); } template <> struct FromValue<page::StartScreencastResult> { static std::unique_ptr<page::StartScreencastResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::StartScreencastResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::StartScreencastResult& value) { return value.Serialize(); } template <> struct FromValue<page::StopLoadingParams> { static std::unique_ptr<page::StopLoadingParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::StopLoadingParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::StopLoadingParams& value) { return value.Serialize(); } template <> struct FromValue<page::StopLoadingResult> { static std::unique_ptr<page::StopLoadingResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::StopLoadingResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::StopLoadingResult& value) { return value.Serialize(); } template <> struct FromValue<page::CrashParams> { static std::unique_ptr<page::CrashParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::CrashParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::CrashParams& value) { return value.Serialize(); } template <> struct FromValue<page::CrashResult> { static std::unique_ptr<page::CrashResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::CrashResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::CrashResult& value) { return value.Serialize(); } template <> struct FromValue<page::CloseParams> { static std::unique_ptr<page::CloseParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::CloseParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::CloseParams& value) { return value.Serialize(); } template <> struct FromValue<page::CloseResult> { static std::unique_ptr<page::CloseResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::CloseResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::CloseResult& value) { return value.Serialize(); } template <> struct FromValue<page::SetWebLifecycleStateState> { static page::SetWebLifecycleStateState Parse(const base::Value& value, ErrorReporter* errors) { if (!value.is_string()) { errors->AddError("string enum value expected"); return page::SetWebLifecycleStateState::FROZEN; } if (value.GetString() == "frozen") return page::SetWebLifecycleStateState::FROZEN; if (value.GetString() == "active") return page::SetWebLifecycleStateState::ACTIVE; errors->AddError("invalid enum value"); return page::SetWebLifecycleStateState::FROZEN; } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetWebLifecycleStateState& value) { switch (value) { case page::SetWebLifecycleStateState::FROZEN: return std::make_unique<base::Value>("frozen"); case page::SetWebLifecycleStateState::ACTIVE: return std::make_unique<base::Value>("active"); }; NOTREACHED(); return nullptr; } template <> struct FromValue<page::SetWebLifecycleStateParams> { static std::unique_ptr<page::SetWebLifecycleStateParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetWebLifecycleStateParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetWebLifecycleStateParams& value) { return value.Serialize(); } template <> struct FromValue<page::SetWebLifecycleStateResult> { static std::unique_ptr<page::SetWebLifecycleStateResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetWebLifecycleStateResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetWebLifecycleStateResult& value) { return value.Serialize(); } template <> struct FromValue<page::StopScreencastParams> { static std::unique_ptr<page::StopScreencastParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::StopScreencastParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::StopScreencastParams& value) { return value.Serialize(); } template <> struct FromValue<page::StopScreencastResult> { static std::unique_ptr<page::StopScreencastResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::StopScreencastResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::StopScreencastResult& value) { return value.Serialize(); } template <> struct FromValue<page::SetProduceCompilationCacheParams> { static std::unique_ptr<page::SetProduceCompilationCacheParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetProduceCompilationCacheParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetProduceCompilationCacheParams& value) { return value.Serialize(); } template <> struct FromValue<page::SetProduceCompilationCacheResult> { static std::unique_ptr<page::SetProduceCompilationCacheResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetProduceCompilationCacheResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetProduceCompilationCacheResult& value) { return value.Serialize(); } template <> struct FromValue<page::AddCompilationCacheParams> { static std::unique_ptr<page::AddCompilationCacheParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::AddCompilationCacheParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::AddCompilationCacheParams& value) { return value.Serialize(); } template <> struct FromValue<page::AddCompilationCacheResult> { static std::unique_ptr<page::AddCompilationCacheResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::AddCompilationCacheResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::AddCompilationCacheResult& value) { return value.Serialize(); } template <> struct FromValue<page::ClearCompilationCacheParams> { static std::unique_ptr<page::ClearCompilationCacheParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::ClearCompilationCacheParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ClearCompilationCacheParams& value) { return value.Serialize(); } template <> struct FromValue<page::ClearCompilationCacheResult> { static std::unique_ptr<page::ClearCompilationCacheResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::ClearCompilationCacheResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ClearCompilationCacheResult& value) { return value.Serialize(); } template <> struct FromValue<page::GenerateTestReportParams> { static std::unique_ptr<page::GenerateTestReportParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::GenerateTestReportParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GenerateTestReportParams& value) { return value.Serialize(); } template <> struct FromValue<page::GenerateTestReportResult> { static std::unique_ptr<page::GenerateTestReportResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::GenerateTestReportResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::GenerateTestReportResult& value) { return value.Serialize(); } template <> struct FromValue<page::WaitForDebuggerParams> { static std::unique_ptr<page::WaitForDebuggerParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::WaitForDebuggerParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::WaitForDebuggerParams& value) { return value.Serialize(); } template <> struct FromValue<page::WaitForDebuggerResult> { static std::unique_ptr<page::WaitForDebuggerResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::WaitForDebuggerResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::WaitForDebuggerResult& value) { return value.Serialize(); } template <> struct FromValue<page::SetInterceptFileChooserDialogParams> { static std::unique_ptr<page::SetInterceptFileChooserDialogParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetInterceptFileChooserDialogParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetInterceptFileChooserDialogParams& value) { return value.Serialize(); } template <> struct FromValue<page::SetInterceptFileChooserDialogResult> { static std::unique_ptr<page::SetInterceptFileChooserDialogResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::SetInterceptFileChooserDialogResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::SetInterceptFileChooserDialogResult& value) { return value.Serialize(); } template <> struct FromValue<page::HandleFileChooserAction> { static page::HandleFileChooserAction Parse(const base::Value& value, ErrorReporter* errors) { if (!value.is_string()) { errors->AddError("string enum value expected"); return page::HandleFileChooserAction::ACCEPT; } if (value.GetString() == "accept") return page::HandleFileChooserAction::ACCEPT; if (value.GetString() == "cancel") return page::HandleFileChooserAction::CANCEL; if (value.GetString() == "fallback") return page::HandleFileChooserAction::FALLBACK; errors->AddError("invalid enum value"); return page::HandleFileChooserAction::ACCEPT; } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::HandleFileChooserAction& value) { switch (value) { case page::HandleFileChooserAction::ACCEPT: return std::make_unique<base::Value>("accept"); case page::HandleFileChooserAction::CANCEL: return std::make_unique<base::Value>("cancel"); case page::HandleFileChooserAction::FALLBACK: return std::make_unique<base::Value>("fallback"); }; NOTREACHED(); return nullptr; } template <> struct FromValue<page::HandleFileChooserParams> { static std::unique_ptr<page::HandleFileChooserParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::HandleFileChooserParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::HandleFileChooserParams& value) { return value.Serialize(); } template <> struct FromValue<page::HandleFileChooserResult> { static std::unique_ptr<page::HandleFileChooserResult> Parse(const base::Value& value, ErrorReporter* errors) { return page::HandleFileChooserResult::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::HandleFileChooserResult& value) { return value.Serialize(); } template <> struct FromValue<page::DomContentEventFiredParams> { static std::unique_ptr<page::DomContentEventFiredParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::DomContentEventFiredParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::DomContentEventFiredParams& value) { return value.Serialize(); } template <> struct FromValue<page::FileChooserOpenedMode> { static page::FileChooserOpenedMode Parse(const base::Value& value, ErrorReporter* errors) { if (!value.is_string()) { errors->AddError("string enum value expected"); return page::FileChooserOpenedMode::SELECT_SINGLE; } if (value.GetString() == "selectSingle") return page::FileChooserOpenedMode::SELECT_SINGLE; if (value.GetString() == "selectMultiple") return page::FileChooserOpenedMode::SELECT_MULTIPLE; errors->AddError("invalid enum value"); return page::FileChooserOpenedMode::SELECT_SINGLE; } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FileChooserOpenedMode& value) { switch (value) { case page::FileChooserOpenedMode::SELECT_SINGLE: return std::make_unique<base::Value>("selectSingle"); case page::FileChooserOpenedMode::SELECT_MULTIPLE: return std::make_unique<base::Value>("selectMultiple"); }; NOTREACHED(); return nullptr; } template <> struct FromValue<page::FileChooserOpenedParams> { static std::unique_ptr<page::FileChooserOpenedParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::FileChooserOpenedParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FileChooserOpenedParams& value) { return value.Serialize(); } template <> struct FromValue<page::FrameAttachedParams> { static std::unique_ptr<page::FrameAttachedParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::FrameAttachedParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FrameAttachedParams& value) { return value.Serialize(); } template <> struct FromValue<page::FrameClearedScheduledNavigationParams> { static std::unique_ptr<page::FrameClearedScheduledNavigationParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::FrameClearedScheduledNavigationParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FrameClearedScheduledNavigationParams& value) { return value.Serialize(); } template <> struct FromValue<page::FrameDetachedParams> { static std::unique_ptr<page::FrameDetachedParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::FrameDetachedParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FrameDetachedParams& value) { return value.Serialize(); } template <> struct FromValue<page::FrameNavigatedParams> { static std::unique_ptr<page::FrameNavigatedParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::FrameNavigatedParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FrameNavigatedParams& value) { return value.Serialize(); } template <> struct FromValue<page::FrameResizedParams> { static std::unique_ptr<page::FrameResizedParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::FrameResizedParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FrameResizedParams& value) { return value.Serialize(); } template <> struct FromValue<page::FrameRequestedNavigationParams> { static std::unique_ptr<page::FrameRequestedNavigationParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::FrameRequestedNavigationParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FrameRequestedNavigationParams& value) { return value.Serialize(); } template <> struct FromValue<page::FrameScheduledNavigationReason> { static page::FrameScheduledNavigationReason Parse(const base::Value& value, ErrorReporter* errors) { if (!value.is_string()) { errors->AddError("string enum value expected"); return page::FrameScheduledNavigationReason::FORM_SUBMISSION_GET; } if (value.GetString() == "formSubmissionGet") return page::FrameScheduledNavigationReason::FORM_SUBMISSION_GET; if (value.GetString() == "formSubmissionPost") return page::FrameScheduledNavigationReason::FORM_SUBMISSION_POST; if (value.GetString() == "httpHeaderRefresh") return page::FrameScheduledNavigationReason::HTTP_HEADER_REFRESH; if (value.GetString() == "scriptInitiated") return page::FrameScheduledNavigationReason::SCRIPT_INITIATED; if (value.GetString() == "metaTagRefresh") return page::FrameScheduledNavigationReason::META_TAG_REFRESH; if (value.GetString() == "pageBlockInterstitial") return page::FrameScheduledNavigationReason::PAGE_BLOCK_INTERSTITIAL; if (value.GetString() == "reload") return page::FrameScheduledNavigationReason::RELOAD; errors->AddError("invalid enum value"); return page::FrameScheduledNavigationReason::FORM_SUBMISSION_GET; } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FrameScheduledNavigationReason& value) { switch (value) { case page::FrameScheduledNavigationReason::FORM_SUBMISSION_GET: return std::make_unique<base::Value>("formSubmissionGet"); case page::FrameScheduledNavigationReason::FORM_SUBMISSION_POST: return std::make_unique<base::Value>("formSubmissionPost"); case page::FrameScheduledNavigationReason::HTTP_HEADER_REFRESH: return std::make_unique<base::Value>("httpHeaderRefresh"); case page::FrameScheduledNavigationReason::SCRIPT_INITIATED: return std::make_unique<base::Value>("scriptInitiated"); case page::FrameScheduledNavigationReason::META_TAG_REFRESH: return std::make_unique<base::Value>("metaTagRefresh"); case page::FrameScheduledNavigationReason::PAGE_BLOCK_INTERSTITIAL: return std::make_unique<base::Value>("pageBlockInterstitial"); case page::FrameScheduledNavigationReason::RELOAD: return std::make_unique<base::Value>("reload"); }; NOTREACHED(); return nullptr; } template <> struct FromValue<page::FrameScheduledNavigationParams> { static std::unique_ptr<page::FrameScheduledNavigationParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::FrameScheduledNavigationParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FrameScheduledNavigationParams& value) { return value.Serialize(); } template <> struct FromValue<page::FrameStartedLoadingParams> { static std::unique_ptr<page::FrameStartedLoadingParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::FrameStartedLoadingParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FrameStartedLoadingParams& value) { return value.Serialize(); } template <> struct FromValue<page::FrameStoppedLoadingParams> { static std::unique_ptr<page::FrameStoppedLoadingParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::FrameStoppedLoadingParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::FrameStoppedLoadingParams& value) { return value.Serialize(); } template <> struct FromValue<page::DownloadWillBeginParams> { static std::unique_ptr<page::DownloadWillBeginParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::DownloadWillBeginParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::DownloadWillBeginParams& value) { return value.Serialize(); } template <> struct FromValue<page::InterstitialHiddenParams> { static std::unique_ptr<page::InterstitialHiddenParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::InterstitialHiddenParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::InterstitialHiddenParams& value) { return value.Serialize(); } template <> struct FromValue<page::InterstitialShownParams> { static std::unique_ptr<page::InterstitialShownParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::InterstitialShownParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::InterstitialShownParams& value) { return value.Serialize(); } template <> struct FromValue<page::JavascriptDialogClosedParams> { static std::unique_ptr<page::JavascriptDialogClosedParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::JavascriptDialogClosedParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::JavascriptDialogClosedParams& value) { return value.Serialize(); } template <> struct FromValue<page::JavascriptDialogOpeningParams> { static std::unique_ptr<page::JavascriptDialogOpeningParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::JavascriptDialogOpeningParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::JavascriptDialogOpeningParams& value) { return value.Serialize(); } template <> struct FromValue<page::LifecycleEventParams> { static std::unique_ptr<page::LifecycleEventParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::LifecycleEventParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::LifecycleEventParams& value) { return value.Serialize(); } template <> struct FromValue<page::LoadEventFiredParams> { static std::unique_ptr<page::LoadEventFiredParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::LoadEventFiredParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::LoadEventFiredParams& value) { return value.Serialize(); } template <> struct FromValue<page::NavigatedWithinDocumentParams> { static std::unique_ptr<page::NavigatedWithinDocumentParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::NavigatedWithinDocumentParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::NavigatedWithinDocumentParams& value) { return value.Serialize(); } template <> struct FromValue<page::ScreencastFrameParams> { static std::unique_ptr<page::ScreencastFrameParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::ScreencastFrameParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ScreencastFrameParams& value) { return value.Serialize(); } template <> struct FromValue<page::ScreencastVisibilityChangedParams> { static std::unique_ptr<page::ScreencastVisibilityChangedParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::ScreencastVisibilityChangedParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::ScreencastVisibilityChangedParams& value) { return value.Serialize(); } template <> struct FromValue<page::WindowOpenParams> { static std::unique_ptr<page::WindowOpenParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::WindowOpenParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::WindowOpenParams& value) { return value.Serialize(); } template <> struct FromValue<page::CompilationCacheProducedParams> { static std::unique_ptr<page::CompilationCacheProducedParams> Parse(const base::Value& value, ErrorReporter* errors) { return page::CompilationCacheProducedParams::Parse(value, errors); } }; template <> inline std::unique_ptr<base::Value> ToValue(const page::CompilationCacheProducedParams& value) { return value.Serialize(); } } // namespace internal } // namespace headless #endif // HEADLESS_PUBLIC_DEVTOOLS_INTERNAL_TYPE_CONVERSIONS_PAGE_H_
[ "wasmview@gmail.com" ]
wasmview@gmail.com
6dcbd1617a557ecbc7ee66be2f4c78888ff79d31
792ecce420ec443469140f4b2f48efc1a94367b0
/src/rpcmining.cpp
1295ce09b6a5f9db9dc00b8992930950cc0f6ec5
[ "MIT" ]
permissive
Cleverhash/BOOM
024bfcf18ec3541d75770b37acb226e7792af029
f1739f952aae4c87fb68842812fb8c5c694077d9
refs/heads/master
2021-01-04T02:36:34.884883
2015-05-07T22:29:24
2015-05-07T22:29:24
26,034,888
0
2
null
null
null
null
UTF-8
C++
false
false
19,465
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "db.h" #include "txdb.h" #include "init.h" #include "miner.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; extern unsigned int nTargetSpacing; Value getsubsidy(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getsubsidy [nTarget]\n" "Returns proof-of-work subsidy value for the specified value of target."); unsigned int nBits = 0; if (params.size() != 0) { CBigNum bnTarget(uint256(params[0].get_str())); nBits = bnTarget.GetCompact(); } else { nBits = GetNextTargetRequired(pindexBest, false); } return (uint64_t)GetProofOfWorkReward(0); } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0; pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight); Object obj, diff, weight; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); diff.push_back(Pair("proof-of-work", GetDifficulty())); diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval)); obj.push_back(Pair("difficulty", diff)); obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(0))); obj.push_back(Pair("netmhashps", GetPoWMHashPS())); obj.push_back(Pair("netstakeweight", GetPoSKernelPS())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); weight.push_back(Pair("minimum", (uint64_t)nMinWeight)); weight.push_back(Pair("maximum", (uint64_t)nMaxWeight)); weight.push_back(Pair("combined", (uint64_t)nWeight)); obj.push_back(Pair("stakeweight", weight)); obj.push_back(Pair("stakeinterest", (uint64_t)COIN_YEAR_REWARD)); obj.push_back(Pair("testnet", fTestNet)); return obj; } Value getstakinginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getstakinginfo\n" "Returns an object containing staking-related information."); uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0; pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight); uint64_t nNetworkWeight = GetPoSKernelPS(); bool staking = nLastCoinStakeSearchInterval && nWeight; int nExpectedTime = staking ? (nTargetSpacing * nNetworkWeight / nWeight) : -1; Object obj; obj.push_back(Pair("enabled", GetBoolArg("-staking", true))); obj.push_back(Pair("staking", staking)); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx)); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval)); obj.push_back(Pair("weight", (uint64_t)nWeight)); obj.push_back(Pair("netstakeweight", (uint64_t)nNetworkWeight)); obj.push_back(Pair("expectedtime", nExpectedTime)); return obj; } Value getworkex(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getworkex [data, coinbase]\n" "If [data, coinbase] is not specified, returns extended work data.\n" ); if (vNodes.empty()) throw JSONRPCError(-9, "BoomCoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(-10, "BoomCoin is downloading blocks..."); if (pindexBest->nHeight >= LAST_POW_BLOCK) throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks"); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; static vector<CBlock*> vNewBlock; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64_t nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlock* pblock, vNewBlock) delete pblock; vNewBlock.clear(); } nTransactionsUpdatedLast = nTransactionsUpdated; pindexPrev = pindexBest; nStart = GetTime(); // Create new block pblock = CreateNewBlock(pwalletMain); if (!pblock) throw JSONRPCError(-7, "Out of memory"); vNewBlock.push_back(pblock); } // Update nTime pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, GetAdjustedTime()); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Prebuild hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); CTransaction coinbaseTx = pblock->vtx[0]; std::vector<uint256> merkle = pblock->GetMerkleBranch(0); Object result; result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << coinbaseTx; result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end()))); Array merkle_arr; BOOST_FOREACH(uint256 merkleh, merkle) { merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh))); } result.push_back(Pair("merkle", merkle_arr)); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); vector<unsigned char> coinbase; if(params.size() == 2) coinbase = ParseHex(params[1].get_str()); if (vchData.size() != 128) throw JSONRPCError(-8, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; if(coinbase.size() == 0) pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; else CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HASH! pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "BoomCoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "BoomCoin is downloading blocks..."); if (pindexBest->nHeight >= LAST_POW_BLOCK) throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks"); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlock*> vNewBlock; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64_t nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlock* pblock, vNewBlock) delete pblock; vNewBlock.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblock = CreateNewBlock(pwalletMain); if (!pblock) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlock.push_back(pblock); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getblocktemplate [params]\n" "Returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); std::string strMode = "template"; if (params.size() > 0) { const Object& oparam = params[0].get_obj(); const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (modeval.type() == null_type) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "BoomCoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "BoomCoin is downloading blocks..."); if (pindexBest->nHeight >= LAST_POW_BLOCK) throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks"); static CReserveKey reservekey(pwalletMain); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64_t nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block if(pblock) { delete pblock; pblock = NULL; } pblock = CreateNewBlock(pwalletMain); if (!pblock) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; CTxDB txdb("r"); BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase() || tx.IsCoinStake()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut()))); Array deps; BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs) { if (setTxIndex.count(inp.first)) deps.push_back(setTxIndex[inp.first]); } entry.push_back(Pair("depends", deps)); int64_t nSigOps = tx.GetLegacySigOpCount(); nSigOps += tx.GetP2SHSigOpCount(mapInputs); entry.push_back(Pair("sigops", nSigOps)); } transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetPastTimeLimit()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock <hex data> [optional-params-obj]\n" "[optional-params-obj] parameter is currently ignored.\n" "Attempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock block; try { ssBlock >> block; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } bool fAccepted = ProcessBlock(NULL, &block); if (!fAccepted) return "rejected"; return Value::null; }
[ "admin@cleverhash.com" ]
admin@cleverhash.com
d708fce036513f913c091d1c946f28bb328ec31d
0f8ee2a862862dfe3a17c924ff45aac30ee71015
/model/CM300Joystick.h
dd435fddeb2e6082e96838e6b1e1c3b464c2f7a2
[]
no_license
ROBOTIS-GIT/codal-cm300
309c38e2172ff1ada12536230bd1665c582d3d07
4c0e9fed82d94feb74d18e43716648d100604b47
refs/heads/master
2020-12-30T04:00:10.248305
2020-04-08T08:01:41
2020-04-08T08:01:41
238,852,891
0
0
null
2020-05-08T05:05:35
2020-02-07T05:46:24
C++
UTF-8
C++
false
false
1,697
h
/******************************************************************************* * Copyright 2016 ROBOTIS 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 CM300_JOY_STICK_H #define CM300_JOY_STICK_H #include "CodalConfig.h" #include "CM300IO.h" #include "Event.h" #include "Sensor.h" #include "device_pinmap.h" namespace codal { class CM300Joystick : public Sensor { Pin& pinX; // Pin where the sensor is connected. Pin& pinY; // Pin where the sensor is connected. uint32_t temp; public: /** * Constructor. * * Creates a generic AnalogSensor. * * @param pin The pin on which to sense * @param id The ID of this compoenent e.g. */ CM300Joystick(Pin &pinX, uint16_t id1, Pin &pinY, uint16_t id2); /** * Read the value from pin. */ // virtual int readValue(uint8_t Num); virtual int readValue(); /** * Destructor. */ ~CM300Joystick(); }; } #endif
[ "ldh@robotis.com" ]
ldh@robotis.com
095afd99c63ee26b4f4c7961df9ef04059ceb633
3af9e8da5915d27084b04e1ca8582b2b15b213b0
/Week13/simpleHandShaking/SerialCommunication.ino
bb1ed23f5a8a1df1865dbb4d8b9b2a8bd9be0075
[]
no_license
entertainmenttechnology/Dols-MTEC-2280-Spring2019
65116423e617ad841c9859aa2807c3d01913edcf
f67d8895eb203ae57ee5387122887074e8fec0d7
refs/heads/master
2020-04-18T23:20:23.326169
2019-05-30T14:30:27
2019-05-30T14:30:27
167,818,841
1
19
null
2019-05-28T19:39:16
2019-01-27T14:36:40
Processing
UTF-8
C++
false
false
892
ino
char val; // Data received from the serial port int ledPin = 13; // Set the pin to digital I/O 13 boolean ledState = LOW; //to toggle our LED void setup() { pinMode(ledPin, OUTPUT); // Set pin as OUTPUT //initialize serial communications at a 9600 baud rate Serial.begin(9600); establishContact(); // send a byte to establish contact until receiver responds } void loop() { if (Serial.available() > 0) { // If data is available to read, val = Serial.read(); // read it and store it in val if(val == '1') //if we get a 1 { ledState = !ledState; //flip the ledState digitalWrite(ledPin, ledState); } delay(100); } else { Serial.println("Hello, world!"); //send back a hello world delay(50); } } void establishContact() { while (Serial.available() <= 0) { Serial.println("A"); // send a capital A delay(300); } }
[ "noreply@github.com" ]
noreply@github.com
1d54ebdc1ab3731116d8130d117bdf8c51c7d95f
0ffd0c702dd5df0bbb0ce50ed01ee47accef6bfc
/AREA 51/codeINO/RTC_DS1307_EEPROM/RTC_DS1307_EEPROM.ino
e08beb81511604abb56f20d598da9244d36f3fca
[ "MIT" ]
permissive
higo-ricardo/ARDUINO
6831e49578bae38594a7fa806eb10e5fdc3f9eb7
d0f2b3edf0d17bd5bdc8961925ac2828e5efc257
refs/heads/master
2023-04-13T11:57:29.475345
2021-05-05T03:03:50
2021-05-05T03:03:50
256,534,220
0
0
null
null
null
null
UTF-8
C++
false
false
9,190
ino
/* MÓDULO RTC COM DS1307 e EEPROM 24C32: Como o módulo RTC utiliza o barramento I2C para se comunicar com o Arduino então deve-se conectar o módulo ao Arduino ligando-se o pino SCL do módulo na porta analógica A5 do Arduino, o pino SDA na porta analógica A4 do Arduino, o pino positivo VCC no 5V e o pino negativo no GND. Para o correto funcionamento deste módulo é necessário que a bateria de 3V esteja inserida no suporte, localizado no verso da placa. */ /////////////////////////////////// // INICIALIZAÇÃO DAS BIBLIOTECAS // /////////////////////////////////// /* A biblioteca Wire foi desenvolvida para permitir a comunicação serial através do I2C(Inter-Integrated Circuit), que é um barramento serial multi-mestre desenvolvido pela Philips utilizado para conectar periféricos de baixa velocidade a uma placa mãe ou sistemas embarcados. */ #include <Wire.h> ///////////////////////////////// // INICIALIZAÇÃO DAS VARIÁVEIS // ///////////////////////////////// /* Como a comunicação será realizada através do barramento I2C a primeira coisa que precisa saber é o endereço, que no caso é "0x68". Logo define-se uma variável para armazenar esse endereço. */ #define enderecoI2C 0x68 /* Como este módulo trabalha em grupos de 7 Bytes, então define-se as variáveis para esse conjunto de 7 dados, que são as horas e data. */ byte segundo, minuto, hora, diaDaSemana, diaDoMes, mes, ano; /////////// // SETUP // /////////// void setup() { Serial.begin(9600); //configurando a comunicação via porta //serial à uma velocidade de 9600bps(baud). Wire.begin(); //inicializando a biblioteca. configuraModulo(); //chamando a função para configurar o módulo. } /////////// // LOOP // /////////// void loop() { imprimeDadosModulo(); //chamando a função para imprimir na tela os dados //gravados no módulo. delay(2000); //aguardando 2 segundos para próxima leitura. } //////////// // FUNÇÃO // //////////// /* Essa função configura o módulo com dados de hora e data inicialmente desejados. Essa função deve ser executada uma única vez na inicialização do módulo, pois ao definir os dados inicias no módulo, fará como que ele comece a contar o tempo e nunca mais pare de contar enquanto tiver energia, seja ela fornecida pela fonte principal ou pela bateria auxiliar de 3V. Logo para as próximas compilações deve-se colocar um comentário na chamada da função configuraModulo() localizada no setup(). Para escrever os dados de hora e data no módulo deve-se realizar os seguintes passos: 1) Abrir a comunicação I2C em modo de gravação; 2) Redefinir o ponteiro para o primeiro registro (0x00); 3) Escrever sete bytes de dados; 4) Finalizar o modo de gravação. */ void configuraModulo() { /* Inicializando as variáveis abaixo com os dados de hora e data desejados. Lembrando que quando o dado for menor que 10, ou seja, tiver apenas um dígito não deve-se digitar o zero à esquerda. Exemplo: se deseja armazenar na variável hora o valor de 9horas, digite apenas o dígito 9, nunca 09. */ segundo = 0; minuto = 40; hora = 14; diaDaSemana = 3; diaDoMes = 11; mes = 12; ano = 13; Wire.beginTransmission(enderecoI2C); //Abrindo o modo I2C no modo de gravação. Wire.write((byte)0x00); //Redefinindo o ponteiro para o primeiro registro (0x00). //Para escrever dados no módulo é necessário uma conversão de Decimal para Binário Wire.write(decToBcd(segundo)); //convertendo os segundos. Wire.write(decToBcd(minuto)); //convertendo os minutos. Wire.write(decToBcd(hora)); //convertendo as horas. Wire.write(decToBcd(diaDaSemana)); //dia da semana, onde o domingo começa com "0". Wire.write(decToBcd(diaDoMes)); //convertendo o dia do mês. Wire.write(decToBcd(mes)); //convertendo o mês. Wire.write(decToBcd(ano)); //convertendo o ano. Wire.endTransmission(); //finalizando o modo de gravação. } /* Essa função é reponsável por ler os dados de hora e data gravados no módulo e imprimi-los na tela do Monitor Serial. */ void imprimeDadosModulo() { /* Como para valores menores que 10 o dado armazenado no módulo possui apenas um dígito, então será criado variáveis de ajustes, permitindo que no momento da impressão na tela esses valores com apenas um dígito sejam mostrados com um zero à esquerda. Exemplo: ao invés de 9:58:10 a impressão ficará 09:58:10 */ String ajustaSegundo; String ajustaMinuto; String ajustaHora; String ajustaDiaDoMes; String ajustaMes; /* Para ler os dados de hora e data no módulo deve-se realizar os seguintes passos: 1) Abrir a comunicação I2C em modo de gravação; 2) Redefinir o ponteiro para o primeiro registro (0x00); 3) Finalizar o modo de gravação; 4) Abrir a comunicação I2C em modo de leitura; 5) Ler os sete bytes de dados. */ Wire.beginTransmission(enderecoI2C); //Abrindo o modo I2C no modo de gravação. Wire.write((byte)0x00); //Redefinindo o ponteiro para o primeiro registro (0x00). Wire.endTransmission(); //finalizando o modo de gravação. Wire.requestFrom(enderecoI2C, 7); //Abrindo o modo I2C no modo de leitura. //Para ler e posteriormente imprimir os dados lidos do módulo é necessário uma //conversão de Binário para Decimal. segundo = bcdToDec(Wire.read() & 0x7f); //Alguns dados precisam de máscaras antes //da conversão porque certos bits são //bits de controle. minuto = bcdToDec(Wire.read()); //convertendo os minutos. hora = bcdToDec(Wire.read() & 0x3f); //Alguns dados precisam de máscaras antes //da conversão porque certos bits são //bits de controle. Essa máscara define o //relógio para trabalhar no modo de 24h. diaDaSemana = bcdToDec(Wire.read()); //dia da semana, onde domingo começa com "0". diaDoMes = bcdToDec(Wire.read()); //convertendo o dia do mês. mes = bcdToDec(Wire.read()); //convertendo o mês. ano = bcdToDec(Wire.read()); //convertendo o ano. //Imprimindo os dois dígitos das horas separados por dois pontos. Serial.print("Agora sao: "); //chmando a função ajustaZero para o caso de dados gravado no módulo com apenas um dígito. ajustaHora += ajustaZero(hora); Serial.print(ajustaHora); Serial.print(":"); //chmando a função ajustaZero para o caso de dados gravado no módulo com apenas um dígito. ajustaMinuto += ajustaZero(minuto); Serial.print(ajustaMinuto); Serial.print(":"); //chmando a função ajustaZero para o caso de dados gravado no módulo com apenas um dígito. ajustaSegundo += ajustaZero(segundo); Serial.println(ajustaSegundo); Serial.print("Dia da semana: "); switch(diaDaSemana) { case 0:Serial.println("Domingo"); break; //se a variável diaDaSemana for zero //imprima na tela "Domingo" case 1:Serial.println("Segunda-feira"); break; //idem ao anterior case 2:Serial.println("Terca-feira"); break; //idem case 3:Serial.println("Quarta-feira"); break; //idem case 4:Serial.println("Quinta-feira"); break; //idem case 5:Serial.println("Sexta-feira"); break; //idem case 6:Serial.println("Sabado"); break; //idem } //Imprimindo os dois dígitos das datas separadas por uma barra. Serial.print("Data: "); //chmando a função ajustaZero para o caso de dados gravado no módulo com apenas um dígito. ajustaDiaDoMes += ajustaZero(diaDoMes); Serial.print(ajustaDiaDoMes); Serial.print("/"); //chmando a função ajustaZero para o caso de dados gravado no módulo com apenas um dígito. ajustaMes += ajustaZero(mes); Serial.print(ajustaMes); Serial.print("/"); Serial.println(ano); Serial.println(); //salta uma linha. } /* Função que realiza uma conversão de Decimal para Binário. Utilizada na gravação de dados no módulo. */ byte decToBcd(byte val) { return ( (val/10*16) + (val%10) ); } /* Função que realiza uma conversão de Binário para Decimal. Utilizada na impressão dos dados na tela do Monitor Serial. */ byte bcdToDec(byte val) { return ( (val/16*10) + (val%16) ); } /* Essa função insere o dígito "0" à esquerda dos dados gravados no módulo com apenas um dígito, já que os valores menores que 10 são armazenados no módulo com apenas um dígito. */ String ajustaZero(byte dado) { String dadoAjustado; if (dado < 10) { dadoAjustado += "0"; //concatena o dígito "0" ao valor da variável. } dadoAjustado += dado; //concatena o dígito "0" ao valor do dado. return dadoAjustado; //retorna o valor do dado ajustado. }
[ "hig0@icloud.com" ]
hig0@icloud.com
d2453925361057f2aaf591238cb81016e990816e
df81c7fafcacc916d0377345ab947fe606ac7027
/hw3d/Mouse.cpp
37a12827214074b440076447ae8847ee732f34ce
[]
no_license
qfeuilla/CustomGameEngine
6e15120e8355fabb3f81ee0b20cfcc18cf594e86
48ac70fe7a2a3ca835c6fea1438e1d7c08d676f9
refs/heads/master
2022-11-29T10:33:31.086111
2020-08-09T12:51:26
2020-08-09T12:51:26
277,605,404
0
0
null
2020-08-09T12:51:28
2020-07-06T17:23:52
null
UTF-8
C++
false
false
4,362
cpp
/****************************************************************************************** * Chili DirectX Framework Version 16.07.20 * * Mouse.cpp * * Copyright 2016 PlanetChili <http://www.planetchili.net> * * * * This file is part of The Chili DirectX Framework. * * * * The Chili DirectX Framework is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * The Chili DirectX Framework 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 The Chili DirectX Framework. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************************/ #include "CustomWindows.h" #include "Mouse.h" std::pair<int,int> Mouse::GetPos() const noexcept { return { x,y }; } std::optional<Mouse::RawDelta> Mouse::ReadRawDelta() noexcept { if( rawDeltaBuffer.empty() ) { return std::nullopt; } const RawDelta d = rawDeltaBuffer.front(); rawDeltaBuffer.pop(); return d; } int Mouse::GetPosX() const noexcept { return x; } int Mouse::GetPosY() const noexcept { return y; } bool Mouse::IsInWindow() const noexcept { return isInWindow; } bool Mouse::LeftIsPressed() const noexcept { return leftIsPressed; } bool Mouse::RightIsPressed() const noexcept { return rightIsPressed; } std::optional<Mouse::Event> Mouse::Read() noexcept { if( buffer.size() > 0u ) { Mouse::Event e = buffer.front(); buffer.pop(); return e; } return {}; } void Mouse::Flush() noexcept { buffer = std::queue<Event>(); } void Mouse::EnableRaw() noexcept { rawEnabled = true; } void Mouse::DisableRaw() noexcept { rawEnabled = false; } bool Mouse::RawEnabled() const noexcept { return rawEnabled; } void Mouse::OnMouseMove( int newx,int newy ) noexcept { x = newx; y = newy; buffer.push( Mouse::Event( Mouse::Event::Type::Move,*this ) ); TrimBuffer(); } void Mouse::OnMouseLeave() noexcept { isInWindow = false; buffer.push( Mouse::Event( Mouse::Event::Type::Leave,*this ) ); TrimBuffer(); } void Mouse::OnMouseEnter() noexcept { isInWindow = true; buffer.push( Mouse::Event( Mouse::Event::Type::Enter,*this ) ); TrimBuffer(); } void Mouse::OnRawDelta( int dx,int dy ) noexcept { rawDeltaBuffer.push( { dx,dy } ); TrimBuffer(); } void Mouse::OnLeftPressed( int x,int y ) noexcept { leftIsPressed = true; buffer.push( Mouse::Event( Mouse::Event::Type::LPress,*this ) ); TrimBuffer(); } void Mouse::OnLeftReleased( int x,int y ) noexcept { leftIsPressed = false; buffer.push( Mouse::Event( Mouse::Event::Type::LRelease,*this ) ); TrimBuffer(); } void Mouse::OnRightPressed( int x,int y ) noexcept { rightIsPressed = true; buffer.push( Mouse::Event( Mouse::Event::Type::RPress,*this ) ); TrimBuffer(); } void Mouse::OnRightReleased( int x,int y ) noexcept { rightIsPressed = false; buffer.push( Mouse::Event( Mouse::Event::Type::RRelease,*this ) ); TrimBuffer(); } void Mouse::OnWheelUp( int x,int y ) noexcept { buffer.push( Mouse::Event( Mouse::Event::Type::WheelUp,*this ) ); TrimBuffer(); } void Mouse::OnWheelDown( int x,int y ) noexcept { buffer.push( Mouse::Event( Mouse::Event::Type::WheelDown,*this ) ); TrimBuffer(); } void Mouse::TrimBuffer() noexcept { while( buffer.size() > bufferSize ) { buffer.pop(); } } void Mouse::TrimRawInputBuffer() noexcept { while( rawDeltaBuffer.size() > bufferSize ) { rawDeltaBuffer.pop(); } } void Mouse::OnWheelDelta( int x,int y,int delta ) noexcept { wheelDeltaCarry += delta; // generate events for every 120 while( wheelDeltaCarry >= WHEEL_DELTA ) { wheelDeltaCarry -= WHEEL_DELTA; OnWheelUp( x,y ); } while( wheelDeltaCarry <= -WHEEL_DELTA ) { wheelDeltaCarry += WHEEL_DELTA; OnWheelDown( x,y ); } }
[ "quentin.feuillade33@gmail.com" ]
quentin.feuillade33@gmail.com
46835e81117f27701300e1d3d82c9601b0e5ce2b
1ad2ac811c607f9b2821073843352e3e250af683
/src/myInputGenJetsParticleSelector.cc
63472610533b3b4bfe26db14a93c3ccabef89927
[ "Apache-2.0" ]
permissive
BristolTopGroup/NTupleProduction
6d7d1918ddb0ff9f79f335ed7d6b0a371bfaa471
1319183de0ce00749c8f5841fa925479b9024b48
refs/heads/master
2020-04-04T06:22:06.601999
2017-09-20T08:50:03
2017-09-20T08:50:03
6,820,183
1
1
null
2017-10-19T11:10:41
2012-11-22T23:33:39
Python
UTF-8
C++
false
false
11,083
cc
/* \class GenJetInputParticleSelector * * Selects particles that are used as input for the GenJet collection. * Logic: select all stable particles, except for particles specified in * the config file that come from * W,Z and H decays, and except for a special list, which can be used for * unvisible BSM-particles. * It is also possible to only selected the partonic final state, * which means all particles before the hadronization step. * * The algorithm is based on code of Christophe Saout. * * Usage: [example for no resonance from nu an mu, and deselect invisible BSM * particles ] * * module genJetParticles = InputGenJetsParticleSelector { * InputTag src = "genParticles" * bool partonicFinalState = false * bool excludeResonances = true * vuint32 excludeFromResonancePids = {13,12,14,16} * bool tausAsJets = false * int32 flavour = 5 * vuint32 ignoreParticleIDs = { 1000022, 2000012, 2000014, * 2000016, 1000039, 5000039, * 4000012, 9900012, 9900014, * 9900016, 39} * } * * * \author: Christophe Saout, Andreas Oehler * */ #include "BristolAnalysis/NTupleTools/interface/myInputGenJetsParticleSelector.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" //#include <iostream> #include <memory> #include "CommonTools/CandUtils/interface/pdgIdUtils.h" using namespace std; myInputGenJetsParticleSelector::myInputGenJetsParticleSelector(const edm::ParameterSet &params ): inTag(params.getParameter<edm::InputTag>("src")), partonicFinalState(params.getParameter<bool>("partonicFinalState")), excludeResonances(params.getParameter<bool>("excludeResonances")), tausAsJets(params.getParameter<bool>("tausAsJets")), flavour(params.getParameter<int>("flavour")), ptMin(0.0){ if (params.exists("ignoreParticleIDs")) setIgnoredParticles(params.getParameter<std::vector<unsigned int> > ("ignoreParticleIDs")); setExcludeFromResonancePids(params.getParameter<std::vector<unsigned int> > ("excludeFromResonancePids")); // produces <reco::GenParticleRefVector> (); // Replaced in order to add new hadron particles with scaled energy produces <reco::GenParticleCollection> (); } myInputGenJetsParticleSelector::~myInputGenJetsParticleSelector(){} void myInputGenJetsParticleSelector::setIgnoredParticles(const std::vector<unsigned int> &particleIDs) { ignoreParticleIDs = particleIDs; std::sort(ignoreParticleIDs.begin(), ignoreParticleIDs.end()); } void myInputGenJetsParticleSelector::setExcludeFromResonancePids(const std::vector<unsigned int> &particleIDs) { excludeFromResonancePids = particleIDs; std::sort( excludeFromResonancePids.begin(), excludeFromResonancePids.end()); } bool myInputGenJetsParticleSelector::isParton(int pdgId) const{ pdgId = (pdgId > 0 ? pdgId : -pdgId) % 10000; return (pdgId > 0 && pdgId < 6) || pdgId == 7 || pdgId == 9 || (tausAsJets && pdgId == 15) || pdgId == 21; // tops are not considered "regular" partons // but taus eventually are (since they may hadronize later) } bool myInputGenJetsParticleSelector::isHadron(int pdgId) { pdgId = (pdgId > 0 ? pdgId : -pdgId) % 10000; return (pdgId > 100 && pdgId < 900) || (pdgId > 1000 && pdgId < 9000); } bool myInputGenJetsParticleSelector::isResonance(int pdgId) { // gauge bosons and tops pdgId = (pdgId > 0 ? pdgId : -pdgId) % 10000; return (pdgId > 21 && pdgId <= 42) || pdgId == 6 || pdgId == 8 ; //BUG! war 21. 22=gamma.. } bool myInputGenJetsParticleSelector::isIgnored(int pdgId) const { pdgId = pdgId > 0 ? pdgId : -pdgId; std::vector<unsigned int>::const_iterator pos = std::lower_bound(ignoreParticleIDs.begin(), ignoreParticleIDs.end(), (unsigned int)pdgId); return pos != ignoreParticleIDs.end() && *pos == (unsigned int)pdgId; } bool myInputGenJetsParticleSelector::isExcludedFromResonance(int pdgId) const { pdgId = pdgId > 0 ? pdgId : -pdgId; std::vector<unsigned int>::const_iterator pos = std::lower_bound(excludeFromResonancePids.begin(), excludeFromResonancePids.end(), (unsigned int)pdgId); return pos != excludeFromResonancePids.end() && *pos == (unsigned int)pdgId; } static unsigned int partIdx(const myInputGenJetsParticleSelector::ParticleVector &p, const reco::GenParticle *particle) { myInputGenJetsParticleSelector::ParticleVector::const_iterator pos = std::lower_bound(p.begin(), p.end(), particle); if (pos == p.end() || *pos != particle) throw cms::Exception("CorruptedData") << "reco::GenEvent corrupted: Unlisted particles" " in decay tree." << std::endl; return pos - p.begin(); } static void invalidateTree(myInputGenJetsParticleSelector::ParticleBitmap &invalid, const myInputGenJetsParticleSelector::ParticleVector &p, const reco::GenParticle *particle) { unsigned int npart=particle->numberOfDaughters(); if (!npart) return; for (unsigned int i=0;i<npart;++i){ unsigned int idx=partIdx(p,dynamic_cast<const reco::GenParticle*>(particle->daughter(i))); if (invalid[idx]) continue; invalid[idx] = true; //cout<<"Invalidated: ["<<setw(4)<<idx<<"] With pt:"<<particle->daughter(i)->pt()<<endl; invalidateTree(invalid, p, dynamic_cast<const reco::GenParticle*>(particle->daughter(i))); } } int myInputGenJetsParticleSelector::testPartonChildren (myInputGenJetsParticleSelector::ParticleBitmap &invalid, const myInputGenJetsParticleSelector::ParticleVector &p, const reco::GenParticle *particle) const { unsigned int npart=particle->numberOfDaughters(); if (!npart) {return 0;} for (unsigned int i=0;i<npart;++i){ unsigned int idx = partIdx(p,dynamic_cast<const reco::GenParticle*>(particle->daughter(i))); if (invalid[idx]) continue; if (isParton((particle->daughter(i)->pdgId()))){ return 1; } if (isHadron((particle->daughter(i)->pdgId()))){ return -1; } int result = testPartonChildren(invalid,p,dynamic_cast<const reco::GenParticle*>(particle->daughter(i))); if (result) return result; } return 0; } myInputGenJetsParticleSelector::ResonanceState myInputGenJetsParticleSelector::fromResonance(ParticleBitmap &invalid, const ParticleVector &p, const reco::GenParticle *particle) const { unsigned int idx = partIdx(p, particle); int id = particle->pdgId(); if (invalid[idx]) return kIndirect; if (isResonance(id) && particle->status() == 3){ return kDirect; } if (!isIgnored(id) && (isParton(id))) return kNo; unsigned int nMo=particle->numberOfMothers(); if (!nMo) return kNo; for(unsigned int i=0;i<nMo;++i){ ResonanceState result = fromResonance(invalid,p,dynamic_cast<const reco::GenParticle*>(particle->mother(i))); switch(result) { case kNo: break; case kDirect: if (dynamic_cast<const reco::GenParticle*>(particle->mother(i))->pdgId()==id || isResonance(id) || abs(id)==15) return kDirect; if(!isExcludedFromResonance(id)) break; case kIndirect: return kIndirect; } } return kNo; } bool myInputGenJetsParticleSelector::hasPartonChildren(ParticleBitmap &invalid, const ParticleVector &p, const reco::GenParticle *particle) const { return testPartonChildren(invalid, p, particle) > 0; } //###################################################### //function NEEDED and called per EVENT by FRAMEWORK: void myInputGenJetsParticleSelector::produce (edm::Event &evt, const edm::EventSetup &evtSetup){ // std::auto_ptr<reco::GenParticleRefVector> selected_ (new reco::GenParticleRefVector); // Replaced in order to add new hadron particles with scaled energy std::auto_ptr<reco::GenParticleCollection> selected_ (new reco::GenParticleCollection); edm::Handle<reco::GenParticleCollection> genParticles; // evt.getByLabel("genParticles", genParticles ); evt.getByLabel(inTag, genParticles ); ParticleVector particles; for (reco::GenParticleCollection::const_iterator iter=genParticles->begin();iter!=genParticles->end();++iter){ particles.push_back(&*iter); } std::sort(particles.begin(), particles.end()); unsigned int size = particles.size(); ParticleBitmap selected(size, false); ParticleBitmap invalid(size, false); for(unsigned int i = 0; i < size; i++) { const reco::GenParticle *particle = particles[i]; if (invalid[i]) continue; if (particle->status() == 1) selected[i] = true; // Putting hadron of specified flavour into the list of particles for jet clustering if(abs(particle->pdgId()/1000) == flavour || abs(particle->pdgId()/100 % 10) == flavour){ selected[i] = true; // Skipping hadron that has hadron daughter (doesn't decay weakly) for(unsigned int k=0; k<particle->numberOfDaughters();k++){ if(abs(particle->daughter(k)->pdgId()/1000) == flavour || abs(particle->daughter(k)->pdgId()/100 % 10) == flavour){ selected[i] = false; } } } if (partonicFinalState && isParton(particle->pdgId())) { if (particle->numberOfDaughters()==0 && particle->status() != 1) { // some brokenness in event... invalid[i] = true; } else if (!hasPartonChildren(invalid, particles, particle)) { selected[i] = true; invalidateTree(invalid, particles,particle); //this?!? } } } unsigned int count=0; for(size_t idx=0;idx<genParticles->size();++idx){ const reco::GenParticle *particle = particles[idx]; if (!selected[idx] || invalid[idx]){ continue; } if (excludeResonances && fromResonance(invalid, particles, particle)) { invalid[idx] = true; //cout<<"[INPUTSELECTOR] Invalidates FROM RESONANCE!: ["<<setw(4)<<idx<<"] "<<particle->pdgId()<<" "<<particle->pt()<<endl; continue; } if (isIgnored(particle->pdgId())){ continue; } if (particle->pt() >= ptMin){ // edm::Ref<reco::GenParticleCollection> particleRef(genParticles,idx); // Replaced because we use particles instead of references for hadrons reco::GenParticle part = (*particle); if(abs(part.pdgId()/1000) == flavour || abs(part.pdgId()/100 % 10) == flavour){ // std::printf("hadInEve: Pdg: %d\tPt: %.1f\tEta: %.3f\tPhi: %.3f\n",particle->pdgId(), particle->pt(), particle->eta(), particle->phi()); part.setP4(part.p4()*.0000000000000000001); // Scaling down the energy of the hadron so that jet energy isn't affected } // selected_->push_back(particleRef); // Commented because references are replaced by particles selected_->push_back(part); //cout<<"Finally we have: ["<<setw(4)<<idx<<"] "<<setw(4)<<particle->pdgId()<<" "<<particle->pt()<<endl; count++; } } evt.put(selected_); } //define this as a plug-in DEFINE_FWK_MODULE(myInputGenJetsParticleSelector);
[ "philip.hugh.symonds@cern.ch" ]
philip.hugh.symonds@cern.ch
af44a8d9c22c6f95009cf67ac7dd71b40ba03111
b518d7b94bf1e14ab580da417b133e59c8664e79
/string algo/new.cpp
4e81cd14feb041bb6e8aaffcf7e4fc7aee6a5493
[]
no_license
jitunmohajan/competitive-programming
919c7b26af01c30b2398c1284f95f40fafd50061
3cbaa761f00cd311989cfcc4aa8422d481e29435
refs/heads/master
2023-02-24T16:36:02.150414
2021-01-30T19:09:26
2021-01-30T19:09:26
170,622,999
4
0
null
null
null
null
UTF-8
C++
false
false
96
cpp
#include<bits/stdc++.h> using namespace std; int main(){ int a; cin>>a; cout<<a; return 0; }
[ "jitunmohajan@gmail.com" ]
jitunmohajan@gmail.com
6bb477d7ce34c1a2106931c3172295b015a2cd9f
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/blink/renderer/core/animation/scroll_timeline_util.h
2a85f0138af76b4b5b6d7c4fb7310d88bc1bb634
[ "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", "BSD-3-Clause", "Apache-2.0", "MIT" ]
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
1,836
h
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_SCROLL_TIMELINE_UTIL_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_SCROLL_TIMELINE_UTIL_H_ #include "cc/animation/scroll_timeline.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/renderer/core/animation/scroll_timeline.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/animation/compositor_animation.h" namespace blink { using CompositorScrollTimeline = cc::ScrollTimeline; using ScrollOffsets = cc::ScrollTimeline::ScrollOffsets; using ScrollAxis = V8ScrollAxis::Enum; class AnimationTimeline; class ComputedStyle; class Node; namespace scroll_timeline_util { // Converts the input timeline to the compositor representation of a // ScrollTimeline. Returns nullptr if the input is not a ScrollTimeline. scoped_refptr<CompositorScrollTimeline> CORE_EXPORT ToCompositorScrollTimeline(AnimationTimeline*); // Retrieves the 'scroll' compositor element id for the input node, or // absl::nullopt if it does not exist. absl::optional<CompositorElementId> CORE_EXPORT GetCompositorScrollElementId(const Node*); // Convert the blink concept of a ScrollTimeline axis into the cc one. // // This implements a subset of the conversions documented in // https://drafts.csswg.org/css-writing-modes-3/#logical-to-physical CompositorScrollTimeline::ScrollDirection CORE_EXPORT ConvertOrientation(ScrollAxis, const ComputedStyle*); absl::optional<ScrollOffsets> CreateScrollOffsets(ScrollTimeline* timeline); } // namespace scroll_timeline_util } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_SCROLL_TIMELINE_UTIL_H_
[ "jengelh@inai.de" ]
jengelh@inai.de
c79f15160604fa40379247a670ed15ec0b92751a
7f1baee32ecbe8cfe81ab3b077f9cb8af98888e7
/hashing/src/MailingAddress.cpp
ea314ef12af16a5171858e56672ed2a2ba283abf
[]
no_license
ypwk/oscarch
f3b461267babf6e2234d6f9a3b17fdbb66b29c0c
b7587617d3ae721ac7f3efc958ca8a606e7c1080
refs/heads/main
2023-04-10T23:33:32.589941
2021-04-18T19:05:22
2021-04-18T19:05:22
359,638,501
1
0
null
null
null
null
UTF-8
C++
false
false
706
cpp
#include "MailingAddress.h" MailingAddress::MailingAddress(string street, string city, string state, int zipCode) { this->street = std::move(street); this->city = std::move(city); this->state = std::move(state); this->zipCode = zipCode; } bool MailingAddress::equals(const MailingAddress &a) { if (this->street != a.street) return false; if (this->city != a.city) return false; if (this->state != a.state) return false; return zipCode == a.zipCode; } string MailingAddress::toString() { string str = "{"; str.append(street).append(", ").append(city).append(", ").append(state).append(", ").append( to_string(zipCode)).append("}"); return str; }
[ "ojcch1@gmail.com" ]
ojcch1@gmail.com
c2b8af72e6a645655f75ca2143f49140750c8982
745d39cad6b9e11506d424f008370b5dcb454c45
/BOJ/6000/6064.cpp
7c96ab0985675375a2204db0b7e80b635b56435d
[]
no_license
nsj6646/PS
0191a36afa0c04451d704d8120dc25f336988a17
d53c111a053b159a0fb584ff5aafc18556c54a1c
refs/heads/master
2020-04-28T09:18:43.333045
2019-06-19T07:19:03
2019-06-19T07:19:03
175,162,727
0
0
null
null
null
null
UTF-8
C++
false
false
821
cpp
#include <cstdio> int gcd(int x, int y) { return y ? gcd(y, x%y) : x; } int lcm(int x, int y) { return x * y / gcd(x, y); } int main() { int t; scanf("%d", &t); while (t--) { int m, n, x, y; scanf("%d %d %d %d", &m, &n, &x, &y); int l = lcm(m, n); int ans = -1; for (int i = 0; i < l / m; i++) { if ((i*m + x - y) % n == 0) { ans = i * m + x; break; } } printf("%d\n", ans); } return 0; } /* #include<cstdio> int t; int m, n, x, y; int gcd(int x, int y) { if (x % y == 0) return y; else return(gcd(y, x%y)); } int main() { scanf("%d", &t); for (int i = 0; i < t; i++) { scanf("%d %d %d %d", &m, &n, &x, &y); int mn = m * n / gcd(m, n); while (x != y && x <= mn) { if (x < y) x += m; else y += n; } if (x != y) printf("-1\n"); else printf("%d\n", x); } } */
[ "nsj6646@gmail.com" ]
nsj6646@gmail.com
1bb447106f346868c32d17cedbc3484d4ad98e67
fa9877968535297eea3ce8157444f73dcfb6be16
/C++/Volume001/AOJ-0165-20121006(素数 範囲内の素数の数 配列確保注意1172のほうがより簡単).cpp
a3033de063927191f9d048f7ffda954b1924430c
[]
no_license
kyos1704/aoj
3681fe9c83ea13bb16f69ef3365819406a4becbb
e5358370668646ee263ba8570b59777f772feb1f
refs/heads/master
2021-01-22T01:05:42.612286
2015-02-17T10:13:42
2015-02-17T10:13:42
9,950,885
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
1,057
cpp
#include<iostream> #include <algorithm> #include<functional>//greater‚ĚŽg—p using namespace std; #define MAX_LIST 999983+100 #define MP 999983 int main(){ bool prime[MAX_LIST]; for(int i=0;i<MAX_LIST;i++){ prime[i]=1; } prime[0]=prime[1]=0; for(int i=0;i*i<MAX_LIST;i++){ if(prime[i]==1){ for(int j=i*2;j<MAX_LIST;j=j+i){ prime[j]=0; } } } for(int i=MP+1;i<MAX_LIST;i++){ prime[i]=0; } int *prime_num=(int*)malloc(sizeof(int)*MAX_LIST); //int prime_num[MAX_LIST]; prime_num[0]=1; for(int i=1;i<MAX_LIST;i++){ prime_num[i]=prime_num[i-1]+prime[i]; } int pair_num; while(cin>>pair_num,pair_num){ int ans=0; for(int i=0;i<pair_num;i++){ int p,m; cin>>p; cin>>m; int x=0; int a,b; if(p+m>MP){ a=MP; }else{ a=p+m; } if(p-m<0){ b=0; }else{ b=p-m; } x=prime_num[a]-prime_num[b]+prime[b]; if(x==0){ ans--; }else{ x--; ans=ans+x; } } cout<<ans<<endl; } return 0; }
[ "kyos.kyos1704@gmail.com" ]
kyos.kyos1704@gmail.com
b4a660e97dcd39a95302debe66fdb0e82c1be8c1
2b932c4047f1898006c81815f78666d06403c4dc
/spisakpasaporasi.cpp
160a1a581b224e67982dc7b2ccb8f73422746ce7
[]
no_license
ZavrenMaturskiEIT/Program2Mini
9e6ce1446ae610c8ffbc84ab116c2d1e3dcacdad
75d1288f524f2480bc737854d5078403b1a14509
refs/heads/master
2020-03-19T06:35:24.577767
2018-06-04T14:22:54
2018-06-04T14:22:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,382
cpp
#include "spisakpasaporasi.h" #include "ui_spisakpasaporasi.h" #include "konekcija.h" #include <QMessageBox> SpisakPasaPoRasi::SpisakPasaPoRasi(QWidget *parent) : QDialog(parent), ui(new Ui::SpisakPasaPoRasi) { ui->setupUi(this); Konekcija baza; baza.dbOpen(); QSqlQuery upit; upit.prepare("SELECT IzlozbaID FROM Izlozba ORDER BY IzlozbaID;"); upit.exec(); QSqlQueryModel *model; model = new QSqlQueryModel(); model->setQuery(upit); ui->comboBoxIzlozba->setModel(model); upit.prepare("SELECT NazivRase FROM Rasa ORDER BY NazivRase;"); upit.exec(); QSqlQueryModel *model2; model2 = new QSqlQueryModel(); model2->setQuery(upit); ui->comboBoxRasa->setModel(model2); baza.dbClose(); } SpisakPasaPoRasi::~SpisakPasaPoRasi() { delete ui; } void SpisakPasaPoRasi::on_pushButtonIzadji_clicked() { this->close(); } void SpisakPasaPoRasi::on_pushButtonPrikazi_clicked() { QString izlozbaID = ui->comboBoxIzlozba->currentText(); QString rasa = ui->comboBoxRasa->currentText(); Konekcija baza; baza.dbOpen(); QSqlQuery upit; upit.prepare("SELECT COUNT (*) FROM Rezultat WHERE IzlozbaID = :izlozbaID AND Rezultat IS NOT NULL;"); upit.bindValue(":izlozbaID", izlozbaID); upit.exec(); upit.next(); ui->labelBrojUcesnika->setText(upit.value(0).toString()); upit.prepare("SELECT COUNT (*) FROM Rezultat INNER JOIN Pas ON Rezultat.PasID = Pas.PasID INNER JOIN Rasa ON Pas.RasaID = Rasa.RasaID WHERE Rezultat.IzlozbaID = :izlozbaID AND Rasa.NazivRase = :rasa AND Rezultat.Rezultat IS NOT NULL;"); upit.bindValue(":izlozbaID", izlozbaID); upit.bindValue(":rasa", rasa); upit.exec(); upit.next(); ui->labelBrojRasaUcestvovali->setText(upit.value(0).toString()); upit.prepare("SELECT Pas.Ime AS [Ime psa] FROM Pas INNER JOIN Rezultat ON Rezultat.PasID = Pas.PasID INNER JOIN Rasa ON Pas.RasaID = Rasa.RasaID WHERE Rezultat.IzlozbaID = :izlozbaID AND Rasa.NazivRase = :rasa AND Rezultat.Rezultat IS NOT NULL;"); upit.bindValue(":izlozbaID", izlozbaID); upit.bindValue(":rasa", rasa); upit.exec(); QSqlQueryModel *model; model = new QSqlQueryModel(); model->setQuery(upit); ui->tableView->setModel(model); baza.dbClose(); }
[ "noreply@github.com" ]
noreply@github.com
77645b80743992e562fa4288bc7a84c1b9008bbe
33035c05aad9bca0b0cefd67529bdd70399a9e04
/src/boost_fusion_include_as_deque.hpp
13314b0f01b9108e436dfbb41471005073f2d976
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
elvisbugs/BoostForArduino
7e2427ded5fd030231918524f6a91554085a8e64
b8c912bf671868e2182aa703ed34076c59acf474
refs/heads/master
2023-03-25T13:11:58.527671
2021-03-27T02:37:29
2021-03-27T02:37:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
45
hpp
#include <boost/fusion/include/as_deque.hpp>
[ "k@kekyo.net" ]
k@kekyo.net
7cd7fbe6ca9761b4f5430af899f1f2ca5086b06c
38d49f62684bc307b9e6f12f1eecab3fa0ff48ea
/Part4_Concurrency/01_Introduction_and_Running_Threads/04_Running_Multiple_Threads/example_1.cpp
ed5b20524f7712e583fff269d2ea1a23e27826f1
[ "MIT" ]
permissive
qqsj789/Cpp_Practice
be5af902b9d72d04f11055bb6b4b295ee988ec16
8a1b628fd9f8c6fe94d6e9bea2126eb773d1b1ce
refs/heads/main
2023-07-17T20:43:31.272384
2021-08-18T20:49:06
2021-08-18T20:49:06
397,718,192
1
0
null
null
null
null
UTF-8
C++
false
false
799
cpp
#include <iostream> #include <thread> #include <vector> void printHello() { // perform work std::cout << "Hello from Worker thread #" << std::this_thread::get_id() << std::endl; } int main() { // create threads std::vector<std::thread> threads; for (size_t i = 0; i < 5; ++i) { // copying thread objects causes a compile error /* std::thread t(printHello); threads.push_back(t); */ // moving thread objects will work threads.emplace_back(std::thread(printHello)); } // do something in main() std::cout << "Hello from Main thread #" << std::this_thread::get_id() << std::endl; // call join on all thread objects using a range-based loop for (auto &t : threads) { t.join(); } return 0; }
[ "qqsj789@gmail.com" ]
qqsj789@gmail.com
9f0aa53291d30c19908c327449623eee69667491
497c6f4c3f5cdb0573a5d892b7a2e2464f5f5b8e
/BigFactorial.cpp
bc00b6e2fbb15646523586f7f67d7bc76ee9a462
[]
no_license
Sanyam96/Programming
cde481359f361d3c055285b5b772525a752be256
507cc12fc124612764764f888720643ff4d76a88
refs/heads/master
2020-12-02T16:38:22.499217
2017-10-26T18:04:24
2017-10-26T18:04:24
96,563,328
0
0
null
null
null
null
UTF-8
C++
false
false
763
cpp
// Program to calculate factorial of bigger numbers /* Factorial of 30 is not calculated by normal method or by Recursion But by using this method we can solve 30! or even higer numbers factorial */ #include <bits/stdc++.h> #define MAX 500 using namespace std; int main(int argc, char const *argv[]){ int a[MAX]; int n = 6; int n2 = n; int i = 0; int x = n; int y; int m = 0; int j; while( x != 0 ) { a[i++] = x % 10; x = x / 10; m++; } for( i = n; i > 1; i--) { int temp=0; int c=i-1; for( j = 0; j < m; j++) { y = a[j] * c + temp; a[j] = y % 10; temp = y / 10; } while( temp != 0) { a[m++] = temp % 10; temp /= 10; } } for( i = m-1; i >= 0; i--) { printf( "%d", a[i]); } cout << endl; return 0; }
[ "sanyam.bvcoe96@gmail.com" ]
sanyam.bvcoe96@gmail.com
765ff02e236283d1d3e23b5277d7a5112fdee93e
7d6a0ba11d7489de73fb171a92ed06c32e8891ec
/ui/modifyinfopage.h
c23352e3917a338313edfdf545da7d028e38279e
[]
no_license
LXZNProject/disnetPackage
a99a0a5c3be5d9f5716b4629503179406aeaa8c5
983fc8b9516e2ce7f2d8c2c3d99ee22cc8d51447
refs/heads/master
2021-09-08T07:14:15.628142
2018-03-08T08:43:44
2018-03-08T08:43:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
859
h
#ifndef MODIFYINFOPAGE_H #define MODIFYINFOPAGE_H #include <QWidget> #include "msgbox.h" #include "keyboard.h" namespace Ui { class modifyINfoPage; } class modifyINfoPage : public QWidget { Q_OBJECT public: explicit modifyINfoPage(QWidget *parent = 0); ~modifyINfoPage(); void timeStart(); private: void initPage(); void dealReadCardInfo(QStringList valueList); void clearInfo(); void setBtnEnable(bool status); QString getStringFromIndex(QString indexStr); bool checkInfo(); signals: void resetTime(); public slots: void okBtn_slots(); void quitBtn_slots(); void readCard_slots(); private: Ui::modifyINfoPage *ui; MsgBox myMsgBox; QTimer *openQueryTimer; QStringList mReadDataList; QTextCodec *tc; int userType; }; #endif // MODIFYINFOPAGE_H
[ "jan.zhang@hansong-china.com" ]
jan.zhang@hansong-china.com
17eb8e21f1458e739108d606c7cdf8d9273304a5
ff16f06c73369efebd5b228241f7145a0496df65
/XFactory.h
f10bbe8391d43d5e09cca520fe71d6a2fe5a9297
[]
no_license
xming4321/asptools
55590c76c4853e83de202d7ad7e2c5a80ba5ff7d
74656c3f7133e9fb3c53dc1efa3975fa9c0f6039
refs/heads/master
2021-01-01T04:55:45.179816
2016-04-12T16:54:29
2016-04-12T16:54:29
56,076,799
9
4
null
null
null
null
UTF-8
C++
false
false
1,692
h
// XFactory.h : Declaration of the CXFactory #pragma once #include "resource.h" // main symbols #include "asptools.h" #if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA) #error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms." #endif // CXFactory class ATL_NO_VTABLE CXFactory : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<CXFactory, &CLSID_XFactory>, public IDispatchImpl<IXFactory, &IID_IXFactory, &LIBID_asptoolsLib, /*wMajor =*/ 1, /*wMinor =*/ 0> { public: CXFactory() { m_pUnkMarshaler = NULL; } DECLARE_REGISTRY_RESOURCEID(IDR_XFACTORY) BEGIN_COM_MAP(CXFactory) COM_INTERFACE_ENTRY(IXFactory) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY_AGGREGATE(IID_IMarshal, m_pUnkMarshaler.p) END_COM_MAP() DECLARE_PROTECT_FINAL_CONSTRUCT() DECLARE_GET_CONTROLLING_UNKNOWN() HRESULT FinalConstruct() { return CoCreateFreeThreadedMarshaler( GetControllingUnknown(), &m_pUnkMarshaler.p); } void FinalRelease() { m_pUnkMarshaler.Release(); } CComPtr<IUnknown> m_pUnkMarshaler; public: STDMETHOD(CreateObject)(BSTR objName, IDispatch** retVal); }; OBJECT_ENTRY_AUTO(__uuidof(XFactory), CXFactory)
[ "xming4321@163.com" ]
xming4321@163.com
794ea7f8482c324df0af67fb768a5693a9e3650c
f7bd0e605a80b57467f5c26917d7ba40d22de9ef
/include/map.hpp
2832c1f264c38dbc36fad68a87160d85126e79f5
[]
no_license
claudehenchoz/ia
6b4fac1181916bc67f91cf52df0c2686282badbf
1fadb3474b5abaa07252ec18f48dac379177eca8
refs/heads/develop
2020-12-25T23:47:55.066398
2017-11-05T10:52:53
2017-11-05T10:52:53
48,068,851
0
0
null
2015-12-15T21:02:45
2015-12-15T21:02:45
null
UTF-8
C++
false
false
2,505
hpp
#ifndef MAP_HPP #define MAP_HPP #include <vector> #include "colors.hpp" #include "item_data.hpp" #include "feature.hpp" #include "config.hpp" #include "actor_player.hpp" #include "fov.hpp" #include "io.hpp" #include "game.hpp" class Rigid; class Mob; struct Cell { Cell(); ~Cell(); void reset(); bool is_explored, is_seen_by_player, is_lit, is_dark; LosResult player_los; // Updated when player updates FOV Item* item; Rigid* rigid; CellRenderData player_visual_memory; P pos; }; enum class MapType { intro, std, egypt, leng, rat_cave, boss, trapez }; struct ChokePointData { ChokePointData() : p (), player_side (-1), stairs_side (-1) { sides[0].resize(0); sides[1].resize(0); } ChokePointData& operator=(const ChokePointData& other) { p = other.p; sides[0] = other.sides[0]; sides[1] = other.sides[1]; return *this; } P p; // These shall only ever have a value of 0 or 1 int player_side; int stairs_side; std::vector<P> sides[2]; }; namespace map { extern Player* player; extern int dlvl; extern Cell cells[map_w][map_h]; extern Clr wall_clr; // This vector is the room owner extern std::vector<Room*> room_list; // Helper array, for convenience and optimization extern Room* room_map[map_w][map_h]; // NOTE: This data is only intended to be used for the purpose of map generation // (and placing items etc), it is NOT updated while playing the map. extern std::vector<ChokePointData> choke_point_data; void init(); void cleanup(); void save(); void load(); void reset_map(); Rigid* put(Rigid* const rigid); // This should be called when e.g. a door closes, or a wall is destoyed - // updates light map, player fov (etc). void update_vision(); void mk_blood(const P& origin); void mk_gore(const P& origin); void delete_and_remove_room_from_list(Room* const room); bool is_pos_seen_by_player(const P& p); Actor* actor_at_pos(const P& pos, ActorState state = ActorState::alive); Mob* first_mob_at_pos(const P& pos); void actor_cells(const std::vector<Actor*>& actors, std::vector<P>& out); void mk_actor_array(Actor* a[map_w][map_h]); Actor* random_closest_actor(const P& c, const std::vector<Actor*>& actors); bool is_pos_inside_map(const P& pos, const bool count_edge_as_inside = true); bool is_area_inside_map(const R& area); } // map #endif // MAP_HPP
[ "m.tornq@gmail.com" ]
m.tornq@gmail.com
e62f979d9d98cdef29d8ff797cc829c0b2da2c64
c619459c8ab6cb317c51716f5be0156714846813
/test/common/test_intensity.cpp
6843040fcedfeb0a47a42ea120f2e7d39f9ddfab
[ "BSD-3-Clause" ]
permissive
psoetens/pcl-svn
127a48c5ab65068fb29070a25b70c2aa2a5cf294
f9baf7fe7760053c9100696b0a3757ceef6b22f7
refs/heads/master
2021-01-20T13:47:50.488296
2012-08-26T21:25:42
2012-08-26T21:25:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,461
cpp
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2012, Willow Garage, 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 the copyright holder(s) 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. * * $Id$ * */ #include <gtest/gtest.h> #include <pcl/pcl_tests.h> #include <pcl/point_types.h> #include <pcl/common/point_operators.h> #include <pcl/common/intensity.h> using namespace pcl; using namespace pcl::test; TEST (PointOperators, PointXYZRGBtoIntensity) { using namespace pcl::common; IntensityFieldAccessor <PointXYZRGB> convert; PointXYZRGB p0; p0.x = 0.1f; p0.y = 0.2f; p0.z = 0.3f; p0.r = 0; p0.g = 127; p0.b = 127; PointXYZRGB p1; p1.x = 0.05f; p1.y = 0.05f; p1.z = 0.05f; p1.r = 0; p1.g = 127; p1.b = 127; float p2 = convert (p0 + p1); EXPECT_EQ (p2, static_cast<float> (299*p0.r + 587*p0.g + 114*p0.b)/1000.0f + static_cast<float> (299*p1.r + 587*p1.g + 114*p1.b)/1000.0f); p2 = 0.1f * convert (p1); EXPECT_NEAR (p2, 0.1 * static_cast<float> (299*p1.r + 587*p1.g + 114*p1.b)/1000.0f, 1e-4); } TEST (PointOperators, PointXYZRGBtoPointXYZI) { using namespace pcl::common; IntensityFieldAccessor <PointXYZRGB> rgb_intensity; IntensityFieldAccessor <PointXYZI> intensity; PointXYZRGB p0; p0.x = 0.1f; p0.y = 0.2f; p0.z = 0.3f; p0.r = 0; p0.g = 127; p0.b = 127; PointXYZRGB p1; p1.x = 0.05f; p1.y = 0.05f; p1.z = 0.05f; p1.r = 0; p1.g = 127; p1.b = 127; float value = rgb_intensity (p0 + p1); PointXYZI p2; intensity.set (p2, value); EXPECT_EQ (p2.intensity, static_cast<float> (299*p0.r + 587*p0.g + 114*p0.b)/1000.0f + static_cast<float> (299*p1.r + 587*p1.g + 114*p1.b)/1000.0f); value = rgb_intensity (p1); intensity.set (p2, rgb_intensity (p1) * 0.1f); EXPECT_NEAR (p2.intensity, static_cast<float> (299*p1.r + 587*p1.g + 114*p1.b) / 1000.0f * 0.1, 1e-4); } int main (int argc, char** argv) { testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); }
[ "rusu@a9d63959-f2ad-4865-b262-bf0e56cfafb6" ]
rusu@a9d63959-f2ad-4865-b262-bf0e56cfafb6
33980a77c985869ef50acb1b86284ff377d7ad9f
bdec79a3d7940c1961d5a214a0eacdab8058ade7
/Jutge-C3/P81104 FIPS.cpp
7d66b6b5419cd07b55edb5b7c9de02fc659427a2
[]
no_license
Angella3/Jutge.org-PRO1
bf807c46bec78af91171b328ee653a357c318ffa
7c8dde079df1d769eb688acbe6da102a68408cb4
refs/heads/master
2021-12-12T12:21:46.889144
2017-01-11T17:19:12
2017-01-11T17:19:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,281
cpp
#include <iostream> #include <vector> using namespace std; struct Subject { string name; // Subject’s name double mark; // Between 0 and 10, -1 shows NP }; struct Student { string name; // Student’s name int idn; // Student’s IDN vector<Subject> subj; // Subject list of the student }; double mark(const vector<Student>& stu, int idn, string name){ // Returns the mark of a student in a subject // Search the student int i = 0; int sizestudents = int(stu.size()); bool encontrado = false; while(!encontrado and i < sizestudents){ if(stu[i].idn == idn) encontrado = true; if(!encontrado)++i; } // Search the subject int j = 0; encontrado = false; int sizesubjects = int(stu[i].subj.size()); if (i < sizestudents){ while(!encontrado and j < sizesubjects){ if(stu[i].subj[j].name == name) encontrado = true; if(!encontrado) ++j; } // Return if correct if (j < sizesubjects and stu[i].subj[j].mark != -1) return stu[i].subj[j].mark; else return -1; } else return -1; } double mean(const vector<Subject>& subj){ // Returns the average mark of a group of subjects double avg = -1; int size = int(subj.size()); int totalsubjects = size; for(int i = 0; i < size; ++i){ if(subj[i].mark != -1){ if(avg != -1) avg += subj[i].mark; else avg = subj[i].mark; } else --totalsubjects; } if(totalsubjects != 0) return avg / (double)totalsubjects; else return -1; } void count(const vector <Student>& stu, int idn , string name, int& counter ){ double compmark = mark(stu,idn,name); counter = 0; int size = int(stu.size()); for(int i = 0; i < size; ++i){ if(mean(stu[i].subj) > compmark) ++counter; } cout << counter << endl; } int main() { int n; cin >> n; vector<Student> stu(n); Student stud; for (int i = 0; i < n; ++i) { int x; cin >> stud.name >> stud.idn >> x; vector<Subject> subj(x); Subject sub; for (int j = 0; j < x; ++j) { cin >> sub.name >> sub.mark; subj[j] = sub; } stud.subj = subj; stu[i] = stud; } int counter; int idn; string name; while (cin >> idn and cin >> name) { count(stu,idn,name,counter); } }
[ "rob.ariosa@hotmail.com" ]
rob.ariosa@hotmail.com
ed41aa3ca29d36ed1de35df52951034d45bfb149
f0924143f41ece9c7310c0e850c88121f16f7da0
/src/test/sanity_tests.cpp
63139ec8a3b6d9109ef9b54eb097d7d386d95fb7
[ "MIT" ]
permissive
Mogoai/Franc
a8cb6c33b7f29ac475f785d7ecf895f1fa481da9
f9e7c0ca447077c512add17cae557bf1d59e3d88
refs/heads/master
2020-05-04T15:02:47.497587
2019-04-23T09:58:37
2019-04-23T09:58:37
179,221,510
2
0
null
null
null
null
UTF-8
C++
false
false
655
cpp
// Copyright (c) 2012-2018 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 <compat/sanity.h> #include <key.h> #include <test/test_franc.h> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(sanity_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(basic_sanity) { BOOST_CHECK_MESSAGE(glibc_sanity_test() == true, "libc sanity test"); BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test"); BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "openssl ECC test"); } BOOST_AUTO_TEST_SUITE_END()
[ "pagde@orange.fr" ]
pagde@orange.fr
16526230bcff3de461a08291c2ec18e9409b9072
77a9682fb86b5f417615562063fca1eea6c6246c
/src/lib/random.cpp
40501b8646ada15e29a2af9fc2d0253ee629863b
[]
no_license
seanigami/RDPSOVina
9f64f858260aecdd5e8992a2e420942f45453336
3e17948904696fbb2679d6e467b321fef2bdf1ec
refs/heads/master
2023-07-27T19:45:02.128838
2021-09-06T08:40:46
2021-09-06T08:40:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,013
cpp
/* Copyright (c) 2006-2010, The Scripps Research Institute 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. Author: Dr. Oleg Trott <ot14@columbia.edu>, The Olson Lab, The Scripps Research Institute */ #include <ctime> // for time (for seeding) #include "random.h" #include "my_pid.h" fl random_fl(fl a, fl b, rng& generator) { // expects a < b, returns rand in [a, b] assert(a < b); // BOOST also asserts a < b typedef boost::uniform_real<fl> distr; boost::variate_generator<rng&, distr> r(generator, distr(a, b)); fl tmp = r(); assert(tmp >= a); assert(tmp <= b); return tmp; } fl random_normal(fl mean, fl sigma, rng& generator) { // expects sigma >= 0 assert(sigma >= 0); // BOOST asserts this as well typedef boost::normal_distribution<fl> distr; boost::variate_generator<rng&, distr> r(generator, distr(mean, sigma)); return r(); } int random_int(int a, int b, rng& generator) { // expects a <= b, returns rand in [a, b] assert(a <= b); // BOOST asserts this as well typedef boost::uniform_int<int> distr; boost::variate_generator<rng&, distr> r(generator, distr(a, b)); int tmp = r(); assert(tmp >= a); assert(tmp <= b); return tmp; } double random_double(double a, double b, rng& generator) { // expects a <= b, returns rand in [a, b] assert(a <= b); // BOOST asserts this as well typedef boost::uniform_real<double> distr; boost::variate_generator<rng&, distr> r(generator, distr(a, b)); double tmp = r(); assert(tmp >= a); assert(tmp <= b); return tmp; } sz random_sz(sz a, sz b, rng& generator) { // expects a <= b, returns rand in [a, b] assert(a <= b); assert(int(a) >= 0); assert(int(b) >= 0); int i = random_int(int(a), int(b), generator); assert(i >= 0); assert(i >= int(a)); assert(i <= int(b)); return static_cast<sz>(i); } vec random_inside_sphere(rng& generator) { while(true) { // on average, this will have to be run about twice fl r1 = random_fl(-1, 1, generator); fl r2 = random_fl(-1, 1, generator); fl r3 = random_fl(-1, 1, generator); vec tmp(r1, r2, r3); if(sqr(tmp) < 1) return tmp; } } vec random_in_box(const vec& corner1, const vec& corner2, rng& generator) { // expects corner1[i] < corner2[i] vec tmp; VINA_FOR_IN(i, tmp) tmp[i] = random_fl(corner1[i], corner2[i], generator); return tmp; } int auto_seed() { // make seed from PID and time return my_pid() * int(std::time(NULL)); }
[ "noreply@github.com" ]
noreply@github.com
04e83a4925d9da149e751c409bde0a13b975a16f
4fa3ccc28769d384af2a1127eb2c19fc96432013
/TeamProjectRPGgame/playAudioEvent.h
fdd4d763cbd754f74071f08e3fac2c3705d03494
[]
no_license
klecior/TeamRPGgameProject
de6b2a3309d236dc8835ed102f82ed5274ba6235
9bbdba956b1c3d2844abe6b3b2ff09f3e5ff2455
refs/heads/master
2021-01-01T05:29:18.179348
2016-06-06T20:52:28
2016-06-06T20:52:28
57,945,213
0
0
null
2016-05-24T14:39:28
2016-05-03T06:04:21
C
UTF-8
C++
false
false
304
h
#pragma once #include "abstractEvent.h" #include <string> class playAudioEvent : public abstractEvent { public: playAudioEvent(std::string path, bool music, bool playing); virtual eventTypeId getEventType()const override { return playAudioMessage; } std::string filePath; bool isMusic, isPlaying; };
[ "klecior@gmail.com" ]
klecior@gmail.com
50dfe0c1a5eab5e0893bc1948a49bf31002c81c5
9fcfa82b3f2415a467d99c05996991ec08533fce
/illumina/Classes/Door.h
ae896b8adb97227ab9724c1a2d1cb1e1ecb441b1
[]
no_license
YoonI3in/Illumina
040fa1dcb8c52ee3e783e30981da13708d02f03c
da55ec96cc3fdf077eea4d23b9709cc33a94350c
refs/heads/master
2020-06-02T13:25:28.960835
2019-06-10T13:12:33
2019-06-10T13:12:33
191,168,748
0
0
null
null
null
null
UTF-8
C++
false
false
214
h
#pragma once #include <cocos2d.h> USING_NS_CC; class Door :public Sprite { protected: Sprite* door; Vec2 door_Pos; Rect door_Rect; public: CREATE_FUNC(Door); virtual bool init(); Rect BoundingBox(); };
[ "zmfflswj@naver.com" ]
zmfflswj@naver.com
006138b1a019f94e334bcdc4aa4842bb9879d791
cf16911bc92458e31c8accb95f2062dcdea75ff2
/SoC-Validation/firmware/AV417/standalone_codecs/H264_Decoder/H264DecoderLib/H264SIMDDec/AuroraH264Deblock.cpp
11d6f9d897b87d17c8300098451a7702e760f249
[]
no_license
alexvatti/embedded-documents
b4f7a789f66dad592a655677788da4003df29082
5bcf34328a4f19c514c1bca12ad52dcc06e60f09
refs/heads/master
2023-08-14T20:23:00.180050
2019-11-29T10:48:05
2019-11-29T10:48:05
224,813,397
0
0
null
null
null
null
UTF-8
C++
false
false
57,828
cpp
/* CONFIDENTIAL AND PROPRIETARY INFORMATION */ /* Copyright 2006 ARC International (Unpublished) */ /* All Rights Reserved. */ /* */ /* This document, material and/or software contains confidential */ /* and proprietary information of ARC International and is */ /* protected by copyright, trade secret and other state, federal, */ /* and international laws, and may be embodied in patents issued */ /* or pending. Its receipt or possession does not convey any */ /* rights to use, reproduce, disclose its contents, or to */ /* manufacture, or sell anything it may describe. Reverse */ /* engineering is prohibited, and reproduction, disclosure or use */ /* without specific written authorization of ARC International is */ /* strictly forbidden. ARC and the ARC logotype are trademarks of */ /* ARC International. */ #ifdef _WIN32 #include "StdAfx.h" #else #include <stdio.h> #endif #include "ARCMedia.h" #include "AuroraH264Dec.h" #include "H264Tables.h" #if defined __ARC_MPLAYER__ extern "C" { #include "memctl.h" } #endif // DEBLOCK functions #ifdef AURORA_DEBLOCK /* Transpose an 8x8 matrix in vector registers R1 to R8 */ #define TRANSPOSE(VR1,VR2,VR3,VR4,VR5,VR6,VR7,VR8) \ vexch1 %vr##VR1,%vr##VR2 ` \ vexch1 %vr##VR3,%vr##VR4 ` \ vexch1 %vr##VR5,%vr##VR6 ` \ vexch1 %vr##VR7,%vr##VR8 ` \ vexch2 %vr##VR1,%vr##VR3 ` \ vexch2 %vr##VR2,%vr##VR4 ` \ vexch2 %vr##VR5,%vr##VR7 ` \ vexch2 %vr##VR6,%vr##VR8 ` \ vexch4 %vr##VR1,%vr##VR5 ` \ vexch4 %vr##VR2,%vr##VR6 ` \ vexch4 %vr##VR3,%vr##VR7 ` \ vexch4 %vr##VR4,%vr##VR8 /* ; H264 deblocking ; ---- ---------- ; NOT FULLY OPTIMIZED ; Two cases of memory alignment for an edge ; On 4 or 8 pixel alignment ; Macro block buffer (Luma) ; 0 4 8 24 ; 0xxxxxxxx................ p3 ; xxxxxxxx................ p2 ; xxxxxxxx................ p1 ; xxxxxxxx................ p0 ; 4xxxx....**************** q0< * Macro block edge ; xxxx....*...+...+...+... q1 + Internal edge ; xxxx....*...+...+...+... q2 . pixels ; xxxx....*...+...+...+... q3 x unknown ; xxxx....*+++++++++++++++ ; xxxx....*...+...+...+... ; xxxx....*...+...+...+... ; xxxx....*...+...+...+... ; xxxx....*+++++++++++++++ ; xxxx....*...+...+...+... ; xxxx....*...+...+...+... ; xxxx....*...+...+...+... ; xxxx....*+++++++++++++++ ; xxxx....*...+...+...+... ; xxxx....*...+...+...+... ; xxxx....*...+...+...+... ;24 1st 2nd 3rd 4th ; A A ; | | ; ppppqqqq ; 32100123 ; (8 pixel aligned edges) ; Macro block buffer (Chroma) ; ;; 0 4 8 16 ; 0xxxxxxxx........ ; xxxxxxxx........ ; 2xxxxxx..******** ; xxxxxx..*...+... ; xxxxxx..*...+... ; xxxxxx..*...+... ; xxxxxx..*+++++++ ; xxxxxx..*...+... ; xxxxxx..*...+... ; xxxxxx..*...+... ; A A ; | | ; ppqqppqq ; 10011001 */ #if defined(I32K_D32K) || defined(I16K_D16K) || defined(I8K_D8K) #pragma Code("codesec3") #endif // Move overlap area for next block _Asm int MACRO_MoveForNextBlockL( int addr) { %reg addr vrec addr // Move luma data ptr in %i0 vld32 %vr01,[%i0,20+0 ] vld32 %vr02,[%i0,20+24] vld32 %vr03,[%i0,20+48] vld32 %vr04,[%i0,20+72] vst32 %vr01,[%i0,4+0 ] vst32 %vr02,[%i0,4+24] vst32 %vr03,[%i0,4+48] vst32 %vr04,[%i0,4+72] vld32 %vr01,[%i0,20+0 +96] vld32 %vr02,[%i0,20+24+96] vld32 %vr03,[%i0,20+48+96] vld32 %vr04,[%i0,20+72+96] vst32 %vr01,[%i0,4+0 +96] vst32 %vr02,[%i0,4+24 +96] vst32 %vr03,[%i0,4+48 +96] vst32 %vr04,[%i0,4+72 +96] vld32 %vr01,[%i0,20 +192] vld32 %vr02,[%i0,20+24+192] vld32 %vr03,[%i0,20+48+192] vld32 %vr04,[%i0,20+72+192] vst32 %vr01,[%i0,4 +192] vst32 %vr02,[%i0,4+24+192] vst32 %vr03,[%i0,4+48+192] vst32 %vr04,[%i0,4+72+192] vld32 %vr01,[%i0,20 +288] vld32 %vr02,[%i0,20+24+288] vld32 %vr03,[%i0,20+48+288] vld32 %vr04,[%i0,20+72+288] vst32 %vr01,[%i0,4 +288] vst32 %vr02,[%i0,4+24+288] vst32 %vr03,[%i0,4+48+288] vst32 %vr04,[%i0,4+72+288] vld32 %vr01,[%i0,20 +384] vld32 %vr02,[%i0,20+24+384] vld32 %vr03,[%i0,20+48+384] // vld32 %vr04,[%i0,20+72+384] vst32 %vr01,[%i0,4 +384] vst32 %vr02,[%i0,4+24+384] vst32 %vr03,[%i0,4+48+384] // vst32 %vr04,[%i0,4+72+384] vendrec %r0 } _Asm int MACRO_MoveForNextBlockU( int addr) { %reg addr vrec addr // Move chroma u data ptr in %i1 vld32 %vr01,[%i1,12] vld32 %vr02,[%i1,12+16] vld32 %vr03,[%i1,12+32] vld32 %vr04,[%i1,12+48] vst32 %vr01,[%i1,4] vst32 %vr02,[%i1,4+16] vst32 %vr03,[%i1,4+32] vst32 %vr04,[%i1,4+48] vld32 %vr01,[%i1,12+64] vld32 %vr02,[%i1,12+16+64] vld32 %vr03,[%i1,12+32+64] vld32 %vr04,[%i1,12+48+64] vst32 %vr01,[%i1,4+64] vst32 %vr02,[%i1,4+16+64] vst32 %vr03,[%i1,4+32+64] vst32 %vr04,[%i1,4+48+64] vld32 %vr01,[%i1,12+128] vst32 %vr01,[%i1,4+128] vendrec %r0 } _Asm int MACRO_MoveForNextBlockV( int addr) { %reg addr vrec addr // Move chroma v data ptr in %i2 vld32 %vr01,[%i2,12] vld32 %vr02,[%i2,12+16] vld32 %vr03,[%i2,12+32] vld32 %vr04,[%i2,12+48] vst32 %vr01,[%i2,4] vst32 %vr02,[%i2,4+16] vst32 %vr03,[%i2,4+32] vst32 %vr04,[%i2,4+48] vld32 %vr01,[%i2,12+64] vld32 %vr02,[%i2,12+16+64] vld32 %vr03,[%i2,12+32+64] vld32 %vr04,[%i2,12+48+64] vst32 %vr01,[%i2,4+64] vst32 %vr02,[%i2,4+16+64] vst32 %vr03,[%i2,4+32+64] vst32 %vr04,[%i2,4+48+64] vld32 %vr01,[%i2,12+128] vst32 %vr01,[%i2,4+128] vendrec %r0 } #if defined(I32K_D32K) || defined(I16K_D16K) || defined(I8K_D8K) #pragma Code() #endif _Asm void ASMSetupDeblockDMA( int frameTabAddr) { %reg frameTabAddr // For DMA in // vdiwr %dr0,SDM_d ;// SDM destination addr // vdiwr %dr1,24 ;// SDM Stride always 24 // vdiwr %dr2,0x001414 ;// idx 0, blk_ver_size<<8 || block_hor_size vdiwr %dr6,2 ;// Clip mode - NON INTERLACE vdiwr %dr7, frameTabAddr ;// SDM frame table address // For DMA out // vdowr %dr1,24 ;// SDM Stride always 24 // vdowr %dr6,2 ;// Clip mode - NON INTERLACE vdowr %dr7, frameTabAddr ;// SDM frame table address } // Setup frame table 0 for 20 x 20 DMA from referance pitctue void AuroraH264Dec::SetupDeblockDMA(unsigned char * pic_y, unsigned char * pic_u, unsigned char * pic_v, int picWidth, int picHeight) { unsigned int sdm_frame_table_add = m_dma_frames; unsigned int ref_pic_phy_add; // Luma #if defined(__ARC_MPLAYER__) ref_pic_phy_add = h264_get_physical_adrs( (unsigned int) pic_y); #else ref_pic_phy_add = (unsigned int) pic_y; #endif SetDMAFrame(sdm_frame_table_add /* frame table offset from sdm-base*/, ref_pic_phy_add /* inp add in ARC memory */, picWidth /* Stride */, picWidth /* xDim */, picHeight /* yDim */); // Chroma u #if defined(__ARC_MPLAYER__) ref_pic_phy_add = h264_get_physical_adrs( (unsigned int) pic_u); #else ref_pic_phy_add = (unsigned int) pic_u; #endif SetDMAFrame(sdm_frame_table_add+16 /* frame table offset from sdm-base*/, ref_pic_phy_add /* inp add in ARC memory */, picWidth/2 /* Stride */, picWidth/2 /* xDim */, picHeight/2 /* yDim */); // Chroma v #if defined(__ARC_MPLAYER__) ref_pic_phy_add = h264_get_physical_adrs( (unsigned int) pic_v); #else ref_pic_phy_add = (unsigned int) pic_v; #endif SetDMAFrame(sdm_frame_table_add+32 /* frame table offset from sdm-base*/, ref_pic_phy_add /* inp add in ARC memory */, picWidth/2 /* Stride */, picWidth/2 /* xDim */, picHeight/2 /* yDim */); ASMSetupDeblockDMA(sdm_frame_table_add>>9); } #if defined(I32K_D32K) || defined(I16K_D16K) || defined(I8K_D8K) #pragma Code("codesec2") #endif _Asm int MACRO_VerticalFilter2(int addr) { %reg addr vrec addr //------ //; VR07 - p3 //; VR08 - p2 //; VR09 - p1 //; VR10 - p0 //; VR11 - q0 //; VR12 - q1 //; VR13 - q2 //; VR14 - q3 vld64w %vr04,[%i1,0] ;// p3 vld64w %vr05,[%i1,24] ;// p2 vld64w %vr06,[%i1,48] ;// p1 vld64w %vr07,[%i1,72] ;// p0 vld64w %vr08,[%i1,96] ;// q0 vld64w %vr09,[%i1,120] ;// q1 vld64w %vr10,[%i1,144] ;// q2 vld64w %vr11,[%i1,168] ;// q3 TRANSPOSE(04,05,06,07,08,09,10,11); vh264ft %vr12, %vr04, %vr01 ;// vh264ft %vr13, %vr05, %vr01 ;// vh264ft %vr14, %vr06, %vr01 ;// vh264ft %vr15, %vr07, %vr01 ;// vh264ft %vr16, %vr08, %vr01 ;// vh264ft %vr17, %vr09, %vr01 ;// vh264ft %vr18, %vr10, %vr01 ;// vh264ft %vr19, %vr11, %vr01 ;// vh264fw %vr04, %vr04, %vr12 ;// vh264fw %vr05, %vr05, %vr13 ;// vh264fw %vr06, %vr06, %vr14 ;// vh264fw %vr07, %vr07, %vr15 ;// vh264fw %vr08, %vr08, %vr16 ;// vh264fw %vr09, %vr09, %vr17 ;// vh264fw %vr10, %vr10, %vr18 ;// vh264fw %vr11, %vr11, %vr19 ;// TRANSPOSE(04,05,06,07,08,09,10,11); vasrpwb %vr05, %vr05, 0 ;// p2 Pack to bytes vasrpwb %vr06, %vr06, 0 ;// p1 vasrpwb %vr07, %vr07, 0 ;// p0 vasrpwb %vr08, %vr08, 0 ;// q0 vasrpwb %vr09, %vr09, 0 ;// q1 vasrpwb %vr10, %vr10, 0 ;// q2 vst64 %vr05,[%i1,24] ;// p2 vst64 %vr06,[%i1,48] ;// p1 vst64 %vr07,[%i1,72] ;// p0 vst64 %vr08,[%i1,96] ;// q0 vst64 %vr09,[%i1,120] ;// q1 vst64 %vr10,[%i1,144] ;// q2 vbaddw %vr00,%vr00,8 // Next 2 edges along vendrec %r0 } // Now does 2 edges at a time _Asm int MACRO_StrongVerticalFilter(int addr) { %reg addr vrec addr //------ //; VR07 - p3 //; VR08 - p2 //; VR09 - p1 //; VR10 - p0 //; VR11 - q0 //; VR12 - q1 //; VR13 - q2 //; VR14 - q3 vld64w %vr07,[%i1,0] ;// p3 vld64w %vr08,[%i1,24] ;// p2 vld64w %vr09,[%i1,48] ;// p1 vld64w %vr10,[%i1,72] ;// p0 vld64w %vr11,[%i1,96] ;// q0 vld64w %vr12,[%i1,120] ;// q1 vld64w %vr13,[%i1,144] ;// q2 vld64w %vr14,[%i1,168] ;// q3 vdifw %vr20, %vr10, %vr11 ;// | p0-q0 | for enable vdifw %vr21, %vr09, %vr10 ;// | p1-p0 | .. vdifw %vr22, %vr11, %vr12 ;// | q0-q1 | .. vasrw %vr23, %vr01, 2 ;// (alpha >> 2) for Sg vbaddw %vr23, %vr23, 2 ;// (alpha >> 2) + 2 for Sg vdifw %vr04, %vr08, %vr10 ;// | p2-p0 | for ApD vdifw %vr05, %vr13, %vr11 ;// | q2-q0 | for AqD vltw %vr06, %vr20, %vr01 ;// | p0-q0 | < alpha for enable vltw %vr17, %vr21, %vr02 ;// | p1-p0 | < beta .. vltw %vr18, %vr22, %vr02 ;// | q0-q1 | < beta .. vltw %vr04, %vr04, %vr02 ;// ApD vltw %vr05, %vr05, %vr02 ;// AqD vand %vr06, %vr06, %vr17 ;// for enable vaddw %vr15, %vr08, %vr12 ;// p2 + q1 for P0 ApD&Sg vaddaw %vr15, %vr09, %vr09 ;// +p1 + p1 vaddaw %vr15, %vr10, %vr10 ;// +p0 + p0 vaddaw %vr15, %vr11, %vr11 ;// +q0 + q0 vltw %vr23, %vr20, %vr23 ;// Sg vand %vr06, %vr06, %vr18 ;// Enable vaddw %vr16, %vr08, %vr09 ;// p2 + p1 for P1 ApD&Sg vaddaw %vr16, %vr10, %vr11 ;// +p0 + q0 vaddw %vr17, %vr08, %vr09 ;// p2 + p1 for P2 ApD&Sg vaddaw %vr17, %vr10, %vr11 ;// +p0 + q0 vaddaw %vr17, %vr07, %vr07 ;// +p3 + p3 vaddaw %vr17, %vr08, %vr08 ;// +p2 + p2 vand %vr04, %vr04, %vr23 ;// ApD&Sg vand %vr05, %vr05, %vr23 ;// AqD&Sg vaddw %vr18, %vr10, %vr12 ;// p0 + q1 for P0_NOT_ApD&Sg vaddaw %vr18, %vr09, %vr09 ;// +p1 + p1 vaddw %vr19, %vr09, %vr13 ;// p1 + q2 for Q0 AqD&Sg vaddaw %vr19, %vr10, %vr10 ;// +p0 + p0 vaddaw %vr19, %vr11, %vr11 ;// +q0 + q0 vaddaw %vr19, %vr12, %vr12 ;// +q1 + q1 vbic %vr23, %vr06, %vr04 ;// Enable & NOT ApD&Sg vbic %vr07, %vr06, %vr05 ;// Enable & NOT AqD&Sg vand %vr04, %vr06, %vr04 ;// Enable & ApD&Sg vand %vr05, %vr06, %vr05 ;// Enable & AqD&Sg vaddw %vr20, %vr10, %vr11 ;// p0 + q0 for Q1 AqD&Sg vaddaw %vr20, %vr12, %vr13 ;// +q1 + q2 vaddw %vr21, %vr13, %vr12 ;// q2 + q1 for Q2 AqD&Sg vaddaw %vr21, %vr11, %vr10 ;// +q0 + p0 vaddaw %vr21, %vr14, %vr14 ;// +q3 + q3 vaddaw %vr21, %vr13, %vr13 ;// +q2 + q2 vaddw %vr22, %vr11, %vr09 ;// q0 + p1 for Q0_NOT_AqD&Sg vaddaw %vr22, %vr12, %vr12 ;// +q1 + q1 vasrrw %vr15, %vr15, 3 ;// P0 ApD&Sg vasrrw %vr16, %vr16, 2 ;// P1 ApD&Sg vasrrw %vr17, %vr17, 3 ;// P2 ApD&Sg vasrrw %vr18, %vr18, 2 ;// P0_NOT_ApD&Sg vasrrw %vr19, %vr19, 3 ;// Q0 AqD&Sg vasrrw %vr20, %vr20, 2 ;// Q1 AqD&Sg vasrrw %vr21, %vr21, 3 ;// Q2 AqD&Sg vasrrw %vr22, %vr22, 2 ;// Q0_NOT_AqD&Sg // vsubw %vr17,%vr17,%vr17); vbic %vr08, %vr08, %vr04 ;// p2 & !(Enable & ApD&Sg) for p2 vandaw %vr08, %vr17, %vr04 ;// +P2 & Enable & ApD&Sg vbic %vr09, %vr09, %vr04 ;// p1 & !Enable for p1 vandaw %vr09, %vr16, %vr04 ;// +P1 & Enable & ApD&Sg vbic %vr10, %vr10, %vr06 ;// p0 & !Enable for p0 vandaw %vr10, %vr15, %vr04 ;// +P0 & Enable & ApD&Sg vandaw %vr10, %vr18, %vr23 ;// +P0_NOT_ApD&Sg & (Enable & NOT ApD&Sg) vbic %vr11, %vr11, %vr06 ;// q0 & Not Enable for q0 vandaw %vr11, %vr19, %vr05 ;// +Q0 & Enable & AqD&Sg vandaw %vr11, %vr22, %vr07 ;// +Q0_NOT_AqD&Sg & (Enable & NOT AqD&Sg) vbic %vr12, %vr12, %vr05 ;// q1 & !(Enable & AqD&Sg) for q1 vandaw %vr12, %vr20, %vr05 ;// +Q1 & Enable & AqD&Sg vbic %vr13, %vr13, %vr05 ;// q2 & !(Enable & AqD&Sg) for q2 vandaw %vr13, %vr21, %vr05 ;// +Q2 & Enable & AqD&Sg vasrpwb %vr08, %vr08, 0 ;// p2 Pack to bytes vasrpwb %vr09, %vr09, 0 ;// p1 vasrpwb %vr10, %vr10, 0 ;// p0 vasrpwb %vr11, %vr11, 0 ;// q0 vasrpwb %vr12, %vr12, 0 ;// q1 vasrpwb %vr13, %vr13, 0 ;// q2 vst64 %vr08,[%i1,24] ;// p2 vst64 %vr09,[%i1,48] ;// p1 vst64 %vr10,[%i1,72] ;// p0 vst64 %vr11,[%i1,96] ;// q0 vst64 %vr12,[%i1,120] ;// q1 vst64 %vr13,[%i1,144] ;// q2 vbaddw %vr00,%vr00,8 // Next 2 edges along //------ // vor %vr23,%vr23,%vr23 vendrec %r0 } _Asm int MACRO_NormalVerticalFilter(int addr) { %reg addr vrec addr //------ vld64w %vr07,[%i1,0] ;// p3 vld64w %vr08,[%i1,24] ;// p2 vld64w %vr09,[%i1,48] ;// p1 vld64w %vr10,[%i1,72] ;// p0 vld64w %vr11,[%i1,96] ;// q0 vld64w %vr12,[%i1,120] ;// q1 vld64w %vr13,[%i1,144] ;// q2 vld64w %vr14,[%i1,168] ;// q3 // Ordiary filter vdifw %vr20, %vr10/*P0*/, %vr11/*Q0*/ ;// | p0-q0 | for enable vdifw %vr21, %vr09/*P1*/, %vr10/*P0*/ ;// | p1-p0 | .. vdifw %vr22, %vr11/*Q0*/, %vr12/*Q1*/ ;// | q0-q1 | .. vdifw %vr19, %vr08/*P2*/, %vr10/*P0*/ ;// | p2-p0 | for ApD vdifw %vr23, %vr13/*Q2*/, %vr11/*Q0*/ ;// | q2-q0 | for AqD vltw %vr04, %vr20, %vr01 ;// | p0-q0 | < alpha for enable vltw %vr05, %vr21, %vr02 ;// | p1-p0 | < beta .. vltw %vr17, %vr22, %vr02 ;// | q0-q1 | < beta .. vltw %vr19, %vr19, %vr02 ;// ApD vltw %vr23, %vr23, %vr02 ;// AqD vsubw %vr20, %vr11/*Q0*/, %vr10/*P0*/ ;// q0 - p0 for delta vand %vr04, %vr04, %vr05 ;// for enable vaddw %vr22, %vr10/*P0*/, %vr11/*Q0*/ ;// p0 + q0 for p0q0rs1 vsubw %vr05, %vr03, %vr19 ;// C0 - ApD (-1=true) for +C vaddw %vr16, %vr20, %vr20 ;// q0-p0 + q0-p0 for delta vaddaw %vr16, %vr20, %vr20 ;// +q0-p0 + q0-p0 vsubaw %vr16, %vr09/*P1*/, %vr12/*Q1*/ ;// +p1 - q1 vsubw %vr05, %vr05, %vr23 ;// + C0 + ApD - AqD +C vasrrw %vr22, %vr22, 1 ;// p0q0rs1 vand %vr04, %vr04, %vr17 ;// Enable vasrrw %vr16, %vr16, 3 ;// for delta vand %vr19, %vr19, %vr04 ;// ApD & Enable vand %vr23, %vr23, %vr04 ;// AqD & Enable vand %vr05, %vr05, %vr04 ;// Mask C with enable vsubw %vr17, %vr22, %vr09/*P1*/ ;// p0q0rs1 - p1 for P1 vsubaw %vr17, %vr08/*P2*/, %vr09/*P1*/ ;// +p2 + -p1 vsubw %vr18, %vr22, %vr12/*Q1*/ ;// p0q0rs1 - q1 for Q1 vsubaw %vr18, %vr13/*Q2*/, %vr12/*Q1*/ ;// +q2 + -q1 vbmulw %vr06, %vr05, -1 ;// -C vbmulw %vr21, %vr03, -1 ;// -Co vminw %vr20, %vr16, %vr05 ;// Min delta, C vasrw %vr17, %vr17, 1 ;// for P1 vasrw %vr18, %vr18, 1 ;// for Q1 vmaxw %vr20, %vr20, %vr06 ;// Max delta, -C delta vminw %vr17, %vr17, %vr03 ;// min P1, C0 for P1 vminw %vr18, %vr18, %vr03 ;// min Q1, C0 for Q1 vaddw %vr10, %vr10/*P0*/, %vr20 ;// p0 + delta P0 vsubw %vr11, %vr11/*Q0*/, %vr20 ;// q0 - delta Q0 vmaxw %vr17, %vr17, %vr21 ;// max P1, -C0 for P1 vmaxw %vr18, %vr18, %vr21 ;// max Q1, -C0 for Q1 vaddw %vr17, %vr09/*P1*/, %vr17 ;// p1 + P1 P1 vaddw %vr18, %vr12/*Q1*/, %vr18 ;// q1 + Q1 Q1 vbic %vr09/*P1*/, %vr09/*P1*/, %vr19 ;// p1 & not ApD&Enable vandaw %vr09/*P1*/, %vr17, %vr19 ;// +P1 & ApD&Enable vbic %vr12/*Q1*/, %vr12/*Q1*/, %vr23 ;// q1 & not AqD&Enable vandaw %vr12/*Q1*/, %vr18, %vr23 ;// +Q1 & AqD&Enable vasrpwb %vr09/*P1*/, %vr09/*P1*/, 0 ;// p1 Pack to bytes vasrpwb %vr10/*P0*/, %vr10/*P0*/, 0 ;// p0 vasrpwb %vr11/*Q0*/, %vr11/*Q0*/, 0 ;// q0 vasrpwb %vr12/*Q1*/, %vr12/*Q1*/, 0 ;// q1 vst64 %vr09,[%i1,48] ;// p1 vst64 %vr10,[%i1,72] ;// p0 vst64 %vr11,[%i1,96] ;// q0 vst64 %vr12,[%i1,120] ;// q1 //------ // vor %vr23,%vr23,%vr23 vendrec %r0 } _Asm int MACRO_HorzontalFilterAligned(int addr) { %reg addr vrec addr // vdiwr %dr6,2 ;// Clip mode - NON INTERLACE(block on DMA in not complete vld64w %vr07,[%i1,0+96] ;// 0 vld64w %vr08,[%i1,24+96] ;// 1 vld64w %vr09,[%i1,48+96] ;// 2 vld64w %vr10,[%i1,72+96] ;// 3 vbaddw %vr00,%vr00,96 ;// %I1 to Edge below vh264ft %vr11, %vr07, %vr01 ;// vh264ft %vr12, %vr08, %vr01 ;// vh264ft %vr13, %vr09, %vr01 ;// vh264ft %vr14, %vr10, %vr01 ;// vh264f %vr07, %vr07, %vr11 ;// vh264f %vr08, %vr08, %vr12 ;// vh264f %vr09, %vr09, %vr13 ;// vh264f %vr10, %vr10, %vr14 ;// vst64 %vr07,[%i1,0] ;// 0 vst64 %vr08,[%i1,24] ;// 1 vst64 %vr09,[%i1,48] ;// 2 vst64 %vr10,[%i1,72] ;// 3 //------ // vor %vr23,%vr23,%vr23 vendrec %r0 } _Asm int MACRO_HorzontalFilter(int addr) { %reg addr vrec addr // vdiwr %dr6,2 ;// Clip mode - NON INTERLACE(block on DMA in not complete vld32wl %vr07,[%i1,0+96] ;// 0 vld32wh %vr07,[%i1,0+4+96] ;// 0 vld32wl %vr08,[%i1,24+96] ;// 1 vld32wh %vr08,[%i1,24+4+96] ;// 1 vld32wl %vr09,[%i1,48+96] ;// 2 vld32wh %vr09,[%i1,48+4+96] ;// 2 vld32wl %vr10,[%i1,72+96] ;// 3 vld32wh %vr10,[%i1,72+4+96] ;// 3 vbaddw %vr00,%vr00,96 ;// %I1 to Edge below vh264ft %vr11, %vr07, %vr01 ;// vh264ft %vr12, %vr08, %vr01 ;// vh264ft %vr13, %vr09, %vr01 ;// vh264ft %vr14, %vr10, %vr01 ;// vh264f %vr07, %vr07, %vr11 ;// vh264f %vr08, %vr08, %vr12 ;// vh264f %vr09, %vr09, %vr13 ;// vh264f %vr10, %vr10, %vr14 ;// vst32 %vr07,[%i1,0] ;// 0 vst32 %vr08,[%i1,24] ;// 1 vst32 %vr09,[%i1,48] ;// 2 vst32 %vr10,[%i1,72] ;// 3 vst32_2 %vr07,[%i1,0+4] ;// 0 vst32_2 %vr08,[%i1,24+4] ;// 1 vst32_2 %vr09,[%i1,48+4] ;// 2 vst32_2 %vr10,[%i1,72+4] ;// 3 //------ // vor %vr23,%vr23,%vr23 vendrec %r0 } //------------------------------------------------------------ // TODO Optimize _Asm int MACRO_LoopFilterEdgeChromaHorizontal(int addr) { %reg addr vrec addr //------ // %i4 U pixels // %I5 V // vr01 alpha // vr02 beta // vr20 c // vr21 -c // Data as loaded U & V for lines a & b // 7 6 5 4 3 2 1 0 // vr03 Vp0a Vp1a xxxx xxxx Up0a Up1a xxxx xxxx // vr04 Vp0b Vp1b xxxx xxxx Up0b Up1b xxxx xxxx // vr05 xxxx xxxx Vq1a Vq0a xxxx xxxx Uq1a Uq0a // vr06 xxxx xxxx Vq1b Vq0b xxxx xxxx Uq1b Uq0b vdiwr %dr6,2 // Wait DMA in complete vld32wl %vr03,[%i4,0] // (a) U vld32wh %vr03,[%i5,0] // (a) V vld32wl %vr04,[%i4,16] // (b) U vld32wh %vr04,[%i5,16] // (b) V vld32wl %vr05,[%i4,4] // (a) vld32wh %vr05,[%i5,4] // (a) vld32wl %vr06,[%i4,20] // (b) vld32wh %vr06,[%i5,20] // (b) // vr03 0000 0000 Vp0a Vp1a xxxx xxxx Up0a Up1a // vr04 0000 0000 Vp0b Vp1b xxxx xxxx Up0b Up1b // vr05 xxxx xxxx Vq1a Vq0a xxxx xxxx Uq1a Uq0a // vr06 xxxx xxxx Vq1b Vq0b xxxx xxxx Uq1b Uq0b vsr8 %vr03,%vr03,4 vsr8 %vr04,%vr04,4 // vr03 0000 0000[Vp1b]Vp1a xxxx xxxx[Up1b]Up1a // vr04 0000 0000 Vp0b[Vp0a]xxxx xxxx Up0b[Up0a] // vr05 xxxx xxxx{Vq0b}Vq0a xxxx xxxx{Uq0b}Uq0a // vr06 xxxx xxxx Vq1b{Vq1a}xxxx xxxx Uq1b{Uq1a} vexch1 %vr03,%vr04 vexch1 %vr05,%vr06 // vr03 p1 // vr04 p0 // vr05 q0 // vr06 q1 vbmulw %vr21,%vr20,-1 // -c vdifw %vr08,%vr03,%vr04 // ABS_PEL_DIFF(p1 - p0) vdifw %vr07,%vr05,%vr04 // ABS_PEL_DIFF(q0 - p0) vdifw %vr09,%vr06,%vr05 // ABS_PEL_DIFF(q1 - q0) vltw %vr07,%vr07,%vr01 // ABS_PEL_DIFF(q0 - p0) < alpha vltw %vr08,%vr08,%vr02 // ABS_PEL_DIFF(p1 - p0) < beta vltw %vr09,%vr09,%vr02 // ABS_PEL_DIFF(q1 - q0) < beta vsubw %vr12,%vr05,%vr04 // q0-p0 vand %vr07,%vr07,%vr08 // For enable vbmulw %vr12,%vr12,4 vsubw %vr13,%vr03,%vr06 // p1-q1 // (((q0-p0)<<2) + (p1-q1) + 4) >> 3; vand %vr07,%vr07,%vr09 // Enable vaddw %vr13,%vr13,%vr12 // (q0-p0)<<2) + (p1-q1) vand %vr19,%vr20,%vr07 // Mask C with enables vasrrw %vr13,%vr13,3 // (((q0-p0)<<2) + (p1-q1) + 4) >> 3 vand %vr21,%vr21,%vr07 // Mask -C with enables vmaxw %vr12,%vr13,%vr21 // max -c vminw %vr12,%vr12,%vr19 // min c (delta) vaddw %vr04,%vr04,%vr12 // p0 + delta vsubw %vr05,%vr05,%vr12 // q0 - delta // vr03 0000 0000 Vp0a Vp1a xxxx xxxx Up0a Up1a // vr04 0000 0000 Vp0b Vp1b xxxx xxxx Up0b Up1b // vr05 xxxx xxxx Vq1a Vq0a xxxx xxxx Uq1a Uq0a // vr06 xxxx xxxx Vq1b Vq0b xxxx xxxx Uq1b Uq0b vexch1 %vr03,%vr04 vexch1 %vr05,%vr06 vasrpwb %vr03,%vr03,0 vasrpwb %vr04,%vr04,0 vasrpwb %vr05,%vr05,0 vasrpwb %vr06,%vr06,0 // Store U vst16 %vr03,[%i4,2] // (a) Up0a Up1a vst16 %vr04,[%i4,18] // (b) Up0b Up1b vst16 %vr05,[%i4,4] // (a) Uq1a Uq0a vst16 %vr06,[%i4,20] // (b) Uq1b Uq0b // Store V vst16_2 %vr03,[%i5,2] // (a) Vp0a Vp1a vst16_2 %vr04,[%i5,18] // (b) Vp0b Vp1b vst16_2 %vr05,[%i5,4] // (a) Vq1a Vq0a vst16_2 %vr06,[%i5,20] // (b) Vq1b Vq0b vbaddw %vr00,%vr00,32 // Next line down // // i5 ptr -4 // // vr01 alpha // // vr02 beta // // // vr20 c // // // lanes 0 & 4 / calc a & b // // vr03 p1 // // vr04 p0 // // vr05 q0 // // vr06 q1 // // // vr10 p0 p1 xx xx calc a // // vr11 xx xx q1 q0 calc a // // // vr14 p0 p1 xx xx calc b // // vr15 xx xx q1 q0 calc b // vxor %vr10,%vr10,%vr10 // vxor %vr11,%vr11,%vr11 // vxor %vr14,%vr14,%vr14 // // vdiwr %dr6,2 // Wait DMA in complete // vld32wl %vr10,[%i5,0] // (a) // vld32wl %vr11,[%i5,4] // (a) // vld32wl %vr14,[%i5,16] // (b) // vxor %vr15,%vr15,%vr15 // vld32wl %vr15,[%i5,20] // (b) // //// vr10 // xx xx xx xx p0 p1 xx xx (a) //// vr11 // xx xx xx xx xx xx q1 q0 (a) //// vr14 // xx xx xx xx p0 p1 xx xx (b) //// vr15 // xx xx xx xx xx xx q1 q0 (b) // // vsr8 %vr03,%vr10,4 // align p1 (a) xxxxxxxa // vmr6aw %vr03,%vr14,%vr14 // align p1 (b) +xxxxxbxx[xxxxxbxx] >>6 = xxxbxxxa // vsr8 %vr04,%vr10,6 // align p0 (a) xxxxxxxa // vmr7aw %vr04,%vr14,%vr14 // align p0 (b) +xxxxbxxx[xxxxbxxx] >>7 = xxxbxxxa // // vsr8 %vr05,%vr11,0 // align q0 (a) xxxxxxxa // vmr4aw %vr05,%vr15,%vr15 // align q0 (b) +xxxxxxxb[xxxxxxxb] >>4 = xxxbxxxa // vsr8 %vr06,%vr11,2 // align q1 (a) xxxxxxxa // vmr5aw %vr06,%vr15,%vr15 // align q0 (b) +xxxxxxbx[xxxxxxbx] >>5 = xxxbxxxa // // vdifw %vr07,%vr05,%vr04 // ABS_PEL_DIFF(q0 - p0) // vdifw %vr08,%vr03,%vr04 // ABS_PEL_DIFF(p1 - p0) // vdifw %vr09,%vr06,%vr05 // ABS_PEL_DIFF(q1 - q0) // // vltw %vr07,%vr07,%vr01 // ABS_PEL_DIFF(q0 - p0) < alpha // vltw %vr08,%vr08,%vr02 // ABS_PEL_DIFF(p1 - p0) < beta // vltw %vr09,%vr09,%vr02 // ABS_PEL_DIFF(q1 - q0) < beta // // vand %vr07,%vr07,%vr08 // For enable // // // //// (((q0-p0)<<2) + (p1-q1) + 4) >> 3; // vsubw %vr12,%vr05,%vr04 // q0-p0 // vsubw %vr13,%vr03,%vr06 // p1-q1 // vaddaw %vr13,%vr12,%vr12 // (q0-p0)<<1) + (p1-q1) // vaddaw %vr13,%vr12,%vr12 // (q0-p0)<<2) + (p1-q1) // // vand %vr07,%vr07,%vr09 // Enable // // vbmulw %vr21,%vr20,-1 // -c // // vmvzw %vr08,%vr07,0x01 // Enable mask 0 0 0 0 0 0 0 A // // vasrrw %vr13,%vr13,3 // (((q0-p0)<<2) + (p1-q1) + 4) >> 3 // // vmr5w %vr09,%vr08,%vr08 // 0000000A[0000000A] >>5 = 0000A000 // // vmaxw %vr12,%vr13,%vr21 // max -c // // vmvzw %vr19,%vr07,0x10 // Enable mask 0 0 0 B 0 0 0 0 // // vminw %vr12,%vr12,%vr20 // min c (delta) // // vsr8 %vr18,%vr19,8 // 000B0000 >>4 = 0000000B // vsr8 %vr19,%vr19,2 // 000B0000 >>4 = 0000B000 // // // vaddw %vr04,%vr04,%vr12 // p0 + delta xxxBxxxA // vsubw %vr05,%vr05,%vr12 // q0 - delta xxxBxxxA // // vmr5w %vr03,%vr04,%vr04 // align p0 (a) xx xx xx xx p0 xx xx xx // vmr1w %vr04,%vr04,%vr04 // align p0 (b) xx xx xx xx p0 xx xx xx // vmr4w %vr06,%vr05,%vr05 // align q0 (b) xx xx xx xx xx xx xx q0 // // // vbic %vr10,%vr10,%vr09 //(a) // vandaw %vr10,%vr03,%vr09 // p0 (a) // // vbic %vr14,%vr14,%vr19 // (b) // vandaw %vr14,%vr04,%vr19 // p0 (b) // // vbic %vr11,%vr11,%vr08 //(a) // vandaw %vr11,%vr05,%vr08 // q0 (a) // // vbic %vr15,%vr15,%vr18 //(b) // vandaw %vr15,%vr06,%vr18 // q0 (b) // // vasrpwb %vr10,%vr10,0 //(a) // vasrpwb %vr11,%vr11,0 //(a) // vasrpwb %vr14,%vr14,0 //(b) // vasrpwb %vr15,%vr15,0 //(b) // // vst32 %vr10,[%i5,0] //(a) // vst32 %vr11,[%i5,4] //(a) // vst32 %vr14,[%i5,16] //(b) // vst32 %vr15,[%i5,20] //(b) // // vbaddw %vr00,%vr00,32 // Next line down // //------ vendrec %r0 } // TODO Optimize _Asm int MACRO_LoopFilterEdgeChromaHorizontalStrong(int addr) { %reg addr vrec addr //------ // i4 U // i5 V // vr01 alpha // vr02 beta // vr03 p1 // vr04 p0 // vr05 q0 // vr06 q1 // Data as loaded U & V for lines a & b // 7 6 5 4 3 2 1 0 // vr03 Vp0a Vp1a xxxx xxxx Up0a Up1a xxxx xxxx // vr04 Vp0b Vp1b xxxx xxxx Up0b Up1b xxxx xxxx // vr05 xxxx xxxx Vq1a Vq0a xxxx xxxx Uq1a Uq0a // vr06 xxxx xxxx Vq1b Vq0b xxxx xxxx Uq1b Uq0b vdiwr %dr6,2 // Wait DMA in complete vld32wl %vr03,[%i4,0] // (a) U vld32wh %vr03,[%i5,0] // (a) V vld32wl %vr04,[%i4,16] // (b) U vld32wh %vr04,[%i5,16] // (b) V vld32wl %vr05,[%i4,4] // (a) vld32wh %vr05,[%i5,4] // (a) vld32wl %vr06,[%i4,20] // (b) vld32wh %vr06,[%i5,20] // (b) // vr07 Vp0c Vp1c xxxx xxxx Up0c Up1c xxxx xxxx // vr08 Vp0d Vp1d xxxx xxxx Up0d Up1d xxxx xxxx // vr09 xxxx xxxx Vq1c Vq0c xxxx xxxx Uq1c Uq0c // vr10 xxxx xxxx Vq1d Vq0d xxxx xxxx Uq1d Uq0d vld32wl %vr07,[%i4,0+32] // (c) U vld32wh %vr07,[%i5,0+32] // (c) V vld32wl %vr08,[%i4,16+32] // (d) U vld32wh %vr08,[%i5,16+32] // (d) V vld32wl %vr09,[%i4,4+32] // (c) vld32wh %vr09,[%i5,4+32] // (c) vld32wl %vr10,[%i4,20+32] // (d) vld32wh %vr10,[%i5,20+32] // (d) // vr03 0000 0000 Vp0a Vp1a xxxx xxxx Up0a Up1a // vr04 0000 0000 Vp0b Vp1b xxxx xxxx Up0b Up1b // vr05 xxxx xxxx Vq1a Vq0a xxxx xxxx Uq1a Uq0a // vr06 xxxx xxxx Vq1b Vq0b xxxx xxxx Uq1b Uq0b vsr8 %vr03,%vr03,4 vsr8 %vr04,%vr04,4 // vr07 Vp0c Vp1c xxxx xxxx Up0c Up1c xxxx xxxx // vr08 Vp0d Vp1d xxxx xxxx Up0d Up1d xxxx xxxx // vr09 Vq1c Vq0c xxxx xxxx Uq1c Uq0c xxxx xxxx // vr10 Vq1d Vq0d xxxx xxxx Uq1d Uq0d xxxx xxxx vmr6w %vr09,%vr09,%vr09 vmr6w %vr10,%vr10,%vr10 // vr03 Vp0c Vp1c Vp0a Vp1a Up0c Up1c Up0a Up1a // vr04 Vp0d Vp1d Vp0b Vp1b Up0d Up1d Up0b Up1b // vr05 Vq1c Vq0c Vq1a Vq0a Uq1c Uq0c Uq1a Uq0a // vr06 Vq1d Vq0d Vq1b Vq0b Uq1d Uq0d Uq1b Uq0b vmvw %vr03,%vr07,0xcc vmvw %vr04,%vr08,0xcc vmvw %vr05,%vr09,0xcc vmvw %vr06,%vr10,0xcc // vr03 Vp1d Vp1c[Vp1b]Vp1a Up1d Up1c[Up1b]Up1a // vr04 Vp0d Vp0c Vp0b[Vp0a]Up0d Up0c Up0b[Up0a] // vr05 Vq0d Vq0c{Vq0b}Vq0a Uq0d Uq0c{Uq0b}Uq0a // vr06 Vq1d Vq1c Vq1b{Vq1a}Uq1d Uq1c Uq1b{Uq1a} vexch1 %vr03,%vr04 vexch1 %vr05,%vr06 vdifw %vr08,%vr03,%vr04 // ABS_PEL_DIFF(p1 - p0) vdifw %vr07,%vr05,%vr04 // ABS_PEL_DIFF(q0 - p0) vdifw %vr09,%vr06,%vr05 // ABS_PEL_DIFF(q1 - q0) vltw %vr07,%vr07,%vr01 // ABS_PEL_DIFF(q0 - p0) < alpha vltw %vr08,%vr08,%vr02 // ABS_PEL_DIFF(p1 - p0) < beta vltw %vr09,%vr09,%vr02 // ABS_PEL_DIFF(q1 - q0) < beta vand %vr07,%vr07,%vr08 // For enable vand %vr07,%vr07,%vr09 // Enable vaddw %vr10,%vr04,%vr06 // p0 + q1 vaddaw %vr10,%vr03,%vr03 // p0 + q1 + (p1 << 1) vaddw %vr11,%vr05,%vr03 // q0 + p1 vaddaw %vr11,%vr06,%vr06 // q0 + p1 + (q1 << 1) vasrrw %vr10,%vr10,2 // p0+2 >> 2 vasrrw %vr11,%vr11,2 // q0+2 >> 2 vbic %vr04,%vr04,%vr07 // select vandaw %vr04,%vr10,%vr07 vbic %vr05,%vr05,%vr07 // select vandaw %vr05,%vr11,%vr07 // vr03 Vp0c Vp1c Vp0a Vp1a Up0c Up1c Up0a Up1a // vr04 Vp0d Vp1d Vp0b Vp1b Up0d Up1d Up0b Up1b // vr05 Vq1c Vq0c Vq1a Vq0a Uq1c Uq0c Uq1a Uq0a // vr06 Vq1d Vq0d Vq1b Vq0b Uq1d Uq0d Uq1b Uq0b vexch1 %vr03,%vr04 vexch1 %vr05,%vr06 vasrpwb %vr03,%vr03,0 vasrpwb %vr04,%vr04,0 vasrpwb %vr05,%vr05,0 vasrpwb %vr06,%vr06,0 // Store U a b vst16 %vr03,[%i4,2] // (a) Up0a Up1a vst16 %vr04,[%i4,18] // (b) Up0b Up1b vst16 %vr05,[%i4,4] // (a) Uq1a Uq0a vst16 %vr06,[%i4,20] // (b) Uq1b Uq0b // Store U c d vst16_1 %vr03,[%i4,2+32] // (c) Up0c Up1c vst16_1 %vr04,[%i4,18+32] // (d) Up0d Up1d vst16_1 %vr05,[%i4,4+32] // (c) Uq1c Uq0c vst16_1 %vr06,[%i4,20+32] // (d) Uq1d Uq0d // Store V a b vst16_2 %vr03,[%i5,2] // (a) Vp0a Vp1a vst16_2 %vr04,[%i5,18] // (b) Vp0b Vp1b vst16_2 %vr05,[%i5,4] // (a) Vq1a Vq0a vst16_2 %vr06,[%i5,20] // (b) Vq1b Vq0b // Store V c d vst16_3 %vr03,[%i5,2+32] // (c) Vp0c Vp1c vst16_3 %vr04,[%i5,18+32] // (d) Vp0d Vp1d vst16_3 %vr05,[%i5,4+32] // (c) Vq1c Vq0c vst16_3 %vr06,[%i5,20+32] // (d) Vq1d Vq0d vbaddw %vr00,%vr00,64 // Next 2 lines down //------ vendrec %r0 } // TODO Optimize _Asm int MACRO_LoopFilterEdgeChromaVertical(int addr) { %reg addr vrec addr //------ // i5 ptr -2*data_inc // vr01 alpha // vr02 beta // vr20 c // vr21 -c // vr03 p1 // vr04 p0 // vr05 q0 // vr06 q1 vdiwr %dr6,2 ;// Wait DMA in complete vld32wl %vr03,[%i4,0] // p1 U vld32wl %vr04,[%i4,16] // p0 vld32wl %vr05,[%i4,32] // q0 vld32wl %vr06,[%i4,48] // q1 vld32wh %vr03,[%i5,0] // p1 V vld32wh %vr04,[%i5,16] // p0 vld32wh %vr05,[%i5,32] // q0 vld32wh %vr06,[%i5,48] // q1 vbmulw %vr21,%vr20,-1 // -c vdifw %vr08,%vr03,%vr04 // ABS_PEL_DIFF(p1 - p0) vdifw %vr07,%vr05,%vr04 // ABS_PEL_DIFF(q0 - p0) vdifw %vr09,%vr06,%vr05 // ABS_PEL_DIFF(q1 - q0) vltw %vr07,%vr07,%vr01 // ABS_PEL_DIFF(q0 - p0) < alpha vltw %vr08,%vr08,%vr02 // ABS_PEL_DIFF(p1 - p0) < beta vltw %vr09,%vr09,%vr02 // ABS_PEL_DIFF(q1 - q0) < beta vsubw %vr12,%vr05,%vr04 // q0-p0 vand %vr07,%vr07,%vr08 // For enable vbmulw %vr12,%vr12,4 vsubw %vr13,%vr03,%vr06 // p1-q1 // (((q0-p0)<<2) + (p1-q1) + 4) >> 3; vand %vr07,%vr07,%vr09 // Enable vaddw %vr13,%vr13,%vr12 // (q0-p0)<<2) + (p1-q1) vand %vr19,%vr20,%vr07 // Mask C with enables vasrrw %vr13,%vr13,3 // (((q0-p0)<<2) + (p1-q1) + 4) >> 3 vand %vr21,%vr21,%vr07 // Mask -C with enables vmaxw %vr12,%vr13,%vr21 // max -c vminw %vr12,%vr12,%vr19 // min c (delta) vaddw %vr04,%vr04,%vr12 // p0 + delta vsubw %vr05,%vr05,%vr12 // q0 - delta vasrpwb %vr04,%vr04,0 vasrpwb %vr05,%vr05,0 vst32 %vr04,[%i4,16] // p0 U vst32 %vr05,[%i4,32] // q0 vst32_2 %vr04,[%i5,16] // p0 V vst32_2 %vr05,[%i5,32] // q0 //------ vendrec %r0 } // TODO Optimize // Now does complete top line of macro block _Asm int MACRO_LoopFilterEdgeChromaVerticalStrong(int addr) { %reg addr vrec addr //------ // i5 ptr -2*data_inc // vr01 alpha // vr02 beta // vr22 Master enable mask // vr03 p1 // vr04 p0 // vr05 q0 // vr06 q1 vdiwr %dr6,2 ;// Wait DMA in complete vld64w %vr03,[%i5,0] // p1 vld64w %vr04,[%i5,16] // p0 vld64w %vr05,[%i5,32] // q0 vld64w %vr06,[%i5,48] // q1 vdifw %vr08,%vr03,%vr04 // ABS_PEL_DIFF(p1 - p0) vdifw %vr07,%vr05,%vr04 // ABS_PEL_DIFF(q0 - p0) vdifw %vr09,%vr06,%vr05 // ABS_PEL_DIFF(q1 - q0) vltw %vr07,%vr07,%vr01 // ABS_PEL_DIFF(q0 - p0) < alpha vltw %vr08,%vr08,%vr02 // ABS_PEL_DIFF(p1 - p0) < beta vltw %vr09,%vr09,%vr02 // ABS_PEL_DIFF(q1 - q0) < beta vand %vr07,%vr07,%vr08 // For enable vand %vr07,%vr07,%vr09 // Enable // vand %vr07,%vr07,%vr22 // Master enable vaddw %vr10,%vr04,%vr06 // p0 + q1 vaddaw %vr10,%vr03,%vr03 // p0 + q1 + (p1 << 1) vaddw %vr11,%vr05,%vr03 // q0 + p1 vaddaw %vr11,%vr06,%vr06 // q0 + p1 + (q1 << 1) vbmulw %vr04,%vr04,4 // p0 << 2 vbmulw %vr05,%vr05,4 // q0 << 2 vbic %vr04,%vr04,%vr07 // select vandaw %vr04,%vr10,%vr07 vbic %vr05,%vr05,%vr07 // select vandaw %vr05,%vr11,%vr07 vasrrpwb %vr04,%vr04,2 // (p0+2) >>2 vasrrpwb %vr05,%vr05,2 // (q0+2) >>2 vst64 %vr04,[%i5,16] // p0 vst64 %vr05,[%i5,32] // q0 //------ vendrec %r0 } // Record macros for deblocking // Called indirectly from the AuroraH264Dec constructor void AuroraRecMgr::RecordDeblockMacros() { Record(AM_DB_HorzontalFilterAligned, MACRO_HorzontalFilterAligned(NextAddr)); Record(AM_DB_HorzontalFilter, MACRO_HorzontalFilter(NextAddr)); Record(AM_DB_NormalVerticalFilter, MACRO_NormalVerticalFilter(NextAddr)); Record(AM_DB_StrongVerticalFilter, MACRO_StrongVerticalFilter(NextAddr)); Record(AM_DB_EdgeChromaHorizontal, MACRO_LoopFilterEdgeChromaHorizontal(NextAddr)); Record(AM_DB_EdgeChromaHorizontalStrong, MACRO_LoopFilterEdgeChromaHorizontalStrong(NextAddr)); Record(AM_DB_EdgeChromaVertical, MACRO_LoopFilterEdgeChromaVertical(NextAddr)); Record(AM_DB_EdgeChromaVerticalStrong, MACRO_LoopFilterEdgeChromaVerticalStrong(NextAddr)); Record(AM_DB_MoveForNextBlockY, MACRO_MoveForNextBlockL(NextAddr)); Record(AM_DB_MoveForNextBlockU, MACRO_MoveForNextBlockU(NextAddr)); Record(AM_DB_MoveForNextBlockV, MACRO_MoveForNextBlockV(NextAddr)); Record(AM_DB_VerticalFilter2, MACRO_VerticalFilter2(NextAddr)); // Record(AM_DB_, (NextAddr)); } //#ifdef INLOOP_DBLOCK //Move overlap area for next block _Asm int MACRO_CopyTopLine16( int addr) { %reg addr vrec addr // Move luma data ptr in %i0 vld64 %vr01,[%i0,0 ] vld64 %vr02,[%i0,0 + 8] vst64 %vr01,[%i1,0 ] vst64 %vr02,[%i1,0 + 8] vendrec %r0 } _Asm int MACRO_CopyTopLine20( int addr) { %reg addr vrec addr // Move luma data ptr in %i0 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + 4 ] vld32 %vr03,[%i0,0 + 8 ] vld32 %vr04,[%i0,0 + 12 ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + 4 ] vst32 %vr03,[%i1,0 + 8 ] vst32 %vr04,[%i1,0 + 12 ] vld32 %vr01,[%i0,0 + 16] vst32 %vr01,[%i1,0 + 16] vendrec %r0 } _Asm int MACRO_CopyTopLine24( int addr) { %reg addr vrec addr // Move luma data ptr in %i0 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + 4 ] vld32 %vr03,[%i0,0 + 8 ] vld32 %vr04,[%i0,0 + 12 ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + 4 ] vst32 %vr03,[%i1,0 + 8 ] vst32 %vr04,[%i1,0 + 12 ] vld32 %vr01,[%i0,0 + 16] vld32 %vr02,[%i0,0 + 20] vst32 %vr01,[%i1,0 + 16] vst32 %vr02,[%i1,0 + 20] vendrec %r0 } _Asm int MACRO_CopyTopLine8( int addr) { %reg addr vrec addr // Move luma data ptr in %i0 vld64 %vr01,[%i0,0 ] vst64 %vr01,[%i1,0 ] vendrec %r0 } _Asm int MACRO_CopyTopLine4( int addr) { %reg addr vrec addr // Move luma data ptr in %i0 vld32 %vr01,[%i0,0] vst32 %vr01,[%i1,0] vendrec %r0 } _Asm int MACRO_CopyTopLine12( int addr) { %reg addr vrec addr // Move luma data ptr in %i0 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + 4 ] vld32 %vr03,[%i0,0 + 8 ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + 4 ] vst32 %vr03,[%i1,0 + 8 ] vendrec %r0 } _Asm int MACRO_Copy16x16_off_24_720( int addr) { %reg addr vrec addr vmovzw %vr07, 48,0x1 vmovw %vr07,1440,0x2 // Move luma data ptr in %i0 vld64 %vr01,[%i0,0 ] vld64 %vr02,[%i0,0 + 8] vld64 %vr03,[%i0,0 + (1*24) ] vld64 %vr04,[%i0,0 + (1*24) + 8] vst64 %vr01,[%i1,0 ] vst64 %vr02,[%i1,0 + 8] vst64 %vr03,[%i1,0 + (1*720) ] vst64 %vr04,[%i1,0 + (1*720) + 8] vaddw %vr00, %vr00, %vr07 vld64 %vr01,[%i0,0 ] vld64 %vr02,[%i0,0 + 8] vld64 %vr03,[%i0,0 + (1*24) ] vld64 %vr04,[%i0,0 + (1*24) + 8] vst64 %vr01,[%i1,0 ] vst64 %vr02,[%i1,0 + 8] vst64 %vr03,[%i1,0 + (1*720) ] vst64 %vr04,[%i1,0 + (1*720) + 8] vaddw %vr00, %vr00, %vr07 vld64 %vr01,[%i0,0 ] vld64 %vr02,[%i0,0 + 8] vld64 %vr03,[%i0,0 + (1*24) ] vld64 %vr04,[%i0,0 + (1*24) + 8] vst64 %vr01,[%i1,0 ] vst64 %vr02,[%i1,0 + 8] vst64 %vr03,[%i1,0 + (1*720) ] vst64 %vr04,[%i1,0 + (1*720) + 8] vaddw %vr00, %vr00, %vr07 vld64 %vr01,[%i0,0 ] vld64 %vr02,[%i0,0 + 8] vld64 %vr03,[%i0,0 + (1*24) ] vld64 %vr04,[%i0,0 + (1*24) + 8] vst64 %vr01,[%i1,0 ] vst64 %vr02,[%i1,0 + 8] vst64 %vr03,[%i1,0 + (1*720) ] vst64 %vr04,[%i1,0 + (1*720) + 8] vaddw %vr00, %vr00, %vr07 vld64 %vr01,[%i0,0 ] vld64 %vr02,[%i0,0 + 8] vld64 %vr03,[%i0,0 + (1*24) ] vld64 %vr04,[%i0,0 + (1*24) + 8] vst64 %vr01,[%i1,0 ] vst64 %vr02,[%i1,0 + 8] vst64 %vr03,[%i1,0 + (1*720) ] vst64 %vr04,[%i1,0 + (1*720) + 8] vaddw %vr00, %vr00, %vr07 vld64 %vr01,[%i0,0 ] vld64 %vr02,[%i0,0 + 8] vld64 %vr03,[%i0,0 + (1*24) ] vld64 %vr04,[%i0,0 + (1*24) + 8] vst64 %vr01,[%i1,0 ] vst64 %vr02,[%i1,0 + 8] vst64 %vr03,[%i1,0 + (1*720) ] vst64 %vr04,[%i1,0 + (1*720) + 8] vaddw %vr00, %vr00, %vr07 vld64 %vr01,[%i0,0 ] vld64 %vr02,[%i0,0 + 8] vld64 %vr03,[%i0,0 + (1*24) ] vld64 %vr04,[%i0,0 + (1*24) + 8] vst64 %vr01,[%i1,0 ] vst64 %vr02,[%i1,0 + 8] vst64 %vr03,[%i1,0 + (1*720) ] vst64 %vr04,[%i1,0 + (1*720) + 8] vaddw %vr00, %vr00, %vr07 vld64 %vr01,[%i0,0 ] vld64 %vr02,[%i0,0 + 8] vld64 %vr03,[%i0,0 + (1*24) ] vld64 %vr04,[%i0,0 + (1*24) + 8] vst64 %vr01,[%i1,0 ] vst64 %vr02,[%i1,0 + 8] vst64 %vr03,[%i1,0 + (1*720) ] vst64 %vr04,[%i1,0 + (1*720) + 8] vendrec %r0 } _Asm int MACRO_Copy16x4_off_24_720( int addr) { %reg addr vrec addr vmovzw %vr07, 48,0x1 vmovw %vr07,1440,0x2 // Move luma data ptr in %i0 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*24) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*720) ] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*24) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*720) ] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*24) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*720) ] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*24) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*720) ] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*24) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*720) ] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*24) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*720) ] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*24) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*720) ] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*24) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*720) ] vendrec %r0 } _Asm int MACRO_Copy8x8_off_16_360( int addr) { %reg addr vrec addr vmovzw %vr07, 64,0x1 vmovw %vr07,1440,0x2 // Move luma data ptr in %i0 vld64 %vr01,[%i0,0 ] vld64 %vr02,[%i0,0 + 16] vld64 %vr03,[%i0,0 + 32] vld64 %vr04,[%i0,0 + 48] vst64 %vr01,[%i1,0 ] vst64 %vr02,[%i1,0 + (1*360)] vst64 %vr03,[%i1,0 + (2*360)] vst64 %vr04,[%i1,0 + (3*360)] vaddw %vr00, %vr00, %vr07 vld64 %vr01,[%i0,0 ] vld64 %vr02,[%i0,0 + 16] vld64 %vr03,[%i0,0 + 32] vld64 %vr04,[%i0,0 + 48] vst64 %vr01,[%i1,0 ] vst64 %vr02,[%i1,0 + (1*360)] vst64 %vr03,[%i1,0 + (2*360)] vst64 %vr04,[%i1,0 + (3*360)] vendrec %r0 } _Asm int MACRO_Copy8x2_off_16_360( int addr) { %reg addr vrec addr vmovzw %vr07, 32,0x1 vmovw %vr07,720,0x2 // Move luma data ptr in %i0 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + 16] vst16_1 %vr01,[%i1,0 ] vst16_1 %vr02,[%i1,0 + (1*360)] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + 16] vst16_1 %vr01,[%i1,0 ] vst16_1 %vr02,[%i1,0 + (1*360)] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + 16] vst16_1 %vr01,[%i1,0 ] vst16_1 %vr02,[%i1,0 + (1*360)] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + 16] vst16_1 %vr01,[%i1,0 ] vst16_1 %vr02,[%i1,0 + (1*360)] vaddw %vr00, %vr00, %vr07 vendrec %r0 } _Asm int MACRO_Copy8x2_off_360_16_DBInput( int addr) { %reg addr vrec addr vmovzw %vr07, 720,0x1 vmovw %vr07,32,0x2 // Move luma data ptr in %i0 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*360)] vst16_1 %vr01,[%i1,0 ] vst16_1 %vr02,[%i1,0 + 16] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*360)] vst16_1 %vr01,[%i1,0 ] vst16_1 %vr02,[%i1,0 + 16] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*360)] vst16_1 %vr01,[%i1,0 ] vst16_1 %vr02,[%i1,0 + 16] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*360)] vst16_1 %vr01,[%i1,0 ] vst16_1 %vr02,[%i1,0 + 16] //vaddw %vr00, %vr00, %vr07 vendrec %r0 } _Asm int MACRO_Copy16x4_off_720_24_DBINPUT( int addr) { %reg addr vrec addr vmovzw %vr07, 1440,0x1 vmovw %vr07,48,0x2 // Move luma data ptr in %i0 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*720) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*24) ] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*720) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*24) ] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*720) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*24) ] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*720) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*24) ] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*720) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*24) ] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*720) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*24) ] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*720) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*24) ] vaddw %vr00, %vr00, %vr07 vld32 %vr01,[%i0,0 ] vld32 %vr02,[%i0,0 + (1*720) ] vst32 %vr01,[%i1,0 ] vst32 %vr02,[%i1,0 + (1*24) ] vendrec %r0 } _Asm int MACRO_Copy16x16_off_16_24_DBInput( int addr) { %reg addr vrec addr // vmovzw %vr07, 48,0x1 // vmovw %vr07,1440,0x2 // Move luma data ptr in %i0 vld64 %vr01,[%i0,0 ] vld64 %vr02,[%i0,0 + 8] vld64 %vr03,[%i0,0 + (1*16) ] vld64 %vr04,[%i0,0 + (1*16) + 8] vst64 %vr01,[%i1,0 ] vst64 %vr02,[%i1,0 + 8] vst64 %vr03,[%i1,0 + (1*24) ] vst64 %vr04,[%i1,0 + (1*24) + 8] vld64 %vr01,[%i0,0 + (2*16) ] vld64 %vr02,[%i0,0 + (2*16) + 8] vld64 %vr03,[%i0,0 + (3*16) ] vld64 %vr04,[%i0,0 + (3*16) + 8] vst64 %vr01,[%i1,0 + (2*24) ] vst64 %vr02,[%i1,0 + (2*24) + 8] vst64 %vr03,[%i1,0 + (3*24) ] vst64 %vr04,[%i1,0 + (3*24) + 8] vld64 %vr01,[%i0,0 + (4*16) ] vld64 %vr02,[%i0,0 + (4*16) + 8] vld64 %vr03,[%i0,0 + (5*16) ] vld64 %vr04,[%i0,0 + (5*16) + 8] vst64 %vr01,[%i1,0 + (4*24) ] vst64 %vr02,[%i1,0 + (4*24) + 8] vst64 %vr03,[%i1,0 + (5*24) ] vst64 %vr04,[%i1,0 + (5*24) + 8] vld64 %vr01,[%i0,0 + (6*16) ] vld64 %vr02,[%i0,0 + (6*16) + 8] vld64 %vr03,[%i0,0 + (7*16) ] vld64 %vr04,[%i0,0 + (7*16) + 8] vst64 %vr01,[%i1,0 + (6*24) ] vst64 %vr02,[%i1,0 + (6*24) + 8] vst64 %vr03,[%i1,0 + (7*24) ] vst64 %vr04,[%i1,0 + (7*24) + 8] vld64 %vr01,[%i0,0 + (8*16) ] vld64 %vr02,[%i0,0 + (8*16) + 8] vld64 %vr03,[%i0,0 + (9*16) ] vld64 %vr04,[%i0,0 + (9*16) + 8] vst64 %vr01,[%i1,0 + (8*24) ] vst64 %vr02,[%i1,0 + (8*24) + 8] vst64 %vr03,[%i1,0 + (9*24) ] vst64 %vr04,[%i1,0 + (9*24) + 8] vld64 %vr01,[%i0,0 + (10*16) ] vld64 %vr02,[%i0,0 + (10*16) + 8] vld64 %vr03,[%i0,0 + (11*16) ] vld64 %vr04,[%i0,0 + (11*16) + 8] vst64 %vr01,[%i1,0 + (10*24) ] vst64 %vr02,[%i1,0 + (10*24) + 8] vst64 %vr03,[%i1,0 + (11*24) ] vst64 %vr04,[%i1,0 + (11*24) + 8] vld64 %vr01,[%i0,0 + (12*16) ] vld64 %vr02,[%i0,0 + (12*16) + 8] vld64 %vr03,[%i0,0 + (13*16) ] vld64 %vr04,[%i0,0 + (13*16) + 8] vst64 %vr01,[%i1,0 + (12*24) ] vst64 %vr02,[%i1,0 + (12*24) + 8] vst64 %vr03,[%i1,0 + (13*24) ] vst64 %vr04,[%i1,0 + (13*24) + 8] vld64 %vr01,[%i0,0 + (14*16) ] vld64 %vr02,[%i0,0 + (14*16) + 8] vld64 %vr03,[%i0,0 + (15*16) ] vld64 %vr04,[%i0,0 + (15*16) + 8] vst64 %vr01,[%i1,0 + (14*24) ] vst64 %vr02,[%i1,0 + (14*24) + 8] vst64 %vr03,[%i1,0 + (15*24) ] vst64 %vr04,[%i1,0 + (15*24) + 8] vendrec %r0 } _Asm int MACRO_Copy8x8_off_8_16_DBInput( int addr) { %reg addr vrec addr // vmovzw %vr07, 48,0x1 // vmovw %vr07,1440,0x2 // Move luma data ptr in %i0 vld64 %vr01,[%i0,0 ] vld64 %vr02,[%i0,0 + (1*8)] vld64 %vr03,[%i0,0 + (2*8)] vld64 %vr04,[%i0,0 + (3*8)] vst64 %vr01,[%i1,0 ] vst64 %vr02,[%i1,0 + (1*16)] vst64 %vr03,[%i1,0 + (2*16)] vst64 %vr04,[%i1,0 + (3*16)] vld64 %vr01,[%i0,0 + (4*8)] vld64 %vr02,[%i0,0 + (5*8)] vld64 %vr03,[%i0,0 + (6*8)] vld64 %vr04,[%i0,0 + (7*8)] vst64 %vr01,[%i1,0 + (4*16)] vst64 %vr02,[%i1,0 + (5*16)] vst64 %vr03,[%i1,0 + (6*16)] vst64 %vr04,[%i1,0 + (7*16)] vendrec %r0 } void AuroraRecMgr::RecordInloopDBMacros() { Record(AM_COPYTOPLINE16, MACRO_CopyTopLine16(NextAddr)); Record(AM_COPYTOPLINE20, MACRO_CopyTopLine20(NextAddr)); Record(AM_COPYTOPLINE24, MACRO_CopyTopLine24(NextAddr)); Record(AM_COPYTOPLINE8, MACRO_CopyTopLine8(NextAddr)); Record(AM_COPYTOPLINE4, MACRO_CopyTopLine4(NextAddr)); Record(AM_COPYTOPLINE12, MACRO_CopyTopLine12(NextAddr)); Record(AM_COPY16x16_OFF_24_720, MACRO_Copy16x16_off_24_720(NextAddr)); Record(AM_COPY16x4_OFF_24_720, MACRO_Copy16x4_off_24_720(NextAddr)); Record(AM_COPY8x8_OFF_16_360, MACRO_Copy8x8_off_16_360(NextAddr)); Record(AM_COPY8x2_OFF_16_360, MACRO_Copy8x2_off_16_360(NextAddr)); Record(AM_COPY8x2_OFF_360_16_DBINPUT, MACRO_Copy8x2_off_360_16_DBInput(NextAddr)); Record(AM_COPY16X4_OFF_720_24_DBINPUT, MACRO_Copy16x4_off_720_24_DBINPUT(NextAddr)); Record(AM_COPY16X16_OFF_16_24_DBINPUT, MACRO_Copy16x16_off_16_24_DBInput(NextAddr)); Record(AM_COPY8X8_OFF_8_16_DBINPUT, MACRO_Copy8x8_off_8_16_DBInput(NextAddr)); } //#endif #if defined(I32K_D32K) || defined(I16K_D16K) || defined(I8K_D8K) #pragma Code() #endif #endif
[ "alexvatti@gmail.com" ]
alexvatti@gmail.com
9a52eb7a90ff9a57ba09b406d4c98ae2dd950225
0f5bbe3f3d2db6b34737ff1e8ad111782938145d
/practise problems/hello world.cpp
43dabe9a45b9d7adc3648c890803649693144089
[]
no_license
pi-rate14/C-codes
948452f8981e7aa38021b43057ea77a8019e69a6
b95b434e9f0358a681083db3d143b86ecdab446e
refs/heads/master
2022-11-23T08:31:25.413251
2022-11-10T10:34:41
2022-11-10T10:34:41
237,594,360
2
0
null
null
null
null
UTF-8
C++
false
false
96
cpp
#include<iostream> using namespace :: std; int main() { cout<<"hello world"; return 0; }
[ "apoorvasrivastava.14@gmail.com~" ]
apoorvasrivastava.14@gmail.com~
3748915740ac4e3d5e6aa1337f5259d3a3fb4753
018ec7ff27696a3a6b62a5a0e2bfde5876253a91
/include/zapata/conf/load.h
563c09a8ab2055e379ee40c6a25a252e0a8016b4
[ "MIT", "FSFAP" ]
permissive
gitter-badger/zapata
4d9cee9c3a32cef68c59e8dcba18be262d4d9e5a
bef5ff76e381c936a671621cbda110bad1fcc49c
refs/heads/master
2020-02-26T13:52:20.406651
2015-01-01T21:48:31
2015-01-01T21:48:31
29,194,003
0
0
null
2015-01-13T14:39:21
2015-01-13T14:39:21
null
UTF-8
C++
false
false
1,379
h
/* The MIT License (MIT) Copyright (c) 2014 Pedro (n@zgul) Figueiredo <pedro.figueiredo@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <zapata/file/manip.h> #include <zapata/parsers/json.h> using namespace std; #if !defined __APPLE__ using namespace __gnu_cxx; #endif namespace zapata { bool to_configuration(zapata::JSONObj& _out, string& _key_file_path); }
[ "pedro.figueiredo@gmail.com" ]
pedro.figueiredo@gmail.com
6242bdd5372e2178d2cdd74c3a35d802e80d7982
b9ccd51e6891e97c7c7e9b7d36d13a2a5ff068de
/tests/LuaStateTest.cpp
5c1f37faed97e42223c4ea8ba90ba1cd6c951e43
[ "MIT" ]
permissive
spoonless/luaosgviewer
c667f25f735a1aa0bf55665f8c69516d5a13e3ef
9e255f059e3e24867c57df47c798db2b1ab1566a
refs/heads/master
2020-05-19T15:34:11.516271
2014-05-14T17:51:03
2014-05-14T17:51:03
19,789,815
1
0
null
null
null
null
UTF-8
C++
false
false
6,066
cpp
#include <fstream> #include "luaX.h" #include "gtest/gtest.h" #include "LuaState.h" class SimpleLuaExtensionLib : public LuaExtensionLibrary { public: virtual int open(LuaState &luaState) { libname = lua_tostring(luaState, -1); return 0; } std::string libname; }; class FailureLuaExtensionLib : public LuaExtensionLibrary { public: virtual int open(LuaState &luaState) { lua_pushstring(luaState, "FailedLuaExtensionLib"); lua_error(luaState); return 0; } }; class NoopScriptResultHandler : public LuaResultHandler { public: NoopScriptResultHandler() : _handleInvoked(false) { } void handle(LuaState &luaState, unsigned int nbResults) { this->_handleInvoked = true; } bool _handleInvoked; }; class IntegersScriptResultHandler : public LuaResultHandler { public: IntegersScriptResultHandler(unsigned int expectedResult = LuaResultHandler::UNLIMITED_RESULTS) : LuaResultHandler(expectedResult), _results(0), _nbResults(0) { } ~IntegersScriptResultHandler() { delete[] _results; } void handle(LuaState &luaState, unsigned int nbResults) { delete[] _results; _results = new int[nbResults]; this->_nbResults = nbResults; for (unsigned int i = 1; i <= nbResults; ++i) { _results[nbResults - i] = lua_tointeger(luaState, -i); } } int* _results; unsigned int _nbResults; }; TEST(LuaStateTest, createdWithoutError) { LuaState luaState; ASSERT_EQ(std::string(), luaState.lastError()); } TEST(LuaStateTest, canGetLuaStateFromLua_State) { LuaState luaState; ASSERT_EQ(&luaState, LuaState::from(luaState)); ASSERT_EQ(0, LuaState::from(0)); } TEST(LuaStateTest, canOpenLibrary) { LuaState luaState; bool result = luaState.openLibrary<SimpleLuaExtensionLib>("simpleLib"); ASSERT_TRUE(result); SimpleLuaExtensionLib* lib = luaState.getLibrary<SimpleLuaExtensionLib>(); ASSERT_TRUE(lib); ASSERT_EQ("simpleLib", lib->libname); } TEST(LuaStateTest, cannotOpenLibraryTwice) { LuaState luaState; bool result = luaState.openLibrary<SimpleLuaExtensionLib>("simpleLib"); ASSERT_TRUE(result); result = luaState.openLibrary<SimpleLuaExtensionLib>("anotherTry"); ASSERT_FALSE(result); ASSERT_EQ("library already opened", luaState.lastError()); } TEST(LuaStateTest, cannotOpenFailureLibrary) { LuaState luaState; bool result = luaState.openLibrary<FailureLuaExtensionLib>("failureLib"); ASSERT_FALSE(result); ASSERT_EQ("FailedLuaExtensionLib", luaState.lastError()); FailureLuaExtensionLib* lib = luaState.getLibrary<FailureLuaExtensionLib>(); ASSERT_FALSE(lib); } TEST(LuaStateTest, cannotGetUnopenedLibrary) { LuaState luaState; SimpleLuaExtensionLib* lib = luaState.getLibrary<SimpleLuaExtensionLib>(); ASSERT_FALSE(lib); } TEST(LuaStateTest, canExecuteLuaCode) { LuaState luaState; std::istringstream stream("local a = 2+2"); ASSERT_TRUE(luaState.exec(stream)); ASSERT_EQ(std::string(), luaState.lastError()); } TEST(LuaStateTest, canGetLastErrorWhenCompilationFailed) { LuaState luaState; std::istringstream stream("non valid lua script!"); EXPECT_FALSE(luaState.exec(stream, "invalid_script")); ASSERT_EQ("[string \"invalid_script\"]:1: '=' expected near 'valid'", luaState.lastError()); } TEST(LuaStateTest, canGetLastErrorWhenFileDoesNotExist) { LuaState luaState; std::ifstream nonExistingFile("non_existing_file"); EXPECT_FALSE(luaState.exec(nonExistingFile, "nonExistingFile")); ASSERT_EQ("Error while reading 'nonExistingFile'!", luaState.lastError()); } TEST(LuaStateTest, cannotExecScriptWithHandlerWhenFileDoesNotExist) { LuaState luaState; std::ifstream nonExistingFile("non_existing_file"); NoopScriptResultHandler handler; EXPECT_FALSE(luaState.exec(handler, nonExistingFile, "nonExistingFile")); ASSERT_EQ("Error while reading 'nonExistingFile'!", luaState.lastError()); ASSERT_FALSE(handler._handleInvoked); } TEST(LuaStateTest, canExecuteLuaCodeWithNoopScriptHandler) { LuaState luaState; NoopScriptResultHandler noopScriptResultHandler; std::istringstream stream("local a = 2+2"); ASSERT_TRUE(luaState.exec(noopScriptResultHandler, stream)); ASSERT_TRUE(noopScriptResultHandler._handleInvoked); } TEST(LuaStateTest, canExecuteLuaCodeAndUseHandlerToConvertResults) { LuaState luaState; IntegersScriptResultHandler integersScriptResultHandler(3); std::istringstream stream("local result = {} " "for i = 1, 10 do " " result[i] = i " "end " "return unpack(result)"); ASSERT_TRUE(luaState.exec(integersScriptResultHandler, stream)); ASSERT_EQ(static_cast<unsigned int>(3), integersScriptResultHandler._nbResults); ASSERT_EQ(1, integersScriptResultHandler._results[0]); ASSERT_EQ(2, integersScriptResultHandler._results[1]); ASSERT_EQ(3, integersScriptResultHandler._results[2]); } TEST(LuaStateTest, canExecuteLuaCodeAndUseHandlerToConvertUnlimitedResults) { LuaState luaState; IntegersScriptResultHandler integersScriptResultHandler; std::istringstream stream("return 1, 2"); ASSERT_TRUE(luaState.exec(integersScriptResultHandler, stream)); ASSERT_EQ(static_cast<unsigned int>(2), integersScriptResultHandler._nbResults); ASSERT_EQ(1, integersScriptResultHandler._results[0]); ASSERT_EQ(2, integersScriptResultHandler._results[1]); } TEST(LuaStateTest, canExecuteLuaScriptAndDetectFailure) { LuaState luaState; NoopScriptResultHandler handler; std::istringstream stream("assert(false)"); ASSERT_FALSE(luaState.exec(handler, stream, "failed script")); ASSERT_EQ("[string \"failed script\"]:1: assertion failed!", luaState.lastError()); ASSERT_FALSE(handler._handleInvoked); }
[ "dagaydevel@free.fr" ]
dagaydevel@free.fr
f95c1645a73eece3fd4d209311bfa667b285556c
0c619682d82e155047ff1c9adcdecf5e9c4cc17a
/ABC179/D/D.cpp
5c210c885bef6abf1ca7afe68f232a9a6c80e338
[]
no_license
kasataku777/atcoder_solution
822a6638ec78079c35877fadc78f6fad24dd5252
8838eb10bf844ac3209f527d7b5ac213902352ec
refs/heads/master
2023-01-23T06:36:59.810060
2020-12-03T02:02:40
2020-12-03T02:02:40
247,486,743
0
0
null
null
null
null
UTF-8
C++
false
false
641
cpp
#include<iostream> #include<string> #include<algorithm> #include<vector> using namespace std; const int waru = 998244353; int main() { int n, k; cin >> n >> k; vector<long long> l(k), r(k); for (int i = 0; i < k; i++) { cin >> l[i] >> r[i]; } vector<long long>dp(n + 1); vector<long long>dpsum(n + 1); dp[1] = 1; dpsum[1] = 1; for (int i = 2; i <= n; i++) { for (int j = 0; j < k; j++) { int li = i - r[j]; int ri = i - l[j]; if (ri < 0) continue; li = max(li, 1); dp[i] += (dpsum[ri] - dpsum[li - 1]); dp[i] %= waru; } dpsum[i] = (dpsum[i - 1] + dp[i]); } cout << dp[n] << endl; return 0; }
[ "takumi.jihen@gmail.com" ]
takumi.jihen@gmail.com
d4454f7c613ad372e2b631130b3021ef4772492c
3e487bb102d72aac2b7edf0ee4ef4300a0e41394
/src/gaggled_main.cpp
694456a12a095308616cd65ce8cd4d484972afda
[ "Apache-2.0" ]
permissive
20c/gaggled
bab6802afa3eeb1d429d8dba68afc97b73175606
05b8a9c44e0040c068c0cb243d8c2d405c30c253
refs/heads/master
2021-01-14T19:30:08.510153
2014-10-13T04:34:50
2014-10-13T04:34:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,328
cpp
// L I C E N S E #############################################################// /* * Copyright 2011 BigWells Technology (Zen-Fire) * * 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. * */ // I N C L U D E S ###########################################################// #include <signal.h> #include <stdlib.h> #include <unistd.h> #include <iostream> #include <string> #include <vector> #include <getopt.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/info_parser.hpp> #include "gv.hpp" #include "Program.hpp" #include "Gaggled.hpp" using namespace gaggled; Gaggled* g = NULL; void die_callback(int a) { if (g == NULL) { // don't try to shutdown if we didn't even create a daemon yet exit(0); } g->stop(); } void usage() { std::cout << "gaggled v" << gaggled::version << ", process manager for running a gaggle of daemons." << std::endl << std::endl; std::cout << "usage: gaggled (-h|-c <file> [-t])" << std::endl; std::cout << "\t-c <file> where file is the configuration file." << std::endl; std::cout << "\t-h to show help." << std::endl; std::cout << "\t-t to only test the configuration rather than running it." << std::endl; std::cout << "\t-n to disable ^c on the terminal (or SIGINT) from shutting down gaggled. Shutdown should be accomplished by sending SIGTERM in this case." << std::endl; } int main(int argc, char** argv) { char* conf_file = NULL; bool config_test = false; bool help = false; bool ign_sigint = false; int c; while ((c = getopt(argc, argv, "htnc:")) != -1) { switch(c) { case 'h': help = true; break; case 't': config_test = true; break; case 'c': conf_file = optarg; break; case 'n': ign_sigint = true; break; case '?': usage(); return 1; default : usage(); return 1; } } if (help) { if (conf_file or config_test) { usage(); return 1; } else { usage(); return 0; } } if (conf_file == NULL) { usage(); return 2; } try { g = new Gaggled(conf_file); } catch (BadConfigException& bce) { std::cout << "configtest " << conf_file << ": failed, " << bce.reason << std::endl; return 1; } catch (boost::property_tree::info_parser::info_parser_error& pe) { std::cout << "configtest " << conf_file << ": parse error at " << pe.filename() << ":" << pe.line() << ": " << pe.message() << std::endl; return 1; } if (config_test) { std::cout << "configtest " << conf_file << ": ok" << std::endl; delete g; return 0; } signal(SIGTERM, die_callback); if (ign_sigint) signal(SIGINT, SIG_IGN); else signal(SIGINT, die_callback); g->run(); delete g; return 0; }
[ "eastein@zenfire.com" ]
eastein@zenfire.com
4a86cf8c45d6d64ffa925bf48c4742867fde63bc
b9c1098de9e26cedad92f6071b060dfeb790fbae
/src/module/players/tfm/tfc.cpp
defe0799f80b9fdc67ed5783b25c737397ae2ad6
[]
no_license
vitamin-caig/zxtune
2a6f38a941f3ba2548a0eb8310eb5c61bb934dbe
9940f3f0b0b3b19e94a01cebf803d1a14ba028a1
refs/heads/master
2023-08-31T01:03:45.603265
2023-08-27T11:50:45
2023-08-27T11:51:26
13,986,319
138
13
null
2021-09-13T13:58:32
2013-10-30T12:51:01
C++
UTF-8
C++
false
false
5,761
cpp
/** * * @file * * @brief TurboFM Compiled chiptune factory implementation * * @author vitamin.caig@gmail.com * **/ // local includes #include "module/players/tfm/tfc.h" #include "module/players/tfm/tfm_base_stream.h" // common includes #include <iterator.h> #include <make_ptr.h> // library includes #include <formats/chiptune/fm/tfc.h> #include <module/players/platforms.h> #include <module/players/properties_helper.h> #include <module/players/properties_meta.h> #include <module/players/streaming.h> // std includes #include <algorithm> namespace Module::TFC { const Char PROGRAM_PREFIX[] = "TurboFM Compiler v"; class ChannelData { public: ChannelData() = default; void AddFrame() { Offsets.push_back(Data.size()); } void AddFrames(uint_t count) { Offsets.resize(Offsets.size() + count - 1, Data.size()); } void AddRegister(Devices::FM::Register reg) { Data.push_back(reg); } void SetLoop() { Loop = Offsets.size(); } RangeIterator<Devices::FM::Registers::const_iterator> Get(std::size_t row) const { if (row >= Offsets.size()) { const std::size_t size = Offsets.size(); row = Loop + (row - size) % (size - Loop); } const std::size_t start = Offsets[row]; const std::size_t end = row != Offsets.size() - 1 ? Offsets[row + 1] : Data.size(); return {Data.begin() + start, Data.begin() + end}; } std::size_t GetSize() const { return Offsets.size(); } private: std::vector<std::size_t> Offsets; Devices::FM::Registers Data; std::size_t Loop = 0; }; class ModuleData : public TFM::StreamModel { public: using RWPtr = std::shared_ptr<ModuleData>; uint_t GetTotalFrames() const override { return static_cast<uint_t>(std::max({Data[0].GetSize(), Data[1].GetSize(), Data[2].GetSize(), Data[3].GetSize(), Data[4].GetSize(), Data[5].GetSize()})); } uint_t GetLoopFrame() const override { return 0; } void Get(uint_t frameNum, Devices::TFM::Registers& res) const override { Devices::TFM::Registers result; for (uint_t idx = 0; idx != 6; ++idx) { const uint_t chip = idx < 3 ? 0 : 1; for (RangeIterator<Devices::FM::Registers::const_iterator> regs = Data[idx].Get(frameNum); regs; ++regs) { result.emplace_back(chip, *regs); } } res.swap(result); } ChannelData& GetChannel(uint_t channel) { return Data[channel]; } private: std::array<ChannelData, 6> Data; }; class DataBuilder : public Formats::Chiptune::TFC::Builder { public: explicit DataBuilder(PropertiesHelper& props) : Properties(props) , Meta(props) , Data(MakeRWPtr<ModuleData>()) , Frequency() {} Formats::Chiptune::MetaBuilder& GetMetaBuilder() override { return Meta; } void SetVersion(StringView version) override { Properties.SetProgram(String(PROGRAM_PREFIX).append(version)); } void SetIntFreq(uint_t freq) override { if (freq) { FrameDuration = Time::Microseconds::FromFrequency(freq); } } void StartChannel(uint_t idx) override { Channel = idx; } void StartFrame() override { GetChannel().AddFrame(); } void SetSkip(uint_t count) override { GetChannel().AddFrames(count); } void SetLoop() override { GetChannel().SetLoop(); } void SetSlide(uint_t slide) override { const uint_t oldFreq = Frequency[Channel]; const uint_t newFreq = (oldFreq & 0xff00) | ((oldFreq + slide) & 0xff); SetFreq(newFreq); } void SetKeyOff() override { const uint_t key = Channel < 3 ? Channel : Channel + 1; SetRegister(0x28, key); } void SetFreq(uint_t freq) override { Frequency[Channel] = freq; const uint_t chan = Channel % 3; SetRegister(0xa4 + chan, freq >> 8); SetRegister(0xa0 + chan, freq & 0xff); } void SetRegister(uint_t idx, uint_t val) override { GetChannel().AddRegister(Devices::FM::Register(idx, val)); } void SetKeyOn() override { const uint_t key = Channel < 3 ? Channel : Channel + 1; SetRegister(0x28, 0xf0 | key); } TFM::StreamModel::Ptr CaptureResult() const { return Data; } Time::Microseconds GetFrameDuration() const { return FrameDuration; } private: ChannelData& GetChannel() { return Data->GetChannel(Channel); } private: PropertiesHelper& Properties; MetaProperties Meta; const ModuleData::RWPtr Data; uint_t Channel = 0; std::array<uint_t, 6> Frequency; Time::Microseconds FrameDuration = TFM::BASE_FRAME_DURATION; }; class Factory : public TFM::Factory { public: TFM::Chiptune::Ptr CreateChiptune(const Binary::Container& rawData, Parameters::Container::Ptr properties) const override { PropertiesHelper props(*properties); DataBuilder dataBuilder(props); if (const auto container = Formats::Chiptune::TFC::Parse(rawData, dataBuilder)) { auto data = dataBuilder.CaptureResult(); if (data->GetTotalFrames()) { props.SetSource(*container); props.SetPlatform(Platforms::ZX_SPECTRUM); return TFM::CreateStreamedChiptune(dataBuilder.GetFrameDuration(), std::move(data), std::move(properties)); } } return {}; } }; TFM::Factory::Ptr CreateFactory() { return MakePtr<Factory>(); } } // namespace Module::TFC
[ "vitamin.caig@gmail.com" ]
vitamin.caig@gmail.com
6b5dcfcddf5e01ef0d34f382d5984b01054c4b4c
227c2d1d0ab3dcba6e9cb011961ec21a0d265f35
/Include/GUI/Item/CGUIItem.h
391ab82ccd7a58567b7a112174affaaedf6efa02
[]
no_license
X-Seti/IMGF
5b2a79d52b56c6b28aa639c2b07f0823982704f5
c4e8f450160c51ba7f5060bf8ddde9f92142619f
refs/heads/master
2020-06-24T02:52:20.433533
2016-12-18T04:41:25
2016-12-18T04:41:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,375
h
#ifndef CGUIItem_H #define CGUIItem_H #include "Type/Vector/CVector2i32.h" #include "Type/Vector/CPoint2D.h" #include "Type/Vector/CSize2D.h" #include "Styles/CGUIStyleableEntity.h" class CGUILayer; class CWindow; class CGUIItem : public CGUIStyleableEntity { public: CGUIItem(void); void unload(void) {} virtual void unserialize(bool bSkipItemId = false) = 0; virtual void serialize(void) = 0; virtual void render(void) = 0; virtual bool isPointInItem(mcore::CPoint2D& vecPoint) = 0; virtual mcore::CPoint2D getBoundingRectanglePosition(void) = 0; virtual mcore::CSize2D getBoundingRectangleSize(void) = 0; virtual void moveItem(mcore::CVector2i32& vecItemPositionChange) = 0; virtual void resizeItemViaOffsets(mcore::CVector2i32& vecItemSizeChange) = 0; void onMoveItem(mcore::CVector2i32& vecItemPositionChange); void onResizeItem(mcore::CVector2i32& vecItemPositionChange, mcore::CVector2i32& vecItemSizeChange); void setActiveItem(void); CWindow* getWindow(void); bool isPointInBoundingRectangle(mcore::CPoint2D& vecPoint, uint32 uiOuterSpacing); void setLayer(CGUILayer* pLayer) { m_pLayer = pLayer; } CGUILayer* getLayer(void) { return m_pLayer; } private: CGUILayer* m_pLayer; }; #endif
[ "mexuk@hotmail.co.uk" ]
mexuk@hotmail.co.uk
f871c64900bfac192b8974eca1aba743c5a9d762
b6c6abd9ca237622143dedd712b8f48b1000dfb6
/net/quic/test_tools/gtest_util.h
76226109d751606ee67b6539e3572649f905186f
[ "BSD-3-Clause" ]
permissive
chadrockey/chromium
b4e68f5f9faa7bf03aae7cda72e80903ef88cddb
434b5a0940e0c76d371ecd465a0d066824a69db8
refs/heads/master
2021-01-15T23:58:19.270969
2014-01-24T21:50:23
2014-01-24T21:50:23
16,219,343
0
1
null
null
null
null
UTF-8
C++
false
false
4,280
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Testing utilities that extend gtest. #ifndef NET_QUIC_TEST_TOOLS_GTEST_UTIL_H_ #define NET_QUIC_TEST_TOOLS_GTEST_UTIL_H_ #include "net/quic/test_tools/scoped_disable_exit_on_dfatal.h" #include "net/quic/test_tools/scoped_mock_log.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { namespace test { // Internal implementation for the EXPECT_DFATAL and ASSERT_DFATAL // macros. Do not use this directly. #define GTEST_DFATAL_(statement, matcher, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (true) { \ ::net::test::ScopedMockLog gtest_log; \ ::net::test::ScopedDisableExitOnDFatal gtest_disable_exit; \ using ::testing::_; \ EXPECT_CALL(gtest_log, Log(_, _, _, _, _)) \ .WillRepeatedly(::testing::Return(false)); \ EXPECT_CALL(gtest_log, Log(logging::LOG_DFATAL, _, _, _, matcher)) \ .Times(::testing::AtLeast(1)) \ .WillOnce(::testing::Return(false)); \ gtest_log.StartCapturingLogs(); \ { statement; } \ gtest_log.StopCapturingLogs(); \ if (!testing::Mock::VerifyAndClear(&gtest_log)) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_dfatal_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_dfatal_, __LINE__): \ fail("") // The EXPECT_DFATAL and ASSERT_DFATAL macros are lightweight // alternatives to EXPECT_DEBUG_DEATH and ASSERT_DEBUG_DEATH. They // are appropriate for testing that your code logs a message at the // DFATAL level. // // Unlike EXPECT_DEBUG_DEATH and ASSERT_DEBUG_DEATH, these macros // execute the given statement in the current process, not a forked // one. This works because we disable exiting the program for // LOG(DFATAL). This makes the tests run more quickly. // // The _WITH() variants allow one to specify any matcher for the // DFATAL log message, whereas the other variants assume a regex. #define EXPECT_DFATAL_WITH(statement, matcher) \ GTEST_DFATAL_(statement, matcher, GTEST_NONFATAL_FAILURE_) #define ASSERT_DFATAL_WITH(statement, matcher) \ GTEST_DFATAL_(statement, matcher, GTEST_FATAL_FAILURE_) #define EXPECT_DFATAL(statement, regex) \ EXPECT_DFATAL_WITH(statement, ::testing::ContainsRegex(regex)) #define ASSERT_DFATAL(statement, regex) \ ASSERT_DFATAL_WITH(statement, ::testing::ContainsRegex(regex)) // The EXPECT_DEBUG_DFATAL and ASSERT_DEBUG_DFATAL macros are similar to // EXPECT_DFATAL and ASSERT_DFATAL. Use them in conjunction with DLOG(DFATAL) // or similar macros that produce no-op in opt build and DFATAL in dbg build. #ifndef NDEBUG #define EXPECT_DEBUG_DFATAL(statement, regex) \ EXPECT_DFATAL(statement, regex) #define ASSERT_DEBUG_DFATAL(statement, regex) \ ASSERT_DFATAL(statement, regex) #else // NDEBUG #define EXPECT_DEBUG_DFATAL(statement, regex) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (true) { \ (void)(regex); \ statement; \ } else \ GTEST_NONFATAL_FAILURE_("") #define ASSERT_DEBUG_DFATAL(statement, regex) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (true) { \ (void)(regex); \ statement; \ } else \ GTEST_NONFATAL_FAILURE_("") #endif // NDEBUG } // namespace test } // namespace net #endif // NET_QUIC_TEST_TOOLS_GTEST_UTIL_H_
[ "rch@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98" ]
rch@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98
c0d274d8e391ccfd8719216f8ef7846558318331
53efe285c9fa8cff0b6402afda520b539f413365
/Socket Programming Practice/BroadcastReceiver.cc
7d395bff3da84d929dd874b5e2edc5973d90656b
[ "MIT" ]
permissive
mohitreddy1996/Parallel-Programming
df4f66bec48e0f8bb697450940b05d76ab28cec6
5c70aa2ce110859504b9fe68056e3d123d0b2f42
refs/heads/master
2020-05-23T09:09:57.260198
2017-05-04T18:08:19
2017-05-04T18:08:19
80,441,256
0
0
null
null
null
null
UTF-8
C++
false
false
1,149
cc
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #define MAXRECVSTRING 255 int main(int argc, char *argv[]){ int socket; struct sockaddr_in broadcastAddr; unsigned short broadcastPort; char recvString[MAXRECVSTRING+1]; int recvStringLen; broadcastPort = atoi(argv[1]); // create a socket; if((socket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0){ perror("socket() failed"); exit(1); } // broadcast Addr. memset(&broadcastAddr, 0, sizeof(broadcastAddr)); broadcastAddr.sin_family = AF_INET; broadcastAddr.sin_port = htons(broadcastPort); broadcastAddr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(socket, (struct sockaddr *)&broadcastAddr, sizeof(broadcastAddr)) < 0){ perror("bind() failed"); exit(1); } if((recvStringLen = recvfrom(socket, recvString, MAXRECVSTRING, 0, NULL, 0)) < 0){ perror("recvfrom() failed"); exit(1); } recvString[recvStringLen] = '\0'; printf("Received : %s", recvString); close(socket); return 0; }
[ "mohitreddy1996@gmail.com" ]
mohitreddy1996@gmail.com
ebcc985afda9624639910eb083d08d7692e566e5
483428f23277dc3fd2fad6588de334fc9b8355d2
/hpp/Win32/Release/Vcl.uTPLb_ComponentRegistration.hpp
3378b3f7e55ecf7195a29bf630504b5f757d4276
[]
no_license
gzwplato/LockBox3-1
7084932d329beaaa8169b94729c4b05c420ebe44
89e300b47f8c1393aefbec01ffb89ddf96306c55
refs/heads/master
2021-05-10T18:41:18.748523
2015-07-04T09:48:06
2015-07-04T09:48:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,534
hpp
// CodeGear C++Builder // Copyright (c) 1995, 2015 by Embarcadero Technologies, Inc. // All rights reserved // (DO NOT EDIT: machine generated header) 'Vcl.uTPLb_ComponentRegistration.pas' rev: 29.00 (Windows) #ifndef Vcl_Utplb_componentregistrationHPP #define Vcl_Utplb_componentregistrationHPP #pragma delphiheader begin #pragma option push #pragma option -w- // All warnings off #pragma option -Vx // Zero-length empty class member #pragma pack(push,8) #include <System.hpp> #include <SysInit.hpp> //-- user supplied ----------------------------------------------------------- namespace Vcl { namespace Utplb_componentregistration { //-- forward type declarations ----------------------------------------------- //-- type declarations ------------------------------------------------------- //-- var, const, procedure --------------------------------------------------- extern DELPHI_PACKAGE void __fastcall Register(void); } /* namespace Utplb_componentregistration */ } /* namespace Vcl */ #if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_VCL_UTPLB_COMPONENTREGISTRATION) using namespace Vcl::Utplb_componentregistration; #endif #if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_VCL) using namespace Vcl; #endif #pragma pack(pop) #pragma option pop #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // Vcl_Utplb_componentregistrationHPP
[ "roman.kassebaum@kdv-dt.de" ]
roman.kassebaum@kdv-dt.de
720dd017f8540f78275fcb9317f9d1df3d2801f4
26055315da4fc1ccc3f99a6a927184fa9a8b9e5a
/Agent.cpp
0e98d1e82deb1d550b3c0c7d481eef3c3f6088ba
[]
no_license
NUDTQI/PredatorPrey-MAXQ-BT
4645ff98464d101fc49641474f6d401a4c1351c8
ed98f1e5ac914f02fc22c0f89cdb341319612578
refs/heads/master
2021-01-02T09:29:53.527281
2017-08-03T10:44:48
2017-08-03T10:44:48
99,222,031
0
0
null
null
null
null
UTF-8
C++
false
false
6,994
cpp
#include "Agent.h" #include "2d/C2DMatrix.h" #include "2d/Geometry.h" #include "SteeringBehaviors.h" #include "2d/Transformations.h" #include "GameWorld.h" #include "misc/CellSpacePartition.h" #include "misc/cgdi.h" #include "SensorMemory.h" #include "GameMap.h" using std::vector; using std::list; //----------------------------- ctor ------------------------------------- //------------------------------------------------------------------------ Agent::Agent(GameWorld* world, Vector2D position, double rotation, Vector2D velocity, double mass, double max_force, double max_speed, double max_turn_rate, double scale, double ViewDistance, int max_Health): MovingEntity(position, scale, velocity, max_speed, Vector2D(sin(rotation),-cos(rotation)), mass, Vector2D(scale,scale), max_turn_rate, max_force), m_pWorld(world), m_vSmoothedHeading(Vector2D(0,0)), m_bSmoothingOn(false), m_dTimeElapsed(0.0), m_dSensorRange(ViewDistance), m_iHealth(max_Health), m_iMaxHealth(max_Health), m_iScore(0) { InitializeBuffer(); m_dFieldOfView = 2*pi; SetAlive(); //set up the steering behavior class m_pSteering = new SteeringBehavior(this); //set up the steering behavior class m_pSenseSys = new SensorMemory(this); //set up the smoother m_pHeadingSmoother = new Smoother<Vector2D>(Prm.NumSamplesForSmoothing, Vector2D(0.0, 0.0)); m_bDamaged = false; m_iEnemyNum = 0; } //---------------------------- dtor ------------------------------------- //----------------------------------------------------------------------- Agent::~Agent() { delete m_pSteering; m_pSteering = NULL; delete m_pSenseSys; m_pSenseSys = NULL; delete m_pHeadingSmoother; m_pHeadingSmoother = NULL; } //------------------------------ Update ---------------------------------- // // Updates the Agent's position from a series of steering behaviors //------------------------------------------------------------------------ void Agent::UpdateMovement(double time_elapsed) { //update the time elapsed m_dTimeElapsed = time_elapsed; //calculate the combined steering force Vector2D force = m_pSteering->Calculate(); //if no steering force is produced decelerate the player by applying a //braking force if (m_pSteering->Force().isZero()) { const double BrakingRate = 0.01; m_vVelocity = m_vVelocity * BrakingRate; } //calculate the acceleration Vector2D accel = force / m_dMass; //update the velocity m_vVelocity += accel* time_elapsed; //make sure Agent does not exceed maximum velocity m_vVelocity.Truncate(m_dMaxSpeed); //update the position m_vPos += m_vVelocity * time_elapsed; //if the Agent has a non zero velocity the heading and side vectors must //be updated if (!m_vVelocity.isZero()) { m_vHeading = Vec2DNormalize(m_vVelocity); m_vSide = m_vHeading.Perp(); } //treat the screen as a toroid WrapAround(m_vPos, m_pWorld->cxClient(), m_pWorld->cyClient()); } //-------------------------------- Render ------------------------------------- //----------------------------------------------------------------------------- void Agent::Render() { gdi->BluePen(); gdi->HollowBrush(); gdi->Circle(Pos(), BRadius()+1); } //----------------------------- InitializeBuffer ----------------------------- // // fills the Agent's shape buffer with its vertices //----------------------------------------------------------------------------- void Agent::InitializeBuffer() { const int NumAgentVerts = 3; Vector2D Agent[NumAgentVerts] = {Vector2D(-1.0f,0.6f), Vector2D(1.0f,0.0f), Vector2D(-1.0f,-0.6f)}; //setup the vertex buffers and calculate the bounding radius for (int vtx=0; vtx<NumAgentVerts; ++vtx) { m_vecAgentVB.push_back(Agent[vtx]); } } void Agent::UpdateSensorSys() { m_pSenseSys->UpdateVision(); } void Agent::RestoreHealthToMaximum() { m_iHealth = m_iMaxHealth; } //------------------ RotateFacingTowardPosition ------------------------------- // // given a target position, this method rotates the bot's facing vector // by an amount not greater than m_dMaxTurnRate until it // directly faces the target. // // returns true when the heading is facing in the desired direction bool Agent::RotateFacingTowardPosition( Vector2D target ) { Vector2D toTarget = Vec2DNormalize(target - Pos()); double dot = m_vFacing.Dot(toTarget); //clamp to rectify any rounding errors Clamp(dot, -1, 1); //determine the angle between the heading vector and the target double angle = acos(dot); //return true if the bot's facing is within WeaponAimTolerance degs of //facing the target const double WeaponAimTolerance = 0.01; //2 degs approx if (angle < WeaponAimTolerance) { m_vFacing = toTarget; return true; } //clamp the amount to turn to the max turn rate if (angle > m_dMaxTurnRate) angle = m_dMaxTurnRate; //The next few lines use a rotation matrix to rotate the player's facing //vector accordingly C2DMatrix RotationMatrix; //notice how the direction of rotation has to be determined when creating //the rotation matrix RotationMatrix.Rotate(angle * m_vFacing.Sign(toTarget)); RotationMatrix.TransformVector2Ds(m_vFacing); return false; } void Agent::ReduceHealth( unsigned int val ) { m_iHealth -= val; if (m_iHealth <= 0) { SetDead(); } } void Agent::IncreaseHealth( unsigned int val ) { m_iHealth+=val; Clamp(m_iHealth, 0, m_iMaxHealth); } void Agent::Update(double time_elapsed) { //update the sensory memory with any visual stimulus UpdateSensorSys(); //think-decide to choose action SelectAction(); //Calculate the steering force and update the bot's velocity and position UpdateMovement(time_elapsed); } void Agent::SelectAction() { } std::vector<Agent*>& Agent::GetAllyBotsInRange() { return GetSensorMem()->m_AllBotsInRange; } Prey* Agent::GetNearestPrey() { return GetSensorMem()->pNearestPrey; } Predator* Agent::GetNearestPredator() { return GetSensorMem()->pNearestPredator; } BaseGameEntity* Agent::GetNearestHaven() { return GetSensorMem()->pNearestHaven; } BaseGameEntity* Agent::GetNearestFood() { return GetSensorMem()->pNearestFood; }
[ "zhangqiy123@gmail.com" ]
zhangqiy123@gmail.com
ad7d98814be01bc288a50483fb89f3afdbc9576b
2b1b459706bbac83dad951426927b5798e1786fc
/zircon/system/ulib/concurrent/copy.cc
50a6368dcb74fe4cfe8e8e639d0731768b30294b
[ "BSD-2-Clause", "BSD-3-Clause", "MIT" ]
permissive
gnoliyil/fuchsia
bc205e4b77417acd4513fd35d7f83abd3f43eb8d
bc81409a0527580432923c30fbbb44aba677b57d
refs/heads/main
2022-12-12T11:53:01.714113
2022-01-08T17:01:14
2022-12-08T01:29:53
445,866,010
4
3
BSD-2-Clause
2022-10-11T05:44:30
2022-01-08T16:09:33
C++
UTF-8
C++
false
false
6,809
cc
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/concurrent/copy.h> #include <lib/stdcompat/atomic.h> #include <zircon/assert.h> namespace concurrent { namespace internal { template <typename T, CopyDir kDirection, std::memory_order kOrder> inline void CopyElement(void* _dst, const void* _src, size_t offset_bytes) { const T* src = reinterpret_cast<const T*>(reinterpret_cast<const uint8_t*>(_src) + offset_bytes); T* dst = reinterpret_cast<T*>(reinterpret_cast<uint8_t*>(_dst) + offset_bytes); static_assert(((kDirection == CopyDir::To) && ((kOrder == std::memory_order_relaxed) || (kOrder == std::memory_order_release))) || ((kDirection == CopyDir::From) && ((kOrder == std::memory_order_relaxed) || (kOrder == std::memory_order_acquire)))); if constexpr (kDirection == CopyDir::To) { cpp20::atomic_ref(*dst).store(*src, kOrder); } else { *dst = cpp20::atomic_ref(*src).load(kOrder); } } template <CopyDir kDir, SyncOpt kSyncOpt, MaxTransferAligned kMaxTransferAligned> void WellDefinedCopy(void* dst, const void* src, size_t size_bytes) { // To keep life simple, we demand that both the source and the destination // have the same alignment relative to our max transfer granularity. ZX_DEBUG_ASSERT((reinterpret_cast<uintptr_t>(src) & (kMaxTransferGranularity - 1)) == (reinterpret_cast<uintptr_t>(dst) & (kMaxTransferGranularity - 1))); // In debug builds, make sure that src and dst obey the template specified // worst case alignment. // // TODO(johngro): Consider demoting these asserts to existing only in a // super-duper-debug build, if we ever have such a thing. ZX_DEBUG_ASSERT((kMaxTransferAligned == MaxTransferAligned::No) || (reinterpret_cast<uintptr_t>(src) & (kMaxTransferGranularity - 1)) == 0); ZX_DEBUG_ASSERT((kMaxTransferAligned == MaxTransferAligned::No) || (reinterpret_cast<uintptr_t>(dst) & (kMaxTransferGranularity - 1)) == 0); // Sync options at this point should be either to use Acquire/Release on the // options, or to simply use relaxed. Use of fences should have been handled // at the inline wrapper level. static_assert((kSyncOpt == SyncOpt::AcqRelOps) || (kSyncOpt == SyncOpt::None)); if (size_bytes == 0) { return; } constexpr std::memory_order kOrder = (kSyncOpt == SyncOpt::None) ? std::memory_order_relaxed : ((kDir == CopyDir::To) ? std::memory_order_release : std::memory_order_acquire); // Start by bringing our pointer to 8 byte alignment. Skip any steps which // are not required based on our template specified worst case alignment. size_t offset_bytes = 0; if constexpr (kMaxTransferAligned == MaxTransferAligned::No) { const size_t current_alignment = (reinterpret_cast<uintptr_t>(src) & (sizeof(uint64_t) - 1)); if (current_alignment > 0) { const size_t align_bytes = std::min(size_bytes, sizeof(uint64_t) - current_alignment); switch (align_bytes) { case 1: CopyElement<uint8_t, kDir, kOrder>(dst, src, 0); break; case 2: CopyElement<uint16_t, kDir, kOrder>(dst, src, 0); break; case 3: CopyElement<uint8_t, kDir, kOrder>(dst, src, 0); CopyElement<uint16_t, kDir, kOrder>(dst, src, 1); break; case 4: CopyElement<uint32_t, kDir, kOrder>(dst, src, 0); break; case 5: CopyElement<uint8_t, kDir, kOrder>(dst, src, 0); CopyElement<uint32_t, kDir, kOrder>(dst, src, 1); break; case 6: CopyElement<uint16_t, kDir, kOrder>(dst, src, 0); CopyElement<uint32_t, kDir, kOrder>(dst, src, 2); break; case 7: CopyElement<uint8_t, kDir, kOrder>(dst, src, 0); CopyElement<uint16_t, kDir, kOrder>(dst, src, 1); CopyElement<uint32_t, kDir, kOrder>(dst, src, 3); break; default: ZX_DEBUG_ASSERT(false); } offset_bytes += align_bytes; } } // Now copy the bulk portion of the data using 64 bit transfers. static_assert(kMaxTransferGranularity == sizeof(uint64_t)); while (offset_bytes + sizeof(uint64_t) <= size_bytes) { CopyElement<uint64_t, kDir, kOrder>(dst, src, offset_bytes); offset_bytes += sizeof(uint64_t); } // If there is anything left to do, take care of the remainder using smaller // transfers. size_t remainder = size_bytes - offset_bytes; if (remainder > 0) { switch (remainder) { case 1: CopyElement<uint8_t, kDir, kOrder>(dst, src, offset_bytes + 0); break; case 2: CopyElement<uint16_t, kDir, kOrder>(dst, src, offset_bytes + 0); break; case 3: CopyElement<uint16_t, kDir, kOrder>(dst, src, offset_bytes + 0); CopyElement<uint8_t, kDir, kOrder>(dst, src, offset_bytes + 2); break; case 4: CopyElement<uint32_t, kDir, kOrder>(dst, src, offset_bytes + 0); break; case 5: CopyElement<uint32_t, kDir, kOrder>(dst, src, offset_bytes + 0); CopyElement<uint8_t, kDir, kOrder>(dst, src, offset_bytes + 4); break; case 6: CopyElement<uint32_t, kDir, kOrder>(dst, src, offset_bytes + 0); CopyElement<uint16_t, kDir, kOrder>(dst, src, offset_bytes + 4); break; case 7: CopyElement<uint32_t, kDir, kOrder>(dst, src, offset_bytes + 0); CopyElement<uint16_t, kDir, kOrder>(dst, src, offset_bytes + 4); CopyElement<uint8_t, kDir, kOrder>(dst, src, offset_bytes + 6); break; default: ZX_DEBUG_ASSERT(false); } } } // explicit instantiation of all of the different forms of WellDefinedCopy using SO = SyncOpt; using MTA = MaxTransferAligned; template void WellDefinedCopy<CopyDir::To, SO::AcqRelOps, MTA::No>(void*, const void*, size_t); template void WellDefinedCopy<CopyDir::To, SO::AcqRelOps, MTA::Yes>(void*, const void*, size_t); template void WellDefinedCopy<CopyDir::To, SO::None, MTA::No>(void*, const void*, size_t); template void WellDefinedCopy<CopyDir::To, SO::None, MTA::Yes>(void*, const void*, size_t); template void WellDefinedCopy<CopyDir::From, SO::AcqRelOps, MTA::No>(void*, const void*, size_t); template void WellDefinedCopy<CopyDir::From, SO::AcqRelOps, MTA::Yes>(void*, const void*, size_t); template void WellDefinedCopy<CopyDir::From, SO::None, MTA::No>(void*, const void*, size_t); template void WellDefinedCopy<CopyDir::From, SO::None, MTA::Yes>(void*, const void*, size_t); } // namespace internal } // namespace concurrent
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
a53777a4cf33ff29f76a156b470d4295a54ace43
9c5eb516959ebd728a6c5c7c13ef00e3ac2d5c33
/src/pscpu/YMatrix.h
d9b1596475cffb40aa868c7845394731ae0d04ef
[ "ISC", "BSD-3-Clause" ]
permissive
shufengdong/c-algorithms
63e6fdb7f7817ba08f0e48411b5cb5ca358e1e71
dce643a3c8cdf101fb971244e39620fbca784216
refs/heads/master
2020-12-26T21:35:49.732935
2016-10-07T06:10:46
2016-10-07T06:10:46
35,422,620
0
1
null
2015-05-11T12:32:44
2015-05-11T12:32:44
null
UTF-8
C++
false
false
675
h
#ifndef __YMatrix_H__ #define __YMatrix_H__ #include"IEEEDataIsland.hpp" #include"SparseMatrix.h" using namespace std; namespace cpscpu { class YMatrix { public: YMatrix(); ~YMatrix() { freeSpace(); }; SparseMatrix admittance[2]; // G:admittance[0]; B:admittance[1]; int * lineFrom; int * lineTo; double * lineFromAdmittance; double * lineToAdmittance; void formMatrix(IEEEDataIsland *island); private: void freeSpace(); void getBranchAdmittance(BranchData, double[][4]); void getBranchAdmittanceFrom(BranchData branch, double v[4]); void getBranchAdmittanceTo(BranchData branch, double v[4]); }; }//end of namespace #endif
[ "dongshufeng@zju.edu.cn" ]
dongshufeng@zju.edu.cn
ba0e7495f30257f530afaf052cf7e1e6f593d706
9d74c3758df140202e49885062037a7e4076c5cf
/CMSCpp2.1/src/gui/Unit3.h
8411f2083831e7295323ce5e440f57677d35ac69
[]
no_license
skyforcetw/mygoodjob
4c3a787b651d8ea181b843848f829facf051fbfe
fcfd34203825282e4adaac5aff7396d06775ed15
refs/heads/master
2016-09-06T07:52:18.962274
2015-07-21T16:50:17
2015-07-21T16:50:17
32,502,731
0
0
null
null
null
null
BIG5
C++
false
false
2,032
h
//--------------------------------------------------------------------------- #ifndef Unit3H #define Unit3H //--------------------------------------------------------------------------- //C系統文件 //C++系統文件 //其他庫頭文件 #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> //本項目內頭文件 #include <java/lang.h> //--------------------------------------------------------------------------- class TForm3:public TForm { __published: // IDE-managed Components TButton * Button1; TGroupBox *GroupBox1; TRadioButton *RadioButton_Single; TEdit *Edit_Single; TRadioButton *RadioButton_Dual; TEdit *Edit_Master; TEdit *Edit_Slave; TGroupBox *GroupBox2; TRadioButton *RadioButton_USB; TRadioButton *RadioButton_LPT; TCheckBox *CheckBox_Connecting; TGroupBox *GroupBox3; TLabel *Label1; TLabel *Label2; TLabel *Label3; TCheckBox *CheckBox1; TEdit *Edit_R; TEdit *Edit_G; TEdit *Edit_B; TGroupBox *GroupBox4; TEdit *Edit_GammaTestAddress; TEdit *Edit_GammaTestBit; TEdit *Edit_TestRGBAdress; TCheckBox *CheckBox_IndepRGB; void __fastcall Button1Click(TObject *Sender); void __fastcall CheckBox_ConnectingClick(TObject *Sender); void __fastcall CheckBox1Click(TObject *Sender); void __fastcall Edit_RChange(TObject *Sender); void __fastcall Edit_GChange(TObject *Sender); void __fastcall Edit_BChange(TObject *Sender); private: // User declarations bptr < cms::i2c::i2cControl > i2c; bptr < cms::i2c::TCONParameter > parameter; bptr < cms::i2c::TCONControl > control; public: // User declarations __fastcall TForm3(TComponent * Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TForm3 *Form3; //--------------------------------------------------------------------------- #endif
[ "skyforce@1153854a-e0ba-11de-81d3-db62269da9c1" ]
skyforce@1153854a-e0ba-11de-81d3-db62269da9c1
7069f39b2128eccb36901af5c79fade22b7a84c8
94fc5fdb1286c831f19c376829671aa695281365
/plugins/protein/src/Protein.cpp
0d5c112befaad1213751fad4a33af652489c198e
[]
no_license
PhilippGruber/megamol
08c483d3df7e6ae4931cbeafb689a9dacefe7887
15b17e200b8e7d4f9da0b7143e08327936233b97
refs/heads/master
2021-07-11T08:22:50.011350
2017-10-06T11:48:14
2017-10-06T11:48:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,164
cpp
/* * Protein.cpp * * Copyright (C) 2009 by VISUS (Universitaet Stuttgart) * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "protein/Protein.h" #include "mmcore/api/MegaMolCore.std.h" // views #include "View3DSpaceMouse.h" #include "View3DMouse.h" // jobs #include "PDBWriter.h" #include "VTIWriter.h" // 3D renderers #include "ProteinVolumeRenderer.h" #include "SolventVolumeRenderer.h" #include "SimpleMoleculeRenderer.h" #include "SphereRenderer.h" #include "SolPathRenderer.h" #include "MoleculeSESRenderer.h" #include "MoleculeCartoonRenderer.h" #include "ElectrostaticsRenderer.h" #include "HapticsMoleculeRenderer.h" #include "SSAORendererDeferred.h" #include "ToonRendererDeferred.h" #include "DofRendererDeferred.h" #include "SphereRendererMouse.h" #include "GLSLVolumeRenderer.h" #include "VariantMatchRenderer.h" #include "SecPlaneRenderer.h" #include "UnstructuredGridRenderer.h" #include "VolumeDirectionRenderer.h" #include "LayeredIsosurfaceRenderer.h" #include "CartoonRenderer.h" #include "CartoonTessellationRenderer.h" // 2D renderers #include "VolumeSliceRenderer.h" #include "Diagram2DRenderer.h" #include "DiagramRenderer.h" #include "SplitMergeRenderer.h" #include "SequenceRenderer.h" // data sources #include "PDBLoader.h" #include "SolPathDataSource.h" #include "CCP4VolumeData.h" #include "CoarseGrainDataLoader.h" #include "FrodockLoader.h" #include "XYZLoader.h" #include "SolventHydroBondGenerator.h" #include "GROLoader.h" #include "CrystalStructureDataSource.h" #include "VTILoader.h" #include "VMDDXLoader.h" #include "TrajectorySmoothFilter.h" #include "BindingSiteDataSource.h" #include "AggregatedDensity.h" #include "ResidueSelection.h" #include "VTKLegacyDataLoaderUnstructuredGrid.h" #include "MolecularBezierData.h" #include "MultiPDBLoader.h" #include "OpenBabelLoader.h" // data interfaces (calls) #include "SolPathDataCall.h" #include "mmcore/CallVolumeData.h" #include "CallColor.h" #include "SphereDataCall.h" #include "VolumeSliceCall.h" #include "Diagram2DCall.h" #include "ParticleDataCall.h" #include "ForceDataCall.h" #include "VTKLegacyDataCallUnstructuredGrid.h" #include "MoleculeBallifier.h" // other modules (filter etc) #include "ColorModule.h" #include "IntSelection.h" #include "MultiParticleDataFilter.h" #include "PDBInterpolator.h" #include "ProteinExploder.h" #include "MolecularNeighborhood.h" #include "HydroBondFilter.h" #include "mmcore/versioninfo.h" #include "vislib/vislibversion.h" #include "vislib/sys/Log.h" #include "vislib/Trace.h" /* anonymous namespace hides this type from any other object files */ namespace { /** Implementing the instance class of this plugin */ class plugin_instance : public ::megamol::core::utility::plugins::Plugin200Instance { public: /** ctor */ plugin_instance(void) : ::megamol::core::utility::plugins::Plugin200Instance( /* machine-readable plugin assembly name */ "Protein", /* human-readable plugin description */ "Plugin for protein rendering (SFB716 D4)") { // here we could perform addition initialization }; /** Dtor */ virtual ~plugin_instance(void) { // here we could perform addition de-initialization } /** Registers modules and calls */ virtual void registerClasses(void) { // register modules here: #ifdef WITH_OPENHAPTICS this->module_descriptions.RegisterAutoDescription<megamol::protein::HapticsMoleculeRenderer>(); #endif // WITH_OPENHAPTICS #ifdef WITH_OPENBABEL this->module_descriptions.RegisterAutoDescription<megamol::protein::OpenBabelLoader>(); #endif // WITH_OPENBABEL this->module_descriptions.RegisterAutoDescription<megamol::protein::SequenceRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::BindingSiteDataSource>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::SolPathDataSource>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::SolPathRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::ProteinVolumeRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::CCP4VolumeData>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::PDBLoader>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::SimpleMoleculeRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::CoarseGrainDataLoader>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::SphereRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::MoleculeSESRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::MoleculeCartoonRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::FrodockLoader>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::VolumeSliceRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::Diagram2DRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::XYZLoader>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::ElectrostaticsRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::SolventVolumeRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::SolventHydroBondGenerator>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::View3DSpaceMouse>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::GROLoader>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::SSAORendererDeferred>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::ToonRendererDeferred>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::DofRendererDeferred>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::SphereRendererMouse>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::View3DMouse>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::GLSLVolumeRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::DiagramRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::SplitMergeRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::IntSelection>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::CrystalStructureDataSource>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::VTILoader>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::PDBWriter>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::VTIWriter>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::VMDDXLoader>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::TrajectorySmoothFilter>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::VariantMatchRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::MoleculeBallifier>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::ResidueSelection>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::SecPlaneRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::AggregatedDensity>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::VTKLegacyDataLoaderUnstructuredGrid>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::UnstructuredGridRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::MolecularBezierData>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::MultiParticleDataFilter>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::VolumeDirectionRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::LayeredIsosurfaceRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::MultiPDBLoader>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::ColorModule>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::PDBInterpolator>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::CartoonRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::CartoonTessellationRenderer>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::ProteinExploder>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::MolecularNeighborhood>(); this->module_descriptions.RegisterAutoDescription<megamol::protein::HydroBondFilter>(); // register calls here: this->call_descriptions.RegisterAutoDescription<megamol::protein::SolPathDataCall>(); this->call_descriptions.RegisterAutoDescription<megamol::protein::CallProteinVolumeData>(); this->call_descriptions.RegisterAutoDescription<megamol::protein::SphereDataCall>(); this->call_descriptions.RegisterAutoDescription<megamol::protein::VolumeSliceCall>(); this->call_descriptions.RegisterAutoDescription<megamol::protein::Diagram2DCall>(); this->call_descriptions.RegisterAutoDescription<megamol::protein::ParticleDataCall>(); this->call_descriptions.RegisterAutoDescription<megamol::protein::ForceDataCall>(); this->call_descriptions.RegisterAutoDescription<megamol::protein::VTKLegacyDataCallUnstructuredGrid>(); this->call_descriptions.RegisterAutoDescription<megamol::protein::CallColor>(); } MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_plugininstance_connectStatics }; } /* * mmplgPluginAPIVersion */ PROTEIN_API int mmplgPluginAPIVersion(void) { MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgPluginAPIVersion } /* * mmplgGetPluginCompatibilityInfo */ PROTEIN_API ::megamol::core::utility::plugins::PluginCompatibilityInfo * mmplgGetPluginCompatibilityInfo( ::megamol::core::utility::plugins::ErrorCallback onError) { // compatibility information with core and vislib using ::megamol::core::utility::plugins::PluginCompatibilityInfo; using ::megamol::core::utility::plugins::LibraryVersionInfo; PluginCompatibilityInfo *ci = new PluginCompatibilityInfo; ci->libs_cnt = 2; ci->libs = new LibraryVersionInfo[2]; SetLibraryVersionInfo(ci->libs[0], "MegaMolCore", MEGAMOL_CORE_MAJOR_VER, MEGAMOL_CORE_MINOR_VER, MEGAMOL_CORE_COMP_REV, 0 #if defined(DEBUG) || defined(_DEBUG) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DEBUG_BUILD #endif #if defined(MEGAMOL_CORE_DIRTY) && (MEGAMOL_CORE_DIRTY != 0) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DIRTY_BUILD #endif ); SetLibraryVersionInfo(ci->libs[1], "vislib", VISLIB_VERSION_MAJOR, VISLIB_VERSION_MINOR, VISLIB_VERSION_REVISION, 0 #if defined(DEBUG) || defined(_DEBUG) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DEBUG_BUILD #endif #if defined(VISLIB_DIRTY_BUILD) && (VISLIB_DIRTY_BUILD != 0) | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DIRTY_BUILD #endif ); // // If you want to test additional compatibilties, add the corresponding versions here // return ci; } /* * mmplgReleasePluginCompatibilityInfo */ PROTEIN_API void mmplgReleasePluginCompatibilityInfo( ::megamol::core::utility::plugins::PluginCompatibilityInfo* ci) { // release compatiblity data on the correct heap MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginCompatibilityInfo(ci) } /* * mmplgGetPluginInstance */ PROTEIN_API ::megamol::core::utility::plugins::AbstractPluginInstance* mmplgGetPluginInstance( ::megamol::core::utility::plugins::ErrorCallback onError) { MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgGetPluginInstance(plugin_instance, onError) } /* * mmplgReleasePluginInstance */ PROTEIN_API void mmplgReleasePluginInstance( ::megamol::core::utility::plugins::AbstractPluginInstance* pi) { MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginInstance(pi) }
[ "guido.reina@informatik.uni-stuttgart.de" ]
guido.reina@informatik.uni-stuttgart.de
4295b7bd45c834cbf0b98c322a81a5b627b18c60
6e87882e55d08fe94fc6b85c1f5b062bd149f64e
/src/test/cpp/RefTo.hpp
9cef50a1f0a84f8d4828bf2c792e7093ba83c902
[]
no_license
jvff/mestrado-implementacao
1033a490860977a8ffb0bdfe648564f53e3cbabf
47fb47495112d30940328e7e55cf7e7efba903a9
refs/heads/master
2020-12-29T01:54:06.142023
2016-07-03T01:11:37
2016-07-07T15:30:27
42,725,607
0
0
null
null
null
null
UTF-8
C++
false
false
910
hpp
#ifndef REF_TO_HPP #define REF_TO_HPP #include "fakeit.hpp" template <typename T> struct RefToMatcherCreator : public fakeit::TypedMatcherCreator<T> { private: const T& expected; public: RefToMatcherCreator(const T& arg) : expected(arg) { } virtual fakeit::TypedMatcher<T>* createMatcher() const override { return new Matcher(expected); } struct Matcher : public fakeit::TypedMatcher<T> { private: const T& expected; public: Matcher(const T& arg) : expected(arg) { } virtual bool matches(const T& actual) const override { return &actual == &expected; } virtual std::string format() const override { return fakeit::Formatter<T>::format(this->expected); } }; }; template <typename T> RefToMatcherCreator<T> RefTo(const T& arg) { return RefToMatcherCreator<T>(arg); } #endif
[ "janito.vff@gmail.com" ]
janito.vff@gmail.com
98b1e2c0fa4c71d6b5e339c7400530dc68cbfe42
5454e5d7054305f69c9a743e5031289d9788c5b1
/piscine_cpp_d13/ex00/Picture.h
ffa8fb9b5b498fa6327eb47b232f596c7adaf10e
[]
no_license
Sherry-Du/piscine_cpp_2014
fb6556e2fe50cbb631755f2e7e6f8d4364c5cf6c
31ca6d3094d9c5b49e08bf6a8f8f6bc7d878f2b9
refs/heads/master
2020-03-22T03:52:42.873976
2015-07-05T13:31:47
2015-07-05T13:31:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
274
h
/** * vadee_s */ #ifndef PICTURE_ # define PICTURE_ #include <iostream> #include <fstream> class Picture { public: Picture(); ~Picture(); bool getPictureFromFile(const std::string& file); Picture(const std::string& file); std::string data; }; #endif
[ "simon.vadee@gmail.com" ]
simon.vadee@gmail.com
05e6412f97fa0b5383821e4ecabe96ff4ad22813
eb0c73172385bbab2007c317e018eaf5f080089a
/Source/ThirdPersonMP/ThirdPersonMPCharacter.cpp
ffd610efdd9d5a500ce599cc81e0c1356455bc0e
[]
no_license
nmaltais/ThirdPersonMP
5e3de084eecb2a8719ed835e81d046c1ca2fa1c0
9561c3d76203ee9805170dd1436e7e272843a86f
refs/heads/master
2023-03-10T17:15:35.131305
2021-02-24T22:36:10
2021-02-24T22:36:10
341,393,396
1
0
null
null
null
null
UTF-8
C++
false
false
9,311
cpp
#include "ThirdPersonMPCharacter.h" #include "HeadMountedDisplayFunctionLibrary.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "Components/InputComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "GameFramework/Controller.h" #include "GameFramework/SpringArmComponent.h" #include "Net/UnrealNetwork.h" #include "Engine/Engine.h" #include "ThirdPersonMPProjectile.h" #include "TimerManager.h" #include "ThirdPersonMPGameMode.h" ////////////////////////////////////////////////////////////////////////// // AThirdPersonMPCharacter AThirdPersonMPCharacter::AThirdPersonMPCharacter() { // Set size for collision capsule GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); // set our turn rates for input BaseTurnRate = 45.f; BaseLookUpRate = 45.f; // Don't rotate when the controller rotates. Let that just affect the camera. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = true; // 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++) //Initialize the player's Health MaxHealth = 100.0f; CurrentHealth = MaxHealth; //Initialize projectile class ProjectileClass = AThirdPersonMPProjectile::StaticClass(); //Initialize fire rate FireRate = 0.25f; bIsFiringWeapon = false; } ////////////////////////////////////////////////////////////////////////// // Input void AThirdPersonMPCharacter::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, &AThirdPersonMPCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &AThirdPersonMPCharacter::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, &AThirdPersonMPCharacter::TurnAtRate); PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); PlayerInputComponent->BindAxis("LookUpRate", this, &AThirdPersonMPCharacter::LookUpAtRate); // handle touch devices PlayerInputComponent->BindTouch(IE_Pressed, this, &AThirdPersonMPCharacter::TouchStarted); PlayerInputComponent->BindTouch(IE_Released, this, &AThirdPersonMPCharacter::TouchStopped); // VR headset functionality PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &AThirdPersonMPCharacter::OnResetVR); // Handle firing projectiles PlayerInputComponent->BindAction("Fire", IE_Pressed, this, &AThirdPersonMPCharacter::StartFire); //PlayerInputComponent->BindAction("Fire", IE_Released, this, &AThirdPersonMPCharacter::StopFire); } ////////////////////////////////////////////////////////////////////////// // Replicated Properties void AThirdPersonMPCharacter::GetLifetimeReplicatedProps(TArray <FLifetimeProperty> & OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(AThirdPersonMPCharacter, CurrentHealth); } void AThirdPersonMPCharacter::StartFire() { if (!bIsFiringWeapon) { bIsFiringWeapon = true; UWorld* World = GetWorld(); World->GetTimerManager().SetTimer(FiringTimer, this, &AThirdPersonMPCharacter::StopFire, FireRate, false); HandleFire(); } } void AThirdPersonMPCharacter::StopFire() { bIsFiringWeapon = false; } void AThirdPersonMPCharacter::HandleFire_Implementation() { FVector spawnLocation = GetActorLocation() + ( GetControlRotation().Vector() * 100.0f ) + (GetActorUpVector() * 50.0f); FRotator spawnRotation = GetActorRotation(); FActorSpawnParameters spawnParameters; spawnParameters.Instigator = GetInstigator(); spawnParameters.Owner = this; AThirdPersonMPProjectile* spawnedProjectile = GetWorld()->SpawnActor<AThirdPersonMPProjectile>(spawnLocation, spawnRotation, spawnParameters); } void AThirdPersonMPCharacter::OnHealthUpdate() { //Client-specific functionality if (IsLocallyControlled()) { FString healthMessage = FString::Printf(TEXT("You now have %f health remaining."), CurrentHealth); GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Blue, healthMessage); if (CurrentHealth <= 0) { FString deathMessage = FString::Printf(TEXT("You have been killed.")); GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, deathMessage); } } //Server-specific functionality if (GetLocalRole() == ROLE_Authority) { FString healthMessage = FString::Printf(TEXT("%s now has %f health remaining."), *GetFName().ToString(), CurrentHealth); GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Blue, healthMessage); } //Functions that occur on all machines. /* Any special functionality that should occur as a result of damage or death should be placed here. */ } void AThirdPersonMPCharacter::OnRep_CurrentHealth() { OnHealthUpdate(); } void AThirdPersonMPCharacter::SetCurrentHealth(float healthValue) { if (GetLocalRole() == ROLE_Authority) { CurrentHealth = FMath::Clamp(healthValue, 0.f, MaxHealth); OnHealthUpdate(); } } float AThirdPersonMPCharacter::TakeDamage(float DamageTaken, struct FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser) { float healthLeft = CurrentHealth - DamageTaken; SetCurrentHealth(healthLeft); if(healthLeft <= 0){ Die(); } return healthLeft; } void AThirdPersonMPCharacter::OnResetVR() { UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition(); } void AThirdPersonMPCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location) { Jump(); } void AThirdPersonMPCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location) { StopJumping(); } void AThirdPersonMPCharacter::TurnAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void AThirdPersonMPCharacter::LookUpAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds()); } void AThirdPersonMPCharacter::MoveForward(float Value) { 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); AddMovementInput(Direction, Value); } } void AThirdPersonMPCharacter::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 AddMovementInput(Direction, Value); } } void AThirdPersonMPCharacter::Die() { // Respawn after 3 seconds AController* PC = Controller; AThirdPersonMPGameMode* GM = Cast<AThirdPersonMPGameMode>(GetWorld()->GetAuthGameMode()); if (GM) { GM->RespawnPlayerWithDelay(PC, 3); } Destroy(); }
[ "nic.maltais@gmail.com" ]
nic.maltais@gmail.com
4b4c4af31bc1e2194a3d320859384ffd811d35f8
5499e8b91353ef910d2514c8a57a80565ba6f05b
/src/connectivity/wlan/lib/common/cpp/include/wlan/common/from_bytes.h
9677291bce7c5d69be9747fbf8191824194abc3f
[ "BSD-3-Clause" ]
permissive
winksaville/fuchsia
410f451b8dfc671f6372cb3de6ff0165a2ef30ec
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
refs/heads/master
2022-11-01T11:57:38.343655
2019-11-01T17:06:19
2019-11-01T17:06:19
223,695,500
3
2
BSD-3-Clause
2022-10-13T13:47:02
2019-11-24T05:08:59
C++
UTF-8
C++
false
false
976
h
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SRC_CONNECTIVITY_WLAN_LIB_COMMON_CPP_INCLUDE_WLAN_COMMON_FROM_BYTES_H_ #define SRC_CONNECTIVITY_WLAN_LIB_COMMON_CPP_INCLUDE_WLAN_COMMON_FROM_BYTES_H_ #include <cstdint> #include <fbl/span.h> namespace wlan { template <typename T> T* FromBytes(uint8_t* buf, size_t len) { if (len < sizeof(T)) return nullptr; return reinterpret_cast<T*>(buf); } template <typename T> const T* FromBytes(const uint8_t* buf, size_t len) { if (len < sizeof(T)) return nullptr; return reinterpret_cast<const T*>(buf); } template <typename T> const T* FromBytes(fbl::Span<const uint8_t> bytes) { if (bytes.size() < sizeof(T)) return nullptr; return reinterpret_cast<const T*>(bytes.data()); } } // namespace wlan #endif // SRC_CONNECTIVITY_WLAN_LIB_COMMON_CPP_INCLUDE_WLAN_COMMON_FROM_BYTES_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
312197077c312a07bd2c6a27b448c2c5f63e7a06
e109e8b1fea4626827d2a6c57e87de514f7fc761
/排序算法/希尔排序.cpp
3ff35b3110b64bb2d3f6be659994b98e038bb805
[]
no_license
xwlee9/cpp
83a61f59a07b9a1059fd8f5dcc12db337e712b45
76d3f31d2f61fc1125f7526c2fb45473f850fed9
refs/heads/master
2020-05-06T14:04:07.885822
2019-06-25T18:21:47
2019-06-25T18:21:47
180,171,063
0
0
null
null
null
null
UTF-8
C++
false
false
879
cpp
#include <iostream> using namespace std; void PrintArray(int arr[], int length) { for(int i = 0; i < length; ++i) cout << arr[i] << " "; cout << endl; } void ShellSort(int arr[], int length) { int incereament = length; int i,j,k,temp; do { incereament = incereament / 3 + 1; for (i = 0; i < incereament; ++i) { for(j = i + incereament; j < length; j += incereament) { if (arr[j] < arr[j - incereament]) { temp = arr[j]; for(k = j-incereament; k >= 0 && temp< arr[k]; k -= incereament) arr[k + incereament] = arr[k]; arr[k + incereament] = temp; } } } } while(incereament > 1); } int main() { int MyArr[] = {4,2,8,0,5,7,1,3,6,9}; int length = sizeof(MyArr) / sizeof(int); PrintArray(MyArr, length); ShellSort(MyArr, length); PrintArray(MyArr, length); return 0; }
[ "noreply@github.com" ]
noreply@github.com
8ce4c0b4e7f601bc4557ebc16ae19178dbe25533
ba9322f7db02d797f6984298d892f74768193dcf
/ons/src/model/OnsDLQMessageGetByIdRequest.cc
d81f01d69d0a1a930889bcd94df1ae84f8ea8885
[ "Apache-2.0" ]
permissive
sdk-team/aliyun-openapi-cpp-sdk
e27f91996b3bad9226c86f74475b5a1a91806861
a27fc0000a2b061cd10df09cbe4fff9db4a7c707
refs/heads/master
2022-08-21T18:25:53.080066
2022-07-25T10:01:05
2022-07-25T10:01:05
183,356,893
3
0
null
2019-04-25T04:34:29
2019-04-25T04:34:28
null
UTF-8
C++
false
false
1,915
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/ons/model/OnsDLQMessageGetByIdRequest.h> using AlibabaCloud::Ons::Model::OnsDLQMessageGetByIdRequest; OnsDLQMessageGetByIdRequest::OnsDLQMessageGetByIdRequest() : RpcServiceRequest("ons", "2019-02-14", "OnsDLQMessageGetById") {} OnsDLQMessageGetByIdRequest::~OnsDLQMessageGetByIdRequest() {} long OnsDLQMessageGetByIdRequest::getPreventCache()const { return preventCache_; } void OnsDLQMessageGetByIdRequest::setPreventCache(long preventCache) { preventCache_ = preventCache; setCoreParameter("PreventCache", std::to_string(preventCache)); } std::string OnsDLQMessageGetByIdRequest::getInstanceId()const { return instanceId_; } void OnsDLQMessageGetByIdRequest::setInstanceId(const std::string& instanceId) { instanceId_ = instanceId; setCoreParameter("InstanceId", instanceId); } std::string OnsDLQMessageGetByIdRequest::getGroupId()const { return groupId_; } void OnsDLQMessageGetByIdRequest::setGroupId(const std::string& groupId) { groupId_ = groupId; setCoreParameter("GroupId", groupId); } std::string OnsDLQMessageGetByIdRequest::getMsgId()const { return msgId_; } void OnsDLQMessageGetByIdRequest::setMsgId(const std::string& msgId) { msgId_ = msgId; setCoreParameter("MsgId", msgId); }
[ "haowei.yao@alibaba-inc.com" ]
haowei.yao@alibaba-inc.com
db79d5392ec0204a6dcdacb11c82881c5ee9d4ab
5ebd5cee801215bc3302fca26dbe534e6992c086
/blazetest/src/mathtest/smatdmatsub/UCaUHb.cpp
f4b6f75e70f0a0cc8611d1c3b87a697b9450b05a
[ "BSD-3-Clause" ]
permissive
mhochsteger/blaze
c66d8cf179deeab4f5bd692001cc917fe23e1811
fd397e60717c4870d942055496d5b484beac9f1a
refs/heads/master
2020-09-17T01:56:48.483627
2019-11-20T05:40:29
2019-11-20T05:41:35
223,951,030
0
0
null
null
null
null
UTF-8
C++
false
false
4,205
cpp
//================================================================================================= /*! // \file src/mathtest/smatdmatsub/UCaUHb.cpp // \brief Source file for the UCaUHb sparse matrix/dense matrix subtraction math test // // Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/HybridMatrix.h> #include <blaze/math/UpperMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/smatdmatsub/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'UCaUHb'..." << std::endl; using blazetest::mathtest::TypeA; using blazetest::mathtest::TypeB; try { // Matrix type definitions using UCa = blaze::UpperMatrix< blaze::CompressedMatrix<TypeA> >; using UHb = blaze::UpperMatrix< blaze::HybridMatrix<TypeB,128UL,128UL> >; // Creator type definitions using CUCa = blazetest::Creator<UCa>; using CUHb = blazetest::Creator<UHb>; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=UCa::maxNonZeros( i ); ++j ) { RUN_SMATDMATSUB_OPERATION_TEST( CUCa( i, j ), CUHb( i ) ); } } // Running tests with large matrices RUN_SMATDMATSUB_OPERATION_TEST( CUCa( 67UL, 7UL ), CUHb( 67UL ) ); RUN_SMATDMATSUB_OPERATION_TEST( CUCa( 128UL, 16UL ), CUHb( 128UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix subtraction:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
b1710c10a5470a44fffd744b8bf2dbde0f45d1e2
21dfd5124c2f05ef5f98355996dc2313f1a29f5a
/Src/Controller/RoboCupCtrl.h
e26826009f3129a15c16da69bb9dbcd86383eb29
[ "BSD-2-Clause" ]
permissive
fabba/BH2013-with-coach
50244c3f69135cc18004a1af9e01604617b6859f
88d7ddc43456edc5daf0e259c058f6eca2ff8ef6
refs/heads/master
2020-05-16T03:21:29.005314
2015-03-04T10:41:08
2015-03-04T10:41:08
31,651,432
1
0
null
null
null
null
UTF-8
C++
false
false
4,299
h
/** * @file Controller/RoboCupCtrl.h * * This file declares the class RoboCupCtrl. * * @author <a href="mailto:Thomas.Roefer@dfki.de">Thomas Röfer</a> */ #pragma once #include <QList> #include <list> #include "SimRobotCore2.h" #include "Oracle.h" #include "GameController.h" class Robot; /** * The class implements the SimRobot controller for RoboCup. */ class RoboCupCtrl : public SimRobot::Module, public SimRobotCore2::CollisionCallback { public: static RoboCupCtrl* controller; /**< A pointer to the SimRobot controller. */ static SimRobot::Application* application; /**< The interface to the SimRobot GUI */ GameController gameController; /** * Constructor. */ RoboCupCtrl(SimRobot::Application& application); /** * Adds a scene graph object to the scene graph displayed in SimRobot * @param object The scene graph object to add * @param parent The parent scene graph object (e.g. a category or null) * @param flags Some flags for registering the scene graph object (see SimRobot::Flag) */ void addView(SimRobot::Object* object, const SimRobot::Object* parent = 0, int flags = 0); /** * Adds a scene graph object to the scene graph displayed in SimRobot * @param object The scene graph object to add * @param categoryName The full name of the parent categroy * @param flags Some flags for registering the scene graph object (see SimRobot::Flag) */ void addView(SimRobot::Object* object, const QString& categoryName, int flags = 0); /** * Adds a category to the scene graph displayed in SimRobot that can be used for grouping views * @param name The name of the category * @param parent The parent scene graph object (e.g. a category or null) * @param icon The icon used to list the category in the scene graph * @return The category */ SimRobot::Object* addCategory(const QString& name, const SimRobot::Object* parent = 0, const char* icon = 0); /** * Adds a category to the scene graph displayed in SimRobot that can be used for grouping views * @param name The name of the category * @param parentName The name of the parent scene graph object (e.g. a category) * @return The category */ SimRobot::Object* addCategory(const QString& name, const QString& parentName); /** * The function returns the full name of the robot currently constructed. * @return The name of the robot. */ static const char* getRobotFullName() {return controller->robotName;} /** * The function returns the name of the robot associated to the current thread. * @return The name of the robot. */ std::string getRobotName() const; /** * The function returns the model of the robot associated to the current thread. * @return The model of the robot. */ std::string getModelName() const; /** * The function returns the simulation time. * @return The pseudo-time in milliseconds. */ unsigned getTime() const; protected: const char* robotName; /**< The name of the robot currently constructed. */ std::list<Robot*> robots; /**< The list of all robots. */ int simStepLength; /**< The length of one simulation step (in ms) */ bool simTime; /**< Switches between simulation time mode and real time mode. */ bool dragTime; /**< Drag simulation to avoid running faster then realtime. */ int time; /**< The simulation time. */ unsigned lastTime; /**< The last time execute was called. */ std::string statusText; /**< The text to be printed in the status bar. */ /** * Destructor. */ virtual ~RoboCupCtrl(); /** * The function is called to initialize the module. */ virtual bool compile(); /** * The function is called in each simulation step. */ virtual void update(); /** * The callback function. * Called whenever the geometry at which this interface is registered collides with another geometry. * @param geom1 The geometry at which the interface has been registered * @param geom2 The other geometry */ virtual void collided(SimRobotCore2::Geometry& geom1, SimRobotCore2::Geometry& geom2); /** * Has to be called by derived class to start processes. */ void start(); /** * Has to be called by derived class to stop processes. */ void stop(); private: QList<SimRobot::Object*> views; /**< List of registered views */ };
[ "fab_v_cool@hotmail.com" ]
fab_v_cool@hotmail.com
e61b9563b8599da6a0a07ae6bf6d5cb59aa34afc
24d6004fa8058c3aa0256177c29db1b9df269904
/Converter/main.cpp
a8a9cea6d64832dfe6f350cfc706b6c61b83fad8
[]
no_license
MohabAyoub10/Numeral-System-Converter-
d07d0a465a0b308bde432f3bfa4a82c12ea528e1
95447a1b1d3452ce827f1c9ae24359836753f2a9
refs/heads/master
2022-12-05T17:10:44.134092
2020-08-31T21:28:06
2020-08-31T21:28:06
291,827,798
0
0
null
null
null
null
UTF-8
C++
false
false
1,692
cpp
#include <bits/stdc++.h> using namespace std; int main() { string no, out; double x = 0; int y = 0; bool f = 0; cout << "Enter the base of your input\n"; int inbase; cin >> inbase; cout << "Enter the number\n"; cin >> no; for (int i = 0; i < no.size(); i++) { if (no[i] == '.') { f = 1; for (int j = i + 1, k = -1; j < no.size(); j++, k--) { if (no[j] <= 9 + 48) x += (no[j] - 48) * pow(inbase, k); else x += (no[j] - 55) * pow(inbase, k); } for (int j = i - 1, k = 0; j >= 0; j--, k++) { if (no[j] <= 9 + 48) y += (no[j] - 48) * round(pow(inbase, k)); else y += (no[j] - 55) * round(pow(inbase, k)); } } else if (i == no.size() - 1 && f == 0) { for (int j = i, k = 0; j >= 0; j--, k++) { if (no[j] <= 9 + 48) y += (no[j] - 48) * round(pow(inbase, k)); else y += (no[j] - 55) * round(pow(inbase, k)); } } } cout << "Enter the base of your output\n"; int base; cin >> base; while (y > 0) { if (y % base <= 9) out += to_string(y % base); else { out += y % base + 55; } y /= base; } reverse(out.begin(), out.end()); if (f == 1) { out += '.'; double z = x; while (1) { if (int(z * base) <= 9) { out += to_string(int(z * base)); } else { out += int(z * base) + 55; } z = z * base - int(z * base); if (z * base - int(z * base) == 0) { out += to_string(int(z * base)); break; } } } cout << out; }
[ "noreply@github.com" ]
noreply@github.com
a698518751d94a15dfb6c0a41916b16177d50e88
e157a1df2688823f73457f9f3e690a06ac1342e1
/AwesomeEngine/Events/IEventManage.h
cf87486729e5224e358393907318fb6ebc95093f
[]
no_license
Team-Whatever/AwesomeEngine
83750e5a9ca5051b480974dd11e25e1e97c55cce
00756797dd565f26d059828a958e89a9f620702d
refs/heads/development
2020-07-23T13:34:33.867676
2020-04-21T13:38:34
2020-04-21T13:38:34
207,574,376
2
1
null
2019-10-01T15:42:49
2019-09-10T13:57:51
C++
UTF-8
C++
false
false
2,286
h
#pragma once #include "IEventData.h" namespace AwesomeEngine { class IEventManager { public: enum eConstants { kINFINITE = 0xffffffff }; // Registers a delegate function that will get called when the // event type is triggered. Returns true if successful, false if not. virtual bool VAddListener(const SimpleVoidFunctionDelegate& eventDelegate, const EventType& type) = 0; // Removes a delegate/event type pairing from the internal tables. // Returns false if the pairing was not found. virtual bool VRemoveListener(const SimpleVoidFunctionDelegate& eventDelegate, const EventType& type) = 0; // Fires off event NOW. This bypasses the queue entirely and // immediately calls all delegate functions registered for the event. virtual bool VTriggerEvent(const IEventDataPtr& pEvent) const = 0; // Fires off event. This uses the queue and will call the // delegate function on the next call to VTickVUpdate(), assuming there's enough time. virtual bool VQueueEvent(const IEventDataPtr& pEvent) = 0; // Finds the next-available instance of the named event type and // remove it from the processing queue.This may be done up to the // point that it is actively being processed ... e.g.: is safe to // happen during event processing itself. // If allOfType is true, then all events of that type are // cleared from the input queue. Returns true if the event was found // and removed, false otherwise virtual bool VAbortEvent(const EventType& type, bool allOfType = false) = 0; // Allows for processing of any queued messages, optionally // specify a processing time limit so that the event processing does // not take too long.Note the danger of using this artificial // limiter is that all messages may not in fact get processed. // returns true if all messages ready for processing were completed, false otherwise(e.g.timeout). virtual bool VTickVUpdate(unsigned long maxMillis = kINFINITE) = 0; // Getter for the main global event manager. This is the event // manager that is used by the majority of the engine, though you // are free to define your own as long as you instantiate it with // setAsGlobal set to false.It is not valid to have more than one global event manager. static IEventManager* Get(void); }; }
[ "cozyncoze@gmail.com" ]
cozyncoze@gmail.com
fb6e0efcbb17e4db6241bbd4309e83540f585ad4
4484824815fc13b6bdfaa722bb4c833ce73f586c
/CSVReader.h
2b3aac62ec9b6c97beb6d37b88fe426eb0e8b628
[]
no_license
prithviKantanAAU/RSMC-Sonification
1b4673a23ef384026f9ce6b963afc01bca10d7f0
7ffb792917ea3610bbcee68769b8d1a41812507d
refs/heads/master
2020-08-09T21:28:17.139062
2019-11-11T16:49:24
2019-11-11T16:49:24
214,178,710
0
0
null
null
null
null
UTF-8
C++
false
false
1,862
h
#pragma once #include <iostream> #include <fstream> #include <string> using namespace std; class CSVReader { public: CSVReader() {}; ~CSVReader() {}; void readMelCSV_Metadata(std::string path,string *songName, int *tonic, short *orderArray, int lineNum) { ifstream ip(path); if (!ip.is_open()) std::cout << "ERROR: File Open" << '\n'; string name; string tonicString; string order[24] = { "" }; if (lineNum == 2) { getline(ip, name, '\n'); name.erase(std::remove(name.begin(), name.end(), ','), name.end()); *songName = name; getline(ip, tonicString, '\n'); tonicString.erase(std::remove(tonicString.begin(), tonicString.end(), ','), tonicString.end()); *tonic = std::stoi(tonicString); for (int k = 0; k < 23; k++) { getline(ip, order[k], ','); orderArray[k] = std::stoi(order[k]); } getline(ip, order[23], '\n'); orderArray[23] = std::stoi(order[23]); } }; void readMelCSV_Custom(std::string path, int *melMatrix, int *scaleVar, int lineNum, int startLine) { ifstream ip(path); if (!ip.is_open()) std::cout << "ERROR: File Open" << '\n'; string scale; string codes[8] = { "" }; for (int j = 0; j < startLine; j++) { getline(ip, scale); } for (int i = startLine; i <= lineNum; i++) { getline(ip, codes[0], ','); getline(ip, codes[1], ','); getline(ip, codes[2], ','); getline(ip, codes[3], ','); getline(ip, codes[4], ','); getline(ip, codes[5], ','); getline(ip, codes[6], ','); if (lineNum >= 8) { getline(ip, codes[7], '\n'); } else { getline(ip, codes[7], ','); getline(ip, scale, '\n'); *scaleVar = std::stoi(scale); } } for (int i = 0; i < 8; i++) { melMatrix[i] = std::stoi(codes[i]); } } };
[ "noreply@github.com" ]
noreply@github.com
dee94095e77a8b378977445102091f7535f660d4
cc194107ba23263291ae3bb7af78cb63292ad4d2
/Source/BullCowGame/BullCowCartridge.cpp
a2adfa40e52528be390a47514bf3316f0f1cbca3
[]
no_license
SgtFlex/BullCowGame
9767c8b43ff1c6b070f44b705b3849d29c56a44a
c9cdeeb530151f3ff9a4c6a72f0611570c667fc3
refs/heads/master
2022-12-29T14:16:43.964459
2020-10-12T22:03:03
2020-10-12T22:03:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,408
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "BullCowCartridge.h" #include "Misc/FileHelper.h" #include "Misc/Paths.h" //#incldue "Math/UnrealMathUtility.h" //Already included in CoreMinimal.h from the header file void UBullCowCartridge::BeginPlay() // When the game starts { Super::BeginPlay(); const FString WordListPath = FPaths::ProjectContentDir() / TEXT("WordLists/HiddenWordList.txt"); FFileHelper::LoadFileToStringArrayWithPredicate(Isograms, *WordListPath, [](const FString& Word) { return Word.Len() > 4 && Word.Len() < 8 && IsIsogram(Word); }); SetupGame(); //Setting up Game } void UBullCowCartridge::OnInput(const FString& Input) // When the player hits enter { if (bGameOver) { ClearScreen(); SetupGame(); } else //check playerguess { ProcessGuess(Input); } } void UBullCowCartridge::SetupGame() { HiddenWord = Isograms[FMath::RandRange(0,Isograms.Num() - 1)]; PlayerLives = HiddenWord.Len() * 2; GuessHistory.Empty(); bGameOver = false; PrintLine(TEXT("Welcome! Press 'Tab' to interact."), HiddenWord.Len()); PrintLine(TEXT("Guess the %i letter isogram."), HiddenWord.Len()); PrintLine(TEXT("Bulls = Correct letter in the correct spot")); PrintLine(TEXT("Cows = Correct letter in the wrong spot.")); PrintLine(TEXT("You have %i Lives."), PlayerLives); PrintLine(TEXT("Please input a guess and press 'Enter.'")); PrintLine(TEXT("Type 'Words' to see what you have entered.")); // PrintLine(TEXT("The HiddenWord is: %s"), *HiddenWord); IsIsogram(HiddenWord); } void UBullCowCartridge::EndGame() { bGameOver = true; PrintLine(TEXT("Press 'Enter' to play again.")); } void UBullCowCartridge::ProcessGuess(const FString& Guess) { //Check if isogram //Prompt to GuessAgain //Check if correct # of letters //Prompt to GuessAgain //Remove Life //Show Lives left //Check if Lives > 0 //If Yes, GuessAgain //Else, Prompt to PlayAgain //If Yes, Restart //If No, Exit if (Guess=="Words") { PrintHistory(); return; } else if (Guess==HiddenWord) { PrintLine(TEXT("You got it right!")); EndGame(); return; } else if (Guess.Len()!=HiddenWord.Len()) { PrintLine(TEXT("Wrong length! The isogram is %i letters"), HiddenWord.Len()); return; } else if (!IsIsogram(Guess)) { PrintLine(TEXT("No repeating letters")); return; } PrintLine(TEXT("Wrong, %i lives left"), --PlayerLives); if (PlayerLives <= 0) { ClearScreen(); PrintLine(TEXT("No Lives left. Game Over.")); PrintLine(TEXT("The hidden isogram was: %s"), *HiddenWord); EndGame(); return; } FBullCowCount Score = GetBullCows(Guess); PrintLine(TEXT("You have %i Bulls and %i Cows"), Score.Bulls, Score.Cows); GuessHistory.Emplace(Score); } bool UBullCowCartridge::IsIsogram(const FString& Word) { //Nested for loop checking each letter forwards for (int32 Index = 0; Index < Word.Len(); Index++) { for (int32 Comparison = Index + 1; Comparison < Word.Len(); Comparison++) { if (Word[Comparison] == Word[Index]) { return false; } } } return true; } FBullCowCount UBullCowCartridge::GetBullCows(const FString& Guess) const { FBullCowCount Count; Count.CheckWord = Guess; for (int32 GuessIndex = 0; GuessIndex < Guess.Len(); GuessIndex++) { if (Guess[GuessIndex] == HiddenWord[GuessIndex]) { Count.Bulls++; continue; } for (int32 HiddenIndex = 0; HiddenIndex < HiddenWord.Len(); HiddenIndex++) { if (Guess[GuessIndex] == HiddenWord[HiddenIndex]) { Count.Cows++; break; //Because it's an isogram, there's no reason to continue once we find a matching letter } } } return Count; } void UBullCowCartridge::PrintHistory() const { for (int32 Index = 0; Index < GuessHistory.Num(); Index++) { PrintLine(TEXT("Word: %s, %i Bulls, %i Cows"), *GuessHistory[Index].CheckWord, GuessHistory[Index].Bulls, GuessHistory[Index].Cows); } }
[ "sgtflexxx@gmail.com" ]
sgtflexxx@gmail.com
22317a35108db87b3afc68d460d4b91277222a13
c3d4f9b8754632e5fe31ce4fae3b31c0b75dad00
/Tech/벡터 - 지우기.cpp
5a4e100b05e4ce69fab6e207ce7cdf2a8d5764df
[]
no_license
jeongminccc/algo
f42b21e06fb97ae7711759ee05f5d5e000ba8f8c
d74461a0b523adb2414d5d8c83e5b585bd00dcc7
refs/heads/master
2023-04-23T06:06:57.143874
2021-05-17T12:39:52
2021-05-17T12:39:52
279,296,585
0
0
null
null
null
null
UTF-8
C++
false
false
571
cpp
// ConsoleApplication27.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다. // #include "pch.h" #include <iostream> #include <vector> using namespace std; int main() { int n, m ,pos=0; vector<int> a; cin >> n >> m; for (int i = 0; i < n; i++) { a.push_back(i + 1); cout << a[i]; }cout << "<"; while (1) { pos = (pos + m - 1) % a.size(); if (a.size() > 1) { cout << a[pos] << ", "; } else { cout << a[pos] << ">"; break; } a.erase(a.begin() + pos); } return 0; }
[ "shinerbot@naver.com" ]
shinerbot@naver.com
a7ca616b132ad12c07c0870f768daa94cb882517
a3ec7ce8ea7d973645a514b1b61870ae8fc20d81
/LeetCode/297.cc
bd97f0365ff478466cfd13f17eed3d7c436bf2f6
[]
no_license
userr2232/PC
226ab07e3f2c341cbb087eecc2c8373fff1b340f
528314b608f67ff8d321ef90437b366f031e5445
refs/heads/master
2022-05-29T09:13:54.188308
2022-05-25T23:24:48
2022-05-25T23:24:48
130,185,439
1
0
null
null
null
null
UTF-8
C++
false
false
3,316
cc
class Codec { public: string serialized; Codec() {serialized = "";} void BFS(TreeNode* current) { if(!current) { serialized = "null"; return; } queue<pair<TreeNode*,int>> q; set<int> levels; map<int, string> level_string; q.push({current,0}); cout << current->left << " " << current->right << endl; while(!q.empty()) { auto [current_node, current_level] = q.front(); q.pop(); if(current_node) { levels.insert(current_level); if(!level_string.count(current_level)) level_string[current_level] = ""; level_string[current_level] += to_string(current_node->val) + ","; q.push({current_node->left, current_level+1}); q.push({current_node->right, current_level+1}); } else { if(!level_string.count(current_level)) level_string[current_level] = ""; level_string[current_level] += "null,"; continue; } } for(auto [level, ser_string] : level_string) { if(levels.count(level)) { serialized += ser_string; } } serialized = serialized.substr(0, serialized.length()-1); } // Encodes a tree to a single string. string serialize(TreeNode* root) { BFS(root); return serialized; } queue<string> split(string s, char delimiter = ',') { cout << "string: " << s << endl; string token; istringstream iss(s); queue<string> results; while(getline(iss, token, delimiter)) { // cout << "token: " << token << endl; results.push(token); } return results; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { auto ser = split(data); queue<TreeNode*> prevs; bool left = true; TreeNode* root{0}; while(!ser.empty()) { // cout << "entra" << endl; auto current = ser.front(); // cout << "current: " << current << endl; ser.pop(); if(current != "null") { TreeNode* new_node = new TreeNode{stoi(current),nullptr,nullptr}; if(!root) root = new_node; if(!prevs.empty()) { if(left) { auto prev = prevs.front(); prev->left = new_node; left = false; } else { auto prev = prevs.front(); prevs.pop(); prev->right = new_node; left = true; } } prevs.push(new_node); } else { if(left) left = false; else { left = true; if(!prevs.empty()) prevs.pop(); } } // cout << "sale" << endl; } // cout << root->left->val << " " << root->right->val << endl; return root; } };
[ "reynaldo.rz.26@gmail.com" ]
reynaldo.rz.26@gmail.com
dfe1b6729ee9182c2412511860002920c14e2956
9f81d77e028503dcbb6d7d4c0c302391b8fdd50c
/google/cloud/migrationcenter/v1/internal/migration_center_option_defaults.cc
a44545bcac8e312c6ce1c4287ea42e8069852861
[ "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,399
cc
// Copyright 2023 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/migrationcenter/v1/migrationcenter.proto #include "google/cloud/migrationcenter/v1/internal/migration_center_option_defaults.h" #include "google/cloud/migrationcenter/v1/migration_center_connection.h" #include "google/cloud/migrationcenter/v1/migration_center_options.h" #include "google/cloud/internal/populate_common_options.h" #include "google/cloud/internal/populate_grpc_options.h" #include <memory> namespace google { namespace cloud { namespace migrationcenter_v1_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace { auto constexpr kBackoffScaling = 2.0; } // namespace Options MigrationCenterDefaultOptions(Options options) { options = google::cloud::internal::PopulateCommonOptions( std::move(options), "GOOGLE_CLOUD_CPP_MIGRATION_CENTER_ENDPOINT", "", "GOOGLE_CLOUD_CPP_MIGRATION_CENTER_AUTHORITY", "migrationcenter.googleapis.com"); options = google::cloud::internal::PopulateGrpcOptions(std::move(options), ""); if (!options.has<migrationcenter_v1::MigrationCenterRetryPolicyOption>()) { options.set<migrationcenter_v1::MigrationCenterRetryPolicyOption>( migrationcenter_v1::MigrationCenterLimitedTimeRetryPolicy( std::chrono::minutes(30)) .clone()); } if (!options.has<migrationcenter_v1::MigrationCenterBackoffPolicyOption>()) { options.set<migrationcenter_v1::MigrationCenterBackoffPolicyOption>( ExponentialBackoffPolicy( std::chrono::seconds(0), std::chrono::seconds(1), std::chrono::minutes(5), kBackoffScaling, kBackoffScaling) .clone()); } if (!options.has<migrationcenter_v1::MigrationCenterPollingPolicyOption>()) { options.set<migrationcenter_v1::MigrationCenterPollingPolicyOption>( GenericPollingPolicy< migrationcenter_v1::MigrationCenterRetryPolicyOption::Type, migrationcenter_v1::MigrationCenterBackoffPolicyOption::Type>( options.get<migrationcenter_v1::MigrationCenterRetryPolicyOption>() ->clone(), ExponentialBackoffPolicy(std::chrono::seconds(1), std::chrono::minutes(5), kBackoffScaling) .clone()) .clone()); } if (!options.has<migrationcenter_v1:: MigrationCenterConnectionIdempotencyPolicyOption>()) { options.set< migrationcenter_v1::MigrationCenterConnectionIdempotencyPolicyOption>( migrationcenter_v1:: MakeDefaultMigrationCenterConnectionIdempotencyPolicy()); } return options; } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace migrationcenter_v1_internal } // namespace cloud } // namespace google
[ "noreply@github.com" ]
noreply@github.com
90595a4b9f208f8cf9a336414eac9d17582cb870
24653c0a8be19e46eb95451de1d961ffbcc01341
/software/src/master/src/kernel/Vca_IPeek.h
0772ba7e0d499f37110390cec160a6e36b620191
[ "BSD-3-Clause" ]
permissive
VisionAerie/vision
150e5bfa7eb16116b1e5b4bdb1bb8cee888fbfe5
e40c39e3abc49b0e2c9623204c54b900c4333f29
refs/heads/master
2021-01-19T09:23:34.429209
2019-01-30T17:10:59
2019-01-30T17:10:59
82,104,368
2
1
BSD-3-Clause
2019-01-30T17:11:00
2017-02-15T20:41:27
C++
UTF-8
C++
false
false
1,841
h
#ifndef Vca_IPeek_Interface #define Vca_IPeek_Interface #ifndef Vca_IPeek #define Vca_IPeek extern #endif /************************ ***** Components ***** ************************/ #include "IVUnknown.h" /************************** ***** Declarations ***** **************************/ #include "Vca_IRequest.h" VINTERFACE_TEMPLATE_INSTANTIATIONS (Vca,IPeek) /************************* ***** Definitions ***** *************************/ namespace Vca { /** * @class IPeek * * Interface used to inspect and subscribe to the properties of an object. Implemented by VRolePlayer. */ VcaINTERFACE (IPeek, IVUnknown) /** * Obtain the value of an object property. * * @param p1 The name of the property to examine. * @param p2 The IClient whose specialization will receive the current value of the * requested property. * @param p3 An optional receiver an IRequest ticket. If the property identified by * parameter 1 supports update tracking and this parameter's value is non- * null, a ticket for an update tracking subscription will be returned via * this parameter and the IClient identified by parameter 2 will receive * an 'OnData' message for each subsequent change to the property's value. * If the requested property does not support update tracking and this * parameter is specified, a null will be passed as the value the tracking * returned via this receiver to indicate that a tracking subscription was * not created. */ VINTERFACE_METHOD_3 (GetValue,VString const&,IClient*,IVReceiver<IRequest*>*); VINTERFACE_END VINTERFACE_ROLE (IPeek, IVUnknown) VINTERFACE_ROLE_3 (GetValue,VString const&,IClient*,IVReceiver<IRequest*>*); VINTERFACE_ROLE_END } #endif
[ "mcaruso@alum.mit.edu" ]
mcaruso@alum.mit.edu
8ed3df40a6acd50ecd4c3d15752c85abfa2c9cd2
7a478ef9efd0c3b4424c5f2f3a17fede7bb95254
/Libraries/libil2cpp/include/os/Path.h
1983b6907c3378f077622510e3fc6c433a080887
[]
no_license
Marcurion/test2
dfe1bfd3cc50fa24a76cd88f74b52c2c8f9096e5
37425035a4db1084b4b03154b16d6cac90c2e31b
refs/heads/master
2021-01-10T17:01:21.212134
2015-11-26T10:32:37
2015-11-26T10:32:37
46,919,935
0
0
null
null
null
null
UTF-8
C++
false
false
169
h
#pragma once #include <string> #include <stdint.h> namespace il2cpp { namespace os { class Path { public: static std::string GetTempPath(); }; } }
[ "marcurion@googlemail.com" ]
marcurion@googlemail.com
94bc84a78e6abf6f8ffb00b265b9b79441afbd96
4ee1f1eb373ce363398d503db299c329545fa6fb
/Include/DWLDialogoAbrir.cpp
3eab7fff995644cad580f1f6b87f8280f31ec9cf
[]
no_license
devildrey33/DWL
540dcc38bac31789e589bbeb6a4a31f6a4a69a50
eaadbe908190daa8587a9487c636be8e4e6c2b49
refs/heads/master
2021-01-19T04:05:20.769838
2020-10-29T09:18:59
2020-10-29T09:18:59
60,091,313
0
1
null
null
null
null
ISO-8859-1
C++
false
false
4,358
cpp
/*! \file DWLDialogoAbrir.cpp \brief Archivo que contiene una clase para mostrar el dialogo abrir del sistema. \author devildrey33 \date Creado el [10/06/2004], ultima modificación el [05/10/2010] \remarks Archivo creado por devildrey33 para http://www.devildrey33.es \n Este archivo es parte de la DWL (DReY Windows Lib) y se distribuye bajo la licencia GPL, para mas información consulta estos enlaces : \n - http://www.gnu.org/licenses/gpl.html (Ingles, documento oficial) \n - http://www.viti.es/gnu/licenses/gpl.html (Castellano, traduccion no oficial) \n - http://www.softcatala.cat/wiki/GPL3 (Catalá, traduccion no oficial) \n */ #ifndef DWL_DIALOGOABRIR_CPP #define DWL_DIALOGOABRIR_CPP #include "DWLDialogoAbrir.h" #include <commdlg.h> #include <shlobj.h> // Libreria para los objetos Shell //! Espacio de nombres DWL namespace DWL { //! Espacio de nombres Ventanas namespace Ventanas { //! Función que muestra el diálogo para abrir archivos. /*! Función que muestra el diálogo para abrir archivos según los parametros especificados. \fn UINT MostrarAbrir(const TCHAR *PathSh, const TCHAR *Filtro, const TCHAR *Titulo, const bool MultiSeleccion, HWND hWndPadre) { \param[in] PathSh : Ruta inicial desde donde empezara el dialogo abrir \param[in] Filtro : Filtro de archivos \param[in] Titulo : Titulo del dialogo \param[in] MultiSeleccion : Habilitar multiselección \param[in] hWndPadre : Ventana padre, puede ser NULL. Si especificamos una ventana padre, esta se desactivara mientras el dialogo este activo. \return Devuelve el numero de archivos seleccionados. \remarks Titulo debera estar formateado de la siguiente forma :\n \code Todos los archivos\0*.*\0\0 \endcode Observad que primero hay un string con el nombre del filtro, luego el tipo de filtro, y por ultimo termina con un doble caracter <b>\\0</b>. \n\n Si por ejemplo queremos tener un filtro para documentos de texto debemos construirlo de una forma similar a este : \n \code Todos los archivos\0*.*\0Documentos de texto\0*.doc;*.txt;*.rtf\0\0 \endcode Observad que esta vez hemos añadido 3 tipos de archivo para el filtro Documentos de texto, esos tipos de archivo deben estar separados por el caracter <b>;</b> */ UINT DWLDialogoAbrir::MostrarAbrir(const TCHAR *PathSh, const TCHAR *Filtro, const TCHAR *Titulo, const bool MultiSeleccion, HWND hWndPadre) { OPENFILENAME ofn; TCHAR szFile[4096]; bool Multi = false; TCHAR Path[512]; TCHAR Archi[512]; TCHAR UltimoDir[MAX_PATH +1]; DWL::DWLString Tmp; int N = 0; int i; ZeroMemory(&ofn, sizeof(ofn)); ofn.lpstrCustomFilter = NULL; ofn.nFilterIndex = 1; ofn.lpstrFile = szFile; ofn.nMaxFile = 4096; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 4096; ofn.lpstrInitialDir = TEXT(".\0"); ofn.lpstrTitle = Titulo; ofn.lpstrFilter = Filtro; ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hWndPadre; if (MultiSeleccion == true) ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT; else ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; _Archivos.clear(); for (i = 0; i < 4096; i++) szFile[i] = 0; szFile[0] = '\0'; // Obtengo el directorio actual para luego volverlo a asignar GetCurrentDirectory(MAX_PATH +1, UltimoDir); SetCurrentDirectory(PathSh); if (GetOpenFileName(&ofn)) { DWLStrCopy(Path, 512, szFile); i = static_cast<int>(DWLStrLen(Path)); while (szFile[i] != 0 || szFile[i+ 1] != 0) { i++; if (szFile[i] != 0) { Archi[N] = szFile[i]; N++; } else { Archi[N] = 0; N = 0; Multi = true; Tmp = Path; if (Tmp[Tmp.Tam() -1] != '\\') { Tmp += '\\'; } Tmp += Archi; _Archivos.push_back(Tmp); } } if (Multi == false) { Tmp = szFile; _Archivos.push_back(Tmp); } } SetCurrentDirectory(UltimoDir); return _Archivos.size(); }; } } #endif // DWL_DIALOGOSCOMUNES_CPP
[ "devildrey33@hotmail.com" ]
devildrey33@hotmail.com
325abe48657df70c56f0e88cd7254609c3e3180c
12f2e07421fed03f81a4aae965d325bba7215a8b
/cpp_d09_2019/Character.cpp
fb80a8e002c0a7d0064b5639ff93cc120cb929f0
[]
no_license
valtonngara/Cpp_Pool
c0bafc1c302688092de548aba8a4a8c3eafd8491
f31b19a16fd68400e09fab92c318a05cc7cf6418
refs/heads/master
2023-07-30T05:13:02.811233
2021-09-19T16:50:39
2021-09-19T16:50:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,363
cpp
// // EPITECH PROJECT, 2020 // EPITECH 2020 // File description: // main character // #include "Character.hpp" #include "Warrior.hpp" Character::~Character() { } Character::Character(const std::string& name, int lvl) : name(name) { const char *create = " Created"; this->Range = CLOSE; this->lvl = lvl; this->Pv = 100; this->Energy = 100; this->Intelligence = 5; this->Spirit = 5; this->Agility = 5; this->Strength = 5; this->Stamina = 5; std::cout << this->name << create << std::endl; } const std::string &Character::getName() const { return (this->name); } int Character::getPv() const { return (this->Pv); } int Character::getPower() const { return (this->Energy); } int Character::getLvl() const { return (this->lvl); } int Character::RangeAttack() { const char *launche = " tosses a stone"; const char *oop = " out of power"; int ten = 10; int five = 5; int result = five + this->Strength; if (this->Energy >= ten) { this->Energy = this->Energy - ten; std::cout << this->name << launche << std::endl; return (result); } else { std::cout << this->name << oop << std::endl; return (0); } } void Character::TakeDamage(int _damage) { this->Pv = this->Pv - _damage; const char *ooc = " out of combat"; const char *take = " takes "; const char *damage = " damage"; if (this->Pv <= 0) { this->Energy = 0; std::cout << this->name << ooc << std::endl; } else { std::cout << this->name << take << _damage << damage << std::endl; } } int Character::CloseAttack() { const char *strike = " strikes with a wooden stick"; const char *oop = " out of power"; int ten = 10; int result = ten + this->Strength; if (this->Energy >= ten) { this->Energy = this->Energy - ten; std::cout << this->name << strike << std::endl; return (result); } else { std::cout << this->name << oop << std::endl; return (0); } } void Character::RestorePower() { this->Energy = 100; const char *eat = " eats"; std::cout << this->name << eat << std::endl; } void Character::Heal() { this->Pv = this->Pv + 50; const char *potion = " takes a potion"; if (this->Pv > 100) { this->Pv = 100; } std::cout << this->name << potion << std::endl; }
[ "valton.gara@gmail.com" ]
valton.gara@gmail.com
85a03430c80d988f880d0c9c686d61f5c24fa96a
266a4c550a561c810ae376a4477d61bc81bb4f40
/Set_2/PSHOT.cpp
1d4299f054415a74499bf4f1ac881e599956665b
[]
no_license
Rajeev0651/Codechef
423687213dc09332d1b5afcd80b791f46fc4359f
d5cfb05340ba3b91f8868215e348f43d7847a5bb
refs/heads/master
2023-03-30T15:06:41.151843
2021-04-05T16:55:26
2021-04-05T16:55:26
258,600,370
0
0
null
null
null
null
UTF-8
C++
false
false
859
cpp
#include <bits/stdc++.h> using namespace std; int main() { int T; cin >> T; while (T--) { int N, A = 0, B = 0; cin >> N; char S[N * 2]; for (int i = 0; i < N * 2; i++) { cin >> S[i]; } int aleft = N, bleft = N, ans = N * 2; for (int i = 0; i < N * 2; i++) { if (i % 2 == 0) { aleft--; A += S[i] - 48; if ((B - A) > aleft) { ans = i + 1; break; } if ((A - B) > bleft) { ans = i + 1; break; } } else { bleft--; B += S[i] - 48; if ((A - B) > bleft) { ans = i + 1; break; } if ((B - A) > aleft) { ans = i + 1; break; } } } cout << ans << "\n"; } return 0; }
[ "singhrajiv0651@gmail.com" ]
singhrajiv0651@gmail.com
8414f6e658765d52ddb32a9f9e12efe18b36d53c
e5fa99b5372374f4eb060a307f17d613cbf3c4ad
/include/physics/collisions/Shapes/OgreBulletCollisionsCylinderShape.h
ebeb62897258b32612ff3e3cbe51238c1ab061ce
[]
no_license
Dima-Meln/ORSE
648d185164791c755a9c8e5556d60104f9fffd5b
7f96fb3f8a8e5a15adc714825e08ef1a0071564a
refs/heads/master
2020-08-10T18:55:34.097355
2012-09-18T04:59:20
2012-09-18T04:59:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,036
h
/*************************************************************************** This source file is part of OGREBULLET (Object-oriented Graphics Rendering Engine Bullet Wrapper) For the latest info, see http://www.ogre3d.org/phpBB2addons/viewforum.php?f=10 Copyright (c) 2007 tuan.kuranes@gmail.com (Use it Freely, even Statically, but have to contribute any changes) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef _OGREBULLETCOLLISIONS_CylinderShape_H #define _OGREBULLETCOLLISIONS_CylinderShape_H #include "OgreBulletCollisionsPreRequisites.h" #include "OgreBulletCollisionsShape.h" namespace OgreBulletCollisions { // ------------------------------------------------------------------------- // basic CylinderShape class CylinderCollisionShape : public CollisionShape { public: CylinderCollisionShape(const Ogre::Vector3& halfExtents, const Ogre::Vector3& axe); virtual ~CylinderCollisionShape(); }; } #endif //_OGREBULLETCOLLISIONS_CylinderShape_H
[ "dimamelnichuk11@gmail.com" ]
dimamelnichuk11@gmail.com
4b86f76d0f8376da1adb821b7b0f9de654cf175a
1d9b1b78887bdff6dd5342807c4ee20f504a2a75
/lib/libcxx/include/__functional/operations.h
1c73c999db918e1e0e4336cf914ac5547150a608
[ "NCSA", "LLVM-exception", "MIT", "Apache-2.0", "LicenseRef-scancode-other-permissive" ]
permissive
mikdusan/zig
86831722d86f518d1734ee5a1ca89d3ffe9555e8
b2ffe113d3fd2835b25ddf2de1cc8dd49f5de722
refs/heads/master
2023-08-31T21:29:04.425401
2022-11-13T15:43:29
2022-11-13T15:43:29
173,955,807
1
0
MIT
2021-11-02T03:19:36
2019-03-05T13:52:53
Zig
UTF-8
C++
false
false
17,095
h
// -*- C++ -*- //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef _LIBCPP___FUNCTIONAL_OPERATIONS_H #define _LIBCPP___FUNCTIONAL_OPERATIONS_H #include <__config> #include <__functional/binary_function.h> #include <__functional/unary_function.h> #include <__utility/forward.h> #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header #endif _LIBCPP_BEGIN_NAMESPACE_STD // Arithmetic operations #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS plus : __binary_function<_Tp, _Tp, _Tp> { typedef _Tp __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY _Tp operator()(const _Tp& __x, const _Tp& __y) const {return __x + __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS plus<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS minus : __binary_function<_Tp, _Tp, _Tp> { typedef _Tp __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY _Tp operator()(const _Tp& __x, const _Tp& __y) const {return __x - __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS minus<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) - _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) - _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) - _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS multiplies : __binary_function<_Tp, _Tp, _Tp> { typedef _Tp __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY _Tp operator()(const _Tp& __x, const _Tp& __y) const {return __x * __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS multiplies<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) * _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) * _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) * _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS divides : __binary_function<_Tp, _Tp, _Tp> { typedef _Tp __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY _Tp operator()(const _Tp& __x, const _Tp& __y) const {return __x / __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS divides<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) / _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) / _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) / _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS modulus : __binary_function<_Tp, _Tp, _Tp> { typedef _Tp __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY _Tp operator()(const _Tp& __x, const _Tp& __y) const {return __x % __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS modulus<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) % _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) % _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) % _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS negate : __unary_function<_Tp, _Tp> { typedef _Tp __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY _Tp operator()(const _Tp& __x) const {return -__x;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS negate<void> { template <class _Tp> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_Tp&& __x) const noexcept(noexcept(- _VSTD::forward<_Tp>(__x))) -> decltype( - _VSTD::forward<_Tp>(__x)) { return - _VSTD::forward<_Tp>(__x); } typedef void is_transparent; }; #endif // Bitwise operations #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS bit_and : __binary_function<_Tp, _Tp, _Tp> { typedef _Tp __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY _Tp operator()(const _Tp& __x, const _Tp& __y) const {return __x & __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS bit_and<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) & _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) & _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) & _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> struct _LIBCPP_TEMPLATE_VIS bit_not : __unary_function<_Tp, _Tp> { _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY _Tp operator()(const _Tp& __x) const {return ~__x;} }; template <> struct _LIBCPP_TEMPLATE_VIS bit_not<void> { template <class _Tp> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_Tp&& __x) const noexcept(noexcept(~_VSTD::forward<_Tp>(__x))) -> decltype( ~_VSTD::forward<_Tp>(__x)) { return ~_VSTD::forward<_Tp>(__x); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS bit_or : __binary_function<_Tp, _Tp, _Tp> { typedef _Tp __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY _Tp operator()(const _Tp& __x, const _Tp& __y) const {return __x | __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS bit_or<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) | _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) | _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) | _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS bit_xor : __binary_function<_Tp, _Tp, _Tp> { typedef _Tp __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY _Tp operator()(const _Tp& __x, const _Tp& __y) const {return __x ^ __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS bit_xor<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) ^ _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) ^ _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) ^ _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif // Comparison operations #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS equal_to : __binary_function<_Tp, _Tp, bool> { typedef bool __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY bool operator()(const _Tp& __x, const _Tp& __y) const {return __x == __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS equal_to<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) == _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) == _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) == _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS not_equal_to : __binary_function<_Tp, _Tp, bool> { typedef bool __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY bool operator()(const _Tp& __x, const _Tp& __y) const {return __x != __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS not_equal_to<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) != _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) != _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) != _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS less : __binary_function<_Tp, _Tp, bool> { typedef bool __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY bool operator()(const _Tp& __x, const _Tp& __y) const {return __x < __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS less<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) < _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) < _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) < _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS less_equal : __binary_function<_Tp, _Tp, bool> { typedef bool __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY bool operator()(const _Tp& __x, const _Tp& __y) const {return __x <= __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS less_equal<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) <= _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) <= _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) <= _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS greater_equal : __binary_function<_Tp, _Tp, bool> { typedef bool __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY bool operator()(const _Tp& __x, const _Tp& __y) const {return __x >= __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS greater_equal<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) >= _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) >= _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) >= _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS greater : __binary_function<_Tp, _Tp, bool> { typedef bool __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY bool operator()(const _Tp& __x, const _Tp& __y) const {return __x > __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS greater<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) > _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) > _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) > _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif // Logical operations #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS logical_and : __binary_function<_Tp, _Tp, bool> { typedef bool __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY bool operator()(const _Tp& __x, const _Tp& __y) const {return __x && __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS logical_and<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) && _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) && _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) && _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS logical_not : __unary_function<_Tp, bool> { typedef bool __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY bool operator()(const _Tp& __x) const {return !__x;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS logical_not<void> { template <class _Tp> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_Tp&& __x) const noexcept(noexcept(!_VSTD::forward<_Tp>(__x))) -> decltype( !_VSTD::forward<_Tp>(__x)) { return !_VSTD::forward<_Tp>(__x); } typedef void is_transparent; }; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS logical_or : __binary_function<_Tp, _Tp, bool> { typedef bool __result_type; // used by valarray _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY bool operator()(const _Tp& __x, const _Tp& __y) const {return __x || __y;} }; #if _LIBCPP_STD_VER > 11 template <> struct _LIBCPP_TEMPLATE_VIS logical_or<void> { template <class _T1, class _T2> _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY auto operator()(_T1&& __t, _T2&& __u) const noexcept(noexcept(_VSTD::forward<_T1>(__t) || _VSTD::forward<_T2>(__u))) -> decltype( _VSTD::forward<_T1>(__t) || _VSTD::forward<_T2>(__u)) { return _VSTD::forward<_T1>(__t) || _VSTD::forward<_T2>(__u); } typedef void is_transparent; }; #endif _LIBCPP_END_NAMESPACE_STD #endif // _LIBCPP___FUNCTIONAL_OPERATIONS_H
[ "andrew@ziglang.org" ]
andrew@ziglang.org
fb70e88c61fff7f21a313f35ef8b166fb2269b0d
0c029027d702488d7938139b4654d637a558739c
/experiments_km/myStiefelBrockettTest.cpp
532787e7f1dba9d66c9fb68bb97bafdc808a9532
[]
no_license
krrish94/roptlib-experiments
6e13b74f11a8968b8c7b531275f3bf736263684a
e39c9d338cd13e961f99ca642053fb2041faaaa8
refs/heads/master
2020-05-25T20:08:09.516221
2017-03-18T04:38:32
2017-03-18T04:38:32
84,963,010
0
0
null
null
null
null
UTF-8
C++
false
false
1,382
cpp
/* Test file for my version of optimizing the Brockett cost function over the Stiefel manifold. */ // Problem related classes #include "Problems/Problem.h" #include "experiments_km/myStiefelBrockett.h" // Manifold related classes #include "Manifolds/Manifold.h" #include "Manifolds/Stiefel/StieVector.h" #include "Manifolds/Stiefel/StieVariable.h" #include "Manifolds/Stiefel/Stiefel.h" // Solver we intend to use (RTRNewton) #include "Solvers/RTRNewton.h" // File containing global definitions #include "Others/def.h" // Random number generator #include "Others/randgen.h" // Standard C++ headers #include <iostream> #include <ctime> // Using the Eigen library to represent matrices using namespace ROPTLIB; // Main function int main() { // Seed the random number generator, for repeatability genrandseed(0); // Size of the Stiefel manifold int n = 12, p = 8; // Generate matrices for the problem double *B = new double[n*n + p]; double *D = B + n * n; // Initial guess StieVariable X(n, p); X.RandInManifold(); // Define the Stiefel Manifold Stiefel Domain(n, p); // Define the problem (optimizing the Brockett cost function) MyStiefelBrockett Problem(B, D, n, p); // Set the domain of the problem to the Stiefel manifold Problem.SetDomain(&Domain); // Output the parameters of the manifold of the domain Domain.CheckParams(); return 0; }
[ "krrish94@gmail.com" ]
krrish94@gmail.com
73f04590b2a50ad5c3de04e6d04ae4730793bdc4
bceeed02a31d3284128bf18871d17ce397b2911b
/369A.cpp
b09ad66dfaf4975946972deb6b55f63b3539d21e
[]
no_license
anubhab91/codeforces
7201cc050744ba6163b5b9e0b4fd732fdc2e89ba
5b38422b282cb7378ea78b1f686e49e6d93e311c
refs/heads/master
2021-01-22T20:08:21.564523
2014-07-28T01:33:53
2014-07-28T01:33:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
788
cpp
#include<iostream> #include<vector> #include<string.h> #include<stdio.h> #include<map> #include<math.h> #include<algorithm> #define LL long long #define P(N) printf("%d\n",N); #define S(N) scanf("%d",&N); #define SL(N) scanf("%d",&N); #define pb push_back #define mp make_pair using namespace std; main() { int n,m,k,x,i; cin>>n>>m>>k; int ans=0; for(i=1;i<=n;i++) { cin>>x; if(x==1) { if(m>0) { m--; } else ans++; } else { if(k>0) { k--; } else if(m>0) m--; else ans++; } } cout<<ans<<endl; return 0; }
[ "sanjeev1779@ubuntu.ubuntu-domain" ]
sanjeev1779@ubuntu.ubuntu-domain
de0bc6f48d6f9ba8f0c3594821470af1a9ea14ed
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/src/core/scoring/methods/EnvSmoothEnergy.cc
2a2ce552fa05a9831103bec92c50ebff9a3a31cf
[]
no_license
MedicaicloudLink/Rosetta
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
01affdf77abb773ed375b83cdbbf58439edd8719
refs/heads/master
2020-12-07T17:52:01.350906
2020-01-10T08:24:09
2020-01-10T08:24:09
232,757,729
2
6
null
null
null
null
UTF-8
C++
false
false
16,274
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file core/scoring/methods/EnvSmoothEnergy.cc /// @brief Statistically derived rotamer pair potential class implementation /// @author Phil Bradley /// @author Andrew Leaver-Fay // Unit headers #include <core/scoring/methods/EnvSmoothEnergy.hh> #include <core/scoring/methods/EnvSmoothEnergyCreator.hh> // Package headers #include <basic/database/open.hh> #include <core/chemical/AA.hh> #include <core/chemical/VariantType.hh> #include <core/conformation/Atom.hh> #include <core/id/AtomID.hh> #include <core/scoring/Energies.hh> #include <core/scoring/methods/EnergyMethodOptions.hh> #include <core/scoring/TwelveANeighborGraph.hh> #include <core/scoring/ContextGraphTypes.hh> // symmetry #include <core/pose/symmetry/util.hh> #include <core/conformation/symmetry/SymmetricConformation.hh> #include <core/conformation/symmetry/SymmetryInfo.hh> // Project headers #include <core/pose/Pose.hh> #include <core/conformation/Residue.hh> // Utility headers #include <utility/io/izstream.hh> #include <utility/vector1.hh> #include <utility/vector0.hh> namespace core { namespace scoring { namespace methods { /// @details This must return a fresh instance of the EnvSmoothEnergy class, /// never an instance already in use methods::EnergyMethodOP EnvSmoothEnergyCreator::create_energy_method( methods::EnergyMethodOptions const & options ) const { return utility::pointer::make_shared< EnvSmoothEnergy >( options ); } ScoreTypes EnvSmoothEnergyCreator::score_types_for_method() const { ScoreTypes sts; sts.push_back( envsmooth ); return sts; } Distance const start_sig = 9.8; Distance const end_sig = 10.2; DistanceSquared const start_sig2 = start_sig*start_sig; DistanceSquared const end_sig2 = end_sig*end_sig; /// c-tor EnvSmoothEnergy::EnvSmoothEnergy( EnergyMethodOptions const & options ) : parent( utility::pointer::make_shared< EnvSmoothEnergyCreator >() ) { initialize( options ); } EnvSmoothEnergy::EnvSmoothEnergy( EnvSmoothEnergy const & src ) : parent( src ), envdata_( src.envdata_ ) {} /// clone EnergyMethodOP EnvSmoothEnergy::clone() const { return utility::pointer::make_shared< EnvSmoothEnergy >( *this ); } /// initialize with envdata from database void EnvSmoothEnergy::initialize( EnergyMethodOptions const & options ) { // envdata is provided for each aa in 40 bins, corresponding to number of neighbors in 12A neighbor graph core::Size const num_bins( 40 ); envdata_.resize( chemical::num_canonical_aas ); // check option for alternative envsmooth database file utility::io::izstream stream; if ( options.envsmooth_zero_negatives() ) { basic::database::open( stream, "scoring/score_functions/envsmooth/envdata_zero_negatives.txt" ); } else { basic::database::open( stream, "scoring/score_functions/envsmooth/envdata.txt" ); } core::Real bin_value; std::string line; // fill envdata_ with values from file for ( core::Size ii = 0; ii < chemical::num_canonical_aas; ++ii ) { debug_assert( stream ); getline( stream, line ); std::istringstream l( line ); for ( core::Size jj = 0; jj < num_bins; ++jj ) { debug_assert( l ); l >> bin_value; envdata_[ ii ].push_back( bin_value ); } } } ///////////////////////////////////////////////////////////////////////////// // scoring ///////////////////////////////////////////////////////////////////////////// inline Real sqr ( Real x ) { return x*x; } /// @details stores dScore/dNumNeighbors so that when neighbor atoms on adjacent /// residues move, their influence on the score of the surrounding residues is /// rapidly computed. void EnvSmoothEnergy::setup_for_derivatives( pose::Pose & pose, ScoreFunction const & ) const { pose.update_residue_neighbors(); Size nres( pose.size() ); core::conformation::symmetry::SymmetryInfoCOP symm_info; if ( core::pose::symmetry::is_symmetric(pose) ) { auto & SymmConf ( dynamic_cast<core::conformation::symmetry::SymmetricConformation &> ( pose.conformation()) ); symm_info = SymmConf.Symmetry_Info(); } residue_N_.clear(); residue_E_.clear(); residue_dEdN_.clear(); // iterate over all the residues in the protein and count their neighbours // and save values of E, N, and dEdN for ( Size i = 1; i <= nres; ++i ) { if ( symm_info && !symm_info->bb_is_independent( i ) ) { residue_E_.push_back(0); residue_N_.push_back(0); residue_dEdN_.push_back(0); continue; } // get the appropriate residue from the pose. conformation::Residue const & rsd( pose.residue(i) ); // currently this is only for protein residues if ( !rsd.is_protein() || rsd.aa() == chemical::aa_unk ) { residue_E_.push_back(0); residue_N_.push_back(0); residue_dEdN_.push_back(0); continue; //return; } Size const atomindex_i = rsd.atom_index( representative_atom_name( rsd.aa() )); core::conformation::Atom const & atom_i = rsd.atom(atomindex_i); const Energies & energies( pose.energies() ); const TwelveANeighborGraph & graph ( energies.twelveA_neighbor_graph() ); Real countN = 0.0; // iterate across neighbors within 12 angstroms for ( utility::graph::Graph::EdgeListConstIter ir = graph.get_node(i)->const_edge_list_begin(), ire = graph.get_node(i)->const_edge_list_end(); ir != ire; ++ir ) { Size const j( (*ir)->get_other_ind( i ) ); conformation::Residue const & rsd_j( pose.residue(j) ); Size atomindex_j( rsd_j.type().nbr_atom() ); core::conformation::Atom const & atom_j = rsd_j.atom(atomindex_j); Real sqdist = atom_i.xyz().distance_squared(atom_j.xyz()); countN += sigmoidish_neighbor( sqdist ); } Real score = 0; Real dscoredN = 0; calc_energy( countN, rsd.aa(), score, dscoredN ); residue_N_.push_back( countN ); residue_E_.push_back( score ); residue_dEdN_.push_back( dscoredN ); //std::cout << "ENV: " << i << " " << score << std::endl; } // symmetrize if ( symm_info ) { for ( Size i = 1; i <= nres; ++i ) { if ( !symm_info->bb_is_independent( i ) ) { Size master_i = symm_info->bb_follows( i ); residue_N_[i] = residue_N_[master_i]; residue_E_[i] = residue_E_[master_i]; residue_dEdN_[i] = residue_dEdN_[master_i]; } } } } void EnvSmoothEnergy::setup_for_scoring( pose::Pose & pose, ScoreFunction const & ) const { pose.update_residue_neighbors(); } /// @details counts the number of nbr atoms within a given radius of the for the input /// residue. Because the representative atom on the input residue may be in a different /// location than the representative atom on the same residue when scoring_begin() is called, /// these neighbor counts cannot be reused; therefore, scoring_begin does not keep /// neighbor counts. void EnvSmoothEnergy::residue_energy( conformation::Residue const & rsd, pose::Pose const & pose, EnergyMap & emap ) const { // ignore scoring residues which have been marked as "REPLONLY" residues (only the repulsive energy will be calculated) if ( rsd.has_variant_type( core::chemical::REPLONLY ) ) { return; } // currently this is only for protein residues if ( ! rsd.is_protein() ) return; if ( rsd.aa() == chemical::aa_unk ) return; TwelveANeighborGraph const & graph ( pose.energies().twelveA_neighbor_graph() ); Size const atomindex_i = rsd.atom_index( representative_atom_name( rsd.aa() )); core::conformation::Atom const & atom_i = rsd.atom(atomindex_i); Real countN = 0.0; // iterate across neighbors within 12 angstroms for ( utility::graph::Graph::EdgeListConstIter ir = graph.get_node( rsd.seqpos() )->const_edge_list_begin(), ire = graph.get_node( rsd.seqpos() )->const_edge_list_end(); ir != ire; ++ir ) { Size const j( (*ir)->get_other_ind( rsd.seqpos() ) ); conformation::Residue const & rsd_j( pose.residue(j) ); // if virtual residue, don't score if ( rsd_j.aa() == core::chemical::aa_vrt ) continue; Size atomindex_j( rsd_j.nbr_atom() ); core::conformation::Atom const & atom_j = rsd_j.atom(atomindex_j); Real sqdist = atom_i.xyz().distance_squared( atom_j.xyz() ); countN += sigmoidish_neighbor( sqdist ); } Real score = 0, dscoredN = 0; calc_energy( countN, rsd.aa(), score, dscoredN ); emap[ envsmooth ] += score; } /// @details Special cases handled for when an atom is both the representative /// atom for an amino acid, and its nbr_atom. void EnvSmoothEnergy::eval_atom_derivative( id::AtomID const & atom_id, pose::Pose const & pose, kinematics::DomainMap const & , ScoreFunction const &, EnergyMap const & weights, Vector & F1, Vector & F2 ) const { // ignore scoring residues which have been marked as "REPLONLY" residues (only the repulsive energy will be calculated) if ( pose.residue( atom_id.rsd() ).has_variant_type( core::chemical::REPLONLY ) ) { return; } conformation::Residue const & rsd = pose.residue( atom_id.rsd() ); if ( ! rsd.is_protein() ) return; if ( rsd.aa() == chemical::aa_unk ) return; Size const i = rsd.seqpos(); Size const i_nbr_atom = rsd.type().nbr_atom(); Size const i_rep_atom = rsd.atom_index( representative_atom_name( rsd.aa() )); // forces act only on the nbr atom (CB or CA) or the representative atom if ( i_nbr_atom != (Size) atom_id.atomno() && i_rep_atom != (Size) atom_id.atomno() ) return; core::conformation::Atom const & atom_i = rsd.atom( atom_id.atomno() ); TwelveANeighborGraph const & graph ( pose.energies().twelveA_neighbor_graph() ); // its possible both of these are true bool const input_atom_is_nbr( i_nbr_atom == Size (atom_id.atomno()) ); bool const input_atom_is_rep( i_rep_atom == Size ( atom_id.atomno() )); Vector f1(0.0), f2(0.0); for ( utility::graph::Graph::EdgeListConstIter ir = graph.get_node(i)->const_edge_list_begin(), ire = graph.get_node(i)->const_edge_list_end(); ir != ire; ++ir ) { Size const j( (*ir)->get_other_ind( i ) ); conformation::Residue const & rsd_j( pose.residue(j) ); // if virtual residue, don't score if ( rsd_j.aa() == core::chemical::aa_vrt ) continue; if ( input_atom_is_nbr && input_atom_is_rep && (rsd_j.is_protein() && rsd_j.aa()<=core::chemical::num_canonical_aas) ) { Size const resj_rep_atom = rsd_j.atom_index( representative_atom_name( rsd_j.aa() )); Size const resj_nbr_atom = rsd_j.nbr_atom(); if ( resj_rep_atom == resj_nbr_atom ) { /// two birds, one stone increment_f1_f2_for_atom_pair( atom_i, rsd_j.atom( resj_rep_atom ), weights[ envsmooth ] * ( residue_dEdN_[ j ] + residue_dEdN_[ i ] ), F1, F2 ); } else { increment_f1_f2_for_atom_pair( atom_i, rsd_j.atom( resj_rep_atom ), weights[ envsmooth ] * ( residue_dEdN_[ j ] ), F1, F2 ); increment_f1_f2_for_atom_pair( atom_i, rsd_j.atom( resj_nbr_atom ), weights[ envsmooth ] * ( residue_dEdN_[ i ] ), F1, F2 ); } } else if ( input_atom_is_nbr && (rsd_j.is_protein() && rsd_j.aa()<=core::chemical::num_canonical_aas) ) { Size const resj_rep_atom = rsd_j.atom_index( representative_atom_name( rsd_j.aa() )); increment_f1_f2_for_atom_pair( atom_i, rsd_j.atom( resj_rep_atom ), weights[ envsmooth ] * ( residue_dEdN_[ j ] ), F1, F2 ); } else { Size const resj_nbr_atom = rsd_j.nbr_atom(); increment_f1_f2_for_atom_pair( atom_i, rsd_j.atom( resj_nbr_atom ), weights[ envsmooth ] * ( residue_dEdN_[ i ] ), F1, F2 ); } } } /// @details returns const & to static data members to avoid expense /// of string allocation and destruction. Do not call this function /// on non-canonical aas std::string const & EnvSmoothEnergy::representative_atom_name( chemical::AA const aa ) const { //debug_assert( aa >= 1 && aa <= chemical::num_canonical_aas ); static std::string const cbeta_string( "CB" ); static std::string const sgamma_string( "SG" ); static std::string const cgamma_string( "CG" ); static std::string const cdelta_string( "CD" ); static std::string const czeta_string( "CZ" ); static std::string const calpha_string( "CA" ); static std::string const ceps_1_string( "CE1" ); static std::string const cdel_1_string( "CD1" ); static std::string const ceps_2_string( "CE2" ); static std::string const sdelta_string( "SD" ); switch ( aa ) { case ( chemical::aa_ala ) : return cbeta_string; case ( chemical::aa_cys ) : return sgamma_string; case ( chemical::aa_asp ) : return cgamma_string; case ( chemical::aa_glu ) : return cdelta_string; case ( chemical::aa_phe ) : return czeta_string; case ( chemical::aa_gly ) : return calpha_string; case ( chemical::aa_his ) : return ceps_1_string; case ( chemical::aa_ile ) : return cdel_1_string; case ( chemical::aa_lys ) : return cdelta_string; case ( chemical::aa_leu ) : return cgamma_string; case ( chemical::aa_met ) : return sdelta_string; case ( chemical::aa_asn ) : return cgamma_string; case ( chemical::aa_pro ) : return cgamma_string; case ( chemical::aa_gln ) : return cdelta_string; case ( chemical::aa_arg ) : return czeta_string; case ( chemical::aa_ser ) : return cbeta_string; case ( chemical::aa_thr ) : return cbeta_string; case ( chemical::aa_val ) : return cbeta_string; case ( chemical::aa_trp ) : return ceps_2_string; case ( chemical::aa_tyr ) : return czeta_string; default : utility_exit_with_message( "ERROR: Failed to find amino acid " + chemical::name_from_aa( aa ) + " in EnvSmooth::representative_atom_name" ); break; } // unreachable return calpha_string; } /// @brief EnvSmoothEnergy distance cutoff Distance EnvSmoothEnergy::atomic_interaction_cutoff() const { return 0.0; } /// @brief EnvSmoothEnergy void EnvSmoothEnergy::indicate_required_context_graphs( utility::vector1< bool > & context_graphs_required ) const { context_graphs_required[ twelve_A_neighbor_graph ] = true; } void EnvSmoothEnergy::calc_energy( Real const neighbor_count, chemical::AA const aa, Real & score, Real & dscore_dneighbor_count ) const { auto low_bin = static_cast< Size > ( floor(neighbor_count)); auto high_bin = static_cast< Size > ( ceil(neighbor_count)); Real inter = neighbor_count - low_bin; auto const aa_as_int = static_cast< int > (aa); if ( high_bin < 40 ) { score = envdata_[ aa_as_int - 1 ][ low_bin ] * (1.0-inter) + envdata_[ aa_as_int - 1 ][ high_bin ] * (inter); dscore_dneighbor_count = envdata_[ aa_as_int - 1 ][ high_bin ] - envdata_[ aa_as_int - 1 ][ low_bin ]; } else { score = envdata_[ aa_as_int - 1 ][ 39 ]; dscore_dneighbor_count = 0; } score *= 2.019; // this factor is from rosetta++ and fuck knows where it came from originally :-) dscore_dneighbor_count *= 2.019; } Real EnvSmoothEnergy::sigmoidish_neighbor( DistanceSquared const sqdist ) const { if ( sqdist > end_sig2 ) { return 0.0; } else if ( sqdist < start_sig2 ) { return 1.0; } else { Real dist = sqrt( sqdist ); return sqr(1.0 - sqr( (dist - start_sig) / (end_sig - start_sig) ) ); } } void EnvSmoothEnergy::increment_f1_f2_for_atom_pair( conformation::Atom const & atom1, conformation::Atom const & atom2, Real weighted_dScore_dN, Vector & F1, Vector & F2 ) const { DistanceSquared dist2 = atom1.xyz().distance_squared(atom2.xyz()); Distance dist( 0.0 ); // only used if start_sig2 <= dist2 <= end_sig2 Real dNdd = 0; if ( dist2 > end_sig2 ) { dNdd = 0; } else if ( dist2 < start_sig2 ) { dNdd = 0.0; } else { dist = sqrt( dist2 ); Real x = (dist - start_sig)/ (end_sig - start_sig); dNdd = 4*x*(-1 + x*x) / (end_sig - start_sig); } Real dscoredd = ( weighted_dScore_dN ) * dNdd; if ( dscoredd != 0 ) { Vector const f1( cross( atom1.xyz(), atom2.xyz() )); Vector const f2( atom1.xyz() - atom2.xyz() ); dscoredd /= dist; F1 += dscoredd * f1; F2 += dscoredd * f2; } } core::Size EnvSmoothEnergy::version() const { return 1; // Initial versioning } } } }
[ "36790013+MedicaicloudLink@users.noreply.github.com" ]
36790013+MedicaicloudLink@users.noreply.github.com
ae34f94125256d0ade9c7a5413cb83b51dfe1319
3d97884696ac21cc84a77db7b0150536d3cd3dd3
/addons/cirkit-addon-reversible/src/reversible/mapping/maslov_mapping.hpp
487f6e55d236d6dfab2e116a47f66a1675a07b01
[ "MIT" ]
permissive
gwdueck/cirkit
db59b0a8a253030a684e635ba9ca004b10a02824
9795bac66aaf35873e47228b46db6546963cf4cb
refs/heads/master
2021-06-19T23:40:59.109732
2020-03-18T01:03:45
2020-03-18T01:03:45
98,331,135
0
2
null
2020-01-15T14:00:53
2017-07-25T17:10:48
C++
UTF-8
C++
false
false
1,776
hpp
/* CirKit: A circuit toolkit * Copyright (C) 2009-2015 University of Bremen * Copyright (C) 2015-2017 EPFL * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** * @file maslov_mapping.hpp * * @brief Mapping with relative-phase Toffoli gates * * @author Mathias Soeken * @since 2.3 */ #ifndef MASLOV_MAPPING_HPP #define MASLOV_MAPPING_HPP #include <core/properties.hpp> #include <reversible/circuit.hpp> namespace cirkit { circuit maslov_mapping( const circuit& src, const properties::ptr& settings = properties::ptr(), const properties::ptr& statistics = properties::ptr() ); } #endif // Local Variables: // c-basic-offset: 2 // eval: (c-set-offset 'substatement-open 0) // eval: (c-set-offset 'innamespace 0) // End:
[ "mathias.soeken@epfl.ch" ]
mathias.soeken@epfl.ch
6e7f8b0819b1adbc510cfc9f942e895642019e5f
ab8e4abb2c6f86d041cba4017d6f75ef0d649093
/Lab4/labG++.cpp
81d3bd0687487478b37720649467a47d6afc588b
[]
no_license
beachcoder25/326-Operating-Systems
3134d6d4a6b8346d109a21e75f7fe5b6a8d3a212
87813e4aaca889af96ff39235395dbeb32a3fd7a
refs/heads/master
2021-10-27T07:39:31.190976
2019-04-16T16:35:33
2019-04-16T16:35:33
168,808,820
0
1
null
null
null
null
UTF-8
C++
false
false
138
cpp
#include <unistd.h> #include <sys/wait.h> #include <iostream> using namespace std; int main(){ cout << "HEY\n"; exit(0); }
[ "cornish25@gmail.com" ]
cornish25@gmail.com
c8b86731244aae80451c56bd3256d57580afe9e4
57f7eedac8421f84aa699bab8a5652dc160e45e6
/src/IndexBuffer.h
5c187841d845192fb9351f32b52959e9a18b41ef
[]
no_license
Yuanke-Pan/Graphic-Test-Frame
84855ef551ac9ad069705124b8b0a0d460afc15d
a81e44e8aa10be3473cd4ad3a7cce71a7e5cf848
refs/heads/master
2023-02-12T22:16:42.404990
2021-01-04T03:55:40
2021-01-04T03:55:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
305
h
#pragma once #include<gl/glew.h> class IndexBuffer { private: unsigned int m_IndexBufferID; unsigned int m_count; public: IndexBuffer(const unsigned int *data, unsigned int size); ~IndexBuffer(); void bind() const; void unbind() const; inline unsigned int GetCount() const { return m_count; } };
[ "dreamice@outlook.com" ]
dreamice@outlook.com
d6cffd0f64bf42bbf653e8617c189a554799c1ae
d0aabfcfdac454ac1c9cce7da6cdcb0cfedf2460
/Advanced Recursion Problems/Permutations_of_Strings.cpp
fd133548cfc76c5af0a0c27636407bbe1cdcc2eb
[]
no_license
mitanshubhavsar/Data_Structures_CPP
51a62827ea25eb1f84ac98536f42cea19e3ab205
f3ebebc173ba7285b0314207dc9056fb03d3c1bd
refs/heads/master
2023-04-12T09:30:40.333845
2021-04-17T20:01:34
2021-04-17T20:01:34
352,342,016
1
0
null
null
null
null
UTF-8
C++
false
false
406
cpp
#include <iostream> using namespace std; void permutations(string s, string ans){ if(s.length()==0){ cout<<ans<<endl; return; } for(int i=0;i<s.length();i++){ char ch = s[i]; string rest_of_string = s.substr(0,i)+ s.substr(i+1); permutations(rest_of_string,ans+ch); } } int main(){ string s = "ABC"; permutations(s,""); return 0; }
[ "mitanshubhavsar90@gmail.com" ]
mitanshubhavsar90@gmail.com
8ff6bcd30b8d86c3a4541b7c35454d7abfc4fac6
94303aaf3384184608723be26121f1ea76fa75cf
/IdCfgRom/WriteReadDlg.cpp
4bb467780ba0c86e2e375246775600339f14fc30
[]
no_license
insys-projects/ICR
d8cb40e36764f10346b862c24188aab5757d07e1
ef2357a8b41aba3ecf41a3b0d4afed5ece5ad3f4
refs/heads/master
2021-08-15T21:49:55.375551
2020-08-24T15:35:19
2020-08-24T15:35:19
215,523,343
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
35,284
cpp
// WriteReadDlg.cpp : implementation file // #include "stdafx.h" #include "IdCfgRom.h" #include "WriteReadDlg.h" #include "IdCfgRomDlg.h" int g_nSortColumnNum = 0; int g_nLastArrowType = NO_ARROW; // CWriteReadDlg dialog IMPLEMENT_DYNAMIC(CWriteReadDlg, CDialog) CWriteReadDlg::CWriteReadDlg(CWnd* pParent /*=NULL*/) : CDialog(CWriteReadDlg::IDD, pParent) , m_sWriteName(_T("")) , m_sWriteDevId(_T("")) , m_sWriteVer(_T("")) , m_sWritePId(_T("")) , m_sWriteDate(_T("")) , m_sFileBaseDir(_T("")) { m_nLastClickedColumnNum = -1; m_hUpArrow = LoadBitmap(AfxGetResourceHandle(),MAKEINTRESOURCE(IDB_ARROW_UP)); m_hDownArrow = LoadBitmap(AfxGetResourceHandle(),MAKEINTRESOURCE(IDB_ARROW_DOWN)); m_nCanResize = 0; m_pFilterDlg = NULL; } CWriteReadDlg::~CWriteReadDlg() { } void CWriteReadDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_BASE, m_ctrlBase); DDX_Text(pDX, IDC_WRITE_NAME, m_sWriteName); DDX_Text(pDX, IDC_WRITE_DEVID, m_sWriteDevId); DDX_Text(pDX, IDC_WRITE_VER, m_sWriteVer); DDX_Text(pDX, IDC_WRITE_ZAKAZ, m_sWriteZakaz); DDX_Text(pDX, IDC_WRITE_PID, m_sWritePId); DDX_Text(pDX, IDC_WRITE_SURNAME, m_sWriteSurname); DDX_Text(pDX, IDC_WRITE_KEYWORD, m_sWriteKeyword); DDX_Text(pDX, IDC_WRITE_DATE, m_sWriteDate); DDX_Control(pDX, IDC_READ_BASE, m_ctrlReadBase); DDX_Control(pDX, IDC_EDIT_BASE, m_ctrlEditBase); DDX_Control(pDX, IDC_DELETE_BASE, m_ctrlDeleteBase); DDX_Control(pDX, IDC_SAVE_BASE, m_ctrlSaveBase); DDX_Text(pDX, IDC_FILE_BASE_DIR, m_sFileBaseDir); } BEGIN_MESSAGE_MAP(CWriteReadDlg, CDialog) ON_BN_CLICKED(IDC_READ_FILE, &CWriteReadDlg::OnBnClickedReadFile) ON_BN_CLICKED(IDC_SAVE_BASE, &CWriteReadDlg::OnBnClickedSaveBase) ON_BN_CLICKED(IDC_READ_BASE, &CWriteReadDlg::OnBnClickedReadBase) ON_BN_CLICKED(IDC_DELETE_BASE, &CWriteReadDlg::OnBnClickedDeleteBase) ON_NOTIFY(LVN_COLUMNCLICK, IDC_BASE, &CWriteReadDlg::OnLvnColumnclickBase) ON_NOTIFY(NM_CLICK, IDC_BASE, &CWriteReadDlg::OnNMClickBase) ON_NOTIFY(LVN_KEYDOWN, IDC_BASE, &CWriteReadDlg::OnLvnKeydownBase) ON_WM_DESTROY() ON_WM_CLOSE() ON_BN_CLICKED(IDC_SAVE_FILE_HEX, &CWriteReadDlg::OnBnClickedSaveFileHex) ON_BN_CLICKED(IDC_SAVE_FILE_BIN, &CWriteReadDlg::OnBnClickedSaveFileBin) ON_BN_CLICKED(IDC_FILTER, &CWriteReadDlg::OnBnClickedFilter) ON_WM_SIZE() ON_WM_GETMINMAXINFO() ON_BN_CLICKED(IDC_EDIT_BASE, &CWriteReadDlg::OnBnClickedEditBase) ON_NOTIFY(NM_DBLCLK, IDC_BASE, &CWriteReadDlg::OnNMDblclkBase) ON_BN_CLICKED(IDC_FILE_BASE_PATH, &CWriteReadDlg::OnBnClickedFileBasePath) // ON_WM_CREATE() END_MESSAGE_MAP() // CWriteReadDlg message handlers BOOL CWriteReadDlg::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here SetIcon(g_hIcon, TRUE); // Set big icon SetIcon(g_hIcon, FALSE); // Set small icon m_ctrlBase.SetExtendedStyle(LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT); m_ctrlBase.InsertColumn(0, "Имя устройства", LVCFMT_LEFT, 100); m_ctrlBase.InsertColumn(1, "ID устройства", LVCFMT_LEFT, 90); m_ctrlBase.InsertColumn(2, "Версия", LVCFMT_LEFT, 50); m_ctrlBase.InsertColumn(3, "Номер заказа", LVCFMT_LEFT, 90); m_ctrlBase.InsertColumn(4, "PID", LVCFMT_LEFT, 70); m_ctrlBase.InsertColumn(5, "Фамилия", LVCFMT_LEFT, 90); m_ctrlBase.InsertColumn(6, "Ключевое слово", LVCFMT_LEFT, 100); m_ctrlBase.InsertColumn(7, "Дата", LVCFMT_LEFT, 80); m_ctrlReadBase.EnableWindow(FALSE); m_ctrlEditBase.EnableWindow(FALSE); m_ctrlDeleteBase.EnableWindow(FALSE); // заполнение таблицы базой файлов m_sFileBaseDir = GetFileBasePathFromRegistry(); UpdateData(FALSE); LoadFileBaseFromDir(m_sFileBaseDir); // установка размера и положения окна WINDOWPLACEMENT place; GetWindowPlacement(&place); m_nDefaultDialogLeft = place.rcNormalPosition.left; m_nDefaultDialogRight = place.rcNormalPosition.right; m_nDefaultDialogTop = place.rcNormalPosition.top; m_nDefaultDialogBottom = place.rcNormalPosition.bottom; SaveItemPosition(this, IDC_BASE, FIELD); SaveItemPosition(this, IDC_BASE_WORK_STATIC, TOP_RIGHT); SaveItemPosition(this, IDC_NAME_STATIC, TOP_RIGHT); SaveItemPosition(this, IDC_DEVID_STATIC, TOP_RIGHT); SaveItemPosition(this, IDC_VER_STATIC, TOP_RIGHT); SaveItemPosition(this, IDC_ZAKAZ_STATIC, TOP_RIGHT); SaveItemPosition(this, IDC_PID_STATIC, TOP_RIGHT); SaveItemPosition(this, IDC_SURNAME_STATIC, TOP_RIGHT); SaveItemPosition(this, IDC_KEYWORD_STATIC, TOP_RIGHT); SaveItemPosition(this, IDC_DATE_STATIC, TOP_RIGHT); SaveItemPosition(this, IDC_WRITE_NAME, TOP_RIGHT); SaveItemPosition(this, IDC_WRITE_DEVID, TOP_RIGHT); SaveItemPosition(this, IDC_WRITE_VER, TOP_RIGHT); SaveItemPosition(this, IDC_WRITE_ZAKAZ, TOP_RIGHT); SaveItemPosition(this, IDC_WRITE_PID, TOP_RIGHT); SaveItemPosition(this, IDC_WRITE_SURNAME, TOP_RIGHT); SaveItemPosition(this, IDC_WRITE_KEYWORD, TOP_RIGHT); SaveItemPosition(this, IDC_WRITE_DATE, TOP_RIGHT); SaveItemPosition(this, IDC_SAVE_BASE, TOP_RIGHT); SaveItemPosition(this, IDC_READ_BASE, TOP_RIGHT); SaveItemPosition(this, IDC_EDIT_BASE, TOP_RIGHT); SaveItemPosition(this, IDC_DELETE_BASE, TOP_RIGHT); SaveItemPosition(this, IDC_FILTER, TOP_RIGHT); SaveItemPosition(this, IDC_HAND_WORK_STATIC, TOP_RIGHT); SaveItemPosition(this, IDC_SAVE_FILE_BIN, TOP_RIGHT); SaveItemPosition(this, IDC_SAVE_FILE_HEX, TOP_RIGHT); SaveItemPosition(this, IDC_READ_FILE, TOP_RIGHT); SaveItemPosition(this, IDC_STATIC_FILE_BASE_DIR, TOP_RIGHT); SaveItemPosition(this, IDC_FILE_BASE_DIR, TOP_RIGHT); SaveItemPosition(this, IDC_FILE_BASE_PATH, TOP_RIGHT); for( int ii=0; ii<(int)m_vItemsPositions.size(); ii++ ) MoveItemRelativePosition(m_vItemsPositions[ii]); m_nCanResize = 1; // окно отображается чуть ниже основного { WINDOWPLACEMENT place; GetWindowPlacement(&place); WINDOWPLACEMENT placeParent; m_poIdCfgRomWindow->GetWindowPlacement(&placeParent); WINDOWPLACEMENT placeNew = place; placeNew.rcNormalPosition.left = (placeParent.rcNormalPosition.right + placeParent.rcNormalPosition.left)/2 - (place.rcNormalPosition.right)/2; placeNew.rcNormalPosition.right = (placeParent.rcNormalPosition.right + placeParent.rcNormalPosition.left)/2 + (place.rcNormalPosition.right)/2; placeNew.rcNormalPosition.top = placeParent.rcNormalPosition.top + 80; placeNew.rcNormalPosition.bottom = placeParent.rcNormalPosition.top + 80 + place.rcNormalPosition.bottom; SetWindowPlacement(&placeNew); } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } CString CWriteReadDlg::GetFileBasePathFromRegistry() { CString sFileBasePath = ""; char acFileBasePath[MAX_PATH]; acFileBasePath[0] = 0; ReadRegistryString("Software\\Instrumental Systems\\IdCfgRom", "FileBaseDirectory", acFileBasePath, MAX_PATH); if( acFileBasePath[0] != 0 ) { sFileBasePath = acFileBasePath; } else { sFileBasePath = GetCurDirFromCommandLine() + "ConfigBase\\"; } return sFileBasePath; } void CWriteReadDlg::SetFileBasePathToRegistry(CString sFileBasePath) { WriteRegistryString("Software\\Instrumental Systems\\IdCfgRom", "FileBaseDirectory", sFileBasePath); } void CWriteReadDlg::OnBnClickedSaveFileBin() { // TODO: Add your control notification handler code here m_poIdCfgRomWindow->SaveBinThroughtDialog(); } void CWriteReadDlg::OnBnClickedSaveFileHex() { // TODO: Add your control notification handler code here m_poIdCfgRomWindow->SaveHexThroughtDialog(); } void CWriteReadDlg::OnBnClickedReadFile() { // TODO: Add your control notification handler code here m_poIdCfgRomWindow->ReadThroughDialog(); } void CWriteReadDlg::OnBnClickedSaveBase() { // TODO: Add your control notification handler code here UpdateData(TRUE); CString sFilePath = MakeFilePathForFileBase(); if( IsFileExist(m_sFileBaseDir, GetFileNameOfPath(sFilePath)) ) { int nRes = AfxMessageBox("Файл с таким именем уже существует! Перезаписать этот файл?", MB_YESNO|MB_ICONQUESTION); if( nRes==IDNO ) return; m_ctrlBase.SetSelectionMark(FindFileInFileBaseList()); } else { AddRowToList(m_sWriteName, m_sWriteDevId, m_sWriteVer, m_sWriteZakaz, m_sWritePId, m_sWriteSurname, m_sWriteKeyword, m_sWriteDate); m_ctrlBase.SetSelectionMark(m_ctrlBase.GetItemCount()-1); } if(!IsDirExist(GetDirOfPath(sFilePath))) CreateDirectory(GetDirOfPath(sFilePath), NULL); m_poIdCfgRomWindow->SaveBin(sFilePath); m_ctrlReadBase.EnableWindow(TRUE); m_ctrlEditBase.EnableWindow(TRUE); m_ctrlDeleteBase.EnableWindow(TRUE); } int CWriteReadDlg::IsFileExist(CString sSearchDir, CString sFileName) { if( sSearchDir.GetAt(sSearchDir.GetLength()-1) != '\\' ) sSearchDir.Append("\\"); CString sSearchFilePath = sSearchDir + "*.*"; HANDLE hFind; WIN32_FIND_DATA findData; hFind = FindFirstFile(sSearchFilePath, &findData); if( hFind != INVALID_HANDLE_VALUE ) { do { CString sFoundFileName = findData.cFileName; if( (sFoundFileName.Compare(".") ==0 ) || (sFoundFileName.Compare("..") == 0) ) continue; if( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { CString sSubSearchDir = sSearchDir + sFoundFileName; if( IsFileExist(sSubSearchDir, sFileName) ) return 1; } if( IsCfgFile(sFoundFileName) ) { if( sFileName.Compare(sFoundFileName) == 0 ) return 1; } } while( FindNextFile(hFind, &findData) != 0 ); } return 0; } int CWriteReadDlg::IsDirExist(CString sSearchDir) { if( sSearchDir.GetAt(sSearchDir.GetLength()-1) == '\\' ) sSearchDir.Delete(sSearchDir.GetLength()-1); HANDLE hFind; WIN32_FIND_DATA findData; hFind = FindFirstFile(sSearchDir, &findData); if( hFind != INVALID_HANDLE_VALUE ) return 1; else return 0; } void CWriteReadDlg::OnNMDblclkBase(NMHDR *pNMHDR, LRESULT *pResult) { // TODO: Add your control notification handler code here OnBnClickedReadBase(); *pResult = 0; } void CWriteReadDlg::OnBnClickedReadBase() { // TODO: Add your control notification handler code here int nSelNum = m_ctrlBase.GetSelectionMark(); m_poIdCfgRomWindow->ReadCfgFile(FindFilePathInFileBase(nSelNum)); m_sWriteName = m_ctrlBase.GetItemText(nSelNum, 0); m_sWriteDevId = m_ctrlBase.GetItemText(nSelNum, 1); m_sWriteVer = m_ctrlBase.GetItemText(nSelNum, 2); m_sWriteZakaz = m_ctrlBase.GetItemText(nSelNum, 3); m_sWritePId = m_ctrlBase.GetItemText(nSelNum, 4); m_sWriteSurname = m_ctrlBase.GetItemText(nSelNum, 5); m_sWriteKeyword = m_ctrlBase.GetItemText(nSelNum, 6); m_sWriteDate = m_ctrlBase.GetItemText(nSelNum, 7); UpdateData(FALSE); } void CWriteReadDlg::OnBnClickedEditBase() { // TODO: Add your control notification handler code here if( MessageBox("Вы уверены, что хотите изменить запись и перезаписать файл?", "IdCfgRom", MB_YESNO|MB_ICONQUESTION) != IDYES ) return; UpdateData(TRUE); CString sFilePath = MakeFilePathForFileBase(); int nFileExist = 0; if( IsFileExist(m_sFileBaseDir, GetFileNameOfPath(sFilePath)) ) { int nRes = AfxMessageBox("Файл с таким именем уже существует! Перезаписать этот файл?", MB_YESNO|MB_ICONQUESTION); if( nRes==IDNO ) return; nFileExist = 1; } int nSelNum = m_ctrlBase.GetSelectionMark(); DeleteFile(FindFilePathInFileBase(nSelNum)); if( nFileExist ) { m_ctrlBase.DeleteItem(nSelNum); nSelNum = FindFileInFileBaseList(); m_ctrlBase.SetSelectionMark(nSelNum); DeleteFile(FindFilePathInFileBase(nSelNum)); } else EditRowInList(nSelNum, m_sWriteName, m_sWriteDevId, m_sWriteVer, m_sWriteZakaz, m_sWritePId, m_sWriteSurname, m_sWriteKeyword, m_sWriteDate); m_poIdCfgRomWindow->SaveBin(sFilePath); } void CWriteReadDlg::OnBnClickedDeleteBase() { // TODO: Add your control notification handler code here vector <TDeleteFile> vDeleteFiles; POSITION pos = m_ctrlBase.GetFirstSelectedItemPosition(); while( pos ) { TDeleteFile rDeleteFile; int nFileIndex = m_ctrlBase.GetNextSelectedItem(pos); rDeleteFile.nIndex = nFileIndex; CString sFilePath = ""; rDeleteFile.sFilePath = FindFilePathInFileBase(nFileIndex); vDeleteFiles.push_back(rDeleteFile); } if( DeleteFilesFromBase(vDeleteFiles) ) { m_ctrlReadBase.EnableWindow(FALSE); m_ctrlEditBase.EnableWindow(FALSE); m_ctrlDeleteBase.EnableWindow(FALSE); } vDeleteFiles.clear(); } CString CWriteReadDlg::FindFilePathInFileBase(int nFileIndex) { CString sFileName = "{" + m_ctrlBase.GetItemText(nFileIndex, 0) + "}" + "{" + m_ctrlBase.GetItemText(nFileIndex, 1) + "}" + "{" + m_ctrlBase.GetItemText(nFileIndex, 2) + "}" + "{" + m_ctrlBase.GetItemText(nFileIndex, 3) + "}" + "{" + m_ctrlBase.GetItemText(nFileIndex, 4) + "}" + "{" + m_ctrlBase.GetItemText(nFileIndex, 5) + "}" + "{" + m_ctrlBase.GetItemText(nFileIndex, 6) + "}" + "{" + m_ctrlBase.GetItemText(nFileIndex, 7) + "}" + ".bin"; return FindFileInDir(m_sFileBaseDir, sFileName); } int CWriteReadDlg::FindFileInFileBaseList() { for(int ii=0; ii<m_ctrlBase.GetItemCount(); ii++ ) { if( (m_ctrlBase.GetItemText(ii, 0) == m_sWriteName) && (m_ctrlBase.GetItemText(ii, 1) == m_sWriteDevId) && (m_ctrlBase.GetItemText(ii, 2) == m_sWriteVer) && (m_ctrlBase.GetItemText(ii, 3) == m_sWriteZakaz) && (m_ctrlBase.GetItemText(ii, 4) == m_sWritePId) && (m_ctrlBase.GetItemText(ii, 5) == m_sWriteSurname) && (m_ctrlBase.GetItemText(ii, 6) == m_sWriteKeyword) && (m_ctrlBase.GetItemText(ii, 7) == m_sWriteDate) ) return ii; } return -1; } CString CWriteReadDlg::FindFileInDir(CString sSearchDir, CString sFileName) { if( sSearchDir.GetAt(sSearchDir.GetLength()-1) != '\\' ) sSearchDir.Append("\\"); CString sSearchFilePath = sSearchDir + "*.*"; HANDLE hFind; WIN32_FIND_DATA findData; hFind = FindFirstFile(sSearchFilePath, &findData); if( hFind != INVALID_HANDLE_VALUE ) { do { CString sFoundFileName = findData.cFileName; if( (sFoundFileName.Compare(".") ==0 ) || (sFoundFileName.Compare("..") == 0) ) continue; if( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { CString sSubSearchDir = sSearchDir + sFoundFileName; return FindFileInDir(sSubSearchDir, sFileName); } if( IsCfgFile(sFoundFileName) ) { if( sFileName.Compare(sFoundFileName) == 0 ) return sSearchDir + sFileName; } } while( FindNextFile(hFind, &findData) != 0 ); } return ""; } int CWriteReadDlg::DeleteFilesFromBase(vector <TDeleteFile> vDeleteFiles) { int nRes = IDNO; if( (int)vDeleteFiles.size()==1 ) nRes = AfxMessageBox("Вы уверены, что хотите удалить выделенный файл?", MB_YESNO|MB_ICONQUESTION); else if( (int)vDeleteFiles.size()>1 ) nRes = AfxMessageBox("Вы уверены, что хотите удалить выделенные файлы?", MB_YESNO|MB_ICONQUESTION); if( nRes!=IDYES ) return 0; for( int ii=(int)vDeleteFiles.size()-1; ii>=0; ii-- ) { DeleteFile(vDeleteFiles[ii].sFilePath); m_ctrlBase.DeleteItem(vDeleteFiles[ii].nIndex); } return 1; } CString CWriteReadDlg::MakeFilePathForFileBase() { CString sFileName = ""; sFileName = m_sFileBaseDir + "{" + m_sWriteName + "}" + "{" + m_sWriteDevId + "}" + "{" + m_sWriteVer + "}" + "{" + m_sWriteZakaz + "}" + "{" + m_sWritePId + "}" + "{" + m_sWriteSurname + "}" + "{" + m_sWriteKeyword + "}" + "{" + m_sWriteDate + "}" + ".bin"; return sFileName; } // добавление строки в таблицу void CWriteReadDlg::AddRowToList(CString sWriteName, CString sWriteDevId, CString sWriteVer, CString sWriteZakaz, CString sWritePId, CString sWriteSurname, CString sWriteKeyword, CString sWriteDate) { LVITEM lvi; CString strItem; lvi.mask = LVIF_IMAGE | LVIF_TEXT; lvi.iItem = m_ctrlBase.GetItemCount(); lvi.iSubItem = 0; lvi.pszText = (LPTSTR)(LPCTSTR)sWriteName; int index = m_ctrlBase.InsertItem(&lvi); lvi.iItem = index; lvi.iSubItem = 1; lvi.pszText = (LPTSTR)(LPCTSTR)sWriteDevId; m_ctrlBase.SetItem(&lvi); lvi.iSubItem = 2; lvi.pszText = (LPTSTR)(LPCTSTR)sWriteVer; m_ctrlBase.SetItem(&lvi); lvi.iSubItem = 3; lvi.pszText = (LPTSTR)(LPCTSTR)sWriteZakaz; m_ctrlBase.SetItem(&lvi); lvi.iSubItem = 4; lvi.pszText = (LPTSTR)(LPCTSTR)sWritePId; m_ctrlBase.SetItem(&lvi); lvi.iSubItem = 5; lvi.pszText = (LPTSTR)(LPCTSTR)sWriteSurname; m_ctrlBase.SetItem(&lvi); lvi.iSubItem = 6; lvi.pszText = (LPTSTR)(LPCTSTR)sWriteKeyword; m_ctrlBase.SetItem(&lvi); lvi.iSubItem = 7; lvi.pszText = (LPTSTR)(LPCTSTR)sWriteDate; m_ctrlBase.SetItem(&lvi); m_ctrlBase.SetItemData(index, index); } // изменение строки в таблице void CWriteReadDlg::EditRowInList(int nItem, CString sWriteName, CString sWriteDevId, CString sWriteVer, CString sWriteZakaz, CString sWritePId, CString sWriteSurname, CString sWriteKeyword, CString sWriteDate) { m_ctrlBase.SetItemText(nItem, 0, sWriteName); m_ctrlBase.SetItemText(nItem, 1, sWriteDevId); m_ctrlBase.SetItemText(nItem, 2, sWriteVer); m_ctrlBase.SetItemText(nItem, 3, sWriteZakaz); m_ctrlBase.SetItemText(nItem, 4, sWritePId); m_ctrlBase.SetItemText(nItem, 5, sWriteSurname); m_ctrlBase.SetItemText(nItem, 6, sWriteKeyword); m_ctrlBase.SetItemText(nItem, 7, sWriteDate); } void CWriteReadDlg::LoadFileBaseFromDir(CString sSearchDir, int nFilter) { m_ctrlBase.DeleteAllItems(); if( sSearchDir.GetAt(sSearchDir.GetLength()-1) != '\\' ) sSearchDir.Append("\\"); CString sSearchFilePath = sSearchDir + "*.*"; HANDLE hFind; WIN32_FIND_DATA findData; hFind = FindFirstFile(sSearchFilePath, &findData); if( hFind == INVALID_HANDLE_VALUE ) return; do { CString sFoundFileName = findData.cFileName; if( (sFoundFileName.Compare(".") ==0 ) || (sFoundFileName.Compare("..") == 0) ) continue; if( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { //CString sSubSearchDir = sSearchDir + sFoundFileName; //LoadFileBaseFromDir(sSubSearchDir); continue; } if( IsCfgFile(sFoundFileName) ) { if( nFilter && (Filter(sFoundFileName)==0) ) continue; AddCfgFileToList(sFoundFileName); } } while( FindNextFile(hFind, &findData) != 0 ); } int CWriteReadDlg::IsCfgFile(CString sFoundFileName) { int nCurParamPos = 0; for(int ii=0; ii<CFG_FILE_PARAMS_CNT; ii++) { if( sFoundFileName.Find('{', nCurParamPos) < 0 ) return 0; nCurParamPos = sFoundFileName.Find('{', nCurParamPos) + 1; if( sFoundFileName.Find('}', nCurParamPos) < 0 ) return 0; nCurParamPos = sFoundFileName.Find('}', nCurParamPos) + 1; } return 1; } void CWriteReadDlg::AddCfgFileToList(CString sCfgFileName) { CString sWriteName = ""; CString sWriteDevId = ""; CString sWriteVer = ""; CString sWriteZakaz = ""; CString sWritePId = ""; CString sWriteSurname = ""; CString sWriteKeyword = ""; CString sWriteDate = ""; int nCurParamPos = 0; nCurParamPos = sCfgFileName.Find('{', nCurParamPos) + 1; sWriteName = sCfgFileName.Mid(nCurParamPos, sCfgFileName.Find('}', nCurParamPos) - nCurParamPos); nCurParamPos = sCfgFileName.Find('{', nCurParamPos) + 1; sWriteDevId = sCfgFileName.Mid(nCurParamPos, sCfgFileName.Find('}', nCurParamPos) - nCurParamPos); nCurParamPos = sCfgFileName.Find('{', nCurParamPos) + 1; sWriteVer = sCfgFileName.Mid(nCurParamPos, sCfgFileName.Find('}', nCurParamPos) - nCurParamPos); nCurParamPos = sCfgFileName.Find('{', nCurParamPos) + 1; sWriteZakaz = sCfgFileName.Mid(nCurParamPos, sCfgFileName.Find('}', nCurParamPos) - nCurParamPos); nCurParamPos = sCfgFileName.Find('{', nCurParamPos) + 1; sWritePId = sCfgFileName.Mid(nCurParamPos, sCfgFileName.Find('}', nCurParamPos) - nCurParamPos); nCurParamPos = sCfgFileName.Find('{', nCurParamPos) + 1; sWriteSurname = sCfgFileName.Mid(nCurParamPos, sCfgFileName.Find('}', nCurParamPos) - nCurParamPos); nCurParamPos = sCfgFileName.Find('{', nCurParamPos) + 1; sWriteKeyword = sCfgFileName.Mid(nCurParamPos, sCfgFileName.Find('}', nCurParamPos) - nCurParamPos); nCurParamPos = sCfgFileName.Find('{', nCurParamPos) + 1; sWriteDate = sCfgFileName.Mid(nCurParamPos, sCfgFileName.Find('}', nCurParamPos) - nCurParamPos); AddRowToList(sWriteName, sWriteDevId, sWriteVer, sWriteZakaz, sWritePId, sWriteSurname, sWriteKeyword, sWriteDate); } void CWriteReadDlg::OnLvnColumnclickBase(NMHDR *pNMHDR, LRESULT *pResult) { LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR); // TODO: Add your control notification handler code here HDITEM hItem; // если стрелка установлена на другой колонке, удаляем её if( (m_nLastClickedColumnNum != pNMLV->iSubItem) && (m_nLastClickedColumnNum != -1) ) { m_ctrlBase.GetHeaderCtrl()->GetItem(m_nLastClickedColumnNum, &hItem); hItem.mask = HDI_FORMAT; hItem.fmt = HDF_STRING; m_ctrlBase.GetHeaderCtrl()->SetItem(m_nLastClickedColumnNum, &hItem); g_nLastArrowType = NO_ARROW; } // рисуем стрелку m_nLastClickedColumnNum = pNMLV->iSubItem; m_ctrlBase.GetHeaderCtrl()->GetItem(m_nLastClickedColumnNum, &hItem); hItem.mask = HDI_BITMAP | HDI_FORMAT; hItem.fmt = HDF_STRING | HDF_BITMAP | HDF_BITMAP_ON_RIGHT; if( g_nLastArrowType == ARROW_UP ) { hItem.hbm = m_hDownArrow; g_nLastArrowType = ARROW_DOWN; } else { hItem.hbm = m_hUpArrow; g_nLastArrowType = ARROW_UP; } m_ctrlBase.GetHeaderCtrl()->SetItem(m_nLastClickedColumnNum, &hItem); // сортировка g_nSortColumnNum = pNMLV->iSubItem; // для даты отдельная функция сортировки int cnt = m_ctrlBase.GetHeaderCtrl()->GetItemCount(); if( pNMLV->iSubItem == (cnt-1) ) m_ctrlBase.SortItems(DateCompareFunc, (LPARAM)&m_ctrlBase); else m_ctrlBase.SortItems(CompareFunc, (LPARAM)&m_ctrlBase); *pResult = 0; } static int CALLBACK CompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { CMyListCtrl* pListCtrl = (CMyListCtrl*) lParamSort; LV_FINDINFO a1; LV_FINDINFO a2; a1.flags = LVFI_PARAM; a2.flags = LVFI_PARAM; a1.lParam = lParam1; a2.lParam = lParam2; CString strItem1 = pListCtrl->GetItemText(pListCtrl->FindItem(&a1), g_nSortColumnNum); CString strItem2 = pListCtrl->GetItemText(pListCtrl->FindItem(&a2), g_nSortColumnNum); if( g_nLastArrowType == ARROW_DOWN ) return -strItem1.CompareNoCase(strItem2); else if( g_nLastArrowType == ARROW_UP ) return strItem1.CompareNoCase(strItem2); return 0; } static int CALLBACK DateCompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { CMyListCtrl* pListCtrl = (CMyListCtrl*) lParamSort; LV_FINDINFO a1; LV_FINDINFO a2; a1.flags = LVFI_PARAM; a2.flags = LVFI_PARAM; a1.lParam = lParam1; a2.lParam = lParam2; CString strItem1 = pListCtrl->GetItemText(pListCtrl->FindItem(&a1), g_nSortColumnNum); CString strItem2 = pListCtrl->GetItemText(pListCtrl->FindItem(&a2), g_nSortColumnNum); CString sYear1 = strItem1.Mid(strItem1.ReverseFind('.')+1); CString sYear2 = strItem2.Mid(strItem2.ReverseFind('.')+1); CString sMon1 = strItem1.Mid(strItem1.Find(".")+1); sMon1 = sMon1.Left(sMon1.Find(".")); CString sMon2 = strItem2.Mid(strItem2.Find(".")+1); sMon2 = sMon2.Left(sMon2.Find(".")); CString sDay1 = strItem1.Left(strItem1.Find(".")); CString sDay2 = strItem2.Left(strItem2.Find(".")); int comp = sYear1.Compare(sYear2); if( comp == 0 ) { comp = sMon1.Compare(sMon2); if( comp == 0 ) { comp = sDay1.Compare(sDay2); } } if( g_nLastArrowType == ARROW_DOWN ) return -comp; else if( g_nLastArrowType == ARROW_UP ) return comp; return 0; } void CWriteReadDlg::OnNMClickBase(NMHDR *pNMHDR, LRESULT *pResult) { // TODO: Add your control notification handler code here LPNMITEMACTIVATE pItem = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR); int nSelCnt = m_ctrlBase.GetSelectedCount(); if( nSelCnt ) { if( nSelCnt == 1 ) { m_ctrlReadBase.EnableWindow(); m_ctrlEditBase.EnableWindow(); } else { m_ctrlReadBase.EnableWindow(FALSE); m_ctrlEditBase.EnableWindow(FALSE); } m_ctrlDeleteBase.EnableWindow(); } else { m_ctrlReadBase.EnableWindow(FALSE); m_ctrlEditBase.EnableWindow(FALSE); m_ctrlDeleteBase.EnableWindow(FALSE); } *pResult = 0; } void CWriteReadDlg::OnLvnKeydownBase(NMHDR *pNMHDR, LRESULT *pResult) { LPNMLVKEYDOWN pLVKeyDow = reinterpret_cast<LPNMLVKEYDOWN>(pNMHDR); // TODO: Add your control notification handler code here *pResult = 0; if( pLVKeyDow->wVKey == VK_DELETE ) OnBnClickedDeleteBase(); else return; } void CWriteReadDlg::OnClose() { // TODO: Add your message handler code here and/or call default m_nCanResize = 0; CDialog::OnClose(); } void CWriteReadDlg::OnDestroy() { CDialog::OnDestroy(); // TODO: Add your message handler code here delete m_pFilterDlg; } void CWriteReadDlg::OnBnClickedFilter() { // TODO: Add your control notification handler code here if( m_pFilterDlg ) { if( !m_pFilterDlg->IsWindowVisible() ) m_pFilterDlg->ShowWindow(SW_SHOW); return; } m_pFilterDlg = new CFileBaseFilterDlg(); m_pFilterDlg->Create(IDD_FILE_BASE_FILTER, this); m_pFilterDlg->ShowWindow(SW_SHOW); m_ctrlReadBase.EnableWindow(FALSE); m_ctrlEditBase.EnableWindow(FALSE); m_ctrlDeleteBase.EnableWindow(FALSE); } int CWriteReadDlg::Filter(CString sFoundFileName) { m_pFilterDlg->UpdateData(TRUE); CString sParam = ""; int nCurParamPos = 0; sParam = sFoundFileName.Mid(sFoundFileName.Find('{', nCurParamPos)+1, sFoundFileName.Find('}', nCurParamPos)-sFoundFileName.Find('{', nCurParamPos)-1); nCurParamPos = sFoundFileName.Find('}', nCurParamPos) + 1; if( sParam.MakeLower().Find(m_pFilterDlg->m_sName.MakeLower()) < 0 ) return 0; sParam = sFoundFileName.Mid(sFoundFileName.Find('{', nCurParamPos)+1, sFoundFileName.Find('}', nCurParamPos)-sFoundFileName.Find('{', nCurParamPos)-1); nCurParamPos = sFoundFileName.Find('}', nCurParamPos) + 1; if( sParam.MakeLower().Find(m_pFilterDlg->m_sDevId.MakeLower()) < 0 ) return 0; sParam = sFoundFileName.Mid(sFoundFileName.Find('{', nCurParamPos)+1, sFoundFileName.Find('}', nCurParamPos)-sFoundFileName.Find('{', nCurParamPos)-1); nCurParamPos = sFoundFileName.Find('}', nCurParamPos) + 1; if( sParam.MakeLower().Find(m_pFilterDlg->m_sVer.MakeLower()) < 0 ) return 0; sParam = sFoundFileName.Mid(sFoundFileName.Find('{', nCurParamPos)+1, sFoundFileName.Find('}', nCurParamPos)-sFoundFileName.Find('{', nCurParamPos)-1); nCurParamPos = sFoundFileName.Find('}', nCurParamPos) + 1; if( sParam.MakeLower().Find(m_pFilterDlg->m_sZakaz.MakeLower()) < 0 ) return 0; sParam = sFoundFileName.Mid(sFoundFileName.Find('{', nCurParamPos)+1, sFoundFileName.Find('}', nCurParamPos)-sFoundFileName.Find('{', nCurParamPos)-1); nCurParamPos = sFoundFileName.Find('}', nCurParamPos) + 1; if( sParam.MakeLower().Find(m_pFilterDlg->m_sPId.MakeLower()) < 0 ) return 0; sParam = sFoundFileName.Mid(sFoundFileName.Find('{', nCurParamPos)+1, sFoundFileName.Find('}', nCurParamPos)-sFoundFileName.Find('{', nCurParamPos)-1); nCurParamPos = sFoundFileName.Find('}', nCurParamPos) + 1; if( sParam.MakeLower().Find(m_pFilterDlg->m_sSurname.MakeLower()) < 0 ) return 0; sParam = sFoundFileName.Mid(sFoundFileName.Find('{', nCurParamPos)+1, sFoundFileName.Find('}', nCurParamPos)-sFoundFileName.Find('{', nCurParamPos)-1); nCurParamPos = sFoundFileName.Find('}', nCurParamPos) + 1; if( sParam.MakeLower().Find(m_pFilterDlg->m_sKeyword.MakeLower()) < 0 ) return 0; // Дата sParam = sFoundFileName.Mid(sFoundFileName.Find('{', nCurParamPos)+1, sFoundFileName.Find('}', nCurParamPos)-sFoundFileName.Find('{', nCurParamPos)-1); int nDay = atoi(sParam.Left(sParam.Find('.'))); int nMonth = atoi(sParam.Mid(sParam.Find('.')+1, sParam.ReverseFind('.')-sParam.Find('.')-1)); int nYear = atoi(sParam.Mid(sParam.ReverseFind('.')+1)); int nDayStart = atoi(m_pFilterDlg->m_sDayStart); int nMonthStart = atoi(m_pFilterDlg->m_sMonthStart); int nYearStart = atoi(m_pFilterDlg->m_sYearStart); if( nDayStart && nMonthStart && nYearStart ) { if( nYear<nYearStart ) return 0; if( nYear==nYearStart ) { if( nMonth<nMonthStart ) return 0; if( nMonth==nMonthStart ) { if( nDay<nDayStart ) return 0; } } } int nDayEnd = atoi(m_pFilterDlg->m_sDayEnd); int nMonthEnd = atoi(m_pFilterDlg->m_sMonthEnd); int nYearEnd = atoi(m_pFilterDlg->m_sYearEnd); if( nDayEnd && nMonthEnd && nYearEnd ) { if( nYear>nYearEnd ) return 0; if( nYear==nYearEnd ) { if( nMonth>nMonthEnd ) return 0; if( nMonth==nMonthEnd ) { if( nDay>nDayEnd ) return 0; } } } return 1; } void CWriteReadDlg::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); // TODO: Add your message handler code here if( m_nCanResize ) { for( int ii=0; ii<(int)m_vItemsPositions.size(); ii++ ) { MoveItemRelativePosition(m_vItemsPositions[ii]); if( ii==((int)m_vItemsPositions.size()-1) ) this->RedrawWindow(); } } } // Сохранение расположения элементов окна при запуске программы void CWriteReadDlg::SaveItemPosition(CWnd* pWnd, int nID, int nRelationToParent) { WINDOWPLACEMENT itemPlace; if( nRelationToParent == WINDOW ) pWnd->GetWindowPlacement(&itemPlace); else { CWnd *pItem = pWnd->GetDlgItem(nID); pItem->GetWindowPlacement(&itemPlace); } TItemPosition rItemPosition; rItemPosition.nID = nID; int nDeltaLeft = -1; int nDeltaRight = -1; int nDeltaTop = -1; int nDeltaBottom = -1; rItemPosition.nWidth = itemPlace.rcNormalPosition.right - itemPlace.rcNormalPosition.left; rItemPosition.nHeight = itemPlace.rcNormalPosition.bottom - itemPlace.rcNormalPosition.top; switch( nRelationToParent ) { case TOP_LEFT: break; case TOP_RIGHT: nDeltaRight = m_nDefaultDialogRight - itemPlace.rcNormalPosition.right - m_nDefaultDialogLeft; break; case BOTTOM_LEFT: nDeltaBottom = m_nDefaultDialogBottom - itemPlace.rcNormalPosition.bottom - m_nDefaultDialogTop; break; case BOTTOM_RIGHT: case FIELD: case WINDOW: case BOTTOM: nDeltaRight = m_nDefaultDialogRight - itemPlace.rcNormalPosition.right - m_nDefaultDialogLeft; nDeltaBottom = m_nDefaultDialogBottom - itemPlace.rcNormalPosition.bottom - m_nDefaultDialogTop; break; } rItemPosition.nDeltaLeft = nDeltaLeft; rItemPosition.nDeltaRight = nDeltaRight; rItemPosition.nDeltaTop = nDeltaTop; rItemPosition.nDeltaBottom = nDeltaBottom; rItemPosition.nRelationToParent = nRelationToParent; rItemPosition.pWnd = pWnd; m_vItemsPositions.push_back(rItemPosition); } // Относительный сдвиг всех элементов окна при изменении места расположения void CWriteReadDlg::MoveItemRelativePosition(TItemPosition rItemPosition) { RECT rect; GetWindowRect(&rect); WINDOWPLACEMENT itemPlace; CWnd *pItem = (CWnd*)0; if( rItemPosition.nRelationToParent == WINDOW ) rItemPosition.pWnd->GetWindowPlacement(&itemPlace); else { pItem = rItemPosition.pWnd->GetDlgItem(rItemPosition.nID); pItem->GetWindowPlacement(&itemPlace); } switch( rItemPosition.nRelationToParent ) { case TOP_LEFT: break; case TOP_RIGHT: itemPlace.rcNormalPosition.right = rect.right - rItemPosition.nDeltaRight - rect.left; itemPlace.rcNormalPosition.left = itemPlace.rcNormalPosition.right - rItemPosition.nWidth; break; case BOTTOM_LEFT: itemPlace.rcNormalPosition.bottom = rect.bottom - rItemPosition.nDeltaBottom - rect.top; itemPlace.rcNormalPosition.top = itemPlace.rcNormalPosition.bottom - rItemPosition.nHeight; break; case BOTTOM_RIGHT: itemPlace.rcNormalPosition.right = rect.right - rItemPosition.nDeltaRight - rect.left; itemPlace.rcNormalPosition.bottom = rect.bottom - rItemPosition.nDeltaBottom - rect.top; itemPlace.rcNormalPosition.left = itemPlace.rcNormalPosition.right - rItemPosition.nWidth; itemPlace.rcNormalPosition.top = itemPlace.rcNormalPosition.bottom - rItemPosition.nHeight; break; case FIELD: case WINDOW: itemPlace.rcNormalPosition.right = rect.right - rItemPosition.nDeltaRight - rect.left; itemPlace.rcNormalPosition.bottom = rect.bottom - rItemPosition.nDeltaBottom - rect.top; break; case BOTTOM: itemPlace.rcNormalPosition.right = rect.right - rItemPosition.nDeltaRight - rect.left; itemPlace.rcNormalPosition.bottom = rect.bottom - rItemPosition.nDeltaBottom - rect.top; itemPlace.rcNormalPosition.top = itemPlace.rcNormalPosition.bottom - rItemPosition.nHeight; break; } pItem->SetWindowPlacement(&itemPlace); pItem->RedrawWindow(); } void CWriteReadDlg::OnGetMinMaxInfo(MINMAXINFO* lpMMI) { // TODO: Add your message handler code here and/or call default lpMMI->ptMinTrackSize.x = 401; lpMMI->ptMinTrackSize.y = 740*2/3; CDialog::OnGetMinMaxInfo(lpMMI); } void CWriteReadDlg::OnBnClickedFileBasePath() { BROWSEINFO bi; bi.hwndOwner = 0; bi.pidlRoot = NULL;//ConvertPathToLpItemIdList("C:\\JenyaWork\\_ICR\\"); char pszBuffer[MAX_PATH]; bi.pszDisplayName = pszBuffer; bi.lpszTitle = "Выбирите директорию базы файлов"; bi.ulFlags = BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS; bi.lpfn = NULL; bi.lParam = 0; LPITEMIDLIST pidl; if( (pidl = ::SHBrowseForFolder(&bi)) == NULL ) return; char acFileBaseDir[MAX_PATH]; if( ::SHGetPathFromIDList(pidl, acFileBaseDir) == FALSE ) return; m_sFileBaseDir = acFileBaseDir; if (m_sFileBaseDir.GetAt(m_sFileBaseDir.GetLength() - 1) != '\\') { m_sFileBaseDir += "\\"; } UpdateData(FALSE); LoadFileBaseFromDir(m_sFileBaseDir); SetFileBasePathToRegistry(m_sFileBaseDir); } LPITEMIDLIST CWriteReadDlg::ConvertPathToLpItemIdList(const char *pszPath) { LPITEMIDLIST pidl; LPSHELLFOLDER pDesktopFolder; OLECHAR olePath[MAX_PATH]; ULONG chEaten; ULONG dwAttributes; HRESULT hr; if (SUCCEEDED(SHGetDesktopFolder(&pDesktopFolder))) { MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pszPath, -1, olePath, MAX_PATH); hr = pDesktopFolder->ParseDisplayName(NULL,NULL,olePath,&chEaten, &pidl,&dwAttributes); pDesktopFolder->Release(); } return pidl; }
[ "Tsikin@a8a5cdc4-a91d-e646-800f-a4054892b1cc" ]
Tsikin@a8a5cdc4-a91d-e646-800f-a4054892b1cc
2d626727eee47dedc0b1c3af670baf917545225b
71bbd5648e15b0098777e0de57559d8647873b55
/Source/MidiKeyboardComp.h
72aa96fe99d5dd02726be4d6cbace3993fa1cfde
[]
no_license
josephwhite/BitCruiser
8a01288bb00d57787d3bc24d52a21bad34e0c963
575930861ab0a079e6547bf4b198068d165d8f07
refs/heads/master
2020-12-21T10:05:23.654010
2020-04-14T01:16:58
2020-04-14T01:16:58
236,395,658
2
0
null
2020-02-21T14:25:34
2020-01-27T00:20:45
C++
UTF-8
C++
false
false
1,346
h
/* ============================================================================== MidiKeyboardComp.h Author: Tom Couto ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" class MidiKeyboardComp : public MidiKeyboardComponent { public: MidiKeyboardComp (MidiKeyboardState& state, Orientation orientation) : MidiKeyboardComponent(state, orientation) { setColour(MidiKeyboardComponent::keyDownOverlayColourId, Colours::mediumturquoise); } void mouseMove (const MouseEvent &) override { } void mouseDrag (const MouseEvent &) override { } void mouseDown (const MouseEvent &) override { } void mouseUp (const MouseEvent &) override { } void mouseEnter (const MouseEvent &) override { } void mouseExit (const MouseEvent &) override { } void mouseWheelMove (const MouseEvent &, const MouseWheelDetails &) override { } void pedalDown() { setColour(MidiKeyboardComponent::keyDownOverlayColourId, Colours::violet); } void pedalUp() { setColour(MidiKeyboardComponent::keyDownOverlayColourId, Colours::mediumturquoise); } private: JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardComp) };
[ "noreply@github.com" ]
noreply@github.com
20ba43245eff3ebd441ee3897da5f1506c685dfc
b2711c67946a3e8c0d0dda7bbe2c424975ac3bde
/example/less-than-4k/operation/yaml/serialize.cpp
ba317073291b55c8cb0f5f391f64366500d2a57c
[ "Apache-2.0" ]
permissive
RaphaelK12/reflection
5332a272a01e635620ed547b38569f72e2c0bc3d
cc53218fcfc62ec1be9a85288c552da0a1ac8733
refs/heads/master
2022-11-30T12:27:10.286422
2020-08-16T15:25:49
2020-08-16T18:10:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,546
cpp
#include <iostream> #include <iomanip> #include <string> #include <functional> #include "reflection/reflection.hpp" class MyFirstClassOriginal //!< Original condition. Not bloated with any other code. { public: MyFirstClassOriginal():m_float(98765){ } void a(){ } float & traitor(){ return m_float; } float const& reader()const{ return m_float; } bool writer( float const& a ){ m_float = a; return true; } private: // And private member float m_float; }; class MyBaseClass //!< Original condition. Not bloated with any other code. { public: MyBaseClass():m_float(98765){ } void a(){ } float & traitor(){ return m_float; } float const& reader()const{ return m_float; } bool writer( float const& a ){ m_float = a; return true; } private: // And private member float m_float; }; class MyMainClass //!< Original condition. Not bloated with any other code. : public MyBaseClass { public: enum Enumerator{ enum1, enum2, enum10=10, enum11=150 }; typedef std::array<float,2> MyTypDef; typedef std::vector<int> MyVectorType; typedef std::set<int> MySetType; typedef std::list<int> MyListType; typedef std::map<int, std::string> MyMapType; MyMainClass():m_int(123456) { m_vector.resize(3,456); m_set.insert(456); m_set.insert(1456); m_list.push_back(12456); m_list.push_back(987); m_map[1]="q"; m_map[3]="f"; m_map[4]="d"; } void a(){ } void b0( float const& f ){ static std::string s; } std::string const& b1( float const& f ){ static std::string s; return s; } int c( float const& f, std::string const& str ){ return 1; } int d( float const& f, std::string const& str, bool const& b ){ return 1; } int & traitor(){ return m_int; } int const& reader()const{ return m_int; } bool writer( int const& a ){ m_int = a; return true; } bool writerV( int const& a )volatile{ m_int = a; return true; } MyFirstClassOriginal & subsider_traitor(){ return m_subsider; } MyFirstClassOriginal const& subsider_reader()const{ return m_subsider; } static int some_static_function( float const&f ){ return 12; } Enumerator const& enum_read()const{ return m_enum; } bool enum_write( Enumerator const& a ){ m_enum = a; return true; } MyVectorType const& vector_reader()const{ return m_vector; } MyVectorType & vector_traitor(){ return m_vector; } MySetType const& set_reader()const{ return m_set; } MySetType & set_traitor() { return m_set; } MyListType const& list_reader()const{ return m_list; } MyListType & list_traitor() { return m_list; } MyMapType const& map_reader()const{ return m_map; } MyMapType & map_traitor() { return m_map; } public: double m_public = 456; const double m_const_public = 123; volatile const double m_volatile_const_public = 456; volatile double m_volatile_public = 789; public: static std::string m_static; private: // And private member Enumerator m_enum = enum2; int m_int; volatile int m_cv; MyFirstClassOriginal m_subsider; MyVectorType m_vector; MySetType m_set; MyListType m_list; MyMapType m_map; }; std::string MyMainClass::m_static="blahblahfoofoo"; //!< TODO reflection__CLASS_BEGIN_view( MyFirstClassReflectionView, public, MyFirstClassOriginal, MyFirstClassOriginal* ) reflection__CLASS_MEMBER_exposed( "number", MyFirstClassOriginal, traitor, writer ) reflection__CLASS_END_view( MyFirstClassReflectionView, MyFirstClassOriginal ); reflection__CLASS_BEGIN_view( MyBaseClasssReflectionView, public, MyBaseClass, MyBaseClass* ) reflection__CLASS_MEMBER_exposed( "number-float", MyBaseClass, traitor, writer ) reflection__CLASS_END_view( MyBaseClasssReflectionView, MyBaseClass ); // Reflect to reflection //template< typename someType_name > // Yeah template. reflection__CLASS_BEGIN_inherit( MyClassReflection, public, MyMainClass ) reflection__CLASS_BASE_direct( "1base-something", MyMainClass, public, default, MyBaseClass ); reflection__CLASS_BASE_inspect( "2base-something", MyMainClass, public, default, MyBaseClass ); reflection__CLASS_BASE_mutate( "3base-something", MyMainClass, public, default, MyBaseClass ); reflection__CLASS_BASE_exposed( "4base-something", MyMainClass, public, default, MyBaseClass ); reflection__CLASS_BASE_variable( "5base-something", MyMainClass, public, default, MyBaseClass ); reflection__CLASS_BASE_guarded( "6base-something", MyMainClass, public, default, MyBaseClass ); reflection__CLASS_BASE_trinity( "7base-something", MyMainClass, public, default, MyBaseClass ); reflection__CLASS_TYPEDEF_member( "typedef-of-something", MyMainClass, public, MyTypDef ); reflection__CLASS_TYPEDEF_member( "typedef-of-vector", MyMainClass, public, MyVectorType ); reflection__CLASS_TYPEDEF_member( "typedef-of-set", MyMainClass, public, MySetType ); reflection__CLASS_TYPEDEF_member( "typedef-of-list", MyMainClass, public, MyListType ); reflection__CLASS_TYPEDEF_member( "typedef-of-map", MyMainClass, public, MyMapType ); reflection__CLASS_ENUM_begin( "enum-for-something", MyMainClass::Enumerator ); reflection__CLASS_ENUM_value( "enum1", MyMainClass::enum1 ) reflection__CLASS_ENUM_value( "enum2", MyMainClass::enum2 ) reflection__CLASS_ENUM_value( "enum10", MyMainClass::enum10 ) reflection__CLASS_ENUM_value( "enum11", MyMainClass::enum11 ) reflection__CLASS_ENUM_end( MyMainClass::Enumerator ) reflection__CLASS_MEMBER_mutate( "asasd3", MyMainClass, writer ) reflection__CLASS_MEMBER_direct( "asasd4", MyMainClass, traitor ) reflection__CLASS_MEMBER_inspect( "asasd5", MyMainClass, reader ) reflection__CLASS_MEMBER_variable( "asasd1", MyMainClass, traitor, reader ) reflection__CLASS_MEMBER_guarded( "asasd2", MyMainClass, writer, reader ) reflection__CLASS_MEMBER_guarded( "00enum", MyMainClass, enum_write, enum_read ) reflection__CLASS_FUNCTION_member( "traitor", MyMainClass, public, traitor ) reflection__CLASS_FUNCTION_member( "reader", MyMainClass, public, reader ) //reflection__CLASS_FUNCTION_member( "writerV", MyMainClass, public, writerV) reflection__CLASS_FUNCTION_member( "writer", MyMainClass, public, writer ) reflection__CLASS_FUNCTION_member( "f10", MyMainClass, public, b0 ) reflection__CLASS_FUNCTION_member( "f11", MyMainClass, public, b1 ) reflection__CLASS_FUNCTION_member( "f2", MyMainClass, public, c ) reflection__CLASS_FUNCTION_member( "f3", MyMainClass, public, d ) reflection__CLASS_FUNCTION_static( "my_static", MyMainClass, public, some_static_function ) reflection__CLASS_MEMBER_variable( "0subsider-traitor", MyMainClass, subsider_traitor, subsider_reader ) reflection__CLASS_MEMBER_variable( "my-vector", MyMainClass, vector_traitor, vector_reader ) reflection__CLASS_MEMBER_variable( "my-set", MyMainClass, set_traitor, set_reader ) reflection__CLASS_MEMBER_variable( "my-list", MyMainClass, list_traitor, list_reader ) reflection__CLASS_MEMBER_variable( "my-map", MyMainClass, map_traitor, map_reader ) reflection__CLASS_FIELD_direct( "some-field-doubleD", MyMainClass, public, m_public ) reflection__CLASS_FIELD_direct( "some-const-field-doubleD", MyMainClass, public, m_const_public ) reflection__CLASS_FIELD_direct( "some-const-volatile-field-doubleD", MyMainClass, public, m_volatile_const_public ) reflection__CLASS_FIELD_direct( "some-volatile-field-doubleD", MyMainClass, public, m_volatile_public ) reflection__CLASS_FIELD_mutate( "some-field-doubleM", MyMainClass, public, m_public ) reflection__CLASS_FIELD_inspect( "some-field-doubleI", MyMainClass, public, m_public ) reflection__CLASS_FIELD_exposed( "some-field-doubleE", MyMainClass, public, m_public ) reflection__CLASS_FIELD_guarded( "some-field-doubleG", MyMainClass, public, m_public ) reflection__CLASS_FIELD_variable( "some-field-doubleV", MyMainClass, public, m_public ) reflection__CLASS_FIELD_trinity( "some-field-doubleT", MyMainClass, public, m_public ) reflection__CLASS_STATIC_direct( "some-common-stringD", MyMainClass, public, m_static ) reflection__CLASS_STATIC_inspect( "some-common-stringI", MyMainClass, public, m_static ) reflection__CLASS_STATIC_mutate( "some-common-stringM", MyMainClass, public, m_static ) reflection__CLASS_STATIC_variable( "some-common-stringV", MyMainClass, public, m_static ) reflection__CLASS_STATIC_guarded( "some-common-stringG", MyMainClass, public, m_static ) reflection__CLASS_STATIC_exposed( "some-common-stringE", MyMainClass, public, m_static ) reflection__CLASS_STATIC_trinity( "some-common-stringT", MyMainClass, public, m_static ) reflection__CLASS_MEMBER_exposed( "asasd2", MyMainClass, traitor, writer ) reflection__CLASS_END_inherit( MyClassReflection, MyMainClass ); int main( int argc, char *argv[] ) { MyMainClass o; MyClassReflection r; //!< Reflection of Original, with pointing to some instance ::reflection::operation::transfer::observe_class<std::ostream> observe; { typedef ::reflection::operation::transfer::yaml::serialize_struct<std::ostream> serialize_type; auto serialize_context = serialize_type::context(); serialize_type serialize( observe, serialize_context ); serialize_type::register_class<MyFirstClassOriginal, MyFirstClassReflectionView>( observe, serialize_context ); serialize_type::register_class<MyBaseClass, MyBaseClasssReflectionView>( observe, serialize_context ); serialize_type::register_enum<MyMainClass::Enumerator>( observe, serialize_context ); serialize_type::register_container< std::vector<int> >( observe, serialize_context ); serialize_type::register_container< std::set<int> >( observe, serialize_context ); serialize_type::register_container< std::list<int> >( observe, serialize_context ); serialize_type::register_container< std::map<int,std::string> >( observe, serialize_context ); } observe.view( std::cout, r ); // XMLize return EXIT_SUCCESS; }
[ "dmilos@gmail.com" ]
dmilos@gmail.com
4ea910dc3bfa64a7985767559c8af614e49e4545
da1e8ae097dbcda58ca4d714b7318c5f69cb0881
/oop345/ms/ms3/LineManager.cpp
4dd1716494e497ad763ec8ef0098213bae4be8e8
[]
no_license
Hansol-Cho/Sem3
f9c4e40b4621317e6f013e87c501ae8a705cfedd
0daee123c0b9ca3738f16f12c52f96fedfa7daff
refs/heads/master
2020-05-29T11:26:19.198355
2019-05-28T23:32:02
2019-05-28T23:32:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,869
cpp
// Name: Hansol Cho // Seneca Student ID: 103608170 // Seneca email: hscho5@myseneca.ca // Date of completion: Nov 30th 2018 // // I confirm that I am the only author of this file // and the content was created entirely by me. #include <fstream> #include <string> #include <functional> #include "Utilities.h" #include "LineManager.h" std::deque<size_t> taskIndex; size_t k = 0; LineManager::LineManager(const std::string& str, std::vector<Task*>& _task, std::vector<CustomerOrder>& _cusord){ std::ifstream file(str); if(file){ Utilities util; std::string token; std::string temp; while(!file.eof()){ bool more =true; size_t position =0; std::getline(file,temp); token = util.extractToken(temp,position,more); for(size_t i = 0; i < _task.size(); i++) { if(_task[i]->getName() == token) { taskIndex.push_back(i); if(more) { token = util.extractToken(temp, position, more); for(size_t j = 0; j < _task.size(); j++) { if(_task[j]->getName() == token) { _task[i]->setNextTask(*_task[j]); } } } i = _task.size(); } } } } for(size_t i= 0; i<_task.size(); i++){ AssemblyLine.push_back(_task[i]); } for(size_t i=0; i<_cusord.size();i++){ ToBeFilled.push_front(std::move(_cusord[i])); } m_cntCustomerOrder = ToBeFilled.size(); } bool LineManager::run(std::ostream& os){ if(ToBeFilled.size()) { AssemblyLine[taskIndex[k]]->operator+=(std::move(ToBeFilled.back())); ToBeFilled.pop_back(); } for(size_t i = 0; i < AssemblyLine.size(); i++) { AssemblyLine[i]->runProcess(os); } for(size_t i = 0; i < AssemblyLine.size(); i++) { if ( AssemblyLine[i]->moveTask() ) { CustomerOrder temp; if ( AssemblyLine[i]->getCompleted(std::ref(temp)) ) { Completed.push_back(std::move(temp)); } } } if(Completed.size() == m_cntCustomerOrder && !ToBeFilled.size()){ return true; }else{ return false; } } void LineManager::displayCompleted(std::ostream& os) const{ for(size_t i =0; i<Completed.size(); i++){ Completed[i].display(os); } } void LineManager::validateTasks() const{ for(size_t i = 0ul; i < AssemblyLine.size(); i++) { AssemblyLine[i]->validate(std::cout); } }
[ "hansol.cho613@gmail.com" ]
hansol.cho613@gmail.com
a0b2d231e0a1a0206c7b10726f34e59dd7b40840
e34d69f33d9bf3d9de99343ba24ad78bc5197a93
/src/classes.h
532b015fef54294fb6f32dd23b1e9f395f87ee8e
[]
no_license
cms-ttH/ttH-TauRoast
8e8728a49d02d9e8d7dc119376a4aefb6e8fd77d
3fe6529d7270dc091db00f95997ca6add8b95ac9
refs/heads/master
2021-01-24T06:13:06.485445
2017-10-11T14:04:05
2017-10-11T14:04:05
10,819,593
2
5
null
2016-09-15T07:19:20
2013-06-20T12:46:59
Python
UTF-8
C++
false
false
1,557
h
#include "DataFormats/Common/interface/Wrapper.h" #include "ttH/TauRoast/interface/Fastlane.h" #include "ttH/TauRoast/interface/SuperSlim.h" namespace { struct dictionary { fastlane::Leaf<int> dummy_ileaf; fastlane::Leaf<float> dummy_fleaf; fastlane::Leaf<std::vector<int>> dummy_vileaf; fastlane::Leaf<std::vector<float>> dummy_vfleaf; fastlane::Cut dummy_cut; fastlane::StaticCut dummy_static_cut; superslim::LorentzVector dummy_vector; std::map<std::string, superslim::LorentzVector> dummy_vector_map; superslim::CutHistogram dummy_hist; edm::Wrapper<superslim::CutHistogram> dummy_hist_wrapper; superslim::PhysObject dummy_object; superslim::Vertex dummy_vertex; std::vector<superslim::Vertex> dummy_vertex_vector; superslim::GenObject dummy_genobject; std::vector<superslim::GenObject> dummy_genobject_vector; superslim::GenJet dummy_genjet; std::vector<superslim::GenJet> dummy_genjet_vector; superslim::Jet dummy_jet; std::vector<superslim::Jet> dummy_jet_vector; std::map<std::string, std::vector<superslim::Jet>> dummy_jet_map; superslim::Lepton dummy_lepton; std::vector<superslim::Lepton> dummy_lepton_vector; superslim::Tau dummy_tau; std::vector<superslim::Tau> dummy_tau_vector; std::map<std::string, std::vector<superslim::Tau>> dummy_tau_map; superslim::Trigger dummy_trigger; superslim::Event dummy_event; edm::Wrapper<superslim::Event> dummy_event_wrapper; }; }
[ "matthias@sushinara.net" ]
matthias@sushinara.net