blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fb8a8c5a62f50251cee46f9191f6d6c9dade6e2d | 79813a2689ae22b0315323f398337017639662bb | /src/modules/file-formats/FITS/FITSModule.h | d4797d1750166429a719465a72834f92d45632d8 | [
"LicenseRef-scancode-other-permissive"
] | permissive | jackros1022/PCL-1 | 4b51b494c69e4d97182387aa84ead1a964798264 | 059423bc8a3d7946a628fe1913b805bc3633aea5 | refs/heads/master | 2021-01-23T05:09:19.844862 | 2017-02-08T11:53:24 | 2017-02-08T11:53:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,751 | h | // ____ ______ __
// / __ \ / ____// /
// / /_/ // / / /
// / ____// /___ / /___ PixInsight Class Library
// /_/ \____//_____/ PCL 02.01.01.0784
// ----------------------------------------------------------------------------
// Standard FITS File Format Module Version 01.01.04.0359
// ----------------------------------------------------------------------------
// FITSModule.h - Released 2016/12/27 17:12:52 UTC
// ----------------------------------------------------------------------------
// This file is part of the standard FITS PixInsight module.
//
// Copyright (c) 2003-2016 Pleiades Astrophoto S.L. All Rights Reserved.
//
// Redistribution and use in both source and binary forms, with or without
// modification, is permitted provided that the following conditions are met:
//
// 1. All redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. All 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 "PixInsight" and "Pleiades Astrophoto", nor the names
// of their contributors, may be used to endorse or promote products derived
// from this software without specific prior written permission. For written
// permission, please contact info@pixinsight.com.
//
// 4. All products derived from this software, in any form whatsoever, must
// reproduce the following acknowledgment in the end-user documentation
// and/or other materials provided with the product:
//
// "This product is based on software from the PixInsight project, developed
// by Pleiades Astrophoto and its contributors (http://pixinsight.com/)."
//
// Alternatively, if that is where third-party acknowledgments normally
// appear, this acknowledgment must be reproduced in the product itself.
//
// THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PLEIADES ASTROPHOTO OR ITS
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS
// INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE,
// DATA OR PROFITS) 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 __FITSModule_h
#define __FITSModule_h
#include <pcl/MetaModule.h>
namespace pcl
{
// ----------------------------------------------------------------------------
class FITSModule : public MetaModule
{
public:
FITSModule();
virtual const char* Version() const;
virtual IsoString Name() const;
virtual String Description() const;
virtual String Company() const;
virtual String Author() const;
virtual String Copyright() const;
virtual String TradeMarks() const;
virtual String OriginalFileName() const;
virtual void GetReleaseDate( int& year, int& month, int& day ) const;
};
// ----------------------------------------------------------------------------
} // pcl
#endif // __FITSModule_h
// ----------------------------------------------------------------------------
// EOF FITSModule.h - Released 2016/12/27 17:12:52 UTC
| [
"juan.conejero@pixinsight.com"
] | juan.conejero@pixinsight.com |
6f71e63e2178c1062cd4e3e1f5ceeec2ff9b6183 | f75eefba63cf4e11e268c5c91e10df0af96d98e3 | /Source/NoesisGui/Private/GeneratedClasses/NoesisGuiResourceDictionaryCollection.cpp | a4d0e224c1e1dda311b89c3aa260a6ff1362d77d | [] | no_license | bibleuspro/UE4Plugin | 7468b4a175ecd37c00e77953a2b0b97cde61ad2a | 1e09fa2b327f33e21dfd8d8351ce6eea5cdb78f5 | refs/heads/master | 2021-01-11T02:37:42.648194 | 2016-10-20T10:49:06 | 2016-10-20T10:49:06 | 70,951,187 | 0 | 0 | null | 2016-10-14T22:20:26 | 2016-10-14T22:20:26 | null | UTF-8 | C++ | false | false | 1,409 | cpp | ////////////////////////////////////////////////////////////////////////////////////////////////////
// Noesis Engine - http://www.noesisengine.com
// Copyright (c) 2009-2010 Noesis Technologies S.L. All Rights Reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "NoesisGuiPrivatePCH.h"
#include "GeneratedClasses/NoesisGuiResourceDictionaryCollection.h"
using namespace Noesis;
using namespace Gui;
UNoesisGuiResourceDictionaryCollection::UNoesisGuiResourceDictionaryCollection(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
void UNoesisGuiResourceDictionaryCollection::SetNoesisComponent(Noesis::Core::BaseComponent* InNoesisComponent)
{
Super::SetNoesisComponent(InNoesisComponent);
Noesis::Gui::TypedCollection<Noesis::Gui::ResourceDictionary>* NoesisResourceDictionaryCollection = NsDynamicCast<Noesis::Gui::TypedCollection<Noesis::Gui::ResourceDictionary>*>(InNoesisComponent);
check(NoesisResourceDictionaryCollection);
}
void UNoesisGuiResourceDictionaryCollection::BeginDestroy()
{
Noesis::Gui::TypedCollection<Noesis::Gui::ResourceDictionary>* NoesisResourceDictionaryCollection = NsDynamicCast<Noesis::Gui::TypedCollection<Noesis::Gui::ResourceDictionary>*>(NoesisComponent.GetPtr());
if (!NoesisResourceDictionaryCollection)
return Super::BeginDestroy();
Super::BeginDestroy();
}
| [
"hcpizzi@hotmail.com"
] | hcpizzi@hotmail.com |
6a1dfedeb8f6ff06ed1008bbc20c89739635d36f | 43c34d3945cd15dd7ba474341f07ca6d5582f796 | /RrgStore.cpp | 1fe5d321e88d9e4225b3fc8158f6e95ed942b5f0 | [] | no_license | Transom/Rrg2DB | edbbf2b9a9aa5c3feac3c6eed24f4ab40a09806e | 0ddf49e600f1c8c534ac720faef4334b994cbe0b | refs/heads/master | 2021-01-01T18:07:50.687398 | 2013-06-19T13:40:13 | 2013-06-19T13:40:13 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 14,545 | cpp | #include "RrgStore.h"
using namespace SQLVALTYPE;
RrgStore::~RrgStore(void)
{
}
const string tileUnit_T_name="TileUnitArray";
const string PinWire_T_name="pinWireMap";
const string wireStore_T_name="wireStore";
const string tileStroe_T_name="tileStore";
bool RrgStore::rrgStoreIntoDB()
{
sqlTable_sptr rrg_table=creatRrgTable();
loadRrgTable(rrg_table);
sqlTable_sptr wireStore_table=creatWireStoreTable();
loadWireStoreTable(wireStore_table);
sqlTable_sptr tileStore_talbe=createTileStoreTable();
loadTileStoreTable(tileStore_talbe);
creatAndLordTileUnitTable(tileUnit_T_name);
creatAndLoadwireIndexForTT("wireIndexForTTs");
creatAndLoadFanoutStore("fanouts_hopUnit",fanouts);
creatAndLoadSegmentStore("segments_hopUnit",segments);
creatAndLoadPinwireList("PinWireList");
return true;
}
SQLVALTYPE::sqlTable_sptr RrgStore::creatRrgTable()
{
string tableName="rrg";
sqlTable_sptr rrg_table(new SqlTalbe(tableName,sql_int));
SqlColumn_sptr fpga_package(new Sqlcolumn_var_Long("fpga_pachage"));
SqlColumn_sptr tileUnit_table(new Sqlcolumn_var_Short("tileUnit_table"));
SqlColumn_sptr pinWireMap_table(new Sqlcolumn_var_Short("pinWireMap_table"));
SqlColumn_sptr wireStore_tabale(new Sqlcolumn_var_Short("wireStore_table"));
SqlColumn_sptr tileStore_tabale(new Sqlcolumn_var_Short("tileStore_table"));
SqlColumn_sptr fpga_scale_x(new Sqlcolumn_Small("fpga_scale_x"));
SqlColumn_sptr fpga_scale_y(new Sqlcolumn_Small("fpga_scale_y"));
rrg_table->addAColumn(fpga_package);
rrg_table->addAColumn(tileUnit_table);
rrg_table->addAColumn(pinWireMap_table);
rrg_table->addAColumn(wireStore_tabale);
rrg_table->addAColumn(tileStore_tabale);
rrg_table->addAColumn(fpga_scale_x);
rrg_table->addAColumn(fpga_scale_y);
return rrg_table;
}
void RrgStore::loadRrgTable(sqlTable_sptr rrg_tabel)
{
recordType record;
string pakageName=cur_rrg->getfpga()->getpackage();
short fpga_scale_x=cur_rrg->get_fpga_scale().getx();
short fpga_scale_y=cur_rrg->get_fpga_scale().gety();
record.push_back(SqlValue_sptr(cur_factory.makeSQLValVarchar(pakageName)));
record.push_back(SqlValue_sptr(cur_factory.makeSQLValVarchar(tileUnit_T_name)));
record.push_back(SqlValue_sptr(cur_factory.makeSQLValVarchar(PinWire_T_name)));
record.push_back(SqlValue_sptr(cur_factory.makeSQLValVarchar(wireStore_T_name)));
record.push_back(SqlValue_sptr(cur_factory.makeSQLValVarchar(tileStroe_T_name)));
record.push_back(SqlValue_sptr(cur_factory.makeSQLValSmallInt(fpga_scale_x)));
record.push_back(SqlValue_sptr(cur_factory.makeSQLValSmallInt(fpga_scale_y)));
rrg_tabel->pushARecord(record);
rrg_tabel->StoreTableToDB();
}
SQLVALTYPE::sqlTable_sptr RrgStore::creatWireStoreTable()
{
sqlTable_sptr wireStore_table(new SqlTalbe(wireStore_T_name,sql_int));
SqlColumn_sptr wirename(new Sqlcolumn_var_Short("wireName"));
SqlColumn_sptr index(new Sqlcolumn_Small("wire_index"));
SqlColumn_sptr fanouts_l(new Sqlcolumn_int("fanouts_l"));
SqlColumn_sptr fanouts_h(new Sqlcolumn_int("fanouts_h"));
SqlColumn_sptr segments_l(new Sqlcolumn_int("segments_l"));
SqlColumn_sptr segments_h(new Sqlcolumn_int ("segments_h"));
wireStore_table->addAColumn(wirename);
wireStore_table->addAColumn(index);
wireStore_table->addAColumn(fanouts_l);
wireStore_table->addAColumn(fanouts_h);
wireStore_table->addAColumn(segments_l);
wireStore_table->addAColumn(segments_h);
return wireStore_table;
}
void RrgStore::loadWireStoreTable(sqlTable_sptr wireStore_tabel)
{
multimap<string,WireTemplate*>::const_iterator itr;
unsigned index=0;
cout<<"wire store size: "<<cur_rrg->wire_size()<<endl;
for (itr=cur_rrg->wire_begin();itr!=cur_rrg->wire_end();itr++){
wireLUT.insert(make_pair(itr->second,index++));
recordType cur_record;
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValVarchar(itr->first)));
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValSmallInt(itr->second->getIndex())));
pair<unsigned,unsigned> fanouts_pair=fanouts.hopUnit_insert(itr->second->pip_begin(),itr->second->pip_end());
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValInt(fanouts_pair.first)));
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValInt(fanouts_pair.second)));
pair<unsigned,unsigned> segments_pair=segments.hopUnit_insert(itr->second->seg_begin(),itr->second->seg_end());
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValInt(segments_pair.first)));
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValInt(segments_pair.second)));
wireStore_tabel->pushARecord(cur_record);
}
wireStore_tabel->StoreTableToDB();
}
SQLVALTYPE::sqlTable_sptr RrgStore::createTileStoreTable()
{
sqlTable_sptr tileStore_table(new SqlTalbe(tileStroe_T_name,sql_int));
SqlColumn_sptr wireList_l(new Sqlcolumn_int("wireList_l"));
SqlColumn_sptr wireList_h(new Sqlcolumn_int("wireList_h"));
tileStore_table->addAColumn(wireList_l);
tileStore_table->addAColumn(wireList_h);
return tileStore_table;
}
void RrgStore::loadTileStoreTable( sqlTable_sptr tileStore_table )
{
unsigned TT_num=0;
multimap<size_t,TileTemplate*>::const_iterator itr;
for(itr=cur_rrg->tile_begin();itr!=cur_rrg->tile_end();itr++){
vector<WireTemplate*>::const_iterator itr_wire;
unsigned wireIndex_l=wireIndexForTTs.size();
unsigned counter=0;
for(itr_wire=itr->second->begin();itr_wire!=itr->second->end();itr_wire++){
if((*itr_wire)==NULL) wireIndexForTTs.push_back(ILLEGAL_WIRE_INDEX);
else if(wireLUT.count(*itr_wire))
wireIndexForTTs.push_back(wireLUT[*itr_wire]);
else {
cout<<"something wrong!"<<endl;
cout<<(*itr_wire)->getname()<<endl;
system("pause");
}
counter++;
}
unsigned wireIndex_h=wireIndexForTTs.size();
tileLUT.insert(make_pair(itr->second,TT_num++));
recordType cur_record;
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValInt(wireIndex_l)));
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValInt(wireIndex_h)));
tileStore_table->pushARecord(cur_record);
}
tileStore_table->StoreTableToDB_ByStep();
}
void RrgStore::creatAndLoadTT( TileTemplate* tile,string TTName)
{
sqlTable_sptr tile_table(new SqlTalbe(TTName,sql_int));
SqlColumn_sptr wire_index(new Sqlcolumn_int("wire_index"));
tile_table->addAColumn(wire_index);
vector<WireTemplate*>::const_iterator itr;
for(itr=tile->begin();itr!=tile->end();itr++){
recordType cur_record;
SqlValue_sptr cur_index(cur_factory.makeSQLValInt(wireLUT[*itr]));
cur_record.push_back(cur_index);
tile_table->pushARecord(cur_record);
}
tile_table->StoreTableToDB();
}
void RrgStore::creatAndLoadSegmentStore( string tableName,const HopUnitStore& _HU )
{
sqlTable_sptr hu_table(new SqlTalbe(tableName,sql_int));
SqlColumn_sptr hu_x(new Sqlcolumn_tiny("x"));
SqlColumn_sptr hu_y(new Sqlcolumn_tiny("y"));
SqlColumn_sptr hu_i(new Sqlcolumn_Small("i"));
hu_table->addAColumn(hu_x);
hu_table->addAColumn(hu_y);
hu_table->addAColumn(hu_i);
vector<HopUnit>::const_iterator itr;
for(itr=_HU.begin();itr!=_HU.end();itr++)
{
SqlValue_sptr val_x(cur_factory.makSQLValTinyInt(itr->x));
SqlValue_sptr val_y(cur_factory.makSQLValTinyInt(itr->y));
SqlValue_sptr val_i(cur_factory.makeSQLValSmallInt(itr->index));
recordType cur_record;
cur_record.push_back(val_x);
cur_record.push_back(val_y);
cur_record.push_back(val_i);
hu_table->pushARecord(cur_record);
}
hu_table->StoreTableToDB();
}
void RrgStore::creatAndLoadFanoutStore( string tableName,const HopUnitStore& _HU )
{
sqlTable_sptr hu_table(new SqlTalbe(tableName,sql_int));
SqlColumn_sptr hu_i(new Sqlcolumn_Small("i"));
hu_table->addAColumn(hu_i);
vector<HopUnit>::const_iterator itr;
for(itr=_HU.begin();itr!=_HU.end();itr++)
{
SqlValue_sptr val_i(cur_factory.makeSQLValSmallInt(itr->index));
recordType cur_record;
cur_record.push_back(val_i);
hu_table->pushARecord(cur_record);
}
hu_table->StoreTableToDB();
}
void RrgStore::creatAndLoadwireIndexForTT( string tableName)
{
vector<unsigned short> compressed_vec;
vector<unsigned short> ::const_iterator itr;
unsigned short compressed_val=ILLEGAL_WIRE_INDEX;
for(itr=wireIndexForTTs.begin();itr!=wireIndexForTTs.end();++itr){
if(*itr==ILLEGAL_WIRE_INDEX){
++compressed_val;
}
else{
if(compressed_val>ILLEGAL_WIRE_INDEX){
compressed_vec.push_back(compressed_val);
compressed_val=ILLEGAL_WIRE_INDEX;
}
compressed_vec.push_back(*itr);
}
}
if(compressed_val>ILLEGAL_WIRE_INDEX)
compressed_vec.push_back(compressed_val);
cout<<wireIndexForTTs.size()<<" | "<<compressed_vec.size()<<endl;
cout<<compressed_vec.at(323903)<<endl;
sqlTable_sptr wireIndex_table(new SqlTalbe(tableName,sql_int));
int column_num=8;
for(int ii=0;ii<column_num;ii++)
{
char buff[4];
_itoa_s(ii,buff,10);
string post_fix(buff);
wireIndex_table->addAColumn(SqlColumn_sptr(new Sqlcolumn_Small("wireT_index_"+post_fix)));
}
for(itr=compressed_vec.begin();itr!=compressed_vec.end();)
{
recordType cur_record;
for(int jj=0;jj<column_num;jj++){
if(itr!=compressed_vec.end()){// 这里的bug调了一个下午! 序列首位很容易存在错误!
SqlValue_sptr val_A(cur_factory.makeSQLValSmallInt(*itr));
cur_record.push_back(val_A);
itr++;
}
else {
SqlValue_sptr val_B(cur_factory.makeSQLValSmallInt(0));
cur_record.push_back(val_B);
//if(jj==column_num-1)itr++;
}
}
wireIndex_table->pushARecord(cur_record);
}
cout<<" creatAndLoadwireIndexForTT record_vec size: "<<wireIndex_table->record_vec_size()<<endl;
wireIndex_table->StoreTableToDB_ByStepS();
}
void RrgStore::creatAndLordTileUnitTable( string tableName )
{
sqlTable_sptr table(new SqlTalbe(tableName,sql_int));
table->addAColumn(SqlColumn_sptr(new Sqlcolumn_var_Short("tile_name")));
table->addAColumn(SqlColumn_sptr(new Sqlcolumn_Small("TT_index")));
table->addAColumn(SqlColumn_sptr(new Sqlcolumn_int("longWireIndex_l")));
table->addAColumn(SqlColumn_sptr(new Sqlcolumn_int("longWireIndex_h")));
short x=0,y=0;
for(x=0;x<cur_rrg->get_fpga_scale().getx();x++)
for(y=0;y<cur_rrg->get_fpga_scale().gety();y++){
const TileUnit& curTileUnit=cur_rrg->get_tile_by_pos(Point(x,y,0));
string name=curTileUnit.gettilename();
TileTemplate* TT_ptr=curTileUnit.getTileTemplate();
hash_map<short,WireTemplate*>::const_iterator itr,itr_begin,itr_end;
itr_begin=curTileUnit.long_global_nets.begin();
itr_end=curTileUnit.long_global_nets.end();
recordType cur_record;
//SqlValue_sptr tile_name(cur_factory.makeSQLValVarchar(name));
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValVarchar(name)));
if(tileLUT.count(TT_ptr)==0){cout<<"something wrong! "<<__LINE__<<endl;system("pause");}
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValSmallInt(tileLUT[TT_ptr])));
unsigned wireIndex_l=wireIndexForTTs.size();
for(itr=itr_begin;itr!=itr_end;itr++){
if(wireLUT.count(itr->second)==0){cout<<"something wrong! "<<__LINE__<<endl;system("pause");}
wireIndexForTTs.push_back(wireLUT[itr->second]);
}
unsigned wireIndex_h=wireIndexForTTs.size();
//if(x==71&&y==64){
// cout<<"longWireIndex_h-1: "<<wireIndex_h-1<<endl;
// cout<<"wireIndexList "<<wireIndexForTTs.at(wireIndex_h-1)<<endl;
// //cout<<"wireTstore: "<<wireTstore.at(wireIndexForTTs.at(wireIndex_h-1))->getIndex()<<endl;
// system("pause");
//}
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValInt(wireIndex_l)));
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValInt(wireIndex_h)));
table->pushARecord(cur_record);
}
table->StoreTableToDB();
}
void RrgStore::creatAndLoadPinwireList( string tableName )
{
sqlTable_sptr table(new SqlTalbe(tableName,sql_int));
table->addAColumn(SqlColumn_sptr(new Sqlcolumn_var_Short("sitePinName")));
table->addAColumn(SqlColumn_sptr(new Sqlcolumn_var_Short("siteName")));
table->addAColumn(SqlColumn_sptr(new Sqlcolumn_var_Short("pinWireName")));
table->addAColumn(SqlColumn_sptr(new Sqlcolumn_Small("x")));
table->addAColumn(SqlColumn_sptr(new Sqlcolumn_Small("y")));
table->addAColumn(SqlColumn_sptr(new Sqlcolumn_Small("z")));
short x,y;
const vector<sitePinToPinwire>* pinWire_vec=NULL;
for(x=0;x<cur_rrg->get_fpga_scale().getx();x++)
for(y=0;y<cur_rrg->get_fpga_scale().gety();y++){
pinWire_vec=&cur_rrg->getpinwire_vec(x,y);
vector<sitePinToPinwire>::const_iterator itr;
for (itr=pinWire_vec->begin();itr!=pinWire_vec->end();itr++){
recordType cur_record;
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValVarchar(itr->sitePinName)));
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValVarchar(itr->siteName)));
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValVarchar(itr->pinWireName)));
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValSmallInt(x)));
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValSmallInt(y)));
cur_record.push_back(SqlValue_sptr(cur_factory.makeSQLValSmallInt(itr->z)));
table->pushARecord(cur_record);
}
}
table->StoreTableToDB();
}
//
//void RrgStore::creatAndLoadwireIndexForTU( string tableName )
//{
// sqlTable_sptr wireIndex_table(new SqlTalbe(tableName,sql_int));
// wireIndex_table->addAColumn(SqlColumn_sptr(new Sqlcolumn_Small("indexInTile")));
// wireIndex_table->addAColumn(SqlColumn_sptr(new Sqlcolumn_Small("indexForLUT")));
// vector<pair<unsigned short,unsigned short> >::const_iterator itr;
// for(itr=longWireIndexForTUs.begin();itr!=longWireIndexForTUs.end();itr++)
// {
// recordType cur_record;
// SqlValue_sptr val_A(cur_factory.makeSQLValSmallInt(itr->first));
// cur_record.push_back(val_A);
// SqlValue_sptr val_B(cur_factory.makeSQLValSmallInt(itr->second));
// cur_record.push_back(val_B);
// wireIndex_table->pushARecord(cur_record);
// }
// cout<<" creatAndLoadwireIndexForTU record_vec size: "<<wireIndex_table->record_vec_size()<<endl;
// wireIndex_table->StoreTableToDB();
//}
pair<unsigned int,unsigned int> HopUnitStore::hopUnit_insert( const vector<HopUnit> & temp_vec )
{
unsigned int begin_pos=hop_vec.size();
for (vector<HopUnit>::const_iterator itr=temp_vec.begin();itr!=temp_vec.end();itr++){
hop_vec.push_back(*itr);
}
unsigned int end_pos=hop_vec.size();
return make_pair(begin_pos,end_pos);
}
pair<unsigned int,unsigned int> HopUnitStore::hopUnit_insert( cnst_itr itr_begin,cnst_itr itr_end )
{
unsigned int begin_pos=hop_vec.size();
for (vector<HopUnit>::const_iterator itr=itr_begin;itr!=itr_end;itr++){
hop_vec.push_back(*itr);
}
unsigned int end_pos=hop_vec.size();
return make_pair(begin_pos,end_pos);
} | [
"yhm_liang@qq.com"
] | yhm_liang@qq.com |
54967b69eefc435ebfb9f9eac10bdc73e3ead921 | 76a5814b43ffb285e5c02b7b727b1ffeaab60957 | /UnderstandingCommandBasedProgramming/src/Commands/SerialCommunication.cpp | 90834e239c2bda549945ff450765af441767741d | [] | no_license | Team135BlackKnights/2015-Code2 | e73a31c7348f2279718f45a7c1b7e2d8a10d8760 | 90200ff2a8796d863911eafb076b4852388bbe6d | refs/heads/master | 2021-01-02T22:51:09.701959 | 2016-02-01T20:57:50 | 2016-02-01T20:57:50 | 29,403,901 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,160 | cpp | #include <Commands/SerialCommunication.h>
#include "RobotMap.h"
SerialCommunication::SerialCommunication()
{
// Use Requires() here to declare subsystem dependencies
// eg. Requires(chassis);
Requires(serialComs);
}
// Called just before this Command runs the first time
void SerialCommunication::Initialize()
{
SmartDashboard::PutString(SERIAL_RUNNING, "Initialized");
//serialComs->SendData(new char('G'));
}
// Called repeatedly when this Command is scheduled to run
void SerialCommunication::Execute()
{
SmartDashboard::PutString(SERIAL_RUNNING, "Running");
double value = serialComs->WaitForData();
if (value != NO_DATA)
{
mecanumDrive->SetGyroAngle(value);
}
}
// Make this return true when this Command no longer needs to run execute()
bool SerialCommunication::IsFinished()
{
return false;
}
// Called once after isFinished returns true
void SerialCommunication::End()
{
SmartDashboard::PutString(SERIAL_RUNNING, "Ended");
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void SerialCommunication::Interrupted()
{
SmartDashboard::PutString(SERIAL_RUNNING, "Interrupted");
}
| [
"robotics@phm.k12.in.us"
] | robotics@phm.k12.in.us |
a329bc6519f309266d2c1bf97c79b146c16afaf3 | 05bf70a494c15406e5c1f4ccc9b63edaf3871ba6 | /cpp/DirectedGraph.hpp | 78ebf298d156f71d8eecc9d7a37d1f0b006e68da | [
"Apache-2.0"
] | permissive | yohm/sim_exhaustive_m3_PDgame | 545ba86cf6617ecc4bc7a1f53be2e9e1683ed245 | 67b2d1c57174d6a8562488ae661e295f5c46f8c4 | refs/heads/master | 2021-10-30T19:37:35.037716 | 2021-09-14T09:06:28 | 2021-09-14T09:06:28 | 179,042,079 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,304 | hpp | #ifndef DIRECTED_GRAPH_HPP
#define DIRECTED_GRAPH_HPP
#include <iostream>
#include <vector>
#include <map>
#include <stack>
#include <set>
#include <functional>
#include <queue>
#include <algorithm>
typedef std::vector<long> comp_t;
typedef std::vector<comp_t> components_t;
class DirectedGraph {
public:
DirectedGraph(size_t num_nodes);
void AddLink(long from, long to);
bool HasLink(long from, long to) const;
bool Reachable(long from, long to) const;
friend std::ostream &operator<<(std::ostream &os, const DirectedGraph &graph);
void SCCs(components_t& components) const {
ComponentFinder cf(*this);
cf.SCCs(components);
}
std::set<long> TransitionNodes() const;
components_t NonTransitionComponents() const;
components_t SinkSCCs() const; // SCCs that has no outgoing link
template <class T>
void ForEachLink( const T& f) const {
for( long i=0; i<m_num_nodes; i++) {
for( long j: m_links[i]) {
f(i,j);
}
}
}
template <class T> void BFS(long init, const T& f) const {
std::vector<int> visited(m_num_nodes, 0);
std::queue<long> q;
q.push(init);
visited[init] = 1;
while( q.size() > 0 ) {
long i = q.front();
q.pop();
f(i);
for(long j: m_links[i]) {
if(visited[j] == 0) {
visited[j] = 1;
q.push(j);
}
}
}
}
template <class T> void DFS(long init, const T& f) const {
std::vector<int> visited(m_num_nodes, 0);
std::stack<long> s;
s.push(init);
while( s.size() > 0 ) {
long i = s.top();
s.pop();
if( visited[i] > 0 ) { continue; }
visited[i] = 1;
f(i);
for(long j: m_links[i]) {
if(visited[j] == 0) { s.push(j); }
}
}
}
const size_t m_num_nodes;
std::vector<std::vector<long> > m_links;
private:
bool HasSelfLoop(long n) const; // return true if node n has a self-loop
class ComponentFinder {
public:
ComponentFinder(const DirectedGraph &m_g);
void SCCs( components_t& components );
private:
const DirectedGraph& m_g;
long m_t;
std::vector<long> desc;
std::vector<long> low;
std::stack<long> stack;
std::vector<bool> on_stack;
void StrongConnect( long v, components_t& components);
};
};
#endif //DIRECTED_GRAPH_HPP
| [
"yohsuke.murase@gmail.com"
] | yohsuke.murase@gmail.com |
c4d9d5a534e19cfae3b04efc57702c89d75d83fa | 95ae9595dc72dbaceadf42c3b0ac873b2b6b340f | /euler/common/zk_server_monitor.h | ce6426ed3e783268bd5fe8393782ffcf6b7863a4 | [
"BSD-3-Clause",
"Zlib",
"BSD-2-Clause-Views",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | jmzhoulab/euler | b4951006ef215cabfba59c9397302333fffd112f | acf6c0606762335226d3c596ad0b37ece05a89bf | refs/heads/master | 2021-07-11T03:45:30.904836 | 2020-11-04T02:19:54 | 2020-11-04T02:19:54 | 278,325,293 | 0 | 0 | Apache-2.0 | 2020-11-04T02:19:55 | 2020-07-09T09:46:52 | null | UTF-8 | C++ | false | false | 2,344 | h | /* Copyright 2020 Alibaba Group Holding Limited. 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.
==============================================================================*/
#ifndef EULER_COMMON_ZK_SERVER_MONITOR_H_
#define EULER_COMMON_ZK_SERVER_MONITOR_H_
#include <unordered_set>
#include <string>
#include <memory>
#include "zookeeper.h" // NOLINT
#include "euler/common/server_monitor.h"
#include "euler/common/zk_util_cache.h"
namespace euler {
class ZkServerMonitor : public ServerMonitorBase {
friend std::shared_ptr<ZkServerMonitor> GetOrCreate<ZkServerMonitor>(
const std::string &, const std::string &);
public:
~ZkServerMonitor() override;
private:
static void Watcher(zhandle_t *zh, int type, int state, const char *path,
void *data);
static void RootCallback(int rc, const struct Stat *stat, const void *data);
static void RootWatcher(zhandle_t *zk_handle, int type, int state,
const char *path, void *data);
static void ChildCallback(int rc, const struct String_vector *strings,
const void *data);
static void ChildWatcher(zhandle_t *zh, int type, int state,
const char *path, void *data);
static void MetaCallback(int rc, const char *value, int value_len,
const struct Stat *stat, const void *data);
ZkServerMonitor(std::string zk_addr, std::string zk_path)
: zk_addr_(zk_addr), zk_path_(zk_path), zk_handle_(nullptr) { }
bool Initialize() override;
void OnAddChild(const std::string &child);
void OnRemoveChild(const std::string &child);
std::string zk_addr_;
std::string zk_path_;
std::mutex zk_mu_;
zhandle_t *zk_handle_;
std::unordered_set<std::string> children_;
};
} // namespace euler
#endif // EULER_COMMON_ZK_SERVER_MONITOR_H_
| [
"18810543471@163.com"
] | 18810543471@163.com |
4e70c4d3fd4fd644815e0f5ae4b1db3af3409535 | a5d733d9b841a9127dc4a1aad63a3904dbfe0a3d | /0098. Validate Binary Search Tree/main.cpp | 0814d676866dc4d46835a96311006b982ab4c63f | [] | no_license | yeholdon/Ye-s-LeetCode | 207d24a9b3e0804679e101dfeca4c0cc39a107cb | e17125e57ab0664ac39befc6405e4ea2e48051ee | refs/heads/master | 2021-08-09T01:50:17.991260 | 2021-01-18T02:45:53 | 2021-01-18T02:45:53 | 241,823,865 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 145 | cpp | #include <vector>
#include "solution.h"
#include "../catch.hpp"
using std::vector;
TEST_CASE("Validate Binary Search Tree", "[isValidBST]")
{
}
| [
"yeholdon@gmail.com"
] | yeholdon@gmail.com |
74397bf2ece9ff5cdbb98bc38595ccdcf59a13cb | 33a961276497abc1096aca8d0fb7519ddfcb3bdb | /esl/geography/python_module_geography.cpp | 84159a790b8fb4f3ea25890103e81aea2f59ff9d | [
"Apache-2.0"
] | permissive | ShrutiAppiah/ESL | 3a7d8bb7756d28990730a377c6e5e0c3423a7e99 | 069a9afa0150355a1903ddc76fce04f376a6940d | refs/heads/master | 2023-02-25T07:56:54.536007 | 2021-01-27T04:55:15 | 2021-01-27T04:55:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,679 | cpp | /// \file python_module_geography.cpp
///
/// \brief
///
/// \authors Maarten P. Scholl
/// \date 2020-11-09
/// \copyright Copyright 2017-2020 The Institute for New Economic Thinking,
/// Oxford Martin School, University of Oxford
///
/// 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.
///
/// You may obtain instructions to fulfill the attribution
/// requirements in CITATION.cff
///
#include <esl/geography/python_module_geography.hpp>
#include <esl/geography/countries.hpp>
#ifdef WITH_PYTHON
#include <string>
#define BOOST_BIND_GLOBAL_PLACEHOLDERS
#include <boost/python.hpp>
using namespace boost::python;
///
/// \brief
/// \param c
/// \return
std::string python_country_code(const esl::geography::iso_3166_1_alpha_2 &c)
{
return (std::string() + c.code[0]) + c.code[1];
}
BOOST_PYTHON_MODULE(_geography)
{
class_<esl::geography::iso_3166_1_alpha_2>("iso_3166_1_alpha_2")
.add_property("code", python_country_code)
.def("__repr__", &esl::geography::iso_3166_1_alpha_2::representation)
.def("__str__", &esl::geography::iso_3166_1_alpha_2::representation)
;
scope().attr("AE") = esl::geography::countries::AE;
scope().attr("AF") = esl::geography::countries::AF;
scope().attr("AG") = esl::geography::countries::AG;
scope().attr("AI") = esl::geography::countries::AI;
scope().attr("AL") = esl::geography::countries::AL;
scope().attr("AM") = esl::geography::countries::AM;
scope().attr("AO") = esl::geography::countries::AO;
scope().attr("AQ") = esl::geography::countries::AQ;
scope().attr("AR") = esl::geography::countries::AR;
scope().attr("AS") = esl::geography::countries::AS;
scope().attr("AT") = esl::geography::countries::AT;
scope().attr("AU") = esl::geography::countries::AU;
scope().attr("AW") = esl::geography::countries::AW;
scope().attr("AX") = esl::geography::countries::AX;
scope().attr("AZ") = esl::geography::countries::AZ;
scope().attr("BA") = esl::geography::countries::BA;
scope().attr("BB") = esl::geography::countries::BB;
scope().attr("BD") = esl::geography::countries::BD;
scope().attr("BE") = esl::geography::countries::BE;
scope().attr("BF") = esl::geography::countries::BF;
scope().attr("BG") = esl::geography::countries::BG;
scope().attr("BH") = esl::geography::countries::BH;
scope().attr("BI") = esl::geography::countries::BI;
scope().attr("BJ") = esl::geography::countries::BJ;
scope().attr("BL") = esl::geography::countries::BL;
scope().attr("BM") = esl::geography::countries::BM;
scope().attr("BN") = esl::geography::countries::BN;
scope().attr("BO") = esl::geography::countries::BO;
scope().attr("BQ") = esl::geography::countries::BQ;
scope().attr("BR") = esl::geography::countries::BR;
scope().attr("BS") = esl::geography::countries::BS;
scope().attr("BT") = esl::geography::countries::BT;
scope().attr("BV") = esl::geography::countries::BV;
scope().attr("BW") = esl::geography::countries::BW;
scope().attr("BY") = esl::geography::countries::BY;
scope().attr("BZ") = esl::geography::countries::BZ;
scope().attr("CA") = esl::geography::countries::CA;
scope().attr("CC") = esl::geography::countries::CC;
scope().attr("CD") = esl::geography::countries::CD;
scope().attr("CF") = esl::geography::countries::CF;
scope().attr("CG") = esl::geography::countries::CG;
scope().attr("CH") = esl::geography::countries::CH;
scope().attr("CI") = esl::geography::countries::CI;
scope().attr("CK") = esl::geography::countries::CK;
scope().attr("CL") = esl::geography::countries::CL;
scope().attr("CM") = esl::geography::countries::CM;
scope().attr("CN") = esl::geography::countries::CN;
scope().attr("CO") = esl::geography::countries::CO;
scope().attr("CR") = esl::geography::countries::CR;
scope().attr("CU") = esl::geography::countries::CU;
scope().attr("CV") = esl::geography::countries::CV;
scope().attr("CW") = esl::geography::countries::CW;
scope().attr("CX") = esl::geography::countries::CX;
scope().attr("CY") = esl::geography::countries::CY;
scope().attr("CZ") = esl::geography::countries::CZ;
scope().attr("DE") = esl::geography::countries::DE;
scope().attr("DJ") = esl::geography::countries::DJ;
scope().attr("DK") = esl::geography::countries::DK;
scope().attr("DM") = esl::geography::countries::DM;
scope().attr("DO") = esl::geography::countries::DO;
scope().attr("DZ") = esl::geography::countries::DZ;
scope().attr("EC") = esl::geography::countries::EC;
scope().attr("EE") = esl::geography::countries::EE;
scope().attr("EG") = esl::geography::countries::EG;
scope().attr("EH") = esl::geography::countries::EH;
scope().attr("ER") = esl::geography::countries::ER;
scope().attr("ES") = esl::geography::countries::ES;
scope().attr("ET") = esl::geography::countries::ET;
scope().attr("FI") = esl::geography::countries::FI;
scope().attr("FJ") = esl::geography::countries::FJ;
scope().attr("FK") = esl::geography::countries::FK;
scope().attr("FM") = esl::geography::countries::FM;
scope().attr("FO") = esl::geography::countries::FO;
scope().attr("FR") = esl::geography::countries::FR;
scope().attr("GA") = esl::geography::countries::GA;
scope().attr("GB") = esl::geography::countries::GB;
scope().attr("GD") = esl::geography::countries::GD;
scope().attr("GE") = esl::geography::countries::GE;
scope().attr("GF") = esl::geography::countries::GF;
scope().attr("GG") = esl::geography::countries::GG;
scope().attr("GH") = esl::geography::countries::GH;
scope().attr("GI") = esl::geography::countries::GI;
scope().attr("GL") = esl::geography::countries::GL;
scope().attr("GM") = esl::geography::countries::GM;
scope().attr("GN") = esl::geography::countries::GN;
scope().attr("GP") = esl::geography::countries::GP;
scope().attr("GQ") = esl::geography::countries::GQ;
scope().attr("GR") = esl::geography::countries::GR;
scope().attr("GS") = esl::geography::countries::GS;
scope().attr("GT") = esl::geography::countries::GT;
scope().attr("GU") = esl::geography::countries::GU;
scope().attr("GW") = esl::geography::countries::GW;
scope().attr("GY") = esl::geography::countries::GY;
scope().attr("HK") = esl::geography::countries::HK;
scope().attr("HM") = esl::geography::countries::HM;
scope().attr("HN") = esl::geography::countries::HN;
scope().attr("HR") = esl::geography::countries::HR;
scope().attr("HT") = esl::geography::countries::HT;
scope().attr("HU") = esl::geography::countries::HU;
scope().attr("ID") = esl::geography::countries::ID;
scope().attr("IE") = esl::geography::countries::IE;
scope().attr("IL") = esl::geography::countries::IL;
scope().attr("IM") = esl::geography::countries::IM;
scope().attr("IN") = esl::geography::countries::IN;
scope().attr("IO") = esl::geography::countries::IO;
scope().attr("IQ") = esl::geography::countries::IQ;
scope().attr("IR") = esl::geography::countries::IR;
scope().attr("IS") = esl::geography::countries::IS;
scope().attr("IT") = esl::geography::countries::IT;
scope().attr("JE") = esl::geography::countries::JE;
scope().attr("JM") = esl::geography::countries::JM;
scope().attr("JO") = esl::geography::countries::JO;
scope().attr("JP") = esl::geography::countries::JP;
scope().attr("KE") = esl::geography::countries::KE;
scope().attr("KG") = esl::geography::countries::KG;
scope().attr("KH") = esl::geography::countries::KH;
scope().attr("KI") = esl::geography::countries::KI;
scope().attr("KM") = esl::geography::countries::KM;
scope().attr("KN") = esl::geography::countries::KN;
scope().attr("KP") = esl::geography::countries::KP;
scope().attr("KR") = esl::geography::countries::KR;
scope().attr("KW") = esl::geography::countries::KW;
scope().attr("KY") = esl::geography::countries::KY;
scope().attr("KZ") = esl::geography::countries::KZ;
scope().attr("LA") = esl::geography::countries::LA;
scope().attr("LB") = esl::geography::countries::LB;
scope().attr("LC") = esl::geography::countries::LC;
scope().attr("LI") = esl::geography::countries::LI;
scope().attr("LK") = esl::geography::countries::LK;
scope().attr("LR") = esl::geography::countries::LR;
scope().attr("LS") = esl::geography::countries::LS;
scope().attr("LT") = esl::geography::countries::LT;
scope().attr("LU") = esl::geography::countries::LU;
scope().attr("LV") = esl::geography::countries::LV;
scope().attr("LY") = esl::geography::countries::LY;
scope().attr("MA") = esl::geography::countries::MA;
scope().attr("MC") = esl::geography::countries::MC;
scope().attr("MD") = esl::geography::countries::MD;
scope().attr("ME") = esl::geography::countries::ME;
scope().attr("MF") = esl::geography::countries::MF;
scope().attr("MG") = esl::geography::countries::MG;
scope().attr("MH") = esl::geography::countries::MH;
scope().attr("MK") = esl::geography::countries::MK;
scope().attr("ML") = esl::geography::countries::ML;
scope().attr("MM") = esl::geography::countries::MM;
scope().attr("MN") = esl::geography::countries::MN;
scope().attr("MO") = esl::geography::countries::MO;
scope().attr("MP") = esl::geography::countries::MP;
scope().attr("MQ") = esl::geography::countries::MQ;
scope().attr("MR") = esl::geography::countries::MR;
scope().attr("MS") = esl::geography::countries::MS;
scope().attr("MT") = esl::geography::countries::MT;
scope().attr("MU") = esl::geography::countries::MU;
scope().attr("MV") = esl::geography::countries::MV;
scope().attr("MW") = esl::geography::countries::MW;
scope().attr("MX") = esl::geography::countries::MX;
scope().attr("MY") = esl::geography::countries::MY;
scope().attr("MZ") = esl::geography::countries::MZ;
scope().attr("NA") = esl::geography::countries::NA;
scope().attr("NC") = esl::geography::countries::NC;
scope().attr("NE") = esl::geography::countries::NE;
scope().attr("NF") = esl::geography::countries::NF;
scope().attr("NG") = esl::geography::countries::NG;
scope().attr("NI") = esl::geography::countries::NI;
scope().attr("NL") = esl::geography::countries::NL;
scope().attr("NO") = esl::geography::countries::NO;
scope().attr("NP") = esl::geography::countries::NP;
scope().attr("NR") = esl::geography::countries::NR;
scope().attr("NU") = esl::geography::countries::NU;
scope().attr("NZ") = esl::geography::countries::NZ;
scope().attr("OM") = esl::geography::countries::OM;
scope().attr("PA") = esl::geography::countries::PA;
scope().attr("PE") = esl::geography::countries::PE;
scope().attr("PF") = esl::geography::countries::PF;
scope().attr("PG") = esl::geography::countries::PG;
scope().attr("PH") = esl::geography::countries::PH;
scope().attr("PK") = esl::geography::countries::PK;
scope().attr("PL") = esl::geography::countries::PL;
scope().attr("PM") = esl::geography::countries::PM;
scope().attr("PN") = esl::geography::countries::PN;
scope().attr("PR") = esl::geography::countries::PR;
scope().attr("PS") = esl::geography::countries::PS;
scope().attr("PT") = esl::geography::countries::PT;
scope().attr("PW") = esl::geography::countries::PW;
scope().attr("PY") = esl::geography::countries::PY;
scope().attr("QA") = esl::geography::countries::QA;
scope().attr("RE") = esl::geography::countries::RE;
scope().attr("RO") = esl::geography::countries::RO;
scope().attr("RS") = esl::geography::countries::RS;
scope().attr("RU") = esl::geography::countries::RU;
scope().attr("RW") = esl::geography::countries::RW;
scope().attr("SA") = esl::geography::countries::SA;
scope().attr("SB") = esl::geography::countries::SB;
scope().attr("SC") = esl::geography::countries::SC;
scope().attr("SD") = esl::geography::countries::SD;
scope().attr("SE") = esl::geography::countries::SE;
scope().attr("SG") = esl::geography::countries::SG;
scope().attr("SH") = esl::geography::countries::SH;
scope().attr("SI") = esl::geography::countries::SI;
scope().attr("SJ") = esl::geography::countries::SJ;
scope().attr("SK") = esl::geography::countries::SK;
scope().attr("SL") = esl::geography::countries::SL;
scope().attr("SM") = esl::geography::countries::SM;
scope().attr("SN") = esl::geography::countries::SN;
scope().attr("SO") = esl::geography::countries::SO;
scope().attr("SR") = esl::geography::countries::SR;
scope().attr("SS") = esl::geography::countries::SS;
scope().attr("ST") = esl::geography::countries::ST;
scope().attr("SV") = esl::geography::countries::SV;
scope().attr("SX") = esl::geography::countries::SX;
scope().attr("SY") = esl::geography::countries::SY;
scope().attr("SZ") = esl::geography::countries::SZ;
scope().attr("TC") = esl::geography::countries::TC;
scope().attr("TD") = esl::geography::countries::TD;
scope().attr("TF") = esl::geography::countries::TF;
scope().attr("TG") = esl::geography::countries::TG;
scope().attr("TH") = esl::geography::countries::TH;
scope().attr("TJ") = esl::geography::countries::TJ;
scope().attr("TK") = esl::geography::countries::TK;
scope().attr("TL") = esl::geography::countries::TL;
scope().attr("TM") = esl::geography::countries::TM;
scope().attr("TN") = esl::geography::countries::TN;
scope().attr("TO") = esl::geography::countries::TO;
scope().attr("TR") = esl::geography::countries::TR;
scope().attr("TT") = esl::geography::countries::TT;
scope().attr("TV") = esl::geography::countries::TV;
scope().attr("TW") = esl::geography::countries::TW;
scope().attr("TZ") = esl::geography::countries::TZ;
scope().attr("UA") = esl::geography::countries::UA;
scope().attr("UG") = esl::geography::countries::UG;
scope().attr("UM") = esl::geography::countries::UM;
scope().attr("US") = esl::geography::countries::US;
scope().attr("UY") = esl::geography::countries::UY;
scope().attr("UZ") = esl::geography::countries::UZ;
scope().attr("VA") = esl::geography::countries::VA;
scope().attr("VC") = esl::geography::countries::VC;
scope().attr("VE") = esl::geography::countries::VE;
scope().attr("VG") = esl::geography::countries::VG;
scope().attr("VI") = esl::geography::countries::VI;
scope().attr("VN") = esl::geography::countries::VN;
scope().attr("VU") = esl::geography::countries::VU;
scope().attr("WF") = esl::geography::countries::WF;
scope().attr("WS") = esl::geography::countries::WS;
scope().attr("YE") = esl::geography::countries::YE;
scope().attr("YT") = esl::geography::countries::YT;
scope().attr("ZA") = esl::geography::countries::ZA;
scope().attr("ZM") = esl::geography::countries::ZM;
scope().attr("ZW") = esl::geography::countries::ZW;
}
#endif
| [
"scholl.maarten@gmail.com"
] | scholl.maarten@gmail.com |
84d1e2a59dacf14c5e1a6820eeb235dd328106dc | 7ec327e08a35fa7ba13e64db417475eed8b258fb | /controllers/ros_custom/include/webots_ros/receiver_get_emitter_directionRequest.h | 4ae97cc0b5dca4c41fe3dde6e922ad4575569c5b | [] | no_license | Federico-Ciuffardi/webots_benchmark | accb69213098b534011c6ddfcd466a8ca1d466b5 | 0c2c2e464cfdc1b0a021e79b7f338884f68903b6 | refs/heads/master | 2023-04-20T01:30:39.314603 | 2021-05-13T19:25:21 | 2021-05-13T19:25:21 | 360,763,711 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,141 | h | /*
* Copyright 1996-2020 Cyberbotics Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WEBOTS_ROS_MESSAGE_RECEIVER_GET_EMITTER_DIRECTIONREQUEST_H
#define WEBOTS_ROS_MESSAGE_RECEIVER_GET_EMITTER_DIRECTIONREQUEST_H
#include <string>
#include <vector>
#include <map>
#include "ros/types.h"
#include "ros/serialization.h"
#include "ros/builtin_message_traits.h"
#include "ros/message_operations.h"
namespace webots_ros
{
template <class ContainerAllocator>
struct receiver_get_emitter_directionRequest_
{
typedef receiver_get_emitter_directionRequest_<ContainerAllocator> Type;
receiver_get_emitter_directionRequest_()
: ask(0) {
}
receiver_get_emitter_directionRequest_(const ContainerAllocator& _alloc)
: ask(0) {
}
typedef uint8_t _ask_type;
_ask_type ask;
typedef boost::shared_ptr< ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> const> ConstPtr;
boost::shared_ptr<std::map<std::string, std::string> > __connection_header;
};
typedef ::webots_ros::receiver_get_emitter_directionRequest_<std::allocator<void> > receiver_get_emitter_directionRequest;
typedef boost::shared_ptr< ::webots_ros::receiver_get_emitter_directionRequest > receiver_get_emitter_directionRequestPtr;
typedef boost::shared_ptr< ::webots_ros::receiver_get_emitter_directionRequest const> receiver_get_emitter_directionRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace webots_ros
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/groovy/share/std_msgs/msg'], 'webots_ros
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> >
{
static const char* value()
{
return "cad5a90bedce22b568c949b40e9cc6e0";
}
static const char* value(const ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xf9df5232b65af94fULL;
static const uint64_t static_value2 = 0x73f79fe6d84301bbULL;
};
template<class ContainerAllocator>
struct DataType< ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> >
{
static const char* value()
{
return "webots_ros/receiver_get_emitter_directionRequest";
}
static const char* value(const ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> >
{
static const char* value()
{
return "uint8 ask\n\\n\
\n\
";
}
static const char* value(const ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.ask);
}
ROS_DECLARE_ALLINONE_SERIALIZER;
};
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::webots_ros::receiver_get_emitter_directionRequest_<ContainerAllocator>& v)
{
s << indent << "ask: ";
Printer<uint8_t>::stream(s, indent + " ", v.ask);
}
};
} // namespace message_operations
} // namespace ros
#endif // WEBOTS_ROS_MESSAGE_RECEIVER_GET_EMITTER_DIRECTIONREQUEST_H
| [
"federico.ciuffardi@outlook.com"
] | federico.ciuffardi@outlook.com |
ef82c518fce2ed12a53e3eef205408a849f32448 | 42b2facd9452035086d8829ba4113350209ad65f | /clock.cpp | ab975eeeb5867e0cfb21b682cce9b21c433a8296 | [] | no_license | Danicast-c/Cache_Coherence | 668b2f576cf8c6b630d0625b4263591ecbce8747 | 0ded65c74478aa4dde60c8e9799746f804445df3 | refs/heads/master | 2020-07-26T05:35:23.097597 | 2019-09-15T16:10:44 | 2019-09-15T16:10:44 | 208,551,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 131 | cpp | //
// Created by Daniel Castro on 2019-08-21.
//
#include "clock.h"
clock::clock() = default;
void clock::tick() {clk = !clk;}
| [
"daniel.esteban.8@hotmail.com"
] | daniel.esteban.8@hotmail.com |
5795f9770c6e8213aaaede08862817c9cc23cfae | 45c380f99b2e297455ee7de631b1d5ca947d6aeb | /programming_assignment_3/prog_assign_3-1.cpp | 210065d9fa6a218108a3b50b4b41fec6915a9141 | [] | no_license | kkretzer/design_and_analysis_of_algorithms_2 | 114e562e3c9fd791430991e634437af8f754998c | 58e6a0d1f493c4c27cc6f0bf1db40fb8ae1e178a | refs/heads/master | 2016-09-09T21:00:21.185454 | 2013-01-24T13:17:27 | 2013-01-24T13:17:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,149 | cpp | #include <iostream>
#include <fstream>
#include <vector>
struct item {
unsigned int value;
unsigned int weight;
};
int main(int argc, char** argv)
{
std::ifstream input("knapsack1.txt");
unsigned int knapsack_size, num_items;
unsigned int value, weight;
std::vector<item> items;
items.push_back({0,0}); // array 'A' has a dummy first entry, keep this in sync
input >> knapsack_size >> num_items;
unsigned int A[num_items+1][knapsack_size+1];
for (unsigned int x = 0; x <= knapsack_size; ++x) {
A[0][x] = 0;
}
while (input >> value >> weight) {
items.push_back({value, weight});
}
for (unsigned int i = 1; i <= num_items; ++i) {
for (unsigned int x = 0; x <= knapsack_size; ++x) {
unsigned int without_this_item = A[i-1][x];
unsigned int with_this_item = x >= items[i].weight ? A[i-1][x-items[i].weight] + items[i].value : 0;
A[i][x] = without_this_item > with_this_item ? without_this_item : with_this_item;
}
}
std::cout << "optimal solution is " << A[num_items][knapsack_size] << std::endl;
return 0;
}
| [
"kurt.kretzer@gmail.com"
] | kurt.kretzer@gmail.com |
552c19ca5e3a0b72f01f714a6af4abf4b0635321 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/eb/bc9102a41b3fbf/main.cpp | 213ce5d9582df15ea0b4ca4691a832b07e3bf306 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 545 | cpp | #include <iostream>
auto g() {
class Evil {
int V;
public:
Evil(int i) : V(i) {}
const int &get() const { return V; }
};
static Evil e(42); // When does this initialization take place?
struct I { Evil &f() { return e; } };
return I();
}
void f() {
// Remember, decltype()'s operand is unevaluated, so g() is never called.
typedef decltype(g()) HiddenInnerType;
HiddenInnerType HIT;
std::cout << HIT.f().get(); // Call I::f() without ever executing g()
}
int main() {
f();
} | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
46e885ad78814b19e531c5227f8fd2001cf20f8a | 717d5d687221c642bb1f74a276976033499ab453 | /middle-end-optis/dominance/src/lib/digraph-order.hh | d83e22b80856b90747956ad1ae92fe24b156e816 | [
"MIT"
] | permissive | obs145628/cle | 1dbb4f9c99366cb2376c10a2115312f7443b9879 | 4a4a18b2ab5a6fbf26629f6845147541edabd7c9 | refs/heads/master | 2023-02-08T00:21:54.944759 | 2020-12-30T14:17:41 | 2020-12-30T14:17:41 | 288,396,897 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 395 | hh | #pragma once
#include "digraph.hh"
// Compute a DFS ordering of the vertices
// Pre-order: visit vertex before it's successors
// Post-order: visit vertex after its successors
// Reverse post-order: reverse order of post-order
std::vector<std::size_t> preorder(const Digraph &g);
std::vector<std::size_t> postorder(const Digraph &g);
std::vector<std::size_t> rev_postorder(const Digraph &g);
| [
"obs145628@gmail.com"
] | obs145628@gmail.com |
9cd1ed7ec37474c10252f43dc931a2d88103b2fe | 0269e655fd4414a50c67cc949be42a7b7f33f143 | /cpp/Smoothing.cpp | 53cd84c7583edc8a05aa1674c015cb85609b7a1a | [] | no_license | 8018/opencvdemo | caf9d16b95c327e8516bbd40a7d03937374d0e53 | 9fc90c505770957d902039e6edf4d32e2ab375dc | refs/heads/master | 2023-03-06T03:59:22.951612 | 2021-02-16T09:08:42 | 2021-02-16T09:08:42 | 268,398,229 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,020 | cpp | /**
* file Smoothing.cpp
* brief Sample code for simple filters
* author OpenCV team
*/
#include <iostream>
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
using namespace std;
using namespace cv;
/// Global Variables
int DELAY_CAPTION = 1500;
int DELAY_BLUR = 100;
int MAX_KERNEL_LENGTH = 31;
Mat src; Mat dst;
char window_name[] = "Smoothing Demo";
/// Function headers
int display_caption( const char* caption );
int display_dst( int delay );
/**
* function main
*/
int main( int argc, char ** argv )
{
namedWindow( window_name, WINDOW_AUTOSIZE );
src = imread("../../Resources/anita.png", IMREAD_COLOR);
if (src.empty())
{
printf(" Error opening image\n");
printf(" Usage:\n %s [image_name-- default lena.jpg] \n", argv[0]);
return EXIT_FAILURE;
}
if( display_caption( "Original Image" ) != 0 )
{
return 0;
}
dst = src.clone();
if( display_dst( DELAY_CAPTION ) != 0 )
{
return 0;
}
/// Applying Homogeneous blur
if( display_caption( "Homogeneous Blur" ) != 0 )
{
return 0;
}
//![blur]
for ( int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2 )
{
blur( src, dst, Size( i, i ), Point(-1,-1) );
if( display_dst( DELAY_BLUR ) != 0 )
{
return 0;
}
}
//![blur]
/// Applying Gaussian blur
if( display_caption( "Gaussian Blur" ) != 0 )
{
return 0;
}
//![gaussianblur]
for ( int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2 )
{
GaussianBlur( src, dst, Size( i, i ), 0, 0 );
if( display_dst( DELAY_BLUR ) != 0 )
{
return 0;
}
}
//![gaussianblur]
/// Applying Median blur
if( display_caption( "Median Blur" ) != 0 )
{
return 0;
}
//![medianblur]
for ( int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2 )
{
medianBlur ( src, dst, i );
if( display_dst( DELAY_BLUR ) != 0 )
{
return 0;
}
}
//![medianblur]
/// Applying Bilateral Filter
if( display_caption( "Bilateral Blur" ) != 0 )
{
return 0;
}
//![bilateralfilter]
for ( int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2 )
{
bilateralFilter ( src, dst, i, i*2, i/2 );
if( display_dst( DELAY_BLUR ) != 0 )
{
return 0;
}
}
//![bilateralfilter]
/// Done
display_caption( "Done!" );
return 0;
}
/**
* @function display_caption
*/
int display_caption( const char* caption )
{
dst = Mat::zeros( src.size(), src.type() );
putText( dst, caption,
Point( src.cols/4, src.rows/2),
FONT_HERSHEY_COMPLEX, 1, Scalar(255, 255, 255) );
return display_dst(DELAY_CAPTION);
}
/**
* @function display_dst
*/
int display_dst( int delay )
{
imshow( window_name, dst );
int c = waitKey ( delay );
if( c >= 0 ) { return -1; }
return 0;
}
| [
"liuxiangfei29@gmail.com"
] | liuxiangfei29@gmail.com |
d6070f946eef4d5173b7e77f7d2b1c80ff097957 | ad3bd50df9c91a086f6108a1c707b18609842940 | /Utilities/src/.svn/text-base/BBPurity.cc.svn-base | 16b1ca1dfea32485455ccd5f7ce32e172165e630 | [] | no_license | igormarfin/MSSMHbb | 2889f6f3e45b6e045839e8961aa872d49cfbc429 | f690baef0c1b058bb2b7b786ebab1c203f8bff8b | refs/heads/master | 2020-06-03T04:47:12.422517 | 2013-09-12T18:50:18 | 2013-09-12T18:50:18 | 12,791,478 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,389 | #include "Analysis/Utilities/interface/BBPurity.h"
BBPurity::BBPurity(TString fileName) {
TFile * file = new TFile(fileName);
taggers[0] = "TCHPT";
taggers[1] = "TCHP6";
taggers[2] = "CSVT";
taggers[3] = "SSVHPT";
categories[0] = "Xbb";
categories[1] = "bXb";
categories[2] = "bbX";
btagConfigurations[0][0] = "00";
btagConfigurations[0][1] = "10";
btagConfigurations[0][2] = "20";
btagConfigurations[0][3] = "01";
btagConfigurations[0][4] = "11";
btagConfigurations[0][5] = "21";
btagConfigurations[1][0] = "00";
btagConfigurations[1][1] = "10";
btagConfigurations[1][2] = "20";
btagConfigurations[1][3] = "01";
btagConfigurations[1][4] = "11";
btagConfigurations[1][5] = "21";
btagConfigurations[2][0] = "Sum0";
btagConfigurations[2][1] = "Sum1";
btagConfigurations[2][2] = "Sum2";
btagConfigurations[2][3] = "Sum0";
btagConfigurations[2][4] = "Sum1";
btagConfigurations[2][5] = "Sum2";
for (int itagger=0; itagger<4; ++itagger) {
for (int icat=0; icat<3; ++icat) {
for (int ibconf=0; ibconf<6; ++ibconf) {
TString funcName = "bb_" + taggers[itagger] + "_" + categories[icat] + "_" + btagConfigurations[icat][ibconf];
func[itagger][icat][ibconf] = (TF1*)file->Get(funcName);
}
}
}
}
BBPurity::~BBPurity() {
}
float BBPurity::getBBPurity(int tagger, int categ, float dijetMass, int n1, int n2) {
int iconf = 0;
if (categ==2) { // bbX
int sum = n1 + n2;
if (sum<2)
iconf = 0;
else if (sum<3)
iconf = 1;
else
iconf = 2;
}
else { // bXb or Xbb
int T2 = 0;
if (n2>1)
T2 = 3;
iconf = n1 + T2;
}
double xminD = 0;
double xmaxD = 500;
func[tagger][categ][iconf]->GetRange(xminD,xmaxD);
float xmin = float(xminD);
float xmax = float(xmaxD);
float non2bb = 0;
if (dijetMass<xmin)
non2bb = func[tagger][categ][iconf]->Eval(xmin);
else if (dijetMass>xmax)
non2bb = func[tagger][categ][iconf]->Eval(xmax);
else
non2bb = func[tagger][categ][iconf]->Eval(dijetMass);
if (non2bb<0) non2bb = 0;
float purity = 1/(1+non2bb);
return purity;
}
float BBPurity::getBBPurity(int tagger, int categ, float dijetMass, float svMass1, float svMass2) {
int n1 = getSVMassBin(svMass1);
int n2 = getSVMassBin(svMass2);
float purity = getBBPurity(tagger, categ, dijetMass, n1, n2);
return purity;
}
| [
"marfin@desy-cms013.desy.de"
] | marfin@desy-cms013.desy.de | |
bc058c24be1d2b26b83c82844c7f8d8c0c6733b9 | 27a87f65a8cf5f3fb0638b1eb913d2dbee6c6a93 | /ClassCode/9.IIC_2/Arduino_L475/src/main.cpp | 9777a3f063fbf63a7e1d3fe789abe0133cc4b6b6 | [] | no_license | breakeryu/Summer_training_course_2021_07 | e13d5039ed1516216a508ae785483fe6569dad8d | 93dc9d78537fbf576c70e23597d518d86a29d48b | refs/heads/main | 2023-08-28T12:31:35.491845 | 2021-10-19T04:36:48 | 2021-10-19T04:36:48 | 392,227,454 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 578 | cpp | #include <Arduino.h>
#include "iic/icm20608.h"
#include "Wire.h"
void setup() {
Serial.begin(9600);
ICM20608_Init();
delay(1000);
}
void loop() {
ICM20608_TestDemo();
delay(500);
}
/*
我们在使用IIC一类的接口传感器,往往可以在arduino框架下找到前人做好的传感器驱动,可以直接调用。
今天演示的光强度和接近传感器一体的这款AP3216传感器就是如此。需要调整的部分是IIC的初始化部分,调整了
输入的接口部分,然后其他的就如同example中的例子就可以。
*/
| [
"35825642+breakeryu@users.noreply.github.com"
] | 35825642+breakeryu@users.noreply.github.com |
021f6fc27e8377371237e237c10272989db32018 | 70ad3badf3fa6e2edf1889d8640f25a7ec0d9db1 | /ros_catkin_ws/devel_isolated/tf2_msgs/include/tf2_msgs/LookupTransformFeedback.h | e1a79e488f6f81081158935b019bae26403c0208 | [] | no_license | MathieuHwei/OldGaitMaven | 758a937dfda2cf4f1aee266dbbf682ef34989199 | 873f7d9089c5d1c0772bd3447e2b0a31dac68b70 | refs/heads/main | 2023-06-17T18:40:06.230823 | 2021-07-19T23:08:20 | 2021-07-19T23:08:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,236 | h | // Generated by gencpp from file tf2_msgs/LookupTransformFeedback.msg
// DO NOT EDIT!
#ifndef TF2_MSGS_MESSAGE_LOOKUPTRANSFORMFEEDBACK_H
#define TF2_MSGS_MESSAGE_LOOKUPTRANSFORMFEEDBACK_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace tf2_msgs
{
template <class ContainerAllocator>
struct LookupTransformFeedback_
{
typedef LookupTransformFeedback_<ContainerAllocator> Type;
LookupTransformFeedback_()
{
}
LookupTransformFeedback_(const ContainerAllocator& _alloc)
{
(void)_alloc;
}
typedef boost::shared_ptr< ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> const> ConstPtr;
}; // struct LookupTransformFeedback_
typedef ::tf2_msgs::LookupTransformFeedback_<std::allocator<void> > LookupTransformFeedback;
typedef boost::shared_ptr< ::tf2_msgs::LookupTransformFeedback > LookupTransformFeedbackPtr;
typedef boost::shared_ptr< ::tf2_msgs::LookupTransformFeedback const> LookupTransformFeedbackConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace tf2_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'tf2_msgs': ['/home/pi/ros_catkin_ws/src/tf2/tf2_msgs/msg', '/home/pi/ros_catkin_ws/devel_isolated/tf2_msgs/share/tf2_msgs/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> >
{
static const char* value()
{
return "d41d8cd98f00b204e9800998ecf8427e";
}
static const char* value(const ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xd41d8cd98f00b204ULL;
static const uint64_t static_value2 = 0xe9800998ecf8427eULL;
};
template<class ContainerAllocator>
struct DataType< ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> >
{
static const char* value()
{
return "tf2_msgs/LookupTransformFeedback";
}
static const char* value(const ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> >
{
static const char* value()
{
return "# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\
\n\
";
}
static const char* value(const ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream&, T)
{}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct LookupTransformFeedback_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream&, const std::string&, const ::tf2_msgs::LookupTransformFeedback_<ContainerAllocator>&)
{}
};
} // namespace message_operations
} // namespace ros
#endif // TF2_MSGS_MESSAGE_LOOKUPTRANSFORMFEEDBACK_H
| [
"giahuy050201@gmail.com"
] | giahuy050201@gmail.com |
a719167c91975468f702ac1244cdf9ccab761b67 | 18a3f93e4b94f4f24ff17280c2820497e019b3db | /geant4/QGSP_BIC_HP.hh | fe1ffc4b1aa6c2a5749550d41e8bdfa3b0bc6496 | [] | no_license | jjzhang166/BOSS_ExternalLibs | 0e381d8420cea17e549d5cae5b04a216fc8a01d7 | 9b3b30f7874ed00a582aa9526c23ca89678bf796 | refs/heads/master | 2023-03-15T22:24:21.249109 | 2020-11-22T15:11:45 | 2020-11-22T15:11:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,552 | hh | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// $Id: QGSP_BIC_HP.hh,v 1.1 2006/11/24 16:31:35 gunter Exp $
// GEANT4 tag $Name: geant4-09-03-patch-01 $
//
//---------------------------------------------------------------------------
//
// ClassName: QGSP_BIC_HP
//
// Author: 2006 G.Folger
//
// based on QGSP_BIC
// Modified:
//
//----------------------------------------------------------------------------
//
#ifndef TQGSP_BIC_HP_h
#define TQGSP_BIC_HP_h 1
#include "G4VModularPhysicsList.hh"
#include "globals.hh"
#include "CompileTimeConstraints.hh"
template<class T>
class TQGSP_BIC_HP: public T
{
public:
TQGSP_BIC_HP(G4int ver = 1);
virtual ~TQGSP_BIC_HP();
public:
// SetCuts()
virtual void SetCuts();
private:
enum {ok = CompileTimeConstraints::IsA<T, G4VModularPhysicsList>::ok };
};
#include "QGSP_BIC_HP.icc"
typedef TQGSP_BIC_HP<G4VModularPhysicsList> QGSP_BIC_HP;
// 2002 by J.P. Wellisch
#endif
| [
"r.e.deboer@students.uu.nl"
] | r.e.deboer@students.uu.nl |
9187d0c2fcc374929d2fbf6a34bc12cf95eea037 | 10baf23884604724fe5e8d9828a0fc7d64886a3b | /src/httpserver.cpp | 8949c558de89b8b4304e94c4100e50f67e52ff03 | [
"MIT"
] | permissive | forkee/Salen-Project | 41e8ad3a3a6527ec881752bc9742b88bc46ee44d | cdfe67e0b2c0bd69a60d26e01ac8e2ca782270d5 | refs/heads/master | 2021-04-09T11:25:37.611419 | 2018-03-02T14:48:50 | 2018-03-02T14:48:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,228 | cpp | // Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "httpserver.h"
#include "chainparamsbase.h"
#include "compat.h"
#include "util.h"
#include "netbase.h"
#include "rpcprotocol.h" // For HTTP status codes
#include "sync.h"
#include "ui_interface.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/thread.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/keyvalq_struct.h>
#ifdef EVENT__HAVE_NETINET_IN_H
#include <netinet/in.h>
#ifdef _XOPEN_SOURCE_EXTENDED
#include <arpa/inet.h>
#endif
#endif
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
/** Maximum size of http request (request line + headers) */
static const size_t MAX_HEADERS_SIZE = 8192;
/** HTTP request work item */
class HTTPWorkItem : public HTTPClosure
{
public:
HTTPWorkItem(HTTPRequest* req, const std::string &path, const HTTPRequestHandler& func):
req(req), path(path), func(func)
{
}
void operator()()
{
func(req.get(), path);
}
boost::scoped_ptr<HTTPRequest> req;
private:
std::string path;
HTTPRequestHandler func;
};
/** Simple work queue for distributing work over multiple threads.
* Work items are simply callable objects.
*/
template <typename WorkItem>
class WorkQueue
{
private:
/** Mutex protects entire object */
CWaitableCriticalSection cs;
CConditionVariable cond;
/* XXX in C++11 we can use std::unique_ptr here and avoid manual cleanup */
std::deque<WorkItem*> queue;
bool running;
size_t maxDepth;
int numThreads;
/** RAII object to keep track of number of running worker threads */
class ThreadCounter
{
public:
WorkQueue &wq;
ThreadCounter(WorkQueue &w): wq(w)
{
boost::lock_guard<boost::mutex> lock(wq.cs);
wq.numThreads += 1;
}
~ThreadCounter()
{
boost::lock_guard<boost::mutex> lock(wq.cs);
wq.numThreads -= 1;
wq.cond.notify_all();
}
};
public:
WorkQueue(size_t maxDepth) : running(true),
maxDepth(maxDepth),
numThreads(0)
{
}
/*( Precondition: worker threads have all stopped
* (call WaitExit)
*/
~WorkQueue()
{
while (!queue.empty()) {
delete queue.front();
queue.pop_front();
}
}
/** Enqueue a work item */
bool Enqueue(WorkItem* item)
{
boost::unique_lock<boost::mutex> lock(cs);
if (queue.size() >= maxDepth) {
return false;
}
queue.push_back(item);
cond.notify_one();
return true;
}
/** Thread function */
void Run()
{
ThreadCounter count(*this);
while (running) {
WorkItem* i = 0;
{
boost::unique_lock<boost::mutex> lock(cs);
while (running && queue.empty())
cond.wait(lock);
if (!running)
break;
i = queue.front();
queue.pop_front();
}
(*i)();
delete i;
}
}
/** Interrupt and exit loops */
void Interrupt()
{
boost::unique_lock<boost::mutex> lock(cs);
running = false;
cond.notify_all();
}
/** Wait for worker threads to exit */
void WaitExit()
{
boost::unique_lock<boost::mutex> lock(cs);
while (numThreads > 0){
cond.wait(lock);
}
}
/** Return current depth of queue */
size_t Depth()
{
boost::unique_lock<boost::mutex> lock(cs);
return queue.size();
}
};
struct HTTPPathHandler
{
HTTPPathHandler() {}
HTTPPathHandler(std::string prefix, bool exactMatch, HTTPRequestHandler handler):
prefix(prefix), exactMatch(exactMatch), handler(handler)
{
}
std::string prefix;
bool exactMatch;
HTTPRequestHandler handler;
};
/** HTTP module state */
//! libevent event loop
static struct event_base* eventBase = 0;
//! HTTP server
struct evhttp* eventHTTP = 0;
//! List of subnets to allow RPC connections from
static std::vector<CSubNet> rpc_allow_subnets;
//! Work queue for handling longer requests off the event loop thread
static WorkQueue<HTTPClosure>* workQueue = 0;
//! Handlers for (sub)paths
std::vector<HTTPPathHandler> pathHandlers;
//! Bound listening sockets
std::vector<evhttp_bound_socket *> boundSockets;
/** Check if a network address is allowed to access the HTTP server */
static bool ClientAllowed(const CNetAddr& netaddr)
{
if (!netaddr.IsValid())
return false;
BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets)
if (subnet.Match(netaddr))
return true;
return false;
}
/** Initialize ACL list for HTTP server */
static bool InitHTTPAllowList()
{
rpc_allow_subnets.clear();
rpc_allow_subnets.push_back(CSubNet("127.0.0.0/8")); // always allow IPv4 local subnet
rpc_allow_subnets.push_back(CSubNet("::1")); // always allow IPv6 localhost
if (mapMultiArgs.count("-rpcallowip")) {
const std::vector<std::string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH (std::string strAllow, vAllow) {
CSubNet subnet(strAllow);
if (!subnet.IsValid()) {
uiInterface.ThreadSafeMessageBox(
strprintf("Invalid -rpcallowip subnet specification: %s. Valid are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24).", strAllow),
"", CClientUIInterface::MSG_ERROR);
return false;
}
rpc_allow_subnets.push_back(subnet);
}
}
std::string strAllowed;
BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets)
strAllowed += subnet.ToString() + " ";
LogPrint("http", "Allowing HTTP connections from: %s\n", strAllowed);
return true;
}
/** HTTP request method as string - use for logging only */
static std::string RequestMethodString(HTTPRequest::RequestMethod m)
{
switch (m) {
case HTTPRequest::GET:
return "GET";
break;
case HTTPRequest::POST:
return "POST";
break;
case HTTPRequest::HEAD:
return "HEAD";
break;
case HTTPRequest::PUT:
return "PUT";
break;
default:
return "unknown";
}
}
/** HTTP request callback */
static void http_request_cb(struct evhttp_request* req, void* arg)
{
std::auto_ptr<HTTPRequest> hreq(new HTTPRequest(req));
LogPrint("http", "Received a %s request for %s from %s\n",
RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
// Early address-based allow check
if (!ClientAllowed(hreq->GetPeer())) {
hreq->WriteReply(HTTP_FORBIDDEN);
return;
}
// Early reject unknown HTTP methods
if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
hreq->WriteReply(HTTP_BADMETHOD);
return;
}
// Find registered handler for prefix
std::string strURI = hreq->GetURI();
std::string path;
std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
for (; i != iend; ++i) {
bool match = false;
if (i->exactMatch)
match = (strURI == i->prefix);
else
match = (strURI.substr(0, i->prefix.size()) == i->prefix);
if (match) {
path = strURI.substr(i->prefix.size());
break;
}
}
// Dispatch to worker thread
if (i != iend) {
std::auto_ptr<HTTPWorkItem> item(new HTTPWorkItem(hreq.release(), path, i->handler));
assert(workQueue);
if (workQueue->Enqueue(item.get()))
item.release(); /* if true, queue took ownership */
else
item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
} else {
hreq->WriteReply(HTTP_NOTFOUND);
}
}
/** Callback to reject HTTP requests after shutdown. */
static void http_reject_request_cb(struct evhttp_request* req, void*)
{
LogPrint("http", "Rejecting request while shutting down\n");
evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
}
/** Event dispatcher thread */
static void ThreadHTTP(struct event_base* base, struct evhttp* http)
{
RenameThread("salen-http");
LogPrint("http", "Entering http event loop\n");
event_base_dispatch(base);
// Event loop will be interrupted by InterruptHTTPServer()
LogPrint("http", "Exited http event loop\n");
}
/** Bind HTTP server to specified addresses */
static bool HTTPBindAddresses(struct evhttp* http)
{
int defaultPort = GetArg("-rpcport", BaseParams().RPCPort());
std::vector<std::pair<std::string, uint16_t> > endpoints;
// Determine what addresses to bind to
if (!mapArgs.count("-rpcallowip")) { // Default to loopback if not allowing external IPs
endpoints.push_back(std::make_pair("::1", defaultPort));
endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
if (mapArgs.count("-rpcbind")) {
LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
}
} else if (mapArgs.count("-rpcbind")) { // Specific bind address
const std::vector<std::string>& vbind = mapMultiArgs["-rpcbind"];
for (std::vector<std::string>::const_iterator i = vbind.begin(); i != vbind.end(); ++i) {
int port = defaultPort;
std::string host;
SplitHostPort(*i, port, host);
endpoints.push_back(std::make_pair(host, port));
}
} else { // No specific bind address specified, bind to any
endpoints.push_back(std::make_pair("::", defaultPort));
endpoints.push_back(std::make_pair("0.0.0.0", defaultPort));
}
// Bind addresses
for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
LogPrint("http", "Binding RPC on address %s port %i\n", i->first, i->second);
evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? NULL : i->first.c_str(), i->second);
if (bind_handle) {
boundSockets.push_back(bind_handle);
} else {
LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
}
}
return !boundSockets.empty();
}
/** Simple wrapper to set thread name and run work queue */
static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue)
{
RenameThread("salen-httpworker");
queue->Run();
}
/** libevent event log callback */
static void libevent_log_cb(int severity, const char *msg)
{
#ifndef EVENT_LOG_WARN
// EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
# define EVENT_LOG_WARN _EVENT_LOG_WARN
#endif
if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category
LogPrintf("libevent: %s\n", msg);
else
LogPrint("libevent", "libevent: %s\n", msg);
}
bool InitHTTPServer()
{
struct evhttp* http = 0;
struct event_base* base = 0;
if (!InitHTTPAllowList())
return false;
if (GetBoolArg("-rpcssl", false)) {
uiInterface.ThreadSafeMessageBox(
"SSL mode for RPC (-rpcssl) is no longer supported.",
"", CClientUIInterface::MSG_ERROR);
return false;
}
// Redirect libevent's logging to our own log
event_set_log_callback(&libevent_log_cb);
#if LIBEVENT_VERSION_NUMBER >= 0x02010100
// If -debug=libevent, set full libevent debugging.
// Otherwise, disable all libevent debugging.
if (LogAcceptCategory("libevent"))
event_enable_debug_logging(EVENT_DBG_ALL);
else
event_enable_debug_logging(EVENT_DBG_NONE);
#endif
#ifdef WIN32
evthread_use_windows_threads();
#else
evthread_use_pthreads();
#endif
base = event_base_new(); // XXX RAII
if (!base) {
LogPrintf("Couldn't create an event_base: exiting\n");
return false;
}
/* Create a new evhttp object to handle requests. */
http = evhttp_new(base); // XXX RAII
if (!http) {
LogPrintf("couldn't create evhttp. Exiting.\n");
event_base_free(base);
return false;
}
evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
evhttp_set_max_body_size(http, MAX_SIZE);
evhttp_set_gencb(http, http_request_cb, NULL);
if (!HTTPBindAddresses(http)) {
LogPrintf("Unable to bind any endpoint for RPC server\n");
evhttp_free(http);
event_base_free(base);
return false;
}
LogPrint("http", "Initialized HTTP server\n");
int workQueueDepth = std::max((long)GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
eventBase = base;
eventHTTP = http;
return true;
}
boost::thread threadHTTP;
bool StartHTTPServer()
{
LogPrint("http", "Starting HTTP server\n");
int rpcThreads = std::max((long)GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
LogPrintf("HTTP: starting %d worker threads\n", rpcThreads);
threadHTTP = boost::thread(boost::bind(&ThreadHTTP, eventBase, eventHTTP));
for (int i = 0; i < rpcThreads; i++)
boost::thread(boost::bind(&HTTPWorkQueueRun, workQueue));
return true;
}
void InterruptHTTPServer()
{
LogPrint("http", "Interrupting HTTP server\n");
if (eventHTTP) {
// Unlisten sockets
BOOST_FOREACH (evhttp_bound_socket *socket, boundSockets) {
evhttp_del_accept_socket(eventHTTP, socket);
}
// Reject requests on current connections
evhttp_set_gencb(eventHTTP, http_reject_request_cb, NULL);
}
if (workQueue)
workQueue->Interrupt();
}
void StopHTTPServer()
{
LogPrint("http", "Stopping HTTP server\n");
if (workQueue) {
LogPrint("http", "Waiting for HTTP worker threads to exit\n");
#ifndef WIN32
// ToDo: Disabling WaitExit() for Windows platforms is an ugly workaround for the wallet not
// closing during a repair-restart. It doesn't hurt, though, because threadHTTP.timed_join
// below takes care of this and sends a loopbreak.
workQueue->WaitExit();
#endif
delete workQueue;
}
if (eventBase) {
LogPrint("http", "Waiting for HTTP event thread to exit\n");
// Give event loop a few seconds to exit (to send back last RPC responses), then break it
// Before this was solved with event_base_loopexit, but that didn't work as expected in
// at least libevent 2.0.21 and always introduced a delay. In libevent
// master that appears to be solved, so in the future that solution
// could be used again (if desirable).
// (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
#if BOOST_VERSION >= 105000
if (!threadHTTP.try_join_for(boost::chrono::milliseconds(2000))) {
#else
if (!threadHTTP.timed_join(boost::posix_time::milliseconds(2000))) {
#endif
LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
event_base_loopbreak(eventBase);
threadHTTP.join();
}
}
if (eventHTTP) {
evhttp_free(eventHTTP);
eventHTTP = 0;
}
if (eventBase) {
event_base_free(eventBase);
eventBase = 0;
}
LogPrint("http", "Stopped HTTP server\n");
}
struct event_base* EventBase()
{
return eventBase;
}
static void httpevent_callback_fn(evutil_socket_t, short, void* data)
{
// Static handler: simply call inner handler
HTTPEvent *self = ((HTTPEvent*)data);
self->handler();
if (self->deleteWhenTriggered)
delete self;
}
HTTPEvent::HTTPEvent(struct event_base* base, bool deleteWhenTriggered, const boost::function<void(void)>& handler):
deleteWhenTriggered(deleteWhenTriggered), handler(handler)
{
ev = event_new(base, -1, 0, httpevent_callback_fn, this);
assert(ev);
}
HTTPEvent::~HTTPEvent()
{
event_free(ev);
}
void HTTPEvent::trigger(struct timeval* tv)
{
if (tv == NULL)
event_active(ev, 0, 0); // immediately trigger event in main thread
else
evtimer_add(ev, tv); // trigger after timeval passed
}
HTTPRequest::HTTPRequest(struct evhttp_request* req) : req(req),
replySent(false)
{
}
HTTPRequest::~HTTPRequest()
{
if (!replySent) {
// Keep track of whether reply was sent to avoid request leaks
LogPrintf("%s: Unhandled request\n", __func__);
WriteReply(HTTP_INTERNAL, "Unhandled request");
}
// evhttpd cleans up the request, as long as a reply was sent.
}
std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr)
{
const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
assert(headers);
const char* val = evhttp_find_header(headers, hdr.c_str());
if (val)
return std::make_pair(true, val);
else
return std::make_pair(false, "");
}
std::string HTTPRequest::ReadBody()
{
struct evbuffer* buf = evhttp_request_get_input_buffer(req);
if (!buf)
return "";
size_t size = evbuffer_get_length(buf);
/** Trivial implementation: if this is ever a performance bottleneck,
* internal copying can be avoided in multi-segment buffers by using
* evbuffer_peek and an awkward loop. Though in that case, it'd be even
* better to not copy into an intermediate string but use a stream
* abstraction to consume the evbuffer on the fly in the parsing algorithm.
*/
const char* data = (const char*)evbuffer_pullup(buf, size);
if (!data) // returns NULL in case of empty buffer
return "";
std::string rv(data, size);
evbuffer_drain(buf, size);
return rv;
}
void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
{
struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
assert(headers);
evhttp_add_header(headers, hdr.c_str(), value.c_str());
}
/** Closure sent to main thread to request a reply to be sent to
* a HTTP request.
* Replies must be sent in the main loop in the main http thread,
* this cannot be done from worker threads.
*/
void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
{
assert(!replySent && req);
// Send event to main http thread to send reply message
struct evbuffer* evb = evhttp_request_get_output_buffer(req);
assert(evb);
evbuffer_add(evb, strReply.data(), strReply.size());
HTTPEvent* ev = new HTTPEvent(eventBase, true,
boost::bind(evhttp_send_reply, req, nStatus, (const char*)NULL, (struct evbuffer *)NULL));
ev->trigger(0);
replySent = true;
req = 0; // transferred back to main thread
}
CService HTTPRequest::GetPeer()
{
evhttp_connection* con = evhttp_request_get_connection(req);
CService peer;
if (con) {
// evhttp retains ownership over returned address string
const char* address = "";
uint16_t port = 0;
evhttp_connection_get_peer(con, (char**)&address, &port);
peer = CService(address, port);
}
return peer;
}
std::string HTTPRequest::GetURI()
{
return evhttp_request_get_uri(req);
}
HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod()
{
switch (evhttp_request_get_command(req)) {
case EVHTTP_REQ_GET:
return GET;
break;
case EVHTTP_REQ_POST:
return POST;
break;
case EVHTTP_REQ_HEAD:
return HEAD;
break;
case EVHTTP_REQ_PUT:
return PUT;
break;
default:
return UNKNOWN;
break;
}
}
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
{
LogPrint("http", "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
}
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
{
std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
for (; i != iend; ++i)
if (i->prefix == prefix && i->exactMatch == exactMatch)
break;
if (i != iend)
{
LogPrint("http", "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
pathHandlers.erase(i);
}
}
| [
"salencoin01@gmail.com"
] | salencoin01@gmail.com |
334bf47b18a5d607a935dcc7f436b050e4183df0 | 7a36a0652fe0704b4b27f644653e7b0f7e72060f | /TianShan/StreamService/CloneIndex/CloneIndexFile.cpp | a7a9420d94e5ee019c9b953c088ffd71e5b20b5a | [] | no_license | darcyg/CXX | 1ee13c1765f1987e293c15b9cbc51ae625ac3a2e | ef288ad0e1624ed0582839f2a5a0ef66073d415e | refs/heads/master | 2020-04-06T04:27:11.940141 | 2016-12-29T03:49:56 | 2016-12-29T03:49:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,612 | cpp | #include "CloneIndexFile.h"
#include <fstream>
#include "SimpleXMLParser.h"
using ZQ::IdxParser::CsicoIndexFileParser;
namespace ZQ
{
namespace IdxParser
{
IndexFileClone::IndexFileClone(ZQ::common::Log& fileLog, const std::string oriIndexFile, const std::string newIndexFile)
:_oriIndexFile(oriIndexFile), _newIndexFile(newIndexFile), _fileLog(fileLog)
{
}
IndexFileClone::~IndexFileClone()
{
}
bool IndexFileClone::replaceSubFile(const std::string oriSubFile, const std::string newSubFile)
{
if (oriSubFile.size() != newSubFile.size())
{
_fileLog(ZQ::common::Log::L_ERROR, CLOGFMT(IndexFileClone, "replaceSubFile() : New index file[%s]'s length is unequal to Original index file[%s]'s length"), newSubFile.c_str(), oriSubFile.c_str());
return false;
}
StringMap::iterator strIter = _subFiles.find(oriSubFile);
if (strIter == _subFiles.end())
{
_subFiles.insert(std::make_pair(oriSubFile, newSubFile)); // insert
}
else
{
strIter->second = newSubFile; // replace
}
return true;
}
bool IndexFileClone::clone()
{
// open new index file
std::ofstream fileOut;
fileOut.open(_newIndexFile.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
if (!fileOut)
{
_fileLog(ZQ::common::Log::L_ERROR, CLOGFMT(IndexFileClone, "clone() : Fail to open new index file [%s] to write"), _newIndexFile.c_str());
return false;
}
// open original index file
IdxParserEnv env;
FileReaderNative reader(env);
if (!reader.open(_oriIndexFile))
{
_fileLog(ZQ::common::Log::L_ERROR, CLOGFMT(IndexFileClone, "clone() : Fail to open original index file [%s] to read"), _oriIndexFile.c_str());
fileOut.close();
return false;
}
if (reader.getFileSize(_oriIndexFile, true) <= 0)
{
fileOut.close();
return true;
}
if (_subFiles.empty())
{
readRestFile(&reader, fileOut);
}
else
{
cloneCiscoIndex(&reader, fileOut);
}
// close original and new index file
fileOut.flush();
fileOut.close();
reader.close();
_subFiles.clear();
return true;
}
void IndexFileClone::cloneCiscoIndex(FileReader* reader, std::ofstream& fileOut)
{
// copy file header section
CsicoIndexFileParser::CsicoIndexFileHeader fileHeader;
memset(&fileHeader, 0, sizeof(fileHeader));
int32 nRead = reader->read(&fileHeader, sizeof(fileHeader));
fileOut.write(reinterpret_cast<char*>(&fileHeader), nRead);
if(nRead != (int32)sizeof(fileHeader))
{
// file is end
_fileLog(ZQ::common::Log::L_ERROR,CLOGFMT(IndexFileParser,"Failed to read CsicoIndexFileHeader for file[%s]"), _oriIndexFile.c_str());
}
else
{
parseCsicoINDEX11(reader, fileOut);
}
}
#define CSICOINDEX_TAG_SECTIONHEADERTAG 0x11000001
#define CSICOINDEX_TAG_SUBFILESECTION 0x110005FF
#define CSICOINDEX_TAG_SUBFILENAME 0x15000502
bool IndexFileClone::parseOtherSection(ZQ::IdxParser::FileReader* reader, std::ofstream& fileOut, uint16 sectionLength)
{
char* buf = new char[sectionLength];
int32 nRead = reader->read(buf, sectionLength);
fileOut.write(buf, nRead);
delete [] buf;
if (nRead != sectionLength)
{
return false;
}
return true;
}
void IndexFileClone::parseCsicoINDEX11(ZQ::IdxParser::FileReader *reader, std::ofstream &fileOut)
{
CsicoIndexFileParser::CsicoIndexFileTagAndLength tal;
bool bQuit = false;
while (!bQuit)
{
if (getTag(reader, fileOut, tal))
{
try
{
switch (tal.tagId)
{
case CSICOINDEX_TAG_SECTIONHEADERTAG: // index header section
parseSection(reader, fileOut, tal.length);
readRestFile(reader, fileOut);
bQuit = true;
break;
default: // other sections between file header section and index header section
if (!parseOtherSection(reader, fileOut, tal.length))
{
bQuit = true;
}
break;
}
}
catch (const char* reason)
{
_fileLog(ZQ::common::Log::L_ERROR,CLOGFMT(IndexFileParser,"failed to parse[%s] because [%s]"), _oriIndexFile.c_str(), reason);
bQuit = true;
}
}
else
{
_fileLog(ZQ::common::Log::L_ERROR,CLOGFMT(IndexFileParser,"insufficient data to parse of [%s]"), _oriIndexFile.c_str());
bQuit = true;
}
}
}
bool IndexFileClone::getTag(FileReader* reader, std::ofstream& fileOut,
CsicoIndexFileParser::CsicoIndexFileTagAndLength& tal)
{
int32 nRead = reader->read(&tal, sizeof(tal));
fileOut.write(reinterpret_cast<char*>(&tal), nRead);
if (nRead != sizeof(tal))
{
// file is end;
_fileLog(ZQ::common::Log::L_ERROR,CLOGFMT(IndexFileParser,"insufficient data to parse of [%s]"),_oriIndexFile.c_str());
return false;
}
while (*((char*)&tal) == 0x00)
{
CsicoIndexFileParser::CsicoIndexFileTagAndLength tmpTal;
unsigned char c;
nRead = reader->read(&c, sizeof(c));
fileOut.write(reinterpret_cast<char*>(&c), nRead);
if (nRead != sizeof(c))
{
// file is end
_fileLog(ZQ::common::Log::L_ERROR,CLOGFMT(IndexFileParser,"insufficient data to parse of [%s]"),_oriIndexFile.c_str());
return false;
}
char* pTemp = (char*)&tal;
pTemp ++;
memcpy(&tmpTal, pTemp, sizeof(tal) -1);
pTemp = (char*)&tmpTal;
pTemp += sizeof(tmpTal) - 1;
memcpy(pTemp, &c, sizeof(c));
memcpy(&tal, &tmpTal, sizeof(tal));
}
return true;
}
void IndexFileClone::parseSection(ZQ::IdxParser::FileReader* reader, std::ofstream& fileOut, uint16 sectionLength)
{
CsicoIndexFileParser::CsicoIndexFileTagAndLength tal;
bool bQuit = false;
uint16 curLength = 0;
while (!bQuit && !_subFiles.empty() && curLength < sectionLength)
{
if (getTag(reader, fileOut, tal))
{
switch (tal.tagId)
{
case CSICOINDEX_TAG_SUBFILESECTION:
if (!parseSubFiles(reader, fileOut, tal.length))
{
bQuit = true;
}
break;
default:
if (!parseOtherSection(reader, fileOut, tal.length))
{
bQuit = true;
}
break;
} // end for switch
}
else
{
bQuit = true;
_fileLog(ZQ::common::Log::L_ERROR,CLOGFMT(IndexFileParser,"insufficient data to parse of [%s]"),_oriIndexFile.c_str());
}
curLength += tal.length;
} // end for while
}
void IndexFileClone::readRestFile(ZQ::IdxParser::FileReader* reader, std::ofstream& fileOut)
{
char buffer[2048];
int32 nRead;
do
{
nRead = reader->read(buffer, sizeof(buffer));
fileOut.write(buffer, nRead);
} while (nRead == sizeof(buffer));
}
bool IndexFileClone::parseSubFiles(ZQ::IdxParser::FileReader* reader, std::ofstream& fileOut, uint16 sectionLength)
{
CsicoIndexFileParser::CsicoIndexFileTagAndLength tal;
bool bQuit = false;
uint16 curLength = 0;
int i = 0;
while(!bQuit && curLength < sectionLength)
{
if (getTag(reader, fileOut, tal))
{
switch (tal.tagId)
{
case CSICOINDEX_TAG_SUBFILENAME:
replaceSubFileName(reader, fileOut, tal.length);
bQuit = true;
break;
default:
if (!parseOtherSection(reader, fileOut, tal.length))
{
bQuit = true;
}
break;
}
}
else
{
bQuit = true;
_fileLog(ZQ::common::Log::L_ERROR,CLOGFMT(IndexFileParser,"insufficient data to parse of [%s]"),_oriIndexFile.c_str());
}
curLength += tal.length;
}
return true;
}
void IndexFileClone::replaceSubFileName(ZQ::IdxParser::FileReader* reader, std::ofstream& fileOut, uint16 sectionLength)
{
std::string strXmlContent;
strXmlContent = readString(reader, sectionLength);
SimpleXMLParser parser;
std::string xmlContent = "<root>" ;
xmlContent = xmlContent + strXmlContent;
xmlContent = xmlContent + "</root>";
try
{
parser.parse( xmlContent.c_str() ,static_cast<int>( xmlContent.length() ), 1 );
const SimpleXMLParser::Node& root = parser.document();
const SimpleXMLParser::Node* pSubType = findNode(&root,"root/SubType");
if(pSubType)
{
StringMap::iterator strIter = _subFiles.find(pSubType->content);
if (strIter != _subFiles.end())
{
size_t iterStart = strXmlContent.find(pSubType->content);
strXmlContent.replace(iterStart, pSubType->content.size(), strIter->second);
_subFiles.erase(strIter);
}
}
else
{
_fileLog(ZQ::common::Log::L_ERROR,CLOGFMT(IndexFileParser,"failed to parse subfile extension for [%s] with [%s] , can't get subtype"), _oriIndexFile.c_str() ,xmlContent.c_str() );
}
}
catch( ZQ::common::ExpatException& )
{
_fileLog(ZQ::common::Log::L_ERROR,CLOGFMT(IndexFileParser,"failed to parse subfile extension for [%s] with [%s]"), _oriIndexFile.c_str() ,xmlContent.c_str() );
}
fileOut.write(strXmlContent.c_str(), strXmlContent.length() + 1);
}
std::string IndexFileClone::readString( FileReader* reader , size_t size )
{
char* buf = new char[size];
int32 nRead = reader->read(buf, size);
std::string strContent = buf;
delete [] buf;
return strContent;
}
} // end for IndexClone
} // end for ZQ | [
"jjz@example.com"
] | jjz@example.com |
ca44687156fdadc8b2b5b943dc5045bfa39294d1 | 711a940ba27909bf2194da895053463923ace29f | /ProcessMC3/EMJbkgNew.cc | 190dc815ed5e18d37bb99e62f8ba9d5fc5e2b841 | [] | no_license | jengbou/ntuplePrint | c6591dca74bcf2f26ff7c030306c242d979e9940 | 7644667e28c547211021f4178b34aff46341e18c | refs/heads/master | 2021-01-22T05:27:56.768136 | 2019-05-11T17:33:26 | 2019-05-11T17:33:26 | 81,662,903 | 0 | 0 | null | 2017-02-11T15:48:35 | 2017-02-11T15:48:35 | null | UTF-8 | C++ | false | false | 112,406 | cc | #include <iostream>
#include <iomanip>
#include <locale>
#include <sstream>
#include <TROOT.h>
#include <TChain.h>
#include <TFile.h>
#include <TMatrixD.h>
#include <map>
#include "vector"
using std::vector;
#include "algorithm"
#include <TH2.h>
#include <TStyle.h>
#include <TCanvas.h>
#include "EMJselect.h"
#include "EMJ16003.h"
#include "QCDhists.h"
#include "EMJbkg.h"
#include "EMJbkgNew.h"
#include "TLorentzVector.h"
int EMJbkgNew(bool otfile, bool hasPre, const char* inputfilename, const char* outputfilename, bool blind, bool isData, bool printCutSets, std::string runyr) {
//Remember to change runJobsUMD80New_FastAll.sh and MergeHistsNoNormNew.cc accordingly
std::string Cutstorun[] = {"1","21"};
//std::string Cutstorun[] = {"1","2","3","4","5","6","7","8"};
//std::string Cutstorun[] = {"9","10","11"};
//std::string Cutstorun[] = {"11","11a"};
//std::string Cutstorun[] = {"1","2","5","6","7","8","9"};
const int nCuts = sizeof(Cutstorun)/sizeof(Cutstorun[0]);
// common cuts/setups
const float pvztrkcut=0.01;//cm
const int varType = 3;// 1: alpha; 2: alpha2Dsig; 3 (default): alpha3Dsig
double minJetPt = 100.0;
const float jetacut=2.0;
const float NemfracCut=0.9;
const float CemfracCut=0.9;
const int ntrk1cut=0;
////////////////////
// Cutset cuts
////////////////////
// map cut using cutset name
std::map<std::string,int> CutIdx;
CutIdx["1"] = 0;
CutIdx["2"] = 1;
CutIdx["3"] = 2;
CutIdx["4"] = 3;
CutIdx["5"] = 4;
CutIdx["6"] = 5;
CutIdx["7"] = 6;
CutIdx["8"] = 7;
CutIdx["9"] = 8;
CutIdx["10"] = 9;
CutIdx["11"] = 10;
CutIdx["11a"] = 11;
// 2017
CutIdx["21"] = 0;
// Cut Name "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "11a"
float DHTcuts[] = { 900, 900, 900, 900, 1100, 1000, 1000, 1200, 900, 900, 900, 900};
float Dpt1cuts[] = { 225, 225, 225, 225, 275, 250, 250, 300, 225, 225, 225, 225};
float Dpt2cuts[] = { 100, 100, 100, 100, 250, 150, 150, 250, 100, 100, 100, 100};
float Dpt3cuts[] = { 100, 100, 100, 100, 150, 100, 100, 200, 100, 100, 100, 100};
float Dpt4cuts[] = { 100, 100, 100, 100, 150, 100, 100, 150, 100, 100, 100, 100};
float DMETcuts[] = { 0, 0, 150, 200, 0, 0, 0, 0, 0, 150, 200, 200};
int Dnemcuts[] = { 2, 2, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1};
int DntagTypes[] = { 22, 22, 12, 12, 22, 22, 22, 22, 22, 12, 12, 1};
float DPUdzCuts[] = { 2.5, 4, 15, 4, 2.5, 2.5, 2.5, 2.5, 2.5, 15, 4, 4};
float DsigzCuts[] = { 4, 4, 30, 20, 4, 4, 20, 10, 4, 30, 20, 20};
float DmedIPcuts[] = {0.05, 0.1, 0.15, 0.25, 0.05, 0.1, 0.05, 0.05, 0.05, 0.15, 0.10, 0.10};
float DalphaCuts[] = {0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.4, 0.5, 0.5, 0.5};
// bool passFR[] = {true,true,true,true,true,true,true,true,true,true};
// bool passSR[] = {true,true,true,true,true,true,true,true,true,true};
////////////////////
// End of cutsets
////////////////////
// btagging related: remember to change BTagCalibrationStandaloneReader in QCDhists.cc
// defined here:
// 80X (2016) https://twiki.cern.ch/twiki/bin/viewauth/CMS/BtagRecommendation80XReReco
// >> 0.5426(CSVv2L);//0.8484(CSVv2M);//0.9535(CSVv2T); 0.627516656(user);
// 94X (2017) https://twiki.cern.ch/twiki/bin/viewauth/CMS/BtagRecommendation94X
// >> 0.5803(CSVv2L);//0.8838(CSVv2M);//0.9693(CSVv2T)
float bTagWP=0.8484;
int bUnfType=2;//1: loose; 2: medium; 3: tight; 4: user
int ptType=1;//1: low pT; 2: high pT; note: this setting is only effective for constant b-tag eff case
// end btagging related
int NemergingCut = 0;
int npass=0;
TFile *f = new TFile(inputfilename);
if(f->IsZombie()) {
std::cout << "File: " << inputfilename << " does not exist." << std::endl;
return 0;
}
QCDhists* qcdtools=0;
//histogram map
std::map<TString,TH1*> hs1D; // map of usual 1D histogram
std::map<TString,TH2*> hs2D; // map of usual 2D histogram
std::cout << "CSV batgger cut used = " << bTagWP << std::endl;
TTree *tt = (TTree*)f->Get("emJetAnalyzer/emJetTree");
Int_t nVtx, lumi, run, nTrueInt, nTracks;
unsigned long long event;
Float_t met_pt, met_phi;
//bool hltTrig1n, hltTrig1d, hltTrig2n, hltTrig2d, hltTrig3d;
bool hltTrig3n;
vector<int> *pv_index=0;
vector<float> *pv_zv=0;
vector<int> *jet_index=0;
vector<int> *jet_source=0;
vector<float> *jet_pt = 0;
vector<float> *jet_eta = 0;
vector<float> *jet_phi = 0;
// vector<float> *jet_alphaMax = 0;
vector<float> *jet_cef = 0;
vector<float> *jet_nef = 0;
// vector<float> *jet_chf = 0;
// vector<float> *jet_nhf = 0;
vector<float> *jet_theta2D = 0;
vector<float> *jet_csv = 0;
vector<vector<float> > *track_pt = 0;
vector<vector<float> > *track_eta = 0;
vector<vector<float> > *track_phi = 0;
vector<vector<int> > *track_source = 0;
vector<vector<int> > *track_index = 0;
// vector<vector<int> > *track_jet_index = 0;
// vector<vector<int> > *track_vertex_index = 0;
// vector<vector<int> > *track_algo = 0;
vector<vector<int> > *track_quality = 0;
// vector<vector<float> > *track_vertex_weight =0;
// vector<vector<float> > *track_pvWeight = 0;
vector<vector<float> > *track_ipZ =0;
vector<vector<float> > *track_ipXY = 0;
vector<vector<float> > *track_ipXYSig = 0;
vector<vector<float> > *track_ref_z =0;//analysis_20170523_v0
// vector<vector<int> > *track_nMissInnerHits = 0;
// vector<vector<int> > *track_nMissInnerPxlLayers = 0;
// vector<vector<int> > *track_nPxlLayers = 0;
// vector<vector<int> > *track_nHits = 0;
vector<vector<float> > *track_dRToJetAxis=0;
vector<vector<float> > *track_distanceToJet=0;
//vector<vector<TLorentzVector> > *track_p4;//not in ntuple
// gen particles
vector<int> *gp_index = new vector<int>;
vector<int> *gp_pdgId = new vector<int>;
vector<float> *gp_pt = new vector<float>;
vector<float> *gp_eta = new vector<float>;
vector<float> *gp_phi = new vector<float>;
vector<int> *gp_charge = new vector<int>;
vector<int> *gp_status = new vector<int>;
vector<float> *gp_vx = new vector<float>;
vector<float> *gp_vy = new vector<float>;
vector<float> *gp_vz = new vector<float>;
//get event count pre trigger
// gen particles
tt->SetBranchAddress("gp_index",&gp_index);
tt->SetBranchAddress("gp_pdgId",&gp_pdgId);
tt->SetBranchAddress("gp_pt",&gp_pt);
tt->SetBranchAddress("gp_eta",&gp_eta);
tt->SetBranchAddress("gp_phi",&gp_phi);
tt->SetBranchAddress("gp_charge",&gp_charge);
tt->SetBranchAddress("gp_status",&gp_status);
tt->SetBranchAddress("gp_vx",&gp_vx);
tt->SetBranchAddress("gp_vy",&gp_vy);
tt->SetBranchAddress("gp_vz",&gp_vz);
//for ntuple
tt->SetBranchAddress("pv_z",&pv_zv);
tt->SetBranchAddress("pv_index",&pv_index);
tt->SetBranchAddress("nVtx",&nVtx);
tt->SetBranchAddress("nTrueInt",&nTrueInt);
tt->SetBranchAddress("nTracks",&nTracks);
tt->SetBranchAddress("event",&event);
tt->SetBranchAddress("lumi",&lumi);
tt->SetBranchAddress("run",&run);
tt->SetBranchAddress("met_pt",&met_pt);
tt->SetBranchAddress("met_phi",&met_phi);
tt->SetBranchAddress("jet_index",&jet_index);
tt->SetBranchAddress("jet_source",&jet_source);
if (runyr.find("2016")!=std::string::npos) {
tt->SetBranchAddress("jet_pt",&jet_pt);
}
else {
tt->SetBranchAddress("jet_ptRaw",&jet_pt);
}
tt->SetBranchAddress("jet_eta",&jet_eta);
tt->SetBranchAddress("jet_phi",&jet_phi);
tt->SetBranchAddress("jet_cef",&jet_cef);
tt->SetBranchAddress("jet_nef",&jet_nef);
// tt->SetBranchAddress("jet_chf",&jet_chf);
// tt->SetBranchAddress("jet_nhf",&jet_nhf);
tt->SetBranchAddress("jet_theta2D",&jet_theta2D);
tt->SetBranchAddress("jet_csv",&jet_csv);
// tt->SetBranchAddress("jet_alphaMax",&jet_alphaMax);
tt->SetBranchAddress("track_pt",&track_pt);
tt->SetBranchAddress("track_eta",&track_eta);
tt->SetBranchAddress("track_phi",&track_phi);
tt->SetBranchAddress("track_source",&track_source);
tt->SetBranchAddress("track_index",&track_index);
// tt->SetBranchAddress("track_jet_index",&track_jet_index);
// tt->SetBranchAddress("track_algo",&track_algo);
tt->SetBranchAddress("track_quality",&track_quality);
// tt->SetBranchAddress("track_vertex_index",&track_vertex_index);
// tt->SetBranchAddress("track_vertex_weight",&track_vertex_weight);
// tt->SetBranchAddress("track_pvWeight",&track_pvWeight);
tt->SetBranchAddress("track_ipXY",&track_ipXY);
tt->SetBranchAddress("track_ipXYSig",&track_ipXYSig);
tt->SetBranchAddress("track_ref_z",&track_ref_z);
// tt->SetBranchAddress("track_nMissInnerHits",&track_nMissInnerHits);
// tt->SetBranchAddress("track_nMissInnerPxlLayers",&track_nMissInnerPxlLayers);
// tt->SetBranchAddress("track_nPxlLayers",&track_nPxlLayers);
// tt->SetBranchAddress("track_nHits",&track_nHits);
tt->SetBranchAddress("track_ipZ",&track_ipZ);
tt->SetBranchAddress("track_dRToJetAxis",&track_dRToJetAxis);
tt->SetBranchAddress("track_distanceToJet",&track_distanceToJet);
//tt->SetBranchAddress("track_p4",&track_p4);//not in ntuple
// tt->SetBranchAddress("HLT_HT400",&hltTrig1d);
// tt->SetBranchAddress("HLT_HT500",&hltTrig1n);
// tt->SetBranchAddress("HLT_HT250",&hltTrig2d);
// tt->SetBranchAddress("HLT_HT350",&hltTrig2n);
// tt->SetBranchAddress("HLT_PFHT600",&hltTrig3d);
if (runyr.find("2016")!=std::string::npos) {
tt->SetBranchAddress("HLT_PFHT900",&hltTrig3n);//G,H
}
else if (runyr.find("2017")!=std::string::npos) {
std::cout << "[EMJbkgNew] 2017 HLT" << std::endl;
tt->SetBranchAddress("HLT_PFHT1050",&hltTrig3n);
}
else {
// need to check 2018 HLT
tt->SetBranchAddress("HLT_PFHT1050",&hltTrig3n);
}
std::cout << "Number of cuts to run = " << nCuts << std::endl;
if(otfile) {
TH1::SetDefaultSumw2();
for (int iCut=0; iCut<nCuts; iCut++) {
std::cout << "cut: " << Cutstorun[iCut] << std::endl;
std::string histcutname="Cutset"+Cutstorun[iCut];
//std::cout << "iCut = " << iCut << ":" << histcutname <<std::endl;
// get histogram of events before trigger
if(hasPre) {
if(otfile) hs1D[TString("eventCountPreTrigger_"+histcutname)] =
static_cast<TH1F*>(f->Get("eventCountPreTrigger/eventCountPreTrigger")->Clone(TString("eventCountPreTrigger_"+histcutname)));
} else {
if(otfile) hs1D[TString("eventCountPreTrigger_"+histcutname)] =
new TH1F(TString("eventCountPreTrigger_"+histcutname),"eventCountPreTrigger",2,0.,2.);
}
hs1D[TString("acount_"+histcutname)] = new TH1F(TString("acount_"+histcutname),"counts",20,0.,20.);
hs1D[TString("count_"+histcutname)] = new TH1F(TString("count_"+histcutname),"counts",3,0.,3);
hs1D[TString("count_"+histcutname)]->SetStats(0);
hs1D[TString("count_"+histcutname)]->SetCanExtend(TH1::kAllAxes);
hs1D[TString("count_"+histcutname)]->Fill("All",0);
hs1D[TString("count_"+histcutname)]->Fill("filter",0);
hs1D[TString("count_"+histcutname)]->Fill("4 jets",0);
hs1D[TString("count_"+histcutname)]->Fill("HT",0);
hs1D[TString("count_"+histcutname)]->Fill("jet pt1",0);
hs1D[TString("count_"+histcutname)]->Fill("jet pt2",0);
hs1D[TString("count_"+histcutname)]->Fill("jet pt3",0);
hs1D[TString("count_"+histcutname)]->Fill("jet pt4",0);
hs1D[TString("count_"+histcutname)]->Fill("MET",0);
hs1D[TString("count_"+histcutname)]->Fill("emerging",0);
hs1D[TString("count_"+histcutname)]->Fill("almostemerging",0);
hs1D[TString("count_"+histcutname)]->Fill("FakeRateBKG",0);
//1D
hs1D[TString("hjpt1SR_"+histcutname)] = new TH1F(TString("hjpt1SR_"+histcutname)," pT of 1st-leading jets (SR)",100,0.,1000.);
hs1D[TString("hjpt1FR_"+histcutname)] = new TH1F(TString("hjpt1FR_"+histcutname)," pT of 1st-leading jets (FR)",100,0.,1000.);
hs1D[TString("hjpt2SR_"+histcutname)] = new TH1F(TString("hjpt2SR_"+histcutname)," pT of 2nd-leading jets (SR)",100,0.,1000.);
hs1D[TString("hjpt2FR_"+histcutname)] = new TH1F(TString("hjpt2FR_"+histcutname)," pT of 2nd-leading jets (FR)",100,0.,1000.);
hs1D[TString("hjpt3SR_"+histcutname)] = new TH1F(TString("hjpt3SR_"+histcutname)," pT of 3rd-leading jets (SR)",100,0.,1000.);
hs1D[TString("hjpt3FR_"+histcutname)] = new TH1F(TString("hjpt3FR_"+histcutname)," pT of 3rd-leading jets (FR)",100,0.,1000.);
hs1D[TString("hjpt4SR_"+histcutname)] = new TH1F(TString("hjpt4SR_"+histcutname)," pT of 4th-leading jets (SR)",100,0.,1000.);
hs1D[TString("hjpt4FR_"+histcutname)] = new TH1F(TString("hjpt4FR_"+histcutname)," pT of 4th-leading jets (FR)",100,0.,1000.);
hs1D[TString("heta1SR_"+histcutname)] = new TH1F(TString("heta1SR_"+histcutname)," eta of 1st-leading jets (SR)",100,-4.,4.);
hs1D[TString("heta1FR_"+histcutname)] = new TH1F(TString("heta1FR_"+histcutname)," eta of 1st-leading jets (FR)",100,-4.,4.);
hs1D[TString("heta2SR_"+histcutname)] = new TH1F(TString("heta2SR_"+histcutname)," eta of 2nd-leading jets (SR)",100,-4.,4.);
hs1D[TString("heta2FR_"+histcutname)] = new TH1F(TString("heta2FR_"+histcutname)," eta of 2nd-leading jets (FR)",100,-4.,4.);
hs1D[TString("heta3SR_"+histcutname)] = new TH1F(TString("heta3SR_"+histcutname)," eta of 3rd-leading jets (SR)",100,-4.,4.);
hs1D[TString("heta3FR_"+histcutname)] = new TH1F(TString("heta3FR_"+histcutname)," eta of 4rd-leading jets (FR)",100,-4.,4.);
hs1D[TString("heta4SR_"+histcutname)] = new TH1F(TString("heta4SR_"+histcutname)," eta of 4th-leading jets (SR)",100,-4.,4.);
hs1D[TString("heta4FR_"+histcutname)] = new TH1F(TString("heta4FR_"+histcutname)," eta of 4th-leading jets (FR)",100,-4.,4.);
hs1D[TString("METSR_"+histcutname)] = new TH1F(TString("METSR_"+histcutname)," MET distribution (SR)", 200,0.,1000.);
hs1D[TString("METFR_"+histcutname)] = new TH1F(TString("METFR_"+histcutname)," MET distribution (FR)", 200,0.,1000.);
hs1D[TString("dRjtrk0SR_"+histcutname)] = new TH1F(TString("dRjtrk0SR_"+histcutname)," #Delta R(track,jet) distribution (SR)", 1000,0.,10.);
hs1D[TString("dRjtrk0FR_"+histcutname)] = new TH1F(TString("dRjtrk0FR_"+histcutname)," #Delta R(track,jet) distribution (FR)", 1000,0.,10.);
hs1D[TString("dRjtrkSR_"+histcutname)] = new TH1F(TString("dRjtrkSR_"+histcutname)," #Delta R(track-PV,jet) distribution (SR)", 1000,0.,10.);
hs1D[TString("dRjtrkFR_"+histcutname)] = new TH1F(TString("dRjtrkFR_"+histcutname)," #Delta R(track-PV,jet) distribution (FR)", 1000,0.,10.);
hs1D[TString("djtrkSR_"+histcutname)] = new TH1F(TString("djtrkSR_"+histcutname)," distance (track,jet) distribution (SR)", 1000,0.,50.);
hs1D[TString("djtrkFR_"+histcutname)] = new TH1F(TString("djtrkFR_"+histcutname)," distance(track,jet) distribution (FR)", 1000,0.,50.);
//hs1D[TString("EtRatioSR_"+histcutname)] = new TH1F(TString("EtRatioSR_"+histcutname)," Summed track ET ratio distribution (SR)", 100,0.,10.0);
//hs1D[TString("EtRatioFR_"+histcutname)] = new TH1F(TString("EtRatioFR_"+histcutname)," Summed track ET ratio distribution (FR)", 100,0.,1.0);
//All
hs1D[TString("chiAll_"+histcutname)] = new TH1F(TString("chiAll_"+histcutname)," #chi distribution (All)", 1000,0.,100.);
hs1D[TString("dzAll_"+histcutname)] = new TH1F(TString("dzAll_"+histcutname)," #Delta z distribution (All) [cm]", 1000,0.,100.);
//preselection only
hs1D[TString("medipXY_"+histcutname)] = new TH1F(TString("medipXY_"+histcutname)," <|IP_{2D}|> distribution [cm]", 200,0.,2.);
hs1D[TString("hjptaSR_"+histcutname)] = new TH1F(TString("hjptaSR_"+histcutname)," pT of emergng jets (SR)",100,0.,1000.);
hs1D[TString("hjptaFR_"+histcutname)] = new TH1F(TString("hjptaFR_"+histcutname)," pT of emergng jets (FR)",100,0.,1000.);
hs1D[TString("hetaaSR_"+histcutname)] = new TH1F(TString("hetaaSR_"+histcutname)," eta of emergng jets (SR)",100,-4.,4.);
hs1D[TString("hetaaFR_"+histcutname)] = new TH1F(TString("hetaaFR_"+histcutname)," eta of emergng jets (FR)",100,-4.,4.);
hs1D[TString("hntrkSR_"+histcutname)] = new TH1F(TString("hntrkSR_"+histcutname),"number tracks pt>1 (SR)",50,0.,50.);
hs1D[TString("hntrkFR_"+histcutname)] = new TH1F(TString("hntrkFR_"+histcutname),"number tracks pt>1 (FR)",50,0.,50.);
hs1D[TString("hmedipXYSigSR_"+histcutname)] = new TH1F(TString("hmedipXYSigSR_"+histcutname),"median ip_{sig} emerging jets (SR)",1000,0.,100.);
hs1D[TString("hmedipXYSigFR_"+histcutname)] = new TH1F(TString("hmedipXYSigFR_"+histcutname),"median ip_{sig} emerging jets (FR)",1000,0.,100.);
hs1D[TString("hlogmedipXYSigSR_"+histcutname)] = new TH1F(TString("hlogmedipXYSigSR_"+histcutname),
"median log_{10} ip_{sig} emerging jets (SR)",1000,-1.,4.);
hs1D[TString("hlogmedipXYSigFR_"+histcutname)] = new TH1F(TString("hlogmedipXYSigFR_"+histcutname),
"median log_{10} ip_{sig} emerging jets (FR)",1000,-1.,4.);
hs1D[TString("hmedtheta2DSR_"+histcutname)] = new TH1F(TString("hmedtheta2DSR_"+histcutname),
"median #hat{#Theta_{2D}} emerging jets (SR)",200,0.,0.4);
hs1D[TString("hmedtheta2DFR_"+histcutname)] = new TH1F(TString("hmedtheta2DFR_"+histcutname),
"median #hat{#Theta_{2D}} emerging jets (FR)",200,0.,0.4);
hs1D[TString("hlogmedtheta2DSR_"+histcutname)] = new TH1F(TString("hlogmedtheta2DSR_"+histcutname),
"median log_{10} #hat{#Theta_{2D}} emerging jets (SR)",1000,-3.5,0.5);
hs1D[TString("hlogmedtheta2DFR_"+histcutname)] = new TH1F(TString("hlogmedtheta2DFR_"+histcutname),
"median log_{10} #hat{#Theta_{2D}} emerging jets (FR)",1000,-3.5,0.5);
hs1D[TString("hmassSR_"+histcutname)] = new TH1F(TString("hmassSR_"+histcutname),"mass emerging and non pairs (SR)",500,0.,5000.);
hs1D[TString("hmassFR_"+histcutname)] = new TH1F(TString("hmassFR_"+histcutname),"mass emerging and non pairs (FR)",500,0.,5000.);
hs2D[TString("htheta2DvipXYSigSR_"+histcutname)] = new TH2F(TString("htheta2DvipXYSigSR_"+histcutname),
" #hat{#Theta}_{2D} vs. #hat{IP}^{2D}_{Sig} plot (SR)",100,0.,0.4,100,0.,10.0);
hs2D[TString("htheta2DvipXYSigFR_"+histcutname)] = new TH2F(TString("htheta2DvipXYSigFR_"+histcutname),
" #hat{#Theta}_{2D} vs. #hat{IP}^{2D}_{Sig} plot (FR)",100,0.,0.4,100,0.,10.0);
// Interesting plots
hs1D[TString("h_nemg_"+histcutname)] = new TH1F(TString("h_nemg_"+histcutname),"number of emerging jets",20,0.,20.);
hs1D[TString("h_nemgSR_"+histcutname)] = new TH1F(TString("h_nemgSR_"+histcutname),"number of emerging jets (SR)",20,0.,20.);
hs1D[TString("h_nemgFR_"+histcutname)] = new TH1F(TString("h_nemgFR_"+histcutname),"number of emerging jets (FR)",20,0.,20.);
hs1D[TString("h_nalemg_"+histcutname)] = new TH1F(TString("h_alnemg_"+histcutname),"number of almostemerging jets",20,0.,20.);
hs1D[TString("hnjet_"+histcutname)] = new TH1F(TString("hnjet_"+histcutname),"number of jets",20,0.,20.);
hs1D[TString("hnjetSR_"+histcutname)] = new TH1F(TString("hnjetSR_"+histcutname),"number of jets (SR)",20,0.,20.);
hs1D[TString("hnjetFR_"+histcutname)] = new TH1F(TString("hnjetFR_"+histcutname),"number of jets (FR)",20,0.,20.);
hs1D[TString("halpha_"+histcutname)] = new TH1F(TString("halpha_"+histcutname),"jet alpha distribution",1000,0.,1.0);
hs1D[TString("halphaZero_"+histcutname)] = new TH1F(TString("halphaZero_"+histcutname),"jet alpha==0 distribution",1000,-0.1,0.1);
hs1D[TString("H_TSR_"+histcutname)] = new TH1F(TString("H_TSR_"+histcutname)," HT distribution at end (SR)", 100,0.,5000.);
hs1D[TString("H_TFR_"+histcutname)] = new TH1F(TString("H_TFR_"+histcutname)," HT distribution at end (FR)", 100,0.,5000.);
}
}
//read all entries and fill the histograms
Int_t nentries = (Int_t)tt->GetEntries();
// counters
vector<double> np0(nCuts);
vector<double> np1(nCuts);
vector<double> np2(nCuts);
vector<double> np3(nCuts);
vector<int> nbTaggedTotAll(nCuts);//all jets
vector<int> nNotbTagTotAll(nCuts);//all jets
vector<int> nbTaggedTot(nCuts);//leading four jets
vector<int> nNotbTagTot(nCuts);//leading four jets
//======================
// Loop over events
//======================
for (Int_t i=0; i<nentries; i++) {
//std::cout<<"***event "<<event<<std::endl;
if (printCutSets) {
if (i==0) {
for (int iCut=0; iCut<nCuts; iCut++) {
int idx_=CutIdx[Cutstorun[iCut]];
if (iCut==0) {
std::cout << std::setw(14) << " "
<< std::setw(4) << "HT" << " "
<< std::setw(4) << "pt1" << " "
<< std::setw(4) << "pt2" << " "
<< std::setw(4) << "pt3" << " "
<< std::setw(4) << "pt4" << " "
<< std::setw(4) << "MET" << " "
<< std::setw(4) << "nemg" << " "
<< std::setw(10) << "(ntagType)" << " "
<< std::setw(4) << "PUdz" << " "
<< std::setw(5) << "3Dsig" << " "
<< std::setw(5) << "medIP" << " "
<< std::setw(10) << "alpha3Dcut"
<< std::endl;
}
std::cout << "Cutset[" << std::setw(4) << Cutstorun[iCut]
<< "]: "
<< std::setw(4) << DHTcuts[idx_] << " "
<< std::setw(4) << Dpt1cuts[idx_] << " "
<< std::setw(4) << Dpt2cuts[idx_] << " "
<< std::setw(4) << Dpt3cuts[idx_] << " "
<< std::setw(4) << Dpt4cuts[idx_] << " "
<< std::setw(4) << DMETcuts[idx_] << " "
<< std::setw(4) << Dnemcuts[idx_] << " ("
<< std::setw(8) << DntagTypes[idx_] << ") "
<< std::setw(4) << DPUdzCuts[idx_] << " "
<< std::setw(5) << DsigzCuts[idx_] << " "
<< std::setw(5) << DmedIPcuts[idx_] << " "
<< std::setw(10) << DalphaCuts[idx_] << std::endl;
}
}
}
for (int iCut=0; iCut<nCuts; iCut++) {
std::string cutname=Cutstorun[iCut];
std::string histcutname="Cutset"+Cutstorun[iCut];
if(!hasPre && otfile) hs1D[TString("eventCountPreTrigger_"+histcutname)]->Fill(1);
if(otfile) hs1D[TString("count_"+histcutname)]->Fill("All",1); // count number of events
if(otfile) hs1D[TString("acount_"+histcutname)]->Fill(0); // events passing JetFilter
}
tt->GetEntry(i);
// PV failure removal
if (pv_index->at(0) != 0) continue;
// PVZ cut
float pv_z = pv_zv->at(0);
if(fabs(pv_z)>15) continue;
const int NNNjet = jet_index->size();
// Note: we're only interested in events with at least four jets
if(NNNjet<4) continue;
// These counters are very important
// Do not move this outside event loop
vector<int> nbTaggedAll(nCuts);//# of all b-tagged jets
vector<int> nbTagged(nCuts);//# of b-tagged jets of leading four basic jets
int nZeroAlpha=0;
//======================
// Loop over cutsets
//======================
for (int eCut=0; eCut<nCuts; eCut++) {
std::string cutname=Cutstorun[eCut];
std::string histcutname="Cutset"+Cutstorun[eCut];
int eidx_=CutIdx[cutname];//for cuts only
if (minJetPt>Dpt4cuts[eidx_]) minJetPt = Dpt4cuts[eidx_];
//std::cout << "eCut = " << eCut << ":" << histcutname <<std::endl;
// Counting variables for PVTrackFraction
int nTotGoodTrk = 0;
int nGoodPVzTrk = 0;
switch (DntagTypes[eidx_]) {
case 0 : {NemergingCut=0; break;}
case 1 : {NemergingCut=1; break;}
case 12: {NemergingCut=1; break;}
case 2 : {NemergingCut=2; break;}
case 21: {NemergingCut=2; break;}
case 22: {NemergingCut=2; break;}
case 3 : {NemergingCut=3; break;}
}
vector<double> jet_fmaxtrkpt(NNNjet);
vector<int> jet_ntrkpt1(NNNjet);
vector<float> jet_alpha(NNNjet);
vector<float> jet_medip(NNNjet);
vector<float> jet_medipsig(NNNjet);
vector<float> jet_logmedipsig(NNNjet);
vector<float> jet_medtheta2D(NNNjet);
vector<float> jet_logmedtheta2D(NNNjet);
vector<int> jntrack(NNNjet);
vector<float> jet_e(NNNjet);
vector<float> jet_theta(NNNjet);
vector<float> jet_px(NNNjet);
vector<float> jet_py(NNNjet);
vector<float> jet_pz(NNNjet);
vector<int> jet_pid_maxEt(NNNjet);
vector<float> jet_maxET_part(NNNjet);
vector<float> dRjtrk0(NNNjet);//CSVv2 variable
vector<float> dRjtrk(NNNjet);
vector<float> djtrk(NNNjet);//CSVv2 variable
//vector<float> EtRatio(NNNjet);//CSVv2 variable
if(otfile) hs1D[TString("hnjet_"+histcutname)]->Fill(NNNjet);
//======================
// First loop over jets
//======================
for(Int_t j=0; j<NNNjet; j++) {
// std::cout<<"jet j = "<<j<<std::endl;
jet_theta[j]=2.*atan(exp(-jet_eta->at(j)));
jet_e[j]=jet_pt->at(j)/sin(jet_theta[j]);
jet_px[j]=jet_pt->at(j)*cos(jet_phi->at(j));
jet_py[j]=jet_pt->at(j)*sin(jet_phi->at(j));
jet_pz[j]=jet_pt->at(j)/tan(jet_theta[j]);
jet_ntrkpt1[j]=0;
jet_medip[j]=-1.;
jet_medipsig[j]=-1.;
jet_logmedipsig[j]=-1.;
jet_medtheta2D[j]=-1.;
jet_logmedtheta2D[j]=-3.5;
jet_alpha[j]=-1.;
jet_fmaxtrkpt[j]=0.;
vector<float> track_pts = track_pt->at(j);
vector<float> track_etas = track_eta->at(j);
vector<float> track_phis = track_phi->at(j);
vector<int> track_sources = track_source->at(j);
vector<int> track_qualitys = track_quality->at(j);
//vector<float> track_pvWeights = track_pvWeight->at(j);
vector<float> track_ipXYs = track_ipXY->at(j);
vector<float> track_ipXYSigs = track_ipXYSig->at(j);
vector<float> track_dRToJetAxiss = track_dRToJetAxis->at(j);
vector<float> track_distanceToJets = track_distanceToJet->at(j);
//vector<TLorentzVector> track_p4s = track_p4->at(j);//not in ntuple
vector<float> sort_ip(track_pts.size());
vector<float> sort_ipsig(track_pts.size());
for(uint it=0;it<track_pts.size();it++) sort_ip[it]=0;
for(uint it=0;it<track_pts.size();it++) sort_ipsig[it]=0;
vector<float> jet_trkip;
vector<float> jet_trkipsig;
vector<float> track_ref_zs = track_ref_z->at(j);
// jet_alpha
jet_alpha[j] = qcdtools->GetAlpha3Dsig(track_pts,track_sources,track_qualitys,track_ipXYSigs,track_ref_zs,pv_z,DPUdzCuts[eidx_],DsigzCuts[eidx_]);
if (jet_alpha[j]==0) nZeroAlpha++;
jntrack[j]=0;
dRjtrk0[j]=0;
dRjtrk[j]=0;
djtrk[j]=0;
double ptmaxtrk=0.;
double IP2DSigMax=0.;
//TLorentzVector SumTrkP4 (0.,0.,0.,0.);
double ptsum_total=0, ptsum=0;
//===================================
// Loop over tracks of first jet loop
//===================================
for (unsigned itrack=0; itrack<track_pts.size(); itrack++) {
if(track_sources[itrack]==0 && ((track_qualitys[itrack] & 4) > 0)) {
// PVTrackFraction use tracks without pilecut
nTotGoodTrk++;//Count good tracks for PVTrackFraction
if (fabs(pv_z-track_ref_zs[itrack])<pvztrkcut) nGoodPVzTrk++;//Count good tracks passing pvztkcut for PVTrackFraction
hs1D[TString("dzAll_"+histcutname)]->Fill(fabs(pv_z-track_ref_zs[itrack]));
// pileup cut
if (fabs(pv_z-track_ref_zs[itrack])>DPUdzCuts[eidx_]) continue;// remove tracks with exceedingly large z
ptsum_total += track_pts[itrack];
double track_chi = sqrt(pow((pv_z-track_ref_zs[itrack])/0.01,2)+pow(track_ipXYSigs[itrack],2));
hs1D[TString("chiAll_"+histcutname)]->Fill(track_chi);
if (track_chi < DsigzCuts[eidx_]) ptsum += track_pts[itrack];
if(track_pts[itrack]>ptmaxtrk) {
ptmaxtrk=track_pts[itrack];
}
if(track_ipXYSigs[itrack]>IP2DSigMax) {
IP2DSigMax=track_ipXYSigs[itrack];
dRjtrk0[j]=DeltaR(jet_eta->at(j),jet_phi->at(j),track_etas[itrack],track_phis[itrack]);
dRjtrk[j]=track_dRToJetAxiss[itrack];
djtrk[j]=track_distanceToJets[itrack];
}
//SumTrkP4+=track_p4s[itrack];
sort_ip[jntrack[j]]=fabs(track_ipXYs[itrack]);
sort_ipsig[jntrack[j]]=fabs(track_ipXYSigs[itrack]);
// std::cout<<"track vertex weight is "<<track_vertex_weights[itrack]<<std::endl;
if(track_pts[itrack]>1) jet_ntrkpt1[j]+=1;
jet_trkip.push_back(fabs(track_ipXYs[itrack]));
jet_trkipsig.push_back(fabs(track_ipXYSigs[itrack]));
jntrack[j]++;
}
}
double alpha_temp = (ptsum_total > 0 ? ptsum/ptsum_total : 0.);
if (fabs(alpha_temp - jet_alpha[j])>1.e-7) {
std::cout << "WARNING!!! alpha 3D calculation maybe imprecise: alpha_temp = "
<< std::setprecision(9) << alpha_temp << " != jet_alpha = "
<< jet_alpha[j] << std::endl;
}
//=======================================
// End loop over tracks of first jet loop
//=======================================
float atmp = jntrack[j];
if(jntrack[j]>0) {
// median
jet_medip[j] = CalcMedian(jet_trkip);
jet_medipsig[j] = CalcMedian(jet_trkipsig);
jet_logmedipsig[j] = log10(jet_medipsig[j]);
jet_medtheta2D[j] = jet_theta2D->at(j);
jet_logmedtheta2D[j] = (jet_medtheta2D[j]==-1 ? -3.5 : log10(jet_theta2D->at(j)));
}
jet_fmaxtrkpt[j]=ptmaxtrk/jet_pt->at(j);//max trk pt/jet pt//analysis_20170523_v0
//EtRatio[j]=SumTrkP4.Perp()/jet_pt->at(j);
std::sort(sort_ip.begin(), sort_ip.end(), std::greater<float>());
std::sort(sort_ipsig.begin(), sort_ipsig.end(), std::greater<float>());
//===================================
// Jet flavor id
//===================================
jet_pid_maxEt[j]=0;
jet_maxET_part[j]=0;
if (!isData) {
// calculate some gen particle information for jet
int NNNgp = gp_index->size();
int igenmax=-1;
float etgenmax=0.;
for(Int_t igen=1; igen<NNNgp; igen++) {
if((abs(gp_pdgId->at(igen))<6)||(abs(gp_pdgId->at(igen))==21)) { // quark or gluon
if(DeltaR(jet_eta->at(j),jet_phi->at(j),gp_eta->at(igen),gp_phi->at(igen))<0.4) {
if(gp_pt->at(igen)>etgenmax) {
igenmax=igen;
etgenmax=gp_pt->at(igen);
}
}
}
}
// fix glue to bbbar
float igenmax2=-1;
float etgenmax2=0.;
if(igenmax>0) {
if(abs(gp_pdgId->at(igenmax))==21) {
for(Int_t igen=1; igen<NNNgp; igen++) {
if((abs(gp_pdgId->at(igen))==5)&&(gp_pt->at(igen)>10.)) { // b
if(DeltaR(jet_eta->at(j),jet_phi->at(j),gp_eta->at(igen),gp_phi->at(igen))<0.4) {
if(gp_pt->at(igen)>etgenmax2) {
igenmax2=1;
etgenmax2=gp_pt->at(igen);
}
}
}
}
}
}
if(igenmax>-1) {
int ipid = gp_pdgId->at(igenmax);
if(abs(ipid)<6) {
jet_pid_maxEt[j]=gp_pdgId->at(igenmax);
jet_maxET_part[j] = etgenmax;
} else {
if(igenmax2==-1) {
jet_pid_maxEt[j]=7;
jet_maxET_part[j] = etgenmax;
} else {//g->bb
jet_pid_maxEt[j]=8;
jet_maxET_part[j] = etgenmax;
}
}
} // end calculate some gen particle information for jet
}//end of MC truth only block
if(jet_csv->at(j) >= bTagWP) {
if (isData) jet_pid_maxEt[j]=5;
nbTaggedTotAll[eCut]++;
nbTaggedAll[eCut]++;
//std::cout << "Jet b-tagged." << std::endl;
}
else {
if (isData) jet_pid_maxEt[j]=0;
nNotbTagTotAll[eCut]++;
//std::cout << "Jet not b-tagged." << std::endl;
}
}
//===================================
// End of first loop over jets
//===================================
float PVTrackFraction = (float)nGoodPVzTrk/(float)nTotGoodTrk;
//std::cout <<"PVTrackFraction = " << PVTrackFraction << std::endl;
//now see which jets are emerging
// std::cout<<" in event "<<event<<" number of jets is "<<NNNjet<<std::endl;
vector<bool> emerging(NNNjet);
vector<bool> almostemerging(NNNjet);
vector<bool> basicjet(NNNjet);
for( int i=0;i<NNNjet;i++) {
emerging[i]=false;
almostemerging[i]=false;
basicjet[i]=false;
}
int nemerging=0;
int nalmostemerging=0;
//===================================
// Second loop over jets
// Jet selection
//===================================
for(int ij=0;ij<NNNjet;ij++) {
vector<int> track_qualitys = track_quality->at(ij);
vector<float> track_ipXYs = track_ipXY->at(ij);
vector<float> track_ipXYSigs = track_ipXYSig->at(ij);
vector<int> track_sources = track_source->at(ij);
//vector<float> track_vertex_weights = track_vertex_weight->at(ij);
//vector<float> track_pvWeights = track_pvWeight->at(ij);
vector<float> track_ref_zs = track_ref_z->at(ij);//analysis_20170523_v0
if(fabs(jet_eta->at(ij))<jetacut) { // jet eta cut
if(jet_nef->at(ij)<NemfracCut) { // neutral fraction
if(jet_ntrkpt1[ij]>ntrk1cut) { // tracks pt>1
if(jet_cef->at(ij)<CemfracCut) { //charged fraction
if(jet_fmaxtrkpt[ij]>0.6) continue;//analysis_20170523_v0
//basicjet[ij]=true;
if(ij<4) {
basicjet[ij]=true;
// # of btagged for leading 4 jets
if(jet_csv->at(ij) >= bTagWP) {
nbTaggedTot[eCut]++;
nbTagged[eCut]++;
//std::cout << "Jet b-tagged." << std::endl;
}
else {
nNotbTagTot[eCut]++;
//std::cout << "Jet not b-tagged." << std::endl;
}
}
//if(jet_alpha[ij]<DalphaCuts[eidx_]) { // alpha max
if(jet_alpha[ij]<DalphaCuts[eidx_] && jet_alpha[ij]>-1) { // alpha max
almostemerging[ij]=true;
// uncomment if count only leading jets for event selection later
if(ij<4)
nalmostemerging+=1;
//if(jet_medip[ij]>DmedIPcuts[eidx_]) { // med IP cut
if(jet_medip[ij]>DmedIPcuts[eidx_] && jet_medtheta2D[ij]>0) { // med IP cut
emerging[ij]=true;
// uncomment if count only leading jets for event selection later
if(ij<4)
nemerging+=1;
}//medIPcut
}//alphaMaxCut
}//CemfractCut
}//ntrk1cut
}//NemfracCut
}//jet eta cut
}
//===================================
// End of second loop over jets
//===================================
if(otfile) hs1D[TString("h_nalemg_"+histcutname)]->Fill(nalmostemerging);
if(otfile) hs1D[TString("h_nemg_"+histcutname)]->Fill(nemerging);
// *************************************************************
// now start the event selection preparation
// *************************************************************
if(otfile) hs1D[TString("count_"+histcutname)]->Fill("filter",1);
if(otfile) hs1D[TString("acount_"+histcutname)]->Fill(1);
// PVTrackFraction cut introduced after AN-16-146_v2
if (PVTrackFraction<=0.1) continue;
//if (nZeroAlpha>2) continue;//AN-16-146_v2
// require at least 4 jets
bool C4jet=true;
int nemgGoodjet = 0;
int nalemgGoodjet = 0;
vector<int> goodjetIdx;
//for(int nj=0;nj<NNNjet;nj++) {
for(int nj=0;nj<4;nj++) {
if (!basicjet[nj] || jet_pt->at(nj)<minJetPt) continue;//comment out this line for leading four jets
goodjetIdx.push_back(nj);
//std::cout << "Idx[" << nj <<"] is good jet" << std::endl;
if (emerging[nj]) nemgGoodjet+=1;
if (almostemerging[nj]) nalemgGoodjet+=1;
if(otfile) {
hs1D[TString("halpha_"+histcutname)]->Fill(jet_alpha[nj]);
hs1D[TString("medipXY_"+histcutname)]->Fill(jet_medip[nj]);
if (jet_alpha[nj]==0) hs1D[TString("halphaZero_"+histcutname)]->Fill(jet_alpha[nj]);
}
}
// bool PVreco = false;
// if (nZeroAlpha<3) PVreco=true;
//if(NNNjet<4) continue;
if(goodjetIdx.size()!=4) {
//if(goodjetIdx.size()<4) {
C4jet=false;
continue;
}
// HT
double HT = jet_pt->at(0)+jet_pt->at(1)+jet_pt->at(2)+jet_pt->at(3);
// HLT efficiency plots:
bool HLT=false;
if (hltTrig3n) HLT=true;
bool CHT=true;
if(HT<DHTcuts[eidx_]) CHT=false;
// jet pt
bool Cpt1=false;
bool Cpt2=false;
bool Cpt3=false;
bool Cpt4=false;
if((jet_pt->at(0)>Dpt1cuts[eidx_])&&(fabs(jet_eta->at(0))<jetacut)) Cpt1=true;
if((jet_pt->at(1)>Dpt2cuts[eidx_])&&(fabs(jet_eta->at(1))<jetacut)) Cpt2=true;
if((jet_pt->at(2)>Dpt3cuts[eidx_])&&(fabs(jet_eta->at(2))<jetacut)) Cpt3=true;
if((jet_pt->at(3)>Dpt4cuts[eidx_])&&(fabs(jet_eta->at(3))<jetacut)) Cpt4=true;
// basicjet includes eta cut already
// if(jet_pt->at(goodjetIdx[0])>Dpt1cuts[eidx_]) Cpt1=true;
// if(jet_pt->at(goodjetIdx[1])>Dpt2cuts[eidx_]) Cpt2=true;
// if(jet_pt->at(goodjetIdx[2])>Dpt3cuts[eidx_]) Cpt3=true;
// if(jet_pt->at(goodjetIdx[3])>Dpt4cuts[eidx_]) Cpt4=true;
// number emerging jets
bool Cnem = true;
if(nemerging<NemergingCut) Cnem=false;
//if(nemerging!=NemergingCut) Cnem=false;
bool Canem =true;
//if(nalmostemerging>=4) Canem=false;
//if(nalemgGoodjet>=4) Canem=false;
bool Cmet = false;
if(met_pt>DMETcuts[eidx_]) Cmet = true;
//blind
if(blind) {
Cnem=false;
//Canem=false;
}
// *************************************************************
// End of the event selection preparation
// *************************************************************
// *************************************************************
// apply event selection cuts sequentially
// *************************************************************
// std::cout<<"c4jet cht cpt1 cpt2 cpt3 cpt4 cnem "<<C4jet<<" "<<CHT<<" "<<Cpt1<<" "<<Cpt2<<" "<<Cpt3<<" "<<Cpt4<<" "<<Cnem<<std::endl;
if(C4jet) {
if(otfile) hs1D[TString("count_"+histcutname)]->Fill("4 jets",1);
if(otfile) hs1D[TString("acount_"+histcutname)]->Fill(2);
// calculate HT and require it greater than some cut value
//if(HLT && CHT && PVreco) {
if(HLT && CHT) {
if(otfile) hs1D[TString("count_"+histcutname)]->Fill("HT",1);
if(otfile) hs1D[TString("acount_"+histcutname)]->Fill(3);
// do pT cuts on jets
if(Cpt1) {
if(otfile) hs1D[TString("count_"+histcutname)]->Fill("jet pt1",1);
if(otfile) hs1D[TString("acount_"+histcutname)]->Fill(4);
if(Cpt2) {
if(otfile) hs1D[TString("count_"+histcutname)]->Fill("jet pt2",1);
if(otfile) hs1D[TString("acount_"+histcutname)]->Fill(5);
if(Cpt3) {
if(otfile) hs1D[TString("count_"+histcutname)]->Fill("jet pt3",1);
if(otfile) hs1D[TString("acount_"+histcutname)]->Fill(6);
if(Cpt4) {
int njetsFR = 4;
//int njetsFR = goodjetIdx.size();
if(otfile) hs1D[TString("count_"+histcutname)]->Fill("jet pt4",1);
if(otfile) hs1D[TString("acount_"+histcutname)]->Fill(7);
//std::cout << "# btagged = " << nbTagged[eCut] << " for evt#: " << event << std::endl;
// MET cut
if (!Cmet) continue;
if(otfile) hs1D[TString("count_"+histcutname)]->Fill("MET",1);
if(otfile) hs1D[TString("acount_"+histcutname)]->Fill(8);
if(otfile) {//Data-driven fake background
//if( ( Canem || (isData && nalmostemerging<4) ) ) {if(otfile) hs1D[TString("h_nemgSR_"+histcutname)]->Fill(nemerging);}
if( Canem ) {if(otfile && !blind) hs1D[TString("h_nemgSR_"+histcutname)]->Fill(nemerging);}
//if( (nemgGoodjet < 1) && ( Canem || (isData && nalemgGoodjet<4) ) ) {
//if( (nemerging < 1) && ( Canem || (isData && nalmostemerging<4) ) ) {
if( (nemerging < 1) && Canem ) {
//if( Canem ) {
//if ( !Cnem && Canem) {
//if( Canem || (isData && blind && nalemgGoodjet<4) ) {
//if(otfile) hs1D[TString("h_nemgSR_"+histcutname)]->Fill(nemerging);
//if(otfile) hs1D[TString("h_nemgSR_"+histcutname)]->Fill(nemgGoodjet);
//std::cout << "# btagged = " << nbTagged[eCut] << " for evt#: " << event << std::endl;
// ********************************
// Data-driven fake background
// ********************************
int ngoodjet = 0;
for(int nj=0;nj<njetsFR;nj++) {
if (!basicjet[nj] || jet_pt->at(nj)<minJetPt) continue;
ngoodjet+=1;
}
// ngoodjet should be = goodjetIdx.size()
//std::cout << "ngoodjet = " << ngoodjet << " ?= " << "goodjetIdx.size() = " << goodjetIdx.size() << std::endl;
//double nGJwgt = nGJrewgt(goodjetIdx.size());
double nGJwgt = 1.0;
// Default:
double frwgt0 = qcdtools->frWeightFT0(jet_pt,jet_eta,goodjetIdx,jntrack,
jet_pid_maxEt,njetsFR,minJetPt,varType,cutname);
double frwgt1 = qcdtools->frWeightFT1(jet_pt,jet_eta,goodjetIdx,jntrack,
jet_pid_maxEt,njetsFR,minJetPt,varType,cutname);
double frwgt2 = qcdtools->frWeightFT2(jet_pt,jet_eta,goodjetIdx,jntrack,
jet_pid_maxEt,njetsFR,minJetPt,varType,cutname);
double frwgt3 = qcdtools->frWeightFT3(jet_pt,jet_eta,goodjetIdx,jntrack,
jet_pid_maxEt,njetsFR,minJetPt,varType,cutname);
// Alternatives:
double frwgt12 = qcdtools->frWeightFT12(jet_pt,jet_eta,goodjetIdx,jntrack,
minJetPt,bUnfType,nbTagged[eCut],ptType,varType,isData,cutname);
double frwgt21 = qcdtools->frWeightT21(jet_pt,jet_eta,goodjetIdx,jntrack,
njetsFR,minJetPt,varType);
double frwgt22 = qcdtools->frWeightFT22(jet_pt,jet_eta,goodjetIdx,jntrack,
minJetPt,bUnfType,nbTagged[eCut],ptType,varType,isData,cutname);
double frwgtge2 = qcdtools->frWeight1(jet_pt,jet_eta,goodjetIdx,jntrack,
njetsFR,minJetPt,varType);
// Choose event-wise weight
double frwgt = 1.0;
switch (DntagTypes[eidx_]) {
case 0 : frwgt = nGJwgt*(1.0 - frwgt0); break;//>=1 tag
case 1 : frwgt = nGJwgt*frwgt1; break;//==1 tag
case 2 : frwgt = nGJwgt*frwgt2; break;//==2 tag
case 3 : frwgt = nGJwgt*frwgt3; break;//==3 tag (not implemented yet)
case 12: frwgt = nGJwgt*frwgt12; break;//==1 tag
case 21: frwgt = nGJwgt*frwgt21; break;//==2 tag; tag-and-probe
case 22: frwgt = nGJwgt*frwgt22; break;//==2 tag; ture b unfolded
default: frwgt = nGJwgt*frwgtge2; break;//>=2tag (need to check calculation)
}
// Fill histograms
hs1D[TString("hnjetFR_"+histcutname)]->Fill(ngoodjet,frwgt);
hs1D[TString("count_"+histcutname)]->Fill("FakeRateBKG",frwgt);
hs1D[TString("acount_"+histcutname)]->Fill(11,frwgt);
hs1D[TString("H_TFR_"+histcutname)]->Fill(HT,frwgt);
hs1D[TString("METFR_"+histcutname)]->Fill(met_pt,frwgt);
np0[eCut] += frwgt0;
for(int i=0;i<4;i++) {
int idx = goodjetIdx[i];
std::ostringstream ss;
ss << i+1;
//std::cout << "hjpt" << ss.str() << "FR_" << histcutname << std::endl;
hs1D[TString("hjpt"+ss.str()+"FR_"+histcutname)]->Fill(jet_pt->at(idx),frwgt);
hs1D[TString("heta"+ss.str()+"FR_"+histcutname)]->Fill(jet_eta->at(idx),frwgt);
//hs1D[TString("EtRatioFR_"+histcutname)]->Fill(EtRatio[idx],frwgt);
hs1D[TString("dRjtrk0FR_"+histcutname)]->Fill(dRjtrk0[idx],frwgt);
hs1D[TString("dRjtrkFR_"+histcutname)]->Fill(dRjtrk[idx],frwgt);
hs1D[TString("djtrkFR_"+histcutname)]->Fill(djtrk[idx],frwgt);
}
if (DntagTypes[eidx_]==1) np1[eCut] += frwgt1;
else np1[eCut] += frwgt12;
if (DntagTypes[eidx_]==21) np2[eCut] += frwgt21;
else if (DntagTypes[eidx_]==22 || DntagTypes[eidx_]==12) np2[eCut] += frwgt22;
else np2[eCut] += frwgt2;
np3[eCut] += frwgt3;
hs1D[TString("h_nemgFR_"+histcutname)]->Fill(0.0,qcdtools->frWeightFT0(jet_pt,jet_eta,goodjetIdx,jntrack,
jet_pid_maxEt,njetsFR,minJetPt,varType,cutname));
// ntag==1 cases:
if (DntagTypes[eidx_]==1)
hs1D[TString("h_nemgFR_"+histcutname)]->Fill(1.0,qcdtools->frWeightFT1(jet_pt,jet_eta,goodjetIdx,jntrack,
jet_pid_maxEt,njetsFR,minJetPt,varType,cutname));
else
hs1D[TString("h_nemgFR_"+histcutname)]->Fill(1.0,qcdtools->frWeightFT12(jet_pt,jet_eta,goodjetIdx,jntrack,
minJetPt,bUnfType,nbTagged[eCut],ptType,varType,isData,cutname));
// ntag==2 cases:
if (DntagTypes[eidx_]==21)
hs1D[TString("h_nemgFR_"+histcutname)]->Fill(2.0,qcdtools->frWeightT21(jet_pt,jet_eta,goodjetIdx,jntrack,
njetsFR,minJetPt,varType));
else if (DntagTypes[eidx_]==22)
hs1D[TString("h_nemgFR_"+histcutname)]->Fill(2.0,qcdtools->frWeightFT22(jet_pt,jet_eta,goodjetIdx,jntrack,
minJetPt,bUnfType,nbTagged[eCut],ptType,varType,isData,cutname));
else
hs1D[TString("h_nemgFR_"+histcutname)]->Fill(2.0,qcdtools->frWeightFT2(jet_pt,jet_eta,goodjetIdx,jntrack,
jet_pid_maxEt,njetsFR,minJetPt,varType,cutname));
// end ntag==2 cases
hs1D[TString("h_nemgFR_"+histcutname)]->Fill(3.0,qcdtools->frWeightFT3(jet_pt,jet_eta,goodjetIdx,jntrack,
jet_pid_maxEt,njetsFR,minJetPt,varType,cutname));
//hs1D[TString("h_nemgFR_"+histcutname)]->Fill(4.0,1-frwgt0-frwgt1-frwgt2);//x-check w.r.t. 3.0 ==> verified
switch (DntagTypes[eidx_]) {
case 1: {
// For Ntag==1
for(int i3=0;i3<njetsFR;i3++) {
int idx3 = goodjetIdx[i3];
double jfr = qcdtools->fakerateF(jet_pt->at(idx3),jet_eta->at(idx3),jntrack[idx3],
varType,jet_pid_maxEt[idx3],cutname);
for(int i31=0;i31<njetsFR;i31++) {
int idx31 = goodjetIdx[i31];
if (i31 != i3) jfr *= (1.0-qcdtools->fakerateF(jet_pt->at(idx31),jet_eta->at(idx31),
jntrack[idx31],varType,jet_pid_maxEt[idx31],cutname));
}
if (!basicjet[idx3] || jet_pt->at(idx3)<minJetPt) continue;
hs1D[TString("hjptaFR_"+histcutname)]->Fill(jet_pt->at(idx3),jfr);
hs1D[TString("hetaaFR_"+histcutname)]->Fill(jet_eta->at(idx3),jfr);
hs1D[TString("hntrkFR_"+histcutname)]->Fill(jntrack[idx3],jfr);
hs1D[TString("hmedipXYSigFR_"+histcutname)]->Fill(jet_medipsig[idx3],jfr);
hs1D[TString("hlogmedipXYSigFR_"+histcutname)]->Fill(jet_logmedipsig[idx3],jfr);
hs1D[TString("hmedtheta2DFR_"+histcutname)]->Fill(jet_medtheta2D[idx3],jfr);
hs1D[TString("hlogmedtheta2DFR_"+histcutname)]->Fill(jet_logmedtheta2D[idx3],jfr);
hs2D[TString("htheta2DvipXYSigFR_"+histcutname)]->Fill(jet_medtheta2D[idx3],jet_medipsig[idx3],jfr);
for(int i4=0;i4<njetsFR;i4++) {
if (i4 == i3) continue;
int idx4 = goodjetIdx[i4];
if (!basicjet[idx4] || jet_pt->at(idx4)<minJetPt) continue;
double mass = sqrt(
pow((jet_e[idx3]+jet_e[idx4]),2) -
pow((jet_px[idx3]+jet_px[idx4]),2) -
pow((jet_py[idx3]+jet_py[idx4]),2) -
pow((jet_pz[idx3]+jet_pz[idx4]),2)
);
hs1D[TString("hmassFR_"+histcutname)]->Fill(mass,jfr);
}
}
break;
}//end case 1 (Ntag==1)
case 12: {
char *hnames[9]={(char*)"hjptaFR",(char*)"hetaaFR",(char*)"hntrkFR",
(char*)"hmedipXYSigFR",(char*)"hlogmedipXYSigFR",(char*)"hmedtheta2DFR",
(char*)"hlogmedtheta2DFR",(char*)"hmassFR",(char*)"htheta2DvipXYSigFR"};
// For Ntag==1; flav dep; data unfolded; only for 4 jet events
double frwgttmp=0.;
double frwgts[5];
TMatrixD Mwgt(5,5);
bool goodWgt = qcdtools->UnfoldWgtPtDep(Mwgt, bUnfType, jet_pt, isData);
if (!goodWgt) {
std::cout << "Bad unfolding matrix inversion!" << std::endl;
}
// loop # unfolded "true" b jets
for (int nbT=0;nbT<5;nbT++){
double evtWgt = 0.0;
//if (isData) evtWgt = qcdtools->UnfoldWgtD(bUnfType, nbT, nbTagged[eCut], ptType);
//else evtWgt = qcdtools->UnfoldWgt(bUnfType, nbT, nbTagged[eCut], ptType);
//evtWgt=qcdtools->UnfoldWgtPtDep(bUnfType, nbT, nbTagged[eCut], jet_pt, isData);
evtWgt=Mwgt(nbT, nbTagged[eCut]);
int ncomb=1;
switch (nbT) {
case 1: ncomb=4; break;
case 2: ncomb=6; break;
case 3: ncomb=4; break;
default: break;
}
evtWgt/=ncomb;
switch (nbT) {
case 0: {
int flavors[] = {0,0,0,0};
qcdtools->frWeightUFT1(frwgts,jet_pt,jet_eta,goodjetIdx,jntrack,flavors,varType,isData,cutname);
frwgttmp+=(evtWgt*frwgts[4]);
qcdtools->fillFRPlots(histcutname,hnames,
jet_pt, jet_eta, goodjetIdx,jntrack,jet_medipsig,jet_logmedipsig,
jet_medtheta2D, jet_logmedtheta2D,
jet_e,jet_px,jet_py,jet_pz,
frwgts, evtWgt,1.0);
break;}
case 1: {
for (int fidx=0;fidx<4;fidx++) {
int flavors[] = {0,0,0,0};
flavors[fidx]=5;
qcdtools->frWeightUFT1(frwgts,jet_pt,jet_eta,goodjetIdx,jntrack,flavors,varType,isData,cutname);
frwgttmp+=(evtWgt*frwgts[4]);
qcdtools->fillFRPlots(histcutname,hnames,
jet_pt, jet_eta, goodjetIdx,jntrack,jet_medipsig,jet_logmedipsig,
jet_medtheta2D, jet_logmedtheta2D,
jet_e,jet_px,jet_py,jet_pz,
frwgts, evtWgt,1.0);
}
break;}
case 2: {
//flavor double counted due to looping
for (int fidx0=0;fidx0<4;fidx0++) {
for (int fidx1=fidx0+1;fidx1<4;fidx1++) {
int flavors[] = {0,0,0,0};
flavors[fidx0]=5;
flavors[fidx1]=5;
qcdtools->frWeightUFT1(frwgts,jet_pt,jet_eta,goodjetIdx,jntrack,flavors,varType,isData,cutname);
frwgttmp+=(evtWgt*frwgts[4]);
qcdtools->fillFRPlots(histcutname,hnames,
jet_pt, jet_eta, goodjetIdx,jntrack,jet_medipsig,jet_logmedipsig,
jet_medtheta2D, jet_logmedtheta2D,
jet_e,jet_px,jet_py,jet_pz,
frwgts, evtWgt,1.0);
}
}
break;}
case 3: {
for (int fidx=0;fidx<4;fidx++) {
int flavors[] = {5,5,5,5};
flavors[fidx]=0;
qcdtools->frWeightUFT1(frwgts,jet_pt,jet_eta,goodjetIdx,jntrack,flavors,varType,isData,cutname);
frwgttmp+=(evtWgt*frwgts[4]);
qcdtools->fillFRPlots(histcutname,hnames,
jet_pt, jet_eta, goodjetIdx,jntrack,jet_medipsig,jet_logmedipsig,
jet_medtheta2D, jet_logmedtheta2D,
jet_e,jet_px,jet_py,jet_pz,
frwgts, evtWgt,1.0);
}
break;}
case 4: {
int flavors[] = {5,5,5,5};
qcdtools->frWeightUFT1(frwgts,jet_pt,jet_eta,goodjetIdx,jntrack,flavors,varType,isData,cutname);
frwgttmp+=(evtWgt*frwgts[4]);
qcdtools->fillFRPlots(histcutname,hnames,
jet_pt, jet_eta, goodjetIdx,jntrack,jet_medipsig,jet_logmedipsig,
jet_medtheta2D, jet_logmedtheta2D,
jet_e,jet_px,jet_py,jet_pz,
frwgts, evtWgt,1.0);
break;}
}
}
if (fabs(frwgt-frwgttmp)>1.e-7) {
std::cout << "[WARNING] frwgt = " << std::setprecision(9)
<< frwgt << " != frwgttmp = " << frwgttmp << "!!!!" << std::endl;
}
break;
}//end case 12 (Ntag==1; flav dep; data unfolded)
case 2: {
// For Ntag==2; flav dep
double frwgttmp=0.;
for(int i1=0;i1<njetsFR;i1++) {
int idx1 = goodjetIdx[i1];
if (!basicjet[idx1] || jet_pt->at(idx1)<minJetPt) continue;
double jfr = qcdtools->fakerateF(jet_pt->at(idx1),jet_eta->at(idx1),jntrack[idx1],
varType,jet_pid_maxEt[idx1],cutname);
for(int i2=0;i2<njetsFR;i2++) {
int idx2 = goodjetIdx[i2];
if (!basicjet[idx2] || jet_pt->at(idx2)<minJetPt) continue;
if (i2==i1) continue;
double kfr = jfr*(1.0-qcdtools->fakerateF(jet_pt->at(idx2),jet_eta->at(idx2),jntrack[idx2],
varType,jet_pid_maxEt[idx2],cutname));
for(int i3=0;i3<njetsFR;i3++) {
if (i3==i1 || i3==i2) continue;
int idx3 = goodjetIdx[i3];
if (!basicjet[idx3] || jet_pt->at(idx3)<minJetPt) continue;
double lfr = kfr*qcdtools->fakerateF(jet_pt->at(idx3),jet_eta->at(idx3),jntrack[idx3],
varType,jet_pid_maxEt[idx3],cutname);
for(int i4=0;i4<njetsFR;i4++) {
if (i4==i1 || i4==i2 || i4==i3) continue;
int idx4 = goodjetIdx[i4];
if (!basicjet[idx4] || jet_pt->at(idx4)<minJetPt) continue;
lfr *= (1.0-qcdtools->fakerateF(jet_pt->at(idx4),jet_eta->at(idx4),jntrack[idx4],
varType,jet_pid_maxEt[idx4],cutname));
}
//take care of combinatorics: e.g., var(1) double counted by (1_tag,2)(3_tag,4) and (1_tag,4)(3_tag,2)
double varWgt = lfr/(ngoodjet-2);
frwgttmp += varWgt;
hs1D[TString("hjptaFR_"+histcutname)]->Fill(jet_pt->at(idx1),varWgt);
hs1D[TString("hetaaFR_"+histcutname)]->Fill(jet_eta->at(idx1),varWgt);
hs1D[TString("hntrkFR_"+histcutname)]->Fill(jntrack[idx1],varWgt);
hs1D[TString("hmedipXYSigFR_"+histcutname)]->Fill(jet_medipsig[idx1],varWgt);
hs1D[TString("hlogmedipXYSigFR_"+histcutname)]->Fill(jet_logmedipsig[idx1],varWgt);
hs1D[TString("hmedtheta2DFR_"+histcutname)]->Fill(jet_medtheta2D[idx1],varWgt);
hs1D[TString("hlogmedtheta2DFR_"+histcutname)]->Fill(jet_logmedtheta2D[idx1],varWgt);
hs2D[TString("htheta2DvipXYSigFR_"+histcutname)]->Fill(jet_medtheta2D[idx1],jet_medipsig[idx1],varWgt);
double mass = sqrt(
pow((jet_e[idx1]+jet_e[idx2]),2) -
pow((jet_px[idx1]+jet_px[idx2]),2) -
pow((jet_py[idx1]+jet_py[idx2]),2) -
pow((jet_pz[idx1]+jet_pz[idx2]),2)
);
hs1D[TString("hmassFR_"+histcutname)]->Fill(mass,lfr);
}
}
}
if (fabs(frwgt*2-frwgttmp)>1.e-7) {
std::cout << "[WARNING] frwgtx2 = " << std::setprecision(9)
<< frwgt*2 << " != frwgttmp = " << frwgttmp << "!!!!" << std::endl;
}
break;
}//end case 2 (Ntag==2; flav dep)
case 21: {
// For Ntag==2; tag-and-probe
double frwgttmp=0.;
for(int i1=0;i1<njetsFR;i1++) {
int idx1 = goodjetIdx[i1];
if (!basicjet[idx1] || jet_pt->at(idx1)<minJetPt) continue;
double jfr = qcdtools->fakerate(jet_pt->at(idx1),jet_eta->at(idx1),jntrack[idx1],varType);
for(int i2=0;i2<njetsFR;i2++) {
int idx2 = goodjetIdx[i2];
if (!basicjet[idx2] || jet_pt->at(idx2)<minJetPt) continue;
if (i2==i1) continue;
double kfr = jfr*(1.0-qcdtools->fakerateTP(jet_pt->at(idx2),jet_eta->at(idx2),jntrack[idx2],varType));
//kfr *= (1.0-qcdtools->fakerate(jet_pt->at(idx2),jet_eta->at(idx2),jntrack[idx2],varType));
for(int i3=0;i3<njetsFR;i3++) {
if (i3==i1 || i3==i2) continue;
int idx3 = goodjetIdx[i3];
if (!basicjet[idx3] || jet_pt->at(idx3)<minJetPt) continue;
double lfr = kfr*qcdtools->fakerateTP(jet_pt->at(idx3),jet_eta->at(idx3),jntrack[idx3],varType);
for(int i4=0;i4<njetsFR;i4++) {
if (i4==i1 || i4==i2 || i4==i3) continue;
int idx4 = goodjetIdx[i4];
if (!basicjet[idx4] || jet_pt->at(idx4)<minJetPt) continue;
lfr *= (1.0-qcdtools->fakerateTP(jet_pt->at(idx4),jet_eta->at(idx4),jntrack[idx4],varType));
//lfr *= (1.0-qcdtools->fakerate(jet_pt->at(idx4),jet_eta->at(idx4),jntrack[idx4],varType));
}
//take care of combinatorics: e.g., var(1) double counted by (1_tag,2)(3_tag,4) and (1_tag,4)(3_tag,2)
double varWgt = lfr/(ngoodjet-2);
frwgttmp += varWgt;
hs1D[TString("hjptaFR_"+histcutname)]->Fill(jet_pt->at(idx1),varWgt);
hs1D[TString("hetaaFR_"+histcutname)]->Fill(jet_eta->at(idx1),varWgt);
hs1D[TString("hntrkFR_"+histcutname)]->Fill(jntrack[idx1],varWgt);
hs1D[TString("hmedipXYSigFR_"+histcutname)]->Fill(jet_medipsig[idx1],varWgt);
hs1D[TString("hlogmedipXYSigFR_"+histcutname)]->Fill(jet_logmedipsig[idx1],varWgt);
hs1D[TString("hmedtheta2DFR_"+histcutname)]->Fill(jet_medtheta2D[idx1],varWgt);
hs1D[TString("hlogmedtheta2DFR_"+histcutname)]->Fill(jet_logmedtheta2D[idx1],varWgt);
hs2D[TString("htheta2DvipXYSigFR_"+histcutname)]->Fill(jet_medtheta2D[idx1],jet_medipsig[idx1],varWgt);
double mass = sqrt(
pow((jet_e[idx1]+jet_e[idx2]),2) -
pow((jet_px[idx1]+jet_px[idx2]),2) -
pow((jet_py[idx1]+jet_py[idx2]),2) -
pow((jet_pz[idx1]+jet_pz[idx2]),2)
);
hs1D[TString("hmassFR_"+histcutname)]->Fill(mass,lfr);
}
}
}
if (fabs(frwgt*2-frwgttmp)>1.e-7) {
std::cout << "[WARNING] frwgtx2 = " << std::setprecision(9)
<< frwgt*2 << " != frwgttmp = " << frwgttmp << "!!!!" << std::endl;
}
break;
}//end case 21 (Ntag==2; tag-and-probe)
case 22: {
char *hnames[9]={(char*)"hjptaFR",(char*)"hetaaFR",(char*)"hntrkFR",
(char*)"hmedipXYSigFR",(char*)"hlogmedipXYSigFR",(char*)"hmedtheta2DFR",
(char*)"hlogmedtheta2DFR",(char*)"hmassFR",(char*)"htheta2DvipXYSigFR"};
// For Ntag==1; flav dep; data unfolded; only for 4 jet events
double frwgttmp=0.;
double frwgts[7];
TMatrixD Mwgt(5,5);
bool goodWgt = qcdtools->UnfoldWgtPtDep(Mwgt, bUnfType, jet_pt, isData);
// for (int i=0;i<5;i++){
// for (int j=0;j<5;j++){
// std::cout << "Mwgt(" << i << "," << j <<")=" << Mwgt(i,j) << std::endl;
// }
// }
if (!goodWgt) {
std::cout << "Bad unfolding matrix inversion!" << std::endl;
}
// loop # unfolded "true" b jets
for (int nbT=0;nbT<5;nbT++){
double evtWgt = 0.0;
//if (isData) evtWgt = qcdtools->UnfoldWgtD(bUnfType, nbT, nbTagged[eCut], ptType);
//else evtWgt = qcdtools->UnfoldWgt(bUnfType, nbT, nbTagged[eCut], ptType);
//evtWgt=qcdtools->UnfoldWgtPtDep(bUnfType, nbT, nbTagged[eCut], jet_pt, isData);
evtWgt=Mwgt(nbT, nbTagged[eCut]);
double ncomb=1;
switch (nbT) {
case 1: ncomb=4; break;
case 2: ncomb=6; break;
case 3: ncomb=4; break;
default: break;
}
evtWgt/=ncomb;
switch (nbT) {
case 0: {
int flavors[] = {0,0,0,0};
qcdtools->frWeightUFT23(frwgts,jet_pt,jet_eta,goodjetIdx,jntrack,
flavors,varType,isData,cutname);
frwgttmp+=(evtWgt*frwgts[6]);
qcdtools->fillFRPlots22(histcutname,hnames,
jet_pt, jet_eta, goodjetIdx,jntrack,jet_medipsig,jet_logmedipsig,
jet_medtheta2D, jet_logmedtheta2D,
jet_e,jet_px,jet_py,jet_pz,
frwgts, evtWgt, 1.0);
break;}
case 1: {
for (int fidx=0;fidx<4;fidx++) {
int flavors[] = {0,0,0,0};
flavors[fidx]=5;
qcdtools->frWeightUFT23(frwgts,jet_pt,jet_eta,goodjetIdx,jntrack,
flavors,varType,isData,cutname);
frwgttmp+=(evtWgt*frwgts[6]);
qcdtools->fillFRPlots22(histcutname,hnames,
jet_pt, jet_eta, goodjetIdx,jntrack,jet_medipsig,jet_logmedipsig,
jet_medtheta2D, jet_logmedtheta2D,
jet_e,jet_px,jet_py,jet_pz,
frwgts, evtWgt, 1.0);
}
break;}
case 2: {
//flavor double counted due to looping
for (int fidx0=0;fidx0<4;fidx0++) {
for (int fidx1=fidx0+1;fidx1<4;fidx1++) {
int flavors[] = {0,0,0,0};
flavors[fidx0]=5;
flavors[fidx1]=5;
qcdtools->frWeightUFT23(frwgts,jet_pt,jet_eta,goodjetIdx,jntrack,
flavors,varType,isData,cutname);
frwgttmp+=(evtWgt*frwgts[6]);
qcdtools->fillFRPlots22(histcutname,hnames,
jet_pt, jet_eta, goodjetIdx,jntrack,jet_medipsig,jet_logmedipsig,
jet_medtheta2D, jet_logmedtheta2D,
jet_e,jet_px,jet_py,jet_pz,
frwgts, evtWgt, 1.0);
}
}
break;}
case 3: {
for (int fidx=0;fidx<4;fidx++) {
int flavors[] = {5,5,5,5};
flavors[fidx]=0;
qcdtools->frWeightUFT23(frwgts,jet_pt,jet_eta,goodjetIdx,jntrack,
flavors,varType,isData,cutname);
frwgttmp+=(evtWgt*frwgts[6]);
qcdtools->fillFRPlots22(histcutname,hnames,
jet_pt, jet_eta, goodjetIdx,jntrack,jet_medipsig,jet_logmedipsig,
jet_medtheta2D, jet_logmedtheta2D,
jet_e,jet_px,jet_py,jet_pz,
frwgts, evtWgt, 1.0);
}
break;}
case 4: {
int flavors[] = {5,5,5,5};
qcdtools->frWeightUFT23(frwgts,jet_pt,jet_eta,goodjetIdx,jntrack,
flavors,varType,isData,cutname);
frwgttmp+=(evtWgt*frwgts[6]);
qcdtools->fillFRPlots22(histcutname,hnames,
jet_pt, jet_eta, goodjetIdx,jntrack,jet_medipsig,jet_logmedipsig,
jet_medtheta2D, jet_logmedtheta2D,
jet_e,jet_px,jet_py,jet_pz,
frwgts, evtWgt, 1.0);
break;}
}
}
if (fabs(frwgt-frwgttmp)>1.e-7) {
std::cout << "[WARNING] frwgt = " << std::setprecision(9)
<< frwgt << " != frwgttmp = " << frwgttmp << "!!!!" << std::endl;
}
break;
}//end case 22 (Ntag==2; flav dep; data unfolded)
case 3: {
// For Ntag==3; flav dep
double frwgttmp=0.;
for(int i1=0;i1<njetsFR;i1++) {
int idx1 = goodjetIdx[i1];
if (!basicjet[idx1] || jet_pt->at(idx1)<minJetPt) continue;
double jfr = qcdtools->fakerateF(jet_pt->at(idx1),jet_eta->at(idx1),jntrack[idx1],
varType,jet_pid_maxEt[idx1],cutname);
for(int i2=0;i2<njetsFR;i2++) {
int idx2 = goodjetIdx[i2];
if (!basicjet[idx2] || jet_pt->at(idx2)<minJetPt) continue;
if (i2==i1) continue;
double kfr = jfr*qcdtools->fakerateF(jet_pt->at(idx2),jet_eta->at(idx2),jntrack[idx2],
varType,jet_pid_maxEt[idx2],cutname);
for(int i3=0;i3<njetsFR;i3++) {
if (i3==i1 || i3==i2) continue;
int idx3 = goodjetIdx[i3];
if (!basicjet[idx3] || jet_pt->at(idx3)<minJetPt) continue;
double lfr = kfr*qcdtools->fakerateF(jet_pt->at(idx3),jet_eta->at(idx3),jntrack[idx3],
varType,jet_pid_maxEt[idx3],cutname);
for(int i4=0;i4<njetsFR;i4++) {
if (i4==i1 || i4==i2 || i4==i3) continue;
int idx4 = goodjetIdx[i4];
if (!basicjet[idx4] || jet_pt->at(idx4)<minJetPt) continue;
double mfr = lfr*(1.0-qcdtools->fakerateF(jet_pt->at(idx4),jet_eta->at(idx4),jntrack[idx4],
varType,jet_pid_maxEt[idx4],cutname));
if (njetsFR>4) {
for(int i5=0;i5<njetsFR;i5++) {
if (i5==i1 || i5==i2 || i5==i3 || i5==i4) continue;
int idx5 = goodjetIdx[i5];
if (!basicjet[idx5] || jet_pt->at(idx5)<minJetPt) continue;
mfr *= (1.0-qcdtools->fakerateF(jet_pt->at(idx5),jet_eta->at(idx5),jntrack[idx5],
varType,jet_pid_maxEt[idx5],cutname));
}
}
double varWgt = mfr/2;
frwgttmp += varWgt;
hs1D[TString("hjptaFR_"+histcutname)]->Fill(jet_pt->at(idx1),varWgt);
hs1D[TString("hetaaFR_"+histcutname)]->Fill(jet_eta->at(idx1),varWgt);
hs1D[TString("hntrkFR_"+histcutname)]->Fill(jntrack[idx1],varWgt);
hs1D[TString("hmedipXYSigFR_"+histcutname)]->Fill(jet_medipsig[idx1],varWgt);
hs1D[TString("hlogmedipXYSigFR_"+histcutname)]->Fill(jet_logmedipsig[idx1],varWgt);
hs1D[TString("hmedtheta2DFR_"+histcutname)]->Fill(jet_medtheta2D[idx1],varWgt);
hs1D[TString("hlogmedtheta2DFR_"+histcutname)]->Fill(jet_logmedtheta2D[idx1],varWgt);
hs2D[TString("htheta2DvipXYSigFR_"+histcutname)]->Fill(jet_medtheta2D[idx1],jet_medipsig[idx1],varWgt);
double mass = sqrt(
pow((jet_e[idx1]+jet_e[idx4]),2) -
pow((jet_px[idx1]+jet_px[idx4]),2) -
pow((jet_py[idx1]+jet_py[idx4]),2) -
pow((jet_pz[idx1]+jet_pz[idx4]),2)
);
//hs1D[TString("hmassFR_"+histcutname)]->Fill(mass,mfr);
hs1D[TString("hmassFR_"+histcutname)]->Fill(mass,varWgt);
}
}
}
}
if (fabs(frwgt*3-frwgttmp)>1.e-7) {
std::cout << "[WARNING] frwgt = " << std::setprecision(9)
<< frwgt*3 << " != frwgttmp = " << frwgttmp << "!!!!" << std::endl;
}
break;
}//end case 3 (Ntag==3; flav dep)
default: break;
}//end switch
}// Canem Data-driven fake background
}
// ********************************
// end otfile Data-driven fake background
// ********************************
// ********************************
// SR plots
// ********************************
// require at least N emerging jets
if(Cnem) {//NOTE: revert Canem and Cnem for the time being
if(otfile) hs1D[TString("count_"+histcutname)]->Fill("emerging",1);
if(otfile) hs1D[TString("acount_"+histcutname)]->Fill(9);
if(Canem) {
// if(otfile) hs1D[TString("h_nemgSR_"+histcutname)]->Fill(nemerging);
// //if(otfile) hs1D[TString("h_nemgSR_"+histcutname)]->Fill(nemgGoodjet);
if(otfile) hs1D[TString("count_"+histcutname)]->Fill("almostemerging",1);
if(otfile) hs1D[TString("acount_"+histcutname)]->Fill(10);
npass+=1;
std::cout<<"cutset["<<cutname<< "]:"<<std::endl;
std::cout<<"passing run lumi event filename is "<<run<<" "<<lumi<<" "<<event<<" "<<inputfilename<<std::endl;
for(int i=0;i<4;i++) {
int idx = goodjetIdx[i];
std::ostringstream ss;
ss << i+1;
std::cout<<" for jet "<<i<<" pt eta nef cfe ntrkpt1 alphamax medIP"<<std::endl;
std::cout<<" "<<jet_pt->at(idx)<<" "<<jet_eta->at(idx)<<" "<< jet_nef->at(idx)<<" "<< jet_cef->at(idx)<<" "<<jet_ntrkpt1[idx]<<" "<<jet_alpha[idx]<<" " << jet_medip[idx] << " " <<std::endl;
//std::cout << "hjpt" << ss.str() << "SR_" << histcutname << std::endl;
hs1D[TString("hjpt"+ss.str()+"SR_"+histcutname)]->Fill(jet_pt->at(idx));
hs1D[TString("heta"+ss.str()+"SR_"+histcutname)]->Fill(jet_eta->at(idx));
//hs1D[TString("EtRatioSR_"+histcutname)]->Fill(EtRatio[idx]);
hs1D[TString("dRjtrk0SR_"+histcutname)]->Fill(dRjtrk0[idx]);
hs1D[TString("dRjtrkSR_"+histcutname)]->Fill(dRjtrk[idx]);
hs1D[TString("djtrkSR_"+histcutname)]->Fill(djtrk[idx]);
}
if(otfile) {
hs1D[TString("H_TSR_"+histcutname)]->Fill(HT);
hs1D[TString("METSR_"+histcutname)]->Fill(met_pt);
int ngoodjetSR = 0;
for(int nj=0;nj<4;nj++) {
if (!basicjet[nj] || jet_pt->at(nj)<minJetPt) continue;
ngoodjetSR+=1;
}
hs1D[TString("hnjetSR_"+histcutname)]->Fill(ngoodjetSR);
for(int i5=0;i5<4;i5++) {
int idx5 = goodjetIdx[i5];
if (jet_pt->at(idx5)<minJetPt) continue;
if (emerging[idx5] && otfile){
hs1D[TString("hjptaSR_"+histcutname)]->Fill(jet_pt->at(idx5));
hs1D[TString("hetaaSR_"+histcutname)]->Fill(jet_eta->at(idx5));
hs1D[TString("hntrkSR_"+histcutname)]->Fill(jntrack[idx5]);
hs1D[TString("hmedipXYSigSR_"+histcutname)]->Fill(jet_medipsig[idx5]);
hs1D[TString("hlogmedipXYSigSR_"+histcutname)]->Fill(jet_logmedipsig[idx5]);
hs1D[TString("hmedtheta2DSR_"+histcutname)]->Fill(jet_medtheta2D[idx5]);
hs1D[TString("hlogmedtheta2DSR_"+histcutname)]->Fill(jet_logmedtheta2D[idx5]);
hs2D[TString("htheta2DvipXYSigSR_"+histcutname)]->Fill(jet_medtheta2D[idx5],jet_medipsig[idx5]);
}
for(int i6=i5+1;i6<4;i6++) {
int idx6 = goodjetIdx[i6];
if (jet_pt->at(idx6)<minJetPt) continue;
if ((emerging[idx5]&&!emerging[idx6])||(!emerging[idx5]&&emerging[idx6])) {
double mass = sqrt(
pow((jet_e[idx5]+jet_e[idx6]),2) -
pow((jet_px[idx5]+jet_px[idx6]),2) -
pow((jet_py[idx5]+jet_py[idx6]),2) -
pow((jet_pz[idx5]+jet_pz[idx6]),2)
);
hs1D[TString("hmassSR_"+histcutname)]->Fill(mass);
}
}
}
}
std::cout<<"npass event is "<<npass<<" "<<event<<std::endl;
std::cout<<"nemerging nalmostemerging "<<nemerging<<" "<<nalmostemerging<<std::endl;
std::cout<<"nemgGoodjet nalemgGoodjet "<<nemgGoodjet<<" "<<nalemgGoodjet<<std::endl;
}//Canem (SR)
}//Cnem (SR)
// ********************************
// End of SR plots
// ********************************
}//Cpt4
}//Cpt3
}//Cpt2
}//Cpt1
}//HLT&&CHT
}//C4jet
// *************************************************************
// End of apply event selection cuts sequentially
// *************************************************************
}// End of cutsets loop
// *************************************************************
// End of cutsets loop
// *************************************************************
}// end of loop over events
// *************************************************************
// End of loop over events
// *************************************************************
for (int fCut=0; fCut<nCuts; fCut++) {
std::cout << "Result of cutset[ " << Cutstorun[fCut] << "]" << std::endl;
std::cout << "np0 = " << np0[fCut] << std::endl;
std::cout << "np1 = " << np1[fCut] << std::endl;
std::cout << "np2 = " << np2[fCut] << std::endl;
std::cout << "np3 = " << np3[fCut] << std::endl;
std::cout << "Total # btagged = " << nbTaggedTot[fCut] << std::endl;
std::cout << "Total # not btagged = " << nNotbTagTot[fCut] << std::endl;
std::cout << "Total # btagged (ALL) = " << nbTaggedTotAll[fCut] << std::endl;
std::cout << "Total # not btagged (ALL) = " << nNotbTagTotAll[fCut] << std::endl;
}
if(otfile) {
TFile myfile(outputfilename,"UPDATE");
for (int fCut=0; fCut<nCuts; fCut++) {
std::string histcutname="Cutset"+Cutstorun[fCut];
hs1D[TString("count_"+histcutname)]->LabelsDeflate();
hs1D[TString("count_"+histcutname)]->LabelsOption("v");
// hs1D[TString("count_"+histcutname)]->LabelsOption("a");
hs1D[TString("eventCountPreTrigger_"+histcutname)]->Write();
hs1D[TString("acount_"+histcutname)]->Write();
hs1D[TString("count_"+histcutname)]->Write();
hs1D[TString("hnjet_"+histcutname)]->Write();
hs1D[TString("hnjetSR_"+histcutname)]->Write();
hs1D[TString("hnjetFR_"+histcutname)]->Write();
hs1D[TString("hetaaSR_"+histcutname)]->Write();
hs1D[TString("hetaaFR_"+histcutname)]->Write();
hs1D[TString("halpha_"+histcutname)]->Write();
hs1D[TString("halphaZero_"+histcutname)]->Write();
hs1D[TString("H_TSR_"+histcutname)]->Write();
hs1D[TString("H_TFR_"+histcutname)]->Write();
hs1D[TString("h_nemg_"+histcutname)]->Write();
hs1D[TString("h_nemgSR_"+histcutname)]->Write();
hs1D[TString("h_nemgFR_"+histcutname)]->Write();
hs1D[TString("h_nalemg_"+histcutname)]->Write();
hs1D[TString("hntrkSR_"+histcutname)]->Write();
hs1D[TString("hntrkFR_"+histcutname)]->Write();
hs1D[TString("hjptaSR_"+histcutname)]->Write();
hs1D[TString("hjptaFR_"+histcutname)]->Write();
hs1D[TString("hmassSR_"+histcutname)]->Write();
hs1D[TString("hmassFR_"+histcutname)]->Write();
hs1D[TString("hmedipXYSigSR_"+histcutname)]->Write();
hs1D[TString("hmedtheta2DSR_"+histcutname)]->Write();
hs1D[TString("hlogmedipXYSigSR_"+histcutname)]->Write();
hs1D[TString("hlogmedtheta2DSR_"+histcutname)]->Write();
hs1D[TString("hmedipXYSigFR_"+histcutname)]->Write();
hs1D[TString("hmedtheta2DFR_"+histcutname)]->Write();
hs1D[TString("hlogmedipXYSigFR_"+histcutname)]->Write();
hs1D[TString("hlogmedtheta2DFR_"+histcutname)]->Write();
//2d
hs2D[TString("htheta2DvipXYSigSR_"+histcutname)]->Write();
hs2D[TString("htheta2DvipXYSigFR_"+histcutname)]->Write();
// For review
hs1D[TString("hjpt1SR_"+histcutname)]->Write();
hs1D[TString("hjpt1FR_"+histcutname)]->Write();
hs1D[TString("hjpt2SR_"+histcutname)]->Write();
hs1D[TString("hjpt2FR_"+histcutname)]->Write();
hs1D[TString("hjpt3SR_"+histcutname)]->Write();
hs1D[TString("hjpt3FR_"+histcutname)]->Write();
hs1D[TString("hjpt4SR_"+histcutname)]->Write();
hs1D[TString("hjpt4FR_"+histcutname)]->Write();
hs1D[TString("heta1SR_"+histcutname)]->Write();
hs1D[TString("heta1FR_"+histcutname)]->Write();
hs1D[TString("heta2SR_"+histcutname)]->Write();
hs1D[TString("heta2FR_"+histcutname)]->Write();
hs1D[TString("heta3SR_"+histcutname)]->Write();
hs1D[TString("heta3FR_"+histcutname)]->Write();
hs1D[TString("heta4SR_"+histcutname)]->Write();
hs1D[TString("heta4FR_"+histcutname)]->Write();
hs1D[TString("METSR_"+histcutname)]->Write();
hs1D[TString("METFR_"+histcutname)]->Write();
hs1D[TString("dRjtrk0SR_"+histcutname)]->Write();
hs1D[TString("dRjtrk0FR_"+histcutname)]->Write();
hs1D[TString("dRjtrkSR_"+histcutname)]->Write();
hs1D[TString("dRjtrkFR_"+histcutname)]->Write();
hs1D[TString("djtrkSR_"+histcutname)]->Write();
hs1D[TString("djtrkFR_"+histcutname)]->Write();
//hs1D[TString("EtRatioSR_"+histcutname)]->Write();
//hs1D[TString("EtRatioFR_"+histcutname)]->Write();
hs1D[TString("chiAll_"+histcutname)]->Write();
hs1D[TString("dzAll_"+histcutname)]->Write();
hs1D[TString("medipXY_"+histcutname)]->Write();
}
myfile.Close();
}
tt->ResetBranchAddresses();
delete jet_index;
delete jet_source;
delete jet_pt;
delete jet_eta;
delete jet_phi;
//delete jet_alphaMax;
delete jet_cef;
delete jet_nef;
//delete jet_chf;
delete jet_theta2D;
// delete jet_phf;
delete jet_csv;
delete track_pt;
delete track_eta;
delete track_phi;
delete track_source;
delete track_index;
//delete track_jet_index;
//delete track_vertex_index;
//delete track_algo;
delete track_quality;
//delete track_vertex_weight;
//delete track_pvWeight;
delete track_dRToJetAxis;
delete track_distanceToJet;
delete track_ipZ;
delete track_ipXY;
delete track_ipXYSig;
delete qcdtools;
f->Close();
return npass;
}
| [
"Geng-Yuan.Jeng@cern.ch"
] | Geng-Yuan.Jeng@cern.ch |
2395426156437f0fb118ab703f0cd5632ed2f98c | 9ea575abc4b9641d0deb5285d4e6cb2396e3ac27 | /0117_Populating_Next_Right_Pointers_In_Each_Node_II.cpp | afb6eeae0e36bbd172571f0920d25953d07f8f72 | [] | no_license | Ming-J/LeetCode | 65e11cdeb1530ae163fa1fc9851acbcee7f05744 | a69f56a1e92a4cb32a1a16bc3201027910f1a877 | refs/heads/master | 2022-05-08T00:37:01.830067 | 2022-03-06T15:40:43 | 2022-03-06T15:40:43 | 26,152,966 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,724 | cpp | #include <iostream>
using namespace std;
// Definition for binary tree with next pointer.
struct TreeLinkNode {
int val;
TreeLinkNode *left, *right, *next;
TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};
class Solution {
public:
void connect(TreeLinkNode *root) {
TreeLinkNode *head = root; // head of the treeLinklist for next level
TreeLinkNode *prev = NULL; // previous node to connect to current child
TreeLinkNode *cur = NULL; // current node working on
// checking if the is more treeLinkedlist to connect
while (head) {
cur = head; // we are on new level, start connection this level's children
head = NULL;
while (cur) {
// connection left child
if (cur->left) {
if (!prev)
head = cur->left; // next level head
else
prev->next = cur->left;
prev = cur->left;
}
//connection right child
if (cur->right) {
if (!prev)
head = cur->right; // next level head
else
prev->next = cur->right;
prev = cur->right;
}
//Going to the new node of current level
cur = cur->next;
}
prev = NULL;
}
}
};
int main() {
TreeLinkNode *one = new TreeLinkNode(1);
TreeLinkNode *two = new TreeLinkNode(2);
TreeLinkNode *three = new TreeLinkNode(3);
one->left = two;
one->right = three;
Solution t;
t.connect(one);
} | [
"minwu@deloitte.co.uk"
] | minwu@deloitte.co.uk |
de7e4be1af51aac4a0c6e1b68d304cc3f0a6178f | 6ed530cc9fc7758c1df341c9d624e92539300c6a | /projects/sharedlibs/gy521/gy521 - simple.cpp | b9a641c08b040bccda3e8abc26a06c175cafc2e4 | [] | no_license | GuyCarver/raspi | aa87bff08969069074a98196574edaa27be8585c | 30dc2b595274cdc5afe07767b584fbb2cfdfa7f1 | refs/heads/master | 2022-11-24T14:05:33.867306 | 2022-11-11T16:20:22 | 2022-11-11T16:20:22 | 109,533,023 | 0 | 0 | null | 2020-10-13T04:36:04 | 2017-11-04T21:53:07 | C++ | UTF-8 | C++ | false | false | 8,023 | cpp | //----------------------------------------------------------------------
// Copyright (c) 2020, gcarver
// 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.
//
// * The name of Guy Carver may not 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.
//
// FILE gy521.cpp
// BY gcarver
// DATE 09/20/2020 09:33 PM
//----------------------------------------------------------------------
//Module to handle communication with the gy521 6 axis accelerometer
// This controller communicates using I2C.
#include <iostream>
#include <unistd.h>
#include <errno.h>
#include <wiringPiI2C.h>
#include <wiringPi.h>
namespace
{
constexpr uint32_t _ADDRESS = 0x68; // 0x69 is also possible
constexpr uint32_t CALIBRATE_COUNT = 50;
constexpr uint32_t RA_SMPLRT_DIV = 0x19;
constexpr uint32_t RA_CONFIG = 0x1A;
constexpr uint32_t RA_GYRO_CONFIG = 0x1B;
constexpr uint32_t RA_INT_ENABLE = 0x38;
constexpr uint32_t RA_ACCEL_XOUT_H = 0x3B;
constexpr uint32_t RA_GYRO_XOUT_H = 0x43;
constexpr uint32_t RA_PWR_MGMT_1 = 0x6B;
} //namespace
//--------------------------------------------------------
class gy521
{
public:
//--------------------------------------------------------
gy521( bool bHigh = false )
{
uint32_t a = _ADDRESS + (bHigh ? 1 : 0);
_i2c = wiringPiI2CSetup(a); // If this is -1 an error occurred.
delayMicroseconds(50); // Wait for init to settle.
bGood = _i2c >= 0;
_write8(RA_SMPLRT_DIV, 0x07);
_write8(RA_CONFIG, 0);
_write8(RA_GYRO_CONFIG, 24);
_write8(RA_INT_ENABLE, 0x01);
_write8(RA_PWR_MGMT_1, 0x00);
_instance = this; // We currently only support 1 instance of this object.
Calibrate();
}
//--------------------------------------------------------
~gy521( )
{
close(_i2c);
_instance = nullptr;
}
//--------------------------------------------------------
static gy521 *QInstance( ) { return _instance; }
//--------------------------------------------------------
bool QGood( ) const { return bGood; }
const int32_t *GetAccelTempRot( )
{
auto pdata = _readbuffer(RA_ACCEL_XOUT_H, 7);
for ( uint32_t i = 0; i < 7; ++i) {
pdata[i] -= _Adj[i];
}
return pdata;
}
const int32_t *GetAccelTempRot16( )
{
auto pdata = _readbuffer16(RA_ACCEL_XOUT_H, 7);
for ( uint32_t i = 0; i < 7; ++i) {
pdata[i] -= _Adj[i];
}
return pdata;
}
const int32_t *GetAcceleration( )
{
auto pdata = _readbuffer(RA_ACCEL_XOUT_H, 3);
for ( uint32_t i = 0; i < 3; ++i) {
pdata[i] -= _Adj[i];
}
return pdata;
}
const int32_t *GetAcceleration16( )
{
auto pdata = _readbuffer16(RA_ACCEL_XOUT_H, 3);
for ( uint32_t i = 0; i < 3; ++i) {
pdata[i] -= _Adj[i];
}
return pdata;
}
const int32_t *GetRotation( )
{
auto pdata = _readbuffer(RA_GYRO_XOUT_H, 3);
for ( uint32_t i = 0; i < 3; ++i) {
pdata[i] -= _Adj[5 + i];
}
return pdata;
}
const int32_t *GetRotation16( )
{
auto pdata = _readbuffer16(RA_GYRO_XOUT_H, 3);
for ( uint32_t i = 0; i < 3; ++i) {
pdata[i] -= _Adj[5 + i];
}
return pdata;
}
//private:
int32_t _i2c = 0;
int32_t _buffer[8];
int32_t _Adj[8];
bool bGood = true;
static gy521 *_instance;
//--------------------------------------------------------
// Read 8 bit value and return.
const int32_t _read8( uint32_t aLoc )
{
int32_t ret = wiringPiI2CReadReg8(_i2c, aLoc);
//If the value is <0 it's a read error.
return ret >= 0 ? ret : 0;
}
//--------------------------------------------------------
// Read 16 bit value and return.
const int32_t _read16( uint32_t aLoc )
{
int32_t ret = wiringPiI2CReadReg16(_i2c, aLoc);
return ret >= 0 ? ret : 0;
}
int32_t *_readbuffer( uint32_t aLoc, uint32_t aCount )
{
for ( uint32_t i = 0; i < aCount; ++i) {
uint32_t j = i * 2;
int32_t v = _read8(aLoc + j++) << 8;
v |= _read8(aLoc + j);
_buffer[i] = utoi(v);
}
return _buffer;
}
int32_t *_readbuffer16( uint32_t aLoc, uint32_t aCount )
{
for ( uint32_t i = 0; i < aCount; ++i) {
int32_t v = _read16(aLoc + i * 2);
v = ((v & 0xFF) << 8) | ((v >> 8) & 0xFF);
//Set the value but endian convert it 1st
_buffer[i] = utoi(v);
}
return _buffer;
}
//--------------------------------------------------------
// Write 8 bit integer aVal to given address aLoc.
int32_t _write8( uint8_t aValue, uint32_t aLoc )
{
return wiringPiI2CWriteReg8(_i2c, aLoc, aValue);
}
static int32_t utoi( int32_t aValue )
{
if (aValue >= 0x8000) {
aValue = -((65535 - aValue) + 1);
}
return aValue;
}
void Calibrate( )
{
for ( auto &v : _Adj ) {
v = 0.0f;
}
for ( uint32_t i = 0; i < CALIBRATE_COUNT; ++i) {
auto pdata = GetAccelTempRot16();
uint32_t j = 0;
for ( auto &v : _Adj ) {
v += pdata[j++];
}
delayMicroseconds(10);
}
for ( auto &v : _Adj ) {
v /= static_cast<float>(CALIBRATE_COUNT);
}
//Don't adjust temperature.
_Adj[3] = 0.0f;
}
};
gy521 *gy521::_instance = nullptr;
//Following are the 8th interface functions.
extern "C"
{
//--------------------------------------------------------
bool Startup( )
{
if (!gy521::QInstance()) {
auto p = new gy521();
}
return gy521::QInstance()->QGood();
}
//--------------------------------------------------------
bool IsGood( )
{
auto p = gy521::QInstance();
return p ? p->QGood() : false;
}
const int32_t *Adj( )
{
auto p = gy521::QInstance();
return p->_Adj;
}
//--------------------------------------------------------
void Shutdown( )
{
auto p = gy521::QInstance();
if (p) {
delete p;
}
}
int32_t Read8( uint32_t aIndex )
{
auto p = gy521::QInstance();
return p ? p->_read8(aIndex) : 0;
}
int32_t Read16( uint32_t aIndex )
{
auto p = gy521::QInstance();
return p ? p->_read16(aIndex) : 0;
}
const int32_t *GetAccelTempRot( )
{
const int32_t *d = nullptr;
auto p = gy521::QInstance();
if (p) {
d = p->GetAccelTempRot();
}
return d;
}
const int32_t *GetAcceleration( )
{
const int32_t *d = nullptr;
auto p = gy521::QInstance();
if (p) {
d = p->GetAcceleration();
}
return d;
}
const int32_t *GetRotation( )
{
const int32_t *d = nullptr;
auto p = gy521::QInstance();
if (p) {
d = p->GetRotation();
}
return d;
}
const int32_t *GetAccelTempRot16( )
{
const int32_t *d = nullptr;
auto p = gy521::QInstance();
if (p) {
d = p->GetAccelTempRot16();
}
return d;
}
const int32_t *GetAcceleration16( )
{
const int32_t *d = nullptr;
auto p = gy521::QInstance();
if (p) {
d = p->GetAcceleration16();
}
return d;
}
const int32_t *GetRotation16( )
{
const int32_t *d = nullptr;
auto p = gy521::QInstance();
if (p) {
d = p->GetRotation16();
}
return d;
}
} //extern C
| [
"gcarver@bethsoft.com"
] | gcarver@bethsoft.com |
c64cbda085246c7f7ba31c18b7936f045d18db0a | ea30544c533dcb5063703004ff1d1f3da89ce641 | /openvxi-3.4+vglue/src/log/SBlog.cpp | 097db3e5d7791c428b633301fe834798a7b7fbf6 | [] | no_license | ausmarton/voiceglue-centos-6 | 30a88b3b285fd9c321e11f52b48cb8a08ab00b35 | 45316438a69e771153b8e7734b6041b9036162c7 | refs/heads/master | 2016-09-06T19:15:07.473052 | 2012-03-23T09:57:41 | 2012-03-23T09:57:41 | 3,807,126 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 45,357 | cpp |
/****************License************************************************
* Vocalocity OpenVXI
* Copyright (C) 2004-2005 by Vocalocity, Inc. All Rights Reserved.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* Vocalocity, the Vocalocity logo, and VocalOS are trademarks or
* registered trademarks of Vocalocity, Inc.
* OpenVXI is a trademark of Scansoft, Inc. and used under license
* by Vocalocity.
***********************************************************************/
// -----1=0-------2=0-------3=0-------4=0-------5=0-------6=0-------7=0-------8
#include "SBlogInternal.h"
#include <cstring> // For memset()
#include <ctime> // For time_t
#include <vector> // For STL vector template class
#define SBLOG_EXPORTS
#include "SBlog.h" // Header for these functions
#include "SBlogOSUtils.h" // for SBlogGetTime(), SBlogVswprintf()
#ifdef __THREADED
#include "VXItrd.h" // for VXItrdMutex
#endif
static const VXIunsigned MAX_LOG_BUFFER = 4096 * 2;
static const VXIunsigned TAG_ARRAY_SIZE = (((SBLOG_MAX_TAG) + 1) / 8 + 1);
#define SBLOG_ERR_OUT_OF_MEMORY 100, L"SBlog: Out of memory", NULL
#define SBLOG_ERR_ALREADY_INITIALIZED 104, L"SBlog: Already initialized", NULL
#define SBLOG_ERR_NOT_INITIALIZED 105, L"SBlog: Not initialized", NULL
#ifndef MODULE_PREFIX
#define MODULE_PREFIX COMPANY_DOMAIN L"."
#endif
#define MODULE_NAME MODULE_PREFIX L"SBlog"
// Global variable to track whether this is initialized
static bool gblInitialized = false;
struct myAPI {
SBlogInterface intf;
void *impl_;
};
struct SBlogErrorCallbackData {
SBlogErrorListener *callback;
void *userdata;
bool operator==(struct SBlogErrorCallbackData &other)
{ return (callback == other.callback && userdata == other.userdata); }
bool operator!=(struct SBlogErrorCallbackData &other)
{ return !operator==(other); }
};
struct SBlogDiagCallbackData {
SBlogDiagnosticListener *callback;
void *userdata;
bool operator==(struct SBlogDiagCallbackData &other)
{ return (callback == other.callback && userdata == other.userdata); }
bool operator!=(struct SBlogDiagCallbackData &other)
{ return !operator==(other); }
};
struct SBlogEventCallbackData{
SBlogEventListener *callback;
void *userdata;
bool operator==(struct SBlogEventCallbackData &other)
{ return (callback == other.callback && userdata == other.userdata); }
bool operator!=(struct SBlogEventCallbackData &other)
{ return !operator==(other); }
};
struct SBlogContentCallbackData{
SBlogContentListener *callback;
void *userdata;
bool operator==(struct SBlogContentCallbackData &other)
{ return (callback == other.callback && userdata == other.userdata); }
bool operator!=(struct SBlogContentCallbackData &other)
{ return !operator==(other); }
};
// Our definition of the opaque VXIlogStream
extern "C" {
struct VXIlogStream {
// Linked list of underlying SBlogListener content streams
typedef std::vector<SBlogStream *> STREAMS;
STREAMS streams;
};
}
class SBlog {
public:
SBlog(SBlogInterface *pThis);
virtual ~SBlog();
bool DiagnosticIsEnabled(VXIunsigned tagID);
VXIlogResult DiagnosticLog(VXIunsigned tagID,
const VXIchar* subtag,
const VXIchar* format,
va_list arguments) const;
VXIlogResult EventLog(VXIunsigned eventID,
const VXIchar* format,
va_list arguments) const;
VXIlogResult EventLog(VXIunsigned eventID,
const VXIVector* keys,
const VXIVector* values) const;
VXIlogResult ErrorLog(const VXIchar* moduleName,
VXIunsigned errorID,
const VXIchar* format,
va_list arguments) const;
VXIlogResult ContentOpen(const VXIchar* moduleName,
const VXIchar* contentType,
VXIString** logKey,
VXIString** logValue,
VXIlogStream** stream) const;
VXIlogResult ContentClose(VXIlogStream** stream) const;
VXIlogResult ContentWrite(const VXIbyte* buffer,
VXIulong buflen,
VXIulong* nwritten,
VXIlogStream* stream) const;
VXIlogResult ControlDiagnosticTag(VXIunsigned tagID,
VXIbool state);
// ----- Register/Unregister callback functions
VXIlogResult RegisterErrorListener(SBlogErrorCallbackData *info);
SBlogErrorCallbackData*
UnregisterErrorListener(SBlogErrorCallbackData *info);
VXIlogResult RegisterDiagnosticListener(SBlogDiagCallbackData *info);
SBlogDiagCallbackData*
UnregisterDiagnosticListener(SBlogDiagCallbackData *info);
VXIlogResult RegisterEventListener(SBlogEventCallbackData *info);
SBlogEventCallbackData*
UnregisterEventListener(SBlogEventCallbackData *info);
VXIlogResult RegisterContentListener(SBlogContentCallbackData *info);
SBlogContentCallbackData*
UnregisterContentListener(SBlogContentCallbackData *info);
// ----- Internal error logging functions
VXIlogResult Error(VXIunsigned errorID, const VXIchar *errorIDText,
const VXIchar *format, ...) const;
static VXIlogResult GlobalError(VXIunsigned errorID,
const VXIchar *errorIDText,
const VXIchar *format, ...);
private:
// Internal methods
static unsigned testbit(unsigned char num, int bitpos);
static void setbit(unsigned char *num, int bitpos);
static void clearbit(unsigned char *num, int bitpos);
bool Convert2Index(VXIunsigned tagID,
VXIunsigned *index,
VXIunsigned *bit_pos) const;
VXIlogResult ParseKeyValue(const VXIchar *format,
va_list args,
VXIVector *keys,
VXIVector *values) const;
#ifdef __THREADED
inline bool Lock( ) const {
bool rc = (VXItrdMutexLock(_callbackLock) == VXItrd_RESULT_SUCCESS);
if (! rc) Error(102, L"SBlog: Mutex lock failed", NULL);
return rc;
}
inline bool Unlock( ) const {
bool rc = (VXItrdMutexUnlock(_callbackLock) == VXItrd_RESULT_SUCCESS);
if (! rc) Error(103, L"SBlog: Mutex unlock failed", NULL);
return rc;
}
inline VXIthreadID GetThreadID( ) const {
return VXItrdThreadGetID();
}
#else
inline bool Lock( ) const { return true; }
inline bool Unlock( ) const { return true; }
inline VXIthreadID GetThreadID( ) const { return (VXIthreadID) 1; }
#endif
private:
typedef std::vector<SBlogDiagCallbackData *> DIAGCALLBACKS;
DIAGCALLBACKS diagCallbacks;
typedef std::vector<SBlogErrorCallbackData *> ERRORCALLBACKS;
ERRORCALLBACKS errorCallbacks;
typedef std::vector<SBlogEventCallbackData *> EVENTCALLBACKS;
EVENTCALLBACKS eventCallbacks;
typedef std::vector<SBlogContentCallbackData *> CONTENTCALLBACKS;
CONTENTCALLBACKS contentCallbacks;
#ifdef __THREADED
VXItrdMutex *_callbackLock;
VXItrdMutex *_internalErrorLoggingLock;
#endif
SBlogInterface *_pThis;
VXIthreadID _internalErrorLoggingThread;
unsigned char _tagIDs[TAG_ARRAY_SIZE];
};
SBlog::SBlog(SBlogInterface *pThis) :
#ifdef __THREADED
_callbackLock(NULL),
_internalErrorLoggingLock(NULL),
#endif
_pThis(pThis),
_internalErrorLoggingThread((VXIthreadID) -1)
{
// reset TAG ID range
memset(_tagIDs, 0, TAG_ARRAY_SIZE);
#ifdef __THREADED
// Create the mutexes
if ((VXItrdMutexCreate(&_callbackLock) != VXItrd_RESULT_SUCCESS) ||
(VXItrdMutexCreate(&_internalErrorLoggingLock) != VXItrd_RESULT_SUCCESS))
Error(101, L"OSBlog: Mutex create failed", NULL);
#endif
}
SBlog::~SBlog()
{
#ifdef __THREADED
// Destroy the mutexes
VXItrdMutexDestroy(&_callbackLock);
VXItrdMutexDestroy(&_internalErrorLoggingLock);
#endif
}
/**
* testbit
* testbit returns the value of the given bit
* 1 is set, 0 is clear
*/
unsigned SBlog::testbit(unsigned char num, int bitpos)
{
return (num >> bitpos) & ~(~0 << 1);
}
/**
* setbit sets a given bit
*/
void SBlog::setbit(unsigned char *num, int bitpos)
{
*num |= (1 << bitpos);
}
/**
* clearbit clears a given bit
*/
void SBlog::clearbit(unsigned char *num, int bitpos)
{
*num &= ~(1 << bitpos);
}
bool SBlog::Convert2Index(VXIunsigned tagID,
VXIunsigned *index,
VXIunsigned *bit_pos) const
{
// check for overflow TAG ID
if (tagID > SBLOG_MAX_TAG) {
Error(300, L"SBlog: Tag ID is too large", L"%s%u", L"tagID", tagID);
return false;
}
// retrieving index for char array
*index = tagID/8; // 8 bits per char
// retrieving bit position (bit range from 0-7)
*bit_pos = tagID%8;
return true; // done
}
VXIlogResult SBlog::ControlDiagnosticTag(VXIunsigned tagID,
VXIbool state)
{
VXIunsigned bindex, bpos;
if(!Convert2Index(tagID, &bindex, &bpos))
return VXIlog_RESULT_INVALID_ARGUMENT;
if(state)
setbit(&_tagIDs[bindex], bpos);
else
clearbit(&_tagIDs[bindex], bpos);
return VXIlog_RESULT_SUCCESS;
}
VXIlogResult SBlog::RegisterErrorListener(SBlogErrorCallbackData *info)
{
if (info == NULL) {
Error(200, L"SBlog: Internal error in RegisterErrorListener(), NULL "
L"callback data", NULL);
return VXIlog_RESULT_INVALID_ARGUMENT;
}
if (! Lock( )) {
return VXIlog_RESULT_SYSTEM_ERROR;
} else {
errorCallbacks.push_back(info);
if (! Unlock( ))
return VXIlog_RESULT_SYSTEM_ERROR;
}
return VXIlog_RESULT_SUCCESS;
}
SBlogErrorCallbackData*
SBlog::UnregisterErrorListener(SBlogErrorCallbackData *info)
{
if (info == NULL) {
Error(201, L"SBlog: Internal error in UnregisterErrorListener(), NULL "
L"callback data", NULL);
return NULL;
}
SBlogErrorCallbackData *status = NULL;
if (! Lock( )) {
return NULL;
} else {
for (ERRORCALLBACKS::iterator i = errorCallbacks.begin();
i != errorCallbacks.end(); ++i)
{
if (*info != *(*i)) continue;
status = *i;
errorCallbacks.erase(i);
break;
}
if (! Unlock( ))
return NULL;
}
return status;
}
VXIlogResult SBlog::RegisterDiagnosticListener(SBlogDiagCallbackData *info)
{
if (info == NULL) {
Error(202, L"SBlog: Internal error in RegisterDiagnosticListener(), NULL "
L"callback data", NULL);
return VXIlog_RESULT_INVALID_ARGUMENT;
}
if (! Lock( )) {
return VXIlog_RESULT_SYSTEM_ERROR;
} else {
diagCallbacks.push_back(info);
if (! Unlock( ))
return VXIlog_RESULT_SYSTEM_ERROR;
}
return VXIlog_RESULT_SUCCESS;
}
SBlogDiagCallbackData*
SBlog::UnregisterDiagnosticListener(SBlogDiagCallbackData *info)
{
if (info == NULL) {
Error(203, L"SBlog: Internal error in UnregisterDiagnosticListener(), "
L"NULL callback data", NULL);
return NULL;
}
SBlogDiagCallbackData *status = NULL;
if (! Lock( )) {
return NULL;
} else {
for (DIAGCALLBACKS::iterator i = diagCallbacks.begin();
i != diagCallbacks.end(); ++i)
{
if (*info != *(*i)) continue;
status = *i;
diagCallbacks.erase(i);
break;
}
if (! Unlock( ))
return NULL;
}
return status;
}
VXIlogResult SBlog::RegisterEventListener(SBlogEventCallbackData *info)
{
if (info == NULL) {
Error(204, L"SBlog: Internal error in RegisterEventListener(), NULL "
L"callback data", NULL);
return VXIlog_RESULT_INVALID_ARGUMENT;
}
if (! Lock( )) {
return VXIlog_RESULT_SYSTEM_ERROR;
} else {
eventCallbacks.push_back(info);
if (! Unlock( ))
return VXIlog_RESULT_SYSTEM_ERROR;
}
return VXIlog_RESULT_SUCCESS;
}
SBlogEventCallbackData*
SBlog::UnregisterEventListener(SBlogEventCallbackData *info)
{
if (info == NULL) {
Error(205, L"SBlog: Internal error in UnregisterEventListener(), NULL "
L"callback data", NULL);
return NULL;
}
SBlogEventCallbackData *status = NULL;
if (! Lock( )) {
return NULL;
} else {
for (EVENTCALLBACKS::iterator i = eventCallbacks.begin();
i != eventCallbacks.end(); ++i)
{
if (*info != *(*i)) continue;
status = *i;
eventCallbacks.erase(i);
break;
}
if (! Unlock( ))
return NULL;
}
return status;
}
VXIlogResult SBlog::RegisterContentListener(SBlogContentCallbackData *info)
{
if (info == NULL) {
Error(206, L"SBlog: Internal error in RegisterContentListener(), NULL "
L"callback data", NULL);
return VXIlog_RESULT_INVALID_ARGUMENT;
}
if (! Lock( )) {
return VXIlog_RESULT_SYSTEM_ERROR;
} else {
contentCallbacks.push_back(info);
if (! Unlock( ))
return VXIlog_RESULT_SYSTEM_ERROR;
}
return VXIlog_RESULT_SUCCESS;
}
SBlogContentCallbackData*
SBlog::UnregisterContentListener(SBlogContentCallbackData *info)
{
if (info == NULL) {
Error(207, L"SBlog: Internal error in RegisterContentListener(), NULL "
L"callback data", NULL);
return NULL;
}
SBlogContentCallbackData *status = NULL;
if (! Lock( )) {
return NULL;
} else {
for (CONTENTCALLBACKS::iterator i = contentCallbacks.begin();
i != contentCallbacks.end(); ++i)
{
if (*info != *(*i)) continue;
status = *i;
contentCallbacks.erase(i);
break;
}
if (! Unlock( ))
return NULL;
}
return status;
}
VXIlogResult SBlog::ParseKeyValue(const VXIchar *format,
va_list args,
VXIVector *keys,
VXIVector *values) const
{
const VXIchar SEP[] = L"{*}";
const int SEP_LEN = 3;
if (( format == NULL ) || ( keys == NULL ) || ( values == NULL )) {
Error(208, L"SBlog: Internal error in ParseKeyValue(), invalid argument",
NULL);
return VXIlog_RESULT_INVALID_ARGUMENT;
}
// Insert delimiters into a revised format string, this does
// validation as well as letting us split it into key/values later
VXIlogResult rc = VXIlog_RESULT_SUCCESS;
bool hadFreeformText = false;
int replacementStart = -1, fieldCount = 0;
size_t resultFormatLen = 0;
VXIchar resultFormat[MAX_LOG_BUFFER];
resultFormat[0] = L'\0';
for (int i = 0; (format[i] != L'\0') && (rc == VXIlog_RESULT_SUCCESS); i++) {
if (format[i] == '%') {
if (replacementStart > -1)
replacementStart = -1; // double %%
else
replacementStart = i;
} else if ((replacementStart > -1) && (SBlogIsAlpha(format[i])) &&
(format[i] != L'l') && (format[i] != L'L') &&
(format[i] != L'h')) {
if ((fieldCount % 2 == 0) && (format[i] != L's') &&
(format[i] != L'S')) {
// Keys must be a %s or %S, truncate from here
Error(301, L"SBlog: Invalid format string for VXIlog API call, "
L"replacements for key names must be %s", L"%s%s", L"format",
format);
rc = VXIlog_RESULT_NON_FATAL_ERROR;
} else {
// Insert the replacement expression and the seperator
size_t index = resultFormatLen;
resultFormatLen += (i - replacementStart) + 1 + SEP_LEN;
if (resultFormatLen < MAX_LOG_BUFFER) {
wcsncpy(&resultFormat[index], &format[replacementStart],
(i - replacementStart) + 1);
index += (i - replacementStart) + 1;
wcscpy(&resultFormat[index], SEP);
} else {
// Overflow, truncate the format string from here
rc = VXIlog_RESULT_NON_FATAL_ERROR;
}
replacementStart = -1;
fieldCount++;
}
} else if (replacementStart == -1) {
// Shouldn't have free-form text, skip it. Proceeding allows us
// to gracefully handle things like "%s0x%p".
hadFreeformText = true;
}
}
// if key/value is not even truncate the field and return an error,
// but proceed with the other fields. If there was free form text,
// we skipped it and return an error, but proceed with logging.
if (fieldCount % 2 != 0) {
Error(302, L"SBlog: Invalid format string for VXIlog API call, "
L"missing value for a key", L"%s%s", L"format", format);
rc = VXIlog_RESULT_NON_FATAL_ERROR;
fieldCount--;
} else if (hadFreeformText) {
Error(303, L"SBlog: Invalid format string for VXIlog API call, "
L"must be a list of format strings for key/value pairs",
L"%s%s", L"format", format);
rc = VXIlog_RESULT_NON_FATAL_ERROR;
}
// get the values
VXIchar result[MAX_LOG_BUFFER];
result[0] = L'\0';
SBlogVswprintf(result, MAX_LOG_BUFFER-1, resultFormat, args);
// parse the key/value based on the inserted separators
long fieldNum = 0;
const VXIchar *start = result, *end;
while ((fieldNum < fieldCount) && ((end = wcsstr(start, SEP)) != NULL)) {
// Insert into key/value vector
fieldNum++;
if (fieldNum % 2) // odd is key
VXIVectorAddElement(keys,(VXIValue*)VXIStringCreateN(start,end-start));
else
VXIVectorAddElement(values,(VXIValue*)VXIStringCreateN(start,end-start));
// Advance
start = &end[SEP_LEN];
}
if (fieldNum != fieldCount) {
// parse error
Error(304, L"SBlog: Internal error, parse failure after key/value "
L"insertions", L"%s%s%s%s", L"format", format, L"result", result);
rc = VXIlog_RESULT_NON_FATAL_ERROR;
}
return rc;
}
VXIlogResult SBlog::Error(VXIunsigned errorID, const VXIchar *errorIDText,
const VXIchar *format, ...) const
{
VXIlogResult rc = VXIlog_RESULT_SUCCESS;
// Avoid recursively reporting logging errors
if (_internalErrorLoggingThread == GetThreadID())
return VXIlog_RESULT_FAILURE;
if (VXItrdMutexLock(_internalErrorLoggingLock) != VXItrd_RESULT_SUCCESS) {
return VXIlog_RESULT_SYSTEM_ERROR;
} else {
VXIthreadID *loggingThread =
const_cast<VXIthreadID *>(&_internalErrorLoggingThread);
*loggingThread = GetThreadID();
va_list args;
va_start(args, format);
rc = ErrorLog(MODULE_NAME, errorID, format, args);
if ( rc != VXIlog_RESULT_SUCCESS )
SBlogVLogErrorToConsole(MODULE_NAME, errorID, errorIDText, format, args);
va_end(args);
*loggingThread = (VXIthreadID) -1;
if (VXItrdMutexUnlock(_internalErrorLoggingLock) != VXItrd_RESULT_SUCCESS)
return VXIlog_RESULT_SYSTEM_ERROR;
}
return rc;
}
VXIlogResult SBlog::GlobalError(VXIunsigned errorID,
const VXIchar *errorIDText,
const VXIchar *format, ...)
{
va_list args;
va_start(args, format);
VXIlogResult rc = SBlogVLogErrorToConsole(MODULE_NAME, errorID, errorIDText,
format, args);
va_end(args);
return rc;
}
bool SBlog::DiagnosticIsEnabled(VXIunsigned tagID)
{
VXIunsigned bindex, bpos;
if (!Convert2Index(tagID, &bindex, &bpos))
return false;
// if this tag is not turned on, just return
if (!testbit(_tagIDs[bindex],bpos))
return false;
return true;
}
VXIlogResult SBlog::DiagnosticLog(VXIunsigned tagID,
const VXIchar* subtag,
const VXIchar* format,
va_list arguments) const
{
VXIunsigned bindex, bpos;
if (!Convert2Index(tagID, &bindex, &bpos))
return VXIlog_RESULT_INVALID_ARGUMENT;
// if this tag is not turned on, just return
if (!testbit(_tagIDs[bindex],bpos))
return VXIlog_RESULT_SUCCESS;
time_t timestamp;
VXIunsigned timestampMsec;
SBlogGetTime (×tamp, ×tampMsec);
wchar_t printmsg[MAX_LOG_BUFFER];
printmsg[0] = L'\0';
if (format != NULL)
SBlogVswprintf(printmsg, MAX_LOG_BUFFER-1, format, arguments);
if (subtag == NULL)
subtag = L"";
// Get a temporary callback vector copy to traverse, allows
// listeners to unregister from within the listener, also increases
// parallelism by allowing multiple threads to be calling the
// callbacks at once
VXIlogResult rc = VXIlog_RESULT_FAILURE;
if (! Lock( )) {
return VXIlog_RESULT_SYSTEM_ERROR;
} else {
DIAGCALLBACKS tempDiag = diagCallbacks;
if (! Unlock( ))
return VXIlog_RESULT_SYSTEM_ERROR;
for (DIAGCALLBACKS::iterator i = tempDiag.begin(); i != tempDiag.end();++i)
{
(*i)->callback(_pThis, tagID, subtag, timestamp, timestampMsec,
printmsg, (*i)->userdata);
rc = VXIlog_RESULT_SUCCESS;
}
}
return rc;
}
VXIlogResult SBlog::EventLog(VXIunsigned eventID,
const VXIchar* format,
va_list args) const
{
time_t timestamp;
VXIunsigned timestampMsec;
SBlogGetTime (×tamp, ×tampMsec);
// Create key/value pairs
VXIVector *keys = VXIVectorCreate();
VXIVector *values = VXIVectorCreate();
if ((! keys) || (! values)) {
Error(SBLOG_ERR_OUT_OF_MEMORY);
return VXIlog_RESULT_OUT_OF_MEMORY;
}
VXIlogResult rc = VXIlog_RESULT_SUCCESS;
if (format) {
rc = ParseKeyValue(format, args, keys, values);
if (rc < VXIlog_RESULT_SUCCESS) {
VXIVectorDestroy(&keys);
VXIVectorDestroy(&values);
return rc;
}
}
// Get a temporary callback vector copy to traverse, allows
// listeners to unregister from within the listener, also increases
// parallelism by allowing multiple threads to be calling the
// callbacks at once
if (rc == VXIlog_RESULT_SUCCESS)
rc = VXIlog_RESULT_FAILURE;
if (! Lock( )) {
return VXIlog_RESULT_SYSTEM_ERROR;
} else {
EVENTCALLBACKS tempEvent = eventCallbacks;
if (! Unlock( ))
return VXIlog_RESULT_SYSTEM_ERROR;
for (EVENTCALLBACKS::iterator i = tempEvent.begin();
i != tempEvent.end(); ++i)
{
(*i)->callback(_pThis, eventID, timestamp, timestampMsec, keys, values,
(*i)->userdata);
if (rc == VXIlog_RESULT_FAILURE)
rc = VXIlog_RESULT_SUCCESS;
}
}
VXIVectorDestroy(&keys);
VXIVectorDestroy(&values);
return rc;
}
VXIlogResult SBlog::EventLog(VXIunsigned eventID,
const VXIVector* keys,
const VXIVector* values) const
{
time_t timestamp;
VXIunsigned timestampMsec;
SBlogGetTime (×tamp, ×tampMsec);
// Get a temporary callback vector copy to traverse, allows
// listeners to unregister from within the listener, also increases
// parallelism by allowing multiple threads to be calling the
// callbacks at once
VXIlogResult rc = VXIlog_RESULT_FAILURE;
if (! Lock( )) {
return VXIlog_RESULT_SYSTEM_ERROR;
} else {
EVENTCALLBACKS tempEvent = eventCallbacks;
if (! Unlock( ))
return VXIlog_RESULT_SYSTEM_ERROR;
for (EVENTCALLBACKS::iterator i = tempEvent.begin();
i != tempEvent.end(); ++i)
{
(*i)->callback(_pThis, eventID, timestamp, timestampMsec, keys, values,
(*i)->userdata);
rc = VXIlog_RESULT_SUCCESS;
}
}
return rc;
}
VXIlogResult SBlog::ErrorLog(const VXIchar* moduleName,
VXIunsigned errorID,
const VXIchar* format,
va_list args) const
{
time_t timestamp;
VXIunsigned timestampMsec;
SBlogGetTime (×tamp, ×tampMsec);
// Create key/value pairs
VXIVector *keys = VXIVectorCreate();
VXIVector *values = VXIVectorCreate();
if ((! keys) || (! values)) {
Error(SBLOG_ERR_OUT_OF_MEMORY);
return VXIlog_RESULT_OUT_OF_MEMORY;
}
VXIlogResult rc = VXIlog_RESULT_SUCCESS;
if (format) {
rc = ParseKeyValue(format, args, keys, values);
if (rc < VXIlog_RESULT_SUCCESS) {
VXIVectorDestroy(&keys);
VXIVectorDestroy(&values);
return rc;
}
}
// Get a temporary callback vector copy to traverse, allows
// listeners to unregister from within the listener, also increases
// parallelism by allowing multiple threads to be calling the
// callbacks at once
if (rc == VXIlog_RESULT_SUCCESS)
rc = VXIlog_RESULT_FAILURE;
if (! Lock( )) {
return VXIlog_RESULT_SYSTEM_ERROR;
} else {
ERRORCALLBACKS tempError = errorCallbacks;
if (! Unlock( ))
return VXIlog_RESULT_SYSTEM_ERROR;
for (ERRORCALLBACKS::iterator i = tempError.begin();
i != tempError.end(); ++i)
{
(*i)->callback(_pThis,
(moduleName && moduleName[0] ? moduleName : L"UNKNOWN"),
errorID, timestamp, timestampMsec, keys, values,
(*i)->userdata);
if (rc == VXIlog_RESULT_FAILURE)
rc = VXIlog_RESULT_SUCCESS;
}
}
VXIVectorDestroy(&keys);
VXIVectorDestroy(&values);
// Want to warn the caller that NULL moduleName really isn't OK, but
// logged it anyway
if ((! moduleName) || (! moduleName[0])) {
Error(305, L"SBlog: Empty module name passed to VXIlog API call", NULL);
rc = VXIlog_RESULT_INVALID_ARGUMENT;
}
return rc;
}
VXIlogResult SBlog::ContentOpen(const VXIchar* moduleName,
const VXIchar* contentType,
VXIString** logKey,
VXIString** logValue,
VXIlogStream** stream) const
{
if ((! contentType) || (! contentType[0]) || (! logKey) || (! logValue) ||
(! stream)) {
Error(306, L"SBlog: Invalid argument to VXIlog::ContentOpen()", NULL);
return VXIlog_RESULT_INVALID_ARGUMENT;
}
*logKey = *logValue = NULL;
*stream = NULL;
const VXIchar *finalModuleName = L"UNKNOWN";
if ((! moduleName) || (! moduleName[0])) {
Error(305, L"SBlog: Empty module name passed to VXIlog API call", NULL);
} else {
finalModuleName = moduleName;
}
VXIlogResult rc = VXIlog_RESULT_FAILURE;
// Get a temporary callback vector copy to traverse, allows
// listeners to unregister from within the listener, also increases
// parallelism by allowing multiple threads to be calling the
// callbacks at once
if (! Lock( )) {
return VXIlog_RESULT_SYSTEM_ERROR;
} else {
CONTENTCALLBACKS tempContent = contentCallbacks;
if (! Unlock( ))
return VXIlog_RESULT_SYSTEM_ERROR;
VXIlogStream *finalStream = NULL;
for (CONTENTCALLBACKS::iterator i = tempContent.begin();
i != tempContent.end(); ++i)
{
VXIString *logKey_ = NULL;
VXIString *logValue_ = NULL;
SBlogStream *stream_ = NULL;
VXIlogResult rc2 = (*i)->callback(_pThis,
finalModuleName,
contentType,
(*i)->userdata,
&logKey_,
&logValue_,
&stream_);
if ((rc2 == VXIlog_RESULT_SUCCESS) && (stream_)) {
// Return the key and value of only the first listener
if ( rc != VXIlog_RESULT_SUCCESS ) {
finalStream = new VXIlogStream;
if (! finalStream) {
VXIStringDestroy(&logKey_);
VXIStringDestroy(&logValue_);
stream_->Close(&stream_);
Error(SBLOG_ERR_OUT_OF_MEMORY);
return VXIlog_RESULT_OUT_OF_MEMORY;
}
rc = VXIlog_RESULT_SUCCESS;
*logKey = logKey_;
*logValue = logValue_;
*stream = (VXIlogStream *) finalStream;
} else {
VXIStringDestroy(&logKey_);
VXIStringDestroy(&logValue_);
}
// Store the stream
finalStream->streams.push_back(stream_);
} else if ((rc != VXIlog_RESULT_SUCCESS) &&
(((rc < 0) && (rc2 < rc)) ||
((rc > 0) && (rc2 > rc)))) {
// Return success if any listener returns success but keep the
// worst error otherwise
rc = rc2;
}
}
}
return rc;
}
VXIlogResult SBlog::ContentClose(VXIlogStream** stream) const
{
if ((! stream) || (! *stream)) {
Error(307, L"SBlog: Invalid argument to VXIlog::ContentClose()", NULL);
return VXIlog_RESULT_INVALID_ARGUMENT;
}
VXIlogResult rc = VXIlog_RESULT_SUCCESS;
// Close each of the underlying listener streams
for (VXIlogStream::STREAMS::iterator vi = (*stream)->streams.begin( );
vi != (*stream)->streams.end( ); vi++) {
SBlogStream *s = *vi;
VXIlogResult rc2 = s->Close (&s);
if ((rc == VXIlog_RESULT_SUCCESS) || ((rc < 0) && (rc2 < rc)) ||
((rc > 0) && (rc2 > rc)))
rc = rc2;
}
delete *stream;
*stream = NULL;
return rc;
}
VXIlogResult SBlog::ContentWrite(const VXIbyte* buffer,
VXIulong buflen,
VXIulong* nwritten,
VXIlogStream* stream) const
{
if ((! buffer) || (buflen < 1) || (! nwritten) || (! stream)) {
Error(308, L"SBlog: Invalid argument to VXIlog::ContentWrite()", NULL);
return VXIlog_RESULT_INVALID_ARGUMENT;
}
VXIlogResult rc = VXIlog_RESULT_SUCCESS;
*nwritten = 0;
// Write to each of the underlying listener streams
for (VXIlogStream::STREAMS::iterator vi = stream->streams.begin( );
vi != stream->streams.end( ); vi++) {
SBlogStream *s = *vi;
VXIulong nw = 0;
VXIlogResult rc2 = s->Write (s, buffer, buflen, &nw);
if (rc == VXIlog_RESULT_SUCCESS) {
if (nw > *nwritten)
*nwritten = nw;
} else if ((rc == VXIlog_RESULT_SUCCESS) || ((rc < 0) && (rc2 < rc)) ||
((rc > 0) && (rc2 > rc))) {
rc = rc2;
}
}
return rc;
}
/***********************************************************************/
VXIlogResult SBlogControlDiagnosticTag(SBlogInterface *pThis,
VXIunsigned tagID,
VXIbool state)
{
if (pThis == NULL)
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI *) pThis;
SBlog *me = (SBlog *)temp->impl_;
return (me->ControlDiagnosticTag(tagID, state));
}
VXIlogResult SBlogRegisterErrorListener(SBlogInterface *pThis,
SBlogErrorListener* alistener,
void* userdata)
{
if ((pThis == NULL) || (alistener == NULL))
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI *) pThis;
SBlog *me = (SBlog *)temp->impl_;
SBlogErrorCallbackData *info = new SBlogErrorCallbackData;
if (info == NULL) {
me->Error(SBLOG_ERR_OUT_OF_MEMORY);
return VXIlog_RESULT_OUT_OF_MEMORY;
}
info->callback = alistener;
info->userdata = userdata;
return ( me->RegisterErrorListener(info));
}
VXIlogResult SBlogUnregisterErrorListener(SBlogInterface *pThis,
SBlogErrorListener* alistener,
void* userdata)
{
if ((pThis == NULL) || (alistener == NULL))
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI *) pThis;
SBlog *me = (SBlog *)temp->impl_;
SBlogErrorCallbackData info = { alistener, userdata };
SBlogErrorCallbackData *p = me->UnregisterErrorListener(&info);
if (p) delete p;
return VXIlog_RESULT_SUCCESS;
}
VXIlogResult SBlogRegisterDiagnosticListener(SBlogInterface *pThis,
SBlogDiagnosticListener*alistener,
void* userdata)
{
if ((pThis == NULL) || (alistener == NULL))
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI *) pThis;
SBlog *me = (SBlog *)temp->impl_;
SBlogDiagCallbackData *info = new SBlogDiagCallbackData;
if (info == NULL) {
me->Error(SBLOG_ERR_OUT_OF_MEMORY);
return VXIlog_RESULT_OUT_OF_MEMORY;
}
info->callback = alistener;
info->userdata = userdata;
return ( me->RegisterDiagnosticListener(info));
}
VXIlogResult SBlogUnregisterDiagnosticListener(
SBlogInterface *pThis,
SBlogDiagnosticListener* alistener,
void* userdata)
{
if ((pThis == NULL) || (alistener == NULL))
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI *) pThis;
SBlog *me = (SBlog *)temp->impl_;
SBlogDiagCallbackData info = { alistener, userdata };
SBlogDiagCallbackData *p = me->UnregisterDiagnosticListener(&info);
if (p) delete p;
return VXIlog_RESULT_SUCCESS;
}
VXIlogResult SBlogRegisterEventListener(SBlogInterface *pThis,
SBlogEventListener* alistener,
void* userdata)
{
if ((pThis == NULL) || (alistener == NULL))
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI *) pThis;
SBlog *me = (SBlog *)temp->impl_;
SBlogEventCallbackData *info = new SBlogEventCallbackData;
if (info == NULL) {
me->Error(SBLOG_ERR_OUT_OF_MEMORY);
return VXIlog_RESULT_OUT_OF_MEMORY;
}
info->callback = alistener;
info->userdata = userdata;
return ( me->RegisterEventListener(info));
}
VXIlogResult SBlogUnregisterEventListener(SBlogInterface *pThis,
SBlogEventListener* alistener,
void* userdata)
{
if ((pThis == NULL) || (alistener == NULL))
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI *) pThis;
SBlog *me = (SBlog *)temp->impl_;
SBlogEventCallbackData info = { alistener, userdata };
SBlogEventCallbackData *p = me->UnregisterEventListener(&info);
if (p) delete p;
return VXIlog_RESULT_SUCCESS;
}
VXIlogResult SBlogRegisterContentListener(SBlogInterface *pThis,
SBlogContentListener* alistener,
void* userdata)
{
if ((pThis == NULL) || (alistener == NULL))
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI *) pThis;
SBlog *me = (SBlog *)temp->impl_;
SBlogContentCallbackData *info = new SBlogContentCallbackData;
if (info == NULL) {
me->Error(SBLOG_ERR_OUT_OF_MEMORY);
return VXIlog_RESULT_OUT_OF_MEMORY;
}
info->callback = alistener;
info->userdata = userdata;
return ( me->RegisterContentListener(info));
}
VXIlogResult SBlogUnregisterContentListener(SBlogInterface *pThis,
SBlogContentListener* alistener,
void* userdata)
{
if ((pThis == NULL) || (alistener == NULL))
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI *) pThis;
SBlog *me = (SBlog *)temp->impl_;
SBlogContentCallbackData info = { alistener, userdata };
SBlogContentCallbackData *p = me->UnregisterContentListener(&info);
if (p) delete p;
return VXIlog_RESULT_SUCCESS;
}
/**********************************************************************
*/
SBLOG_API VXIint32 SBlogGetVersion(void)
{
return VXI_CURRENT_VERSION;
}
SBLOG_API const VXIchar* SBlogGetImplementationName(void)
{
static const VXIchar IMPLEMENTATION_NAME[] = COMPANY_DOMAIN L".SBlog";
return IMPLEMENTATION_NAME;
}
SBLOG_API VXIbool SBlogDiagnosticIsEnabled(VXIlogInterface * pThis,
VXIunsigned tagID)
{
if (pThis == NULL)
return FALSE;
myAPI *temp = (myAPI *) pThis;
SBlog *me = (SBlog *) temp->impl_;
if (!me->DiagnosticIsEnabled(tagID)) return FALSE;
return TRUE;
}
SBLOG_API VXIlogResult SBlogDiagnostic(VXIlogInterface* pThis,
VXIunsigned tagID,
const VXIchar* subtag,
const VXIchar* format,
...)
{
if (pThis == NULL)
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI *) pThis;
SBlog *me = (SBlog *) temp->impl_;
va_list args;
va_start(args, format);
VXIlogResult ret = me->DiagnosticLog(tagID, subtag, format, args);
va_end(args);
return ret;
}
SBLOG_API VXIlogResult SBlogVDiagnostic(VXIlogInterface* pThis,
VXIunsigned tagID,
const VXIchar* subtag,
const VXIchar* format,
va_list vargs)
{
if (pThis == NULL)
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI *)pThis;
SBlog *me = (SBlog *)temp->impl_;
VXIlogResult ret = me->DiagnosticLog(tagID, subtag, format, vargs);
return ret;
}
SBLOG_API VXIlogResult SBlogEvent(VXIlogInterface* pThis,
VXIunsigned eventID,
const VXIchar* format,
...)
{
if (pThis == NULL)
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI*)pThis;
SBlog *me = (SBlog *)temp->impl_;
va_list args;
va_start(args, format);
VXIlogResult ret = me->EventLog(eventID, format, args);
va_end(args);
return ret;
}
SBLOG_API VXIlogResult SBlogVEvent(VXIlogInterface* pThis,
VXIunsigned eventID,
const VXIchar* format,
va_list vargs)
{
if (pThis == NULL)
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI*)pThis;
SBlog *me = (SBlog *)temp->impl_;
VXIlogResult ret = me->EventLog(eventID, format, vargs);
return ret;
}
SBLOG_API VXIlogResult SBlogEventVector(VXIlogInterface* pThis,
VXIunsigned eventID,
const VXIVector* keys,
const VXIVector* values)
{
if (pThis == NULL)
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI*)pThis;
SBlog *me = (SBlog *)temp->impl_;
VXIlogResult ret = me->EventLog(eventID, keys, values);
return ret;
}
SBLOG_API VXIlogResult SBlogError(VXIlogInterface* pThis,
const VXIchar* moduleName,
VXIunsigned errorID,
const VXIchar* format,
...)
{
if (pThis == NULL)
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI*)pThis;
SBlog *me = (SBlog *)temp->impl_;
va_list args;
va_start(args, format);
VXIlogResult ret = me->ErrorLog(moduleName, errorID, format, args);
va_end(args);
return ret;
}
SBLOG_API VXIlogResult SBlogVError(VXIlogInterface* pThis,
const VXIchar* moduleName,
VXIunsigned errorID,
const VXIchar* format,
va_list vargs)
{
if (pThis == NULL)
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI*)pThis;
SBlog *me = (SBlog *)temp->impl_;
VXIlogResult ret = me->ErrorLog(moduleName, errorID, format, vargs);
return ret;
}
SBLOG_API VXIlogResult SBlogContentOpen(VXIlogInterface* pThis,
const VXIchar* moduleName,
const VXIchar* contentType,
VXIString** logKey,
VXIString** logValue,
VXIlogStream** stream)
{
if (pThis == NULL)
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI*)pThis;
SBlog *me = (SBlog *)temp->impl_;
VXIlogResult ret = me->ContentOpen(moduleName, contentType,
logKey, logValue, stream);
return ret;
}
SBLOG_API VXIlogResult SBlogContentClose(VXIlogInterface* pThis,
VXIlogStream** stream)
{
if (pThis == NULL)
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI*)pThis;
SBlog *me = (SBlog *)temp->impl_;
VXIlogResult ret = me->ContentClose(stream);
return ret;
}
SBLOG_API VXIlogResult SBlogContentWrite(VXIlogInterface* pThis,
const VXIbyte* buffer,
VXIulong buflen,
VXIulong* nwritten,
VXIlogStream* stream)
{
if (pThis == NULL)
return VXIlog_RESULT_INVALID_ARGUMENT;
myAPI *temp = (myAPI*)pThis;
SBlog *me = (SBlog *)temp->impl_;
VXIlogResult ret = me->ContentWrite(buffer, buflen, nwritten, stream);
return ret;
}
// -----1=0-------2=0-------3=0-------4=0-------5=0-------6=0-------7=0-------8
/**
* Global platform initialization of SBlog
*
* @result VXIlogResult 0 on success
*/
SBLOG_API VXIlogResult SBlogInit(void)
{
if (gblInitialized == true) {
SBlog::GlobalError(SBLOG_ERR_ALREADY_INITIALIZED);
return VXIlog_RESULT_FATAL_ERROR;
}
gblInitialized = true;
return VXIlog_RESULT_SUCCESS;
}
/**
* Global platform shutdown of Log
*
* @result VXIlogResult 0 on success
*/
SBLOG_API VXIlogResult SBlogShutDown(void)
{
if (gblInitialized == false) {
SBlog::GlobalError(SBLOG_ERR_NOT_INITIALIZED);
return VXIlog_RESULT_FATAL_ERROR;
}
gblInitialized = false;
return VXIlog_RESULT_SUCCESS;
}
/**
* Create a new log service handle
*
* @result VXIlogResult 0 on success
*/
SBLOG_API VXIlogResult SBlogCreateResource(VXIlogInterface **log)
{
if (gblInitialized == false) {
SBlog::GlobalError(SBLOG_ERR_NOT_INITIALIZED);
return VXIlog_RESULT_FATAL_ERROR;
}
if (log == NULL) {
SBlog::GlobalError(309, L"SBlog: SBlogCreateResource() requires a "
L"non-NULL log interface pointer", NULL);
return VXIlog_RESULT_INVALID_ARGUMENT;
}
myAPI *temp = new myAPI;
if (temp == NULL) {
SBlog::GlobalError(SBLOG_ERR_OUT_OF_MEMORY);
return VXIlog_RESULT_OUT_OF_MEMORY;
}
memset (temp, 0, sizeof (myAPI));
SBlog *me = new SBlog(&temp->intf);
if (me == NULL) {
delete temp;
SBlog::GlobalError(SBLOG_ERR_OUT_OF_MEMORY);
return VXIlog_RESULT_OUT_OF_MEMORY;
}
// Initialize the VXIlogInterface function pointers
temp->intf.vxilog.GetVersion = SBlogGetVersion;
temp->intf.vxilog.GetImplementationName = SBlogGetImplementationName;
temp->intf.vxilog.Error = SBlogError;
temp->intf.vxilog.VError = SBlogVError;
temp->intf.vxilog.Diagnostic = SBlogDiagnostic;
temp->intf.vxilog.VDiagnostic = SBlogVDiagnostic;
temp->intf.vxilog.DiagnosticIsEnabled = SBlogDiagnosticIsEnabled;
temp->intf.vxilog.Event = SBlogEvent;
temp->intf.vxilog.VEvent = SBlogVEvent;
temp->intf.vxilog.EventVector = SBlogEventVector;
temp->intf.vxilog.ContentOpen = SBlogContentOpen;
temp->intf.vxilog.ContentClose = SBlogContentClose;
temp->intf.vxilog.ContentWrite = SBlogContentWrite;
// Initialize the SBlogInterface functions
temp->intf.RegisterErrorListener = SBlogRegisterErrorListener;
temp->intf.UnregisterErrorListener = SBlogUnregisterErrorListener;
temp->intf.RegisterDiagnosticListener = SBlogRegisterDiagnosticListener;
temp->intf.UnregisterDiagnosticListener = SBlogUnregisterDiagnosticListener;
temp->intf.RegisterEventListener = SBlogRegisterEventListener;
temp->intf.UnregisterEventListener = SBlogUnregisterEventListener;
temp->intf.RegisterContentListener = SBlogRegisterContentListener;
temp->intf.UnregisterContentListener = SBlogUnregisterContentListener;
temp->intf.ControlDiagnosticTag = SBlogControlDiagnosticTag;
temp->impl_ = (void*)me;
// Return the object
*log = &temp->intf.vxilog;
return VXIlog_RESULT_SUCCESS;
}
/**
* Destroy the interface and free internal resources
*
* @result VXIlogResult 0 on success
*/
SBLOG_API VXIlogResult SBlogDestroyResource(VXIlogInterface **log)
{
if (gblInitialized == false) {
SBlog::GlobalError(SBLOG_ERR_NOT_INITIALIZED);
return VXIlog_RESULT_FATAL_ERROR;
}
if ((log == NULL) || (*log == NULL)) {
SBlog::GlobalError(310, L"SBlog: SBlogDestroyResource() requires a "
L"non-NULL log interface pointer", NULL);
return VXIlog_RESULT_INVALID_ARGUMENT;
}
// Delete the object
myAPI *temp = (myAPI *) *log;
SBlog *me = (SBlog *)temp->impl_;
if (me) delete me;
if (temp) delete temp;
*log = NULL;
return VXIlog_RESULT_SUCCESS;
}
| [
"ausmarton@gmail.com"
] | ausmarton@gmail.com |
67dd8c8952c2309a7893c69f30be5e73f0044c71 | 3e56a1aea87fe544cfb83e98d346b5722f08ab96 | /Add-On/FileAccess.cpp | 2157f741b7675436f299987111f9c343e4ea20e4 | [] | no_license | HaikuArchives/Lava | 72b420edb98ed697f41d53829a68706ff66e1102 | 161a4212f03a02727d6c8434333f91fa4e02fc04 | refs/heads/master | 2021-01-20T15:36:08.027281 | 2014-12-11T03:03:19 | 2014-12-11T03:03:19 | 11,778,535 | 1 | 1 | null | 2014-01-05T11:51:32 | 2013-07-31T00:11:25 | C++ | UTF-8 | C++ | false | false | 7,261 | cpp | /*
* Copyright 2010 Team MAUI All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Robert Stiehler, Negr0@team-maui.org
*/
#include "FileAccess.h"
#include <Alert.h>
FileAccess::FileAccess()
: intSizeOfFiles(0), fStateContainer(NULL)
{
fIsGenerated = false;
FileList = new BList();
TypeList = new BList();
fVolumes = new BVolumeRoster();
}
FileAccess::~FileAccess()
{
delete TypeList, FileList, fVolumes;
}
void
FileAccess::setStateContainer(BString *StateCont)
{
fStateContainer = StateCont;
}
void
FileAccess::setFiles(BList *FileList)
{
this->FileList = FileList;
fIsGenerated = false;
}
BList*
FileAccess::getFiles()
{
return this->FileList;
}
BList*
FileAccess::getTypes()
{
return this->TypeList;
}
off_t
FileAccess::getFileSize()
{
return intSizeOfFiles;
}
/* getFileTree
* returns the files as tree
*/
FileTree*
FileAccess::getFileTree()
{
return fObjFileTree;
}
/* getIconOfFile
* returns icons as Bitmap
*/
BBitmap*
FileAccess::getIconOfFile(BString strPath)
{
BNode *node = new BNode(strPath.String());
BNodeInfo *info = new BNodeInfo();
info->SetTo(node);
#if __HAIKU__
BBitmap *Icon = new BBitmap(BRect(0, 0, B_MINI_ICON - 1, B_MINI_ICON - 1), B_RGBA32); //for haiku
#else
BBitmap *Icon = new BBitmap(BRect(0, 0, B_MINI_ICON - 1, B_MINI_ICON - 1), B_COLOR_8_BIT); //BeOS, Zeta, etc.
#endif
info->GetTrackerIcon(Icon, B_MINI_ICON);
delete node, info;
return Icon;
}
/* FileTypeInTypeList
* checks if a filetype is already in the type list
*/
bool
FileAccess::_FileTypeInTypeList(BString strType)
{
BString *strTMP;
for(int i = 0; i < TypeList->CountItems(); i++) {
strTMP = (BString*)TypeList->ItemAt(i);
if(strTMP->Compare(strType) == 0)
return true;
}
return false;
}
/* getTypeOfFilesByAttr
* method read the type of a list of files and
* and write it to a BList object ((protected)TypeList)
*/
void
FileAccess::getTypeOfFilesByAttr()
{
BString *strTMP;
BString strTMP2;
BNode *node = new BNode();
for(int i = 0; i < FileList->CountItems(); i++) {
strTMP = (BString*)FileList->ItemAt(i);
node = new BNode(strTMP->String());
memset(buffer, 0, sizeof(buffer));
node->ReadAttr("BEOS:TYPE", B_STRING_TYPE, 0, buffer, sizeof(buffer));
if(!_FileTypeInTypeList(buffer))
TypeList->AddItem(new BString(buffer));
delete node;
}
}
/* _addToSizeOfFiles
* method sum the size of files
*/
void
FileAccess::_addToSizeOfFiles(off_t Size)
{
intSizeOfFiles += Size;
}
/* getFilesFromQuery
* method get files from a query and put them to filestructure
*/
bool
FileAccess::getFilesFromQuery(BString strQueryFile, BString strParent, off_t *sizeOfFolder)
{
fNode->SetTo(strQueryFile.String());
memset(buffer, 0, sizeof(buffer));
fNode->ReadAttr("BEOS:TYPE", B_STRING_TYPE, 0, buffer, sizeof(buffer));
if(strcmp(buffer, "application/x-vnd.Be-query") == 0) {
off_t TMP = 0;
off_t *ptFolderSize;
fQuery->Clear();
memset(buffer, 0, sizeof(buffer));
fNode->ReadAttr("_trk/qrystr", B_STRING_TYPE, 0, buffer, sizeof(buffer));
fQuery->SetPredicate(buffer);
while(fVolumes->GetNextVolume(fVolume) != B_BAD_VALUE) {
fQuery->SetVolume(fVolume);
fQuery->Fetch();
while(fQuery->GetNextEntry(fEntry) == B_OK) {
fEntry->GetPath(fPath);
fDirectory->SetTo(fPath->Path());
if(fDirectory->InitCheck() != B_OK) {
if(strQueryFile.Compare(fPath->Path()) != 0) {
fFileAcces->SetTo(fPath->Path(), B_READ_ONLY);
fFileAcces->GetSize(&TMP);
_addToSizeOfFiles(TMP);
if(sizeOfFolder != NULL)
sizeOfFolder += TMP;
fObjFileTree->AddNode(strParent.String(), fPath->Path(), true, new off_t((int64)TMP), true);
}
}
else {
ptFolderSize = new off_t(0);
fObjFileTree->AddNode(strParent.String(), fPath->Path(), false, ptFolderSize, true);
*ptFolderSize = _walkThroughFolder(new BString(fPath->Path()));
}
}
}
fVolumes->Rewind();
return true;
}
else
return false;
}
/* _walkThroughFolder
* method walks through selected subfolders and gets size of them
*/
off_t
FileAccess::_walkThroughFolder(BString *Path)
{
DIR *dir;// = new DIR();
struct dirent *dirzeiger = new dirent;
off_t TMP = 0;
off_t *ptFolderSize;
off_t sizeOfFolder = 0;
if((dir = opendir(Path->String())) != NULL) {
while((dirzeiger=readdir(dir)) != NULL) {
if(strcmp((*dirzeiger).d_name, ".") != 0 && strcmp((*dirzeiger).d_name, "..") != 0) {
fFileName->SetTo((*dirzeiger).d_name);
fPathAndFile->SetTo(Path->String());
*fPathAndFile += "/";
*fPathAndFile += *fFileName;
fDirectory->SetTo(fPathAndFile->String());
if(fDirectory->InitCheck() != B_OK) {
if(!getFilesFromQuery(fPathAndFile->String(), Path->String(), &sizeOfFolder)) {
fFileAcces->SetTo(fPathAndFile->String(), B_READ_ONLY);
fFileAcces->GetSize(&TMP);
_addToSizeOfFiles(TMP);
sizeOfFolder += TMP;
fStateContainer->SetTo(fFileName->String());
fObjFileTree->AddNode(Path->String(), fPathAndFile->String(), true, new off_t((int64)TMP), false);
}
}
else if(fDirectory->InitCheck() == B_OK) {
ptFolderSize = new off_t(0);
fStateContainer->SetTo(fFileName->String());
fObjFileTree->AddNode(Path->String(), fPathAndFile->String(), false, ptFolderSize, false);
*ptFolderSize = _walkThroughFolder(new BString(fPathAndFile->String()));
sizeOfFolder += *ptFolderSize;
}
}
}
}
if(dir != NULL)
closedir(dir);
delete dirzeiger, Path;
return sizeOfFolder;
}
/* walkThroughFiles
* method walks through selected files and build file tree and greps the size of
* the selected files
* and sume it to (protected)intSizeOfFiles
*/
void
FileAccess::walkThroughFiles()
{
fObjFileTree = new FileTree();
fDirectory = new BDirectory();
fFileAcces = new BFile();
fQuery = new BQuery();
fNode = new BNode();
fVolume = new BVolume();
fEntry = new BEntry();
fPath = new BPath();
fPathAndFile = new BString();
fFileName = new BString();
BString *strTMP;
off_t TMP = 0;
off_t *ptFolderSize;
for(int i = 0; i < FileList->CountItems(); i++) {
strTMP = (BString*)FileList->ItemAt(i);
fDirectory->SetTo(strTMP->String());
if(fDirectory->InitCheck() != B_OK) {
if(!getFilesFromQuery(strTMP->String(), "", NULL)) {
fFileAcces->SetTo(strTMP->String(), B_READ_ONLY);
fFileAcces->GetSize(&TMP);
_addToSizeOfFiles(TMP);
fStateContainer->SetTo(strTMP->String());
fObjFileTree->AddNode("", strTMP->String(), true, new off_t((int64)TMP), false);
}
}
else {
ptFolderSize = new off_t(0);
fStateContainer->SetTo(strTMP->String());
fObjFileTree->AddNode("", strTMP->String(), false, ptFolderSize, false);
*ptFolderSize = _walkThroughFolder(new BString(strTMP->String()));
}
}
delete fDirectory, fFileAcces, fPathAndFile, fFileName, fNode, fQuery,
fVolume, fVolumes, fEntry, fPath;
}
/* generateFileInfos
* this method generates all needed informations (size, attributes etc.)
*/
void
FileAccess::generateFileInfos()
{
if(!fIsGenerated) {
walkThroughFiles();
getTypeOfFilesByAttr();
fIsGenerated = true;
}
}
| [
"stargater@a1012e6f-0782-4aa0-a230-a3f5a3a22efe"
] | stargater@a1012e6f-0782-4aa0-a230-a3f5a3a22efe |
84756e20d67da47a23f74b4e58dc90afbc9dfa9a | 793cc114474631d0ea6a58b0b4547f54c9278ca5 | /game/opengl/huffman_decode_lengths.cpp | 3d70a5bc5ef25891762ef640ac4ea4d8b166be84 | [
"Apache-2.0"
] | permissive | cassiersg/elec-2103 | a624e1e81836bd82c6421db8e8c2917c9ae0d64a | f0152c81e8d808a1ab62c78e9324fb99b341638a | refs/heads/master | 2021-06-18T00:03:31.346578 | 2017-05-11T08:45:42 | 2017-05-11T08:45:42 | 81,305,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,873 | cpp | // DO NOT EDIT - file generated by game/gen_huffman.py
if ((code >> 0) & 0x1) {
if ((code >> 1) & 0x1) {
if ((code >> 2) & 0x1) {
if ((code >> 3) & 0x1) {
if ((code >> 4) & 0x1) {
decoded = 0x8;
code_len = 5;
} else {
if ((code >> 5) & 0x1) {
if ((code >> 6) & 0x1) {
decoded = 0xd;
code_len = 7;
} else {
decoded = 0xf;
code_len = 7;
}
} else {
decoded = 0xa;
code_len = 6;
}
}
} else {
if ((code >> 4) & 0x1) {
decoded = 0x2;
code_len = 5;
} else {
if ((code >> 5) & 0x1) {
decoded = 0xc;
code_len = 6;
} else {
decoded = 0x800;
code_len = 6;
}
}
}
} else {
decoded = 0x10;
code_len = 3;
}
} else {
if ((code >> 2) & 0x1) {
if ((code >> 3) & 0x1) {
if ((code >> 4) & 0x1) {
decoded = 0x6;
code_len = 5;
} else {
decoded = 0x5;
code_len = 5;
}
} else {
if ((code >> 4) & 0x1) {
decoded = 0x1;
code_len = 5;
} else {
if ((code >> 5) & 0x1) {
decoded = 0xb;
code_len = 6;
} else {
decoded = 0xe;
code_len = 6;
}
}
}
} else {
decoded = 0x20;
code_len = 3;
}
}
} else {
if ((code >> 1) & 0x1) {
if ((code >> 2) & 0x1) {
if ((code >> 3) & 0x1) {
decoded = 0x80;
code_len = 4;
} else {
decoded = 0x9;
code_len = 4;
}
} else {
if ((code >> 3) & 0x1) {
if ((code >> 4) & 0x1) {
decoded = 0x200;
code_len = 5;
} else {
decoded = 0x7;
code_len = 5;
}
} else {
decoded = 0x4;
code_len = 4;
}
}
} else {
if ((code >> 2) & 0x1) {
decoded = 0x40;
code_len = 3;
} else {
if ((code >> 3) & 0x1) {
decoded = 0x3;
code_len = 4;
} else {
decoded = 0x100;
code_len = 4;
}
}
}
}
| [
"gaetan.cassiers@gmail.com"
] | gaetan.cassiers@gmail.com |
d1e856646ba957084e33644febf09492c9e1e971 | d836c18f79efefecbf38e4c221d54aae2e7e79ec | /src/script/standard.h | e6186437b6d012d034f1286ade39a5982babec19 | [] | no_license | xgy1221/jdcoin | 329c410489c31a55ff95b38e7e643dd5869ed947 | ac351c1120750712679b7893446a8f517730a658 | refs/heads/main | 2023-03-11T14:57:09.740625 | 2021-03-02T18:45:38 | 2021-03-02T18:45:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,922 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2017-2020 The JDCOIN developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_SCRIPT_STANDARD_H
#define BITCOIN_SCRIPT_STANDARD_H
#include "script/interpreter.h"
#include "uint256.h"
#include <boost/variant.hpp>
#include <stdint.h>
class CKeyID;
class CScript;
/** A reference to a CScript: the Hash160 of its serialization (see script.h) */
class CScriptID : public uint160
{
public:
CScriptID() : uint160() {}
CScriptID(const CScript& in);
CScriptID(const uint160& in) : uint160(in) {}
};
static const unsigned int MAX_OP_RETURN_RELAY = 83; //!< bytes (+1 for OP_RETURN, +2 for the pushdata opcodes)
extern unsigned nMaxDatacarrierBytes;
/**
* Mandatory script verification flags that all new blocks must comply with for
* them to be valid. (but old blocks may not comply with) Currently just P2SH,
* but in the future other flags may be added, such as a soft-fork to enforce
* strict DER encoding.
*
* Failing one of these tests may trigger a DoS ban - see CheckInputs() for
* details.
*/
static const unsigned int MANDATORY_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH;
/**
* Standard script verification flags that standard transactions will comply
* with. However scripts violating these flags may still be present in valid
* blocks and we must accept those blocks.
*/
static const unsigned int STANDARD_SCRIPT_VERIFY_FLAGS = MANDATORY_SCRIPT_VERIFY_FLAGS |
SCRIPT_VERIFY_DERSIG |
SCRIPT_VERIFY_STRICTENC |
SCRIPT_VERIFY_MINIMALDATA |
SCRIPT_VERIFY_NULLDUMMY |
SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS;
/** For convenience, standard but not mandatory verify flags. */
static const unsigned int STANDARD_NOT_MANDATORY_VERIFY_FLAGS = STANDARD_SCRIPT_VERIFY_FLAGS & ~MANDATORY_SCRIPT_VERIFY_FLAGS;
enum txnouttype
{
TX_NONSTANDARD,
// 'standard' transaction types:
TX_PUBKEY,
TX_PUBKEYHASH,
TX_SCRIPTHASH,
TX_MULTISIG,
TX_NULL_DATA,
TX_ZEROCOINMINT,
TX_COLDSTAKE
};
class CNoDestination {
public:
friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; }
friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
};
/**
* A txout script template with a specific destination. It is either:
* * CNoDestination: no destination set
* * CKeyID: TX_PUBKEYHASH destination
* * CScriptID: TX_SCRIPTHASH destination
* A CTxDestination is the internal data type encoded in a CBitcoinAddress
*/
typedef boost::variant<CNoDestination, CKeyID, CScriptID> CTxDestination;
const char* GetTxnOutputType(txnouttype t);
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType);
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet, bool fColdStake = false);
bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
CScript GetScriptForDestination(const CTxDestination& dest);
CScript GetScriptForRawPubKey(const CPubKey& pubKey);
CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys);
CScript GetScriptForStakeDelegation(const CKeyID& stakingKey, const CKeyID& spendingKey);
#endif // BITCOIN_SCRIPT_STANDARD_H
| [
"developer@jdcoin.us"
] | developer@jdcoin.us |
486d8da0c5d1e69ce399c9caa4a98acbe395711e | af252466836eb55c17fe450635cf9acb28e8de88 | /Test2/main.cpp | ca0e07976c37070f34932a37b2d0f519c78a08ca | [] | no_license | sarsilmazgulsahh/github-xcode-cattletracking | 5146d48cb864bc2c5a509162d438f0905b36ba8d | f8e677d2fe8874dcd98344009963917729be3097 | refs/heads/master | 2020-04-03T09:57:18.757050 | 2016-09-29T15:33:06 | 2016-09-29T15:33:06 | 69,580,929 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,631 | cpp | #include <iostream>
#include <string>
#include <vector>
using namespace std;
class MilkCattle;
class BeefCattle;
class Carbohydrate;
class Protein;
class Carbohydrate {
public:
virtual void Print()=0;
};
// A 'ConcreteProduct A1' class
class Wheat : public Carbohydrate{
public:
Wheat() {
cout << "Carbohydrate is chosen as Wheat " << endl;
}
void Print() {cout<<"I am a Carbohydrate";}
};
// A 'ConcreteProduct A2' class
class Corn : public Carbohydrate{
public:
Corn() {
cout << "Carbohydrate is chosen as Corn " << endl;
}
void Print() {
cout << "I am a Carbohydrate" << endl;
}
};
// An 'Abstract Product B' class
class Protein {
public:
virtual void Print2() = 0;
};
// A 'ConcreteProduct B1' class
class Canola : public Protein{
public:
Canola() {
cout << "Protein is chosen as Canola" << endl;
}
void Print2() {
cout << "I am a protein " << endl;
}
};
// A 'ConcreteProduct B2' class
class Soybean : public Protein{
public:
Soybean(){
cout << "Soybean is chosen as Protein." << endl;
}
void Print2() {
cout << "I am a protein." << endl;
}
};
class Visitor {
public:
bool autumn = true;
virtual ~Visitor(){};
virtual void Visit() = 0;
protected:
Visitor(){};
};
class VetPhysician : public Visitor {
public:
string _name;
VetPhysician(string name){_name=name;}
void Visit(){
cout<<"Cattles Visited and Vaccined"<<endl;
};
};
class MinistryofFAL : public Visitor {
public:
string _name;
MinistryofFAL(string name){_name=name;}
void Visit(){
cout<<"Cattles Visited and Tags checked"<<endl;
};
};
class Farmer;
class Cattle
{
public:
static Cattle* getInstance();
static bool exists();
virtual int getLocation(){ return 0; };
virtual void setLocation(int _in){};
virtual void Attach (Farmer* farmer);
virtual void Notify();
virtual void Accept() = 0;
static Carbohydrate* createCarbohydrate() ;
static Protein* CreateProtein();
protected:
Cattle(int);
virtual ~Cattle(){};
static Cattle* Instance;
vector<Farmer*> farmers;
private:
int location_val;
};
Cattle* Cattle::Instance = 0;
Cattle::Cattle(int _location): location_val(_location){}
void Cattle::Attach(Farmer* farmer) {
farmers.push_back(farmer);
}
void Cattle::Notify() {
cout<<"Notified"<<endl;
}
bool Cattle::exists(){
return (Instance != NULL);
}
Cattle* Cattle::getInstance()
{
if(Instance == 0) std::cout << "Class has not been created" << std::endl;
return Instance;
}
class MilkCattle : public Cattle
{
public:
static void create(int);
void setLocation(int _in){ location = _in; Notify();}
int getLocation(){ return location;}
void Accept(){cout<<"Accepted"<<endl; }
Carbohydrate* createCarbohydrate () {
return new Corn();
}
Protein* createProtein() {
return new Soybean();
}
protected:
MilkCattle(int);
virtual ~MilkCattle() {};
private:
int location;
};
MilkCattle::MilkCattle(int _location): Cattle(_location){
location =_location;
}
void MilkCattle::create(int cattle_location){
if(Instance)
cout << "Recreation" << endl;
else
Instance = new MilkCattle(cattle_location);
}
class Farmers {
public:
virtual ~Farmers(){};
virtual void Update() = 0;
};
class Farmer:public Farmers {
private:
string farmer_name;
public:
Farmer(string n):farmer_name(n){};
void Update(){
cout<<"There is an update in function"<<endl;
}
};
class BeefCattle : public Cattle {
public:
static void create(int);
void setLocation(int _in){ location = _in; Notify();}
int getLocation(){ return location;}
void Accept(){cout<<"Accepted"<<endl;}
Carbohydrate* createCarbohydrate () {
return new Wheat();
}
Protein* createProtein() {
return new Canola();
}
protected:
BeefCattle(int);
virtual ~BeefCattle() {};
private:
int location;
};
BeefCattle::BeefCattle(int _location): Cattle(_location){
location =_location;
}
void BeefCattle::create(int cattle_location)
{
if(Instance)
cout << "Recreation of object" << endl;
else
Instance = new BeefCattle(cattle_location);
}
class ZigbeeSignals {
public:
virtual void usingZigbeSignals()= 0;
};
class BluetoothSignals {
public:
void Bluetoothconverter() {
string device = "Bluetooth";
cout << "Converting Zigbee to Bluetooth"<<endl;
cout <<"The new device is : "<< device<< endl;
}
};
class ConnectorAdapter : public ZigbeeSignals, private BluetoothSignals{
public:
void usingZigbeSignals() {
Bluetoothconverter();
}
};
int main()
{
Farmer *farmer = new Farmer("Tulin");
farmer->Update();
MilkCattle::create(3);
cout << MilkCattle::getInstance()->getLocation() << endl;
MilkCattle::getInstance()->setLocation(5);
cout << MilkCattle::getInstance()->getLocation() << endl;
farmer->Update();
cout << BeefCattle::getInstance()->getLocation() << endl;
BeefCattle::getInstance()->setLocation(8);
cout << BeefCattle::getInstance()->getLocation() << endl;
VetPhysician *vet = new VetPhysician("George");
vet->Visit();
MinistryofFAL *mstry = new MinistryofFAL("John");
mstry->Visit();
ZigbeeSignals *signals = new ConnectorAdapter();
signals->usingZigbeSignals();
return 0;
}
| [
"gulsah.sarsilmaz@takipsan.com"
] | gulsah.sarsilmaz@takipsan.com |
38b22d970b458636bed9d2185623725bded80bd2 | 565f9938fcef5d8e277bbc448d22f60e05ef69a9 | /Object-Oriented-Programming with C++ 1(OOP244)/Labs/WS01/in_lab/tools.h | b045d0a452aabd9a8b933a26eb6fbd2a8bc7e719 | [] | no_license | Sandro927/School-Work | 9165a68e11f99960c99864d48e3640cfb611e8b7 | 7c50585fec1691f7ac0d18ea21087514216d590f | refs/heads/main | 2023-02-16T07:38:11.295116 | 2021-01-13T21:20:43 | 2021-01-13T21:20:43 | 329,430,279 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 183 | h | #pragma once
#ifndef NAMESPACE_HEADERFILENAMETOOL_H
#define NAMESPACE_HEADERFILENAMETOOL_H
namespace sict
{
int menu(void);
int getInt(int minimum, int maximum);
}
#endif | [
"47231162+Sandro927@users.noreply.github.com"
] | 47231162+Sandro927@users.noreply.github.com |
ee0447bb91c6e9d04168a550281bec322284d7bc | 25c6386f2896ae3189558b0b71598323bc876adb | /CodeForces/CF555/C2/code.cpp | fb6fceb5dff82eeb471edaac037a46c3071c7ab5 | [] | no_license | schiebermc/CP_Lib | 134dedc90b0806db46ee116ea0640fd831da5245 | 109dc2aed47b79acd253bc48dd3645ca9237f0aa | refs/heads/master | 2021-06-28T14:42:35.589021 | 2019-04-27T20:31:13 | 2019-04-27T20:31:13 | 140,892,706 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,398 | cpp | //#include <bits/stdc++.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <climits>
#include <bitset>
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
using namespace std;
typedef long long int ll;
pair<bool, int> best_from_here(vector<int>& a, int ind1, int ind2) {
int countl = 0, countr = 0;
int ind = ind1;
int prev = a[ind];
while(ind < ind2) {
ind++;
int num = a[ind];
if(num <= prev)
break;
prev = num;
countl++;
}
ind = ind2;
prev = a[ind2];
while(ind1 < ind) {
ind--;
int num = a[ind];
if(num <= prev)
break;
prev = num;
countr++;
}
// printf("c1: %d, c2: %d\n", countl, countr);
if(countl > countr) {
return {true, countl};
} else {
return {false, countr};
}
}
int main() {
IOS;
int n;
cin >> n;
vector<int> a; a.resize(n);
for(ll i=0; i<n; i++) {
cin >> a[i];
}
int ind1 = 0;
int ind2 = n-1;
int prev = 0;
vector<char> ans;
while(ans.size() < n) {
int num1 = a[ind1];
int num2 = a[ind2];
if(num1 <= prev and num2 <= prev)
break;
bool push_left = false;
bool push_right = false;
if(num1 == num2) {
auto p = best_from_here(a, ind1, ind2);
bool side = p.first;
int amount = p.second;
char c = (side ? 'L' : 'R');
for(int i=0; i<amount+1; i++)
ans.push_back(c);
break;
} else if(num1 < num2) {
if(num1 > prev)
push_left = true;
else
push_right = true;
} else {
if(num2 > prev)
push_right = true;
else
push_left = true;
}
if(push_left) {
ans.push_back('L');
prev = num1;
ind1++;
} else if(push_right) {
ans.push_back('R');
prev = num2;
ind2--;
} else {
exit(1);
}
}
cout << ans.size() << endl;
for(auto x : ans)
cout << x;
cout << endl;
return 0;
}
| [
"matthewschieber@gmail.com"
] | matthewschieber@gmail.com |
0b079197282ad95099f86869c54ffca70c814311 | 825dbfde537faf753581a2ab86d8f536c1125737 | /src/infra/String.cpp | d2d411995d99aa0626bce5451f47bff65cd924b0 | [
"Zlib"
] | permissive | oceancx/mud | e59a739f69fbb48fc9c7e53f4412ee2c9aabc913 | a7ca88d062bf2679e2977b03dc63d6e315912e14 | refs/heads/master | 2020-03-30T05:42:00.403384 | 2018-09-23T23:06:31 | 2018-09-23T23:06:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,003 | cpp | // Copyright (c) 2018 Hugo Amiard hugo.amiard@laposte.net
// This software is provided 'as-is' under the zlib License, see the LICENSE.txt file.
// This notice and the license may not be removed or altered from any source distribution.
#include <infra/Cpp20.h>
#ifndef MUD_CPP_20
#include <algorithm>
#endif
#ifdef MUD_MODULES
module mud.infra;
#else
#include <infra/Config.h>
#include <infra/String.h>
#include <infra/StringConvert.h>
#include <infra/Strung.h>
#include <infra/NonCopy.h>
#endif
namespace mud
{
template MUD_INFRA_EXPORT void from_string(const string& str, float& val);
template MUD_INFRA_EXPORT void to_string(const float& val, string& str);
const size_t g_num_precision = 3;
void split_string(const string& str, const string& separator, array<string> output)
{
size_t start = 0;
size_t next = str.find(separator, start);
size_t index = 0;
while(next != string::npos && index < output.size())
{
output[index++].assign(str.data() + start, next - start);
start = next + 1;
next = str.find(separator, start);
}
if(index < output.size())
output[index++].assign(str.data() + start, str.size() - start);
}
std::vector<string> split_string(const string& str, const string& separator)
{
std::vector<string> result;
if(str.size() == 0)
return result;
size_t cur_pos = 0;
size_t last_pos = 0;
while (cur_pos != string::npos)
{
cur_pos = str.find(separator, last_pos);
result.push_back(str.substr(last_pos, cur_pos - last_pos));
last_pos = cur_pos + separator.size();
}
return result;
}
string replace_all(const string& original, const string& before, const string& after)
{
string retval;
string::const_iterator end = original.end();
string::const_iterator current = original.begin();
string::const_iterator next = std::search(current, end, before.begin(), before.end());
while(next != end)
{
retval.append(current, next);
retval.append(after);
current = next + before.size();
next = std::search(current, end, before.begin(), before.end());
}
retval.append(current, next);
return retval;
}
string to_lower(const string& original)
{
string result = original;
std::transform(result.begin(), result.end(), result.begin(), ::tolower);
return result;
}
string to_upper(const string& original)
{
string result = original;
std::transform(result.begin(), result.end(), result.begin(), ::toupper);
return result;
}
string to_pascalcase(const string& name)
{
string result = name;
result[0] = char(::toupper(name[0]));
for (size_t pos = result.find('_'); pos != string::npos; pos = result.find('_', pos))
{
result.erase(pos, 1);
result[pos] = char(::toupper(result[pos]));
}
return result;
}
string to_camelcase(const string& name)
{
string result = name;
for(size_t pos = result.find('_'); pos != string::npos; pos = result.find('_', pos))
{
result.erase(pos, 1);
result[pos] = char(::toupper(result[pos]));
}
return result;
}
}
| [
"hugo.amiard@laposte.net"
] | hugo.amiard@laposte.net |
55662dbb897162f52ed2ad7e2d585230d93354ec | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-support/source/model/DescribeAttachmentRequest.cpp | 95a871833551cafe76379a682f5b4d77f054afb9 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 944 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/support/model/DescribeAttachmentRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Support::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DescribeAttachmentRequest::DescribeAttachmentRequest() :
m_attachmentIdHasBeenSet(false)
{
}
Aws::String DescribeAttachmentRequest::SerializePayload() const
{
JsonValue payload;
if(m_attachmentIdHasBeenSet)
{
payload.WithString("attachmentId", m_attachmentId);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection DescribeAttachmentRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSSupport_20130415.DescribeAttachment"));
return headers;
}
| [
"sdavtaker@users.noreply.github.com"
] | sdavtaker@users.noreply.github.com |
e865c0cee4f2cd007ba383e96067f1b1cf98a035 | e9fc7dee267d49f361421090f4d933cae93bc3fc | /src/obj_tools/Matrix/Matrix3x3.hpp | 9627feb0f31548c42801c3398f989c0c16e19283 | [] | no_license | alexgerasimov58rus/Physics_For_Game | 3a1f5125a6c38ed44f6c5a7210cf0f3ac90568c8 | 45a78f7b6355f73b83cdb0a05073eca955c75432 | refs/heads/master | 2023-05-06T01:25:47.035458 | 2021-05-21T15:59:53 | 2021-05-21T15:59:53 | 342,588,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,261 | hpp | #pragma once
#include "../tools_exp.hpp"
namespace obj_tools {
struct OBJ_TOOLS_EXPORT Matrix3x3
{
friend OBJ_TOOLS_EXPORT Matrix3x3 operator * (const float& s, const Matrix3x3& m);
static Matrix3x3 createScaleMatrix(const float& dx, const float& dy, const float& dz);
static Matrix3x3 createRotateXMatrix(const double& rad);
static Matrix3x3 createRotateYMatrix(const double& rad);
static Matrix3x3 createRotateZMatrix(const double& rad);
Matrix3x3(void);
Matrix3x3(const Matrix3x3& m);
Matrix3x3& operator =(const Matrix3x3& m);
float getElement(const int& row, const int& col) const;
void setElement(const int& row, const int& col, const float& value);
Matrix3x3 operator + (const Matrix3x3& m) const;
Matrix3x3 operator - (const Matrix3x3& m) const;
Matrix3x3 operator * (const float& s) const;
Matrix3x3& operator += (const Matrix3x3& m);
Matrix3x3& operator -= (const Matrix3x3& m);
Matrix3x3 operator *= (const float& s);
Matrix3x3 operator * (const Matrix3x3& m) const;
bool operator == (const Matrix3x3& m) const;
Matrix3x3 transposition(void) const;
Matrix3x3 inverse(void) const;
float determinant(void) const;
private: //__________________
float elements_[3][3];
};
}; | [
"vintegewhitecool@yandex.ru"
] | vintegewhitecool@yandex.ru |
9f951224dbb3004f368bf871d8db5f8447b3df3c | de01cb554c2292b0fbb79b4d5413a2f6414ea472 | /algorithms/Easy/507.perfect-number.cpp | 6c6855ace585e444e89c4cb0f891a4b7a4dc3924 | [] | no_license | h4hany/yeet-the-leet | 98292017eadd3dde98a079aafcd7648aa98701b4 | 563d779467ef5a7cc85cbe954eeaf3c1f5463313 | refs/heads/master | 2022-12-10T08:35:39.830260 | 2020-09-02T23:12:15 | 2020-09-02T23:12:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 763 | cpp | /*
* @lc app=leetcode id=507 lang=cpp
*
* [507] Perfect Number
*
* https://leetcode.com/problems/perfect-number/description/
*
* algorithms
* Easy (35.50%)
* Total Accepted: 65.8K
* Total Submissions: 185.5K
* Testcase Example: '28'
*
* We define the Perfect Number is a positive integer that is equal to the sum
* of all its positive divisors except itself.
*
* Now, given an integer n, write a function that returns true when it is a
* perfect number and false when it is not.
*
*
* Example:
*
* Input: 28
* Output: True
* Explanation: 28 = 1 + 2 + 4 + 7 + 14
*
*
*
* Note:
* The input number n will not exceed 100,000,000. (1e8)
*
*/
class Solution {
public:
bool checkPerfectNumber(int num) {
}
};
| [
"kevin.wkmiao@gmail.com"
] | kevin.wkmiao@gmail.com |
6ac93bd939c38f3e2cfc5bbac76d8ffb8002ff61 | 097007b435b1bf420a19ce33aabee32f0789f145 | /codeforces/640_div4/51.cpp | 0a6ae2328b3c7f3dd73b49d817c9e6bf494b6d21 | [] | no_license | Anshit01/Competitive-Programming | 71f84a85dde49278f8c3318d00db70616d8ea470 | 13911ec7f622abc061fea1ccc1f35d34118641f7 | refs/heads/master | 2023-06-11T12:06:11.722865 | 2021-06-30T11:51:01 | 2021-06-30T11:51:01 | 266,321,296 | 5 | 2 | null | 2020-10-19T09:47:06 | 2020-05-23T11:21:40 | C++ | UTF-8 | C++ | false | false | 1,073 | cpp | #include <bits/stdc++.h>
#define ll long long
#define f(i, x, n) for(int i = x; i < n; i++)
#define dbg(x) cout << x << endl
#define dbg2(x, y) cout << x << " " << y << endl
#define dbg3(x, y, z) cout << x << " " << y << " " << z << endl
#define mod 1000000007
using namespace std;
int main(){
ios::sync_with_stdio(0);
cin.tie(NULL);
int t, n;
cin >> t;
while(t--){
cin >> n;
vector<int> arr(n);
vector<int> count(n+1, 0);
vector<bool> sums(n+1, false);
f(i, 0, n){
cin >> arr[i];
count[arr[i]]++;
}
int sum = 0;
f(i, 0, n-1){
sum = arr[i];
int j = i+1;
while(j < n){
sum += arr[j];
j++;
if(sum > n){
break;
}
sums[sum] = true;
}
}
int c = 0;
f(i, 1, n+1){
if(count[i] != 0 && sums[i]){
c += count[i];
}
}
cout << c << endl;
}
} | [
"bhardwaj.anshit1379@gmail.com"
] | bhardwaj.anshit1379@gmail.com |
7e56f65ea23480a6da126a4869963bb8e7f013dc | c1c7a5978c550cf796b052485f01b2c392ab2790 | /Network/Netbroker/inc/IDispatcher.h | 6ab15495343693a053b7ee40d1b73223bbaa3b04 | [] | no_license | strangedays1979/Netbroker | 15b1c69f761649c5a158fa735eb5e30b780946f3 | 77b385f94c1852e657ee807c9d0180dbe80e9a12 | refs/heads/master | 2020-03-16T19:49:14.270173 | 2018-05-14T20:56:49 | 2018-05-14T20:56:49 | 132,929,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,575 | h |
#pragma once
#include "connector.h"
#include <windows.h>
#include <string>
class DispatcherException;
class Buffer;
class EXPORT_NETBROKER IDispatcher
{
public:
virtual ~IDispatcher() { }
virtual bool connect() throw( DispatcherException ) = 0;
virtual void registerGroup(
const std::string& _groupName
, const long& _bufferSize
, const unsigned long& _qsize
, const bool sendOnly = false )
throw( DispatcherException ) = 0;
virtual void unregisterGroup( const std::string& _groupName )
throw( DispatcherException ) = 0;
virtual int sendMessageToGroupManaged( const Buffer* __pBuf ) = 0;
virtual Buffer* makeMessageManaged(
const std::string& _groupName
, const unsigned long& _size
, const char* const _data
, const short& _opCode
, const std::string _callerFuncName = "" )
throw( DispatcherException ) = 0;
virtual bool receiveMessageFromGroup( const std::string& _groupName
, Buffer& _buf
, bool _isLocking = false ) throw ( DispatcherException ) = 0;
virtual void start() throw ( DispatcherException ) = 0;
virtual bool stop() throw( DispatcherException) = 0;
virtual bool isOnline() = 0;
virtual void disconnect() throw ( DispatcherException ) = 0;
virtual bool findGroup( const std::string _group ) = 0;
};
EXPORT_NETBROKER IDispatcher* WINAPI GetDispatcher
(
const std::string& _client_name
, const std::string& _address
, const Connector::ConnectorType _connType
, const Connector::LogLevel _log
, const bool _displayLog
, const bool _dropEchoMessage
, const bool _dropMembershipMessages
); | [
"39166470+strangedays1979@users.noreply.github.com"
] | 39166470+strangedays1979@users.noreply.github.com |
0b624aa4e82b788d586f838d0e8d7615ff321fa1 | 96b728a53d54c5a08a2a3cf5cf9aa6ab331f89c6 | /CRServer/tasks/CRTaskClientAccept.h | 32385c8a8373cb18440849498afb0ab5dcd51eee | [] | no_license | rwang82/HMNWC | b42a782a96916afb53a8ec4f86fc4202c84ca338 | 20738378cbbb3706ebaa005f94e7b8633031ed09 | refs/heads/master | 2021-01-16T19:31:06.817775 | 2015-03-30T08:32:56 | 2015-03-30T08:32:56 | 27,456,968 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 374 | h | #ifndef __CRTASKCMDCLIENTACCEPT_H__
#define __CRTASKCMDCLIENTACCEPT_H__
#include "HMTaskEngine.h"
class CRTaskClientAccept : public HMTaskBase {
public:
CRTaskClientAccept( SOCKET sConnect, const sockaddr_in* pAddr );
virtual ~CRTaskClientAccept();
public:
virtual void Run();
private:
SOCKET m_sConnect;
sockaddr_in m_sAddr;
};
#endif //__CRTASKCMDCLIENTACCEPT_H__ | [
"rwang82@gmail.com"
] | rwang82@gmail.com |
cd818f40fab2232ea2446a2e030d574d225af30a | f1d83b8d14fd937d1db9c04ccdc3b6688d65bd70 | /main.cpp | 1edeb3963975711c269ec5435f9de872bb041395 | [] | no_license | arasharchor/SDA-2 | 8ac39ff1de0e47079a1b968358aa54a1b0ef71db | e6250b0c101436d2717443360d61463e193bb278 | refs/heads/master | 2021-05-31T11:25:29.976794 | 2016-06-17T07:47:14 | 2016-06-17T07:47:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,764 | cpp | /*
* SdA.cpp (Stacked Denoising Autoencoders)
*
* @author yusugomori (http://yusugomori.com)
* @usage $ g++ SdA.cpp
*
*/
#include "autoencoder_utility.h"
//#include "SdA.h"
#include "SdA.cpp"
#include <iostream>
#include <math.h>
using namespace std;
void test_sda() {
srand(0);
double pretrain_lr = 0.1;
double corruption_level = 0.3;
int pretraining_epochs = 1000;
double finetune_lr = 0.1;
int finetune_epochs = 500;
int train_N = 10;
int test_N = 4;
int n_ins = 28;
int n_outs = 2;
int hidden_layer_sizes[] = { 15, 15 };
int n_layers = sizeof(hidden_layer_sizes) / sizeof(hidden_layer_sizes[0]);
// training data
int train_X[10][28] = {
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 }
};
int train_Y[10][2] = {
{ 1, 0 },
{ 1, 0 },
{ 1, 0 },
{ 1, 0 },
{ 1, 0 },
{ 0, 1 },
{ 0, 1 },
{ 0, 1 },
{ 0, 1 },
{ 0, 1 }
};
#if 1
for (int i = 0; i < 10; i++){
for (int j = 0; j < 28; j++){
train_X[i][j] *= 255;
}
}
#endif
// construct SdA
SdA<int> sda(train_N, n_ins, hidden_layer_sizes, n_outs, n_layers);
// pretrain
sda.pretrain(*train_X, pretrain_lr, corruption_level, pretraining_epochs);
// finetune
sda.finetune(*train_X, *train_Y, finetune_lr, finetune_epochs);
// test data
int test_X[4][28] = {
{ 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 }
};
#if 1
for (int i = 0; i < 10; i++){
for (int j = 0; j < 28; j++){
test_X[i][j] *= 255;
}
}
#endif
double test_Y[4][28];
// test
for (int i = 0; i < test_N; i++) {
sda.predict(test_X[i], test_Y[i]);
for (int j = 0; j < n_outs; j++) {
printf("%.5f ", test_Y[i][j]);
}
cout << endl;
}
}
void test_sda_mnist()
{
//loading data
//read train and label data
Mat trainX, trainY;
readMnistData(trainX, trainY, "../mnist/train-images-idx3-ubyte", "../mnist/train-labels-idx1-ubyte", 60000);
cout << "Read trainX successfully, including " << trainX.cols << " features and " << trainX.rows << " samples." << endl;
cout << "Read trainY successfully, including " << trainY.cols << " labels and " << trainY.rows << " samples." << endl;
// pre-processing data.
//Scalar mean, stddev;
//meanStdDev(trainX, mean, stddev);
//Mat normX = trainX - mean[0];
//normX.copyTo(trainX);
Mat testX, testY;
readMnistData(testX, testY, "../mnist/t10k-images-idx3-ubyte", "../mnist/t10k-labels-idx1-ubyte", 10000);
cout << "Read testX successfully, including " << testX.cols << " features and " << testX.rows << " samples." << endl;
cout << "Read testY successfully, including " << testY.cols << " labels and " << testY.rows << " samples." << endl;
Mat trainXInt, trainYInt;
trainX.convertTo(trainXInt, CV_32FC1);
trainY.convertTo(trainYInt, CV_32SC1);
Mat testXInt, testYInt;
testX.convertTo(testXInt, CV_32FC1);
testY.convertTo(testYInt, CV_32SC1);
//for (int i = 0; i < trainX.cols; i++){
// cout << trainXInt.at<int>(0, i) << ", ";
// if ((i + 1) % 16 == 0)cout << endl;
//}
//cout << endl;
//for (int i = 0; i < trainY.cols; i++){
// cout << trainYInt.at<int>(0, i) << ", ";
//}
//return;
float *train_X = (float*)trainXInt.data;
int *train_Y = (int*)trainYInt.data;
//
srand(0);
double pretrain_lr = 0.1;
double corruption_level = 0.3;
int pretraining_epochs = 1000;
double finetune_lr = 0.1;
int finetune_epochs = 1000;
int train_N = trainX.rows;
int test_N = testY.rows;
int n_ins = trainX.cols;
int n_outs = 10;
int hidden_layer_sizes[] = { 100, 50 };
int n_layers = sizeof(hidden_layer_sizes) / sizeof(hidden_layer_sizes[0]);
// construct SdA
SdA<float> sda(train_N, n_ins, hidden_layer_sizes, n_outs, n_layers);
// pretrain
cout << "pretrainning... \n";
sda.pretrain(train_X, pretrain_lr, corruption_level, pretraining_epochs);
// finetune
cout << "finetuning... \n";
sda.finetune(train_X, train_Y, finetune_lr, finetune_epochs);
// test
double *predict_y = new double[n_outs];
int correct_cnt = 0;
for (int i = 0; i < test_N; i++) {
float *test_X = ((float*)testXInt.data) + i * testXInt.cols;
sda.predict(test_X, predict_y);
int max_j = 0;
double max_val = 0;
for (int j = 0; j < n_outs; j++) {
if (predict_y[j] > max_val){
max_val = predict_y[j];
max_j = j;
}
//if (i < 10)printf("%.5f ", predict_y[j]);
}
int gt_j = 0;
for (int j = 0; j < n_outs; j++) {
if (testYInt.at<int>(i, j) == 1)gt_j = j;
//if (i < 10)printf("%d ", testYInt.at<int>(i, j));
}
if (gt_j == max_j)correct_cnt++;
}
cout << "\nprecision: " << 100.0 * correct_cnt / test_N << endl;
delete[]predict_y;
}
int main() {
//test_sda();
test_sda_mnist();
return 0;
}
| [
"shengxingdong@163.com"
] | shengxingdong@163.com |
044206dc913f2c9da34d2cfecfc5e438ff0a5ff3 | 6f4cf4048df7d113bcbd6e4eda8ab9cd6a754b04 | /others/__builtin_popcount.cpp | 5d6d16abaacf3b98a9384bd5507ed4ca7b326e77 | [] | no_license | Olvi73/FK-Solutions | 553efc0604a34a6dbaeb3657a2037674c992ca85 | 0bb8f070eec9c49b782c9fbabd1ab3453c784b41 | refs/heads/main | 2023-06-25T00:57:40.955208 | 2021-07-27T12:05:50 | 2021-07-27T12:05:50 | 315,937,089 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 593 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
vector<string> words = {"aaaa","asas","able","ability","actt","actor","access"};
unordered_map<int,int> frequency;
for(auto word:words)
{
int mask=0;
for(char ch:word)
{
mask|=(1<<(ch-'a'));
cout<<"ch:"<<ch<<" mask:"<<mask<<endl;
}
if(__builtin_popcount(mask)<=7)
++frequency[mask];
}
for(auto i=frequency.begin();i!=frequency.end();i++)
{
cout<<"first:"<<i->first<<endl;
cout<<"second:"<<i->second<<endl;
}
}
| [
"1668066875@qq.com"
] | 1668066875@qq.com |
f7a989853284ee87421185cc4cf6b80314f092c3 | 3bd8b14ea44a468ec5194dfd718bfc2b2fbb73c1 | /Engine2D/headers/Mesh.h | 2b90e2762cf65b479b543c0f75c10f9ab86abb64 | [] | no_license | narc0tiq/Unnamed-Train-Game | 305086d740e99ccb4730bd4b8aa4d8905f325982 | 5c905b6c30cd61b5a5602cf2af91a00ac1734a9b | refs/heads/master | 2021-01-01T18:34:53.580116 | 2011-10-18T10:24:06 | 2011-10-18T10:24:06 | 1,309,699 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,544 | h | #ifndef _MESH_H
#define _MESH_H
#include "Engine2D.h"
#include "Entity.h"
//***mod--floats to doubles
namespace Engine2D {
class Mesh : public Entity
{
private:
LPD3DXMESH mesh;
D3DMATERIAL9* materials;
LPD3DXMATERIAL d3dxMaterials;
LPD3DXBUFFER matbuffer;
DWORD material_count;
LPDIRECT3DTEXTURE9* textures;
D3DXVECTOR3 position;
D3DXVECTOR3 velocity;
D3DXVECTOR3 rotation;
D3DXVECTOR3 scale;
D3DXMATRIX matWorld;
D3DXMATRIX matTranslate;
D3DXMATRIX matRotate;
D3DXMATRIX matScale;
public:
Mesh(void);
~Mesh(void);
void move();
void animate() { }
void draw();
int GetFaceCount();
int GetVertexCount();
bool Load(char *filename);
void CreateSphere(double radius = 0.1f, int slices = 10, int stacks = 10);
void CreateCube(double width = 1.0f, double height = 1.0f, double depth = 1.0f);
void Draw();
void Transform();
void Rotate(D3DXVECTOR3 rot);
void Rotate(double x,double y,double z);
void Update();
void LimitBoundary(double left,double right,double top,double bottom,double back,double front);
void SetPosition(D3DXVECTOR3 pos) { position = pos; }
void SetPosition(double x,double y,double z)
{
position = D3DXVECTOR3((float)x,(float)y,(float)z);
}
D3DXVECTOR3 GetPosition() { return position; }
void SetVelocity(D3DXVECTOR3 vel) { velocity = vel; }
void SetVelocity(double x,double y,double z)
{
velocity = D3DXVECTOR3((float)x,(float)y,(float)z);
}
D3DXVECTOR3 GetVelocity() { return velocity; }
void SetRotation(D3DXVECTOR3 rot) { rotation = rot; }
void SetRotation(double x,double y,double z)
{
rotation = D3DXVECTOR3((float)x,(float)y,(float)z);
}
void SetRotationX(double x) { rotation.x = (float)x; }
double GetRotationX() { return rotation.x; }
void SetRotationY(double y) { rotation.y = (float)y; }
double GetRotationY() { return rotation.y; }
void SetRotationZ(double z) { rotation.z = (float)z; }
double GetRotationZ() { return rotation.z; }
void SetScale(D3DXVECTOR3 value) { scale = value; }
void SetScale(double x,double y,double z)
{
scale = D3DXVECTOR3((float)x,(float)y,(float)z);
}
D3DXVECTOR3 GetScale() { return scale; }
void SetScaleX(double x) { scale.x = (float)x; }
double GetScaleX() { return scale.x; }
void SetScaleY(double y) { scale.y = (float)y; }
double GetScaleY() { return scale.y; }
void SetScaleZ(double z) { scale.z = (float)z; }
double GetScaleZ() { return scale.z; }
};
};
#endif | [
"eztarget.uk@gmail.com"
] | eztarget.uk@gmail.com |
79ba2b03bf2776d2b41abf2e296dc516b68b0a21 | f3d3796a62d5f2c222bd88054ea1ec0c6ebea454 | /src/license_generator/license.cpp | 3a66bded634bc4ce6376cc3b65fcf8718ab094aa | [
"LicenseRef-scancode-proprietary-license",
"BSD-3-Clause"
] | permissive | open-license-manager/lcc-license-generator | 57ae2c42c13e8f8376d396867ef777cbedf7d6c6 | 816fc5787786541a9074b2a5c3f665d54fac28b0 | refs/heads/develop | 2022-08-27T11:11:11.602507 | 2021-05-27T00:38:34 | 2021-05-27T00:38:34 | 217,804,988 | 39 | 37 | BSD-3-Clause | 2022-08-22T14:35:11 | 2019-10-27T04:30:51 | C++ | UTF-8 | C++ | false | false | 6,646 | cpp | /*
* License.cpp
*
* Created on: Nov 10, 2019
* Author: GC
*/
#define SI_SUPPORT_IOSTREAMS
#include <sstream>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <unordered_set>
#include <stdexcept>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include "../ini/SimpleIni.h"
#include "../base_lib/crypto_helper.hpp"
#include "../base_lib/base.h"
#include "license.hpp"
namespace license {
using namespace std;
namespace fs = boost::filesystem;
static const unordered_set<string> NO_OUTPUT_PARAM = {
PARAM_BASE64, PARAM_LICENSE_OUTPUT, PARAM_FEATURE_NAMES,
PARAM_PROJECT_FOLDER, PARAM_PRIMARY_KEY, PARAM_MAGIC_NUMBER,
};
const std::string formats[] = {"%4u-%2u-%2u", "%4u/%2u/%2u", "%4u%2u%2u"};
const size_t formats_n = 3;
static const string normalize_date(const std::string &sDate) {
if (sDate.size() < 8) throw invalid_argument("Date string too small for known formats");
unsigned int year, month, day;
bool found = false;
for (size_t i = 0; i < formats_n && !found; ++i) {
const int chread = sscanf(sDate.c_str(), formats[i].c_str(), &year, &month, &day);
if (chread == 3) {
found = true;
break;
}
}
if (!found) throw invalid_argument("Date [" + sDate + "] did not match a known format. try YYYY-MM-DD");
ostringstream oss;
oss << year << "-" << setfill('0') << std::setw(2) << month << "-" << setfill('0') << std::setw(2) << day;
return oss.str();
}
static const string normalize_project_path(const string &project_path) {
const fs::path rproject_path(project_path);
if (!fs::exists(rproject_path) || !fs::is_directory(rproject_path)) {
throw logic_error("Path " + project_path + " doesn't exist or is not a directory.");
}
fs::path normalized;
const string rproject_path_str = rproject_path.string();
if (rproject_path.string() == ".") {
normalized = fs::current_path();
// sometimes is_relative fails under wine: a linux path is taken for a relative path.
normalized = fs::canonical(fs::current_path() / rproject_path);
} else {
normalized = fs::canonical(rproject_path);
}
return normalized.string();
}
static void create_license_path(const string &license_file_name) {
const fs::path license_name(license_file_name);
fs::path parentPath = license_name.parent_path();
if (!parentPath.empty()) {
if (!fs::exists(parentPath)) {
if (!fs::create_directories(parentPath)) {
throw runtime_error("Cannot create licenses directory [" + parentPath.string() + "]");
}
} else if (fs::is_regular_file(parentPath)) {
throw runtime_error("trying to create folder [" + parentPath.string() +
"] but there is a file with the same name. ");
}
}
}
static const string print_for_sign(const string &feature_name, const CSimpleIniA::TKeyVal *section) {
stringstream buf;
buf << boost::to_upper_copy(feature_name);
for (auto it = section->begin(); it != section->end(); it++) {
string key(it->first.pItem);
if (key != LICENSE_SIGNATURE) {
buf << boost::algorithm::trim_copy(key) << boost::algorithm::trim_copy(string(it->second));
}
}
return buf.str();
}
License::License(const std::string *licenseName, const std::string &project_folder, bool base64)
: m_base64(base64), m_license_fname(licenseName), m_project_folder(normalize_project_path(project_folder)) {
fs::path proj_folder(m_project_folder);
// default feature = project name
m_feature_names = proj_folder.filename().string();
m_private_key = (proj_folder / PRIVATE_KEY_FNAME).string();
}
void License::write_license() {
ofstream license_stream;
ostream *output_license;
CSimpleIniA ini;
if (m_license_fname == nullptr) {
output_license = &cout;
} else {
ifstream previous_license(*m_license_fname);
if (previous_license.is_open()) {
SI_Error error = ini.LoadData(previous_license);
if (error != SI_Error::SI_OK) {
throw runtime_error(
"License file existing, but there were errors in loading it. Is it a license file?");
}
} else {
// new license
create_license_path(*m_license_fname);
}
output_license = &license_stream;
license_stream.open(*m_license_fname, ios::trunc | ios::binary);
if (!license_stream.is_open()) {
throw runtime_error("Can not create file [" + *m_license_fname + "].");
}
}
const string features = boost::to_upper_copy(m_feature_names);
vector<string> feature_v;
boost::algorithm::split(feature_v, features, boost::is_any_of(","));
unique_ptr<CryptoHelper> crypto(CryptoHelper::getInstance());
crypto->loadPrivateKey_file(m_private_key);
for (const string feature : feature_v) {
ini.SetLongValue(feature.c_str(), "lic_ver", LICENSE_FILE_VERSION);
for (auto it : values_map) {
ini.SetValue(feature.c_str(), it.first.c_str(), it.second.c_str());
}
const CSimpleIniA::TKeyVal *section = ini.GetSection(feature.c_str());
string license_for_sign = print_for_sign(feature, section);
const string signature = crypto->signString(license_for_sign);
ini.SetValue(feature.c_str(), LICENSE_SIGNATURE, signature.c_str());
}
ini.Save(*output_license, true);
}
// TODO better validation on the input parameters
// TODO, split this code in multiple classes
void License::add_parameter(const std::string ¶m_name, const std::string ¶m_value) {
if (NO_OUTPUT_PARAM.find(param_name) == NO_OUTPUT_PARAM.end()) {
if (param_name.find("date") != std::string::npos || param_name.find(PARAM_EXPIRY_DATE) != std::string::npos ||
param_name.find(PARAM_BEGIN_DATE) != std::string::npos) {
values_map[param_name] = normalize_date(param_value);
} else if (param_name.find("version") != std::string::npos) {
if (param_value != "0") {
values_map[param_name] = param_value;
}
} else {
values_map[param_name] = param_value;
}
} else if (PARAM_FEATURE_NAMES == param_name) {
m_feature_names = param_value;
if (m_feature_names.find('[') != std::string::npos || m_feature_names.find(']') != std::string::npos ||
m_feature_names.find('/') != std::string::npos || m_feature_names.find('\\') != std::string::npos) {
throw invalid_argument(
string("feature name should not contain any of '[ ] / \' characters. Parameter " PARAM_FEATURE_NAMES
"value :") +
param_name);
}
} else if (PARAM_PRIMARY_KEY == param_name) {
if (!fs::exists(param_value)) {
cerr << "Primary key " << param_value << " not found." << endl;
throw logic_error("Primary key [" + param_value + "] not found");
}
m_private_key = param_value;
} else if (PARAM_LICENSE_OUTPUT == param_name || PARAM_PROJECT_FOLDER == param_name) {
// just ignore
} else {
throw logic_error(param_name + " not recognized");
}
}
} /* namespace license */
| [
"gcontini@users.noreply.github.com"
] | gcontini@users.noreply.github.com |
621436e11220dbac95d2c6893d2878eb96eda651 | 4447dacbb9fbdff5bccd9438a19a7376883185d0 | /RunGame/Sor/System/Inputter.cpp | 9bd1c79b4f0917c1b7e319f3b09532dd421057d9 | [] | no_license | sep-inc/campus_202009_matsui | 73bf99131ab48219d01b6bb2d519ecb45352d059 | 1683d55c7eea8cdfe342911ca432d96267be8625 | refs/heads/master | 2023-01-14T06:27:37.986458 | 2020-11-18T06:12:33 | 2020-11-18T06:12:33 | 292,440,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,303 | cpp | #include "Inputter.h"
#include <stdio.h>
#include <Windows.h>
#include <conio.h>
#include <signal.h>
//!ジャンプキー入力待ち関数
bool Inputter::InputJumpKey()
{
printf("Rキーでジャンプ\n");
char input_; //!入力保存用
//!入力判定(入力があったら通る)
if (_kbhit())
{
input_ = _getch(); //!入力
//!R or rキーなら
if (input_ == 'r' || input_ == 'R')
{
return true;
}
//!ESCが押された場合
else if (input_ == ESC)
{
m_esc = true; //!ESCフラグをtrue
}
}
InputForcedKey(); //!強制終了判定
return false;
}
//!ゲーム開始入力待ち関数
bool Inputter::InputStartKey()
{
printf("Enterでゲームスタート\n");
printf("操作方法:Rキーでジャンプ\n");
printf("終了条件:壁にぶつかるか、300マス先のゴールにたどり着くか。\n");
char input_; //!入力保存用
//!コンティニュー関数と似ているが、押すキーが違った場合if文が変わってくるため分ける
if (_kbhit())
{
input_ = _getch(); //!入力
//!Enterキーなら
if (input_ == ENTER)
{
system("cls");
return true;
}
else if (input_ == ESC)
{
m_esc = true;
system("cls");
return true;
}
}
//!強制終了
InputForcedKey();
return false;
}
//!終了待ち関数
void Inputter::InputForcedKey()
{
//!ctrl+cが押されたとき
signal(SIGINT, SIG_DFL); //!終了
}
//!コンティニュー関数
bool Inputter::InputContinue()
{
char input_; //!入力保存用
printf("まだ続けますか?\n");
printf("続けるならEnter\n");
printf("終わるならESC、もしくはctr+c\n");
if (_kbhit())
{
input_ = _getch(); //!入力
//!Enterキーなら
if (input_ == ENTER)
{
system("cls");
return true;
}
else if (input_ == ESC)
{
m_esc = true;
system("cls");
return false;
}
}
//!強制終了
InputForcedKey();
return false;
}
| [
"siryu725@gmail.com"
] | siryu725@gmail.com |
8ec54d890d39fe8e8251799a736382eb202a8f1e | 8bcdf44df28b68d1d13b2cba2aac352e2fb1d883 | /src/UnitTesting/UnitTest.cpp | a1ffc930af257947b613a2a5d39452de4d52f939 | [] | no_license | nico-dog/Sempervirens | 99a70991071506c211717e0be22ca1029a566724 | 21e127d5d753a1327dbadd039ad5b112b9911462 | refs/heads/master | 2022-11-11T05:24:12.222660 | 2020-06-26T20:09:44 | 2020-06-26T20:09:44 | 206,409,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 176 | cpp | #define UNITTEST_CPP
#include <UnitTesting/UnitTest.hpp>
namespace sempervirens::unittesting
{
void test(UnitTest const& unitTest)
{
unitTest._self->_test();
}
}
| [
"niko.znotinside@gmail.com"
] | niko.znotinside@gmail.com |
b0e3d57af13b70764753bdfb761d3aa275e6da10 | 7d71fa3604d4b0538f19ed284bc5c7d8b52515d2 | /Clients/AG/Pm8/App/TypeCmbo.cpp | 22b308eca94454d9995828cddedf2418e714eb97 | [] | no_license | lineCode/ArchiveGit | 18e5ddca06330018e4be8ab28c252af3220efdad | f9cf965cb7946faa91b64e95fbcf8ad47f438e8b | refs/heads/master | 2020-12-02T09:59:37.220257 | 2016-01-20T23:55:26 | 2016-01-20T23:55:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,696 | cpp | // TypeCmbo.cpp : implementation file
//
#include <stdafx.h>
#include "pmw.h"
#include "TypeCmbo.h"
#include "file.h"
#include "text.h"
#include "typeface.h"
#include "pmwini.h"
#include "pmwdoc.h"
#include "pmgfont.h"
#include "frameobj.h"
#include "ctxp.h"
#include "pmwview.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern CPalette *pOurPal;
/////////////////////////////////////////////////////////////////////////////
// CTypefaceCombo
CTypefaceCombo::CTypefaceCombo() :
CBarMRUCombo(0, SECTION_FontsMRU, ENTRY_FontMRU, MAX_FONTS_MRU)
{
m_nTimer = 0;
m_bShowPreview = FALSE;
m_pPreviewWnd = NULL;
}
CTypefaceCombo::~CTypefaceCombo()
{
DestroyPreview();
}
BOOL CTypefaceCombo::Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID)
{
if (INHERITED::Create(dwStyle, rect, pParentWnd, nID))
{
m_pPreviewWnd = new CFontPreviewWnd(this);
HidePreview();
return TRUE;
}
return FALSE;
}
void CTypefaceCombo::BuildList()
{
BOOL is_registered = GET_PMWAPP()->user_is_registered();
// Add all the chooseable faces to the list.
FaceEntry* entry;
int i;
// First the best
int nFaceIndex;
for (i = 0; i < m_nMRUItems; i++)
{
if ((nFaceIndex = typeface_server.face_list.find_face(m_RecentItemList[i])) != -1)
{
entry = typeface_server.face_list.get_face(nFaceIndex);
if (entry->is_chooseable(is_registered))
{
int nIndex = InsertString(-1, entry->get_name());
if (nIndex != -1)
{
SetItemData(nIndex, (DWORD)nFaceIndex);
}
}
}
}
// Now the rest
for (entry = typeface_server.face_list.first_face(), i = 0;
entry != NULL;
entry = entry->next_face(), i++)
{
if (entry->is_chooseable(is_registered))
{
int nIndex = InsertString(-1, entry->get_name());
if (nIndex != -1)
{
SetItemData(nIndex, (DWORD)i);
}
}
}
}
// Preview window
void CTypefaceCombo::ShowPreview()
{
if (GetDroppedState())
{
UpdatePreview();
MovePreview();
m_pPreviewWnd->ShowWindow(SW_SHOWNOACTIVATE);
}
}
void CTypefaceCombo::HidePreview()
{
m_pPreviewWnd->ShowWindow(SW_HIDE);
}
void CTypefaceCombo::MovePreview()
{
// Move the window to be next to the box
CRect rct;
GetClientRect(rct);
ClientToScreen(rct);
rct.OffsetRect(rct.Width(), 0);
m_pPreviewWnd->SetWindowPos(&wndTop, rct.TopLeft().x, rct.TopLeft().y+30, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE);
}
void CTypefaceCombo::UpdatePreview()
{
m_pPreviewWnd->SetFontID(GetItemData(m_DrawItemStruct.itemID));
m_pPreviewWnd->Invalidate();
}
void CTypefaceCombo::DestroyPreview()
{
if (m_pPreviewWnd != NULL)
{
m_pPreviewWnd->DestroyWindow();
delete m_pPreviewWnd;
m_pPreviewWnd = NULL;
}
}
void CTypefaceCombo::UpdateMRU()
{
// Make sure preview goes AWAY
HidePreview();
CBarMRUCombo::UpdateMRU();
}
BEGIN_MESSAGE_MAP(CTypefaceCombo, CBarMRUCombo)
//{{AFX_MSG_MAP(CTypefaceCombo)
ON_WM_DRAWITEM()
ON_WM_TIMER()
ON_WM_KILLFOCUS()
ON_CONTROL_REFLECT(CBN_CLOSEUP, OnCloseup)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTypefaceCombo message handlers
void CTypefaceCombo::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
// See if we need to set the preview creation timer
if ((lpDrawItemStruct->itemState & ODS_SELECTED) != 0 &&
(lpDrawItemStruct->itemID != m_DrawItemStruct.itemID || !m_pPreviewWnd->IsWindowVisible()))
{
m_DrawItemStruct = *lpDrawItemStruct;
if (!m_pPreviewWnd->IsWindowVisible())
{
// Kill the last timer
if (m_nTimer)
{
KillTimer(m_nTimer);
m_nTimer = 0;
}
// Set the timer for creation (for a delay)
if ((m_nTimer = SetTimer(1, 750, NULL)) != 0)
{
// All set...
m_bShowPreview = TRUE;
}
else
{
// Failed to create timer-- do preview now
ShowPreview();
}
}
else
{
// Update with new font
UpdatePreview();
}
}
CBarMRUCombo::OnDrawItem(nIDCtl, lpDrawItemStruct);
}
void CTypefaceCombo::OnTimer(UINT nIDEvent)
{
// May need to show a preview window
if (m_bShowPreview)
{
ShowPreview();
m_bShowPreview = FALSE;
}
}
void CTypefaceCombo::OnKillFocus(CWnd* pNewWnd)
{
CBarMRUCombo::OnKillFocus(pNewWnd);
HidePreview();
}
void CTypefaceCombo::OnCloseup()
{
HidePreview();
}
/////////////////////////////////////////////////////////////////////////////
// CFontPreviewWnd dialog
CFontPreviewWnd::CFontPreviewWnd(CWnd* pParent /*=NULL*/)
{
//{{AFX_DATA_INIT(CFontPreviewWnd)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
CSize szWnd(240, 80);
if(GET_PMWAPP()->LargeFontMode())
szWnd.cy = 100;
CWnd::CreateEx(WS_EX_DLGMODALFRAME,
::AfxRegisterWndClass(CS_SAVEBITS,
AfxGetApp()->LoadStandardCursor(IDC_ARROW)),
NULL,
WS_BORDER | WS_POPUP,
0, 0, szWnd.cx, szWnd.cy,
pParent->GetSafeHwnd(),
(HMENU)0);
}
BEGIN_MESSAGE_MAP(CFontPreviewWnd, CWnd)
//{{AFX_MSG_MAP(CFontPreviewWnd)
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CFontPreviewWnd message handlers
void CFontPreviewWnd::OnPaint()
{
CPaintDC dc(this); // device context for painting
// Draw the background
CRect rct;
GetClientRect(rct);
dc.FillSolidRect(&rct, RGB(255, 255, 255));
// Get the active view
CMDIFrameWnd *pFrame = (CMDIFrameWnd*)GET_PMWAPP()->m_pMainWnd;
CMDIChildWnd *pChild =
(CMDIChildWnd *) pFrame->GetActiveFrame();
CPmwView *pView = (CPmwView *)pChild->GetActiveView();
// Find the current document
CPmwDoc* pDoc = (CPmwDoc*)(pChild->GetActiveDocument());
ASSERT(pDoc != NULL);
// Get the database
PMGDatabasePtr database = pDoc->get_database();
// Get the current style
CTextStyle Style(database);
CTxp* pTxp = pView->GetTxp();
Style = pTxp->Style();
// If text color is white, make it black so we can see it
FillFormatV1& Fill = Style.Fill();
if (Fill.m_ForegroundColor == COLOR_WHITE)
{
Fill.m_ForegroundColor = COLOR_BLACK;
}
// Get the entry for this face.
FaceEntry* entry;
int face_to_use = m_nFontID;
int font_number = -1;
if ((entry = typeface_server.face_list.get_face(face_to_use)) != NULL)
{
int nVariation = 0;
if (Style.Bold())
{
nVariation |= FONT_STYLE_Bold;
}
if (Style.Italic())
{
nVariation |= FONT_STYLE_Italic;
}
VARIATION_TYPE vtype = entry->get_variation_type(nVariation);
if (vtype == VARIATION_TYPE_VIRTUAL || vtype == VARIATION_TYPE_REGISTRATION)
{
// We want to use the preview font for "virtual" (PMW.FFL) fonts. Check if
// the font has an entry in the preview font.
font_number = entry->get_preview_font_number(nVariation);
if (font_number != -1)
{
// Set the font number back to -1 in case we fail. It will
// be reloaded if we can sucessfully use the preview font.
font_number = -1;
// We want to use the font preview. Try to switch to the preview font.
PCSTR pn = typeface_server.preview_face_name();
if (pn != NULL)
{
int found_face;
if ((found_face = typeface_server.find_face(pn, FALSE)) != -1)
{
face_to_use = found_face;
font_number = entry->get_preview_font_number(nVariation);
}
}
}
}
}
// Get a database record for this face.
// This will be a 'temporary' reference which we must free.
PMGFontServer *pFontServer = (PMGFontServer*)pDoc->get_font_server();
DB_RECORD_NUMBER f_record = pFontServer->font_face_to_record(face_to_use);
// Set the face in the style. The style gets its own reference.
Style.Font(f_record);
// Default to 36 point.
Style.BaseSize(MakeFixed(36));
Style.Size(Style.BaseSize());
Style.UpdateFontMetrics();
// Free our temp reference.
database->free_font_record(f_record, TRUE);
// Build the redisplay context.
RedisplayContext rc;
rc.destination_hdc = dc.m_hDC;
rc.hwnd = m_hWnd;
rc.scaled_source_x0 =
rc.scaled_source_y0 = 0;
rc.destination_rect = rct;
rc.destination_x0 = 0;
rc.destination_y0 = 0;
rc.x_resolution = GetDeviceCaps(dc.m_hDC, LOGPIXELSX);
rc.y_resolution = GetDeviceCaps(dc.m_hDC, LOGPIXELSY);
//rc.outline_gamma_curve = rc.bitmap_gamma_curve = screen_gamma_curve;
//rc.set_check_interrupt(standard_check_interrupt, (void*)&rc);
rc.terminate_interrupts = TRUE;
rc.clip_rect = rct;
// Initialize the redisplay context so we can use it
rc.set_info(dc.m_hDC);
rc.screen_to_pbox(&rct, &rc.source_pbox);
// Create the frame object now.
FRAMEOBJ_CREATE_STRUCT fcs;
fcs.alignment = ALIGN_center;
fcs.vert_alignment = ALIGN_middle;
fcs.bound = rc.source_pbox;
CFrameObject* pObject;
if ((pObject = database->create_frame_object(&fcs)) != NULL)
{
// This object is not on the page!
pObject->OnPage(FALSE);
// Nor is it selected!
pObject->remove_select_flags(SELECT_FLAG_boundary);
// Prepare to add some text.
CTxp Txp(database);
CHARACTER Text[4];
if (font_number == -1)
{
Text[0] = 'T';
Text[1] = 'y';
Text[2] = 'p';
Text[3] = 'e';
}
else
{
// We substituted the preview font
int ch_base = font_number*4 + '!';
Text[0] = ch_base++;
Text[1] = ch_base++;
Text[2] = ch_base++;
Text[3] = ch_base++;
}
// Stick in some text
Txp.Init(pObject, 0);
Txp.SetHorizontalAlignment(ALIGN_center);
Txp.Style(Style);
Txp.InsertText(Text, 4);
// Select our palette in.
CPalette* pOldPalette = dc.SelectPalette(pOurPal, FALSE);
if (pOldPalette != NULL)
{
dc.RealizePalette();
}
// And draw the object!
UpdateStatePtr ustate;
if ((ustate = pObject->update(&rc, &fcs.bound, &rct, NULL, REFRESH_ALL)) != NULL)
{
// See what happened
switch (ustate->type)
{
case UPDATE_TYPE_Interrupted:
{
// This should not happen
delete ustate;
// Fall through to...
}
case UPDATE_TYPE_Terminated:
{
// Try again later
InvalidateRect(&rct, FALSE);
break;
}
default:
{
break;
}
}
}
pObject->destroy(); // Remove from the document.
delete pObject;
// Select our palette back out.
if (pOldPalette != NULL)
{
dc.SelectPalette(pOldPalette, FALSE);
}
}
// Do not call CBarMRUCombo::OnPaint() for painting messages
}
| [
"jim@facetofacesoftware.com"
] | jim@facetofacesoftware.com |
376698e79f3b4d8b451a1c3a1efbd690240e529d | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14043/function14043_schedule_15/function14043_schedule_15.cpp | 2bf894873eb312077cfedd659c28404e7b7bdda0 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 686 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14043_schedule_15");
constant c0("c0", 256), c1("c1", 512), c2("c2", 256);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i01("i01"), i02("i02"), i03("i03"), i04("i04");
computation comp0("comp0", {i0, i1, i2}, 4 * 8 - 5);
comp0.tile(i1, i2, 128, 64, i01, i02, i03, i04);
comp0.parallelize(i0);
buffer buf0("buf0", {256, 512, 256}, p_int32, a_output);
comp0.store_in(&buf0);
tiramisu::codegen({&buf0}, "../data/programs/function14043/function14043_schedule_15/function14043_schedule_15.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
4f28ba48a320db2d68c712ce14a698e7a15b8ee2 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_new_hunk_476.cpp | 3003a29cf49b0cc339b6d3e0de82a5942d2f59d1 | [] | 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 | 258 | cpp | #if XMALLOC_DEBUG
check_malloc(p, sz * n);
#endif
#if XMALLOC_STATISTICS
malloc_stat(sz * n);
#endif
#if MEM_GEN_TRACE
if (tracefp)
fprintf(tracefp, "c:%u:%u:%p\n", (unsigned int) n, (unsigned int) sz, p);
#endif
PROF_stop(xcalloc);
| [
"993273596@qq.com"
] | 993273596@qq.com |
6763abdd7fd7e60f474dc3b3f4dcbaf8206292ed | bd3681d48c1d694bfba50f2f28b202907e9af95d | /PhysicsSimulator/Domain/Scene.h | 5d241c780147931a17eedb5a2feb8cc1a28a5714 | [] | no_license | redfeatherplusplus/PhysicsSimulator | edb938184db7e212781158cab6c40441c3cae0a9 | b1afea1978ff31f06b9f8fd84dfb3facc919469a | refs/heads/master | 2021-01-10T05:05:14.438557 | 2020-01-06T06:29:27 | 2020-01-06T06:29:27 | 48,464,106 | 9 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,692 | h | // Author: Daren Cheng
// Class: CS 4392
// Date: 12/7/2015
// Desc:
// Header file that contains the Scene class
// A Scene is a collection of Meshes
//include guard
#ifndef SCENE_H_INCLUDED
#define SCENE_H_INCLUDED
//include dependancies
#include <GL/freeglut.h>
#include <math.h>
#include <time.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <SWIFT.h>
#include <algorithm> // std::random_shuffle
//include local dependancies
#include <Domain/Rigidbody.h>
//forward declared class references
class Rigidbody;
using namespace std;
struct RigidBodyState {
void saveCurrentState(Rigidbody body);
double orientation[4];
double position[3];
double p_velocity[3];
double l_velocity[3];
};
class Scene
{
private:
void computeImpulseMagnitude(int id, double restitution,
double* location, double* impulse);
void computeImpulseMagnitude(int id1, int id2, double restitution,
double* location1, double* location2, double* normal);
void handleCollision(int id1, int id2,
double* location1, double* location2, double* normal);
void handleContact(int id1, int id2, double restitution,
double* location1, double* location2, double* normal);
public:
SWIFT_Scene* swift_scene; //SWIFT scene for collision detection
vector<Rigidbody> bodies; //collection of bodies in the scene
RigidBodyState* states; //temporarily saved body states
double gravity; //gravity for all objects in the scene
Scene();
void add_body(const char* object_filename,
double *orientation, double *offset, bool fixed,
double density, double *p_velocity, double *l_velocity,
double restitution);
void add_body(const char* object_filename, float* color,
double *orientation, double *offset, bool fixed,
double density, double *p_velocity, double *l_velocity,
double restitution);
void copy_body(int body_id,
double *orientation, double *offset, bool fixed,
double *p_velocity, double *l_velocity, double restitution);
//scene time integration methods
void update(double elapsed_time);
void updateMeshTransformations();
void applyImpulse(double *location, double *impulse, int id);
//scene collision and contact handling methods
void updateVelocities(double elapsed_time);
void saveBodyStates();
void restoreState();
bool handleCollisions();
bool handleContacts(double restitution);
//scene rendering and setup methods
void draw();
void activate();
void kill();
void print();
};
#endif | [
"2012DCheng@gmail.com"
] | 2012DCheng@gmail.com |
240c87417be5ddc88e78b927eb1303a1c4b5c915 | 12d49cf0bdd8844d747f40783ce547e940540f0c | /grail/classes/afa/afa.cpp | c8e0c79912e93a7745c622f4e2aacc937d319edb | [] | no_license | guenhae/Orbit | 42375d44a0d8a047243b89826815512e4723fb0a | 5d676bdb92a85702d24e39064ed04ee2ffd92b6a | refs/heads/master | 2021-01-10T10:58:24.647783 | 2016-01-27T23:29:12 | 2016-01-27T23:29:12 | 50,544,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,689 | cpp | /******************************************************************************************
File: classes/afa/afa.cpp
-----
Description:
------------
This file contains the definition of the following functions:
afa<T>::afa ()
afa<T>::afa (const afa<T>& a)
afa<T>::afa (const fm<T>& d)
afa<T>::~afa()
These functions are members of the template class afa (declared
in afa.h). They are all public members (constructors and
destructors).
Revision History:
-----------------
X. Wu Initial version of source code
S. Huerter 08/11/98 Header and comments
******************************************************************************************/
//#include "afa.h"
/******************************************************************************************
afa<T>::afa()
Description:
This function is a public member of the template class afa (declared in afa.h).
This is the default constructor for afa. This function returns an afa which
accepts no input string.
******************************************************************************************/
template <class T>
afa<T>::afa ()
{
table = 0;
states = 0;
head.set_head(0);
final = 0;
}
/******************************************************************************************
afa<T>::afa(const afa<T>& a)
Description:
This function is a public member of the template class afa (declared in afa.h).
This function is the copy constructor for afa. The new afa will be a copy of
the parameter afa.
Parameters:
const afa<T>& a - the afa to be copied into the new afa.
******************************************************************************************/
template <class T>
afa<T>::afa (const afa<T>& a)
{
symbol = a.symbol;
states = a.states;
final = a.final;
head = a.head; //copy the head function
int snumber = symbol.size();
table = new funct[states * snumber]; //allocate space for the function table
//copy the transtion functions
for (int i=0; i<states; i++)
for (int j=0; j<snumber; j++)
table[i*(snumber) + j] = (a.table)[i*(snumber) + j];
}
/******************************************************************************************
afa<T>::afa(const fm<T>& d)
Description:
This function is a public member of the template class afa (declared in afa.h).
This is a conversion constructor for afa. This function constructs an afa which
accepts the same language as the given finite state machine d.
Parameters:
const fm<T>& d - the deterministic finite machine on which the new afa is based.
Requirements on the input dfa: (i)the size of the dfa state set
must not exceed pow(2,31); (ii)the dfa states must be numbered contiguously
starting at 0 (ie. 0,1,2,..without skipping any integers)
If any of these requirements are not met, result is invalid -- no error
messages are provided.
******************************************************************************************/
template <class T>
afa<T>::afa (const fm<T>& d)
{
this->fmtoafa(d);
}
/******************************************************************************************
afa<T>::~afa()
Description:
This function is a public member of the template class afa (declared in afa.h).
This is the destructor for afa. All that is deleted is the transition table
(largest part of the afa).
******************************************************************************************/
template <class T>
afa<T>::~afa()
{
delete [] table;
}
/******************************************************************************************/
| [
"rlarmsgo92@yonsei.ac.kr"
] | rlarmsgo92@yonsei.ac.kr |
e08649f39286593321de4a516deddae21e397e63 | 8308a98e45b077e0378748add0d02a5cdfe305ec | /in_class.cpp | 9b688e2a136ad3d3837c70c13606b298f79e00b6 | [] | no_license | n-popov/classes | f2c84c499d9065efdf82e238ff5358474bfe4e8f | 6dcc902ad6e11831f2cac8d9c9c9f4ddc40242ac | refs/heads/master | 2023-03-27T22:56:34.845702 | 2021-04-02T15:32:58 | 2021-04-02T15:32:58 | 338,363,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,313 | cpp | #include <string>
#include <iostream>
class Student {
public:
Student(const std::string &name, unsigned int age) :
name(name), age(age) {}
explicit Student(const std::string &name) :
name(name), age(unsigned()) {}
Student(const Student& student) = delete;
// Student(const Student& student) :
// name(student.name), age(student.age) {
// std::cout << "Student copied" << std::endl;
// }
Student& operator=(const Student&) = delete;
virtual ~Student() {
}
const std::string &getName() const {
return name;
}
void setName(const std::string &name) {
Student::name = name;
}
void setAge(unsigned int age) {
Student::age = age;
}
unsigned int getAge() const {
return age;
}
private:
std::string name;
unsigned age;
};
class StringPtr {
public:
StringPtr() : ptr(nullptr) {}
StringPtr(std::string *ptr) : ptr(ptr) {}
StringPtr(const StringPtr& anotherptr) {
ptr = new std::string;
*ptr = *(anotherptr.getPtr());
}
~StringPtr() {
delete ptr;
}
StringPtr& operator=(const StringPtr&) = delete;
[[nodiscard]] std::string* getPtr() const {
return ptr;
}
std::string& operator*() {
return *ptr;
}
private:
std::string* ptr;
};
std::ostream& operator<<(std::ostream& ostr, const StringPtr& ptr) {
ostr << ptr.getPtr();
return ostr;
}
std::istream& operator>>(std::istream& istr, StringPtr& ptr) {
istr >> *ptr;
return istr;
}
void someFunc(Student s) {
std::cout << s.getName() << std::endl;
}
int main() {
// Student arkadiy("Arkadiy", 15);
// Student another_arkadiy = arkadiy;
// std::string niki = "Niki";
// someFunc(another_arkadiy);
// StringPtr* array_of_ptrs = new StringPtr[15];
std::string* some_string = new std::string("Niki");
StringPtr smart_ptr(some_string);
StringPtr another_ptr(smart_ptr);
std::cout << *another_ptr << ' ' << *smart_ptr << std::endl;
// std::cout << smart_ptr.operator*() << std::endl;
// std::cin >> smart_ptr;
// std::cout << smart_ptr << ' ' << *smart_ptr << std::endl;
// int* intptr = new int;
// *intptr = 5;
// std::cout << intptr << ' ' << *intptr << std::endl;
auto x = 5;
} | [
"popov.nv@phystech.edu"
] | popov.nv@phystech.edu |
fa1ac0a9b480ebf8fb4324cacad10537074e386e | 257de719a2108497d6a81126a3efea7c329f5f52 | /SMTrader/ChildFrm.cpp | b33f18f6796e06a0affe20f8953407782bc93565 | [] | no_license | pieangel/SMTrader | 4cb54f5c255a12dd5461f70de47900ef4aaccb41 | 979185eca71575c722d04d66113e51e5dfd21c1c | refs/heads/master | 2020-04-20T04:34:43.009971 | 2020-02-06T01:29:44 | 2020-02-06T01:29:44 | 168,631,995 | 1 | 2 | null | null | null | null | UHC | C++ | false | false | 940 | cpp |
// ChildFrm.cpp : CChildFrame 클래스의 구현
//
#include "stdafx.h"
#include "SMTrader.h"
#include "ChildFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CChildFrame
IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWndEx)
BEGIN_MESSAGE_MAP(CChildFrame, CMDIChildWndEx)
END_MESSAGE_MAP()
// CChildFrame 생성/소멸
CChildFrame::CChildFrame()
{
// TODO: 여기에 멤버 초기화 코드를 추가합니다.
}
CChildFrame::~CChildFrame()
{
}
BOOL CChildFrame::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: CREATESTRUCT cs를 수정하여 여기에서 Window 클래스 또는 스타일을 수정합니다.
if( !CMDIChildWndEx::PreCreateWindow(cs) )
return FALSE;
return TRUE;
}
// CChildFrame 진단
#ifdef _DEBUG
void CChildFrame::AssertValid() const
{
CMDIChildWndEx::AssertValid();
}
void CChildFrame::Dump(CDumpContext& dc) const
{
CMDIChildWndEx::Dump(dc);
}
#endif //_DEBUG
// CChildFrame 메시지 처리기
| [
"shiwansung@SHIWANSUNG1DF8"
] | shiwansung@SHIWANSUNG1DF8 |
69ba0f64b9487b51cc8e712189984bdcc55a0972 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /content/browser/renderer_interface_binders.cc | a391b2789480156ae9406dc879fba84a97483597 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 13,031 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_interface_binders.h"
#include <utility>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/no_destructor.h"
#include "content/browser/background_fetch/background_fetch_service_impl.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/cookie_store/cookie_store_context.h"
#include "content/browser/locks/lock_manager.h"
#include "content/browser/native_file_system/native_file_system_manager_impl.h"
#include "content/browser/notifications/platform_notification_context_impl.h"
#include "content/browser/payments/payment_manager.h"
#include "content/browser/permissions/permission_service_context.h"
#include "content/browser/quota_dispatcher_host.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/storage_partition_impl.h"
#include "content/browser/websockets/websocket_manager.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "media/mojo/interfaces/video_decode_perf_history.mojom.h"
#include "media/mojo/services/video_decode_perf_history.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/device/public/mojom/vibration_manager.mojom.h"
#include "services/network/restricted_cookie_manager.h"
#include "services/service_manager/public/cpp/binder_registry.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/shape_detection/public/mojom/barcodedetection_provider.mojom.h"
#include "services/shape_detection/public/mojom/constants.mojom.h"
#include "services/shape_detection/public/mojom/facedetection_provider.mojom.h"
#include "services/shape_detection/public/mojom/textdetection.mojom.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/mojom/cache_storage/cache_storage.mojom.h"
#include "third_party/blink/public/mojom/cookie_store/cookie_store.mojom.h"
#include "third_party/blink/public/mojom/native_file_system/native_file_system_manager.mojom.h"
#include "third_party/blink/public/mojom/notifications/notification_service.mojom.h"
#include "url/origin.h"
namespace content {
namespace {
// A holder for a parameterized BinderRegistry for content-layer interfaces
// exposed to web workers.
class RendererInterfaceBinders {
public:
RendererInterfaceBinders() { InitializeParameterizedBinderRegistry(); }
// Bind an interface request |interface_pipe| for |interface_name| received
// from a web worker with origin |origin| hosted in the renderer |host|.
void BindInterface(const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe,
RenderProcessHost* host,
const url::Origin& origin) {
if (parameterized_binder_registry_.TryBindInterface(
interface_name, &interface_pipe, host, origin)) {
return;
}
GetContentClient()->browser()->BindInterfaceRequestFromWorker(
host, origin, interface_name, std::move(interface_pipe));
}
// Try binding an interface request |interface_pipe| for |interface_name|
// received from |frame|.
bool TryBindInterface(const std::string& interface_name,
mojo::ScopedMessagePipeHandle* interface_pipe,
RenderFrameHost* frame) {
return parameterized_binder_registry_.TryBindInterface(
interface_name, interface_pipe, frame->GetProcess(),
frame->GetLastCommittedOrigin());
}
private:
void InitializeParameterizedBinderRegistry();
static void CreateWebSocket(network::mojom::WebSocketRequest request,
RenderProcessHost* host,
const url::Origin& origin);
service_manager::BinderRegistryWithArgs<RenderProcessHost*,
const url::Origin&>
parameterized_binder_registry_;
};
// Forwards service requests to Service Manager since the renderer cannot launch
// out-of-process services on is own.
template <typename Interface>
void ForwardServiceRequest(const char* service_name,
mojo::InterfaceRequest<Interface> request,
RenderProcessHost* host,
const url::Origin& origin) {
auto* connector = BrowserContext::GetConnectorFor(host->GetBrowserContext());
connector->BindInterface(service_name, std::move(request));
}
void GetRestrictedCookieManager(
network::mojom::RestrictedCookieManagerRequest request,
RenderProcessHost* render_process_host,
const url::Origin& origin) {
StoragePartition* storage_partition =
render_process_host->GetStoragePartition();
network::mojom::NetworkContext* network_context =
storage_partition->GetNetworkContext();
network_context->GetRestrictedCookieManager(std::move(request), origin);
}
// Register renderer-exposed interfaces. Each registered interface binder is
// exposed to all renderer-hosted execution context types (document/frame,
// dedicated worker, shared worker and service worker) where the appropriate
// capability spec in the content_browser manifest includes the interface. For
// interface requests from frames, binders registered on the frame itself
// override binders registered here.
void RendererInterfaceBinders::InitializeParameterizedBinderRegistry() {
parameterized_binder_registry_.AddInterface(base::Bind(
&ForwardServiceRequest<shape_detection::mojom::BarcodeDetectionProvider>,
shape_detection::mojom::kServiceName));
parameterized_binder_registry_.AddInterface(base::Bind(
&ForwardServiceRequest<shape_detection::mojom::FaceDetectionProvider>,
shape_detection::mojom::kServiceName));
parameterized_binder_registry_.AddInterface(
base::Bind(&ForwardServiceRequest<shape_detection::mojom::TextDetection>,
shape_detection::mojom::kServiceName));
parameterized_binder_registry_.AddInterface(
base::Bind(&ForwardServiceRequest<device::mojom::VibrationManager>,
device::mojom::kServiceName));
// Used for shared workers and service workers to create a websocket.
// In other cases, RenderFrameHostImpl for documents or DedicatedWorkerHost
// for dedicated workers handles interface requests in order to associate
// websockets with a frame. Shared workers and service workers don't have to
// do it because they don't have a frame.
// TODO(nhiroki): Consider moving this into SharedWorkerHost and
// ServiceWorkerProviderHost.
parameterized_binder_registry_.AddInterface(
base::BindRepeating(CreateWebSocket));
parameterized_binder_registry_.AddInterface(
base::Bind([](payments::mojom::PaymentManagerRequest request,
RenderProcessHost* host, const url::Origin& origin) {
static_cast<StoragePartitionImpl*>(host->GetStoragePartition())
->GetPaymentAppContext()
->CreatePaymentManager(std::move(request));
}));
parameterized_binder_registry_.AddInterface(base::BindRepeating(
[](blink::mojom::CacheStorageRequest request, RenderProcessHost* host,
const url::Origin& origin) {
static_cast<RenderProcessHostImpl*>(host)->BindCacheStorage(
std::move(request), origin);
}));
parameterized_binder_registry_.AddInterface(base::BindRepeating(
[](blink::mojom::IDBFactoryRequest request, RenderProcessHost* host,
const url::Origin& origin) {
static_cast<RenderProcessHostImpl*>(host)->BindIndexedDB(
std::move(request), origin);
}));
// TODO(https://crbug.com/873661): Pass origin to FileSystemMananger.
parameterized_binder_registry_.AddInterface(base::BindRepeating(
[](blink::mojom::FileSystemManagerRequest request,
RenderProcessHost* host, const url::Origin& origin) {
static_cast<RenderProcessHostImpl*>(host)->BindFileSystemManager(
std::move(request));
}));
if (base::FeatureList::IsEnabled(blink::features::kNativeFileSystemAPI)) {
parameterized_binder_registry_.AddInterface(base::BindRepeating(
[](blink::mojom::NativeFileSystemManagerRequest request,
RenderProcessHost* host, const url::Origin& origin) {
auto* manager =
static_cast<StoragePartitionImpl*>(host->GetStoragePartition())
->GetNativeFileSystemManager();
// This code path is only for workers, hence always pass in
// MSG_ROUTING_NONE as frame ID. Frames themselves go through
// RenderFrameHostImpl instead.
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::IO},
base::BindOnce(&NativeFileSystemManagerImpl::BindRequest,
base::Unretained(manager),
NativeFileSystemManagerImpl::BindingContext(
origin, host->GetID(), MSG_ROUTING_NONE),
std::move(request)));
}));
}
parameterized_binder_registry_.AddInterface(
base::Bind([](blink::mojom::PermissionServiceRequest request,
RenderProcessHost* host, const url::Origin& origin) {
static_cast<RenderProcessHostImpl*>(host)
->permission_service_context()
.CreateServiceForWorker(std::move(request), origin);
}));
parameterized_binder_registry_.AddInterface(base::BindRepeating(
[](blink::mojom::LockManagerRequest request, RenderProcessHost* host,
const url::Origin& origin) {
static_cast<StoragePartitionImpl*>(host->GetStoragePartition())
->GetLockManager()
->CreateService(std::move(request), origin);
}));
parameterized_binder_registry_.AddInterface(
base::Bind([](blink::mojom::NotificationServiceRequest request,
RenderProcessHost* host, const url::Origin& origin) {
static_cast<StoragePartitionImpl*>(host->GetStoragePartition())
->GetPlatformNotificationContext()
->CreateService(origin, std::move(request));
}));
parameterized_binder_registry_.AddInterface(
base::BindRepeating(&BackgroundFetchServiceImpl::CreateForWorker));
parameterized_binder_registry_.AddInterface(
base::BindRepeating(GetRestrictedCookieManager));
parameterized_binder_registry_.AddInterface(
base::BindRepeating(&QuotaDispatcherHost::CreateForWorker));
parameterized_binder_registry_.AddInterface(base::BindRepeating(
[](blink::mojom::CookieStoreRequest request, RenderProcessHost* host,
const url::Origin& origin) {
static_cast<StoragePartitionImpl*>(host->GetStoragePartition())
->GetCookieStoreContext()
->CreateService(std::move(request), origin);
}));
parameterized_binder_registry_.AddInterface(base::BindRepeating(
[](media::mojom::VideoDecodePerfHistoryRequest request,
RenderProcessHost* host, const url::Origin& origin) {
host->GetBrowserContext()->GetVideoDecodePerfHistory()->BindRequest(
std::move(request));
}));
}
RendererInterfaceBinders& GetRendererInterfaceBinders() {
static base::NoDestructor<RendererInterfaceBinders> binders;
return *binders;
}
void RendererInterfaceBinders::CreateWebSocket(
network::mojom::WebSocketRequest request,
RenderProcessHost* host,
const url::Origin& origin) {
// TODO(jam): is it ok to not send extraHeaders for sockets created from
// shared and service workers?
WebSocketManager::CreateWebSocket(host->GetID(), MSG_ROUTING_NONE, origin,
network::mojom::kWebSocketOptionNone,
nullptr, nullptr, std::move(request));
}
} // namespace
void BindWorkerInterface(const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe,
RenderProcessHost* host,
const url::Origin& origin) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
GetRendererInterfaceBinders().BindInterface(
interface_name, std::move(interface_pipe), host, origin);
}
bool TryBindFrameInterface(const std::string& interface_name,
mojo::ScopedMessagePipeHandle* interface_pipe,
RenderFrameHost* frame) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return GetRendererInterfaceBinders().TryBindInterface(interface_name,
interface_pipe, frame);
}
} // namespace content
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
378828b8fd79b8b539387acbf6b2e7e41eb26664 | f1eedd5a5d36faa210410e2b5fdf7c5fe218ff18 | /prefix_suffix/src/main.cpp | 31e54d13f33e8c46c56d5e650de81a66bb356e6f | [] | no_license | MumblesCrzy/simple-programs | d4ff7abfbfa7ca3bacee372a677e210b2f6c834b | 55e1be5acfc5313399e65ee390d669f41291bfc0 | refs/heads/master | 2021-08-11T11:04:38.204828 | 2017-11-12T09:58:16 | 2017-11-12T09:58:16 | 109,446,808 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 718 | cpp | #include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include "prefix_suffix.h"
int main(int argc, char const* argv[])
{
std::string testFileName = "TestFile.txt";
if (argc == 2)
{
testFileName = argv[1];
}
printf("Using test file %s\n", testFileName.c_str());
std::ifstream testFile;
testFile.open(testFileName.c_str());
if (testFile.is_open())
{
printf("\n");
char test[1024];
while (testFile.getline(test, 1024))
{
std::string testString(test);
int value = solution(testString);
printf("Return Value %d\n\n", value);
}
}
else
printf("Error: could not find or open %s\n", testFileName.c_str());
testFile.close();
return 0;
}
// Final time 9:37am | [
"bhilton@test.build"
] | bhilton@test.build |
a7dfe16172a897e98d708f074b9c56a0659fe049 | 0d11203e6a143b2383b5baa8a9a2b3e48383c9b1 | /minhminh-main/tich lon nhat.cpp | 4d3f7984de87c802fe574b72a6a556fc15c7fb3e | [] | no_license | namnguyen215/CTDLGT | c36b8526b3af00ea2d4bd113efe378f95091f895 | 6e7e602940fb5c28b7af830f44f58443375b7666 | refs/heads/main | 2023-06-25T08:48:47.269848 | 2021-07-21T16:36:36 | 2021-07-21T16:36:36 | 360,927,428 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 981 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int a[n+3];
vector<int> va,vd;
va.clear();
vd.clear();
for(int i=1;i<=n;i++) {
cin>>a[i];
if(a[i]<0) va.push_back(a[i]);
else vd.push_back(a[i]);
}
sort(va.begin(),va.end());
sort(vd.begin(),vd.end());
long long m2,m3;
if(vd.size()>=2&&va.size()<=1) m2=vd[vd.size()-1]*vd[vd.size()-2];
else if(vd.size()<=1&&va.size()>=2) m2=va[0]*va[1];
else if(va.size()>=2&&vd.size()>=2) m2=max(vd[vd.size()-1]*vd[vd.size()-2],va[0]*va[1]);
if(vd.size()>=3&&va.size()<=1) m3=vd[vd.size()-1]*vd[vd.size()-2]*vd[vd.size()-3];
else if(vd.size()==0&& va.size()>=3) m3=va[va.size()-1]*va[va.size()-2]*va[va.size()-3];
else if((vd.size()==1||vd.size()==2)&&va.size()>=2) m3=va[0]*va[1]*vd[vd.size()-1];
else if(vd.size()==2&&va.size()==1) m3=va[0]*vd[1]*vd[0];
else if(vd.size()>=3&&va.size()>=3) m3=vd[vd.size()-1]*max(vd[vd.size()-2]*vd[vd.size()-3],va[0]*va[1]);
cout<<max(m2,m3)<<endl;
}
| [
"namnguyenphuong215@gmail.com"
] | namnguyenphuong215@gmail.com |
ebebfb878a0498c5d456d18318d32aedf95a7e1a | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /ash/webui/personalization_app/search/search_handler_unittest.cc | 74eeae73591c45b93cda82166ccb54ddcdf10000 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 23,581 | cc | // Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/webui/personalization_app/search/search_handler.h"
#include <array>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/public/cpp/ambient/ambient_prefs.h"
#include "ash/public/cpp/personalization_app/enterprise_policy_delegate.h"
#include "ash/public/cpp/personalization_app/time_of_day_test_utils.h"
#include "ash/test/ash_test_base.h"
#include "ash/webui/personalization_app/personalization_app_url_constants.h"
#include "ash/webui/personalization_app/search/search.mojom-shared.h"
#include "ash/webui/personalization_app/search/search.mojom.h"
#include "ash/webui/personalization_app/search/search_concept.h"
#include "ash/webui/personalization_app/search/search_tag_registry.h"
#include "base/functional/callback.h"
#include "base/ranges/algorithm.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "base/types/cxx23_to_underlying.h"
#include "chromeos/ash/components/local_search_service/public/cpp/local_search_service_proxy.h"
#include "chromeos/ash/components/test/ash_test_suite.h"
#include "chromeos/strings/grit/chromeos_strings.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/testing_pref_service.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace ash::personalization_app {
namespace {
inline constexpr int kMaxNumResults = 3;
constexpr std::array<int, 6> kTimeOfDayWallpaperMessageIds = {
IDS_PERSONALIZATION_APP_SEARCH_RESULT_TIME_OF_DAY_WALLPAPER,
IDS_PERSONALIZATION_APP_SEARCH_RESULT_TIME_OF_DAY_WALLPAPER_ALT1,
IDS_PERSONALIZATION_APP_SEARCH_RESULT_TIME_OF_DAY_WALLPAPER_ALT2,
IDS_PERSONALIZATION_APP_SEARCH_RESULT_TIME_OF_DAY_WALLPAPER_ALT3,
IDS_PERSONALIZATION_APP_SEARCH_RESULT_TIME_OF_DAY_WALLPAPER_ALT4,
IDS_PERSONALIZATION_APP_SEARCH_RESULT_TIME_OF_DAY_WALLPAPER_ALT5,
};
constexpr std::array<int, 4> kAmbientModeTimeOfDayMessageIds = {
IDS_PERSONALIZATION_APP_SEARCH_RESULT_AMBIENT_MODE_TIME_OF_DAY,
IDS_PERSONALIZATION_APP_SEARCH_RESULT_AMBIENT_MODE_TIME_OF_DAY_ALT1,
IDS_PERSONALIZATION_APP_SEARCH_RESULT_AMBIENT_MODE_TIME_OF_DAY_ALT2,
IDS_PERSONALIZATION_APP_SEARCH_RESULT_AMBIENT_MODE_TIME_OF_DAY_ALT3,
};
bool HasSearchResult(const std::vector<mojom::SearchResultPtr>& search_results,
const std::u16string& text) {
for (const auto& result : search_results) {
if (result->text == text) {
return true;
}
}
return false;
}
std::string SearchConceptIdToString(
mojom::SearchConceptId search_result_concept) {
return base::NumberToString(base::to_underlying(search_result_concept));
}
class TestSearchResultsObserver : public mojom::SearchResultsObserver {
public:
TestSearchResultsObserver() = default;
TestSearchResultsObserver(const TestSearchResultsObserver&) = delete;
TestSearchResultsObserver& operator=(const TestSearchResultsObserver&) =
delete;
~TestSearchResultsObserver() override = default;
void OnSearchResultsChanged() override {
if (quit_callback_) {
std::move(quit_callback_).Run();
}
}
void WaitForSearchResultsChanged() {
DCHECK(quit_callback_.is_null());
base::RunLoop loop;
quit_callback_ = loop.QuitClosure();
loop.Run();
}
mojo::PendingRemote<mojom::SearchResultsObserver> GetRemote() {
receiver_.reset();
return receiver_.BindNewPipeAndPassRemote();
}
private:
base::OnceClosure quit_callback_;
mojo::Receiver<mojom::SearchResultsObserver> receiver_{this};
};
class TestEnterprisePolicyDelegate : public EnterprisePolicyDelegate {
public:
TestEnterprisePolicyDelegate() = default;
TestEnterprisePolicyDelegate(const TestEnterprisePolicyDelegate&) = delete;
TestEnterprisePolicyDelegate& operator=(const TestEnterprisePolicyDelegate&) =
delete;
~TestEnterprisePolicyDelegate() override = default;
// EnterprisePolicyDelegate:
bool IsUserImageEnterpriseManaged() const override {
return is_user_image_enterprise_managed_;
}
bool IsWallpaperEnterpriseManaged() const override {
return is_wallpaper_enterprise_managed_;
}
void AddObserver(EnterprisePolicyDelegate::Observer* observer) override {
observer_list_.AddObserver(observer);
}
void RemoveObserver(EnterprisePolicyDelegate::Observer* observer) override {
observer_list_.RemoveObserver(observer);
}
void SetIsUserImageEnterpriseManaged(bool is_user_image_enterprise_managed) {
is_user_image_enterprise_managed_ = is_user_image_enterprise_managed;
for (auto& observer : observer_list_) {
observer.OnUserImageIsEnterpriseManagedChanged(
is_user_image_enterprise_managed_);
}
}
void SetIsWallpaperImageEnterpriseManaged(
bool is_wallpaper_enterprise_managed) {
is_wallpaper_enterprise_managed_ = is_wallpaper_enterprise_managed;
for (auto& observer : observer_list_) {
observer.OnWallpaperIsEnterpriseManagedChanged(
is_wallpaper_enterprise_managed_);
}
}
private:
bool is_user_image_enterprise_managed_ = false;
bool is_wallpaper_enterprise_managed_ = false;
base::ObserverList<TestEnterprisePolicyDelegate::Observer> observer_list_;
};
} // namespace
class PersonalizationAppSearchHandlerTest : public AshTestBase {
protected:
PersonalizationAppSearchHandlerTest() {
scoped_feature_list_.InitWithFeatures(
{}, personalization_app::GetTimeOfDayDisabledFeatures());
}
~PersonalizationAppSearchHandlerTest() override = default;
// ash::AshTestBase:
void SetUp() override {
ui::ResourceBundle::CleanupSharedInstance();
AshTestSuite::LoadTestResources();
AshTestBase::SetUp();
local_search_service_proxy_ =
std::make_unique<local_search_service::LocalSearchServiceProxy>(
/*for_testing=*/true);
test_pref_service_ = std::make_unique<TestingPrefServiceSimple>();
test_pref_service_->registry()->RegisterBooleanPref(
::ash::ambient::prefs::kAmbientModeEnabled, true);
test_pref_service_->registry()->RegisterBooleanPref(
::ash::prefs::kDarkModeEnabled, false);
InitSearchHandler();
}
void InitSearchHandler() {
search_handler_remote_.reset();
search_handler_ = std::make_unique<SearchHandler>(
*local_search_service_proxy_, test_pref_service_.get(),
std::make_unique<TestEnterprisePolicyDelegate>());
search_handler_->BindInterface(
search_handler_remote_.BindNewPipeAndPassReceiver());
}
std::vector<mojom::SearchResultPtr> SimulateSearchCompleted(
uint32_t max_num_results,
local_search_service::ResponseStatus response_status,
const absl::optional<std::vector<local_search_service::Result>>&
local_search_service_results) {
std::vector<mojom::SearchResultPtr> result;
base::RunLoop loop;
search_handler_->OnLocalSearchDone(
base::BindLambdaForTesting(
[&result, done = loop.QuitClosure()](
std::vector<mojom::SearchResultPtr> search_results) {
result = std::move(search_results);
std::move(done).Run();
}),
max_num_results, response_status, local_search_service_results);
return result;
}
SearchHandler* search_handler() { return search_handler_.get(); }
SearchTagRegistry* search_tag_registry() {
return search_handler_->search_tag_registry_.get();
}
TestEnterprisePolicyDelegate* test_enterprise_policy_delegate() {
return static_cast<TestEnterprisePolicyDelegate*>(
search_tag_registry()->enterprise_policy_delegate_.get());
}
mojo::Remote<mojom::SearchHandler>* search_handler_remote() {
return &search_handler_remote_;
}
void SetDarkModeEnabled(bool enabled) {
test_pref_service_->SetBoolean(::ash::prefs::kDarkModeEnabled, enabled);
}
std::vector<mojom::SearchResultPtr> Search(const std::u16string& query,
int32_t max_num_results) {
base::test::TestFuture<std::vector<mojom::SearchResultPtr>> future;
search_handler_remote_->Search(query, max_num_results,
future.GetCallback());
return future.Take();
}
std::vector<mojom::SearchResultPtr> RunSearch(int message_id) {
std::u16string query = SearchTagRegistry::MessageIdToString(message_id);
// Search results match better if one character is subtracted.
query.pop_back();
return Search(query, /*max_num_results=*/kMaxNumResults);
}
// Remove all existing search concepts saved in the registry.
void ClearSearchTagRegistry() {
base::test::TestFuture<void> future;
search_tag_registry()->index_remote_->ClearIndex(future.GetCallback());
EXPECT_TRUE(future.Wait());
search_tag_registry()->result_id_to_search_concept_.clear();
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
std::unique_ptr<local_search_service::LocalSearchServiceProxy>
local_search_service_proxy_;
std::unique_ptr<TestingPrefServiceSimple> test_pref_service_;
std::unique_ptr<SearchHandler> search_handler_;
mojo::Remote<mojom::SearchHandler> search_handler_remote_;
};
TEST_F(PersonalizationAppSearchHandlerTest, AnswersPersonalizationQuery) {
std::vector<mojom::SearchResultPtr> search_results =
Search(u"testing", /*max_num_results=*/kMaxNumResults);
EXPECT_TRUE(search_results.empty());
std::u16string title =
l10n_util::GetStringUTF16(IDS_PERSONALIZATION_APP_SEARCH_RESULT_TITLE);
search_results = Search(title, /*max_num_results=*/kMaxNumResults);
EXPECT_EQ(search_results.size(), 1u);
EXPECT_EQ(search_results.front()->text, title);
EXPECT_GT(search_results.front()->relevance_score, 0.9);
}
TEST_F(PersonalizationAppSearchHandlerTest, ObserverFiresWhenResultsUpdated) {
ClearSearchTagRegistry();
TestSearchResultsObserver test_observer;
search_handler_remote()->get()->AddObserver(test_observer.GetRemote());
SearchConcept search_concept = {
.id = mojom::SearchConceptId::kChangeWallpaper,
.message_id = IDS_PERSONALIZATION_APP_WALLPAPER_LABEL,
.relative_url = "testing",
};
// Add a search concept.
search_tag_registry()->UpdateSearchConcepts(
{{&search_concept, /*add=*/true}});
test_observer.WaitForSearchResultsChanged();
EXPECT_EQ(&search_concept, search_tag_registry()->GetSearchConceptById(
SearchConceptIdToString(search_concept.id)))
<< "Search concept was added";
// Remove the search concept.
search_tag_registry()->UpdateSearchConcepts({{&search_concept, false}});
test_observer.WaitForSearchResultsChanged();
EXPECT_EQ(nullptr,
search_tag_registry()->GetSearchConceptById(
base::NumberToString(IDS_PERSONALIZATION_APP_WALLPAPER_LABEL)))
<< "Search concept was removed";
}
TEST_F(PersonalizationAppSearchHandlerTest, RespondsToAltQuery) {
std::u16string search_query = l10n_util::GetStringUTF16(
IDS_PERSONALIZATION_APP_SEARCH_RESULT_TITLE_ALT1);
std::vector<mojom::SearchResultPtr> search_results =
Search(search_query, /*max_num_results=*/kMaxNumResults);
EXPECT_EQ(search_results.size(), 1u);
EXPECT_EQ(search_results.front()->text, search_query);
EXPECT_GT(search_results.front()->relevance_score, 0.9);
}
TEST_F(PersonalizationAppSearchHandlerTest, HasBasicPersonalizationConcepts) {
// Message id to expected relative url.
std::unordered_map<int, std::string> message_ids_to_search = {
{IDS_PERSONALIZATION_APP_SEARCH_RESULT_TITLE_ALT2, std::string()},
{IDS_PERSONALIZATION_APP_SEARCH_RESULT_CHANGE_WALLPAPER_ALT2,
kWallpaperSubpageRelativeUrl},
{IDS_PERSONALIZATION_APP_SEARCH_RESULT_CHANGE_DEVICE_ACCOUNT_IMAGE_ALT4,
kUserSubpageRelativeUrl},
};
for (const auto& [message_id, expected_url] : message_ids_to_search) {
std::vector<mojom::SearchResultPtr> search_results = RunSearch(message_id);
EXPECT_LE(1u, search_results.size());
EXPECT_EQ(expected_url, search_results.front()->relative_url);
}
}
TEST_F(PersonalizationAppSearchHandlerTest, RemovesAvatarForEnterprise) {
EXPECT_TRUE(
search_tag_registry()->GetSearchConceptById(SearchConceptIdToString(
mojom::SearchConceptId::kChangeDeviceAccountImage)));
TestSearchResultsObserver test_observer;
search_handler_remote()->get()->AddObserver(test_observer.GetRemote());
test_enterprise_policy_delegate()->SetIsUserImageEnterpriseManaged(true);
test_observer.WaitForSearchResultsChanged();
EXPECT_FALSE(
search_tag_registry()->GetSearchConceptById(SearchConceptIdToString(
mojom::SearchConceptId::kChangeDeviceAccountImage)));
}
TEST_F(PersonalizationAppSearchHandlerTest, RemovesWallpaperForEnterprise) {
EXPECT_TRUE(search_tag_registry()->GetSearchConceptById(
SearchConceptIdToString(mojom::SearchConceptId::kChangeWallpaper)));
TestSearchResultsObserver test_observer;
search_handler_remote()->get()->AddObserver(test_observer.GetRemote());
test_enterprise_policy_delegate()->SetIsWallpaperImageEnterpriseManaged(true);
test_observer.WaitForSearchResultsChanged();
EXPECT_FALSE(search_tag_registry()->GetSearchConceptById(
SearchConceptIdToString(mojom::SearchConceptId::kChangeWallpaper)));
}
TEST_F(PersonalizationAppSearchHandlerTest, HasDarkModeSearchResults) {
{
// Search one of the basic dark mode tags.
std::vector<mojom::SearchResultPtr> dark_mode_results =
RunSearch(IDS_PERSONALIZATION_APP_SEARCH_RESULT_DARK_MODE_ALT2);
EXPECT_EQ(dark_mode_results.front()->text,
l10n_util::GetStringUTF16(
IDS_PERSONALIZATION_APP_SEARCH_RESULT_DARK_MODE_ALT2));
for (const auto& search_result : dark_mode_results) {
// All dark mode results link to main page.
EXPECT_EQ(std::string(), search_result->relative_url);
}
}
// Terms to search when dark mode is on.
std::vector<int> dark_mode_on_tags = {
IDS_PERSONALIZATION_APP_SEARCH_RESULT_DARK_MODE_TURN_OFF,
IDS_PERSONALIZATION_APP_SEARCH_RESULT_DARK_MODE_TURN_OFF_ALT1,
};
// Terms to search when dark mode is off.
std::vector<int> dark_mode_off_tags = {
IDS_PERSONALIZATION_APP_SEARCH_RESULT_DARK_MODE_TURN_ON,
IDS_PERSONALIZATION_APP_SEARCH_RESULT_DARK_MODE_TURN_ON_ALT1,
};
{
SetDarkModeEnabled(true);
for (auto message_id : dark_mode_on_tags) {
// Has expected search result because dark mode is on.
auto expected_result = l10n_util::GetStringUTF16(message_id);
EXPECT_TRUE(HasSearchResult(RunSearch(message_id), expected_result))
<< "Search result should be present: " << expected_result;
}
for (auto message_id : dark_mode_off_tags) {
// Does not have dark mode off search result because dark mode is on.
auto unexpected_result = l10n_util::GetStringUTF16(message_id);
EXPECT_FALSE(HasSearchResult(RunSearch(message_id), unexpected_result))
<< "Search result should not be present: " << unexpected_result;
}
}
{
SetDarkModeEnabled(false);
for (auto message_id : dark_mode_on_tags) {
// Does not have dark mode on search result because dark mode is off.
auto unexpected_result = l10n_util::GetStringUTF16(message_id);
EXPECT_FALSE(HasSearchResult(RunSearch(message_id), unexpected_result))
<< "Search result should not be present: " << unexpected_result;
}
for (auto message_id : dark_mode_off_tags) {
// Has expected search result because dark mode is off.
auto expected_result = l10n_util::GetStringUTF16(message_id);
EXPECT_TRUE(HasSearchResult(RunSearch(message_id), expected_result))
<< "Search result should be present: " << expected_result;
}
}
}
TEST_F(PersonalizationAppSearchHandlerTest, SortsAndTruncatesResults) {
ClearSearchTagRegistry();
// Test search concepts.
std::vector<const SearchConcept> test_search_concepts = {
{
.id = mojom::SearchConceptId::kChangeWallpaper,
.message_id = IDS_PERSONALIZATION_APP_WALLPAPER_LABEL,
},
{
.id = mojom::SearchConceptId::kPersonalization,
.message_id = IDS_PERSONALIZATION_APP_PERSONALIZATION_HUB_TITLE,
},
{
.id = mojom::SearchConceptId::kAmbientMode,
.message_id = IDS_PERSONALIZATION_APP_SCREENSAVER_LABEL,
},
{
.id = mojom::SearchConceptId::kChangeDeviceAccountImage,
.message_id = IDS_PERSONALIZATION_APP_AVATAR_LABEL,
},
};
SearchTagRegistry::SearchConceptUpdates updates;
for (const auto& search_concept : test_search_concepts) {
updates.insert(std::make_pair(&search_concept, true));
}
search_tag_registry()->UpdateSearchConcepts(updates);
// Scores that correspond to each of the |test_search_concepts|.
std::vector<double> scores = {0.33, 0.5, 0.1, 0.99};
std::vector<local_search_service::Result> fake_local_results;
for (size_t i = 0; i < scores.size(); i++) {
std::vector<local_search_service::Position> positions;
positions.emplace_back(/*content_id=*/base::NumberToString(
test_search_concepts.at(i).message_id),
/*start=*/0, /*length=*/0);
fake_local_results.emplace_back(
/*id=*/SearchConceptIdToString(test_search_concepts.at(i).id),
/*score=*/scores.at(i), std::move(positions));
}
constexpr size_t maxNumResults = 2;
auto results = SimulateSearchCompleted(
/*max_num_results=*/maxNumResults,
local_search_service::ResponseStatus::kSuccess,
absl::make_optional(fake_local_results));
// Capped at |maxNumResults|.
EXPECT_EQ(maxNumResults, results.size());
// First result is top scoring result.
EXPECT_EQ(l10n_util::GetStringUTF16(IDS_PERSONALIZATION_APP_AVATAR_LABEL),
results.at(0)->text);
EXPECT_EQ(0.99, results.at(0)->relevance_score);
// Next result is second best score.
EXPECT_EQ(l10n_util::GetStringUTF16(
IDS_PERSONALIZATION_APP_PERSONALIZATION_HUB_TITLE),
results.at(1)->text);
EXPECT_EQ(0.5, results.at(1)->relevance_score);
}
TEST_F(PersonalizationAppSearchHandlerTest, NoTimeOfDayWallpaperResults) {
for (const auto message_id : kTimeOfDayWallpaperMessageIds) {
std::vector<mojom::SearchResultPtr> time_of_day_search_results =
RunSearch(message_id);
auto time_of_day_result = base::ranges::find_if(
time_of_day_search_results, [](const auto& result) {
return result->search_concept_id ==
mojom::SearchConceptId::kTimeOfDayWallpaper;
});
EXPECT_EQ(time_of_day_search_results.end(), time_of_day_result);
}
}
TEST_F(PersonalizationAppSearchHandlerTest, NoAmbientModeTimeOfDayResults) {
for (const auto message_id : kAmbientModeTimeOfDayMessageIds) {
std::vector<mojom::SearchResultPtr> time_of_day_search_results =
RunSearch(message_id);
auto time_of_day_result = base::ranges::find_if(
time_of_day_search_results, [](const auto& result) {
return result->search_concept_id ==
mojom::SearchConceptId::kAmbientModeTimeOfDay;
});
EXPECT_EQ(time_of_day_search_results.end(), time_of_day_result);
}
}
class PersonalizationAppSearchHandlerTimeOfDayTest
: public PersonalizationAppSearchHandlerTest {
public:
PersonalizationAppSearchHandlerTimeOfDayTest() {
scoped_feature_list_.InitWithFeatures(
personalization_app::GetTimeOfDayEnabledFeatures(), {});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
TEST_F(PersonalizationAppSearchHandlerTimeOfDayTest, TimeOfDayWallpaperSearch) {
for (const auto message_id : kTimeOfDayWallpaperMessageIds) {
std::vector<mojom::SearchResultPtr> time_of_day_search_results =
RunSearch(message_id);
auto time_of_day_result = base::ranges::find_if(
time_of_day_search_results, [](const auto& result) {
return result->search_concept_id ==
mojom::SearchConceptId::kTimeOfDayWallpaper;
});
EXPECT_NE(time_of_day_search_results.end(), time_of_day_result);
EXPECT_EQ("wallpaper/collection?id=_time_of_day_chromebook_collection",
time_of_day_result->get()->relative_url);
}
}
TEST_F(PersonalizationAppSearchHandlerTimeOfDayTest,
AmbientModeTimeOfDaySearch) {
for (const auto message_id : kAmbientModeTimeOfDayMessageIds) {
std::vector<mojom::SearchResultPtr> time_of_day_search_results =
RunSearch(message_id);
auto time_of_day_result = base::ranges::find_if(
time_of_day_search_results, [](const auto& result) {
return result->search_concept_id ==
mojom::SearchConceptId::kAmbientModeTimeOfDay;
});
EXPECT_NE(time_of_day_search_results.end(), time_of_day_result);
EXPECT_EQ(kAmbientSubpageRelativeUrl,
time_of_day_result->get()->relative_url);
}
}
TEST_F(PersonalizationAppSearchHandlerTimeOfDayTest,
TimeOfDayWallpaperSearchPolicyControlled) {
test_enterprise_policy_delegate()->SetIsWallpaperImageEnterpriseManaged(true);
for (const auto message_id : kTimeOfDayWallpaperMessageIds) {
std::vector<mojom::SearchResultPtr> time_of_day_search_results =
RunSearch(message_id);
auto time_of_day_result = base::ranges::find_if(
time_of_day_search_results, [](const auto& result) {
return result->search_concept_id ==
mojom::SearchConceptId::kTimeOfDayWallpaper;
});
EXPECT_EQ(time_of_day_search_results.end(), time_of_day_result);
}
}
TEST_F(PersonalizationAppSearchHandlerTimeOfDayTest,
TimeOfDayScreenSaverDisallowed) {
// Search tag registry does not live update when ambient mode allowed is set
// to false. This cannot happen during a session for a given account, so no
// need for an observer method. Log in as a non-eligible account and clear and
// recreate the search handler to receive updates.
SimulateUserLogin("asdf@example.com");
ClearSearchTagRegistry();
InitSearchHandler();
{
// Search another message id that should be present to confirm that search
// is still working.
std::vector<mojom::SearchResultPtr> other_search_results =
RunSearch(IDS_PERSONALIZATION_APP_SEARCH_RESULT_CHANGE_WALLPAPER);
auto desired_result =
base::ranges::find_if(other_search_results, [](const auto& result) {
return result->search_concept_id ==
mojom::SearchConceptId::kChangeWallpaper;
});
ASSERT_NE(other_search_results.end(), desired_result);
}
for (const auto message_id : kAmbientModeTimeOfDayMessageIds) {
std::vector<mojom::SearchResultPtr> time_of_day_search_results =
RunSearch(message_id);
auto time_of_day_result = base::ranges::find_if(
time_of_day_search_results, [](const auto& result) {
return result->search_concept_id ==
mojom::SearchConceptId::kAmbientModeTimeOfDay;
});
EXPECT_EQ(time_of_day_search_results.end(), time_of_day_result);
}
}
} // namespace ash::personalization_app
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
8d7e3dc6102d5e83a7bf15d12ce48b3103cf3e91 | fbc3ee4467922e3a01aaef61af33ad0a79e6a8df | /stl/pair.cpp | 4e40a3dedee5b052d35ca58f181c31c38cd159f8 | [] | no_license | snh3003/CB-Master-Course | 9c5026c65ae02dd6114946981f08faff97501fc1 | fd6599fce1463c68fc4c2c1fa3552718fdd43b24 | refs/heads/master | 2023-08-24T12:41:38.067743 | 2021-09-30T07:17:36 | 2021-09-30T07:17:36 | 288,263,538 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 200 | cpp | #include<iostream>
#include<algorithm>
using namespace std;
int main(){
pair<int, char> p;
p.first = 10;
p.second = 'B';
cout<<p.first<<endl;
cout<<p.second<<endl;
return 0;
} | [
"shahsama542@gmail.com"
] | shahsama542@gmail.com |
d46fa6e9bd5cafc8a228dd4b244374cf0e09c387 | e568fc51da8ddb89c5c9669cbe8bf39b8b28984a | /QBert/Menus.cpp | 1d2301a7427d60638192d3e1ddc2b892ad2a2dec | [] | no_license | TiboRombaut/Minigin | 0a0e6757a9fdb967525c8ba370f201aa8aa8272d | 8123286273c376c1f2763bf4e54cd4f71b48469e | refs/heads/master | 2023-05-09T12:52:52.353368 | 2021-06-06T15:28:45 | 2021-06-06T15:28:45 | 357,920,809 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,960 | cpp | #include "Menus.h"
#include "GameObject.h"
#include "InputManager.h"
#include "CommandQbert.h"
Menus::Menus(std::shared_ptr<dae::TextureComponent> playButton,std::shared_ptr<dae::TextureComponent> exitButton,
std::shared_ptr<dae::TextureComponent> restartButton, std::shared_ptr<dae::TextureComponent> mainMenuButton,
std::shared_ptr<dae::TextureComponent> pauseScreen, std::shared_ptr<dae::TextureComponent> DeathScreen,
std::shared_ptr<dae::TextComponent> textFinalScore)
: m_pPlayButton(playButton)
, m_pDeathScreen(DeathScreen)
, m_pMainMenuButton(mainMenuButton)
, m_pRestartButton(restartButton)
, m_pExitButton(exitButton)
, m_pPauseScreen(pauseScreen)
,m_pTextFinalScore(textFinalScore)
{
m_pDeathScreen->GetGameObject()->SetIsActive(false);
m_pPauseScreen->GetGameObject()->SetIsActive(false);
m_pPlayButton->GetGameObject()->SetIsActive(false);
m_pMainMenuButton->GetGameObject()->SetIsActive(false);
m_pRestartButton->GetGameObject()->SetIsActive(false);
m_pExitButton->GetGameObject()->SetIsActive(false);
}
void Menus::Update()
{
auto mousePos = dae::InputManager::GetMousePos();
if (m_pPlayButton->GetGameObject()->GetIsActive())
{
if (IsInButton(mousePos, glm::vec2(m_pPlayButton->GetTransform().GetPosition().x, m_pPlayButton->GetTransform().GetPosition().y),
glm::vec2(m_pPlayButton->GetWidth(), m_pPlayButton->GetHeight())))
{
m_pPlayButton->SetTexture("ResumePressed.png");
m_MouseClickHappenend = InWhatButtonGameMenu::Play;
}
else
{
m_pPlayButton->SetTexture("Resume.png");
if (m_MouseClickHappenend == InWhatButtonGameMenu::Play)
{
m_MouseClickHappenend = InWhatButtonGameMenu::None;
}
}
}
if (m_pMainMenuButton->GetGameObject()->GetIsActive())
{
if (IsInButton(mousePos, glm::vec2(m_pMainMenuButton->GetTransform().GetPosition().x, m_pMainMenuButton->GetTransform().GetPosition().y),
glm::vec2(m_pMainMenuButton->GetWidth(), m_pMainMenuButton->GetHeight())))
{
m_pMainMenuButton->SetTexture("MainMenuPressed.png");
m_MouseClickHappenend = InWhatButtonGameMenu::MainMenu;
}
else
{
m_pMainMenuButton->SetTexture("MainMenu.png");
if (m_MouseClickHappenend == InWhatButtonGameMenu::MainMenu)
{
m_MouseClickHappenend = InWhatButtonGameMenu::None;
}
}
}
if (m_pRestartButton->GetGameObject()->GetIsActive())
{
if (IsInButton(mousePos, glm::vec2(m_pRestartButton->GetTransform().GetPosition().x, m_pRestartButton->GetTransform().GetPosition().y),
glm::vec2(m_pRestartButton->GetWidth(), m_pRestartButton->GetHeight())))
{
m_pRestartButton->SetTexture("RestartPressed.png");
m_MouseClickHappenend = InWhatButtonGameMenu::Restart;
}
else
{
m_pRestartButton->SetTexture("Restart.png");
if (m_MouseClickHappenend == InWhatButtonGameMenu::Restart)
{
m_MouseClickHappenend = InWhatButtonGameMenu::None;
}
}
}
if (m_pExitButton->GetGameObject()->GetIsActive())
{
if (IsInButton(mousePos, glm::vec2(m_pExitButton->GetTransform().GetPosition().x, m_pExitButton->GetTransform().GetPosition().y),
glm::vec2(m_pExitButton->GetWidth(), m_pExitButton->GetHeight())))
{
m_pExitButton->SetTexture("ExitPressed.png");
m_MouseClickHappenend = InWhatButtonGameMenu::Exit;
}
else
{
m_pExitButton->SetTexture("Exit.png");
if (m_MouseClickHappenend == InWhatButtonGameMenu::Exit)
{
m_MouseClickHappenend = InWhatButtonGameMenu::None;
}
}
}
}
void Menus::SetPauseScreenActive()
{
m_pPlayButton->GetGameObject()->SetIsActive(true);
m_pRestartButton->GetGameObject()->SetIsActive(true);
m_pMainMenuButton->GetGameObject()->SetIsActive(true);
m_pExitButton->GetGameObject()->SetIsActive(true);
m_pPauseScreen->GetGameObject()->SetIsActive(true);
}
void Menus::SetPauseScreenInActive()
{
m_pPauseScreen->GetGameObject()->SetIsActive(false);
m_pPlayButton->GetGameObject()->SetIsActive(false);
m_pMainMenuButton->GetGameObject()->SetIsActive(false);
m_pRestartButton->GetGameObject()->SetIsActive(false);
m_pExitButton->GetGameObject()->SetIsActive(false);
}
void Menus::SetDeathScreenActive(int finalScore)
{
m_pMainMenuButton->GetGameObject()->SetIsActive(true);
m_pRestartButton->GetGameObject()->SetIsActive(true);
m_pExitButton->GetGameObject()->SetIsActive(true);
m_pDeathScreen->GetGameObject()->SetIsActive(true);
m_pTextFinalScore->GetGameObject()->SetIsActive(true);
m_pTextFinalScore->SetText("Score: " + std::to_string(finalScore));
}
void Menus::SetDeathScreenInActive()
{
m_pDeathScreen->GetGameObject()->SetIsActive(false);
m_pRestartButton->GetGameObject()->SetIsActive(false);
m_pMainMenuButton->GetGameObject()->SetIsActive(false);
m_pExitButton->GetGameObject()->SetIsActive(false);
}
bool Menus::IsInButton(glm::vec2 pos, glm::vec2 posTexture, glm::vec2 sizeTexture)
{
if (pos.x > posTexture.x && pos.x < posTexture.x + sizeTexture.x &&
pos.y > posTexture.y && pos.y < posTexture.y + sizeTexture.y)
{
return true;
}
return false;
}
| [
"tibo.rombaut@student.howest.be"
] | tibo.rombaut@student.howest.be |
4ffec523c23d8e89601a0de2c5e059b7678c1e86 | f5553b723ea9ef30d9f403d4939145e7b598c9dc | /src/z80/interrupts.cc | 85449794cf4f139af2bce7a8657936b751e264a6 | [] | no_license | fmichea/nebula | 494681679cb27334647a9eb784c2a5d81313dced | 2a20880511abec1f7cf3f5c7ddee0a304e7798a6 | refs/heads/master | 2021-01-25T12:19:44.481334 | 2016-10-23T13:42:06 | 2016-10-23T13:42:06 | 23,530,762 | 0 | 1 | null | 2015-03-31T01:54:01 | 2014-09-01T04:38:48 | C++ | UTF-8 | C++ | false | false | 3,460 | cc | #include "interrupts.hh"
#define TIMER_ENABLED(Tac) ((Tac & 0x4) >> 2)
#define TIMER_CYCLES_SELECTOR(Tac) (Tac & 0x3)
static void _div_reg_written_to(void* data, const WatchEvent* UNUSED(event)) {
Interrupts* interrupts = static_cast<Interrupts*>(data);
interrupts->div_reg_written_to();
}
static void _tac_reg_written_to(void* data, const WatchEvent* event) {
Interrupts* interrupts = static_cast<Interrupts*>(data);
interrupts->tac_reg_written_to(event);
}
Interrupts::Interrupts(MMU* mmu, Z80Registers& regs)
: mmu_ (mmu)
, regs_ (regs)
, _timer_counter (0)
, _delayed_timer_val (0)
, tima_reload_scheduled_ (false)
{
this->mmu_->subscribe(this->mmu_->DIV.addr(), WatchType::WRITE_ONLY, _div_reg_written_to, this);
this->mmu_->subscribe(this->mmu_->TAC.addr(), WatchType::WRITE_ONLY, _tac_reg_written_to, this);
}
void Interrupts::manage_interrupts() {
uint8_t ints[] = {0x40, 0x48, 0x50, 0x58, 0x60};
uint8_t if_flag = this->mmu_->IF.get();
uint8_t state = mmu_->IE.get() & if_flag;
if (!(this->regs_.IME || this->regs_.halt_mode) || !state) {
return;
}
if (state && this->regs_.halt_mode) {
this->regs_.halt_mode = false;
return;
}
for (uint8_t it = 0; it < 5 && state; ++it) {
if ((state >> it) & 0x1) {
this->mmu_->IF.set(if_flag & (~(0x1 << it)));
this->regs_.PC -= 1;
di(*this->mmu_, this->regs_);
rst_nn(*this->mmu_, this->regs_, ints[it]);
break;
}
}
}
void Interrupts::div_reg_written_to() {
this->_timer_counter = 0;
this->_manage_tima_increment();
}
void Interrupts::tac_reg_written_to(const WatchEvent* UNUSED(event)) {
this->_manage_tima_increment();
}
void Interrupts::manage_timer(uint8_t cycles) {
for (uint8_t x = 0; x < cycles; x += 4) {
uint16_t orig_timer_counter = this->_timer_counter;
this->_timer_counter += 4;
// Divider register, inc at a speed of 16384 Hz (every 256 cpu cycles).
if ((orig_timer_counter & 0xff00) != (this->_timer_counter & 0xff00)) {
this->mmu_->DIV.set(this->mmu_->DIV.get() + 1);
}
if (this->tima_reload_scheduled_) {
this->mmu_->TIMA.set(this->mmu_->TMA.get());
this->mmu_->IF.set(this->mmu_->IF.get() | INTERRUPT_TIMER);
this->tima_reload_scheduled_ = false;
}
this->_manage_tima_increment();
}
}
void Interrupts::_manage_tima_increment() {
uint8_t tac = this->mmu_->TAC.get();
// TAC controls the behaviour of the timer, TIMA is the timer itself.
uint8_t val = TIMER_ENABLED(tac);
uint16_t timer_counter_mask = this->_cycles_for_timer(tac);
val &= (this->_timer_counter & timer_counter_mask) ? 1 : 0;
if (!val && this->_delayed_timer_val) {
this->mmu_->TIMA.set((this->mmu_->TIMA.get() + 1) & 0xff);
if (this->mmu_->TIMA.get() == 0) {
this->tima_reload_scheduled_ = true;
}
}
this->_delayed_timer_val = val;
}
uint16_t Interrupts::_cycles_for_timer(uint8_t tac) {
switch (TIMER_CYCLES_SELECTOR(tac)) { // Controls speed of timer.
case 0x0: // 4096 Hz - 1024 cpu cycles
return 0x0200;
case 0x1: // 262144 Hz - 16 cpu cycles
return 0x0008;
case 0x2: // 65536 Hz - 64 cpu cycles
return 0x0020;
case 0x3: // 16384 Hz - 256 cpu cycles
return 0x0080;
};
}
| [
"franck.michea@gmail.com"
] | franck.michea@gmail.com |
04a64769d7ef216008f91a98b774edbdf7ce607a | 050c8a810d34fe125aecae582f9adfd0625356c6 | /cf1439/B.cpp | 58db2702ec1c0fe44fb6fea0ffa0069bb4d79a7c | [] | no_license | georgerapeanu/c-sources | adff7a268121ae8c314e846726267109ba1c62e6 | af95d3ce726325dcd18b3d94fe99969006b8e138 | refs/heads/master | 2022-12-24T22:57:39.526205 | 2022-12-21T16:05:01 | 2022-12-21T16:05:01 | 144,864,608 | 11 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,408 | cpp | #include <bits/stdc++.h>
using namespace std;
const int NMAX = 1e5;
int t;
int n,m,k;
vector<int> graph[NMAX + 5];
int gr[NMAX + 5];
bool active[NMAX + 5];
bool in[NMAX + 5];
bool exists(int i,int j){
vector<int> :: iterator it = lower_bound(graph[i].begin(),graph[i].end(),j);
if(it != graph[i].end() && *it == j){
return true;
}
return false;
}
int main(){
scanf("%d",&t);
while(t--){
scanf("%d %d %d",&n,&m,&k);
for(int i = 1;i <= n;i++){
gr[i] = 0;
graph[i].clear();
active[i] = 1;
in[i] = 0;
}
for(int i = 1;i <= m;i++){
int u,v;
scanf("%d %d",&u,&v);
graph[u].push_back(v);
graph[v].push_back(u);
gr[u]++;
gr[v]++;
}
if(1LL * k * (k - 1) > 2 * m){
printf("-1\n");
continue;
}
queue<int> q;
for(int i = 1;i <= n;i++){
sort(graph[i].begin(),graph[i].end());
if(gr[i] < k){
q.push(i);
in[i] = 1;
}
}
while(!q.empty()){
int nod = q.front();
active[nod] = 0;
q.pop();
for(auto it:graph[nod]){
gr[it]--;
if(in[it] == 0 && gr[it] < k){
in[it] = 1;
q.push(it);
}
}
}
vector<int> ans;
for(int i = 1;i <= n;i++){
if(active[i] == 1){
ans.push_back(i);
}
}
if(ans.empty() == false){
printf("1 %d\n",(int)ans.size());
for(auto it:ans){
printf("%d ",it);
}
printf("\n");
continue;
}
for(int i = 1;i <= n;i++){
gr[i] = graph[i].size();
active[i] = 1;
in[i] = 0;
}
for(int i = 1;i <= n;i++){
if(gr[i] < k){
in[i] = 1;
q.push(i);
}
}
bool found = false;
while(!q.empty()){
int nod = q.front();
q.pop();
active[nod] = 0;
if(gr[nod] == k - 1){
vector<int> nodes = {nod};
for(auto it:graph[nod]){
if(active[it] == 1){
nodes.push_back(it);
}
}
bool ok = true;
for(int i = 0;i < (int)nodes.size() && ok;i++){
for(int j = i + 1;j < (int)nodes.size() && ok;j++){
ok &= exists(nodes[i],nodes[j]);
}
}
if(ok == true){
found = true;
printf("2\n");
for(auto it:nodes){
printf("%d ",it);
}
printf("\n");
break;
}
}
for(auto it:graph[nod]){
gr[it]--;
if(in[it] == 0 && gr[it] < k){
in[it] = 1;
q.push(it);
}
}
}
if(found == false){
printf("-1\n");
continue;
}
}
return 0;
}
| [
"alexandrurapeanu@yahoo.com"
] | alexandrurapeanu@yahoo.com |
c1336bcafb1abb41c09cbd7ae61365013a99be13 | 6f1a8bae3b7916b94bf0409288a3a80692d8e4d3 | /CS251/Projects/program1_rgenov2/test-suite/t10_join_plus_maxA.cpp | 12399334e416e5ea30511d424cf261d84e138df9 | [] | no_license | Rg3n0v4/schoolProjects | 8acf490abf9a5c0ecc840b41c4b55747765d81e8 | c959b7e31d8dd5b7ea8138dd66447e42907de85d | refs/heads/master | 2023-02-15T03:10:50.156762 | 2021-01-11T18:29:47 | 2021-01-11T18:29:47 | 286,540,842 | 0 | 0 | null | 2020-08-19T15:16:32 | 2020-08-10T17:40:13 | null | UTF-8 | C++ | false | false | 2,424 | cpp | #include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "TravelOptions.h"
// #include <string>
#include "_test.h"
#include "_to_util.h"
bool t_join_pm_B_always_slowest() {
std::vector<std::pair<double,double>> A{{1,10}, {2,9}, {3,8}};
std::vector<std::pair<double,double>> B{{1,13}, {2,12}, {3,11}};
std::vector<std::pair<double,double>> correct{{2,13}, {3,12}, {4,11}};
std::vector<std::pair<double,double>> *result;
TravelOptions *a = TravelOptions::from_vec(A);;
TravelOptions *b = TravelOptions::from_vec(B);;
TravelOptions *join;
join = a->join_plus_max(*b);
result = join->to_vec();
bool passed = cmp_vec(correct, *result);
delete a;
delete b;
delete result;
return passed;
}
bool t_join_pm_self() {
std::vector<std::pair<double,double>> A{{1,10}, {2,9}, {3,8}};
// std::vector<std::pair<double,double>> B{{1,13}, {2,12}, {3,11}};
std::vector<std::pair<double,double>> correct{{2,10}, {4,9}, {6,8}};
std::vector<std::pair<double,double>> *result;
TravelOptions *a = TravelOptions::from_vec(A);;
// TravelOptions *b = TravelOptions::from_vec(B);;
TravelOptions *join;
join = a->join_plus_max(*a);
result = join->to_vec();
bool passed = cmp_vec(correct, *result);
delete a;
// delete b;
delete result;
return passed;
}
bool t_join_pp_identity() {
std::vector<std::pair<double,double>> A{{1,10}, {2,9}, {3,8}, {4,7}};
std::vector<std::pair<double,double>> B{{0,0}};
std::vector<std::pair<double,double>> correct{{1,10}, {2,9}, {3,8}, {4,7}};
std::vector<std::pair<double,double>> *result;
TravelOptions *a = TravelOptions::from_vec(A);;
TravelOptions *b = TravelOptions::from_vec(B);;
TravelOptions *join;
join = a->join_plus_plus(*b);
result = join->to_vec();
bool passed = cmp_vec(correct, *result);
delete a;
delete b;
delete result;
return passed;
}
int main(int argc, char *argv[]) {
int n = ___N;
int ntrials=1;
if(argc > 1)
n = atoi(argv[1]);
if(argc > 2){
ntrials = atoi(argv[2]);
set_ntrials(ntrials);
}
START("[join_plus_max] partI");
TEST_RET_MESSAGE(t_join_pm_B_always_slowest(),
"TEST: join( {{1,10}, {2,9}, {3,8}}, {{1,13}, {2,12}, {3,11}}) = {{2,10}, {3,12}, {4,11}}",
true, 3.5);
TEST_RET_MESSAGE(t_join_pm_self(),
"TEST: join( {{1,10}, {2,9}, {3,8}}, <same>) = {{2,10}, {4,9}, {6,8}}",
true, 3.5);
report();
END;
}
| [
"rgenov2@uic.edu"
] | rgenov2@uic.edu |
52ebc570afccdcf5b2dfb53c3dcfabec86673d03 | 63be88961f2217a6e5578a655736ad5cd4142655 | /src/HmacHasher.h | 63dc3efe9c2cb99038f20a429d4df48bd2b25795 | [
"MIT"
] | permissive | arcao/Crypto | 8eb6db6e1caa23772ce7e94d6c963f84aaa585af | fec4667e9bdafc853c36b916b540a1d63d4063e1 | refs/heads/master | 2021-01-21T06:53:46.538437 | 2017-02-27T10:45:40 | 2017-02-27T10:45:40 | 83,296,108 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | h | #ifndef CRYPTO_HMACHASHER_H
#define CRYPTO_HMACHASHER_H
#include "CryptoTypes.h"
#include "AbstractHasher.h"
class HmacHasher : public AbstractHasher {
public:
HmacHasher(hash_algo_t algorithm);
~HmacHasher();
size_t write(const uint8_t *buffer, size_t size) override;
size_t write(uint8_t data) override;
bool begin(const uint8_t *key, size_t keyLen);
bool begin(const char *key) {
return begin((uint8_t *) key, strlen(key));
}
bool begin(const String &key) {
return begin((uint8_t *) key.c_str(), key.length());
}
void end() override;
static String hash(hash_algo_t algorithm, const uint8_t *key, size_t keyLen, const uint8_t *data, size_t dataLen) {
HmacHasher hasher(algorithm);
if (!hasher.begin(key, keyLen))
return String();
hasher.write(data, dataLen);
hasher.end();
return hasher.getHashHex();
}
static String hashHex(hash_algo_t algorithm, const char *key, const uint8_t *data, size_t dataLen) {
return hash(algorithm, (uint8_t *) key, strlen(key), data, dataLen);
}
};
#endif //CRYPTO_HMACHASHER_H
| [
"arcao@arcao.com"
] | arcao@arcao.com |
490def642536a3850099c27820461ec1e32a78a7 | 5095bbe94f3af8dc3b14a331519cfee887f4c07e | /apsim/sorghum/source/Dll.cpp | 87fc6a9488fd06246a87bc3370bfd2221bf27ed5 | [] | no_license | sativa/apsim_development | efc2b584459b43c89e841abf93830db8d523b07a | a90ffef3b4ed8a7d0cce1c169c65364be6e93797 | refs/heads/master | 2020-12-24T06:53:59.364336 | 2008-09-17T05:31:07 | 2008-09-17T05:31:07 | 64,154,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,514 | cpp | #include <general\pch.h>
#include <windows.h>
//---------------------------------------------------------------------------
// Important note about DLL memory management when your DLL uses the
// static version of the RunTime Library:
//
// If your DLL exports any functions that pass String objects (or structs/
// classes containing nested Strings) as parameter or function results,
// you will need to add the library MEMMGR.LIB to both the DLL project and
// any other projects that use the DLL. You will also need to use MEMMGR.LIB
// if any other projects which use the DLL will be perfomring new or delete
// operations on any non-TObject-derived classes which are exported from the
// DLL. Adding MEMMGR.LIB to your project will change the DLL and its calling
// EXE's to use the BORLNDMM.DLL as their memory manager. In these cases,
// the file BORLNDMM.DLL should be deployed along with your DLL.
//
// To avoid using BORLNDMM.DLL, pass string information using "char *" or
// ShortString parameters.
//
// If your DLL uses the dynamic version of the RTL, you do not need to
// explicitly add MEMMGR.LIB as this will be done implicitly for you
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void*)
{
return 1;
}
//---------------------------------------------------------------------------
| [
"devoilp@8bb03f63-af10-0410-889a-a89e84ef1bc8"
] | devoilp@8bb03f63-af10-0410-889a-a89e84ef1bc8 |
51bf04cacb55e6bcd6fb6b903f76d400803e8b49 | eaf0c24a620807e1304c4d663a493637a85f6d84 | /server/src/Handle.h | e1019df23f51998a1a17112e3ad233260c77cab5 | [] | no_license | xiaopeifeng/dbproxy | 71f488e61c0a50ffdd74d0e1671cde0eb76cbb78 | 0c972e2db766e6bfd15ad9e98e8867566f41a43c | refs/heads/master | 2021-01-10T01:19:24.529260 | 2016-03-10T14:04:46 | 2016-03-10T14:04:46 | 52,366,310 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 161 | h | #ifndef DBPROXY_HANDLE_H
#define DBPROXY_HANDLE_H
class Handle
{
public:
virtual void handleEvent(int events) = 0;
virtual int getSocket() = 0;
};
#endif
| [
"xiaopeifenng@gmail.com"
] | xiaopeifenng@gmail.com |
a030ff48e97dd2384aba7a00b97def9d7fb8a9a4 | d365896bf974f7108e1aee5c3ed4b43ed38d1dc3 | /src/envelope.pb.h | 8267f70e98e6d50233f9fc8993ad1938baf7c018 | [] | no_license | bbroder/ztest | 1a5be3c2c1dfd5efaef9bcf1575591029e9abb0e | f469901583d9c59e0e4c98b5efd30f0448e64428 | refs/heads/master | 2020-05-27T16:37:50.804956 | 2012-12-20T03:35:18 | 2012-12-20T03:35:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 7,248 | h | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: envelope.proto
#ifndef PROTOBUF_envelope_2eproto__INCLUDED
#define PROTOBUF_envelope_2eproto__INCLUDED
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 2005000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 2005000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
// Internal implementation detail -- do not call these.
void protobuf_AddDesc_envelope_2eproto();
void protobuf_AssignDesc_envelope_2eproto();
void protobuf_ShutdownFile_envelope_2eproto();
class Envelope;
// ===================================================================
class Envelope : public ::google::protobuf::Message {
public:
Envelope();
virtual ~Envelope();
Envelope(const Envelope& from);
inline Envelope& operator=(const Envelope& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const Envelope& default_instance();
void Swap(Envelope* other);
// implements Message ----------------------------------------------
Envelope* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const Envelope& from);
void MergeFrom(const Envelope& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// optional int32 timestamp = 1;
inline bool has_timestamp() const;
inline void clear_timestamp();
static const int kTimestampFieldNumber = 1;
inline ::google::protobuf::int32 timestamp() const;
inline void set_timestamp(::google::protobuf::int32 value);
// optional string ticker = 2;
inline bool has_ticker() const;
inline void clear_ticker();
static const int kTickerFieldNumber = 2;
inline const ::std::string& ticker() const;
inline void set_ticker(const ::std::string& value);
inline void set_ticker(const char* value);
inline void set_ticker(const char* value, size_t size);
inline ::std::string* mutable_ticker();
inline ::std::string* release_ticker();
inline void set_allocated_ticker(::std::string* ticker);
// @@protoc_insertion_point(class_scope:Envelope)
private:
inline void set_has_timestamp();
inline void clear_has_timestamp();
inline void set_has_ticker();
inline void clear_has_ticker();
::google::protobuf::UnknownFieldSet _unknown_fields_;
::std::string* ticker_;
::google::protobuf::int32 timestamp_;
mutable int _cached_size_;
::google::protobuf::uint32 _has_bits_[(2 + 31) / 32];
friend void protobuf_AddDesc_envelope_2eproto();
friend void protobuf_AssignDesc_envelope_2eproto();
friend void protobuf_ShutdownFile_envelope_2eproto();
void InitAsDefaultInstance();
static Envelope* default_instance_;
};
// ===================================================================
// ===================================================================
// Envelope
// optional int32 timestamp = 1;
inline bool Envelope::has_timestamp() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void Envelope::set_has_timestamp() {
_has_bits_[0] |= 0x00000001u;
}
inline void Envelope::clear_has_timestamp() {
_has_bits_[0] &= ~0x00000001u;
}
inline void Envelope::clear_timestamp() {
timestamp_ = 0;
clear_has_timestamp();
}
inline ::google::protobuf::int32 Envelope::timestamp() const {
return timestamp_;
}
inline void Envelope::set_timestamp(::google::protobuf::int32 value) {
set_has_timestamp();
timestamp_ = value;
}
// optional string ticker = 2;
inline bool Envelope::has_ticker() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void Envelope::set_has_ticker() {
_has_bits_[0] |= 0x00000002u;
}
inline void Envelope::clear_has_ticker() {
_has_bits_[0] &= ~0x00000002u;
}
inline void Envelope::clear_ticker() {
if (ticker_ != &::google::protobuf::internal::kEmptyString) {
ticker_->clear();
}
clear_has_ticker();
}
inline const ::std::string& Envelope::ticker() const {
return *ticker_;
}
inline void Envelope::set_ticker(const ::std::string& value) {
set_has_ticker();
if (ticker_ == &::google::protobuf::internal::kEmptyString) {
ticker_ = new ::std::string;
}
ticker_->assign(value);
}
inline void Envelope::set_ticker(const char* value) {
set_has_ticker();
if (ticker_ == &::google::protobuf::internal::kEmptyString) {
ticker_ = new ::std::string;
}
ticker_->assign(value);
}
inline void Envelope::set_ticker(const char* value, size_t size) {
set_has_ticker();
if (ticker_ == &::google::protobuf::internal::kEmptyString) {
ticker_ = new ::std::string;
}
ticker_->assign(reinterpret_cast<const char*>(value), size);
}
inline ::std::string* Envelope::mutable_ticker() {
set_has_ticker();
if (ticker_ == &::google::protobuf::internal::kEmptyString) {
ticker_ = new ::std::string;
}
return ticker_;
}
inline ::std::string* Envelope::release_ticker() {
clear_has_ticker();
if (ticker_ == &::google::protobuf::internal::kEmptyString) {
return NULL;
} else {
::std::string* temp = ticker_;
ticker_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
return temp;
}
}
inline void Envelope::set_allocated_ticker(::std::string* ticker) {
if (ticker_ != &::google::protobuf::internal::kEmptyString) {
delete ticker_;
}
if (ticker) {
set_has_ticker();
ticker_ = ticker;
} else {
clear_has_ticker();
ticker_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
}
}
// @@protoc_insertion_point(namespace_scope)
#ifndef SWIG
namespace google {
namespace protobuf {
} // namespace google
} // namespace protobuf
#endif // SWIG
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_envelope_2eproto__INCLUDED
| [
"bbroder@ballyhoo.(none)"
] | bbroder@ballyhoo.(none) |
7476bfac5e4edd49b3a299abae0aac985ea4faee | c7b8efd6c9c475d5fe3a4cb343392878213e8590 | /test/OpenMP/target_update_depend_codegen.cpp | 6542aa1958d3e3a0a9f7cb6a2447b6766330f27f | [
"NCSA"
] | permissive | tbfleming/cib-clang | 224a6596dde97f2852fd3f30020184173e7c251e | 6bea6f7d496d5fefec598d69c1e797e2617dce19 | refs/heads/master | 2021-09-13T22:36:26.695101 | 2017-12-29T06:39:16 | 2017-12-29T06:39:16 | 113,887,337 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 30,047 | cpp | // RUN: %clang_cc1 -verify -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck %s --check-prefix CK1 --check-prefix CK1-64
// RUN: %clang_cc1 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CK1 --check-prefix CK1-64
// RUN: %clang_cc1 -verify -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -emit-llvm %s -o - | FileCheck %s --check-prefix CK1 --check-prefix CK1-32
// RUN: %clang_cc1 -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ -std=c++11 -triple i386-unknown-unknown -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CK1 --check-prefix CK1-32
// expected-no-diagnostics
// CK1: [[ST:%.+]] = type { i32, double* }
// CK1: %struct.kmp_depend_info = type { i[[sz:64|32]],
// CK1-SAME: i[[sz]], i8 }
#ifndef HEADER
#define HEADER
template <typename T>
struct ST {
T a;
double *b;
};
ST<int> gb;
double gc[100];
// CK1: [[SIZE00:@.+]] = {{.+}}constant [1 x i[[sz]]] [i[[sz]] 800]
// CK1: [[MTYPE00:@.+]] = {{.+}}constant [1 x i64] [i64 34]
// CK1: [[SIZE02:@.+]] = {{.+}}constant [1 x i[[sz]]] [i[[sz]] 4]
// CK1: [[MTYPE02:@.+]] = {{.+}}constant [1 x i64] [i64 33]
// CK1: [[MTYPE03:@.+]] = {{.+}}constant [1 x i64] [i64 34]
// CK1: [[SIZE04:@.+]] = {{.+}}constant [2 x i[[sz]]] [i[[sz]] {{8|4}}, i[[sz]] 24]
// CK1: [[MTYPE04:@.+]] = {{.+}}constant [2 x i64] [i64 33, i64 17]
// CK1-LABEL: _Z3fooi
void foo(int arg) {
int la;
float lb[arg];
// CK1: alloca [1 x %struct.kmp_depend_info],
// CK1: alloca [3 x %struct.kmp_depend_info],
// CK1: alloca [4 x %struct.kmp_depend_info],
// CK1: alloca [5 x %struct.kmp_depend_info],
// Region 00
// CK1: [[BP0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[BP:%.+]], i32 0, i32 0
// CK1: [[BP0_BC:%.+]] = bitcast i8** [[BP0]] to [100 x double]**
// CK1: store [100 x double]* @gc, [100 x double]** [[BP0_BC]],
// CK1: [[P0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[P:%.+]], i32 0, i32 0
// CK1: [[P0_BC:%.+]] = bitcast i8** [[P0]] to [100 x double]**
// CK1: store [100 x double]* @gc, [100 x double]** [[P0_BC]],
// CK1: [[GEPBP0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[BP]], i32 0, i32 0
// CK1: [[GEPP0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[P]], i32 0, i32 0
// CK1: [[CAP_DEVICE:%.+]] = getelementptr inbounds %struct.anon, %struct.anon* [[CAPTURES:%.+]], i32 0, i32 0
// CK1: [[DEVICE:%.+]] = load i32, i32* %{{.+}}
// CK1: store i32 [[DEVICE]], i32* [[CAP_DEVICE]],
// CK1: [[RES:%.+]] = call i8* @__kmpc_omp_task_alloc(%ident_t* {{.+}}, i32 {{.+}}, i32 1, i[[sz]] [[sz]], i[[sz]] 4, i32 (i32, i8*)* bitcast (i32 (i32, %struct.kmp_task_t_with_privates*)* [[TASK_ENTRY0:@.+]] to i32 (i32, i8*)*))
// CK1: [[BC:%.+]] = bitcast i8* [[RES]] to %struct.kmp_task_t_with_privates*
// CK1: [[TASK_T:%.+]] = getelementptr inbounds %struct.kmp_task_t_with_privates, %struct.kmp_task_t_with_privates* [[BC]], i32 0, i32 0
// CK1: [[SHAREDS:%.+]] = getelementptr inbounds %struct.kmp_task_t, %struct.kmp_task_t* [[TASK_T]], i32 0, i32 0
// CK1: [[SHAREDS_REF:%.+]] = load i8*, i8** [[SHAREDS]],
// CK1: [[BC1:%.+]] = bitcast %struct.anon* [[CAPTURES]] to i8*
// CK1: call void @llvm.memcpy.p0i8.p0i8.i[[sz]](i8* [[SHAREDS_REF]], i8* [[BC1]], i[[sz]] 4, i32 4, i1 false)
// CK1: [[PRIVS:%.+]] = getelementptr inbounds %struct.kmp_task_t_with_privates, %struct.kmp_task_t_with_privates* [[BC]], i32 0, i32 1
// CK1: [[PRIVS_BASEPTRS:%.+]] = getelementptr inbounds %struct..kmp_privates.t, %struct..kmp_privates.t* [[PRIVS]], i32 0, i32 0
// CK1: [[BC_PRIVS_BASEPTRS:%.+]] = bitcast [1 x i8*]* [[PRIVS_BASEPTRS]] to i8*
// CK1: [[BC_BASEPTRS:%.+]] = bitcast i8** [[GEPBP0]] to i8*
// CK1: call void @llvm.memcpy.p0i8.p0i8.i[[sz]](i8* [[BC_PRIVS_BASEPTRS]], i8* [[BC_BASEPTRS]], i[[sz]] {{8|4}}, i32 {{8|4}}, i1 false)
// CK1: [[PRIVS_PTRS:%.+]] = getelementptr inbounds %struct..kmp_privates.t, %struct..kmp_privates.t* [[PRIVS]], i32 0, i32 1
// CK1: [[BC_PRIVS_PTRS:%.+]] = bitcast [1 x i8*]* [[PRIVS_PTRS]] to i8*
// CK1: [[BC_PTRS:%.+]] = bitcast i8** [[GEPP0]] to i8*
// CK1: call void @llvm.memcpy.p0i8.p0i8.i[[sz]](i8* [[BC_PRIVS_PTRS]], i8* [[BC_PTRS]], i[[sz]] {{8|4}}, i32 {{8|4}}, i1 false)
// CK1: [[PRIVS_SIZES:%.+]] = getelementptr inbounds %struct..kmp_privates.t, %struct..kmp_privates.t* [[PRIVS]], i32 0, i32 2
// CK1: [[BC_PRIVS_SIZES:%.+]] = bitcast [1 x i[[sz]]]* [[PRIVS_SIZES]] to i8*
// CK1: call void @llvm.memcpy.p0i8.p0i8.i[[sz]](i8* [[BC_PRIVS_SIZES]], i8* bitcast ([1 x i[[sz]]]* [[SIZE00]] to i8*), i[[sz]] {{8|4}}, i32 {{8|4}}, i1 false)
// CK1: [[DEP:%.+]] = getelementptr inbounds [1 x %struct.kmp_depend_info], [1 x %struct.kmp_depend_info]* [[MAIN_DEP:%.+]], i[[sz]] 0, i[[sz]] 0
// CK1: [[DEP_ADR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 0
// CK1: [[BC_ADR:%.+]] = ptrtoint i32* %{{.+}} to i[[sz]]
// CK1: store i[[sz]] [[BC_ADR]], i[[sz]]* [[DEP_ADR]],
// CK1: [[DEP_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 1
// CK1: store i[[sz]] 4, i[[sz]]* [[DEP_SIZE]],
// CK1: [[DEP_ATTRS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 2
// CK1: store i8 1, i8* [[DEP_ATTRS]]
// CK1: [[DEP:%.+]] = getelementptr inbounds [1 x %struct.kmp_depend_info], [1 x %struct.kmp_depend_info]* [[MAIN_DEP]], i32 0, i32 0
// CK1: [[BC:%.+]] = bitcast %struct.kmp_depend_info* [[DEP]] to i8*
// CK1: = call i32 @__kmpc_omp_task_with_deps(%ident_t* @{{.+}}, i32 %{{.+}}, i8* [[RES]], i32 1, i8* [[BC]], i32 0, i8* null)
// CK1: %{{.+}} = add nsw i32 %{{[^,]+}}, 1
#pragma omp target update if(1+3-5) device(arg) from(gc) nowait depend(in: arg)
{++arg;}
// Region 01
// CK1: %{{.+}} = add nsw i32 %{{[^,]+}}, 1
#pragma omp target update to(la) if(1+3-4) depend(in: la) depend(out: arg)
{++arg;}
// Region 02
// CK1: br i1 %{{[^,]+}}, label %[[IFTHEN:[^,]+]], label %[[IFELSE:[^,]+]]
// CK1: [[IFTHEN]]
// CK1: [[BP0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[BP:%.+]], i32 0, i32 0
// CK1: [[BP0_BC:%.+]] = bitcast i8** [[BP0]] to i32**
// CK1: store i32* [[ARG:%.+]], i32** [[BP0_BC]],
// CK1: [[P0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[P:%.+]], i32 0, i32 0
// CK1: [[P0_BC:%.+]] = bitcast i8** [[P0]] to i32**
// CK1: store i32* [[ARG]], i32** [[P0_BC]],
// CK1: [[GEPBP0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[BP]], i32 0, i32 0
// CK1: [[GEPP0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[P]], i32 0, i32 0
// CK1: [[IF_DEVICE:%.+]] = getelementptr inbounds %struct.anon{{.+}}, %struct.anon{{.+}}* [[CAPTURES:%.+]], i32 0, i32 0
// CK1: [[IF:%.+]] = load i8, i8* %{{.+}}
// CK1: [[IF_BOOL:%.+]] = trunc i8 [[IF]] to i1
// CK1: [[IF:%.+]] = zext i1 [[IF_BOOL]] to i8
// CK1: store i8 [[IF]], i8* [[IF_DEVICE]],
// CK1: [[RES:%.+]] = call i8* @__kmpc_omp_task_alloc(%ident_t* {{.+}}, i32 {{.+}}, i32 1, i[[sz]] [[sz]], i[[sz]] 1, i32 (i32, i8*)* bitcast (i32 (i32, %struct.kmp_task_t_with_privates{{.+}}*)* [[TASK_ENTRY2:@.+]] to i32 (i32, i8*)*))
// CK1: [[RES_BC:%.+]] = bitcast i8* [[RES]] to %struct.kmp_task_t_with_privates{{.+}}*
// CK1: [[TASK_T:%.+]] = getelementptr inbounds %struct.kmp_task_t_with_privates{{.+}}, %struct.kmp_task_t_with_privates{{.+}}* [[RES_BC]], i32 0, i32 0
// CK1: [[SHAREDS:%.+]] = getelementptr inbounds %struct.kmp_task_t, %struct.kmp_task_t* [[TASK_T]], i32 0, i32 0
// CK1: [[SHAREDS_REF:%.+]] = load i8*, i8** [[SHAREDS]],
// CK1: [[BC1:%.+]] = bitcast %struct.anon{{.+}}* [[CAPTURES]] to i8*
// CK1: call void @llvm.memcpy.p0i8.p0i8.i[[sz]](i8* [[SHAREDS_REF]], i8* [[BC1]], i[[sz]] 1, i32 1, i1 false)
// CK1: [[PRIVS:%.+]] = getelementptr inbounds %struct.kmp_task_t_with_privates{{.+}}, %struct.kmp_task_t_with_privates{{.+}}* [[RES_BC]], i32 0, i32 1
// CK1: [[PRIVS_BASEPTRS:%.+]] = getelementptr inbounds %struct..kmp_privates.t{{.+}}, %struct..kmp_privates.t{{.+}}* [[PRIVS]], i32 0, i32 0
// CK1: [[BC_PRIVS_BASEPTRS:%.+]] = bitcast [1 x i8*]* [[PRIVS_BASEPTRS]] to i8*
// CK1: [[BC_BASEPTRS:%.+]] = bitcast i8** [[GEPBP0]] to i8*
// CK1: call void @llvm.memcpy.p0i8.p0i8.i[[sz]](i8* [[BC_PRIVS_BASEPTRS]], i8* [[BC_BASEPTRS]], i[[sz]] {{8|4}}, i32 {{8|4}}, i1 false)
// CK1: [[PRIVS_PTRS:%.+]] = getelementptr inbounds %struct..kmp_privates.t{{.+}}, %struct..kmp_privates.t{{.+}}* [[PRIVS]], i32 0, i32 1
// CK1: [[BC_PRIVS_PTRS:%.+]] = bitcast [1 x i8*]* [[PRIVS_PTRS]] to i8*
// CK1: [[BC_PTRS:%.+]] = bitcast i8** [[GEPP0]] to i8*
// CK1: call void @llvm.memcpy.p0i8.p0i8.i[[sz]](i8* [[BC_PRIVS_PTRS]], i8* [[BC_PTRS]], i[[sz]] {{8|4}}, i32 {{8|4}}, i1 false)
// CK1: [[PRIVS_SIZES:%.+]] = getelementptr inbounds %struct..kmp_privates.t{{.+}}, %struct..kmp_privates.t{{.+}}* [[PRIVS]], i32 0, i32 2
// CK1: [[BC_PRIVS_SIZES:%.+]] = bitcast [1 x i[[sz]]]* [[PRIVS_SIZES]] to i8*
// CK1: call void @llvm.memcpy.p0i8.p0i8.i[[sz]](i8* [[BC_PRIVS_SIZES]], i8* bitcast ([1 x i[[sz]]]* [[SIZE02]] to i8*), i[[sz]] {{8|4}}, i32 {{8|4}}, i1 false)
// CK1: [[DEP:%.+]] = getelementptr inbounds [3 x %struct.kmp_depend_info], [3 x %struct.kmp_depend_info]* [[MAIN_DEP:%.+]], i[[sz]] 0, i[[sz]] 0
// CK1: [[DEP_ADR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 0
// CK1: [[BC_ADR:%.+]] = ptrtoint i32* %{{.+}} to i[[sz]]
// CK1: store i[[sz]] [[BC_ADR]], i[[sz]]* [[DEP_ADR]],
// CK1: [[DEP_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 1
// CK1: store i[[sz]] 4, i[[sz]]* [[DEP_SIZE]],
// CK1: [[DEP_ATTRS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 2
// CK1: store i8 3, i8* [[DEP_ATTRS]]
// CK1: [[DEP:%.+]] = getelementptr inbounds [3 x %struct.kmp_depend_info], [3 x %struct.kmp_depend_info]* [[MAIN_DEP]], i[[sz]] 0, i[[sz]] 1
// CK1: [[DEP_ADR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 0
// CK1: [[BC_ADR:%.+]] = ptrtoint i32* %{{.+}} to i[[sz]]
// CK1: store i[[sz]] [[BC_ADR]], i[[sz]]* [[DEP_ADR]],
// CK1: [[DEP_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 1
// CK1: store i[[sz]] 4, i[[sz]]* [[DEP_SIZE]],
// CK1: [[DEP_ATTRS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 2
// CK1: store i8 3, i8* [[DEP_ATTRS]]
// CK1: [[DEP:%.+]] = getelementptr inbounds [3 x %struct.kmp_depend_info], [3 x %struct.kmp_depend_info]* [[MAIN_DEP]], i[[sz]] 0, i[[sz]] 2
// CK1: [[DEP_ADR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 0
// CK1: store i[[sz]] ptrtoint ([100 x double]* @gc to i[[sz]]), i[[sz]]* [[DEP_ADR]],
// CK1: [[DEP_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 1
// CK1: store i[[sz]] 800, i[[sz]]* [[DEP_SIZE]],
// CK1: [[DEP_ATTRS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 2
// CK1: store i8 3, i8* [[DEP_ATTRS]]
// CK1: [[DEP:%.+]] = getelementptr inbounds [3 x %struct.kmp_depend_info], [3 x %struct.kmp_depend_info]* [[MAIN_DEP]], i32 0, i32 0
// CK1: [[BC:%.+]] = bitcast %struct.kmp_depend_info* [[DEP]] to i8*
// CK1: call void @__kmpc_omp_wait_deps(%ident_t* @{{.+}}, i32 %{{.+}}, i32 3, i8* [[BC]], i32 0, i8* null)
// CK1: call void @__kmpc_omp_task_begin_if0(%ident_t* @{{.+}}, i32 %{{.+}}, i8* [[RES]])
// CK1: = call i32 [[TASK_ENTRY2]](i32 %{{.+}}, %struct.kmp_task_t_with_privates{{.+}}* [[RES_BC]])
// CK1: call void @__kmpc_omp_task_complete_if0(%ident_t* @{{.+}}, i32 %{{.+}}, i8* [[RES]])
// CK1: br label %[[IFEND:[^,]+]]
// CK1: [[IFELSE]]
// CK1: br label %[[IFEND]]
// CK1: [[IFEND]]
// CK1: %{{.+}} = add nsw i32 %{{[^,]+}}, 1
#pragma omp target update to(arg) if(arg) device(4) depend(inout: arg, la, gc)
{++arg;}
// CK1: %{{.+}} = add nsw i32 %{{[^,]+}}, 1
{++arg;}
// Region 03
// CK1: [[BP0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[BP:%.+]], i32 0, i32 0
// CK1: [[BP0_BC:%.+]] = bitcast i8** [[BP0]] to float**
// CK1: store float* [[VLA:%.+]], float** [[BP0_BC]],
// CK1: [[P0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[P:%.+]], i32 0, i32 0
// CK1: [[P0_BC:%.+]] = bitcast i8** [[P0]] to float**
// CK1: store float* [[VLA]], float** [[P0_BC]],
// CK1: [[S0:%.+]] = getelementptr inbounds [1 x i[[sz]]], [1 x i[[sz]]]* [[S:%.+]], i32 0, i32 0
// CK1: store i[[sz]] {{.+}}, i[[sz]]* [[S0]],
// CK1: [[GEPBP0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[BP]], i32 0, i32 0
// CK1: [[GEPP0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[P]], i32 0, i32 0
// CK1: [[GEPS0:%.+]] = getelementptr inbounds [1 x i[[sz]]], [1 x i[[sz]]]* [[S]], i32 0, i32 0
// CK1: [[RES:%.+]] = call i8* @__kmpc_omp_task_alloc(%ident_t* {{.+}}, i32 {{.+}}, i32 1, i[[sz]] [[sz]], i[[sz]] 1, i32 (i32, i8*)* bitcast (i32 (i32, %struct.kmp_task_t_with_privates{{.+}}*)* [[TASK_ENTRY3:@.+]] to i32 (i32, i8*)*))
// CK1: [[RES_BC:%.+]] = bitcast i8* [[RES]] to %struct.kmp_task_t_with_privates{{.+}}*
// CK1: [[TASK_T:%.+]] = getelementptr inbounds %struct.kmp_task_t_with_privates{{.+}}, %struct.kmp_task_t_with_privates{{.+}}* [[RES_BC]], i32 0, i32 0
// CK1: [[PRIVS:%.+]] = getelementptr inbounds %struct.kmp_task_t_with_privates{{.+}}, %struct.kmp_task_t_with_privates{{.+}}* [[RES_BC]], i32 0, i32 1
// CK1: [[PRIVS_BASEPTRS:%.+]] = getelementptr inbounds %struct..kmp_privates.t{{.+}}, %struct..kmp_privates.t{{.+}}* [[PRIVS]], i32 0, i32 0
// CK1: [[BC_PRIVS_BASEPTRS:%.+]] = bitcast [1 x i8*]* [[PRIVS_BASEPTRS]] to i8*
// CK1: [[BC_BASEPTRS:%.+]] = bitcast i8** [[GEPBP0]] to i8*
// CK1: call void @llvm.memcpy.p0i8.p0i8.i[[sz]](i8* [[BC_PRIVS_BASEPTRS]], i8* [[BC_BASEPTRS]], i[[sz]] {{8|4}}, i32 {{8|4}}, i1 false)
// CK1: [[PRIVS_PTRS:%.+]] = getelementptr inbounds %struct..kmp_privates.t{{.+}}, %struct..kmp_privates.t{{.+}}* [[PRIVS]], i32 0, i32 1
// CK1: [[BC_PRIVS_PTRS:%.+]] = bitcast [1 x i8*]* [[PRIVS_PTRS]] to i8*
// CK1: [[BC_PTRS:%.+]] = bitcast i8** [[GEPP0]] to i8*
// CK1: call void @llvm.memcpy.p0i8.p0i8.i[[sz]](i8* [[BC_PRIVS_PTRS]], i8* [[BC_PTRS]], i[[sz]] {{8|4}}, i32 {{8|4}}, i1 false)
// CK1: [[PRIVS_SIZES:%.+]] = getelementptr inbounds %struct..kmp_privates.t{{.+}}, %struct..kmp_privates.t{{.+}}* [[PRIVS]], i32 0, i32 2
// CK1: [[BC_PRIVS_SIZES:%.+]] = bitcast [1 x i[[sz]]]* [[PRIVS_SIZES]] to i8*
// CK1: [[BC_SIZES:%.+]] = bitcast i[[sz]]* [[GEPS0]] to i8*
// CK1: call void @llvm.memcpy.p0i8.p0i8.i[[sz]](i8* [[BC_PRIVS_SIZES]], i8* [[BC_SIZES]], i[[sz]] {{8|4}}, i32 {{8|4}}, i1 false)
// CK1: [[DEP:%.+]] = getelementptr inbounds [4 x %struct.kmp_depend_info], [4 x %struct.kmp_depend_info]* [[MAIN_DEP:%.+]], i[[sz]] 0, i[[sz]] 0
// CK1: [[DEP_ADR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 0
// CK1: [[BC_ADR:%.+]] = ptrtoint float* %{{.+}} to i[[sz]]
// CK1: store i[[sz]] [[BC_ADR]], i[[sz]]* [[DEP_ADR]],
// CK1: [[DEP_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 1
// CK1: store i[[sz]] %{{.+}}, i[[sz]]* [[DEP_SIZE]],
// CK1: [[DEP_ATTRS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 2
// CK1: store i8 3, i8* [[DEP_ATTRS]]
// CK1: [[DEP:%.+]] = getelementptr inbounds [4 x %struct.kmp_depend_info], [4 x %struct.kmp_depend_info]* [[MAIN_DEP]], i[[sz]] 0, i[[sz]] 1
// CK1: [[DEP_ADR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 0
// CK1: [[BC_ADR:%.+]] = ptrtoint i32* %{{.+}} to i[[sz]]
// CK1: store i[[sz]] [[BC_ADR]], i[[sz]]* [[DEP_ADR]],
// CK1: [[DEP_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 1
// CK1: store i[[sz]] 4, i[[sz]]* [[DEP_SIZE]],
// CK1: [[DEP_ATTRS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 2
// CK1: store i8 3, i8* [[DEP_ATTRS]]
// CK1: [[DEP:%.+]] = getelementptr inbounds [4 x %struct.kmp_depend_info], [4 x %struct.kmp_depend_info]* [[MAIN_DEP]], i[[sz]] 0, i[[sz]] 2
// CK1: [[DEP_ADR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 0
// CK1: [[BC_ADR:%.+]] = ptrtoint i32* %{{.+}} to i[[sz]]
// CK1: store i[[sz]] [[BC_ADR]], i[[sz]]* [[DEP_ADR]],
// CK1: [[DEP_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 1
// CK1: store i[[sz]] 4, i[[sz]]* [[DEP_SIZE]],
// CK1: [[DEP_ATTRS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 2
// CK1: store i8 3, i8* [[DEP_ATTRS]]
// CK1: [[DEP:%.+]] = getelementptr inbounds [4 x %struct.kmp_depend_info], [4 x %struct.kmp_depend_info]* [[MAIN_DEP]], i[[sz]] 0, i[[sz]] 3
// CK1: [[DEP_ADR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 0
// CK1: store i[[sz]] ptrtoint ([100 x double]* @gc to i[[sz]]), i[[sz]]* [[DEP_ADR]],
// CK1: [[DEP_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 1
// CK1: store i[[sz]] 800, i[[sz]]* [[DEP_SIZE]],
// CK1: [[DEP_ATTRS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 2
// CK1: store i8 3, i8* [[DEP_ATTRS]]
// CK1: [[DEP:%.+]] = getelementptr inbounds [4 x %struct.kmp_depend_info], [4 x %struct.kmp_depend_info]* [[MAIN_DEP]], i32 0, i32 0
// CK1: [[BC:%.+]] = bitcast %struct.kmp_depend_info* [[DEP]] to i8*
// CK1: call void @__kmpc_omp_wait_deps(%ident_t* @{{.+}}, i32 %{{.+}}, i32 4, i8* [[BC]], i32 0, i8* null)
// CK1: call void @__kmpc_omp_task_begin_if0(%ident_t* @{{.+}}, i32 %{{.+}}, i8* [[RES]])
// CK1: = call i32 [[TASK_ENTRY3]](i32 %{{.+}}, %struct.kmp_task_t_with_privates{{.+}}* [[RES_BC]])
// CK1: call void @__kmpc_omp_task_complete_if0(%ident_t* @{{.+}}, i32 %{{.+}}, i8* [[RES]])
#pragma omp target update from(lb) depend(out: lb, arg, la, gc)
{++arg;}
// CK1: %{{.+}} = add nsw i32 %{{[^,]+}}, 1
{++arg;}
// Region 04
// CK1: [[BP0:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[BP:%.+]], i32 0, i32 0
// CK1: [[BP0_BC:%.+]] = bitcast i8** [[BP0]] to %struct.ST**
// CK1: store %struct.ST* @gb, %struct.ST** [[BP0_BC]],
// CK1: [[P0:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[P:%.+]], i32 0, i32 0
// CK1: [[P0_BC:%.+]] = bitcast i8** [[P0]] to double***
// CK1: store double** getelementptr inbounds (%struct.ST, %struct.ST* @gb, i32 0, i32 1), double*** [[P0_BC]],
// CK1: [[BP1:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[BP]], i32 0, i32 1
// CK1: [[BP1_BC:%.+]] = bitcast i8** [[BP1]] to double***
// CK1: store double** getelementptr inbounds (%struct.ST, %struct.ST* @gb, i32 0, i32 1), double*** [[BP1_BC]],
// CK1: [[P1:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[P]], i32 0, i32 1
// CK1: [[P1_BC:%.+]] = bitcast i8** [[P1]] to double**
// CK1: store double* %{{.+}}, double** [[P1_BC]],
// CK1: [[GEPBP0:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[BP]], i32 0, i32 0
// CK1: [[GEPP0:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[P]], i32 0, i32 0
// CK1: [[RES:%.+]] = call i8* @__kmpc_omp_task_alloc(%ident_t* {{.+}}, i32 {{.+}}, i32 1, i[[sz]] {{88|44}}, i[[sz]] 1, i32 (i32, i8*)* bitcast (i32 (i32, %struct.kmp_task_t_with_privates{{.+}}*)* [[TASK_ENTRY4:@.+]] to i32 (i32, i8*)*))
// CK1: [[RES_BC:%.+]] = bitcast i8* [[RES]] to %struct.kmp_task_t_with_privates{{.+}}*
// CK1: [[TASK_T:%.+]] = getelementptr inbounds %struct.kmp_task_t_with_privates{{.+}}, %struct.kmp_task_t_with_privates{{.+}}* [[RES_BC]], i32 0, i32 0
// CK1: [[PRIVS:%.+]] = getelementptr inbounds %struct.kmp_task_t_with_privates{{.+}}, %struct.kmp_task_t_with_privates{{.+}}* [[RES_BC]], i32 0, i32 1
// CK1: [[PRIVS_BASEPTRS:%.+]] = getelementptr inbounds %struct..kmp_privates.t{{.+}}, %struct..kmp_privates.t{{.+}}* [[PRIVS]], i32 0, i32 0
// CK1: [[BC_PRIVS_BASEPTRS:%.+]] = bitcast [2 x i8*]* [[PRIVS_BASEPTRS]] to i8*
// CK1: [[BC_BASEPTRS:%.+]] = bitcast i8** [[GEPBP0]] to i8*
// CK1: call void @llvm.memcpy.p0i8.p0i8.i[[sz]](i8* [[BC_PRIVS_BASEPTRS]], i8* [[BC_BASEPTRS]], i[[sz]] {{16|8}}, i32 {{8|4}}, i1 false)
// CK1: [[PRIVS_PTRS:%.+]] = getelementptr inbounds %struct..kmp_privates.t{{.+}}, %struct..kmp_privates.t{{.+}}* [[PRIVS]], i32 0, i32 1
// CK1: [[BC_PRIVS_PTRS:%.+]] = bitcast [2 x i8*]* [[PRIVS_PTRS]] to i8*
// CK1: [[BC_PTRS:%.+]] = bitcast i8** [[GEPP0]] to i8*
// CK1: call void @llvm.memcpy.p0i8.p0i8.i[[sz]](i8* [[BC_PRIVS_PTRS]], i8* [[BC_PTRS]], i[[sz]] {{16|8}}, i32 {{8|4}}, i1 false)
// CK1: [[PRIVS_SIZES:%.+]] = getelementptr inbounds %struct..kmp_privates.t{{.+}}, %struct..kmp_privates.t{{.+}}* [[PRIVS]], i32 0, i32 2
// CK1: [[BC_PRIVS_SIZES:%.+]] = bitcast [2 x i[[sz]]]* [[PRIVS_SIZES]] to i8*
// CK1: call void @llvm.memcpy.p0i8.p0i8.i[[sz]](i8* [[BC_PRIVS_SIZES]], i8* bitcast ([2 x i[[sz]]]* [[SIZE04]] to i8*), i[[sz]] {{16|8}}, i32 {{8|4}}, i1 false)
// CK1: [[DEP:%.+]] = getelementptr inbounds [5 x %struct.kmp_depend_info], [5 x %struct.kmp_depend_info]* [[MAIN_DEP:%.+]], i[[sz]] 0, i[[sz]] 0
// CK1: [[DEP_ADR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 0
// CK1: [[BC_ADR:%.+]] = ptrtoint double* %{{.+}} to i[[sz]]
// CK1: store i[[sz]] [[BC_ADR]], i[[sz]]* [[DEP_ADR]],
// CK1: [[DEP_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 1
// CK1: store i[[sz]] %{{.+}}, i[[sz]]* [[DEP_SIZE]],
// CK1: [[DEP_ATTRS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 2
// CK1: store i8 1, i8* [[DEP_ATTRS]]
// CK1: [[DEP:%.+]] = getelementptr inbounds [5 x %struct.kmp_depend_info], [5 x %struct.kmp_depend_info]* [[MAIN_DEP]], i[[sz]] 0, i[[sz]] 1
// CK1: [[DEP_ADR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 0
// CK1: [[BC_ADR:%.+]] = ptrtoint i32* %{{.+}} to i[[sz]]
// CK1: store i[[sz]] [[BC_ADR]], i[[sz]]* [[DEP_ADR]],
// CK1: [[DEP_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 1
// CK1: store i[[sz]] 4, i[[sz]]* [[DEP_SIZE]],
// CK1: [[DEP_ATTRS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 2
// CK1: store i8 1, i8* [[DEP_ATTRS]]
// CK1: [[DEP:%.+]] = getelementptr inbounds [5 x %struct.kmp_depend_info], [5 x %struct.kmp_depend_info]* [[MAIN_DEP]], i[[sz]] 0, i[[sz]] 2
// CK1: [[DEP_ADR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 0
// CK1: [[BC_ADR:%.+]] = ptrtoint float* %{{.+}} to i[[sz]]
// CK1: store i[[sz]] [[BC_ADR]], i[[sz]]* [[DEP_ADR]],
// CK1: [[DEP_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 1
// CK1: store i[[sz]] %{{.+}}, i[[sz]]* [[DEP_SIZE]],
// CK1: [[DEP_ATTRS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 2
// CK1: store i8 1, i8* [[DEP_ATTRS]]
// CK1: [[DEP:%.+]] = getelementptr inbounds [5 x %struct.kmp_depend_info], [5 x %struct.kmp_depend_info]* [[MAIN_DEP]], i[[sz]] 0, i[[sz]] 3
// CK1: [[DEP_ADR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 0
// CK1: store i[[sz]] ptrtoint ([100 x double]* @gc to i[[sz]]), i[[sz]]* [[DEP_ADR]],
// CK1: [[DEP_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 1
// CK1: store i[[sz]] 800, i[[sz]]* [[DEP_SIZE]],
// CK1: [[DEP_ATTRS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 2
// CK1: store i8 1, i8* [[DEP_ATTRS]]
// CK1: [[DEP:%.+]] = getelementptr inbounds [5 x %struct.kmp_depend_info], [5 x %struct.kmp_depend_info]* [[MAIN_DEP]], i[[sz]] 0, i[[sz]] 4
// CK1: [[DEP_ADR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 0
// CK1: [[BC_ADR:%.+]] = ptrtoint i32* %{{.+}} to i[[sz]]
// CK1: store i[[sz]] [[BC_ADR]], i[[sz]]* [[DEP_ADR]],
// CK1: [[DEP_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 1
// CK1: store i[[sz]] 4, i[[sz]]* [[DEP_SIZE]],
// CK1: [[DEP_ATTRS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEP]], i32 0, i32 2
// CK1: store i8 1, i8* [[DEP_ATTRS]]
// CK1: [[DEP:%.+]] = getelementptr inbounds [5 x %struct.kmp_depend_info], [5 x %struct.kmp_depend_info]* [[MAIN_DEP]], i32 0, i32 0
// CK1: [[BC:%.+]] = bitcast %struct.kmp_depend_info* [[DEP]] to i8*
// CK1: call void @__kmpc_omp_wait_deps(%ident_t* @{{.+}}, i32 %{{.+}}, i32 5, i8* [[BC]], i32 0, i8* null)
// CK1: call void @__kmpc_omp_task_begin_if0(%ident_t* @{{.+}}, i32 %{{.+}}, i8* [[RES]])
// CK1: = call i32 [[TASK_ENTRY4]](i32 %{{.+}}, %struct.kmp_task_t_with_privates{{.+}}* [[RES_BC]])
// CK1: call void @__kmpc_omp_task_complete_if0(%ident_t* @{{.+}}, i32 %{{.+}}, i8* [[RES]])
#pragma omp target update to(gb.b[:3]) depend(in: gb.b[:3], la, lb, gc, arg)
{++arg;}
}
// CK1: define internal{{.*}} i32 [[TASK_ENTRY0]](i32{{.*}}, %struct.kmp_task_t_with_privates* noalias)
// CK1-DAG: call void @__tgt_target_data_update_nowait(i64 [[DEV:%[^,]+]], i32 1, i8** [[GEPBP:%.+]], i8** [[GEPP:%.+]], i[[sz]]* [[GEPS:%.+]], {{.+}}getelementptr {{.+}}[1 x i{{.+}}]* [[MTYPE00]]{{.+}})
// CK1-DAG: [[DEV]] = sext i32 [[DEVi32:%[^,]+]] to i64
// CK1-DAG: [[DEVi32]] = load i32, i32* %{{[^,]+}},
// CK1-DAG: [[GEPBP]] = getelementptr inbounds {{.+}}[[BP:%[^,]+]]
// CK1-DAG: [[GEPP]] = getelementptr inbounds {{.+}}[[P:%[^,]+]]
// CK1-DAG: [[GEPS]] = getelementptr inbounds {{.+}}[[S:%[^,]+]]
// CK1-DAG: [[BP]] = load [1 x i8*]*, [1 x i8*]** [[BP_PRIV:%.+]],
// CK1-DAG: [[P]] = load [1 x i8*]*, [1 x i8*]** [[P_PRIV:%.+]],
// CK1-DAG: [[S]] = load [1 x i[[sz]]]*, [1 x i[[sz]]]** [[S_PRIV:%.+]],
// CK1-DAG: call void (i8*, ...) %{{.+}}(i8* %{{[^,]+}}, [1 x i8*]** [[BP_PRIV]], [1 x i8*]** [[P_PRIV]], [1 x i[[sz]]]** [[S_PRIV]])
// CK1: ret i32 0
// CK1: }
// CK1: define internal{{.*}} i32 [[TASK_ENTRY2]](i32{{.*}}, %struct.kmp_task_t_with_privates{{.+}}* noalias)
// CK1-DAG: call void @__tgt_target_data_update(i64 4, i32 1, i8** [[GEPBP:%.+]], i8** [[GEPP:%.+]], i[[sz]]* [[GEPS:%.+]], {{.+}}getelementptr {{.+}}[1 x i{{.+}}]* [[MTYPE02]]{{.+}})
// CK1-DAG: [[GEPBP]] = getelementptr inbounds {{.+}}[[BP:%[^,]+]]
// CK1-DAG: [[GEPP]] = getelementptr inbounds {{.+}}[[P:%[^,]+]]
// CK1-DAG: [[GEPS]] = getelementptr inbounds {{.+}}[[S:%[^,]+]]
// CK1-DAG: [[BP]] = load [1 x i8*]*, [1 x i8*]** [[BP_PRIV:%.+]],
// CK1-DAG: [[P]] = load [1 x i8*]*, [1 x i8*]** [[P_PRIV:%.+]],
// CK1-DAG: [[S]] = load [1 x i[[sz]]]*, [1 x i[[sz]]]** [[S_PRIV:%.+]],
// CK1-DAG: call void (i8*, ...) %{{.+}}(i8* %{{[^,]+}}, [1 x i8*]** [[BP_PRIV]], [1 x i8*]** [[P_PRIV]], [1 x i[[sz]]]** [[S_PRIV]])
// CK1: ret i32 0
// CK1: }
// CK1: define internal{{.*}} i32 [[TASK_ENTRY3]](i32{{.*}}, %struct.kmp_task_t_with_privates{{.+}}* noalias)
// CK1-DAG: call void @__tgt_target_data_update(i64 -1, i32 1, i8** [[GEPBP:%.+]], i8** [[GEPP:%.+]], i[[sz]]* [[GEPS:%.+]], {{.+}}getelementptr {{.+}}[1 x i{{.+}}]* [[MTYPE03]]{{.+}})
// CK1-DAG: [[GEPBP]] = getelementptr inbounds {{.+}}[[BP:%[^,]+]]
// CK1-DAG: [[GEPP]] = getelementptr inbounds {{.+}}[[P:%[^,]+]]
// CK1-DAG: [[GEPS]] = getelementptr inbounds {{.+}}[[S:%[^,]+]]
// CK1-DAG: [[BP]] = load [1 x i8*]*, [1 x i8*]** [[BP_PRIV:%.+]],
// CK1-DAG: [[P]] = load [1 x i8*]*, [1 x i8*]** [[P_PRIV:%.+]],
// CK1-DAG: [[S]] = load [1 x i[[sz]]]*, [1 x i[[sz]]]** [[S_PRIV:%.+]],
// CK1-DAG: call void (i8*, ...) %{{.+}}(i8* %{{[^,]+}}, [1 x i8*]** [[BP_PRIV]], [1 x i8*]** [[P_PRIV]], [1 x i[[sz]]]** [[S_PRIV]])
// CK1-NOT: __tgt_target_data_end
// CK1: ret i32 0
// CK1: }
// CK1: define internal{{.*}} i32 [[TASK_ENTRY4]](i32{{.*}}, %struct.kmp_task_t_with_privates{{.+}}* noalias)
// CK1-DAG: call void @__tgt_target_data_update(i64 -1, i32 2, i8** [[GEPBP:%.+]], i8** [[GEPP:%.+]], i[[sz]]* [[GEPS:%.+]], {{.+}}getelementptr {{.+}}[2 x i{{.+}}]* [[MTYPE04]]{{.+}})
// CK1-DAG: [[GEPBP]] = getelementptr inbounds {{.+}}[[BP:%[^,]+]]
// CK1-DAG: [[GEPP]] = getelementptr inbounds {{.+}}[[P:%[^,]+]]
// CK1-DAG: [[GEPS]] = getelementptr inbounds {{.+}}[[S:%[^,]+]]
// CK1-DAG: [[BP]] = load [2 x i8*]*, [2 x i8*]** [[BP_PRIV:%.+]],
// CK1-DAG: [[P]] = load [2 x i8*]*, [2 x i8*]** [[P_PRIV:%.+]],
// CK1-DAG: [[S]] = load [2 x i[[sz]]]*, [2 x i[[sz]]]** [[S_PRIV:%.+]],
// CK1-DAG: call void (i8*, ...) %{{.+}}(i8* %{{[^,]+}}, [2 x i8*]** [[BP_PRIV]], [2 x i8*]** [[P_PRIV]], [2 x i[[sz]]]** [[S_PRIV]])
// CK1-NOT: __tgt_target_data_end
// CK1: ret i32 0
// CK1: }
#endif
| [
"a.bataev@hotmail.com"
] | a.bataev@hotmail.com |
a30a59c902584b335408484c062aa92d3a1abce4 | 79ea992982bb2263e9b0aa014a066d2cabeb1637 | /libraries/chain/include/muse/chain/get_config.hpp | 1d903c86fe30eabbdce6122a60d54d99fc946d8c | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | soundac/SounDAC-Source | bc71f1d9aef261706ad98b07809a9a70ed6508ac | 56bf367c1ac78fd71d16efd63affa5c293c674f7 | refs/heads/master | 2021-06-02T12:42:56.038961 | 2021-01-23T15:16:27 | 2021-01-23T15:16:27 | 145,311,239 | 2 | 7 | NOASSERTION | 2021-01-23T15:16:29 | 2018-08-19T14:40:31 | C++ | UTF-8 | C++ | false | false | 137 | hpp | #pragma once
#include <fc/variant_object.hpp>
namespace muse { namespace chain {
fc::variant_object get_config();
} } // muse::chain
| [
"nmzl.gabriel@gmail.com"
] | nmzl.gabriel@gmail.com |
7711c9b6b6205e0a536b9ef3d21252aaa16c64f9 | 93f6e0e44e9063d02e6c44faae184f83681e67b5 | /includes/SatHelper/differentialencoding.h | ca374914b8a80d214bcb414affbeb0064151ce88 | [
"MIT"
] | permissive | opensatelliteproject/libsathelper | b3c43bfbd7dda79cfac40601137c4f47121b535f | 0c5ee163b540539ed5a5d2a0053b45d4485b0bba | refs/heads/master | 2021-01-11T20:08:17.970458 | 2020-12-13T20:50:30 | 2020-12-13T20:50:30 | 79,047,302 | 42 | 12 | MIT | 2018-06-04T05:33:13 | 2017-01-15T17:22:32 | C++ | UTF-8 | C++ | false | false | 386 | h | /*
* DifferentialDecoder.h
*
* Created on: 25/01/2017
* Author: Lucas Teske
*/
#ifndef SRC_DIFFERENTIALDECODER_H_
#define SRC_DIFFERENTIALDECODER_H_
#include <cstdint>
namespace SatHelper {
class DifferentialEncoding {
public:
static void nrzmDecode(uint8_t *data, int length);
};
} /* namespace SatHelper */
#endif /* SRC_DIFFERENTIALDECODER_H_ */
| [
"lucas@teske.net.br"
] | lucas@teske.net.br |
1d2ff2f900180fed225805b45063a59d13202149 | d4939983e7cba16bdd754e032c1a5fe3d6205bb4 | /src/lib/hover_thrust_estimator/hover_thrust_estimator.hpp | 2c4aaf6519eaa6ddf1acc8d26b5f10aa5fc6ece4 | [
"BSD-3-Clause"
] | permissive | Saru-1/Firmware | 494af6e64a08a40b642f185a15315b530cbc1f5e | d9ae242760b5b95113ad3b2b243e78093248e83e | refs/heads/master | 2021-01-25T22:33:10.783694 | 2020-02-26T07:33:38 | 2020-02-26T07:44:20 | 243,205,561 | 1 | 0 | BSD-3-Clause | 2020-02-26T08:10:45 | 2020-02-26T08:10:44 | null | UTF-8 | C++ | false | false | 3,170 | hpp | /****************************************************************************
*
* Copyright (c) 2020 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file hover_thrust_estimator.hpp
* @brief Interface class for a hover thrust estimator
* Convention is positive thrust, hover thrust and acceleration UP
*
* @author Mathieu Bresciani <brescianimathieu@gmail.com>
*/
#pragma once
#include <px4_platform_common/module_params.h>
#include <uORB/Publication.hpp>
#include <uORB/topics/hover_thrust_estimate.h>
#include <drivers/drv_hrt.h>
#include "zero_order_hover_thrust_ekf.hpp"
class HoverThrustEstimator : public ModuleParams
{
public:
HoverThrustEstimator(ModuleParams *parent) :
ModuleParams(parent)
{
ZeroOrderHoverThrustEkf::status status{};
publishStatus(status);
}
~HoverThrustEstimator() = default;
void reset();
void update(float dt);
void setThrust(float thrust) { _thrust = thrust; };
void setAccel(float accel) { _acc_z = accel; };
float getHoverThrustEstimate() const { return _hover_thrust_ekf.getHoverThrustEstimate(); }
protected:
void updateParams() override;
private:
void publishStatus(ZeroOrderHoverThrustEkf::status &status);
ZeroOrderHoverThrustEkf _hover_thrust_ekf{};
float _acc_z{};
float _thrust{};
DEFINE_PARAMETERS(
(ParamFloat<px4::params::HTE_HT_NOISE>) _param_hte_ht_noise,
(ParamFloat<px4::params::HTE_ACC_GATE>) _param_hte_acc_gate,
(ParamFloat<px4::params::HTE_HT_ERR_INIT>) _param_hte_ht_err_init
)
uORB::Publication<hover_thrust_estimate_s> _hover_thrust_ekf_pub{ORB_ID(hover_thrust_estimate)};
};
| [
"brescianimathieu@gmail.com"
] | brescianimathieu@gmail.com |
e624f4ad5612b374a7defa855b0ecac33d1517ec | a84edc307452519e101093c96861fe269b965be0 | /src/script.cpp | 71fbc39cf8c60f5e65e239f9f5327009a102e4ec | [
"MIT"
] | permissive | zebbra2014/rublebit | d339ae3063b6b1b19c49da4eccfe946657a10406 | 39bb89fa7186a4782ae1d1856d17067f243c8f89 | refs/heads/master | 2021-01-17T17:20:30.606553 | 2015-11-12T08:12:55 | 2015-11-12T08:12:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 65,564 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The RubleBit developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/foreach.hpp>
#include <boost/tuple/tuple.hpp>
using namespace std;
using namespace boost;
#include "script.h"
#include "keystore.h"
#include "bignum.h"
#include "key.h"
#include "main.h"
#include "sync.h"
#include "util.h"
bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, int flags);
typedef vector<unsigned char> valtype;
static const valtype vchFalse(0);
static const valtype vchZero(0);
static const valtype vchTrue(1, 1);
static const CBigNum bnZero(0);
static const CBigNum bnOne(1);
static const CBigNum bnFalse(0);
static const CBigNum bnTrue(1);
static const size_t nMaxNumSize = 4;
CBigNum CastToBigNum(const valtype& vch)
{
if (vch.size() > nMaxNumSize)
throw runtime_error("CastToBigNum() : overflow");
// Get rid of extra leading zeros
return CBigNum(CBigNum(vch).getvch());
}
bool CastToBool(const valtype& vch)
{
for (unsigned int i = 0; i < vch.size(); i++)
{
if (vch[i] != 0)
{
// Can be negative zero
if (i == vch.size()-1 && vch[i] == 0x80)
return false;
return true;
}
}
return false;
}
//
// Script is a stack machine (like Forth) that evaluates a predicate
// returning a bool indicating valid or not. There are no loops.
//
#define stacktop(i) (stack.at(stack.size()+(i)))
#define altstacktop(i) (altstack.at(altstack.size()+(i)))
static inline void popstack(vector<valtype>& stack)
{
if (stack.empty())
throw runtime_error("popstack() : stack empty");
stack.pop_back();
}
const char* GetTxnOutputType(txnouttype t)
{
switch (t)
{
case TX_NONSTANDARD: return "nonstandard";
case TX_PUBKEY: return "pubkey";
case TX_PUBKEYHASH: return "pubkeyhash";
case TX_SCRIPTHASH: return "scripthash";
case TX_MULTISIG: return "multisig";
}
return NULL;
}
const char* GetOpName(opcodetype opcode)
{
switch (opcode)
{
// push value
case OP_0 : return "0";
case OP_PUSHDATA1 : return "OP_PUSHDATA1";
case OP_PUSHDATA2 : return "OP_PUSHDATA2";
case OP_PUSHDATA4 : return "OP_PUSHDATA4";
case OP_1NEGATE : return "-1";
case OP_RESERVED : return "OP_RESERVED";
case OP_1 : return "1";
case OP_2 : return "2";
case OP_3 : return "3";
case OP_4 : return "4";
case OP_5 : return "5";
case OP_6 : return "6";
case OP_7 : return "7";
case OP_8 : return "8";
case OP_9 : return "9";
case OP_10 : return "10";
case OP_11 : return "11";
case OP_12 : return "12";
case OP_13 : return "13";
case OP_14 : return "14";
case OP_15 : return "15";
case OP_16 : return "16";
// control
case OP_NOP : return "OP_NOP";
case OP_VER : return "OP_VER";
case OP_IF : return "OP_IF";
case OP_NOTIF : return "OP_NOTIF";
case OP_VERIF : return "OP_VERIF";
case OP_VERNOTIF : return "OP_VERNOTIF";
case OP_ELSE : return "OP_ELSE";
case OP_ENDIF : return "OP_ENDIF";
case OP_VERIFY : return "OP_VERIFY";
case OP_RETURN : return "OP_RETURN";
// stack ops
case OP_TOALTSTACK : return "OP_TOALTSTACK";
case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
case OP_2DROP : return "OP_2DROP";
case OP_2DUP : return "OP_2DUP";
case OP_3DUP : return "OP_3DUP";
case OP_2OVER : return "OP_2OVER";
case OP_2ROT : return "OP_2ROT";
case OP_2SWAP : return "OP_2SWAP";
case OP_IFDUP : return "OP_IFDUP";
case OP_DEPTH : return "OP_DEPTH";
case OP_DROP : return "OP_DROP";
case OP_DUP : return "OP_DUP";
case OP_NIP : return "OP_NIP";
case OP_OVER : return "OP_OVER";
case OP_PICK : return "OP_PICK";
case OP_ROLL : return "OP_ROLL";
case OP_ROT : return "OP_ROT";
case OP_SWAP : return "OP_SWAP";
case OP_TUCK : return "OP_TUCK";
// splice ops
case OP_CAT : return "OP_CAT";
case OP_SUBSTR : return "OP_SUBSTR";
case OP_LEFT : return "OP_LEFT";
case OP_RIGHT : return "OP_RIGHT";
case OP_SIZE : return "OP_SIZE";
// bit logic
case OP_INVERT : return "OP_INVERT";
case OP_AND : return "OP_AND";
case OP_OR : return "OP_OR";
case OP_XOR : return "OP_XOR";
case OP_EQUAL : return "OP_EQUAL";
case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
case OP_RESERVED1 : return "OP_RESERVED1";
case OP_RESERVED2 : return "OP_RESERVED2";
// numeric
case OP_1ADD : return "OP_1ADD";
case OP_1SUB : return "OP_1SUB";
case OP_2MUL : return "OP_2MUL";
case OP_2DIV : return "OP_2DIV";
case OP_NEGATE : return "OP_NEGATE";
case OP_ABS : return "OP_ABS";
case OP_NOT : return "OP_NOT";
case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
case OP_ADD : return "OP_ADD";
case OP_SUB : return "OP_SUB";
case OP_MUL : return "OP_MUL";
case OP_DIV : return "OP_DIV";
case OP_MOD : return "OP_MOD";
case OP_LSHIFT : return "OP_LSHIFT";
case OP_RSHIFT : return "OP_RSHIFT";
case OP_BOOLAND : return "OP_BOOLAND";
case OP_BOOLOR : return "OP_BOOLOR";
case OP_NUMEQUAL : return "OP_NUMEQUAL";
case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
case OP_LESSTHAN : return "OP_LESSTHAN";
case OP_GREATERTHAN : return "OP_GREATERTHAN";
case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
case OP_MIN : return "OP_MIN";
case OP_MAX : return "OP_MAX";
case OP_WITHIN : return "OP_WITHIN";
// crypto
case OP_RIPEMD160 : return "OP_RIPEMD160";
case OP_SHA1 : return "OP_SHA1";
case OP_SHA256 : return "OP_SHA256";
case OP_HASH160 : return "OP_HASH160";
case OP_HASH256 : return "OP_HASH256";
case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
case OP_CHECKSIG : return "OP_CHECKSIG";
case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
// expanson
case OP_NOP1 : return "OP_NOP1";
case OP_NOP2 : return "OP_NOP2";
case OP_NOP3 : return "OP_NOP3";
case OP_NOP4 : return "OP_NOP4";
case OP_NOP5 : return "OP_NOP5";
case OP_NOP6 : return "OP_NOP6";
case OP_NOP7 : return "OP_NOP7";
case OP_NOP8 : return "OP_NOP8";
case OP_NOP9 : return "OP_NOP9";
case OP_NOP10 : return "OP_NOP10";
// template matching params
case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
case OP_PUBKEY : return "OP_PUBKEY";
case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
default:
return "OP_UNKNOWN";
}
}
bool IsCanonicalPubKey(const valtype &vchPubKey) {
if (vchPubKey.size() < 33)
return error("Non-canonical public key: too short");
if (vchPubKey[0] == 0x04) {
if (vchPubKey.size() != 65)
return error("Non-canonical public key: invalid length for uncompressed key");
} else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
if (vchPubKey.size() != 33)
return error("Non-canonical public key: invalid length for compressed key");
} else {
return error("Non-canonical public key: compressed nor uncompressed");
}
return true;
}
bool IsCanonicalSignature(const valtype &vchSig) {
// See https://rublebittalk.org/index.php?topic=8392.msg127623#msg127623
// A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
// Where R and S are not negative (their first byte has its highest bit not set), and not
// excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
// in which case a single 0 byte is necessary and even required).
if (vchSig.size() < 9)
return error("Non-canonical signature: too short");
if (vchSig.size() > 73)
return error("Non-canonical signature: too long");
unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
return error("Non-canonical signature: unknown hashtype byte");
if (vchSig[0] != 0x30)
return error("Non-canonical signature: wrong type");
if (vchSig[1] != vchSig.size()-3)
return error("Non-canonical signature: wrong length marker");
unsigned int nLenR = vchSig[3];
if (5 + nLenR >= vchSig.size())
return error("Non-canonical signature: S length misplaced");
unsigned int nLenS = vchSig[5+nLenR];
if ((unsigned long)(nLenR+nLenS+7) != vchSig.size())
return error("Non-canonical signature: R+S length mismatch");
const unsigned char *R = &vchSig[4];
if (R[-2] != 0x02)
return error("Non-canonical signature: R value type mismatch");
if (nLenR == 0)
return error("Non-canonical signature: R length is zero");
if (R[0] & 0x80)
return error("Non-canonical signature: R value negative");
if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
return error("Non-canonical signature: R value excessively padded");
const unsigned char *S = &vchSig[6+nLenR];
if (S[-2] != 0x02)
return error("Non-canonical signature: S value type mismatch");
if (nLenS == 0)
return error("Non-canonical signature: S length is zero");
if (S[0] & 0x80)
return error("Non-canonical signature: S value negative");
if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
return error("Non-canonical signature: S value excessively padded");
return true;
}
bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
{
CAutoBN_CTX pctx;
CScript::const_iterator pc = script.begin();
CScript::const_iterator pend = script.end();
CScript::const_iterator pbegincodehash = script.begin();
opcodetype opcode;
valtype vchPushValue;
vector<bool> vfExec;
vector<valtype> altstack;
if (script.size() > 10000)
return false;
int nOpCount = 0;
bool fStrictEncodings = flags & SCRIPT_VERIFY_STRICTENC;
try
{
while (pc < pend)
{
bool fExec = !count(vfExec.begin(), vfExec.end(), false);
//
// Read instruction
//
if (!script.GetOp(pc, opcode, vchPushValue))
return false;
if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
return false;
if (opcode > OP_16 && ++nOpCount > 201)
return false;
if (opcode == OP_CAT ||
opcode == OP_SUBSTR ||
opcode == OP_LEFT ||
opcode == OP_RIGHT ||
opcode == OP_INVERT ||
opcode == OP_AND ||
opcode == OP_OR ||
opcode == OP_XOR ||
opcode == OP_2MUL ||
opcode == OP_2DIV ||
opcode == OP_MUL ||
opcode == OP_DIV ||
opcode == OP_MOD ||
opcode == OP_LSHIFT ||
opcode == OP_RSHIFT)
return false; // Disabled opcodes.
if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
stack.push_back(vchPushValue);
else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
switch (opcode)
{
//
// Push value
//
case OP_1NEGATE:
case OP_1:
case OP_2:
case OP_3:
case OP_4:
case OP_5:
case OP_6:
case OP_7:
case OP_8:
case OP_9:
case OP_10:
case OP_11:
case OP_12:
case OP_13:
case OP_14:
case OP_15:
case OP_16:
{
// ( -- value)
CBigNum bn((int)opcode - (int)(OP_1 - 1));
stack.push_back(bn.getvch());
}
break;
//
// Control
//
case OP_NOP:
case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
break;
case OP_IF:
case OP_NOTIF:
{
// <expression> if [statements] [else [statements]] endif
bool fValue = false;
if (fExec)
{
if (stack.size() < 1)
return false;
valtype& vch = stacktop(-1);
fValue = CastToBool(vch);
if (opcode == OP_NOTIF)
fValue = !fValue;
popstack(stack);
}
vfExec.push_back(fValue);
}
break;
case OP_ELSE:
{
if (vfExec.empty())
return false;
vfExec.back() = !vfExec.back();
}
break;
case OP_ENDIF:
{
if (vfExec.empty())
return false;
vfExec.pop_back();
}
break;
case OP_VERIFY:
{
// (true -- ) or
// (false -- false) and return
if (stack.size() < 1)
return false;
bool fValue = CastToBool(stacktop(-1));
if (fValue)
popstack(stack);
else
return false;
}
break;
case OP_RETURN:
{
return false;
}
break;
//
// Stack ops
//
case OP_TOALTSTACK:
{
if (stack.size() < 1)
return false;
altstack.push_back(stacktop(-1));
popstack(stack);
}
break;
case OP_FROMALTSTACK:
{
if (altstack.size() < 1)
return false;
stack.push_back(altstacktop(-1));
popstack(altstack);
}
break;
case OP_2DROP:
{
// (x1 x2 -- )
if (stack.size() < 2)
return false;
popstack(stack);
popstack(stack);
}
break;
case OP_2DUP:
{
// (x1 x2 -- x1 x2 x1 x2)
if (stack.size() < 2)
return false;
valtype vch1 = stacktop(-2);
valtype vch2 = stacktop(-1);
stack.push_back(vch1);
stack.push_back(vch2);
}
break;
case OP_3DUP:
{
// (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
if (stack.size() < 3)
return false;
valtype vch1 = stacktop(-3);
valtype vch2 = stacktop(-2);
valtype vch3 = stacktop(-1);
stack.push_back(vch1);
stack.push_back(vch2);
stack.push_back(vch3);
}
break;
case OP_2OVER:
{
// (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
if (stack.size() < 4)
return false;
valtype vch1 = stacktop(-4);
valtype vch2 = stacktop(-3);
stack.push_back(vch1);
stack.push_back(vch2);
}
break;
case OP_2ROT:
{
// (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
if (stack.size() < 6)
return false;
valtype vch1 = stacktop(-6);
valtype vch2 = stacktop(-5);
stack.erase(stack.end()-6, stack.end()-4);
stack.push_back(vch1);
stack.push_back(vch2);
}
break;
case OP_2SWAP:
{
// (x1 x2 x3 x4 -- x3 x4 x1 x2)
if (stack.size() < 4)
return false;
swap(stacktop(-4), stacktop(-2));
swap(stacktop(-3), stacktop(-1));
}
break;
case OP_IFDUP:
{
// (x - 0 | x x)
if (stack.size() < 1)
return false;
valtype vch = stacktop(-1);
if (CastToBool(vch))
stack.push_back(vch);
}
break;
case OP_DEPTH:
{
// -- stacksize
CBigNum bn(stack.size());
stack.push_back(bn.getvch());
}
break;
case OP_DROP:
{
// (x -- )
if (stack.size() < 1)
return false;
popstack(stack);
}
break;
case OP_DUP:
{
// (x -- x x)
if (stack.size() < 1)
return false;
valtype vch = stacktop(-1);
stack.push_back(vch);
}
break;
case OP_NIP:
{
// (x1 x2 -- x2)
if (stack.size() < 2)
return false;
stack.erase(stack.end() - 2);
}
break;
case OP_OVER:
{
// (x1 x2 -- x1 x2 x1)
if (stack.size() < 2)
return false;
valtype vch = stacktop(-2);
stack.push_back(vch);
}
break;
case OP_PICK:
case OP_ROLL:
{
// (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
// (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
if (stack.size() < 2)
return false;
int n = CastToBigNum(stacktop(-1)).getint();
popstack(stack);
if (n < 0 || n >= (int)stack.size())
return false;
valtype vch = stacktop(-n-1);
if (opcode == OP_ROLL)
stack.erase(stack.end()-n-1);
stack.push_back(vch);
}
break;
case OP_ROT:
{
// (x1 x2 x3 -- x2 x3 x1)
// x2 x1 x3 after first swap
// x2 x3 x1 after second swap
if (stack.size() < 3)
return false;
swap(stacktop(-3), stacktop(-2));
swap(stacktop(-2), stacktop(-1));
}
break;
case OP_SWAP:
{
// (x1 x2 -- x2 x1)
if (stack.size() < 2)
return false;
swap(stacktop(-2), stacktop(-1));
}
break;
case OP_TUCK:
{
// (x1 x2 -- x2 x1 x2)
if (stack.size() < 2)
return false;
valtype vch = stacktop(-1);
stack.insert(stack.end()-2, vch);
}
break;
case OP_SIZE:
{
// (in -- in size)
if (stack.size() < 1)
return false;
CBigNum bn(stacktop(-1).size());
stack.push_back(bn.getvch());
}
break;
//
// Bitwise logic
//
case OP_EQUAL:
case OP_EQUALVERIFY:
//case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
{
// (x1 x2 - bool)
if (stack.size() < 2)
return false;
valtype& vch1 = stacktop(-2);
valtype& vch2 = stacktop(-1);
bool fEqual = (vch1 == vch2);
// OP_NOTEQUAL is disabled because it would be too easy to say
// something like n != 1 and have some wiseguy pass in 1 with extra
// zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
//if (opcode == OP_NOTEQUAL)
// fEqual = !fEqual;
popstack(stack);
popstack(stack);
stack.push_back(fEqual ? vchTrue : vchFalse);
if (opcode == OP_EQUALVERIFY)
{
if (fEqual)
popstack(stack);
else
return false;
}
}
break;
//
// Numeric
//
case OP_1ADD:
case OP_1SUB:
case OP_NEGATE:
case OP_ABS:
case OP_NOT:
case OP_0NOTEQUAL:
{
// (in -- out)
if (stack.size() < 1)
return false;
CBigNum bn = CastToBigNum(stacktop(-1));
switch (opcode)
{
case OP_1ADD: bn += bnOne; break;
case OP_1SUB: bn -= bnOne; break;
case OP_NEGATE: bn = -bn; break;
case OP_ABS: if (bn < bnZero) bn = -bn; break;
case OP_NOT: bn = (bn == bnZero); break;
case OP_0NOTEQUAL: bn = (bn != bnZero); break;
default: assert(!"invalid opcode"); break;
}
popstack(stack);
stack.push_back(bn.getvch());
}
break;
case OP_ADD:
case OP_SUB:
case OP_BOOLAND:
case OP_BOOLOR:
case OP_NUMEQUAL:
case OP_NUMEQUALVERIFY:
case OP_NUMNOTEQUAL:
case OP_LESSTHAN:
case OP_GREATERTHAN:
case OP_LESSTHANOREQUAL:
case OP_GREATERTHANOREQUAL:
case OP_MIN:
case OP_MAX:
{
// (x1 x2 -- out)
if (stack.size() < 2)
return false;
CBigNum bn1 = CastToBigNum(stacktop(-2));
CBigNum bn2 = CastToBigNum(stacktop(-1));
CBigNum bn;
switch (opcode)
{
case OP_ADD:
bn = bn1 + bn2;
break;
case OP_SUB:
bn = bn1 - bn2;
break;
case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
case OP_NUMEQUAL: bn = (bn1 == bn2); break;
case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
case OP_LESSTHAN: bn = (bn1 < bn2); break;
case OP_GREATERTHAN: bn = (bn1 > bn2); break;
case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
default: assert(!"invalid opcode"); break;
}
popstack(stack);
popstack(stack);
stack.push_back(bn.getvch());
if (opcode == OP_NUMEQUALVERIFY)
{
if (CastToBool(stacktop(-1)))
popstack(stack);
else
return false;
}
}
break;
case OP_WITHIN:
{
// (x min max -- out)
if (stack.size() < 3)
return false;
CBigNum bn1 = CastToBigNum(stacktop(-3));
CBigNum bn2 = CastToBigNum(stacktop(-2));
CBigNum bn3 = CastToBigNum(stacktop(-1));
bool fValue = (bn2 <= bn1 && bn1 < bn3);
popstack(stack);
popstack(stack);
popstack(stack);
stack.push_back(fValue ? vchTrue : vchFalse);
}
break;
//
// Crypto
//
case OP_RIPEMD160:
case OP_SHA1:
case OP_SHA256:
case OP_HASH160:
case OP_HASH256:
{
// (in -- hash)
if (stack.size() < 1)
return false;
valtype& vch = stacktop(-1);
valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
if (opcode == OP_RIPEMD160)
RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
else if (opcode == OP_SHA1)
SHA1(&vch[0], vch.size(), &vchHash[0]);
else if (opcode == OP_SHA256)
SHA256(&vch[0], vch.size(), &vchHash[0]);
else if (opcode == OP_HASH160)
{
uint160 hash160 = Hash160(vch);
memcpy(&vchHash[0], &hash160, sizeof(hash160));
}
else if (opcode == OP_HASH256)
{
uint256 hash = Hash(vch.begin(), vch.end());
memcpy(&vchHash[0], &hash, sizeof(hash));
}
popstack(stack);
stack.push_back(vchHash);
}
break;
case OP_CODESEPARATOR:
{
// Hash starts after the code separator
pbegincodehash = pc;
}
break;
case OP_CHECKSIG:
case OP_CHECKSIGVERIFY:
{
// (sig pubkey -- bool)
if (stack.size() < 2)
return false;
valtype& vchSig = stacktop(-2);
valtype& vchPubKey = stacktop(-1);
////// debug print
//PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
//PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
// Subset of script starting at the most recent codeseparator
CScript scriptCode(pbegincodehash, pend);
// Drop the signature, since there's no way for a signature to sign itself
scriptCode.FindAndDelete(CScript(vchSig));
bool fSuccess = (!fStrictEncodings || (IsCanonicalSignature(vchSig) && IsCanonicalPubKey(vchPubKey)));
if (fSuccess)
fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
popstack(stack);
popstack(stack);
stack.push_back(fSuccess ? vchTrue : vchFalse);
if (opcode == OP_CHECKSIGVERIFY)
{
if (fSuccess)
popstack(stack);
else
return false;
}
}
break;
case OP_CHECKMULTISIG:
case OP_CHECKMULTISIGVERIFY:
{
// ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
int i = 1;
if ((int)stack.size() < i)
return false;
int nKeysCount = CastToBigNum(stacktop(-i)).getint();
if (nKeysCount < 0 || nKeysCount > 20)
return false;
nOpCount += nKeysCount;
if (nOpCount > 201)
return false;
int ikey = ++i;
i += nKeysCount;
if ((int)stack.size() < i)
return false;
int nSigsCount = CastToBigNum(stacktop(-i)).getint();
if (nSigsCount < 0 || nSigsCount > nKeysCount)
return false;
int isig = ++i;
i += nSigsCount;
if ((int)stack.size() < i)
return false;
// Subset of script starting at the most recent codeseparator
CScript scriptCode(pbegincodehash, pend);
// Drop the signatures, since there's no way for a signature to sign itself
for (int k = 0; k < nSigsCount; k++)
{
valtype& vchSig = stacktop(-isig-k);
scriptCode.FindAndDelete(CScript(vchSig));
}
bool fSuccess = true;
while (fSuccess && nSigsCount > 0)
{
valtype& vchSig = stacktop(-isig);
valtype& vchPubKey = stacktop(-ikey);
// Check signature
bool fOk = (!fStrictEncodings || (IsCanonicalSignature(vchSig) && IsCanonicalPubKey(vchPubKey)));
if (fOk)
fOk = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
if (fOk) {
isig++;
nSigsCount--;
}
ikey++;
nKeysCount--;
// If there are more signatures left than keys left,
// then too many signatures have failed
if (nSigsCount > nKeysCount)
fSuccess = false;
}
while (i-- > 0)
popstack(stack);
stack.push_back(fSuccess ? vchTrue : vchFalse);
if (opcode == OP_CHECKMULTISIGVERIFY)
{
if (fSuccess)
popstack(stack);
else
return false;
}
}
break;
default:
return false;
}
// Size limits
if (stack.size() + altstack.size() > 1000)
return false;
}
}
catch (...)
{
return false;
}
if (!vfExec.empty())
return false;
return true;
}
uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
{
if (nIn >= txTo.vin.size())
{
printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
return 1;
}
CTransaction txTmp(txTo);
// In case concatenating two scripts ends up with two codeseparators,
// or an extra one at the end, this prevents all those possible incompatibilities.
scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
// Blank out other inputs' signatures
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
txTmp.vin[i].scriptSig = CScript();
txTmp.vin[nIn].scriptSig = scriptCode;
// Blank out some of the outputs
if ((nHashType & 0x1f) == SIGHASH_NONE)
{
// Wildcard payee
txTmp.vout.clear();
// Let the others update at will
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
{
// Only lock-in the txout payee at same index as txin
unsigned int nOut = nIn;
if (nOut >= txTmp.vout.size())
{
printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
return 1;
}
txTmp.vout.resize(nOut+1);
for (unsigned int i = 0; i < nOut; i++)
txTmp.vout[i].SetNull();
// Let the others update at will
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
// Blank out other inputs completely, not recommended for open transactions
if (nHashType & SIGHASH_ANYONECANPAY)
{
txTmp.vin[0] = txTmp.vin[nIn];
txTmp.vin.resize(1);
}
// Serialize and hash
CHashWriter ss(SER_GETHASH, 0);
ss << txTmp << nHashType;
return ss.GetHash();
}
// Valid signature cache, to avoid doing expensive ECDSA signature checking
// twice for every transaction (once when accepted into memory pool, and
// again when accepted into the block chain)
class CSignatureCache
{
private:
// sigdata_type is (signature hash, signature, public key):
typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey> sigdata_type;
std::set< sigdata_type> setValid;
boost::shared_mutex cs_sigcache;
public:
bool
Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
{
boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
sigdata_type k(hash, vchSig, pubKey);
std::set<sigdata_type>::iterator mi = setValid.find(k);
if (mi != setValid.end())
return true;
return false;
}
void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
{
// DoS prevention: limit cache size to less than 10MB
// (~200 bytes per cache entry times 50,000 entries)
// Since there are a maximum of 20,000 signature operations per block
// 50,000 is a reasonable default.
int64 nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
if (nMaxCacheSize <= 0) return;
boost::unique_lock<boost::shared_mutex> lock(cs_sigcache);
while (static_cast<int64>(setValid.size()) > nMaxCacheSize)
{
// Evict a random entry. Random because that helps
// foil would-be DoS attackers who might try to pre-generate
// and re-use a set of valid signatures just-slightly-greater
// than our cache size.
uint256 randomHash = GetRandHash();
std::vector<unsigned char> unused;
std::set<sigdata_type>::iterator it =
setValid.lower_bound(sigdata_type(randomHash, unused, unused));
if (it == setValid.end())
it = setValid.begin();
setValid.erase(*it);
}
sigdata_type k(hash, vchSig, pubKey);
setValid.insert(k);
}
};
bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode,
const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
{
static CSignatureCache signatureCache;
CPubKey pubkey(vchPubKey);
if (!pubkey.IsValid())
return false;
// Hash type is one byte tacked on to the end of the signature
if (vchSig.empty())
return false;
if (nHashType == 0)
nHashType = vchSig.back();
else if (nHashType != vchSig.back())
return false;
vchSig.pop_back();
uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
if (signatureCache.Get(sighash, vchSig, pubkey))
return true;
if (!pubkey.Verify(sighash, vchSig))
return false;
if (!(flags & SCRIPT_VERIFY_NOCACHE))
signatureCache.Set(sighash, vchSig, pubkey);
return true;
}
//
// Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
//
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
{
// Templates
static map<txnouttype, CScript> mTemplates;
if (mTemplates.empty())
{
// Standard tx, sender provides pubkey, receiver adds signature
mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
// RubleBit address tx, sender provides hash of pubkey, receiver provides signature and pubkey
mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
// Sender provides N pubkeys, receivers provides M signatures
mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
}
// Shortcut for pay-to-script-hash, which are more constrained than the other types:
// it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
if (scriptPubKey.IsPayToScriptHash())
{
typeRet = TX_SCRIPTHASH;
vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
vSolutionsRet.push_back(hashBytes);
return true;
}
// Scan templates
const CScript& script1 = scriptPubKey;
BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
{
const CScript& script2 = tplate.second;
vSolutionsRet.clear();
opcodetype opcode1, opcode2;
vector<unsigned char> vch1, vch2;
// Compare
CScript::const_iterator pc1 = script1.begin();
CScript::const_iterator pc2 = script2.begin();
loop
{
if (pc1 == script1.end() && pc2 == script2.end())
{
// Found a match
typeRet = tplate.first;
if (typeRet == TX_MULTISIG)
{
// Additional checks for TX_MULTISIG:
unsigned char m = vSolutionsRet.front()[0];
unsigned char n = vSolutionsRet.back()[0];
if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
return false;
}
return true;
}
if (!script1.GetOp(pc1, opcode1, vch1))
break;
if (!script2.GetOp(pc2, opcode2, vch2))
break;
// Template matching opcodes:
if (opcode2 == OP_PUBKEYS)
{
while (vch1.size() >= 33 && vch1.size() <= 120)
{
vSolutionsRet.push_back(vch1);
if (!script1.GetOp(pc1, opcode1, vch1))
break;
}
if (!script2.GetOp(pc2, opcode2, vch2))
break;
// Normal situation is to fall through
// to other if/else statements
}
if (opcode2 == OP_PUBKEY)
{
if (vch1.size() < 33 || vch1.size() > 120)
break;
vSolutionsRet.push_back(vch1);
}
else if (opcode2 == OP_PUBKEYHASH)
{
if (vch1.size() != sizeof(uint160))
break;
vSolutionsRet.push_back(vch1);
}
else if (opcode2 == OP_SMALLINTEGER)
{ // Single-byte small integer pushed onto vSolutions
if (opcode1 == OP_0 ||
(opcode1 >= OP_1 && opcode1 <= OP_16))
{
char n = (char)CScript::DecodeOP_N(opcode1);
vSolutionsRet.push_back(valtype(1, n));
}
else
break;
}
else if (opcode1 != opcode2 || vch1 != vch2)
{
// Others must match exactly
break;
}
}
}
vSolutionsRet.clear();
typeRet = TX_NONSTANDARD;
return false;
}
bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
{
CKey key;
if (!keystore.GetKey(address, key))
return false;
vector<unsigned char> vchSig;
if (!key.Sign(hash, vchSig))
return false;
vchSig.push_back((unsigned char)nHashType);
scriptSigRet << vchSig;
return true;
}
bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
{
int nSigned = 0;
int nRequired = multisigdata.front()[0];
for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
{
const valtype& pubkey = multisigdata[i];
CKeyID keyID = CPubKey(pubkey).GetID();
if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
++nSigned;
}
return nSigned==nRequired;
}
//
// Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
// Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
// unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
// Returns false if scriptPubKey could not be completely satisfied.
//
bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
CScript& scriptSigRet, txnouttype& whichTypeRet)
{
scriptSigRet.clear();
vector<valtype> vSolutions;
if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
return false;
CKeyID keyID;
switch (whichTypeRet)
{
case TX_NONSTANDARD:
return false;
case TX_PUBKEY:
keyID = CPubKey(vSolutions[0]).GetID();
return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
case TX_PUBKEYHASH:
keyID = CKeyID(uint160(vSolutions[0]));
if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
return false;
else
{
CPubKey vch;
keystore.GetPubKey(keyID, vch);
scriptSigRet << vch;
}
return true;
case TX_SCRIPTHASH:
return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
case TX_MULTISIG:
scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
}
return false;
}
int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
{
switch (t)
{
case TX_NONSTANDARD:
return -1;
case TX_PUBKEY:
return 1;
case TX_PUBKEYHASH:
return 2;
case TX_MULTISIG:
if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
return -1;
return vSolutions[0][0] + 1;
case TX_SCRIPTHASH:
return 1; // doesn't include args needed by the script
}
return -1;
}
bool IsStandard(const CScript& scriptPubKey)
{
vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_MULTISIG)
{
unsigned char m = vSolutions.front()[0];
unsigned char n = vSolutions.back()[0];
// Support up to x-of-3 multisig txns as standard
if (n < 1 || n > 3)
return false;
if (m < 1 || m > n)
return false;
}
return whichType != TX_NONSTANDARD;
}
unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
{
unsigned int nResult = 0;
BOOST_FOREACH(const valtype& pubkey, pubkeys)
{
CKeyID keyID = CPubKey(pubkey).GetID();
if (keystore.HaveKey(keyID))
++nResult;
}
return nResult;
}
class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
{
private:
const CKeyStore *keystore;
public:
CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
bool operator()(const CNoDestination &dest) const { return false; }
bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
};
bool IsMine(const CKeyStore &keystore, const CTxDestination &dest)
{
return boost::apply_visitor(CKeyStoreIsMineVisitor(&keystore), dest);
}
bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
{
vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions))
return false;
CKeyID keyID;
switch (whichType)
{
case TX_NONSTANDARD:
return false;
case TX_PUBKEY:
keyID = CPubKey(vSolutions[0]).GetID();
return keystore.HaveKey(keyID);
case TX_PUBKEYHASH:
keyID = CKeyID(uint160(vSolutions[0]));
return keystore.HaveKey(keyID);
case TX_SCRIPTHASH:
{
CScript subscript;
if (!keystore.GetCScript(CScriptID(uint160(vSolutions[0])), subscript))
return false;
return IsMine(keystore, subscript);
}
case TX_MULTISIG:
{
// Only consider transactions "mine" if we own ALL the
// keys involved. multi-signature transactions that are
// partially owned (somebody else has a key that can spend
// them) enable spend-out-from-under-you attacks, especially
// in shared-wallet situations.
vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
return HaveKeys(keys, keystore) == keys.size();
}
}
return false;
}
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
{
vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
addressRet = CPubKey(vSolutions[0]).GetID();
return true;
}
else if (whichType == TX_PUBKEYHASH)
{
addressRet = CKeyID(uint160(vSolutions[0]));
return true;
}
else if (whichType == TX_SCRIPTHASH)
{
addressRet = CScriptID(uint160(vSolutions[0]));
return true;
}
// Multisig txns have more than one address...
return false;
}
bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
{
addressRet.clear();
typeRet = TX_NONSTANDARD;
vector<valtype> vSolutions;
if (!Solver(scriptPubKey, typeRet, vSolutions))
return false;
if (typeRet == TX_MULTISIG)
{
nRequiredRet = vSolutions.front()[0];
for (unsigned int i = 1; i < vSolutions.size()-1; i++)
{
CTxDestination address = CPubKey(vSolutions[i]).GetID();
addressRet.push_back(address);
}
}
else
{
nRequiredRet = 1;
CTxDestination address;
if (!ExtractDestination(scriptPubKey, address))
return false;
addressRet.push_back(address);
}
return true;
}
bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
unsigned int flags, int nHashType)
{
vector<vector<unsigned char> > stack, stackCopy;
if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
return false;
if (flags & SCRIPT_VERIFY_P2SH)
stackCopy = stack;
if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
return false;
if (stack.empty())
return false;
if (CastToBool(stack.back()) == false)
return false;
// Additional validation for spend-to-script-hash transactions:
if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
{
if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
return false; // or validation fails
// stackCopy cannot be empty here, because if it was the
// P2SH HASH <> EQUAL scriptPubKey would be evaluated with
// an empty stack and the EvalScript above would return false.
assert(!stackCopy.empty());
const valtype& pubKeySerialized = stackCopy.back();
CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
popstack(stackCopy);
if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
return false;
if (stackCopy.empty())
return false;
return CastToBool(stackCopy.back());
}
return true;
}
bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
{
assert(nIn < txTo.vin.size());
CTxIn& txin = txTo.vin[nIn];
// Leave out the signature from the hash, since a signature can't sign itself.
// The checksig op will also drop the signatures from its hash.
uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
txnouttype whichType;
if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
return false;
if (whichType == TX_SCRIPTHASH)
{
// Solver returns the subscript that need to be evaluated;
// the final scriptSig is the signatures from that
// and then the serialized subscript:
CScript subscript = txin.scriptSig;
// Recompute txn hash using subscript in place of scriptPubKey:
uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
txnouttype subType;
bool fSolved =
Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
// Append serialized subscript whether or not it is completely signed:
txin.scriptSig << static_cast<valtype>(subscript);
if (!fSolved) return false;
}
// Test solution
return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, 0);
}
bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
{
assert(nIn < txTo.vin.size());
CTxIn& txin = txTo.vin[nIn];
assert(txin.prevout.n < txFrom.vout.size());
const CTxOut& txout = txFrom.vout[txin.prevout.n];
return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
}
static CScript PushAll(const vector<valtype>& values)
{
CScript result;
BOOST_FOREACH(const valtype& v, values)
result << v;
return result;
}
static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
const vector<valtype>& vSolutions,
vector<valtype>& sigs1, vector<valtype>& sigs2)
{
// Combine all the signatures we've got:
set<valtype> allsigs;
BOOST_FOREACH(const valtype& v, sigs1)
{
if (!v.empty())
allsigs.insert(v);
}
BOOST_FOREACH(const valtype& v, sigs2)
{
if (!v.empty())
allsigs.insert(v);
}
// Build a map of pubkey -> signature by matching sigs to pubkeys:
assert(vSolutions.size() > 1);
unsigned int nSigsRequired = vSolutions.front()[0];
unsigned int nPubKeys = vSolutions.size()-2;
map<valtype, valtype> sigs;
BOOST_FOREACH(const valtype& sig, allsigs)
{
for (unsigned int i = 0; i < nPubKeys; i++)
{
const valtype& pubkey = vSolutions[i+1];
if (sigs.count(pubkey))
continue; // Already got a sig for this pubkey
if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
{
sigs[pubkey] = sig;
break;
}
}
}
// Now build a merged CScript:
unsigned int nSigsHave = 0;
CScript result; result << OP_0; // pop-one-too-many workaround
for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
{
if (sigs.count(vSolutions[i+1]))
{
result << sigs[vSolutions[i+1]];
++nSigsHave;
}
}
// Fill any missing with OP_0:
for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
result << OP_0;
return result;
}
static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
const txnouttype txType, const vector<valtype>& vSolutions,
vector<valtype>& sigs1, vector<valtype>& sigs2)
{
switch (txType)
{
case TX_NONSTANDARD:
// Don't know anything about this, assume bigger one is correct:
if (sigs1.size() >= sigs2.size())
return PushAll(sigs1);
return PushAll(sigs2);
case TX_PUBKEY:
case TX_PUBKEYHASH:
// Signatures are bigger than placeholders or empty scripts:
if (sigs1.empty() || sigs1[0].empty())
return PushAll(sigs2);
return PushAll(sigs1);
case TX_SCRIPTHASH:
if (sigs1.empty() || sigs1.back().empty())
return PushAll(sigs2);
else if (sigs2.empty() || sigs2.back().empty())
return PushAll(sigs1);
else
{
// Recur to combine:
valtype spk = sigs1.back();
CScript pubKey2(spk.begin(), spk.end());
txnouttype txType2;
vector<vector<unsigned char> > vSolutions2;
Solver(pubKey2, txType2, vSolutions2);
sigs1.pop_back();
sigs2.pop_back();
CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
result << spk;
return result;
}
case TX_MULTISIG:
return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
}
return CScript();
}
CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
const CScript& scriptSig1, const CScript& scriptSig2)
{
txnouttype txType;
vector<vector<unsigned char> > vSolutions;
Solver(scriptPubKey, txType, vSolutions);
vector<valtype> stack1;
EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
vector<valtype> stack2;
EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
}
unsigned int CScript::GetSigOpCount(bool fAccurate) const
{
unsigned int n = 0;
const_iterator pc = begin();
opcodetype lastOpcode = OP_INVALIDOPCODE;
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
break;
if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
n++;
else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
{
if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
n += DecodeOP_N(lastOpcode);
else
n += 20;
}
lastOpcode = opcode;
}
return n;
}
unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
{
if (!IsPayToScriptHash())
return GetSigOpCount(true);
// This is a pay-to-script-hash scriptPubKey;
// get the last item that the scriptSig
// pushes onto the stack:
const_iterator pc = scriptSig.begin();
vector<unsigned char> data;
while (pc < scriptSig.end())
{
opcodetype opcode;
if (!scriptSig.GetOp(pc, opcode, data))
return 0;
if (opcode > OP_16)
return 0;
}
/// ... and return its opcount:
CScript subscript(data.begin(), data.end());
return subscript.GetSigOpCount(true);
}
bool CScript::IsPayToScriptHash() const
{
// Extra-fast test for pay-to-script-hash CScripts:
return (this->size() == 23 &&
this->at(0) == OP_HASH160 &&
this->at(1) == 0x14 &&
this->at(22) == OP_EQUAL);
}
bool CScript::HasCanonicalPushes() const
{
const_iterator pc = begin();
while (pc < end())
{
opcodetype opcode;
std::vector<unsigned char> data;
if (!GetOp(pc, opcode, data))
return false;
if (opcode > OP_16)
continue;
if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
// Could have used an OP_n code, rather than a 1-byte push.
return false;
if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
// Could have used a normal n-byte push, rather than OP_PUSHDATA1.
return false;
if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
// Could have used an OP_PUSHDATA1.
return false;
if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
// Could have used an OP_PUSHDATA2.
return false;
}
return true;
}
class CScriptVisitor : public boost::static_visitor<bool>
{
private:
CScript *script;
public:
CScriptVisitor(CScript *scriptin) { script = scriptin; }
bool operator()(const CNoDestination &dest) const {
script->clear();
return false;
}
bool operator()(const CKeyID &keyID) const {
script->clear();
*script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
return true;
}
bool operator()(const CScriptID &scriptID) const {
script->clear();
*script << OP_HASH160 << scriptID << OP_EQUAL;
return true;
}
};
void CScript::SetDestination(const CTxDestination& dest)
{
boost::apply_visitor(CScriptVisitor(this), dest);
}
void CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)
{
this->clear();
*this << EncodeOP_N(nRequired);
BOOST_FOREACH(const CPubKey& key, keys)
*this << key;
*this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
}
bool CScriptCompressor::IsToKeyID(CKeyID &hash) const
{
if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160
&& script[2] == 20 && script[23] == OP_EQUALVERIFY
&& script[24] == OP_CHECKSIG) {
memcpy(&hash, &script[3], 20);
return true;
}
return false;
}
bool CScriptCompressor::IsToScriptID(CScriptID &hash) const
{
if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20
&& script[22] == OP_EQUAL) {
memcpy(&hash, &script[2], 20);
return true;
}
return false;
}
bool CScriptCompressor::IsToPubKey(CPubKey &pubkey) const
{
if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG
&& (script[1] == 0x02 || script[1] == 0x03)) {
pubkey.Set(&script[1], &script[34]);
return true;
}
if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG
&& script[1] == 0x04) {
pubkey.Set(&script[1], &script[66]);
return pubkey.IsFullyValid(); // if not fully valid, a case that would not be compressible
}
return false;
}
bool CScriptCompressor::Compress(std::vector<unsigned char> &out) const
{
CKeyID keyID;
if (IsToKeyID(keyID)) {
out.resize(21);
out[0] = 0x00;
memcpy(&out[1], &keyID, 20);
return true;
}
CScriptID scriptID;
if (IsToScriptID(scriptID)) {
out.resize(21);
out[0] = 0x01;
memcpy(&out[1], &scriptID, 20);
return true;
}
CPubKey pubkey;
if (IsToPubKey(pubkey)) {
out.resize(33);
memcpy(&out[1], &pubkey[1], 32);
if (pubkey[0] == 0x02 || pubkey[0] == 0x03) {
out[0] = pubkey[0];
return true;
} else if (pubkey[0] == 0x04) {
out[0] = 0x04 | (pubkey[64] & 0x01);
return true;
}
}
return false;
}
unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const
{
if (nSize == 0 || nSize == 1)
return 20;
if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5)
return 32;
return 0;
}
bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char> &in)
{
switch(nSize) {
case 0x00:
script.resize(25);
script[0] = OP_DUP;
script[1] = OP_HASH160;
script[2] = 20;
memcpy(&script[3], &in[0], 20);
script[23] = OP_EQUALVERIFY;
script[24] = OP_CHECKSIG;
return true;
case 0x01:
script.resize(23);
script[0] = OP_HASH160;
script[1] = 20;
memcpy(&script[2], &in[0], 20);
script[22] = OP_EQUAL;
return true;
case 0x02:
case 0x03:
script.resize(35);
script[0] = 33;
script[1] = nSize;
memcpy(&script[2], &in[0], 32);
script[34] = OP_CHECKSIG;
return true;
case 0x04:
case 0x05:
unsigned char vch[33] = {};
vch[0] = nSize - 2;
memcpy(&vch[1], &in[0], 32);
CPubKey pubkey(&vch[0], &vch[33]);
if (!pubkey.Decompress())
return false;
assert(pubkey.size() == 65);
script.resize(67);
script[0] = 65;
memcpy(&script[1], pubkey.begin(), 65);
script[66] = OP_CHECKSIG;
return true;
}
return false;
}
| [
"root@poolcoin.pw"
] | root@poolcoin.pw |
8f349d5f6926608b1066253b4b869eaf31b80888 | 947d63ff55ece7c2333ebe4190da435e17edb088 | /LaunchProgressBarApp.cpp | b37002c3d43f0e5517b39397c7003e770ae13d23 | [] | no_license | hitenderprakash/GtkProgressBar | c01c560ef244b834f7bd5ccae37c887607f1c4c9 | 2819b193776725c3942ab6e3bd9a384a9cc31195 | refs/heads/master | 2023-06-25T04:16:03.869910 | 2021-07-29T17:19:24 | 2021-07-29T17:19:24 | 390,799,713 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 635 | cpp | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <spawn.h>
#include <sys/wait.h>
extern char **environ;
void run_cmd(char *cmd)
{
pid_t pid;
char *argv[] = {(char*)"SimpleGtkProgressBar",NULL};
int status;
printf("Run command: %s\n", cmd);
status = posix_spawn(&pid, "SimpleGtkProgressBar", NULL, NULL, argv, environ);
if (status == 0) {
printf("Child pid: %i\n", pid);
} else {
printf("posix_spawn: %s\n", strerror(status));
}
printf("\nEXITING");
//sleep(100);
}
int main(int argc, char* argv[])
{
run_cmd(argv[1]);
return 0;
} | [
"hitenderprakash@gmail.com"
] | hitenderprakash@gmail.com |
031ae447bea61fe812718b3bd9f5a63a08c62c5e | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/collectd/gumtree/collectd_old_hunk_523.cpp | 79f6dc3c9cddd4b2cb55be8f23a2e7b3504dfdb9 | [] | 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 | 1,103 | cpp | il->head = item;
}
#if HAVE_REGEX_H
static int ignorelist_append_regex(ignorelist_t *il, const char *entry)
{
regex_t *re;
ignorelist_item_t *item;
int status;
/* create buffer */
re = malloc (sizeof (*re));
if (re == NULL)
{
ERROR ("ignorelist_append_regex: malloc failed.");
return ENOMEM;
}
memset (re, 0, sizeof (*re));
/* compile regex */
status = regcomp (re, entry, REG_EXTENDED);
if (status != 0)
{
char errbuf[1024];
(void) regerror (status, re, errbuf, sizeof (errbuf));
ERROR ("ignorelist_append_regex: Compiling regular expression \"%s\" failed: %s", entry, errbuf);
sfree (re);
return status;
}
/* create new entry */
item = malloc (sizeof (*item));
if (item == NULL)
{
ERROR ("ignorelist_append_regex: malloc failed.");
regfree (re);
sfree (re);
return ENOMEM;
}
memset (item, 0, sizeof (*item));
item->rmatch = re;
/* append new entry */
ignorelist_append (il, item);
return (0);
} /* int ignorelist_append_regex(ignorelist_t *il, const char *entry) */
#endif
static int ignorelist_append_string(ignorelist_t *il, const char *entry)
| [
"993273596@qq.com"
] | 993273596@qq.com |
c196194465570d6f7a774200fca0e00ae45a1a71 | 25f61bf8e39fbe9f6084950d686063abc4b38dfc | /amethystforest/Source/amethystforest/Private/Weapon/AmethystWeapon.cpp | 0f85dee9393b1d34da023a3f77a8175c0eb687e0 | [] | no_license | opiepj/amethystforest | 940fd62faf875fad64b376c330dad1d1237c0a91 | 517a4b34071ad4b30088928e46553e434eb7d658 | refs/heads/master | 2021-01-15T13:51:56.175195 | 2015-02-05T17:58:22 | 2015-02-05T17:58:22 | 24,573,955 | 0 | 0 | null | 2015-02-05T17:58:22 | 2014-09-29T00:08:07 | C++ | UTF-8 | C++ | false | false | 21,549 | cpp |
#include "amethystforest.h"
#include "Classes/Weapon/AmethystWeapon.h"
#include "Classes/Bots/AmethystAIController.h"
#include "Classes/Player/AmethystCharacter.h"
#include "Classes/Player/amethystforestPlayerController.h"
#include "Classes/Bots/AmethystAIController.h"
AAmethystWeapon::AAmethystWeapon(const class FPostConstructInitializeProperties& PCIP) : Super(PCIP)
{
Mesh1P = PCIP.CreateDefaultSubobject<USkeletalMeshComponent>(this, TEXT("WeaponMesh1P"));
Mesh1P->MeshComponentUpdateFlag = EMeshComponentUpdateFlag::OnlyTickPoseWhenRendered;
Mesh1P->bChartDistanceFactor = false;
Mesh1P->bReceivesDecals = false;
Mesh1P->CastShadow = false;
Mesh1P->SetCollisionObjectType(ECC_WorldDynamic);
Mesh1P->SetCollisionEnabled(ECollisionEnabled::NoCollision);
Mesh1P->SetCollisionResponseToAllChannels(ECR_Ignore);
RootComponent = Mesh1P;
Mesh3P = PCIP.CreateDefaultSubobject<USkeletalMeshComponent>(this, TEXT("WeaponMesh3P"));
Mesh3P->MeshComponentUpdateFlag = EMeshComponentUpdateFlag::OnlyTickPoseWhenRendered;
Mesh3P->bChartDistanceFactor = true;
Mesh3P->bReceivesDecals = false;
Mesh3P->CastShadow = true;
Mesh3P->SetCollisionObjectType(ECC_WorldDynamic);
Mesh3P->SetCollisionEnabled(ECollisionEnabled::NoCollision);
Mesh3P->SetCollisionResponseToAllChannels(ECR_Ignore);
Mesh3P->SetCollisionResponseToChannel(COLLISION_WEAPON, ECR_Block);
Mesh3P->SetCollisionResponseToChannel(ECC_Visibility, ECR_Block);
Mesh3P->SetCollisionResponseToChannel(COLLISION_PROJECTILE, ECR_Block);
Mesh3P->AttachParent = Mesh1P;
bLoopedMuzzleFX = false;
bLoopedFireAnim = false;
bPlayingFireAnim = false;
bIsEquipped = false;
bWantsToFire = false;
bPendingReload = false;
bPendingEquip = false;
CurrentState = EWeaponState::Idle;
CurrentAmmo = 0;
CurrentAmmoInClip = 0;
BurstCounter = 0;
LastFireTime = 0.0f;
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.TickGroup = TG_PrePhysics;
SetRemoteRoleForBackwardsCompat(ROLE_SimulatedProxy);
bReplicates = true;
bReplicateInstigator = true;
bNetUseOwnerRelevancy = true;
}
void AAmethystWeapon::PostInitializeComponents()
{
Super::PostInitializeComponents();
if (WeaponConfig.InitialClips > 0)
{
CurrentAmmoInClip = WeaponConfig.AmmoPerClip;
CurrentAmmo = WeaponConfig.AmmoPerClip * WeaponConfig.InitialClips;
}
DetachMeshFromPawn();
}
void AAmethystWeapon::Destroyed()
{
Super::Destroyed();
StopSimulatingWeaponFire();
}
//////////////////////////////////////////////////////////////////////////
// Inventory
void AAmethystWeapon::OnEquip()
{
AttachMeshToPawn();
bPendingEquip = true;
DetermineWeaponState();
float Duration = PlayWeaponAnimation(EquipAnim);
if (Duration <= 0.0f)
{
// failsafe
Duration = 0.5f;
}
EquipStartedTime = GetWorld()->GetTimeSeconds();
EquipDuration = Duration;
GetWorldTimerManager().SetTimer(this, &AAmethystWeapon::OnEquipFinished, Duration, false);
if (MyPawn && MyPawn->IsLocallyControlled())
{
PlayWeaponSound(EquipSound);
}
}
void AAmethystWeapon::OnEquipFinished()
{
AttachMeshToPawn();
bIsEquipped = true;
bPendingEquip = false;
if (MyPawn)
{
// try to reload empty clip
if (MyPawn->IsLocallyControlled() &&
CurrentAmmoInClip <= 0 &&
CanReload())
{
StartReload();
}
}
DetermineWeaponState();
}
void AAmethystWeapon::OnUnEquip()
{
DetachMeshFromPawn();
bIsEquipped = false;
StopFire();
if (bPendingReload)
{
StopWeaponAnimation(ReloadAnim);
bPendingReload = false;
GetWorldTimerManager().ClearTimer(this, &AAmethystWeapon::StopReload);
GetWorldTimerManager().ClearTimer(this, &AAmethystWeapon::ReloadWeapon);
}
if (bPendingEquip)
{
StopWeaponAnimation(EquipAnim);
bPendingEquip = false;
GetWorldTimerManager().ClearTimer(this, &AAmethystWeapon::OnEquipFinished);
}
DetermineWeaponState();
}
void AAmethystWeapon::OnEnterInventory(AAmethystCharacter* NewOwner)
{
SetOwningPawn(NewOwner);
}
void AAmethystWeapon::OnLeaveInventory()
{
if (Role == ROLE_Authority)
{
SetOwningPawn(NULL);
}
if (IsAttachedToPawn())
{
OnUnEquip();
}
}
void AAmethystWeapon::AttachMeshToPawn()
{
if (MyPawn)
{
// Remove and hide both first and third person meshes
DetachMeshFromPawn();
// For locally controller players we attach both weapons and let the bOnlyOwnerSee, bOwnerNoSee flags deal with visibility.
FName AttachPoint = MyPawn->GetWeaponAttachPoint();
if (MyPawn->IsLocallyControlled() == true)
{
USkeletalMeshComponent* PawnMesh1p = MyPawn->GetSpecifcPawnMesh(true);
USkeletalMeshComponent* PawnMesh3p = MyPawn->GetSpecifcPawnMesh(false);
Mesh1P->SetHiddenInGame(false);
Mesh3P->SetHiddenInGame(false);
Mesh1P->AttachTo(PawnMesh1p, AttachPoint);
Mesh3P->AttachTo(PawnMesh3p, AttachPoint);
}
else
{
USkeletalMeshComponent* UseWeaponMesh = GetWeaponMesh();
USkeletalMeshComponent* UsePawnMesh = MyPawn->GetPawnMesh();
UseWeaponMesh->AttachTo(UsePawnMesh, AttachPoint);
UseWeaponMesh->SetHiddenInGame(false);
}
}
}
void AAmethystWeapon::DetachMeshFromPawn()
{
Mesh1P->DetachFromParent();
Mesh1P->SetHiddenInGame(true);
Mesh3P->DetachFromParent();
Mesh3P->SetHiddenInGame(true);
}
//////////////////////////////////////////////////////////////////////////
// Input
void AAmethystWeapon::StartFire()
{
if (Role < ROLE_Authority)
{
ServerStartFire();
}
if (!bWantsToFire)
{
bWantsToFire = true;
DetermineWeaponState();
}
}
void AAmethystWeapon::StopFire()
{
if (Role < ROLE_Authority)
{
ServerStopFire();
}
if (bWantsToFire)
{
bWantsToFire = false;
DetermineWeaponState();
}
}
void AAmethystWeapon::StartReload(bool bFromReplication)
{
if (!bFromReplication && Role < ROLE_Authority)
{
ServerStartReload();
}
if (bFromReplication || CanReload())
{
bPendingReload = true;
DetermineWeaponState();
float AnimDuration = PlayWeaponAnimation(ReloadAnim);
if (AnimDuration <= 0.0f)
{
AnimDuration = WeaponConfig.NoAnimReloadDuration;
}
GetWorldTimerManager().SetTimer(this, &AAmethystWeapon::StopReload, AnimDuration, false);
if (Role == ROLE_Authority)
{
GetWorldTimerManager().SetTimer(this, &AAmethystWeapon::ReloadWeapon, FMath::Max(0.1f, AnimDuration - 0.1f), false);
}
if (MyPawn && MyPawn->IsLocallyControlled())
{
PlayWeaponSound(ReloadSound);
}
}
}
void AAmethystWeapon::StopReload()
{
if (CurrentState == EWeaponState::Reloading)
{
bPendingReload = false;
DetermineWeaponState();
StopWeaponAnimation(ReloadAnim);
}
}
bool AAmethystWeapon::ServerStartFire_Validate()
{
return true;
}
void AAmethystWeapon::ServerStartFire_Implementation()
{
StartFire();
}
bool AAmethystWeapon::ServerStopFire_Validate()
{
return true;
}
void AAmethystWeapon::ServerStopFire_Implementation()
{
StopFire();
}
bool AAmethystWeapon::ServerStartReload_Validate()
{
return true;
}
void AAmethystWeapon::ServerStartReload_Implementation()
{
StartReload();
}
bool AAmethystWeapon::ServerStopReload_Validate()
{
return true;
}
void AAmethystWeapon::ServerStopReload_Implementation()
{
StopReload();
}
void AAmethystWeapon::ClientStartReload_Implementation()
{
StartReload();
}
//////////////////////////////////////////////////////////////////////////
// Control
bool AAmethystWeapon::CanFire() const
{
bool bCanFire = MyPawn && MyPawn->CanFire();
bool bStateOKToFire = ((CurrentState == EWeaponState::Idle) || (CurrentState == EWeaponState::Firing));
return ((bCanFire == true) && (bStateOKToFire == true) && (bPendingReload == false));
}
bool AAmethystWeapon::CanReload() const
{
bool bCanReload = (!MyPawn || MyPawn->CanReload());
bool bGotAmmo = (CurrentAmmoInClip < WeaponConfig.AmmoPerClip) && (CurrentAmmo - CurrentAmmoInClip > 0 || HasInfiniteClip());
bool bStateOKToReload = ((CurrentState == EWeaponState::Idle) || (CurrentState == EWeaponState::Firing));
return ((bCanReload == true) && (bGotAmmo == true) && (bStateOKToReload == true));
}
//////////////////////////////////////////////////////////////////////////
// Weapon usage
void AAmethystWeapon::GiveAmmo(int AddAmount)
{
const int32 MissingAmmo = FMath::Max(0, WeaponConfig.MaxAmmo - CurrentAmmo);
AddAmount = FMath::Min(AddAmount, MissingAmmo);
CurrentAmmo += AddAmount;
AAmethystAIController* BotAI = MyPawn ? Cast<AAmethystAIController>(MyPawn->GetController()) : NULL;
if (BotAI)
{
BotAI->CheckAmmo(this);
}
// start reload if clip was empty
if (GetCurrentAmmoInClip() <= 0 &&
CanReload() &&
MyPawn->GetWeapon() == this)
{
ClientStartReload();
}
}
void AAmethystWeapon::UseAmmo()
{
if (!HasInfiniteAmmo())
{
CurrentAmmoInClip--;
}
if (!HasInfiniteAmmo() && !HasInfiniteClip())
{
CurrentAmmo--;
}
AAmethystAIController* BotAI = MyPawn ? Cast<AAmethystAIController>(MyPawn->GetController()) : NULL;
AamethystforestPlayerController* PlayerController = MyPawn ? Cast<AamethystforestPlayerController>(MyPawn->GetController()) : NULL;
if (BotAI)
{
BotAI->CheckAmmo(this);
}
}
void AAmethystWeapon::HandleFiring()
{
if ((CurrentAmmoInClip > 0 || HasInfiniteClip() || HasInfiniteAmmo()) && CanFire())
{
if (GetNetMode() != NM_DedicatedServer)
{
SimulateWeaponFire();
}
if (MyPawn && MyPawn->IsLocallyControlled())
{
FireWeapon();
UseAmmo();
// update firing FX on remote clients if function was called on server
BurstCounter++;
}
}
else if (CanReload())
{
StartReload();
}
else if (MyPawn && MyPawn->IsLocallyControlled())
{
if (GetCurrentAmmo() == 0 && !bRefiring)
{
PlayWeaponSound(OutOfAmmoSound);
AamethystforestPlayerController* MyPC = Cast<AamethystforestPlayerController>(MyPawn->Controller);
AAmethystHUD* MyHUD = MyPC ? Cast<AAmethystHUD>(MyPC->GetHUD()) : NULL;
if (MyHUD)
{
MyHUD->NotifyOutOfAmmo();
}
}
// stop weapon fire FX, but stay in Firing state
if (BurstCounter > 0)
{
OnBurstFinished();
}
}
if (MyPawn && MyPawn->IsLocallyControlled())
{
// local client will notify server
if (Role < ROLE_Authority)
{
ServerHandleFiring();
}
// reload after firing last round
if (CurrentAmmoInClip <= 0 && CanReload())
{
StartReload();
}
// setup refire timer
bRefiring = (CurrentState == EWeaponState::Firing && WeaponConfig.TimeBetweenShots > 0.0f);
if (bRefiring)
{
GetWorldTimerManager().SetTimer(this, &AAmethystWeapon::HandleFiring, WeaponConfig.TimeBetweenShots, false);
}
}
LastFireTime = GetWorld()->GetTimeSeconds();
}
bool AAmethystWeapon::ServerHandleFiring_Validate()
{
return true;
}
void AAmethystWeapon::ServerHandleFiring_Implementation()
{
const bool bShouldUpdateAmmo = (CurrentAmmoInClip > 0 && CanFire());
HandleFiring();
if (bShouldUpdateAmmo)
{
// update ammo
UseAmmo();
// update firing FX on remote clients
BurstCounter++;
}
}
void AAmethystWeapon::ReloadWeapon()
{
int32 ClipDelta = FMath::Min(WeaponConfig.AmmoPerClip - CurrentAmmoInClip, CurrentAmmo - CurrentAmmoInClip);
if (HasInfiniteClip())
{
ClipDelta = WeaponConfig.AmmoPerClip - CurrentAmmoInClip;
}
if (ClipDelta > 0)
{
CurrentAmmoInClip += ClipDelta;
}
if (HasInfiniteClip())
{
CurrentAmmo = FMath::Max(CurrentAmmoInClip, CurrentAmmo);
}
}
void AAmethystWeapon::SetWeaponState(EWeaponState::Type NewState)
{
const EWeaponState::Type PrevState = CurrentState;
if (PrevState == EWeaponState::Firing && NewState != EWeaponState::Firing)
{
OnBurstFinished();
}
CurrentState = NewState;
if (PrevState != EWeaponState::Firing && NewState == EWeaponState::Firing)
{
OnBurstStarted();
}
}
void AAmethystWeapon::DetermineWeaponState()
{
EWeaponState::Type NewState = EWeaponState::Idle;
if (bIsEquipped)
{
if (bPendingReload)
{
if (CanReload() == false)
{
NewState = CurrentState;
}
else
{
NewState = EWeaponState::Reloading;
}
}
else if ((bPendingReload == false) && (bWantsToFire == true) && (CanFire() == true))
{
NewState = EWeaponState::Firing;
}
}
else if (bPendingEquip)
{
NewState = EWeaponState::Equipping;
}
SetWeaponState(NewState);
}
void AAmethystWeapon::OnBurstStarted()
{
// start firing, can be delayed to satisfy TimeBetweenShots
const float GameTime = GetWorld()->GetTimeSeconds();
if (LastFireTime > 0 && WeaponConfig.TimeBetweenShots > 0.0f &&
LastFireTime + WeaponConfig.TimeBetweenShots > GameTime)
{
GetWorldTimerManager().SetTimer(this, &AAmethystWeapon::HandleFiring, LastFireTime + WeaponConfig.TimeBetweenShots - GameTime, false);
}
else
{
HandleFiring();
}
}
void AAmethystWeapon::OnBurstFinished()
{
// stop firing FX on remote clients
BurstCounter = 0;
// stop firing FX locally, unless it's a dedicated server
if (GetNetMode() != NM_DedicatedServer)
{
StopSimulatingWeaponFire();
}
GetWorldTimerManager().ClearTimer(this, &AAmethystWeapon::HandleFiring);
bRefiring = false;
}
//////////////////////////////////////////////////////////////////////////
// Weapon usage helpers
UAudioComponent* AAmethystWeapon::PlayWeaponSound(USoundCue* Sound)
{
UAudioComponent* AC = NULL;
if (Sound && MyPawn)
{
AC = UGameplayStatics::PlaySoundAttached(Sound, MyPawn->GetRootComponent());
}
return AC;
}
float AAmethystWeapon::PlayWeaponAnimation(const FWeaponAnim& Animation)
{
float Duration = 0.0f;
if (MyPawn)
{
UAnimMontage* UseAnim = MyPawn->IsFirstPerson() ? Animation.Pawn1P : Animation.Pawn3P;
if (UseAnim)
{
Duration = MyPawn->PlayAnimMontage(UseAnim);
}
}
return Duration;
}
void AAmethystWeapon::StopWeaponAnimation(const FWeaponAnim& Animation)
{
if (MyPawn)
{
UAnimMontage* UseAnim = MyPawn->IsFirstPerson() ? Animation.Pawn1P : Animation.Pawn3P;
if (UseAnim)
{
MyPawn->StopAnimMontage(UseAnim);
}
}
}
FVector AAmethystWeapon::GetCameraAim() const
{
AamethystforestPlayerController* const PlayerController = Instigator ? Cast<AamethystforestPlayerController>(Instigator->Controller) : NULL;
FVector FinalAim = FVector::ZeroVector;
if (PlayerController)
{
FVector CamLoc;
FRotator CamRot;
PlayerController->GetPlayerViewPoint(CamLoc, CamRot);
FinalAim = CamRot.Vector();
}
else if (Instigator)
{
FinalAim = Instigator->GetBaseAimRotation().Vector();
}
return FinalAim;
}
FVector AAmethystWeapon::GetAdjustedAim() const
{
AamethystforestPlayerController* const PlayerController = Instigator ? Cast<AamethystforestPlayerController>(Instigator->Controller) : NULL;
FVector FinalAim = FVector::ZeroVector;
// If we have a player controller use it for the aim
if (PlayerController)
{
FVector CamLoc;
FRotator CamRot;
PlayerController->GetPlayerViewPoint(CamLoc, CamRot);
FinalAim = CamRot.Vector();
}
else if (Instigator)
{
// Now see if we have an AI controller - we will want to get the aim from there if we do
AAmethystAIController* AIController = MyPawn ? Cast<AAmethystAIController>(MyPawn->Controller) : NULL;
if (AIController != NULL)
{
FinalAim = AIController->GetControlRotation().Vector();
}
else
{
FinalAim = Instigator->GetBaseAimRotation().Vector();
}
}
return FinalAim;
}
FVector AAmethystWeapon::GetCameraDamageStartLocation(const FVector& AimDir) const
{
AamethystforestPlayerController* PC = MyPawn ? Cast<AamethystforestPlayerController>(MyPawn->Controller) : NULL;
AAmethystAIController* AIPC = MyPawn ? Cast<AAmethystAIController>(MyPawn->Controller) : NULL;
FVector OutStartTrace = FVector::ZeroVector;
if (PC)
{
// use player's camera
FRotator UnusedRot;
PC->GetPlayerViewPoint(OutStartTrace, UnusedRot);
// Adjust trace so there is nothing blocking the ray between the camera and the pawn, and calculate distance from adjusted start
OutStartTrace = OutStartTrace + AimDir * ((Instigator->GetActorLocation() - OutStartTrace) | AimDir);
}
else if (AIPC)
{
OutStartTrace = GetMuzzleLocation();
}
return OutStartTrace;
}
FVector AAmethystWeapon::GetMuzzleLocation() const
{
USkeletalMeshComponent* UseMesh = GetWeaponMesh();
return UseMesh->GetSocketLocation(MuzzleAttachPoint);
}
FVector AAmethystWeapon::GetMuzzleDirection() const
{
USkeletalMeshComponent* UseMesh = GetWeaponMesh();
return UseMesh->GetSocketRotation(MuzzleAttachPoint).Vector();
}
FHitResult AAmethystWeapon::WeaponTrace(const FVector& StartTrace, const FVector& EndTrace) const
{
static FName WeaponFireTag = FName(TEXT("WeaponTrace"));
// Perform trace to retrieve hit info
FCollisionQueryParams TraceParams(WeaponFireTag, true, Instigator);
TraceParams.bTraceAsyncScene = true;
TraceParams.bReturnPhysicalMaterial = true;
FHitResult Hit(ForceInit);
GetWorld()->LineTraceSingle(Hit, StartTrace, EndTrace, COLLISION_WEAPON, TraceParams);
return Hit;
}
void AAmethystWeapon::SetOwningPawn(AAmethystCharacter* NewOwner)
{
if (MyPawn != NewOwner)
{
Instigator = NewOwner;
MyPawn = NewOwner;
// net owner for RPC calls
SetOwner(NewOwner);
}
}
//////////////////////////////////////////////////////////////////////////
// Replication & effects
void AAmethystWeapon::OnRep_MyPawn()
{
if (MyPawn)
{
OnEnterInventory(MyPawn);
}
else
{
OnLeaveInventory();
}
}
void AAmethystWeapon::OnRep_BurstCounter()
{
if (BurstCounter > 0)
{
SimulateWeaponFire();
}
else
{
StopSimulatingWeaponFire();
}
}
void AAmethystWeapon::OnRep_Reload()
{
if (bPendingReload)
{
StartReload(true);
}
else
{
StopReload();
}
}
void AAmethystWeapon::SimulateWeaponFire()
{
if (Role == ROLE_Authority && CurrentState != EWeaponState::Firing)
{
return;
}
if (MuzzleFX)
{
USkeletalMeshComponent* UseWeaponMesh = GetWeaponMesh();
if (!bLoopedMuzzleFX || MuzzlePSC == NULL)
{
// Split screen requires we create 2 effects. One that we see and one that the other player sees.
if ((MyPawn != NULL) && (MyPawn->IsLocallyControlled() == true))
{
AController* PlayerCon = MyPawn->GetController();
if (PlayerCon != NULL)
{
Mesh1P->GetSocketLocation(MuzzleAttachPoint);
MuzzlePSC = UGameplayStatics::SpawnEmitterAttached(MuzzleFX, Mesh1P, MuzzleAttachPoint);
MuzzlePSC->bOwnerNoSee = false;
MuzzlePSC->bOnlyOwnerSee = true;
Mesh3P->GetSocketLocation(MuzzleAttachPoint);
MuzzlePSCSecondary = UGameplayStatics::SpawnEmitterAttached(MuzzleFX, Mesh3P, MuzzleAttachPoint);
MuzzlePSCSecondary->bOwnerNoSee = true;
MuzzlePSCSecondary->bOnlyOwnerSee = false;
}
}
else
{
MuzzlePSC = UGameplayStatics::SpawnEmitterAttached(MuzzleFX, UseWeaponMesh, MuzzleAttachPoint);
}
}
}
if (!bLoopedFireAnim || !bPlayingFireAnim)
{
PlayWeaponAnimation(FireAnim);
bPlayingFireAnim = true;
}
if (bLoopedFireSound)
{
if (FireAC == NULL)
{
FireAC = PlayWeaponSound(FireLoopSound);
}
}
else
{
PlayWeaponSound(FireSound);
}
AamethystforestPlayerController* PC = (MyPawn != NULL) ? Cast<AamethystforestPlayerController>(MyPawn->Controller) : NULL;
if (PC != NULL && PC->IsLocalController())
{
if (FireCameraShake != NULL)
{
PC->ClientPlayCameraShake(FireCameraShake, 1);
}
if (FireForceFeedback != NULL)
{
PC->ClientPlayForceFeedback(FireForceFeedback, false, "Weapon");
}
}
}
void AAmethystWeapon::StopSimulatingWeaponFire()
{
if (bLoopedMuzzleFX)
{
if (MuzzlePSC != NULL)
{
MuzzlePSC->DeactivateSystem();
MuzzlePSC = NULL;
}
if (MuzzlePSCSecondary != NULL)
{
MuzzlePSCSecondary->DeactivateSystem();
MuzzlePSCSecondary = NULL;
}
}
if (bLoopedFireAnim && bPlayingFireAnim)
{
StopWeaponAnimation(FireAnim);
bPlayingFireAnim = false;
}
if (FireAC)
{
FireAC->FadeOut(0.1f, 0.0f);
FireAC = NULL;
PlayWeaponSound(FireFinishSound);
}
}
void AAmethystWeapon::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(AAmethystWeapon, MyPawn);
DOREPLIFETIME_CONDITION(AAmethystWeapon, CurrentAmmo, COND_OwnerOnly);
DOREPLIFETIME_CONDITION(AAmethystWeapon, CurrentAmmoInClip, COND_OwnerOnly);
DOREPLIFETIME_CONDITION(AAmethystWeapon, BurstCounter, COND_SkipOwner);
DOREPLIFETIME_CONDITION(AAmethystWeapon, bPendingReload, COND_SkipOwner);
}
USkeletalMeshComponent* AAmethystWeapon::GetWeaponMesh() const
{
return (MyPawn != NULL && MyPawn->IsFirstPerson()) ? Mesh1P : Mesh3P;
}
class AAmethystCharacter* AAmethystWeapon::GetPawnOwner() const
{
return MyPawn;
}
bool AAmethystWeapon::IsEquipped() const
{
return bIsEquipped;
}
bool AAmethystWeapon::IsAttachedToPawn() const
{
return bIsEquipped || bPendingEquip;
}
EWeaponState::Type AAmethystWeapon::GetCurrentState() const
{
return CurrentState;
}
int32 AAmethystWeapon::GetCurrentAmmo() const
{
return CurrentAmmo;
}
int32 AAmethystWeapon::GetCurrentAmmoInClip() const
{
return CurrentAmmoInClip;
}
int32 AAmethystWeapon::GetAmmoPerClip() const
{
return WeaponConfig.AmmoPerClip;
}
int32 AAmethystWeapon::GetMaxAmmo() const
{
return WeaponConfig.MaxAmmo;
}
bool AAmethystWeapon::HasInfiniteAmmo() const
{
const AamethystforestPlayerController* MyPC = (MyPawn != NULL) ? Cast<const AamethystforestPlayerController>(MyPawn->Controller) : NULL;
return WeaponConfig.bInfiniteAmmo || (MyPC && MyPC->HasInfiniteAmmo());
}
bool AAmethystWeapon::HasInfiniteClip() const
{
const AamethystforestPlayerController* MyPC = (MyPawn != NULL) ? Cast<const AamethystforestPlayerController>(MyPawn->Controller) : NULL;
return WeaponConfig.bInfiniteClip || (MyPC && MyPC->HasInfiniteClip());
}
float AAmethystWeapon::GetEquipStartedTime() const
{
return EquipStartedTime;
}
float AAmethystWeapon::GetEquipDuration() const
{
return EquipDuration;
}
| [
"opiepj@plu.edu"
] | opiepj@plu.edu |
151486ad4ba4741a4e810ef7f116a87f018374e5 | cfd9878263624bfff0e0348b3372ed0b5b652ed7 | /zachariah3D/run/0/kstar | 542099a85de285e1bd103ab100bb3807e2e3964d | [
"MIT"
] | permissive | CathyZZZ/OpenFOAM | cf6acb610fbe381512ae8ceb7e4d2646d1533080 | 2e7e869d8fcd0b67cfc0a3be3a4aacf0708dd504 | refs/heads/master | 2020-04-02T04:17:07.190247 | 2019-02-27T08:54:16 | 2019-02-27T08:54:16 | 154,009,515 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,600 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0";
object kstar;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [ 0 0 0 0 0 0 0 ];
internalField uniform 0;
boundaryField
{
inlet
{
type zeroGradient;
}
outlet
{
type fixedValue;
value $internalField;
}
lowerWall0
{
type empty;
}
lowerWall1
{
type empty;
}
lowerWall2
{
type empty;
}
upperWall0
{
type zeroGradient;
}
upperWall1
{
type zeroGradient;
}
upperWall2
{
type zeroGradient;
}
frontAndBack_half0
{
type cyclic;
}
frontAndBack_half1
{
type cyclic;
}
}
// ************************************************************************* //
| [
"ziyizhu00@gmail.com"
] | ziyizhu00@gmail.com | |
69c5dc83327dd10b7859ae83f31997a6103f1f77 | c6843b4ef6111ccbea2c13ff028df768fc25f3fb | /src/OpenClosed.cpp | b2d51e212a5de8e1e7c7f3ca696bf2bc5210f3a3 | [] | no_license | ysabhi1993/DesignPatterns | f6d8c9be8fb686fbc2c713aee65e2c9d00367742 | 2d9f640157a6e08ffe76acb7883d6b6a954d98dc | refs/heads/master | 2022-11-06T20:59:57.875275 | 2020-06-14T18:45:51 | 2020-06-14T18:45:51 | 269,810,574 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 651 | cpp | #include <OpenClosed.h>
bool SizeSpecification::is_satisfied(Product *item) const
{
return item->size == this->size;
}
bool ColorSpecification::is_satisfied(Product *item) const
{
return item->color == this->color;
}
std::vector<Product *> FilterOnTypes::filter(std::vector<Product*> items, Specification<Product> &spec) const
{
std::vector<Product *> result;
for(auto &item : items) {
if(spec.is_satisfied(item))
result.push_back(item);
}
return result;
}
template <typename T>
bool AndSpecification<T>::is_satisfied(T *item) const
{
first.is_satisfied(item) && second.is_satisfied(item);
}
| [
"abhishekys1993@gmail.com"
] | abhishekys1993@gmail.com |
385d84ab71d4a21077ced5185744fb644d829927 | 4e88e0300779e7a758edec0c01c8f88cac946f31 | /Induction/Permutations.cpp | b724ecb3df550e2c6739e05072d3aaa0cbf298f6 | [] | no_license | CodingYuanLiu/Algorithm | 86bb46889ff021f0b1ce0e269cfc8f545255415a | a08976ba0f11d86973e0dc73f1b64980ab99f6fc | refs/heads/master | 2020-04-11T14:34:42.384971 | 2019-01-07T14:01:36 | 2019-01-07T14:01:36 | 161,860,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,037 | cpp | #include <iostream>
using namespace std;
void perm1(int a[], int m,int len);
void perm2(int a[], int m,int len);
void print(int a[], int len);
int main()
{
int a[4]={1,2,3,4};
//perm1(a, 0,4);
int b[4] = {};
perm2(b, 1, 4);
return 0;
}
void print(int a[], int len)
{
for (int i = 0; i < len;i++)
{
cout << a[i];
}
cout << endl;
}
void perm1(int a[],int m,int len)
{
if(m == len-1)
{
print(a, len);
return;
}
int temp;
for (int j = m; j < len;j++)
{
temp = a[m];
a[m] = a[j];
a[j] = temp;
perm1(a, m + 1, len);
temp = a[m];
a[m] = a[j];
a[j] = temp;
}
}
void perm2(int a[],int m,int len)
{
if(m == len+1)
{
print(a, len);
return;
}
else
{
for (int j = 0; j < len;j++)
{
if(a[j] == 0)
{
a[j] = m;
perm2(a,m + 1,len);
a[j] = 0;
}
}
}
} | [
"lqyuan980413@163.com"
] | lqyuan980413@163.com |
fcc6aec8e0232e593007b08ab3399b4e613d0d23 | 67ede3ff38eebc0dfaad9fea84a497b27fc8c4bf | /tlv.h | 2346b49b299afea804ca91e351b2b5efba40df9f | [] | no_license | originalsouth/tlv | 0f7eaa433b5961c7e4244f0128b17804fa7c40ec | b6a33c7ecd46160ebe9d8a9ed324dc95e57fa77e | refs/heads/master | 2020-04-06T06:58:55.406646 | 2016-06-07T09:56:28 | 2016-06-07T09:56:28 | 41,798,272 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,446 | h | /* By BC van Zuiden -- Leiden, February 2016 */
/* Probably very buggy USE AT OWN RISK this will brick everything you own */
/* NOBODY but YOU is liable for anything that happened in result of using this */
/* WARNING: DON'T RUN THIS PROGRAM THIS WILL DESTROY YOUR COMPUTER AND/OR HOUSE */
/* Any copyrighted piece of code within this code is NOT mine */
/* Inclusion of that code is forced upon me by a scary anonymous guy with a gun*/
/* https://github.com/originalsouth/tlv */
#ifndef __TLV__
#define __TLV__
#if __cplusplus < 201103L
#error "C++11 not detetected: tlv requires C++11 to work (update your compiler)."
#else
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
#include <vector>
namespace tlv
{
struct svg
{
double width,height;
std::string header;
std::vector<std::string> data;
svg();
svg(double x);
svg(double w,double h);
bool write(std::string fout_name);
void prepend(svg *img);
void append(svg *img);
void import(svg *img);
void clear();
};
template<typename ...Args> bool tlv_hdr(svg *img,std::string str,Args... args);
template<typename ...Args> bool tlv_drw(svg *img,std::string str,Args... args);
template<typename ...Args> bool tlv_opn(svg *img,std::string str,Args... args);
bool tlv_cls(svg *img,std::string str);
template<typename ...Args> bool tlv_yfo(svg *img,std::string marker,std::string content,std::string str,Args... args);
template<typename ...Args> bool tlv_obj(svg *img,std::string marker,svg *object,std::string str,Args... args);
template<typename ...Args,typename lambda> bool tlv_for(svg *img,std::string marker,lambda x,std::string str,Args... args);
std::string rgb(unsigned char r,unsigned char g,unsigned char b);
std::string hsv(double h,double s,double v);
}
tlv::svg::svg()
{
width=height=1e3;
tlv_hdr(this,"width=\"%g\" height=\"%g\"",width,height);
}
tlv::svg::svg(double x)
{
width=height=x;
tlv_hdr(this,"width=\"%g\" height=\"%g\"",width,height);
}
tlv::svg::svg(double w,double h)
{
width=w,height=h;
tlv_hdr(this,"width=\"%g\" height=\"%g\"",width,height);
}
bool tlv::svg::write(std::string fout_name)
{
FILE *fout=fopen(fout_name.c_str(),"w");
if(fout)
{
fprintf(fout,"%s\n",header.c_str());
for(std::string str: data) fprintf(fout,"%s\n",str.c_str());
fprintf(fout,"</svg>\n");
fclose(fout);
return true;
}
else return false;
}
void tlv::svg::prepend(svg *img)
{
data.insert(data.begin(),img->data.begin(),img->data.end());
}
void tlv::svg::append(svg *img)
{
data.insert(data.end(),img->data.begin(),img->data.end());
}
void tlv::svg::import(svg *img)
{
data=img->data;
}
void tlv::svg::clear()
{
data.clear();
}
template<typename ...Args> bool tlv::tlv_hdr(svg *img,std::string str,Args... args)
{
const std::string svd="<svg xmlns=\"http://www.w3.org/2000/svg\" "+str+">";
const size_t size=1+snprintf(nullptr,0,svd.c_str(),args...);
char *buffer=new(std::nothrow) char[size];
if(buffer==nullptr) return false;
else
{
snprintf(buffer,size,svd.c_str(),args...);
img->header=std::string(buffer);
delete[] buffer;
return true;
}
}
template<typename ...Args> bool tlv::tlv_drw(svg *img,std::string str,Args... args)
{
const std::string svd="<"+str+"/>";
const size_t size=1+snprintf(nullptr,0,svd.c_str(),args...);
char *buffer=new(std::nothrow) char[size];
if(buffer==nullptr) return false;
else
{
snprintf(buffer,size,svd.c_str(),args...);
img->data.push_back(std::string(buffer));
delete[] buffer;
return true;
}
}
template<typename ...Args> bool tlv::tlv_opn(svg *img,std::string str,Args... args)
{
const std::string svd="<"+str+">";
const size_t size=1+snprintf(nullptr,0,svd.c_str(),args...);
char *buffer=new(std::nothrow) char[size];
if(buffer==nullptr) return false;
else
{
snprintf(buffer,size,svd.c_str(),args...);
img->data.push_back(std::string(buffer));
delete[] buffer;
return true;
}
}
bool tlv::tlv_cls(svg *img,std::string str)
{
const std::string svd="</"+str+">";
img->data.push_back(svd);
return true;
}
template<typename ...Args> bool tlv::tlv_yfo(svg *img,std::string marker,std::string content,std::string str,Args... args)
{
const std::string svd="<"+marker+" "+str+">";
const size_t size=1+snprintf(nullptr,0,svd.c_str(),args...);
char *buffer=new(std::nothrow) char[size];
if(buffer==nullptr) return false;
else
{
snprintf(buffer,size,svd.c_str(),args...);
img->data.push_back(std::string(buffer)+content+std::string("</")+marker+std::string(">"));
delete[] buffer;
return true;
}
}
template<typename ...Args> bool tlv::tlv_obj(svg *img,std::string marker,svg *object,std::string str,Args... args)
{
const std::string svd="<"+marker+" "+str+">";
const size_t size=1+snprintf(nullptr,0,svd.c_str(),args...);
char *buffer=new(std::nothrow) char[size];
if(buffer==nullptr) return false;
else
{
snprintf(buffer,size,svd.c_str(),args...);
img->data.push_back(std::string(buffer));
img->append(object);
img->data.push_back(std::string("</")+marker+std::string(">"));
delete[] buffer;
return true;
}
}
template<typename ...Args,typename lambda> bool tlv::tlv_for(svg *img,std::string marker,lambda x,std::string str,Args... args)
{
const std::string svd="<"+marker+" "+str+">";
const size_t size=1+snprintf(nullptr,0,svd.c_str(),args...);
char *buffer=new(std::nothrow) char[size];
if(buffer==nullptr) return false;
else
{
snprintf(buffer,size,svd.c_str(),args...);
img->data.push_back(std::string(buffer));
x();
img->data.push_back(std::string("</")+marker+std::string(">"));
delete[] buffer;
return true;
}
}
std::string tlv::rgb(unsigned char r,unsigned char g,unsigned char b)
{
char cstr[3];
std::string retval=std::string("#");
snprintf(cstr,3,"%02X",r);
retval+=std::string(cstr);
snprintf(cstr,3,"%02X",g);
retval+=std::string(cstr);
snprintf(cstr,3,"%02X",b);
retval+=std::string(cstr);
return retval;
}
std::string tlv::hsv(double h,double s,double v)
{
h/=60.0,v*=256.0;
if(v>255.0) v=255.0;
const double f=h-std::floor(h),p=v*(1.0-s),q=v*(1.0-s*f),t=v*(1.0-(1.0-f)*s);
switch((int)h)
{
case 0: return tlv::rgb(v,t,p);
case 1: return tlv::rgb(q,v,p);
case 2: return tlv::rgb(p,v,t);
case 3: return tlv::rgb(p,q,v);
case 4: return tlv::rgb(t,p,v);
case 5: return tlv::rgb(v,p,q);
default: return tlv::rgb(0,0,0);
}
}
#define tlv_hdr(img,str,...) tlv::tlv_hdr(img,#str,##__VA_ARGS__)
#define tlv_drw(img,str,...) tlv::tlv_drw(img,#str,##__VA_ARGS__)
#define tlv_opn(img,str,...) tlv::tlv_opn(img,#str,##__VA_ARGS__)
#define tlv_cls(img,str,...) tlv::tlv_cls(img,#str,##__VA_ARGS__)
#define tlv_yfo(img,mrk,txt,str,...) tlv::tlv_yfo(img,mrk,txt,#str,##__VA_ARGS__)
#define tlv_obj(img,mrk,object,str,...) tlv::tlv_obj(img,mrk,object,#str,##__VA_ARGS__)
#define tlv_for(img,mrk,lambda,str,...) tlv::tlv_for(img,mrk,lambda,#str,##__VA_ARGS__)
#endif
#endif
| [
"zuiden@lorentz.leidenuniv.nl"
] | zuiden@lorentz.leidenuniv.nl |
ab9449d088a9065e63ce0cf6eab2ca8d6fb62663 | 1b7f6b320f547573c7eacf33747731323b3c1251 | /barrett_hand_hardware_interface/owd/openwam/Kinematics.cc | 9ae0f08377dd80911fd24e1e95ab4e14c36a3a9a | [] | no_license | kucars/barrett_hand | 44174f22a61602879c403b1057b0d5a2d0c4f44f | 53cd0db45cb1bead1db9faba6c50d5237e295643 | refs/heads/master | 2021-05-29T12:58:15.488335 | 2015-04-06T07:31:42 | 2015-04-06T07:31:42 | 20,765,433 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,254 | cc | /*
Copyright 2006 Simon Leonard
This file is part of openwam.
openwam is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
openwam 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Kinematics.hh"
#include <stdlib.h>
#include "Plugin.hh" // for debugging the Jacobian
#include <stdio.h>
// #define ADD_
//#include <cblas_f77.h>
extern "C" {
void dgemm_(char *transa, char *transb, int *m, int *n, int *k,double *alpha,
double *a, int *lda, double *b, int *ldb, double *beta,double *c,
int *ldc);
void dgemv_(char *trans, int *m, int *n, double *alpha, double *a, int *lda,
double *x, int *incx, double *beta, double *y, int *incy);
void dgesvd_(char *jobu, char *jobvt, int *m,
int *n, double *a, int *lda,
double *s, double *u, int *ldu, double *vt,
int *ldvt, double *work, int *lwork, int *info);
}
namespace OWD {
// allocate and initialize the static members
//
// note: use of the TRANST flag basically says to blas that the
// input matrix has been transposed, and it should be "untransposed"
// before the operation. So the number of rows/columns reflect the
// native size of the matrix before it was transposed, or
// after it is untransposed.
char Kinematics::TRANST = 'T';
char Kinematics::TRANSN = 'N';
double Kinematics::ALPHA = 1.0;
double Kinematics::BETA = 0.0;
char Kinematics::UPLO = 'L';
int Kinematics::LD_Jacobian=NDIMS;
int Kinematics::LD_JacobianPseudoInverse=NJOINTS;
int Kinematics::LD_Nullspace_matrix=NJOINTS;
int Kinematics::INC=1;
bool Kinematics::valid_Jacobian(false);
bool Kinematics::valid_JacobianPseudoInverse(false);
bool Kinematics::valid_Nullspace_matrix(false);
double Kinematics::JacobianEE[NJOINTS][NDIMS];
double Kinematics::Jacobian0[NJOINTS][NDIMS];
double Kinematics::Jacobian0PseudoInverse[NDIMS][NJOINTS];
double Kinematics::Nullspace_matrix[NJOINTS][NJOINTS];
std::stringstream Kinematics::last_error;
void Kinematics::Jacobian0_times_vector(double *q, double *out) {
if (!valid_Jacobian) {
throw "Current Jacobian matrix not available";
}
// multiply by the supplied vector
int M=NDIMS;
int N=NJOINTS;
dgemv_(&TRANSN, &M, &N, &ALPHA,
&Jacobian0[0][0], &LD_Jacobian,
(double*)q, &INC,
&BETA, out, &INC);
}
void Kinematics::JacobianPseudoInverse_times_vector(R6 &v, double *out) {
if (!valid_Jacobian) {
throw "Current Jacobian matrix not available";
}
if (!valid_JacobianPseudoInverse) {
// must be at a singularity, so cannot use the Pseudo Inverse.
// calling function can catch this as a const char *.
std::string error = "No valid Jacobian Pseudo Inverse available: ";
error += last_error.str();
throw (const char *) error.c_str();
}
// multiply by the supplied vector
int M=NJOINTS;
int N=NDIMS;
double B[6];
B[0]=v.v[0]; B[1]=v.v[1]; B[2]=v.v[2]; B[3]=v.w[0]; B[4]=v.w[1]; B[5]=v.w[2];
dgemv_(&TRANSN, &M, &N, &ALPHA,
&Jacobian0PseudoInverse[0][0], &LD_JacobianPseudoInverse,
B, &INC, &BETA,
out, &INC);
}
void Kinematics::Jacobian0Transpose_times_vector(R6 &v, double *out) {
if (!valid_Jacobian) {
throw "Current Jacobian matrix not available";
}
int M=NDIMS;
int N=NJOINTS;
double B[6];
B[0]=v.v[0]; B[1]=v.v[1]; B[2]=v.v[2]; B[3]=v.w[0]; B[4]=v.w[1]; B[5]=v.w[2];
dgemv_(&TRANST, &M, &N, &ALPHA,
&Jacobian0 [0][0], &LD_Jacobian,
B, &INC,
&BETA, out, &INC);
}
// Computes the product of Jacobian (in EE frame) transpose with the
// input vector
void Kinematics::JacobianEETranspose_times_vector(R6 &v, double *out) {
if (!valid_Jacobian) {
throw "Current Jacobian matrix not available";
}
int M=NDIMS;
int N=NJOINTS;
double B[6];
B[0]=v.v[0]; B[1]=v.v[1]; B[2]=v.v[2]; B[3]=v.w[0]; B[4]=v.w[1]; B[5]=v.w[2];
dgemv_(&TRANST, &M, &N, &ALPHA,
&JacobianEE [0][0], &LD_Jacobian,
B, &INC,
&BETA, out, &INC);
}
SE3 Kinematics::forward_kinematics(Link* link){
SE3 H = (SE3)link[Link::L0];
for(int l=Link::L1; l<=Link::Ln; l++)
H = H * (SE3)link[l];
return H;
}
void Kinematics::update_jacobians(Link *links) {
// all the matrices are in column-major order, for Fortran
// as soon as we start changing the Jacobians, the Pseudo-Inverse
// be out of date, so go ahead and mark it now
valid_JacobianPseudoInverse=false;
valid_Nullspace_matrix=false;
// calculate the Jacobian in the End-Effector frame and
// the Link 0 frame
Jacobians(JacobianEE, Jacobian0, links);
valid_Jacobian=true;
PseudoInverse(Jacobian0PseudoInverse,Jacobian0);
Nullspace_Matrix(Nullspace_matrix,Jacobian0PseudoInverse,Jacobian0);
}
void Kinematics::PseudoInverse(double JPI[][NJOINTS],
double J0[][NDIMS]) {
static double A[NJOINTS][NDIMS];
static double S[NDIMS];
static int LD_U=NDIMS;
static int LD_VT=NJOINTS;
static int LD_DUT=NJOINTS;
static int L_WORK=5*NDIMS;
static double U[NDIMS][NDIMS];
static double VT[NJOINTS][NJOINTS];
static double DUT[NDIMS][NJOINTS];
static double WORK[5*NDIMS];
int INFO;
static const double maxConditionNumber = 24;
last_error.str() = std::string("");
// copy over the Jacobian (since the A matrix will be changed)
memcpy(A,Jacobian0,NJOINTS*NDIMS*sizeof(double));
// find SVD of Jacobian
char JOBU='A';
char JOBVT='A';
int M=NDIMS;
int N=NJOINTS;
dgesvd_(&JOBU, &JOBVT, &M, &N,
&A[0][0], &LD_Jacobian,
&S[0],
&U[0][0], &LD_U,
&VT[0][0], &LD_VT,
&WORK[0], &L_WORK,
&INFO);
if (INFO<0) {
last_error.str() = std::string("Bad argument number ");
last_error << -INFO;
last_error << " to dgesvd call";
} else if (INFO > 0) {
last_error.str() = std::string("dgesvd: ");
last_error << INFO;
last_error << " superdiagonals did not converge to zero";
}
// Calculate the pseudo-inverse of D by inverting the S values,
// thresholding them as we go. We'll calculate them in-place,
// reusing the same storage.
thresholded_count=0;
zero_count=0;
double max_eigen = S[0];
for (int i=0; i<NDIMS; ++i) {
if (S[i] > 0) {
if ((i>0) && (max_eigen / S[i] > maxConditionNumber)) {
S[i] = maxConditionNumber / max_eigen; // threshold and invert
} else {
S[i] = 1.0/S[i]; // just invert
}
max_condition=max_eigen * S[i];
} else {
zero_count++;
}
}
// Calculate D * U**T
// top rows come from U
for (int r=0; r<NDIMS; ++r) {
for (int c=0; c<NDIMS; ++c) {
DUT[c][r] = U[r][c] * S[r];
}
}
// remaining rows are all zero
for (int r=NDIMS; r<NJOINTS; ++r) {
for (int c=0; c<NDIMS; ++c) {
DUT[c][r] = 0;
}
}
// finally, we calculate V * DUT
{
int M=NJOINTS;
int N=NDIMS;
int K=NJOINTS;
dgemm_(&TRANST, &TRANSN, &M, &N, &K,
&ALPHA, &VT[0][0], &LD_VT,
&DUT[0][0], &LD_DUT, &BETA,
&Jacobian0PseudoInverse[0][0], &LD_JacobianPseudoInverse);
}
valid_JacobianPseudoInverse=true;
return;
}
void Kinematics::Nullspace_projection(double *v, double *result) {
if (!valid_Nullspace_matrix) {
throw "No valid nullspace matrix available";
}
int M=NJOINTS;
int N=NJOINTS;
dgemv_(&TRANSN, &M, &N, &ALPHA,
&Nullspace_matrix[0][0], &LD_Nullspace_matrix,
v, &INC, &BETA,
result, &INC);
}
/*
* Body manipulator Jacobian
* Paul IEEE SMC 11(6) 1981
*
* BIG FAT WARNING: The jacobians are in column major (for Fortran)
*/
void Kinematics::Jacobians(double JN[][NDIMS], double J0[][NDIMS], Link *links){
SE3 U;
double local_JN[NJOINTS][NDIMS];
if (!JN) {
JN=local_JN; // use our temp storage so that we can successfully
// compute J0 even if JN isn't defined
}
for(int l=Link::Ln; l>=Link::L1; --l){
U = ((SE3)links[l]) * U;
JN[l-1][0] = U[SE3::TX]*U[SE3::NY] - U[SE3::TY]*U[SE3::NX];
JN[l-1][1] = U[SE3::TX]*U[SE3::OY] - U[SE3::TY]*U[SE3::OX];
JN[l-1][2] = U[SE3::TX]*U[SE3::AY] - U[SE3::TY]*U[SE3::AX];
JN[l-1][3] = U[SE3::NZ];
JN[l-1][4] = U[SE3::OZ];
JN[l-1][5] = U[SE3::AZ];
}
// Rotate the end-effector Jacobian to the base frame
if (J0) {
for (int i=0; i<Kinematics::NJOINTS; ++i) {
// upper three rows, translation
J0[i][0] = JN[i][0]*U[SE3::R11] + JN[i][1]*U[SE3::R12] + JN[i][2]*U[SE3::R13];
J0[i][1] = JN[i][0]*U[SE3::R21] + JN[i][1]*U[SE3::R22] + JN[i][2]*U[SE3::R23];
J0[i][2] = JN[i][0]*U[SE3::R31] + JN[i][1]*U[SE3::R32] + JN[i][2]*U[SE3::R33];
// bottom three rows, rotation
J0[i][3] = JN[i][3]*U[SE3::R11] + JN[i][4]*U[SE3::R12] + JN[i][5]*U[SE3::R13];
J0[i][4] = JN[i][3]*U[SE3::R21] + JN[i][4]*U[SE3::R22] + JN[i][5]*U[SE3::R23];
J0[i][5] = JN[i][3]*U[SE3::R31] + JN[i][4]*U[SE3::R32] + JN[i][5]*U[SE3::R33];
}
}
}
R3 Kinematics::Elbow_Velocity(double q[], double qd[]) {
// calculate the Jacobian for the Elbow in this config
static double Jacobian[3][3];
SE3 U;
for (int l=Link::L3; l>=Link::L1; --l) {
vlinks[l].theta(q[l-1]); // set the joint angle
U = ((SE3)vlinks[l])*U; // update the transform
Jacobian[l-1][0] = U[SE3::TX]*U[SE3::NY] - U[SE3::TY]*U[SE3::NX];
Jacobian[l-1][1] = U[SE3::TX]*U[SE3::OY] - U[SE3::TY]*U[SE3::OX];
Jacobian[l-1][2] = U[SE3::TX]*U[SE3::AY] - U[SE3::TY]*U[SE3::AX];
}
// multiply the jacobian by the joint velocities
R3 xyz_vel;
int M(3), N(3), LD_J(3);
dgemv_(&TRANSN, &M, &N, &ALPHA,
&Jacobian[0][0], &LD_J,
qd, &INC,
&BETA, xyz_vel.x, &INC);
return xyz_vel;
}
R3 Kinematics::Endpoint_Velocity(double q[], double qd[]) {
// calculate the Jacobian for the Endpoint (350mm past elbow)
static double Jacobian[4][3];
SE3 U;
for (int l=Link::L4; l>=Link::L1; --l) {
vlinks[l].theta(q[l-1]); // set the joint angle
U = ((SE3)vlinks[l])*U; // update the transform
Jacobian[l-1][0] = U[SE3::TX]*U[SE3::NY] - U[SE3::TY]*U[SE3::NX];
Jacobian[l-1][1] = U[SE3::TX]*U[SE3::OY] - U[SE3::TY]*U[SE3::OX];
Jacobian[l-1][2] = U[SE3::TX]*U[SE3::AY] - U[SE3::TY]*U[SE3::AX];
}
// multiply the jacobian by the joint velocities
R3 xyz_vel;
int M(3), N(4), LD_J(3);
dgemv_(&TRANSN, &M, &N, &ALPHA,
&Jacobian[0][0], &LD_J,
qd, &INC,
&BETA, xyz_vel.x, &INC);
return xyz_vel;
}
void Kinematics::Nullspace_Matrix(double Nullspace_matrix[][NJOINTS],
double JPI[][NJOINTS],
double J[][NDIMS]) {
if (!valid_Jacobian) {
throw "No valid Jacobian available";
} else if (!valid_JacobianPseudoInverse) {
throw "No valid Jacobian Pseudo-Inverse available";
}
int M=NJOINTS;
int N=NJOINTS;
int K=NDIMS;
dgemm_(&TRANSN, &TRANSN, &M, &N, &K,
&ALPHA, &JPI[0][0], &LD_JacobianPseudoInverse,
&J[0][0], &LD_Jacobian, &BETA,
&Nullspace_matrix[0][0], &LD_Nullspace_matrix);
// subtract the result from the identity matrix
for (int r=0; r<NJOINTS; ++r) {
for (int c=0; c<NJOINTS; ++c) {
if (r==c) {
// diagonal term
Nullspace_matrix[c][r] = 1-Nullspace_matrix[c][r];
} else {
// off-diagonal term
Nullspace_matrix[c][r] = 0-Nullspace_matrix[c][r];
}
}
}
valid_Nullspace_matrix = true;
}
void Kinematics::JacobianDB(double J[][NDIMS], Link *links){
SE3 U,EE;
R3 v,axis,anchor,tEE;
/*
for(int l=Link::L1; l <= Link::Ln; l++)
{
EE = (((SE3)links[l])^-1) * EE;
}*/
EE = forward_kinematics(links);
tEE = R3(EE[3],EE[7],EE[11]);
U = (SE3)links[Link::L0];
for(int l=Link::L1; l <= Link::Ln; l++)
{
axis = R3(U[2],U[6],U[10]);
anchor = R3(U[3],U[7],U[11]);
v = axis^(anchor - tEE);
J[l-1][0] = v[0];
J[l-1][1] = v[1];
J[l-1][2] = v[2];
J[l-1][3] = 0;
J[l-1][4] = 0;
J[l-1][5] = 0;
U = U * (SE3)links[l];
}
}
// row-major version of the EE Jacobian
void Kinematics::JacobianN(double J[][NJOINTS], Link *links){
SE3 U;
for(int l=Link::Ln; Link::L1<=l; l--){
U = ((SE3)links[l]) * U;
J[0][l-1] = U[SE3::TX]*U[SE3::NY] - U[SE3::TY]*U[SE3::NX];
J[1][l-1] = U[SE3::TX]*U[SE3::OY] - U[SE3::TY]*U[SE3::OX];
J[2][l-1] = U[SE3::TX]*U[SE3::AY] - U[SE3::TY]*U[SE3::AX];
J[3][l-1] = U[SE3::NZ];
J[4][l-1] = U[SE3::OZ];
J[5][l-1] = U[SE3::AZ];
}
}
void Kinematics::InitializeVelocityLinks() {
vlinks[Link::L0]=Link( DH( 0.0000, 0.0000, 0.0000, 0.0000), 0,
R3( 0.0000, 0.0000, 0.0000),
Inertia(0,0,0,0,0,0));
vlinks[Link::L1]=Link( DH( -M_PI_2, 0.0000, 0.0000, 0.0000), 0,
R3( 0.0000, 0.0000, 0.0000),
Inertia(0,0,0,0,0,0));
vlinks[Link::L2]=Link( DH( M_PI_2, 0.0000, 0.0000, 0.0000), 0,
R3( 0.0000, 0.0000, 0.0000),
Inertia(0,0,0,0,0,0));
vlinks[Link::L3]=Link( DH( -M_PI_2, 0.0450, 0.5500, 0.0000), 0,
R3( 0.0000, 0.0000, 0.0000),
Inertia(0,0,0,0,0,0));
vlinks[Link::L4]=Link( DH( M_PI_2, 0.3529, 0.0000, -M_PI_2-0.1279), 0,
R3( 0.0000, 0.0000, 0.0000),
Inertia(0,0,0,0,0,0)); // origin 350mm beyond elbow
}
int Kinematics::thresholded_count=0;
int Kinematics::zero_count=0;
double Kinematics::max_condition=0;
double Kinematics::thresholded_values[NJOINTS];
OWD::Link Kinematics::vlinks[5];
}; // namespace OWD
| [
"rui.defigueiredo@kustar.ac.ae"
] | rui.defigueiredo@kustar.ac.ae |
45cca8c30585b142d329d7f054d7ed0055d6b6f4 | 1fb94747193ca54c22bfd57fb8993978d7356063 | /36/jmuduo/muduo/net/Buffer.h | e9e8d7c916695565f5bee1a3c2a9d8f47a131f73 | [] | no_license | lightjameslyy/muduotest | 38b8bd06bbdb821cb1e22f3ea9057b80ee61f5ab | 93d91d2450752fb4367657211319507deb8224e4 | refs/heads/master | 2020-04-20T14:42:04.425109 | 2017-08-25T03:51:48 | 2017-08-25T03:51:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,737 | h | // Copyright 2010, Shuo Chen. All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
// This is a public header file, it must only include public header files.
#ifndef MUDUO_NET_BUFFER_H
#define MUDUO_NET_BUFFER_H
#include <muduo/base/copyable.h>
#include <muduo/base/StringPiece.h>
#include <muduo/base/Types.h>
#include <muduo/net/Endian.h>
#include <algorithm>
#include <vector>
#include <assert.h>
#include <string.h>
//#include <unistd.h> // ssize_t
namespace muduo
{
namespace net
{
/// A buffer class modeled after org.jboss.netty.buffer.ChannelBuffer
///
/// @code
/// +-------------------+------------------+------------------+
/// | prependable bytes | readable bytes | writable bytes |
/// | | (CONTENT) | |
/// +-------------------+------------------+------------------+
/// | | | |
/// 0 <= readerIndex <= writerIndex <= size
/// @endcode
class Buffer : public muduo::copyable
{
public:
static const size_t kCheapPrepend = 8;
static const size_t kInitialSize = 1024;
Buffer()
: buffer_(kCheapPrepend + kInitialSize),
readerIndex_(kCheapPrepend),
writerIndex_(kCheapPrepend)
{
assert(readableBytes() == 0);
assert(writableBytes() == kInitialSize);
assert(prependableBytes() == kCheapPrepend);
}
// default copy-ctor, dtor and assignment are fine
void swap(Buffer& rhs)
{
buffer_.swap(rhs.buffer_);
std::swap(readerIndex_, rhs.readerIndex_);
std::swap(writerIndex_, rhs.writerIndex_);
}
size_t readableBytes() const
{ return writerIndex_ - readerIndex_; }
size_t writableBytes() const
{ return buffer_.size() - writerIndex_; }
size_t prependableBytes() const
{ return readerIndex_; }
const char* peek() const
{ return begin() + readerIndex_; }
const char* findCRLF() const
{
const char* crlf = std::search(peek(), beginWrite(), kCRLF, kCRLF+2);//闭开区间
return crlf == beginWrite() ? NULL : crlf;
}
const char* findCRLF(const char* start) const
{
assert(peek() <= start);
assert(start <= beginWrite());
const char* crlf = std::search(start, beginWrite(), kCRLF, kCRLF+2);
return crlf == beginWrite() ? NULL : crlf;
}
// retrieve returns void, to prevent
// string str(retrieve(readableBytes()), readableBytes());
// the evaluation of two functions are unspecified
void retrieve(size_t len)
{
assert(len <= readableBytes());
if (len < readableBytes())
{
readerIndex_ += len;
}
else
{
retrieveAll();
}
}
void retrieveUntil(const char* end)
{
assert(peek() <= end);
assert(end <= beginWrite());
retrieve(end - peek());
}
void retrieveInt32()
{
retrieve(sizeof(int32_t));
}
void retrieveInt16()
{
retrieve(sizeof(int16_t));
}
void retrieveInt8()
{
retrieve(sizeof(int8_t));
}
void retrieveAll()
{
readerIndex_ = kCheapPrepend;
writerIndex_ = kCheapPrepend;
}
string retrieveAllAsString()
{
return retrieveAsString(readableBytes());;
}
string retrieveAsString(size_t len)
{
assert(len <= readableBytes());
string result(peek(), len);
retrieve(len);
return result;
}
StringPiece toStringPiece() const
{
return StringPiece(peek(), static_cast<int>(readableBytes()));
}
void append(const StringPiece& str)
{
append(str.data(), str.size());
}
void append(const char* /*restrict*/ data, size_t len)
{
ensureWritableBytes(len);
std::copy(data, data+len, beginWrite());
hasWritten(len);
}
void append(const void* /*restrict*/ data, size_t len)
{
append(static_cast<const char*>(data), len);
}
// 确保缓冲区可写空间>=len,如果不足则扩充
void ensureWritableBytes(size_t len)
{
if (writableBytes() < len)
{
makeSpace(len);
}
assert(writableBytes() >= len);
}
char* beginWrite()
{ return begin() + writerIndex_; }
const char* beginWrite() const
{ return begin() + writerIndex_; }
void hasWritten(size_t len)
{ writerIndex_ += len; }
///
/// Append int32_t using network endian
///
void appendInt32(int32_t x)
{
int32_t be32 = sockets::hostToNetwork32(x);
append(&be32, sizeof be32);
}
void appendInt16(int16_t x)
{
int16_t be16 = sockets::hostToNetwork16(x);
append(&be16, sizeof be16);
}
void appendInt8(int8_t x)
{
append(&x, sizeof x);
}
///
/// Read int32_t from network endian
///
/// Require: buf->readableBytes() >= sizeof(int32_t)
int32_t readInt32()
{
int32_t result = peekInt32();
retrieveInt32();
return result;
}
int16_t readInt16()
{
int16_t result = peekInt16();
retrieveInt16();
return result;
}
int8_t readInt8()
{
int8_t result = peekInt8();
retrieveInt8();
return result;
}
///
/// Peek int32_t from network endian
///
/// Require: buf->readableBytes() >= sizeof(int32_t)
int32_t peekInt32() const
{
assert(readableBytes() >= sizeof(int32_t));
int32_t be32 = 0;
::memcpy(&be32, peek(), sizeof be32);
return sockets::networkToHost32(be32);
}
int16_t peekInt16() const
{
assert(readableBytes() >= sizeof(int16_t));
int16_t be16 = 0;
::memcpy(&be16, peek(), sizeof be16);
return sockets::networkToHost16(be16);
}
int8_t peekInt8() const
{
assert(readableBytes() >= sizeof(int8_t));
int8_t x = *peek();
return x;
}
///
/// Prepend int32_t using network endian
///
void prependInt32(int32_t x)
{
int32_t be32 = sockets::hostToNetwork32(x);
prepend(&be32, sizeof be32);
}
void prependInt16(int16_t x)
{
int16_t be16 = sockets::hostToNetwork16(x);
prepend(&be16, sizeof be16);
}
void prependInt8(int8_t x)
{
prepend(&x, sizeof x);
}
void prepend(const void* /*restrict*/ data, size_t len)
{
assert(len <= prependableBytes());
readerIndex_ -= len;
const char* d = static_cast<const char*>(data);
std::copy(d, d+len, begin()+readerIndex_);
}
// 收缩,保留reserve个字节
void shrink(size_t reserve)
{
// FIXME: use vector::shrink_to_fit() in C++ 11 if possible.
Buffer other;
other.ensureWritableBytes(readableBytes()+reserve);
other.append(toStringPiece());//当前数据
swap(other);//当前对象与other交换
}
/// Read data directly into buffer.
///
/// It may implement with readv(2)
/// @return result of read(2), @c errno is saved
ssize_t readFd(int fd, int* savedErrno);
private:
char* begin()
{ return &*buffer_.begin(); }
const char* begin() const
{ return &*buffer_.begin(); }
void makeSpace(size_t len)
{
if (writableBytes() + prependableBytes() < len + kCheapPrepend)
{
// FIXME: move readable data
buffer_.resize(writerIndex_+len);
}
else
{
// move readable data to the front, make space inside buffer
assert(kCheapPrepend < readerIndex_);
size_t readable = readableBytes();
std::copy(begin()+readerIndex_,
begin()+writerIndex_,
begin()+kCheapPrepend);
readerIndex_ = kCheapPrepend;
writerIndex_ = readerIndex_ + readable;
assert(readable == readableBytes());
}
}
private:
std::vector<char> buffer_; // vector用于替代固定大小数组
size_t readerIndex_; // 读位置
size_t writerIndex_; // 写位置
static const char kCRLF[]; // "\r\n"
};
}
}
#endif // MUDUO_NET_BUFFER_H
| [
"ccc@ubuntu.(none)"
] | ccc@ubuntu.(none) |
b6a09b49c365e030f52d6b5ffc2abd3eae0d8783 | c225d891cd03c73da3798062139f95021773e1af | /1182.cpp | ddd28ce492183adeb7c7c3fcd2e53b08da80bb1e | [] | no_license | ototsuyume/poj-solution | 8061614654cab96b61c654ba6c2bd369a806cb86 | eb3746cb16a21f19d85b795b65fed8544ac99764 | refs/heads/master | 2016-09-06T00:19:32.312260 | 2015-02-27T09:21:49 | 2015-02-27T09:21:49 | 25,431,563 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,052 | cpp | #include <stdio.h>
#include <string.h>
int findroot(int A[],int n)
{
if(A[n]==n)
return n;
A[n]=findroot(A,A[n]);
return A[n];
}
bool same(int A[],int a,int b)
{
return findroot(A,a)==findroot(A,b);
}
void merge(int A[],int a,int b)
{
int ra = findroot(A,a);
A[ra] = findroot(A,b);
}
int main()
{
int n,k;
scanf("%d %d",&n,&k);
int *set = new int [3*n];
for(int i=0;i<n;++i)
{
set[i]=i;
set[i+n]=i+n;
set[i+2*n]=i+2*n;
}
int res=0;
for(int i=0;i<k;++i)
{
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
if(b>n||b<1||c>n||c<1)
++res;
else if(a==1)
{
--b;
--c;
if(same(set,b,c+n)||same(set,c,b+n))
{
++res;
}
else
{
merge(set,c,b);
merge(set,c+n,b+n);
merge(set,c+2*n,b+2*n);
}
}
else
{
--b;
--c;
if(same(set,b,c)||same(set,c,b+n))
++res;
else
{
merge(set,b,c+n);
merge(set,b+n,c+2*n);
merge(set,b+2*n,c);
}
}
}
printf("%d\n",res);
delete [] set;
return 0;
}
| [
"yume@ototsuyume.(none)"
] | yume@ototsuyume.(none) |
042524bc5fd6d36bee357152734df69edeea0d70 | 3bcbbcb988c0d6a9ed06cb865f7fbb6876e0fb9f | /core/src/cluster/CommChannel.cpp | dbc7c62e6d101bec0683b4a0d87361d3246f3c81 | [] | permissive | voei/megamol | 7afd26ff7bd106ecf99e56393593a8b92f978207 | 569b7b58c1f9bc5405b79549b86f84009329f668 | refs/heads/master | 2022-12-26T08:18:13.553724 | 2020-10-03T13:26:49 | 2020-10-03T13:26:49 | 263,350,326 | 0 | 0 | BSD-3-Clause | 2020-05-12T13:49:50 | 2020-05-12T13:49:50 | null | UTF-8 | C++ | false | false | 4,877 | cpp | /*
* CommChannel.cpp
*
* Copyright (C) 2010 by VISUS (Universitaet Stuttgart).
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "mmcore/cluster/CommChannel.h"
#include "vislib/IllegalStateException.h"
#include "vislib/sys/Log.h"
#include "vislib/UnsupportedOperationException.h"
using namespace megamol::core;
/*
* cluster::CommChannel::CommChannel
*/
cluster::CommChannel::CommChannel(void)
: vislib::Listenable<CommChannel>(),
vislib::net::SimpleMessageDispatchListener(),
channel(), counterpartName("Unknown") {
// Intentionally empty
this->receiver.AddListener(this);
}
/*
* cluster::CommChannel::CommChannel
*/
cluster::CommChannel::CommChannel(const cluster::CommChannel& src)
: vislib::Listenable<CommChannel>(),
vislib::net::SimpleMessageDispatchListener(),
channel(), counterpartName("Unknown") {
if (!(src == *this)) {
throw vislib::UnsupportedOperationException("copy ctor",
__FILE__, __LINE__);
}
}
/*
* cluster::CommChannel::~CommChannel
*/
cluster::CommChannel::~CommChannel(void) {
this->Close();
}
/*
* cluster::CommChannel::Close
*/
void cluster::CommChannel::Close(void) {
if (this->receiver.IsRunning()) {
this->receiver.Terminate(false);
}
if (!this->channel.IsNull()) {
try {
this->channel->Close();
} catch(...) {
}
this->channel = NULL;
}
}
/*
* cluster::CommChannel::IsOpen
*/
bool cluster::CommChannel::IsOpen(void) const {
return !this->channel.IsNull() && this->receiver.IsRunning();
}
/*
* cluster::CommChannel::Open
*/
void cluster::CommChannel::Open(vislib::SmartRef<vislib::net::AbstractCommClientChannel> channel) {
this->Close();
this->channel = channel;
vislib::net::SimpleMessageDispatcher::Configuration cfg(channel);
this->receiver.Start(&cfg);
if ((!this->receiver.IsRunning()) && (!this->channel.IsNull())) {
try {
this->channel->Close();
} catch(...) {
}
this->channel = NULL;
}
}
/*
* cluster::CommChannel::SendMessage
*/
void cluster::CommChannel::SendMessage(const vislib::net::AbstractSimpleMessage& msg) {
if (this->channel.IsNull()) {
throw vislib::IllegalStateException("Channel not open", __FILE__, __LINE__);
}
if (this->channel->Send(msg, msg.GetMessageSize(), 0, true) != msg.GetMessageSize()) {
throw vislib::Exception("Unable to send the whole message", __FILE__, __LINE__);
}
}
/*
* cluster::CommChannel::operator==
*/
bool cluster::CommChannel::operator==(const cluster::CommChannel& rhs) const {
return (this->channel == rhs.channel);
}
/*
* cluster::CommChannel::operator=
*/
cluster::CommChannel& cluster::CommChannel::operator=(const cluster::CommChannel& rhs) {
if (this->IsOpen() || rhs.IsOpen()) {
throw vislib::IllegalStateException("operator= is illegal on open channels", __FILE__, __LINE__);
}
this->channel = rhs.channel;
return *this;
}
/*
* cluster::CommChannel::OnCommunicationError
*/
bool cluster::CommChannel::OnCommunicationError(vislib::net::SimpleMessageDispatcher& src, const vislib::Exception& exception) throw() {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_WARN, "Communication Channel: %s\n", exception.GetMsgA());
return true; // keep receiver running
}
/*
* cluster::CommChannel::OnDispatcherExited
*/
void cluster::CommChannel::OnDispatcherExited(vislib::net::SimpleMessageDispatcher& src) throw() {
vislib::Listenable<CommChannel>::ListenerIterator iter = this->GetListeners();
while (iter.HasNext()) {
Listener *l = dynamic_cast<Listener *>(iter.Next());
if (l == NULL) continue;
l->OnCommChannelDisconnect(*this);
}
if (!this->channel.IsNull()) {
try {
this->channel->Close();
} catch(...) {
}
this->channel = NULL;
}
}
/*
* cluster::CommChannel::OnDispatcherStarted
*/
void cluster::CommChannel::OnDispatcherStarted(vislib::net::SimpleMessageDispatcher& src) throw() {
vislib::Listenable<CommChannel>::ListenerIterator iter = this->GetListeners();
while (iter.HasNext()) {
Listener *l = dynamic_cast<Listener *>(iter.Next());
if (l == NULL) continue;
l->OnCommChannelConnect(*this);
}
}
/*
* cluster::CommChannel::OnMessageReceived
*/
bool cluster::CommChannel::OnMessageReceived(vislib::net::SimpleMessageDispatcher& src, const vislib::net::AbstractSimpleMessage& msg) throw() {
vislib::Listenable<CommChannel>::ListenerIterator iter = this->GetListeners();
while (iter.HasNext()) {
Listener *l = dynamic_cast<Listener *>(iter.Next());
if (l == NULL) continue;
l->OnCommChannelMessage(*this, msg);
}
return true; // keep receiver running
}
| [
"guido.reina@informatik.uni-stuttgart.de"
] | guido.reina@informatik.uni-stuttgart.de |
844a0671dde6671581ca3093b07083a86d87dfa8 | c5fdce3264f55f1e52665baeb1f18bae33aa06c1 | /src/Transport.cpp | ae656724b7ff95bc323ab5e9ba7e39a492d513c2 | [] | no_license | streju/mathematical_operations_factory | 3ecd5e02c639957a593750c8ee28d24ad3826be0 | 8ed5b055bc20915c123474fcbb0b133474876e33 | refs/heads/master | 2022-09-12T19:35:33.579860 | 2020-06-01T15:52:04 | 2020-06-01T15:52:04 | 180,580,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,342 | cpp | #include "Transport.hpp"
#include <thread>
#include "Tools/Randoms.hpp"
#include "Tools/Timer.hpp"
Transport::Transport(const tools::ProgramStopControllerPtr& stopController,
const WarehouseEntryPointPtr& warehouse,
const ShopPtr& shop)
: stopController_(stopController), warehouse_(warehouse) , shop_(shop)
{
}
void Transport::start(unsigned transporterNr)
{
std::string prefix{"Transporter nr" + std::to_string(transporterNr) + ": "};
while (!stopController_->wasStopRequested())
{
simulateWayBetweenWarehouseAndShop(prefix);
Logger(prefix) << "Will arive to warehouse" << std::endl;
auto product = warehouse_->notifyAboutNewTransporter(transporterNr);
if (!product)
{
if (stopController_->wasStopRequested()) return;
Logger(prefix) << "Critical error! Transport loading failed.";
std::abort();
continue;
}
simulateWayBetweenWarehouseAndShop(prefix);
shop_->deliver(product);
}
}
void Transport::simulateWayBetweenWarehouseAndShop(const std::string& prefix)
{
tools::SecondsTimer timer;
std::this_thread::sleep_for(std::chrono::seconds(tools::random(5, 10)));
Logger(prefix) << "Traveled the road between warehouse and shop in " << timer.stopAndGetTime() << "s." << std::endl;
}
| [
"tomasz.streich@nokia.com"
] | tomasz.streich@nokia.com |
9b81e71006da21339c564a81a3f7d55233535635 | efd0a60b036299febc06f0b3cb9d445b172fa89a | /src-prng/pch.hpp | 9cffa0ffea7178a89547e5526233ba49a8be36ae | [
"MIT"
] | permissive | magicmoremagic/bengine-util | 7e5371f646e4eb13706bf0d3f45d4f5e58839630 | 398ccedf39ce8d85c15ad0b8334991a6498ac80d | refs/heads/master | 2021-01-12T04:51:24.733582 | 2018-09-02T00:26:55 | 2018-09-02T00:26:56 | 77,802,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | hpp | #pragma once
#ifndef BE_UTIL_PRNG_PCH_HPP_
#define BE_UTIL_PRNG_PCH_HPP_
// #ifndef BE_PCH_NO_DEPS
// # include <gsl/gsl>
// # ifdef BE_PCH_GLM
// # include <glm/glm.hpp>
// # endif
// # ifdef BE_PCH_SQLITE
// # include <sqlite3.h>
// # endif
// #endif
// #ifndef BE_PCH_NO_BOOST
// # ifdef BE_PCH_BOOST_ASIO
// # include <boost/asio/io_service.hpp>
// # endif
// # ifdef BE_PCH_BOOST_CONTAINER
// # include <boost/container/deque.hpp>
// # endif
// #endif
// #ifndef BE_PCH_NO_CORE
// # include <be/core/be.hpp>
// # include <be/core/alg.hpp>
// # include <be/core/services.hpp>
// # include <be/core/buf.hpp>
// # include <be/core/id.hpp>
// # ifndef BE_PCH_NO_IO
// # include <be/core/console.hpp>
// # include <be/core/logging.hpp>
// # endif
// #endif
// #ifndef BE_PCH_NO_STD
// # include <cstddef>
// # include <cstdint>
// # include <utility>
// # include <type_traits>
// # include <memory>
// # include <algorithm>
// # include <numeric>
// # include <vector>
// # include <array>
// # include <unordered_map>
// # include <unordered_set>
// # include <functional>
// # include <limits>
// # ifndef BE_PCH_NO_IO
// # include <iostream>
// # include <sstream>
// # include <iomanip>
// # endif
// #endif
#endif
| [
"ben@magicmoremagic.com"
] | ben@magicmoremagic.com |
cf8060532f76e1c78f3eb82b42a4be92c2f873d7 | 4bc340db113236d270cabb9b81bd0949689ed654 | /windows_embedded_7_2014M12/WINCE700/private/test/net/tapi/CETK40/tapiserver/tapiserver.cpp | d6d2e8a893673153eee165c23c74b8cb7647270d | [] | no_license | xiaoqgao/windows_embedded_7_2014M12 | c2eff379b961443083d17853891f6d68d8adf106 | 39042192614d5a12a9cc037cbc47ac9f70f28b52 | refs/heads/master | 2022-12-25T15:57:36.305277 | 2020-09-28T20:08:02 | 2020-09-28T20:08:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,344 | cpp | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft shared
// source or premium shared source license agreement under which you licensed
// this source code. If you did not accept the terms of the license agreement,
// you are not authorized to use this source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the SOURCE.RTF on your install media or the root of your tools installation.
// THE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
#include <windows.h>
#include <winbase.h> /* for "Sleep" */
#include <tchar.h>
#include <tapi.h>
#include <katoex.h>
#include <tux.h>
#include "tapiinfo.h"
#include "tuxmain.h"
extern CKato* g_pKato;
void MonitorLines(void);
long DropCall(HCALL);
LineInfoStr LineInfo[MAX_OPEN_LINES];
DWORD dwMediaMode = LINEMEDIAMODE_DATAMODEM;
DWORD dwTestRunTime = RUN_FOREVER; /* test length (milliseconds) */
DWORD dwConnectTimeout = RUN_FOREVER; /* time to hold call after connection made */
DWORD dwCallsReceived = 0; /* number of calls received */
DWORD dwCallsConnected = 0; /* number of calls connected */
DWORD dwTotalErrors = 0; /* total errors reported by program */
HINSTANCE hInst; /* handle to current instance */
DWORD nOpenLines = 0;
#define DEFAULT_THREAD_COUNT 0
TESTPROCAPI DefaultTest (UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE)
{
UNREFERENCED_PARAMETER(lpFTE);
if (uMsg == TPM_QUERY_THREAD_COUNT)
{
((LPTPS_QUERY_THREAD_COUNT)tpParam)->dwThreadCount = DEFAULT_THREAD_COUNT;
return TPR_HANDLED;
}
else if (uMsg != TPM_EXECUTE)
{
return TPR_NOT_HANDLED;
}
MonitorLines();
if (dwTotalErrors > 0)
return TPR_FAIL;
else if (dwCallsReceived == 0 && dwCallsConnected == 0)
{
g_pKato->Log(LOG_COMMENT, TEXT("No calls received, skipping test.\r\n"));
return TPR_SKIP;
}
else return TPR_PASS;
}
void MonitorLines(void)
{
long lRet; /* return value from function */
HLINEAPP hLineApp; /* line application handle */
DWORD dwAPIVersion = TAPI_CURRENT_VERSION; /* negotiated TAPI version */
DWORD dwNumDevs; /* number of line devices available */
DWORD dwCurrentTime, dwFinishTime,dwStartTime;/* times read via GetTickCount() */
DWORD i, j;
BOOL bAcceptMoreCalls = TRUE; /* set to FALSE when timer runs out */
DWORD nActiveCalls = 0; /* number of currently active calls */
BOOL bOverflowOccured = FALSE; /* checks if overflow occured in GetTickCount() */
TCHAR szBuff[512]; /* buffer for error messages */
LINEINITIALIZEEXPARAMS LineInitializeExParams; /* for TAPI initialization */
LINEEXTENSIONID ExtensionID; /* for "lineNegotiateAPIVersion" */
LINEMESSAGE LineMessage;
/* Timer initialization (Note: timers do not compensate */
/* for overflow in GetTickCount() every 49.7 days) */
dwStartTime = GetTickCount();
dwCurrentTime = GetTickCount();
g_pKato->Log(LOG_COMMENT, TEXT("Server started: tick count = %lu"), dwCurrentTime);
if (dwTestRunTime != RUN_FOREVER)
{
dwFinishTime = dwCurrentTime + dwTestRunTime;
if (dwFinishTime < dwCurrentTime)
bOverflowOccured = TRUE;
}
else
{
g_pKato->Log(LOG_COMMENT, TEXT("Server looping forever"));
dwFinishTime = 0xFFFFFFFF;
}
// Initialize TAPI:
g_pKato->Log(LOG_COMMENT, TEXT("Calling \"lineInitializeEx\":"));
LineInitializeExParams.dwTotalSize = sizeof(LINEINITIALIZEEXPARAMS);
LineInitializeExParams.dwOptions = LINEINITIALIZEEXOPTION_USEEVENT;
lRet = lineInitializeEx(&hLineApp, hInst, NULL, NULL, &dwNumDevs, &dwAPIVersion,
&LineInitializeExParams);
if (lRet)
{
g_pKato->Log(LOG_FAIL, TEXT("\"lineInitializeEx\" failed: %s"),
FormatLineError(lRet, szBuff));
dwTotalErrors++;
return;
}
g_pKato->Log(LOG_DETAIL, TEXT("\"lineInitializeEx\" succeeded: %lu devices available"),
dwNumDevs);
// Negotiate API version (the version returned from "lineInitializeEx"
// is not necessarily valid for NT):
g_pKato->Log(LOG_DETAIL, TEXT("Negotiating API version for device %lu:"),
LineInfo[0].dwDeviceID);
lRet = lineNegotiateAPIVersion(hLineApp, LineInfo[0].dwDeviceID, 0x00010000,
TAPI_CURRENT_VERSION, &dwAPIVersion, &ExtensionID);
if (lRet)
{
g_pKato->Log(LOG_FAIL, TEXT("\"lineNegotiateAPIVersion\" failed: %s"),
FormatLineError(lRet, szBuff));
++dwTotalErrors;
lineShutdown(hLineApp);
return;
}
g_pKato->Log(LOG_COMMENT, TEXT("API version used: %.8X"), dwAPIVersion);
for (i = 0; i < nOpenLines; ++i)
{
if (LineInfo[i].dwDeviceID >= dwNumDevs)
{ // skip out-of-range devices
g_pKato->Log(LOG_COMMENT, TEXT("Device ID (%lu) is outside permitted range (0 - %lu) - skipping"),
LineInfo[i].dwDeviceID, dwNumDevs - 1);
for (j = i + 1; j < nOpenLines; ++j)
LineInfo[j - 1].dwDeviceID = LineInfo[j].dwDeviceID;
nOpenLines--;
}
}
// TODO - This should be replaced with a call to "lineOpen" using LINEMAPPER
// to select a line to be monitored.
if (nOpenLines == 0)
{
g_pKato->Log(LOG_COMMENT, TEXT("No TAPI devices selected - using device 0 by default"));
nOpenLines++;
LineInfo[0].dwDeviceID = 0;
}
for (i = 0; i < nOpenLines; ++i)
{
g_pKato->Log(LOG_COMMENT, TEXT("Opening line %lu of %lu: TAPI device %lu"), i + 1,
nOpenLines, LineInfo[i].dwDeviceID);
// Open line - pass in array index as callback data
lRet = lineOpen(hLineApp, LineInfo[i].dwDeviceID, &(LineInfo[i].hLine),
dwAPIVersion, 0, i, LINECALLPRIVILEGE_OWNER, dwMediaMode, NULL);
if (lRet)
{
g_pKato->Log(LOG_FAIL, TEXT("\"lineOpen\" failed: %s"), FormatLineError(lRet, szBuff));
++dwTotalErrors;
continue;
}
g_pKato->Log(LOG_COMMENT, TEXT("Device %d successfully opened - handle = %lu"),
LineInfo[i].dwDeviceID, LineInfo[i].hLine);
}
while ((bAcceptMoreCalls) || (nActiveCalls > 0))
{
Sleep(50); // wait to let other applications catch up
dwCurrentTime = GetTickCount();
for (i = 0; i < nOpenLines; ++i)
{ // Check timeout for each call
if ((dwTestRunTime != RUN_FOREVER) &&
(dwCurrentTime > LineInfo[i].dwTime + dwTestRunTime) &&
(LineInfo[i].dwStatus == LINECALLSTATE_CONNECTED) &&
(((bOverflowOccured == TRUE) && (dwCurrentTime < dwStartTime)) || (bOverflowOccured == FALSE)) )
{
g_pKato->Log(LOG_COMMENT, TEXT("Call on line %lu expired - dropping"),
LineInfo[i].dwDeviceID);
DropCall(LineInfo[i].hCall);
LineInfo[i].dwStatus = LINECALLSTATE_DISCONNECTED;
}
}
if ((dwTestRunTime != RUN_FOREVER) && (dwCurrentTime > dwFinishTime) &&
(((bOverflowOccured == TRUE) && (dwCurrentTime < dwStartTime)) || (bOverflowOccured == FALSE)) )
{ // Check program timeout
if (bAcceptMoreCalls)
{
g_pKato->Log(LOG_COMMENT, TEXT("Time to quit - dropping any active calls"));
bAcceptMoreCalls = FALSE;
for (i = 0; i < nOpenLines; ++i)
{
if ((LineInfo[i].dwStatus != LINECALLSTATE_DISCONNECTED) &&
(LineInfo[i].dwStatus != LINECALLSTATE_IDLE) &&
(LineInfo[i].dwStatus != 0))
{
g_pKato->Log(LOG_COMMENT, TEXT("Dropping call on line %lu"),
LineInfo[i].dwDeviceID);
DropCall(LineInfo[i].hCall);
LineInfo[i].dwStatus = LINECALLSTATE_DISCONNECTED;
}
}
}
if ((dwCurrentTime - dwFinishTime > 15000) &&
(((bOverflowOccured == TRUE) && (dwCurrentTime < dwStartTime)) || (bOverflowOccured == FALSE)))
{
g_pKato->Log(LOG_COMMENT, TEXT("Time to quit application"));
nActiveCalls = 0; // Force to shutdown if hung for 15 seconds
}
}
lRet = lineGetMessage(hLineApp, &LineMessage, 0);
if (lRet)
{
// "lineGetMessage" will return LINEERR_OPERATIONFAILED
// if there is no message waiting in the queue
if (lRet != LINEERR_OPERATIONFAILED)
{
g_pKato->Log(LOG_FAIL, TEXT("\"lineGetMessage\" failed: %s"),
FormatLineError(lRet, szBuff));
++dwTotalErrors;
}
continue;
}
g_pKato->Log(LOG_COMMENT, TEXT("Message received: %s"),
FormatLineCallback(szBuff, LineMessage.hDevice, LineMessage.dwMessageID,
LineMessage.dwCallbackInstance, LineMessage.dwParam1, LineMessage.dwParam2,
LineMessage.dwParam3));
// Sanity check: dwCallbackInstance should be index into "LineInfo"
if (LineMessage.dwCallbackInstance >= nOpenLines)
{
g_pKato->Log(LOG_FAIL, TEXT("Callback ID %lu does not match an open line"),
LineMessage.dwCallbackInstance);
if (LineMessage.dwMessageID == LINE_APPNEWCALL)
DropCall((HCALL)LineMessage.dwParam2);
dwTotalErrors++;
continue;
}
i = LineMessage.dwCallbackInstance;
switch (LineMessage.dwMessageID)
{
case LINE_APPNEWCALL:
if (!bAcceptMoreCalls)
{
g_pKato->Log(LOG_COMMENT, TEXT("Quitting time - can't accept call"));
DropCall((HCALL)LineMessage.dwParam2);
break;
}
LineInfo[i].hCall = (HCALL)LineMessage.dwParam2;
LineInfo[i].dwTime = dwCurrentTime;
g_pKato->Log(LOG_COMMENT, TEXT("Call #%lu received at %lu - %lu active call(s)"),
++dwCallsReceived, LineInfo[i].dwTime, ++nActiveCalls);
break;
case LINE_CALLSTATE:
LineInfo[i].dwStatus = LineMessage.dwParam1;
switch (LineMessage.dwParam1)
{
case LINECALLSTATE_OFFERING:
g_pKato->Log(LOG_COMMENT, TEXT("Answering call:"));
if ((lRet = lineAnswer(LineInfo[i].hCall, NULL, 0)) < 0)
{
g_pKato->Log(LOG_FAIL, TEXT("\"lineAnswer\" failed: %s"),
FormatLineError(lRet, szBuff));
++dwTotalErrors;
}
else
g_pKato->Log(LOG_COMMENT, TEXT("\"lineAnswer\" succeeded; request ID = %lu"),
lRet);
break;
case LINECALLSTATE_CONNECTED:
g_pKato->Log(LOG_COMMENT, TEXT("Call connected - connection #%lu"),
++dwCallsConnected);
g_pKato->Log(LOG_COMMENT, TEXT("Connected after %lu milliseconds"),
dwCurrentTime - LineInfo[i].dwTime);
break;
case LINECALLSTATE_DISCONNECTED:
g_pKato->Log(LOG_COMMENT, TEXT("Call disconnected on line %lu"),
LineInfo[i].dwDeviceID);
// NT doesn't always send CALLSTATE_IDLE so we deallocate the call on DISCONNECTED
// CE "lineDeallocateCall" fails unless we are in CALLSTATE_IDLE
#ifdef UNDER_CE
break;
case LINECALLSTATE_IDLE:
#endif
g_pKato->Log(LOG_COMMENT, TEXT("Call on line %lu dropped - %lu active call(s)"),
LineInfo[i].dwDeviceID, --nActiveCalls);
lRet = lineDeallocateCall(LineInfo[i].hCall);
if (lRet)
{
g_pKato->Log(LOG_FAIL, TEXT("\"lineDeallocateCall\" failed: %s"),
FormatLineError(lRet, szBuff));
++dwTotalErrors;
}
else
{
g_pKato->Log(LOG_DETAIL, TEXT("Call deallocated"));
LineInfo[i].hCall = NULL;
}
break;
}
break;
case LINE_REPLY:
if (LineMessage.dwParam2)
{
g_pKato->Log(LOG_FAIL, TEXT("LINE_REPLY error: %s"),
FormatLineError(LineMessage.dwParam2, szBuff));
++dwTotalErrors;
}
break;
} // end switch (LineMessage.dwMessageID)
} // end while ((bAcceptMoreCalls) ||(bCallsActive))
for (i = 0; i < nOpenLines; ++i)
{
if (LineInfo[i].hLine)
{
lRet = lineClose(LineInfo[i].hLine);
if (lRet)
{
g_pKato->Log(LOG_FAIL, TEXT("\"lineClose\" failed for line %lu: %s"),
LineInfo[i].dwDeviceID, FormatLineError(lRet, szBuff));
++dwTotalErrors;
}
else
{
g_pKato->Log(LOG_COMMENT, TEXT("Line %lu successfully closed"),
LineInfo[i].dwDeviceID);
LineInfo[i].hLine = NULL;
}
}
}
lRet = lineShutdown(hLineApp);
if (lRet)
{
g_pKato->Log(LOG_FAIL, TEXT("\"lineShutdown\" failed: %s"),
FormatLineError(lRet, szBuff));
++dwTotalErrors;
}
else
g_pKato->Log(LOG_DETAIL, TEXT("\"lineShutdown\" completed"));
}
long DropCall(HCALL hCall)
{
long lRet; /* return value from function */
TCHAR szBuff[64]; /* buffer for error messages */
g_pKato->Log(LOG_COMMENT, TEXT("Dropping call:"));
if ((lRet = lineDrop(hCall, NULL, 0)) < 0)
{
g_pKato->Log(LOG_FAIL, TEXT("\"lineDrop\" failed: %s"),
FormatLineError(lRet, szBuff));
++dwTotalErrors;
}
else
g_pKato->Log(LOG_DETAIL, TEXT("\"lineDrop\" succeeded: request ID = %lu"), lRet);
return lRet;
}
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
4fdee2b120384ab385f04c02c4f93d11eaef956d | 4eb051f5060533d0a5cd5715b63f1ff1ba8edd20 | /j03/ex00/main.cpp | 7926cb30d52622996ea60ceed3413d576c483440 | [] | no_license | vquesnel/Piscine-Cpp | 2942261db9c44ad50abc58b290b8f093c8f8d0cf | b193a87149a4e4299918a6b9d7bfb21699f15e48 | refs/heads/master | 2021-03-27T13:55:13.350583 | 2018-01-26T17:57:48 | 2018-01-26T17:57:48 | 116,653,215 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,857 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vquesnel <vquesnel@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/10 09:39:11 by vquesnel #+# #+# */
/* Updated: 2018/01/10 12:35:13 by vquesnel ### ########.fr */
/* */
/* ************************************************************************** */
#include "FragTrap.hpp"
int main(void)
{
FragTrap f1;
FragTrap f2("NOOD");
FragTrap f3(f2);
std::cout << "---------------------------------------------" << std::endl;
while (f1.getHitPoints() > 0) {
f1.beRepaired(5);
f1.takeDamage(50);
f1.meleeAttack("Blightbot");
f1.rangedAttack("Holobot");
f1.vaulthunter_dot_exe("Miniontrap");
std::cout << std::endl;
}
std::cout << "---------------------------------------------" << std::endl;
while (f2.getHitPoints() > 0) {
f2.beRepaired(2);
f2.takeDamage(25);
f2.meleeAttack("Punkbot");
f2.vaulthunter_dot_exe("Holobot");
std::cout << std::endl;
}
std::cout << "---------------------------------------------" <<std::endl;
while (f3.getHitPoints() > 0) {
f3.beRepaired(4);
f3.takeDamage(35);
f3.vaulthunter_dot_exe("Claptrap");
std::cout << std::endl;
}
std::cout << "---------------------------------------------" <<std::endl;
return (0);
} | [
"vquesnel@student.42.fr"
] | vquesnel@student.42.fr |
2e6bdb642af149a29a2396ac32ae5a4191949cae | 2099b4e20c55fc0b92352faa22787a331bb6329c | /ProjetFenetrage/Line.cpp | 9d7ab142bd38e5f30aa2bd262ddb68d2b1d27fa0 | [] | no_license | EB-Elder/NARJFenetrage | 368342e39a3c98cfe5858a3a8f46ee17b34b6f8f | 1064a46e8a0fef24b7b7c5e81dbb04b41974554f | refs/heads/master | 2020-12-27T05:38:23.558027 | 2020-02-16T11:49:24 | 2020-02-16T11:49:24 | 237,782,048 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,641 | cpp | #define NON_INIT -10.0f
#define WHITE 0
#define RED 1
#define GREEN 2
#define BLUE 3
#define YELLOW 4
#define PURPLE 5
#define CYAN 6
#define BLACK 7
#define _USE_MATH_DEFINES
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <../../common/GLShader.h>
#include <iostream>
#include <vector>
#include <math.h>
#include "Vecteur.h"
#include "Line.h"
using namespace std;
Line::Line()
{
}
Line::Line(float P1x, float P1y, float P2x, float P2y, float width, float height)
{
setPos(P1x, P1y, width, height);
setPos(P2x, P2y, width, height);
}
Line::~Line()
{
}
void Line::drawLine()
{
if (!isDrawable) return;
glBegin(GL_LINES);
cout << endl;
glColor3fv(color.data());
glVertex2f(lineVec.getPos1()[0], lineVec.getPos1()[1]);
glColor3fv(color.data());
glVertex2f(lineVec.getPos2()[0], lineVec.getPos2()[1]);
if (lineDebug)
{
cout << "___x0___" << lineVec.getPos1()[0];
cout << "___y0___" << lineVec.getPos1()[1];
cout << "___x1___" << lineVec.getPos2()[0];
cout << "___y1___" << lineVec.getPos2()[1];
}
if (normalDebug)
{
float x = lineVec.getPos2()[0] - normalVec.getPos1()[0];
float y = normalVec.getPos2()[1] - normalVec.getPos1()[1];
float offsetX = (normalVec.getPos2()[0] + normalVec.getPos1()[0]) / 2;
float offsetY = (normalVec.getPos2()[1] + normalVec.getPos1()[1]) / 2;
glVertex2f(offsetX, offsetY);
glVertex2f(y + offsetX, -x + offsetY);
}
glEnd();
}
Vecteur Line::getVecteur()
{
return lineVec;
}
Vecteur Line::getNormal()
{
return normalVec;
}
void Line::setPos(float x, float y, float width, float height)
{
x = -1.0f + 2 * x / width;
y = 1.0f - 2 * y / height;
pointsTab.push_back(Point(x, y));
if (flipFlop == false)
{
lineVec.setPos_1(x, y);
isDrawable = false;
flipFlop = true;
}
else
{
lineVec.setPos_2(x, y);
isDrawable = true;
flipFlop = false;
lineVec.setDirection(lineVec.getPos2()[0] - lineVec.getPos1()[0], lineVec.getPos2()[1] - lineVec.getPos1()[1]);
normalVec.setDirection(lineVec.getPos2()[0] - lineVec.getPos1()[0], -(lineVec.getPos2()[1] - lineVec.getPos1()[1]));
}
}
void Line::switchColor()
{
if (colorCounter > BLACK)
{
colorCounter = 0;
}
switch (colorCounter)
{
case WHITE:
color = { 1.0,1.0,1.0 };
break;
case RED:
color = { 1.0,0.0,0.0 };
break;
case GREEN:
color = { 0.0,1.0,0.0 };
break;
case BLUE:
color = { 0.0,0.0,1.0 };
break;
case YELLOW:
color = { 1.0,1.0,0.0 };
break;
case PURPLE:
color = { 1.0,0.0,1.0 };
break;
case CYAN:
color = { 0.0,1.0,1.0 };
break;
case BLACK:
color = { 0.0,0.0,0.0 };
break;
}
colorCounter++;
}
| [
"elhajjam.abdallah1@gmail.com"
] | elhajjam.abdallah1@gmail.com |
1b816414ce811201800b36953badde3122beaf85 | 3448827dd4b7da1e2429343cf4f25abfce046aae | /src/TSolAnalyzer.h | a5ff6f7292184a4054e9064052e94e59cba30c5f | [] | no_license | xweizhi/libsolgem | ae06ac73ad487012b083f61ac29255d60be6f69e | 4e1b7202cd6c8bcd69b7e56f35b988125b9a67e5 | refs/heads/master | 2021-07-13T10:49:55.851611 | 2021-03-24T01:50:59 | 2021-03-24T01:50:59 | 68,326,838 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 272 | h | #ifndef __TSOLANALYZER_H
#define __TSOLANALYZER_H
#include "THaAnalyzer.h"
class TSolAnalyzer : public THaAnalyzer {
public:
TSolAnalyzer() {;}
virtual ~TSolAnalyzer() {;}
private:
Int_t f;
public:
ClassDef(TSolAnalyzer,0)
};
#endif//__TSOLANALYZER_H
| [
"uweizhisc@gmail.com"
] | uweizhisc@gmail.com |
71c52d3ee8289e3b3bc906585e94a227c96a7a5a | 895594e52af5f2ef624802d6fc408573640ded58 | /leetcode/837_new21Game.cpp | 509cca770492cd4fc606682ff5f8184aafdd0b9c | [] | no_license | NICKEY-CHEN/my_leetcode | d9c592a6a9662b7272ad0bca1befba47244ee4c8 | cbc1aea960eadc1a56fb5b5710534f74c836b4c7 | refs/heads/master | 2023-01-02T15:56:18.932954 | 2020-10-24T06:14:53 | 2020-10-24T06:14:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,099 | cpp | // @File : 837_new21Game.cpp
// @Source : https://leetcode-cn.com/problems/new-21-game/
// @Title : 837. 新21点
// @Auther : sun_ds
// @Date : 2020/6/3
/** 题目描述:
爱丽丝参与一个大致基于纸牌游戏 “21点” 规则的游戏,描述如下:
爱丽丝以 0 分开始,并在她的得分少于 K 分时抽取数字。 抽取时,她从 [1, W] 的范围中随机获得一个整数作为分数进行累计,其中 W 是整数。 每次抽取都是独立的,其结果具有相同的概率。
当爱丽丝获得不少于 K 分时,她就停止抽取数字。 爱丽丝的分数不超过 N 的概率是多少?
示例 1:
输入:N = 10, K = 1, W = 10
输出:1.00000
说明:爱丽丝得到一张卡,然后停止。
示例 2:
输入:N = 6, K = 1, W = 10
输出:0.60000
说明:爱丽丝得到一张卡,然后停止。
在 W = 10 的 6 种可能下,她的得分不超过 N = 6 分。
示例 3:
输入:N = 21, K = 17, W = 10
输出:0.73278
提示:
0 <= K <= N <= 10000
1 <= W <= 10000
如果答案与正确答案的误差不超过 10^-5,则该答案将被视为正确答案通过。
此问题的判断限制时间已经减少。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/new-21-game
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
/**
*
* 1.dp
* dp[x] 表示当前得分为 x 时的获胜概率。
* 有题目可知,当 x >= K 时,不能再次抽牌,所以此时概率固定了。
* 即 K <= x <= N 时概率为 1 ,x > N 时概率为 0.
* 由已知推未知,后面概率已知,我们所要求的是 dp[0] , 即从头开始他获胜的概率。
* 转移方程:
* dp[x] = 1 / w * ( dp[x+1] + dp[x+2] + ... + dp[x+W] ); x < K
* 当 x < k 时,需要继续抽牌,而由于每次抽牌的范围为[1,W],所以 dp[x] 的概率与后面 W 个概率有关,
* 又由于各个抽到每一张牌的概率都是相等的,所以乘以 1 / w。
*
* 由于每次抽牌的范围为[1,W],且 x >= k 就停止抽牌,所以牌面 x 的范围为 [0,k+w-1]
* 定义 vector<int> dp(k+w) 足够。
*
* 根据状态转移方程从后往前计算。
*
* 比较 dp[x] = 1 / w * ( dp[x+1] + dp[x+2] + ... + dp[x+W] )
* dp[x-1] = 1 / w * ( dp[x] + dp[x+1] + ... + dp[x+W-1] )
* 进一步优化 可得 dp[x-1] = dp[x] - (dp(x+W) - dp(x)) / w;
*
* 最后得到 dp[0] 即为所求结果。
*/
//dp
class Solution {
public:
double new21Game(int N, int K, int W) {
if (K == 0) {
return 1.0;
}
vector<double> dp(K + W , 0);
// K <= i <= N 获胜的概率为 1
for (int i = K; i <= N && i < K + W; i++) {
dp[i] = 1.0;
}
dp[K - 1] = 1.0 * min(N - K + 1, W) / W;
for (int i = K - 2; i >= 0; i--) {
// 借助前面 dp
dp[i] = dp[i + 1] - (dp[i + W + 1] - dp[i + 1]) / W;
}
return dp[0];
}
};
| [
"1406161541@qq.com"
] | 1406161541@qq.com |
0a924004544e6809cd0549b9b03e9765694c1427 | b2028b9de672fdd8da56f88e0f4582ce7be1033c | /4/4ass1/main.cpp | 329b912337e9b7a20e90486726b7c27d94f61114 | [] | no_license | somefunAgba/Accelerated-Cpp-Ex | d0a2ed0eef6b58d18cc340d2288e2415c6eee456 | 521005b485520c7dd4dc06c27c284cb864e59cc2 | refs/heads/master | 2021-01-02T22:27:56.261806 | 2017-08-04T09:30:32 | 2017-08-04T09:30:32 | 99,323,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,317 | cpp | #include <iomanip>
#include <ios>
#include <iostream>
#include <string>
#include <vector>
int main() {
int int_num(1000);
double double_num(1000.0);
while(int_num >= 1000 || double_num >= 1000.0){
std::cout << "Square of integers < 1000" << std::endl;
std::cout << "Number: "; std::cin >> int_num;
std::cout << "Square of double values < 1000.0" << std::endl;
std::cout << "Number: "; std::cin >> double_num;
}
std::vector<int> storei; storei.push_back(int_num);
std::string spacei = std::to_string(storei[0]);
int w = spacei.size();
std::cout << std::setw(w) << int_num
<< std::setw(w+w+2) << int_num * int_num << std::endl;
std::vector<double> stored; stored.push_back(double_num);
std::string spaced = std::to_string(stored[0]);
std::cout<<spaced<<std::endl;
int i = 0;
for(auto s : spaced){
if(s=='.'){
break;
}
else {
++i;
}
}
std::cout << i << std::endl;
int wd = spaced.size();
wd = wd-1-i; // 4 d.p
std::cout << wd << std::endl;
int prec =std::cout.precision();
std::cout << std::setw(wd) << double_num
<< std::setprecision(i+i+4) << std::setw(2+i+i+5)
<< double_num * double_num <<std::setprecision(prec)
<<std::endl;
return 0;
} | [
"oluwasegun.somefun@yahoo.co.uk"
] | oluwasegun.somefun@yahoo.co.uk |
077d345b1b278da9d5e7c45a9a7bfe1aa2e968cc | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /openanalytics-open/include/alibabacloud/openanalytics-open/model/GrantPrivilegesRequest.h | 4049e42c833bb09fed6989751fa2c66aa14df032 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,416 | h | /*
* 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.
*/
#ifndef ALIBABACLOUD_OPENANALYTICS_OPEN_MODEL_GRANTPRIVILEGESREQUEST_H_
#define ALIBABACLOUD_OPENANALYTICS_OPEN_MODEL_GRANTPRIVILEGESREQUEST_H_
#include <string>
#include <vector>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <alibabacloud/openanalytics-open/Openanalytics_openExport.h>
namespace AlibabaCloud
{
namespace Openanalytics_open
{
namespace Model
{
class ALIBABACLOUD_OPENANALYTICS_OPEN_EXPORT GrantPrivilegesRequest : public RpcServiceRequest
{
public:
GrantPrivilegesRequest();
~GrantPrivilegesRequest();
Struct getPrivilegeBag()const;
void setPrivilegeBag(const Struct& privilegeBag);
private:
Struct privilegeBag_;
};
}
}
}
#endif // !ALIBABACLOUD_OPENANALYTICS_OPEN_MODEL_GRANTPRIVILEGESREQUEST_H_ | [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
4ff4c97321be4cce6ad755e2dd82d34bf5792e53 | e94de8a015cc70ff16fa71bb4895e9be24f200bd | /src/WProtect/PE/PEImport.cpp | 47f0df4916acec7b141270286cbeef91f4b78813 | [] | no_license | xu7103224/wprotect-2 | ac60bec85e8df1bc92e215de3fbca7c51a5dd2d4 | 213b43136e69d1fa94579926dcb4e40f37363919 | refs/heads/master | 2021-05-31T01:35:31.051266 | 2015-12-17T13:07:35 | 2015-12-17T13:07:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,494 | cpp | #ifndef WPROTECTCONFIG_H
#define WPROTECTCONFIG_H
#include <WProtectConfig.h>
#endif
#include <stdio.h>
#include "PEImport.h"
#ifndef WINDOWS
#ifndef PESTRUCT_H
#define PESTRUCT_H
#include <PEStruct.h>
#endif
#else
#ifndef WINDOWS_H
#define WINDOWS_H
#include <Windows.h>
#endif
#endif
CPEImport::CPEImport(void)
{
}
CPEImport::~CPEImport(void)
{
}
void CPEImport::operator =(CPEFile& lPeFile)
{
SetInfo(lPeFile.GetInfo());
}
//µÃµœÕûžöÊמöµŒÈë±í
PIMAGE_IMPORT_DESCRIPTOR CPEImport::GetFirstImportDesc()
{
PIMAGE_IMPORT_DESCRIPTOR pImportDesc;
pImportDesc=(PIMAGE_IMPORT_DESCRIPTOR)GetDirectoryEntryToData(IMAGE_DIRECTORY_ENTRY_IMPORT);
if(!pImportDesc)
return NULL;
return pImportDesc;
}
//µÃµœ¹²ÓжàÉÙžödll
int CPEImport::GetImportDesCount()
{
int i=0;
PIMAGE_IMPORT_DESCRIPTOR pTempImport=GetFirstImportDesc();
while (pTempImport->FirstThunk)
{
++i;
++pTempImport;
}
return i;
}
// µÃµœÄ³žödllµŒÈë±í
PIMAGE_IMPORT_DESCRIPTOR CPEImport::GetImportDesc(int index)
{
int i=GetImportDesCount();
if (index>=i)
{
return NULL;
}
PIMAGE_IMPORT_DESCRIPTOR pTempImport=GetFirstImportDesc();
return &pTempImport[index];
}
// Ç¿ÖÆµÃµœÄ³žödllµŒÈë±í
PIMAGE_IMPORT_DESCRIPTOR CPEImport::ForceGetImportDesc(int index)
{
PIMAGE_IMPORT_DESCRIPTOR pTempImport=GetFirstImportDesc();
return &pTempImport[index];
}
//µÃµœÄ³žöAPI º¯ÊýµÄÃû×Ö
PIMAGE_IMPORT_BY_NAME CPEImport::GetImportFucByName(DWORD RavThunk)
{
PIMAGE_NT_HEADERS32 pNtH=NULL;
PIMAGE_IMPORT_BY_NAME pApiName=NULL;
pApiName=(PIMAGE_IMPORT_BY_NAME)RvaToPtr(RavThunk);
return pApiName;
}
DWORD CPEImport::GetImportThunk(PIMAGE_IMPORT_DESCRIPTOR pImportDesc)
{
return pImportDesc->OriginalFirstThunk?pImportDesc->OriginalFirstThunk:pImportDesc->FirstThunk;
}
BOOL CPEImport::ReLocalImport(DWORD dwRVA)
{
int iCount=GetImportDesCount();
CPEImport lPeSection;
lPeSection.SetInfo(GetInfo());
for (int i=0;i<iCount;i++)
{
PIMAGE_IMPORT_DESCRIPTOR pImport=GetImportDesc(i);
DWORD dwOrThunk=pImport->OriginalFirstThunk;
DWORD dwIatThunk=pImport->FirstThunk;
pImport->OriginalFirstThunk+=(dwRVA-0x2000);
pImport->Name+=(dwRVA-0x2000);
pImport->FirstThunk+=(dwRVA-0x2000);
while(*(DWORD*)RvaToPtr(dwOrThunk)!=0)
{
*(DWORD*)RvaToPtr(dwOrThunk)+=(dwRVA-0x2000);
*(DWORD*)RvaToPtr(dwIatThunk)+=(dwRVA-0x2000);
dwOrThunk+=sizeof(DWORD);
dwIatThunk+=sizeof(DWORD);
}
}
return TRUE;
}
| [
"transwareag.com"
] | transwareag.com |
8d8b5849e36541913054d98d24d82e07d8accec9 | c980055ec71c5c745743fa2acfc0168e7fde0bc3 | /main.cpp | e2f7b1e3ad36419a110453cef08e824f06297b8b | [] | no_license | cruzriga/Tablero | e0fdfd6c8ac3ce6aac61e1c25614cd442c346db0 | 557a21aa6b964f75384292d2c621b869401f9a69 | refs/heads/master | 2020-12-03T00:02:00.997168 | 2017-07-01T17:16:15 | 2017-07-01T17:16:15 | 95,970,503 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,475 | cpp | #include <cstdlib>
#include <iostream>
#include <conio.h>
using namespace std;
//variables globales
int flag = 0;
int movil[2];
int caja[2];
int pos_x = 0;
int pos_y = 12;
int cm_y =9;
int cm_x =11;
//prototipos
void dibuja_tablero(int &pos_x, int &pos_y, int &cm_x, int &cm_y, char tecla);
void resetea_posiciones();
int main(int argc, char *argv[])
{
char tecla;
int x = 22;
int y = 20;
// se guarda en variables globales la informacion de la posicion inicial
movil[0] = pos_x;
movil[1] = pos_y;
caja[0] = cm_x;
caja[1] = cm_y;
do{
system("cls");
// se le pasa por referencia las variables de la posicion del movil y la caja asi como la tecla presionada.
dibuja_tablero(pos_x,pos_y,cm_x,cm_y,tecla);
cout << "use las teclas a w s d para moverse: \n";
tecla=getch();
}while(tecla != 32);
system("PAUSE");
return EXIT_SUCCESS;
}
void dibuja_tablero(int &pos_x, int &pos_y, int &cm_x, int &cm_y, char tecla){
char p=179;
char r=196;
char c=197;
char t=180;
char t_=195;
char t__=194;
char t___=193;
char laa=218;
char lca=191;
char lab=192;
char lcb=217;
char icon = 169;
char pp = 219;
int x = 22;
int y = 20;
//posicion caja de madera
char cm = 176;
int n_pos_x=pos_x;
int n_pos_y=pos_y;
int n_cm_x=cm_x;
int n_cm_y=cm_y;
//se inicializa el contenido del char en ascii 176(un cuadro blanco)
char a[20][22] ={
{32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32},
{32,32,32,pp,pp,pp,pp,pp,pp,pp,pp,pp,pp,pp,pp,pp,pp,pp,pp,32,32,32},
{32,32,32,pp,32,32,32,32,32,32,32,32,32,32,32,32,32,32,pp,32,32,32},
{32,32,32,pp,32,32,32,32,32,32,32,32,32,32,32,32,32,32,pp,32,32,32},
{32,32,32,pp,32,32,32,pp,pp,pp,pp,pp,pp,pp,pp,pp,32,32,pp,32,32,32},
{32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,pp,32,32,pp,32,32,32},
{32,32,32,32,32,32,32,pp,32,32,32,32,32,32,32,pp,32,32,pp,32,32,32},
{32,32,32,pp,32,32,32,pp,32,32,32,32,32,32,32,pp,32,32,32,32,32,32},
{32,32,32,pp,32,32,32,pp,32,32,32,32,32,32,32,pp,32,32,32,32,32,32},
{32,32,32,pp,32,32,32,pp,32,32,32,32,32,32,32,pp,32,32,32,32,32,32},
{32,32,32,pp,32,32,32,pp,32,32,32,32,32,32,32,pp,32,32,32,32,32,32},
{32,32,32,pp,32,32,32,pp,32,32,32,32,32,32,32,pp,32,32,pp,32,32,32},
{32,32,32,pp,32,32,32,pp,pp,pp,pp,pp,pp,pp,pp,pp,32,32,pp,32,32,32},
{32,32,32,pp,32,32,32,32,32,32,32,32,32,32,32,32,32,32,pp,32,32,32},
{32,32,32,pp,32,32,32,32,pp,32,32,32,32,32,pp,32,32,32,pp,32,32,32},
{32,32,32,pp,32,32,32,32,pp,32,pp,pp,pp,32,pp,32,32,32,pp,32,32,32},
{32,32,32,pp,32,32,32,32,pp,32,32,32,32,32,pp,32,32,32,pp,32,32,32},
{32,32,32,pp,32,32,32,32,32,32,32,32,32,32,32,32,32,32,pp,32,32,32},
{32,32,32,pp,pp,pp,pp,pp,pp,pp,pp,32,pp,pp,pp,pp,pp,pp,pp,32,32,32},
{32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32},
};
// se ubica la caja en su posicion
if(a[cm_y][cm_x] == 32){
a[cm_y][cm_x]=cm;
}
//______________________________________________
// movimientos
// se mueve a la izq
if(tecla == 97){
n_pos_x = n_pos_x -1;
n_cm_x = n_cm_x -1;
}
// se mueve a la derecha
if(tecla == 100){
n_pos_x = n_pos_x +1;
n_cm_x = n_cm_x +1;
}
// se mueve a la para abajo
if(tecla == 115){
n_pos_y = n_pos_y +1;
n_cm_y = n_cm_y +1;
}
// se mueve para arriba
if(tecla == 119){
n_pos_y = n_pos_y -1;
n_cm_y = n_cm_y -1;
}
// verifico que en la nueva posicion no se salga y si se sale se resetea las posiciones
if(n_pos_x < 0 || n_pos_x > 21 || n_pos_y < 0 || n_pos_y > 19 ){
a[pos_y][pos_x]=32;
resetea_posiciones();
} else if(a[n_pos_y][n_pos_x] == 32){
// verifico que a donde se este moviendo este vacio, se le asigna la nueva pos del movil a las variables principales
pos_x = n_pos_x;
pos_y = n_pos_y;
}else if(a[n_pos_y][n_pos_x] == cm){
// verifico si haciadonde se mueve esta la caja, ser asi la caja se mueve y el movil toma su posicion
// si esta la caja, mirio si la nueva posicion de la caja no esta fuera
if(n_cm_x < 0 || n_cm_x > 21 || n_cm_y < 0 || n_cm_y > 19 ){
a[pos_y][pos_x]=32;
a[cm_y][cm_x]=32;
resetea_posiciones();
}else if(a[n_cm_y][n_cm_x] == 32){
// verifico que a donde se este moviendo este vacio, se le asigna la nueva pos del movil a las variables principales
a[pos_y][pos_x]=32;
a[cm_y][cm_x]=32;
cm_x = n_cm_x;
cm_y = n_cm_y;
pos_x = n_pos_x;
pos_y = n_pos_y;
}
}
cout<<"tecla: "<<tecla <<" pos_x:"<<n_pos_x<<" pos_y:"<<n_pos_y<< " value: "<<a[n_pos_y][n_pos_x];
//se coloca la posicion el movil
if(a[pos_y][pos_x] == 32){
a[pos_y][pos_x]=icon;
}
// se ubica la caja en su posicion
if(a[cm_y][cm_x] == 32){
a[cm_y][cm_x]=cm;
}
//--------------------------------------------------------------------
// muestro en pantalla el cuadro
for (int i = 0; i < y; ++i)
{
// dibuja el indice horizontal arriba
if(i == 0){
cout<<"\n";
// cout<<"\t";
cout<<" ";
for (int j = 0; j < x; ++j)
{
cout<<" ";
cout<<j;
if(j<10){cout<<" ";}
}
}
// dibuja la linea horizontal de arriba
if(i == 0){
cout<<"\n";
//cout<<"\t";
cout<<" ";
cout<<laa;
for (int j = 0; j < x; ++j)
{
cout<<r;
cout<<r;
if(j < x-1){
cout<<t__;
}else{
// si llega al final cierre el cuadro
cout<<lca;
}
}
}
//dibuja las casillas internas
cout<<"\n";
//cout<<"\t";
if(i < 10){
cout<<" "<<i;
}else{
cout<< i;
}
cout<<p;
for (int j = 0; j < x; ++j)
{
cout<<a[i][j];
cout<<a[i][j];
cout<<p;
}
// dibuja la linea horizontal
if(i<y-1){
cout<<"\n";
// cout<<"\t";
cout<<" ";
cout<<t_;
for (int j = 0; j < x; ++j)
{
cout<<r;
cout<<r;
if(j < x-1){
cout<<c;
}else{
// si llega al final cierre el cuadro
cout<<t;
}
}
}
// dibujo la ultima linea
if(i == y-1){
cout<<"\n";
//cout<<"\t";
cout<<" ";
cout<<lab;
for (int j = 0; j < x; ++j)
{
cout<<r;
cout<<r;
if(j < x-1){
cout<<t___;
}else{
// si llega al final cierre el cuadro
cout<<lcb;
}
}
}
}
cout<<"\n";
}
void resetea_posiciones(){
pos_x=movil[0];
pos_y=movil[1];
cm_x=caja[0];
cm_y=caja[1];
}
| [
"cruz.riga@hotmail.com"
] | cruz.riga@hotmail.com |
23dd1d8e6d7948e79b2f8a3d4a292fc8dee5b4d1 | 6948bbafbdc09038348213dde39d3f40be640b49 | /Source/LuaMachine/Private/LuaState.cpp | c39d6e7896c329abbae951dc644bc55d049b5165 | [
"MIT"
] | permissive | fromasmtodisasm/LuaMachine | 172b61b8cd10460695defbc4eb54be50f569753a | 21a6b405a0344635e1693348199dad2b9c1c30bb | refs/heads/master | 2020-09-20T22:17:06.103857 | 2019-09-05T15:39:02 | 2019-09-05T15:39:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,131 | cpp | // Copyright 2019 - Roberto De Ioris
#include "LuaState.h"
#include "LuaComponent.h"
#include "LuaMachine.h"
#include "GameFramework/Actor.h"
#include "Runtime/Core/Public/Misc/FileHelper.h"
#include "Runtime/Core/Public/Misc/Paths.h"
#include "Runtime/Core/Public/Serialization/BufferArchive.h"
#include "Runtime/CoreUObject/Public/UObject/TextProperty.h"
LUAMACHINE_API DEFINE_LOG_CATEGORY(LogLuaMachine);
ULuaState::ULuaState()
{
L = nullptr;
bLuaOpenLibs = true;
bDisabled = false;
bLogError = true;
bAddProjectContentDirToPackagePath = true;
bPersistent = false;
bEnableLineHook = false;
bEnableCallHook = false;
bEnableReturnHook = false;
}
ULuaState* ULuaState::GetLuaState(UWorld* InWorld)
{
CurrentWorld = InWorld;
if (L != nullptr)
{
return this;
}
if (bDisabled)
return nullptr;
L = luaL_newstate();
if (bLuaOpenLibs)
luaL_openlibs(L);
ULuaState** LuaExtraSpacePtr = (ULuaState**)lua_getextraspace(L);
*LuaExtraSpacePtr = this;
// get the global table
lua_pushglobaltable(L);
// override print
PushCFunction(ULuaState::TableFunction_print);
SetField(-2, "print");
GetField(-1, "package");
if (!OverridePackagePath.IsEmpty())
{
lua_pushstring(L, TCHAR_TO_UTF8(*OverridePackagePath));
SetField(-2, "path");
}
if (bAddProjectContentDirToPackagePath)
{
GetField(-1, "path");
const char* CurrentLuaPath = lua_tostring(L, -1);
FString NewPackagePath = FString(CurrentLuaPath) + ";" + FPaths::ProjectContentDir() + "/?.lua";
Pop();
lua_pushstring(L, TCHAR_TO_UTF8(*NewPackagePath));
SetField(-2, "path");
}
for (FString SubDir : AppendProjectContentDirSubDir)
{
GetField(-1, "path");
const char* CurrentLuaPath = lua_tostring(L, -1);
FString NewPackagePath = FString(CurrentLuaPath) + ";" + FPaths::ProjectContentDir() / SubDir + "/?.lua";
Pop();
lua_pushstring(L, TCHAR_TO_UTF8(*NewPackagePath));
SetField(-2, "path");
}
if (!OverridePackageCPath.IsEmpty())
{
lua_pushstring(L, TCHAR_TO_UTF8(*OverridePackageCPath));
SetField(-2, "cpath");
}
// manage RequireTable
GetField(-1, "preload");
for (TPair<FString, ULuaCode*>& Pair : RequireTable)
{
PushCFunction(ULuaState::TableFunction_package_preload);
SetField(-2, TCHAR_TO_UTF8(*Pair.Key));
}
for (TPair<FString, TSubclassOf<UBlueprintFunctionLibrary>>& Pair : RequireBlueprintFunctionLibraryTable)
{
PushCFunction(ULuaState::TableFunction_package_preload);
SetField(-2, TCHAR_TO_UTF8(*Pair.Key));
}
// pop package.preload
Pop(2);
// assign global symbols to nil, this will allow to override global functions/symbols
for (TPair<FString, FLuaValue>& Pair : Table)
{
PushNil();
SetField(-2, TCHAR_TO_UTF8(*Pair.Key));
}
// metatable
NewTable();
PushCFunction(MetaTableFunctionState__index);
SetField(-2, "__index");
PushCFunction(MetaTableFunctionState__newindex);
SetField(-2, "__newindex");
SetMetaTable(-2);
// pop global table
Pop();
int DebugMask = 0;
// install hooks
if (bEnableLineHook)
{
DebugMask |= LUA_MASKLINE;
}
if (bEnableCallHook)
{
DebugMask |= LUA_MASKCALL;
}
if (bEnableReturnHook)
{
DebugMask |= LUA_MASKRET;
}
if (DebugMask != 0)
{
lua_sethook(L, Debug_Hook, DebugMask, 0);
}
if (LuaCodeAsset)
{
if (!RunCodeAsset(LuaCodeAsset))
{
if (bLogError)
LogError(LastError);
ReceiveLuaError(LastError);
bDisabled = true;
lua_close(L);
L = nullptr;
return nullptr;
}
}
if (!LuaFilename.IsEmpty())
{
if (!RunFile(LuaFilename, true))
{
if (bLogError)
LogError(LastError);
ReceiveLuaError(LastError);
bDisabled = true;
lua_close(L);
L = nullptr;
return nullptr;
}
}
if (UserDataMetaTableFromCodeAsset)
{
if (!RunCodeAsset(UserDataMetaTableFromCodeAsset, 1))
{
if (bLogError)
LogError(LastError);
ReceiveLuaError(LastError);
bDisabled = true;
lua_close(L);
L = nullptr;
return nullptr;
}
UserDataMetaTable = ToLuaValue(-1);
Pop();
}
return this;
}
bool ULuaState::RunCodeAsset(ULuaCode* CodeAsset, int NRet)
{
if (CodeAsset->bCooked && CodeAsset->bCookAsBytecode)
{
#if PLATFORM_ANDROID
// fix size_t of the bytecode
if (CodeAsset->ByteCode.Num() >= 14)
CodeAsset->ByteCode[13] = sizeof(size_t);
#endif
return RunCode(CodeAsset->ByteCode, CodeAsset->GetPathName(), NRet);
}
return RunCode(CodeAsset->Code.ToString(), CodeAsset->GetPathName(), NRet);
}
bool ULuaState::RunFile(FString Filename, bool bIgnoreNonExistent, int NRet)
{
TArray<uint8> Code;
FString AbsoluteFilename = FPaths::Combine(FPaths::ProjectContentDir(), Filename);
if (!FPaths::FileExists(AbsoluteFilename))
{
if (bIgnoreNonExistent)
return true;
LastError = FString::Printf(TEXT("Unable to open file %s"), *Filename);
FLuaValue LuaLastError = FLuaValue(LastError);
FromLuaValue(LuaLastError);
return false;
}
if (FFileHelper::LoadFileToArray(Code, *AbsoluteFilename))
{
if (RunCode(Code, AbsoluteFilename, NRet))
{
return true;
}
return false;
}
LastError = FString::Printf(TEXT("Unable to open file %s"), *Filename);
FLuaValue LuaLastError = FLuaValue(LastError);
FromLuaValue(LuaLastError);
return false;
}
bool ULuaState::RunCode(FString Code, FString CodePath, int NRet)
{
TArray<uint8> Bytes;
Bytes.Append((uint8 *)TCHAR_TO_UTF8(*Code), FCStringAnsi::Strlen(TCHAR_TO_UTF8(*Code)));
return RunCode(Bytes, CodePath, NRet);
}
bool ULuaState::RunCode(TArray<uint8> Code, FString CodePath, int NRet)
{
FString FullCodePath = FString("@") + CodePath;
if (luaL_loadbuffer(L, (const char *)Code.GetData(), Code.Num(), TCHAR_TO_UTF8(*FullCodePath)))
{
LastError = FString::Printf(TEXT("Lua loading error: %s"), UTF8_TO_TCHAR(lua_tostring(L, -1)));
return false;
}
else
{
if (lua_pcall(L, 0, NRet, 0))
{
LastError = FString::Printf(TEXT("Lua execution error: %s"), UTF8_TO_TCHAR(lua_tostring(L, -1)));
return false;
}
}
return true;
}
int ULuaState::ToByteCode_Writer(lua_State* L, const void* Ptr, size_t Size, void* UserData)
{
TArray<uint8>* Output = (TArray<uint8> *)UserData;
Output->Append((uint8 *)Ptr, Size);
return 0;
}
TArray<uint8> ULuaState::ToByteCode(FString Code, FString CodePath, FString& ErrorString)
{
const TCHAR* CodeRaw = *Code;
FString FullCodePath = FString("@") + CodePath;
TArray<uint8> Output;
lua_State* L = luaL_newstate();
if (luaL_loadbuffer(L, TCHAR_TO_UTF8(CodeRaw), FCStringAnsi::Strlen(TCHAR_TO_UTF8(CodeRaw)), TCHAR_TO_UTF8(*FullCodePath)))
{
ErrorString = UTF8_TO_TCHAR(lua_tostring(L, -1));
Output.Empty();
lua_close(L);
return Output;
}
if (lua_dump(L, ULuaState::ToByteCode_Writer, &Output, 1))
{
ErrorString = UTF8_TO_TCHAR(lua_tostring(L, -1));
Output.Empty();
lua_close(L);
return Output;
}
lua_close(L);
return Output;
}
void ULuaState::FromLuaValue(FLuaValue& LuaValue, UObject* CallContext, lua_State* State)
{
if (!State)
State = this->L;
switch (LuaValue.Type)
{
case ELuaValueType::Bool:
lua_pushboolean(State, LuaValue.Bool ? 1 : 0);
break;
case ELuaValueType::Integer:
lua_pushinteger(State, LuaValue.Integer);
break;
case ELuaValueType::Number:
lua_pushnumber(State, LuaValue.Number);
break;
case ELuaValueType::String:
lua_pushstring(State, TCHAR_TO_UTF8(*LuaValue.String));
break;
case ELuaValueType::Table:
if (LuaValue.LuaRef == LUA_NOREF)
{
lua_newtable(State);
lua_pushvalue(State, -1);
// hold references in the main state
LuaValue.LuaRef = luaL_ref(this->L, LUA_REGISTRYINDEX);
LuaValue.LuaState = this;
break;
}
if (this != LuaValue.LuaState)
{
lua_pushnil(State);
break;
}
lua_rawgeti(this->L, LUA_REGISTRYINDEX, LuaValue.LuaRef);
if (this->L != State)
lua_xmove(this->L, State, 1);
break;
case ELuaValueType::Thread:
if (LuaValue.LuaRef == LUA_NOREF)
{
lua_newthread(State);
lua_pushvalue(State, -1);
LuaValue.LuaRef = luaL_ref(this->L, LUA_REGISTRYINDEX);
LuaValue.LuaState = this;
break;
}
if (this != LuaValue.LuaState)
{
lua_pushnil(State);
break;
}
lua_rawgeti(this->L, LUA_REGISTRYINDEX, LuaValue.LuaRef);
if (this->L != State)
lua_xmove(this->L, State, 1);
break;
case ELuaValueType::Function:
if (this != LuaValue.LuaState || LuaValue.LuaRef == LUA_NOREF)
{
lua_pushnil(State);
break;
}
lua_rawgeti(this->L, LUA_REGISTRYINDEX, LuaValue.LuaRef);
if (this->L != State)
lua_xmove(this->L, State, 1);
break;
case ELuaValueType::UObject:
{
NewUObject(LuaValue.Object);
ULuaComponent* LuaComponent = Cast<ULuaComponent>(LuaValue.Object);
if (LuaComponent)
{
// ensure we are in the same LuaState
if (LuaComponent->LuaState == GetClass())
{
LuaComponent->SetupMetatable(State);
}
}
else {
bool bHasMetaTable = false;
if (UserDataMetaTable.Type == ELuaValueType::Table)
{
FromLuaValue(UserDataMetaTable, nullptr, State);
lua_setmetatable(State, -2);
lua_getmetatable(State, -1);
bHasMetaTable = true;
}
else
{
lua_newtable(State);
}
// allow comparison between userdata/UObject/UFunction
lua_pushcfunction(State, ULuaState::MetaTableFunctionUserData__eq);
lua_setfield(State, -2, "__eq");
if (bHasMetaTable)
{
lua_pop(State, 1);
}
else
{
lua_setmetatable(State, -2);
}
}
}
break;
case ELuaValueType::UFunction:
// if no context is assigned to the function, own it !
if (!LuaValue.LuaState)
{
LuaValue.LuaState = this;
}
if (this != LuaValue.LuaState)
{
lua_pushnil(State);
break;
}
// first time we should have a CallContext, then we cache it in the Object field
if (!CallContext)
{
CallContext = LuaValue.Object;
}
if (CallContext)
{
UFunction* Function = CallContext->FindFunction(LuaValue.FunctionName);
if (Function)
{
// cache it for context-less calls
LuaValue.Object = CallContext;
FLuaUserData* LuaCallContext = (FLuaUserData*)lua_newuserdata(State, sizeof(FLuaUserData));
LuaCallContext->Type = ELuaValueType::UFunction;
LuaCallContext->Context = CallContext;
LuaCallContext->Function = Function;
lua_newtable(State);
lua_pushcfunction(State, ULuaState::MetaTableFunction__call);
lua_setfield(State, -2, "__call");
lua_setmetatable(State, -2);
return;
}
}
default:
lua_pushnil(State);
}
}
FLuaValue ULuaState::ToLuaValue(int Index, lua_State* State)
{
if (!State)
State = this->L;
FLuaValue LuaValue;
if (lua_isboolean(State, Index))
{
LuaValue.Type = ELuaValueType::Bool;
LuaValue.Bool = lua_toboolean(State, Index) != 0;
}
else if (lua_type(State, Index) == LUA_TSTRING)
{
LuaValue.Type = ELuaValueType::String;
LuaValue.String = FString(UTF8_TO_TCHAR(lua_tostring(State, Index)));
}
else if (lua_isinteger(State, Index))
{
LuaValue.Type = ELuaValueType::Integer;
LuaValue.Integer = lua_tointeger(State, Index);
}
else if (lua_type(State, Index) == LUA_TNUMBER)
{
LuaValue.Type = ELuaValueType::Number;
LuaValue.Number = lua_tonumber(State, Index);
}
else if (lua_istable(State, Index))
{
if (State != this->L)
lua_xmove(State, this->L, 1);
else
lua_pushvalue(State, Index);
LuaValue.Type = ELuaValueType::Table;
LuaValue.LuaState = this;
LuaValue.LuaRef = luaL_ref(this->L, LUA_REGISTRYINDEX);
}
else if (lua_isthread(State, Index))
{
if (State != this->L)
lua_xmove(State, this->L, 1);
else
lua_pushvalue(State, Index);
LuaValue.Type = ELuaValueType::Thread;
LuaValue.LuaState = this;
LuaValue.LuaRef = luaL_ref(this->L, LUA_REGISTRYINDEX);
}
else if (lua_isfunction(State, Index))
{
if (State != this->L)
lua_xmove(State, this->L, 1);
else
lua_pushvalue(State, Index);
LuaValue.Type = ELuaValueType::Function;
LuaValue.LuaState = this;
LuaValue.LuaRef = luaL_ref(this->L, LUA_REGISTRYINDEX);
}
else if (lua_isuserdata(State, Index))
{
FLuaUserData* UserData = (FLuaUserData*)lua_touserdata(State, Index);
switch (UserData->Type)
{
case(ELuaValueType::UObject):
if (UserData->Context.IsValid())
{
LuaValue.Type = UserData->Type;
LuaValue.Object = UserData->Context.Get();
LuaValue.LuaState = this;
}
break;
case(ELuaValueType::UFunction):
if (UserData->Context.IsValid() && UserData->Function.IsValid())
{
LuaValue.Type = UserData->Type;
LuaValue.FunctionName = UserData->Function->GetFName();
LuaValue.Object = UserData->Context.Get();
LuaValue.LuaState = this;
}
break;
}
}
return LuaValue;
}
int32 ULuaState::GetTop()
{
return lua_gettop(L);
}
int ULuaState::MetaTableFunctionState__index(lua_State *L)
{
ULuaState* LuaState = ULuaState::GetFromExtraSpace(L);
FString Key = UTF8_TO_TCHAR(lua_tostring(L, 2));
FLuaValue* LuaValue = LuaState->Table.Find(Key);
if (LuaValue)
{
LuaState->FromLuaValue(*LuaValue, LuaState, L);
return 1;
}
lua_pushnil(L);
return 1;
}
int ULuaState::MetaTableFunctionState__newindex(lua_State *L)
{
ULuaState* LuaState = ULuaState::GetFromExtraSpace(L);
FString Key = UTF8_TO_TCHAR(lua_tostring(L, 2));
FLuaValue* LuaValue = LuaState->Table.Find(Key);
if (LuaValue)
{
*LuaValue = LuaState->ToLuaValue(3, L);
}
else
{
lua_rawset(L, 1);
}
return 0;
}
int ULuaState::MetaTableBlueprintFunctionLibraryState__index(lua_State *L)
{
ULuaState* LuaState = ULuaState::GetFromExtraSpace(L);
if (!lua_isuserdata(L, 1))
{
return luaL_error(L, "invalid state for BlueprintFunctionLibrary");
}
FLuaUserData* UserData = (FLuaUserData*)lua_touserdata(L, 1);
if (!UserData->Context.IsValid())
{
return luaL_error(L, "invalid state for BlueprintFunctionLibrary");
}
UBlueprintFunctionLibrary* FunctionLibrary = Cast<UBlueprintFunctionLibrary>(UserData->Context);
if (!FunctionLibrary)
return luaL_error(L, "invalid state for BlueprintFunctionLibrary");
FString Key = UTF8_TO_TCHAR(lua_tostring(L, 2));
UFunction* Function = FunctionLibrary->FindFunction(FName(*Key));
if (Function)
{
FLuaUserData* LuaCallContext = (FLuaUserData*)lua_newuserdata(L, sizeof(FLuaUserData));
LuaCallContext->Type = ELuaValueType::UFunction;
LuaCallContext->Context = FunctionLibrary;
LuaCallContext->Function = Function;
lua_newtable(L);
lua_pushcfunction(L, ULuaState::MetaTableFunction__call);
lua_setfield(L, -2, "__call");
lua_setmetatable(L, -2);
return 1;
}
lua_pushnil(L);
return 1;
}
int ULuaState::MetaTableFunctionLuaComponent__index(lua_State *L)
{
ULuaState* LuaState = ULuaState::GetFromExtraSpace(L);
if (!lua_isuserdata(L, 1))
{
return luaL_error(L, "invalid state for ULuaComponent");
}
FLuaUserData* UserData = (FLuaUserData*)lua_touserdata(L, 1);
if (!UserData->Context.IsValid())
{
return luaL_error(L, "invalid state for ULuaComponent");
}
ULuaComponent* LuaComponent = Cast<ULuaComponent>(UserData->Context.Get());
if (!LuaComponent)
return luaL_error(L, "invalid state for ULuaComponent");
FString Key = UTF8_TO_TCHAR(lua_tostring(L, 2));
FLuaValue* LuaValue = LuaComponent->Table.Find(Key);
if (LuaValue)
{
LuaState->FromLuaValue(*LuaValue, LuaComponent->GetOwner(), L);
return 1;
}
lua_pushnil(L);
return 1;
}
int ULuaState::MetaTableFunctionLuaComponent__newindex(lua_State *L)
{
ULuaState* LuaState = ULuaState::GetFromExtraSpace(L);
if (!lua_isuserdata(L, 1))
{
return luaL_error(L, "invalid state for ULuaComponent");
}
FLuaUserData* UserData = (FLuaUserData*)lua_touserdata(L, 1);
if (!UserData->Context.IsValid())
{
return luaL_error(L, "invalid state for ULuaComponent");
}
ULuaComponent* LuaComponent = Cast<ULuaComponent>(UserData->Context.Get());
if (!LuaComponent)
return luaL_error(L, "invalid state for ULuaComponent");
FString Key = UTF8_TO_TCHAR(lua_tostring(L, 2));
FLuaValue* LuaValue = LuaComponent->Table.Find(Key);
if (LuaValue)
{
*LuaValue = LuaState->ToLuaValue(3, L);
}
else
{
LuaComponent->Table.Add(Key, LuaState->ToLuaValue(3, L));
}
return 0;
}
void ULuaState::Debug_Hook(lua_State* L, lua_Debug* ar)
{
ULuaState* LuaState = ULuaState::GetFromExtraSpace(L);
FLuaDebug LuaDebug;
lua_getinfo(L, "lSn", ar);
LuaDebug.CurrentLine = ar->currentline;
LuaDebug.Source = UTF8_TO_TCHAR(ar->source);
LuaDebug.Name = UTF8_TO_TCHAR(ar->name);
LuaDebug.NameWhat = UTF8_TO_TCHAR(ar->namewhat);
LuaDebug.What = UTF8_TO_TCHAR(ar->what);
switch (ar->event)
{
case LUA_HOOKLINE:
LuaState->ReceiveLuaLineHook(LuaDebug);
break;
case LUA_HOOKCALL:
LuaState->ReceiveLuaCallHook(LuaDebug);
break;
case LUA_HOOKRET:
LuaState->ReceiveLuaReturnHook(LuaDebug);
break;
default:
break;
}
}
int ULuaState::MetaTableFunctionUserData__eq(lua_State *L)
{
ULuaState* LuaState = ULuaState::GetFromExtraSpace(L);
if (!lua_isuserdata(L, 1))
{
return luaL_error(L, "invalid state for usedata");
}
if (!lua_isuserdata(L, 2))
{
lua_pushboolean(L, 0);
return 1;
}
FLuaUserData* UserData = (FLuaUserData*)lua_touserdata(L, 1);
if (!UserData->Context.IsValid())
{
return luaL_error(L, "invalid UObject for first userdata");
}
FLuaUserData* UserData2 = (FLuaUserData*)lua_touserdata(L, 2);
if (!UserData2->Context.IsValid())
{
return luaL_error(L, "invalid UObject for second userdata");
}
if (UserData->Type == UserData2->Type && UserData->Context.Get() == UserData2->Context.Get())
{
if (UserData->Type == ELuaValueType::UFunction)
{
if (!UserData->Function.IsValid())
{
return luaL_error(L, "invalid UFunction for first userdata");
}
if (!UserData2->Function.IsValid())
{
return luaL_error(L, "invalid UFunction for second userdata");
}
if (UserData->Function.Get() == UserData2->Function.Get())
{
lua_pushboolean(L, 1);
return 1;
}
}
else if (UserData->Type == ELuaValueType::UObject)
{
lua_pushboolean(L, 1);
return 1;
}
}
lua_pushboolean(L, 0);
return 1;
}
int ULuaState::MetaTableFunction__call(lua_State *L)
{
ULuaState* LuaState = ULuaState::GetFromExtraSpace(L);
if (!lua_isuserdata(L, 1))
{
return luaL_error(L, "invalid state for lua UFunction");
}
FLuaUserData* LuaCallContext = (FLuaUserData*)lua_touserdata(L, 1);
if (!LuaCallContext->Context.IsValid() || !LuaCallContext->Function.IsValid())
{
return luaL_error(L, "invalid state for lua UFunction");
}
int NArgs = lua_gettop(L);
FScopeCycleCounterUObject ObjectScope(LuaCallContext->Context.Get());
FScopeCycleCounterUObject FunctionScope(LuaCallContext->Function.Get());
void* Parameters = FMemory_Alloca(LuaCallContext->Function->ParmsSize);
FMemory::Memzero(Parameters, LuaCallContext->Function->ParmsSize);
int StackPointer = 2;
// arguments
for (TFieldIterator<UProperty> FArgs(LuaCallContext->Function.Get()); FArgs && ((FArgs->PropertyFlags & (CPF_Parm | CPF_ReturnParm)) == CPF_Parm); ++FArgs)
{
UProperty *Prop = *FArgs;
UStructProperty* LuaProp = Cast<UStructProperty>(Prop);
if (!LuaProp)
{
UArrayProperty* ArrayProp = Cast<UArrayProperty>(Prop);
if (ArrayProp)
{
LuaProp = Cast<UStructProperty>(ArrayProp->Inner);
if (!LuaProp)
break;
if (LuaProp->Struct != FLuaValue::StaticStruct())
break;
// start filling the array with the rest of arguments
int ArgsToProcess = NArgs - StackPointer + 1;
if (ArgsToProcess < 1)
break;
FScriptArrayHelper_InContainer ArrayHelper(ArrayProp, LuaProp->ContainerPtrToValuePtr<uint8>(Parameters));
ArrayHelper.AddValues(ArgsToProcess);
for (int i = StackPointer; i < StackPointer + ArgsToProcess; i++)
{
FLuaValue LuaValue = LuaState->ToLuaValue(i, L);
*LuaProp->ContainerPtrToValuePtr<FLuaValue>(ArrayHelper.GetRawPtr(i - StackPointer)) = LuaValue;
}
}
break;
}
if (LuaProp->Struct != FLuaValue::StaticStruct())
break;
FLuaValue LuaValue = LuaState->ToLuaValue(StackPointer++, L);
*LuaProp->ContainerPtrToValuePtr<FLuaValue>(Parameters) = LuaValue;
}
LuaState->InceptionLevel++;
LuaCallContext->Context->ProcessEvent(LuaCallContext->Function.Get(), Parameters);
check(LuaState->InceptionLevel > 0);
LuaState->InceptionLevel--;
if (LuaState->InceptionLevel == 0)
{
FString Error;
while (LuaState->InceptionErrors.Dequeue(Error))
{
ULuaComponent* LuaComponent = Cast <ULuaComponent>(LuaCallContext->Context);
if (LuaComponent)
{
if (LuaComponent->bLogError)
{
LuaState->LogError(Error);
}
LuaComponent->OnLuaError.Broadcast(Error);
}
else
{
if (LuaState->bLogError)
{
LuaState->LogError(Error);
}
LuaState->ReceiveLuaError(Error);
}
}
}
int ReturnedValues = 0;
// get return value
for (TFieldIterator<UProperty> FArgs(LuaCallContext->Function.Get()); FArgs; ++FArgs)
{
UProperty *Prop = *FArgs;
if (!Prop->HasAnyPropertyFlags(CPF_ReturnParm | CPF_OutParm))
continue;
// avoid input args (at all costs !)
if (Prop->HasAnyPropertyFlags(CPF_ConstParm | CPF_ReferenceParm))
continue;
UStructProperty* LuaProp = Cast<UStructProperty>(Prop);
if (!LuaProp)
{
UArrayProperty* ArrayProp = Cast<UArrayProperty>(Prop);
if (ArrayProp)
{
LuaProp = Cast<UStructProperty>(ArrayProp->Inner);
if (!LuaProp)
break;
if (LuaProp->Struct != FLuaValue::StaticStruct())
break;
FScriptArrayHelper_InContainer ArrayHelper(ArrayProp, LuaProp->ContainerPtrToValuePtr<uint8>(Parameters));
for (int i = 0; i < ArrayHelper.Num(); i++)
{
FLuaValue* LuaValue = LuaProp->ContainerPtrToValuePtr<FLuaValue>(ArrayHelper.GetRawPtr(i));
ReturnedValues++;
LuaState->FromLuaValue(*LuaValue, nullptr, L);
}
}
break;
}
if (LuaProp->Struct != FLuaValue::StaticStruct())
break;
FLuaValue* LuaValue = LuaProp->ContainerPtrToValuePtr<FLuaValue>(Parameters);
if (LuaValue)
{
ReturnedValues++;
LuaState->FromLuaValue(*LuaValue, nullptr, L);
}
}
if (ReturnedValues > 0)
return ReturnedValues;
lua_pushnil(L);
return 1;
}
int ULuaState::TableFunction_print(lua_State *L)
{
ULuaState* LuaState = ULuaState::GetFromExtraSpace(L);
TArray<FString> Messages;
int n = lua_gettop(L);
lua_getglobal(L, "tostring");
for (int i = 1; i <= n; i++)
{
lua_pushvalue(L, -1);
lua_pushvalue(L, i);
lua_call(L, 1, 1);
const char *s = lua_tostring(L, -1);
if (!s)
return luaL_error(L, "'tostring must return a string to 'print'");
FString Value = FString(UTF8_TO_TCHAR(s));
lua_pop(L, 1);
Messages.Add(Value);
}
LuaState->Log(FString::Join(Messages, TEXT("\t")));
return 0;
}
int ULuaState::TableFunction_package_preload(lua_State *L)
{
ULuaState* LuaState = ULuaState::GetFromExtraSpace(L);
FString Key = UTF8_TO_TCHAR(lua_tostring(L, 1));
if (LuaState->L != L)
return luaL_error(L, "you cannot call package.preload from a thread/coroutine (error while loading %s)", TCHAR_TO_UTF8(*Key));
// first check for BlueprintFunctionLibrary
TSubclassOf<UBlueprintFunctionLibrary>* FunctionLibrary = LuaState->RequireBlueprintFunctionLibraryTable.Find(Key);
if (FunctionLibrary)
{
LuaState->NewUObject(FunctionLibrary->GetDefaultObject());
// metatable
LuaState->NewTable();
LuaState->PushCFunction(MetaTableBlueprintFunctionLibraryState__index);
LuaState->SetField(-2, "__index");
LuaState->SetMetaTable(-2);
return 1;
}
// then check for code assets
ULuaCode** LuaCodePtr = LuaState->RequireTable.Find(Key);
if (!LuaCodePtr)
{
if (LuaState->bAddProjectContentDirToPackagePath && LuaState->RunFile(Key + ".lua", true, 1))
{
return 1;
}
return luaL_error(L, "%s", lua_tostring(L, -1));
// now search in additional paths
for (FString AdditionalPath : LuaState->AppendProjectContentDirSubDir)
{
if (LuaState->RunFile(AdditionalPath / Key + ".lua", true, 1))
{
return 1;
}
return luaL_error(L, "%s", lua_tostring(L, -1));
}
return luaL_error(L, "unable to find package %s", TCHAR_TO_UTF8(*Key));
}
ULuaCode* LuaCode = *LuaCodePtr;
if (!LuaCode)
{
return luaL_error(L, "LuaCodeAsset not set for package %s", TCHAR_TO_UTF8(*Key));
}
if (!LuaState->RunCodeAsset(LuaCode, 1))
{
return luaL_error(L, "%s", lua_tostring(L, -1));
}
return 1;
}
void ULuaState::ReceiveLuaError_Implementation(const FString& Message)
{
}
void ULuaState::ReceiveLuaCallHook_Implementation(const FLuaDebug& LuaDebug)
{
}
void ULuaState::ReceiveLuaReturnHook_Implementation(const FLuaDebug& LuaDebug)
{
}
void ULuaState::ReceiveLuaLineHook_Implementation(const FLuaDebug& LuaDebug)
{
}
void ULuaState::NewTable()
{
lua_newtable(L);
}
void ULuaState::SetMetaTable(int Index)
{
lua_setmetatable(L, Index);
}
void ULuaState::GetMetaTable(int Index)
{
lua_getmetatable(L, Index);
}
void ULuaState::SetField(int Index, const char* FieldName)
{
lua_setfield(L, Index, FieldName);
}
void ULuaState::GetField(int Index, const char* FieldName)
{
lua_getfield(L, Index, FieldName);
}
void ULuaState::RawGetI(int Index, int N)
{
lua_rawgeti(L, Index, N);
}
void ULuaState::RawSetI(int Index, int N)
{
lua_rawseti(L, Index, N);
}
void ULuaState::PushGlobalTable()
{
lua_pushglobaltable(L);
}
int32 ULuaState::GetFieldFromTree(FString Tree, bool bGlobal)
{
TArray<FString> Parts;
Tree.ParseIntoArray(Parts, TEXT("."));
if (Parts.Num() == 0)
{
LastError = FString::Printf(TEXT("invalid Lua key: \"%s\""), *Tree);
if (bLogError)
LogError(LastError);
ReceiveLuaError(LastError);
PushNil();
return 1;
}
int32 AdditionalPop = bGlobal ? 1 : 0;
if (bGlobal)
{
PushGlobalTable();
}
int32 i;
for (i = 0; i < Parts.Num(); i++)
{
GetField(-1, TCHAR_TO_UTF8(*Parts[i]));
if (lua_isnil(L, -1))
{
if (i == Parts.Num() - 1)
{
return i + 1 + AdditionalPop;
}
LastError = FString::Printf(TEXT("Lua key \"%s\" is nil"), *Parts[i]);
if (bLogError)
LogError(LastError);
ReceiveLuaError(LastError);
return i + 1 + AdditionalPop;
}
}
return i + AdditionalPop;
}
void ULuaState::SetFieldFromTree(FString Tree, FLuaValue& Value, bool bGlobal)
{
TArray<FString> Parts;
Tree.ParseIntoArray(Parts, TEXT("."));
int32 ItemsToPop = GetFieldFromTree(Tree, bGlobal);
// invalid key
if (ItemsToPop != (Parts.Num() + (bGlobal ? 1 : 0)))
{
Pop(ItemsToPop);
return;
}
Pop();
FromLuaValue(Value);
SetField(-2, TCHAR_TO_UTF8(*Parts.Last()));
Pop(ItemsToPop - 1);
}
void ULuaState::NewUObject(UObject* Object)
{
FLuaUserData* UserData = (FLuaUserData*)lua_newuserdata(L, sizeof(FLuaUserData));
UserData->Type = ELuaValueType::UObject;
UserData->Context = Object;
UserData->Function = nullptr;
}
void ULuaState::GetGlobal(const char* Name)
{
lua_getglobal(L, Name);
}
void ULuaState::SetGlobal(const char* Name)
{
lua_setglobal(L, Name);
}
void ULuaState::PushValue(int Index)
{
lua_pushvalue(L, Index);
}
bool ULuaState::PCall(int NArgs, FLuaValue& Value, int NRet)
{
bool bSuccess = Call(NArgs, Value, NRet);
if (!bSuccess)
{
if (InceptionLevel > 0)
{
InceptionErrors.Enqueue(LastError);
}
else
{
if (bLogError)
LogError(LastError);
ReceiveLuaError(LastError);
}
}
return bSuccess;
}
bool ULuaState::Call(int NArgs, FLuaValue& Value, int NRet)
{
if (lua_pcall(L, NArgs, NRet, 0))
{
LastError = FString::Printf(TEXT("Lua error: %s"), UTF8_TO_TCHAR(lua_tostring(L, -1)));
return false;
}
if (NRet > 0)
{
Value = ToLuaValue(-1);
}
return true;
}
void ULuaState::Pop(int32 Amount)
{
lua_pop(L, Amount);
}
void ULuaState::PushNil()
{
lua_pushnil(L);
}
void ULuaState::PushCFunction(lua_CFunction Function)
{
lua_pushcfunction(L, Function);
}
void* ULuaState::NewUserData(size_t DataSize)
{
return lua_newuserdata(L, DataSize);
}
void ULuaState::Unref(int Ref)
{
luaL_unref(L, LUA_REGISTRYINDEX, Ref);
}
int ULuaState::NewRef()
{
return luaL_ref(L, LUA_REGISTRYINDEX);
}
void ULuaState::GetRef(int Ref)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, Ref);
}
int ULuaState::Next(int Index)
{
return lua_next(L, Index);
}
bool ULuaState::Resume(int Index, int NArgs)
{
lua_State* Coroutine = lua_tothread(L, Index);
if (!Coroutine)
return false;
if (lua_status(Coroutine) == LUA_OK && lua_gettop(Coroutine) == 0)
{
lua_pushboolean(L, 0);
lua_pushstring(L, "Lua error: cannot resume dead coroutine");
return false;
}
lua_xmove(L, Coroutine, NArgs);
int Ret = lua_resume(Coroutine, L, NArgs);
if (Ret != LUA_OK && Ret != LUA_YIELD)
{
lua_pushboolean(L, 0);
lua_xmove(Coroutine, L, 1);
return false;
}
int NRet = lua_gettop(Coroutine);
lua_pushboolean(L, 1);
lua_xmove(Coroutine, L, NRet);
return true;
}
int ULuaState::GC(int What, int Data)
{
return lua_gc(L, What, Data);
}
void ULuaState::Len(int Index)
{
lua_len(L, Index);
}
int32 ULuaState::ToInteger(int Index)
{
return lua_tointeger(L, Index);
}
FLuaValue ULuaState::CreateLuaTable()
{
FLuaValue NewTable;
NewTable.Type = ELuaValueType::Table;
NewTable.LuaState = this;
return NewTable;
}
ULuaState::~ULuaState()
{
if (L)
lua_close(L);
FLuaMachineModule::Get().UnregisterLuaState(this);
}
#define LUAVALUE_PROP_CAST(Type, Type2) Type* __##Type##__ = Cast<Type>(Property);\
if (__##Type##__)\
{\
return FLuaValue((Type2)__##Type##__->GetPropertyValue_InContainer(Buffer, Index));\
}
#define LUAVALUE_PROP_CAST_TOSTRING(Type) Type* __##Type##__ = Cast<Type>(Property);\
if (__##Type##__)\
{\
return FLuaValue(__##Type##__->GetPropertyValue_InContainer(Buffer, Index).ToString());\
}
#define LUAVALUE_PROP_SET(Type, Value) Type* __##Type##__ = Cast<Type>(Property);\
if (__##Type##__)\
{\
__##Type##__->SetPropertyValue_InContainer(Buffer, Value, Index);\
return;\
}
FLuaValue ULuaState::FromUProperty(void* Buffer, UProperty* Property, bool& bSuccess, int32 Index)
{
bSuccess = true;
LUAVALUE_PROP_CAST(UBoolProperty, bool);
LUAVALUE_PROP_CAST(UFloatProperty, float);
LUAVALUE_PROP_CAST(UIntProperty, int32);
LUAVALUE_PROP_CAST(UUInt32Property, int32);
LUAVALUE_PROP_CAST(UInt16Property, int32);
LUAVALUE_PROP_CAST(UInt8Property, int32);
LUAVALUE_PROP_CAST(UByteProperty, int32);
LUAVALUE_PROP_CAST(UUInt16Property, int32);
LUAVALUE_PROP_CAST(UStrProperty, FString);
LUAVALUE_PROP_CAST_TOSTRING(UNameProperty);
LUAVALUE_PROP_CAST_TOSTRING(UTextProperty);
LUAVALUE_PROP_CAST(UClassProperty, UObject*);
LUAVALUE_PROP_CAST(UObjectProperty, UObject*);
UObjectPropertyBase* ObjectPropertyBase = Cast<UObjectPropertyBase>(Property);
if (ObjectPropertyBase)
{
return FLuaValue(ObjectPropertyBase->GetObjectPropertyValue_InContainer(Buffer, Index));
}
UWeakObjectProperty* WeakObjectProperty = Cast<UWeakObjectProperty>(Property);
if (WeakObjectProperty)
{
const FWeakObjectPtr& WeakPtr = WeakObjectProperty->GetPropertyValue_InContainer(Buffer, Index);
return FLuaValue(WeakPtr.Get());
}
bSuccess = false;
return FLuaValue();
}
void ULuaState::ToUProperty(void* Buffer, UProperty* Property, FLuaValue Value, bool& bSuccess, int32 Index)
{
bSuccess = true;
LUAVALUE_PROP_SET(UBoolProperty, Value.ToBool());
LUAVALUE_PROP_SET(UFloatProperty, Value.ToFloat());
LUAVALUE_PROP_SET(UIntProperty, Value.ToInteger());
LUAVALUE_PROP_SET(UUInt32Property, Value.ToInteger());
LUAVALUE_PROP_SET(UInt16Property, Value.ToInteger());
LUAVALUE_PROP_SET(UInt8Property, Value.ToInteger());
LUAVALUE_PROP_SET(UByteProperty, Value.ToInteger());
LUAVALUE_PROP_SET(UUInt16Property, Value.ToInteger());
LUAVALUE_PROP_SET(UStrProperty, Value.ToString());
LUAVALUE_PROP_SET(UNameProperty, Value.ToName());
LUAVALUE_PROP_SET(UTextProperty, FText::FromString(Value.ToString()));
LUAVALUE_PROP_SET(UClassProperty, Value.Object);
LUAVALUE_PROP_SET(UObjectProperty, Value.Object);
UObjectPropertyBase* ObjectPropertyBase = Cast<UObjectPropertyBase>(Property);
if (ObjectPropertyBase)
{
ObjectPropertyBase->SetObjectPropertyValue_InContainer(Buffer, Value.Object, Index);
}
UWeakObjectProperty* WeakObjectProperty = Cast<UWeakObjectProperty>(Property);
if (WeakObjectProperty)
{
FWeakObjectPtr WeakPtr(Value.Object);
WeakObjectProperty->SetPropertyValue_InContainer(Buffer, WeakPtr, Index);
return;
}
bSuccess = false;
}
void ULuaState::SetUserDataMetaTable(FLuaValue MetaTable)
{
UserDataMetaTable = MetaTable;
}
| [
"roberto.deioris@gmail.com"
] | roberto.deioris@gmail.com |
4ec26d71ba530199349869f68b9f18bdc2298a7c | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/InnerDetector/InDetValidation/InDetPhysValMonitoring/src/InDetPerfPlot_ExtendedFakes.h | 1797dbac10d0a9d1512a6f788451806bcd4048c9 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,578 | h | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#ifndef INDETPHYSVALMONITORING_INDETPERFPLOT_EXTENDEDFAKES
#define INDETPHYSVALMONITORING_INDETPERFPLOT_EXTENDEDFAKES
/**
* @file InDetPerfPlot_ExtendedFakes.h
* @author shaun roe
**/
// local includes
#include "InDetPerfPlot_fakes.h"
// std includes
#include <string>
#include <map>
#include <vector>
class TProfile;
///class holding fake plots for Inner Detector RTT Validation and implementing fill methods
class InDetPerfPlot_ExtendedFakes: public InDetPerfPlot_fakes {
public:
InDetPerfPlot_ExtendedFakes (InDetPlotBase* pParent, const std::string& dirName);
void fill(const xAOD::TrackParticle& trkprt, const bool isFake, const InDetPerfPlot_fakes::Category& f = ALL);
private:
// fake rates as TProfiles
std::map< std::string, TProfile* > m_HitInfoFakerates;
std::map< std::string, TProfile* > m_KinematicFakerates;
// Variables (for easy access).
std::vector< std::string > m_variables = {
"nBLayerHits",
"nBLayerOutliers",
"nBLayerSplitHits",
"nBLayerSharedHits",
"nPixHits",
"nPixHoles",
"nPixSharedHits",
"nPixOutliers",
"nPixContribLayers",
"nPixSplitHits",
"nPixGangedHits",
"nSCTHits",
"nSCTHoles",
"nSCTDoubleHoles",
"nSCTSharedHits",
"nSCTOutliers",
"nSiHits",
"nTRTHits",
"nTRTHighThresholdHits",
"nTRTOutliers",
"nTRTHighThresholdOutliers",
};
// plot base has nop default implementation of this; we use it to book the histos
void initializePlots();
};
#endif
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
11c57655880b13fce7234a4e2a34e061f83a122d | c075cfe521103977789d600b61ad05b605f4fb10 | /30марта/ZAD_C_3.cpp | c8d203cebb4fce3b92e2a2546e2251bfce487ec3 | [] | no_license | igoroogle/codeforces | dd3c99b6a5ceb19d7d9495b370d4b2ef8949f534 | 579cd1d2aa30a0b0b4cc61d104a02499c69ac152 | refs/heads/master | 2020-07-20T12:37:07.225539 | 2019-09-05T19:21:27 | 2019-09-05T19:35:26 | 206,639,451 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,321 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
const ll INF = 2000000100000000000;
vector <ll> a[100010], w[100010], ch[100010];
ld dps[2][100010], dpk[2][100010], ss = 0, kl = 0;
ll dfs(ll v, ll p);
int main()
{
//freopen("tree.in", "r", stdin);
//freopen("tree.out", "w", stdout);
ll n, i, x, y, z, t;
cin >> n;
for (i = 0; i < n - 1; i++)
{
scanf("%I64d%I64d%I64d%I64d", &x, &y, &z, &t);
x--;
y--;
a[x].push_back(y);
a[y].push_back(x);
w[x].push_back(z);
w[y].push_back(z);
ch[x].push_back(t);
ch[y].push_back(t);
}
dfs(0, -1);
cout << kl << endl;
if (kl > 0)
cout << fixed << setprecision(11) << ss / kl << endl;
else
cout << 0 << endl;
}
ll dfs(ll v, ll p)
{
ll i;
for (i = 0; i < a[v].size(); i++)
if (a[v][i] != p)
{
if (ch[v][i])
{
ss += dps[0][v] * dpk[0][a[v][i]] + dps[0][a[v][i]] * dpk[0][v] + ld(w[v][i]) * dpk[0][a[v][i]] * dpk[0][v];
kl += dpk[0][a[v][i]] * dpk[0][v];// g g
ss += dps[0][v] * dpk[1][a[v][i]] + dps[1][a[v][i]] * dpk[0][v] + ld(w[v][i]) * dpk[1][a[v][i]] * dpk[0][v];
kl += dpk[1][a[v][i]] * dpk[0][v];// g ch
ss += dps[1][v] * dpk[0][a[v][i]] + dps[0][a[v][i]] * dpk[1][v] + ld(w[v][i]) * dpk[0][a[v][i]] * dpk[1][v];
kl += dpk[0][a[v][i]] * dpk[1][v];// ch g
ss += dps[1][v] * dpk[1][a[v][i]] + dps[1][a[v][i]] * dpk[1][v] + ld(w[v][i]) * dpk[1][a[v][i]] * dpk[1][v];
kl += dpk[1][a[v][i]] * dpk[1][v];// ch ch
ss += dps[0][v] + w[v][i] * dpk[0][v];
kl += dpk[0][v]; // g
ss += dps[1][v] + w[v][i] * dpk[1][v];
kl += dpk[1][v]; // ch
dps[1][v] += dps[0][a[v][i]] + ld(w[v][i]) * dpk[0][a[v][i]];
dpk[1][v] += dpk[0][a[v][i]];
dps[1][v] += dps[1][a[v][i]] + ld(w[v][i]) * dpk[1][a[v][i]];
dpk[1][v] += dpk[1][a[v][i]];
dps[1][v] += w[v][i];
dpk[1][v] += 1.0;
}
else
{
ss += dps[0][v] * dpk[1][a[v][i]] + dps[1][a[v][i]] * dpk[0][v] + ld(w[v][i]) * dpk[1][a[v][i]] * dpk[0][v];
kl += dpk[1][a[v][i]] * dpk[0][v];// g ch
ss += dps[1][v] * dpk[0][a[v][i]] + dps[0][a[v][i]] * dpk[1][v] + ld(w[v][i]) * dpk[0][a[v][i]] * dpk[1][v];
kl += dpk[0][a[v][i]] * dpk[1][v];// ch g
ss += dps[1][v] * dpk[1][a[v][i]] + dps[1][a[v][i]] * dpk[1][v] + ld(w[v][i]) * dpk[1][a[v][i]] * dpk[1][v];
kl += dpk[1][a[v][i]] * dpk[1][v];// ch ch
ss += dps[1][v] + w[v][i] * dpk[1][v];
kl += dpk[1][v]; // ch
dps[0][v] += dps[0][a[v][i]] + ld(w[v][i]) * dpk[0][a[v][i]];
dpk[0][v] += dpk[0][a[v][i]];
dps[1][v] += dps[1][a[v][i]] + ld(w[v][i]) * dpk[1][a[v][i]];
dpk[1][v] += dpk[1][a[v][i]];
dps[0][v] += w[v][i];
dpk[0][v] += 1.0;
}
}
ss += dps[1][v];
kl += dpk[1][v];
}
/*
3
1 2 1 1
1 3 1 1
*/
| [
"160698qnigor98"
] | 160698qnigor98 |
d06c4f090de62a21db7165f237e83a821de920a9 | 149b1c36bc41fbcac2f1f021f4910adf5f19b77c | /GoStop/CardList.cpp | 3436c7b7e3b975b2397649f7064062e8701cdacf | [] | no_license | BoxResin/GoStop | 440e7a8305b050f0ea2609ef4c29107783883203 | e9c5f1204074e44788f7561d706a0e7b0fc8b670 | refs/heads/master | 2021-01-13T01:00:09.473133 | 2015-12-07T06:18:00 | 2015-12-07T06:18:00 | 47,532,391 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,985 | cpp | #include "CardList.h"
// 카드 리스트를 생성하는 함수
// ※ 생성한 카드 리스트는 반드시 free로 해제해야 한다.
// 반환 카드 리스트
CardList *CreateCardList(void)
{
CardList *list = (CardList *) malloc(sizeof(CardList));
list->head.id = -1;
list->head.lpNext = NULL;
list->tail = &list->head;
return list;
}
// 카드 리스트에 들어있는 카드의 개수를 가져오는 함수
// list 카드 리스트
// 반환 카드의 개수
int GetCardCount(CardList *list)
{
Card *tmp = &list->head;
int count = 0;
// head와 tail이 같으면 노드가 없는 것이므로
if (&list->head == list->tail)
return 0;
while (tmp != list->tail)
{
tmp = tmp->lpNext; // 주의: 오류 발생 위험 있음
count++;
}
return count;
}
// 리스트의 모든 원소를 특정 함수에 매칭시켜 출력, 비교 등을 할 수 있게 하는 함수
// list 카드 리스트
// handler 카드 리스트의 원소에 접근할 함수
void ForEachCard(CardList *list, void (*handler)(const Card *))
{
Card *tmp = &list->head;
while (tmp != list->tail)
{
handler(tmp->lpNext);
tmp = tmp->lpNext;
}
}
// 카드 리스트의 끝에 카드를 추가하는 함수
// list 카드 리스트
// card 추가할 카드
void PushCardBack(CardList *list, Card *card)
{
list->tail->lpNext = card;
list->tail = card;
card->lpNext = NULL;
}
// 카드 리스트 끝의 카드를 꺼내는 함수 (※ 카드 개수만큼의 시간복잡도를 가짐)
// list 카드 리스트
// 반환 꺼낸 카드 (꺼낼 카드가 없으면 NULL 반환)
Card *PopCardBack(CardList *list)
{
if (GetCardCount(list) == 0)
return NULL;
Card *tmp = &list->head;
Card *last = list->tail;
// tail의 바로 전 노드를 찾는다. tmp: tail의 바로 전 노드
while (tmp->lpNext != list->tail)
tmp = tmp->lpNext; // 주의: 오류 발생 위험 있음
// 마지막 노드와의 논리적 연결을 끊는다.
list->tail = tmp;
list->tail->lpNext = NULL;
return last;
}
// 카드 리스트의 맨 앞에 카드를 추가하는 함수
// list 카드 리스트
// card 추가할 카드
void PushCardFront(CardList *list, Card *card)
{
// 빈 리스트이면
if (list->head.lpNext == NULL)
{
// 리스트의 head와 card를 논리적으로 연결하고, 리스트의 tail을 card로 지정한다.
list->head.lpNext = card;
list->tail = card;
card->lpNext = NULL;
}
else
{
// head와 head의 다음 노드 사이에 card를 끼워넣는다.
Card *tmp = list->head.lpNext;
list->head.lpNext = card;
card->lpNext = tmp;
}
}
// 카드 리스트 맨 앞의 카드를 꺼내는 함수
// list 카드 리스트
// 반환 꺼낸 카드 (꺼낼 카드가 없으면 NULL 반환)
Card *PopCardFront(CardList *list)
{
if (&list->head == list->tail)
return NULL;
else if (list->head.lpNext == list->tail)
list->tail = &list->head;
Card *tmp = list->head.lpNext;
list->head.lpNext = tmp->lpNext;
return tmp;
} | [
"eominsuk55@naver.com"
] | eominsuk55@naver.com |
09461decd6170555b1b0f1e3b3b620afc84a3ee5 | b4896960b7b49385df0377bd185616e992dd42f4 | /AC代码/CodeForces/CodeForces-999D.cpp | 644aff36493ce8f71534a2f32aaf48c50b60fdf4 | [] | no_license | qaz734913414/MyACM | c74f5d2096c77e0963bd209fb0e84547a98fa9df | 5781adafd6824815a466eb859b335cb809154816 | refs/heads/master | 2020-03-26T21:56:22.048910 | 2018-08-20T11:18:59 | 2018-08-20T11:18:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,178 | cpp | #include <bits/stdc++.h>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> P;
const int INF = 0x3f3f3f3f;
const int maxn = 20;
const int mod = 1e9+7;
const double eps = 1e-8;
const double pi = asin(1.0)*2;
const double e = 2.718281828459;
void fre() {
freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
}
int main(){
//fre();
int n, m;
scanf("%d%d", &n, &m);
int k = n / m;
vector<int> a(n);
vector<vector<int>> val(m);
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
val[a[i] % m].pb(i);
}
ll ans = 0;
vector<P> fre;
for (int i = 0; i < (m << 1); ++i) {
int cur = i % m;
while (val[cur].size() > k) {
int elem = val[cur].back();
val[cur].pop_back();
fre.pb(mp(elem, i));
}
while (val[cur].size() < k && !fre.empty()) {
int elem = fre.back().first;
int mmod = fre.back().second;
fre.pop_back();
val[cur].pb(elem);
a[elem] += i - mmod;
ans += i - mmod;
}
}
printf("%lld\n", ans);
for (int i = 0; i < n; ++i) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
| [
"978539910@qq.com"
] | 978539910@qq.com |
9a850fa03339c889011dafd22ef7fbf860963c7b | e6559df51c2a14256962c3757073a491ea66de7c | /URI/2329 - Pão a Metro.cpp | f185265e1e43ad3cd2883a68bbfe18b46cbb69ca | [] | no_license | Maycon708/Maratona | c30eaedc3ee39d69582b0ed1a60f31ad8d666d43 | b6d07582544c230e67c23a20e1a1be99d4b47576 | refs/heads/master | 2020-04-25T23:37:53.992330 | 2019-02-28T17:10:25 | 2019-02-28T17:10:25 | 143,191,679 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 911 | cpp | #include <bits/stdc++.h>
#define INF 0x3F3F3F3F
#define rep(i, a, b) for(int i = int(a); i < int(b); i++)
#define pb push_back
#define debug(x) cout << #x << " = " << x << endl;
#define debug2(x,y) cout << #x << " = " << x << " --- " << #y << " = " << y << "\n";
#define debugM( x, l, c ) { rep( i, 0, l ){ rep( j, 0, c ) cout << x[i][j] << " "; printf("\n");}}
#define all(S) (S).begin(), (S).end()
#define F first
#define S second
#define mk make_pair
using namespace std;
typedef pair <int, int> ii;
typedef long long int ll;
int n, k, v[10100];
int bb(){
int ini = 1, fim = 10000;
while( ini < fim ){
int mid = ( ini + fim + 1 ) >> 1;
int ans = 0;
rep( i, 0, n ){
ans += ( v[i]/mid );
}
if( ans < k ) fim = mid-1;
else ini = mid;
}
return ini;
}
int main(){
while( scanf("%d", &k ) != EOF ){
scanf("%d", &n );
rep( i, 0, n ) scanf("%d", &v[i] );
printf("%d\n", bb() );
}
}
| [
"mayconalves@gea.inatel.br"
] | mayconalves@gea.inatel.br |
234d092b907a82689d16670ecdd1294c1eab3814 | 753a70bc416e8dced2853f278b08ef60cdb3c768 | /include/tensorflow/lite/tools/make/downloads/absl/absl/flags/internal/type_erased_test.cc | ac749a6075485e0bf5e85ef5dcf2c36039e83d4c | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | finnickniu/tensorflow_object_detection_tflite | ef94158e5350613590641880cb3c1062f7dd0efb | a115d918f6894a69586174653172be0b5d1de952 | refs/heads/master | 2023-04-06T04:59:24.985923 | 2022-09-20T16:29:08 | 2022-09-20T16:29:08 | 230,891,552 | 60 | 19 | MIT | 2023-03-25T00:31:18 | 2019-12-30T09:58:41 | C++ | UTF-8 | C++ | false | false | 5,870 | cc | //
// Copyright 2019 The Abseil Authors.
//
// 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.
#include "absl/flags/internal/type_erased.h"
#include <cmath>
#include "gtest/gtest.h"
#include "absl/flags/flag.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
ABSL_FLAG(int, int_flag, 1, "int_flag help");
ABSL_FLAG(std::string, string_flag, "dflt", "string_flag help");
ABSL_RETIRED_FLAG(bool, bool_retired_flag, false, "bool_retired_flag help");
namespace {
namespace flags = absl::flags_internal;
class TypeErasedTest : public testing::Test {
protected:
void SetUp() override { flag_saver_ = absl::make_unique<flags::FlagSaver>(); }
void TearDown() override { flag_saver_.reset(); }
private:
std::unique_ptr<flags::FlagSaver> flag_saver_;
};
// --------------------------------------------------------------------
TEST_F(TypeErasedTest, TestGetCommandLineOption) {
std::string value;
EXPECT_TRUE(flags::GetCommandLineOption("int_flag", &value));
EXPECT_EQ(value, "1");
EXPECT_TRUE(flags::GetCommandLineOption("string_flag", &value));
EXPECT_EQ(value, "dflt");
EXPECT_FALSE(flags::GetCommandLineOption("bool_retired_flag", &value));
EXPECT_FALSE(flags::GetCommandLineOption("unknown_flag", &value));
}
// --------------------------------------------------------------------
TEST_F(TypeErasedTest, TestSetCommandLineOption) {
EXPECT_TRUE(flags::SetCommandLineOption("int_flag", "101"));
EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), 101);
EXPECT_TRUE(flags::SetCommandLineOption("string_flag", "asdfgh"));
EXPECT_EQ(absl::GetFlag(FLAGS_string_flag), "asdfgh");
EXPECT_FALSE(flags::SetCommandLineOption("bool_retired_flag", "true"));
EXPECT_FALSE(flags::SetCommandLineOption("unknown_flag", "true"));
}
// --------------------------------------------------------------------
TEST_F(TypeErasedTest, TestSetCommandLineOptionWithMode_SET_FLAGS_VALUE) {
EXPECT_TRUE(flags::SetCommandLineOptionWithMode("int_flag", "101",
flags::SET_FLAGS_VALUE));
EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), 101);
EXPECT_TRUE(flags::SetCommandLineOptionWithMode("string_flag", "asdfgh",
flags::SET_FLAGS_VALUE));
EXPECT_EQ(absl::GetFlag(FLAGS_string_flag), "asdfgh");
EXPECT_FALSE(flags::SetCommandLineOptionWithMode("bool_retired_flag", "true",
flags::SET_FLAGS_VALUE));
EXPECT_FALSE(flags::SetCommandLineOptionWithMode("unknown_flag", "true",
flags::SET_FLAGS_VALUE));
}
// --------------------------------------------------------------------
TEST_F(TypeErasedTest, TestSetCommandLineOptionWithMode_SET_FLAG_IF_DEFAULT) {
EXPECT_TRUE(flags::SetCommandLineOptionWithMode("int_flag", "101",
flags::SET_FLAG_IF_DEFAULT));
EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), 101);
// This semantic is broken. We return true instead of false. Value is not
// updated.
EXPECT_TRUE(flags::SetCommandLineOptionWithMode("int_flag", "202",
flags::SET_FLAG_IF_DEFAULT));
EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), 101);
EXPECT_TRUE(flags::SetCommandLineOptionWithMode("string_flag", "asdfgh",
flags::SET_FLAG_IF_DEFAULT));
EXPECT_EQ(absl::GetFlag(FLAGS_string_flag), "asdfgh");
EXPECT_FALSE(flags::SetCommandLineOptionWithMode("bool_retired_flag", "true",
flags::SET_FLAG_IF_DEFAULT));
EXPECT_FALSE(flags::SetCommandLineOptionWithMode("unknown_flag", "true",
flags::SET_FLAG_IF_DEFAULT));
}
// --------------------------------------------------------------------
TEST_F(TypeErasedTest, TestSetCommandLineOptionWithMode_SET_FLAGS_DEFAULT) {
EXPECT_TRUE(flags::SetCommandLineOptionWithMode("int_flag", "101",
flags::SET_FLAGS_DEFAULT));
EXPECT_TRUE(flags::SetCommandLineOptionWithMode("string_flag", "asdfgh",
flags::SET_FLAGS_DEFAULT));
EXPECT_EQ(absl::GetFlag(FLAGS_string_flag), "asdfgh");
EXPECT_FALSE(flags::SetCommandLineOptionWithMode("bool_retired_flag", "true",
flags::SET_FLAGS_DEFAULT));
EXPECT_FALSE(flags::SetCommandLineOptionWithMode("unknown_flag", "true",
flags::SET_FLAGS_DEFAULT));
// This should be successfull, since flag is still is not set
EXPECT_TRUE(flags::SetCommandLineOptionWithMode("int_flag", "202",
flags::SET_FLAG_IF_DEFAULT));
EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), 202);
}
// --------------------------------------------------------------------
TEST_F(TypeErasedTest, TestIsValidFlagValue) {
EXPECT_TRUE(flags::IsValidFlagValue("int_flag", "57"));
EXPECT_TRUE(flags::IsValidFlagValue("int_flag", "-101"));
EXPECT_FALSE(flags::IsValidFlagValue("int_flag", "1.1"));
EXPECT_TRUE(flags::IsValidFlagValue("string_flag", "#%^#%^$%DGHDG$W%adsf"));
EXPECT_TRUE(flags::IsValidFlagValue("bool_retired_flag", "true"));
}
} // namespace
| [
"finn.niu@apptech.com.hk"
] | finn.niu@apptech.com.hk |
ba94cb1796518d0b58bc03b07d04392cca16dc1d | 576af574c490d79c28908979b048bcf71848febe | /DAA Lab Questions/25SortArrayAfterConvertingToSquares.cpp | 6a8978c9086b5ba19720f425942ddaddfa237144 | [] | no_license | jaskaranbhatia/DSA-Practice-Problems | 01f7ad8b895fde710148fe52e19e4b26e0948552 | 14dcdffd0d2ef3a31a89d158e0f84cbe17f31dd1 | refs/heads/master | 2023-06-14T09:42:07.600856 | 2021-07-05T17:49:47 | 2021-07-05T17:49:47 | 285,176,572 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,325 | cpp | #include <bits/stdc++.h>
using namespace std;
void sortSquares(int arr[], int n)
{
// first dived array into part negative and positive
int K = 0;
for (K = 0; K < n; K++)
if (arr[K] >= 0)
break;
int i = K - 1;
int j = K;
int ind = 0;
// store sorted array
int temp[n];
while (i >= 0 && j < n) {
if (arr[i] * arr[i] < arr[j] * arr[j]) {
temp[ind] = arr[i] * arr[i];
i--;
}
else {
temp[ind] = arr[j] * arr[j];
j++;
}
ind++;
}
/* Copy the remaining elements of first half */
while (i >= 0) {
temp[ind] = arr[i] * arr[i];
i--;
ind++;
}
/* Copy the remaining elements of second half */
while (j < n) {
temp[ind] = arr[j] * arr[j];
j++;
ind++;
}
// copy 'temp' array into original array
for (int i = 0; i < n; i++)
arr[i] = temp[i];
}
int main()
{
int arr[] = { -6, -3, -1, 2, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Before sort " << endl;
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
sortSquares(arr, n);
cout << "\nAfter Sort " << endl;
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
} | [
"jaskaransingh.singh77@gmail.com"
] | jaskaransingh.singh77@gmail.com |
6781628ac60438c23664a59ce8b210327db5d2ff | 4be64e459c3a08723971d73de3cb30a5511c96cc | /mainwindow.h | 8cffe00c0b49815b86c110361b2f7f9470c4c80c | [] | no_license | rvbc1/MKWM_GUI | c1d08a12cec128f73d09dcae53792e521c6d99c6 | 88045144f0f3776774046687ba02affc875073bb | refs/heads/master | 2020-05-25T06:30:56.535310 | 2019-05-20T15:38:06 | 2019-05-20T15:38:06 | 187,668,940 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,355 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtSerialPort>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
private:
QSerialPort *serial;
QTimer *updateing_angle_timer;
QTimer *tracking_timer;
QTimer *recieve_timer;
void addAvaibleSerials();
void prepareSerial();
void prepareData();
void updateData();
void enableDataWidgets();
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void sendData();
void serialReceived();
void tracking();
void on_pushButton_pressed();
void on_pushButton_2_pressed();
void on_pushButton_3_pressed();
void on_spinBox_valueChanged(int arg1);
void on_horizontalSlider_valueChanged(int value);
void on_spinBox_2_valueChanged(int arg1);
void on_horizontalSlider_2_valueChanged(int value);
void on_spinBox_3_valueChanged(int arg1);
void on_horizontalSlider_3_valueChanged(int value);
void on_checkBox_pressed();
void on_checkBox_stateChanged(int arg1);
void on_spinBox_4_valueChanged(int arg1);
void on_horizontalSlider_4_valueChanged(int value);
void on_pushButton_4_clicked();
void on_checkBox_2_stateChanged(int arg1);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"marek_knosala@vp.pl"
] | marek_knosala@vp.pl |
7ebada08ca498ecfba8e61435c04f36239ff0eb6 | 4bea57e631734f8cb1c230f521fd523a63c1ff23 | /projects/openfoam/rarefied-flows/impingment/sims/test/nozzle1/7.96/grad(T) | bd52fd63f0ca387028e5a28fe63e6bb4327bf591 | [] | no_license | andytorrestb/cfal | 76217f77dd43474f6b0a7eb430887e8775b78d7f | 730fb66a3070ccb3e0c52c03417e3b09140f3605 | refs/heads/master | 2023-07-04T01:22:01.990628 | 2021-08-01T15:36:17 | 2021-08-01T15:36:17 | 294,183,829 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 53,026 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1912 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volVectorField;
location "7.96";
object grad(T);
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 -1 0 1 0 0 0];
internalField nonuniform List<vector>
1900
(
(1.44008 -9.59461e-07 0)
(-1.67415 2.67355e-06 0)
(-0.444023 2.82317e-05 0)
(-0.0641595 8.37603e-08 0)
(0.0196676 4.57697e-06 0)
(0.059074 -3.77623e-05 0)
(0.0811122 -2.68428e-05 0)
(0.0650604 -0.000178938 0)
(0.0282706 0.000486986 0)
(0.0296804 -0.000996801 0)
(1.44008 -1.71623e-06 0)
(-1.67412 6.30803e-06 0)
(-0.444025 5.09328e-05 0)
(-0.0641831 1.87344e-05 0)
(0.0196298 4.10521e-05 0)
(0.0590426 7.72023e-06 0)
(0.080971 6.02244e-05 0)
(0.0655742 -0.00086193 0)
(0.0274527 -0.00150676 0)
(-0.00170398 -0.00393152 0)
(1.44008 -4.42354e-13 0)
(-1.67409 -3.92481e-13 0)
(-0.44401 -5.10659e-13 0)
(-0.0641694 -3.36103e-13 0)
(0.0196566 -3.65376e-13 0)
(0.0590932 -2.1684e-13 0)
(0.0802425 1.0842e-13 0)
(0.0634934 1.0842e-14 0)
(0.025201 1.0842e-15 0)
(-0.0049011 1.30104e-14 0)
(1.44008 1.71623e-06 0)
(-1.67412 -6.30803e-06 0)
(-0.444025 -5.09328e-05 0)
(-0.0641831 -1.87344e-05 0)
(0.0196298 -4.10521e-05 0)
(0.0590426 -7.72023e-06 0)
(0.080971 -6.02244e-05 0)
(0.0655742 0.00086193 0)
(0.0274527 0.00150676 0)
(-0.00170398 0.00393152 0)
(1.44008 9.59461e-07 0)
(-1.67415 -2.67355e-06 0)
(-0.444023 -2.82317e-05 0)
(-0.0641595 -8.37607e-08 0)
(0.0196676 -4.57697e-06 0)
(0.059074 3.77623e-05 0)
(0.0811122 2.68428e-05 0)
(0.0650604 0.000178938 0)
(0.0282706 -0.000486986 0)
(0.0296804 0.000996801 0)
(-0.00158816 -0.0268013 9.40789e-16)
(-0.0159187 -0.020401 -1.12826e-15)
(0.0941615 -0.033222 -1.43226e-15)
(0.378295 -0.0628003 0)
(-0.515435 -0.321946 -6.44766e-15)
(-0.0180874 -0.0319318 9.35946e-16)
(-0.00603161 -0.0236765 1.12826e-15)
(0.0753417 -0.0401247 1.43226e-15)
(0.272178 -0.0646654 0)
(-0.448322 -0.351087 0)
(-0.0270016 9.82067e-15 0)
(-0.0123405 2.85316e-14 0)
(0.065028 1.20467e-14 0)
(0.2427 2.87478e-14 0)
(-0.579908 3.22679e-14 0)
(-0.0180874 0.0319318 9.35946e-16)
(-0.00603161 0.0236765 1.12826e-15)
(0.0753417 0.0401247 1.43226e-15)
(0.272178 0.0646654 0)
(-0.448322 0.351087 0)
(-0.00158816 0.0268013 -2.81268e-15)
(-0.0159187 0.020401 -1.12826e-15)
(0.0941615 0.033222 -1.43226e-15)
(0.378295 0.0628003 -3.94568e-15)
(-0.515435 0.321946 6.44766e-15)
(-1.86886 0.448985 2.18206e-15)
(-0.957428 0.313609 -1.57894e-15)
(-0.58891 0.214394 0)
(-0.407956 0.197517 1.01233e-15)
(-0.30558 0.0777638 -4.2561e-16)
(-1.66583 0.447732 -1.09779e-15)
(-0.998099 0.206345 7.94192e-16)
(-0.606203 0.110897 0)
(-0.44988 0.128446 -6.3739e-16)
(-0.298389 -0.0440493 1.06656e-16)
(-1.719 1.31418e-13 0)
(-1.0542 1.89967e-13 0)
(-0.617374 1.0842e-13 0)
(-0.482837 2.4802e-14 2.56503e-16)
(-0.28331 1.72775e-13 -2.13313e-16)
(-1.66583 -0.447732 -1.09779e-15)
(-0.998099 -0.206345 7.94192e-16)
(-0.606203 -0.110897 0)
(-0.44988 -0.128446 -6.3739e-16)
(-0.298389 0.0440493 1.06656e-16)
(-1.86886 -0.448985 1.09779e-15)
(-0.957428 -0.313609 -9.44489e-18)
(-0.58891 -0.214394 0)
(-0.407956 -0.197517 5.94856e-18)
(-0.30558 -0.0777638 4.2561e-16)
(-0.200031 0.742885 0)
(-0.0915532 0.868523 0)
(-0.0572731 0.893041 0)
(-0.0460513 0.851404 0)
(-0.0388725 0.745399 0)
(-0.0602559 0.632184 0)
(-0.0880507 0.507646 0)
(-0.0448366 0.385983 0)
(0.0903305 0.362551 0)
(0.34231 0.345707 0)
(0.398295 0.348532 0)
(0.199618 0.263142 0)
(0.0906246 0.173206 0)
(0.0408864 0.0836831 0)
(-0.0184698 0.0583316 0)
(-0.10795 0.0474245 0)
(-0.200873 0.0387729 0)
(-0.209244 0.0121006 0)
(-0.169393 -0.00144239 0)
(-0.174777 0.00326372 0)
(-0.241769 0.0118625 0)
(-0.304831 0.0162646 0)
(-0.239307 0.00929044 0)
(-0.0976389 0.00103645 0)
(-0.0284664 -0.000218969 0)
(-0.0177118 -0.00013963 0)
(-0.0152196 -0.000196651 0)
(-0.0117923 -0.000398233 0)
(-0.00507513 -0.000507907 0)
(0.0160577 -0.000563889 0)
(0.134086 -0.000434491 0)
(0.294719 6.63478e-05 0)
(0.263846 0.0001631 0)
(0.133012 -0.000167746 0)
(0.0967104 -0.000535729 0)
(0.112347 -0.000857377 0)
(0.110157 -0.000422885 0)
(0.0652326 -0.000899513 0)
(0.00745088 -0.00148851 0)
(-0.00932362 -0.00213817 0)
(-0.0917717 0.224781 0)
(-0.0135023 0.469206 0)
(-0.0418967 0.577544 0)
(-0.0696298 0.625345 0)
(-0.083688 0.575548 0)
(-0.10638 0.462159 0)
(-0.127242 0.347537 0)
(-0.0654954 0.258785 0)
(0.092892 0.242938 0)
(0.347389 0.241818 0)
(0.38304 0.248758 0)
(0.173315 0.193249 0)
(0.0634329 0.130432 0)
(0.0204075 0.0554649 0)
(-0.026845 0.0316662 0)
(-0.111724 0.0168294 0)
(-0.20444 0.0364161 0)
(-0.213015 0.0493402 0)
(-0.169019 0.0360564 0)
(-0.172335 0.0139108 0)
(-0.240437 0.0088147 0)
(-0.306116 0.00613709 0)
(-0.241559 0.00285842 0)
(-0.098649 0.000330663 0)
(-0.0285568 -0.00011135 0)
(-0.0177014 -4.05127e-05 0)
(-0.015247 -6.81263e-05 0)
(-0.0118234 -0.000173787 0)
(-0.00509391 -0.000225664 0)
(0.0160625 -0.00025966 0)
(0.134124 -0.000195434 0)
(0.294755 -4.75883e-05 0)
(0.26383 -1.33538e-05 0)
(0.132932 -0.000205276 0)
(0.0966082 -0.000457697 0)
(0.11234 -0.000685736 0)
(0.110159 -0.0004518 0)
(0.0651393 -0.000590928 0)
(0.00735391 -0.000953809 0)
(-0.00936937 -0.00142012 0)
(-0.0345112 1.43903e-13 0)
(0.0110687 -8.67362e-14 0)
(-0.011851 -2.66122e-13 0)
(-0.0466319 -4.41566e-13 0)
(-0.0863446 -4.57336e-13 0)
(-0.126587 -4.55365e-13 0)
(-0.147214 -2.18812e-13 0)
(-0.0752653 -1.04478e-13 0)
(0.0853948 -1.97128e-13 0)
(0.344003 -4.15939e-13 0)
(0.384166 -1.83329e-13 0)
(0.165196 6.52493e-13 0)
(0.0505421 -1.06252e-12 0)
(0.0121546 -2.0797e-12 0)
(-0.0297092 -2.25711e-12 0)
(-0.106568 -1.9831e-12 0)
(-0.191416 -2.52915e-12 0)
(-0.209349 -1.84906e-12 0)
(-0.179699 -9.60012e-13 0)
(-0.182702 1.26162e-13 0)
(-0.24403 1.80963e-12 0)
(-0.306564 1.39172e-12 0)
(-0.240996 -6.11096e-14 0)
(-0.0985028 -6.84033e-13 0)
(-0.0285744 4.75078e-13 0)
(-0.0176992 1.56716e-13 0)
(-0.0152584 -3.64686e-14 0)
(-0.0118381 6.18981e-13 0)
(-0.00510012 8.77218e-13 0)
(0.0160664 5.70685e-13 0)
(0.134148 2.94706e-13 0)
(0.294772 7.58942e-13 0)
(0.2638 -1.17291e-12 0)
(0.132883 -5.69699e-13 0)
(0.0965706 -2.75979e-13 0)
(0.112348 -2.38524e-13 0)
(0.110185 -6.70234e-14 0)
(0.0650866 -3.84399e-13 0)
(0.00720966 -5.63785e-13 0)
(-0.00945927 -6.05182e-13 0)
(-0.0917717 -0.224781 0)
(-0.0135023 -0.469206 0)
(-0.0418967 -0.577544 0)
(-0.0696298 -0.625345 0)
(-0.083688 -0.575548 0)
(-0.10638 -0.462159 0)
(-0.127242 -0.347537 0)
(-0.0654954 -0.258785 0)
(0.092892 -0.242938 0)
(0.347389 -0.241818 0)
(0.38304 -0.248758 0)
(0.173315 -0.193249 0)
(0.0634329 -0.130432 0)
(0.0204075 -0.0554649 0)
(-0.026845 -0.0316662 0)
(-0.111724 -0.0168294 0)
(-0.20444 -0.0364161 0)
(-0.213015 -0.0493402 0)
(-0.169019 -0.0360564 0)
(-0.172335 -0.0139108 0)
(-0.240437 -0.0088147 0)
(-0.306116 -0.00613709 0)
(-0.241559 -0.00285842 0)
(-0.098649 -0.000330663 0)
(-0.0285568 0.00011135 0)
(-0.0177014 4.05127e-05 0)
(-0.015247 6.81263e-05 0)
(-0.0118234 0.000173787 0)
(-0.00509391 0.000225664 0)
(0.0160625 0.00025966 0)
(0.134124 0.000195434 0)
(0.294755 4.75883e-05 0)
(0.26383 1.33538e-05 0)
(0.132932 0.000205276 0)
(0.0966082 0.000457697 0)
(0.11234 0.000685736 0)
(0.110159 0.0004518 0)
(0.0651393 0.000590928 0)
(0.00735391 0.000953809 0)
(-0.00936937 0.00142012 0)
(-0.200031 -0.742885 0)
(-0.0915532 -0.868523 0)
(-0.0572731 -0.893041 0)
(-0.0460513 -0.851404 0)
(-0.0388725 -0.745399 0)
(-0.0602559 -0.632184 0)
(-0.0880507 -0.507646 0)
(-0.0448366 -0.385983 0)
(0.0903305 -0.362551 0)
(0.34231 -0.345707 0)
(0.398295 -0.348532 0)
(0.199618 -0.263142 0)
(0.0906246 -0.173206 0)
(0.0408864 -0.0836831 0)
(-0.0184698 -0.0583316 0)
(-0.10795 -0.0474245 0)
(-0.200873 -0.0387729 0)
(-0.209244 -0.0121006 0)
(-0.169393 0.00144239 0)
(-0.174777 -0.00326372 0)
(-0.241769 -0.0118625 0)
(-0.304831 -0.0162646 0)
(-0.239307 -0.00929044 0)
(-0.0976389 -0.00103645 0)
(-0.0284664 0.000218969 0)
(-0.0177118 0.00013963 0)
(-0.0152196 0.000196651 0)
(-0.0117923 0.000398233 0)
(-0.00507513 0.000507907 0)
(0.0160577 0.000563889 0)
(0.134086 0.000434491 0)
(0.294719 -6.63478e-05 0)
(0.263846 -0.0001631 0)
(0.133012 0.000167746 0)
(0.0967104 0.000535729 0)
(0.112347 0.000857377 0)
(0.110157 0.000422885 0)
(0.0652326 0.000899513 0)
(0.00745088 0.00148851 0)
(-0.00932362 0.00213817 0)
(-0.0105965 -0.744035 0)
(-0.0174445 -0.659949 0)
(-0.0133793 -0.620376 0)
(-0.00428033 -0.584971 0)
(0.00200444 -0.547893 0)
(-0.0105748 -0.511142 0)
(-0.0181204 -0.442006 0)
(0.00163208 -0.350617 0)
(0.121117 -0.309069 0)
(0.362054 -0.223016 0)
(0.417191 -0.271842 0)
(0.25288 -0.229744 0)
(0.144562 -0.15539 0)
(0.0687864 -0.086419 0)
(-0.0137847 -0.0727383 0)
(-0.103819 -0.0757243 0)
(-0.186406 -0.067708 0)
(-0.192149 -0.0396284 0)
(-0.163044 -0.0201572 0)
(-0.177858 -0.0178239 0)
(-0.247051 -0.0217734 0)
(-0.305988 -0.0250681 0)
(-0.234611 -0.0148339 0)
(-0.0938521 -0.00181354 0)
(-0.0279236 0.000344402 0)
(-0.0177033 0.000297073 0)
(-0.0151165 0.000375353 0)
(-0.011664 0.00068742 0)
(-0.00501171 0.000889478 0)
(0.0160221 0.000965476 0)
(0.133771 0.000754069 0)
(0.294422 -0.0003254 0)
(0.263958 -0.000488106 0)
(0.133278 0.000121948 0)
(0.0969227 0.000634345 0)
(0.112262 0.000992327 0)
(0.110187 0.000565417 0)
(0.0656999 0.000866757 0)
(0.00801878 0.00142175 0)
(-0.00901476 0.00213029 0)
(-0.00625457 -0.214408 0)
(-0.0121303 -0.195369 0)
(-0.00855892 -0.18624 0)
(0.00139697 -0.181227 0)
(0.0103523 -0.188675 0)
(0.0151408 -0.191837 0)
(0.0291384 -0.174756 0)
(0.0583481 -0.150393 0)
(0.196782 -0.115301 0)
(0.367596 -0.0675609 0)
(0.38168 -0.145017 0)
(0.283274 -0.147741 0)
(0.199815 -0.11489 0)
(0.105571 -0.0838387 0)
(-0.0106763 -0.0869657 0)
(-0.105318 -0.099368 0)
(-0.173848 -0.0940648 0)
(-0.17259 -0.0639282 0)
(-0.151785 -0.0446492 0)
(-0.174682 -0.0409655 0)
(-0.245917 -0.0426501 0)
(-0.297524 -0.0410957 0)
(-0.219416 -0.0210619 0)
(-0.0850431 -0.00236792 0)
(-0.0267236 0.000606484 0)
(-0.0176864 0.00054061 0)
(-0.0148988 0.000648381 0)
(-0.0113657 0.00106583 0)
(-0.0048412 0.00137703 0)
(0.0159462 0.00150348 0)
(0.133012 0.00121907 0)
(0.293682 -0.000335878 0)
(0.264217 -0.000659209 0)
(0.133951 0.000112471 0)
(0.0974353 0.000897054 0)
(0.112326 0.00124705 0)
(0.11002 0.00120697 0)
(0.0658073 0.000991598 0)
(0.00836394 0.0012467 0)
(-0.00880646 0.00176551 0)
(0.00775006 -0.000913104 0)
(0.00969838 0.00402164 0)
(0.000247981 0.0077717 0)
(-0.00662609 0.00588793 0)
(-0.00821992 -0.0110916 0)
(0.00283751 -0.0180689 0)
(0.0218165 -0.00795528 0)
(0.0589257 -0.000685744 0)
(0.200938 0.0430415 0)
(0.333418 0.0218219 0)
(0.339927 -0.0212382 0)
(0.281912 -0.0403846 0)
(0.206141 -0.03638 0)
(0.0956951 -0.0650524 0)
(-0.0287493 -0.0936396 0)
(-0.11066 -0.117307 0)
(-0.152255 -0.106183 0)
(-0.14453 -0.0717078 0)
(-0.140916 -0.0540659 0)
(-0.175932 -0.0529204 0)
(-0.247177 -0.0567477 0)
(-0.285185 -0.0543745 0)
(-0.197291 -0.025459 0)
(-0.0729717 -0.0024579 0)
(-0.0251208 0.000907675 0)
(-0.017663 0.000856159 0)
(-0.0146104 0.00102398 0)
(-0.0109619 0.00154482 0)
(-0.00458997 0.0019481 0)
(0.0158699 0.00212761 0)
(0.131999 0.00181742 0)
(0.292612 8.48327e-05 0)
(0.26439 -0.000311331 0)
(0.134777 0.000420392 0)
(0.098016 0.0013486 0)
(0.112561 0.00135715 0)
(0.109941 0.00164212 0)
(0.0657381 0.0011664 0)
(0.00876455 0.00137686 0)
(-0.00851481 0.00208544 0)
(-0.00149927 0.00694741 0)
(-0.00376129 -0.00245544 0)
(-0.00676049 -0.00719779 0)
(-0.0167804 -0.00801551 0)
(-0.0127335 -0.00978264 0)
(0.018163 0.00308662 0)
(0.0458895 0.0265381 0)
(0.107491 0.0648529 0)
(0.218471 0.110556 0)
(0.305654 0.0824547 0)
(0.321735 0.0657575 0)
(0.268683 0.0222073 0)
(0.176044 0.00799681 0)
(0.0503939 -0.0648577 0)
(-0.0610311 -0.10461 0)
(-0.117405 -0.12406 0)
(-0.129907 -0.103765 0)
(-0.122368 -0.0755924 0)
(-0.133681 -0.0652066 0)
(-0.177266 -0.065446 0)
(-0.247318 -0.0701807 0)
(-0.267373 -0.064306 0)
(-0.169388 -0.0257959 0)
(-0.0596352 -0.00187328 0)
(-0.02353 0.00115757 0)
(-0.0175744 0.00117171 0)
(-0.0142351 0.00143184 0)
(-0.0104752 0.00205417 0)
(-0.00427961 0.00252681 0)
(0.0158203 0.00271984 0)
(0.131043 0.0024027 0)
(0.291631 0.000351598 0)
(0.26454 -0.000158505 0)
(0.135551 0.000603808 0)
(0.098338 0.0015775 0)
(0.112608 0.00111605 0)
(0.109836 0.00144869 0)
(0.0655517 0.000993582 0)
(0.00924956 0.00130558 0)
(-0.00812364 0.00222364 0)
(-0.00131086 0.026444 0)
(-0.00393245 0.0270767 0)
(-0.0051099 0.0280724 0)
(-0.00911695 0.0361064 0)
(0.00247849 0.0578969 0)
(0.0378375 0.0800342 0)
(0.0813367 0.100143 0)
(0.139888 0.136018 0)
(0.2179 0.151652 0)
(0.290249 0.145627 0)
(0.28187 0.099373 0)
(0.226252 0.0568395 0)
(0.122242 -0.00487378 0)
(-0.0128167 -0.0915043 0)
(-0.0857985 -0.124609 0)
(-0.109845 -0.120748 0)
(-0.10555 -0.0943692 0)
(-0.107374 -0.0765906 0)
(-0.131139 -0.0730321 0)
(-0.180725 -0.0757259 0)
(-0.246078 -0.0823872 0)
(-0.242414 -0.0688416 0)
(-0.137129 -0.0219825 0)
(-0.0469983 -0.000661166 0)
(-0.0221865 0.00158096 0)
(-0.0173987 0.00167979 0)
(-0.01376 0.00206856 0)
(-0.00990672 0.00278801 0)
(-0.00394851 0.00330792 0)
(0.0157503 0.00353671 0)
(0.129717 0.00324827 0)
(0.290144 0.00129994 0)
(0.264633 0.000554669 0)
(0.13645 0.00115499 0)
(0.0985096 0.00208739 0)
(0.112437 0.00131939 0)
(0.109823 0.00139552 0)
(0.0656002 0.000907239 0)
(0.00994988 0.00116807 0)
(-0.00763014 0.00220152 0)
(-0.000889658 0.0691095 0)
(-0.00219218 0.0706055 0)
(0.00194088 0.076782 0)
(0.0119597 0.0903205 0)
(0.029597 0.116276 0)
(0.058873 0.137699 0)
(0.0998374 0.152852 0)
(0.157126 0.164392 0)
(0.227731 0.180171 0)
(0.255276 0.169163 0)
(0.236177 0.109588 0)
(0.168227 0.0483944 0)
(0.0330943 -0.0651542 0)
(-0.0649876 -0.116255 0)
(-0.0892118 -0.124301 0)
(-0.0882642 -0.104351 0)
(-0.0873548 -0.0846181 0)
(-0.101807 -0.0787642 0)
(-0.132848 -0.0796987 0)
(-0.186281 -0.0850416 0)
(-0.240684 -0.091926 0)
(-0.209165 -0.0652727 0)
(-0.103687 -0.0155029 0)
(-0.0369286 0.000638836 0)
(-0.0212742 0.00202958 0)
(-0.0171045 0.00220712 0)
(-0.0131672 0.0027066 0)
(-0.00928087 0.00349537 0)
(-0.00355814 0.00405165 0)
(0.0157628 0.00426182 0)
(0.128888 0.00396812 0)
(0.289035 0.00155338 0)
(0.264401 0.000485082 0)
(0.137028 0.00116589 0)
(0.0984964 0.00213227 0)
(0.111942 0.00134992 0)
(0.109439 0.00121497 0)
(0.0653325 0.000815235 0)
(0.0104968 0.00108512 0)
(-0.00712778 0.00211845 0)
(0.000130735 0.135319 0)
(0.00346112 0.138213 0)
(0.0138883 0.145094 0)
(0.0289406 0.153645 0)
(0.0481337 0.165065 0)
(0.0730837 0.177872 0)
(0.107059 0.190888 0)
(0.166214 0.206632 0)
(0.222498 0.209483 0)
(0.222233 0.151667 0)
(0.165493 0.0738757 0)
(0.057864 -0.0297625 0)
(-0.0364207 -0.10732 0)
(-0.0698123 -0.119466 0)
(-0.074327 -0.105675 0)
(-0.0716059 -0.0883743 0)
(-0.0808936 -0.0817144 0)
(-0.102634 -0.0827681 0)
(-0.137188 -0.0855327 0)
(-0.192508 -0.0943535 0)
(-0.227028 -0.0969265 0)
(-0.16877 -0.0536872 0)
(-0.0736143 -0.00896637 0)
(-0.0301033 0.0012743 0)
(-0.0206753 0.0019713 0)
(-0.0167463 0.00223598 0)
(-0.0125186 0.00282871 0)
(-0.00861058 0.00362391 0)
(-0.00320992 0.00418253 0)
(0.0156698 0.00437097 0)
(0.127107 0.00409427 0)
(0.286787 0.00129234 0)
(0.264259 -0.000290953 0)
(0.138037 0.000235233 0)
(0.098687 0.00119696 0)
(0.111553 0.000717336 0)
(0.109308 0.000743157 0)
(0.0654751 0.000715911 0)
(0.0112057 0.00118725 0)
(-0.00663438 0.00225316 0)
(0.0018988 0.213954 0)
(0.00722652 0.212519 0)
(0.0168115 0.214214 0)
(0.0312048 0.216793 0)
(0.0529433 0.219323 0)
(0.0837572 0.219514 0)
(0.127552 0.223594 0)
(0.175045 0.227421 0)
(0.174764 0.172253 0)
(0.1246 0.0736105 0)
(0.0613452 -0.00960746 0)
(-0.00638009 -0.0919146 0)
(-0.0533474 -0.114672 0)
(-0.0634021 -0.105317 0)
(-0.0592506 -0.0888896 0)
(-0.065175 -0.0820697 0)
(-0.0819524 -0.0843702 0)
(-0.105487 -0.0869081 0)
(-0.144012 -0.0918404 0)
(-0.197261 -0.103406 0)
(-0.201497 -0.0929176 0)
(-0.124404 -0.037562 0)
(-0.0507236 -0.00501694 0)
(-0.0263886 0.000348892 0)
(-0.0203475 0.00063979 0)
(-0.0162782 0.00106506 0)
(-0.0118298 0.00180669 0)
(-0.00797628 0.00265951 0)
(-0.00283824 0.00326663 0)
(0.0156778 0.0034842 0)
(0.125921 0.00318206 0)
(0.284809 -3.98733e-05 0)
(0.263382 -0.00114836 0)
(0.138461 -6.65111e-05 0)
(0.0989609 0.000795809 0)
(0.111504 0.000280217 0)
(0.109437 0.000467057 0)
(0.0657604 0.00090008 0)
(0.0119781 0.00157365 0)
(-0.00610063 0.00264829 0)
(-0.00125225 0.262287 0)
(0.00371141 0.253428 0)
(0.0180073 0.251014 0)
(0.0338642 0.24395 0)
(0.0507556 0.231458 0)
(0.0771995 0.220363 0)
(0.114679 0.207115 0)
(0.11674 0.150794 0)
(0.0742799 0.0573758 0)
(0.0469852 -0.0105001 0)
(0.0059871 -0.0767822 0)
(-0.0433805 -0.11044 0)
(-0.049336 -0.106032 0)
(-0.0449669 -0.0903701 0)
(-0.0519248 -0.0840222 0)
(-0.0672509 -0.0868473 0)
(-0.0855561 -0.0896519 0)
(-0.109832 -0.0901508 0)
(-0.153086 -0.0987609 0)
(-0.193546 -0.10758 0)
(-0.163579 -0.0734385 0)
(-0.0840657 -0.019377 0)
(-0.037082 0.000526757 0)
(-0.0246523 0.0036446 0)
(-0.0199851 0.00452801 0)
(-0.0156218 0.00571441 0)
(-0.0109821 0.00700421 0)
(-0.00720372 0.00825389 0)
(-0.00241522 0.00912228 0)
(0.0155883 0.00959211 0)
(0.123711 0.00956 0)
(0.282614 0.00714714 0)
(0.264234 0.00769762 0)
(0.139911 0.0097839 0)
(0.0990211 0.0107414 0)
(0.111236 0.00812879 0)
(0.109905 0.00484907 0)
(0.0665415 0.00304992 0)
(0.0128903 0.00289814 0)
(-0.00559882 0.00378791 0)
(-0.00663777 0.248667 0)
(-0.00363629 0.249341 0)
(0.00767771 0.230461 0)
(0.0123602 0.206597 0)
(0.0302148 0.187281 0)
(0.0602993 0.165951 0)
(0.0605115 0.113495 0)
(0.0307505 0.035734 0)
(0.0193354 -0.0261286 0)
(-0.00467941 -0.0716067 0)
(-0.0349601 -0.108194 0)
(-0.0345665 -0.10268 0)
(-0.0340077 -0.0871321 0)
(-0.0421924 -0.0825134 0)
(-0.0558559 -0.0842372 0)
(-0.0706 -0.0849163 0)
(-0.0851357 -0.0813108 0)
(-0.114264 -0.0819822 0)
(-0.160807 -0.0907562 0)
(-0.172859 -0.0845932 0)
(-0.116502 -0.0319195 0)
(-0.0531279 0.00986904 0)
(-0.0285391 0.0217929 0)
(-0.0225329 0.0254318 0)
(-0.018353 0.0284134 0)
(-0.0138921 0.0315939 0)
(-0.00938262 0.0343448 0)
(-0.00593522 0.0369439 0)
(-0.00154868 0.0385221 0)
(0.0160996 0.0398546 0)
(0.123565 0.0413634 0)
(0.283015 0.0463857 0)
(0.265923 0.0530912 0)
(0.141395 0.0520897 0)
(0.097366 0.0446436 0)
(0.105826 0.0315915 0)
(0.104543 0.0218763 0)
(0.0638804 0.0134566 0)
(0.0126893 0.00704709 0)
(-0.00524322 0.00581647 0)
(-0.000602195 0.199563 0)
(-0.0138323 0.1989 0)
(-0.023183 0.172279 0)
(-0.00774513 0.150465 0)
(0.011588 0.12555 0)
(0.00609628 0.0758617 0)
(-0.0108029 0.00941035 0)
(-0.0178068 -0.04246 0)
(-0.0291575 -0.0728459 0)
(-0.0320958 -0.0990603 0)
(-0.0239558 -0.0899561 0)
(-0.0230847 -0.0757439 0)
(-0.0299032 -0.0689791 0)
(-0.0421772 -0.0656288 0)
(-0.0542404 -0.0590983 0)
(-0.064431 -0.0422998 0)
(-0.0827286 -0.0256462 0)
(-0.118934 -0.0246927 0)
(-0.155602 -0.0243627 0)
(-0.136849 0.0224497 0)
(-0.0725515 0.0897296 0)
(-0.0323064 0.122964 0)
(-0.0220852 0.136037 0)
(-0.0182726 0.144649 0)
(-0.0140472 0.15212 0)
(-0.00990616 0.158912 0)
(-0.00582661 0.163852 0)
(-0.00317828 0.16855 0)
(0.000389557 0.170765 0)
(0.0183262 0.17352 0)
(0.130004 0.179776 0)
(0.293916 0.199248 0)
(0.26973 0.195024 0)
(0.13177 0.168936 0)
(0.0792683 0.139818 0)
(0.0892967 0.1008 0)
(0.0924299 0.0667128 0)
(0.0522515 0.0389461 0)
(0.00552803 0.0215515 0)
(-0.00678469 0.0117881 0)
(-0.00727609 0.124594 0)
(-0.0299282 0.101483 0)
(-0.0389962 0.0803987 0)
(-0.032669 0.0595059 0)
(-0.0416758 0.0318733 0)
(-0.0516174 -0.00147216 0)
(-0.0535077 -0.0268644 0)
(-0.0485146 -0.0543537 0)
(-0.0352067 -0.0630275 0)
(-0.0211674 -0.045559 0)
(-0.0124916 -0.0280131 0)
(-0.0143522 -0.0110215 0)
(-0.0242605 0.00714564 0)
(-0.0326709 0.0315171 0)
(-0.0333752 0.0648726 0)
(-0.0383643 0.0947965 0)
(-0.0681689 0.107244 0)
(-0.113027 0.107142 0)
(-0.115379 0.133549 0)
(-0.0629157 0.200597 0)
(-0.0196425 0.249978 0)
(-0.00850416 0.267216 0)
(-0.00764217 0.274453 0)
(-0.0070352 0.279579 0)
(-0.00460939 0.283718 0)
(-0.00258602 0.287533 0)
(-9.44315e-05 0.290379 0)
(0.000726175 0.292523 0)
(0.00323985 0.292895 0)
(0.024783 0.295275 0)
(0.148358 0.302255 0)
(0.297708 0.308979 0)
(0.236714 0.269396 0)
(0.0881962 0.22851 0)
(0.0317075 0.203235 0)
(0.035379 0.167719 0)
(0.0449381 0.125068 0)
(0.0203614 0.0859154 0)
(-0.0134812 0.0526432 0)
(-0.0146516 0.0272443 0)
(-0.0228725 0.0440141 0)
(-0.0564204 0.0281409 0)
(-0.0636339 0.0241151 0)
(-0.054506 0.0218956 0)
(-0.0471727 0.0306844 0)
(-0.0505055 0.0542895 0)
(-0.0617614 0.068329 0)
(-0.0526549 0.0775614 0)
(-0.0206825 0.0914273 0)
(0.00164531 0.112282 0)
(0.00932573 0.13345 0)
(0.0107956 0.14968 0)
(0.0110885 0.164818 0)
(0.0134505 0.182855 0)
(0.00673795 0.194312 0)
(-0.0235999 0.185386 0)
(-0.0708318 0.158193 0)
(-0.0935858 0.15016 0)
(-0.0655455 0.191594 0)
(-0.0246541 0.231887 0)
(-0.00835517 0.241357 0)
(-0.0087215 0.239369 0)
(-0.0101713 0.235595 0)
(-0.00934442 0.232952 0)
(-0.00638271 0.231006 0)
(-0.00348708 0.229752 0)
(-0.00101754 0.229222 0)
(-0.000753854 0.227517 0)
(0.00304122 0.226375 0)
(0.0273464 0.227315 0)
(0.14321 0.227684 0)
(0.262251 0.19976 0)
(0.192187 0.149363 0)
(0.0680156 0.127091 0)
(0.0206879 0.128203 0)
(0.0139723 0.126735 0)
(0.0136013 0.114602 0)
(-0.0175399 0.103331 0)
(-0.0510096 0.0831653 0)
(-0.03126 0.0541216 0)
(-0.0225721 0.0188176 0)
(-0.0491036 0.0409965 0)
(-0.0450144 0.0815297 0)
(-0.0263386 0.123204 0)
(-0.0104599 0.177127 0)
(-0.0153418 0.237959 0)
(-0.031082 0.28083 0)
(-0.0262563 0.301312 0)
(-0.00174858 0.282225 0)
(0.0193269 0.248323 0)
(0.0235463 0.222636 0)
(0.0158754 0.20308 0)
(0.00770849 0.185636 0)
(-0.00424994 0.162178 0)
(-0.0309365 0.122583 0)
(-0.0731698 0.0763886 0)
(-0.102114 0.0513328 0)
(-0.0808407 0.0732742 0)
(-0.0366234 0.110204 0)
(-0.0149619 0.125621 0)
(-0.0124328 0.124787 0)
(-0.0140572 0.121814 0)
(-0.013826 0.120363 0)
(-0.011457 0.120393 0)
(-0.00769268 0.121031 0)
(-0.00430471 0.121679 0)
(-0.00224803 0.122155 0)
(-0.00201775 0.121654 0)
(0.00304493 0.12191 0)
(0.026044 0.12194 0)
(0.121804 0.117939 0)
(0.222235 0.0744294 0)
(0.166688 0.0419037 0)
(0.0678064 0.0414927 0)
(0.0313645 0.0462694 0)
(0.022272 0.048209 0)
(0.0223854 0.0456534 0)
(-0.00993202 0.0518338 0)
(-0.0609015 0.0657717 0)
(-0.0426392 0.0666541 0)
(-0.00150014 0.0368717 0)
(0.00401133 0.070107 0)
(0.0155844 0.120975 0)
(0.0376151 0.164249 0)
(0.0634092 0.215516 0)
(0.0494264 0.257695 0)
(-0.000712238 0.281543 0)
(-0.0513102 0.2733 0)
(-0.0717443 0.215566 0)
(-0.0557769 0.144843 0)
(-0.0342724 0.0949331 0)
(-0.0248597 0.0651903 0)
(-0.0283258 0.0430027 0)
(-0.0473095 0.0161095 0)
(-0.075932 -0.01529 0)
(-0.092259 -0.0299555 0)
(-0.073833 -0.000689987 0)
(-0.0368556 0.0490417 0)
(-0.015102 0.0761422 0)
(-0.0106012 0.083374 0)
(-0.0120235 0.0851944 0)
(-0.012985 0.0871486 0)
(-0.0115411 0.0904251 0)
(-0.0087004 0.0938865 0)
(-0.00514323 0.0968365 0)
(-0.0024039 0.0989394 0)
(-0.00104196 0.100095 0)
(-0.000990419 0.100759 0)
(0.00331681 0.101644 0)
(0.0235201 0.0997215 0)
(0.0974273 0.0936083 0)
(0.188981 0.0441635 0)
(0.160448 0.0163934 0)
(0.0722225 0.0259624 0)
(0.0271601 0.0227327 0)
(0.0133788 0.0139511 0)
(0.0170943 0.00349259 0)
(0.00184681 -0.00130926 0)
(-0.0367282 0.0153607 0)
(-0.0304096 0.04444 0)
(0.00945468 0.0332781 0)
(0.0319412 0.0434738 0)
(0.0457041 0.0643526 0)
(0.0647652 0.0814517 0)
(0.0795878 0.0967828 0)
(0.0482835 0.0880785 0)
(-0.0160443 0.0783486 0)
(-0.0898333 0.0609498 0)
(-0.125534 0.0258946 0)
(-0.0969198 0.00182004 0)
(-0.0532097 -0.00707218 0)
(-0.0341666 -0.0134984 0)
(-0.0395875 -0.0246171 0)
(-0.060423 -0.0343533 0)
(-0.0753264 -0.0277134 0)
(-0.0591007 0.00538044 0)
(-0.0259897 0.0523956 0)
(-0.00680245 0.082634 0)
(-0.00353946 0.0942577 0)
(-0.00623891 0.0985083 0)
(-0.00879553 0.101258 0)
(-0.00901677 0.104422 0)
(-0.00733311 0.108176 0)
(-0.00527872 0.111448 0)
(-0.00282351 0.113725 0)
(-0.00116499 0.114987 0)
(-0.000494357 0.115551 0)
(-0.000524572 0.115818 0)
(0.00204498 0.116262 0)
(0.0183003 0.113129 0)
(0.0682664 0.104812 0)
(0.147828 0.0575582 0)
(0.149148 0.0170822 0)
(0.0739152 0.0213751 0)
(0.0197899 0.0147759 0)
(0.0037315 0.00625971 0)
(0.00768003 -0.00470607 0)
(0.0015045 -0.0173377 0)
(-0.0168158 -0.0193905 0)
(-0.0146172 0.00194353 0)
(0.0083248 -0.00832884 0)
(0.0339558 -0.0064762 0)
(0.0521813 -0.00595329 0)
(0.0688661 -0.00896275 0)
(0.069795 -0.0102074 0)
(0.0316626 -0.0256074 0)
(-0.0268545 -0.0322137 0)
(-0.101857 -0.0342982 0)
(-0.128724 -0.0285912 0)
(-0.0875449 -0.00906939 0)
(-0.0490338 0.00249636 0)
(-0.0417666 0.0031722 0)
(-0.0484224 -0.000891542 0)
(-0.0502932 0.00591202 0)
(-0.0376431 0.0341958 0)
(-0.015063 0.0733014 0)
(0.000611323 0.0971447 0)
(0.00348427 0.10492 0)
(0.000195108 0.106632 0)
(-0.00385551 0.107557 0)
(-0.00632506 0.108895 0)
(-0.00631824 0.110214 0)
(-0.00477035 0.111128 0)
(-0.00335337 0.111694 0)
(-0.001733 0.11192 0)
(-0.000644882 0.11158 0)
(-0.000241435 0.111316 0)
(-0.000305027 0.11097 0)
(0.000725722 0.111188 0)
(0.0124871 0.108882 0)
(0.0438775 0.098545 0)
(0.104441 0.0649033 0)
(0.125581 0.0141381 0)
(0.0700001 0.0146842 0)
(0.0125943 0.0124987 0)
(-0.0053948 0.00561371 0)
(-0.00564508 -0.0075642 0)
(-0.0123036 -0.0117986 0)
(-0.0181481 -0.0242787 0)
(-0.00985139 -0.0474248 0)
(0.0112399 -0.296256 0)
(0.0342303 -0.136644 0)
(0.043308 -0.0603955 0)
(0.0606658 -0.0644211 0)
(0.0635484 -0.0653313 0)
(0.0270774 -0.0684085 0)
(-0.0244191 -0.0624945 0)
(-0.0863425 -0.0515715 0)
(-0.101223 -0.0199237 0)
(-0.0669627 0.00742523 0)
(-0.0414133 0.0170008 0)
(-0.0374313 0.0206013 0)
(-0.0369473 0.0288163 0)
(-0.0266115 0.0458464 0)
(-0.0103876 0.0664086 0)
(0.00155919 0.0796825 0)
(0.00447933 0.0814006 0)
(0.00234003 0.0782508 0)
(-0.000998913 0.0749613 0)
(-0.00405812 0.072994 0)
(-0.00623506 0.0724908 0)
(-0.00686532 0.0722642 0)
(-0.00590645 0.0716468 0)
(-0.00451497 0.0709954 0)
(-0.0029337 0.0705217 0)
(-0.00174737 0.069593 0)
(-0.00108163 0.0689547 0)
(-0.000648297 0.0683345 0)
(3.2656e-05 0.0685016 0)
(0.00611733 0.0677062 0)
(0.0258868 0.0582646 0)
(0.0664904 0.0360106 0)
(0.100755 -0.0109467 0)
(0.0723354 -0.0189512 0)
(0.0110493 -0.00777413 0)
(-0.0156018 -0.00221216 0)
(-0.00909912 -0.014678 0)
(-0.0146022 -0.0176565 0)
(-0.0511465 -0.111045 0)
(-0.0369217 -0.311239 0)
(0.162132 -0.751216 0)
(0.26124 -0.443452 0)
(0.121778 -0.0986609 0)
(0.0641097 -0.0651162 0)
(0.0659526 -0.0803862 0)
(0.0343962 -0.0880564 0)
(-0.0106298 -0.0879936 0)
(-0.0608339 -0.079972 0)
(-0.0718724 -0.0497872 0)
(-0.0519632 -0.0262081 0)
(-0.0363368 -0.0144607 0)
(-0.0303807 -0.00569439 0)
(-0.0240953 0.00696801 0)
(-0.0140679 0.0206541 0)
(-0.00503741 0.0291571 0)
(-0.000616223 0.0291058 0)
(-0.000768339 0.0245899 0)
(-0.00272084 0.0197182 0)
(-0.00487049 0.0158719 0)
(-0.00623621 0.0134177 0)
(-0.00702833 0.0124189 0)
(-0.0071315 0.0124533 0)
(-0.00599307 0.0130399 0)
(-0.00443761 0.0137839 0)
(-0.00308437 0.0147051 0)
(-0.0021549 0.0151588 0)
(-0.0014542 0.0156224 0)
(-0.000741574 0.0160338 0)
(0.000120336 0.0166816 0)
(0.00262228 0.017264 0)
(0.0133345 0.0130365 0)
(0.0377461 -0.00207874 0)
(0.0726173 -0.0363779 0)
(0.0730572 -0.0634783 0)
(0.0287247 -0.0465138 0)
(-0.0120476 -0.0195292 0)
(-0.0205278 -0.0199972 0)
(-0.105167 -0.0531778 0)
(-0.301055 -0.306969 0)
(-0.202766 -0.674899 0)
(0.307812 -0.472821 0)
(0.663056 -0.321644 0)
(0.407886 -0.0558419 0)
(0.078276 -0.0247395 0)
(0.0414424 -0.041141 0)
(0.0197466 -0.0501747 0)
(-0.0166287 -0.0563434 0)
(-0.0495254 -0.0563999 0)
(-0.049414 -0.0446082 0)
(-0.0329207 -0.033094 0)
(-0.0216456 -0.0248471 0)
(-0.0167818 -0.0178484 0)
(-0.011557 -0.0107351 0)
(-0.00522934 -0.00483696 0)
(-0.0022432 -0.00156297 0)
(-0.00284189 -0.00193731 0)
(-0.00456689 -0.00387263 0)
(-0.0060609 -0.0058792 0)
(-0.00707027 -0.00733873 0)
(-0.00738558 -0.00816199 0)
(-0.00716442 -0.00853147 0)
(-0.00626692 -0.00830321 0)
(-0.0046243 -0.00763427 0)
(-0.00291033 -0.00688278 0)
(-0.00160874 -0.00604935 0)
(-0.000863423 -0.00535148 0)
(-0.000238487 -0.00470914 0)
(0.000372372 -0.00408988 0)
(0.00121814 -0.00355316 0)
(0.00260476 -0.00295065 0)
(0.00724745 -0.00357134 0)
(0.0188729 -0.00926741 0)
(0.0415886 -0.0231567 0)
(0.0625681 -0.041467 0)
(0.0534002 -0.0340417 0)
(0.00995047 -0.0158604 0)
(-0.0415241 -0.0112135 0)
(-0.291138 -0.037649 0)
(-0.650259 -0.204203 0)
(-0.391472 -0.400031 0)
(0.307812 0.472821 0)
(0.663056 0.321644 0)
(0.407886 0.0558419 0)
(0.078276 0.0247395 0)
(0.0414424 0.041141 0)
(0.0197466 0.0501747 0)
(-0.0166287 0.0563434 0)
(-0.0495254 0.0563999 0)
(-0.049414 0.0446082 0)
(-0.0329207 0.033094 0)
(-0.0216456 0.0248471 0)
(-0.0167818 0.0178484 0)
(-0.011557 0.0107351 0)
(-0.00522934 0.00483696 0)
(-0.0022432 0.00156297 0)
(-0.00284189 0.00193731 0)
(-0.00456689 0.00387263 0)
(-0.0060609 0.0058792 0)
(-0.00707027 0.00733873 0)
(-0.00738558 0.00816199 0)
(-0.00716442 0.00853147 0)
(-0.00626692 0.00830321 0)
(-0.0046243 0.00763427 0)
(-0.00291033 0.00688278 0)
(-0.00160874 0.00604935 0)
(-0.000863423 0.00535148 0)
(-0.000238487 0.00470914 0)
(0.000372372 0.00408988 0)
(0.00121814 0.00355316 0)
(0.00260476 0.00295065 0)
(0.00724745 0.00357134 0)
(0.0188729 0.00926741 0)
(0.0415886 0.0231567 0)
(0.0625681 0.041467 0)
(0.0534002 0.0340417 0)
(0.00995047 0.0158604 0)
(-0.0415241 0.0112135 0)
(-0.291138 0.037649 0)
(-0.650259 0.204203 0)
(-0.391472 0.400031 0)
(0.162132 0.751216 0)
(0.26124 0.443452 0)
(0.121778 0.0986609 0)
(0.0641097 0.0651162 0)
(0.0659526 0.0803862 0)
(0.0343962 0.0880564 0)
(-0.0106298 0.0879936 0)
(-0.0608339 0.079972 0)
(-0.0718724 0.0497872 0)
(-0.0519632 0.0262081 0)
(-0.0363368 0.0144607 0)
(-0.0303807 0.00569439 0)
(-0.0240953 -0.00696801 0)
(-0.0140679 -0.0206541 0)
(-0.00503741 -0.0291571 0)
(-0.000616223 -0.0291058 0)
(-0.000768339 -0.0245899 0)
(-0.00272084 -0.0197182 0)
(-0.00487049 -0.0158719 0)
(-0.00623621 -0.0134177 0)
(-0.00702833 -0.0124189 0)
(-0.0071315 -0.0124533 0)
(-0.00599307 -0.0130399 0)
(-0.00443761 -0.0137839 0)
(-0.00308437 -0.0147051 0)
(-0.0021549 -0.0151588 0)
(-0.0014542 -0.0156224 0)
(-0.000741574 -0.0160338 0)
(0.000120336 -0.0166816 0)
(0.00262228 -0.017264 0)
(0.0133345 -0.0130365 0)
(0.0377461 0.00207874 0)
(0.0726173 0.0363779 0)
(0.0730572 0.0634783 0)
(0.0287247 0.0465138 0)
(-0.0120476 0.0195292 0)
(-0.0205278 0.0199972 0)
(-0.105167 0.0531778 0)
(-0.301055 0.306969 0)
(-0.202766 0.674899 0)
(0.0112399 0.296256 0)
(0.0342303 0.136644 0)
(0.043308 0.0603955 0)
(0.0606658 0.0644211 0)
(0.0635484 0.0653313 0)
(0.0270774 0.0684085 0)
(-0.0244191 0.0624945 0)
(-0.0863425 0.0515715 0)
(-0.101223 0.0199237 0)
(-0.0669627 -0.00742523 0)
(-0.0414133 -0.0170008 0)
(-0.0374313 -0.0206013 0)
(-0.0369473 -0.0288163 0)
(-0.0266115 -0.0458464 0)
(-0.0103876 -0.0664086 0)
(0.00155919 -0.0796825 0)
(0.00447933 -0.0814006 0)
(0.00234003 -0.0782508 0)
(-0.000998913 -0.0749613 0)
(-0.00405812 -0.072994 0)
(-0.00623506 -0.0724908 0)
(-0.00686532 -0.0722642 0)
(-0.00590645 -0.0716468 0)
(-0.00451497 -0.0709954 0)
(-0.0029337 -0.0705217 0)
(-0.00174737 -0.069593 0)
(-0.00108163 -0.0689547 0)
(-0.000648297 -0.0683345 0)
(3.2656e-05 -0.0685016 0)
(0.00611733 -0.0677062 0)
(0.0258868 -0.0582646 0)
(0.0664904 -0.0360106 0)
(0.100755 0.0109467 0)
(0.0723354 0.0189512 0)
(0.0110493 0.00777413 0)
(-0.0156018 0.00221216 0)
(-0.00909912 0.014678 0)
(-0.0146022 0.0176565 0)
(-0.0511465 0.111045 0)
(-0.0369217 0.311239 0)
(0.0083248 0.00832884 0)
(0.0339558 0.0064762 0)
(0.0521813 0.00595329 0)
(0.0688661 0.00896275 0)
(0.069795 0.0102074 0)
(0.0316626 0.0256074 0)
(-0.0268545 0.0322137 0)
(-0.101857 0.0342982 0)
(-0.128724 0.0285912 0)
(-0.0875449 0.00906939 0)
(-0.0490338 -0.00249636 0)
(-0.0417666 -0.0031722 0)
(-0.0484224 0.000891542 0)
(-0.0502932 -0.00591202 0)
(-0.0376431 -0.0341958 0)
(-0.015063 -0.0733014 0)
(0.000611323 -0.0971447 0)
(0.00348427 -0.10492 0)
(0.000195108 -0.106632 0)
(-0.00385551 -0.107557 0)
(-0.00632506 -0.108895 0)
(-0.00631824 -0.110214 0)
(-0.00477035 -0.111128 0)
(-0.00335337 -0.111694 0)
(-0.001733 -0.11192 0)
(-0.000644882 -0.11158 0)
(-0.000241435 -0.111316 0)
(-0.000305027 -0.11097 0)
(0.000725722 -0.111188 0)
(0.0124871 -0.108882 0)
(0.0438775 -0.098545 0)
(0.104441 -0.0649033 0)
(0.125581 -0.0141381 0)
(0.0700001 -0.0146842 0)
(0.0125943 -0.0124987 0)
(-0.0053948 -0.00561371 0)
(-0.00564508 0.0075642 0)
(-0.0123036 0.0117986 0)
(-0.0181481 0.0242787 0)
(-0.00985139 0.0474248 0)
(0.00945468 -0.0332781 0)
(0.0319412 -0.0434738 0)
(0.0457041 -0.0643526 0)
(0.0647652 -0.0814517 0)
(0.0795878 -0.0967828 0)
(0.0482835 -0.0880785 0)
(-0.0160443 -0.0783486 0)
(-0.0898333 -0.0609498 0)
(-0.125534 -0.0258946 0)
(-0.0969198 -0.00182004 0)
(-0.0532097 0.00707218 0)
(-0.0341666 0.0134984 0)
(-0.0395875 0.0246171 0)
(-0.060423 0.0343533 0)
(-0.0753264 0.0277134 0)
(-0.0591007 -0.00538044 0)
(-0.0259897 -0.0523956 0)
(-0.00680245 -0.082634 0)
(-0.00353946 -0.0942577 0)
(-0.00623891 -0.0985083 0)
(-0.00879553 -0.101258 0)
(-0.00901677 -0.104422 0)
(-0.00733311 -0.108176 0)
(-0.00527872 -0.111448 0)
(-0.00282351 -0.113725 0)
(-0.00116499 -0.114987 0)
(-0.000494357 -0.115551 0)
(-0.000524572 -0.115818 0)
(0.00204498 -0.116262 0)
(0.0183003 -0.113129 0)
(0.0682664 -0.104812 0)
(0.147828 -0.0575582 0)
(0.149148 -0.0170822 0)
(0.0739152 -0.0213751 0)
(0.0197899 -0.0147759 0)
(0.0037315 -0.00625971 0)
(0.00768003 0.00470607 0)
(0.0015045 0.0173377 0)
(-0.0168158 0.0193905 0)
(-0.0146172 -0.00194353 0)
(-0.00150014 -0.0368717 0)
(0.00401133 -0.070107 0)
(0.0155844 -0.120975 0)
(0.0376151 -0.164249 0)
(0.0634092 -0.215516 0)
(0.0494264 -0.257695 0)
(-0.000712238 -0.281543 0)
(-0.0513102 -0.2733 0)
(-0.0717443 -0.215566 0)
(-0.0557769 -0.144843 0)
(-0.0342724 -0.0949331 0)
(-0.0248597 -0.0651903 0)
(-0.0283258 -0.0430027 0)
(-0.0473095 -0.0161095 0)
(-0.075932 0.01529 0)
(-0.092259 0.0299555 0)
(-0.073833 0.000689987 0)
(-0.0368556 -0.0490417 0)
(-0.015102 -0.0761422 0)
(-0.0106012 -0.083374 0)
(-0.0120235 -0.0851944 0)
(-0.012985 -0.0871486 0)
(-0.0115411 -0.0904251 0)
(-0.0087004 -0.0938865 0)
(-0.00514323 -0.0968365 0)
(-0.0024039 -0.0989394 0)
(-0.00104196 -0.100095 0)
(-0.000990419 -0.100759 0)
(0.00331681 -0.101644 0)
(0.0235201 -0.0997215 0)
(0.0974273 -0.0936083 0)
(0.188981 -0.0441635 0)
(0.160448 -0.0163934 0)
(0.0722225 -0.0259624 0)
(0.0271601 -0.0227327 0)
(0.0133788 -0.0139511 0)
(0.0170943 -0.00349259 0)
(0.00184681 0.00130926 0)
(-0.0367282 -0.0153607 0)
(-0.0304096 -0.04444 0)
(-0.0225721 -0.0188176 0)
(-0.0491036 -0.0409965 0)
(-0.0450144 -0.0815297 0)
(-0.0263386 -0.123204 0)
(-0.0104599 -0.177127 0)
(-0.0153418 -0.237959 0)
(-0.031082 -0.28083 0)
(-0.0262563 -0.301312 0)
(-0.00174858 -0.282225 0)
(0.0193269 -0.248323 0)
(0.0235463 -0.222636 0)
(0.0158754 -0.20308 0)
(0.00770849 -0.185636 0)
(-0.00424994 -0.162178 0)
(-0.0309365 -0.122583 0)
(-0.0731698 -0.0763886 0)
(-0.102114 -0.0513328 0)
(-0.0808407 -0.0732742 0)
(-0.0366234 -0.110204 0)
(-0.0149619 -0.125621 0)
(-0.0124328 -0.124787 0)
(-0.0140572 -0.121814 0)
(-0.013826 -0.120363 0)
(-0.011457 -0.120393 0)
(-0.00769268 -0.121031 0)
(-0.00430471 -0.121679 0)
(-0.00224803 -0.122155 0)
(-0.00201775 -0.121654 0)
(0.00304493 -0.12191 0)
(0.026044 -0.12194 0)
(0.121804 -0.117939 0)
(0.222235 -0.0744294 0)
(0.166688 -0.0419037 0)
(0.0678064 -0.0414927 0)
(0.0313645 -0.0462694 0)
(0.022272 -0.048209 0)
(0.0223854 -0.0456534 0)
(-0.00993202 -0.0518338 0)
(-0.0609015 -0.0657717 0)
(-0.0426392 -0.0666541 0)
(-0.0228725 -0.0440141 0)
(-0.0564204 -0.0281409 0)
(-0.0636339 -0.0241151 0)
(-0.054506 -0.0218956 0)
(-0.0471727 -0.0306844 0)
(-0.0505055 -0.0542895 0)
(-0.0617614 -0.068329 0)
(-0.0526549 -0.0775614 0)
(-0.0206825 -0.0914273 0)
(0.00164531 -0.112282 0)
(0.00932573 -0.13345 0)
(0.0107956 -0.14968 0)
(0.0110885 -0.164818 0)
(0.0134505 -0.182855 0)
(0.00673795 -0.194312 0)
(-0.0235999 -0.185386 0)
(-0.0708318 -0.158193 0)
(-0.0935858 -0.15016 0)
(-0.0655455 -0.191594 0)
(-0.0246541 -0.231887 0)
(-0.00835517 -0.241357 0)
(-0.0087215 -0.239369 0)
(-0.0101713 -0.235595 0)
(-0.00934442 -0.232952 0)
(-0.00638271 -0.231006 0)
(-0.00348708 -0.229752 0)
(-0.00101754 -0.229222 0)
(-0.000753854 -0.227517 0)
(0.00304122 -0.226375 0)
(0.0273464 -0.227315 0)
(0.14321 -0.227684 0)
(0.262251 -0.19976 0)
(0.192187 -0.149363 0)
(0.0680156 -0.127091 0)
(0.0206879 -0.128203 0)
(0.0139723 -0.126735 0)
(0.0136013 -0.114602 0)
(-0.0175399 -0.103331 0)
(-0.0510096 -0.0831653 0)
(-0.03126 -0.0541216 0)
(-0.00727609 -0.124594 0)
(-0.0299282 -0.101483 0)
(-0.0389962 -0.0803987 0)
(-0.032669 -0.0595059 0)
(-0.0416758 -0.0318733 0)
(-0.0516174 0.00147216 0)
(-0.0535077 0.0268644 0)
(-0.0485146 0.0543537 0)
(-0.0352067 0.0630275 0)
(-0.0211674 0.045559 0)
(-0.0124916 0.0280131 0)
(-0.0143522 0.0110215 0)
(-0.0242605 -0.00714564 0)
(-0.0326709 -0.0315171 0)
(-0.0333752 -0.0648726 0)
(-0.0383643 -0.0947965 0)
(-0.0681689 -0.107244 0)
(-0.113027 -0.107142 0)
(-0.115379 -0.133549 0)
(-0.0629157 -0.200597 0)
(-0.0196425 -0.249978 0)
(-0.00850416 -0.267216 0)
(-0.00764217 -0.274453 0)
(-0.0070352 -0.279579 0)
(-0.00460939 -0.283718 0)
(-0.00258602 -0.287533 0)
(-9.44315e-05 -0.290379 0)
(0.000726175 -0.292523 0)
(0.00323985 -0.292895 0)
(0.024783 -0.295275 0)
(0.148358 -0.302255 0)
(0.297708 -0.308979 0)
(0.236714 -0.269396 0)
(0.0881962 -0.22851 0)
(0.0317075 -0.203235 0)
(0.035379 -0.167719 0)
(0.0449381 -0.125068 0)
(0.0203614 -0.0859154 0)
(-0.0134812 -0.0526432 0)
(-0.0146516 -0.0272443 0)
(-0.000602195 -0.199563 0)
(-0.0138323 -0.1989 0)
(-0.023183 -0.172279 0)
(-0.00774513 -0.150465 0)
(0.011588 -0.12555 0)
(0.00609628 -0.0758617 0)
(-0.0108029 -0.00941035 0)
(-0.0178068 0.04246 0)
(-0.0291575 0.0728459 0)
(-0.0320958 0.0990603 0)
(-0.0239558 0.0899561 0)
(-0.0230847 0.0757439 0)
(-0.0299032 0.0689791 0)
(-0.0421772 0.0656288 0)
(-0.0542404 0.0590983 0)
(-0.064431 0.0422998 0)
(-0.0827286 0.0256462 0)
(-0.118934 0.0246927 0)
(-0.155602 0.0243627 0)
(-0.136849 -0.0224497 0)
(-0.0725515 -0.0897296 0)
(-0.0323064 -0.122964 0)
(-0.0220852 -0.136037 0)
(-0.0182726 -0.144649 0)
(-0.0140472 -0.15212 0)
(-0.00990616 -0.158912 0)
(-0.00582661 -0.163852 0)
(-0.00317828 -0.16855 0)
(0.000389557 -0.170765 0)
(0.0183262 -0.17352 0)
(0.130004 -0.179776 0)
(0.293916 -0.199248 0)
(0.26973 -0.195024 0)
(0.13177 -0.168936 0)
(0.0792683 -0.139818 0)
(0.0892967 -0.1008 0)
(0.0924299 -0.0667128 0)
(0.0522515 -0.0389461 0)
(0.00552803 -0.0215515 0)
(-0.00678469 -0.0117881 0)
(-0.00663777 -0.248667 0)
(-0.00363629 -0.249341 0)
(0.00767771 -0.230461 0)
(0.0123602 -0.206597 0)
(0.0302148 -0.187281 0)
(0.0602993 -0.165951 0)
(0.0605115 -0.113495 0)
(0.0307505 -0.035734 0)
(0.0193354 0.0261286 0)
(-0.00467941 0.0716067 0)
(-0.0349601 0.108194 0)
(-0.0345665 0.10268 0)
(-0.0340077 0.0871321 0)
(-0.0421924 0.0825134 0)
(-0.0558559 0.0842372 0)
(-0.0706 0.0849163 0)
(-0.0851357 0.0813108 0)
(-0.114264 0.0819822 0)
(-0.160807 0.0907562 0)
(-0.172859 0.0845932 0)
(-0.116502 0.0319195 0)
(-0.0531279 -0.00986904 0)
(-0.0285391 -0.0217929 0)
(-0.0225329 -0.0254318 0)
(-0.018353 -0.0284134 0)
(-0.0138921 -0.0315939 0)
(-0.00938262 -0.0343448 0)
(-0.00593522 -0.0369439 0)
(-0.00154868 -0.0385221 0)
(0.0160996 -0.0398546 0)
(0.123565 -0.0413634 0)
(0.283015 -0.0463857 0)
(0.265923 -0.0530912 0)
(0.141395 -0.0520897 0)
(0.097366 -0.0446436 0)
(0.105826 -0.0315915 0)
(0.104543 -0.0218763 0)
(0.0638804 -0.0134566 0)
(0.0126893 -0.00704709 0)
(-0.00524322 -0.00581647 0)
(-0.00125225 -0.262287 0)
(0.00371141 -0.253428 0)
(0.0180073 -0.251014 0)
(0.0338642 -0.24395 0)
(0.0507556 -0.231458 0)
(0.0771995 -0.220363 0)
(0.114679 -0.207115 0)
(0.11674 -0.150794 0)
(0.0742799 -0.0573758 0)
(0.0469852 0.0105001 0)
(0.0059871 0.0767822 0)
(-0.0433805 0.11044 0)
(-0.049336 0.106032 0)
(-0.0449669 0.0903701 0)
(-0.0519248 0.0840222 0)
(-0.0672509 0.0868473 0)
(-0.0855561 0.0896519 0)
(-0.109832 0.0901508 0)
(-0.153086 0.0987609 0)
(-0.193546 0.10758 0)
(-0.163579 0.0734385 0)
(-0.0840657 0.019377 0)
(-0.037082 -0.000526757 0)
(-0.0246523 -0.0036446 0)
(-0.0199851 -0.00452801 0)
(-0.0156218 -0.00571441 0)
(-0.0109821 -0.00700421 0)
(-0.00720372 -0.00825389 0)
(-0.00241522 -0.00912228 0)
(0.0155883 -0.00959211 0)
(0.123711 -0.00956 0)
(0.282614 -0.00714714 0)
(0.264234 -0.00769762 0)
(0.139911 -0.0097839 0)
(0.0990211 -0.0107414 0)
(0.111236 -0.00812879 0)
(0.109905 -0.00484907 0)
(0.0665415 -0.00304992 0)
(0.0128903 -0.00289814 0)
(-0.00559882 -0.00378791 0)
(0.0018988 -0.213954 0)
(0.00722652 -0.212519 0)
(0.0168115 -0.214214 0)
(0.0312048 -0.216793 0)
(0.0529433 -0.219323 0)
(0.0837572 -0.219514 0)
(0.127552 -0.223594 0)
(0.175045 -0.227421 0)
(0.174764 -0.172253 0)
(0.1246 -0.0736105 0)
(0.0613452 0.00960746 0)
(-0.00638009 0.0919146 0)
(-0.0533474 0.114672 0)
(-0.0634021 0.105317 0)
(-0.0592506 0.0888896 0)
(-0.065175 0.0820697 0)
(-0.0819524 0.0843702 0)
(-0.105487 0.0869081 0)
(-0.144012 0.0918404 0)
(-0.197261 0.103406 0)
(-0.201497 0.0929176 0)
(-0.124404 0.037562 0)
(-0.0507236 0.00501694 0)
(-0.0263886 -0.000348892 0)
(-0.0203475 -0.00063979 0)
(-0.0162782 -0.00106506 0)
(-0.0118298 -0.00180669 0)
(-0.00797628 -0.00265951 0)
(-0.00283824 -0.00326663 0)
(0.0156778 -0.0034842 0)
(0.125921 -0.00318206 0)
(0.284809 3.98733e-05 0)
(0.263382 0.00114836 0)
(0.138461 6.65111e-05 0)
(0.0989609 -0.000795809 0)
(0.111504 -0.000280217 0)
(0.109437 -0.000467057 0)
(0.0657604 -0.00090008 0)
(0.0119781 -0.00157365 0)
(-0.00610063 -0.00264829 0)
(0.000130735 -0.135319 0)
(0.00346112 -0.138213 0)
(0.0138883 -0.145094 0)
(0.0289406 -0.153645 0)
(0.0481337 -0.165065 0)
(0.0730837 -0.177872 0)
(0.107059 -0.190888 0)
(0.166214 -0.206632 0)
(0.222498 -0.209483 0)
(0.222233 -0.151667 0)
(0.165493 -0.0738757 0)
(0.057864 0.0297625 0)
(-0.0364207 0.10732 0)
(-0.0698123 0.119466 0)
(-0.074327 0.105675 0)
(-0.0716059 0.0883743 0)
(-0.0808936 0.0817144 0)
(-0.102634 0.0827681 0)
(-0.137188 0.0855327 0)
(-0.192508 0.0943535 0)
(-0.227028 0.0969265 0)
(-0.16877 0.0536872 0)
(-0.0736143 0.00896637 0)
(-0.0301033 -0.0012743 0)
(-0.0206753 -0.0019713 0)
(-0.0167463 -0.00223598 0)
(-0.0125186 -0.00282871 0)
(-0.00861058 -0.00362391 0)
(-0.00320992 -0.00418253 0)
(0.0156698 -0.00437097 0)
(0.127107 -0.00409427 0)
(0.286787 -0.00129234 0)
(0.264259 0.000290953 0)
(0.138037 -0.000235233 0)
(0.098687 -0.00119696 0)
(0.111553 -0.000717336 0)
(0.109308 -0.000743157 0)
(0.0654751 -0.000715911 0)
(0.0112057 -0.00118725 0)
(-0.00663438 -0.00225316 0)
(-0.000889658 -0.0691095 0)
(-0.00219218 -0.0706055 0)
(0.00194088 -0.076782 0)
(0.0119597 -0.0903205 0)
(0.029597 -0.116276 0)
(0.058873 -0.137699 0)
(0.0998374 -0.152852 0)
(0.157126 -0.164392 0)
(0.227731 -0.180171 0)
(0.255276 -0.169163 0)
(0.236177 -0.109588 0)
(0.168227 -0.0483944 0)
(0.0330943 0.0651542 0)
(-0.0649876 0.116255 0)
(-0.0892118 0.124301 0)
(-0.0882642 0.104351 0)
(-0.0873548 0.0846181 0)
(-0.101807 0.0787642 0)
(-0.132848 0.0796987 0)
(-0.186281 0.0850416 0)
(-0.240684 0.091926 0)
(-0.209165 0.0652727 0)
(-0.103687 0.0155029 0)
(-0.0369286 -0.000638836 0)
(-0.0212742 -0.00202958 0)
(-0.0171045 -0.00220712 0)
(-0.0131672 -0.0027066 0)
(-0.00928087 -0.00349537 0)
(-0.00355814 -0.00405165 0)
(0.0157628 -0.00426182 0)
(0.128888 -0.00396812 0)
(0.289035 -0.00155338 0)
(0.264401 -0.000485082 0)
(0.137028 -0.00116589 0)
(0.0984964 -0.00213227 0)
(0.111942 -0.00134992 0)
(0.109439 -0.00121497 0)
(0.0653325 -0.000815235 0)
(0.0104968 -0.00108512 0)
(-0.00712778 -0.00211845 0)
(-0.00131086 -0.026444 0)
(-0.00393245 -0.0270767 0)
(-0.0051099 -0.0280724 0)
(-0.00911695 -0.0361064 0)
(0.00247849 -0.0578969 0)
(0.0378375 -0.0800342 0)
(0.0813367 -0.100143 0)
(0.139888 -0.136018 0)
(0.2179 -0.151652 0)
(0.290249 -0.145627 0)
(0.28187 -0.099373 0)
(0.226252 -0.0568395 0)
(0.122242 0.00487378 0)
(-0.0128167 0.0915043 0)
(-0.0857985 0.124609 0)
(-0.109845 0.120748 0)
(-0.10555 0.0943692 0)
(-0.107374 0.0765906 0)
(-0.131139 0.0730321 0)
(-0.180725 0.0757259 0)
(-0.246078 0.0823872 0)
(-0.242414 0.0688416 0)
(-0.137129 0.0219825 0)
(-0.0469983 0.000661166 0)
(-0.0221865 -0.00158096 0)
(-0.0173987 -0.00167979 0)
(-0.01376 -0.00206856 0)
(-0.00990672 -0.00278801 0)
(-0.00394851 -0.00330792 0)
(0.0157503 -0.00353671 0)
(0.129717 -0.00324827 0)
(0.290144 -0.00129994 0)
(0.264633 -0.000554669 0)
(0.13645 -0.00115499 0)
(0.0985096 -0.00208739 0)
(0.112437 -0.00131939 0)
(0.109823 -0.00139552 0)
(0.0656002 -0.000907239 0)
(0.00994988 -0.00116807 0)
(-0.00763014 -0.00220152 0)
(-0.00149927 -0.00694741 0)
(-0.00376129 0.00245544 0)
(-0.00676049 0.00719779 0)
(-0.0167804 0.00801551 0)
(-0.0127335 0.00978264 0)
(0.018163 -0.00308662 0)
(0.0458895 -0.0265381 0)
(0.107491 -0.0648529 0)
(0.218471 -0.110556 0)
(0.305654 -0.0824547 0)
(0.321735 -0.0657575 0)
(0.268683 -0.0222073 0)
(0.176044 -0.00799681 0)
(0.0503939 0.0648577 0)
(-0.0610311 0.10461 0)
(-0.117405 0.12406 0)
(-0.129907 0.103765 0)
(-0.122368 0.0755924 0)
(-0.133681 0.0652066 0)
(-0.177266 0.065446 0)
(-0.247318 0.0701807 0)
(-0.267373 0.064306 0)
(-0.169388 0.0257959 0)
(-0.0596352 0.00187328 0)
(-0.02353 -0.00115757 0)
(-0.0175744 -0.00117171 0)
(-0.0142351 -0.00143184 0)
(-0.0104752 -0.00205417 0)
(-0.00427961 -0.00252681 0)
(0.0158203 -0.00271984 0)
(0.131043 -0.0024027 0)
(0.291631 -0.000351598 0)
(0.26454 0.000158505 0)
(0.135551 -0.000603808 0)
(0.098338 -0.0015775 0)
(0.112608 -0.00111605 0)
(0.109836 -0.00144869 0)
(0.0655517 -0.000993582 0)
(0.00924956 -0.00130558 0)
(-0.00812364 -0.00222364 0)
(0.00775006 0.000913104 0)
(0.00969838 -0.00402164 0)
(0.000247981 -0.0077717 0)
(-0.00662609 -0.00588793 0)
(-0.00821992 0.0110916 0)
(0.00283751 0.0180689 0)
(0.0218165 0.00795528 0)
(0.0589257 0.000685744 0)
(0.200938 -0.0430415 0)
(0.333418 -0.0218219 0)
(0.339927 0.0212382 0)
(0.281912 0.0403846 0)
(0.206141 0.03638 0)
(0.0956951 0.0650524 0)
(-0.0287493 0.0936396 0)
(-0.11066 0.117307 0)
(-0.152255 0.106183 0)
(-0.14453 0.0717078 0)
(-0.140916 0.0540659 0)
(-0.175932 0.0529204 0)
(-0.247177 0.0567477 0)
(-0.285185 0.0543745 0)
(-0.197291 0.025459 0)
(-0.0729717 0.0024579 0)
(-0.0251208 -0.000907675 0)
(-0.017663 -0.000856159 0)
(-0.0146104 -0.00102398 0)
(-0.0109619 -0.00154482 0)
(-0.00458997 -0.0019481 0)
(0.0158699 -0.00212761 0)
(0.131999 -0.00181742 0)
(0.292612 -8.48327e-05 0)
(0.26439 0.000311331 0)
(0.134777 -0.000420392 0)
(0.098016 -0.0013486 0)
(0.112561 -0.00135715 0)
(0.109941 -0.00164212 0)
(0.0657381 -0.0011664 0)
(0.00876455 -0.00137686 0)
(-0.00851481 -0.00208544 0)
(-0.00625457 0.214408 0)
(-0.0121303 0.195369 0)
(-0.00855892 0.18624 0)
(0.00139697 0.181227 0)
(0.0103523 0.188675 0)
(0.0151408 0.191837 0)
(0.0291384 0.174756 0)
(0.0583481 0.150393 0)
(0.196782 0.115301 0)
(0.367596 0.0675609 0)
(0.38168 0.145017 0)
(0.283274 0.147741 0)
(0.199815 0.11489 0)
(0.105571 0.0838387 0)
(-0.0106763 0.0869657 0)
(-0.105318 0.099368 0)
(-0.173848 0.0940648 0)
(-0.17259 0.0639282 0)
(-0.151785 0.0446492 0)
(-0.174682 0.0409655 0)
(-0.245917 0.0426501 0)
(-0.297524 0.0410957 0)
(-0.219416 0.0210619 0)
(-0.0850431 0.00236792 0)
(-0.0267236 -0.000606484 0)
(-0.0176864 -0.00054061 0)
(-0.0148988 -0.000648381 0)
(-0.0113657 -0.00106583 0)
(-0.0048412 -0.00137703 0)
(0.0159462 -0.00150348 0)
(0.133012 -0.00121907 0)
(0.293682 0.000335878 0)
(0.264217 0.000659209 0)
(0.133951 -0.000112471 0)
(0.0974353 -0.000897054 0)
(0.112326 -0.00124705 0)
(0.11002 -0.00120697 0)
(0.0658073 -0.000991598 0)
(0.00836394 -0.0012467 0)
(-0.00880646 -0.00176551 0)
(-0.0105965 0.744035 0)
(-0.0174445 0.659949 0)
(-0.0133793 0.620376 0)
(-0.00428033 0.584971 0)
(0.00200444 0.547893 0)
(-0.0105748 0.511142 0)
(-0.0181204 0.442006 0)
(0.00163208 0.350617 0)
(0.121117 0.309069 0)
(0.362054 0.223016 0)
(0.417191 0.271842 0)
(0.25288 0.229744 0)
(0.144562 0.15539 0)
(0.0687864 0.086419 0)
(-0.0137847 0.0727383 0)
(-0.103819 0.0757243 0)
(-0.186406 0.067708 0)
(-0.192149 0.0396284 0)
(-0.163044 0.0201572 0)
(-0.177858 0.0178239 0)
(-0.247051 0.0217734 0)
(-0.305988 0.0250681 0)
(-0.234611 0.0148339 0)
(-0.0938521 0.00181354 0)
(-0.0279236 -0.000344402 0)
(-0.0177033 -0.000297074 0)
(-0.0151165 -0.000375353 0)
(-0.011664 -0.00068742 0)
(-0.00501171 -0.000889478 0)
(0.0160221 -0.000965476 0)
(0.133771 -0.000754069 0)
(0.294422 0.0003254 0)
(0.263958 0.000488106 0)
(0.133278 -0.000121948 0)
(0.0969227 -0.000634345 0)
(0.112262 -0.000992327 0)
(0.110187 -0.000565417 0)
(0.0656999 -0.000866757 0)
(0.00801878 -0.00142175 0)
(-0.00901476 -0.00213029 0)
)
;
boundaryField
{
inlet
{
type extrapolatedCalculated;
value nonuniform List<vector> 5((5.46867 -9.59461e-07 0) (5.46866 -1.71623e-06 0) (5.46866 -4.42354e-13 0) (5.46866 1.71623e-06 0) (5.46867 9.59461e-07 0));
}
outlet
{
type extrapolatedCalculated;
value nonuniform List<vector>
165
(
(0 -0.744035 0)
(0 -0.214408 0)
(0 -0.000913104 0)
(0 0.00694741 0)
(0 0.026444 0)
(0 0.0691095 0)
(0 0.135319 0)
(0 0.213954 0)
(0 0.262287 0)
(0 0.248667 0)
(0 0.199563 0)
(0 0.124594 0)
(0 0.0440141 0)
(0 0.0188176 0)
(0 0.0368717 0)
(0 0.0332781 0)
(0 -0.00832884 0)
(0 -0.296256 0)
(0 -0.751216 0)
(0 -0.472821 0)
(0.307812 0 0)
(0.663056 0 0)
(0.407886 0 0)
(0.078276 0 0)
(0.0414424 0 0)
(0.0197466 0 0)
(-0.0166287 0 0)
(-0.0495254 0 0)
(-0.049414 0 0)
(-0.0329207 0 0)
(-0.0216456 0 0)
(-0.0167818 0 0)
(-0.011557 0 0)
(-0.00522934 0 0)
(-0.0022432 0 0)
(-0.00284189 0 0)
(-0.00456689 0 0)
(-0.0060609 0 0)
(-0.00707027 0 0)
(-0.00738558 0 0)
(-0.00716442 0 0)
(-0.00626692 0 0)
(-0.0046243 0 0)
(-0.00291033 0 0)
(-0.00160874 0 0)
(-0.000863423 0 0)
(-0.000238487 0 0)
(0.000372372 0 0)
(0.00121814 0 0)
(0.00260476 0 0)
(0.00724745 0 0)
(0.0188729 0 0)
(0.0415886 0 0)
(0.0625681 0 0)
(0.0534002 0 0)
(0.00995047 0 0)
(-0.0415241 0 0)
(-0.291138 0 0)
(-0.650259 0 0)
(-0.391472 0 0)
(0 0.00213029 0)
(0 0.00176551 0)
(0 0.00208544 0)
(0 0.00222364 0)
(0 0.00220152 0)
(0 0.00211845 0)
(0 0.00225316 0)
(0 0.00264829 0)
(0 0.00378791 0)
(0 0.00581647 0)
(0 0.0117881 0)
(0 0.0272443 0)
(0 0.0541216 0)
(0 0.0666541 0)
(0 0.04444 0)
(0 0.00194353 0)
(0 -0.0474248 0)
(0 -0.311239 0)
(0 -0.674899 0)
(0 -0.400031 0)
(0 -0.00213817 0)
(0 -0.00142012 0)
(0 -6.05182e-13 0)
(0 0.00142012 0)
(0 0.00213817 0)
(0 0.400031 0)
(0 0.674899 0)
(0 0.311239 0)
(0 0.0474248 0)
(0 -0.00194353 0)
(0 -0.04444 0)
(0 -0.0666541 0)
(0 -0.0541216 0)
(0 -0.0272443 0)
(0 -0.0117881 0)
(0 -0.00581647 0)
(0 -0.00378791 0)
(0 -0.00264829 0)
(0 -0.00225316 0)
(0 -0.00211845 0)
(0 -0.00220152 0)
(0 -0.00222364 0)
(0 -0.00208544 0)
(0 -0.00176551 0)
(0 -0.00213029 0)
(0.307812 0 0)
(0.663056 0 0)
(0.407886 0 0)
(0.078276 0 0)
(0.0414424 0 0)
(0.0197466 0 0)
(-0.0166287 0 0)
(-0.0495254 0 0)
(-0.049414 0 0)
(-0.0329207 0 0)
(-0.0216456 0 0)
(-0.0167818 0 0)
(-0.011557 0 0)
(-0.00522934 0 0)
(-0.0022432 0 0)
(-0.00284189 0 0)
(-0.00456689 0 0)
(-0.0060609 0 0)
(-0.00707027 0 0)
(-0.00738558 0 0)
(-0.00716442 0 0)
(-0.00626692 0 0)
(-0.0046243 0 0)
(-0.00291033 0 0)
(-0.00160874 0 0)
(-0.000863423 0 0)
(-0.000238487 0 0)
(0.000372372 0 0)
(0.00121814 0 0)
(0.00260476 0 0)
(0.00724745 0 0)
(0.0188729 0 0)
(0.0415886 0 0)
(0.0625681 0 0)
(0.0534002 0 0)
(0.00995047 0 0)
(-0.0415241 0 0)
(-0.291138 0 0)
(-0.650259 0 0)
(-0.391472 0 0)
(0 0.472821 0)
(0 0.751216 0)
(0 0.296256 0)
(0 0.00832884 0)
(0 -0.0332781 0)
(0 -0.0368717 0)
(0 -0.0188176 0)
(0 -0.0440141 0)
(0 -0.124594 0)
(0 -0.199563 0)
(0 -0.248667 0)
(0 -0.262287 0)
(0 -0.213954 0)
(0 -0.135319 0)
(0 -0.0691095 0)
(0 -0.026444 0)
(0 -0.00694741 0)
(0 0.000913104 0)
(0 0.214408 0)
(0 0.744035 0)
)
;
}
obstacle
{
type extrapolatedCalculated;
value nonuniform List<vector>
40
(
(1.44008 0 0)
(-1.67415 0 0)
(-0.444023 0 0)
(-0.0641595 0 0)
(0.0196676 0 0)
(0.059074 0 0)
(0.0811122 0 0)
(0.0650604 0 0)
(0.0282706 0 0)
(0.0296804 0 0)
(1.44008 0 0)
(-1.67415 0 0)
(-0.444023 0 0)
(-0.0641595 0 0)
(0.0196676 0 0)
(0.059074 0 0)
(0.0811122 0 0)
(0.0650604 0 0)
(0.0282706 0 0)
(0.0296804 0 0)
(-0.0134693 -0.00897956 9.37569e-16)
(-0.0204365 -0.0136243 -1.12826e-15)
(0.0498555 0.033237 -1.43226e-15)
(0.232912 0.155274 0)
(-0.50543 -0.336953 -6.45037e-15)
(-0.0134693 0.00897956 -2.80946e-15)
(-0.0204365 0.0136243 -1.12826e-15)
(0.0498555 -0.033237 -1.43226e-15)
(0.232912 -0.155274 -3.90627e-15)
(-0.50543 0.336953 6.45037e-15)
(-1.89534 -0.210594 1.09779e-15)
(-0.980173 -0.108908 -3.27996e-18)
(-0.605259 -0.067251 0)
(-0.424659 -0.0471844 1.42104e-18)
(-0.310388 -0.0344876 4.26914e-16)
(-1.89534 0.210594 2.18924e-15)
(-0.980173 0.108908 -1.5851e-15)
(-0.605259 0.067251 0)
(-0.424659 0.0471844 1.01685e-15)
(-0.310388 0.0344876 -4.26914e-16)
)
;
}
empty
{
type empty;
}
}
// ************************************************************************* //
| [
"andytorrestb@gmail.com"
] | andytorrestb@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.